diff options
88 files changed, 6719 insertions, 8979 deletions
diff --git a/cpp/include/Slice/JavaUtil.h b/cpp/include/Slice/JavaUtil.h index 3bb0c692e7e..9915f7e1b6d 100644 --- a/cpp/include/Slice/JavaUtil.h +++ b/cpp/include/Slice/JavaUtil.h @@ -185,27 +185,6 @@ protected: const std::string&, bool, int&, bool, const StringList& = StringList()); // - // Generate code to marshal or unmarshal a type using the public stream API. - // - void writeStreamMarshalUnmarshalCode(::IceUtilInternal::Output&, const std::string&, const TypePtr&, bool, int, - const std::string&, bool, int&, bool = false, - const StringList& = StringList(), const std::string& patchParams = ""); - - // - // Generate code to marshal or unmarshal a dictionary type using the public stream API. - // - void writeStreamDictionaryMarshalUnmarshalCode(::IceUtilInternal::Output&, const std::string&, const DictionaryPtr&, - const std::string&, bool, int&, bool, - const StringList& = StringList()); - - // - // Generate code to marshal or unmarshal a sequence type using the public stream API. - // - void writeStreamSequenceMarshalUnmarshalCode(::IceUtilInternal::Output&, const std::string&, const SequencePtr&, - const std::string&, bool, int&, bool, - const StringList& = StringList()); - - // // Search metadata for an entry with the given prefix and return the entire string. // static bool findMetaData(const std::string&, const StringList&, std::string&); diff --git a/cpp/src/Ice/CollocatedRequestHandler.cpp b/cpp/src/Ice/CollocatedRequestHandler.cpp index d57d9d72934..5e9dee2b5a3 100644 --- a/cpp/src/Ice/CollocatedRequestHandler.cpp +++ b/cpp/src/Ice/CollocatedRequestHandler.cpp @@ -323,13 +323,17 @@ CollocatedRequestHandler::sendResponse(Int requestId, OutputStream* os, Byte, bo Lock sync(*this); assert(_response); + if(_traceLevels->protocol >= 1) + { + fillInValue(os, 10, static_cast<Int>(os->b.size())); + } + InputStream is(os->instance(), os->getEncoding(), *os, true); // Adopting the OutputStream's buffer. is.i = is.b.begin() + sizeof(replyHdr) + 4; if(_traceLevels->protocol >= 1) { - fillInValue(os, 10, static_cast<Int>(os->b.size())); traceRecv(is, _logger, _traceLevels); } @@ -446,17 +450,6 @@ CollocatedRequestHandler::sentAsync(OutgoingAsyncBase* outAsync) void CollocatedRequestHandler::invokeAll(OutputStream* os, Int requestId, Int batchRequestNum) { - InputStream is(os->instance(), os->getEncoding(), *os); - - if(batchRequestNum > 0) - { - is.i = is.b.begin() + sizeof(requestBatchHdr); - } - else - { - is.i = is.b.begin() + sizeof(requestHdr); - } - if(_traceLevels->protocol >= 1) { fillInValue(os, 10, static_cast<Int>(os->b.size())); @@ -471,6 +464,17 @@ CollocatedRequestHandler::invokeAll(OutputStream* os, Int requestId, Int batchRe traceSend(*os, _logger, _traceLevels); } + InputStream is(os->instance(), os->getEncoding(), *os); + + if(batchRequestNum > 0) + { + is.i = is.b.begin() + sizeof(requestBatchHdr); + } + else + { + is.i = is.b.begin() + sizeof(requestHdr); + } + int invokeNum = batchRequestNum > 0 ? batchRequestNum : 1; ServantManagerPtr servantManager = _adapter->getServantManager(); try diff --git a/cpp/src/Slice/JavaUtil.cpp b/cpp/src/Slice/JavaUtil.cpp index f84b30eb8d5..7375215f3f4 100644 --- a/cpp/src/Slice/JavaUtil.cpp +++ b/cpp/src/Slice/JavaUtil.cpp @@ -1259,8 +1259,8 @@ Slice::JavaGenerator::writeMarshalUnmarshalCode(Output& out, { if(optionalMapping) { - out << nl << "if(" << v << " != null && " << v << ".isSet() && " << stream << ".writeOpt(" << tag - << ", " << getOptionalFormat(type) << "))"; + out << nl << "if(" << v << " != null && " << v << ".isSet() && " << stream << ".writeOptional(" + << tag << ", " << getOptionalFormat(type) << "))"; out << sb; out << nl << "int __pos = " << stream << ".startSize();"; out << nl << typeS << "Helper.__write(" << stream << ", " << v << ".get());"; @@ -1269,7 +1269,7 @@ Slice::JavaGenerator::writeMarshalUnmarshalCode(Output& out, } else { - out << nl << "if(" << stream << ".writeOpt(" << tag << ", " << getOptionalFormat(type) << "))"; + out << nl << "if(" << stream << ".writeOptional(" << tag << ", " << getOptionalFormat(type) << "))"; out << sb; out << nl << "int __pos = " << stream << ".startSize();"; out << nl << typeS << "Helper.__write(" << stream << ", " << v << ");"; @@ -1292,7 +1292,7 @@ Slice::JavaGenerator::writeMarshalUnmarshalCode(Output& out, { if(optionalParam) { - out << nl << "if(" << stream << ".readOpt(" << tag << ", " << getOptionalFormat(type) << "))"; + out << nl << "if(" << stream << ".readOptional(" << tag << ", " << getOptionalFormat(type) << "))"; out << sb; out << nl << stream << ".skip(4);"; out << nl << v << ".set(" << typeS << "Helper.__read(" << stream << "));"; @@ -1337,7 +1337,7 @@ Slice::JavaGenerator::writeMarshalUnmarshalCode(Output& out, if(optionalParam) { string typeS = typeToString(type, TypeModeIn, package); - out << nl << "if(" << stream << ".readOpt(" << tag << ", " << getOptionalFormat(type) << "))"; + out << nl << "if(" << stream << ".readOptional(" << tag << ", " << getOptionalFormat(type) << "))"; out << sb; out << nl << stream << ".readObject(new Ice.OptionalObject(" << v << ", " << typeS << ".class, " << getStaticId(type, package) << "));"; @@ -1385,13 +1385,14 @@ Slice::JavaGenerator::writeMarshalUnmarshalCode(Output& out, { if(optionalMapping) { - out << nl << "if(" << v << " != null && " << v << ".isSet() && " << stream << ".writeOpt(" + out << nl << "if(" << v << " != null && " << v << ".isSet() && " << stream << ".writeOptional(" << tag << ", " << getOptionalFormat(type) << "))"; val = v + ".get()"; } else { - out << nl << "if(" << stream << ".writeOpt(" << tag << ", " << getOptionalFormat(type) << "))"; + out << nl << "if(" << stream << ".writeOptional(" << tag << ", " << getOptionalFormat(type) + << "))"; val = v; } out << sb; @@ -1404,13 +1405,13 @@ Slice::JavaGenerator::writeMarshalUnmarshalCode(Output& out, if(st->isVariableLength()) { out << nl << "int __pos = " << stream << ".startSize();"; - out << nl << typeS << ".__write(" << stream << ", " << val << ");"; + out << nl << typeS << ".ice_write(" << stream << ", " << val << ");"; out << nl << stream << ".endSize(__pos);"; } else { out << nl << stream << ".writeSize(" << st->minWireSize() << ");"; - out << nl << typeS << ".__write(" << stream << ", " << val << ");"; + out << nl << typeS << ".ice_write(" << stream << ", " << val << ");"; } if(optionalParam) { @@ -1419,14 +1420,14 @@ Slice::JavaGenerator::writeMarshalUnmarshalCode(Output& out, } else { - out << nl << typeS << ".__write(" << stream << ", " << v << ");"; + out << nl << typeS << ".ice_write(" << stream << ", " << v << ");"; } } else { if(optionalParam) { - out << nl << "if(" << stream << ".readOpt(" << tag << ", " << getOptionalFormat(type) << "))"; + out << nl << "if(" << stream << ".readOptional(" << tag << ", " << getOptionalFormat(type) << "))"; out << sb; if(st->isVariableLength()) @@ -1439,7 +1440,7 @@ Slice::JavaGenerator::writeMarshalUnmarshalCode(Output& out, } out << nl << typeS << " __tmpOpt = new " << typeS << "();"; - out << nl << "__tmpOpt.__read(" << stream << ");"; + out << nl << "__tmpOpt.ice_read(" << stream << ");"; out << nl << v << ".set(__tmpOpt);"; out << eb; @@ -1462,11 +1463,11 @@ Slice::JavaGenerator::writeMarshalUnmarshalCode(Output& out, { out << nl << stream << ".skipSize();"; } - out << nl << v << " = " << typeS << ".__read(" << stream << ", " << v << ");"; + out << nl << v << " = " << typeS << ".ice_read(" << stream << ", " << v << ");"; } else { - out << nl << v << " = " << typeS << ".__read(" << stream << ", " << v << ");"; + out << nl << v << " = " << typeS << ".ice_read(" << stream << ", " << v << ");"; } } return; @@ -1482,32 +1483,32 @@ Slice::JavaGenerator::writeMarshalUnmarshalCode(Output& out, { if(optionalMapping) { - out << nl << "if(" << v << " != null && " << v << ".isSet() && " << stream << ".writeOpt(" << tag - << ", " << getOptionalFormat(type) << "))"; + out << nl << "if(" << v << " != null && " << v << ".isSet() && " << stream << ".writeOptional(" + << tag << ", " << getOptionalFormat(type) << "))"; out << sb; - out << nl << typeS << ".__write(" << stream << ", " << v << ".get());"; + out << nl << typeS << ".ice_write(" << stream << ", " << v << ".get());"; out << eb; } else { - out << nl << "if(" << stream << ".writeOpt(" << tag << ", " << getOptionalFormat(type) << "))"; + out << nl << "if(" << stream << ".writeOptional(" << tag << ", " << getOptionalFormat(type) << "))"; out << sb; - out << nl << typeS << ".__write(" << stream << ", " << v << ");"; + out << nl << typeS << ".ice_write(" << stream << ", " << v << ");"; out << eb; } } else { - out << nl << typeS << ".__write(" << stream << ", " << v << ");"; + out << nl << typeS << ".ice_write(" << stream << ", " << v << ");"; } } else { if(optionalParam) { - out << nl << "if(" << stream << ".readOpt(" << tag << ", " << getOptionalFormat(type) << "))"; + out << nl << "if(" << stream << ".readOptional(" << tag << ", " << getOptionalFormat(type) << "))"; out << sb; - out << nl << v << ".set(" << typeS << ".__read(" << stream << "));"; + out << nl << v << ".set(" << typeS << ".ice_read(" << stream << "));"; out << eb; if(mode == OptionalOutParam) { @@ -1519,7 +1520,7 @@ Slice::JavaGenerator::writeMarshalUnmarshalCode(Output& out, } else { - out << nl << v << " = " << typeS << ".__read(" << stream << ");"; + out << nl << v << " = " << typeS << ".ice_read(" << stream << ");"; } } return; @@ -1540,13 +1541,14 @@ Slice::JavaGenerator::writeMarshalUnmarshalCode(Output& out, { if(optionalMapping) { - out << nl << "if(" << v << " != null && " << v << ".isSet() && " << stream << ".writeOpt(" + out << nl << "if(" << v << " != null && " << v << ".isSet() && " << stream << ".writeOptional(" << tag << ", " << getOptionalFormat(type) << "))"; out << sb; } else { - out << nl << "if(" << stream << ".writeOpt(" << tag << ", " << getOptionalFormat(type) << "))"; + out << nl << "if(" << stream << ".writeOptional(" << tag << ", " << getOptionalFormat(type) + << "))"; out << sb; } } @@ -1589,7 +1591,7 @@ Slice::JavaGenerator::writeMarshalUnmarshalCode(Output& out, if(optionalParam) { tmpName = "__optDict"; - out << nl << "if(" << stream << ".readOpt(" << tag << ", " << getOptionalFormat(type) << "))"; + out << nl << "if(" << stream << ".readOptional(" << tag << ", " << getOptionalFormat(type) << "))"; out << sb; out << nl << typeS << ' ' << tmpName << ';'; } @@ -1701,12 +1703,13 @@ Slice::JavaGenerator::writeMarshalUnmarshalCode(Output& out, { if(optionalMapping) { - out << nl << "if(" << v << " != null && " << v << ".isSet() && " << stream << ".writeOpt(" + out << nl << "if(" << v << " != null && " << v << ".isSet() && " << stream << ".writeOptional(" << tag << ", " << getOptionalFormat(type) << "))"; } else { - out << nl << "if(" << stream << ".writeOpt(" << tag << ", " << getOptionalFormat(type) << "))"; + out << nl << "if(" << stream << ".writeOptional(" << tag << ", " << getOptionalFormat(type) + << "))"; } out << sb; @@ -1793,7 +1796,7 @@ Slice::JavaGenerator::writeMarshalUnmarshalCode(Output& out, if(optionalParam) { tmpName = "__optSeq"; - out << nl << "if(" << stream << ".readOpt(" << tag << ", " << getOptionalFormat(type) << "))"; + out << nl << "if(" << stream << ".readOptional(" << tag << ", " << getOptionalFormat(type) << "))"; out << sb; out << nl << typeS << ' ' << tmpName << ';'; } @@ -2570,1199 +2573,6 @@ Slice::JavaGenerator::writeSequenceMarshalUnmarshalCode(Output& out, } } -void -Slice::JavaGenerator::writeStreamMarshalUnmarshalCode(Output& out, - const string& package, - const TypePtr& type, - bool optional, - int /*tag*/, - const string& param, - bool marshal, - int& iter, - bool holder, - const StringList& metaData, - const string& patchParams) -{ - string stream = marshal ? "__outS" : "__inS"; - string v; - if(holder && !optional) - { - v = param + ".value"; - } - else - { - v = param; - } - - BuiltinPtr builtin = BuiltinPtr::dynamicCast(type); - if(builtin) - { - switch(builtin->kind()) - { - case Builtin::KindByte: - { - if(marshal) - { - out << nl << stream << ".writeByte(" << v << ");"; - } - else - { - out << nl << v << " = " << stream << ".readByte();"; - } - break; - } - case Builtin::KindBool: - { - if(marshal) - { - out << nl << stream << ".writeBool(" << v << ");"; - } - else - { - out << nl << v << " = " << stream << ".readBool();"; - } - break; - } - case Builtin::KindShort: - { - if(marshal) - { - out << nl << stream << ".writeShort(" << v << ");"; - } - else - { - out << nl << v << " = " << stream << ".readShort();"; - } - break; - } - case Builtin::KindInt: - { - if(marshal) - { - out << nl << stream << ".writeInt(" << v << ");"; - } - else - { - out << nl << v << " = " << stream << ".readInt();"; - } - break; - } - case Builtin::KindLong: - { - if(marshal) - { - out << nl << stream << ".writeLong(" << v << ");"; - } - else - { - out << nl << v << " = " << stream << ".readLong();"; - } - break; - } - case Builtin::KindFloat: - { - if(marshal) - { - out << nl << stream << ".writeFloat(" << v << ");"; - } - else - { - out << nl << v << " = " << stream << ".readFloat();"; - } - break; - } - case Builtin::KindDouble: - { - if(marshal) - { - out << nl << stream << ".writeDouble(" << v << ");"; - } - else - { - out << nl << v << " = " << stream << ".readDouble();"; - } - break; - } - case Builtin::KindString: - { - if(marshal) - { - out << nl << stream << ".writeString(" << v << ");"; - } - else - { - out << nl << v << " = " << stream << ".readString();"; - } - break; - } - case Builtin::KindValue: - case Builtin::KindObject: - { - if(marshal) - { - out << nl << stream << ".writeObject(" << v << ");"; - } - else - { - if(holder && !optional) - { - out << nl << stream << ".readObject(" << param << ");"; - } - else - { - if(patchParams.empty()) - { - out << nl << stream << ".readObject(new Patcher());"; - } - else - { - out << nl << stream << ".readObject(" << patchParams << ");"; - } - } - } - break; - } - case Builtin::KindObjectProxy: - { - if(marshal) - { - if(optional) - { - out << nl << "int __pos = " << stream << ".startSize();"; - out << nl << stream << ".writeProxy(" << v << ");"; - out << nl << stream << ".endSize(__pos);"; - } - else - { - out << nl << stream << ".writeProxy(" << v << ");"; - } - } - else - { - if(optional) - { - out << nl << stream << ".skip(4);"; - } - out << nl << v << " = " << stream << ".readProxy();"; - } - break; - } - case Builtin::KindLocalObject: - { - assert(false); - break; - } - } - return; - } - - ProxyPtr prx = ProxyPtr::dynamicCast(type); - if(prx) - { - string typeS = typeToString(type, TypeModeIn, package); - if(marshal) - { - if(optional) - { - out << nl << "int __pos = " << stream << ".startSize();"; - out << nl << typeS << "Helper.write(" << stream << ", " << v << ");"; - out << nl << stream << ".endSize(__pos);"; - } - else - { - out << nl << typeS << "Helper.write(" << stream << ", " << v << ");"; - } - } - else - { - if(optional) - { - out << nl << stream << ".skip(4);"; - } - out << nl << v << " = " << typeS << "Helper.read(" << stream << ");"; - } - return; - } - - ClassDeclPtr cl = ClassDeclPtr::dynamicCast(type); - if(cl) - { - if(marshal) - { - out << nl << stream << ".writeObject(" << v << ");"; - } - else - { - if(holder && !optional) - { - out << nl << stream << ".readObject(" << param << ");"; - } - else - { - if(patchParams.empty()) - { - out << nl << stream << ".readObject(new Patcher());"; - } - else - { - out << nl << stream << ".readObject(" << patchParams << ");"; - } - } - } - return; - } - - StructPtr st = StructPtr::dynamicCast(type); - if(st) - { - string typeS = typeToString(type, TypeModeIn, package); - if(marshal) - { - if(optional) - { - if(st->isVariableLength()) - { - out << nl << "int __pos = " << stream << ".startSize();"; - out << nl << typeS << ".ice_write(" << stream << ", " << v << ");"; - out << nl << stream << ".endSize(__pos);"; - } - else - { - out << nl << stream << ".writeSize(" << st->minWireSize() << ");"; - out << nl << typeS << ".ice_write(" << stream << ", " << v << ");"; - } - } - else - { - out << nl << typeS << ".ice_write(" << stream << ", " << v << ");"; - } - } - else - { - if(optional) - { - if(st->isVariableLength()) - { - out << nl << stream << ".skip(4);"; - } - else - { - out << nl << stream << ".skipSize();"; - } - } - out << nl << v << " = " << typeS << ".ice_read(" << stream << ", " << v << ");"; - } - return; - } - - EnumPtr en = EnumPtr::dynamicCast(type); - if(en) - { - string typeS = typeToString(type, TypeModeIn, package); - if(marshal) - { - out << nl << typeS << ".ice_write(" << stream << ", " << v << ");"; - } - else - { - out << nl << v << " = " << typeS << ".ice_read(" << stream << ");"; - } - return; - } - - DictionaryPtr dict = DictionaryPtr::dynamicCast(type); - if(dict) - { - if(optional) - { - string typeS = typeToString(type, TypeModeIn, package, metaData); - TypePtr keyType = dict->keyType(); - TypePtr valueType = dict->valueType(); - - if(marshal) - { - if(keyType->isVariableLength() || valueType->isVariableLength()) - { - out << nl << "int __pos = " << stream << ".startSize();"; - writeStreamDictionaryMarshalUnmarshalCode(out, package, dict, v, marshal, iter, true, metaData); - out << nl << stream << ".endSize(__pos);"; - } - else - { - const size_t wireSize = keyType->minWireSize() + valueType->minWireSize(); - out << nl << "final int __optSize = " << v << " == null ? 0 : " << v << ".size();"; - out << nl << stream << ".writeSize(__optSize > 254 ? __optSize * " << wireSize - << " + 5 : __optSize * " << wireSize << " + 1);"; - writeStreamDictionaryMarshalUnmarshalCode(out, package, dict, v, marshal, iter, true, metaData); - } - } - else - { - if(keyType->isVariableLength() || valueType->isVariableLength()) - { - out << nl << stream << ".skip(4);"; - } - else - { - out << nl << stream << ".skipSize();"; - } - - writeStreamDictionaryMarshalUnmarshalCode(out, package, dict, v, marshal, iter, true, metaData); - } - } - else - { - writeStreamDictionaryMarshalUnmarshalCode(out, package, dict, v, marshal, iter, true, metaData); - } - return; - } - - SequencePtr seq = SequencePtr::dynamicCast(type); - if(seq) - { - if(optional) - { - string typeS = typeToString(type, TypeModeIn, package, metaData); - TypePtr elemType = seq->type(); - BuiltinPtr elemBuiltin = BuiltinPtr::dynamicCast(elemType); - - string ignore; - - if(marshal) - { - if(elemType->isVariableLength()) - { - out << nl << "int __pos = " << stream << ".startSize();"; - writeStreamSequenceMarshalUnmarshalCode(out, package, seq, v, marshal, iter, true, metaData); - out << nl << stream << ".endSize(__pos);"; - } - else if(findMetaData("java:type:", metaData, ignore) || - findMetaData("java:type:", seq->getMetaData(), ignore)) - { - // - // The sequence is an instance of java.util.List<E>, where E is a fixed-size type. - // If the element type is bool or byte, we do NOT write an extra size. - // - - if(!elemBuiltin || - (elemBuiltin->kind() != Builtin::KindByte && elemBuiltin->kind() != Builtin::KindBool)) - { - out << nl << "final int __optSize = " << v << " == null ? 0 : " << v << ".size();"; - const size_t wireSize = elemType->minWireSize(); - - if(wireSize > 1) - { - out << nl << stream << ".writeSize(__optSize > 254 ? __optSize * " << wireSize - << " + 5 : __optSize * " << wireSize << " + 1);"; - } - else - { - // - // The element type could be a struct with a wire size of 1. - // - out << nl << stream << ".writeSize(__optSize > 254 ? __optSize + 5 : __optSize + 1);"; - } - } - writeStreamSequenceMarshalUnmarshalCode(out, package, seq, v, marshal, iter, true, metaData); - } - else if(findMetaData("java:protobuf:", seq->getMetaData(), ignore) || - findMetaData("java:serializable:", seq->getMetaData(), ignore)) - { - // - // This just writes a byte sequence. - // - writeStreamSequenceMarshalUnmarshalCode(out, package, seq, v, marshal, iter, true, metaData); - } - else - { - // - // At this point we have a regular Java array of a fixed-size type. - // - - if(!elemBuiltin || (elemBuiltin->kind() != Builtin::KindByte && - elemBuiltin->kind() != Builtin::KindBool)) - { - out << nl << "final int __optSize = " << v << " == null ? 0 : " << v << ".length;"; - const size_t wireSize = elemType->minWireSize(); - - if(wireSize > 1) - { - out << nl << stream << ".writeSize(__optSize > 254 ? __optSize * " << wireSize - << " + 5 : __optSize * " << wireSize << " + 1);"; - } - else - { - // - // The element type could be a struct with a wire size of 1. - // - out << nl << stream << ".writeSize(__optSize > 254 ? __optSize + 5 : __optSize + 1);"; - } - } - - writeStreamSequenceMarshalUnmarshalCode(out, package, seq, v, marshal, iter, true, metaData); - } - } - else - { - if(elemType->isVariableLength()) - { - out << nl << stream << ".skip(4);"; - } - else if(findMetaData("java:type:", metaData, ignore) || - findMetaData("java:type:", seq->getMetaData(), ignore)) - { - // - // The sequence is an instance of java.util.List<E>, where E is a fixed-size type. - // If the element type is bool or byte, we do NOT write an extra size. - // - - if(!elemBuiltin || - (elemBuiltin->kind() != Builtin::KindByte && elemBuiltin->kind() != Builtin::KindBool)) - { - out << nl << stream << ".skipSize();"; - } - } - else if(!findMetaData("java:protobuf:", seq->getMetaData(), ignore) && - !findMetaData("java:serializable:", seq->getMetaData(), ignore)) - { - if(!elemBuiltin || - (elemBuiltin->kind() != Builtin::KindByte && elemBuiltin->kind() != Builtin::KindBool)) - { - out << nl << stream << ".skipSize();"; - } - } - - writeStreamSequenceMarshalUnmarshalCode(out, package, seq, v, marshal, iter, true, metaData); - } - } - else - { - writeStreamSequenceMarshalUnmarshalCode(out, package, seq, v, marshal, iter, true, metaData); - } - return; - } - - ConstructedPtr constructed = ConstructedPtr::dynamicCast(type); - assert(constructed); - string typeS = getAbsolute(constructed, package); - if(marshal) - { - out << nl << typeS << "Helper.write(" << stream << ", " << v << ");"; - } - else - { - out << nl << v << " = " << typeS << "Helper.read(" << stream << ");"; - } -} - -void -Slice::JavaGenerator::writeStreamDictionaryMarshalUnmarshalCode(Output& out, - const string& package, - const DictionaryPtr& dict, - const string& param, - bool marshal, - int& iter, - bool useHelper, - const StringList& metaData) -{ - string stream = marshal ? "__outS" : "__inS"; - string v = param; - - // - // We have to determine whether it's possible to use the - // type's generated helper class for this marshal/unmarshal - // task. Since the user may have specified a custom type in - // metadata, it's possible that the helper class is not - // compatible and therefore we'll need to generate the code - // in-line instead. - // - // Specifically, there may be "local" metadata (i.e., from - // a data member or parameter definition) that overrides the - // original type. We'll compare the mapped types with and - // without local metadata to determine whether we can use - // the helper. - // - string instanceType, formalType; - getDictionaryTypes(dict, "", metaData, instanceType, formalType); - string origInstanceType, origFormalType; - getDictionaryTypes(dict, "", StringList(), origInstanceType, origFormalType); - if((formalType != origFormalType) || (!marshal && instanceType != origInstanceType)) - { - useHelper = false; - } - - // - // If we can use the helper, it's easy. - // - if(useHelper) - { - string typeS = getAbsolute(dict, package); - if(marshal) - { - out << nl << typeS << "Helper.write(" << stream << ", " << v << ");"; - } - else - { - out << nl << v << " = " << typeS << "Helper.read(" << stream << ");"; - } - return; - } - - TypePtr key = dict->keyType(); - TypePtr value = dict->valueType(); - - string keyS = typeToString(key, TypeModeIn, package); - string valueS = typeToString(value, TypeModeIn, package); - - ostringstream o; - o << iter; - string iterS = o.str(); - iter++; - - if(marshal) - { - out << nl << "if(" << v << " == null)"; - out << sb; - out << nl << "__outS.writeSize(0);"; - out << eb; - out << nl << "else"; - out << sb; - out << nl << "__outS.writeSize(" << v << ".size());"; - string keyObjectS = typeToObjectString(key, TypeModeIn, package); - string valueObjectS = typeToObjectString(value, TypeModeIn, package); - out << nl << "for(java.util.Map.Entry<" << keyObjectS << ", " << valueObjectS << "> __e : " << v - << ".entrySet())"; - out << sb; - for(int i = 0; i < 2; i++) - { - string arg; - TypePtr type; - if(i == 0) - { - arg = "__e.getKey()"; - type = key; - } - else - { - arg = "__e.getValue()"; - type = value; - } - writeStreamMarshalUnmarshalCode(out, package, type, false, 0, arg, true, iter, false); - } - out << eb; - out << eb; - } - else - { - out << nl << v << " = new " << instanceType << "();"; - out << nl << "int __sz" << iterS << " = __inS.readSize();"; - out << nl << "for(int __i" << iterS << " = 0; __i" << iterS << " < __sz" << iterS << "; __i" << iterS << "++)"; - out << sb; - for(int i = 0; i < 2; i++) - { - string arg; - TypePtr type; - string typeS; - if(i == 0) - { - arg = "__key"; - type = key; - typeS = keyS; - } - else - { - arg = "__value"; - type = value; - typeS = valueS; - } - - BuiltinPtr b = BuiltinPtr::dynamicCast(type); - string s = typeToString(type, TypeModeIn, package); - if(ClassDeclPtr::dynamicCast(type) || (b && b->kind() == Builtin::KindObject)) - { - string keyTypeStr = typeToObjectString(key, TypeModeIn, package); - string valueTypeStr = typeToObjectString(value, TypeModeIn, package); - writeStreamMarshalUnmarshalCode(out, package, type, false, 0, arg, false, iter, false, - StringList(), "new IceInternal.DictionaryPatcher<" + keyTypeStr + - ", " + valueTypeStr + ">(" + v + ", " + s + ".class, \"" + - type->typeId() + "\", __key)"); - } - else - { - if(StructPtr::dynamicCast(type)) - { - out << nl << s << ' ' << arg << " = null;"; - } - else - { - out << nl << s << ' ' << arg << ';'; - } - writeStreamMarshalUnmarshalCode(out, package, type, false, 0, arg, false, iter, false); - } - } - BuiltinPtr builtin = BuiltinPtr::dynamicCast(value); - if(!(builtin && (builtin->kind() == Builtin::KindObject || builtin->kind() == Builtin::KindValue)) && - !ClassDeclPtr::dynamicCast(value)) - { - out << nl << "" << v << ".put(__key, __value);"; - } - out << eb; - } -} - -void -Slice::JavaGenerator::writeStreamSequenceMarshalUnmarshalCode(Output& out, - const string& package, - const SequencePtr& seq, - const string& param, - bool marshal, - int& iter, - bool useHelper, - const StringList& metaData) -{ - string stream = marshal ? "__outS" : "__inS"; - string v = param; - - // - // If the sequence is a byte sequence, check if there's the serializable or protobuf metadata to - // get rid of these two easy cases first. - // - BuiltinPtr builtin = BuiltinPtr::dynamicCast(seq->type()); - if(builtin && builtin->kind() == Builtin::KindByte) - { - string meta; - static const string protobuf = "java:protobuf:"; - static const string serializable = "java:serializable:"; - if(seq->findMetaData(serializable, meta)) - { - if(marshal) - { - out << nl << stream << ".writeSerializable(" << v << ");"; - } - else - { - string type = typeToString(seq, TypeModeIn, package); - out << nl << v << " = (" << type << ")" << stream << ".readSerializable();"; - } - return; - } - else if(seq->findMetaData(protobuf, meta)) - { - if(marshal) - { - out << nl << "if(!" << v << ".isInitialized())"; - out << sb; - out << nl << "throw new Ice.MarshalException(\"type not fully initialized\");"; - out << eb; - out << nl << stream << ".writeByteSeq(" << v << ".toByteArray());"; - } - else - { - string type = meta.substr(protobuf.size()); - out << nl << "try"; - out << sb; - out << nl << v << " = " << type << ".parseFrom(" << stream << ".readByteSeq());"; - out << eb; - out << nl << "catch(com.google.protobuf.InvalidProtocolBufferException __ex)"; - out << sb; - out << nl << "Ice.MarshalException __mex = new Ice.MarshalException();"; - out << nl << "__mex.initCause(__ex);"; - out << nl << "throw __mex;"; - out << eb; - } - return; - } - } - - if(builtin && - (builtin->kind() == Builtin::KindByte || builtin->kind() == Builtin::KindShort || - builtin->kind() == Builtin::KindInt || builtin->kind() == Builtin::KindLong || - builtin->kind() == Builtin::KindFloat || builtin->kind() == Builtin::KindDouble)) - { - string meta; - static const string bytebuffer = "java:buffer"; - if(seq->findMetaData(bytebuffer, meta) || findMetaData(bytebuffer, metaData, meta)) - { - switch(builtin->kind()) - { - case Builtin::KindByte: - { - if(marshal) - { - out << nl << stream << ".writeByteBuffer(" << v << ");"; - } - else - { - out << nl << v << " = " << stream << ".readByteBuffer();"; - } - break; - } - case Builtin::KindShort: - { - if(marshal) - { - out << nl << stream << ".writeShortBuffer(" << v << ");"; - } - else - { - out << nl << v << " = " << stream << ".readShortBuffer();"; - } - break; - } - case Builtin::KindInt: - { - if(marshal) - { - out << nl << stream << ".writeIntBuffer(" << v << ");"; - } - else - { - out << nl << v << " = " << stream << ".readIntBuffer();"; - } - break; - } - case Builtin::KindLong: - { - if(marshal) - { - out << nl << stream << ".writeLongBuffer(" << v << ");"; - } - else - { - out << nl << v << " = " << stream << ".readLongBuffer();"; - } - break; - } - case Builtin::KindFloat: - { - if(marshal) - { - out << nl << stream << ".writeFloatBuffer(" << v << ");"; - } - else - { - out << nl << v << " = " << stream << ".readFloatBuffer();"; - } - break; - } - case Builtin::KindDouble: - { - if(marshal) - { - out << nl << stream << ".writeDoubleBuffer(" << v << ");"; - } - else - { - out << nl << v << " = " << stream << ".readDoubleBuffer();"; - } - break; - } - case Builtin::KindBool: - case Builtin::KindString: - case Builtin::KindObject: - case Builtin::KindObjectProxy: - case Builtin::KindLocalObject: - case Builtin::KindValue: - { - assert(false); - break; - } - } - return; - } - } - - // - // We have to determine whether it's possible to use the - // type's generated helper class for this marshal/unmarshal - // task. Since the user may have specified a custom type in - // metadata, it's possible that the helper class is not - // compatible and therefore we'll need to generate the code - // in-line instead. - // - // Specifically, there may be "local" metadata (i.e., from - // a data member or parameter definition) that overrides the - // original type. We'll compare the mapped types with and - // without local metadata to determine whether we can use - // the helper. - // - string instanceType, formalType; - bool customType = getSequenceTypes(seq, "", metaData, instanceType, formalType); - string origInstanceType, origFormalType; - getSequenceTypes(seq, "", StringList(), origInstanceType, origFormalType); - if((formalType != origFormalType) || (!marshal && instanceType != origInstanceType)) - { - useHelper = false; - } - - // - // If we can use the helper, it's easy. - // - if(useHelper) - { - string typeS = getAbsolute(seq, package); - if(marshal) - { - out << nl << typeS << "Helper.write(" << stream << ", " << v << ");"; - } - else - { - out << nl << v << " = " << typeS << "Helper.read(" << stream << ");"; - } - return; - } - - // - // Determine sequence depth - // - int depth = 0; - TypePtr origContent = seq->type(); - SequencePtr s = SequencePtr::dynamicCast(origContent); - while(s) - { - // - // Stop if the inner sequence type has a custom, serializable or protobuf type. - // - if(hasTypeMetaData(s)) - { - break; - } - depth++; - origContent = s->type(); - s = SequencePtr::dynamicCast(origContent); - } - string origContentS = typeToString(origContent, TypeModeIn, package); - - TypePtr type = seq->type(); - - if(customType) - { - // - // Marshal/unmarshal a custom sequence type. - // - BuiltinPtr b = BuiltinPtr::dynamicCast(type); - string typeS = getAbsolute(seq, package); - ostringstream o; - o << origContentS; - int d = depth; - while(d--) - { - o << "[]"; - } - string cont = o.str(); - if(marshal) - { - out << nl << "if(" << v << " == null)"; - out << sb; - out << nl << stream << ".writeSize(0);"; - out << eb; - out << nl << "else"; - out << sb; - out << nl << stream << ".writeSize(" << v << ".size());"; - string typeS = typeToString(type, TypeModeIn, package); - out << nl << "for(" << typeS << " __elem : " << v << ')'; - out << sb; - writeStreamMarshalUnmarshalCode(out, package, type, false, 0, "__elem", true, iter, false); - out << eb; - out << eb; // else - } - else - { - bool isObject = false; - ClassDeclPtr cl = ClassDeclPtr::dynamicCast(type); - if((b && (b->kind() == Builtin::KindObject || b->kind() == Builtin::KindValue)) || cl) - { - isObject = true; - } - out << nl << v << " = new " << instanceType << "();"; - out << nl << "final int __len" << iter << " = " << stream << ".readAndCheckSeqSize(" << type->minWireSize() - << ");"; - if(isObject) - { - if(b) - { - out << nl << "final String __type" << iter << " = Ice.ObjectImpl.ice_staticId();"; - } - else - { - assert(cl); - if(cl->isInterface()) - { - out << nl << "final String __type" << iter << " = " - << getAbsolute(cl, package, "_", "Disp") << ".ice_staticId();"; - } - else - { - out << nl << "final String __type" << iter << " = " << origContentS << ".ice_staticId();"; - } - } - } - out << nl << "for(int __i" << iter << " = 0; __i" << iter << " < __len" << iter << "; __i" << iter - << "++)"; - out << sb; - if(isObject) - { - // - // Add a null value to the list as a placeholder for the element. - // - out << nl << v << ".add(null);"; - ostringstream patchParams; - patchParams << "new IceInternal.ListPatcher<" << origContentS << ">(" << v << ", " << origContentS - << ".class, __type" << iter << ", __i" << iter << ')'; - writeStreamMarshalUnmarshalCode(out, package, type, false, 0, "__elem", false, iter, false, - StringList(), patchParams.str()); - } - else - { - if(StructPtr::dynamicCast(type)) - { - out << nl << cont << " __elem = null;"; - } - else - { - out << nl << cont << " __elem;"; - } - writeStreamMarshalUnmarshalCode(out, package, type, false, 0, "__elem", false, iter, false); - } - if(!isObject) - { - out << nl << v << ".add(__elem);"; - } - out << eb; - iter++; - } - } - else - { - BuiltinPtr b = BuiltinPtr::dynamicCast(type); - if(b && b->kind() != Builtin::KindObject && - b->kind() != Builtin::KindValue && - b->kind() != Builtin::KindObjectProxy) - { - switch(b->kind()) - { - case Builtin::KindByte: - { - if(marshal) - { - out << nl << stream << ".writeByteSeq(" << v << ");"; - } - else - { - out << nl << v << " = " << stream << ".readByteSeq();"; - } - break; - } - case Builtin::KindBool: - { - if(marshal) - { - out << nl << stream << ".writeBoolSeq(" << v << ");"; - } - else - { - out << nl << v << " = " << stream << ".readBoolSeq();"; - } - break; - } - case Builtin::KindShort: - { - if(marshal) - { - out << nl << stream << ".writeShortSeq(" << v << ");"; - } - else - { - out << nl << v << " = " << stream << ".readShortSeq();"; - } - break; - } - case Builtin::KindInt: - { - if(marshal) - { - out << nl << stream << ".writeIntSeq(" << v << ");"; - } - else - { - out << nl << v << " = " << stream << ".readIntSeq();"; - } - break; - } - case Builtin::KindLong: - { - if(marshal) - { - out << nl << stream << ".writeLongSeq(" << v << ");"; - } - else - { - out << nl << v << " = " << stream << ".readLongSeq();"; - } - break; - } - case Builtin::KindFloat: - { - if(marshal) - { - out << nl << stream << ".writeFloatSeq(" << v << ");"; - } - else - { - out << nl << v << " = " << stream << ".readFloatSeq();"; - } - break; - } - case Builtin::KindDouble: - { - if(marshal) - { - out << nl << stream << ".writeDoubleSeq(" << v << ");"; - } - else - { - out << nl << v << " = " << stream << ".readDoubleSeq();"; - } - break; - } - case Builtin::KindString: - { - if(marshal) - { - out << nl << stream << ".writeStringSeq(" << v << ");"; - } - else - { - out << nl << v << " = " << stream << ".readStringSeq();"; - } - break; - } - case Builtin::KindObject: - case Builtin::KindObjectProxy: - case Builtin::KindLocalObject: - case Builtin::KindValue: - { - assert(false); - break; - } - } - } - else - { - if(marshal) - { - out << nl << "if(" << v << " == null)"; - out << sb; - out << nl << stream << ".writeSize(0);"; - out << eb; - out << nl << "else"; - out << sb; - out << nl << stream << ".writeSize(" << v << ".length);"; - out << nl << "for(int __i" << iter << " = 0; __i" << iter << " < " << v << ".length; __i" << iter - << "++)"; - out << sb; - ostringstream o; - o << v << "[__i" << iter << "]"; - iter++; - writeStreamMarshalUnmarshalCode(out, package, type, false, 0, o.str(), true, iter, false); - out << eb; - out << eb; - } - else - { - bool isObject = false; - ClassDeclPtr cl = ClassDeclPtr::dynamicCast(origContent); - if((b && (b->kind() == Builtin::KindObject || b->kind() == Builtin::KindValue)) || cl) - { - isObject = true; - } - out << nl << "final int __len" << iter << " = " << stream << ".readAndCheckSeqSize(" - << type->minWireSize() << ");"; - if(isObject) - { - if(b) - { - out << nl << "final String __type" << iter << " = Ice.ObjectImpl.ice_staticId();"; - } - else - { - assert(cl); - if(cl->isInterface()) - { - out << nl << "final String __type" << iter << " = " - << getAbsolute(cl, package, "_", "Disp") << ".ice_staticId();"; - } - else - { - out << nl << "final String __type" << iter << " = " << origContentS << ".ice_staticId();"; - } - } - } - // - // We cannot allocate an array of a generic type, such as - // - // arr = new Map<String, String>[sz]; - // - // Attempting to compile this code results in a "generic array creation" error - // message. This problem can occur when the sequence's element type is a - // dictionary, or when the element type is a nested sequence that uses a custom - // mapping. - // - // The solution is to rewrite the code as follows: - // - // arr = (Map<String, String>[])new Map[sz]; - // - // Unfortunately, this produces an unchecked warning during compilation. - // - // A simple test is to look for a "<" character in the content type, which - // indicates the use of a generic type. - // - string::size_type pos = origContentS.find('<'); - if(pos != string::npos) - { - string nonGenericType = origContentS.substr(0, pos); - out << nl << v << " = (" << origContentS << "[]"; - int d = depth; - while(d--) - { - out << "[]"; - } - out << ")new " << nonGenericType << "[__len" << iter << "]"; - } - else - { - out << nl << v << " = new " << origContentS << "[__len" << iter << "]"; - } - int d = depth; - while(d--) - { - out << "[]"; - } - out << ';'; - out << nl << "for(int __i" << iter << " = 0; __i" << iter << " < __len" << iter << "; __i" << iter - << "++)"; - out << sb; - ostringstream o; - o << v << "[__i" << iter << "]"; - ostringstream patchParams; - if(isObject) - { - patchParams << "new IceInternal.SequencePatcher(" << v << ", " << origContentS - << ".class, __type" << iter << ", __i" << iter << ')'; - writeStreamMarshalUnmarshalCode(out, package, type, false, 0, o.str(), false, iter, false, - StringList(), patchParams.str()); - } - else - { - writeStreamMarshalUnmarshalCode(out, package, type, false, 0, o.str(), false, iter, false); - } - out << eb; - iter++; - } - } - } -} - bool Slice::JavaGenerator::findMetaData(const string& prefix, const StringList& metaData, string& value) { diff --git a/cpp/src/slice2java/Gen.cpp b/cpp/src/slice2java/Gen.cpp index 8df6121d117..447b960ac48 100644 --- a/cpp/src/slice2java/Gen.cpp +++ b/cpp/src/slice2java/Gen.cpp @@ -761,7 +761,7 @@ Slice::JavaVisitor::writeMarshalDataMember(Output& out, const string& package, c } else { - out << nl << "if(__has_" << member->name() << " && __os.writeOpt(" << member->tag() << ", " + out << nl << "if(__has_" << member->name() << " && __os.writeOptional(" << member->tag() << ", " << getOptionalFormat(member->type()) << "))"; out << sb; writeMarshalUnmarshalCode(out, package, member->type(), OptionalMember, false, 0, fixKwd(member->name()), true, @@ -793,7 +793,7 @@ Slice::JavaVisitor::writeUnmarshalDataMember(Output& out, const string& package, } else { - out << nl << "if(__has_" << member->name() << " = __is.readOpt(" << member->tag() << ", " + out << nl << "if(__has_" << member->name() << " = __is.readOptional(" << member->tag() << ", " << getOptionalFormat(member->type()) << "))"; out << sb; writeMarshalUnmarshalCode(out, package, member->type(), OptionalMember, false, 0, fixKwd(member->name()), false, @@ -803,66 +803,10 @@ Slice::JavaVisitor::writeUnmarshalDataMember(Output& out, const string& package, } void -Slice::JavaVisitor::writeStreamMarshalDataMember(Output& out, const string& package, const DataMemberPtr& member, - int& iter) -{ - if(!member->optional()) - { - writeStreamMarshalUnmarshalCode(out, package, member->type(), false, 0, fixKwd(member->name()), true, - iter, false, member->getMetaData()); - } - else - { - out << nl << "if(__has_" << member->name() << " && __outS.writeOptional(" << member->tag() << ", " - << getOptionalFormat(member->type()) << "))"; - out << sb; - writeStreamMarshalUnmarshalCode(out, package, member->type(), true, member->tag(), fixKwd(member->name()), - true, iter, false, member->getMetaData()); - out << eb; - } -} - -void -Slice::JavaVisitor::writeStreamUnmarshalDataMember(Output& out, const string& package, const DataMemberPtr& member, - int& iter, bool needPatcher, int& patchIter) -{ - string patchParams; - if(needPatcher) - { - BuiltinPtr builtin = BuiltinPtr::dynamicCast(member->type()); - if((builtin && builtin->kind() == Builtin::KindObject) || ClassDeclPtr::dynamicCast(member->type())) - { - ostringstream ostr; - ostr << "new Patcher(" << patchIter++ << ')'; - patchParams = ostr.str(); - } - } - - if(!member->optional()) - { - writeStreamMarshalUnmarshalCode(out, package, member->type(), false, 0, fixKwd(member->name()), false, - iter, false, member->getMetaData(), patchParams); - } - else - { - out << nl << "if(__has_" << member->name() << " = __inS.readOptional(" << member->tag() << ", " - << getOptionalFormat(member->type()) << "))"; - out << sb; - writeStreamMarshalUnmarshalCode(out, package, member->type(), true, member->tag(), fixKwd(member->name()), - false, iter, false, member->getMetaData(), patchParams); - out << eb; - } -} - -void Slice::JavaVisitor::writePatcher(Output& out, const string& package, const DataMemberList& classMembers, - const DataMemberList& optionalMembers, bool stream) + const DataMemberList& optionalMembers) { - out << sp << nl << "private class Patcher implements IceInternal.Patcher"; - if(stream) - { - out << ", Ice.ReadObjectCallback"; - } + out << sp << nl << "private class Patcher implements Ice.ReadObjectCallback"; out << sb; if(classMembers.size() > 1) { @@ -872,7 +816,7 @@ Slice::JavaVisitor::writePatcher(Output& out, const string& package, const DataM out << eb; } - out << sp << nl << "public void" << nl << "patch(Ice.Object v)"; + out << sp << nl << "public void" << nl << "objectReady(Ice.Object v)"; out << sb; if(classMembers.size() > 1) { @@ -1009,14 +953,6 @@ Slice::JavaVisitor::writePatcher(Output& out, const string& package, const DataM } out << eb; - if(stream) - { - out << sp << nl << "public void" << nl << "invoke(Ice.Object v)"; - out << sb; - out << nl << "patch(v);"; - out << eb; - } - if(classMembers.size() > 1) { out << sp << nl << "private int __member;"; @@ -1027,7 +963,7 @@ Slice::JavaVisitor::writePatcher(Output& out, const string& package, const DataM } void -Slice::JavaVisitor::writeDispatchAndMarshalling(Output& out, const ClassDefPtr& p, bool stream) +Slice::JavaVisitor::writeDispatchAndMarshalling(Output& out, const ClassDefPtr& p) { string name = fixKwd(p->name()); string package = getPackage(p); @@ -1295,7 +1231,7 @@ Slice::JavaVisitor::writeDispatchAndMarshalling(Output& out, const ClassDefPtr& // // Unmarshal 'in' parameters. // - out << nl << "IceInternal.BasicStream __is = __inS.startReadParams();"; + out << nl << "Ice.InputStream __is = __inS.startReadParams();"; for(ParamDeclList::const_iterator pli = inParams.begin(); pli != inParams.end(); ++pli) { TypePtr paramType = (*pli)->type(); @@ -1387,7 +1323,7 @@ Slice::JavaVisitor::writeDispatchAndMarshalling(Output& out, const ClassDefPtr& // if(!outParams.empty() || ret) { - out << nl << "IceInternal.BasicStream __os = __inS.__startWriteParams(" + out << nl << "Ice.OutputStream __os = __inS.__startWriteParams(" << opFormatTypeToString(op) << ");"; writeMarshalUnmarshalParams(out, package, outParams, op, iter, true, optionalMapping, true); if(op->returnsClasses(false)) @@ -1442,7 +1378,7 @@ Slice::JavaVisitor::writeDispatchAndMarshalling(Output& out, const ClassDefPtr& // // Unmarshal 'in' parameters. // - out << nl << "IceInternal.BasicStream __is = __inS.startReadParams();"; + out << nl << "Ice.InputStream __is = __inS.startReadParams();"; iter = 0; for(ParamDeclList::const_iterator pli = inParams.begin(); pli != inParams.end(); ++pli) { @@ -1687,48 +1623,24 @@ Slice::JavaVisitor::writeDispatchAndMarshalling(Output& out, const ClassDefPtr& if(preserved && !basePreserved) { - out << sp << nl << "public void __write(IceInternal.BasicStream __os)"; + out << sp << nl << "public void __write(Ice.OutputStream __os)"; out << sb; - out << nl << "__os.startWriteObject(__slicedData);"; + out << nl << "__os.startObject(__slicedData);"; out << nl << "__writeImpl(__os);"; - out << nl << "__os.endWriteObject();"; + out << nl << "__os.endObject();"; out << eb; - out << sp << nl << "public void __read(IceInternal.BasicStream __is)"; + out << sp << nl << "public void __read(Ice.InputStream __is)"; out << sb; - out << nl << "__is.startReadObject();"; + out << nl << "__is.startObject();"; out << nl << "__readImpl(__is);"; - out << nl << "__slicedData = __is.endReadObject(true);"; + out << nl << "__slicedData = __is.endObject(true);"; out << eb; - - if(stream) - { - out << sp << nl << "public void __write(Ice.OutputStream __outS)"; - out << sb; - if(preserved) - { - out << nl << "__outS.startObject(__slicedData);"; - } - else - { - out << nl << "__outS.startObject(null);"; - } - out << nl << "__writeImpl(__outS);"; - out << nl << "__outS.endObject();"; - out << eb; - - out << sp << nl << "public void __read(Ice.InputStream __inS)"; - out << sb; - out << nl << "__inS.startObject();"; - out << nl << "__readImpl(__inS);"; - out << nl << "__slicedData = __inS.endObject(true);"; - out << eb; - } } - out << sp << nl << "protected void __writeImpl(IceInternal.BasicStream __os)"; + out << sp << nl << "protected void __writeImpl(Ice.OutputStream __os)"; out << sb; - out << nl << "__os.startWriteSlice(ice_staticId(), " << p->compactId() << (!base ? ", true" : ", false") << ");"; + out << nl << "__os.startSlice(ice_staticId(), " << p->compactId() << (!base ? ", true" : ", false") << ");"; iter = 0; for(DataMemberList::const_iterator d = members.begin(); d != members.end(); ++d) { @@ -1741,7 +1653,7 @@ Slice::JavaVisitor::writeDispatchAndMarshalling(Output& out, const ClassDefPtr& { writeMarshalDataMember(out, package, *d, iter); } - out << nl << "__os.endWriteSlice();"; + out << nl << "__os.endSlice();"; if(base) { out << nl << "super.__writeImpl(__os);"; @@ -1753,12 +1665,12 @@ Slice::JavaVisitor::writeDispatchAndMarshalling(Output& out, const ClassDefPtr& if(classMembers.size() != 0) { - writePatcher(out, package, classMembers, optionalMembers, stream); + writePatcher(out, package, classMembers, optionalMembers); } - out << sp << nl << "protected void __readImpl(IceInternal.BasicStream __is)"; + out << sp << nl << "protected void __readImpl(Ice.InputStream __is)"; out << sb; - out << nl << "__is.startReadSlice();"; + out << nl << "__is.startSlice();"; int patchIter = 0; const bool needCustomPatcher = classMembers.size() > 1; @@ -1774,61 +1686,13 @@ Slice::JavaVisitor::writeDispatchAndMarshalling(Output& out, const ClassDefPtr& { writeUnmarshalDataMember(out, package, *d, iter, needCustomPatcher, patchIter); } - out << nl << "__is.endReadSlice();"; + out << nl << "__is.endSlice();"; if(base) { out << nl << "super.__readImpl(__is);"; } out << eb; - if(stream) - { - out << sp << nl << "protected void __writeImpl(Ice.OutputStream __outS)"; - out << sb; - out << nl << "__outS.startSlice(ice_staticId(), " << p->compactId() << (!base ? ", true" : ", false") << ");"; - iter = 0; - for(DataMemberList::const_iterator d = members.begin(); d != members.end(); ++d) - { - if(!(*d)->optional()) - { - writeStreamMarshalDataMember(out, package, *d, iter); - } - } - for(DataMemberList::const_iterator d = optionalMembers.begin(); d != optionalMembers.end(); ++d) - { - writeStreamMarshalDataMember(out, package, *d, iter); - } - out << nl << "__outS.endSlice();"; - if(base) - { - out << nl << "super.__writeImpl(__outS);"; - } - out << eb; - - out << sp << nl << "protected void __readImpl(Ice.InputStream __inS)"; - out << sb; - out << nl << "__inS.startSlice();"; - iter = 0; - patchIter = 0; - for(DataMemberList::const_iterator d = members.begin(); d != members.end(); ++d) - { - if(!(*d)->optional()) - { - writeStreamUnmarshalDataMember(out, package, *d, iter, needCustomPatcher, patchIter); - } - } - for(DataMemberList::const_iterator d = optionalMembers.begin(); d != optionalMembers.end(); ++d) - { - writeStreamUnmarshalDataMember(out, package, *d, iter, needCustomPatcher, patchIter); - } - out << nl << "__inS.endSlice();"; - if(base) - { - out << nl << "super.__readImpl(__inS);"; - } - out << eb; - } - if(preserved && !basePreserved) { out << sp << nl << "protected Ice.SlicedData __slicedData;"; @@ -2397,7 +2261,7 @@ Slice::Gen::~Gen() } void -Slice::Gen::generate(const UnitPtr& p, bool stream) +Slice::Gen::generate(const UnitPtr& p) { JavaGenerator::validateMetaData(p); @@ -2407,7 +2271,7 @@ Slice::Gen::generate(const UnitPtr& p, bool stream) PackageVisitor packageVisitor(_dir); p->visit(&packageVisitor, false); - TypesVisitor typesVisitor(_dir, stream); + TypesVisitor typesVisitor(_dir); p->visit(&typesVisitor, false); CompactIdVisitor compactIdVisitor(_dir); @@ -2416,13 +2280,13 @@ Slice::Gen::generate(const UnitPtr& p, bool stream) HolderVisitor holderVisitor(_dir); p->visit(&holderVisitor, false); - HelperVisitor helperVisitor(_dir, stream); + HelperVisitor helperVisitor(_dir); p->visit(&helperVisitor, false); ProxyVisitor proxyVisitor(_dir); p->visit(&proxyVisitor, false); - DispatcherVisitor dispatcherVisitor(_dir, stream); + DispatcherVisitor dispatcherVisitor(_dir); p->visit(&dispatcherVisitor, false); AsyncVisitor asyncVisitor(_dir); @@ -2884,8 +2748,8 @@ Slice::Gen::PackageVisitor::visitModuleStart(const ModulePtr& p) return false; } -Slice::Gen::TypesVisitor::TypesVisitor(const string& dir, bool stream) : - JavaVisitor(dir), _stream(stream) +Slice::Gen::TypesVisitor::TypesVisitor(const string& dir) : + JavaVisitor(dir) { } @@ -3298,7 +3162,7 @@ Slice::Gen::TypesVisitor::visitClassDefStart(const ClassDefPtr& p) // if(!p->isInterface() && !p->isLocal()) { - writeDispatchAndMarshalling(out, p, _stream); + writeDispatchAndMarshalling(out, p); } return true; @@ -3682,41 +3546,24 @@ Slice::Gen::TypesVisitor::visitExceptionEnd(const ExceptionPtr& p) if(preserved && !basePreserved) { - out << sp << nl << "public void" << nl << "__write(IceInternal.BasicStream __os)"; + out << sp << nl << "public void" << nl << "__write(Ice.OutputStream __os)"; out << sb; - out << nl << "__os.startWriteException(__slicedData);"; + out << nl << "__os.startException(__slicedData);"; out << nl << "__writeImpl(__os);"; - out << nl << "__os.endWriteException();"; + out << nl << "__os.endException();"; out << eb; - out << sp << nl << "public void" << nl << "__read(IceInternal.BasicStream __is)"; + out << sp << nl << "public void" << nl << "__read(Ice.InputStream __is)"; out << sb; - out << nl << "__is.startReadException();"; + out << nl << "__is.startException();"; out << nl << "__readImpl(__is);"; - out << nl << "__slicedData = __is.endReadException(true);"; + out << nl << "__slicedData = __is.endException(true);"; out << eb; - - if(_stream) - { - out << sp << nl << "public void" << nl << "__write(Ice.OutputStream __outS)"; - out << sb; - out << nl << "__outS.startException(__slicedData);"; - out << nl << "__writeImpl(__outS);"; - out << nl << "__outS.endException();"; - out << eb; - - out << sp << nl << "public void" << nl << "__read(Ice.InputStream __inS)"; - out << sb; - out << nl << "__inS.startException();"; - out << nl << "__readImpl(__inS);"; - out << nl << "__slicedData = __inS.endException(true);"; - out << eb; - } } - out << sp << nl << "protected void" << nl << "__writeImpl(IceInternal.BasicStream __os)"; + out << sp << nl << "protected void" << nl << "__writeImpl(Ice.OutputStream __os)"; out << sb; - out << nl << "__os.startWriteSlice(\"" << scoped << "\", -1, " << (!base ? "true" : "false") << ");"; + out << nl << "__os.startSlice(\"" << scoped << "\", -1, " << (!base ? "true" : "false") << ");"; iter = 0; for(DataMemberList::const_iterator d = members.begin(); d != members.end(); ++d) { @@ -3729,7 +3576,7 @@ Slice::Gen::TypesVisitor::visitExceptionEnd(const ExceptionPtr& p) { writeMarshalDataMember(out, package, *d, iter); } - out << nl << "__os.endWriteSlice();"; + out << nl << "__os.endSlice();"; if(base) { out << nl << "super.__writeImpl(__os);"; @@ -3741,11 +3588,11 @@ Slice::Gen::TypesVisitor::visitExceptionEnd(const ExceptionPtr& p) if(classMembers.size() != 0) { - writePatcher(out, package, classMembers, optionalMembers, _stream); + writePatcher(out, package, classMembers, optionalMembers); } - out << sp << nl << "protected void" << nl << "__readImpl(IceInternal.BasicStream __is)"; + out << sp << nl << "protected void" << nl << "__readImpl(Ice.InputStream __is)"; out << sb; - out << nl << "__is.startReadSlice();"; + out << nl << "__is.startSlice();"; iter = 0; int patchIter = 0; const bool needCustomPatcher = classMembers.size() > 1; @@ -3760,61 +3607,13 @@ Slice::Gen::TypesVisitor::visitExceptionEnd(const ExceptionPtr& p) { writeUnmarshalDataMember(out, package, *d, iter, needCustomPatcher, patchIter); } - out << nl << "__is.endReadSlice();"; + out << nl << "__is.endSlice();"; if(base) { out << nl << "super.__readImpl(__is);"; } out << eb; - if(_stream) - { - out << sp << nl << "protected void" << nl << "__writeImpl(Ice.OutputStream __outS)"; - out << sb; - out << nl << "__outS.startSlice(\"" << scoped << "\", -1, " << (!base ? "true" : "false") << ");"; - iter = 0; - for(DataMemberList::const_iterator d = members.begin(); d != members.end(); ++d) - { - if(!(*d)->optional()) - { - writeStreamMarshalDataMember(out, package, *d, iter); - } - } - for(DataMemberList::const_iterator d = optionalMembers.begin(); d != optionalMembers.end(); ++d) - { - writeStreamMarshalDataMember(out, package, *d, iter); - } - out << nl << "__outS.endSlice();"; - if(base) - { - out << nl << "super.__writeImpl(__outS);"; - } - out << eb; - - out << sp << nl << "protected void" << nl << "__readImpl(Ice.InputStream __inS)"; - out << sb; - out << nl << "__inS.startSlice();"; - iter = 0; - patchIter = 0; - for(DataMemberList::const_iterator d = members.begin(); d != members.end(); ++d) - { - if(!(*d)->optional()) - { - writeStreamUnmarshalDataMember(out, package, *d, iter, needCustomPatcher, patchIter); - } - } - for(DataMemberList::const_iterator d = optionalMembers.begin(); d != optionalMembers.end(); ++d) - { - writeStreamUnmarshalDataMember(out, package, *d, iter, needCustomPatcher, patchIter); - } - out << nl << "__inS.endSlice();"; - if(base) - { - out << nl << "super.__readImpl(__inS);"; - } - out << eb; - } - if(p->usesClasses(false)) { if(!base || (base && !base->usesClasses(false))) @@ -4074,7 +3873,7 @@ Slice::Gen::TypesVisitor::visitStructEnd(const StructPtr& p) if(!p->isLocal()) { - out << sp << nl << "public void" << nl << "__write(IceInternal.BasicStream __os)"; + out << sp << nl << "public void" << nl << "ice_write(Ice.OutputStream __os)"; out << sb; iter = 0; for(DataMemberList::const_iterator d = members.begin(); d != members.end(); ++d) @@ -4087,10 +3886,10 @@ Slice::Gen::TypesVisitor::visitStructEnd(const StructPtr& p) if(classMembers.size() != 0) { - writePatcher(out, package, classMembers, DataMemberList(), _stream); + writePatcher(out, package, classMembers, DataMemberList()); } - out << sp << nl << "public void" << nl << "__read(IceInternal.BasicStream __is)"; + out << sp << nl << "public void" << nl << "ice_read(Ice.InputStream __is)"; out << sb; iter = 0; int patchIter = 0; @@ -4101,75 +3900,28 @@ Slice::Gen::TypesVisitor::visitStructEnd(const StructPtr& p) } out << eb; - if(_stream) - { - out << sp << nl << "public void" << nl << "ice_write(Ice.OutputStream __outS)"; - out << sb; - iter = 0; - for(DataMemberList::const_iterator d = members.begin(); d != members.end(); ++d) - { - writeStreamMarshalDataMember(out, package, *d, iter); - } - out << eb; - - out << sp << nl << "public void" << nl << "ice_read(Ice.InputStream __inS)"; - out << sb; - iter = 0; - patchIter = 0; - for(DataMemberList::const_iterator d = members.begin(); d != members.end(); ++d) - { - writeStreamUnmarshalDataMember(out, package, *d, iter, needCustomPatcher, patchIter); - } - out << eb; - } - - out << sp << nl << "static public void" << nl << "__write(IceInternal.BasicStream __os, " << name << " __v)"; + out << sp << nl << "static public void" << nl << "ice_write(Ice.OutputStream __os, " << name << " __v)"; out << sb; out << nl << "if(__v == null)"; out << sb; - out << nl << "__nullMarshalValue.__write(__os);"; + out << nl << "__nullMarshalValue.ice_write(__os);"; out << eb; out << nl << "else"; out << sb; - out << nl << "__v.__write(__os);"; + out << nl << "__v.ice_write(__os);"; out << eb; out << eb; - out << sp << nl << "static public " << name << nl << "__read(IceInternal.BasicStream __is, " << name << " __v)"; + out << sp << nl << "static public " << name << nl << "ice_read(Ice.InputStream __is, " << name << " __v)"; out << sb; out << nl << "if(__v == null)"; out << sb; out << nl << " __v = new " << name << "();"; out << eb; - out << nl << "__v.__read(__is);"; + out << nl << "__v.ice_read(__is);"; out << nl << "return __v;"; out << eb; - if(_stream) - { - out << sp << nl << "static public void" << nl << "ice_write(Ice.OutputStream __outS, " << name << " __v)"; - out << sb; - out << nl << "if(__v == null)"; - out << sb; - out << nl << "__nullMarshalValue.ice_write(__outS);"; - out << eb; - out << nl << "else"; - out << sb; - out << nl << "__v.ice_write(__outS);"; - out << eb; - out << eb; - - out << sp << nl << "static public " << name << nl << "ice_read(Ice.InputStream __inS, " << name << " __v)"; - out << sb; - out << nl << "if(__v == null)"; - out << sb; - out << nl << " __v = new " << name << "();"; - out << eb; - out << nl << "__v.ice_read(__inS);"; - out << nl << "return __v;"; - out << eb; - } - out << nl << nl << "private static final " << name << " __nullMarshalValue = new " << name << "();"; } @@ -4539,12 +4291,12 @@ Slice::Gen::TypesVisitor::visitEnum(const EnumPtr& p) if(!p->isLocal()) { - out << sp << nl << "public void" << nl << "__write(IceInternal.BasicStream __os)"; + out << sp << nl << "public void" << nl << "ice_write(Ice.OutputStream __os)"; out << sb; out << nl << "__os.writeEnum(value(), " << p->maxValue() << ");"; out << eb; - out << sp << nl << "public static void" << nl << "__write(IceInternal.BasicStream __os, " << name << " __v)"; + out << sp << nl << "public static void" << nl << "ice_write(Ice.OutputStream __os, " << name << " __v)"; out << sb; out << nl << "if(__v == null)"; out << sb; @@ -4557,38 +4309,12 @@ Slice::Gen::TypesVisitor::visitEnum(const EnumPtr& p) out << eb; out << eb; - out << sp << nl << "public static " << name << nl << "__read(IceInternal.BasicStream __is)"; + out << sp << nl << "public static " << name << nl << "ice_read(Ice.InputStream __is)"; out << sb; out << nl << "int __v = __is.readEnum(" << p->maxValue() << ");"; out << nl << "return __validate(__v);"; out << eb; - if(_stream) - { - out << sp << nl << "public void" << nl << "ice_write(Ice.OutputStream __outS)"; - out << sb; - out << nl << "__outS.writeEnum(value(), " << p->maxValue() << ");"; - out << eb; - - out << sp << nl << "public static void" << nl << "ice_write(Ice.OutputStream __outS, " << name << " __v)"; - out << sb; - out << nl << "if(__v == null)"; - out << sb; - out << nl << "__outS.writeEnum(" << absolute << '.' << firstEnum << ".value(), " << p->maxValue() << ");"; - out << eb; - out << nl << "else"; - out << sb; - out << nl << "__outS.writeEnum(__v.value(), " << p->maxValue() << ");"; - out << eb; - out << eb; - - out << sp << nl << "public static " << name << nl << "ice_read(Ice.InputStream __inS)"; - out << sb; - out << nl << "int __v = __inS.readEnum(" << p->maxValue() << ");"; - out << nl << "return __validate(__v);"; - out << eb; - } - out << sp << nl << "private static " << name << nl << "__validate(int __v)"; out << sb; @@ -4786,7 +4512,7 @@ Slice::Gen::HolderVisitor::writeHolder(const TypePtr& p) out << eb; out << sp << nl << "public void"; - out << nl << "patch(Ice.Object v)"; + out << nl << "objectReady(Ice.Object v)"; out << sb; out << nl << "if(v == null || v instanceof " << typeS << ")"; out << sb; @@ -4830,8 +4556,8 @@ Slice::Gen::HolderVisitor::writeHolder(const TypePtr& p) close(); } -Slice::Gen::HelperVisitor::HelperVisitor(const string& dir, bool stream) : - JavaVisitor(dir), _stream(stream) +Slice::Gen::HelperVisitor::HelperVisitor(const string& dir) : + JavaVisitor(dir) { } @@ -4949,7 +4675,7 @@ Slice::Gen::HelperVisitor::visitClassDefStart(const ClassDefPtr& p) if(ret || !outParams.empty()) { - out << nl << "IceInternal.BasicStream __is = __result.startReadParams();"; + out << nl << "Ice.InputStream __is = __result.startReadParams();"; const ParamDeclList paramList = op->parameters(); ParamDeclList pl; for(ParamDeclList::const_iterator pli = paramList.begin(); pli != paramList.end(); ++pli) @@ -5157,12 +4883,12 @@ Slice::Gen::HelperVisitor::visitClassDefStart(const ClassDefPtr& p) out << nl << "return __ids[" << scopedPos << "];"; out << eb; - out << sp << nl << "public static void __write(IceInternal.BasicStream __os, " << name << "Prx v)"; + out << sp << nl << "public static void __write(Ice.OutputStream __os, " << name << "Prx v)"; out << sb; out << nl << "__os.writeProxy(v);"; out << eb; - out << sp << nl << "public static " << name << "Prx __read(IceInternal.BasicStream __is)"; + out << sp << nl << "public static " << name << "Prx __read(Ice.InputStream __is)"; out << sb; out << nl << "Ice.ObjectPrx proxy = __is.readProxy();"; out << nl << "if(proxy != null)"; @@ -5174,31 +4900,6 @@ Slice::Gen::HelperVisitor::visitClassDefStart(const ClassDefPtr& p) out << nl << "return null;"; out << eb; - if(_stream) - { - out << sp << nl << "public static void write(Ice.OutputStream __outS, " << name << "Prx v)"; - out << sb; - out << nl << "__outS.writeProxy(v);"; - out << eb; - - out << sp << nl << "public static " << name << "Prx read(Ice.InputStream __inS)"; - out << sb; - out << nl << "Ice.ObjectPrx proxy = __inS.readProxy();"; - out << nl << "if(proxy != null)"; - out << sb; - out << nl << name << "PrxHelper result = new " << name << "PrxHelper();"; - out << nl << "result.__copyFrom(proxy);"; - out << nl << "return result;"; - out << eb; - out << nl << "return null;"; - out << eb; - - out << sp << nl << "public static Ice.OptionalFormat optionalFormat()"; - out << sb; - out << nl << "return Ice.OptionalFormat.FSize;"; - out << eb; - } - // // Avoid serialVersionUID warnings for Proxy Helper classes. // @@ -5207,76 +4908,6 @@ Slice::Gen::HelperVisitor::visitClassDefStart(const ClassDefPtr& p) close(); - if(_stream) - { - // - // Class helper. - // - open(getAbsolute(p, "", "", "Helper"), p->file()); - - Output& out2 = output(); - - out2 << sp << nl << "public final class " << name << "Helper"; - out2 << sb; - - out2 << sp << nl << "public static void write(Ice.OutputStream __outS, " << fixKwd(name) << " __v)"; - out2 << sb; - out2 << nl << "__outS.writeObject(__v);"; - out2 << eb; - - out2 << sp << nl << "public static void read(Ice.InputStream __inS, " << name << "Holder __h)"; - out2 << sb; - out2 << nl << "__inS.readObject(__h);"; - out2 << eb; - - out2 << sp << nl << "public static Ice.OptionalFormat optionalFormat()"; - out2 << sb; - out2 << nl << "return " << getOptionalFormat(p->declaration()) << ';'; - out2 << eb; - - out2 << eb; - close(); - } - - return false; -} - -bool -Slice::Gen::HelperVisitor::visitStructStart(const StructPtr& p) -{ - if(!p->isLocal() && _stream) - { - string name = p->name(); - string fixedName = fixKwd(name); - - open(getAbsolute(p, "", "", "Helper"), p->file()); - - Output& out = output(); - - out << sp << nl << "public final class " << name << "Helper"; - out << sb; - - out << sp << nl << "public static void write(Ice.OutputStream __outS, " << fixedName << " __v)"; - out << sb; - out << nl << "__v.ice_write(__outS);"; - out << eb; - - out << sp << nl << "public static " << fixedName << " read(Ice.InputStream __inS)"; - out << sb; - out << nl << fixedName << " __v = new " << fixedName << "();"; - out << nl << "__v.ice_read(__inS);"; - out << nl << "return __v;"; - out << eb; - - out << sp << nl << "public static Ice.OptionalFormat optionalFormat()"; - out << sb; - out << nl << "return " << getOptionalFormat(p) << ';'; - out << eb; - - out << eb; - close(); - } - return false; } @@ -5370,7 +5001,7 @@ Slice::Gen::HelperVisitor::visitSequence(const SequencePtr& p) out << sp << nl << "public final class " << name << "Helper"; out << sb; - out << nl << "public static void" << nl << "write(IceInternal.BasicStream __os, " << typeS << " __v)"; + out << nl << "public static void" << nl << "write(Ice.OutputStream __os, " << typeS << " __v)"; out << sb; iter = 0; writeSequenceMarshalUnmarshalCode(out, package, p, "__v", true, iter, false); @@ -5381,7 +5012,7 @@ Slice::Gen::HelperVisitor::visitSequence(const SequencePtr& p) { out << nl << "@SuppressWarnings(\"unchecked\")"; } - out << nl << "public static " << typeS << nl << "read(IceInternal.BasicStream __is)"; + out << nl << "public static " << typeS << nl << "read(Ice.InputStream __is)"; out << sb; out << nl << typeS << " __v;"; iter = 0; @@ -5389,33 +5020,6 @@ Slice::Gen::HelperVisitor::visitSequence(const SequencePtr& p) out << nl << "return __v;"; out << eb; - if(_stream) - { - out << sp << nl << "public static void write(Ice.OutputStream __outS, " << typeS << " __v)"; - out << sb; - iter = 0; - writeStreamSequenceMarshalUnmarshalCode(out, package, p, "__v", true, iter, false); - out << eb; - - out << sp; - if(suppressUnchecked) - { - out << nl << "@SuppressWarnings(\"unchecked\")"; - } - out << nl << "public static " << typeS << " read(Ice.InputStream __inS)"; - out << sb; - out << nl << typeS << " __v;"; - iter = 0; - writeStreamSequenceMarshalUnmarshalCode(out, package, p, "__v", false, iter, false); - out << nl << "return __v;"; - out << eb; - - out << sp << nl << "public static Ice.OptionalFormat optionalFormat()"; - out << sb; - out << nl << "return " << getOptionalFormat(p) << ';'; - out << eb; - } - out << eb; close(); } @@ -5449,14 +5053,14 @@ Slice::Gen::HelperVisitor::visitDictionary(const DictionaryPtr& p) out << sp << nl << "public final class " << name << "Helper"; out << sb; - out << nl << "public static void" << nl << "write(IceInternal.BasicStream __os, " << formalType << " __v)"; + out << nl << "public static void" << nl << "write(Ice.OutputStream __os, " << formalType << " __v)"; out << sb; iter = 0; writeDictionaryMarshalUnmarshalCode(out, package, p, "__v", true, iter, false); out << eb; out << sp << nl << "public static " << formalType - << nl << "read(IceInternal.BasicStream __is)"; + << nl << "read(Ice.InputStream __is)"; out << sb; out << nl << formalType << " __v;"; iter = 0; @@ -5464,69 +5068,11 @@ Slice::Gen::HelperVisitor::visitDictionary(const DictionaryPtr& p) out << nl << "return __v;"; out << eb; - if(_stream) - { - out << sp << nl << "public static void write(Ice.OutputStream __outS, " << formalType - << " __v)"; - out << sb; - iter = 0; - writeStreamDictionaryMarshalUnmarshalCode(out, package, p, "__v", true, iter, false); - out << eb; - - out << sp << nl << "public static " << formalType << " read(Ice.InputStream __inS)"; - out << sb; - out << nl << formalType << " __v;"; - iter = 0; - writeStreamDictionaryMarshalUnmarshalCode(out, package, p, "__v", false, iter, false); - out << nl << "return __v;"; - out << eb; - - out << sp << nl << "public static Ice.OptionalFormat optionalFormat()"; - out << sb; - out << nl << "return " << getOptionalFormat(p) << ';'; - out << eb; - } - out << eb; close(); } void -Slice::Gen::HelperVisitor::visitEnum(const EnumPtr& p) -{ - if(!p->isLocal() && _stream) - { - string name = p->name(); - string fixedName = fixKwd(name); - - open(getAbsolute(p, "", "", "Helper"), p->file()); - - Output& out = output(); - - out << sp << nl << "public final class " << name << "Helper"; - out << sb; - - out << sp << nl << "public static void write(Ice.OutputStream __outS, " << fixedName << " __v)"; - out << sb; - out << nl << "__v.ice_write(__outS);"; - out << eb; - - out << sp << nl << "public static " << fixedName << " read(Ice.InputStream __inS)"; - out << sb; - out << nl << "return " << fixedName << ".ice_read(__inS);"; - out << eb; - - out << sp << nl << "public static Ice.OptionalFormat optionalFormat()"; - out << sb; - out << nl << "return " << getOptionalFormat(p) << ';'; - out << eb; - - out << eb; - close(); - } -} - -void Slice::Gen::HelperVisitor::writeOperation(const ClassDefPtr& p, const string& package, const OperationPtr& op, bool optionalMapping) { @@ -5875,7 +5421,7 @@ Slice::Gen::HelperVisitor::writeOperation(const ClassDefPtr& p, const string& pa iter = 0; if(!inArgs.empty()) { - out << nl << "IceInternal.BasicStream __os = __result.startWriteParams(" + out << nl << "Ice.OutputStream __os = __result.startWriteParams(" << opFormatTypeToString(op) << ");"; ParamDeclList pl; for(ParamDeclList::const_iterator pli = paramList.begin(); pli != paramList.end(); ++pli) @@ -6211,8 +5757,8 @@ Slice::Gen::ProxyVisitor::visitOperation(const OperationPtr& p) } } -Slice::Gen::DispatcherVisitor::DispatcherVisitor(const string& dir, bool stream) : - JavaVisitor(dir), _stream(stream) +Slice::Gen::DispatcherVisitor::DispatcherVisitor(const string& dir) : + JavaVisitor(dir) { } @@ -6245,7 +5791,7 @@ Slice::Gen::DispatcherVisitor::visitClassDefStart(const ClassDefPtr& p) out << nl << "throw new java.lang.CloneNotSupportedException();"; out << eb; - writeDispatchAndMarshalling(out, p, _stream); + writeDispatchAndMarshalling(out, p); // // Avoid serialVersionUID warnings for dispatch classes. @@ -6850,7 +6396,7 @@ Slice::Gen::AsyncVisitor::visitOperation(const OperationPtr& p) { out << nl << "try"; out << sb; - out << nl << "IceInternal.BasicStream __os = this.__startWriteParams(" + out << nl << "Ice.OutputStream __os = this.__startWriteParams(" << opFormatTypeToString(p) << ");"; writeMarshalUnmarshalParams(out, classPkg, outParams, p, iter, true, optionalMapping, false); if(p->returnsClasses(false)) diff --git a/cpp/src/slice2java/Gen.h b/cpp/src/slice2java/Gen.h index e4def10d75e..eb3b5f914fb 100644 --- a/cpp/src/slice2java/Gen.h +++ b/cpp/src/slice2java/Gen.h @@ -86,12 +86,12 @@ protected: // // Generate a patcher class. // - void writePatcher(::IceUtilInternal::Output&, const std::string&, const DataMemberList&, const DataMemberList&, bool); + void writePatcher(::IceUtilInternal::Output&, const std::string&, const DataMemberList&, const DataMemberList&); // // Generate dispatch and marshalling methods for a class or interface. // - void writeDispatchAndMarshalling(::IceUtilInternal::Output&, const ClassDefPtr&, bool); + void writeDispatchAndMarshalling(::IceUtilInternal::Output&, const ClassDefPtr&); // // Write a constant or default value initializer. @@ -129,7 +129,7 @@ public: const std::string&); ~Gen(); - void generate(const UnitPtr&, bool); + void generate(const UnitPtr&); void generateTie(const UnitPtr&); void generateImpl(const UnitPtr&); void generateImplTie(const UnitPtr&); @@ -176,7 +176,7 @@ private: { public: - TypesVisitor(const std::string&, bool); + TypesVisitor(const std::string&); virtual bool visitClassDefStart(const ClassDefPtr&); virtual void visitClassDefEnd(const ClassDefPtr&); @@ -194,8 +194,6 @@ private: // Verifies that a data member method does not conflict with an operation. // bool validateMethod(const OperationList&, const std::string&, int, const std::string&, const std::string&); - - bool _stream; }; class CompactIdVisitor : public JavaVisitor @@ -228,19 +226,15 @@ private: { public: - HelperVisitor(const std::string&, bool); + HelperVisitor(const std::string&); virtual bool visitClassDefStart(const ClassDefPtr&); - virtual bool visitStructStart(const StructPtr&); virtual void visitSequence(const SequencePtr&); virtual void visitDictionary(const DictionaryPtr&); - virtual void visitEnum(const EnumPtr&); private: void writeOperation(const ClassDefPtr&, const std::string&, const OperationPtr&, bool); - - bool _stream; }; class ProxyVisitor : public JavaVisitor @@ -258,13 +252,9 @@ private: { public: - DispatcherVisitor(const std::string&, bool); + DispatcherVisitor(const std::string&); virtual bool visitClassDefStart(const ClassDefPtr&); - - private: - - bool _stream; }; class BaseImplVisitor : public JavaVisitor diff --git a/cpp/src/slice2java/Main.cpp b/cpp/src/slice2java/Main.cpp index de53ef640da..8396b17f99a 100644 --- a/cpp/src/slice2java/Main.cpp +++ b/cpp/src/slice2java/Main.cpp @@ -80,7 +80,6 @@ usage(const char* n) "--ice Allow reserved Ice prefix in Slice identifiers.\n" "--underscore Allow underscores in Slice identifiers.\n" "--checksum CLASS Generate checksums for Slice definitions into CLASS.\n" - "--stream Generate marshaling support for public stream API.\n" "--meta META Define global metadata directive META.\n" ; } @@ -108,7 +107,6 @@ compile(int argc, char* argv[]) opts.addOpt("", "ice"); opts.addOpt("", "underscore"); opts.addOpt("", "checksum", IceUtilInternal::Options::NeedArg); - opts.addOpt("", "stream"); opts.addOpt("", "meta", IceUtilInternal::Options::NeedArg, "", IceUtilInternal::Options::Repeat); @@ -189,8 +187,6 @@ compile(int argc, char* argv[]) string checksumClass = opts.optArg("checksum"); - bool stream = opts.isSet("stream"); - bool listGenerated = opts.isSet("list-generated"); StringList globalMetadata; @@ -353,7 +349,7 @@ compile(int argc, char* argv[]) try { Gen gen(argv[0], icecpp->getBaseName(), includePaths, output); - gen.generate(p, stream); + gen.generate(p); if(tie) { gen.generateTie(p); diff --git a/java/src/Ice/build.gradle b/java/src/Ice/build.gradle index ecea163016d..0b3c5b255b6 100644 --- a/java/src/Ice/build.gradle +++ b/java/src/Ice/build.gradle @@ -13,7 +13,7 @@ targetCompatibility = iceTargetCompatibility slice { java { stream { - args = "--ice --stream" + args = "--ice" files = [file("$sliceDir/Ice/BuiltinSequences.ice")] } nostream { diff --git a/java/src/Ice/src/main/java/Ice/ClassResolver.java b/java/src/Ice/src/main/java/Ice/ClassResolver.java new file mode 100644 index 00000000000..a42bfa4a478 --- /dev/null +++ b/java/src/Ice/src/main/java/Ice/ClassResolver.java @@ -0,0 +1,29 @@ +// ********************************************************************** +// +// Copyright (c) 2003-2015 ZeroC, Inc. All rights reserved. +// +// This copy of Ice is licensed to you under the terms described in the +// ICE_LICENSE file included in this distribution. +// +// ********************************************************************** + +package Ice; + +/** + * + * A ClassResolver translates a Slice type Id into a Java class using + * an implementation-defined algorithm. + * + **/ +public interface ClassResolver +{ + /** + * Resolve a Slice type Id into a Java class. The type Id corresponds to a + * Slice value or user exception. + * + * @param typeId A string type ID (such as <code>"::Module::Class"</code>). + * @return The Java class object corresponding to the Slice type ID, or null + * if no class could be found. + **/ + Class<?> resolveClass(String typeId); +} diff --git a/java/src/Ice/src/main/java/Ice/CommunicatorI.java b/java/src/Ice/src/main/java/Ice/CommunicatorI.java index eaf69b42a27..b68a17babc5 100644 --- a/java/src/Ice/src/main/java/Ice/CommunicatorI.java +++ b/java/src/Ice/src/main/java/Ice/CommunicatorI.java @@ -123,13 +123,13 @@ public final class CommunicatorI implements Communicator } @Override @SuppressWarnings("deprecation") - public synchronized void addObjectFactory(ObjectFactory factory, String id) + public void addObjectFactory(ObjectFactory factory, String id) { _instance.addObjectFactory(factory, id); } @Override @SuppressWarnings("deprecation") - public synchronized ObjectFactory findObjectFactory(String id) + public ObjectFactory findObjectFactory(String id) { return _instance.findObjectFactory(id); } diff --git a/java/src/Ice/src/main/java/Ice/ConnectionI.java b/java/src/Ice/src/main/java/Ice/ConnectionI.java index 0954a3bb4f7..31e5e9705a6 100644 --- a/java/src/Ice/src/main/java/Ice/ConnectionI.java +++ b/java/src/Ice/src/main/java/Ice/ConnectionI.java @@ -335,7 +335,7 @@ public final class ConnectionI extends IceInternal.EventHandler sendAsyncRequest(IceInternal.OutgoingAsyncBase out, boolean compress, boolean response, int batchRequestNum) throws IceInternal.RetryException { - final IceInternal.BasicStream os = out.getOs(); + final OutputStream os = out.getOs(); if(_exception != null) { @@ -627,7 +627,7 @@ public final class ConnectionI extends IceInternal.EventHandler } @Override - synchronized public void sendResponse(int requestId, IceInternal.BasicStream os, byte compressFlag, boolean amd) + synchronized public void sendResponse(int requestId, OutputStream os, byte compressFlag, boolean amd) { assert (_state > StateNotValidated); @@ -887,10 +887,10 @@ public final class ConnectionI extends IceInternal.EventHandler throw ex; } - _readProtocol.__read(_readStream); + _readProtocol.ice_read(_readStream); IceInternal.Protocol.checkSupportedProtocol(_readProtocol); - _readProtocolEncoding.__read(_readStream); + _readProtocolEncoding.ice_read(_readStream); IceInternal.Protocol.checkSupportedProtocolEncoding(_readProtocolEncoding); _readStream.readByte(); // messageType @@ -1053,8 +1053,7 @@ public final class ConnectionI extends IceInternal.EventHandler } } - if(!_dispatcher) // Optimization, call dispatch() directly if there's no - // dispatcher. + if(!_dispatcher) // Optimization, call dispatch() directly if there's no dispatcher. { dispatch(startCB, sentCBs, info); } @@ -1068,8 +1067,8 @@ public final class ConnectionI extends IceInternal.EventHandler // thread pool's thread stream. // assert (info.stream == current.stream); - IceInternal.BasicStream stream = info.stream; - info.stream = new IceInternal.BasicStream(_instance, IceInternal.Protocol.currentProtocolEncoding); + InputStream stream = info.stream; + info.stream = new InputStream(_instance, IceInternal.Protocol.currentProtocolEncoding); info.stream.swap(stream); } @@ -1529,10 +1528,10 @@ public final class ConnectionI extends IceInternal.EventHandler _nextRequestId = 1; _messageSizeMax = adapter != null ? adapter.messageSizeMax() : instance.messageSizeMax(); _batchRequestQueue = new IceInternal.BatchRequestQueue(instance, _endpoint.datagram()); - _readStream = new IceInternal.BasicStream(instance, IceInternal.Protocol.currentProtocolEncoding); + _readStream = new InputStream(instance, IceInternal.Protocol.currentProtocolEncoding); _readHeader = false; _readStreamPos = -1; - _writeStream = new IceInternal.BasicStream(instance, IceInternal.Protocol.currentProtocolEncoding); + _writeStream = new OutputStream(instance, IceInternal.Protocol.currentProtocolEncoding); _writeStreamPos = -1; _dispatchCount = 0; _state = StateNotInitialized; @@ -1872,11 +1871,10 @@ public final class ConnectionI extends IceInternal.EventHandler // // Before we shut down, we send a close connection message. // - IceInternal.BasicStream os = new IceInternal.BasicStream(_instance, - IceInternal.Protocol.currentProtocolEncoding); + OutputStream os = new OutputStream(_instance, IceInternal.Protocol.currentProtocolEncoding); os.writeBlob(IceInternal.Protocol.magic); - IceInternal.Protocol.currentProtocol.__write(os); - IceInternal.Protocol.currentProtocolEncoding.__write(os); + IceInternal.Protocol.currentProtocol.ice_write(os); + IceInternal.Protocol.currentProtocolEncoding.ice_write(os); os.writeByte(IceInternal.Protocol.closeConnectionMsg); os.writeByte((byte) 0); // compression status: always report 0 for // CloseConnection in Java. @@ -1906,11 +1904,10 @@ public final class ConnectionI extends IceInternal.EventHandler if(!_endpoint.datagram()) { - IceInternal.BasicStream os = new IceInternal.BasicStream(_instance, - IceInternal.Protocol.currentProtocolEncoding); + OutputStream os = new OutputStream(_instance, IceInternal.Protocol.currentProtocolEncoding); os.writeBlob(IceInternal.Protocol.magic); - IceInternal.Protocol.currentProtocol.__write(os); - IceInternal.Protocol.currentProtocolEncoding.__write(os); + IceInternal.Protocol.currentProtocol.ice_write(os); + IceInternal.Protocol.currentProtocolEncoding.ice_write(os); os.writeByte(IceInternal.Protocol.validateConnectionMsg); os.writeByte((byte) 0); os.writeInt(IceInternal.Protocol.headerSize); // Message size. @@ -1960,8 +1957,8 @@ public final class ConnectionI extends IceInternal.EventHandler if(_writeStream.isEmpty()) { _writeStream.writeBlob(IceInternal.Protocol.magic); - IceInternal.Protocol.currentProtocol.__write(_writeStream); - IceInternal.Protocol.currentProtocolEncoding.__write(_writeStream); + IceInternal.Protocol.currentProtocol.ice_write(_writeStream); + IceInternal.Protocol.currentProtocolEncoding.ice_write(_writeStream); _writeStream.writeByte(IceInternal.Protocol.validateConnectionMsg); _writeStream.writeByte((byte) 0); // Compression status // (always zero for @@ -2034,10 +2031,10 @@ public final class ConnectionI extends IceInternal.EventHandler throw ex; } - _readProtocol.__read(_readStream); + _readProtocol.ice_read(_readStream); IceInternal.Protocol.checkSupportedProtocol(_readProtocol); - _readProtocolEncoding.__read(_readStream); + _readProtocolEncoding.ice_read(_readStream); IceInternal.Protocol.checkSupportedProtocolEncoding(_readProtocolEncoding); byte messageType = _readStream.readByte(); @@ -2058,7 +2055,7 @@ public final class ConnectionI extends IceInternal.EventHandler } } - _writeStream.resize(0, false); + _writeStream.resize(0); _writeStream.pos(0); _readStream.resize(IceInternal.Protocol.headerSize, true); @@ -2147,7 +2144,7 @@ public final class ConnectionI extends IceInternal.EventHandler // message = _sendStreams.getFirst(); assert (!message.prepared); - IceInternal.BasicStream stream = message.stream; + OutputStream stream = message.stream; message.stream = doCompress(stream, message.compress); message.stream.prepareWrite(); @@ -2224,7 +2221,7 @@ public final class ConnectionI extends IceInternal.EventHandler assert (!message.prepared); - IceInternal.BasicStream stream = message.stream; + OutputStream stream = message.stream; message.stream = doCompress(stream, message.compress); message.stream.prepareWrite(); @@ -2277,7 +2274,7 @@ public final class ConnectionI extends IceInternal.EventHandler return IceInternal.AsyncStatus.Queued; } - private IceInternal.BasicStream doCompress(IceInternal.BasicStream uncompressed, boolean compress) + private OutputStream doCompress(OutputStream uncompressed, boolean compress) { boolean compressionSupported = false; if(compress) @@ -2286,7 +2283,7 @@ public final class ConnectionI extends IceInternal.EventHandler // Don't check whether compression support is available unless the // proxy is configured for compression. // - compressionSupported = IceInternal.BasicStream.compressible(); + compressionSupported = IceInternal.BZip2.supported(); } if(compressionSupported && uncompressed.size() >= 100) @@ -2294,9 +2291,13 @@ public final class ConnectionI extends IceInternal.EventHandler // // Do compression. // - IceInternal.BasicStream cstream = uncompressed.compress(IceInternal.Protocol.headerSize, _compressionLevel); - if(cstream != null) + IceInternal.Buffer cbuf = IceInternal.BZip2.compress(uncompressed.getBuffer(), + IceInternal.Protocol.headerSize, _compressionLevel); + if(cbuf != null) { + OutputStream cstream = + new OutputStream(uncompressed.instance(), uncompressed.getEncoding(), cbuf, true); + // // Set compression status. // @@ -2336,12 +2337,12 @@ public final class ConnectionI extends IceInternal.EventHandler private static class MessageInfo { - MessageInfo(IceInternal.BasicStream stream) + MessageInfo(InputStream stream) { this.stream = stream; } - IceInternal.BasicStream stream; + InputStream stream; int invokeNum; int requestId; byte compress; @@ -2380,11 +2381,14 @@ public final class ConnectionI extends IceInternal.EventHandler info.stream.pos(8); byte messageType = info.stream.readByte(); info.compress = info.stream.readByte(); - if(info.compress == (byte) 2) + if(info.compress == (byte)2) { - if(IceInternal.BasicStream.compressible()) + if(IceInternal.BZip2.supported()) { - info.stream = info.stream.uncompress(IceInternal.Protocol.headerSize, _messageSizeMax); + IceInternal.Buffer ubuf = IceInternal.BZip2.uncompress(info.stream.getBuffer(), + IceInternal.Protocol.headerSize, + _messageSizeMax); + info.stream = new InputStream(info.stream.instance(), info.stream.getEncoding(), ubuf, true); } else { @@ -2432,7 +2436,7 @@ public final class ConnectionI extends IceInternal.EventHandler { IceInternal.TraceUtil.trace("received request during closing\n" + "(ignored by server, client will retry)", info.stream, _logger, - _traceLevels); + _traceLevels); } else { @@ -2522,8 +2526,8 @@ public final class ConnectionI extends IceInternal.EventHandler return _state == StateHolding ? IceInternal.SocketOperation.None : IceInternal.SocketOperation.Read; } - private void invokeAll(IceInternal.BasicStream stream, int invokeNum, int requestId, byte compress, - IceInternal.ServantManager servantManager, ObjectAdapter adapter) + private void invokeAll(InputStream stream, int invokeNum, int requestId, byte compress, + IceInternal.ServantManager servantManager, ObjectAdapter adapter) { // // Note: In contrast to other private or protected methods, this @@ -2878,7 +2882,7 @@ public final class ConnectionI extends IceInternal.EventHandler private static class OutgoingMessage { - OutgoingMessage(IceInternal.BasicStream stream, boolean compress, boolean adopt) + OutgoingMessage(OutputStream stream, boolean compress, boolean adopt) { this.stream = stream; this.compress = compress; @@ -2886,7 +2890,7 @@ public final class ConnectionI extends IceInternal.EventHandler this.requestId = 0; } - OutgoingMessage(IceInternal.OutgoingAsyncBase out, IceInternal.BasicStream stream, boolean compress, + OutgoingMessage(IceInternal.OutgoingAsyncBase out, OutputStream stream, boolean compress, int requestId) { this.stream = stream; @@ -2905,8 +2909,8 @@ public final class ConnectionI extends IceInternal.EventHandler { if(adopt) { - IceInternal.BasicStream stream = new IceInternal.BasicStream(this.stream.instance(), - IceInternal.Protocol.currentProtocolEncoding); + OutputStream stream = + new OutputStream(this.stream.instance(), IceInternal.Protocol.currentProtocolEncoding); stream.swap(this.stream); this.stream = stream; adopt = false; @@ -2930,7 +2934,7 @@ public final class ConnectionI extends IceInternal.EventHandler } } - public IceInternal.BasicStream stream; + public OutputStream stream; public IceInternal.OutgoingAsyncBase outAsync; public boolean compress; public int requestId; @@ -2982,9 +2986,9 @@ public final class ConnectionI extends IceInternal.EventHandler private java.util.LinkedList<OutgoingMessage> _sendStreams = new java.util.LinkedList<OutgoingMessage>(); - private IceInternal.BasicStream _readStream; + private InputStream _readStream; private boolean _readHeader; - private IceInternal.BasicStream _writeStream; + private OutputStream _writeStream; private Ice.Instrumentation.ConnectionObserver _observer; private int _readStreamPos; diff --git a/java/src/Ice/src/main/java/Ice/ImplicitContextI.java b/java/src/Ice/src/main/java/Ice/ImplicitContextI.java index 85f519332fa..e312721c971 100644 --- a/java/src/Ice/src/main/java/Ice/ImplicitContextI.java +++ b/java/src/Ice/src/main/java/Ice/ImplicitContextI.java @@ -35,7 +35,7 @@ public abstract class ImplicitContextI implements ImplicitContext } } - abstract public void write(java.util.Map<String, String> prxContext, IceInternal.BasicStream os); + abstract public void write(java.util.Map<String, String> prxContext, OutputStream os); abstract java.util.Map<String, String> combine(java.util.Map<String, String> prxContext); static class Shared extends ImplicitContextI @@ -122,7 +122,7 @@ public abstract class ImplicitContextI implements ImplicitContext } @Override - public void write(java.util.Map<String, String> prxContext, IceInternal.BasicStream os) + public void write(java.util.Map<String, String> prxContext, OutputStream os) { if(prxContext.isEmpty()) { @@ -279,7 +279,7 @@ public abstract class ImplicitContextI implements ImplicitContext } @Override - public void write(java.util.Map<String, String> prxContext, IceInternal.BasicStream os) + public void write(java.util.Map<String, String> prxContext, OutputStream os) { java.util.Map<String, String> threadContext = _map.get(Thread.currentThread()); diff --git a/java/src/Ice/src/main/java/Ice/InputStream.java b/java/src/Ice/src/main/java/Ice/InputStream.java index 89a7c71a9d7..472288e253b 100644 --- a/java/src/Ice/src/main/java/Ice/InputStream.java +++ b/java/src/Ice/src/main/java/Ice/InputStream.java @@ -9,354 +9,3325 @@ package Ice; +import java.io.IOException; + /** * Interface for input streams used to extract Slice types from a sequence * of bytes. * * @see OutputStream **/ -public interface InputStream +public class InputStream { /** - * Returns the communicator for this input stream. + * Constructing an InputStream without providing a communicator means the stream will + * use the default encoding version. A communicator is required in order to unmarshal + * proxies. You can supply a communicator later by calling initialize(). + **/ + public InputStream() + { + initialize(IceInternal.Protocol.currentEncoding); + } + + /** + * Constructing an InputStream without providing a communicator means the stream will + * use the default encoding version. A communicator is required in order to unmarshal + * proxies. You can supply a communicator later by calling initialize(). + * + * @param data The byte array containing encoded Slice types. + **/ + public InputStream(byte[] data) + { + initialize(IceInternal.Protocol.currentEncoding); + _buf = new IceInternal.Buffer(data); + } + + /** + * Constructing an InputStream without providing a communicator means the stream will + * use the default encoding version. A communicator is required in order to unmarshal + * proxies. You can supply a communicator later by calling initialize(). + * + * @param buf The byte buffer containing encoded Slice types. + **/ + public InputStream(java.nio.ByteBuffer buf) + { + initialize(IceInternal.Protocol.currentEncoding); + _buf = new IceInternal.Buffer(buf); + } + + public InputStream(IceInternal.Buffer buf) + { + this(buf, false); + } + + public InputStream(IceInternal.Buffer buf, boolean adopt) + { + initialize(IceInternal.Protocol.currentEncoding); + _buf = new IceInternal.Buffer(buf, adopt); + } + + /** + * This constructor uses the communicator's default encoding version. + * + * @param communicator The communicator to use when initializing the stream. + **/ + public InputStream(Communicator communicator) + { + initialize(communicator); + } + + /** + * This constructor uses the communicator's default encoding version. + * + * @param communicator The communicator to use when initializing the stream. + * @param data The byte array containing encoded Slice types. + **/ + public InputStream(Communicator communicator, byte[] data) + { + initialize(communicator); + _buf = new IceInternal.Buffer(data); + } + + /** + * This constructor uses the communicator's default encoding version. + * + * @param communicator The communicator to use when initializing the stream. + * @param buf The byte buffer containing encoded Slice types. + **/ + public InputStream(Communicator communicator, java.nio.ByteBuffer buf) + { + initialize(communicator); + _buf = new IceInternal.Buffer(buf); + } + + public InputStream(Communicator communicator, IceInternal.Buffer buf) + { + this(communicator, buf, false); + } + + public InputStream(Communicator communicator, IceInternal.Buffer buf, boolean adopt) + { + initialize(communicator); + _buf = new IceInternal.Buffer(buf, adopt); + } + + /** + * This constructor uses the given encoding version. + **/ + public InputStream(EncodingVersion encoding) + { + initialize(encoding); + } + + /** + * This constructor uses the given encoding version. * - * @return The communicator. + * @param data The byte array containing encoded Slice types. **/ - Communicator communicator(); + public InputStream(EncodingVersion encoding, byte[] data) + { + initialize(encoding); + _buf = new IceInternal.Buffer(data); + } + + /** + * This constructor uses the given encoding version. + * + * @param buf The byte buffer containing encoded Slice types. + **/ + public InputStream(EncodingVersion encoding, java.nio.ByteBuffer buf) + { + initialize(encoding); + _buf = new IceInternal.Buffer(buf); + } + + public InputStream(EncodingVersion encoding, IceInternal.Buffer buf) + { + this(encoding, buf, false); + } + + public InputStream(EncodingVersion encoding, IceInternal.Buffer buf, boolean adopt) + { + initialize(encoding); + _buf = new IceInternal.Buffer(buf, adopt); + } + + /** + * This constructor uses the given communicator and encoding version. + * + * @param communicator The communicator to use when initializing the stream. + * @param encoding The desired encoding version. + **/ + public InputStream(Communicator communicator, EncodingVersion encoding) + { + initialize(communicator, encoding); + } + + /** + * This constructor uses the given communicator and encoding version. + * + * @param communicator The communicator to use when initializing the stream. + * @param encoding The desired encoding version. + * @param data The byte array containing encoded Slice types. + **/ + public InputStream(Communicator communicator, EncodingVersion encoding, byte[] data) + { + initialize(communicator, encoding); + _buf = new IceInternal.Buffer(data); + } + + /** + * This constructor uses the given communicator and encoding version. + * + * @param communicator The communicator to use when initializing the stream. + * @param encoding The desired encoding version. + * @param buf The byte buffer containing encoded Slice types. + **/ + public InputStream(Communicator communicator, EncodingVersion encoding, java.nio.ByteBuffer buf) + { + initialize(communicator, encoding); + _buf = new IceInternal.Buffer(buf); + } + + public InputStream(Communicator communicator, EncodingVersion encoding, IceInternal.Buffer buf) + { + this(communicator, encoding, buf, false); + } + + public InputStream(Communicator communicator, EncodingVersion encoding, IceInternal.Buffer buf, boolean adopt) + { + initialize(communicator, encoding); + _buf = new IceInternal.Buffer(buf, adopt); + } + + public InputStream(IceInternal.Instance instance, EncodingVersion encoding) + { + this(instance, encoding, instance.cacheMessageBuffers() > 1); + } + + public InputStream(IceInternal.Instance instance, EncodingVersion encoding, boolean direct) + { + initialize(instance, encoding); + _buf = new IceInternal.Buffer(direct); + } + + public InputStream(IceInternal.Instance instance, EncodingVersion encoding, byte[] data) + { + initialize(instance, encoding); + _buf = new IceInternal.Buffer(data); + } + + public InputStream(IceInternal.Instance instance, EncodingVersion encoding, java.nio.ByteBuffer data) + { + initialize(instance, encoding); + _buf = new IceInternal.Buffer(data); + } + + public InputStream(IceInternal.Instance instance, EncodingVersion encoding, IceInternal.Buffer buf, boolean adopt) + { + initialize(instance, encoding); + _buf = new IceInternal.Buffer(buf, adopt); + } + + /** + * Initializes the stream to use the communicator's default encoding version. + * + * @param communicator The communicator to use when initializing the stream. + **/ + public void initialize(Communicator communicator) + { + IceInternal.Instance instance = IceInternal.Util.getInstance(communicator); + initialize(instance, instance.defaultsAndOverrides().defaultEncoding); + } + + /** + * Initializes the stream to use the given communicator and encoding version. + * + * @param communicator The communicator to use when initializing the stream. + * @param encoding The desired encoding version. + **/ + public void initialize(Communicator communicator, EncodingVersion encoding) + { + IceInternal.Instance instance = IceInternal.Util.getInstance(communicator); + initialize(instance, encoding); + } + + private void initialize(IceInternal.Instance instance, EncodingVersion encoding) + { + initialize(encoding); + + _instance = instance; + _traceSlicing = _instance.traceLevels().slicing > 0; + + _valueFactoryManager = _instance.initializationData().valueFactoryManager; + _logger = _instance.initializationData().logger; + _compactIdResolver = _instance; + _classResolver = _instance; + } + + private void initialize(EncodingVersion encoding) + { + _instance = null; + _encoding = encoding; + _encapsStack = null; + _encapsCache = null; + _traceSlicing = false; + _closure = null; + _sliceObjects = true; + _startSeq = -1; + _minSeqSize = 0; + } + + /** + * Resets this output stream. This method allows the stream to be reused, to avoid creating + * unnecessary garbage. + **/ + public void reset() + { + _buf.reset(); + clear(); + } + + /** + * Releases any data retained by encapsulations. The {@link #reset} method internally calls </code>clear</code>. + **/ + public void clear() + { + if(_encapsStack != null) + { + assert(_encapsStack.next == null); + _encapsStack.next = _encapsCache; + _encapsCache = _encapsStack; + _encapsCache.reset(); + _encapsStack = null; + } + + _startSeq = -1; + _sliceObjects = true; + } + + /** + * Sets the value factory manager to use when marshaling value instances. If the stream + * was initialized with a communicator, the communicator's value factory manager will + * be used by default. + * + * @param vfm The value factory manager. + **/ + public void setValueFactoryManager(ValueFactoryManager vfm) + { + _valueFactoryManager = vfm; + } + + /** + * Sets the logger to use when logging trace messages. If the stream + * was initialized with a communicator, the communicator's logger will + * be used by default. + * + * @param logger The logger to use for logging trace messages. + **/ + public void setLogger(Logger logger) + { + _logger = logger; + } + + /** + * Sets the compact ID resolver to use when unmarshaling value and exception + * instances. If the stream was initialized with a communicator, the communicator's + * resolver will be used by default. + * + * @param r The compact ID resolver. + **/ + public void setCompactIdResolver(CompactIdResolver r) + { + _compactIdResolver = r; + } + + /** + * Sets the class resolver, which the stream will use when attempting to unmarshal + * a value or exception. If the stream was initialized with a communicator, the communicator's + * resolver will be used by default. + * + * @param r The class resolver. + **/ + public void setClassResolver(ClassResolver r) + { + _classResolver = r; + } /** * Determines the behavior of the stream when extracting Slice objects. * A Slice object is "sliced" when a factory cannot be found for a Slice type ID. + * The stream's default behavior is to slice objects. * - * @param slice If <code>true</code> (the default), slicing is enabled; if <code>false</code>, + * @param b If <code>true</code> (the default), slicing is enabled; if <code>false</code>, * slicing is disabled. If slicing is disabled and the stream encounters a Slice type ID * during decoding for which no value factory is installed, it raises {@link NoValueFactoryException}. **/ - void sliceObjects(boolean slice); + public void setSliceObjects(boolean b) + { + _sliceObjects = b; + } /** - * Extracts a boolean value from the stream. + * Determines whether the stream logs messages about slicing instances of Slice values. * - * @return The extracted boolean. + * @param b True to enable logging, false to disable logging. **/ - boolean readBool(); + public void setTraceSlicing(boolean b) + { + _traceSlicing = b; + } /** - * Extracts a sequence of boolean values from the stream. + * Retrieves the closure object associated with this stream. * - * @return The extracted boolean sequence. + * @return The closure object. + **/ + public Object getClosure() + { + return _closure; + } + + /** + * Associates a closure object with this stream. + * + * @param p The new closure object. + * @return The previous closure object, or null. + **/ + public Object setClosure(Object p) + { + Object prev = _closure; + _closure = p; + return prev; + } + + public IceInternal.Instance instance() + { + return _instance; + } + + /** + * Swaps the contents of one stream with another. + * + * @param other The other stream. + **/ + public void swap(InputStream other) + { + assert(_instance == other._instance); + + IceInternal.Buffer tmpBuf = other._buf; + other._buf = _buf; + _buf = tmpBuf; + + EncodingVersion tmpEncoding = other._encoding; + other._encoding = _encoding; + _encoding = tmpEncoding; + + boolean tmpTraceSlicing = other._traceSlicing; + other._traceSlicing = _traceSlicing; + _traceSlicing = tmpTraceSlicing; + + Object tmpClosure = other._closure; + other._closure = _closure; + _closure = tmpClosure; + + boolean tmpSliceObjects = other._sliceObjects; + other._sliceObjects = _sliceObjects; + _sliceObjects = tmpSliceObjects; + + // + // Swap is never called for streams that have encapsulations being read. However, + // encapsulations might still be set in case unmarshaling failed. We just + // reset the encapsulations if there are still some set. + // + resetEncapsulation(); + other.resetEncapsulation(); + + int tmpStartSeq = other._startSeq; + other._startSeq = _startSeq; + _startSeq = tmpStartSeq; + + int tmpMinSeqSize = other._minSeqSize; + other._minSeqSize = _minSeqSize; + _minSeqSize = tmpMinSeqSize; + + ValueFactoryManager tmpVfm = other._valueFactoryManager; + other._valueFactoryManager = _valueFactoryManager; + _valueFactoryManager = tmpVfm; + + Logger tmpLogger = other._logger; + other._logger = _logger; + _logger = tmpLogger; + + CompactIdResolver tmpCompactIdResolver = other._compactIdResolver; + other._compactIdResolver = _compactIdResolver; + _compactIdResolver = tmpCompactIdResolver; + } + + private void resetEncapsulation() + { + _encapsStack = null; + } + + /** + * Resizes the stream to a new size. + * + * @param sz The new size. **/ - boolean[] readBoolSeq(); + public void resize(int sz, boolean reading) + { + _buf.resize(sz, reading); + _buf.b.position(sz); + } + + public IceInternal.Buffer getBuffer() + { + return _buf; + } + + /** + * Marks the start of an Ice object. + * + * @param slicedData Preserved slices for this object, or null. + **/ + public void startObject() + { + assert(_encapsStack != null && _encapsStack.decoder != null); + _encapsStack.decoder.startInstance(SliceType.ObjectSlice); + } + + /** + * Marks the end of an Ice object. + * + * @param preserve Pass true and the stream will preserve the unknown slices of the object, or false + * to discard the unknown slices. + * @return An object that encapsulates the unknown slice data. + **/ + public SlicedData endObject(boolean preserve) + { + assert(_encapsStack != null && _encapsStack.decoder != null); + return _encapsStack.decoder.endInstance(preserve); + } + + /** + * Marks the start of a user exception. + * + * @param slicedData Preserved slices for this exception, or null. + **/ + public void startException() + { + assert(_encapsStack != null && _encapsStack.decoder != null); + _encapsStack.decoder.startInstance(SliceType.ExceptionSlice); + } + + /** + * Marks the end of a user exception. + * + * @param preserve Pass true and the stream will preserve the unknown slices of the exception, or false + * to discard the unknown slices. + * @return An object that encapsulates the unknown slice data. + **/ + public SlicedData endException(boolean preserve) + { + assert(_encapsStack != null && _encapsStack.decoder != null); + return _encapsStack.decoder.endInstance(preserve); + } + + /** + * Writes the start of an encapsulation to the stream. + * + * @return The encoding version used by the encapsulation. + **/ + public EncodingVersion startEncapsulation() + { + Encaps curr = _encapsCache; + if(curr != null) + { + curr.reset(); + _encapsCache = _encapsCache.next; + } + else + { + curr = new Encaps(); + } + curr.next = _encapsStack; + _encapsStack = curr; + + _encapsStack.start = _buf.b.position(); + + // + // I don't use readSize() for encapsulations, because when creating an encapsulation, + // I must know in advance how many bytes the size information will require in the data + // stream. If I use an Int, it is always 4 bytes. For readSize(), it could be 1 or 5 bytes. + // + int sz = readInt(); + if(sz < 6) + { + throw new UnmarshalOutOfBoundsException(); + } + if(sz - 4 > _buf.b.remaining()) + { + throw new UnmarshalOutOfBoundsException(); + } + _encapsStack.sz = sz; + + EncodingVersion encoding = new EncodingVersion(); + encoding.ice_read(this); + IceInternal.Protocol.checkSupportedEncoding(encoding); // Make sure the encoding is supported. + _encapsStack.setEncoding(encoding); + + return encoding; + } + + /** + * Ends the previous encapsulation. + **/ + public void endEncapsulation() + { + assert(_encapsStack != null); + + if(!_encapsStack.encoding_1_0) + { + skipOpts(); + if(_buf.b.position() != _encapsStack.start + _encapsStack.sz) + { + throw new EncapsulationException(); + } + } + else if(_buf.b.position() != _encapsStack.start + _encapsStack.sz) + { + if(_buf.b.position() + 1 != _encapsStack.start + _encapsStack.sz) + { + throw new EncapsulationException(); + } + + // + // Ice version < 3.3 had a bug where user exceptions with + // class members could be encoded with a trailing byte + // when dispatched with AMD. So we tolerate an extra byte + // in the encapsulation. + // + try + { + _buf.b.get(); + } + catch(java.nio.BufferUnderflowException ex) + { + throw new UnmarshalOutOfBoundsException(); + } + } + + Encaps curr = _encapsStack; + _encapsStack = curr.next; + curr.next = _encapsCache; + _encapsCache = curr; + _encapsCache.reset(); + } + + /** + * Skips an empty encapsulation. The encapsulation's encoding version is returned in the argument. + * + * @param encoding The encapsulation's encoding version. + **/ + public void skipEmptyEncapsulation(EncodingVersion encoding) + { + int sz = readInt(); + if(sz != 6) + { + throw new EncapsulationException(); + } + + final int pos = _buf.b.position(); + if(pos + 2 > _buf.size()) + { + throw new UnmarshalOutOfBoundsException(); + } + + if(encoding != null) + { + encoding.ice_read(this); + } + else + { + _buf.b.position(pos + 2); + } + } + + /** + * Returns a blob of bytes representing an encapsulation. The encapsulation's encoding version + * is returned in the argument. + * + * @param encoding The encapsulation's encoding version. + **/ + public byte[] readEncapsulation(EncodingVersion encoding) + { + int sz = readInt(); + if(sz < 6) + { + throw new UnmarshalOutOfBoundsException(); + } + + if(sz - 4 > _buf.b.remaining()) + { + throw new UnmarshalOutOfBoundsException(); + } + + if(encoding != null) + { + encoding.ice_read(this); + _buf.b.position(_buf.b.position() - 6); + } + else + { + _buf.b.position(_buf.b.position() - 4); + } + + byte[] v = new byte[sz]; + try + { + _buf.b.get(v); + return v; + } + catch(java.nio.BufferUnderflowException ex) + { + throw new UnmarshalOutOfBoundsException(); + } + } + + /** + * Determines the current encoding version. + * + * @return The encoding version. + **/ + public EncodingVersion getEncoding() + { + return _encapsStack != null ? _encapsStack.encoding : _encoding; + } + + /** + * Determines the size of the current encapsulation, excluding the encapsulation header. + * + * @return The size of the encapsulated data. + **/ + public int getEncapsulationSize() + { + assert(_encapsStack != null); + return _encapsStack.sz - 6; + } + + /** + * Skips over an encapsulation. + * + * @return The encoding version of the skipped encapsulation. + **/ + public EncodingVersion skipEncapsulation() + { + int sz = readInt(); + if(sz < 6) + { + throw new UnmarshalOutOfBoundsException(); + } + EncodingVersion encoding = new EncodingVersion(); + encoding.ice_read(this); + try + { + _buf.b.position(_buf.b.position() + sz - 6); + } + catch(IllegalArgumentException ex) + { + throw new UnmarshalOutOfBoundsException(); + } + return encoding; + } + + /** + * Reads the start of an object or exception slice. + * + * @return The Slice type ID for this slice. + **/ + public String startSlice() // Returns type ID of next slice + { + assert(_encapsStack != null && _encapsStack.decoder != null); + return _encapsStack.decoder.startSlice(); + } + + /** + * Indicates that the end of an object or exception slice has been reached. + **/ + public void endSlice() + { + assert(_encapsStack != null && _encapsStack.decoder != null); + _encapsStack.decoder.endSlice(); + } + + /** + * Skips over an object or exception slice. + **/ + public void skipSlice() + { + assert(_encapsStack != null && _encapsStack.decoder != null); + _encapsStack.decoder.skipSlice(); + } + + /** + * Indicates that unmarshaling is complete, except for any Slice objects. The application must call this method + * only if the stream actually contains Slice objects. Calling <code>readPendingObjects</code> triggers the + * calls to {@link ReadObjectCallback#invoke} that inform the application that unmarshaling of a Slice + * object is complete. + **/ + public void readPendingObjects() + { + if(_encapsStack != null && _encapsStack.decoder != null) + { + _encapsStack.decoder.readPendingObjects(); + } + else if(_encapsStack != null ? _encapsStack.encoding_1_0 : _encoding.equals(Util.Encoding_1_0)) + { + // + // If using the 1.0 encoding and no objects were read, we + // still read an empty sequence of pending objects if + // requested (i.e.: if this is called). + // + // This is required by the 1.0 encoding, even if no objects + // are written we do marshal an empty sequence if marshaled + // data types use classes. + // + skipSize(); + } + } + + /** + * Extracts a size from the stream. + * + * @return The extracted size. + **/ + public int readSize() + { + try + { + byte b = _buf.b.get(); + if(b == -1) + { + int v = _buf.b.getInt(); + if(v < 0) + { + throw new UnmarshalOutOfBoundsException(); + } + return v; + } + else + { + return b < 0 ? b + 256 : b; + } + } + catch(java.nio.BufferUnderflowException ex) + { + throw new UnmarshalOutOfBoundsException(); + } + } + + /** + * Validates a sequence size. + * + * @return The extracted size. + **/ + public int readAndCheckSeqSize(int minSize) + { + int sz = readSize(); + + if(sz == 0) + { + return sz; + } + + // + // The _startSeq variable points to the start of the sequence for which + // we expect to read at least _minSeqSize bytes from the stream. + // + // If not initialized or if we already read more data than _minSeqSize, + // we reset _startSeq and _minSeqSize for this sequence (possibly a + // top-level sequence or enclosed sequence it doesn't really matter). + // + // Otherwise, we are reading an enclosed sequence and we have to bump + // _minSeqSize by the minimum size that this sequence will require on + // the stream. + // + // The goal of this check is to ensure that when we start un-marshalling + // a new sequence, we check the minimal size of this new sequence against + // the estimated remaining buffer size. This estimatation is based on + // the minimum size of the enclosing sequences, it's _minSeqSize. + // + if(_startSeq == -1 || _buf.b.position() > (_startSeq + _minSeqSize)) + { + _startSeq = _buf.b.position(); + _minSeqSize = sz * minSize; + } + else + { + _minSeqSize += sz * minSize; + } + + // + // If there isn't enough data to read on the stream for the sequence (and + // possibly enclosed sequences), something is wrong with the marshalled + // data: it's claiming having more data that what is possible to read. + // + if(_startSeq + _minSeqSize > _buf.size()) + { + throw new UnmarshalOutOfBoundsException(); + } + + return sz; + } + + /** + * Reads a blob of bytes from the stream. + * + * @param sz The number of bytes to read. + * @return The requested bytes as a byte array. + **/ + public byte[] readBlob(int sz) + { + if(_buf.b.remaining() < sz) + { + throw new UnmarshalOutOfBoundsException(); + } + byte[] v = new byte[sz]; + try + { + _buf.b.get(v); + return v; + } + catch(java.nio.BufferUnderflowException ex) + { + throw new UnmarshalOutOfBoundsException(); + } + } + + /** + * Determine if an optional value is available for reading. + * + * @param tag The tag associated with the value. + * @param expectedFormat The optional format for the value. + * @return True if the value is present, false otherwise. + **/ + public boolean readOptional(int tag, OptionalFormat expectedFormat) + { + assert(_encapsStack != null); + if(_encapsStack.decoder != null) + { + return _encapsStack.decoder.readOptional(tag, expectedFormat); + } + else + { + return readOptImpl(tag, expectedFormat); + } + } /** * Extracts a byte value from the stream. * * @return The extracted byte. **/ - byte readByte(); + public byte readByte() + { + try + { + return _buf.b.get(); + } + catch(java.nio.BufferUnderflowException ex) + { + throw new UnmarshalOutOfBoundsException(); + } + } + + /** + * Extracts an optional byte value from the stream. + * + * @param tag The numeric tag associated with the value. + * @param v Holds the optional value (if any). + **/ + public void readByte(int tag, ByteOptional v) + { + if(readOptional(tag, OptionalFormat.F1)) + { + v.set(readByte()); + } + else + { + v.clear(); + } + } /** * Extracts a sequence of byte values from the stream. * * @return The extracted byte sequence. **/ - byte[] readByteSeq(); + public byte[] readByteSeq() + { + try + { + final int sz = readAndCheckSeqSize(1); + byte[] v = new byte[sz]; + _buf.b.get(v); + return v; + } + catch(java.nio.BufferUnderflowException ex) + { + throw new UnmarshalOutOfBoundsException(); + } + } + + /** + * Extracts an optional byte sequence from the stream. + * + * @param tag The numeric tag associated with the value. + * @param v Holds the optional value (if any). + **/ + public void readByteSeq(int tag, Optional<byte[]> v) + { + if(readOptional(tag, OptionalFormat.VSize)) + { + v.set(readByteSeq()); + } + else + { + v.clear(); + } + } /** - * Extracts a sequence of byte values from the stream as a ByteBuffer. + * Returns a byte buffer representing a sequence of bytes. This method does not copy the data. * - * @return The ByteBuffer wrapping the sequence. + * @return A byte buffer "slice" of the internal buffer. **/ - java.nio.ByteBuffer readByteBuffer(); + public java.nio.ByteBuffer readByteBuffer() + { + try + { + final int sz = readAndCheckSeqSize(1); + java.nio.ByteBuffer v = _buf.b.slice(); + v.limit(sz); + _buf.b.position(_buf.b.position() + sz); + return v.asReadOnlyBuffer(); + } + catch(java.nio.BufferUnderflowException ex) + { + throw new UnmarshalOutOfBoundsException(); + } + } /** * Extracts a serializable Java object from the stream. * * @return The deserialized Java object. **/ - java.io.Serializable readSerializable(); + public java.io.Serializable readSerializable() + { + int sz = readAndCheckSeqSize(1); + if (sz == 0) + { + return null; + } + IceInternal.ObjectInputStream in = null; + try + { + IceInternal.InputStreamWrapper w = new IceInternal.InputStreamWrapper(sz, _buf.b); + in = new IceInternal.ObjectInputStream(_instance, w); + return (java.io.Serializable)in.readObject(); + } + catch(LocalException ex) + { + throw ex; + } + catch(java.lang.Exception ex) + { + throw new MarshalException("cannot deserialize object", ex); + } + finally + { + if(in != null) + { + try + { + in.close(); + } + catch (IOException ex) + { + throw new MarshalException("cannot deserialize object", ex); + } + } + } + } /** - * Extracts a short value from the stream. + * Extracts a boolean value from the stream. * - * @return The extracted short value. + * @return The extracted boolean. **/ - short readShort(); + public boolean readBool() + { + try + { + return _buf.b.get() == 1; + } + catch(java.nio.BufferUnderflowException ex) + { + throw new UnmarshalOutOfBoundsException(); + } + } /** - * Extracts a sequence of short values from the stream. + * Extracts an optional boolean value from the stream. * - * @return The extracted short sequence. + * @param tag The numeric tag associated with the value. + * @param v Holds the optional value (if any). + **/ + public void readBool(int tag, BooleanOptional v) + { + if(readOptional(tag, OptionalFormat.F1)) + { + v.set(readBool()); + } + else + { + v.clear(); + } + } + + /** + * Extracts a sequence of boolean values from the stream. + * + * @return The extracted boolean sequence. **/ - short[] readShortSeq(); + public boolean[] readBoolSeq() + { + try + { + final int sz = readAndCheckSeqSize(1); + boolean[] v = new boolean[sz]; + for(int i = 0; i < sz; i++) + { + v[i] = _buf.b.get() == 1; + } + return v; + } + catch(java.nio.BufferUnderflowException ex) + { + throw new UnmarshalOutOfBoundsException(); + } + } /** - * Extracts a sequence of short values from the stream as a ShortBuffer. + * Extracts an optional boolean sequence from the stream. * - * @return The ShortBuffer wrapping the sequence. + * @param tag The numeric tag associated with the value. + * @param v Holds the optional value (if any). **/ - java.nio.ShortBuffer readShortBuffer(); + public void readBoolSeq(int tag, Optional<boolean[]> v) + { + if(readOptional(tag, OptionalFormat.VSize)) + { + v.set(readBoolSeq()); + } + else + { + v.clear(); + } + } /** - * Extracts an integer value from the stream. + * Extracts a short value from the stream. * - * @return The extracted integer. + * @return The extracted short. **/ - int readInt(); + public short readShort() + { + try + { + return _buf.b.getShort(); + } + catch(java.nio.BufferUnderflowException ex) + { + throw new UnmarshalOutOfBoundsException(); + } + } /** - * Extracts a sequence of integer values from the stream. + * Extracts an optional short value from the stream. * - * @return The extracted integer sequence. + * @param tag The numeric tag associated with the value. + * @param v Holds the optional value (if any). **/ - int[] readIntSeq(); + public void readShort(int tag, ShortOptional v) + { + if(readOptional(tag, OptionalFormat.F2)) + { + v.set(readShort()); + } + else + { + v.clear(); + } + } /** - * Extracts a sequence of int values from the stream as a IntBuffer. + * Extracts a sequence of short values from the stream. * - * @return The IntBuffer wrapping the sequence. + * @return The extracted short sequence. **/ - java.nio.IntBuffer readIntBuffer(); + public short[] readShortSeq() + { + try + { + final int sz = readAndCheckSeqSize(2); + short[] v = new short[sz]; + java.nio.ShortBuffer shortBuf = _buf.b.asShortBuffer(); + shortBuf.get(v); + _buf.b.position(_buf.b.position() + sz * 2); + return v; + } + catch(java.nio.BufferUnderflowException ex) + { + throw new UnmarshalOutOfBoundsException(); + } + } /** - * Extracts a long value from the stream. + * Extracts an optional short sequence from the stream. * - * @return The extracted long value. + * @param tag The numeric tag associated with the value. + * @param v Holds the optional value (if any). **/ - long readLong(); + public void readShortSeq(int tag, Optional<short[]> v) + { + if(readOptional(tag, OptionalFormat.VSize)) + { + skipSize(); + v.set(readShortSeq()); + } + else + { + v.clear(); + } + } /** - * Extracts a sequence of long values from the stream. + * Returns a short buffer representing a sequence of shorts. This method does not copy the data. * - * @return The extracted long sequence. + * @return A short buffer "slice" of the internal buffer. **/ - long[] readLongSeq(); + public java.nio.ShortBuffer readShortBuffer() + { + try + { + final int sz = readAndCheckSeqSize(2); + java.nio.ShortBuffer shortBuf = _buf.b.asShortBuffer(); + java.nio.ShortBuffer v = shortBuf.slice(); + v.limit(sz); + _buf.b.position(_buf.b.position() + sz * 2); + return v.asReadOnlyBuffer(); + } + catch(java.nio.BufferUnderflowException ex) + { + throw new UnmarshalOutOfBoundsException(); + } + } /** - * Extracts a sequence of long values from the stream as a LongBuffer. + * Extracts an int value from the stream. * - * @return The LongBuffer wrapping the sequence. + * @return The extracted int. **/ - java.nio.LongBuffer readLongBuffer(); + public int readInt() + { + try + { + return _buf.b.getInt(); + } + catch(java.nio.BufferUnderflowException ex) + { + throw new UnmarshalOutOfBoundsException(); + } + } /** - * Extracts a float value from the stream. + * Extracts an optional int value from the stream. * - * @return The extracted float value. + * @param tag The numeric tag associated with the value. + * @param v Holds the optional value (if any). **/ - float readFloat(); + public void readInt(int tag, IntOptional v) + { + if(readOptional(tag, OptionalFormat.F4)) + { + v.set(readInt()); + } + else + { + v.clear(); + } + } /** - * Extracts a sequence of float values from the stream. + * Extracts a sequence of int values from the stream. * - * @return The extracted float sequence. + * @return The extracted int sequence. **/ - float[] readFloatSeq(); + public int[] readIntSeq() + { + try + { + final int sz = readAndCheckSeqSize(4); + int[] v = new int[sz]; + java.nio.IntBuffer intBuf = _buf.b.asIntBuffer(); + intBuf.get(v); + _buf.b.position(_buf.b.position() + sz * 4); + return v; + } + catch(java.nio.BufferUnderflowException ex) + { + throw new UnmarshalOutOfBoundsException(); + } + } /** - * Extracts a sequence of float values from the stream as a FloatBuffer. + * Extracts an optional int sequence from the stream. * - * @return The FloatBuffer wrapping the sequence. + * @param tag The numeric tag associated with the value. + * @param v Holds the optional value (if any). **/ - java.nio.FloatBuffer readFloatBuffer(); + public void readIntSeq(int tag, Optional<int[]> v) + { + if(readOptional(tag, OptionalFormat.VSize)) + { + skipSize(); + v.set(readIntSeq()); + } + else + { + v.clear(); + } + } /** - * Extracts a double value from the stream. + * Returns an int buffer representing a sequence of ints. This method does not copy the data. * - * @return The extracted double value. + * @return An int buffer "slice" of the internal buffer. **/ - double readDouble(); + public java.nio.IntBuffer readIntBuffer() + { + try + { + final int sz = readAndCheckSeqSize(4); + java.nio.IntBuffer intBuf = _buf.b.asIntBuffer(); + java.nio.IntBuffer v = intBuf.slice(); + v.limit(sz); + _buf.b.position(_buf.b.position() + sz * 4); + return v.asReadOnlyBuffer(); + } + catch(java.nio.BufferUnderflowException ex) + { + throw new UnmarshalOutOfBoundsException(); + } + } /** - * Extracts a sequence of double values from the stream. + * Extracts a long value from the stream. * - * @return The extracted float sequence. + * @return The extracted long. **/ - double[] readDoubleSeq(); + public long readLong() + { + try + { + return _buf.b.getLong(); + } + catch(java.nio.BufferUnderflowException ex) + { + throw new UnmarshalOutOfBoundsException(); + } + } /** - * Extracts a sequence of double values from the stream as a DoubleBuffer. + * Extracts an optional long value from the stream. * - * @return The DoubleBuffer wrapping the sequence. + * @param tag The numeric tag associated with the value. + * @param v Holds the optional value (if any). **/ - java.nio.DoubleBuffer readDoubleBuffer(); + public void readLong(int tag, LongOptional v) + { + if(readOptional(tag, OptionalFormat.F8)) + { + v.set(readLong()); + } + else + { + v.clear(); + } + } /** - * Extracts a string from the stream. + * Extracts a sequence of long values from the stream. * - * @return The extracted string. + * @return The extracted long sequence. **/ - String readString(); + public long[] readLongSeq() + { + try + { + final int sz = readAndCheckSeqSize(8); + long[] v = new long[sz]; + java.nio.LongBuffer longBuf = _buf.b.asLongBuffer(); + longBuf.get(v); + _buf.b.position(_buf.b.position() + sz * 8); + return v; + } + catch(java.nio.BufferUnderflowException ex) + { + throw new UnmarshalOutOfBoundsException(); + } + } /** - * Extracts a string sequence from the stream. + * Extracts an optional long sequence from the stream. * - * @return The extracted string sequence. - */ - String[] readStringSeq(); + * @param tag The numeric tag associated with the value. + * @param v Holds the optional value (if any). + **/ + public void readLongSeq(int tag, Optional<long[]> v) + { + if(readOptional(tag, OptionalFormat.VSize)) + { + skipSize(); + v.set(readLongSeq()); + } + else + { + v.clear(); + } + } /** - * Extracts a size from the stream. + * Returns a long buffer representing a sequence of longs. This method does not copy the data. * - * @return The extracted size. + * @return A long buffer "slice" of the internal buffer. **/ - int readSize(); + public java.nio.LongBuffer readLongBuffer() + { + try + { + final int sz = readAndCheckSeqSize(8); + java.nio.LongBuffer longBuf = _buf.b.asLongBuffer(); + java.nio.LongBuffer v = longBuf.slice(); + v.limit(sz); + _buf.b.position(_buf.b.position() + sz * 8); + return v.asReadOnlyBuffer(); + } + catch(java.nio.BufferUnderflowException ex) + { + throw new UnmarshalOutOfBoundsException(); + } + } /** - * Extracts and check a sequence size from the stream. The check ensures not too much memory will - * be pre-allocated for the sequence. + * Extracts a float value from the stream. * - * @param minSize The minimum size of an element of the sequence. + * @return The extracted float. + **/ + public float readFloat() + { + try + { + return _buf.b.getFloat(); + } + catch(java.nio.BufferUnderflowException ex) + { + throw new UnmarshalOutOfBoundsException(); + } + } + + /** + * Extracts an optional float value from the stream. * - * @return The extracted size. + * @param tag The numeric tag associated with the value. + * @param v Holds the optional value (if any). **/ - int readAndCheckSeqSize(int minSize); + public void readFloat(int tag, FloatOptional v) + { + if(readOptional(tag, OptionalFormat.F4)) + { + v.set(readFloat()); + } + else + { + v.clear(); + } + } /** - * Extracts a proxy from the stream. + * Extracts a sequence of float values from the stream. * - * @return The extracted proxy. + * @return The extracted float sequence. **/ - ObjectPrx readProxy(); + public float[] readFloatSeq() + { + try + { + final int sz = readAndCheckSeqSize(4); + float[] v = new float[sz]; + java.nio.FloatBuffer floatBuf = _buf.b.asFloatBuffer(); + floatBuf.get(v); + _buf.b.position(_buf.b.position() + sz * 4); + return v; + } + catch(java.nio.BufferUnderflowException ex) + { + throw new UnmarshalOutOfBoundsException(); + } + } /** - * Extracts the index of a Slice class from the stream. + * Extracts an optional float sequence from the stream. * - * @param cb The callback to notify the application when the extracted instance is available. - * The Ice run time extracts Slice classes in stages. The Ice run time calls {@link ReadObjectCallback#invoke} - * when the corresponding instance has been fully unmarshaled. + * @param tag The numeric tag associated with the value. + * @param v Holds the optional value (if any). + **/ + public void readFloatSeq(int tag, Optional<float[]> v) + { + if(readOptional(tag, OptionalFormat.VSize)) + { + skipSize(); + v.set(readFloatSeq()); + } + else + { + v.clear(); + } + } + + /** + * Returns a float buffer representing a sequence of floats. This method does not copy the data. * - * @see ReadObjectCallback + * @return A float buffer "slice" of the internal buffer. **/ - void readObject(ReadObjectCallback cb); + public java.nio.FloatBuffer readFloatBuffer() + { + try + { + final int sz = readAndCheckSeqSize(4); + java.nio.FloatBuffer floatBuf = _buf.b.asFloatBuffer(); + java.nio.FloatBuffer v = floatBuf.slice(); + v.limit(sz); + _buf.b.position(_buf.b.position() + sz * 4); + return v.asReadOnlyBuffer(); + } + catch(java.nio.BufferUnderflowException ex) + { + throw new UnmarshalOutOfBoundsException(); + } + } /** - * Read an enumerated value. + * Extracts a double value from the stream. * - * @param maxValue The maximum enumerator value in the definition. - * @return The enumerator. + * @return The extracted double. **/ - int readEnum(int maxValue); + public double readDouble() + { + try + { + return _buf.b.getDouble(); + } + catch(java.nio.BufferUnderflowException ex) + { + throw new UnmarshalOutOfBoundsException(); + } + } /** - * Extracts a user exception from the stream and throws it. + * Extracts an optional double value from the stream. + * + * @param tag The numeric tag associated with the value. + * @param v Holds the optional value (if any). **/ - void throwException() throws UserException; + public void readDouble(int tag, DoubleOptional v) + { + if(readOptional(tag, OptionalFormat.F8)) + { + v.set(readDouble()); + } + else + { + v.clear(); + } + } /** - * Extracts a user exception from the stream and throws it, using the supplied - * factory to instantiate a UserExceptionReader. + * Extracts a sequence of double values from the stream. * - * @param factory A factory that creates UserExceptionReader instances. + * @return The extracted double sequence. **/ - void throwException(UserExceptionReaderFactory factory) throws UserException; + public double[] readDoubleSeq() + { + try + { + final int sz = readAndCheckSeqSize(8); + double[] v = new double[sz]; + java.nio.DoubleBuffer doubleBuf = _buf.b.asDoubleBuffer(); + doubleBuf.get(v); + _buf.b.position(_buf.b.position() + sz * 8); + return v; + } + catch(java.nio.BufferUnderflowException ex) + { + throw new UnmarshalOutOfBoundsException(); + } + } /** - * Marks the start of an Ice object. + * Extracts an optional double sequence from the stream. + * + * @param tag The numeric tag associated with the value. + * @param v Holds the optional value (if any). **/ - void startObject(); + public void readDoubleSeq(int tag, Optional<double[]> v) + { + if(readOptional(tag, OptionalFormat.VSize)) + { + skipSize(); + v.set(readDoubleSeq()); + } + else + { + v.clear(); + } + } /** - * Marks the end of an Ice object. + * Returns a double buffer representing a sequence of doubles. This method does not copy the data. * - * @return A SlicedData object containing the preserved slices for unknown types. + * @return A double buffer "slice" of the internal buffer. **/ - SlicedData endObject(boolean preserve); + public java.nio.DoubleBuffer readDoubleBuffer() + { + try + { + final int sz = readAndCheckSeqSize(8); + java.nio.DoubleBuffer doubleBuf = _buf.b.asDoubleBuffer(); + java.nio.DoubleBuffer v = doubleBuf.slice(); + v.limit(sz); + _buf.b.position(_buf.b.position() + sz * 8); + return v.asReadOnlyBuffer(); + } + catch(java.nio.BufferUnderflowException ex) + { + throw new UnmarshalOutOfBoundsException(); + } + } + + final static java.nio.charset.Charset _utf8 = java.nio.charset.Charset.forName("UTF8"); + private java.nio.charset.CharsetEncoder _charEncoder = null; /** - * Marks the start of a user exception. + * Extracts a string from the stream. + * + * @return The extracted string. **/ - void startException(); + public String readString() + { + final int len = readSize(); + + if(len == 0) + { + return ""; + } + else + { + // + // Check the buffer has enough bytes to read. + // + if(_buf.b.remaining() < len) + { + throw new UnmarshalOutOfBoundsException(); + } + + try + { + // + // We reuse the _stringBytes array to avoid creating + // excessive garbage. + // + if(_stringBytes == null || len > _stringBytes.length) + { + _stringBytes = new byte[len]; + } + if(_stringChars == null || len > _stringChars.length) + { + _stringChars = new char[len]; + } + _buf.b.get(_stringBytes, 0, len); + + // + // It's more efficient to construct a string using a + // character array instead of a byte array, because + // byte arrays require conversion. + // + for(int i = 0; i < len; i++) + { + if(_stringBytes[i] < 0) + { + // + // Multi-byte character found - we must use + // conversion. + // + // TODO: If the string contains garbage bytes + // that won't correctly decode as UTF, the + // behavior of this constructor is + // undefined. It would be better to explicitly + // decode using + // java.nio.charset.CharsetDecoder and to + // throw MarshalException if the string won't + // decode. + // + return new String(_stringBytes, 0, len, "UTF8"); + } + else + { + _stringChars[i] = (char)_stringBytes[i]; + } + } + return new String(_stringChars, 0, len); + } + catch(java.io.UnsupportedEncodingException ex) + { + assert(false); + return ""; + } + catch(java.nio.BufferUnderflowException ex) + { + throw new UnmarshalOutOfBoundsException(); + } + } + } /** - * Marks the end of a user exception. + * Extracts an optional string value from the stream. * - * @return A SlicedData object containing the preserved slices for unknown types. + * @param tag The numeric tag associated with the value. + * @param v Holds the optional value (if any). **/ - SlicedData endException(boolean preserve); + public void readString(int tag, Optional<String> v) + { + if(readOptional(tag, OptionalFormat.VSize)) + { + v.set(readString()); + } + else + { + v.clear(); + } + } /** - * Reads the start of an object or exception slice. + * Extracts a sequence of string values from the stream. * - * @return The Slice type ID for this slice. + * @return The extracted string sequence. **/ - String startSlice(); + public String[] readStringSeq() + { + final int sz = readAndCheckSeqSize(1); + String[] v = new String[sz]; + for(int i = 0; i < sz; i++) + { + v[i] = readString(); + } + return v; + } /** - * Indicates that the end of an object or exception slice has been reached. + * Extracts an optional string sequence from the stream. + * + * @param tag The numeric tag associated with the value. + * @param v Holds the optional value (if any). **/ - void endSlice(); + public void readStringSeq(int tag, Optional<String[]> v) + { + if(readOptional(tag, OptionalFormat.FSize)) + { + skip(4); + v.set(readStringSeq()); + } + else + { + v.clear(); + } + } /** - * Skips over an object or exception slice. + * Extracts a proxy from the stream. The stream must have been initialized with a communicator. + * + * @return The extracted proxy. **/ - void skipSlice(); + public ObjectPrx readProxy() + { + if(_instance == null) + { + throw new MarshalException("cannot unmarshal a proxy without a communicator"); + } + + return _instance.proxyFactory().streamToProxy(this); + } /** - * Reads the start of an encapsulation. + * Extracts an optional proxy from the stream. The stream must have been initialized with a communicator. * - * @return The encapsulation encoding version. + * @param tag The numeric tag associated with the value. + * @param v Holds the optional value (if any). **/ - EncodingVersion startEncapsulation(); + public void readProxy(int tag, Optional<ObjectPrx> v) + { + if(readOptional(tag, OptionalFormat.FSize)) + { + skip(4); + v.set(readProxy()); + } + else + { + v.clear(); + } + } /** - * Indicates that the end of an encapsulation has been reached. + * Read an enumerated value. + * + * @param maxValue The maximum enumerator value in the definition. + * @return The enumerator. **/ - void endEncapsulation(); + public int readEnum(int maxValue) + { + if(getEncoding().equals(Util.Encoding_1_0)) + { + if(maxValue < 127) + { + return readByte(); + } + else if(maxValue < 32767) + { + return readShort(); + } + else + { + return readInt(); + } + } + else + { + return readSize(); + } + } /** - * Skips over an encapsulation. + * Extracts the index of a Slice value from the stream. + * + * @param cb The callback to notify the application when the extracted instance is available. + * The stream extracts Slice values in stages. The Ice run time calls {@link ReadObjectCallback#objectReady} + * when the corresponding instance has been fully unmarshaled. * - * @return The encapsulation encoding version. + * @see ReadObjectCallback **/ - EncodingVersion skipEncapsulation(); + public void readObject(ReadObjectCallback cb) + { + initEncaps(); + _encapsStack.decoder.readObject(cb); + } /** - * Determines the current encoding version. + * Extracts the index of an optional Slice value from the stream. * - * @return The encoding version. + * @param v Holds the optional value (if any). If a value is present, it will not be set in the + * argument until after {@link #readPendingObjects} has completed. **/ - EncodingVersion getEncoding(); + public void readObject(int tag, Optional<Ice.Object> v) + { + if(readOptional(tag, OptionalFormat.Class)) + { + OptionalObject opt = new OptionalObject(v, Ice.Object.class, ObjectImpl.ice_staticId()); + readObject(opt); + } + else + { + v.clear(); + } + } /** - * Indicates that unmarshaling is complete, except for any Slice objects. The application must call this method - * only if the stream actually contains Slice objects. Calling <code>readPendingObjects</code> triggers the - * calls to {@link ReadObjectCallback#invoke} that inform the application that unmarshaling of a Slice - * object is complete. + * Extracts a user exception from the stream and throws it. **/ - void readPendingObjects(); + public void throwException() + throws UserException + { + throwException(null); + } /** - * Resets the read position of the stream to the beginning. + * Extracts a user exception from the stream and throws it. The caller can supply a factory + * to instantiate exception instances. + * + * @param factory The user exception factory, or null to use the stream's default behavior. **/ - void rewind(); + public void throwException(UserExceptionFactory factory) + throws UserException + { + initEncaps(); + _encapsStack.decoder.throwException(factory); + } + + private boolean readOptImpl(int readTag, OptionalFormat expectedFormat) + { + if(isEncoding_1_0()) + { + return false; // Optional members aren't supported with the 1.0 encoding. + } + + while(true) + { + if(_buf.b.position() >= _encapsStack.start + _encapsStack.sz) + { + return false; // End of encapsulation also indicates end of optionals. + } + + final byte b = readByte(); + final int v = b < 0 ? b + 256 : b; + if(v == IceInternal.Protocol.OPTIONAL_END_MARKER) + { + _buf.b.position(_buf.b.position() - 1); // Rewind. + return false; + } + + OptionalFormat format = OptionalFormat.valueOf(v & 0x07); // First 3 bits. + int tag = v >> 3; + if(tag == 30) + { + tag = readSize(); + } + + if(tag > readTag) + { + int offset = tag < 30 ? 1 : (tag < 255 ? 2 : 6); // Rewind + _buf.b.position(_buf.b.position() - offset); + return false; // No optional data members with the requested tag. + } + else if(tag < readTag) + { + skipOpt(format); // Skip optional data members + } + else + { + if(format != expectedFormat) + { + throw new MarshalException("invalid optional data member `" + tag + "': unexpected format"); + } + return true; + } + } + } + + private void skipOpt(OptionalFormat format) + { + switch(format) + { + case F1: + { + skip(1); + break; + } + case F2: + { + skip(2); + break; + } + case F4: + { + skip(4); + break; + } + case F8: + { + skip(8); + break; + } + case Size: + { + skipSize(); + break; + } + case VSize: + { + skip(readSize()); + break; + } + case FSize: + { + skip(readInt()); + break; + } + case Class: + { + readObject(null); + break; + } + } + } + + private void skipOpts() + { + // + // Skip remaining un-read optional members. + // + while(true) + { + if(_buf.b.position() >= _encapsStack.start + _encapsStack.sz) + { + return; // End of encapsulation also indicates end of optionals. + } + + final byte b = readByte(); + final int v = b < 0 ? b + 256 : b; + if(v == IceInternal.Protocol.OPTIONAL_END_MARKER) + { + return; + } + + OptionalFormat format = OptionalFormat.valueOf(v & 0x07); // Read first 3 bits. + if((v >> 3) == 30) + { + skipSize(); + } + skipOpt(format); + } + } /** - * Skips ahead in the stream. + * Skip the given number of bytes. * - * @param sz The number of bytes to skip. + * @param size The number of bytes to skip. **/ - void skip(int sz); + public void skip(int size) + { + if(size > _buf.b.remaining()) + { + throw new UnmarshalOutOfBoundsException(); + } + _buf.b.position(_buf.b.position() + size); + } /** - * Skips over a size value. + * Skip over a size value. **/ - void skipSize(); + public void skipSize() + { + byte b = readByte(); + if(b == -1) + { + skip(4); + } + } /** - * Determine if an optional value is available for reading. + * Determines the current position in the stream. * - * @param tag The tag associated with the value. - * @param type The optional format for the value. - * @return True if the value is present, false otherwise. + * @return The current position. **/ - boolean readOptional(int tag, OptionalFormat format); + public int pos() + { + return _buf.b.position(); + } - int pos(); + /** + * Sets the current position in the stream. + * + * @param pos The new position. + **/ + public void pos(int n) + { + _buf.b.position(n); + } /** - * Destroys the stream and its associated resources. The application must call <code>destroy</code> prior - * to releasing the last reference to a stream; failure to do so may result in resource leaks. + * Determines the current size of the stream. + * + * @return The current size. **/ - void destroy(); + public int size() + { + return _buf.size(); + } + + /** + * Determines whether the stream is empty. + * + * @return True if the internal buffer has no data, false otherwise. + **/ + public boolean isEmpty() + { + return _buf.empty(); + } + + private Ice.Object createObject(String id) + { + Ice.Object obj = null; + + try + { + if(_classResolver != null) + { + Class<?> c = _classResolver.resolveClass(id); + if(c != null) + { + obj = (Ice.Object)c.newInstance(); + } + } + } + catch(java.lang.Exception ex) + { + throw new NoValueFactoryException("no value factory", id, ex); + } + + return obj; + } + + private UserException createUserException(String id) + { + UserException userEx = null; + + try + { + if(_classResolver != null) + { + Class<?> c = _classResolver.resolveClass(id); + if(c != null) + { + userEx = (UserException)c.newInstance(); + } + } + } + catch(java.lang.Exception ex) + { + throw new MarshalException(ex); + } + + return userEx; + } + + private IceInternal.Instance _instance; + private IceInternal.Buffer _buf; + private Object _closure; + private byte[] _stringBytes; // Reusable array for reading strings. + private char[] _stringChars; // Reusable array for reading strings. + + private enum SliceType { NoSlice, ObjectSlice, ExceptionSlice } + + abstract private static class EncapsDecoder + { + EncapsDecoder(InputStream stream, boolean sliceObjects, ValueFactoryManager f) + { + _stream = stream; + _sliceObjects = sliceObjects; + _servantFactoryManager = f; + _typeIdIndex = 0; + _unmarshaledMap = new java.util.TreeMap<Integer, Ice.Object>(); + } + + abstract void readObject(ReadObjectCallback cb); + abstract void throwException(UserExceptionFactory factory) + throws UserException; + + abstract void startInstance(SliceType type); + abstract SlicedData endInstance(boolean preserve); + abstract String startSlice(); + abstract void endSlice(); + abstract void skipSlice(); + + boolean readOptional(int tag, OptionalFormat format) + { + return false; + } + + void readPendingObjects() + { + } + + protected String readTypeId(boolean isIndex) + { + if(_typeIdMap == null) // Lazy initialization + { + _typeIdMap = new java.util.TreeMap<Integer, String>(); + } + + if(isIndex) + { + int index = _stream.readSize(); + String typeId = _typeIdMap.get(index); + if(typeId == null) + { + throw new UnmarshalOutOfBoundsException(); + } + return typeId; + } + else + { + String typeId = _stream.readString(); + _typeIdMap.put(++_typeIdIndex, typeId); + return typeId; + } + } + + protected Ice.Object newInstance(String typeId) + { + // + // Try to find a factory registered for the specific type. + // + ValueFactory userFactory = _servantFactoryManager.find(typeId); + Ice.Object v = null; + if(userFactory != null) + { + v = userFactory.create(typeId); + } + + // + // If that fails, invoke the default factory if one has been + // registered. + // + if(v == null) + { + userFactory = _servantFactoryManager.find(""); + if(userFactory != null) + { + v = userFactory.create(typeId); + } + } + + // + // Last chance: try to instantiate the class dynamically. + // + if(v == null) + { + v = _stream.createObject(typeId); + } + + return v; + } + + protected void addPatchEntry(int index, ReadObjectCallback cb) + { + assert(index > 0); + + // + // Check if we have already unmarshalled the object. If that's the case, + // just patch the object smart pointer and we're done. + // + Ice.Object obj = _unmarshaledMap.get(index); + if(obj != null) + { + cb.objectReady(obj); + return; + } + + if(_patchMap == null) // Lazy initialization + { + _patchMap = new java.util.TreeMap<Integer, java.util.LinkedList<ReadObjectCallback> >(); + } + + // + // Add patch entry if the object isn't un-marshalled yet, + // the smart pointer will be patched when the instance is + // un-marshalled. + // + java.util.LinkedList<ReadObjectCallback> l = _patchMap.get(index); + if(l == null) + { + // + // We have no outstanding instances to be patched for this + // index, so make a new entry in the patch map. + // + l = new java.util.LinkedList<ReadObjectCallback>(); + _patchMap.put(index, l); + } + + // + // Append a patch entry for this instance. + // + l.add(cb); + } + + protected void unmarshal(int index, Ice.Object v) + { + // + // Add the object to the map of un-marshalled objects, this must + // be done before reading the objects (for circular references). + // + _unmarshaledMap.put(index, v); + + // + // Read the object. + // + v.__read(_stream); + + if(_patchMap != null) + { + // + // Patch all instances now that the object is un-marshalled. + // + java.util.LinkedList<ReadObjectCallback> l = _patchMap.get(index); + if(l != null) + { + assert(l.size() > 0); + + // + // Patch all pointers that refer to the instance. + // + for(ReadObjectCallback cb : l) + { + cb.objectReady(v); + } + + // + // Clear out the patch map for that index -- there is nothing left + // to patch for that index for the time being. + // + _patchMap.remove(index); + } + } + + if((_patchMap == null || _patchMap.isEmpty()) && _objectList == null) + { + try + { + v.ice_postUnmarshal(); + } + catch(java.lang.Exception ex) + { + String s = "exception raised by ice_postUnmarshal:\n" + IceInternal.Ex.toString(ex); + _stream.instance().initializationData().logger.warning(s); + } + } + else + { + if(_objectList == null) // Lazy initialization + { + _objectList = new java.util.ArrayList<Ice.Object>(); + } + _objectList.add(v); + + if(_patchMap == null || _patchMap.isEmpty()) + { + // + // Iterate over the object list and invoke ice_postUnmarshal on + // each object. We must do this after all objects have been + // unmarshaled in order to ensure that any object data members + // have been properly patched. + // + for(Ice.Object p : _objectList) + { + try + { + p.ice_postUnmarshal(); + } + catch(java.lang.Exception ex) + { + String s = "exception raised by ice_postUnmarshal:\n" + IceInternal.Ex.toString(ex); + _stream.instance().initializationData().logger.warning(s); + } + } + _objectList.clear(); + } + } + } + + protected final InputStream _stream; + protected final boolean _sliceObjects; + protected ValueFactoryManager _servantFactoryManager; + + // Encapsulation attributes for object un-marshalling + protected java.util.TreeMap<Integer, java.util.LinkedList<ReadObjectCallback> > _patchMap; + + // Encapsulation attributes for object un-marshalling + private java.util.TreeMap<Integer, Ice.Object> _unmarshaledMap; + private java.util.TreeMap<Integer, String> _typeIdMap; + private int _typeIdIndex; + private java.util.List<Ice.Object> _objectList; + } + + private static final class EncapsDecoder10 extends EncapsDecoder + { + EncapsDecoder10(InputStream stream, boolean sliceObjects, ValueFactoryManager f) + { + super(stream, sliceObjects, f); + _sliceType = SliceType.NoSlice; + } + + @Override + void readObject(ReadObjectCallback cb) + { + assert(cb != null); + + // + // Object references are encoded as a negative integer in 1.0. + // + int index = _stream.readInt(); + if(index > 0) + { + throw new MarshalException("invalid object id"); + } + index = -index; + + if(index == 0) + { + cb.objectReady(null); + } + else + { + addPatchEntry(index, cb); + } + } + + @Override + void throwException(UserExceptionFactory factory) + throws UserException + { + assert(_sliceType == SliceType.NoSlice); + + // + // User exception with the 1.0 encoding start with a boolean flag + // that indicates whether or not the exception has classes. + // + // This allows reading the pending objects even if some part of + // the exception was sliced. + // + boolean usesClasses = _stream.readBool(); + + _sliceType = SliceType.ExceptionSlice; + _skipFirstSlice = false; + + // + // Read the first slice header. + // + startSlice(); + final String mostDerivedId = _typeId; + while(true) + { + UserException userEx = null; + + // + // Use a factory if one was provided. + // + if(factory != null) + { + try + { + factory.createAndThrow(_typeId); + } + catch(UserException ex) + { + userEx = ex; + } + } + + if(userEx == null) + { + userEx = _stream.createUserException(_typeId); + } + + // + // We found the exception. + // + if(userEx != null) + { + userEx.__read(_stream); + if(usesClasses) + { + readPendingObjects(); + } + throw userEx; + + // Never reached. + } + + // + // Slice off what we don't understand. + // + skipSlice(); + try + { + startSlice(); + } + catch(UnmarshalOutOfBoundsException ex) + { + // + // An oversight in the 1.0 encoding means there is no marker to indicate + // the last slice of an exception. As a result, we just try to read the + // next type ID, which raises UnmarshalOutOfBoundsException when the + // input buffer underflows. + // + // Set the reason member to a more helpful message. + // + ex.reason = "unknown exception type `" + mostDerivedId + "'"; + throw ex; + } + } + } + + @Override + void startInstance(SliceType sliceType) + { + assert(_sliceType == sliceType); + _skipFirstSlice = true; + } + + @Override + SlicedData endInstance(boolean preserve) + { + // + // Read the Ice::Object slice. + // + if(_sliceType == SliceType.ObjectSlice) + { + startSlice(); + int sz = _stream.readSize(); // For compatibility with the old AFM. + if(sz != 0) + { + throw new MarshalException("invalid Object slice"); + } + endSlice(); + } + + _sliceType = SliceType.NoSlice; + return null; + } + + @Override + String startSlice() + { + // + // If first slice, don't read the header, it was already read in + // readInstance or throwException to find the factory. + // + if(_skipFirstSlice) + { + _skipFirstSlice = false; + return _typeId; + } + + // + // For objects, first read the type ID boolean which indicates + // whether or not the type ID is encoded as a string or as an + // index. For exceptions, the type ID is always encoded as a + // string. + // + if(_sliceType == SliceType.ObjectSlice) // For exceptions, the type ID is always encoded as a string + { + boolean isIndex = _stream.readBool(); + _typeId = readTypeId(isIndex); + } + else + { + _typeId = _stream.readString(); + } + + _sliceSize = _stream.readInt(); + if(_sliceSize < 4) + { + throw new UnmarshalOutOfBoundsException(); + } + + return _typeId; + } + + @Override + void endSlice() + { + } + + @Override + void skipSlice() + { + _stream.traceSkipSlice(_typeId, _sliceType); + assert(_sliceSize >= 4); + _stream.skip(_sliceSize - 4); + } + + @Override + void readPendingObjects() + { + int num; + do + { + num = _stream.readSize(); + for(int k = num; k > 0; --k) + { + readInstance(); + } + } + while(num > 0); + + if(_patchMap != null && !_patchMap.isEmpty()) + { + // + // If any entries remain in the patch map, the sender has sent an index for an object, but failed + // to supply the object. + // + throw new MarshalException("index for class received, but no instance"); + } + } + + private void readInstance() + { + int index = _stream.readInt(); + + if(index <= 0) + { + throw new MarshalException("invalid object id"); + } + + _sliceType = SliceType.ObjectSlice; + _skipFirstSlice = false; + + // + // Read the first slice header. + // + startSlice(); + final String mostDerivedId = _typeId; + Ice.Object v = null; + while(true) + { + // + // For the 1.0 encoding, the type ID for the base Object class + // marks the last slice. + // + if(_typeId.equals(ObjectImpl.ice_staticId())) + { + throw new NoValueFactoryException("", mostDerivedId); + } + + v = newInstance(_typeId); + + // + // We found a factory, we get out of this loop. + // + if(v != null) + { + break; + } + + // + // If object slicing is disabled, stop un-marshalling. + // + if(!_sliceObjects) + { + throw new NoValueFactoryException("no value factory found and object slicing is disabled", _typeId); + } + + // + // Slice off what we don't understand. + // + skipSlice(); + startSlice(); // Read next Slice header for next iteration. + } + + // + // Un-marshal the object and add-it to the map of un-marshaled objects. + // + unmarshal(index, v); + } + + // Object/exception attributes + private SliceType _sliceType; + private boolean _skipFirstSlice; + + // Slice attributes + private int _sliceSize; + private String _typeId; + } + + private static class EncapsDecoder11 extends EncapsDecoder + { + EncapsDecoder11(InputStream stream, boolean sliceObjects, ValueFactoryManager f, CompactIdResolver r) + { + super(stream, sliceObjects, f); + _compactIdResolver = r; + _current = null; + _objectIdIndex = 1; + } + + @Override + void readObject(ReadObjectCallback cb) + { + int index = _stream.readSize(); + if(index < 0) + { + throw new MarshalException("invalid object id"); + } + else if(index == 0) + { + if(cb != null) + { + cb.objectReady(null); + } + } + else if(_current != null && (_current.sliceFlags & IceInternal.Protocol.FLAG_HAS_INDIRECTION_TABLE) != 0) + { + // + // When reading an object within a slice and there's an + // indirect object table, always read an indirect reference + // that points to an object from the indirect object table + // marshaled at the end of the Slice. + // + // Maintain a list of indirect references. Note that the + // indirect index starts at 1, so we decrement it by one to + // derive an index into the indirection table that we'll read + // at the end of the slice. + // + if(cb != null) + { + if(_current.indirectPatchList == null) // Lazy initialization + { + _current.indirectPatchList = new java.util.ArrayDeque<IndirectPatchEntry>(); + } + IndirectPatchEntry e = new IndirectPatchEntry(); + e.index = index - 1; + e.cb = cb; + _current.indirectPatchList.push(e); + } + } + else + { + readInstance(index, cb); + } + } + + @Override + void throwException(UserExceptionFactory factory) + throws UserException + { + assert(_current == null); + + push(SliceType.ExceptionSlice); + + // + // Read the first slice header. + // + startSlice(); + final String mostDerivedId = _current.typeId; + while(true) + { + UserException userEx = null; + + // + // Use a factory if one was provided. + // + if(factory != null) + { + try + { + factory.createAndThrow(_current.typeId); + } + catch(UserException ex) + { + userEx = ex; + } + } + + if(userEx == null) + { + userEx = _stream.createUserException(_current.typeId); + } + + // + // We found the exception. + // + if(userEx != null) + { + userEx.__read(_stream); + throw userEx; + + // Never reached. + } + + // + // Slice off what we don't understand. + // + skipSlice(); + + if((_current.sliceFlags & IceInternal.Protocol.FLAG_IS_LAST_SLICE) != 0) + { + if(mostDerivedId.startsWith("::")) + { + throw new UnknownUserException(mostDerivedId.substring(2)); + } + else + { + throw new UnknownUserException(mostDerivedId); + } + } + + startSlice(); + } + } + + @Override + void startInstance(SliceType sliceType) + { + assert(_current.sliceType == sliceType); + _current.skipFirstSlice = true; + } + + @Override + SlicedData endInstance(boolean preserve) + { + SlicedData slicedData = null; + if(preserve) + { + slicedData = readSlicedData(); + } + if(_current.slices != null) + { + _current.slices.clear(); + _current.indirectionTables.clear(); + } + _current = _current.previous; + return slicedData; + } + + @Override + String startSlice() + { + // + // If first slice, don't read the header, it was already read in + // readInstance or throwException to find the factory. + // + if(_current.skipFirstSlice) + { + _current.skipFirstSlice = false; + return _current.typeId; + } + + _current.sliceFlags = _stream.readByte(); + + // + // Read the type ID, for object slices the type ID is encoded as a + // string or as an index, for exceptions it's always encoded as a + // string. + // + if(_current.sliceType == SliceType.ObjectSlice) + { + if((_current.sliceFlags & IceInternal.Protocol.FLAG_HAS_TYPE_ID_COMPACT) == + IceInternal.Protocol.FLAG_HAS_TYPE_ID_COMPACT) // Must be checked 1st! + { + _current.typeId = ""; + _current.compactId = _stream.readSize(); + } + else if((_current.sliceFlags & (IceInternal.Protocol.FLAG_HAS_TYPE_ID_INDEX | + IceInternal.Protocol.FLAG_HAS_TYPE_ID_STRING)) != 0) + { + _current.typeId = + readTypeId((_current.sliceFlags & IceInternal.Protocol.FLAG_HAS_TYPE_ID_INDEX) != 0); + _current.compactId = -1; + } + else + { + // Only the most derived slice encodes the type ID for the compact format. + _current.typeId = ""; + _current.compactId = -1; + } + } + else + { + _current.typeId = _stream.readString(); + _current.compactId = -1; + } + + // + // Read the slice size if necessary. + // + if((_current.sliceFlags & IceInternal.Protocol.FLAG_HAS_SLICE_SIZE) != 0) + { + _current.sliceSize = _stream.readInt(); + if(_current.sliceSize < 4) + { + throw new UnmarshalOutOfBoundsException(); + } + } + else + { + _current.sliceSize = 0; + } + + return _current.typeId; + } + + @Override + void endSlice() + { + if((_current.sliceFlags & IceInternal.Protocol.FLAG_HAS_OPTIONAL_MEMBERS) != 0) + { + _stream.skipOpts(); + } + + // + // Read the indirection table if one is present and transform the + // indirect patch list into patch entries with direct references. + // + if((_current.sliceFlags & IceInternal.Protocol.FLAG_HAS_INDIRECTION_TABLE) != 0) + { + // + // The table is written as a sequence<size> to conserve space. + // + int[] indirectionTable = new int[_stream.readAndCheckSeqSize(1)]; + for(int i = 0; i < indirectionTable.length; ++i) + { + indirectionTable[i] = readInstance(_stream.readSize(), null); + } + + // + // Sanity checks. If there are optional members, it's possible + // that not all object references were read if they are from + // unknown optional data members. + // + if(indirectionTable.length == 0) + { + throw new MarshalException("empty indirection table"); + } + if((_current.indirectPatchList == null || _current.indirectPatchList.isEmpty()) && + (_current.sliceFlags & IceInternal.Protocol.FLAG_HAS_OPTIONAL_MEMBERS) == 0) + { + throw new MarshalException("no references to indirection table"); + } + + // + // Convert indirect references into direct references. + // + if(_current.indirectPatchList != null) + { + for(IndirectPatchEntry e : _current.indirectPatchList) + { + assert(e.index >= 0); + if(e.index >= indirectionTable.length) + { + throw new MarshalException("indirection out of range"); + } + addPatchEntry(indirectionTable[e.index], e.cb); + } + _current.indirectPatchList.clear(); + } + } + } + + @Override + void skipSlice() + { + _stream.traceSkipSlice(_current.typeId, _current.sliceType); + + int start = _stream.pos(); + + if((_current.sliceFlags & IceInternal.Protocol.FLAG_HAS_SLICE_SIZE) != 0) + { + assert(_current.sliceSize >= 4); + _stream.skip(_current.sliceSize - 4); + } + else + { + if(_current.sliceType == SliceType.ObjectSlice) + { + throw new NoValueFactoryException("no value factory found and compact format prevents " + + "slicing (the sender should use the sliced format instead)", + _current.typeId); + } + else + { + if(_current.typeId.startsWith("::")) + { + throw new UnknownUserException(_current.typeId.substring(2)); + } + else + { + throw new UnknownUserException(_current.typeId); + } + } + } + + // + // Preserve this slice. + // + SliceInfo info = new SliceInfo(); + info.typeId = _current.typeId; + info.compactId = _current.compactId; + info.hasOptionalMembers = (_current.sliceFlags & IceInternal.Protocol.FLAG_HAS_OPTIONAL_MEMBERS) != 0; + info.isLastSlice = (_current.sliceFlags & IceInternal.Protocol.FLAG_IS_LAST_SLICE) != 0; + java.nio.ByteBuffer b = _stream.getBuffer().b; + final int end = b.position(); + int dataEnd = end; + if(info.hasOptionalMembers) + { + // + // Don't include the optional member end marker. It will be re-written by + // endSlice when the sliced data is re-written. + // + --dataEnd; + } + info.bytes = new byte[dataEnd - start]; + b.position(start); + b.get(info.bytes); + b.position(end); + + if(_current.slices == null) // Lazy initialization + { + _current.slices = new java.util.ArrayList<SliceInfo>(); + _current.indirectionTables = new java.util.ArrayList<int[]>(); + } + + // + // Read the indirect object table. We read the instances or their + // IDs if the instance is a reference to an already un-marhsaled + // object. + // + // The SliceInfo object sequence is initialized only if + // readSlicedData is called. + // + + if((_current.sliceFlags & IceInternal.Protocol.FLAG_HAS_INDIRECTION_TABLE) != 0) + { + int[] indirectionTable = new int[_stream.readAndCheckSeqSize(1)]; + for(int i = 0; i < indirectionTable.length; ++i) + { + indirectionTable[i] = readInstance(_stream.readSize(), null); + } + _current.indirectionTables.add(indirectionTable); + } + else + { + _current.indirectionTables.add(null); + } + + _current.slices.add(info); + } + + @Override + boolean readOptional(int readTag, OptionalFormat expectedFormat) + { + if(_current == null) + { + return _stream.readOptImpl(readTag, expectedFormat); + } + else if((_current.sliceFlags & IceInternal.Protocol.FLAG_HAS_OPTIONAL_MEMBERS) != 0) + { + return _stream.readOptImpl(readTag, expectedFormat); + } + return false; + } + + private int readInstance(int index, ReadObjectCallback cb) + { + assert(index > 0); + + if(index > 1) + { + if(cb != null) + { + addPatchEntry(index, cb); + } + return index; + } + + push(SliceType.ObjectSlice); + + // + // Get the object ID before we start reading slices. If some + // slices are skiped, the indirect object table are still read and + // might read other objects. + // + index = ++_objectIdIndex; + + // + // Read the first slice header. + // + startSlice(); + final String mostDerivedId = _current.typeId; + Ice.Object v = null; + while(true) + { + if(_current.compactId >= 0) + { + // + // Translate a compact (numeric) type ID into a string type ID. + // + _current.typeId = ""; + if(_compactIdResolver != null) + { + try + { + _current.typeId = _compactIdResolver.resolve(_current.compactId); + } + catch(LocalException ex) + { + throw ex; + } + catch(Throwable ex) + { + throw new MarshalException("exception in CompactIdResolver for ID " + + _current.compactId, ex); + } + } + } + + if(_current.typeId.length() > 0) + { + v = newInstance(_current.typeId); + + // + // We found a factory, we get out of this loop. + // + if(v != null) + { + break; + } + } + + // + // If object slicing is disabled, stop un-marshalling. + // + if(!_sliceObjects) + { + throw new NoValueFactoryException("no value factory found and object slicing is disabled", + _current.typeId); + } + + // + // Slice off what we don't understand. + // + skipSlice(); + + // + // If this is the last slice, keep the object as an opaque + // UnknownSlicedData object. + // + if((_current.sliceFlags & IceInternal.Protocol.FLAG_IS_LAST_SLICE) != 0) + { + // + // Provide a factory with an opportunity to supply the object. + // We pass the "::Ice::Object" ID to indicate that this is the + // last chance to preserve the object. + // + v = newInstance(ObjectImpl.ice_staticId()); + if(v == null) + { + v = new UnknownSlicedObject(mostDerivedId); + } + + break; + } + + startSlice(); // Read next Slice header for next iteration. + } + + // + // Unmarshal the object. + // + unmarshal(index, v); + + if(_current == null && _patchMap != null && !_patchMap.isEmpty()) + { + // + // If any entries remain in the patch map, the sender has sent an index for an object, but failed + // to supply the object. + // + throw new MarshalException("index for class received, but no instance"); + } + + if(cb != null) + { + cb.objectReady(v); + } + + return index; + } + + private SlicedData readSlicedData() + { + if(_current.slices == null) // No preserved slices. + { + return null; + } + + // + // The _indirectionTables member holds the indirection table for each slice + // in _slices. + // + assert(_current.slices.size() == _current.indirectionTables.size()); + for(int n = 0; n < _current.slices.size(); ++n) + { + // + // We use the "objects" list in SliceInfo to hold references + // to the target objects. Note that the objects might not have + // been read yet in the case of a circular reference to an + // enclosing object. + // + final int[] table = _current.indirectionTables.get(n); + SliceInfo info = _current.slices.get(n); + info.objects = new Ice.Object[table != null ? table.length : 0]; + for(int j = 0; j < info.objects.length; ++j) + { + addPatchEntry(table[j], new IceInternal.SequencePatcher(info.objects, Ice.Object.class, + ObjectImpl.ice_staticId(), j)); + } + } + + SliceInfo[] arr = new SliceInfo[_current.slices.size()]; + _current.slices.toArray(arr); + return new SlicedData(arr); + } + + private void push(SliceType sliceType) + { + if(_current == null) + { + _current = new InstanceData(null); + } + else + { + _current = _current.next == null ? new InstanceData(_current) : _current.next; + } + _current.sliceType = sliceType; + _current.skipFirstSlice = false; + } + + private static final class IndirectPatchEntry + { + int index; + ReadObjectCallback cb; + } + + private static final class InstanceData + { + InstanceData(InstanceData previous) + { + if(previous != null) + { + previous.next = this; + } + this.previous = previous; + this.next = null; + } + + // Instance attributes + SliceType sliceType; + boolean skipFirstSlice; + java.util.List<SliceInfo> slices; // Preserved slices. + java.util.List<int[]> indirectionTables; + + // Slice attributes + byte sliceFlags; + int sliceSize; + String typeId; + int compactId; + java.util.Deque<IndirectPatchEntry> indirectPatchList; + + final InstanceData previous; + InstanceData next; + } + + private CompactIdResolver _compactIdResolver; + private InstanceData _current; + private int _objectIdIndex; // The ID of the next object to un-marshal. + } + + private static final class Encaps + { + void reset() + { + decoder = null; + } + + void setEncoding(EncodingVersion encoding) + { + this.encoding = encoding; + encoding_1_0 = encoding.equals(Util.Encoding_1_0); + } + + int start; + int sz; + EncodingVersion encoding; + boolean encoding_1_0; + + EncapsDecoder decoder; + + Encaps next; + } + + // + // The encoding version to use when there's no encapsulation to + // read from. This is for example used to read message + // headers. + // + private EncodingVersion _encoding; + + private boolean isEncoding_1_0() + { + return _encapsStack != null ? _encapsStack.encoding_1_0 : _encoding.equals(Util.Encoding_1_0); + } + + private Encaps _encapsStack; + private Encaps _encapsCache; + + private void initEncaps() + { + if(_encapsStack == null) // Lazy initialization + { + _encapsStack = _encapsCache; + if(_encapsStack != null) + { + _encapsCache = _encapsCache.next; + } + else + { + _encapsStack = new Encaps(); + } + _encapsStack.setEncoding(_encoding); + _encapsStack.sz = _buf.b.limit(); + } + + if(_encapsStack.decoder == null) // Lazy initialization. + { + if(_encapsStack.encoding_1_0) + { + _encapsStack.decoder = new EncapsDecoder10(this, _sliceObjects, _valueFactoryManager); + } + else + { + _encapsStack.decoder = new EncapsDecoder11(this, _sliceObjects, _valueFactoryManager, + _compactIdResolver); + } + } + } + + private void traceSkipSlice(String typeId, SliceType sliceType) + { + if(_traceSlicing && _logger != null) + { + IceInternal.TraceUtil.traceSlicing(sliceType == SliceType.ExceptionSlice ? "exception" : "object", typeId, + "Slicing", _logger); + } + } + + private boolean _sliceObjects; + private boolean _traceSlicing; + + private int _startSeq; + private int _minSeqSize; + + private ValueFactoryManager _valueFactoryManager; + private Logger _logger; + private CompactIdResolver _compactIdResolver; + private ClassResolver _classResolver; } diff --git a/java/src/Ice/src/main/java/Ice/InputStreamI.java b/java/src/Ice/src/main/java/Ice/InputStreamI.java deleted file mode 100644 index 238ad7a0ab3..00000000000 --- a/java/src/Ice/src/main/java/Ice/InputStreamI.java +++ /dev/null @@ -1,454 +0,0 @@ -// ********************************************************************** -// -// Copyright (c) 2003-2015 ZeroC, Inc. All rights reserved. -// -// This copy of Ice is licensed to you under the terms described in the -// ICE_LICENSE file included in this distribution. -// -// ********************************************************************** - -package Ice; - -public class InputStreamI implements InputStream -{ - public - InputStreamI(Communicator communicator, byte[] data, boolean copyData) - { - _communicator = communicator; - IceInternal.Instance instance = IceInternal.Util.getInstance(communicator); - initialize(instance, data, instance.defaultsAndOverrides().defaultEncoding, copyData); - } - - public - InputStreamI(Communicator communicator, byte[] data, EncodingVersion v, boolean copyData) - { - _communicator = communicator; - initialize(IceInternal.Util.getInstance(communicator), data, v, copyData); - } - - private void - initialize(IceInternal.Instance instance, byte[] data, EncodingVersion v, boolean copyData) - { - if(copyData) - { - _is = new IceInternal.BasicStream(instance, v, false); - _is.resize(data.length, true); - IceInternal.Buffer buf = _is.getBuffer(); - buf.b.position(0); - buf.b.put(data); - buf.b.position(0); - } - else - { - _is = new IceInternal.BasicStream(instance, v, data); - } - _is.closure(this); - } - - @Override - public Communicator - communicator() - { - return _communicator; - } - - @Override - public void - sliceObjects(boolean slice) - { - _is.sliceObjects(slice); - } - - @Override - public boolean - readBool() - { - return _is.readBool(); - } - - @Override - public boolean[] - readBoolSeq() - { - return _is.readBoolSeq(); - } - - @Override - public byte - readByte() - { - return _is.readByte(); - } - - @Override - public byte[] - readByteSeq() - { - return _is.readByteSeq(); - } - - @Override - public java.nio.ByteBuffer - readByteBuffer() - { - return _is.readByteBuffer(); - } - - @Override - public java.io.Serializable - readSerializable() - { - return _is.readSerializable(); - } - - @Override - public short - readShort() - { - return _is.readShort(); - } - - @Override - public short[] - readShortSeq() - { - return _is.readShortSeq(); - } - - @Override - public java.nio.ShortBuffer - readShortBuffer() - { - return _is.readShortBuffer(); - } - - @Override - public int - readInt() - { - return _is.readInt(); - } - - @Override - public int[] - readIntSeq() - { - return _is.readIntSeq(); - } - - @Override - public java.nio.IntBuffer - readIntBuffer() - { - return _is.readIntBuffer(); - } - - @Override - public long - readLong() - { - return _is.readLong(); - } - - @Override - public long[] - readLongSeq() - { - return _is.readLongSeq(); - } - - @Override - public java.nio.LongBuffer - readLongBuffer() - { - return _is.readLongBuffer(); - } - - @Override - public float - readFloat() - { - return _is.readFloat(); - } - - @Override - public float[] - readFloatSeq() - { - return _is.readFloatSeq(); - } - - @Override - public java.nio.FloatBuffer - readFloatBuffer() - { - return _is.readFloatBuffer(); - } - - @Override - public double - readDouble() - { - return _is.readDouble(); - } - - @Override - public double[] - readDoubleSeq() - { - return _is.readDoubleSeq(); - } - - @Override - public java.nio.DoubleBuffer - readDoubleBuffer() - { - return _is.readDoubleBuffer(); - } - - @Override - public String - readString() - { - return _is.readString(); - } - - @Override - public String[] - readStringSeq() - { - return _is.readStringSeq(); - } - - @Override - public int - readSize() - { - return _is.readSize(); - } - - @Override - public int - readAndCheckSeqSize(int minWire) - { - return _is.readAndCheckSeqSize(minWire); - } - - @Override - public ObjectPrx - readProxy() - { - return _is.readProxy(); - } - - private static class Patcher implements IceInternal.Patcher - { - Patcher(ReadObjectCallback cb) - { - _cb = cb; - } - - @Override - public void - patch(Ice.Object v) - { - _cb.invoke(v); - } - - @Override - public String - type() - { - return "unknown"; - } - - ReadObjectCallback _cb; - } - - @Override - public void - readObject(ReadObjectCallback cb) - { - _is.readObject(new Patcher(cb)); - } - - @Override - public int - readEnum(int maxValue) - { - return _is.readEnum(maxValue); - } - - @Override - public void - throwException() - throws UserException - { - _is.throwException(null); - } - - private static class UserExceptionFactoryI implements IceInternal.UserExceptionFactory - { - UserExceptionFactoryI(UserExceptionReaderFactory factory) - { - _factory = factory; - } - - @Override - public void - createAndThrow(String id) - throws UserException - { - _factory.createAndThrow(id); - } - - @Override - public void - destroy() - { - } - - private UserExceptionReaderFactory _factory; - } - - @Override - public void - throwException(UserExceptionReaderFactory factory) - throws UserException - { - _is.throwException(new UserExceptionFactoryI(factory)); - } - - @Override - public void - startObject() - { - _is.startReadObject(); - } - - @Override - public SlicedData - endObject(boolean preserve) - { - return _is.endReadObject(preserve); - } - - @Override - public void - startException() - { - _is.startReadException(); - } - - @Override - public SlicedData - endException(boolean preserve) - { - return _is.endReadException(preserve); - } - - @Override - public String - startSlice() - { - return _is.startReadSlice(); - } - - @Override - public void - endSlice() - { - _is.endReadSlice(); - } - - @Override - public void - skipSlice() - { - _is.skipSlice(); - } - - @Override - public Ice.EncodingVersion - startEncapsulation() - { - return _is.startReadEncaps(); - } - - @Override - public void - endEncapsulation() - { - _is.endReadEncapsChecked(); - } - - @Override - public Ice.EncodingVersion - skipEncapsulation() - { - return _is.skipEncaps(); - } - - @Override - public EncodingVersion - getEncoding() - { - return _is.getReadEncoding(); - } - - @Override - public void - readPendingObjects() - { - _is.readPendingObjects(); - } - - @Override - public void - rewind() - { - _is.clear(); - _is.getBuffer().b.position(0); - } - - @Override - public void - skip(int sz) - { - _is.skip(sz); - } - - @Override - public void - skipSize() - { - _is.skipSize(); - } - - @Override - public boolean - readOptional(int tag, OptionalFormat format) - { - return _is.readOpt(tag, format); - } - - @Override - public int - pos() - { - return _is.pos(); - } - - @Override - public void - destroy() - { - if(_is != null) - { - _is = null; - } - } - - private Communicator _communicator; - private IceInternal.BasicStream _is; -} diff --git a/java/src/Ice/src/main/java/Ice/Object.java b/java/src/Ice/src/main/java/Ice/Object.java index 6be6c02fda7..2e41b017da9 100644 --- a/java/src/Ice/src/main/java/Ice/Object.java +++ b/java/src/Ice/src/main/java/Ice/Object.java @@ -155,11 +155,8 @@ public interface Object DispatchStatus __dispatch(IceInternal.Incoming in, Current current); - void __write(IceInternal.BasicStream __os); - void __read(IceInternal.BasicStream __is); - - void __write(OutputStream __outS); - void __read(InputStream __inS); + void __write(OutputStream __os); + void __read(InputStream __is); public static final String ice_staticId = "::Ice::Object"; } diff --git a/java/src/Ice/src/main/java/Ice/ObjectHolder.java b/java/src/Ice/src/main/java/Ice/ObjectHolder.java index 6f63d492efc..6181b44c5ff 100644 --- a/java/src/Ice/src/main/java/Ice/ObjectHolder.java +++ b/java/src/Ice/src/main/java/Ice/ObjectHolder.java @@ -36,9 +36,8 @@ public final class ObjectHolder extends ObjectHolderBase<Ice.Object> * * @param v The new object for this holder. **/ - @Override public void - patch(Ice.Object v) + objectReady(Ice.Object v) { value = v; } @@ -49,7 +48,7 @@ public final class ObjectHolder extends ObjectHolderBase<Ice.Object> * * @return The Slice type ID. **/ - @Override + // TBD: Remove public String type() { diff --git a/java/src/Ice/src/main/java/Ice/ObjectHolderBase.java b/java/src/Ice/src/main/java/Ice/ObjectHolderBase.java index 5a651fb4caf..e113f008cfa 100644 --- a/java/src/Ice/src/main/java/Ice/ObjectHolderBase.java +++ b/java/src/Ice/src/main/java/Ice/ObjectHolderBase.java @@ -12,7 +12,7 @@ package Ice; /** * Holder base class for Ice objects that are in- or inout-parameters. **/ -public abstract class ObjectHolderBase<T extends Ice.Object> implements ReadObjectCallback, IceInternal.Patcher +public abstract class ObjectHolderBase<T extends Ice.Object> implements ReadObjectCallback { /** * Instantiates the class with a <code>null</code> value. @@ -32,18 +32,6 @@ public abstract class ObjectHolderBase<T extends Ice.Object> implements ReadObje } /** - * Sets the Ice object of this holder to the passed instance. - * - * @param obj The new object for this holder. - **/ - @Override - public void - invoke(Ice.Object obj) - { - patch(obj); - } - - /** * The Ice object stored by this holder. **/ public T value; diff --git a/java/src/Ice/src/main/java/Ice/ObjectImpl.java b/java/src/Ice/src/main/java/Ice/ObjectImpl.java index 6c4d7c2d4c7..dece04db455 100644 --- a/java/src/Ice/src/main/java/Ice/ObjectImpl.java +++ b/java/src/Ice/src/main/java/Ice/ObjectImpl.java @@ -82,11 +82,11 @@ public abstract class ObjectImpl implements Object, java.lang.Cloneable, java.io public static DispatchStatus ___ice_isA(Ice.Object __obj, IceInternal.Incoming __inS, Current __current) { - IceInternal.BasicStream __is = __inS.startReadParams(); + InputStream __is = __inS.startReadParams(); String __id = __is.readString(); __inS.endReadParams(); boolean __ret = __obj.ice_isA(__id, __current); - IceInternal.BasicStream __os = __inS.__startWriteParams(Ice.FormatType.DefaultFormat); + OutputStream __os = __inS.__startWriteParams(Ice.FormatType.DefaultFormat); __os.writeBool(__ret); __inS.__endWriteParams(true); return DispatchStatus.DispatchOK; @@ -153,7 +153,7 @@ public abstract class ObjectImpl implements Object, java.lang.Cloneable, java.io { __inS.readEmptyParams(); String[] __ret = __obj.ice_ids(__current); - IceInternal.BasicStream __os = __inS.__startWriteParams(Ice.FormatType.DefaultFormat); + OutputStream __os = __inS.__startWriteParams(Ice.FormatType.DefaultFormat); __os.writeStringSeq(__ret); __inS.__endWriteParams(true); return DispatchStatus.DispatchOK; @@ -189,7 +189,7 @@ public abstract class ObjectImpl implements Object, java.lang.Cloneable, java.io { __inS.readEmptyParams(); String __ret = __obj.ice_id(__current); - IceInternal.BasicStream __os = __inS.__startWriteParams(Ice.FormatType.DefaultFormat); + OutputStream __os = __inS.__startWriteParams(Ice.FormatType.DefaultFormat); __os.writeString(__ret); __inS.__endWriteParams(true); return DispatchStatus.DispatchOK; @@ -355,60 +355,30 @@ public abstract class ObjectImpl implements Object, java.lang.Cloneable, java.io @Override public void - __write(IceInternal.BasicStream os) - { - os.startWriteObject(null); - __writeImpl(os); - os.endWriteObject(); - } - - @Override - public void - __read(IceInternal.BasicStream is) - { - is.startReadObject(); - __readImpl(is); - is.endReadObject(false); - } - - @Override - public void __write(OutputStream os) { - os.startObject(null); - __writeImpl(os); - os.endObject(); + os.startObject(null); + __writeImpl(os); + os.endObject(); } @Override public void __read(InputStream is) { - is.startObject(); - __readImpl(is); - is.endObject(false); - } - - protected void - __writeImpl(IceInternal.BasicStream os) - { + is.startObject(); + __readImpl(is); + is.endObject(false); } protected void - __readImpl(IceInternal.BasicStream is) - { - } - - protected void __writeImpl(OutputStream os) { - throw new MarshalException("class was not generated with stream support"); } protected void __readImpl(InputStream is) { - throw new MarshalException("class was not generated with stream support"); } private static String diff --git a/java/src/Ice/src/main/java/Ice/ObjectPrx.java b/java/src/Ice/src/main/java/Ice/ObjectPrx.java index bf822cbd67b..d1e5e0c5311 100644 --- a/java/src/Ice/src/main/java/Ice/ObjectPrx.java +++ b/java/src/Ice/src/main/java/Ice/ObjectPrx.java @@ -1207,4 +1207,6 @@ public interface ObjectPrx **/ @Override boolean equals(java.lang.Object r); + + void __write(OutputStream os); } diff --git a/java/src/Ice/src/main/java/Ice/ObjectPrxHelperBase.java b/java/src/Ice/src/main/java/Ice/ObjectPrxHelperBase.java index 3ceb4b312a6..0e4ad3a002d 100644 --- a/java/src/Ice/src/main/java/Ice/ObjectPrxHelperBase.java +++ b/java/src/Ice/src/main/java/Ice/ObjectPrxHelperBase.java @@ -282,7 +282,7 @@ public class ObjectPrxHelperBase implements ObjectPrx, java.io.Serializable try { __result.prepare(__ice_isA_name, OperationMode.Nonmutating, __context, __explicitCtx, __synchronous); - IceInternal.BasicStream __os = __result.startWriteParams(Ice.FormatType.DefaultFormat); + OutputStream __os = __result.startWriteParams(Ice.FormatType.DefaultFormat); __os.writeString(__id); __result.endWriteParams(); __result.invoke(); @@ -319,7 +319,7 @@ public class ObjectPrxHelperBase implements ObjectPrx, java.io.Serializable } } boolean __ret; - IceInternal.BasicStream __is = __result.startReadParams(); + InputStream __is = __result.startReadParams(); __ret = __is.readBool(); __result.endReadParams(); return __ret; @@ -810,7 +810,7 @@ public class ObjectPrxHelperBase implements ObjectPrx, java.io.Serializable } } String[] __ret = null; - IceInternal.BasicStream __is = __result.startReadParams(); + InputStream __is = __result.startReadParams(); __ret = StringSeqHelper.read(__is); __result.endReadParams(); return __ret; @@ -1085,7 +1085,7 @@ public class ObjectPrxHelperBase implements ObjectPrx, java.io.Serializable } } String __ret = null; - IceInternal.BasicStream __is = __result.startReadParams(); + InputStream __is = __result.startReadParams(); __ret = __is.readString(); __result.endReadParams(); return __ret; @@ -2543,6 +2543,12 @@ public class ObjectPrxHelperBase implements ObjectPrx, java.io.Serializable return false; } + public void __write(OutputStream os) + { + _reference.getIdentity().ice_write(os); + _reference.streamWrite(os); + } + public final IceInternal.Reference __reference() { @@ -2736,7 +2742,7 @@ public class ObjectPrxHelperBase implements ObjectPrx, java.io.Serializable } public void - cacheMessageBuffers(IceInternal.BasicStream is, IceInternal.BasicStream os) + cacheMessageBuffers(InputStream is, OutputStream os) { synchronized(this) { @@ -2976,14 +2982,14 @@ public class ObjectPrxHelperBase implements ObjectPrx, java.io.Serializable private static class StreamCacheEntry { - StreamCacheEntry(IceInternal.BasicStream is, IceInternal.BasicStream os) + StreamCacheEntry(InputStream is, OutputStream os) { this.is = is; this.os = os; } - IceInternal.BasicStream is; - IceInternal.BasicStream os; + InputStream is; + OutputStream os; } private transient IceInternal.Reference _reference; diff --git a/java/src/Ice/src/main/java/Ice/ObjectReader.java b/java/src/Ice/src/main/java/Ice/ObjectReader.java index 50af3772f93..62169646e83 100644 --- a/java/src/Ice/src/main/java/Ice/ObjectReader.java +++ b/java/src/Ice/src/main/java/Ice/ObjectReader.java @@ -18,25 +18,18 @@ public abstract class ObjectReader extends ObjectImpl * Reads the state of this Slice class from an input stream. * * @param in The input stream to read from. - * @param rid If <code>true</code>, extraction begins by reading a Slice type ID - * first. If <code>false</code>, the leading type ID is not read. This is used - * by the unmarshaling code in case the type ID has already been read as part - * of other unmarshaling activities. **/ public abstract void read(InputStream in); @Override - public void - __write(IceInternal.BasicStream os) + public void __write(OutputStream os) { assert(false); } @Override - public void - __read(IceInternal.BasicStream is) + public void __read(InputStream is) { - InputStream stream = (InputStream)is.closure(); - read(stream); + read(is); } } diff --git a/java/src/Ice/src/main/java/Ice/ObjectWriter.java b/java/src/Ice/src/main/java/Ice/ObjectWriter.java index e22dbe758e4..2f3d70e00a0 100644 --- a/java/src/Ice/src/main/java/Ice/ObjectWriter.java +++ b/java/src/Ice/src/main/java/Ice/ObjectWriter.java @@ -22,15 +22,13 @@ public abstract class ObjectWriter extends ObjectImpl public abstract void write(OutputStream out); @Override - public void - __write(IceInternal.BasicStream os) + public void __write(OutputStream os) { - OutputStream stream = (OutputStream)os.closure(); - write(stream); + write(os); } - public void - __read(IceInternal.BasicStream is, boolean rid) + @Override + public void __read(Ice.InputStream is) { assert(false); } diff --git a/java/src/Ice/src/main/java/Ice/OptionalObject.java b/java/src/Ice/src/main/java/Ice/OptionalObject.java index 95d693bf6af..6c9b8be8de6 100644 --- a/java/src/Ice/src/main/java/Ice/OptionalObject.java +++ b/java/src/Ice/src/main/java/Ice/OptionalObject.java @@ -12,7 +12,7 @@ package Ice; /** * Handles callbacks for an optional object parameter. **/ -public class OptionalObject implements ReadObjectCallback, IceInternal.Patcher +public class OptionalObject implements ReadObjectCallback { /** * Instantiates the class with the given optional. @@ -36,9 +36,8 @@ public class OptionalObject implements ReadObjectCallback, IceInternal.Patcher * @param v The new object for the optional. **/ @SuppressWarnings("unchecked") - @Override public void - patch(Ice.Object v) + objectReady(Ice.Object v) { if(v == null || cls.isInstance(v)) { @@ -59,7 +58,7 @@ public class OptionalObject implements ReadObjectCallback, IceInternal.Patcher * * @return The Slice type ID. **/ - @Override + // TBD: Remove public String type() { @@ -67,18 +66,6 @@ public class OptionalObject implements ReadObjectCallback, IceInternal.Patcher } /** - * Sets the Ice object of the optional to the passed instance. - * - * @param obj The new object for the optional. - **/ - @Override - public void - invoke(Ice.Object obj) - { - patch(obj); - } - - /** * The optional object. **/ @SuppressWarnings("rawtypes") diff --git a/java/src/Ice/src/main/java/Ice/OutputStream.java b/java/src/Ice/src/main/java/Ice/OutputStream.java index b63fe9eefcd..721900517e9 100644 --- a/java/src/Ice/src/main/java/Ice/OutputStream.java +++ b/java/src/Ice/src/main/java/Ice/OutputStream.java @@ -9,369 +9,2414 @@ package Ice; -/** - * Interface for output streams used to write Slice types to a sequence - * of bytes. - * - * @see InputStream - **/ -public interface OutputStream +public class OutputStream { /** - * Returns the communicator for this output stream. + * Constructing an OutputStream without providing a communicator means the stream will + * use the default encoding version, the default format for class encoding, and a + * non-direct buffer. You can supply a communicator later by calling initialize(). + **/ + public OutputStream() + { + this(false); + } + + /** + * Constructing an OutputStream without providing a communicator means the stream will + * use the default encoding version and the default format for class encoding. + * You can supply a communicator later by calling initialize(). * - * @return The communicator. + * @param direct Indicates whether to use a direct buffer. **/ - Communicator communicator(); + public OutputStream(boolean direct) + { + _buf = new IceInternal.Buffer(direct); + _instance = null; + _closure = null; + _encoding = IceInternal.Protocol.currentEncoding; + _format = FormatType.CompactFormat; + } /** - * Writes a boolean to the stream. + * This constructor uses the communicator's default encoding version. * - * @param v The boolean to write to the stream. + * @param communicator The communicator to use when initializing the stream. **/ - void writeBool(boolean v); + public OutputStream(Communicator communicator) + { + assert(communicator != null); + final IceInternal.Instance instance = IceInternal.Util.getInstance(communicator); + initialize(instance, instance.defaultsAndOverrides().defaultEncoding, instance.cacheMessageBuffers() > 1); + } /** - * Writes a sequence of booleans to the stream. + * This constructor uses the communicator's default encoding version. * - * @param v The sequence of booleans to write. - * Passing <code>null</code> causes an empty sequence to be written to the stream. + * @param communicator The communicator to use when initializing the stream. + * @param direct Indicates whether to use a direct buffer. + **/ + public OutputStream(Communicator communicator, boolean direct) + { + assert(communicator != null); + final IceInternal.Instance instance = IceInternal.Util.getInstance(communicator); + initialize(instance, instance.defaultsAndOverrides().defaultEncoding, direct); + } + + /** + * This constructor uses the given communicator and encoding version. + * + * @param communicator The communicator to use when initializing the stream. + * @param encoding The desired Ice encoding version. + **/ + public OutputStream(Communicator communicator, EncodingVersion encoding) + { + assert(communicator != null); + final IceInternal.Instance instance = IceInternal.Util.getInstance(communicator); + initialize(instance, encoding, instance.cacheMessageBuffers() > 1); + } + + /** + * This constructor uses the given communicator and encoding version. + * + * @param communicator The communicator to use when initializing the stream. + * @param encoding The desired Ice encoding version. + * @param direct Indicates whether to use a direct buffer. + **/ + public OutputStream(Communicator communicator, EncodingVersion encoding, boolean direct) + { + assert(communicator != null); + final IceInternal.Instance instance = IceInternal.Util.getInstance(communicator); + initialize(instance, encoding, direct); + } + + public OutputStream(IceInternal.Instance instance, EncodingVersion encoding) + { + initialize(instance, encoding, instance.cacheMessageBuffers() > 1); + } + + public OutputStream(IceInternal.Instance instance, EncodingVersion encoding, boolean direct) + { + initialize(instance, encoding, direct); + } + + public OutputStream(IceInternal.Instance instance, EncodingVersion encoding, IceInternal.Buffer buf, boolean adopt) + { + initialize(instance, encoding, new IceInternal.Buffer(buf, adopt)); + } + + /** + * Initializes the stream to use the communicator's default encoding version and class + * encoding format. + * + * @param communicator The communicator to use when initializing the stream. + **/ + public void initialize(Communicator communicator) + { + assert(communicator != null); + final IceInternal.Instance instance = IceInternal.Util.getInstance(communicator); + initialize(instance, instance.defaultsAndOverrides().defaultEncoding, instance.cacheMessageBuffers() > 1); + } + + /** + * Initializes the stream to use the given encoding version and the communicator's + * default class encoding format. + * + * @param communicator The communicator to use when initializing the stream. + * @param encoding The desired Ice encoding version. + **/ + public void initialize(Communicator communicator, EncodingVersion encoding) + { + assert(communicator != null); + final IceInternal.Instance instance = IceInternal.Util.getInstance(communicator); + initialize(instance, encoding, instance.cacheMessageBuffers() > 1); + } + + private void initialize(IceInternal.Instance instance, EncodingVersion encoding, boolean direct) + { + initialize(instance, encoding, new IceInternal.Buffer(direct)); + } + + private void initialize(IceInternal.Instance instance, EncodingVersion encoding, IceInternal.Buffer buf) + { + assert(instance != null); + + _instance = instance; + _buf = buf; + _closure = null; + _encoding = encoding; + + _format = _instance.defaultsAndOverrides().defaultFormat; + + _encapsStack = null; + _encapsCache = null; + } + + /** + * Resets this output stream. This method allows the stream to be reused, to avoid creating + * unnecessary garbage. + **/ + public void reset() + { + _buf.reset(); + clear(); + } + + /** + * Releases any data retained by encapsulations. The {@link #reset} method internally calls </code>clear</code>. + **/ + public void clear() + { + if(_encapsStack != null) + { + assert(_encapsStack.next == null); + _encapsStack.next = _encapsCache; + _encapsCache = _encapsStack; + _encapsCache.reset(); + _encapsStack = null; + } + } + + public IceInternal.Instance instance() + { + return _instance; + } + + /** + * Sets the encoding format for class and exception instances. + * + * @param fmt The encoding format. + **/ + public void setFormat(FormatType fmt) + { + _format = fmt; + } + + /** + * Retrieves the closure object associated with this stream. + * + * @return The closure object. + **/ + public Object getClosure() + { + return _closure; + } + + /** + * Associates a closure object with this stream. + * + * @param p The new closure object. + * @return The previous closure object, or null. + **/ + public Object setClosure(Object p) + { + Object prev = _closure; + _closure = p; + return prev; + } + + /** + * Indicates that marshaling is finished. + * + * @return The byte sequence containing the encoded data. + **/ + public byte[] finished() + { + IceInternal.Buffer buf = prepareWrite(); + byte[] result = new byte[buf.b.limit()]; + buf.b.get(result); + return result; + } + + /** + * Swaps the contents of one stream with another. + * + * @param other The other stream. + **/ + public void swap(OutputStream other) + { + assert(_instance == other._instance); + + IceInternal.Buffer tmpBuf = other._buf; + other._buf = _buf; + _buf = tmpBuf; + + Object tmpClosure = other._closure; + other._closure = _closure; + _closure = tmpClosure; + + // + // Swap is never called for streams that have encapsulations being written. However, + // encapsulations might still be set in case marshalling failed. We just + // reset the encapsulations if there are still some set. + // + resetEncapsulation(); + other.resetEncapsulation(); + } + + private void resetEncapsulation() + { + _encapsStack = null; + } + + /** + * Resizes the stream to a new size. + * + * @param sz The new size. + **/ + public void resize(int sz) + { + _buf.resize(sz, false); + _buf.b.position(sz); + } + + /** + * Prepares the internal data buffer to be written to a socket. + **/ + public IceInternal.Buffer prepareWrite() + { + _buf.b.limit(_buf.size()); + _buf.b.position(0); + return _buf; + } + + /** + * Retrieves the internal data buffer. + * + * @return The buffer. + **/ + public IceInternal.Buffer getBuffer() + { + return _buf; + } + + /** + * Marks the start of an Ice object. + * + * @param slicedData Preserved slices for this object, or null. + **/ + public void startObject(SlicedData data) + { + assert(_encapsStack != null && _encapsStack.encoder != null); + _encapsStack.encoder.startInstance(SliceType.ObjectSlice, data); + } + + /** + * Marks the end of an Ice object. + **/ + public void endObject() + { + assert(_encapsStack != null && _encapsStack.encoder != null); + _encapsStack.encoder.endInstance(); + } + + /** + * Marks the start of a user exception. + * + * @param slicedData Preserved slices for this exception, or null. + **/ + public void startException(SlicedData data) + { + assert(_encapsStack != null && _encapsStack.encoder != null); + _encapsStack.encoder.startInstance(SliceType.ExceptionSlice, data); + } + + /** + * Marks the end of a user exception. + **/ + public void endException() + { + assert(_encapsStack != null && _encapsStack.encoder != null); + _encapsStack.encoder.endInstance(); + } + + /** + * Writes the start of an encapsulation to the stream. + **/ + public void startEncapsulation() + { + // + // If no encoding version is specified, use the current write + // encapsulation encoding version if there's a current write + // encapsulation, otherwise, use the stream encoding version. + // + + if(_encapsStack != null) + { + startEncapsulation(_encapsStack.encoding, _encapsStack.format); + } + else + { + startEncapsulation(_encoding, FormatType.DefaultFormat); + } + } + + /** + * Writes the start of an encapsulation to the stream. + * + * @param encoding The encoding version of the encapsulation. + * + * @param format Specify the compact or sliced format. + * + **/ + public void startEncapsulation(EncodingVersion encoding, FormatType format) + { + IceInternal.Protocol.checkSupportedEncoding(encoding); + + Encaps curr = _encapsCache; + if(curr != null) + { + curr.reset(); + _encapsCache = _encapsCache.next; + } + else + { + curr = new Encaps(); + } + curr.next = _encapsStack; + _encapsStack = curr; + + _encapsStack.format = format; + _encapsStack.setEncoding(encoding); + _encapsStack.start = _buf.size(); + + writeInt(0); // Placeholder for the encapsulation length. + _encapsStack.encoding.ice_write(this); + } + + /** + * Ends the previous encapsulation. + **/ + public void endEncapsulation() + { + assert(_encapsStack != null); + + // Size includes size and version. + int start = _encapsStack.start; + int sz = _buf.size() - start; + _buf.b.putInt(start, sz); + + Encaps curr = _encapsStack; + _encapsStack = curr.next; + curr.next = _encapsCache; + _encapsCache = curr; + _encapsCache.reset(); + } + + /** + * Writes an empty encapsulation using the given encoding version. + * + * @param encoding The desired encoding version. + **/ + public void writeEmptyEncapsulation(EncodingVersion encoding) + { + IceInternal.Protocol.checkSupportedEncoding(encoding); + writeInt(6); // Size + encoding.ice_write(this); + } + + /** + * Writes a pre-encoded encapsulation. + * + * @param v The encapsulation data. + **/ + public void writeEncapsulation(byte[] v) + { + if(v.length < 6) + { + throw new EncapsulationException(); + } + expand(v.length); + _buf.b.put(v); + } + + /** + * Determines the current encoding version. + * + * @return The encoding version. + **/ + public EncodingVersion getEncoding() + { + return _encapsStack != null ? _encapsStack.encoding : _encoding; + } + + /** + * Marks the start of a new slice for an Ice object or user exception. + * + * @param typeId The Slice type ID corresponding to this slice. + + * @param compactId The Slice compact type ID corresponding to + * this slice or -1 if no compact ID is defined for the + * type ID. + + * @param last True if this is the last slice, false otherwise. + **/ + public void startSlice(String typeId, int compactId, boolean last) + { + assert(_encapsStack != null && _encapsStack.encoder != null); + _encapsStack.encoder.startSlice(typeId, compactId, last); + } + + /** + * Marks the end of a slice for an Ice object or user exception. + **/ + public void endSlice() + { + assert(_encapsStack != null && _encapsStack.encoder != null); + _encapsStack.encoder.endSlice(); + } + + /** + * Writes the state of Slice classes whose index was previously + * written with {@link #writeObject} to the stream. + **/ + public void writePendingObjects() + { + if(_encapsStack != null && _encapsStack.encoder != null) + { + _encapsStack.encoder.writePendingObjects(); + } + else if(_encapsStack != null ? _encapsStack.encoding_1_0 : _encoding.equals(Util.Encoding_1_0)) + { + // + // If using the 1.0 encoding and no objects were written, we + // still write an empty sequence for pending objects if + // requested (i.e.: if this is called). + // + // This is required by the 1.0 encoding, even if no objects + // are written we do marshal an empty sequence if marshaled + // data types use classes. + // + writeSize(0); + } + } + + /** + * Writes a size to the stream. + * + * @param sz The size to write. + **/ + public void writeSize(int v) + { + if(v > 254) + { + expand(5); + _buf.b.put((byte)-1); + _buf.b.putInt(v); + } + else + { + expand(1); + _buf.b.put((byte)v); + } + } + + /** + * Returns the current position and allocates four bytes for a fixed-length (32-bit) + * size value. + * + * @return The current position. + **/ + public int startSize() + { + int pos = _buf.b.position(); + writeInt(0); // Placeholder for 32-bit size + return pos; + } + + /** + * Computes the amount of data written since the previous call to startSize and + * writes that value at the saved position. + * + * @param pos The saved position. + **/ + public void endSize(int pos) + { + assert(pos >= 0); + rewriteInt(_buf.b.position() - pos - 4, pos); + } + + /** + * Writes a blob of bytes to the stream. + * + * @param v The byte array to be written. All of the bytes in the array are written. + **/ + public void writeBlob(byte[] v) + { + if(v == null) + { + return; + } + expand(v.length); + _buf.b.put(v); + } + + /** + * Writes a blob of bytes to the stream. + * + * @param v The byte array to be written. + * @param off The offset into the byte array from which to copy. + * @param len The number of bytes from the byte array to copy. **/ - void writeBoolSeq(boolean[] v); + public void writeBlob(byte[] v, int off, int len) + { + if(v == null) + { + return; + } + expand(len); + _buf.b.put(v, off, len); + } + + /** + * Write the header information for an optional value. + * + * @param tag The numeric tag associated with the value. + * @param format The optional format of the value. + **/ + public boolean writeOptional(int tag, OptionalFormat format) + { + assert(_encapsStack != null); + if(_encapsStack.encoder != null) + { + return _encapsStack.encoder.writeOptional(tag, format); + } + else + { + return writeOptionalImpl(tag, format); + } + } /** * Writes a byte to the stream. * * @param v The byte to write to the stream. **/ - void writeByte(byte v); + public void writeByte(byte v) + { + expand(1); + _buf.b.put(v); + } /** - * Writes a sequence of bytes to the stream. + * Writes an optional byte to the stream. * - * @param v The sequence of bytes to write. - * Passing <code>null</code> causes an empty sequence to be written to the stream. + * @param tag The optional tag. + * @param v The optional byte to write to the stream. **/ - void writeByteSeq(byte[] v); + public void writeByte(int tag, ByteOptional v) + { + if(v != null && v.isSet()) + { + writeByte(tag, v.get()); + } + } /** - * Writes a ByteBuffer to the stream. + * Writes an optional byte to the stream. * - * @param v The ByteBuffer to write. + * @param tag The optional tag. + * @param v The byte to write to the stream. + **/ + public void writeByte(int tag, byte v) + { + if(writeOptional(tag, OptionalFormat.F1)) + { + writeByte(v); + } + } + + /** + * Writes a byte to the stream at the given position. The current position of the stream is not modified. + * + * @param v The byte to write to the stream. + * @param dest The position at which to store the byte in the buffer. + **/ + public void rewriteByte(byte v, int dest) + { + _buf.b.put(dest, v); + } + + /** + * Writes a byte sequence to the stream. + * + * @param v The byte sequence to write to the stream. * Passing <code>null</code> causes an empty sequence to be written to the stream. **/ - void writeByteBuffer(java.nio.ByteBuffer v); + public void writeByteSeq(byte[] v) + { + if(v == null) + { + writeSize(0); + } + else + { + writeSize(v.length); + expand(v.length); + _buf.b.put(v); + } + } + + /** + * Writes an optional byte sequence to the stream. + * + * @param tag The optional tag. + * @param v The optional byte sequence to write to the stream. + **/ + public void writeByteSeq(int tag, Optional<byte[]> v) + { + if(v != null && v.isSet()) + { + writeByteSeq(tag, v.get()); + } + } + + /** + * Writes an optional byte sequence to the stream. + * + * @param tag The optional tag. + * @param v The byte sequence to write to the stream. + **/ + public void writeByteSeq(int tag, byte[] v) + { + if(writeOptional(tag, OptionalFormat.VSize)) + { + writeByteSeq(v); + } + } + + /** + * Writes the remaining contents of the byte buffer as a byte sequence to the stream. + * + * @param v The byte buffer to write to the stream. + **/ + public void writeByteBuffer(java.nio.ByteBuffer v) + { + if(v == null || v.remaining() == 0) + { + writeSize(0); + } + else + { + writeSize(v.remaining()); + expand(v.remaining()); + _buf.b.put(v); + } + } /** * Writes a serializable Java object to the stream. * * @param o The serializable object to write. **/ - void writeSerializable(java.io.Serializable o); + public void writeSerializable(java.io.Serializable o) + { + if(o == null) + { + writeSize(0); + return; + } + try + { + IceInternal.OutputStreamWrapper w = new IceInternal.OutputStreamWrapper(this); + java.io.ObjectOutputStream out = new java.io.ObjectOutputStream(w); + out.writeObject(o); + out.close(); + w.close(); + } + catch(java.lang.Exception ex) + { + throw new MarshalException("cannot serialize object: " + ex); + } + } + + /** + * Writes a boolean to the stream. + * + * @param v The boolean to write to the stream. + **/ + public void writeBool(boolean v) + { + expand(1); + _buf.b.put(v ? (byte)1 : (byte)0); + } + + /** + * Writes an optional boolean to the stream. + * + * @param tag The optional tag. + * @param v The optional boolean to write to the stream. + **/ + public void writeBool(int tag, BooleanOptional v) + { + if(v != null && v.isSet()) + { + writeBool(tag, v.get()); + } + } + + /** + * Writes an optional boolean to the stream. + * + * @param tag The optional tag. + * @param v The boolean to write to the stream. + **/ + public void writeBool(int tag, boolean v) + { + if(writeOptional(tag, OptionalFormat.F1)) + { + writeBool(v); + } + } + + /** + * Writes a boolean to the stream at the given position. The current position of the stream is not modified. + * + * @param v The boolean to write to the stream. + * @param dest The position at which to store the boolean in the buffer. + **/ + public void rewriteBool(boolean v, int dest) + { + _buf.b.put(dest, v ? (byte)1 : (byte)0); + } + + /** + * Writes a boolean sequence to the stream. + * + * @param v The boolean sequence to write to the stream. + * Passing <code>null</code> causes an empty sequence to be written to the stream. + **/ + public void writeBoolSeq(boolean[] v) + { + if(v == null) + { + writeSize(0); + } + else + { + writeSize(v.length); + expand(v.length); + for(boolean b : v) + { + _buf.b.put(b ? (byte)1 : (byte)0); + } + } + } + + /** + * Writes an optional boolean sequence to the stream. + * + * @param tag The optional tag. + * @param v The optional boolean sequence to write to the stream. + **/ + public void writeBoolSeq(int tag, Optional<boolean[]> v) + { + if(v != null && v.isSet()) + { + writeBoolSeq(tag, v.get()); + } + } + + /** + * Writes an optional boolean sequence to the stream. + * + * @param tag The optional tag. + * @param v The boolean sequence to write to the stream. + **/ + public void writeBoolSeq(int tag, boolean[] v) + { + if(writeOptional(tag, OptionalFormat.VSize)) + { + writeBoolSeq(v); + } + } /** * Writes a short to the stream. * * @param v The short to write to the stream. **/ - void writeShort(short v); + public void writeShort(short v) + { + expand(2); + _buf.b.putShort(v); + } /** - * Writes a sequence of shorts to the stream. + * Writes an optional short to the stream. * - * @param v The sequence of shorts to write. - * Passing <code>null</code> causes an empty sequence to be written to the stream. + * @param tag The optional tag. + * @param v The optional short to write to the stream. + **/ + public void writeShort(int tag, ShortOptional v) + { + if(v != null && v.isSet()) + { + writeShort(tag, v.get()); + } + } + + /** + * Writes an optional short to the stream. + * + * @param tag The optional tag. + * @param v The short to write to the stream. **/ - void writeShortSeq(short[] v); + public void writeShort(int tag, short v) + { + if(writeOptional(tag, OptionalFormat.F2)) + { + writeShort(v); + } + } /** - * Writes a ShortBuffer to the stream. + * Writes a short sequence to the stream. * - * @param v The ShortBuffer to write. + * @param v The short sequence to write to the stream. * Passing <code>null</code> causes an empty sequence to be written to the stream. **/ - void writeShortBuffer(java.nio.ShortBuffer v); + public void writeShortSeq(short[] v) + { + if(v == null) + { + writeSize(0); + } + else + { + writeSize(v.length); + expand(v.length * 2); + java.nio.ShortBuffer shortBuf = _buf.b.asShortBuffer(); + shortBuf.put(v); + _buf.b.position(_buf.b.position() + v.length * 2); + } + } /** - * Writes an integer to the stream. + * Writes an optional short sequence to the stream. * - * @param v The integer to write to the stream. + * @param tag The optional tag. + * @param v The optional short sequence to write to the stream. **/ - void writeInt(int v); + public void writeShortSeq(int tag, Optional<short[]> v) + { + if(v != null && v.isSet()) + { + writeShortSeq(tag, v.get()); + } + } /** - * Writes a sequence of integers to the stream. + * Writes an optional short sequence to the stream. * - * @param v The sequence of integers to write. - * Passing <code>null</code> causes an empty sequence to be written to the stream. + * @param tag The optional tag. + * @param v The short sequence to write to the stream. + **/ + public void writeShortSeq(int tag, short[] v) + { + if(writeOptional(tag, OptionalFormat.VSize)) + { + writeSize(v == null || v.length == 0 ? 1 : v.length * 2 + (v.length > 254 ? 5 : 1)); + writeShortSeq(v); + } + } + + /** + * Writes the remaining contents of the short buffer as a short sequence to the stream. + * + * @param v The short buffer to write to the stream. + **/ + public void writeShortBuffer(java.nio.ShortBuffer v) + { + if(v == null || v.remaining() == 0) + { + writeSize(0); + } + else + { + int sz = v.remaining(); + writeSize(sz); + expand(sz * 2); + + java.nio.ShortBuffer shortBuf = _buf.b.asShortBuffer(); + shortBuf.put(v); + _buf.b.position(_buf.b.position() + sz * 2); + } + } + + /** + * Writes an int to the stream. + * + * @param v The int to write to the stream. + **/ + public void writeInt(int v) + { + expand(4); + _buf.b.putInt(v); + } + + /** + * Writes an optional int to the stream. + * + * @param tag The optional tag. + * @param v The optional int to write to the stream. **/ - void writeIntSeq(int[] v); + public void writeInt(int tag, IntOptional v) + { + if(v != null && v.isSet()) + { + writeInt(tag, v.get()); + } + } /** - * Writes a IntBuffer to the stream. + * Writes an optional int to the stream. * - * @param v The IntBuffer to write. + * @param tag The optional tag. + * @param v The int to write to the stream. + **/ + public void writeInt(int tag, int v) + { + if(writeOptional(tag, OptionalFormat.F4)) + { + writeInt(v); + } + } + + /** + * Writes an int to the stream at the given position. The current position of the stream is not modified. + * + * @param v The int to write to the stream. + * @param dest The position at which to store the int in the buffer. + **/ + public void rewriteInt(int v, int dest) + { + _buf.b.putInt(dest, v); + } + + /** + * Writes an int sequence to the stream. + * + * @param v The int sequence to write to the stream. * Passing <code>null</code> causes an empty sequence to be written to the stream. **/ - void writeIntBuffer(java.nio.IntBuffer v); + public void writeIntSeq(int[] v) + { + if(v == null) + { + writeSize(0); + } + else + { + writeSize(v.length); + expand(v.length * 4); + java.nio.IntBuffer intBuf = _buf.b.asIntBuffer(); + intBuf.put(v); + _buf.b.position(_buf.b.position() + v.length * 4); + } + } + + /** + * Writes an optional int sequence to the stream. + * + * @param tag The optional tag. + * @param v The optional int sequence to write to the stream. + **/ + public void writeIntSeq(int tag, Optional<int[]> v) + { + if(v != null && v.isSet()) + { + writeIntSeq(tag, v.get()); + } + } + + /** + * Writes an optional int sequence to the stream. + * + * @param tag The optional tag. + * @param v The int sequence to write to the stream. + **/ + public void writeIntSeq(int tag, int[] v) + { + if(writeOptional(tag, OptionalFormat.VSize)) + { + writeSize(v == null || v.length == 0 ? 1 : v.length * 4 + (v.length > 254 ? 5 : 1)); + writeIntSeq(v); + } + } + + /** + * Writes the remaining contents of the int buffer as an int sequence to the stream. + * + * @param v The int buffer to write to the stream. + **/ + public void writeIntBuffer(java.nio.IntBuffer v) + { + if(v == null || v.remaining() == 0) + { + writeSize(0); + } + else + { + int sz = v.remaining(); + writeSize(sz); + expand(sz * 4); + + java.nio.IntBuffer intBuf = _buf.b.asIntBuffer(); + intBuf.put(v); + _buf.b.position(_buf.b.position() + sz * 4); + } + } /** * Writes a long to the stream. * * @param v The long to write to the stream. **/ - void writeLong(long v); + public void writeLong(long v) + { + expand(8); + _buf.b.putLong(v); + } /** - * Writes a sequence of longs to the stream. + * Writes an optional long to the stream. * - * @param v The sequence of longs to write. - * Passing <code>null</code> causes an empty sequence to be written to the stream. + * @param tag The optional tag. + * @param v The optional long to write to the stream. **/ - void writeLongSeq(long[] v); + public void writeLong(int tag, LongOptional v) + { + if(v != null && v.isSet()) + { + writeLong(tag, v.get()); + } + } /** - * Writes a LongBuffer to the stream. + * Writes an optional long to the stream. * - * @param v The LongBuffer to write. - * Passing <code>null</code> causes an empty sequence to be written to the stream. + * @param tag The optional tag. + * @param v The long to write to the stream. **/ - void writeLongBuffer(java.nio.LongBuffer v); + public void writeLong(int tag, long v) + { + if(writeOptional(tag, OptionalFormat.F8)) + { + writeLong(v); + } + } /** - * Writes a float to the stream. + * Writes a long sequence to the stream. * - * @param v The float to write to the stream. + * @param v The long sequence to write to the stream. + * Passing <code>null</code> causes an empty sequence to be written to the stream. **/ - void writeFloat(float v); + public void writeLongSeq(long[] v) + { + if(v == null) + { + writeSize(0); + } + else + { + writeSize(v.length); + expand(v.length * 8); + java.nio.LongBuffer longBuf = _buf.b.asLongBuffer(); + longBuf.put(v); + _buf.b.position(_buf.b.position() + v.length * 8); + } + } /** - * Writes a sequence of floats to the stream. + * Writes an optional long sequence to the stream. * - * @param v The sequence of floats to write. - * Passing <code>null</code> causes an empty sequence to be written to the stream. + * @param tag The optional tag. + * @param v The optional long sequence to write to the stream. **/ - void writeFloatSeq(float[] v); + public void writeLongSeq(int tag, Optional<long[]> v) + { + if(v != null && v.isSet()) + { + writeLongSeq(tag, v.get()); + } + } /** - * Writes a FloatBuffer to the stream. + * Writes an optional long sequence to the stream. * - * @param v The FloatBuffer to write. - * Passing <code>null</code> causes an empty sequence to be written to the stream. + * @param tag The optional tag. + * @param v The long sequence to write to the stream. **/ - void writeFloatBuffer(java.nio.FloatBuffer v); + public void writeLongSeq(int tag, long[] v) + { + if(writeOptional(tag, OptionalFormat.VSize)) + { + writeSize(v == null || v.length == 0 ? 1 : v.length * 8 + (v.length > 254 ? 5 : 1)); + writeLongSeq(v); + } + } /** - * Writes a double to the stream. + * Writes the remaining contents of the long buffer as a long sequence to the stream. * - * @param v The double to write to the stream. + * @param v The long buffer to write to the stream. **/ - void writeDouble(double v); + public void writeLongBuffer(java.nio.LongBuffer v) + { + if(v == null || v.remaining() == 0) + { + writeSize(0); + } + else + { + int sz = v.remaining(); + writeSize(sz); + expand(sz * 8); + + java.nio.LongBuffer longBuf = _buf.b.asLongBuffer(); + longBuf.put(v); + _buf.b.position(_buf.b.position() + sz * 8); + } + } /** - * Writes a sequence of doubles to the stream. + * Writes a float to the stream. * - * @param v The sequence of doubles to write. - * Passing <code>null</code> causes an empty sequence to be written to the stream. + * @param v The float to write to the stream. **/ - void writeDoubleSeq(double[] v); + public void writeFloat(float v) + { + expand(4); + _buf.b.putFloat(v); + } /** - * Writes a DoubleBuffer to the stream. + * Writes an optional float to the stream. * - * @param v The DoubleBuffer to write. - * Passing <code>null</code> causes an empty sequence to be written to the stream. + * @param tag The optional tag. + * @param v The optional float to write to the stream. **/ - void writeDoubleBuffer(java.nio.DoubleBuffer v); + public void writeFloat(int tag, FloatOptional v) + { + if(v != null && v.isSet()) + { + writeFloat(tag, v.get()); + } + } /** - * Writes a string to the stream. + * Writes an optional float to the stream. * - * @param v The string to write to the stream. Passing <code>null</code> causes - * an empty string to be written to the stream. + * @param tag The optional tag. + * @param v The float to write to the stream. **/ - void writeString(String v); + public void writeFloat(int tag, float v) + { + if(writeOptional(tag, OptionalFormat.F4)) + { + writeFloat(v); + } + } /** - * Writes a sequence of strings to the stream. + * Writes a float sequence to the stream. * - * @param v The sequence of strings to write. + * @param v The float sequence to write to the stream. * Passing <code>null</code> causes an empty sequence to be written to the stream. **/ - void writeStringSeq(String[] v); + public void writeFloatSeq(float[] v) + { + if(v == null) + { + writeSize(0); + } + else + { + writeSize(v.length); + expand(v.length * 4); + java.nio.FloatBuffer floatBuf = _buf.b.asFloatBuffer(); + floatBuf.put(v); + _buf.b.position(_buf.b.position() + v.length * 4); + } + } /** - * Writes a size to the stream. + * Writes an optional float sequence to the stream. * - * @param sz The size to write. + * @param tag The optional tag. + * @param v The optional float sequence to write to the stream. **/ - void writeSize(int sz); + public void writeFloatSeq(int tag, Optional<float[]> v) + { + if(v != null && v.isSet()) + { + writeFloatSeq(tag, v.get()); + } + } /** - * Writes a proxy to the stream. + * Writes an optional float sequence to the stream. * - * @param v The proxy to write. + * @param tag The optional tag. + * @param v The float sequence to write to the stream. **/ - void writeProxy(ObjectPrx v); + public void writeFloatSeq(int tag, float[] v) + { + if(writeOptional(tag, OptionalFormat.VSize)) + { + writeSize(v == null || v.length == 0 ? 1 : v.length * 4 + (v.length > 254 ? 5 : 1)); + writeFloatSeq(v); + } + } /** - * Writes a Slice class to the stream. + * Writes the remaining contents of the float buffer as a float sequence to the stream. * - * @param v The class to write. This method writes the index of a Slice class; the state of the class is - * written once {@link #writePendingObjects} is called. + * @param v The float buffer to write to the stream. **/ - void writeObject(Ice.Object v); + public void writeFloatBuffer(java.nio.FloatBuffer v) + { + if(v == null || v.remaining() == 0) + { + writeSize(0); + } + else + { + int sz = v.remaining(); + writeSize(sz); + expand(sz * 4); + + java.nio.FloatBuffer floatBuf = _buf.b.asFloatBuffer(); + floatBuf.put(v); + _buf.b.position(_buf.b.position() + sz * 4); + } + } /** - * Write an enumerated value. + * Writes a double to the stream. * - * @param v The enumerator. - * @param limit The maximum enumerator value in the definition. + * @param v The double to write to the stream. **/ - void writeEnum(int v, int maxValue); + public void writeDouble(double v) + { + expand(8); + _buf.b.putDouble(v); + } /** - * Writes a user exception to the stream. + * Writes an optional double to the stream. * - * @param id The user exception to write. + * @param tag The optional tag. + * @param v The optional double to write to the stream. **/ - void writeException(UserException ex); + public void writeDouble(int tag, DoubleOptional v) + { + if(v != null && v.isSet()) + { + writeDouble(tag, v.get()); + } + } /** - * Marks the start of an Ice object. + * Writes an optional double to the stream. * - * @param slicedData Preserved slices for this object, or null. + * @param tag The optional tag. + * @param v The double to write to the stream. **/ - void startObject(SlicedData slicedData); + public void writeDouble(int tag, double v) + { + if(writeOptional(tag, OptionalFormat.F8)) + { + writeDouble(v); + } + } /** - * Marks the end of an Ice object. + * Writes a double sequence to the stream. + * + * @param v The double sequence to write to the stream. + * Passing <code>null</code> causes an empty sequence to be written to the stream. **/ - void endObject(); + public void writeDoubleSeq(double[] v) + { + if(v == null) + { + writeSize(0); + } + else + { + writeSize(v.length); + expand(v.length * 8); + java.nio.DoubleBuffer doubleBuf = _buf.b.asDoubleBuffer(); + doubleBuf.put(v); + _buf.b.position(_buf.b.position() + v.length * 8); + } + } /** - * Marks the start of a user exception. + * Writes an optional double sequence to the stream. * - * @param slicedData Preserved slices for this exception, or null. + * @param tag The optional tag. + * @param v The optional double sequence to write to the stream. **/ - void startException(SlicedData slicedData); + public void writeDoubleSeq(int tag, Optional<double[]> v) + { + if(v != null && v.isSet()) + { + writeDoubleSeq(tag, v.get()); + } + } /** - * Marks the end of a user exception. + * Writes an optional double sequence to the stream. + * + * @param tag The optional tag. + * @param v The double sequence to write to the stream. **/ - void endException(); + public void writeDoubleSeq(int tag, double[] v) + { + if(writeOptional(tag, OptionalFormat.VSize)) + { + writeSize(v == null || v.length == 0 ? 1 : v.length * 8 + (v.length > 254 ? 5 : 1)); + writeDoubleSeq(v); + } + } /** - * Marks the start of a new slice for an Ice object or user exception. + * Writes the remaining contents of the double buffer as a double sequence to the stream. * - * @param typeId The Slice type ID corresponding to this slice. + * @param v The double buffer to write to the stream. + **/ + public void writeDoubleBuffer(java.nio.DoubleBuffer v) + { + if(v == null || v.remaining() == 0) + { + writeSize(0); + } + else + { + int sz = v.remaining(); + writeSize(sz); + expand(sz * 8); - * @param compactId The Slice compact type ID corresponding to - * this slice or -1 if no compact ID is defined for the - * type ID. + java.nio.DoubleBuffer doubleBuf = _buf.b.asDoubleBuffer(); + doubleBuf.put(v); + _buf.b.position(_buf.b.position() + sz * 8); + } + } - * @param last True if this is the last slice, false otherwise. + final static java.nio.charset.Charset _utf8 = java.nio.charset.Charset.forName("UTF8"); + private java.nio.charset.CharsetEncoder _charEncoder = null; + + /** + * Writes a string to the stream. + * + * @param v The string to write to the stream. Passing <code>null</code> causes + * an empty string to be written to the stream. **/ - void startSlice(String typeId, int compactId, boolean last); + public void writeString(String v) + { + if(v == null) + { + writeSize(0); + } + else + { + final int len = v.length(); + if(len > 0) + { + if(_stringBytes == null || len > _stringBytes.length) + { + _stringBytes = new byte[len]; + } + if(_stringChars == null || len > _stringChars.length) + { + _stringChars = new char[len]; + } + // + // If the string contains only 7-bit characters, it's more efficient + // to perform the conversion to UTF-8 manually. + // + v.getChars(0, len, _stringChars, 0); + for(int i = 0; i < len; ++i) + { + if(_stringChars[i] > (char)127) + { + // + // Found a multibyte character. + // + if(_charEncoder == null) + { + _charEncoder = _utf8.newEncoder(); + } + java.nio.ByteBuffer b = null; + try + { + b = _charEncoder.encode(java.nio.CharBuffer.wrap(_stringChars, 0, len)); + } + catch(java.nio.charset.CharacterCodingException ex) + { + throw new MarshalException(ex); + } + writeSize(b.limit()); + expand(b.limit()); + _buf.b.put(b); + return; + } + _stringBytes[i] = (byte)_stringChars[i]; + } + writeSize(len); + expand(len); + _buf.b.put(_stringBytes, 0, len); + } + else + { + writeSize(0); + } + } + } /** - * Marks the end of a slice for an Ice object or user exception. + * Writes an optional string to the stream. + * + * @param tag The optional tag. + * @param v The optional string to write to the stream. **/ - void endSlice(); + public void writeString(int tag, Optional<String> v) + { + if(v != null && v.isSet()) + { + writeString(tag, v.get()); + } + } /** - * Writes the start of an encapsulation to the stream. + * Writes an optional string to the stream. * - * @param encoding The encoding version of the encapsulation. + * @param tag The optional tag. + * @param v The string to write to the stream. + **/ + public void writeString(int tag, String v) + { + if(writeOptional(tag, OptionalFormat.VSize)) + { + writeString(v); + } + } + + /** + * Writes a string sequence to the stream. * - * @param format Specify the compact or sliced format. + * @param v The string sequence to write to the stream. + * Passing <code>null</code> causes an empty sequence to be written to the stream. + **/ + public void writeStringSeq(String[] v) + { + if(v == null) + { + writeSize(0); + } + else + { + writeSize(v.length); + for(String e : v) + { + writeString(e); + } + } + } + + /** + * Writes an optional string sequence to the stream. * + * @param tag The optional tag. + * @param v The optional string sequence to write to the stream. **/ - void startEncapsulation(Ice.EncodingVersion encoding, Ice.FormatType format); + public void writeStringSeq(int tag, Optional<String[]> v) + { + if(v != null && v.isSet()) + { + writeStringSeq(tag, v.get()); + } + } /** - * Writes the start of an encapsulation to the stream. + * Writes an optional string sequence to the stream. + * + * @param tag The optional tag. + * @param v The string sequence to write to the stream. **/ - void startEncapsulation(); + public void writeStringSeq(int tag, String[] v) + { + if(writeOptional(tag, OptionalFormat.FSize)) + { + int pos = startSize(); + writeStringSeq(v); + endSize(pos); + } + } /** - * Ends the previous encapsulation. + * Writes a proxy to the stream. + * + * @param v The proxy to write. **/ - void endEncapsulation(); + public void writeProxy(ObjectPrx v) + { + if(v != null) + { + v.__write(this); + } + else + { + Identity ident = new Identity(); + ident.ice_write(this); + } + } /** - * Determines the current encoding version. + * Writes an optional proxy to the stream. * - * @return The encoding version. + * @param tag The optional tag. + * @param v The optional proxy to write to the stream. **/ - EncodingVersion getEncoding(); + public void writeProxy(int tag, Optional<ObjectPrx> v) + { + if(v != null && v.isSet()) + { + writeProxy(tag, v.get()); + } + } /** - * Writes the state of Slice classes whose index was previously - * written with {@link #writeObject} to the stream. + * Writes an optional proxy to the stream. + * + * @param tag The optional tag. + * @param v The proxy to write to the stream. **/ - void writePendingObjects(); + public void writeProxy(int tag, ObjectPrx v) + { + if(writeOptional(tag, OptionalFormat.FSize)) + { + int pos = startSize(); + writeProxy(v); + endSize(pos); + } + } /** - * Write the header information for an optional value. + * Write an enumerated value. * - * @param tag The numeric tag associated with the value. - * @param type The optional format of the value. + * @param v The enumerator. + * @param maxValue The maximum enumerator value in the definition. **/ - boolean writeOptional(int tag, Ice.OptionalFormat format); + public void writeEnum(int v, int maxValue) + { + if(isEncoding_1_0()) + { + if(maxValue < 127) + { + writeByte((byte)v); + } + else if(maxValue < 32767) + { + writeShort((short)v); + } + else + { + writeInt(v); + } + } + else + { + writeSize(v); + } + } /** - * Determines the current position in the stream. + * Writes a Slice value to the stream. * - * @return The current position. + * @param v The value to write. This method writes the index of an instance; the state of the value is + * written once {@link #writePendingObjects} is called. **/ - int pos(); + public void writeObject(Ice.Object v) + { + initEncaps(); + _encapsStack.encoder.writeObject(v); + } /** - * Inserts a fixed 32-bit size value into the stream at the given position. + * Writes an optional value to the stream. * - * @param sz The 32-bit size value. - * @param pos The position at which to write the value. + * @param tag The optional tag. + * @param v The optional value to write to the stream. **/ - void rewrite(int sz, int pos); + public <T extends Ice.Object> void writeObject(int tag, Optional<T> v) + { + if(v != null && v.isSet()) + { + writeObject(tag, v.get()); + } + } /** - * Returns the current position and allocates four bytes for a fixed-length (32-bit) - * size value. + * Writes an optional value to the stream. + * + * @param tag The optional tag. + * @param v The value to write to the stream. + **/ + public void writeObject(int tag, Ice.Object v) + { + if(writeOptional(tag, OptionalFormat.Class)) + { + writeObject(v); + } + } + + /** + * Writes a user exception to the stream. + * + * @param v The user exception to write. + **/ + public void writeException(UserException v) + { + initEncaps(); + _encapsStack.encoder.writeException(v); + } + + private boolean writeOptionalImpl(int tag, OptionalFormat format) + { + if(isEncoding_1_0()) + { + return false; // Optional members aren't supported with the 1.0 encoding. + } + + int v = format.value(); + if(tag < 30) + { + v |= tag << 3; + writeByte((byte)v); + } + else + { + v |= 0x0F0; // tag = 30 + writeByte((byte)v); + writeSize(tag); + } + return true; + } + + /** + * Determines the current position in the stream. * * @return The current position. **/ - int startSize(); + public int pos() + { + return _buf.b.position(); + } /** - * Computes the amount of data written since the previous call to startSize and - * writes that value at the saved position. + * Sets the current position in the stream. * - * @param The saved position. + * @param pos The new position. **/ - void endSize(int pos); + public void pos(int n) + { + _buf.b.position(n); + } /** - * Indicates that marshaling of a request or reply is finished. + * Determines the current size of the stream. * - * @return The byte sequence containing the encoded request or reply. + * @return The current size. **/ - byte[] finished(); + public int size() + { + return _buf.size(); + } /** - * Resets this output stream. This method allows the stream to be reused, to avoid creating - * unnecessary garbage. + * Determines whether the stream is empty. * - * @param clearBuffer If <code>true</code>, the stream's internal buffer becomes eligible for - * garbage collection; if <code>false</code>, the stream's internal buffer is retained, to avoid - * creating unnecessary garbage. If retained, the internal buffer may be resized to a smaller - * capacity. Either way, <code>reset</code> resets the stream's writing position to zero. + * @return True if no data has been written yet, false otherwise. **/ - void reset(boolean clearBuffer); + public boolean isEmpty() + { + return _buf.empty(); + } /** - * Destroys the stream and its associated resources. The application must call <code>destroy</code> prior - * to releasing the last reference to a stream; failure to do so may result in resource leaks. + * Expand the stream to accept more data. + * + * @param n The number of bytes to accommodate in the stream. **/ - void destroy(); + public void expand(int n) + { + _buf.expand(n); + } + + private IceInternal.Instance _instance; + private IceInternal.Buffer _buf; + private Object _closure; + private FormatType _format; + private byte[] _stringBytes; // Reusable array for string operations. + private char[] _stringChars; // Reusable array for string operations. + + private enum SliceType { NoSlice, ObjectSlice, ExceptionSlice } + + abstract private static class EncapsEncoder + { + protected EncapsEncoder(OutputStream stream, Encaps encaps) + { + _stream = stream; + _encaps = encaps; + _typeIdIndex = 0; + _marshaledMap = new java.util.IdentityHashMap<Ice.Object, Integer>(); + } + + abstract void writeObject(Ice.Object v); + abstract void writeException(UserException v); + + abstract void startInstance(SliceType type, SlicedData data); + abstract void endInstance(); + abstract void startSlice(String typeId, int compactId, boolean last); + abstract void endSlice(); + + boolean writeOptional(int tag, OptionalFormat format) + { + return false; + } + + void writePendingObjects() + { + } + + protected int registerTypeId(String typeId) + { + if(_typeIdMap == null) // Lazy initialization + { + _typeIdMap = new java.util.TreeMap<String, Integer>(); + } + + Integer p = _typeIdMap.get(typeId); + if(p != null) + { + return p; + } + else + { + _typeIdMap.put(typeId, ++_typeIdIndex); + return -1; + } + } + + final protected OutputStream _stream; + final protected Encaps _encaps; + + // Encapsulation attributes for object marshalling. + final protected java.util.IdentityHashMap<Ice.Object, Integer> _marshaledMap; + private java.util.TreeMap<String, Integer> _typeIdMap; + private int _typeIdIndex; + } + + private static final class EncapsEncoder10 extends EncapsEncoder + { + EncapsEncoder10(OutputStream stream, Encaps encaps) + { + super(stream, encaps); + _sliceType = SliceType.NoSlice; + _objectIdIndex = 0; + _toBeMarshaledMap = new java.util.IdentityHashMap<Ice.Object, Integer>(); + } + + @Override + void writeObject(Ice.Object v) + { + // + // Object references are encoded as a negative integer in 1.0. + // + if(v != null) + { + _stream.writeInt(-registerObject(v)); + } + else + { + _stream.writeInt(0); + } + } + + @Override + void writeException(UserException v) + { + // + // User exception with the 1.0 encoding start with a boolean + // flag that indicates whether or not the exception uses + // classes. + // + // This allows reading the pending objects even if some part of + // the exception was sliced. + // + boolean usesClasses = v.__usesClasses(); + _stream.writeBool(usesClasses); + v.__write(_stream); + if(usesClasses) + { + writePendingObjects(); + } + } + + @Override + void startInstance(SliceType sliceType, SlicedData sliceData) + { + _sliceType = sliceType; + } + + @Override + void endInstance() + { + if(_sliceType == SliceType.ObjectSlice) + { + // + // Write the Object slice. + // + startSlice(ObjectImpl.ice_staticId(), -1, true); + _stream.writeSize(0); // For compatibility with the old AFM. + endSlice(); + } + _sliceType = SliceType.NoSlice; + } + + @Override + void startSlice(String typeId, int compactId, boolean last) + { + // + // For object slices, encode a boolean to indicate how the type ID + // is encoded and the type ID either as a string or index. For + // exception slices, always encode the type ID as a string. + // + if(_sliceType == SliceType.ObjectSlice) + { + int index = registerTypeId(typeId); + if(index < 0) + { + _stream.writeBool(false); + _stream.writeString(typeId); + } + else + { + _stream.writeBool(true); + _stream.writeSize(index); + } + } + else + { + _stream.writeString(typeId); + } + + _stream.writeInt(0); // Placeholder for the slice length. + + _writeSlice = _stream.pos(); + } + + @Override + void endSlice() + { + // + // Write the slice length. + // + final int sz = _stream.pos() - _writeSlice + 4; + _stream.rewriteInt(sz, _writeSlice - 4); + } + + @Override + void writePendingObjects() + { + while(_toBeMarshaledMap.size() > 0) + { + // + // Consider the to be marshalled objects as marshalled now, + // this is necessary to avoid adding again the "to be + // marshalled objects" into _toBeMarshaledMap while writing + // objects. + // + _marshaledMap.putAll(_toBeMarshaledMap); + + java.util.IdentityHashMap<Ice.Object, Integer> savedMap = _toBeMarshaledMap; + _toBeMarshaledMap = new java.util.IdentityHashMap<Ice.Object, Integer>(); + _stream.writeSize(savedMap.size()); + for(java.util.Map.Entry<Ice.Object, Integer> p : savedMap.entrySet()) + { + // + // Ask the instance to marshal itself. Any new class + // instances that are triggered by the classes marshaled + // are added to toBeMarshaledMap. + // + _stream.writeInt(p.getValue().intValue()); + + try + { + p.getKey().ice_preMarshal(); + } + catch(java.lang.Exception ex) + { + String s = "exception raised by ice_preMarshal:\n" + IceInternal.Ex.toString(ex); + _stream.instance().initializationData().logger.warning(s); + } + + p.getKey().__write(_stream); + } + } + _stream.writeSize(0); // Zero marker indicates end of sequence of sequences of instances. + } + + private int registerObject(Ice.Object v) + { + assert(v != null); + + // + // Look for this instance in the to-be-marshaled map. + // + Integer p = _toBeMarshaledMap.get(v); + if(p != null) + { + return p.intValue(); + } + + // + // Didn't find it, try the marshaled map next. + // + p = _marshaledMap.get(v); + if(p != null) + { + return p.intValue(); + } + + // + // We haven't seen this instance previously, create a new + // index, and insert it into the to-be-marshaled map. + // + _toBeMarshaledMap.put(v, ++_objectIdIndex); + return _objectIdIndex; + } + + // Instance attributes + private SliceType _sliceType; + + // Slice attributes + private int _writeSlice; // Position of the slice data members + + // Encapsulation attributes for object marshalling. + private int _objectIdIndex; + private java.util.IdentityHashMap<Ice.Object, Integer> _toBeMarshaledMap; + } + + private static final class EncapsEncoder11 extends EncapsEncoder + { + EncapsEncoder11(OutputStream stream, Encaps encaps) + { + super(stream, encaps); + _current = null; + _objectIdIndex = 1; + } + + @Override + void writeObject(Ice.Object v) + { + if(v == null) + { + _stream.writeSize(0); + } + else if(_current != null && _encaps.format == FormatType.SlicedFormat) + { + if(_current.indirectionTable == null) // Lazy initialization + { + _current.indirectionTable = new java.util.ArrayList<Ice.Object>(); + _current.indirectionMap = new java.util.IdentityHashMap<Ice.Object, Integer>(); + } + + // + // If writing an object within a slice and using the sliced + // format, write an index from the object indirection + // table. The indirect object table is encoded at the end of + // each slice and is always read (even if the Slice is + // unknown). + // + Integer index = _current.indirectionMap.get(v); + if(index == null) + { + _current.indirectionTable.add(v); + final int idx = _current.indirectionTable.size(); // Position + 1 (0 is reserved for nil) + _current.indirectionMap.put(v, idx); + _stream.writeSize(idx); + } + else + { + _stream.writeSize(index.intValue()); + } + } + else + { + writeInstance(v); // Write the instance or a reference if already marshaled. + } + } + + @Override + void writeException(UserException v) + { + v.__write(_stream); + } + + @Override + void startInstance(SliceType sliceType, SlicedData data) + { + if(_current == null) + { + _current = new InstanceData(null); + } + else + { + _current = _current.next == null ? new InstanceData(_current) : _current.next; + } + _current.sliceType = sliceType; + _current.firstSlice = true; + + if(data != null) + { + writeSlicedData(data); + } + } + + @Override + void endInstance() + { + _current = _current.previous; + } + + @Override + void startSlice(String typeId, int compactId, boolean last) + { + assert((_current.indirectionTable == null || _current.indirectionTable.isEmpty()) && + (_current.indirectionMap == null || _current.indirectionMap.isEmpty())); + + _current.sliceFlagsPos = _stream.pos(); + + _current.sliceFlags = (byte)0; + if(_encaps.format == FormatType.SlicedFormat) + { + // Encode the slice size if using the sliced format. + _current.sliceFlags |= IceInternal.Protocol.FLAG_HAS_SLICE_SIZE; + } + if(last) + { + _current.sliceFlags |= IceInternal.Protocol.FLAG_IS_LAST_SLICE; // This is the last slice. + } + + _stream.writeByte((byte)0); // Placeholder for the slice flags + + // + // For object slices, encode the flag and the type ID either as a + // string or index. For exception slices, always encode the type + // ID a string. + // + if(_current.sliceType == SliceType.ObjectSlice) + { + // + // Encode the type ID (only in the first slice for the compact + // encoding). + // + if(_encaps.format == FormatType.SlicedFormat || _current.firstSlice) + { + if(compactId >= 0) + { + _current.sliceFlags |= IceInternal.Protocol.FLAG_HAS_TYPE_ID_COMPACT; + _stream.writeSize(compactId); + } + else + { + int index = registerTypeId(typeId); + if(index < 0) + { + _current.sliceFlags |= IceInternal.Protocol.FLAG_HAS_TYPE_ID_STRING; + _stream.writeString(typeId); + } + else + { + _current.sliceFlags |= IceInternal.Protocol.FLAG_HAS_TYPE_ID_INDEX; + _stream.writeSize(index); + } + } + } + } + else + { + _stream.writeString(typeId); + } + + if((_current.sliceFlags & IceInternal.Protocol.FLAG_HAS_SLICE_SIZE) != 0) + { + _stream.writeInt(0); // Placeholder for the slice length. + } + + _current.writeSlice = _stream.pos(); + _current.firstSlice = false; + } + + @Override + void endSlice() + { + // + // Write the optional member end marker if some optional members + // were encoded. Note that the optional members are encoded before + // the indirection table and are included in the slice size. + // + if((_current.sliceFlags & IceInternal.Protocol.FLAG_HAS_OPTIONAL_MEMBERS) != 0) + { + _stream.writeByte((byte)IceInternal.Protocol.OPTIONAL_END_MARKER); + } + + // + // Write the slice length if necessary. + // + if((_current.sliceFlags & IceInternal.Protocol.FLAG_HAS_SLICE_SIZE) != 0) + { + final int sz = _stream.pos() - _current.writeSlice + 4; + _stream.rewriteInt(sz, _current.writeSlice - 4); + } + + // + // Only write the indirection table if it contains entries. + // + if(_current.indirectionTable != null && !_current.indirectionTable.isEmpty()) + { + assert(_encaps.format == FormatType.SlicedFormat); + _current.sliceFlags |= IceInternal.Protocol.FLAG_HAS_INDIRECTION_TABLE; + + // + // Write the indirection object table. + // + _stream.writeSize(_current.indirectionTable.size()); + for(Ice.Object v : _current.indirectionTable) + { + writeInstance(v); + } + _current.indirectionTable.clear(); + _current.indirectionMap.clear(); + } + + // + // Finally, update the slice flags. + // + _stream.rewriteByte(_current.sliceFlags, _current.sliceFlagsPos); + } + + @Override + boolean writeOptional(int tag, OptionalFormat format) + { + if(_current == null) + { + return _stream.writeOptionalImpl(tag, format); + } + else + { + if(_stream.writeOptionalImpl(tag, format)) + { + _current.sliceFlags |= IceInternal.Protocol.FLAG_HAS_OPTIONAL_MEMBERS; + return true; + } + else + { + return false; + } + } + } + + private void writeSlicedData(SlicedData slicedData) + { + assert(slicedData != null); + + // + // We only remarshal preserved slices if we are using the sliced + // format. Otherwise, we ignore the preserved slices, which + // essentially "slices" the object into the most-derived type + // known by the sender. + // + if(_encaps.format != FormatType.SlicedFormat) + { + return; + } + + for(SliceInfo info : slicedData.slices) + { + startSlice(info.typeId, info.compactId, info.isLastSlice); + + // + // Write the bytes associated with this slice. + // + _stream.writeBlob(info.bytes); + + if(info.hasOptionalMembers) + { + _current.sliceFlags |= IceInternal.Protocol.FLAG_HAS_OPTIONAL_MEMBERS; + } + + // + // Make sure to also re-write the object indirection table. + // + if(info.objects != null && info.objects.length > 0) + { + if(_current.indirectionTable == null) // Lazy initialization + { + _current.indirectionTable = new java.util.ArrayList<Ice.Object>(); + _current.indirectionMap = new java.util.IdentityHashMap<Ice.Object, Integer>(); + } + for(Ice.Object o : info.objects) + { + _current.indirectionTable.add(o); + } + } + + endSlice(); + } + } + + private void writeInstance(Ice.Object v) + { + assert(v != null); + + // + // If the instance was already marshaled, just write it's ID. + // + Integer p = _marshaledMap.get(v); + if(p != null) + { + _stream.writeSize(p); + return; + } + + // + // We haven't seen this instance previously, create a new ID, + // insert it into the marshaled map, and write the instance. + // + _marshaledMap.put(v, ++_objectIdIndex); + + try + { + v.ice_preMarshal(); + } + catch(java.lang.Exception ex) + { + String s = "exception raised by ice_preMarshal:\n" + IceInternal.Ex.toString(ex); + _stream.instance().initializationData().logger.warning(s); + } + + _stream.writeSize(1); // Object instance marker. + v.__write(_stream); + } + + private static final class InstanceData + { + InstanceData(InstanceData previous) + { + if(previous != null) + { + previous.next = this; + } + this.previous = previous; + this.next = null; + } + + // Instance attributes + SliceType sliceType; + boolean firstSlice; + + // Slice attributes + byte sliceFlags; + int writeSlice; // Position of the slice data members + int sliceFlagsPos; // Position of the slice flags + java.util.List<Ice.Object> indirectionTable; + java.util.IdentityHashMap<Ice.Object, Integer> indirectionMap; + + final InstanceData previous; + InstanceData next; + } + + private InstanceData _current; + + private int _objectIdIndex; // The ID of the next object to marhsal + } + + private static final class Encaps + { + void reset() + { + encoder = null; + } + + void setEncoding(EncodingVersion encoding) + { + this.encoding = encoding; + encoding_1_0 = encoding.equals(Util.Encoding_1_0); + } + + int start; + FormatType format = FormatType.DefaultFormat; + EncodingVersion encoding; + boolean encoding_1_0; + + EncapsEncoder encoder; + + Encaps next; + } + + // + // The encoding version to use when there's no encapsulation to + // read from or write to. This is for example used to read message + // headers or when the user is using the streaming API with no + // encapsulation. + // + private EncodingVersion _encoding; + + private boolean isEncoding_1_0() + { + return _encapsStack != null ? _encapsStack.encoding_1_0 : _encoding.equals(Util.Encoding_1_0); + } + + private Encaps _encapsStack; + private Encaps _encapsCache; + + private void initEncaps() + { + if(_encapsStack == null) // Lazy initialization + { + _encapsStack = _encapsCache; + if(_encapsStack != null) + { + _encapsCache = _encapsCache.next; + } + else + { + _encapsStack = new Encaps(); + } + _encapsStack.setEncoding(_encoding); + } + + if(_encapsStack.format == FormatType.DefaultFormat) + { + _encapsStack.format = _format; + } + + if(_encapsStack.encoder == null) // Lazy initialization. + { + if(_encapsStack.encoding_1_0) + { + _encapsStack.encoder = new EncapsEncoder10(this, _encapsStack); + } + else + { + _encapsStack.encoder = new EncapsEncoder11(this, _encapsStack); + } + } + } } diff --git a/java/src/Ice/src/main/java/Ice/OutputStreamI.java b/java/src/Ice/src/main/java/Ice/OutputStreamI.java deleted file mode 100644 index 88cbb755c63..00000000000 --- a/java/src/Ice/src/main/java/Ice/OutputStreamI.java +++ /dev/null @@ -1,401 +0,0 @@ -// ********************************************************************** -// -// Copyright (c) 2003-2015 ZeroC, Inc. All rights reserved. -// -// This copy of Ice is licensed to you under the terms described in the -// ICE_LICENSE file included in this distribution. -// -// ********************************************************************** - -package Ice; - -public class OutputStreamI implements OutputStream -{ - public - OutputStreamI(Communicator communicator) - { - _communicator = communicator; - IceInternal.Instance instance = IceInternal.Util.getInstance(communicator); - _os = new IceInternal.BasicStream(instance, instance.defaultsAndOverrides().defaultEncoding, false); - _os.closure(this); - } - - public - OutputStreamI(Communicator communicator, EncodingVersion v) - { - _communicator = communicator; - IceInternal.Instance instance = IceInternal.Util.getInstance(communicator); - _os = new IceInternal.BasicStream(instance, v, false); - _os.closure(this); - } - - public - OutputStreamI(Communicator communicator, IceInternal.BasicStream os) - { - _communicator = communicator; - _os = os; - _os.closure(this); - } - - @Override - public Communicator - communicator() - { - return _communicator; - } - - @Override - public void - writeBool(boolean v) - { - _os.writeBool(v); - } - - @Override - public void - writeBoolSeq(boolean[] v) - { - _os.writeBoolSeq(v); - } - - @Override - public void - writeByte(byte v) - { - _os.writeByte(v); - } - - @Override - public void - writeByteSeq(byte[] v) - { - _os.writeByteSeq(v); - } - - @Override - public void - writeByteBuffer(java.nio.ByteBuffer v) - { - _os.writeByteBuffer(v); - } - - @Override - public void - writeSerializable(java.io.Serializable v) - { - _os.writeSerializable(v); - } - - @Override - public void - writeShort(short v) - { - _os.writeShort(v); - } - - @Override - public void - writeShortSeq(short[] v) - { - _os.writeShortSeq(v); - } - - @Override - public void - writeShortBuffer(java.nio.ShortBuffer v) - { - _os.writeShortBuffer(v); - } - - @Override - public void - writeInt(int v) - { - _os.writeInt(v); - } - - @Override - public void - writeIntSeq(int[] v) - { - _os.writeIntSeq(v); - } - - @Override - public void - writeIntBuffer(java.nio.IntBuffer v) - { - _os.writeIntBuffer(v); - } - - @Override - public void - writeLong(long v) - { - _os.writeLong(v); - } - - @Override - public void - writeLongSeq(long[] v) - { - _os.writeLongSeq(v); - } - - @Override - public void - writeLongBuffer(java.nio.LongBuffer v) - { - _os.writeLongBuffer(v); - } - - @Override - public void - writeFloat(float v) - { - _os.writeFloat(v); - } - - @Override - public void - writeFloatSeq(float[] v) - { - _os.writeFloatSeq(v); - } - - @Override - public void - writeFloatBuffer(java.nio.FloatBuffer v) - { - _os.writeFloatBuffer(v); - } - - @Override - public void - writeDouble(double v) - { - _os.writeDouble(v); - } - - @Override - public void - writeDoubleSeq(double[] v) - { - _os.writeDoubleSeq(v); - } - - @Override - public void - writeDoubleBuffer(java.nio.DoubleBuffer v) - { - _os.writeDoubleBuffer(v); - } - - @Override - public void - writeString(String v) - { - _os.writeString(v); - } - - @Override - public void - writeStringSeq(String[] v) - { - _os.writeStringSeq(v); - } - - @Override - public void - writeSize(int sz) - { - if(sz < 0) - { - throw new MarshalException(); - } - - _os.writeSize(sz); - } - - @Override - public void - writeProxy(ObjectPrx v) - { - _os.writeProxy(v); - } - - @Override - public void - writeObject(Ice.Object v) - { - _os.writeObject(v); - } - - @Override - public void - writeEnum(int v, int maxValue) - { - _os.writeEnum(v, maxValue); - } - - @Override - public void - writeException(UserException v) - { - _os.writeUserException(v); - } - - @Override - public void - startObject(SlicedData slicedData) - { - _os.startWriteObject(slicedData); - } - - @Override - public void - endObject() - { - _os.endWriteObject(); - } - - @Override - public void - startException(SlicedData slicedData) - { - _os.startWriteException(slicedData); - } - - @Override - public void - endException() - { - _os.endWriteException(); - } - - @Override - public void - startSlice(String typeId, int compactId, boolean last) - { - _os.startWriteSlice(typeId, compactId, last); - } - - @Override - public void - endSlice() - { - _os.endWriteSlice(); - } - - @Override - public void - startEncapsulation(Ice.EncodingVersion encoding, Ice.FormatType format) - { - _os.startWriteEncaps(encoding, format); - } - - @Override - public void - startEncapsulation() - { - _os.startWriteEncaps(); - } - - @Override - public void - endEncapsulation() - { - _os.endWriteEncapsChecked(); - } - - @Override - public EncodingVersion - getEncoding() - { - return _os.getWriteEncoding(); - } - - @Override - public void - writePendingObjects() - { - _os.writePendingObjects(); - } - - @Override - public boolean - writeOptional(int tag, Ice.OptionalFormat format) - { - return _os.writeOpt(tag, format); - } - - @Override - public int - pos() - { - return _os.pos(); - } - - @Override - public void - rewrite(int sz, int pos) - { - _os.rewriteInt(sz, pos); - } - - @Override - public int - startSize() - { - return _os.startSize(); - } - - @Override - public void - endSize(int pos) - { - _os.endSize(pos); - } - - @Override - public byte[] - finished() - { - IceInternal.Buffer buf = _os.prepareWrite(); - byte[] result = new byte[buf.b.limit()]; - buf.b.get(result); - - return result; - } - - @Override - public void - reset(boolean clearBuffer) - { - _os.clear(); - - IceInternal.Buffer buf = _os.getBuffer(); - if(clearBuffer) - { - buf.clear(); - } - else - { - buf.reset(); - } - buf.b.position(0); - } - - @Override - public void - destroy() - { - if(_os != null) - { - _os = null; - } - } - - private Communicator _communicator; - private IceInternal.BasicStream _os; -} diff --git a/java/src/Ice/src/main/java/Ice/ReadObjectCallback.java b/java/src/Ice/src/main/java/Ice/ReadObjectCallback.java index 4caea3b396d..d0ac2013a35 100644 --- a/java/src/Ice/src/main/java/Ice/ReadObjectCallback.java +++ b/java/src/Ice/src/main/java/Ice/ReadObjectCallback.java @@ -10,8 +10,8 @@ package Ice; /** - * Callback class to inform an application when a Slice class has been unmarshaled - * from an input stream. + * Callback class to inform an application when an instance of a Slice class has been + * unmarshaled from an input stream. * * @see InputStream#readObject **/ @@ -21,7 +21,7 @@ public interface ReadObjectCallback * The Ice run time calls this method when it has fully unmarshaled the state * of a Slice class. * - * @param obj The unmarshaled Slice class. + * @param obj The unmarshaled Slice class instance. **/ - void invoke(Ice.Object obj); + void objectReady(Ice.Object obj); } diff --git a/java/src/Ice/src/main/java/Ice/UnknownSlicedObject.java b/java/src/Ice/src/main/java/Ice/UnknownSlicedObject.java index 4e7b3fadeac..e3f0b17a50e 100644 --- a/java/src/Ice/src/main/java/Ice/UnknownSlicedObject.java +++ b/java/src/Ice/src/main/java/Ice/UnknownSlicedObject.java @@ -38,18 +38,18 @@ public final class UnknownSlicedObject extends ObjectImpl @Override public void - __write(IceInternal.BasicStream __os) + __write(OutputStream __os) { - __os.startWriteObject(_slicedData); - __os.endWriteObject(); + __os.startObject(_slicedData); + __os.endObject(); } @Override public void - __read(IceInternal.BasicStream __is) + __read(InputStream __is) { - __is.startReadObject(); - _slicedData = __is.endReadObject(true); + __is.startObject(); + _slicedData = __is.endObject(true); } private final String _unknownTypeId; diff --git a/java/src/Ice/src/main/java/Ice/UserException.java b/java/src/Ice/src/main/java/Ice/UserException.java index 8faaf9b7aaf..b40f8a4c2d4 100644 --- a/java/src/Ice/src/main/java/Ice/UserException.java +++ b/java/src/Ice/src/main/java/Ice/UserException.java @@ -87,31 +87,15 @@ public abstract class UserException extends java.lang.Exception implements Clone } public void - __write(IceInternal.BasicStream os) + __write(OutputStream os) { - os.startWriteException(null); - __writeImpl(os); - os.endWriteException(); - } - - public void - __read(IceInternal.BasicStream is) - { - is.startReadException(); - __readImpl(is); - is.endReadException(false); - } - - public void - __write(Ice.OutputStream os) - { - os.startException(null); + os.startException(null); __writeImpl(os); os.endException(); } public void - __read(Ice.InputStream is) + __read(InputStream is) { is.startException(); __readImpl(is); @@ -125,20 +109,8 @@ public abstract class UserException extends java.lang.Exception implements Clone } protected abstract void - __writeImpl(IceInternal.BasicStream os); + __writeImpl(OutputStream os); protected abstract void - __readImpl(IceInternal.BasicStream is); - - protected void - __writeImpl(OutputStream os) - { - throw new MarshalException("exception was not generated with stream support"); - } - - protected void - __readImpl(InputStream is) - { - throw new MarshalException("exception was not generated with stream support"); - } + __readImpl(InputStream is); } diff --git a/java/src/Ice/src/main/java/Ice/UserExceptionReaderFactory.java b/java/src/Ice/src/main/java/Ice/UserExceptionFactory.java index 705e0b79039..8d8c3ba3dd4 100644 --- a/java/src/Ice/src/main/java/Ice/UserExceptionReaderFactory.java +++ b/java/src/Ice/src/main/java/Ice/UserExceptionFactory.java @@ -10,18 +10,17 @@ package Ice; /** - * Creates a UserExceptionReader for extracting a user exception - * from an input stream. + * Instantiates user exceptions. * - * @see InputStream + * @see InputStream#throwException **/ -public interface UserExceptionReaderFactory +public interface UserExceptionFactory { /** - * Creates and throws a UserExceptionReader instance. - * - * @param typeId The Slice type ID of the user exception to be instantiated. + * Instantiate a user exception with the given Slice type id (such as <code>::Module::MyException</code>) + * and throw it. If the implementation does not throw an exception, the Ice run time will fall back + * to using its default behavior for instantiating the user exception. **/ void createAndThrow(String typeId) - throws UserExceptionReader; + throws UserException; } diff --git a/java/src/Ice/src/main/java/Ice/UserExceptionReader.java b/java/src/Ice/src/main/java/Ice/UserExceptionReader.java deleted file mode 100644 index 8e1b83fe958..00000000000 --- a/java/src/Ice/src/main/java/Ice/UserExceptionReader.java +++ /dev/null @@ -1,62 +0,0 @@ -// ********************************************************************** -// -// Copyright (c) 2003-2015 ZeroC, Inc. All rights reserved. -// -// This copy of Ice is licensed to you under the terms described in the -// ICE_LICENSE file included in this distribution. -// -// ********************************************************************** - -package Ice; - -/** - * Allows a Dynamic Ice application to instantiate a user exception and - * intercept its unmarshaling. - * - * @see InputStream - **/ -public abstract class UserExceptionReader extends UserException -{ - /** - * Creates a reader for the given communicator. - **/ - protected UserExceptionReader(Communicator communicator) - { - _communicator = communicator; - } - - /** - * Unmarshal an exception from an output stream. - * - * @param in The input stream. - **/ - public abstract void read(Ice.InputStream is); - - @Override - public void __write(IceInternal.BasicStream os) - { - assert(false); - } - - @Override - public void __read(IceInternal.BasicStream is) - { - InputStream stream = (InputStream)is.closure(); - assert(stream != null); - read(stream); - } - - @Override - public void __write(Ice.OutputStream os) - { - assert(false); - } - - @Override - public void __read(Ice.InputStream is) - { - read(is); - } - - protected Communicator _communicator; -} diff --git a/java/src/Ice/src/main/java/Ice/UserExceptionWriter.java b/java/src/Ice/src/main/java/Ice/UserExceptionWriter.java deleted file mode 100644 index ca8c906ad5d..00000000000 --- a/java/src/Ice/src/main/java/Ice/UserExceptionWriter.java +++ /dev/null @@ -1,68 +0,0 @@ -// ********************************************************************** -// -// Copyright (c) 2003-2015 ZeroC, Inc. All rights reserved. -// -// This copy of Ice is licensed to you under the terms described in the -// ICE_LICENSE file included in this distribution. -// -// ********************************************************************** - -package Ice; - -/** - * Allows a Dynamic Ice application to wrap a native exception and - * intercept its marshaling. - * - * @see OutputStream - **/ -public abstract class UserExceptionWriter extends UserException -{ - /** - * Creates a writer for the given communicator. - **/ - public UserExceptionWriter(Communicator communicator) - { - _communicator = communicator; - } - - /** - * Marshal the encapsulated exception into an output stream. - * - * @param os The output stream. - **/ - public abstract void - write(Ice.OutputStream os); - - @Override - public void - __write(IceInternal.BasicStream os) - { - OutputStream stream = (OutputStream)os.closure(); - if(stream == null) - { - stream = new OutputStreamI(_communicator, os); - } - write(stream); - } - - public void - __read(IceInternal.BasicStream is, boolean rid) - { - assert(false); - } - - @Override - public void - __write(Ice.OutputStream os) - { - write(os); - } - - public void - __read(Ice.InputStream is, boolean rid) - { - assert(false); - } - - protected Communicator _communicator; -} diff --git a/java/src/Ice/src/main/java/Ice/Util.java b/java/src/Ice/src/main/java/Ice/Util.java index d049dc00d84..e086d62771e 100644 --- a/java/src/Ice/src/main/java/Ice/Util.java +++ b/java/src/Ice/src/main/java/Ice/Util.java @@ -440,96 +440,6 @@ public final class Util } /** - * Creates an input stream for dynamic invocation and dispatch. The stream uses - * the communicator's default encoding version. - * - * @param communicator The communicator for the stream. - * @param bytes An encoded request or reply. - * @return The input stream. - **/ - public static InputStream - createInputStream(Communicator communicator, byte[] bytes) - { - return new InputStreamI(communicator, bytes, true); - } - - /** - * Creates an input stream for dynamic invocation and dispatch. The stream uses - * the given encoding version. - * - * @param communicator The communicator for the stream. - * @param bytes An encoded request or reply. - * @param v The desired encoding version. - * @return The input stream. - **/ - public static InputStream - createInputStream(Communicator communicator, byte[] bytes, EncodingVersion v) - { - return new InputStreamI(communicator, bytes, v, true); - } - - /** - * Wraps encoded data with an input stream for dynamic invocation - * and dispatch. The stream uses the communicator's default - * encoding version. - * - * @param communicator The communicator for the stream. - * @param bytes An encoded request or reply. - * @param copyBytes True if the given bytes should be copied, - * false otherwise. - * @return The input stream. - **/ - public static InputStream - wrapInputStream(Communicator communicator, byte[] bytes) - { - return new InputStreamI(communicator, bytes, false); - } - - /** - * Wraps encoded data with an input stream for dynamic invocation - * and dispatch. The stream uses the given encoding version. - * - * @param communicator The communicator for the stream. - * @param bytes An encoded request or reply. - * @param v The desired encoding version. - * @param copyBytes True if the given bytes should be copied, - * false otherwise. - * @return The input stream. - **/ - public static InputStream - wrapInputStream(Communicator communicator, byte[] bytes, EncodingVersion v) - { - return new InputStreamI(communicator, bytes, v, false); - } - - /** - * Creates an output stream for dynamic invocation and dispatch. The stream uses - * the communicator's default encoding version. - * - * @param communicator The communicator for the stream. - * @return The output stream. - **/ - public static OutputStream - createOutputStream(Communicator communicator) - { - return new OutputStreamI(communicator); - } - - /** - * Creates an output stream for dynamic invocation and dispatch. The stream uses - * the given encoding version. - * - * @param communicator The communicator for the stream. - * @param v The desired encoding version. - * @return The output stream. - **/ - public static OutputStream - createOutputStream(Communicator communicator, EncodingVersion v) - { - return new OutputStreamI(communicator, v); - } - - /** * Returns the process-wide logger. * * @return The process-wide logger. @@ -665,6 +575,70 @@ public final class Util return IceInternal.Protocol.currentEncoding.clone(); } + /** + * Translates a Slice type id to a Java class name. + * + * @param id The Slice type id, such as <code>::Module::Type</code>. + * @return The equivalent Java class name, or null if the type id is malformed. + **/ + public static String typeIdToClass(String id) + { + if(!id.startsWith("::")) + { + return null; + } + + StringBuilder buf = new StringBuilder(id.length()); + + int start = 2; + boolean done = false; + while(!done) + { + int end = id.indexOf(':', start); + String s; + if(end != -1) + { + s = id.substring(start, end); + start = end + 2; + } + else + { + s = id.substring(start); + done = true; + } + if(buf.length() > 0) + { + buf.append('.'); + } + buf.append(fixKwd(s)); + } + + return buf.toString(); + } + + private static String fixKwd(String name) + { + // + // Keyword list. *Must* be kept in alphabetical order. Note that checkedCast and uncheckedCast + // are not Java keywords, but are in this list to prevent illegal code being generated if + // someone defines Slice operations with that name. + // + final String[] keywordList = + { + "abstract", "assert", "boolean", "break", "byte", "case", "catch", + "char", "checkedCast", "class", "clone", "const", "continue", "default", "do", + "double", "else", "enum", "equals", "extends", "false", "final", "finalize", + "finally", "float", "for", "getClass", "goto", "hashCode", "if", + "implements", "import", "instanceof", "int", "interface", "long", + "native", "new", "notify", "notifyAll", "null", "package", "private", + "protected", "public", "return", "short", "static", "strictfp", "super", "switch", + "synchronized", "this", "throw", "throws", "toString", "transient", + "true", "try", "uncheckedCast", "void", "volatile", "wait", "while" + }; + boolean found = java.util.Arrays.binarySearch(keywordList, name) >= 0; + return found ? "_" + name : name; + } + static private byte stringToMajor(String str) { diff --git a/java/src/Ice/src/main/java/IceInternal/BZip2.java b/java/src/Ice/src/main/java/IceInternal/BZip2.java new file mode 100644 index 00000000000..a5e2a724e2d --- /dev/null +++ b/java/src/Ice/src/main/java/IceInternal/BZip2.java @@ -0,0 +1,281 @@ +// ********************************************************************** +// +// Copyright (c) 2003-2015 ZeroC, Inc. All rights reserved. +// +// This copy of Ice is licensed to you under the terms described in the +// ICE_LICENSE file included in this distribution. +// +// ********************************************************************** + +package IceInternal; + +public class BZip2 +{ + public static Buffer compress(Buffer buf, int headerSize, int compressionLevel) + { + assert(supported()); + + int uncompressedLen = buf.size() - headerSize; + int compressedLen = (int)(uncompressedLen * 1.01 + 600); + byte[] compressed = new byte[compressedLen]; + + byte[] data = null; + int offset = 0; + try + { + // + // If the ByteBuffer is backed by an array then we can avoid + // an extra copy by using the array directly. + // + data = buf.b.array(); + offset = buf.b.arrayOffset(); + } + catch(Exception ex) + { + // + // Otherwise, allocate an array to hold a copy of the uncompressed data. + // + data = new byte[buf.size()]; + buf.b.position(0); + buf.b.get(data); + } + + try + { + // + // Compress the data using the class org.apache.tools.bzip2.CBZip2OutputStream. + // Its constructor requires an OutputStream argument, therefore we pass the + // compressed buffer in an OutputStream wrapper. + // + BufferedOutputStream bos = new BufferedOutputStream(compressed); + // + // For interoperability with the bzip2 C library, we insert the magic bytes + // 'B', 'Z' before invoking the Java implementation. + // + bos.write('B'); + bos.write('Z'); + java.lang.Object[] args = new java.lang.Object[]{ bos, Integer.valueOf(compressionLevel) }; + java.io.OutputStream os = (java.io.OutputStream)_bzOutputStreamCtor.newInstance(args); + os.write(data, offset + headerSize, uncompressedLen); + os.close(); + compressedLen = bos.pos(); + } + catch(Exception ex) + { + throw new Ice.CompressionException("bzip2 compression failure", ex); + } + + // + // Don't bother if the compressed data is larger than the + // uncompressed data. + // + if(compressedLen >= uncompressedLen) + { + return null; + } + + Buffer r = new Buffer(false); + r.resize(headerSize + 4 + compressedLen, false); + r.b.position(0); + + // + // Copy the header from the uncompressed stream to the compressed one. + // + r.b.put(data, offset, headerSize); + + // + // Add the size of the uncompressed stream before the message body. + // + r.b.putInt(buf.size()); + + // + // Add the compressed message body. + // + r.b.put(compressed, 0, compressedLen); + + return r; + } + + public static Buffer uncompress(Buffer buf, int headerSize, int messageSizeMax) + { + assert(supported()); + + buf.b.position(headerSize); + int uncompressedSize = buf.b.getInt(); + if(uncompressedSize <= headerSize) + { + throw new Ice.IllegalMessageSizeException(); + } + if(uncompressedSize > messageSizeMax) + { + IceInternal.Ex.throwMemoryLimitException(uncompressedSize, messageSizeMax); + } + + int compressedLen = buf.size() - headerSize - 4; + + byte[] compressed = null; + int offset = 0; + try + { + // + // If the ByteBuffer is backed by an array then we can avoid + // an extra copy by using the array directly. + // + compressed = buf.b.array(); + offset = buf.b.arrayOffset(); + } + catch(Exception ex) + { + // + // Otherwise, allocate an array to hold a copy of the compressed data. + // + compressed = new byte[buf.size()]; + buf.b.position(0); + buf.b.get(compressed); + } + + Buffer r = new Buffer(false); + r.resize(uncompressedSize, false); + + try + { + // + // Uncompress the data using the class org.apache.tools.bzip2.CBZip2InputStream. + // Its constructor requires an InputStream argument, therefore we pass the + // compressed data in a ByteArrayInputStream. + // + java.io.ByteArrayInputStream bais = + new java.io.ByteArrayInputStream(compressed, offset + headerSize + 4, compressedLen); + // + // For interoperability with the bzip2 C library, we insert the magic bytes + // 'B', 'Z' during compression and therefore must extract them before we + // invoke the Java implementation. + // + byte magicB = (byte)bais.read(); + byte magicZ = (byte)bais.read(); + if(magicB != (byte)'B' || magicZ != (byte)'Z') + { + Ice.CompressionException e = new Ice.CompressionException(); + e.reason = "bzip2 uncompression failure: invalid magic bytes"; + throw e; + } + java.lang.Object[] args = new java.lang.Object[]{ bais }; + java.io.InputStream is = (java.io.InputStream)_bzInputStreamCtor.newInstance(args); + r.b.position(headerSize); + byte[] arr = new byte[8 * 1024]; + int n; + while((n = is.read(arr)) != -1) + { + r.b.put(arr, 0, n); + } + is.close(); + } + catch(Exception ex) + { + throw new Ice.CompressionException("bzip2 uncompression failure", ex); + } + + // + // Copy the header from the compressed stream to the uncompressed one. + // + r.b.position(0); + r.b.put(compressed, offset, headerSize); + + return r; + } + + private static boolean _checked = false; + private static java.lang.reflect.Constructor<?> _bzInputStreamCtor; + private static java.lang.reflect.Constructor<?> _bzOutputStreamCtor; + + public synchronized static boolean supported() + { + // + // Use lazy initialization when determining whether support for bzip2 compression is available. + // + if(!_checked) + { + _checked = true; + try + { + Class<?> cls; + Class<?>[] types = new Class<?>[1]; + cls = IceInternal.Util.findClass("org.apache.tools.bzip2.CBZip2InputStream", null); + if(cls != null) + { + types[0] = java.io.InputStream.class; + _bzInputStreamCtor = cls.getDeclaredConstructor(types); + } + cls = IceInternal.Util.findClass("org.apache.tools.bzip2.CBZip2OutputStream", null); + if(cls != null) + { + types = new Class[2]; + types[0] = java.io.OutputStream.class; + types[1] = Integer.TYPE; + _bzOutputStreamCtor = cls.getDeclaredConstructor(types); + } + } + catch(Exception ex) + { + // Ignore - bzip2 compression not available. + } + } + return _bzInputStreamCtor != null && _bzOutputStreamCtor != null; + } + + private static class BufferedOutputStream extends java.io.OutputStream + { + BufferedOutputStream(byte[] data) + { + _data = data; + } + + @Override + public void close() + throws java.io.IOException + { + } + + @Override + public void flush() + throws java.io.IOException + { + } + + @Override + public void write(byte[] b) + throws java.io.IOException + { + assert(_data.length - _pos >= b.length); + System.arraycopy(b, 0, _data, _pos, b.length); + _pos += b.length; + } + + @Override + public void write(byte[] b, int off, int len) + throws java.io.IOException + { + assert(_data.length - _pos >= len); + System.arraycopy(b, off, _data, _pos, len); + _pos += len; + } + + @Override + public void write(int b) + throws java.io.IOException + { + assert(_data.length - _pos >= 1); + _data[_pos] = (byte)b; + ++_pos; + } + + int + pos() + { + return _pos; + } + + private byte[] _data; + private int _pos; + } +} diff --git a/java/src/Ice/src/main/java/IceInternal/BasicStream.java b/java/src/Ice/src/main/java/IceInternal/BasicStream.java deleted file mode 100644 index 60c0ebb48ed..00000000000 --- a/java/src/Ice/src/main/java/IceInternal/BasicStream.java +++ /dev/null @@ -1,4867 +0,0 @@ -// ********************************************************************** -// -// Copyright (c) 2003-2015 ZeroC, Inc. All rights reserved. -// -// This copy of Ice is licensed to you under the terms described in the -// ICE_LICENSE file included in this distribution. -// -// ********************************************************************** - -package IceInternal; - -import java.io.IOException; - -public class BasicStream -{ - public - BasicStream(Instance instance, Ice.EncodingVersion encoding) - { - this(instance, encoding, instance.cacheMessageBuffers() > 1); - } - - public - BasicStream(Instance instance, Ice.EncodingVersion encoding, boolean direct) - { - initialize(instance, encoding); - _buf = new Buffer(direct); - } - - public - BasicStream(Instance instance, Ice.EncodingVersion encoding, byte[] data) - { - initialize(instance, encoding); - _buf = new Buffer(data); - } - - public - BasicStream(Instance instance, Ice.EncodingVersion encoding, java.nio.ByteBuffer data) - { - initialize(instance, encoding); - _buf = new Buffer(data); - } - - private void - initialize(Instance instance, Ice.EncodingVersion encoding) - { - _instance = instance; - _closure = null; - _encoding = encoding; - - _readEncapsStack = null; - _writeEncapsStack = null; - _readEncapsCache = null; - _writeEncapsCache = null; - - _sliceObjects = true; - - _startSeq = -1; - } - - // - // This function allows this object to be reused, rather than - // reallocated. - // - public void - reset() - { - _buf.reset(); - clear(); - } - - public void - clear() - { - if(_readEncapsStack != null) - { - assert(_readEncapsStack.next == null); - _readEncapsStack.next = _readEncapsCache; - _readEncapsCache = _readEncapsStack; - _readEncapsCache.reset(); - _readEncapsStack = null; - } - - if(_writeEncapsStack != null) - { - assert(_writeEncapsStack.next == null); - _writeEncapsStack.next = _writeEncapsCache; - _writeEncapsCache = _writeEncapsStack; - _writeEncapsCache.reset(); - _writeEncapsStack = null; - } - - _startSeq = -1; - - _sliceObjects = true; - } - - public Instance - instance() - { - return _instance; - } - - public Object - closure() - { - return _closure; - } - - public Object - closure(Object p) - { - Object prev = _closure; - _closure = p; - return prev; - } - - public void - swap(BasicStream other) - { - assert(_instance == other._instance); - - Buffer tmpBuf = other._buf; - other._buf = _buf; - _buf = tmpBuf; - - Object tmpClosure = other._closure; - other._closure = _closure; - _closure = tmpClosure; - - // - // Swap is never called for BasicStreams that have encapsulations being read/write. However, - // encapsulations might still be set in case marshalling or un-marshalling failed. We just - // reset the encapsulations if there are still some set. - // - resetEncaps(); - other.resetEncaps(); - - int tmpStartSeq = other._startSeq; - other._startSeq = _startSeq; - _startSeq = tmpStartSeq; - - int tmpMinSeqSize = other._minSeqSize; - other._minSeqSize = _minSeqSize; - _minSeqSize = tmpMinSeqSize; - } - - public void - resetEncaps() - { - _readEncapsStack = null; - _writeEncapsStack = null; - } - - public void - resize(int sz, boolean reading) - { - _buf.resize(sz, reading); - _buf.b.position(sz); - } - - public Buffer - prepareWrite() - { - _buf.b.limit(_buf.size()); - _buf.b.position(0); - return _buf; - } - - public Buffer - getBuffer() - { - return _buf; - } - - public void - startWriteObject(Ice.SlicedData data) - { - assert(_writeEncapsStack != null && _writeEncapsStack.encoder != null); - _writeEncapsStack.encoder.startInstance(SliceType.ObjectSlice, data); - } - - public void - endWriteObject() - { - assert(_writeEncapsStack != null && _writeEncapsStack.encoder != null); - _writeEncapsStack.encoder.endInstance(); - } - - public void - startReadObject() - { - assert(_readEncapsStack != null && _readEncapsStack.decoder != null); - _readEncapsStack.decoder.startInstance(SliceType.ObjectSlice); - } - - public Ice.SlicedData - endReadObject(boolean preserve) - { - assert(_readEncapsStack != null && _readEncapsStack.decoder != null); - return _readEncapsStack.decoder.endInstance(preserve); - } - - public void - startWriteException(Ice.SlicedData data) - { - assert(_writeEncapsStack != null && _writeEncapsStack.encoder != null); - _writeEncapsStack.encoder.startInstance(SliceType.ExceptionSlice, data); - } - - public void - endWriteException() - { - assert(_writeEncapsStack != null && _writeEncapsStack.encoder != null); - _writeEncapsStack.encoder.endInstance(); - } - - public void - startReadException() - { - assert(_readEncapsStack != null && _readEncapsStack.decoder != null); - _readEncapsStack.decoder.startInstance(SliceType.ExceptionSlice); - } - - public Ice.SlicedData - endReadException(boolean preserve) - { - assert(_readEncapsStack != null && _readEncapsStack.decoder != null); - return _readEncapsStack.decoder.endInstance(preserve); - } - - public void - startWriteEncaps() - { - // - // If no encoding version is specified, use the current write - // encapsulation encoding version if there's a current write - // encapsulation, otherwise, use the stream encoding version. - // - - if(_writeEncapsStack != null) - { - startWriteEncaps(_writeEncapsStack.encoding, _writeEncapsStack.format); - } - else - { - startWriteEncaps(_encoding, Ice.FormatType.DefaultFormat); - } - } - - public void - startWriteEncaps(Ice.EncodingVersion encoding, Ice.FormatType format) - { - Protocol.checkSupportedEncoding(encoding); - - WriteEncaps curr = _writeEncapsCache; - if(curr != null) - { - curr.reset(); - _writeEncapsCache = _writeEncapsCache.next; - } - else - { - curr = new WriteEncaps(); - } - curr.next = _writeEncapsStack; - _writeEncapsStack = curr; - - _writeEncapsStack.format = format; - _writeEncapsStack.setEncoding(encoding); - _writeEncapsStack.start = _buf.size(); - - writeInt(0); // Placeholder for the encapsulation length. - _writeEncapsStack.encoding.__write(this); - } - - public void - endWriteEncaps() - { - assert(_writeEncapsStack != null); - - // Size includes size and version. - int start = _writeEncapsStack.start; - int sz = _buf.size() - start; - _buf.b.putInt(start, sz); - - WriteEncaps curr = _writeEncapsStack; - _writeEncapsStack = curr.next; - curr.next = _writeEncapsCache; - _writeEncapsCache = curr; - _writeEncapsCache.reset(); - } - - public void - endWriteEncapsChecked() // Used by public stream API. - { - if(_writeEncapsStack == null) - { - throw new Ice.EncapsulationException("not in an encapsulation"); - } - endWriteEncaps(); - } - - public void - writeEmptyEncaps(Ice.EncodingVersion encoding) - { - Protocol.checkSupportedEncoding(encoding); - writeInt(6); // Size - encoding.__write(this); - } - - public void - writeEncaps(byte[] v) - { - if(v.length < 6) - { - throw new Ice.EncapsulationException(); - } - expand(v.length); - _buf.b.put(v); - } - - public Ice.EncodingVersion - getWriteEncoding() - { - return _writeEncapsStack != null ? _writeEncapsStack.encoding : _encoding; - } - - public Ice.EncodingVersion - startReadEncaps() - { - ReadEncaps curr = _readEncapsCache; - if(curr != null) - { - curr.reset(); - _readEncapsCache = _readEncapsCache.next; - } - else - { - curr = new ReadEncaps(); - } - curr.next = _readEncapsStack; - _readEncapsStack = curr; - - _readEncapsStack.start = _buf.b.position(); - - // - // I don't use readSize() and writeSize() for encapsulations, - // because when creating an encapsulation, I must know in advance - // how many bytes the size information will require in the data - // stream. If I use an Int, it is always 4 bytes. For - // readSize()/writeSize(), it could be 1 or 5 bytes. - // - int sz = readInt(); - if(sz < 6) - { - throw new Ice.UnmarshalOutOfBoundsException(); - } - if(sz - 4 > _buf.b.remaining()) - { - throw new Ice.UnmarshalOutOfBoundsException(); - } - _readEncapsStack.sz = sz; - - Ice.EncodingVersion encoding = new Ice.EncodingVersion(); - encoding.__read(this); - Protocol.checkSupportedEncoding(encoding); // Make sure the encoding is supported. - _readEncapsStack.setEncoding(encoding); - - return encoding; - } - - public void - endReadEncaps() - { - assert(_readEncapsStack != null); - - if(!_readEncapsStack.encoding_1_0) - { - skipOpts(); - if(_buf.b.position() != _readEncapsStack.start + _readEncapsStack.sz) - { - throw new Ice.EncapsulationException(); - } - } - else if(_buf.b.position() != _readEncapsStack.start + _readEncapsStack.sz) - { - if(_buf.b.position() + 1 != _readEncapsStack.start + _readEncapsStack.sz) - { - throw new Ice.EncapsulationException(); - } - - // - // Ice version < 3.3 had a bug where user exceptions with - // class members could be encoded with a trailing byte - // when dispatched with AMD. So we tolerate an extra byte - // in the encapsulation. - // - try - { - _buf.b.get(); - } - catch(java.nio.BufferUnderflowException ex) - { - throw new Ice.UnmarshalOutOfBoundsException(); - } - } - - ReadEncaps curr = _readEncapsStack; - _readEncapsStack = curr.next; - curr.next = _readEncapsCache; - _readEncapsCache = curr; - _readEncapsCache.reset(); - } - - public void - skipEmptyEncaps(Ice.EncodingVersion encoding) - { - int sz = readInt(); - if(sz != 6) - { - throw new Ice.EncapsulationException(); - } - - final int pos = _buf.b.position(); - if(pos + 2 > _buf.size()) - { - throw new Ice.UnmarshalOutOfBoundsException(); - } - - if(encoding != null) - { - encoding.__read(this); - } - else - { - _buf.b.position(pos + 2); - } - } - - public void - endReadEncapsChecked() // Used by public stream API. - { - if(_readEncapsStack == null) - { - throw new Ice.EncapsulationException("not in an encapsulation"); - } - endReadEncaps(); - } - - public byte[] - readEncaps(Ice.EncodingVersion encoding) - { - int sz = readInt(); - if(sz < 6) - { - throw new Ice.UnmarshalOutOfBoundsException(); - } - - if(sz - 4 > _buf.b.remaining()) - { - throw new Ice.UnmarshalOutOfBoundsException(); - } - - if(encoding != null) - { - encoding.__read(this); - _buf.b.position(_buf.b.position() - 6); - } - else - { - _buf.b.position(_buf.b.position() - 4); - } - - byte[] v = new byte[sz]; - try - { - _buf.b.get(v); - return v; - } - catch(java.nio.BufferUnderflowException ex) - { - throw new Ice.UnmarshalOutOfBoundsException(); - } - } - - public Ice.EncodingVersion - getReadEncoding() - { - return _readEncapsStack != null ? _readEncapsStack.encoding : _encoding; - } - - public int - getReadEncapsSize() - { - assert(_readEncapsStack != null); - return _readEncapsStack.sz - 6; - } - - public Ice.EncodingVersion - skipEncaps() - { - int sz = readInt(); - if(sz < 6) - { - throw new Ice.UnmarshalOutOfBoundsException(); - } - Ice.EncodingVersion encoding = new Ice.EncodingVersion(); - encoding.__read(this); - try - { - _buf.b.position(_buf.b.position() + sz - 6); - } - catch(IllegalArgumentException ex) - { - throw new Ice.UnmarshalOutOfBoundsException(); - } - return encoding; - } - - public void - startWriteSlice(String typeId, int compactId, boolean last) - { - assert(_writeEncapsStack != null && _writeEncapsStack.encoder != null); - _writeEncapsStack.encoder.startSlice(typeId, compactId, last); - } - - public void - endWriteSlice() - { - assert(_writeEncapsStack != null && _writeEncapsStack.encoder != null); - _writeEncapsStack.encoder.endSlice(); - } - - public String - startReadSlice() // Returns type ID of next slice - { - assert(_readEncapsStack != null && _readEncapsStack.decoder != null); - return _readEncapsStack.decoder.startSlice(); - } - - public void - endReadSlice() - { - assert(_readEncapsStack != null && _readEncapsStack.decoder != null); - _readEncapsStack.decoder.endSlice(); - } - - public void - skipSlice() - { - assert(_readEncapsStack != null && _readEncapsStack.decoder != null); - _readEncapsStack.decoder.skipSlice(); - } - - public void - readPendingObjects() - { - if(_readEncapsStack != null && _readEncapsStack.decoder != null) - { - _readEncapsStack.decoder.readPendingObjects(); - } - else if(_readEncapsStack != null ? _readEncapsStack.encoding_1_0 : _encoding.equals(Ice.Util.Encoding_1_0)) - { - // - // If using the 1.0 encoding and no objects were read, we - // still read an empty sequence of pending objects if - // requested (i.e.: if this is called). - // - // This is required by the 1.0 encoding, even if no objects - // are written we do marshal an empty sequence if marshaled - // data types use classes. - // - skipSize(); - } - } - - public void - writePendingObjects() - { - if(_writeEncapsStack != null && _writeEncapsStack.encoder != null) - { - _writeEncapsStack.encoder.writePendingObjects(); - } - else if(_writeEncapsStack != null ? _writeEncapsStack.encoding_1_0 : _encoding.equals(Ice.Util.Encoding_1_0)) - { - // - // If using the 1.0 encoding and no objects were written, we - // still write an empty sequence for pending objects if - // requested (i.e.: if this is called). - // - // This is required by the 1.0 encoding, even if no objects - // are written we do marshal an empty sequence if marshaled - // data types use classes. - // - writeSize(0); - } - } - - public void - writeSize(int v) - { - if(v > 254) - { - expand(5); - _buf.b.put((byte)-1); - _buf.b.putInt(v); - } - else - { - expand(1); - _buf.b.put((byte)v); - } - } - - public int - readSize() - { - try - { - byte b = _buf.b.get(); - if(b == -1) - { - int v = _buf.b.getInt(); - if(v < 0) - { - throw new Ice.UnmarshalOutOfBoundsException(); - } - return v; - } - else - { - return b < 0 ? b + 256 : b; - } - } - catch(java.nio.BufferUnderflowException ex) - { - throw new Ice.UnmarshalOutOfBoundsException(); - } - } - - public int - readAndCheckSeqSize(int minSize) - { - int sz = readSize(); - - if(sz == 0) - { - return sz; - } - - // - // The _startSeq variable points to the start of the sequence for which - // we expect to read at least _minSeqSize bytes from the stream. - // - // If not initialized or if we already read more data than _minSeqSize, - // we reset _startSeq and _minSeqSize for this sequence (possibly a - // top-level sequence or enclosed sequence it doesn't really matter). - // - // Otherwise, we are reading an enclosed sequence and we have to bump - // _minSeqSize by the minimum size that this sequence will require on - // the stream. - // - // The goal of this check is to ensure that when we start un-marshalling - // a new sequence, we check the minimal size of this new sequence against - // the estimated remaining buffer size. This estimatation is based on - // the minimum size of the enclosing sequences, it's _minSeqSize. - // - if(_startSeq == -1 || _buf.b.position() > (_startSeq + _minSeqSize)) - { - _startSeq = _buf.b.position(); - _minSeqSize = sz * minSize; - } - else - { - _minSeqSize += sz * minSize; - } - - // - // If there isn't enough data to read on the stream for the sequence (and - // possibly enclosed sequences), something is wrong with the marshalled - // data: it's claiming having more data that what is possible to read. - // - if(_startSeq + _minSeqSize > _buf.size()) - { - throw new Ice.UnmarshalOutOfBoundsException(); - } - - return sz; - } - - public int - startSize() - { - int pos = _buf.b.position(); - writeInt(0); // Placeholder for 32-bit size - return pos; - } - - public void - endSize(int pos) - { - assert(pos >= 0); - rewriteInt(_buf.b.position() - pos - 4, pos); - } - - public void - writeBlob(byte[] v) - { - if(v == null) - { - return; - } - expand(v.length); - _buf.b.put(v); - } - - public void - writeBlob(byte[] v, int off, int len) - { - if(v == null) - { - return; - } - expand(len); - _buf.b.put(v, off, len); - } - - public byte[] - readBlob(int sz) - { - if(_buf.b.remaining() < sz) - { - throw new Ice.UnmarshalOutOfBoundsException(); - } - byte[] v = new byte[sz]; - try - { - _buf.b.get(v); - return v; - } - catch(java.nio.BufferUnderflowException ex) - { - throw new Ice.UnmarshalOutOfBoundsException(); - } - } - - // Read/write format and tag for optionals - public boolean - writeOpt(int tag, Ice.OptionalFormat format) - { - assert(_writeEncapsStack != null); - if(_writeEncapsStack.encoder != null) - { - return _writeEncapsStack.encoder.writeOpt(tag, format); - } - else - { - return writeOptImpl(tag, format); - } - } - - public boolean - readOpt(int tag, Ice.OptionalFormat expectedFormat) - { - assert(_readEncapsStack != null); - if(_readEncapsStack.decoder != null) - { - return _readEncapsStack.decoder.readOpt(tag, expectedFormat); - } - else - { - return readOptImpl(tag, expectedFormat); - } - } - - public void - writeByte(byte v) - { - expand(1); - _buf.b.put(v); - } - - public void - writeByte(int tag, Ice.ByteOptional v) - { - if(v != null && v.isSet()) - { - writeByte(tag, v.get()); - } - } - - public void - writeByte(int tag, byte v) - { - if(writeOpt(tag, Ice.OptionalFormat.F1)) - { - writeByte(v); - } - } - - public void - rewriteByte(byte v, int dest) - { - _buf.b.put(dest, v); - } - - public void - writeByteSeq(byte[] v) - { - if(v == null) - { - writeSize(0); - } - else - { - writeSize(v.length); - expand(v.length); - _buf.b.put(v); - } - } - - public void - writeByteSeq(int tag, Ice.Optional<byte[]> v) - { - if(v != null && v.isSet()) - { - writeByteSeq(tag, v.get()); - } - } - - public void - writeByteSeq(int tag, byte[] v) - { - if(writeOpt(tag, Ice.OptionalFormat.VSize)) - { - writeByteSeq(v); - } - } - - public void - writeByteBuffer(java.nio.ByteBuffer v) - { - if(v == null || v.remaining() == 0) - { - writeSize(0); - } - else - { - writeSize(v.remaining()); - expand(v.remaining()); - _buf.b.put(v); - } - } - - public void - writeSerializable(java.io.Serializable o) - { - if(o == null) - { - writeSize(0); - return; - } - try - { - OutputStreamWrapper w = new OutputStreamWrapper(this); - java.io.ObjectOutputStream out = new java.io.ObjectOutputStream(w); - out.writeObject(o); - out.close(); - w.close(); - } - catch(java.lang.Exception ex) - { - throw new Ice.MarshalException("cannot serialize object: " + ex); - } - } - - public byte - readByte() - { - try - { - return _buf.b.get(); - } - catch(java.nio.BufferUnderflowException ex) - { - throw new Ice.UnmarshalOutOfBoundsException(); - } - } - - public void - readByte(int tag, Ice.ByteOptional v) - { - if(readOpt(tag, Ice.OptionalFormat.F1)) - { - v.set(readByte()); - } - else - { - v.clear(); - } - } - - public byte[] - readByteSeq() - { - try - { - final int sz = readAndCheckSeqSize(1); - byte[] v = new byte[sz]; - _buf.b.get(v); - return v; - } - catch(java.nio.BufferUnderflowException ex) - { - throw new Ice.UnmarshalOutOfBoundsException(); - } - } - - public void - readByteSeq(int tag, Ice.Optional<byte[]> v) - { - if(readOpt(tag, Ice.OptionalFormat.VSize)) - { - v.set(readByteSeq()); - } - else - { - v.clear(); - } - } - - public java.nio.ByteBuffer - readByteBuffer() - { - try - { - final int sz = readAndCheckSeqSize(1); - java.nio.ByteBuffer v = _buf.b.slice(); - v.limit(sz); - _buf.b.position(_buf.b.position() + sz); - return v.asReadOnlyBuffer(); - } - catch(java.nio.BufferUnderflowException ex) - { - throw new Ice.UnmarshalOutOfBoundsException(); - } - } - - public java.io.Serializable - readSerializable() - { - int sz = readAndCheckSeqSize(1); - if (sz == 0) - { - return null; - } - ObjectInputStream in = null; - try - { - InputStreamWrapper w = new InputStreamWrapper(sz, this); - in = new ObjectInputStream(_instance, w); - return (java.io.Serializable)in.readObject(); - } - catch(java.lang.Exception ex) - { - throw new Ice.MarshalException("cannot deserialize object", ex); - } - finally - { - if(in != null) - { - try - { - in.close(); - } - catch (IOException ex) - { - throw new Ice.MarshalException("cannot deserialize object", ex); - } - } - } - } - - public void - writeBool(boolean v) - { - expand(1); - _buf.b.put(v ? (byte)1 : (byte)0); - } - - public void - writeBool(int tag, Ice.BooleanOptional v) - { - if(v != null && v.isSet()) - { - writeBool(tag, v.get()); - } - } - - public void - writeBool(int tag, boolean v) - { - if(writeOpt(tag, Ice.OptionalFormat.F1)) - { - writeBool(v); - } - } - - public void - rewriteBool(boolean v, int dest) - { - _buf.b.put(dest, v ? (byte)1 : (byte)0); - } - - public void - writeBoolSeq(boolean[] v) - { - if(v == null) - { - writeSize(0); - } - else - { - writeSize(v.length); - expand(v.length); - for(boolean b : v) - { - _buf.b.put(b ? (byte)1 : (byte)0); - } - } - } - - public void - writeBoolSeq(int tag, Ice.Optional<boolean[]> v) - { - if(v != null && v.isSet()) - { - writeBoolSeq(tag, v.get()); - } - } - - public void - writeBoolSeq(int tag, boolean[] v) - { - if(writeOpt(tag, Ice.OptionalFormat.VSize)) - { - writeBoolSeq(v); - } - } - - public boolean - readBool() - { - try - { - return _buf.b.get() == 1; - } - catch(java.nio.BufferUnderflowException ex) - { - throw new Ice.UnmarshalOutOfBoundsException(); - } - } - - public void - readBool(int tag, Ice.BooleanOptional v) - { - if(readOpt(tag, Ice.OptionalFormat.F1)) - { - v.set(readBool()); - } - else - { - v.clear(); - } - } - - public boolean[] - readBoolSeq() - { - try - { - final int sz = readAndCheckSeqSize(1); - boolean[] v = new boolean[sz]; - for(int i = 0; i < sz; i++) - { - v[i] = _buf.b.get() == 1; - } - return v; - } - catch(java.nio.BufferUnderflowException ex) - { - throw new Ice.UnmarshalOutOfBoundsException(); - } - } - - public void - readBoolSeq(int tag, Ice.Optional<boolean[]> v) - { - if(readOpt(tag, Ice.OptionalFormat.VSize)) - { - v.set(readBoolSeq()); - } - else - { - v.clear(); - } - } - - public void - writeShort(short v) - { - expand(2); - _buf.b.putShort(v); - } - - public void - writeShort(int tag, Ice.ShortOptional v) - { - if(v != null && v.isSet()) - { - writeShort(tag, v.get()); - } - } - - public void - writeShort(int tag, short v) - { - if(writeOpt(tag, Ice.OptionalFormat.F2)) - { - writeShort(v); - } - } - - public void - writeShortSeq(short[] v) - { - if(v == null) - { - writeSize(0); - } - else - { - writeSize(v.length); - expand(v.length * 2); - java.nio.ShortBuffer shortBuf = _buf.b.asShortBuffer(); - shortBuf.put(v); - _buf.b.position(_buf.b.position() + v.length * 2); - } - } - - public void - writeShortSeq(int tag, Ice.Optional<short[]> v) - { - if(v != null && v.isSet()) - { - writeShortSeq(tag, v.get()); - } - } - - public void - writeShortSeq(int tag, short[] v) - { - if(writeOpt(tag, Ice.OptionalFormat.VSize)) - { - writeSize(v == null || v.length == 0 ? 1 : v.length * 2 + (v.length > 254 ? 5 : 1)); - writeShortSeq(v); - } - } - - public void - writeShortBuffer(java.nio.ShortBuffer v) - { - if(v == null || v.remaining() == 0) - { - writeSize(0); - } - else - { - int sz = v.remaining(); - writeSize(sz); - expand(sz * 2); - - java.nio.ShortBuffer shortBuf = _buf.b.asShortBuffer(); - shortBuf.put(v); - _buf.b.position(_buf.b.position() + sz * 2); - } - } - - public short - readShort() - { - try - { - return _buf.b.getShort(); - } - catch(java.nio.BufferUnderflowException ex) - { - throw new Ice.UnmarshalOutOfBoundsException(); - } - } - - public void - readShort(int tag, Ice.ShortOptional v) - { - if(readOpt(tag, Ice.OptionalFormat.F2)) - { - v.set(readShort()); - } - else - { - v.clear(); - } - } - - public short[] - readShortSeq() - { - try - { - final int sz = readAndCheckSeqSize(2); - short[] v = new short[sz]; - java.nio.ShortBuffer shortBuf = _buf.b.asShortBuffer(); - shortBuf.get(v); - _buf.b.position(_buf.b.position() + sz * 2); - return v; - } - catch(java.nio.BufferUnderflowException ex) - { - throw new Ice.UnmarshalOutOfBoundsException(); - } - } - - public void - readShortSeq(int tag, Ice.Optional<short[]> v) - { - if(readOpt(tag, Ice.OptionalFormat.VSize)) - { - skipSize(); - v.set(readShortSeq()); - } - else - { - v.clear(); - } - } - - public java.nio.ShortBuffer - readShortBuffer() - { - try - { - final int sz = readAndCheckSeqSize(2); - java.nio.ShortBuffer shortBuf = _buf.b.asShortBuffer(); - java.nio.ShortBuffer v = shortBuf.slice(); - v.limit(sz); - _buf.b.position(_buf.b.position() + sz * 2); - return v.asReadOnlyBuffer(); - } - catch(java.nio.BufferUnderflowException ex) - { - throw new Ice.UnmarshalOutOfBoundsException(); - } - } - - public void - writeInt(int v) - { - expand(4); - _buf.b.putInt(v); - } - - public void - writeInt(int tag, Ice.IntOptional v) - { - if(v != null && v.isSet()) - { - writeInt(tag, v.get()); - } - } - - public void - writeInt(int tag, int v) - { - if(writeOpt(tag, Ice.OptionalFormat.F4)) - { - writeInt(v); - } - } - - public void - rewriteInt(int v, int dest) - { - _buf.b.putInt(dest, v); - } - - public void - writeIntSeq(int[] v) - { - if(v == null) - { - writeSize(0); - } - else - { - writeSize(v.length); - expand(v.length * 4); - java.nio.IntBuffer intBuf = _buf.b.asIntBuffer(); - intBuf.put(v); - _buf.b.position(_buf.b.position() + v.length * 4); - } - } - - public void - writeIntSeq(int tag, Ice.Optional<int[]> v) - { - if(v != null && v.isSet()) - { - writeIntSeq(tag, v.get()); - } - } - - public void - writeIntSeq(int tag, int[] v) - { - if(writeOpt(tag, Ice.OptionalFormat.VSize)) - { - writeSize(v == null || v.length == 0 ? 1 : v.length * 4 + (v.length > 254 ? 5 : 1)); - writeIntSeq(v); - } - } - - public void - writeIntBuffer(java.nio.IntBuffer v) - { - if(v == null || v.remaining() == 0) - { - writeSize(0); - } - else - { - int sz = v.remaining(); - writeSize(sz); - expand(sz * 4); - - java.nio.IntBuffer intBuf = _buf.b.asIntBuffer(); - intBuf.put(v); - _buf.b.position(_buf.b.position() + sz * 4); - } - } - - public int - readInt() - { - try - { - return _buf.b.getInt(); - } - catch(java.nio.BufferUnderflowException ex) - { - throw new Ice.UnmarshalOutOfBoundsException(); - } - } - - public void - readInt(int tag, Ice.IntOptional v) - { - if(readOpt(tag, Ice.OptionalFormat.F4)) - { - v.set(readInt()); - } - else - { - v.clear(); - } - } - - public int[] - readIntSeq() - { - try - { - final int sz = readAndCheckSeqSize(4); - int[] v = new int[sz]; - java.nio.IntBuffer intBuf = _buf.b.asIntBuffer(); - intBuf.get(v); - _buf.b.position(_buf.b.position() + sz * 4); - return v; - } - catch(java.nio.BufferUnderflowException ex) - { - throw new Ice.UnmarshalOutOfBoundsException(); - } - } - - public void - readIntSeq(int tag, Ice.Optional<int[]> v) - { - if(readOpt(tag, Ice.OptionalFormat.VSize)) - { - skipSize(); - v.set(readIntSeq()); - } - else - { - v.clear(); - } - } - - public java.nio.IntBuffer - readIntBuffer() - { - try - { - final int sz = readAndCheckSeqSize(4); - java.nio.IntBuffer intBuf = _buf.b.asIntBuffer(); - java.nio.IntBuffer v = intBuf.slice(); - v.limit(sz); - _buf.b.position(_buf.b.position() + sz * 4); - return v.asReadOnlyBuffer(); - } - catch(java.nio.BufferUnderflowException ex) - { - throw new Ice.UnmarshalOutOfBoundsException(); - } - } - - public void - writeLong(long v) - { - expand(8); - _buf.b.putLong(v); - } - - public void - writeLong(int tag, Ice.LongOptional v) - { - if(v != null && v.isSet()) - { - writeLong(tag, v.get()); - } - } - - public void - writeLong(int tag, long v) - { - if(writeOpt(tag, Ice.OptionalFormat.F8)) - { - writeLong(v); - } - } - - public void - writeLongSeq(long[] v) - { - if(v == null) - { - writeSize(0); - } - else - { - writeSize(v.length); - expand(v.length * 8); - java.nio.LongBuffer longBuf = _buf.b.asLongBuffer(); - longBuf.put(v); - _buf.b.position(_buf.b.position() + v.length * 8); - } - } - - public void - writeLongSeq(int tag, Ice.Optional<long[]> v) - { - if(v != null && v.isSet()) - { - writeLongSeq(tag, v.get()); - } - } - - public void - writeLongSeq(int tag, long[] v) - { - if(writeOpt(tag, Ice.OptionalFormat.VSize)) - { - writeSize(v == null || v.length == 0 ? 1 : v.length * 8 + (v.length > 254 ? 5 : 1)); - writeLongSeq(v); - } - } - - public void - writeLongBuffer(java.nio.LongBuffer v) - { - if(v == null || v.remaining() == 0) - { - writeSize(0); - } - else - { - int sz = v.remaining(); - writeSize(sz); - expand(sz * 8); - - java.nio.LongBuffer longBuf = _buf.b.asLongBuffer(); - longBuf.put(v); - _buf.b.position(_buf.b.position() + sz * 8); - } - } - - public long - readLong() - { - try - { - return _buf.b.getLong(); - } - catch(java.nio.BufferUnderflowException ex) - { - throw new Ice.UnmarshalOutOfBoundsException(); - } - } - - public void - readLong(int tag, Ice.LongOptional v) - { - if(readOpt(tag, Ice.OptionalFormat.F8)) - { - v.set(readLong()); - } - else - { - v.clear(); - } - } - - public long[] - readLongSeq() - { - try - { - final int sz = readAndCheckSeqSize(8); - long[] v = new long[sz]; - java.nio.LongBuffer longBuf = _buf.b.asLongBuffer(); - longBuf.get(v); - _buf.b.position(_buf.b.position() + sz * 8); - return v; - } - catch(java.nio.BufferUnderflowException ex) - { - throw new Ice.UnmarshalOutOfBoundsException(); - } - } - - public void - readLongSeq(int tag, Ice.Optional<long[]> v) - { - if(readOpt(tag, Ice.OptionalFormat.VSize)) - { - skipSize(); - v.set(readLongSeq()); - } - else - { - v.clear(); - } - } - - public java.nio.LongBuffer - readLongBuffer() - { - try - { - final int sz = readAndCheckSeqSize(8); - java.nio.LongBuffer longBuf = _buf.b.asLongBuffer(); - java.nio.LongBuffer v = longBuf.slice(); - v.limit(sz); - _buf.b.position(_buf.b.position() + sz * 8); - return v.asReadOnlyBuffer(); - } - catch(java.nio.BufferUnderflowException ex) - { - throw new Ice.UnmarshalOutOfBoundsException(); - } - } - - public void - writeFloat(float v) - { - expand(4); - _buf.b.putFloat(v); - } - - public void - writeFloat(int tag, Ice.FloatOptional v) - { - if(v != null && v.isSet()) - { - writeFloat(tag, v.get()); - } - } - - public void - writeFloat(int tag, float v) - { - if(writeOpt(tag, Ice.OptionalFormat.F4)) - { - writeFloat(v); - } - } - - public void - writeFloatSeq(float[] v) - { - if(v == null) - { - writeSize(0); - } - else - { - writeSize(v.length); - expand(v.length * 4); - java.nio.FloatBuffer floatBuf = _buf.b.asFloatBuffer(); - floatBuf.put(v); - _buf.b.position(_buf.b.position() + v.length * 4); - } - } - - public void - writeFloatSeq(int tag, Ice.Optional<float[]> v) - { - if(v != null && v.isSet()) - { - writeFloatSeq(tag, v.get()); - } - } - - public void - writeFloatSeq(int tag, float[] v) - { - if(writeOpt(tag, Ice.OptionalFormat.VSize)) - { - writeSize(v == null || v.length == 0 ? 1 : v.length * 4 + (v.length > 254 ? 5 : 1)); - writeFloatSeq(v); - } - } - - public void - writeFloatBuffer(java.nio.FloatBuffer v) - { - if(v == null || v.remaining() == 0) - { - writeSize(0); - } - else - { - int sz = v.remaining(); - writeSize(sz); - expand(sz * 4); - - java.nio.FloatBuffer floatBuf = _buf.b.asFloatBuffer(); - floatBuf.put(v); - _buf.b.position(_buf.b.position() + sz * 4); - } - } - - public float - readFloat() - { - try - { - return _buf.b.getFloat(); - } - catch(java.nio.BufferUnderflowException ex) - { - throw new Ice.UnmarshalOutOfBoundsException(); - } - } - - public void - readFloat(int tag, Ice.FloatOptional v) - { - if(readOpt(tag, Ice.OptionalFormat.F4)) - { - v.set(readFloat()); - } - else - { - v.clear(); - } - } - - public float[] - readFloatSeq() - { - try - { - final int sz = readAndCheckSeqSize(4); - float[] v = new float[sz]; - java.nio.FloatBuffer floatBuf = _buf.b.asFloatBuffer(); - floatBuf.get(v); - _buf.b.position(_buf.b.position() + sz * 4); - return v; - } - catch(java.nio.BufferUnderflowException ex) - { - throw new Ice.UnmarshalOutOfBoundsException(); - } - } - - public void - readFloatSeq(int tag, Ice.Optional<float[]> v) - { - if(readOpt(tag, Ice.OptionalFormat.VSize)) - { - skipSize(); - v.set(readFloatSeq()); - } - else - { - v.clear(); - } - } - - public java.nio.FloatBuffer - readFloatBuffer() - { - try - { - final int sz = readAndCheckSeqSize(4); - java.nio.FloatBuffer floatBuf = _buf.b.asFloatBuffer(); - java.nio.FloatBuffer v = floatBuf.slice(); - v.limit(sz); - _buf.b.position(_buf.b.position() + sz * 4); - return v.asReadOnlyBuffer(); - } - catch(java.nio.BufferUnderflowException ex) - { - throw new Ice.UnmarshalOutOfBoundsException(); - } - } - - public void - writeDouble(double v) - { - expand(8); - _buf.b.putDouble(v); - } - - public void - writeDouble(int tag, Ice.DoubleOptional v) - { - if(v != null && v.isSet()) - { - writeDouble(tag, v.get()); - } - } - - public void - writeDouble(int tag, double v) - { - if(writeOpt(tag, Ice.OptionalFormat.F8)) - { - writeDouble(v); - } - } - - public void - writeDoubleSeq(double[] v) - { - if(v == null) - { - writeSize(0); - } - else - { - writeSize(v.length); - expand(v.length * 8); - java.nio.DoubleBuffer doubleBuf = _buf.b.asDoubleBuffer(); - doubleBuf.put(v); - _buf.b.position(_buf.b.position() + v.length * 8); - } - } - - public void - writeDoubleSeq(int tag, Ice.Optional<double[]> v) - { - if(v != null && v.isSet()) - { - writeDoubleSeq(tag, v.get()); - } - } - - public void - writeDoubleSeq(int tag, double[] v) - { - if(writeOpt(tag, Ice.OptionalFormat.VSize)) - { - writeSize(v == null || v.length == 0 ? 1 : v.length * 8 + (v.length > 254 ? 5 : 1)); - writeDoubleSeq(v); - } - } - - public void - writeDoubleBuffer(java.nio.DoubleBuffer v) - { - if(v == null || v.remaining() == 0) - { - writeSize(0); - } - else - { - int sz = v.remaining(); - writeSize(sz); - expand(sz * 8); - - java.nio.DoubleBuffer doubleBuf = _buf.b.asDoubleBuffer(); - doubleBuf.put(v); - _buf.b.position(_buf.b.position() + sz * 8); - } - } - - public double - readDouble() - { - try - { - return _buf.b.getDouble(); - } - catch(java.nio.BufferUnderflowException ex) - { - throw new Ice.UnmarshalOutOfBoundsException(); - } - } - - public void - readDouble(int tag, Ice.DoubleOptional v) - { - if(readOpt(tag, Ice.OptionalFormat.F8)) - { - v.set(readDouble()); - } - else - { - v.clear(); - } - } - - public double[] - readDoubleSeq() - { - try - { - final int sz = readAndCheckSeqSize(8); - double[] v = new double[sz]; - java.nio.DoubleBuffer doubleBuf = _buf.b.asDoubleBuffer(); - doubleBuf.get(v); - _buf.b.position(_buf.b.position() + sz * 8); - return v; - } - catch(java.nio.BufferUnderflowException ex) - { - throw new Ice.UnmarshalOutOfBoundsException(); - } - } - - public void - readDoubleSeq(int tag, Ice.Optional<double[]> v) - { - if(readOpt(tag, Ice.OptionalFormat.VSize)) - { - skipSize(); - v.set(readDoubleSeq()); - } - else - { - v.clear(); - } - } - - public java.nio.DoubleBuffer - readDoubleBuffer() - { - try - { - final int sz = readAndCheckSeqSize(8); - java.nio.DoubleBuffer doubleBuf = _buf.b.asDoubleBuffer(); - java.nio.DoubleBuffer v = doubleBuf.slice(); - v.limit(sz); - _buf.b.position(_buf.b.position() + sz * 8); - return v.asReadOnlyBuffer(); - } - catch(java.nio.BufferUnderflowException ex) - { - throw new Ice.UnmarshalOutOfBoundsException(); - } - } - - final static java.nio.charset.Charset _utf8 = java.nio.charset.Charset.forName("UTF8"); - private java.nio.charset.CharsetEncoder _charEncoder = null; - - public void - writeString(String v) - { - if(v == null) - { - writeSize(0); - } - else - { - final int len = v.length(); - if(len > 0) - { - if(_stringBytes == null || len > _stringBytes.length) - { - _stringBytes = new byte[len]; - } - if(_stringChars == null || len > _stringChars.length) - { - _stringChars = new char[len]; - } - // - // If the string contains only 7-bit characters, it's more efficient - // to perform the conversion to UTF-8 manually. - // - v.getChars(0, len, _stringChars, 0); - for(int i = 0; i < len; ++i) - { - if(_stringChars[i] > (char)127) - { - // - // Found a multibyte character. - // - if(_charEncoder == null) - { - _charEncoder = _utf8.newEncoder(); - } - java.nio.ByteBuffer b = null; - try - { - b = _charEncoder.encode(java.nio.CharBuffer.wrap(_stringChars, 0, len)); - } - catch(java.nio.charset.CharacterCodingException ex) - { - throw new Ice.MarshalException(ex); - } - writeSize(b.limit()); - expand(b.limit()); - _buf.b.put(b); - return; - } - _stringBytes[i] = (byte)_stringChars[i]; - } - writeSize(len); - expand(len); - _buf.b.put(_stringBytes, 0, len); - } - else - { - writeSize(0); - } - } - } - - public void - writeString(int tag, Ice.Optional<String> v) - { - if(v != null && v.isSet()) - { - writeString(tag, v.get()); - } - } - - public void - writeString(int tag, String v) - { - if(writeOpt(tag, Ice.OptionalFormat.VSize)) - { - writeString(v); - } - } - - public void - writeStringSeq(String[] v) - { - if(v == null) - { - writeSize(0); - } - else - { - writeSize(v.length); - for(String e : v) - { - writeString(e); - } - } - } - - public void - writeStringSeq(int tag, Ice.Optional<String[]> v) - { - if(v != null && v.isSet()) - { - writeStringSeq(tag, v.get()); - } - } - - public void - writeStringSeq(int tag, String[] v) - { - if(writeOpt(tag, Ice.OptionalFormat.FSize)) - { - int pos = startSize(); - writeStringSeq(v); - endSize(pos); - } - } - - public String - readString() - { - final int len = readSize(); - - if(len == 0) - { - return ""; - } - else - { - // - // Check the buffer has enough bytes to read. - // - if(_buf.b.remaining() < len) - { - throw new Ice.UnmarshalOutOfBoundsException(); - } - - try - { - // - // We reuse the _stringBytes array to avoid creating - // excessive garbage. - // - if(_stringBytes == null || len > _stringBytes.length) - { - _stringBytes = new byte[len]; - } - if(_stringChars == null || len > _stringChars.length) - { - _stringChars = new char[len]; - } - _buf.b.get(_stringBytes, 0, len); - - // - // It's more efficient to construct a string using a - // character array instead of a byte array, because - // byte arrays require conversion. - // - for(int i = 0; i < len; i++) - { - if(_stringBytes[i] < 0) - { - // - // Multi-byte character found - we must use - // conversion. - // - // TODO: If the string contains garbage bytes - // that won't correctly decode as UTF, the - // behavior of this constructor is - // undefined. It would be better to explicitly - // decode using - // java.nio.charset.CharsetDecoder and to - // throw MarshalException if the string won't - // decode. - // - return new String(_stringBytes, 0, len, "UTF8"); - } - else - { - _stringChars[i] = (char)_stringBytes[i]; - } - } - return new String(_stringChars, 0, len); - } - catch(java.io.UnsupportedEncodingException ex) - { - assert(false); - return ""; - } - catch(java.nio.BufferUnderflowException ex) - { - throw new Ice.UnmarshalOutOfBoundsException(); - } - } - } - - public void - readString(int tag, Ice.Optional<String> v) - { - if(readOpt(tag, Ice.OptionalFormat.VSize)) - { - v.set(readString()); - } - else - { - v.clear(); - } - } - - public String[] - readStringSeq() - { - final int sz = readAndCheckSeqSize(1); - String[] v = new String[sz]; - for(int i = 0; i < sz; i++) - { - v[i] = readString(); - } - return v; - } - - public void - readStringSeq(int tag, Ice.Optional<String[]> v) - { - if(readOpt(tag, Ice.OptionalFormat.FSize)) - { - skip(4); - v.set(readStringSeq()); - } - else - { - v.clear(); - } - } - - public void - writeProxy(Ice.ObjectPrx v) - { - _instance.proxyFactory().proxyToStream(v, this); - } - - public void - writeProxy(int tag, Ice.Optional<Ice.ObjectPrx> v) - { - if(v != null && v.isSet()) - { - writeProxy(tag, v.get()); - } - } - - public void - writeProxy(int tag, Ice.ObjectPrx v) - { - if(writeOpt(tag, Ice.OptionalFormat.FSize)) - { - int pos = startSize(); - writeProxy(v); - endSize(pos); - } - } - - public Ice.ObjectPrx - readProxy() - { - return _instance.proxyFactory().streamToProxy(this); - } - - public void - readProxy(int tag, Ice.Optional<Ice.ObjectPrx> v) - { - if(readOpt(tag, Ice.OptionalFormat.FSize)) - { - skip(4); - v.set(readProxy()); - } - else - { - v.clear(); - } - } - - public void - writeEnum(int v, int maxValue) - { - if(isWriteEncoding_1_0()) - { - if(maxValue < 127) - { - writeByte((byte)v); - } - else if(maxValue < 32767) - { - writeShort((short)v); - } - else - { - writeInt(v); - } - } - else - { - writeSize(v); - } - } - - public int - readEnum(int maxValue) - { - if(getReadEncoding().equals(Ice.Util.Encoding_1_0)) - { - if(maxValue < 127) - { - return readByte(); - } - else if(maxValue < 32767) - { - return readShort(); - } - else - { - return readInt(); - } - } - else - { - return readSize(); - } - } - - public void - writeObject(Ice.Object v) - { - initWriteEncaps(); - _writeEncapsStack.encoder.writeObject(v); - } - - public <T extends Ice.Object> void - writeObject(int tag, Ice.Optional<T> v) - { - if(v != null && v.isSet()) - { - writeObject(tag, v.get()); - } - } - - public void - writeObject(int tag, Ice.Object v) - { - if(writeOpt(tag, Ice.OptionalFormat.Class)) - { - writeObject(v); - } - } - - public void - readObject(Patcher patcher) - { - initReadEncaps(); - _readEncapsStack.decoder.readObject(patcher); - } - - public void - readObject(int tag, Ice.Optional<Ice.Object> v) - { - if(readOpt(tag, Ice.OptionalFormat.Class)) - { - Ice.OptionalObject opt = new Ice.OptionalObject(v, Ice.Object.class, Ice.ObjectImpl.ice_staticId()); - readObject(opt); - } - else - { - v.clear(); - } - } - - public void - writeUserException(Ice.UserException e) - { - initWriteEncaps(); - _writeEncapsStack.encoder.writeUserException(e); - } - - public void - throwException(UserExceptionFactory factory) - throws Ice.UserException - { - initReadEncaps(); - _readEncapsStack.decoder.throwException(factory); - } - - public void - sliceObjects(boolean b) - { - _sliceObjects = b; - } - - public boolean - readOptImpl(int readTag, Ice.OptionalFormat expectedFormat) - { - if(isReadEncoding_1_0()) - { - return false; // Optional members aren't supported with the 1.0 encoding. - } - - while(true) - { - if(_buf.b.position() >= _readEncapsStack.start + _readEncapsStack.sz) - { - return false; // End of encapsulation also indicates end of optionals. - } - - final byte b = readByte(); - final int v = b < 0 ? b + 256 : b; - if(v == OPTIONAL_END_MARKER) - { - _buf.b.position(_buf.b.position() - 1); // Rewind. - return false; - } - - Ice.OptionalFormat format = Ice.OptionalFormat.valueOf(v & 0x07); // First 3 bits. - int tag = v >> 3; - if(tag == 30) - { - tag = readSize(); - } - - if(tag > readTag) - { - int offset = tag < 30 ? 1 : (tag < 255 ? 2 : 6); // Rewind - _buf.b.position(_buf.b.position() - offset); - return false; // No optional data members with the requested tag. - } - else if(tag < readTag) - { - skipOpt(format); // Skip optional data members - } - else - { - if(format != expectedFormat) - { - throw new Ice.MarshalException("invalid optional data member `" + tag + "': unexpected format"); - } - return true; - } - } - } - - public boolean - writeOptImpl(int tag, Ice.OptionalFormat format) - { - if(isWriteEncoding_1_0()) - { - return false; // Optional members aren't supported with the 1.0 encoding. - } - - int v = format.value(); - if(tag < 30) - { - v |= tag << 3; - writeByte((byte)v); - } - else - { - v |= 0x0F0; // tag = 30 - writeByte((byte)v); - writeSize(tag); - } - return true; - } - - public void - skipOpt(Ice.OptionalFormat format) - { - switch(format) - { - case F1: - { - skip(1); - break; - } - case F2: - { - skip(2); - break; - } - case F4: - { - skip(4); - break; - } - case F8: - { - skip(8); - break; - } - case Size: - { - skipSize(); - break; - } - case VSize: - { - skip(readSize()); - break; - } - case FSize: - { - skip(readInt()); - break; - } - case Class: - { - readObject(null); - break; - } - } - } - - public void - skipOpts() - { - // - // Skip remaining un-read optional members. - // - while(true) - { - if(_buf.b.position() >= _readEncapsStack.start + _readEncapsStack.sz) - { - return; // End of encapsulation also indicates end of optionals. - } - - final byte b = readByte(); - final int v = b < 0 ? b + 256 : b; - if(v == OPTIONAL_END_MARKER) - { - return; - } - - Ice.OptionalFormat format = Ice.OptionalFormat.valueOf(v & 0x07); // Read first 3 bits. - if((v >> 3) == 30) - { - skipSize(); - } - skipOpt(format); - } - } - - public void - skip(int size) - { - if(size > _buf.b.remaining()) - { - throw new Ice.UnmarshalOutOfBoundsException(); - } - _buf.b.position(_buf.b.position() + size); - } - - public void - skipSize() - { - byte b = readByte(); - if(b == -1) - { - skip(4); - } - } - - public int - pos() - { - return _buf.b.position(); - } - - public void - pos(int n) - { - _buf.b.position(n); - } - - public int - size() - { - return _buf.size(); - } - - public boolean - isEmpty() - { - return _buf.empty(); - } - - private static class BufferedOutputStream extends java.io.OutputStream - { - BufferedOutputStream(byte[] data) - { - _data = data; - } - - @Override - public void - close() - throws java.io.IOException - { - } - - @Override - public void - flush() - throws java.io.IOException - { - } - - @Override - public void - write(byte[] b) - throws java.io.IOException - { - assert(_data.length - _pos >= b.length); - System.arraycopy(b, 0, _data, _pos, b.length); - _pos += b.length; - } - - @Override - public void - write(byte[] b, int off, int len) - throws java.io.IOException - { - assert(_data.length - _pos >= len); - System.arraycopy(b, off, _data, _pos, len); - _pos += len; - } - - @Override - public void - write(int b) - throws java.io.IOException - { - assert(_data.length - _pos >= 1); - _data[_pos] = (byte)b; - ++_pos; - } - - int - pos() - { - return _pos; - } - - private byte[] _data; - private int _pos; - } - - public BasicStream - compress(int headerSize, int compressionLevel) - { - assert(compressible()); - - int uncompressedLen = size() - headerSize; - int compressedLen = (int)(uncompressedLen * 1.01 + 600); - byte[] compressed = new byte[compressedLen]; - - byte[] data = null; - int offset = 0; - try - { - // - // If the ByteBuffer is backed by an array then we can avoid - // an extra copy by using the array directly. - // - data = _buf.b.array(); - offset = _buf.b.arrayOffset(); - } - catch(Exception ex) - { - // - // Otherwise, allocate an array to hold a copy of the uncompressed data. - // - data = new byte[size()]; - pos(0); - _buf.b.get(data); - } - - try - { - // - // Compress the data using the class org.apache.tools.bzip2.CBZip2OutputStream. - // Its constructor requires an OutputStream argument, therefore we pass the - // compressed BasicStream in an OutputStream wrapper. - // - BufferedOutputStream bos = new BufferedOutputStream(compressed); - // - // For interoperability with the bzip2 C library, we insert the magic bytes - // 'B', 'Z' before invoking the Java implementation. - // - bos.write('B'); - bos.write('Z'); - java.lang.Object[] args = new java.lang.Object[]{ bos, Integer.valueOf(compressionLevel) }; - java.io.OutputStream os = (java.io.OutputStream)_bzOutputStreamCtor.newInstance(args); - os.write(data, offset + headerSize, uncompressedLen); - os.close(); - compressedLen = bos.pos(); - } - catch(Exception ex) - { - throw new Ice.CompressionException("bzip2 compression failure", ex); - } - - // - // Don't bother if the compressed data is larger than the - // uncompressed data. - // - if(compressedLen >= uncompressedLen) - { - return null; - } - - BasicStream cstream = new BasicStream(_instance, _encoding); - cstream.resize(headerSize + 4 + compressedLen, false); - cstream.pos(0); - - // - // Copy the header from the uncompressed stream to the - // compressed one. - // - cstream._buf.b.put(data, offset, headerSize); - - // - // Add the size of the uncompressed stream before the - // message body. - // - cstream.writeInt(size()); - - // - // Add the compressed message body. - // - cstream._buf.b.put(compressed, 0, compressedLen); - - return cstream; - } - - public BasicStream - uncompress(int headerSize, int messageSizeMax) - { - assert(compressible()); - - pos(headerSize); - int uncompressedSize = readInt(); - if(uncompressedSize <= headerSize) - { - throw new Ice.IllegalMessageSizeException(); - } - if(uncompressedSize > messageSizeMax) - { - IceInternal.Ex.throwMemoryLimitException(uncompressedSize, messageSizeMax); - } - - int compressedLen = size() - headerSize - 4; - - byte[] compressed = null; - int offset = 0; - try - { - // - // If the ByteBuffer is backed by an array then we can avoid - // an extra copy by using the array directly. - // - compressed = _buf.b.array(); - offset = _buf.b.arrayOffset(); - } - catch(Exception ex) - { - // - // Otherwise, allocate an array to hold a copy of the compressed data. - // - compressed = new byte[size()]; - pos(0); - _buf.b.get(compressed); - } - - BasicStream ucStream = new BasicStream(_instance, _encoding); - ucStream.resize(uncompressedSize, false); - - try - { - // - // Uncompress the data using the class org.apache.tools.bzip2.CBZip2InputStream. - // Its constructor requires an InputStream argument, therefore we pass the - // compressed data in a ByteArrayInputStream. - // - java.io.ByteArrayInputStream bais = - new java.io.ByteArrayInputStream(compressed, offset + headerSize + 4, compressedLen); - // - // For interoperability with the bzip2 C library, we insert the magic bytes - // 'B', 'Z' during compression and therefore must extract them before we - // invoke the Java implementation. - // - byte magicB = (byte)bais.read(); - byte magicZ = (byte)bais.read(); - if(magicB != (byte)'B' || magicZ != (byte)'Z') - { - Ice.CompressionException e = new Ice.CompressionException(); - e.reason = "bzip2 uncompression failure: invalid magic bytes"; - throw e; - } - java.lang.Object[] args = new java.lang.Object[]{ bais }; - java.io.InputStream is = (java.io.InputStream)_bzInputStreamCtor.newInstance(args); - ucStream.pos(headerSize); - byte[] arr = new byte[8 * 1024]; - int n; - while((n = is.read(arr)) != -1) - { - ucStream.writeBlob(arr, 0, n); - } - is.close(); - } - catch(Exception ex) - { - throw new Ice.CompressionException("bzip2 uncompression failure", ex); - } - - // - // Copy the header from the compressed stream to the uncompressed one. - // - ucStream.pos(0); - ucStream._buf.b.put(compressed, offset, headerSize); - - return ucStream; - } - - public void - expand(int n) - { - _buf.expand(n); - } - - private Ice.Object - createObject(String id) - { - Ice.Object obj = null; - - try - { - Class<?> c = findClass(id); - if(c != null) - { - obj = (Ice.Object)c.newInstance(); - } - } - catch(java.lang.Exception ex) - { - throw new Ice.NoValueFactoryException("no value factory", id, ex); - } - - return obj; - } - - private String - getTypeId(int compactId) - { - String className = "IceCompactId.TypeId_" + Integer.toString(compactId); - Class<?> c = getConcreteClass(className); - if(c == null) - { - for(String pkg : _instance.getPackages()) - { - c = getConcreteClass(pkg + "." + className); - if(c != null) - { - break; - } - } - } - if(c != null) - { - try - { - return (String)c.getField("typeId").get(null); - } - catch(Exception ex) - { - assert(false); - } - } - return ""; - } - - private Ice.UserException - createUserException(String id) - { - Ice.UserException userEx = null; - - try - { - Class<?> c = findClass(id); - if(c != null) - { - userEx = (Ice.UserException)c.newInstance(); - } - } - catch(java.lang.Exception ex) - { - throw new Ice.MarshalException(ex); - } - - return userEx; - } - - private Class<?> - findClass(String id) - throws LinkageError - { - Class<?> c = null; - - // - // To convert a Slice type id into a Java class, we do the following: - // - // 1. Convert the Slice type id into a classname (e.g., ::M::X -> M.X). - // 2. If that fails, extract the top-level module (if any) from the type id - // and check for an Ice.Package property. If found, prepend the property - // value to the classname. - // 3. If that fails, check for an Ice.Default.Package property. If found, - // prepend the property value to the classname. - // - String className = _instance.getClassForType(id); - boolean addClass = false; - if(className == null) - { - className = typeToClass(id); - addClass = true; - } - - c = getConcreteClass(className); - if(c == null) - { - int pos = id.indexOf(':', 2); - if(pos != -1) - { - String topLevelModule = id.substring(2, pos); - String pkg = _instance.initializationData().properties.getProperty("Ice.Package." + topLevelModule); - if(pkg.length() > 0) - { - c = getConcreteClass(pkg + "." + className); - } - } - } - - if(c == null) - { - String pkg = _instance.initializationData().properties.getProperty("Ice.Default.Package"); - if(pkg.length() > 0) - { - c = getConcreteClass(pkg + "." + className); - } - } - - if(c != null && addClass) - { - _instance.addClassForType(id, c.getName()); - } - - return c; - } - - private Class<?> - getConcreteClass(String className) - throws LinkageError - { - Class<?> c = _instance.findClass(className); - - if(c != null) - { - // - // Ensure the class is instantiable. The constants are - // defined in the JVM specification (0x200 = interface, - // 0x400 = abstract). - // - int modifiers = c.getModifiers(); - if((modifiers & 0x200) == 0 && (modifiers & 0x400) == 0) - { - return c; - } - } - - return null; - } - - private static String - fixKwd(String name) - { - // - // Keyword list. *Must* be kept in alphabetical order. Note that checkedCast and uncheckedCast - // are not Java keywords, but are in this list to prevent illegal code being generated if - // someone defines Slice operations with that name. - // - final String[] keywordList = - { - "abstract", "assert", "boolean", "break", "byte", "case", "catch", - "char", "checkedCast", "class", "clone", "const", "continue", "default", "do", - "double", "else", "enum", "equals", "extends", "false", "final", "finalize", - "finally", "float", "for", "getClass", "goto", "hashCode", "if", - "implements", "import", "instanceof", "int", "interface", "long", - "native", "new", "notify", "notifyAll", "null", "package", "private", - "protected", "public", "return", "short", "static", "strictfp", "super", "switch", - "synchronized", "this", "throw", "throws", "toString", "transient", - "true", "try", "uncheckedCast", "void", "volatile", "wait", "while" - }; - boolean found = java.util.Arrays.binarySearch(keywordList, name) >= 0; - return found ? "_" + name : name; - } - - private String - typeToClass(String id) - { - if(!id.startsWith("::")) - { - throw new Ice.MarshalException("expected type id but received `" + id + "'"); - } - - StringBuilder buf = new StringBuilder(id.length()); - - int start = 2; - boolean done = false; - while(!done) - { - int end = id.indexOf(':', start); - String s; - if(end != -1) - { - s = id.substring(start, end); - start = end + 2; - } - else - { - s = id.substring(start); - done = true; - } - if(buf.length() > 0) - { - buf.append('.'); - } - buf.append(fixKwd(s)); - } - - return buf.toString(); - } - - private Instance _instance; - private Buffer _buf; - private Object _closure; - private byte[] _stringBytes; // Reusable array for reading strings. - private char[] _stringChars; // Reusable array for reading strings. - - private enum SliceType { NoSlice, ObjectSlice, ExceptionSlice } - - abstract private static class EncapsDecoder - { - EncapsDecoder(BasicStream stream, boolean sliceObjects, Ice.ValueFactoryManager f) - { - _stream = stream; - _sliceObjects = sliceObjects; - _valueFactoryManager = f; - _typeIdIndex = 0; - _unmarshaledMap = new java.util.TreeMap<Integer, Ice.Object>(); - } - - abstract void readObject(Patcher patcher); - abstract void throwException(UserExceptionFactory factory) - throws Ice.UserException; - - abstract void startInstance(SliceType type); - abstract Ice.SlicedData endInstance(boolean preserve); - abstract String startSlice(); - abstract void endSlice(); - abstract void skipSlice(); - - boolean - readOpt(int tag, Ice.OptionalFormat format) - { - return false; - } - - void - readPendingObjects() - { - } - - protected String - readTypeId(boolean isIndex) - { - if(_typeIdMap == null) // Lazy initialization - { - _typeIdMap = new java.util.TreeMap<Integer, String>(); - } - - if(isIndex) - { - int index = _stream.readSize(); - String typeId = _typeIdMap.get(index); - if(typeId == null) - { - throw new Ice.UnmarshalOutOfBoundsException(); - } - return typeId; - } - else - { - String typeId = _stream.readString(); - _typeIdMap.put(++_typeIdIndex, typeId); - return typeId; - } - } - - protected Ice.Object - newInstance(String typeId) - { - // - // Try to find a factory registered for the specific type. - // - Ice.ValueFactory userFactory = _valueFactoryManager.find(typeId); - Ice.Object v = null; - if(userFactory != null) - { - v = userFactory.create(typeId); - } - - // - // If that fails, invoke the default factory if one has been - // registered. - // - if(v == null) - { - userFactory = _valueFactoryManager.find(""); - if(userFactory != null) - { - v = userFactory.create(typeId); - } - } - - // - // Last chance: try to instantiate the class dynamically. - // - if(v == null) - { - v = _stream.createObject(typeId); - } - - return v; - } - - protected void - addPatchEntry(int index, Patcher patcher) - { - assert(index > 0); - - // - // Check if already un-marshalled the object. If that's the case, - // just patch the object smart pointer and we're done. - // - Ice.Object obj = _unmarshaledMap.get(index); - if(obj != null) - { - patcher.patch(obj); - return; - } - - if(_patchMap == null) // Lazy initialization - { - _patchMap = new java.util.TreeMap<Integer, java.util.LinkedList<Patcher> >(); - } - - // - // Add patch entry if the object isn't un-marshalled yet, - // the smart pointer will be patched when the instance is - // un-marshalled. - // - java.util.LinkedList<Patcher> l = _patchMap.get(index); - if(l == null) - { - // - // We have no outstanding instances to be patched for this - // index, so make a new entry in the patch map. - // - l = new java.util.LinkedList<Patcher>(); - _patchMap.put(index, l); - } - - // - // Append a patch entry for this instance. - // - l.add(patcher); - } - - protected void - unmarshal(int index, Ice.Object v) - { - // - // Add the object to the map of un-marshalled objects, this must - // be done before reading the objects (for circular references). - // - _unmarshaledMap.put(index, v); - - // - // Read the object. - // - v.__read(_stream); - - if(_patchMap != null) - { - // - // Patch all instances now that the object is un-marshalled. - // - java.util.LinkedList<Patcher> l = _patchMap.get(index); - if(l != null) - { - assert(l.size() > 0); - - // - // Patch all pointers that refer to the instance. - // - for(Patcher p : l) - { - p.patch(v); - } - - // - // Clear out the patch map for that index -- there is nothing left - // to patch for that index for the time being. - // - _patchMap.remove(index); - } - } - - if((_patchMap == null || _patchMap.isEmpty()) && _objectList == null) - { - try - { - v.ice_postUnmarshal(); - } - catch(java.lang.Exception ex) - { - String s = "exception raised by ice_postUnmarshal:\n" + Ex.toString(ex); - _stream.instance().initializationData().logger.warning(s); - } - } - else - { - if(_objectList == null) // Lazy initialization - { - _objectList = new java.util.ArrayList<Ice.Object>(); - } - _objectList.add(v); - - if(_patchMap == null || _patchMap.isEmpty()) - { - // - // Iterate over the object list and invoke ice_postUnmarshal on - // each object. We must do this after all objects have been - // unmarshaled in order to ensure that any object data members - // have been properly patched. - // - for(Ice.Object p : _objectList) - { - try - { - p.ice_postUnmarshal(); - } - catch(java.lang.Exception ex) - { - String s = "exception raised by ice_postUnmarshal:\n" + Ex.toString(ex); - _stream.instance().initializationData().logger.warning(s); - } - } - _objectList.clear(); - } - } - } - - protected final BasicStream _stream; - protected final boolean _sliceObjects; - protected Ice.ValueFactoryManager _valueFactoryManager; - - // Encapsulation attributes for object un-marshalling - protected java.util.TreeMap<Integer, java.util.LinkedList<Patcher> > _patchMap; - - // Encapsulation attributes for object un-marshalling - private java.util.TreeMap<Integer, Ice.Object> _unmarshaledMap; - private java.util.TreeMap<Integer, String> _typeIdMap; - private int _typeIdIndex; - private java.util.List<Ice.Object> _objectList; - } - - private static final class EncapsDecoder10 extends EncapsDecoder - { - EncapsDecoder10(BasicStream stream, boolean sliceObjects, Ice.ValueFactoryManager f) - { - super(stream, sliceObjects, f); - _sliceType = SliceType.NoSlice; - } - - @Override - void readObject(Patcher patcher) - { - assert(patcher != null); - - // - // Object references are encoded as a negative integer in 1.0. - // - int index = _stream.readInt(); - if(index > 0) - { - throw new Ice.MarshalException("invalid object id"); - } - index = -index; - - if(index == 0) - { - patcher.patch(null); - } - else - { - addPatchEntry(index, patcher); - } - } - - @Override - void throwException(UserExceptionFactory factory) - throws Ice.UserException - { - assert(_sliceType == SliceType.NoSlice); - - // - // User exception with the 1.0 encoding start with a boolean flag - // that indicates whether or not the exception has classes. - // - // This allows reading the pending objects even if some part of - // the exception was sliced. - // - boolean usesClasses = _stream.readBool(); - - _sliceType = SliceType.ExceptionSlice; - _skipFirstSlice = false; - - // - // Read the first slice header. - // - startSlice(); - final String mostDerivedId = _typeId; - while(true) - { - Ice.UserException userEx = null; - - // - // Use a factory if one was provided. - // - if(factory != null) - { - try - { - factory.createAndThrow(_typeId); - } - catch(Ice.UserException ex) - { - userEx = ex; - } - } - - if(userEx == null) - { - userEx = _stream.createUserException(_typeId); - } - - // - // We found the exception. - // - if(userEx != null) - { - userEx.__read(_stream); - if(usesClasses) - { - readPendingObjects(); - } - throw userEx; - - // Never reached. - } - - // - // Slice off what we don't understand. - // - skipSlice(); - try - { - startSlice(); - } - catch(Ice.UnmarshalOutOfBoundsException ex) - { - // - // An oversight in the 1.0 encoding means there is no marker to indicate - // the last slice of an exception. As a result, we just try to read the - // next type ID, which raises UnmarshalOutOfBoundsException when the - // input buffer underflows. - // - // Set the reason member to a more helpful message. - // - ex.reason = "unknown exception type `" + mostDerivedId + "'"; - throw ex; - } - } - } - - @Override - void startInstance(SliceType sliceType) - { - assert(_sliceType == sliceType); - _skipFirstSlice = true; - } - - @Override - Ice.SlicedData endInstance(boolean preserve) - { - // - // Read the Ice::Object slice. - // - if(_sliceType == SliceType.ObjectSlice) - { - startSlice(); - int sz = _stream.readSize(); // For compatibility with the old AFM. - if(sz != 0) - { - throw new Ice.MarshalException("invalid Object slice"); - } - endSlice(); - } - - _sliceType = SliceType.NoSlice; - return null; - } - - @Override - String startSlice() - { - // - // If first slice, don't read the header, it was already read in - // readInstance or throwException to find the factory. - // - if(_skipFirstSlice) - { - _skipFirstSlice = false; - return _typeId; - } - - // - // For objects, first read the type ID boolean which indicates - // whether or not the type ID is encoded as a string or as an - // index. For exceptions, the type ID is always encoded as a - // string. - // - if(_sliceType == SliceType.ObjectSlice) // For exceptions, the type ID is always encoded as a string - { - boolean isIndex = _stream.readBool(); - _typeId = readTypeId(isIndex); - } - else - { - _typeId = _stream.readString(); - } - - _sliceSize = _stream.readInt(); - if(_sliceSize < 4) - { - throw new Ice.UnmarshalOutOfBoundsException(); - } - - return _typeId; - } - - @Override - void endSlice() - { - } - - @Override - void skipSlice() - { - if(_stream.instance().traceLevels().slicing > 0) - { - Ice.Logger logger = _stream.instance().initializationData().logger; - if(_sliceType == SliceType.ObjectSlice) - { - TraceUtil.traceSlicing("object", _typeId, _stream.instance().traceLevels().slicingCat, logger); - } - else - { - TraceUtil.traceSlicing("exception", _typeId, _stream.instance().traceLevels().slicingCat, logger); - } - } - - assert(_sliceSize >= 4); - _stream.skip(_sliceSize - 4); - } - - @Override - void readPendingObjects() - { - int num; - do - { - num = _stream.readSize(); - for(int k = num; k > 0; --k) - { - readInstance(); - } - } - while(num > 0); - - if(_patchMap != null && !_patchMap.isEmpty()) - { - // - // If any entries remain in the patch map, the sender has sent an index for an object, but failed - // to supply the object. - // - throw new Ice.MarshalException("index for class received, but no instance"); - } - } - - private void readInstance() - { - int index = _stream.readInt(); - - if(index <= 0) - { - throw new Ice.MarshalException("invalid object id"); - } - - _sliceType = SliceType.ObjectSlice; - _skipFirstSlice = false; - - // - // Read the first slice header. - // - startSlice(); - final String mostDerivedId = _typeId; - Ice.Object v = null; - while(true) - { - // - // For the 1.0 encoding, the type ID for the base Object class - // marks the last slice. - // - if(_typeId.equals(Ice.ObjectImpl.ice_staticId())) - { - throw new Ice.NoValueFactoryException("", mostDerivedId); - } - - v = newInstance(_typeId); - - // - // We found a factory, we get out of this loop. - // - if(v != null) - { - break; - } - - // - // If object slicing is disabled, stop un-marshalling. - // - if(!_sliceObjects) - { - throw new Ice.NoValueFactoryException("no value factory found and object slicing is disabled", - _typeId); - } - - // - // Slice off what we don't understand. - // - skipSlice(); - startSlice(); // Read next Slice header for next iteration. - } - - // - // Un-marshal the object and add-it to the map of un-marshaled objects. - // - unmarshal(index, v); - } - - // Object/exception attributes - private SliceType _sliceType; - private boolean _skipFirstSlice; - - // Slice attributes - private int _sliceSize; - private String _typeId; - } - - private static class EncapsDecoder11 extends EncapsDecoder - { - EncapsDecoder11(BasicStream stream, boolean sliceObjects, Ice.ValueFactoryManager f) - { - super(stream, sliceObjects, f); - _objectIdIndex = 1; - _current = null; - } - - @Override - void readObject(Patcher patcher) - { - int index = _stream.readSize(); - if(index < 0) - { - throw new Ice.MarshalException("invalid object id"); - } - else if(index == 0) - { - if(patcher != null) - { - patcher.patch(null); - } - } - else if(_current != null && (_current.sliceFlags & FLAG_HAS_INDIRECTION_TABLE) != 0) - { - // - // When reading an object within a slice and there's an - // indirect object table, always read an indirect reference - // that points to an object from the indirect object table - // marshaled at the end of the Slice. - // - // Maintain a list of indirect references. Note that the - // indirect index starts at 1, so we decrement it by one to - // derive an index into the indirection table that we'll read - // at the end of the slice. - // - if(patcher != null) - { - if(_current.indirectPatchList == null) // Lazy initialization - { - _current.indirectPatchList = new java.util.ArrayDeque<IndirectPatchEntry>(); - } - IndirectPatchEntry e = new IndirectPatchEntry(); - e.index = index - 1; - e.patcher = patcher; - _current.indirectPatchList.push(e); - } - } - else - { - readInstance(index, patcher); - } - } - - @Override - void throwException(UserExceptionFactory factory) - throws Ice.UserException - { - assert(_current == null); - - push(SliceType.ExceptionSlice); - - // - // Read the first slice header. - // - startSlice(); - final String mostDerivedId = _current.typeId; - while(true) - { - Ice.UserException userEx = null; - - // - // Use a factory if one was provided. - // - if(factory != null) - { - try - { - factory.createAndThrow(_current.typeId); - } - catch(Ice.UserException ex) - { - userEx = ex; - } - } - - if(userEx == null) - { - userEx = _stream.createUserException(_current.typeId); - } - - // - // We found the exception. - // - if(userEx != null) - { - userEx.__read(_stream); - throw userEx; - - // Never reached. - } - - // - // Slice off what we don't understand. - // - skipSlice(); - - if((_current.sliceFlags & FLAG_IS_LAST_SLICE) != 0) - { - if(mostDerivedId.startsWith("::")) - { - throw new Ice.UnknownUserException(mostDerivedId.substring(2)); - } - else - { - throw new Ice.UnknownUserException(mostDerivedId); - } - } - - startSlice(); - } - } - - @Override - void startInstance(SliceType sliceType) - { - assert(_current.sliceType == sliceType); - _current.skipFirstSlice = true; - } - - @Override - Ice.SlicedData endInstance(boolean preserve) - { - Ice.SlicedData slicedData = null; - if(preserve) - { - slicedData = readSlicedData(); - } - if(_current.slices != null) - { - _current.slices.clear(); - _current.indirectionTables.clear(); - } - _current = _current.previous; - return slicedData; - } - - @Override - String startSlice() - { - // - // If first slice, don't read the header, it was already read in - // readInstance or throwException to find the factory. - // - if(_current.skipFirstSlice) - { - _current.skipFirstSlice = false; - return _current.typeId; - } - - _current.sliceFlags = _stream.readByte(); - - // - // Read the type ID, for object slices the type ID is encoded as a - // string or as an index, for exceptions it's always encoded as a - // string. - // - if(_current.sliceType == SliceType.ObjectSlice) - { - if((_current.sliceFlags & FLAG_HAS_TYPE_ID_COMPACT) == FLAG_HAS_TYPE_ID_COMPACT) // Must be checked 1st! - { - _current.typeId = ""; - _current.compactId = _stream.readSize(); - } - else if((_current.sliceFlags & (FLAG_HAS_TYPE_ID_INDEX | FLAG_HAS_TYPE_ID_STRING)) != 0) - { - _current.typeId = readTypeId((_current.sliceFlags & FLAG_HAS_TYPE_ID_INDEX) != 0); - _current.compactId = -1; - } - else - { - // Only the most derived slice encodes the type ID for the compact format. - _current.typeId = ""; - _current.compactId = -1; - } - } - else - { - _current.typeId = _stream.readString(); - _current.compactId = -1; - } - - // - // Read the slice size if necessary. - // - if((_current.sliceFlags & FLAG_HAS_SLICE_SIZE) != 0) - { - _current.sliceSize = _stream.readInt(); - if(_current.sliceSize < 4) - { - throw new Ice.UnmarshalOutOfBoundsException(); - } - } - else - { - _current.sliceSize = 0; - } - - return _current.typeId; - } - - @Override - void endSlice() - { - if((_current.sliceFlags & FLAG_HAS_OPTIONAL_MEMBERS) != 0) - { - _stream.skipOpts(); - } - - // - // Read the indirection table if one is present and transform the - // indirect patch list into patch entries with direct references. - // - if((_current.sliceFlags & FLAG_HAS_INDIRECTION_TABLE) != 0) - { - // - // The table is written as a sequence<size> to conserve space. - // - int[] indirectionTable = new int[_stream.readAndCheckSeqSize(1)]; - for(int i = 0; i < indirectionTable.length; ++i) - { - indirectionTable[i] = readInstance(_stream.readSize(), null); - } - - // - // Sanity checks. If there are optional members, it's possible - // that not all object references were read if they are from - // unknown optional data members. - // - if(indirectionTable.length == 0) - { - throw new Ice.MarshalException("empty indirection table"); - } - if((_current.indirectPatchList == null || _current.indirectPatchList.isEmpty()) && - (_current.sliceFlags & FLAG_HAS_OPTIONAL_MEMBERS) == 0) - { - throw new Ice.MarshalException("no references to indirection table"); - } - - // - // Convert indirect references into direct references. - // - if(_current.indirectPatchList != null) - { - for(IndirectPatchEntry e : _current.indirectPatchList) - { - assert(e.index >= 0); - if(e.index >= indirectionTable.length) - { - throw new Ice.MarshalException("indirection out of range"); - } - addPatchEntry(indirectionTable[e.index], e.patcher); - } - _current.indirectPatchList.clear(); - } - } - } - - @Override - void skipSlice() - { - if(_stream.instance().traceLevels().slicing > 0) - { - Ice.Logger logger = _stream.instance().initializationData().logger; - String slicingCat = _stream.instance().traceLevels().slicingCat; - if(_current.sliceType == SliceType.ExceptionSlice) - { - TraceUtil.traceSlicing("exception", _current.typeId, slicingCat, logger); - } - else - { - TraceUtil.traceSlicing("object", _current.typeId, slicingCat, logger); - } - } - - int start = _stream.pos(); - - if((_current.sliceFlags & FLAG_HAS_SLICE_SIZE) != 0) - { - assert(_current.sliceSize >= 4); - _stream.skip(_current.sliceSize - 4); - } - else - { - if(_current.sliceType == SliceType.ObjectSlice) - { - throw new Ice.NoValueFactoryException("no value factory found and compact format prevents " + - "slicing (the sender should use the sliced format instead)", - _current.typeId); - } - else - { - if(_current.typeId.startsWith("::")) - { - throw new Ice.UnknownUserException(_current.typeId.substring(2)); - } - else - { - throw new Ice.UnknownUserException(_current.typeId); - } - } - } - - // - // Preserve this slice. - // - Ice.SliceInfo info = new Ice.SliceInfo(); - info.typeId = _current.typeId; - info.compactId = _current.compactId; - info.hasOptionalMembers = (_current.sliceFlags & FLAG_HAS_OPTIONAL_MEMBERS) != 0; - info.isLastSlice = (_current.sliceFlags & FLAG_IS_LAST_SLICE) != 0; - java.nio.ByteBuffer b = _stream.getBuffer().b; - final int end = b.position(); - int dataEnd = end; - if(info.hasOptionalMembers) - { - // - // Don't include the optional member end marker. It will be re-written by - // endSlice when the sliced data is re-written. - // - --dataEnd; - } - info.bytes = new byte[dataEnd - start]; - b.position(start); - b.get(info.bytes); - b.position(end); - - if(_current.slices == null) // Lazy initialization - { - _current.slices = new java.util.ArrayList<Ice.SliceInfo>(); - _current.indirectionTables = new java.util.ArrayList<int[]>(); - } - - // - // Read the indirect object table. We read the instances or their - // IDs if the instance is a reference to an already un-marhsaled - // object. - // - // The SliceInfo object sequence is initialized only if - // readSlicedData is called. - // - - if((_current.sliceFlags & FLAG_HAS_INDIRECTION_TABLE) != 0) - { - int[] indirectionTable = new int[_stream.readAndCheckSeqSize(1)]; - for(int i = 0; i < indirectionTable.length; ++i) - { - indirectionTable[i] = readInstance(_stream.readSize(), null); - } - _current.indirectionTables.add(indirectionTable); - } - else - { - _current.indirectionTables.add(null); - } - - _current.slices.add(info); - } - - @Override - boolean readOpt(int readTag, Ice.OptionalFormat expectedFormat) - { - if(_current == null) - { - return _stream.readOptImpl(readTag, expectedFormat); - } - else if((_current.sliceFlags & FLAG_HAS_OPTIONAL_MEMBERS) != 0) - { - return _stream.readOptImpl(readTag, expectedFormat); - } - return false; - } - - private int readInstance(int index, Patcher patcher) - { - assert(index > 0); - - if(index > 1) - { - if(patcher != null) - { - addPatchEntry(index, patcher); - } - return index; - } - - push(SliceType.ObjectSlice); - - // - // Get the object ID before we start reading slices. If some - // slices are skiped, the indirect object table are still read and - // might read other objects. - // - index = ++_objectIdIndex; - - // - // Read the first slice header. - // - startSlice(); - final String mostDerivedId = _current.typeId; - Ice.Object v = null; - final Ice.CompactIdResolver compactIdResolver = _stream.instance().initializationData().compactIdResolver; - while(true) - { - if(_current.compactId >= 0) - { - // - // Translate a compact (numeric) type ID into a string type ID. - // - _current.typeId = ""; - if(compactIdResolver != null) - { - try - { - _current.typeId = compactIdResolver.resolve(_current.compactId); - } - catch(Ice.LocalException ex) - { - throw ex; - } - catch(Throwable ex) - { - throw new Ice.MarshalException("exception in CompactIdResolver for ID " + - _current.compactId, ex); - } - } - if(_current.typeId.length() == 0) - { - _current.typeId = _stream.getTypeId(_current.compactId); - } - } - - if(_current.typeId.length() > 0) - { - v = newInstance(_current.typeId); - - // - // We found a factory, we get out of this loop. - // - if(v != null) - { - break; - } - } - - // - // If object slicing is disabled, stop un-marshalling. - // - if(!_sliceObjects) - { - throw new Ice.NoValueFactoryException("no value factory found and object slicing is disabled", - _current.typeId); - } - - // - // Slice off what we don't understand. - // - skipSlice(); - - // - // If this is the last slice, keep the object as an opaque - // UnknownSlicedData object. - // - if((_current.sliceFlags & FLAG_IS_LAST_SLICE) != 0) - { - // - // Provide a factory with an opportunity to supply the object. - // We pass the "::Ice::Object" ID to indicate that this is the - // last chance to preserve the object. - // - v = newInstance(Ice.ObjectImpl.ice_staticId()); - if(v == null) - { - v = new Ice.UnknownSlicedObject(mostDerivedId); - } - - break; - } - - startSlice(); // Read next Slice header for next iteration. - } - - // - // Un-marshal the object - // - unmarshal(index, v); - - if(_current == null && _patchMap != null && !_patchMap.isEmpty()) - { - // - // If any entries remain in the patch map, the sender has sent an index for an object, but failed - // to supply the object. - // - throw new Ice.MarshalException("index for class received, but no instance"); - } - - if(patcher != null) - { - patcher.patch(v); - } - return index; - } - - private Ice.SlicedData readSlicedData() - { - if(_current.slices == null) // No preserved slices. - { - return null; - } - - // - // The _indirectionTables member holds the indirection table for each slice - // in _slices. - // - assert(_current.slices.size() == _current.indirectionTables.size()); - for(int n = 0; n < _current.slices.size(); ++n) - { - // - // We use the "objects" list in SliceInfo to hold references - // to the target objects. Note that the objects might not have - // been read yet in the case of a circular reference to an - // enclosing object. - // - final int[] table = _current.indirectionTables.get(n); - Ice.SliceInfo info = _current.slices.get(n); - info.objects = new Ice.Object[table != null ? table.length : 0]; - for(int j = 0; j < info.objects.length; ++j) - { - addPatchEntry(table[j], new SequencePatcher(info.objects, Ice.Object.class, - Ice.ObjectImpl.ice_staticId(), j)); - } - } - - Ice.SliceInfo[] arr = new Ice.SliceInfo[_current.slices.size()]; - _current.slices.toArray(arr); - return new Ice.SlicedData(arr); - } - - private void push(SliceType sliceType) - { - if(_current == null) - { - _current = new InstanceData(null); - } - else - { - _current = _current.next == null ? new InstanceData(_current) : _current.next; - } - _current.sliceType = sliceType; - _current.skipFirstSlice = false; - } - - private static final class IndirectPatchEntry - { - int index; - Patcher patcher; - } - - private static final class InstanceData - { - InstanceData(InstanceData previous) - { - if(previous != null) - { - previous.next = this; - } - this.previous = previous; - this.next = null; - } - - // Instance attributes - SliceType sliceType; - boolean skipFirstSlice; - java.util.List<Ice.SliceInfo> slices; // Preserved slices. - java.util.List<int[]> indirectionTables; - - // Slice attributes - byte sliceFlags; - int sliceSize; - String typeId; - int compactId; - java.util.Deque<IndirectPatchEntry> indirectPatchList; - - final InstanceData previous; - InstanceData next; - } - - private InstanceData _current; - - private int _objectIdIndex; // The ID of the next object to un-marshal. - } - - abstract private static class EncapsEncoder - { - protected EncapsEncoder(BasicStream stream, WriteEncaps encaps) - { - _stream = stream; - _encaps = encaps; - _typeIdIndex = 0; - _marshaledMap = new java.util.IdentityHashMap<Ice.Object, Integer>(); - } - - abstract void writeObject(Ice.Object v); - abstract void writeUserException(Ice.UserException v); - - abstract void startInstance(SliceType type, Ice.SlicedData data); - abstract void endInstance(); - abstract void startSlice(String typeId, int compactId, boolean last); - abstract void endSlice(); - - boolean writeOpt(int tag, Ice.OptionalFormat format) - { - return false; - } - - void writePendingObjects() - { - } - - protected int registerTypeId(String typeId) - { - if(_typeIdMap == null) // Lazy initialization - { - _typeIdMap = new java.util.TreeMap<String, Integer>(); - } - - Integer p = _typeIdMap.get(typeId); - if(p != null) - { - return p; - } - else - { - _typeIdMap.put(typeId, ++_typeIdIndex); - return -1; - } - } - - final protected BasicStream _stream; - final protected WriteEncaps _encaps; - - // Encapsulation attributes for object marshalling. - final protected java.util.IdentityHashMap<Ice.Object, Integer> _marshaledMap; - - // Encapsulation attributes for object marshalling. - private java.util.TreeMap<String, Integer> _typeIdMap; - private int _typeIdIndex; - } - - private static final class EncapsEncoder10 extends EncapsEncoder - { - EncapsEncoder10(BasicStream stream, WriteEncaps encaps) - { - super(stream, encaps); - _sliceType = SliceType.NoSlice; - _objectIdIndex = 0; - _toBeMarshaledMap = new java.util.IdentityHashMap<Ice.Object, Integer>(); - } - - @Override - void writeObject(Ice.Object v) - { - // - // Object references are encoded as a negative integer in 1.0. - // - if(v != null) - { - _stream.writeInt(-registerObject(v)); - } - else - { - _stream.writeInt(0); - } - } - - @Override - void writeUserException(Ice.UserException v) - { - // - // User exception with the 1.0 encoding start with a boolean - // flag that indicates whether or not the exception uses - // classes. - // - // This allows reading the pending objects even if some part of - // the exception was sliced. - // - boolean usesClasses = v.__usesClasses(); - _stream.writeBool(usesClasses); - v.__write(_stream); - if(usesClasses) - { - writePendingObjects(); - } - } - - @Override - void startInstance(SliceType sliceType, Ice.SlicedData sliceData) - { - _sliceType = sliceType; - } - - @Override - void endInstance() - { - if(_sliceType == SliceType.ObjectSlice) - { - // - // Write the Object slice. - // - startSlice(Ice.ObjectImpl.ice_staticId(), -1, true); - _stream.writeSize(0); // For compatibility with the old AFM. - endSlice(); - } - _sliceType = SliceType.NoSlice; - } - - @Override - void startSlice(String typeId, int compactId, boolean last) - { - // - // For object slices, encode a boolean to indicate how the type ID - // is encoded and the type ID either as a string or index. For - // exception slices, always encode the type ID as a string. - // - if(_sliceType == SliceType.ObjectSlice) - { - int index = registerTypeId(typeId); - if(index < 0) - { - _stream.writeBool(false); - _stream.writeString(typeId); - } - else - { - _stream.writeBool(true); - _stream.writeSize(index); - } - } - else - { - _stream.writeString(typeId); - } - - _stream.writeInt(0); // Placeholder for the slice length. - - _writeSlice = _stream.pos(); - } - - @Override - void endSlice() - { - // - // Write the slice length. - // - final int sz = _stream.pos() - _writeSlice + 4; - _stream.rewriteInt(sz, _writeSlice - 4); - } - - @Override - void writePendingObjects() - { - while(_toBeMarshaledMap.size() > 0) - { - // - // Consider the to be marshalled objects as marshalled now, - // this is necessary to avoid adding again the "to be - // marshalled objects" into _toBeMarshaledMap while writing - // objects. - // - _marshaledMap.putAll(_toBeMarshaledMap); - - java.util.IdentityHashMap<Ice.Object, Integer> savedMap = _toBeMarshaledMap; - _toBeMarshaledMap = new java.util.IdentityHashMap<Ice.Object, Integer>(); - _stream.writeSize(savedMap.size()); - for(java.util.Map.Entry<Ice.Object, Integer> p : savedMap.entrySet()) - { - // - // Ask the instance to marshal itself. Any new class - // instances that are triggered by the classes marshaled - // are added to toBeMarshaledMap. - // - _stream.writeInt(p.getValue().intValue()); - - try - { - p.getKey().ice_preMarshal(); - } - catch(java.lang.Exception ex) - { - String s = "exception raised by ice_preMarshal:\n" + Ex.toString(ex); - _stream.instance().initializationData().logger.warning(s); - } - - p.getKey().__write(_stream); - } - } - _stream.writeSize(0); // Zero marker indicates end of sequence of sequences of instances. - } - - private int registerObject(Ice.Object v) - { - assert(v != null); - - // - // Look for this instance in the to-be-marshaled map. - // - Integer p = _toBeMarshaledMap.get(v); - if(p != null) - { - return p.intValue(); - } - - // - // Didn't find it, try the marshaled map next. - // - p = _marshaledMap.get(v); - if(p != null) - { - return p.intValue(); - } - - // - // We haven't seen this instance previously, create a new - // index, and insert it into the to-be-marshaled map. - // - _toBeMarshaledMap.put(v, ++_objectIdIndex); - return _objectIdIndex; - } - - // Instance attributes - private SliceType _sliceType; - - // Slice attributes - private int _writeSlice; // Position of the slice data members - - // Encapsulation attributes for object marshalling. - private int _objectIdIndex; - private java.util.IdentityHashMap<Ice.Object, Integer> _toBeMarshaledMap; - } - - private static final class EncapsEncoder11 extends EncapsEncoder - { - EncapsEncoder11(BasicStream stream, WriteEncaps encaps) - { - super(stream, encaps); - _current = null; - _objectIdIndex = 1; - } - - @Override - void writeObject(Ice.Object v) - { - if(v == null) - { - _stream.writeSize(0); - } - else if(_current != null && _encaps.format == Ice.FormatType.SlicedFormat) - { - if(_current.indirectionTable == null) // Lazy initialization - { - _current.indirectionTable = new java.util.ArrayList<Ice.Object>(); - _current.indirectionMap = new java.util.IdentityHashMap<Ice.Object, Integer>(); - } - - // - // If writting an object within a slice and using the sliced - // format, write an index from the object indirection - // table. The indirect object table is encoded at the end of - // each slice and is always read (even if the Slice is - // unknown). - // - Integer index = _current.indirectionMap.get(v); - if(index == null) - { - _current.indirectionTable.add(v); - final int idx = _current.indirectionTable.size(); // Position + 1 (0 is reserved for nil) - _current.indirectionMap.put(v, idx); - _stream.writeSize(idx); - } - else - { - _stream.writeSize(index.intValue()); - } - } - else - { - writeInstance(v); // Write the instance or a reference if already marshaled. - } - } - - @Override - void writeUserException(Ice.UserException v) - { - v.__write(_stream); - } - - @Override - void startInstance(SliceType sliceType, Ice.SlicedData data) - { - if(_current == null) - { - _current = new InstanceData(null); - } - else - { - _current = _current.next == null ? new InstanceData(_current) : _current.next; - } - _current.sliceType = sliceType; - _current.firstSlice = true; - - if(data != null) - { - writeSlicedData(data); - } - } - - @Override - void endInstance() - { - _current = _current.previous; - } - - @Override - void startSlice(String typeId, int compactId, boolean last) - { - assert((_current.indirectionTable == null || _current.indirectionTable.isEmpty()) && - (_current.indirectionMap == null || _current.indirectionMap.isEmpty())); - - _current.sliceFlagsPos = _stream.pos(); - - _current.sliceFlags = (byte)0; - if(_encaps.format == Ice.FormatType.SlicedFormat) - { - _current.sliceFlags |= FLAG_HAS_SLICE_SIZE; // Encode the slice size if using the sliced format. - } - if(last) - { - _current.sliceFlags |= FLAG_IS_LAST_SLICE; // This is the last slice. - } - - _stream.writeByte((byte)0); // Placeholder for the slice flags - - // - // For object slices, encode the flag and the type ID either as a - // string or index. For exception slices, always encode the type - // ID a string. - // - if(_current.sliceType == SliceType.ObjectSlice) - { - // - // Encode the type ID (only in the first slice for the compact - // encoding). - // - if(_encaps.format == Ice.FormatType.SlicedFormat || _current.firstSlice) - { - if(compactId >= 0) - { - _current.sliceFlags |= FLAG_HAS_TYPE_ID_COMPACT; - _stream.writeSize(compactId); - } - else - { - int index = registerTypeId(typeId); - if(index < 0) - { - _current.sliceFlags |= FLAG_HAS_TYPE_ID_STRING; - _stream.writeString(typeId); - } - else - { - _current.sliceFlags |= FLAG_HAS_TYPE_ID_INDEX; - _stream.writeSize(index); - } - } - } - } - else - { - _stream.writeString(typeId); - } - - if((_current.sliceFlags & FLAG_HAS_SLICE_SIZE) != 0) - { - _stream.writeInt(0); // Placeholder for the slice length. - } - - _current.writeSlice = _stream.pos(); - _current.firstSlice = false; - } - - @Override - void endSlice() - { - // - // Write the optional member end marker if some optional members - // were encoded. Note that the optional members are encoded before - // the indirection table and are included in the slice size. - // - if((_current.sliceFlags & FLAG_HAS_OPTIONAL_MEMBERS) != 0) - { - _stream.writeByte((byte)OPTIONAL_END_MARKER); - } - - // - // Write the slice length if necessary. - // - if((_current.sliceFlags & FLAG_HAS_SLICE_SIZE) != 0) - { - final int sz = _stream.pos() - _current.writeSlice + 4; - _stream.rewriteInt(sz, _current.writeSlice - 4); - } - - // - // Only write the indirection table if it contains entries. - // - if(_current.indirectionTable != null && !_current.indirectionTable.isEmpty()) - { - assert(_encaps.format == Ice.FormatType.SlicedFormat); - _current.sliceFlags |= FLAG_HAS_INDIRECTION_TABLE; - - // - // Write the indirection object table. - // - _stream.writeSize(_current.indirectionTable.size()); - for(Ice.Object v : _current.indirectionTable) - { - writeInstance(v); - } - _current.indirectionTable.clear(); - _current.indirectionMap.clear(); - } - - // - // Finally, update the slice flags. - // - _stream.rewriteByte(_current.sliceFlags, _current.sliceFlagsPos); - } - - @Override - boolean writeOpt(int tag, Ice.OptionalFormat format) - { - if(_current == null) - { - return _stream.writeOptImpl(tag, format); - } - else - { - if(_stream.writeOptImpl(tag, format)) - { - _current.sliceFlags |= FLAG_HAS_OPTIONAL_MEMBERS; - return true; - } - else - { - return false; - } - } - } - - private void writeSlicedData(Ice.SlicedData slicedData) - { - assert(slicedData != null); - - // - // We only remarshal preserved slices if we are using the sliced - // format. Otherwise, we ignore the preserved slices, which - // essentially "slices" the object into the most-derived type - // known by the sender. - // - if(_encaps.format != Ice.FormatType.SlicedFormat) - { - return; - } - - for(Ice.SliceInfo info : slicedData.slices) - { - startSlice(info.typeId, info.compactId, info.isLastSlice); - - // - // Write the bytes associated with this slice. - // - _stream.writeBlob(info.bytes); - - if(info.hasOptionalMembers) - { - _current.sliceFlags |= FLAG_HAS_OPTIONAL_MEMBERS; - } - - // - // Make sure to also re-write the object indirection table. - // - if(info.objects != null && info.objects.length > 0) - { - if(_current.indirectionTable == null) // Lazy initialization - { - _current.indirectionTable = new java.util.ArrayList<Ice.Object>(); - _current.indirectionMap = new java.util.IdentityHashMap<Ice.Object, Integer>(); - } - for(Ice.Object o : info.objects) - { - _current.indirectionTable.add(o); - } - } - - endSlice(); - } - } - - private void writeInstance(Ice.Object v) - { - assert(v != null); - - // - // If the instance was already marshaled, just write it's ID. - // - Integer p = _marshaledMap.get(v); - if(p != null) - { - _stream.writeSize(p); - return; - } - - // - // We haven't seen this instance previously, create a new ID, - // insert it into the marshaled map, and write the instance. - // - _marshaledMap.put(v, ++_objectIdIndex); - - try - { - v.ice_preMarshal(); - } - catch(java.lang.Exception ex) - { - String s = "exception raised by ice_preMarshal:\n" + Ex.toString(ex); - _stream.instance().initializationData().logger.warning(s); - } - - _stream.writeSize(1); // Object instance marker. - v.__write(_stream); - } - - private static final class InstanceData - { - InstanceData(InstanceData previous) - { - if(previous != null) - { - previous.next = this; - } - this.previous = previous; - this.next = null; - } - - // Instance attributes - SliceType sliceType; - boolean firstSlice; - - // Slice attributes - byte sliceFlags; - int writeSlice; // Position of the slice data members - int sliceFlagsPos; // Position of the slice flags - java.util.List<Ice.Object> indirectionTable; - java.util.IdentityHashMap<Ice.Object, Integer> indirectionMap; - - final InstanceData previous; - InstanceData next; - } - - private InstanceData _current; - - private int _objectIdIndex; // The ID of the next object to marhsal - } - - private static final class ReadEncaps - { - void reset() - { - decoder = null; - } - - void setEncoding(Ice.EncodingVersion encoding) - { - this.encoding = encoding; - encoding_1_0 = encoding.equals(Ice.Util.Encoding_1_0); - } - - int start; - int sz; - Ice.EncodingVersion encoding; - boolean encoding_1_0; - - EncapsDecoder decoder; - - ReadEncaps next; - } - - private static final class WriteEncaps - { - void reset() - { - encoder = null; - } - - void setEncoding(Ice.EncodingVersion encoding) - { - this.encoding = encoding; - encoding_1_0 = encoding.equals(Ice.Util.Encoding_1_0); - } - - int start; - Ice.FormatType format = Ice.FormatType.DefaultFormat; - Ice.EncodingVersion encoding; - boolean encoding_1_0; - - EncapsEncoder encoder; - - WriteEncaps next; - } - - // - // The encoding version to use when there's no encapsulation to - // read from or write to. This is for example used to read message - // headers or when the user is using the streaming API with no - // encapsulation. - // - private Ice.EncodingVersion _encoding; - - private boolean isReadEncoding_1_0() - { - return _readEncapsStack != null ? _readEncapsStack.encoding_1_0 : _encoding.equals(Ice.Util.Encoding_1_0); - } - - private boolean isWriteEncoding_1_0() - { - return _writeEncapsStack != null ? _writeEncapsStack.encoding_1_0 : _encoding.equals(Ice.Util.Encoding_1_0); - } - - private ReadEncaps _readEncapsStack; - private WriteEncaps _writeEncapsStack; - private ReadEncaps _readEncapsCache; - private WriteEncaps _writeEncapsCache; - - private void initReadEncaps() - { - if(_readEncapsStack == null) // Lazy initialization - { - _readEncapsStack = _readEncapsCache; - if(_readEncapsStack != null) - { - _readEncapsCache = _readEncapsCache.next; - } - else - { - _readEncapsStack = new ReadEncaps(); - } - _readEncapsStack.setEncoding(_encoding); - _readEncapsStack.sz = _buf.b.limit(); - } - - if(_readEncapsStack.decoder == null) // Lazy initialization. - { - Ice.ValueFactoryManager factoryManager = _instance.initializationData().valueFactoryManager; - if(_readEncapsStack.encoding_1_0) - { - _readEncapsStack.decoder = new EncapsDecoder10(this, _sliceObjects, factoryManager); - } - else - { - _readEncapsStack.decoder = new EncapsDecoder11(this, _sliceObjects, factoryManager); - } - } - } - - private void initWriteEncaps() - { - if(_writeEncapsStack == null) // Lazy initialization - { - _writeEncapsStack = _writeEncapsCache; - if(_writeEncapsStack != null) - { - _writeEncapsCache = _writeEncapsCache.next; - } - else - { - _writeEncapsStack = new WriteEncaps(); - } - _writeEncapsStack.setEncoding(_encoding); - } - - if(_writeEncapsStack.format == Ice.FormatType.DefaultFormat) - { - _writeEncapsStack.format = _instance.defaultsAndOverrides().defaultFormat; - } - - if(_writeEncapsStack.encoder == null) // Lazy initialization. - { - if(_writeEncapsStack.encoding_1_0) - { - _writeEncapsStack.encoder = new EncapsEncoder10(this, _writeEncapsStack); - } - else - { - _writeEncapsStack.encoder = new EncapsEncoder11(this, _writeEncapsStack); - } - } - } - - private boolean _sliceObjects; - - private int _startSeq; - private int _minSeqSize; - - private static final int OPTIONAL_END_MARKER = 0xFF; - - private static final byte FLAG_HAS_TYPE_ID_STRING = (byte)(1<<0); - private static final byte FLAG_HAS_TYPE_ID_INDEX = (byte)(1<<1); - private static final byte FLAG_HAS_TYPE_ID_COMPACT = (byte)(1<<1 | 1<<0); - private static final byte FLAG_HAS_OPTIONAL_MEMBERS = (byte)(1<<2); - private static final byte FLAG_HAS_INDIRECTION_TABLE = (byte)(1<<3); - private static final byte FLAG_HAS_SLICE_SIZE = (byte)(1<<4); - private static final byte FLAG_IS_LAST_SLICE = (byte)(1<<5); - - private static boolean _checkedBZip2 = false; - private static java.lang.reflect.Constructor<?> _bzInputStreamCtor; - private static java.lang.reflect.Constructor<?> _bzOutputStreamCtor; - - public synchronized static boolean - compressible() - { - // - // Use lazy initialization when determining whether support for bzip2 compression - // is available. - // - if(!_checkedBZip2) - { - _checkedBZip2 = true; - try - { - Class<?> cls; - Class<?>[] types = new Class<?>[1]; - cls = IceInternal.Util.findClass("org.apache.tools.bzip2.CBZip2InputStream", null); - if(cls != null) - { - types[0] = java.io.InputStream.class; - _bzInputStreamCtor = cls.getDeclaredConstructor(types); - } - cls = IceInternal.Util.findClass("org.apache.tools.bzip2.CBZip2OutputStream", null); - if(cls != null) - { - types = new Class[2]; - types[0] = java.io.OutputStream.class; - types[1] = Integer.TYPE; - _bzOutputStreamCtor = cls.getDeclaredConstructor(types); - } - } - catch(Exception ex) - { - // Ignore - bzip2 compression not available. - } - } - return _bzInputStreamCtor != null && _bzOutputStreamCtor != null; - } -} diff --git a/java/src/Ice/src/main/java/IceInternal/BatchRequestQueue.java b/java/src/Ice/src/main/java/IceInternal/BatchRequestQueue.java index 5fc582659bf..3e7d2bd81e8 100644 --- a/java/src/Ice/src/main/java/IceInternal/BatchRequestQueue.java +++ b/java/src/Ice/src/main/java/IceInternal/BatchRequestQueue.java @@ -47,7 +47,7 @@ public class BatchRequestQueue private Ice.ObjectPrx _proxy; private String _operation; private int _size; - }; + } public BatchRequestQueue(Instance instance, boolean datagram) @@ -56,7 +56,7 @@ public class BatchRequestQueue _interceptor = initData.batchRequestInterceptor; _batchStreamInUse = false; _batchRequestNum = 0; - _batchStream = new BasicStream(instance, Protocol.currentProtocolEncoding); + _batchStream = new Ice.OutputStream(instance, Protocol.currentProtocolEncoding); _batchStream.writeBlob(Protocol.requestBatchHdr); _batchMarker = _batchStream.size(); _request = new BatchRequestI(); @@ -73,7 +73,7 @@ public class BatchRequestQueue } synchronized public void - prepareBatchRequest(BasicStream os) + prepareBatchRequest(Ice.OutputStream os) { if(_exception != null) { @@ -86,7 +86,7 @@ public class BatchRequestQueue } public void - finishBatchRequest(BasicStream os, Ice.ObjectPrx proxy, String operation) + finishBatchRequest(Ice.OutputStream os, Ice.ObjectPrx proxy, String operation) { // // No need for synchronization, no other threads are supposed @@ -120,7 +120,7 @@ public class BatchRequestQueue { synchronized(this) { - _batchStream.resize(_batchMarker, false); + _batchStream.resize(_batchMarker); _batchStreamInUse = false; _batchStreamCanFlush = false; notifyAll(); @@ -129,19 +129,19 @@ public class BatchRequestQueue } synchronized public void - abortBatchRequest(BasicStream os) + abortBatchRequest(Ice.OutputStream os) { if(_batchStreamInUse) { _batchStream.swap(os); - _batchStream.resize(_batchMarker, false); + _batchStream.resize(_batchMarker); _batchStreamInUse = false; notifyAll(); } } synchronized public int - swap(BasicStream os) + swap(Ice.OutputStream os) { if(_batchRequestNum == 0) { @@ -157,7 +157,7 @@ public class BatchRequestQueue Buffer buffer = _batchStream.getBuffer(); buffer.b.position(_batchMarker); buffer.b.get(lastRequest); - _batchStream.resize(_batchMarker, false); + _batchStream.resize(_batchMarker); } int requestNum = _batchRequestNum; @@ -226,7 +226,7 @@ public class BatchRequestQueue } private Ice.BatchRequestInterceptor _interceptor; - private BasicStream _batchStream; + private Ice.OutputStream _batchStream; private boolean _batchStreamInUse; private boolean _batchStreamCanFlush; private int _batchRequestNum; @@ -236,4 +236,4 @@ public class BatchRequestQueue private int _maxSize; final private static int _udpOverhead = 20 + 8; -}; +} diff --git a/java/src/Ice/src/main/java/IceInternal/Buffer.java b/java/src/Ice/src/main/java/IceInternal/Buffer.java index f1301a6159c..e717be96efa 100644 --- a/java/src/Ice/src/main/java/IceInternal/Buffer.java +++ b/java/src/Ice/src/main/java/IceInternal/Buffer.java @@ -15,13 +15,12 @@ package IceInternal; // public class Buffer { - public - Buffer(boolean direct) + public Buffer(boolean direct) { this(direct, java.nio.ByteOrder.LITTLE_ENDIAN); } - Buffer(boolean direct, java.nio.ByteOrder order) + public Buffer(boolean direct, java.nio.ByteOrder order) { b = _emptyBuffer; _size = 0; @@ -30,12 +29,12 @@ public class Buffer _order = order; } - Buffer(byte[] data) + public Buffer(byte[] data) { this(data, java.nio.ByteOrder.LITTLE_ENDIAN); } - Buffer(byte[] data, java.nio.ByteOrder order) + public Buffer(byte[] data, java.nio.ByteOrder order) { b = java.nio.ByteBuffer.wrap(data); b.order(order); @@ -45,12 +44,12 @@ public class Buffer _order = order; } - Buffer(java.nio.ByteBuffer data) + public Buffer(java.nio.ByteBuffer data) { this(data, java.nio.ByteOrder.LITTLE_ENDIAN); } - Buffer(java.nio.ByteBuffer data, java.nio.ByteOrder order) + public Buffer(java.nio.ByteBuffer data, java.nio.ByteOrder order) { b = data; b.order(order); @@ -60,24 +59,37 @@ public class Buffer _order = order; } - public int - size() + public Buffer(Buffer buf, boolean adopt) + { + b = buf.b; + _size = buf._size; + _capacity = buf._capacity; + _direct = buf._direct; + _shrinkCounter = buf._shrinkCounter; + _order = buf._order; + + if(adopt) + { + buf.clear(); + } + } + + public int size() { return _size; } - public boolean - empty() + public boolean empty() { return _size == 0; } - public void - clear() + public void clear() { b = _emptyBuffer; _size = 0; _capacity = 0; + _shrinkCounter = 0; } // @@ -86,8 +98,7 @@ public class Buffer // expand the buffer if the caller is writing to a location that is // already in the buffer. // - public void - expand(int n) + public void expand(int n) { final int sz = (b == _emptyBuffer) ? n : b.position() + n; if(sz > _size) @@ -96,8 +107,7 @@ public class Buffer } } - public void - resize(int n, boolean reading) + public void resize(int n, boolean reading) { assert(b == _emptyBuffer || _capacity > 0); @@ -120,8 +130,7 @@ public class Buffer } } - public void - reset() + public void reset() { if(_size > 0 && _size * 2 < _capacity) { @@ -149,8 +158,7 @@ public class Buffer } } - private void - reserve(int n) + private void reserve(int n) { if(n > _capacity) { diff --git a/java/src/Ice/src/main/java/IceInternal/CollocatedRequestHandler.java b/java/src/Ice/src/main/java/IceInternal/CollocatedRequestHandler.java index 55c2c69e7d3..a3dd3bcb19e 100644 --- a/java/src/Ice/src/main/java/IceInternal/CollocatedRequestHandler.java +++ b/java/src/Ice/src/main/java/IceInternal/CollocatedRequestHandler.java @@ -13,7 +13,7 @@ public class CollocatedRequestHandler implements RequestHandler, ResponseHandler { private class InvokeAllAsync extends DispatchWorkItem { - private InvokeAllAsync(OutgoingAsyncBase outAsync, BasicStream os, int requestId, int batchRequestNum) + private InvokeAllAsync(OutgoingAsyncBase outAsync, Ice.OutputStream os, int requestId, int batchRequestNum) { _outAsync = outAsync; _os = os; @@ -31,7 +31,7 @@ public class CollocatedRequestHandler implements RequestHandler, ResponseHandler } private final OutgoingAsyncBase _outAsync; - private BasicStream _os; + private Ice.OutputStream _os; private final int _requestId; private final int _batchRequestNum; } @@ -103,23 +103,30 @@ public class CollocatedRequestHandler implements RequestHandler, ResponseHandler @Override public void - sendResponse(int requestId, final BasicStream os, byte status, boolean amd) + sendResponse(int requestId, final Ice.OutputStream os, byte status, boolean amd) { OutgoingAsyncBase outAsync = null; synchronized(this) { assert(_response); - os.pos(Protocol.replyHdr.length + 4); - if(_traceLevels.protocol >= 1) { fillInValue(os, 10, os.size()); - TraceUtil.traceRecv(os, _logger, _traceLevels); + } + + // Adopt the OutputStream's buffer. + Ice.InputStream is = new Ice.InputStream(os.instance(), os.getEncoding(), os.getBuffer(), true); + + is.pos(Protocol.replyHdr.length + 4); + + if(_traceLevels.protocol >= 1) + { + TraceUtil.traceRecv(is, _logger, _traceLevels); } outAsync = _asyncRequests.remove(requestId); - if(outAsync != null && !outAsync.completed(os)) + if(outAsync != null && !outAsync.completed(is)) { outAsync = null; } @@ -272,17 +279,8 @@ public class CollocatedRequestHandler implements RequestHandler, ResponseHandler } private void - invokeAll(BasicStream os, int requestId, int batchRequestNum) + invokeAll(Ice.OutputStream os, int requestId, int batchRequestNum) { - if(batchRequestNum > 0) - { - os.pos(Protocol.requestBatchHdr.length); - } - else - { - os.pos(Protocol.requestHdr.length); - } - if(_traceLevels.protocol >= 1) { fillInValue(os, 10, os.size()); @@ -297,6 +295,17 @@ public class CollocatedRequestHandler implements RequestHandler, ResponseHandler TraceUtil.traceSend(os, _logger, _traceLevels); } + Ice.InputStream is = new Ice.InputStream(os.instance(), os.getEncoding(), os.getBuffer(), false); + + if(batchRequestNum > 0) + { + is.pos(Protocol.requestBatchHdr.length); + } + else + { + is.pos(Protocol.requestHdr.length); + } + int invokeNum = batchRequestNum > 0 ? batchRequestNum : 1; ServantManager servantManager = _adapter.getServantManager(); try @@ -321,7 +330,7 @@ public class CollocatedRequestHandler implements RequestHandler, ResponseHandler Incoming in = new Incoming(_reference.getInstance(), this, null, _adapter, _response, (byte)0, requestId); - in.invoke(servantManager, os); + in.invoke(servantManager, is); --invokeNum; } } @@ -410,7 +419,7 @@ public class CollocatedRequestHandler implements RequestHandler, ResponseHandler } private void - fillInValue(BasicStream os, int pos, int value) + fillInValue(Ice.OutputStream os, int pos, int value) { os.rewriteInt(value, pos); } diff --git a/java/src/Ice/src/main/java/IceInternal/DefaultsAndOverrides.java b/java/src/Ice/src/main/java/IceInternal/DefaultsAndOverrides.java index 453e0968bd9..6d2f591d7fd 100644 --- a/java/src/Ice/src/main/java/IceInternal/DefaultsAndOverrides.java +++ b/java/src/Ice/src/main/java/IceInternal/DefaultsAndOverrides.java @@ -120,7 +120,7 @@ public final class DefaultsAndOverrides { overrideCompress = true; boolean b = properties.getPropertyAsInt("Ice.Override.Compress") > 0; - if(b && !BasicStream.compressible()) + if(b && !BZip2.supported()) { System.err.println("warning: bzip2 support not available, Ice.Override.Compress ignored"); b = false; diff --git a/java/src/Ice/src/main/java/IceInternal/DictionaryPatcher.java b/java/src/Ice/src/main/java/IceInternal/DictionaryPatcher.java index 21a42bbe094..0dd55d80011 100644 --- a/java/src/Ice/src/main/java/IceInternal/DictionaryPatcher.java +++ b/java/src/Ice/src/main/java/IceInternal/DictionaryPatcher.java @@ -9,10 +9,10 @@ package IceInternal; -public class DictionaryPatcher<K, V> implements Patcher, Ice.ReadObjectCallback +public class DictionaryPatcher<K, V> implements Ice.ReadObjectCallback { - public - DictionaryPatcher(java.util.Map<K, V> dict, Class<V> cls, String type, K key) + // TBD: Remove _type? + public DictionaryPatcher(java.util.Map<K, V> dict, Class<V> cls, String type, K key) { _dict = dict; _cls = cls; @@ -20,9 +20,7 @@ public class DictionaryPatcher<K, V> implements Patcher, Ice.ReadObjectCallback _key = key; } - @Override - public void - patch(Ice.Object v) + public void objectReady(Ice.Object v) { if(v != null) { @@ -39,20 +37,6 @@ public class DictionaryPatcher<K, V> implements Patcher, Ice.ReadObjectCallback _dict.put(_key, _cls.cast(v)); } - @Override - public String - type() - { - return _type; - } - - @Override - public void - invoke(Ice.Object v) - { - patch(v); - } - private java.util.Map<K, V> _dict; private Class<V> _cls; private String _type; diff --git a/java/src/Ice/src/main/java/IceInternal/EndpointFactory.java b/java/src/Ice/src/main/java/IceInternal/EndpointFactory.java index 79a8301ef26..5f80919b706 100644 --- a/java/src/Ice/src/main/java/IceInternal/EndpointFactory.java +++ b/java/src/Ice/src/main/java/IceInternal/EndpointFactory.java @@ -14,7 +14,7 @@ public interface EndpointFactory short type(); String protocol(); EndpointI create(java.util.ArrayList<String> args, boolean oaEndpoint); - EndpointI read(BasicStream s); + EndpointI read(Ice.InputStream s); void destroy(); EndpointFactory clone(ProtocolInstance instance); diff --git a/java/src/Ice/src/main/java/IceInternal/EndpointFactoryManager.java b/java/src/Ice/src/main/java/IceInternal/EndpointFactoryManager.java index 0cf65a56176..b09e12ce5ae 100644 --- a/java/src/Ice/src/main/java/IceInternal/EndpointFactoryManager.java +++ b/java/src/Ice/src/main/java/IceInternal/EndpointFactoryManager.java @@ -127,16 +127,16 @@ public final class EndpointFactoryManager // and ask the factory to read the endpoint data from that stream to create // the actual endpoint. // - BasicStream bs = new BasicStream(_instance, Protocol.currentProtocolEncoding, false); - bs.writeShort(ue.type()); - ue.streamWrite(bs); - Buffer buf = bs.getBuffer(); - buf.b.position(0); - buf.b.limit(buf.size()); - bs.readShort(); // type - bs.startReadEncaps(); - EndpointI e = factory.read(bs); - bs.endReadEncaps(); + Ice.OutputStream os = new Ice.OutputStream(_instance, Protocol.currentProtocolEncoding, false); + os.writeShort(ue.type()); + ue.streamWrite(os); + Ice.InputStream is = + new Ice.InputStream(_instance, Protocol.currentProtocolEncoding, os.getBuffer(), true); + is.pos(0); + is.readShort(); // type + is.startEncapsulation(); + EndpointI e = factory.read(is); + is.endEncapsulation(); return e; } return ue; // Endpoint is opaque, but we don't have a factory for its type. @@ -145,14 +145,14 @@ public final class EndpointFactoryManager return null; } - public synchronized EndpointI read(BasicStream s) + public synchronized EndpointI read(Ice.InputStream s) { short type = s.readShort(); EndpointFactory factory = get(type); EndpointI e = null; - s.startReadEncaps(); + s.startEncapsulation(); if(factory != null) { @@ -163,7 +163,7 @@ public final class EndpointFactoryManager e = new OpaqueEndpointI(type, s); } - s.endReadEncaps(); + s.endEncapsulation(); return e; } diff --git a/java/src/Ice/src/main/java/IceInternal/EndpointI.java b/java/src/Ice/src/main/java/IceInternal/EndpointI.java index c6bdfe75f7a..39450114309 100644 --- a/java/src/Ice/src/main/java/IceInternal/EndpointI.java +++ b/java/src/Ice/src/main/java/IceInternal/EndpointI.java @@ -33,7 +33,7 @@ abstract public class EndpointI implements Ice.Endpoint, java.lang.Comparable<En // // Marshal the endpoint. // - public abstract void streamWrite(BasicStream s); + public abstract void streamWrite(Ice.OutputStream s); // // Return the endpoint type. diff --git a/java/src/Ice/src/main/java/IceInternal/FixedReference.java b/java/src/Ice/src/main/java/IceInternal/FixedReference.java index 20c108471f8..45d449cc16d 100644 --- a/java/src/Ice/src/main/java/IceInternal/FixedReference.java +++ b/java/src/Ice/src/main/java/IceInternal/FixedReference.java @@ -188,7 +188,7 @@ public class FixedReference extends Reference @Override public void - streamWrite(BasicStream s) + streamWrite(Ice.OutputStream s) throws Ice.MarshalException { throw new Ice.FixedProxyException(); diff --git a/java/src/Ice/src/main/java/IceInternal/IPEndpointI.java b/java/src/Ice/src/main/java/IceInternal/IPEndpointI.java index eced02e5a1a..b2baf2b9551 100644 --- a/java/src/Ice/src/main/java/IceInternal/IPEndpointI.java +++ b/java/src/Ice/src/main/java/IceInternal/IPEndpointI.java @@ -32,7 +32,7 @@ public abstract class IPEndpointI extends EndpointI _hashInitialized = false; } - protected IPEndpointI(ProtocolInstance instance, BasicStream s) + protected IPEndpointI(ProtocolInstance instance, Ice.InputStream s) { _instance = instance; _host = s.readString(); @@ -43,11 +43,11 @@ public abstract class IPEndpointI extends EndpointI } @Override - public void streamWrite(BasicStream s) + public void streamWrite(Ice.OutputStream s) { - s.startWriteEncaps(); + s.startEncapsulation(); streamWriteImpl(s); - s.endWriteEncaps(); + s.endEncapsulation(); } @Override @@ -260,7 +260,7 @@ public abstract class IPEndpointI extends EndpointI return _port; } - public void streamWriteImpl(BasicStream s) + public void streamWriteImpl(Ice.OutputStream s) { s.writeString(_host); s.writeInt(_port); diff --git a/java/src/Ice/src/main/java/IceInternal/Incoming.java b/java/src/Ice/src/main/java/IceInternal/Incoming.java index 0795cb44939..6d0a1aaf25a 100644 --- a/java/src/Ice/src/main/java/IceInternal/Incoming.java +++ b/java/src/Ice/src/main/java/IceInternal/Incoming.java @@ -78,7 +78,7 @@ final public class Incoming extends IncomingBase implements Ice.Request } public void - invoke(ServantManager servantManager, BasicStream stream) + invoke(ServantManager servantManager, Ice.InputStream stream) { _is = stream; @@ -87,7 +87,7 @@ final public class Incoming extends IncomingBase implements Ice.Request // // Read the current. // - _current.id.__read(_is); + _current.id.ice_read(_is); // // For compatibility with the old FacetPath. @@ -156,7 +156,7 @@ final public class Incoming extends IncomingBase implements Ice.Request } catch(Ice.UserException ex) { - Ice.EncodingVersion encoding = _is.skipEncaps(); // Required for batch requests. + Ice.EncodingVersion encoding = _is.skipEncapsulation(); // Required for batch requests. if(_observer != null) { @@ -166,9 +166,9 @@ final public class Incoming extends IncomingBase implements Ice.Request if(_response) { _os.writeByte(ReplyStatus.replyUserException); - _os.startWriteEncaps(encoding, Ice.FormatType.DefaultFormat); - _os.writeUserException(ex); - _os.endWriteEncaps(); + _os.startEncapsulation(encoding, Ice.FormatType.DefaultFormat); + _os.writeException(ex); + _os.endEncapsulation(); if(_observer != null) { _observer.reply(_os.size() - Protocol.headerSize - 4); @@ -190,13 +190,13 @@ final public class Incoming extends IncomingBase implements Ice.Request } catch(java.lang.Exception ex) { - _is.skipEncaps(); // Required for batch requests. + _is.skipEncapsulation(); // Required for batch requests. __handleException(ex, false); return; } catch(java.lang.Error ex) { - _is.skipEncaps(); // Required for batch requests. + _is.skipEncapsulation(); // Required for batch requests. __handleError(ex, false); // Always throws. } } @@ -245,7 +245,7 @@ final public class Incoming extends IncomingBase implements Ice.Request // Skip the input parameters, this is required for reading // the next batch request if dispatching batch requests. // - _is.skipEncaps(); + _is.skipEncapsulation(); if(servantManager != null && servantManager.hasServant(_current.id)) { @@ -342,7 +342,7 @@ final public class Incoming extends IncomingBase implements Ice.Request _is.pos(_inParamPos); if(_response) { - _os.resize(Protocol.headerSize + 4, false); + _os.resize(Protocol.headerSize + 4); } } } @@ -363,35 +363,35 @@ final public class Incoming extends IncomingBase implements Ice.Request } } - public final BasicStream + public final Ice.InputStream startReadParams() { // // Remember the encoding used by the input parameters, we'll // encode the response parameters with the same encoding. // - _current.encoding = _is.startReadEncaps(); + _current.encoding = _is.startEncapsulation(); return _is; } public final void endReadParams() { - _is.endReadEncaps(); + _is.endEncapsulation(); } public final void readEmptyParams() { _current.encoding = new Ice.EncodingVersion(); - _is.skipEmptyEncaps(_current.encoding); + _is.skipEmptyEncapsulation(_current.encoding); } public final byte[] readParamEncaps() { _current.encoding = new Ice.EncodingVersion(); - return _is.readEncaps(_current.encoding); + return _is.readEncapsulation(_current.encoding); } final void @@ -409,7 +409,7 @@ final public class Incoming extends IncomingBase implements Ice.Request public Incoming next; // For use by ConnectionI. - private BasicStream _is; + private Ice.InputStream _is; private IncomingAsync _cb; private int _inParamPos = -1; diff --git a/java/src/Ice/src/main/java/IceInternal/IncomingBase.java b/java/src/Ice/src/main/java/IceInternal/IncomingBase.java index 17df6a20017..1b60cb2539a 100644 --- a/java/src/Ice/src/main/java/IceInternal/IncomingBase.java +++ b/java/src/Ice/src/main/java/IceInternal/IncomingBase.java @@ -21,7 +21,7 @@ class IncomingBase _compress = compress; if(_response) { - _os = new BasicStream(instance, Protocol.currentProtocolEncoding); + _os = new Ice.OutputStream(instance, Protocol.currentProtocolEncoding); } _current = new Ice.Current(); @@ -90,7 +90,7 @@ class IncomingBase other._responseHandler = null; } - public BasicStream + public Ice.OutputStream __startWriteParams(Ice.FormatType format) { if(!_response) @@ -101,7 +101,7 @@ class IncomingBase assert(_os.size() == Protocol.headerSize + 4); // Reply status position. assert(_current.encoding != null); // Encoding for reply is known. _os.writeByte((byte)0); - _os.startWriteEncaps(_current.encoding, format); + _os.startEncapsulation(_current.encoding, format); return _os; } @@ -119,7 +119,7 @@ class IncomingBase _os.pos(Protocol.headerSize + 4); // Reply status position. _os.writeByte(ok ? ReplyStatus.replyOK : ReplyStatus.replyUserException); _os.pos(save); - _os.endWriteEncaps(); + _os.endEncapsulation(); } public void @@ -130,7 +130,7 @@ class IncomingBase assert(_os.size() == Protocol.headerSize + 4); // Reply status position. assert(_current.encoding != null); // Encoding for reply is known. _os.writeByte(ReplyStatus.replyOK); - _os.writeEmptyEncaps(_current.encoding); + _os.writeEmptyEncapsulation(_current.encoding); } } @@ -149,11 +149,11 @@ class IncomingBase _os.writeByte(ok ? ReplyStatus.replyOK : ReplyStatus.replyUserException); if(v == null || v.length == 0) { - _os.writeEmptyEncaps(_current.encoding); + _os.writeEmptyEncapsulation(_current.encoding); } else { - _os.writeEncaps(v); + _os.writeEncapsulation(v); } } } @@ -161,8 +161,8 @@ class IncomingBase public void __writeUserException(Ice.UserException ex, Ice.FormatType format) { - BasicStream __os = __startWriteParams(format); - __os.writeUserException(ex); + Ice.OutputStream __os = __startWriteParams(format); + __os.writeException(ex); __endWriteParams(false); } @@ -195,7 +195,7 @@ class IncomingBase if(_response && _os == null) { - _os = new BasicStream(instance, Protocol.currentProtocolEncoding); + _os = new Ice.OutputStream(instance, Protocol.currentProtocolEncoding); } _responseHandler = handler; @@ -277,11 +277,11 @@ class IncomingBase // if(_response) { - _os.resize(Protocol.headerSize + 4, false); // Reply status position. + _os.resize(Protocol.headerSize + 4); // Reply status position. _os.writeByte(ReplyStatus.replyUserException); - _os.startWriteEncaps(_current.encoding, Ice.FormatType.DefaultFormat); - _os.writeUserException(ex); - _os.endWriteEncaps(); + _os.startEncapsulation(_current.encoding, Ice.FormatType.DefaultFormat); + _os.writeException(ex); + _os.endEncapsulation(); if(_observer != null) { _observer.reply(_os.size() - Protocol.headerSize - 4); @@ -349,7 +349,7 @@ class IncomingBase if(_response) { - _os.resize(Protocol.headerSize + 4, false); // Reply status position. + _os.resize(Protocol.headerSize + 4); // Reply status position. if(ex instanceof Ice.ObjectNotExistException) { _os.writeByte(ReplyStatus.replyObjectNotExist); @@ -366,7 +366,7 @@ class IncomingBase { assert(false); } - ex.id.__write(_os); + ex.id.ice_write(_os); // // For compatibility with the old FacetPath. @@ -408,7 +408,7 @@ class IncomingBase if(_response) { - _os.resize(Protocol.headerSize + 4, false); // Reply status position. + _os.resize(Protocol.headerSize + 4); // Reply status position. _os.writeByte(ReplyStatus.replyUnknownLocalException); _os.writeString(ex.unknown); if(_observer != null) @@ -436,7 +436,7 @@ class IncomingBase if(_response) { - _os.resize(Protocol.headerSize + 4, false); // Reply status position. + _os.resize(Protocol.headerSize + 4); // Reply status position. _os.writeByte(ReplyStatus.replyUnknownUserException); _os.writeString(ex.unknown); if(_observer != null) @@ -464,7 +464,7 @@ class IncomingBase if(_response) { - _os.resize(Protocol.headerSize + 4, false); // Reply status position. + _os.resize(Protocol.headerSize + 4); // Reply status position. _os.writeByte(ReplyStatus.replyUnknownException); _os.writeString(ex.unknown); if(_observer != null) @@ -500,7 +500,7 @@ class IncomingBase if(_response) { - _os.resize(Protocol.headerSize + 4, false); // Reply status position. + _os.resize(Protocol.headerSize + 4); // Reply status position. _os.writeByte(ReplyStatus.replyUnknownLocalException); //_os.writeString(ex.toString()); java.io.StringWriter sw = new java.io.StringWriter(); @@ -534,7 +534,7 @@ class IncomingBase if(_response) { - _os.resize(Protocol.headerSize + 4, false); // Reply status position. + _os.resize(Protocol.headerSize + 4); // Reply status position. _os.writeByte(ReplyStatus.replyUnknownUserException); //_os.writeString(ex.toString()); java.io.StringWriter sw = new java.io.StringWriter(); @@ -568,7 +568,7 @@ class IncomingBase if(_response) { - _os.resize(Protocol.headerSize + 4, false); // Reply status position. + _os.resize(Protocol.headerSize + 4); // Reply status position. _os.writeByte(ReplyStatus.replyUnknownException); //_os.writeString(ex.toString()); java.io.StringWriter sw = new java.io.StringWriter(); @@ -620,7 +620,7 @@ class IncomingBase if(_response) { - _os.resize(Protocol.headerSize + 4, false); // Reply status position. + _os.resize(Protocol.headerSize + 4); // Reply status position. _os.writeByte(ReplyStatus.replyUnknownException); _os.writeString(uex.unknown); if(_observer != null) @@ -654,7 +654,7 @@ class IncomingBase protected boolean _response; protected byte _compress; - protected BasicStream _os; + protected Ice.OutputStream _os; protected ResponseHandler _responseHandler; diff --git a/java/src/Ice/src/main/java/IceInternal/InputStreamWrapper.java b/java/src/Ice/src/main/java/IceInternal/InputStreamWrapper.java index e86f49e6800..831ac3ee1cf 100644 --- a/java/src/Ice/src/main/java/IceInternal/InputStreamWrapper.java +++ b/java/src/Ice/src/main/java/IceInternal/InputStreamWrapper.java @@ -10,29 +10,27 @@ package IceInternal; // -// Class to provide a java.io.InputStream on top of a BasicStream. +// Class to provide a java.io.InputStream on top of a ByteBuffer. // We use this to deserialize arbitrary Java serializable classes from -// a Slice byte sequence. This class is a wrapper around a BasicStream +// a Slice byte sequence. This class is a wrapper around a Buffer // that passes all methods through. // public class InputStreamWrapper extends java.io.InputStream { - public - InputStreamWrapper(int size, BasicStream s) + public InputStreamWrapper(int size, java.nio.ByteBuffer buf) { - _s = s; + _buf = buf; _markPos = 0; } @Override - public int - read() + public int read() throws java.io.IOException { try { - return _s.getBuffer().b.get(); + return _buf.get(); } catch(java.lang.Exception ex) { @@ -41,21 +39,19 @@ public class InputStreamWrapper extends java.io.InputStream } @Override - public int - read(byte[] b) + public int read(byte[] b) throws java.io.IOException { return read(b, 0, b.length); } @Override - public int - read(byte[] b, int offset, int count) + public int read(byte[] b, int offset, int count) throws java.io.IOException { try { - _s.getBuffer().b.get(b, offset, count); + _buf.get(b, offset, count); } catch(java.lang.Exception ex) { @@ -65,41 +61,36 @@ public class InputStreamWrapper extends java.io.InputStream } @Override - public int - available() + public int available() { - return _s.getBuffer().b.remaining(); + return _buf.remaining(); } @Override - public void - mark(int readlimit) + public void mark(int readlimit) { - _markPos = _s.pos(); + _markPos = _buf.position(); } @Override - public void - reset() + public void reset() throws java.io.IOException { - _s.pos(_markPos); + _buf.position(_markPos); } @Override - public boolean - markSupported() + public boolean markSupported() { return true; } @Override - public void - close() + public void close() throws java.io.IOException { } - private BasicStream _s; + private java.nio.ByteBuffer _buf; private int _markPos; } diff --git a/java/src/Ice/src/main/java/IceInternal/Instance.java b/java/src/Ice/src/main/java/IceInternal/Instance.java index 1e0f07be4a7..21dd67c0394 100644 --- a/java/src/Ice/src/main/java/IceInternal/Instance.java +++ b/java/src/Ice/src/main/java/IceInternal/Instance.java @@ -11,7 +11,7 @@ package IceInternal; import java.util.concurrent.TimeUnit; -public final class Instance +public final class Instance implements Ice.ClassResolver, Ice.CompactIdResolver { static private class ThreadObserverHelper { @@ -255,34 +255,6 @@ public final class Instance return _outgoingConnectionFactory; } - @SuppressWarnings("deprecation") - public synchronized void addObjectFactory(final Ice.ObjectFactory factory, final String id) - { - // - // Create a ValueFactory wrapper around the given ObjectFactory and register the wrapper - // with the value factory manager. This may raise AlreadyRegisteredException. - // - Ice.ValueFactory wrapper = new Ice.ValueFactory() - { - public Ice.Object create(String id) - { - return factory.create(id); - } - }; - _initData.valueFactoryManager.add(wrapper, id); - - // - // Also record the object factory in our own map. - // - _objectFactoryMap.put(id, factory); - } - - @SuppressWarnings("deprecation") - public synchronized Ice.ObjectFactory findObjectFactory(String id) - { - return _objectFactoryMap.get(id); - } - public synchronized ObjectAdapterFactory objectAdapterFactory() { @@ -752,29 +724,134 @@ public final class Instance return _initData.classLoader; } - public synchronized String - getClassForType(String type) + // + // From Ice.ClassResolver. + // + public Class<?> resolveClass(String typeId) + throws LinkageError { - return _typeToClassMap.get(type); + Class<?> c = null; + + // + // To convert a Slice type id into a Java class, we do the following: + // + // 1. Convert the Slice type id into a classname (e.g., ::M::X -> M.X). + // 2. If that fails, extract the top-level module (if any) from the type id + // and check for an Package property. If found, prepend the property + // value to the classname. + // 3. If that fails, check for an Default.Package property. If found, + // prepend the property value to the classname. + // + String className; + boolean addClass = false; + + synchronized(this) + { + className = _typeToClassMap.get(typeId); + } + + if(className == null) + { + className = Ice.Util.typeIdToClass(typeId); + addClass = true; + } + + c = getConcreteClass(className); + + if(c == null) + { + int pos = typeId.indexOf(':', 2); + if(pos != -1) + { + String topLevelModule = typeId.substring(2, pos); + String pkg = _initData.properties.getProperty("Ice.Package." + topLevelModule); + if(pkg.length() > 0) + { + c = getConcreteClass(pkg + "." + className); + } + } + } + + if(c == null) + { + String pkg = _initData.properties.getProperty("Ice.Default.Package"); + if(pkg.length() > 0) + { + c = getConcreteClass(pkg + "." + className); + } + } + + if(c != null && addClass) + { + synchronized(this) + { + className = c.getName(); + if(_typeToClassMap.containsKey(typeId)) + { + assert(_typeToClassMap.get(typeId).equals(className)); + } + else + { + _typeToClassMap.put(typeId, className); + } + } + } + + return c; } - public synchronized void - addClassForType(String type, String className) + // + // From Ice.CompactIdResolver. + // + public String resolve(int compactId) { - if(_typeToClassMap.containsKey(type)) + String className = "IceCompactId.TypeId_" + Integer.toString(compactId); + Class<?> c = getConcreteClass(className); + if(c == null) { - assert(_typeToClassMap.get(type).equals(className)); + for(String pkg : _packages) + { + c = getConcreteClass(pkg + "." + className); + if(c != null) + { + break; + } + } } - else + if(c != null) { - _typeToClassMap.put(type, className); + try + { + return (String)c.getField("typeId").get(null); + } + catch(Exception ex) + { + assert(false); + } } + return ""; } - public String[] - getPackages() + public Class<?> getConcreteClass(String className) + throws LinkageError { - return _packages; + Class<?> c = findClass(className); + + if(c != null) + { + // + // Ensure the class is instantiable. The constants are + // defined in the JVM specification (0x200 = interface, + // 0x400 = abstract). + // + final int modifiers = c.getModifiers(); + if((modifiers & 0x200) == 0 && (modifiers & 0x400) == 0) + { + return c; + } + } + + return null; } public boolean @@ -817,7 +894,7 @@ public final class Instance synchronized(Instance.class) { - if(!_oneOfDone) + if(!_oneOffDone) { String stdOut = _initData.properties.getProperty("Ice.StdOut"); String stdErr = _initData.properties.getProperty("Ice.StdErr"); @@ -867,7 +944,7 @@ public final class Instance } } - _oneOfDone = true; + _oneOffDone = true; } } @@ -1003,7 +1080,7 @@ public final class Instance if(_initData.valueFactoryManager == null) { - _initData.valueFactoryManager = new Ice.ValueFactoryManagerI(); + _initData.valueFactoryManager = new ValueFactoryManagerI(); } _outgoingConnectionFactory = new OutgoingConnectionFactory(communicator, this); @@ -1401,9 +1478,9 @@ public final class Instance // called once. // - for(java.util.Map.Entry<String, Ice.ObjectFactory> e : _objectFactoryMap.entrySet()) + for(Ice.ObjectFactory f : _objectFactoryMap.values()) { - e.getValue().destroy(); + f.destroy(); } _objectFactoryMap.clear(); @@ -1534,6 +1611,31 @@ public final class Instance } } + @SuppressWarnings("deprecation") + public synchronized void addObjectFactory(final Ice.ObjectFactory factory, String id) + { + // + // Create a ValueFactory wrapper around the given ObjectFactory and register the wrapper + // with the value factory manager. This may raise AlreadyRegisteredException. + // + _initData.valueFactoryManager.add( + new Ice.ValueFactory() + { + public Ice.Object create(String id) + { + return factory.create(id); + } + }, id); + + _objectFactoryMap.put(id, factory); + } + + @SuppressWarnings("deprecation") + public synchronized Ice.ObjectFactory findObjectFactory(String id) + { + return _objectFactoryMap.get(id); + } + private void updateConnectionObservers() { @@ -1766,7 +1868,7 @@ public final class Instance final private String[] _packages; final private boolean _useApplicationClassLoader; - private static boolean _oneOfDone = false; + private static boolean _oneOffDone = false; private QueueExecutorService _queueExecutorService; private QueueExecutor _queueExecutor; diff --git a/java/src/Ice/src/main/java/IceInternal/ListPatcher.java b/java/src/Ice/src/main/java/IceInternal/ListPatcher.java index 3072ff65f6f..5e58c0375d2 100644 --- a/java/src/Ice/src/main/java/IceInternal/ListPatcher.java +++ b/java/src/Ice/src/main/java/IceInternal/ListPatcher.java @@ -9,10 +9,10 @@ package IceInternal; -public class ListPatcher<T> implements Patcher, Ice.ReadObjectCallback +public class ListPatcher<T> implements Ice.ReadObjectCallback { - public - ListPatcher(java.util.List<T> list, Class<T> cls, String type, int index) + // TBD: Remove _type? + public ListPatcher(java.util.List<T> list, Class<T> cls, String type, int index) { _list = list; _cls = cls; @@ -20,9 +20,7 @@ public class ListPatcher<T> implements Patcher, Ice.ReadObjectCallback _index = index; } - @Override - public void - patch(Ice.Object v) + public void objectReady(Ice.Object v) { if(v != null) { @@ -44,20 +42,6 @@ public class ListPatcher<T> implements Patcher, Ice.ReadObjectCallback _list.set(_index, _cls.cast(v)); } - @Override - public String - type() - { - return _type; - } - - @Override - public void - invoke(Ice.Object v) - { - patch(v); - } - private java.util.List<T> _list; private Class<T> _cls; private String _type; diff --git a/java/src/Ice/src/main/java/IceInternal/ObjectInputStream.java b/java/src/Ice/src/main/java/IceInternal/ObjectInputStream.java index 085fe9793b6..fec422559e0 100644 --- a/java/src/Ice/src/main/java/IceInternal/ObjectInputStream.java +++ b/java/src/Ice/src/main/java/IceInternal/ObjectInputStream.java @@ -17,8 +17,7 @@ package IceInternal; public class ObjectInputStream extends java.io.ObjectInputStream { - public - ObjectInputStream(Instance instance, java.io.InputStream in) + public ObjectInputStream(Instance instance, java.io.InputStream in) throws java.io.IOException { super(in); @@ -26,10 +25,14 @@ public class ObjectInputStream extends java.io.ObjectInputStream } @Override - protected Class<?> - resolveClass(java.io.ObjectStreamClass cls) + protected Class<?> resolveClass(java.io.ObjectStreamClass cls) throws java.io.IOException, ClassNotFoundException { + if(_instance == null) + { + throw new Ice.MarshalException("cannot unmarshal a serializable without a communicator"); + } + try { Class<?> c = _instance.findClass(cls.getName()); diff --git a/java/src/Ice/src/main/java/IceInternal/OpaqueEndpointI.java b/java/src/Ice/src/main/java/IceInternal/OpaqueEndpointI.java index a4a3b9cc4bd..d73bd6c46c3 100644 --- a/java/src/Ice/src/main/java/IceInternal/OpaqueEndpointI.java +++ b/java/src/Ice/src/main/java/IceInternal/OpaqueEndpointI.java @@ -31,11 +31,11 @@ final class OpaqueEndpointI extends EndpointI calcHashValue(); } - public OpaqueEndpointI(short type, BasicStream s) + public OpaqueEndpointI(short type, Ice.InputStream s) { _type = type; - _rawEncoding = s.getReadEncoding(); - int sz = s.getReadEncapsSize(); + _rawEncoding = s.getEncoding(); + int sz = s.getEncapsulationSize(); _rawBytes = s.readBlob(sz); calcHashValue(); @@ -45,11 +45,11 @@ final class OpaqueEndpointI extends EndpointI // Marshal the endpoint // @Override - public void streamWrite(BasicStream s) + public void streamWrite(Ice.OutputStream s) { - s.startWriteEncaps(_rawEncoding, Ice.FormatType.DefaultFormat); + s.startEncapsulation(_rawEncoding, Ice.FormatType.DefaultFormat); s.writeBlob(_rawBytes); - s.endWriteEncaps(); + s.endEncapsulation(); } // diff --git a/java/src/Ice/src/main/java/IceInternal/OutgoingAsync.java b/java/src/Ice/src/main/java/IceInternal/OutgoingAsync.java index 5c6371d4ab1..6af3463a87c 100644 --- a/java/src/Ice/src/main/java/IceInternal/OutgoingAsync.java +++ b/java/src/Ice/src/main/java/IceInternal/OutgoingAsync.java @@ -31,7 +31,7 @@ public class OutgoingAsync extends ProxyOutgoingAsyncBase _is = null; } - public OutgoingAsync(Ice.ObjectPrx prx, String operation, CallbackBase cb, BasicStream is, BasicStream os) + public OutgoingAsync(Ice.ObjectPrx prx, String operation, CallbackBase cb, Ice.InputStream is, Ice.OutputStream os) { super((Ice.ObjectPrxHelperBase)prx, operation, cb, os); _encoding = Protocol.getCompatibleEncoding(_proxy.__reference().getEncoding()); @@ -72,7 +72,7 @@ public class OutgoingAsync extends ProxyOutgoingAsyncBase Reference ref = _proxy.__reference(); - ref.getIdentity().__write(_os); + ref.getIdentity().ice_write(_os); // // For compatibility with the old FacetPath. @@ -134,7 +134,7 @@ public class OutgoingAsync extends ProxyOutgoingAsyncBase @Override public int invokeCollocated(CollocatedRequestHandler handler) { - // The BasicStream cannot be cached if the proxy is not a twoway or there is an invocation timeout set. + // The stream cannot be cached if the proxy is not a twoway or there is an invocation timeout set. if(!_proxy.ice_isTwoway() || _proxy.__reference().getInvocationTimeout() > 0) { // Disable caching by marking the streams as cached! @@ -184,7 +184,7 @@ public class OutgoingAsync extends ProxyOutgoingAsyncBase } @Override - public final boolean completed(BasicStream is) + public final boolean completed(Ice.InputStream is) { // // NOTE: this method is called from ConnectionI.parseMessage @@ -207,7 +207,7 @@ public class OutgoingAsync extends ProxyOutgoingAsyncBase // _is can already be initialized if the invocation is retried if(_is == null) { - _is = new IceInternal.BasicStream(_instance, IceInternal.Protocol.currentProtocolEncoding); + _is = new Ice.InputStream(_instance, IceInternal.Protocol.currentProtocolEncoding); } _is.swap(is); replyStatus = _is.readByte(); @@ -233,7 +233,7 @@ public class OutgoingAsync extends ProxyOutgoingAsyncBase case ReplyStatus.replyOperationNotExist: { Ice.Identity id = new Ice.Identity(); - id.__read(_is); + id.ice_read(_is); // // For compatibility with the old FacetPath. @@ -341,53 +341,53 @@ public class OutgoingAsync extends ProxyOutgoingAsyncBase } } - public BasicStream startWriteParams(Ice.FormatType format) + public Ice.OutputStream startWriteParams(Ice.FormatType format) { - _os.startWriteEncaps(_encoding, format); + _os.startEncapsulation(_encoding, format); return _os; } public void endWriteParams() { - _os.endWriteEncaps(); + _os.endEncapsulation(); } public void writeEmptyParams() { - _os.writeEmptyEncaps(_encoding); + _os.writeEmptyEncapsulation(_encoding); } public void writeParamEncaps(byte[] encaps) { if(encaps == null || encaps.length == 0) { - _os.writeEmptyEncaps(_encoding); + _os.writeEmptyEncapsulation(_encoding); } else { - _os.writeEncaps(encaps); + _os.writeEncapsulation(encaps); } } - public IceInternal.BasicStream startReadParams() + public Ice.InputStream startReadParams() { - _is.startReadEncaps(); + _is.startEncapsulation(); return _is; } public void endReadParams() { - _is.endReadEncaps(); + _is.endEncapsulation(); } public void readEmptyParams() { - _is.skipEmptyEncaps(null); + _is.skipEmptyEncapsulation(null); } public byte[] readParamEncaps() { - return _is.readEncaps(null); + return _is.readEncapsulation(null); } public final void throwUserException() @@ -395,12 +395,12 @@ public class OutgoingAsync extends ProxyOutgoingAsyncBase { try { - _is.startReadEncaps(); + _is.startEncapsulation(); _is.throwException(null); } catch(Ice.UserException ex) { - _is.endReadEncaps(); + _is.endEncapsulation(); throw ex; } } @@ -433,7 +433,7 @@ public class OutgoingAsync extends ProxyOutgoingAsyncBase } final private Ice.EncodingVersion _encoding; - private BasicStream _is; + private Ice.InputStream _is; // // If true this AMI request is being used for a generated synchronous invocation. diff --git a/java/src/Ice/src/main/java/IceInternal/OutgoingAsyncBase.java b/java/src/Ice/src/main/java/IceInternal/OutgoingAsyncBase.java index 4702d22f1d4..84926df21b4 100644 --- a/java/src/Ice/src/main/java/IceInternal/OutgoingAsyncBase.java +++ b/java/src/Ice/src/main/java/IceInternal/OutgoingAsyncBase.java @@ -21,7 +21,7 @@ public abstract class OutgoingAsyncBase extends IceInternal.AsyncResultI return sent(true); } - public boolean completed(BasicStream is) + public boolean completed(Ice.InputStream is) { assert(false); // Must be implemented by classes that handle responses return false; @@ -58,7 +58,7 @@ public abstract class OutgoingAsyncBase extends IceInternal.AsyncResultI } } - public final IceInternal.BasicStream getOs() + public final Ice.OutputStream getOs() { return _os; } @@ -66,10 +66,11 @@ public abstract class OutgoingAsyncBase extends IceInternal.AsyncResultI protected OutgoingAsyncBase(Ice.Communicator com, Instance instance, String op, CallbackBase del) { super(com, instance, op, del); - _os = new BasicStream(instance, Protocol.currentProtocolEncoding); + _os = new Ice.OutputStream(instance, Protocol.currentProtocolEncoding); } - protected OutgoingAsyncBase(Ice.Communicator com, Instance instance, String op, CallbackBase del, BasicStream os) + protected OutgoingAsyncBase(Ice.Communicator com, Instance instance, String op, CallbackBase del, + Ice.OutputStream os) { super(com, instance, op, del); _os = os; @@ -101,6 +102,6 @@ public abstract class OutgoingAsyncBase extends IceInternal.AsyncResultI return super.finished(ex); } - protected BasicStream _os; + protected Ice.OutputStream _os; protected Ice.Instrumentation.ChildInvocationObserver _childObserver; } diff --git a/java/src/Ice/src/main/java/IceInternal/OutputStreamWrapper.java b/java/src/Ice/src/main/java/IceInternal/OutputStreamWrapper.java index 7cbcf16a275..634a1c5d052 100644 --- a/java/src/Ice/src/main/java/IceInternal/OutputStreamWrapper.java +++ b/java/src/Ice/src/main/java/IceInternal/OutputStreamWrapper.java @@ -12,7 +12,7 @@ package IceInternal; import java.io.*; // -// Class to provide a java.io.OutputStream on top of a BasicStream. +// Class to provide a java.io.OutputStream on top of our stream. // We use this to serialize arbitrary Java serializable classes into // // Slice sequences are encoded on the wire as a count of elements, followed @@ -21,7 +21,7 @@ import java.io.*; // data copying, this class mantains a private _bytes array of 254 bytes and, // initially, writes data into that array. If more than 254 bytes end up being // written, we write a dummy sequence size of 255 (which occupies five bytes -// on the wire) into the BasicStream and, once this stream is closed, patch +// on the wire) into the stream and, once this stream is closed, patch // that size to match the actual size. Otherwise, if the _bytes buffer contains // fewer than 255 bytes when this stream is closed, we write the sequence size // as a single byte, followed by the contents of the _bytes buffer. @@ -30,7 +30,7 @@ import java.io.*; public class OutputStreamWrapper extends java.io.OutputStream { public - OutputStreamWrapper(BasicStream s) + OutputStreamWrapper(Ice.OutputStream s) { _s = s; _spos = s.pos(); @@ -139,7 +139,7 @@ public class OutputStreamWrapper extends java.io.OutputStream flush() throws IOException { // This does nothing because we do not know the final size of a writable stream until it is closed, - // and we cannot write to the BasicStream until we know whether the final size is < 255 or not. + // and we cannot write to the stream until we know whether the final size is < 255 or not. } @Override @@ -171,7 +171,7 @@ public class OutputStreamWrapper extends java.io.OutputStream } } - private BasicStream _s; + private Ice.OutputStream _s; private int _spos; private byte[] _bytes; private int _pos; diff --git a/java/src/Ice/src/main/java/IceInternal/Patcher.java b/java/src/Ice/src/main/java/IceInternal/Patcher.java deleted file mode 100644 index 071282f9bd1..00000000000 --- a/java/src/Ice/src/main/java/IceInternal/Patcher.java +++ /dev/null @@ -1,16 +0,0 @@ -// ********************************************************************** -// -// Copyright (c) 2003-2015 ZeroC, Inc. All rights reserved. -// -// This copy of Ice is licensed to you under the terms described in the -// ICE_LICENSE file included in this distribution. -// -// ********************************************************************** - -package IceInternal; - -public interface Patcher -{ - void patch(Ice.Object v); - String type(); -} diff --git a/java/src/Ice/src/main/java/IceInternal/Protocol.java b/java/src/Ice/src/main/java/IceInternal/Protocol.java index eb98ec0e9f1..2002e0cbfe2 100644 --- a/java/src/Ice/src/main/java/IceInternal/Protocol.java +++ b/java/src/Ice/src/main/java/IceInternal/Protocol.java @@ -185,4 +185,14 @@ final public class Protocol { return version.major == supported.major && version.minor <= supported.minor; } + + public static final int OPTIONAL_END_MARKER = 0xFF; + + public static final byte FLAG_HAS_TYPE_ID_STRING = (byte)(1<<0); + public static final byte FLAG_HAS_TYPE_ID_INDEX = (byte)(1<<1); + public static final byte FLAG_HAS_TYPE_ID_COMPACT = (byte)(1<<1 | 1<<0); + public static final byte FLAG_HAS_OPTIONAL_MEMBERS = (byte)(1<<2); + public static final byte FLAG_HAS_INDIRECTION_TABLE = (byte)(1<<3); + public static final byte FLAG_HAS_SLICE_SIZE = (byte)(1<<4); + public static final byte FLAG_IS_LAST_SLICE = (byte)(1<<5); } diff --git a/java/src/Ice/src/main/java/IceInternal/ProxyFactory.java b/java/src/Ice/src/main/java/IceInternal/ProxyFactory.java index 697bf21977b..2edcb3d6bfc 100644 --- a/java/src/Ice/src/main/java/IceInternal/ProxyFactory.java +++ b/java/src/Ice/src/main/java/IceInternal/ProxyFactory.java @@ -57,10 +57,10 @@ public final class ProxyFactory } public Ice.ObjectPrx - streamToProxy(BasicStream s) + streamToProxy(Ice.InputStream s) { Ice.Identity ident = new Ice.Identity(); - ident.__read(s); + ident.ice_read(s); Reference ref = _instance.referenceFactory().create(ident, s); return referenceToProxy(ref); @@ -81,25 +81,6 @@ public final class ProxyFactory } } - public void - proxyToStream(Ice.ObjectPrx proxy, BasicStream s) - { - if(proxy != null) - { - Ice.ObjectPrxHelperBase h = (Ice.ObjectPrxHelperBase)proxy; - Reference ref = h.__reference(); - ref.getIdentity().__write(s); - ref.streamWrite(s); - } - else - { - Ice.Identity ident = new Ice.Identity(); - ident.name = ""; - ident.category = ""; - ident.__write(s); - } - } - public int checkRetryAfterException(Ice.LocalException ex, Reference ref, Ice.Holder<Integer> sleepInterval, int cnt) { diff --git a/java/src/Ice/src/main/java/IceInternal/ProxyOutgoingAsyncBase.java b/java/src/Ice/src/main/java/IceInternal/ProxyOutgoingAsyncBase.java index 58e7288cc95..cbcdd163773 100644 --- a/java/src/Ice/src/main/java/IceInternal/ProxyOutgoingAsyncBase.java +++ b/java/src/Ice/src/main/java/IceInternal/ProxyOutgoingAsyncBase.java @@ -145,7 +145,7 @@ public abstract class ProxyOutgoingAsyncBase extends OutgoingAsyncBase _sent = false; } - protected ProxyOutgoingAsyncBase(Ice.ObjectPrxHelperBase prx, String op, CallbackBase delegate, BasicStream os) + protected ProxyOutgoingAsyncBase(Ice.ObjectPrxHelperBase prx, String op, CallbackBase delegate, Ice.OutputStream os) { super(prx.ice_getCommunicator(), prx.__reference().getInstance(), op, delegate, os); _proxy = prx; diff --git a/java/src/Ice/src/main/java/IceInternal/Reference.java b/java/src/Ice/src/main/java/IceInternal/Reference.java index d06d45080e2..7505ce2e519 100644 --- a/java/src/Ice/src/main/java/IceInternal/Reference.java +++ b/java/src/Ice/src/main/java/IceInternal/Reference.java @@ -257,7 +257,7 @@ public abstract class Reference implements Cloneable // Marshal the reference. // public void - streamWrite(BasicStream s) + streamWrite(Ice.OutputStream s) { // // Don't write the identity here. Operations calling streamWrite @@ -281,10 +281,10 @@ public abstract class Reference implements Cloneable s.writeBool(_secure); - if(!s.getWriteEncoding().equals(Ice.Util.Encoding_1_0)) + if(!s.getEncoding().equals(Ice.Util.Encoding_1_0)) { - _protocol.__write(s); - _encoding.__write(s); + _protocol.ice_write(s); + _encoding.ice_write(s); } // Derived class writes the remainder of the reference. diff --git a/java/src/Ice/src/main/java/IceInternal/ReferenceFactory.java b/java/src/Ice/src/main/java/IceInternal/ReferenceFactory.java index 042a01ace06..d41e5910ae4 100644 --- a/java/src/Ice/src/main/java/IceInternal/ReferenceFactory.java +++ b/java/src/Ice/src/main/java/IceInternal/ReferenceFactory.java @@ -544,7 +544,7 @@ public final class ReferenceFactory } public Reference - create(Ice.Identity ident, BasicStream s) + create(Ice.Identity ident, Ice.InputStream s) { // // Don't read the identity here. Operations calling this @@ -584,12 +584,12 @@ public final class ReferenceFactory Ice.ProtocolVersion protocol; Ice.EncodingVersion encoding; - if(!s.getReadEncoding().equals(Ice.Util.Encoding_1_0)) + if(!s.getEncoding().equals(Ice.Util.Encoding_1_0)) { protocol = new Ice.ProtocolVersion(); - protocol.__read(s); + protocol.ice_read(s); encoding = new Ice.EncodingVersion(); - encoding.__read(s); + encoding.ice_read(s); } else { diff --git a/java/src/Ice/src/main/java/IceInternal/ResponseHandler.java b/java/src/Ice/src/main/java/IceInternal/ResponseHandler.java index ee20bc08a6b..06ddd77a33a 100644 --- a/java/src/Ice/src/main/java/IceInternal/ResponseHandler.java +++ b/java/src/Ice/src/main/java/IceInternal/ResponseHandler.java @@ -11,7 +11,7 @@ package IceInternal; public interface ResponseHandler { - void sendResponse(int requestId, BasicStream os, byte status, boolean amd); + void sendResponse(int requestId, Ice.OutputStream os, byte status, boolean amd); void sendNoResponse(); boolean systemException(int requestId, Ice.SystemException ex, boolean amd); void invokeException(int requestId, Ice.LocalException ex, int invokeNum, boolean amd); diff --git a/java/src/Ice/src/main/java/IceInternal/RoutableReference.java b/java/src/Ice/src/main/java/IceInternal/RoutableReference.java index 4181ffda251..e4228ccb4cc 100644 --- a/java/src/Ice/src/main/java/IceInternal/RoutableReference.java +++ b/java/src/Ice/src/main/java/IceInternal/RoutableReference.java @@ -298,7 +298,7 @@ public class RoutableReference extends Reference @Override public void - streamWrite(BasicStream s) + streamWrite(Ice.OutputStream s) throws Ice.MarshalException { super.streamWrite(s); diff --git a/java/src/Ice/src/main/java/IceInternal/SequencePatcher.java b/java/src/Ice/src/main/java/IceInternal/SequencePatcher.java index 90e6a939451..ec4cfc22997 100644 --- a/java/src/Ice/src/main/java/IceInternal/SequencePatcher.java +++ b/java/src/Ice/src/main/java/IceInternal/SequencePatcher.java @@ -9,10 +9,10 @@ package IceInternal; -public class SequencePatcher implements Patcher, Ice.ReadObjectCallback +public class SequencePatcher implements Ice.ReadObjectCallback { - public - SequencePatcher(java.lang.Object[] seq, Class<?> cls, String type, int index) + // TBD: Remove _type? + public SequencePatcher(java.lang.Object[] seq, Class<?> cls, String type, int index) { _seq = seq; _cls = cls; @@ -20,9 +20,7 @@ public class SequencePatcher implements Patcher, Ice.ReadObjectCallback _index = index; } - @Override - public void - patch(Ice.Object v) + public void objectReady(Ice.Object v) { if(v != null) { @@ -39,20 +37,6 @@ public class SequencePatcher implements Patcher, Ice.ReadObjectCallback _seq[_index] = v; } - @Override - public String - type() - { - return _type; - } - - @Override - public void - invoke(Ice.Object v) - { - patch(v); - } - private java.lang.Object[] _seq; private Class<?> _cls; private String _type; diff --git a/java/src/Ice/src/main/java/IceInternal/TcpEndpointFactory.java b/java/src/Ice/src/main/java/IceInternal/TcpEndpointFactory.java index 34ff8ba86c2..5ed615c82e1 100644 --- a/java/src/Ice/src/main/java/IceInternal/TcpEndpointFactory.java +++ b/java/src/Ice/src/main/java/IceInternal/TcpEndpointFactory.java @@ -37,7 +37,7 @@ final class TcpEndpointFactory implements EndpointFactory } @Override - public EndpointI read(BasicStream s) + public EndpointI read(Ice.InputStream s) { return new TcpEndpointI(_instance, s); } diff --git a/java/src/Ice/src/main/java/IceInternal/TcpEndpointI.java b/java/src/Ice/src/main/java/IceInternal/TcpEndpointI.java index a4547612335..b49fd206827 100644 --- a/java/src/Ice/src/main/java/IceInternal/TcpEndpointI.java +++ b/java/src/Ice/src/main/java/IceInternal/TcpEndpointI.java @@ -26,7 +26,7 @@ final class TcpEndpointI extends IPEndpointI implements WSEndpointDelegate _compress = false; } - public TcpEndpointI(ProtocolInstance instance, BasicStream s) + public TcpEndpointI(ProtocolInstance instance, Ice.InputStream s) { super(instance, s); _timeout = s.readInt(); @@ -253,7 +253,7 @@ final class TcpEndpointI extends IPEndpointI implements WSEndpointDelegate } @Override - public void streamWriteImpl(BasicStream s) + public void streamWriteImpl(Ice.OutputStream s) { super.streamWriteImpl(s); s.writeInt(_timeout); diff --git a/java/src/Ice/src/main/java/IceInternal/ThreadPoolCurrent.java b/java/src/Ice/src/main/java/IceInternal/ThreadPoolCurrent.java index 71e665759ae..4500da04ec9 100644 --- a/java/src/Ice/src/main/java/IceInternal/ThreadPoolCurrent.java +++ b/java/src/Ice/src/main/java/IceInternal/ThreadPoolCurrent.java @@ -14,7 +14,7 @@ public final class ThreadPoolCurrent ThreadPoolCurrent(Instance instance, ThreadPool threadPool, ThreadPool.EventHandlerThread thread) { operation = SocketOperation.None; - stream = new BasicStream(instance, Protocol.currentProtocolEncoding); + stream = new Ice.InputStream(instance, Protocol.currentProtocolEncoding); _threadPool = threadPool; _thread = thread; @@ -23,7 +23,7 @@ public final class ThreadPoolCurrent } public int operation; - public BasicStream stream; // A per-thread stream to be used by event handlers for optimization. + public Ice.InputStream stream; // A per-thread stream to be used by event handlers for optimization. public boolean ioReady() diff --git a/java/src/Ice/src/main/java/IceInternal/TraceUtil.java b/java/src/Ice/src/main/java/IceInternal/TraceUtil.java index 223a1886f37..9e8b121cc71 100644 --- a/java/src/Ice/src/main/java/IceInternal/TraceUtil.java +++ b/java/src/Ice/src/main/java/IceInternal/TraceUtil.java @@ -12,15 +12,16 @@ package IceInternal; public final class TraceUtil { public static void - traceSend(BasicStream str, Ice.Logger logger, TraceLevels tl) + traceSend(Ice.OutputStream str, Ice.Logger logger, TraceLevels tl) { if(tl.protocol >= 1) { int p = str.pos(); - str.pos(0); + Ice.InputStream is = new Ice.InputStream(str.instance(), str.getEncoding(), str.getBuffer(), false); + is.pos(0); java.io.StringWriter s = new java.io.StringWriter(); - byte type = printMessage(s, str); + byte type = printMessage(s, is); logger.trace(tl.protocolCat, "sending " + getMessageTypeAsString(type) + " " + s.toString()); @@ -29,7 +30,7 @@ public final class TraceUtil } public static void - traceRecv(BasicStream str, Ice.Logger logger, TraceLevels tl) + traceRecv(Ice.InputStream str, Ice.Logger logger, TraceLevels tl) { if(tl.protocol >= 1) { @@ -46,7 +47,25 @@ public final class TraceUtil } public static void - trace(String heading, BasicStream str, Ice.Logger logger, TraceLevels tl) + trace(String heading, Ice.OutputStream str, Ice.Logger logger, TraceLevels tl) + { + if(tl.protocol >= 1) + { + int p = str.pos(); + Ice.InputStream is = new Ice.InputStream(str.instance(), str.getEncoding(), str.getBuffer(), false); + is.pos(0); + + java.io.StringWriter s = new java.io.StringWriter(); + s.write(heading); + printMessage(s, is); + + logger.trace(tl.protocolCat, s.toString()); + str.pos(p); + } + } + + public static void + trace(String heading, Ice.InputStream str, Ice.Logger logger, TraceLevels tl) { if(tl.protocol >= 1) { @@ -64,7 +83,7 @@ public final class TraceUtil private static java.util.Set<String> slicingIds = new java.util.HashSet<String>(); - synchronized static void + public synchronized static void traceSlicing(String kind, String typeId, String slicingCat, Ice.Logger logger) { if(slicingIds.add(typeId)) @@ -76,7 +95,7 @@ public final class TraceUtil } public static void - dumpStream(BasicStream stream) + dumpStream(Ice.InputStream stream) { int pos = stream.pos(); stream.pos(0); @@ -143,12 +162,12 @@ public final class TraceUtil } private static void - printIdentityFacetOperation(java.io.Writer out, BasicStream stream) + printIdentityFacetOperation(java.io.Writer out, Ice.InputStream stream) { try { Ice.Identity identity = new Ice.Identity(); - identity.__read(stream); + identity.ice_read(stream); out.write("\nidentity = " + stream.instance().identityToString(identity)); String[] facet = stream.readStringSeq(); @@ -168,7 +187,7 @@ public final class TraceUtil } private static void - printRequest(java.io.StringWriter s, BasicStream str) + printRequest(java.io.StringWriter s, Ice.InputStream str) { int requestId = str.readInt(); s.write("\nrequest id = " + requestId); @@ -181,7 +200,7 @@ public final class TraceUtil } private static void - printBatchRequest(java.io.StringWriter s, BasicStream str) + printBatchRequest(java.io.StringWriter s, Ice.InputStream str) { int batchRequestNum = str.readInt(); s.write("\nnumber of requests = " + batchRequestNum); @@ -194,7 +213,7 @@ public final class TraceUtil } private static void - printReply(java.io.StringWriter s, BasicStream str) + printReply(java.io.StringWriter s, Ice.InputStream str) { int requestId = str.readInt(); s.write("\nrequest id = " + requestId); @@ -296,7 +315,7 @@ public final class TraceUtil if(replyStatus == ReplyStatus.replyOK || replyStatus == ReplyStatus.replyUserException) { - Ice.EncodingVersion v = str.skipEncaps(); + Ice.EncodingVersion v = str.skipEncapsulation(); if(!v.equals(Ice.Util.Encoding_1_0)) { s.write("\nencoding = "); @@ -306,7 +325,7 @@ public final class TraceUtil } private static void - printRequestHeader(java.io.Writer out, BasicStream stream) + printRequestHeader(java.io.Writer out, Ice.InputStream stream) { printIdentityFacetOperation(out, stream); @@ -354,7 +373,7 @@ public final class TraceUtil } } - Ice.EncodingVersion v = stream.skipEncaps(); + Ice.EncodingVersion v = stream.skipEncapsulation(); if(!v.equals(Ice.Util.Encoding_1_0)) { out.write("\nencoding = "); @@ -368,7 +387,7 @@ public final class TraceUtil } private static byte - printHeader(java.io.Writer out, BasicStream stream) + printHeader(java.io.Writer out, Ice.InputStream stream) { stream.readByte(); // Don't bother printing the magic number stream.readByte(); @@ -433,7 +452,7 @@ public final class TraceUtil } static private byte - printMessage(java.io.StringWriter s, BasicStream str) + printMessage(java.io.StringWriter s, Ice.InputStream str) { byte type = printHeader(s, str); diff --git a/java/src/Ice/src/main/java/IceInternal/UdpEndpointFactory.java b/java/src/Ice/src/main/java/IceInternal/UdpEndpointFactory.java index ce1e5f468e0..678f725f136 100644 --- a/java/src/Ice/src/main/java/IceInternal/UdpEndpointFactory.java +++ b/java/src/Ice/src/main/java/IceInternal/UdpEndpointFactory.java @@ -37,7 +37,7 @@ final class UdpEndpointFactory implements EndpointFactory } @Override - public EndpointI read(BasicStream s) + public EndpointI read(Ice.InputStream s) { return new UdpEndpointI(_instance, s); } diff --git a/java/src/Ice/src/main/java/IceInternal/UdpEndpointI.java b/java/src/Ice/src/main/java/IceInternal/UdpEndpointI.java index 1c211b3ab8d..340f7ade03e 100644 --- a/java/src/Ice/src/main/java/IceInternal/UdpEndpointI.java +++ b/java/src/Ice/src/main/java/IceInternal/UdpEndpointI.java @@ -28,10 +28,10 @@ final class UdpEndpointI extends IPEndpointI _compress = false; } - public UdpEndpointI(ProtocolInstance instance, BasicStream s) + public UdpEndpointI(ProtocolInstance instance, Ice.InputStream s) { super(instance, s); - if(s.getReadEncoding().equals(Ice.Util.Encoding_1_0)) + if(s.getEncoding().equals(Ice.Util.Encoding_1_0)) { s.readByte(); s.readByte(); @@ -252,13 +252,13 @@ final class UdpEndpointI extends IPEndpointI // Marshal the endpoint // @Override - public void streamWriteImpl(BasicStream s) + public void streamWriteImpl(Ice.OutputStream s) { super.streamWriteImpl(s); - if(s.getWriteEncoding().equals(Ice.Util.Encoding_1_0)) + if(s.getEncoding().equals(Ice.Util.Encoding_1_0)) { - Ice.Util.Protocol_1_0.__write(s); - Ice.Util.Encoding_1_0.__write(s); + Ice.Util.Protocol_1_0.ice_write(s); + Ice.Util.Encoding_1_0.ice_write(s); } // Not transmitted. //s.writeBool(_connect); diff --git a/java/src/Ice/src/main/java/IceInternal/UserExceptionFactory.java b/java/src/Ice/src/main/java/IceInternal/UserExceptionFactory.java deleted file mode 100644 index a4e0b2b216a..00000000000 --- a/java/src/Ice/src/main/java/IceInternal/UserExceptionFactory.java +++ /dev/null @@ -1,18 +0,0 @@ -// ********************************************************************** -// -// Copyright (c) 2003-2015 ZeroC, Inc. All rights reserved. -// -// This copy of Ice is licensed to you under the terms described in the -// ICE_LICENSE file included in this distribution. -// -// ********************************************************************** - -package IceInternal; - -public interface UserExceptionFactory -{ - void createAndThrow(String typeId) - throws Ice.UserException; - - void destroy(); -} diff --git a/java/src/Ice/src/main/java/IceInternal/Util.java b/java/src/Ice/src/main/java/IceInternal/Util.java index 5eff3fad68a..bb8a73d2819 100644 --- a/java/src/Ice/src/main/java/IceInternal/Util.java +++ b/java/src/Ice/src/main/java/IceInternal/Util.java @@ -230,6 +230,68 @@ public final class Util } // + // Translate a Slice type id (such as "::Module::Type") into its equivalent + // Java class name (such as "Module.Type"). + // + public static String typeIdToClassName(String typeId) + { + if(!typeId.startsWith("::")) + { + return null; + } + + StringBuilder buf = new StringBuilder(typeId.length()); + + int start = 2; + boolean done = false; + while(!done) + { + int end = typeId.indexOf(':', start); + String s; + if(end != -1) + { + s = typeId.substring(start, end); + start = end + 2; + } + else + { + s = typeId.substring(start); + done = true; + } + if(buf.length() > 0) + { + buf.append('.'); + } + buf.append(fixKwd(s)); + } + + return buf.toString(); + } + + private static String fixKwd(String name) + { + // + // Keyword list. *Must* be kept in alphabetical order. Note that checkedCast and uncheckedCast + // are not Java keywords, but are in this list to prevent illegal code being generated if + // someone defines Slice operations with that name. + // + final String[] keywordList = + { + "abstract", "assert", "boolean", "break", "byte", "case", "catch", + "char", "checkedCast", "class", "clone", "const", "continue", "default", "do", + "double", "else", "enum", "equals", "extends", "false", "final", "finalize", + "finally", "float", "for", "getClass", "goto", "hashCode", "if", + "implements", "import", "instanceof", "int", "interface", "long", + "native", "new", "notify", "notifyAll", "null", "package", "private", + "protected", "public", "return", "short", "static", "strictfp", "super", "switch", + "synchronized", "this", "throw", "throws", "toString", "transient", + "true", "try", "uncheckedCast", "void", "volatile", "wait", "while" + }; + boolean found = java.util.Arrays.binarySearch(keywordList, name) >= 0; + return found ? "_" + name : name; + } + + // // Return true if we're running on Android. // public static boolean isAndroid() diff --git a/java/src/Ice/src/main/java/IceInternal/ValueFactoryManagerI.java b/java/src/Ice/src/main/java/IceInternal/ValueFactoryManagerI.java new file mode 100644 index 00000000000..42a0774c886 --- /dev/null +++ b/java/src/Ice/src/main/java/IceInternal/ValueFactoryManagerI.java @@ -0,0 +1,33 @@ +// ********************************************************************** +// +// Copyright (c) 2003-2015 ZeroC, Inc. All rights reserved. +// +// This copy of Ice is licensed to you under the terms described in the +// ICE_LICENSE file included in this distribution. +// +// ********************************************************************** + +package IceInternal; + +final class ValueFactoryManagerI implements Ice.ValueFactoryManager +{ + public synchronized void add(Ice.ValueFactory factory, String id) + { + Object o = _factoryMap.get(id); + if(o != null) + { + Ice.AlreadyRegisteredException ex = new Ice.AlreadyRegisteredException(); + ex.id = id; + ex.kindOfObject = "value factory"; + throw ex; + } + _factoryMap.put(id, factory); + } + + public synchronized Ice.ValueFactory find(String id) + { + return _factoryMap.get(id); + } + + private java.util.Map<String, Ice.ValueFactory> _factoryMap = new java.util.HashMap<String, Ice.ValueFactory>(); +} diff --git a/java/src/Ice/src/main/java/IceInternal/WSEndpoint.java b/java/src/Ice/src/main/java/IceInternal/WSEndpoint.java index dd64dbfb8af..7cc819c506e 100644 --- a/java/src/Ice/src/main/java/IceInternal/WSEndpoint.java +++ b/java/src/Ice/src/main/java/IceInternal/WSEndpoint.java @@ -31,7 +31,7 @@ final class WSEndpoint extends IceInternal.EndpointI } } - public WSEndpoint(ProtocolInstance instance, EndpointI del, BasicStream s) + public WSEndpoint(ProtocolInstance instance, EndpointI del, Ice.InputStream s) { _instance = instance; _delegate = (IPEndpointI)del; @@ -58,12 +58,12 @@ final class WSEndpoint extends IceInternal.EndpointI } @Override - public void streamWrite(BasicStream s) + public void streamWrite(Ice.OutputStream s) { - s.startWriteEncaps(); + s.startEncapsulation(); _delegate.streamWriteImpl(s); s.writeString(_resource); - s.endWriteEncaps(); + s.endEncapsulation(); } @Override diff --git a/java/src/Ice/src/main/java/IceInternal/WSEndpointFactory.java b/java/src/Ice/src/main/java/IceInternal/WSEndpointFactory.java index 1dce06c0c45..674c864c5b7 100644 --- a/java/src/Ice/src/main/java/IceInternal/WSEndpointFactory.java +++ b/java/src/Ice/src/main/java/IceInternal/WSEndpointFactory.java @@ -36,7 +36,7 @@ final public class WSEndpointFactory implements IceInternal.EndpointFactory } @Override - public IceInternal.EndpointI read(IceInternal.BasicStream s) + public IceInternal.EndpointI read(Ice.InputStream s) { return new WSEndpoint(_instance, _delegate.read(s), s); } diff --git a/java/src/Ice/src/main/java/IceSSL/EndpointFactoryI.java b/java/src/Ice/src/main/java/IceSSL/EndpointFactoryI.java index 7e51d8f2f8f..f867e338bab 100644 --- a/java/src/Ice/src/main/java/IceSSL/EndpointFactoryI.java +++ b/java/src/Ice/src/main/java/IceSSL/EndpointFactoryI.java @@ -37,7 +37,7 @@ final class EndpointFactoryI implements IceInternal.EndpointFactory } @Override - public IceInternal.EndpointI read(IceInternal.BasicStream s) + public IceInternal.EndpointI read(Ice.InputStream s) { return new EndpointI(_instance, s); } diff --git a/java/src/Ice/src/main/java/IceSSL/EndpointI.java b/java/src/Ice/src/main/java/IceSSL/EndpointI.java index 266d59ce306..7988278367f 100644 --- a/java/src/Ice/src/main/java/IceSSL/EndpointI.java +++ b/java/src/Ice/src/main/java/IceSSL/EndpointI.java @@ -28,7 +28,7 @@ final class EndpointI extends IceInternal.IPEndpointI implements IceInternal.WSE _compress = false; } - public EndpointI(Instance instance, IceInternal.BasicStream s) + public EndpointI(Instance instance, Ice.InputStream s) { super(instance, s); _instance = instance; @@ -257,7 +257,7 @@ final class EndpointI extends IceInternal.IPEndpointI implements IceInternal.WSE } @Override - public void streamWriteImpl(IceInternal.BasicStream s) + public void streamWriteImpl(Ice.OutputStream s) { super.streamWriteImpl(s); s.writeInt(_timeout); diff --git a/java/src/IceBT/src/main/java/IceBT/EndpointFactoryI.java b/java/src/IceBT/src/main/java/IceBT/EndpointFactoryI.java index 5db1f578ee1..37b606b3e65 100644 --- a/java/src/IceBT/src/main/java/IceBT/EndpointFactoryI.java +++ b/java/src/IceBT/src/main/java/IceBT/EndpointFactoryI.java @@ -37,7 +37,7 @@ final class EndpointFactoryI implements IceInternal.EndpointFactory } @Override - public IceInternal.EndpointI read(IceInternal.BasicStream s) + public IceInternal.EndpointI read(Ice.InputStream s) { return new EndpointI(_instance, s); } diff --git a/java/src/IceBT/src/main/java/IceBT/EndpointI.java b/java/src/IceBT/src/main/java/IceBT/EndpointI.java index 61bd0da4ba6..9c0bca89bbb 100644 --- a/java/src/IceBT/src/main/java/IceBT/EndpointI.java +++ b/java/src/IceBT/src/main/java/IceBT/EndpointI.java @@ -40,7 +40,7 @@ final class EndpointI extends IceInternal.EndpointI _compress = false; } - public EndpointI(Instance instance, IceInternal.BasicStream s) + public EndpointI(Instance instance, Ice.InputStream s) { _instance = instance; @@ -71,17 +71,17 @@ final class EndpointI extends IceInternal.EndpointI } @Override - public void streamWrite(IceInternal.BasicStream s) + public void streamWrite(Ice.OutputStream s) { // // _name and _channel are not marshaled. // - s.startWriteEncaps(); + s.startEncapsulation(); s.writeString(_addr); s.writeString(_uuid.toString()); s.writeInt(_timeout); s.writeBool(_compress); - s.endWriteEncaps(); + s.endEncapsulation(); } @Override diff --git a/java/test/slice.gradle b/java/test/slice.gradle index 51a12768665..0e953c1a813 100644 --- a/java/test/slice.gradle +++ b/java/test/slice.gradle @@ -47,6 +47,10 @@ task testSliceTask { 'Ice/throughput/*.ice', 'Ice/threadPoolPriority/*.ice', 'Ice/udp/*.ice', + 'Ice/objects/*.ice', + 'Ice/optional/*.ice', + 'Ice/stream/*.ice', + 'Ice/enums/*.ice', 'Glacier2/router/*.ice', 'Glacier2/sessionHelper/*.ice', 'IceDiscovery/simple/*.ice', @@ -62,13 +66,6 @@ task testSliceTask { args = "--tie" files = fileTree(dir: testDir, includes:['Ice/operations/*.ice']) } - set3 { - args = "--stream" - files = fileTree(dir: testDir, includes:['Ice/objects/*.ice', - 'Ice/optional/*.ice', - 'Ice/stream/*.ice', - 'Ice/enums/*.ice']) - } set4 { args = "--checksum test.Ice.checksum.Test.SliceChecksums" files = fileTree(dir: testDir, includes:['Ice/checksum/Test.ice', diff --git a/java/test/src/main/java/test/Ice/background/EndpointFactory.java b/java/test/src/main/java/test/Ice/background/EndpointFactory.java index 5f1b362126e..86e5d04ddb9 100644 --- a/java/test/src/main/java/test/Ice/background/EndpointFactory.java +++ b/java/test/src/main/java/test/Ice/background/EndpointFactory.java @@ -39,14 +39,14 @@ final class EndpointFactory implements IceInternal.EndpointFactory @Override public IceInternal.EndpointI - read(IceInternal.BasicStream s) + read(Ice.InputStream s) { short type = s.readShort(); assert(type == _factory.type()); - s.startReadEncaps(); + s.startEncapsulation(); IceInternal.EndpointI endpoint = new EndpointI(_configuration, _factory.read(s)); - s.endReadEncaps(); + s.endEncapsulation(); return endpoint; } diff --git a/java/test/src/main/java/test/Ice/background/EndpointI.java b/java/test/src/main/java/test/Ice/background/EndpointI.java index 5e971ad7fcf..953e2e62a92 100644 --- a/java/test/src/main/java/test/Ice/background/EndpointI.java +++ b/java/test/src/main/java/test/Ice/background/EndpointI.java @@ -35,12 +35,12 @@ final class EndpointI extends IceInternal.EndpointI @Override public void - streamWrite(IceInternal.BasicStream s) + streamWrite(Ice.OutputStream s) { - s.startWriteEncaps(); + s.startEncapsulation(); s.writeShort(_endpoint.type()); _endpoint.streamWrite(s); - s.endWriteEncaps(); + s.endEncapsulation(); } @Override diff --git a/java/test/src/main/java/test/Ice/enums/AllTests.java b/java/test/src/main/java/test/Ice/enums/AllTests.java index 3ece2a3f784..a65b4a50a6a 100644 --- a/java/test/src/main/java/test/Ice/enums/AllTests.java +++ b/java/test/src/main/java/test/Ice/enums/AllTests.java @@ -128,22 +128,22 @@ public class AllTests final boolean encoding_1_0 = communicator.getProperties().getProperty("Ice.Default.EncodingVersion").equals("1.0"); - os = Ice.Util.createOutputStream(communicator); + os = new Ice.OutputStream(communicator); ByteEnum.benum11.ice_write(os); bytes = os.finished(); test(bytes.length == 1); // ByteEnum should require one byte - os = Ice.Util.createOutputStream(communicator); + os = new Ice.OutputStream(communicator); ShortEnum.senum11.ice_write(os); bytes = os.finished(); test(bytes.length == (encoding_1_0 ? 2 : 5)); - os = Ice.Util.createOutputStream(communicator); + os = new Ice.OutputStream(communicator); IntEnum.ienum11.ice_write(os); bytes = os.finished(); test(bytes.length == (encoding_1_0 ? 4 : 5)); - os = Ice.Util.createOutputStream(communicator); + os = new Ice.OutputStream(communicator); SimpleEnum.blue.ice_write(os); bytes = os.finished(); test(bytes.length == 1); // SimpleEnum should require one byte @@ -247,9 +247,9 @@ public class AllTests try { - os = Ice.Util.createOutputStream(communicator); + os = new Ice.OutputStream(communicator); os.writeByte((byte)2); // Invalid enumerator - Ice.InputStream in = Ice.Util.createInputStream(communicator, os.finished()); + Ice.InputStream in = new Ice.InputStream(communicator, os.finished()); ByteEnum.ice_read(in); test(false); } @@ -259,9 +259,9 @@ public class AllTests try { - os = Ice.Util.createOutputStream(communicator); + os = new Ice.OutputStream(communicator); os.writeByte((byte)128); // Invalid enumerator - Ice.InputStream in = Ice.Util.createInputStream(communicator, os.finished()); + Ice.InputStream in = new Ice.InputStream(communicator, os.finished()); ByteEnum.ice_read(in); test(false); } @@ -271,9 +271,9 @@ public class AllTests try { - os = Ice.Util.createOutputStream(communicator); + os = new Ice.OutputStream(communicator); os.writeShort((short)-1); // Negative enumerators are not supported - Ice.InputStream in = Ice.Util.createInputStream(communicator, os.finished()); + Ice.InputStream in = new Ice.InputStream(communicator, os.finished()); ShortEnum.ice_read(in); test(false); } @@ -283,9 +283,9 @@ public class AllTests try { - os = Ice.Util.createOutputStream(communicator); + os = new Ice.OutputStream(communicator); os.writeShort((short)0); // Invalid enumerator - Ice.InputStream in = Ice.Util.createInputStream(communicator, os.finished()); + Ice.InputStream in = new Ice.InputStream(communicator, os.finished()); ShortEnum.ice_read(in); test(false); } @@ -295,9 +295,9 @@ public class AllTests try { - os = Ice.Util.createOutputStream(communicator); + os = new Ice.OutputStream(communicator); os.writeShort((short)32767); // Invalid enumerator - Ice.InputStream in = Ice.Util.createInputStream(communicator, os.finished()); + Ice.InputStream in = new Ice.InputStream(communicator, os.finished()); ShortEnum.ice_read(in); test(false); } @@ -307,9 +307,9 @@ public class AllTests try { - os = Ice.Util.createOutputStream(communicator); + os = new Ice.OutputStream(communicator); os.writeInt(-1); // Negative enumerators are not supported - Ice.InputStream in = Ice.Util.createInputStream(communicator, os.finished()); + Ice.InputStream in = new Ice.InputStream(communicator, os.finished()); IntEnum.ice_read(in); test(false); } @@ -319,9 +319,9 @@ public class AllTests try { - os = Ice.Util.createOutputStream(communicator); + os = new Ice.OutputStream(communicator); os.writeInt(2); // Invalid enumerator - Ice.InputStream in = Ice.Util.createInputStream(communicator, os.finished()); + Ice.InputStream in = new Ice.InputStream(communicator, os.finished()); IntEnum.ice_read(in); test(false); } diff --git a/java/test/src/main/java/test/Ice/invoke/AllTests.java b/java/test/src/main/java/test/Ice/invoke/AllTests.java index de577181c4f..a641f685a3a 100644 --- a/java/test/src/main/java/test/Ice/invoke/AllTests.java +++ b/java/test/src/main/java/test/Ice/invoke/AllTests.java @@ -73,7 +73,7 @@ public class AllTests Ice.ByteSeqHolder outEncaps = new Ice.ByteSeqHolder(); if(result.getProxy().end_ice_invoke(outEncaps, result)) { - Ice.InputStream inS = Ice.Util.createInputStream(_communicator, outEncaps.value); + Ice.InputStream inS = new Ice.InputStream(_communicator, outEncaps.value); inS.startEncapsulation(); String s = inS.readString(); test(s.equals(testString)); @@ -114,7 +114,7 @@ public class AllTests } else { - Ice.InputStream inS = Ice.Util.createInputStream(_communicator, outEncaps.value); + Ice.InputStream inS = new Ice.InputStream(_communicator, outEncaps.value); inS.startEncapsulation(); try { @@ -153,7 +153,7 @@ public class AllTests { if(ok) { - Ice.InputStream inS = Ice.Util.createInputStream(_communicator, outEncaps); + Ice.InputStream inS = new Ice.InputStream(_communicator, outEncaps); inS.startEncapsulation(); String s = inS.readString(); test(s.equals(testString)); @@ -199,7 +199,7 @@ public class AllTests } else { - Ice.InputStream inS = Ice.Util.createInputStream(_communicator, outEncaps); + Ice.InputStream inS = new Ice.InputStream(_communicator, outEncaps); inS.startEncapsulation(); try { @@ -256,7 +256,7 @@ public class AllTests test(batchOneway.ice_invoke("opOneway", Ice.OperationMode.Normal, null, null)); batchOneway.ice_flushBatchRequests(); - Ice.OutputStream outS = Ice.Util.createOutputStream(communicator); + Ice.OutputStream outS = new Ice.OutputStream(communicator); outS.startEncapsulation(); outS.writeString(testString); outS.endEncapsulation(); @@ -264,7 +264,7 @@ public class AllTests Ice.ByteSeqHolder outEncaps = new Ice.ByteSeqHolder(); if(cl.ice_invoke("opString", Ice.OperationMode.Normal, inEncaps, outEncaps)) { - Ice.InputStream inS = Ice.Util.createInputStream(communicator, outEncaps.value); + Ice.InputStream inS = new Ice.InputStream(communicator, outEncaps.value); inS.startEncapsulation(); String s = inS.readString(); test(s.equals(testString)); @@ -286,7 +286,7 @@ public class AllTests } else { - Ice.InputStream inS = Ice.Util.createInputStream(communicator, outEncaps.value); + Ice.InputStream inS = new Ice.InputStream(communicator, outEncaps.value); inS.startEncapsulation(); try { @@ -316,7 +316,7 @@ public class AllTests test(false); } - Ice.OutputStream outS = Ice.Util.createOutputStream(communicator); + Ice.OutputStream outS = new Ice.OutputStream(communicator); outS.startEncapsulation(); outS.writeString(testString); outS.endEncapsulation(); @@ -326,7 +326,7 @@ public class AllTests result = cl.begin_ice_invoke("opString", Ice.OperationMode.Normal, inEncaps); if(cl.end_ice_invoke(outEncaps, result)) { - Ice.InputStream inS = Ice.Util.createInputStream(communicator, outEncaps.value); + Ice.InputStream inS = new Ice.InputStream(communicator, outEncaps.value); inS.startEncapsulation(); String s = inS.readString(); test(s.equals(testString)); @@ -360,7 +360,7 @@ public class AllTests } else { - Ice.InputStream inS = Ice.Util.createInputStream(communicator, outEncaps.value); + Ice.InputStream inS = new Ice.InputStream(communicator, outEncaps.value); inS.startEncapsulation(); try { diff --git a/java/test/src/main/java/test/Ice/invoke/BlobjectAsyncI.java b/java/test/src/main/java/test/Ice/invoke/BlobjectAsyncI.java index 23df352372b..1ca08af696e 100644 --- a/java/test/src/main/java/test/Ice/invoke/BlobjectAsyncI.java +++ b/java/test/src/main/java/test/Ice/invoke/BlobjectAsyncI.java @@ -18,9 +18,9 @@ public class BlobjectAsyncI extends Ice.BlobjectAsync ice_invoke_async(Ice.AMD_Object_ice_invoke cb, byte[] inParams, Ice.Current current) { Ice.Communicator communicator = current.adapter.getCommunicator(); - Ice.InputStream in = Ice.Util.createInputStream(communicator, inParams); + Ice.InputStream in = new Ice.InputStream(communicator, inParams); in.startEncapsulation(); - Ice.OutputStream out = Ice.Util.createOutputStream(communicator); + Ice.OutputStream out = new Ice.OutputStream(communicator); out.startEncapsulation(); if(current.operation.equals("opOneway")) { diff --git a/java/test/src/main/java/test/Ice/invoke/BlobjectI.java b/java/test/src/main/java/test/Ice/invoke/BlobjectI.java index f61ffb4869c..b4ff3b0757f 100644 --- a/java/test/src/main/java/test/Ice/invoke/BlobjectI.java +++ b/java/test/src/main/java/test/Ice/invoke/BlobjectI.java @@ -18,9 +18,9 @@ public class BlobjectI extends Ice.Blobject ice_invoke(byte[] inParams, Ice.ByteSeqHolder outParams, Ice.Current current) { Ice.Communicator communicator = current.adapter.getCommunicator(); - Ice.InputStream in = Ice.Util.createInputStream(communicator, inParams); + Ice.InputStream in = new Ice.InputStream(communicator, inParams); in.startEncapsulation(); - Ice.OutputStream out = Ice.Util.createOutputStream(communicator); + Ice.OutputStream out = new Ice.OutputStream(communicator); out.startEncapsulation(); if(current.operation.equals("opOneway")) { diff --git a/java/test/src/main/java/test/Ice/objects/UnexpectedObjectExceptionTestI.java b/java/test/src/main/java/test/Ice/objects/UnexpectedObjectExceptionTestI.java index 31ea1d28a6c..67a5a4d025e 100644 --- a/java/test/src/main/java/test/Ice/objects/UnexpectedObjectExceptionTestI.java +++ b/java/test/src/main/java/test/Ice/objects/UnexpectedObjectExceptionTestI.java @@ -10,8 +10,6 @@ package test.Ice.objects; import test.Ice.objects.Test.AlsoEmpty; -import test.Ice.objects.Test.AlsoEmptyHelper; - public final class UnexpectedObjectExceptionTestI extends Ice.Blobject { @@ -20,10 +18,9 @@ public final class UnexpectedObjectExceptionTestI extends Ice.Blobject ice_invoke(byte[] inParams, Ice.ByteSeqHolder outParams, Ice.Current current) { Ice.Communicator communicator = current.adapter.getCommunicator(); - Ice.OutputStream out = Ice.Util.createOutputStream(communicator); + Ice.OutputStream out = new Ice.OutputStream(communicator); out.startEncapsulation(current.encoding, Ice.FormatType.DefaultFormat); - AlsoEmpty ae = new AlsoEmpty(); - AlsoEmptyHelper.write(out, ae); + out.writeObject(new AlsoEmpty()); out.writePendingObjects(); out.endEncapsulation(); outParams.value = out.finished(); diff --git a/java/test/src/main/java/test/Ice/optional/AllTests.java b/java/test/src/main/java/test/Ice/optional/AllTests.java index 932a8547480..a176c858ff0 100644 --- a/java/test/src/main/java/test/Ice/optional/AllTests.java +++ b/java/test/src/main/java/test/Ice/optional/AllTests.java @@ -356,27 +356,27 @@ public class AllTests // are skipped even if the receiver knows nothing about them. // factory.setEnabled(true); - Ice.OutputStream os = Ice.Util.createOutputStream(communicator); + Ice.OutputStream os = new Ice.OutputStream(communicator); os.startEncapsulation(); os.writeObject(oo1); os.endEncapsulation(); byte[] inEncaps = os.finished(); Ice.ByteSeqHolder outEncaps = new Ice.ByteSeqHolder(); test(initial.ice_invoke("pingPong", Ice.OperationMode.Normal, inEncaps, outEncaps)); - Ice.InputStream in = Ice.Util.createInputStream(communicator, outEncaps.value); + Ice.InputStream in = new Ice.InputStream(communicator, outEncaps.value); in.startEncapsulation(); ReadObjectCallbackI cb = new ReadObjectCallbackI(); in.readObject(cb); in.endEncapsulation(); test(cb.obj != null && cb.obj instanceof TestObjectReader); - os = Ice.Util.createOutputStream(communicator); + os = new Ice.OutputStream(communicator); os.startEncapsulation(); os.writeObject(mo1); os.endEncapsulation(); inEncaps = os.finished(); test(initial.ice_invoke("pingPong", Ice.OperationMode.Normal, inEncaps, outEncaps)); - in = Ice.Util.createInputStream(communicator, outEncaps.value); + in = new Ice.InputStream(communicator, outEncaps.value); in.startEncapsulation(); in.readObject(cb); in.endEncapsulation(); @@ -444,14 +444,14 @@ public class AllTests test(mc.getIfsd().size() == 300); factory.setEnabled(true); - os = Ice.Util.createOutputStream(communicator); + os = new Ice.OutputStream(communicator); os.startEncapsulation(); os.writeObject(mc); os.endEncapsulation(); inEncaps = os.finished(); outEncaps = new Ice.ByteSeqHolder(); test(initial.ice_invoke("pingPong", Ice.OperationMode.Normal, inEncaps, outEncaps)); - in = Ice.Util.createInputStream(communicator, outEncaps.value); + in = new Ice.InputStream(communicator, outEncaps.value); in.startEncapsulation(); in.readObject(cb); in.endEncapsulation(); @@ -481,14 +481,14 @@ public class AllTests test(b2.getMd() == 13); factory.setEnabled(true); - os = Ice.Util.createOutputStream(communicator); + os = new Ice.OutputStream(communicator); os.startEncapsulation(); os.writeObject(b); os.endEncapsulation(); inEncaps = os.finished(); outEncaps = new Ice.ByteSeqHolder(); test(initial.ice_invoke("pingPong", Ice.OperationMode.Normal, inEncaps, outEncaps)); - in = Ice.Util.createInputStream(communicator, outEncaps.value); + in = new Ice.InputStream(communicator, outEncaps.value); in.startEncapsulation(); in.readObject(cb); in.endEncapsulation(); @@ -509,18 +509,18 @@ public class AllTests test(rf.ae == rf.getAf()); factory.setEnabled(true); - os = Ice.Util.createOutputStream(communicator); + os = new Ice.OutputStream(communicator); os.startEncapsulation(); os.writeObject(f); os.endEncapsulation(); inEncaps = os.finished(); - in = Ice.Util.createInputStream(communicator, inEncaps); + in = new Ice.InputStream(communicator, inEncaps); in.startEncapsulation(); final FHolder fholder = new FHolder(); in.readObject(new Ice.ReadObjectCallback() { @Override - public void invoke(Ice.Object obj) + public void objectReady(Ice.Object obj) { fholder.value = ((FObjectReader)obj).getF(); } @@ -554,14 +554,14 @@ public class AllTests C c = new C(); c.ss = "test"; c.setMs("testms"); - os = Ice.Util.createOutputStream(communicator); + os = new Ice.OutputStream(communicator); os.startEncapsulation(); os.writeObject(c); os.endEncapsulation(); inEncaps = os.finished(); factory.setEnabled(true); test(initial.ice_invoke("pingPong", Ice.OperationMode.Normal, inEncaps, outEncaps)); - in = Ice.Util.createInputStream(communicator, outEncaps.value); + in = new Ice.InputStream(communicator, outEncaps.value); in.startEncapsulation(); in.readObject(cb); in.endEncapsulation(); @@ -569,14 +569,14 @@ public class AllTests factory.setEnabled(false); factory.setEnabled(true); - os = Ice.Util.createOutputStream(communicator); + os = new Ice.OutputStream(communicator); os.startEncapsulation(); Ice.Object d = new DObjectWriter(); os.writeObject(d); os.endEncapsulation(); inEncaps = os.finished(); test(initial.ice_invoke("pingPong", Ice.OperationMode.Normal, inEncaps, outEncaps)); - in = Ice.Util.createInputStream(communicator, outEncaps.value); + in = new Ice.InputStream(communicator, outEncaps.value); in.startEncapsulation(); in.readObject(cb); in.endEncapsulation(); @@ -591,7 +591,7 @@ public class AllTests { A a = new A(); - os = Ice.Util.createOutputStream(communicator); + os = new Ice.OutputStream(communicator); os.startEncapsulation(); os.writeObject(a); os.writeOptional(1, Ice.OptionalFormat.Class); @@ -600,7 +600,7 @@ public class AllTests inEncaps = os.finished(); test(initial.ice_invoke("opClassAndUnknownOptional", Ice.OperationMode.Normal, inEncaps, outEncaps)); - in = Ice.Util.createInputStream(communicator, outEncaps.value); + in = new Ice.InputStream(communicator, outEncaps.value); in.startEncapsulation(); in.endEncapsulation(); } @@ -635,14 +635,14 @@ public class AllTests p2 = initial.end_opByteReq(p3, r); test(p2.get() == (byte)56 && p3.get() == (byte)56); - os = Ice.Util.createOutputStream(communicator); + os = new Ice.OutputStream(communicator); os.startEncapsulation(); os.writeOptional(2, Ice.OptionalFormat.F1); os.writeByte(p1.get()); os.endEncapsulation(); inEncaps = os.finished(); initial.ice_invoke("opByteReq", Ice.OperationMode.Normal, inEncaps, outEncaps); - in = Ice.Util.createInputStream(communicator, outEncaps.value); + in = new Ice.InputStream(communicator, outEncaps.value); in.startEncapsulation(); test(in.readOptional(1, Ice.OptionalFormat.F1)); test(in.readByte() == (byte)56); @@ -650,7 +650,7 @@ public class AllTests test(in.readByte() == (byte)56); in.endEncapsulation(); - in = Ice.Util.createInputStream(communicator, outEncaps.value); + in = new Ice.InputStream(communicator, outEncaps.value); in.startEncapsulation(); in.endEncapsulation(); } @@ -679,14 +679,14 @@ public class AllTests p2 = initial.end_opBoolReq(p3, r); test(p2.get() == true && p3.get() == true); - os = Ice.Util.createOutputStream(communicator); + os = new Ice.OutputStream(communicator); os.startEncapsulation(); os.writeOptional(2, Ice.OptionalFormat.F1); os.writeBool(p1.get()); os.endEncapsulation(); inEncaps = os.finished(); initial.ice_invoke("opBoolReq", Ice.OperationMode.Normal, inEncaps, outEncaps); - in = Ice.Util.createInputStream(communicator, outEncaps.value); + in = new Ice.InputStream(communicator, outEncaps.value); in.startEncapsulation(); test(in.readOptional(1, Ice.OptionalFormat.F1)); test(in.readBool() == true); @@ -694,7 +694,7 @@ public class AllTests test(in.readBool() == true); in.endEncapsulation(); - in = Ice.Util.createInputStream(communicator, outEncaps.value); + in = new Ice.InputStream(communicator, outEncaps.value); in.startEncapsulation(); in.endEncapsulation(); } @@ -723,14 +723,14 @@ public class AllTests p2 = initial.end_opShortReq(p3, r); test(p2.get() == 56 && p3.get() == 56); - os = Ice.Util.createOutputStream(communicator); + os = new Ice.OutputStream(communicator); os.startEncapsulation(); os.writeOptional(2, Ice.OptionalFormat.F2); os.writeShort(p1.get()); os.endEncapsulation(); inEncaps = os.finished(); initial.ice_invoke("opShortReq", Ice.OperationMode.Normal, inEncaps, outEncaps); - in = Ice.Util.createInputStream(communicator, outEncaps.value); + in = new Ice.InputStream(communicator, outEncaps.value); in.startEncapsulation(); test(in.readOptional(1, Ice.OptionalFormat.F2)); test(in.readShort() == 56); @@ -738,7 +738,7 @@ public class AllTests test(in.readShort() == 56); in.endEncapsulation(); - in = Ice.Util.createInputStream(communicator, outEncaps.value); + in = new Ice.InputStream(communicator, outEncaps.value); in.startEncapsulation(); in.endEncapsulation(); } @@ -767,14 +767,14 @@ public class AllTests p2 = initial.end_opIntReq(p3, r); test(p2.get() == 56 && p3.get() == 56); - os = Ice.Util.createOutputStream(communicator); + os = new Ice.OutputStream(communicator); os.startEncapsulation(); os.writeOptional(2, Ice.OptionalFormat.F4); os.writeInt(p1.get()); os.endEncapsulation(); inEncaps = os.finished(); initial.ice_invoke("opIntReq", Ice.OperationMode.Normal, inEncaps, outEncaps); - in = Ice.Util.createInputStream(communicator, outEncaps.value); + in = new Ice.InputStream(communicator, outEncaps.value); in.startEncapsulation(); test(in.readOptional(1, Ice.OptionalFormat.F4)); test(in.readInt() == 56); @@ -782,7 +782,7 @@ public class AllTests test(in.readInt() == 56); in.endEncapsulation(); - in = Ice.Util.createInputStream(communicator, outEncaps.value); + in = new Ice.InputStream(communicator, outEncaps.value); in.startEncapsulation(); in.endEncapsulation(); } @@ -811,14 +811,14 @@ public class AllTests p2 = initial.end_opLongReq(p3, r); test(p2.get() == 56 && p3.get() == 56); - os = Ice.Util.createOutputStream(communicator); + os = new Ice.OutputStream(communicator); os.startEncapsulation(); os.writeOptional(1, Ice.OptionalFormat.F8); os.writeLong(p1.get()); os.endEncapsulation(); inEncaps = os.finished(); initial.ice_invoke("opLongReq", Ice.OperationMode.Normal, inEncaps, outEncaps); - in = Ice.Util.createInputStream(communicator, outEncaps.value); + in = new Ice.InputStream(communicator, outEncaps.value); in.startEncapsulation(); test(in.readOptional(2, Ice.OptionalFormat.F8)); test(in.readLong() == 56); @@ -826,7 +826,7 @@ public class AllTests test(in.readLong() == 56); in.endEncapsulation(); - in = Ice.Util.createInputStream(communicator, outEncaps.value); + in = new Ice.InputStream(communicator, outEncaps.value); in.startEncapsulation(); in.endEncapsulation(); } @@ -855,14 +855,14 @@ public class AllTests p2 = initial.end_opFloatReq(p3, r); test(p2.get() == 1.0 && p3.get() == 1.0); - os = Ice.Util.createOutputStream(communicator); + os = new Ice.OutputStream(communicator); os.startEncapsulation(); os.writeOptional(2, Ice.OptionalFormat.F4); os.writeFloat(p1.get()); os.endEncapsulation(); inEncaps = os.finished(); initial.ice_invoke("opFloatReq", Ice.OperationMode.Normal, inEncaps, outEncaps); - in = Ice.Util.createInputStream(communicator, outEncaps.value); + in = new Ice.InputStream(communicator, outEncaps.value); in.startEncapsulation(); test(in.readOptional(1, Ice.OptionalFormat.F4)); test(in.readFloat() == 1.0); @@ -870,7 +870,7 @@ public class AllTests test(in.readFloat() == 1.0); in.endEncapsulation(); - in = Ice.Util.createInputStream(communicator, outEncaps.value); + in = new Ice.InputStream(communicator, outEncaps.value); in.startEncapsulation(); in.endEncapsulation(); } @@ -899,14 +899,14 @@ public class AllTests p2 = initial.end_opDoubleReq(p3, r); test(p2.get() == 1.0 && p3.get() == 1.0); - os = Ice.Util.createOutputStream(communicator); + os = new Ice.OutputStream(communicator); os.startEncapsulation(); os.writeOptional(2, Ice.OptionalFormat.F8); os.writeDouble(p1.get()); os.endEncapsulation(); inEncaps = os.finished(); initial.ice_invoke("opDoubleReq", Ice.OperationMode.Normal, inEncaps, outEncaps); - in = Ice.Util.createInputStream(communicator, outEncaps.value); + in = new Ice.InputStream(communicator, outEncaps.value); in.startEncapsulation(); test(in.readOptional(1, Ice.OptionalFormat.F8)); test(in.readDouble() == 1.0); @@ -914,7 +914,7 @@ public class AllTests test(in.readDouble() == 1.0); in.endEncapsulation(); - in = Ice.Util.createInputStream(communicator, outEncaps.value); + in = new Ice.InputStream(communicator, outEncaps.value); in.startEncapsulation(); in.endEncapsulation(); } @@ -943,14 +943,14 @@ public class AllTests p2 = initial.end_opStringReq(p3, r); test(p2.get().equals("test") && p3.get().equals("test")); - os = Ice.Util.createOutputStream(communicator); + os = new Ice.OutputStream(communicator); os.startEncapsulation(); os.writeOptional(2, Ice.OptionalFormat.VSize); os.writeString(p1.get()); os.endEncapsulation(); inEncaps = os.finished(); initial.ice_invoke("opStringReq", Ice.OperationMode.Normal, inEncaps, outEncaps); - in = Ice.Util.createInputStream(communicator, outEncaps.value); + in = new Ice.InputStream(communicator, outEncaps.value); in.startEncapsulation(); test(in.readOptional(1, Ice.OptionalFormat.VSize)); test(in.readString().equals("test")); @@ -958,7 +958,7 @@ public class AllTests test(in.readString().equals("test")); in.endEncapsulation(); - in = Ice.Util.createInputStream(communicator, outEncaps.value); + in = new Ice.InputStream(communicator, outEncaps.value); in.startEncapsulation(); in.endEncapsulation(); } @@ -990,14 +990,14 @@ public class AllTests p2 = initial.end_opMyEnumReq(p3, r); test(p2.get() == MyEnum.MyEnumMember && p3.get() == MyEnum.MyEnumMember); - os = Ice.Util.createOutputStream(communicator); + os = new Ice.OutputStream(communicator); os.startEncapsulation(); os.writeOptional(2, Ice.OptionalFormat.Size); p1.get().ice_write(os); os.endEncapsulation(); inEncaps = os.finished(); initial.ice_invoke("opMyEnumReq", Ice.OperationMode.Normal, inEncaps, outEncaps); - in = Ice.Util.createInputStream(communicator, outEncaps.value); + in = new Ice.InputStream(communicator, outEncaps.value); in.startEncapsulation(); test(in.readOptional(1, Ice.OptionalFormat.Size)); test(MyEnum.ice_read(in) == MyEnum.MyEnumMember); @@ -1005,7 +1005,7 @@ public class AllTests test(MyEnum.ice_read(in) == MyEnum.MyEnumMember); in.endEncapsulation(); - in = Ice.Util.createInputStream(communicator, outEncaps.value); + in = new Ice.InputStream(communicator, outEncaps.value); in.startEncapsulation(); in.endEncapsulation(); } @@ -1036,7 +1036,7 @@ public class AllTests p2 = initial.end_opSmallStructReq(p3, r); test(p2.get().m == (byte)56 && p3.get().m == (byte)56); - os = Ice.Util.createOutputStream(communicator); + os = new Ice.OutputStream(communicator); os.startEncapsulation(); os.writeOptional(2, Ice.OptionalFormat.VSize); os.writeSize(1); @@ -1044,7 +1044,7 @@ public class AllTests os.endEncapsulation(); inEncaps = os.finished(); initial.ice_invoke("opSmallStructReq", Ice.OperationMode.Normal, inEncaps, outEncaps); - in = Ice.Util.createInputStream(communicator, outEncaps.value); + in = new Ice.InputStream(communicator, outEncaps.value); in.startEncapsulation(); test(in.readOptional(1, Ice.OptionalFormat.VSize)); in.skipSize(); @@ -1057,7 +1057,7 @@ public class AllTests test(f.m == (byte)56); in.endEncapsulation(); - in = Ice.Util.createInputStream(communicator, outEncaps.value); + in = new Ice.InputStream(communicator, outEncaps.value); in.startEncapsulation(); in.endEncapsulation(); } @@ -1086,7 +1086,7 @@ public class AllTests p2 = initial.end_opFixedStructReq(p3, r); test(p2.get().m == 56 && p3.get().m == 56); - os = Ice.Util.createOutputStream(communicator); + os = new Ice.OutputStream(communicator); os.startEncapsulation(); os.writeOptional(2, Ice.OptionalFormat.VSize); os.writeSize(4); @@ -1094,7 +1094,7 @@ public class AllTests os.endEncapsulation(); inEncaps = os.finished(); initial.ice_invoke("opFixedStructReq", Ice.OperationMode.Normal, inEncaps, outEncaps); - in = Ice.Util.createInputStream(communicator, outEncaps.value); + in = new Ice.InputStream(communicator, outEncaps.value); in.startEncapsulation(); test(in.readOptional(1, Ice.OptionalFormat.VSize)); in.skipSize(); @@ -1107,7 +1107,7 @@ public class AllTests test(f.m == 56); in.endEncapsulation(); - in = Ice.Util.createInputStream(communicator, outEncaps.value); + in = new Ice.InputStream(communicator, outEncaps.value); in.startEncapsulation(); in.endEncapsulation(); } @@ -1136,7 +1136,7 @@ public class AllTests p2 = initial.end_opVarStructReq(p3, r); test(p2.get().m.equals("test") && p3.get().m.equals("test")); - os = Ice.Util.createOutputStream(communicator); + os = new Ice.OutputStream(communicator); os.startEncapsulation(); os.writeOptional(2, Ice.OptionalFormat.FSize); int pos = os.startSize(); @@ -1145,7 +1145,7 @@ public class AllTests os.endEncapsulation(); inEncaps = os.finished(); initial.ice_invoke("opVarStructReq", Ice.OperationMode.Normal, inEncaps, outEncaps); - in = Ice.Util.createInputStream(communicator, outEncaps.value); + in = new Ice.InputStream(communicator, outEncaps.value); in.startEncapsulation(); test(in.readOptional(1, Ice.OptionalFormat.FSize)); in.skip(4); @@ -1158,7 +1158,7 @@ public class AllTests test(v.m.equals("test")); in.endEncapsulation(); - in = Ice.Util.createInputStream(communicator, outEncaps.value); + in = new Ice.InputStream(communicator, outEncaps.value); in.startEncapsulation(); in.endEncapsulation(); } @@ -1187,14 +1187,14 @@ public class AllTests p2 = initial.end_opOneOptionalReq(p3, r); test(p2.get().getA() == 58 && p3.get().getA() == 58); - os = Ice.Util.createOutputStream(communicator); + os = new Ice.OutputStream(communicator); os.startEncapsulation(); os.writeOptional(2, Ice.OptionalFormat.Class); os.writeObject(p1.get()); os.endEncapsulation(); inEncaps = os.finished(); initial.ice_invoke("opOneOptionalReq", Ice.OperationMode.Normal, inEncaps, outEncaps); - in = Ice.Util.createInputStream(communicator, outEncaps.value); + in = new Ice.InputStream(communicator, outEncaps.value); in.startEncapsulation(); test(in.readOptional(1, Ice.OptionalFormat.Class)); ReadObjectCallbackI p2cb = new ReadObjectCallbackI(); @@ -1205,7 +1205,7 @@ public class AllTests in.endEncapsulation(); test(((OneOptional)p2cb.obj).getA() == 58 && ((OneOptional)p3cb.obj).getA() == 58); - in = Ice.Util.createInputStream(communicator, outEncaps.value); + in = new Ice.InputStream(communicator, outEncaps.value); in.startEncapsulation(); in.endEncapsulation(); } @@ -1234,7 +1234,7 @@ public class AllTests p2 = initial.end_opOneOptionalProxyReq(p3, r); test(p2.get().equals(p1.get()) && p3.get().equals(p1.get())); - os = Ice.Util.createOutputStream(communicator); + os = new Ice.OutputStream(communicator); os.startEncapsulation(); os.writeOptional(2, Ice.OptionalFormat.FSize); int pos = os.startSize(); @@ -1243,7 +1243,7 @@ public class AllTests os.endEncapsulation(); inEncaps = os.finished(); initial.ice_invoke("opOneOptionalProxyReq", Ice.OperationMode.Normal, inEncaps, outEncaps); - in = Ice.Util.createInputStream(communicator, outEncaps.value); + in = new Ice.InputStream(communicator, outEncaps.value); in.startEncapsulation(); test(in.readOptional(1, Ice.OptionalFormat.FSize)); in.skip(4); @@ -1253,7 +1253,7 @@ public class AllTests test(in.readProxy().equals(p1.get())); in.endEncapsulation(); - in = Ice.Util.createInputStream(communicator, outEncaps.value); + in = new Ice.InputStream(communicator, outEncaps.value); in.startEncapsulation(); in.endEncapsulation(); } @@ -1283,14 +1283,14 @@ public class AllTests p2 = initial.end_opByteSeqReq(p3, r); test(java.util.Arrays.equals(p2.get(), p1.get()) && java.util.Arrays.equals(p3.get(), p1.get())); - os = Ice.Util.createOutputStream(communicator); + os = new Ice.OutputStream(communicator); os.startEncapsulation(); os.writeOptional(2, Ice.OptionalFormat.VSize); os.writeByteSeq(p1.get()); os.endEncapsulation(); inEncaps = os.finished(); initial.ice_invoke("opByteSeqReq", Ice.OperationMode.Normal, inEncaps, outEncaps); - in = Ice.Util.createInputStream(communicator, outEncaps.value); + in = new Ice.InputStream(communicator, outEncaps.value); in.startEncapsulation(); test(in.readOptional(1, Ice.OptionalFormat.VSize)); test(java.util.Arrays.equals(in.readByteSeq(), p1.get())); @@ -1298,7 +1298,7 @@ public class AllTests test(java.util.Arrays.equals(in.readByteSeq(), p1.get())); in.endEncapsulation(); - in = Ice.Util.createInputStream(communicator, outEncaps.value); + in = new Ice.InputStream(communicator, outEncaps.value); in.startEncapsulation(); in.endEncapsulation(); } @@ -1327,14 +1327,14 @@ public class AllTests p2 = initial.end_opBoolSeqReq(p3, r); test(java.util.Arrays.equals(p2.get(), p1.get()) && java.util.Arrays.equals(p3.get(), p1.get())); - os = Ice.Util.createOutputStream(communicator); + os = new Ice.OutputStream(communicator); os.startEncapsulation(); os.writeOptional(2, Ice.OptionalFormat.VSize); os.writeBoolSeq(p1.get()); os.endEncapsulation(); inEncaps = os.finished(); initial.ice_invoke("opBoolSeqReq", Ice.OperationMode.Normal, inEncaps, outEncaps); - in = Ice.Util.createInputStream(communicator, outEncaps.value); + in = new Ice.InputStream(communicator, outEncaps.value); in.startEncapsulation(); test(in.readOptional(1, Ice.OptionalFormat.VSize)); test(java.util.Arrays.equals(in.readBoolSeq(), p1.get())); @@ -1342,7 +1342,7 @@ public class AllTests test(java.util.Arrays.equals(in.readBoolSeq(), p1.get())); in.endEncapsulation(); - in = Ice.Util.createInputStream(communicator, outEncaps.value); + in = new Ice.InputStream(communicator, outEncaps.value); in.startEncapsulation(); in.endEncapsulation(); } @@ -1372,7 +1372,7 @@ public class AllTests p2 = initial.end_opShortSeqReq(p3, r); test(java.util.Arrays.equals(p2.get(), p1.get()) && java.util.Arrays.equals(p3.get(), p1.get())); - os = Ice.Util.createOutputStream(communicator); + os = new Ice.OutputStream(communicator); os.startEncapsulation(); os.writeOptional(2, Ice.OptionalFormat.VSize); os.writeSize(p1.get().length * 2 + (p1.get().length > 254 ? 5 : 1)); @@ -1380,7 +1380,7 @@ public class AllTests os.endEncapsulation(); inEncaps = os.finished(); initial.ice_invoke("opShortSeqReq", Ice.OperationMode.Normal, inEncaps, outEncaps); - in = Ice.Util.createInputStream(communicator, outEncaps.value); + in = new Ice.InputStream(communicator, outEncaps.value); in.startEncapsulation(); test(in.readOptional(1, Ice.OptionalFormat.VSize)); in.skipSize(); @@ -1390,7 +1390,7 @@ public class AllTests test(java.util.Arrays.equals(in.readShortSeq(), p1.get())); in.endEncapsulation(); - in = Ice.Util.createInputStream(communicator, outEncaps.value); + in = new Ice.InputStream(communicator, outEncaps.value); in.startEncapsulation(); in.endEncapsulation(); } @@ -1420,7 +1420,7 @@ public class AllTests p2 = initial.end_opIntSeqReq(p3, r); test(java.util.Arrays.equals(p2.get(), p1.get()) && java.util.Arrays.equals(p3.get(), p1.get())); - os = Ice.Util.createOutputStream(communicator); + os = new Ice.OutputStream(communicator); os.startEncapsulation(); os.writeOptional(2, Ice.OptionalFormat.VSize); os.writeSize(p1.get().length * 4 + (p1.get().length > 254 ? 5 : 1)); @@ -1428,7 +1428,7 @@ public class AllTests os.endEncapsulation(); inEncaps = os.finished(); initial.ice_invoke("opIntSeqReq", Ice.OperationMode.Normal, inEncaps, outEncaps); - in = Ice.Util.createInputStream(communicator, outEncaps.value); + in = new Ice.InputStream(communicator, outEncaps.value); in.startEncapsulation(); test(in.readOptional(1, Ice.OptionalFormat.VSize)); in.skipSize(); @@ -1438,7 +1438,7 @@ public class AllTests test(java.util.Arrays.equals(in.readIntSeq(), p1.get())); in.endEncapsulation(); - in = Ice.Util.createInputStream(communicator, outEncaps.value); + in = new Ice.InputStream(communicator, outEncaps.value); in.startEncapsulation(); in.endEncapsulation(); } @@ -1468,7 +1468,7 @@ public class AllTests p2 = initial.end_opLongSeqReq(p3, r); test(java.util.Arrays.equals(p2.get(), p1.get()) && java.util.Arrays.equals(p3.get(), p1.get())); - os = Ice.Util.createOutputStream(communicator); + os = new Ice.OutputStream(communicator); os.startEncapsulation(); os.writeOptional(2, Ice.OptionalFormat.VSize); os.writeSize(p1.get().length * 8 + (p1.get().length > 254 ? 5 : 1)); @@ -1476,7 +1476,7 @@ public class AllTests os.endEncapsulation(); inEncaps = os.finished(); initial.ice_invoke("opLongSeqReq", Ice.OperationMode.Normal, inEncaps, outEncaps); - in = Ice.Util.createInputStream(communicator, outEncaps.value); + in = new Ice.InputStream(communicator, outEncaps.value); in.startEncapsulation(); test(in.readOptional(1, Ice.OptionalFormat.VSize)); in.skipSize(); @@ -1486,7 +1486,7 @@ public class AllTests test(java.util.Arrays.equals(in.readLongSeq(), p1.get())); in.endEncapsulation(); - in = Ice.Util.createInputStream(communicator, outEncaps.value); + in = new Ice.InputStream(communicator, outEncaps.value); in.startEncapsulation(); in.endEncapsulation(); } @@ -1516,7 +1516,7 @@ public class AllTests p2 = initial.end_opFloatSeqReq(p3, r); test(java.util.Arrays.equals(p2.get(), p1.get()) && java.util.Arrays.equals(p3.get(), p1.get())); - os = Ice.Util.createOutputStream(communicator); + os = new Ice.OutputStream(communicator); os.startEncapsulation(); os.writeOptional(2, Ice.OptionalFormat.VSize); os.writeSize(p1.get().length * 4 + (p1.get().length > 254 ? 5 : 1)); @@ -1524,7 +1524,7 @@ public class AllTests os.endEncapsulation(); inEncaps = os.finished(); initial.ice_invoke("opFloatSeqReq", Ice.OperationMode.Normal, inEncaps, outEncaps); - in = Ice.Util.createInputStream(communicator, outEncaps.value); + in = new Ice.InputStream(communicator, outEncaps.value); in.startEncapsulation(); test(in.readOptional(1, Ice.OptionalFormat.VSize)); in.skipSize(); @@ -1534,7 +1534,7 @@ public class AllTests test(java.util.Arrays.equals(in.readFloatSeq(), p1.get())); in.endEncapsulation(); - in = Ice.Util.createInputStream(communicator, outEncaps.value); + in = new Ice.InputStream(communicator, outEncaps.value); in.startEncapsulation(); in.endEncapsulation(); } @@ -1564,7 +1564,7 @@ public class AllTests p2 = initial.end_opDoubleSeqReq(p3, r); test(java.util.Arrays.equals(p2.get(), p1.get()) && java.util.Arrays.equals(p3.get(), p1.get())); - os = Ice.Util.createOutputStream(communicator); + os = new Ice.OutputStream(communicator); os.startEncapsulation(); os.writeOptional(2, Ice.OptionalFormat.VSize); os.writeSize(p1.get().length * 8 + (p1.get().length > 254 ? 5 : 1)); @@ -1572,7 +1572,7 @@ public class AllTests os.endEncapsulation(); inEncaps = os.finished(); initial.ice_invoke("opDoubleSeqReq", Ice.OperationMode.Normal, inEncaps, outEncaps); - in = Ice.Util.createInputStream(communicator, outEncaps.value); + in = new Ice.InputStream(communicator, outEncaps.value); in.startEncapsulation(); test(in.readOptional(1, Ice.OptionalFormat.VSize)); in.skipSize(); @@ -1582,7 +1582,7 @@ public class AllTests test(java.util.Arrays.equals(in.readDoubleSeq(), p1.get())); in.endEncapsulation(); - in = Ice.Util.createInputStream(communicator, outEncaps.value); + in = new Ice.InputStream(communicator, outEncaps.value); in.startEncapsulation(); in.endEncapsulation(); } @@ -1612,7 +1612,7 @@ public class AllTests p2 = initial.end_opStringSeqReq(p3, r); test(java.util.Arrays.equals(p2.get(), p1.get()) && java.util.Arrays.equals(p3.get(), p1.get())); - os = Ice.Util.createOutputStream(communicator); + os = new Ice.OutputStream(communicator); os.startEncapsulation(); os.writeOptional(2, Ice.OptionalFormat.FSize); int pos = os.startSize(); @@ -1621,7 +1621,7 @@ public class AllTests os.endEncapsulation(); inEncaps = os.finished(); initial.ice_invoke("opStringSeqReq", Ice.OperationMode.Normal, inEncaps, outEncaps); - in = Ice.Util.createInputStream(communicator, outEncaps.value); + in = new Ice.InputStream(communicator, outEncaps.value); in.startEncapsulation(); test(in.readOptional(1, Ice.OptionalFormat.FSize)); in.skip(4); @@ -1631,7 +1631,7 @@ public class AllTests test(java.util.Arrays.equals(in.readStringSeq(), p1.get())); in.endEncapsulation(); - in = Ice.Util.createInputStream(communicator, outEncaps.value); + in = new Ice.InputStream(communicator, outEncaps.value); in.startEncapsulation(); in.endEncapsulation(); } @@ -1676,7 +1676,7 @@ public class AllTests test(p2.get()[i].equals(p1.get()[i])); } - os = Ice.Util.createOutputStream(communicator); + os = new Ice.OutputStream(communicator); os.startEncapsulation(); os.writeOptional(2, Ice.OptionalFormat.VSize); os.writeSize(p1.get().length + (p1.get().length > 254 ? 5 : 1)); @@ -1684,7 +1684,7 @@ public class AllTests os.endEncapsulation(); inEncaps = os.finished(); initial.ice_invoke("opSmallStructSeqReq", Ice.OperationMode.Normal, inEncaps, outEncaps); - in = Ice.Util.createInputStream(communicator, outEncaps.value); + in = new Ice.InputStream(communicator, outEncaps.value); in.startEncapsulation(); test(in.readOptional(1, Ice.OptionalFormat.VSize)); in.skipSize(); @@ -1702,7 +1702,7 @@ public class AllTests } in.endEncapsulation(); - in = Ice.Util.createInputStream(communicator, outEncaps.value); + in = new Ice.InputStream(communicator, outEncaps.value); in.startEncapsulation(); in.endEncapsulation(); } @@ -1735,7 +1735,7 @@ public class AllTests p2 = initial.end_opSmallStructListReq(p3, r); test(p2.get().equals(p1.get())); - os = Ice.Util.createOutputStream(communicator); + os = new Ice.OutputStream(communicator); os.startEncapsulation(); os.writeOptional(2, Ice.OptionalFormat.VSize); os.writeSize(p1.get().size() + (p1.get().size() > 254 ? 5 : 1)); @@ -1743,7 +1743,7 @@ public class AllTests os.endEncapsulation(); inEncaps = os.finished(); initial.ice_invoke("opSmallStructListReq", Ice.OperationMode.Normal, inEncaps, outEncaps); - in = Ice.Util.createInputStream(communicator, outEncaps.value); + in = new Ice.InputStream(communicator, outEncaps.value); in.startEncapsulation(); test(in.readOptional(1, Ice.OptionalFormat.VSize)); in.skipSize(); @@ -1755,7 +1755,7 @@ public class AllTests test(arr.equals(p1.get())); in.endEncapsulation(); - in = Ice.Util.createInputStream(communicator, outEncaps.value); + in = new Ice.InputStream(communicator, outEncaps.value); in.startEncapsulation(); in.endEncapsulation(); } @@ -1800,7 +1800,7 @@ public class AllTests test(p2.get()[i].equals(p1.get()[i])); } - os = Ice.Util.createOutputStream(communicator); + os = new Ice.OutputStream(communicator); os.startEncapsulation(); os.writeOptional(2, Ice.OptionalFormat.VSize); os.writeSize(p1.get().length * 4 + (p1.get().length > 254 ? 5 : 1)); @@ -1808,7 +1808,7 @@ public class AllTests os.endEncapsulation(); inEncaps = os.finished(); initial.ice_invoke("opFixedStructSeqReq", Ice.OperationMode.Normal, inEncaps, outEncaps); - in = Ice.Util.createInputStream(communicator, outEncaps.value); + in = new Ice.InputStream(communicator, outEncaps.value); in.startEncapsulation(); test(in.readOptional(1, Ice.OptionalFormat.VSize)); in.skipSize(); @@ -1826,7 +1826,7 @@ public class AllTests } in.endEncapsulation(); - in = Ice.Util.createInputStream(communicator, outEncaps.value); + in = new Ice.InputStream(communicator, outEncaps.value); in.startEncapsulation(); in.endEncapsulation(); } @@ -1859,7 +1859,7 @@ public class AllTests p2 = initial.end_opFixedStructListReq(p3, r); test(p2.get().equals(p1.get())); - os = Ice.Util.createOutputStream(communicator); + os = new Ice.OutputStream(communicator); os.startEncapsulation(); os.writeOptional(2, Ice.OptionalFormat.VSize); os.writeSize(p1.get().size() * 4 + (p1.get().size() > 254 ? 5 : 1)); @@ -1867,7 +1867,7 @@ public class AllTests os.endEncapsulation(); inEncaps = os.finished(); initial.ice_invoke("opFixedStructListReq", Ice.OperationMode.Normal, inEncaps, outEncaps); - in = Ice.Util.createInputStream(communicator, outEncaps.value); + in = new Ice.InputStream(communicator, outEncaps.value); in.startEncapsulation(); test(in.readOptional(1, Ice.OptionalFormat.VSize)); in.skipSize(); @@ -1879,7 +1879,7 @@ public class AllTests test(arr.equals(p1.get())); in.endEncapsulation(); - in = Ice.Util.createInputStream(communicator, outEncaps.value); + in = new Ice.InputStream(communicator, outEncaps.value); in.startEncapsulation(); in.endEncapsulation(); } @@ -1924,7 +1924,7 @@ public class AllTests test(p2.get()[i].equals(p1.get()[i])); } - os = Ice.Util.createOutputStream(communicator); + os = new Ice.OutputStream(communicator); os.startEncapsulation(); os.writeOptional(2, Ice.OptionalFormat.FSize); int pos = os.startSize(); @@ -1933,7 +1933,7 @@ public class AllTests os.endEncapsulation(); inEncaps = os.finished(); initial.ice_invoke("opVarStructSeqReq", Ice.OperationMode.Normal, inEncaps, outEncaps); - in = Ice.Util.createInputStream(communicator, outEncaps.value); + in = new Ice.InputStream(communicator, outEncaps.value); in.startEncapsulation(); test(in.readOptional(1, Ice.OptionalFormat.FSize)); in.skip(4); @@ -1951,7 +1951,7 @@ public class AllTests } in.endEncapsulation(); - in = Ice.Util.createInputStream(communicator, outEncaps.value); + in = new Ice.InputStream(communicator, outEncaps.value); in.startEncapsulation(); in.endEncapsulation(); } @@ -1981,14 +1981,14 @@ public class AllTests p2 = initial.end_opSerializableReq(p3, r); test(p2.get().equals(p1.get()) && p3.get().equals(p1.get())); - os = Ice.Util.createOutputStream(communicator); + os = new Ice.OutputStream(communicator); os.startEncapsulation(); os.writeOptional(2, Ice.OptionalFormat.VSize); os.writeSerializable(p1.get()); os.endEncapsulation(); inEncaps = os.finished(); initial.ice_invoke("opSerializableReq", Ice.OperationMode.Normal, inEncaps, outEncaps); - in = Ice.Util.createInputStream(communicator, outEncaps.value); + in = new Ice.InputStream(communicator, outEncaps.value); in.startEncapsulation(); test(in.readOptional(1, Ice.OptionalFormat.VSize)); SerializableClass sc = SerializableHelper.read(in); @@ -1998,7 +1998,7 @@ public class AllTests test(sc.equals(p1.get())); in.endEncapsulation(); - in = Ice.Util.createInputStream(communicator, outEncaps.value); + in = new Ice.InputStream(communicator, outEncaps.value); in.startEncapsulation(); in.endEncapsulation(); } @@ -2029,7 +2029,7 @@ public class AllTests p2 = initial.end_opIntIntDictReq(p3, r); test(p2.get().equals(p1.get()) && p3.get().equals(p1.get())); - os = Ice.Util.createOutputStream(communicator); + os = new Ice.OutputStream(communicator); os.startEncapsulation(); os.writeOptional(2, Ice.OptionalFormat.VSize); os.writeSize(p1.get().size() * 8 + (p1.get().size() > 254 ? 5 : 1)); @@ -2037,7 +2037,7 @@ public class AllTests os.endEncapsulation(); inEncaps = os.finished(); initial.ice_invoke("opIntIntDictReq", Ice.OperationMode.Normal, inEncaps, outEncaps); - in = Ice.Util.createInputStream(communicator, outEncaps.value); + in = new Ice.InputStream(communicator, outEncaps.value); in.startEncapsulation(); test(in.readOptional(1, Ice.OptionalFormat.VSize)); in.skipSize(); @@ -2049,7 +2049,7 @@ public class AllTests test(m.equals(p1.get())); in.endEncapsulation(); - in = Ice.Util.createInputStream(communicator, outEncaps.value); + in = new Ice.InputStream(communicator, outEncaps.value); in.startEncapsulation(); in.endEncapsulation(); } @@ -2080,7 +2080,7 @@ public class AllTests p2 = initial.end_opStringIntDictReq(p3, r); test(p2.get().equals(p1.get()) && p3.get().equals(p1.get())); - os = Ice.Util.createOutputStream(communicator); + os = new Ice.OutputStream(communicator); os.startEncapsulation(); os.writeOptional(2, Ice.OptionalFormat.FSize); int pos = os.startSize(); @@ -2089,7 +2089,7 @@ public class AllTests os.endEncapsulation(); inEncaps = os.finished(); initial.ice_invoke("opStringIntDictReq", Ice.OperationMode.Normal, inEncaps, outEncaps); - in = Ice.Util.createInputStream(communicator, outEncaps.value); + in = new Ice.InputStream(communicator, outEncaps.value); in.startEncapsulation(); test(in.readOptional(1, Ice.OptionalFormat.FSize)); in.skip(4); @@ -2101,7 +2101,7 @@ public class AllTests test(m.equals(p1.get())); in.endEncapsulation(); - in = Ice.Util.createInputStream(communicator, outEncaps.value); + in = new Ice.InputStream(communicator, outEncaps.value); in.startEncapsulation(); in.endEncapsulation(); } @@ -2113,7 +2113,7 @@ public class AllTests f.getAf().requiredA = 56; f.ae = f.getAf(); - os = Ice.Util.createOutputStream(communicator); + os = new Ice.OutputStream(communicator); os.startEncapsulation(); os.writeOptional(1, Ice.OptionalFormat.Class); os.writeObject(f); @@ -2122,14 +2122,14 @@ public class AllTests os.endEncapsulation(); inEncaps = os.finished(); - in = Ice.Util.createInputStream(communicator, inEncaps); + in = new Ice.InputStream(communicator, inEncaps); in.startEncapsulation(); test(in.readOptional(2, Ice.OptionalFormat.Class)); final AHolder a = new AHolder(); in.readObject(new Ice.ReadObjectCallback() { @Override - public void invoke(Ice.Object obj) + public void objectReady(Ice.Object obj) { a.value = (A)obj; } @@ -2433,7 +2433,7 @@ public class AllTests in.readObject(new Ice.ReadObjectCallback() { @Override - public void invoke(Ice.Object obj) + public void objectReady(Ice.Object obj) { _f.ae = (A)obj; } @@ -2499,7 +2499,7 @@ public class AllTests private static class ReadObjectCallbackI implements Ice.ReadObjectCallback { @Override - public void invoke(Ice.Object obj) + public void objectReady(Ice.Object obj) { this.obj = obj; } diff --git a/java/test/src/main/java/test/Ice/proxy/AllTests.java b/java/test/src/main/java/test/Ice/proxy/AllTests.java index da4218046b1..2d351291731 100644 --- a/java/test/src/main/java/test/Ice/proxy/AllTests.java +++ b/java/test/src/main/java/test/Ice/proxy/AllTests.java @@ -722,7 +722,7 @@ public class AllTests { // Send request with bogus 1.2 encoding. Ice.EncodingVersion version = new Ice.EncodingVersion((byte)1, (byte)2); - Ice.OutputStream os = Ice.Util.createOutputStream(communicator); + Ice.OutputStream os = new Ice.OutputStream(communicator); os.startEncapsulation(); os.endEncapsulation(); byte[] inEncaps = os.finished(); @@ -742,7 +742,7 @@ public class AllTests { // Send request with bogus 2.0 encoding. Ice.EncodingVersion version = new Ice.EncodingVersion((byte)2, (byte)0); - Ice.OutputStream os = Ice.Util.createOutputStream(communicator); + Ice.OutputStream os = new Ice.OutputStream(communicator); os.startEncapsulation(); os.endEncapsulation(); byte[] inEncaps = os.finished(); diff --git a/java/test/src/main/java/test/Ice/stream/Client.java b/java/test/src/main/java/test/Ice/stream/Client.java index e45a51d25bc..3afbfd301e1 100644 --- a/java/test/src/main/java/test/Ice/stream/Client.java +++ b/java/test/src/main/java/test/Ice/stream/Client.java @@ -96,7 +96,7 @@ public class Client extends test.Util.Application { @Override public void - invoke(Ice.Object obj) + objectReady(Ice.Object obj) { this.obj = obj; } @@ -152,34 +152,25 @@ public class Client extends test.Util.Application { byte[] data = new byte[0]; - in = Ice.Util.createInputStream(comm, data); - in.destroy(); + in = new Ice.InputStream(comm, data); } { - out = Ice.Util.createOutputStream(comm); + out = new Ice.OutputStream(comm); out.startEncapsulation(); out.writeBool(true); out.endEncapsulation(); byte[] data = out.finished(); - out.destroy(); - in = Ice.Util.createInputStream(comm, data); + in = new Ice.InputStream(comm, data); in.startEncapsulation(); test(in.readBool()); in.endEncapsulation(); - in.destroy(); - - in = Ice.Util.wrapInputStream(comm, data); - in.startEncapsulation(); - test(in.readBool()); - in.endEncapsulation(); - in.destroy(); } { byte[] data = new byte[0]; - in = Ice.Util.createInputStream(comm, data); + in = new Ice.InputStream(comm, data); try { in.readBool(); @@ -188,87 +179,70 @@ public class Client extends test.Util.Application catch(Ice.UnmarshalOutOfBoundsException ex) { } - in.destroy(); } { - out = Ice.Util.createOutputStream(comm); + out = new Ice.OutputStream(comm); out.writeBool(true); byte[] data = out.finished(); - in = Ice.Util.createInputStream(comm, data); + in = new Ice.InputStream(comm, data); test(in.readBool()); - out.destroy(); - in.destroy(); } { - out = Ice.Util.createOutputStream(comm); + out = new Ice.OutputStream(comm); out.writeByte((byte)1); byte[] data = out.finished(); - in = Ice.Util.createInputStream(comm, data); + in = new Ice.InputStream(comm, data); test(in.readByte() == (byte)1); - out.destroy(); - in.destroy(); } { - out = Ice.Util.createOutputStream(comm); + out = new Ice.OutputStream(comm); out.writeShort((short)2); byte[] data = out.finished(); - in = Ice.Util.createInputStream(comm, data); + in = new Ice.InputStream(comm, data); test(in.readShort() == (short)2); - out.destroy(); - in.destroy(); } { - out = Ice.Util.createOutputStream(comm); + out = new Ice.OutputStream(comm); out.writeInt(3); byte[] data = out.finished(); - in = Ice.Util.createInputStream(comm, data); + in = new Ice.InputStream(comm, data); test(in.readInt() == 3); - out.destroy(); - in.destroy(); } { - out = Ice.Util.createOutputStream(comm); + out = new Ice.OutputStream(comm); out.writeLong(4); byte[] data = out.finished(); - in = Ice.Util.createInputStream(comm, data); + in = new Ice.InputStream(comm, data); test(in.readLong() == 4); - out.destroy(); - in.destroy(); } { - out = Ice.Util.createOutputStream(comm); + out = new Ice.OutputStream(comm); out.writeFloat((float)5.0); byte[] data = out.finished(); - in = Ice.Util.createInputStream(comm, data); + in = new Ice.InputStream(comm, data); test(in.readFloat() == (float)5.0); - out.destroy(); - in.destroy(); } { - out = Ice.Util.createOutputStream(comm); + out = new Ice.OutputStream(comm); out.writeDouble(6.0); byte[] data = out.finished(); - in = Ice.Util.createInputStream(comm, data); + in = new Ice.InputStream(comm, data); test(in.readDouble() == 6.0); - out.destroy(); - in.destroy(); } { - out = Ice.Util.createOutputStream(comm); + out = new Ice.OutputStream(comm); out.writeString("hello world"); byte[] data = out.finished(); - in = Ice.Util.createInputStream(comm, data); + in = new Ice.InputStream(comm, data); test(in.readString().equals("hello world")); - out.destroy(); - in.destroy(); } printWriter.println("ok"); @@ -277,17 +251,15 @@ public class Client extends test.Util.Application printWriter.flush(); { - out = Ice.Util.createOutputStream(comm); + out = new Ice.OutputStream(comm); MyEnum.enum3.ice_write(out); byte[] data = out.finished(); - in = Ice.Util.createInputStream(comm, data); + in = new Ice.InputStream(comm, data); test(MyEnum.ice_read(in) == MyEnum.enum3); - out.destroy(); - in.destroy(); } { - out = Ice.Util.createOutputStream(comm); + out = new Ice.OutputStream(comm); SmallStruct s = new SmallStruct(); s.bo = true; s.by = (byte)1; @@ -301,16 +273,14 @@ public class Client extends test.Util.Application s.p = MyClassPrxHelper.uncheckedCast(comm.stringToProxy("test:default")); s.ice_write(out); byte[] data = out.finished(); - in = Ice.Util.createInputStream(comm, data); + in = new Ice.InputStream(comm, data); SmallStruct s2 = new SmallStruct(); s2.ice_read(in); test(s2.equals(s)); - out.destroy(); - in.destroy(); } { - out = Ice.Util.createOutputStream(comm); + out = new Ice.OutputStream(comm); OptionalClass o = new OptionalClass(); o.bo = true; o.by = (byte)5; @@ -319,7 +289,7 @@ public class Client extends test.Util.Application out.writeObject(o); out.writePendingObjects(); byte[] data = out.finished(); - in = Ice.Util.createInputStream(comm, data); + in = new Ice.InputStream(comm, data); TestReadObjectCallback cb = new TestReadObjectCallback(); in.readObject(cb); in.readPendingObjects(); @@ -336,12 +306,10 @@ public class Client extends test.Util.Application test(o2.getSh() == o.getSh()); test(o2.getI() == o.getI()); } - out.destroy(); - in.destroy(); } { - out = Ice.Util.createOutputStream(comm, Ice.Util.Encoding_1_0); + out = new Ice.OutputStream(comm, Ice.Util.Encoding_1_0); OptionalClass o = new OptionalClass(); o.bo = true; o.by = (byte)5; @@ -350,7 +318,7 @@ public class Client extends test.Util.Application out.writeObject(o); out.writePendingObjects(); byte[] data = out.finished(); - in = Ice.Util.createInputStream(comm, data, Ice.Util.Encoding_1_0); + in = new Ice.InputStream(comm, Ice.Util.Encoding_1_0, data); TestReadObjectCallback cb = new TestReadObjectCallback(); in.readObject(cb); in.readPendingObjects(); @@ -359,8 +327,6 @@ public class Client extends test.Util.Application test(o2.by == o.by); test(!o2.hasSh()); test(!o2.hasI()); - out.destroy(); - in.destroy(); } { @@ -371,14 +337,12 @@ public class Client extends test.Util.Application true, false }; - out = Ice.Util.createOutputStream(comm); + out = new Ice.OutputStream(comm); BoolSeqHelper.write(out, arr); byte[] data = out.finished(); - in = Ice.Util.createInputStream(comm, data); + in = new Ice.InputStream(comm, data); boolean[] arr2 = BoolSeqHelper.read(in); test(java.util.Arrays.equals(arr2, arr)); - out.destroy(); - in.destroy(); final boolean[][] arrS = { @@ -386,14 +350,12 @@ public class Client extends test.Util.Application new boolean[0], arr }; - out = Ice.Util.createOutputStream(comm); + out = new Ice.OutputStream(comm); BoolSSHelper.write(out, arrS); data = out.finished(); - in = Ice.Util.createInputStream(comm, data); + in = new Ice.InputStream(comm, data); boolean[][] arr2S = BoolSSHelper.read(in); test(java.util.Arrays.deepEquals(arr2S, arrS)); - out.destroy(); - in.destroy(); } { @@ -404,14 +366,12 @@ public class Client extends test.Util.Application (byte)0x12, (byte)0x22 }; - out = Ice.Util.createOutputStream(comm); + out = new Ice.OutputStream(comm); ByteSeqHelper.write(out, arr); byte[] data = out.finished(); - in = Ice.Util.createInputStream(comm, data); + in = new Ice.InputStream(comm, data); byte[] arr2 = ByteSeqHelper.read(in); test(java.util.Arrays.equals(arr2, arr)); - out.destroy(); - in.destroy(); final byte[][] arrS = { @@ -419,27 +379,23 @@ public class Client extends test.Util.Application new byte[0], arr }; - out = Ice.Util.createOutputStream(comm); + out = new Ice.OutputStream(comm); ByteSSHelper.write(out, arrS); data = out.finished(); - in = Ice.Util.createInputStream(comm, data); + in = new Ice.InputStream(comm, data); byte[][] arr2S = ByteSSHelper.read(in); test(java.util.Arrays.deepEquals(arr2S, arrS)); - out.destroy(); - in.destroy(); } { test.Ice.stream.Serialize.Small small = new test.Ice.stream.Serialize.Small(); small.i = 99; - out = Ice.Util.createOutputStream(comm); + out = new Ice.OutputStream(comm); out.writeSerializable(small); byte[] data = out.finished(); - in = Ice.Util.createInputStream(comm, data); + in = new Ice.InputStream(comm, data); test.Ice.stream.Serialize.Small small2 = (test.Ice.stream.Serialize.Small)in.readSerializable(); test(small2.i == 99); - out.destroy(); - in.destroy(); } { @@ -450,14 +406,12 @@ public class Client extends test.Util.Application (short)0x12, (short)0x22 }; - out = Ice.Util.createOutputStream(comm); + out = new Ice.OutputStream(comm); ShortSeqHelper.write(out, arr); byte[] data = out.finished(); - in = Ice.Util.createInputStream(comm, data); + in = new Ice.InputStream(comm, data); short[] arr2 = ShortSeqHelper.read(in); test(java.util.Arrays.equals(arr2, arr)); - out.destroy(); - in.destroy(); final short[][] arrS = { @@ -465,14 +419,12 @@ public class Client extends test.Util.Application new short[0], arr }; - out = Ice.Util.createOutputStream(comm); + out = new Ice.OutputStream(comm); ShortSSHelper.write(out, arrS); data = out.finished(); - in = Ice.Util.createInputStream(comm, data); + in = new Ice.InputStream(comm, data); short[][] arr2S = ShortSSHelper.read(in); test(java.util.Arrays.deepEquals(arr2S, arrS)); - out.destroy(); - in.destroy(); } { @@ -483,14 +435,12 @@ public class Client extends test.Util.Application 0x12, 0x22 }; - out = Ice.Util.createOutputStream(comm); + out = new Ice.OutputStream(comm); IntSeqHelper.write(out, arr); byte[] data = out.finished(); - in = Ice.Util.createInputStream(comm, data); + in = new Ice.InputStream(comm, data); int[] arr2 = IntSeqHelper.read(in); test(java.util.Arrays.equals(arr2, arr)); - out.destroy(); - in.destroy(); final int[][] arrS = { @@ -498,14 +448,12 @@ public class Client extends test.Util.Application new int[0], arr }; - out = Ice.Util.createOutputStream(comm); + out = new Ice.OutputStream(comm); IntSSHelper.write(out, arrS); data = out.finished(); - in = Ice.Util.createInputStream(comm, data); + in = new Ice.InputStream(comm, data); int[][] arr2S = IntSSHelper.read(in); test(java.util.Arrays.deepEquals(arr2S, arrS)); - out.destroy(); - in.destroy(); } { @@ -516,14 +464,12 @@ public class Client extends test.Util.Application 0x12, 0x22 }; - out = Ice.Util.createOutputStream(comm); + out = new Ice.OutputStream(comm); LongSeqHelper.write(out, arr); byte[] data = out.finished(); - in = Ice.Util.createInputStream(comm, data); + in = new Ice.InputStream(comm, data); long[] arr2 = LongSeqHelper.read(in); test(java.util.Arrays.equals(arr2, arr)); - out.destroy(); - in.destroy(); final long[][] arrS = { @@ -531,14 +477,12 @@ public class Client extends test.Util.Application new long[0], arr }; - out = Ice.Util.createOutputStream(comm); + out = new Ice.OutputStream(comm); LongSSHelper.write(out, arrS); data = out.finished(); - in = Ice.Util.createInputStream(comm, data); + in = new Ice.InputStream(comm, data); long[][] arr2S = LongSSHelper.read(in); test(java.util.Arrays.deepEquals(arr2S, arrS)); - out.destroy(); - in.destroy(); } { @@ -549,14 +493,12 @@ public class Client extends test.Util.Application 3, 4 }; - out = Ice.Util.createOutputStream(comm); + out = new Ice.OutputStream(comm); FloatSeqHelper.write(out, arr); byte[] data = out.finished(); - in = Ice.Util.createInputStream(comm, data); + in = new Ice.InputStream(comm, data); float[] arr2 = FloatSeqHelper.read(in); test(java.util.Arrays.equals(arr2, arr)); - out.destroy(); - in.destroy(); final float[][] arrS = { @@ -564,14 +506,12 @@ public class Client extends test.Util.Application new float[0], arr }; - out = Ice.Util.createOutputStream(comm); + out = new Ice.OutputStream(comm); FloatSSHelper.write(out, arrS); data = out.finished(); - in = Ice.Util.createInputStream(comm, data); + in = new Ice.InputStream(comm, data); float[][] arr2S = FloatSSHelper.read(in); test(java.util.Arrays.deepEquals(arr2S, arrS)); - out.destroy(); - in.destroy(); } { @@ -582,14 +522,12 @@ public class Client extends test.Util.Application 3, 4 }; - out = Ice.Util.createOutputStream(comm); + out = new Ice.OutputStream(comm); DoubleSeqHelper.write(out, arr); byte[] data = out.finished(); - in = Ice.Util.createInputStream(comm, data); + in = new Ice.InputStream(comm, data); double[] arr2 = DoubleSeqHelper.read(in); test(java.util.Arrays.equals(arr2, arr)); - out.destroy(); - in.destroy(); final double[][] arrS = { @@ -597,14 +535,12 @@ public class Client extends test.Util.Application new double[0], arr }; - out = Ice.Util.createOutputStream(comm); + out = new Ice.OutputStream(comm); DoubleSSHelper.write(out, arrS); data = out.finished(); - in = Ice.Util.createInputStream(comm, data); + in = new Ice.InputStream(comm, data); double[][] arr2S = DoubleSSHelper.read(in); test(java.util.Arrays.deepEquals(arr2S, arrS)); - out.destroy(); - in.destroy(); } { @@ -615,14 +551,12 @@ public class Client extends test.Util.Application "string3", "string4" }; - out = Ice.Util.createOutputStream(comm); + out = new Ice.OutputStream(comm); StringSeqHelper.write(out, arr); byte[] data = out.finished(); - in = Ice.Util.createInputStream(comm, data); + in = new Ice.InputStream(comm, data); String[] arr2 = StringSeqHelper.read(in); test(java.util.Arrays.equals(arr2, arr)); - out.destroy(); - in.destroy(); final String[][] arrS = { @@ -630,14 +564,12 @@ public class Client extends test.Util.Application new String[0], arr }; - out = Ice.Util.createOutputStream(comm); + out = new Ice.OutputStream(comm); StringSSHelper.write(out, arrS); data = out.finished(); - in = Ice.Util.createInputStream(comm, data); + in = new Ice.InputStream(comm, data); String[][] arr2S = StringSSHelper.read(in); test(java.util.Arrays.deepEquals(arr2S, arrS)); - out.destroy(); - in.destroy(); } { @@ -648,14 +580,12 @@ public class Client extends test.Util.Application MyEnum.enum1, MyEnum.enum2 }; - out = Ice.Util.createOutputStream(comm); + out = new Ice.OutputStream(comm); MyEnumSHelper.write(out, arr); byte[] data = out.finished(); - in = Ice.Util.createInputStream(comm, data); + in = new Ice.InputStream(comm, data); MyEnum[] arr2 = MyEnumSHelper.read(in); test(java.util.Arrays.equals(arr2, arr)); - out.destroy(); - in.destroy(); final MyEnum[][] arrS = { @@ -663,14 +593,12 @@ public class Client extends test.Util.Application new MyEnum[0], arr }; - out = Ice.Util.createOutputStream(comm); + out = new Ice.OutputStream(comm); MyEnumSSHelper.write(out, arrS); data = out.finished(); - in = Ice.Util.createInputStream(comm, data); + in = new Ice.InputStream(comm, data); MyEnum[][] arr2S = MyEnumSSHelper.read(in); test(java.util.Arrays.deepEquals(arr2S, arrS)); - out.destroy(); - in.destroy(); } { @@ -695,11 +623,11 @@ public class Client extends test.Util.Application arr[i].d = new java.util.HashMap<String, MyClass>(); arr[i].d.put("hi", arr[i]); } - out = Ice.Util.createOutputStream(comm); + out = new Ice.OutputStream(comm); MyClassSHelper.write(out, arr); out.writePendingObjects(); byte[] data = out.finished(); - in = Ice.Util.createInputStream(comm, data); + in = new Ice.InputStream(comm, data); MyClass[] arr2 = MyClassSHelper.read(in); in.readPendingObjects(); test(arr2.length == arr.length); @@ -720,8 +648,6 @@ public class Client extends test.Util.Application test(java.util.Arrays.equals(arr2[i].seq9, arr[i].seq9)); test(arr2[i].d.get("hi") == arr2[i]); } - out.destroy(); - in.destroy(); final MyClass[][] arrS = { @@ -729,34 +655,32 @@ public class Client extends test.Util.Application new MyClass[0], arr }; - out = Ice.Util.createOutputStream(comm); + out = new Ice.OutputStream(comm); MyClassSSHelper.write(out, arrS); data = out.finished(); - in = Ice.Util.createInputStream(comm, data); + in = new Ice.InputStream(comm, data); MyClass[][] arr2S = MyClassSSHelper.read(in); test(arr2S.length == arrS.length); test(arr2S[0].length == arrS[0].length); test(arr2S[1].length == arrS[1].length); test(arr2S[2].length == arrS[2].length); - out.destroy(); - in.destroy(); } { MyInterface i = new MyInterfaceI(); - out = Ice.Util.createOutputStream(comm); - MyInterfaceHelper.write(out, i); + out = new Ice.OutputStream(comm); + out.writeObject(i); out.writePendingObjects(); byte[] data = out.finished(); - in = Ice.Util.createInputStream(comm, data); + in = new Ice.InputStream(comm, data); MyInterfaceHolder j = new MyInterfaceHolder(); - MyInterfaceHelper.read(in, j); + in.readObject(j); in.readPendingObjects(); test(j.value != null); } { - out = Ice.Util.createOutputStream(comm); + out = new Ice.OutputStream(comm); MyClass obj = new MyClass(); obj.s = new SmallStruct(); obj.s.e = MyEnum.enum2; @@ -765,11 +689,10 @@ public class Client extends test.Util.Application out.writePendingObjects(); out.finished(); test(writer.called); - out.destroy(); } { - out = Ice.Util.createOutputStream(comm); + out = new Ice.OutputStream(comm); MyClass obj = new MyClass(); obj.s = new SmallStruct(); obj.s.e = MyEnum.enum2; @@ -779,7 +702,7 @@ public class Client extends test.Util.Application byte[] data = out.finished(); test(writer.called); factoryWrapper.setFactory(new TestValueFactory()); - in = Ice.Util.createInputStream(comm, data); + in = new Ice.InputStream(comm, data); TestReadObjectCallback cb = new TestReadObjectCallback(); in.readObject(cb); in.readPendingObjects(); @@ -789,13 +712,11 @@ public class Client extends test.Util.Application test(reader.called); test(reader.obj != null); test(reader.obj.s.e == MyEnum.enum2); - out.destroy(); - in.destroy(); factoryWrapper.setFactory(null); } { - out = Ice.Util.createOutputStream(comm); + out = new Ice.OutputStream(comm); MyException ex = new MyException(); MyClass c = new MyClass(); @@ -821,7 +742,7 @@ public class Client extends test.Util.Application out.writeException(ex); byte[] data = out.finished(); - in = Ice.Util.createInputStream(comm, data); + in = new Ice.InputStream(comm, data); try { in.throwException(); @@ -850,10 +771,10 @@ public class Client extends test.Util.Application java.util.Map<Byte, Boolean> dict = new java.util.HashMap<Byte, Boolean>(); dict.put((byte)4, true); dict.put((byte)1, false); - out = Ice.Util.createOutputStream(comm); + out = new Ice.OutputStream(comm); ByteBoolDHelper.write(out, dict); byte data[] = out.finished(); - in = Ice.Util.createInputStream(comm, data); + in = new Ice.InputStream(comm, data); java.util.Map<Byte, Boolean> dict2 = ByteBoolDHelper.read(in); test(dict2.equals(dict)); } @@ -862,10 +783,10 @@ public class Client extends test.Util.Application java.util.Map<Short, Integer> dict = new java.util.HashMap<Short, Integer>(); dict.put((short)1, 9); dict.put((short)4, 8); - out = Ice.Util.createOutputStream(comm); + out = new Ice.OutputStream(comm); ShortIntDHelper.write(out, dict); byte data[] = out.finished(); - in = Ice.Util.createInputStream(comm, data); + in = new Ice.InputStream(comm, data); java.util.Map<Short, Integer> dict2 = ShortIntDHelper.read(in); test(dict2.equals(dict)); } @@ -875,10 +796,10 @@ public class Client extends test.Util.Application java.util.Map<Long, Float> dict = new java.util.HashMap<Long, Float>(); dict.put((long)123809828, 0.51f); dict.put((long)123809829, 0.56f); - out = Ice.Util.createOutputStream(comm); + out = new Ice.OutputStream(comm); LongFloatDHelper.write(out, dict); byte data[] = out.finished(); - in = Ice.Util.createInputStream(comm, data); + in = new Ice.InputStream(comm, data); java.util.Map<Long, Float> dict2 = LongFloatDHelper.read(in); test(dict2.equals(dict)); } @@ -887,10 +808,10 @@ public class Client extends test.Util.Application java.util.Map<String, String> dict = new java.util.HashMap<String, String>(); dict.put("key1", "value1"); dict.put("key2", "value2"); - out = Ice.Util.createOutputStream(comm); + out = new Ice.OutputStream(comm); StringStringDHelper.write(out, dict); byte data[] = out.finished(); - in = Ice.Util.createInputStream(comm, data); + in = new Ice.InputStream(comm, data); java.util.Map<String, String> dict2 = StringStringDHelper.read(in); test(dict2.equals(dict)); } @@ -906,11 +827,11 @@ public class Client extends test.Util.Application c.s = new SmallStruct(); c.s.e = MyEnum.enum3; dict.put("key2", c); - out = Ice.Util.createOutputStream(comm); + out = new Ice.OutputStream(comm); StringMyClassDHelper.write(out, dict); out.writePendingObjects(); byte[] data = out.finished(); - in = Ice.Util.createInputStream(comm, data); + in = new Ice.InputStream(comm, data); java.util.Map<String, MyClass> dict2 = StringMyClassDHelper.read(in); in.readPendingObjects(); test(dict2.size() == dict.size()); |