idx
int64
0
41.2k
question
stringlengths
73
5.81k
target
stringlengths
5
918
300
public Object readRemote ( ) throws IOException { String type = readType ( ) ; String url = readString ( ) ; return resolveRemote ( type , url ) ; }
Reads a remote object .
301
public Object resolveRemote ( String type , String url ) throws IOException { HessianRemoteResolver resolver = getRemoteResolver ( ) ; if ( resolver != null ) return resolver . lookup ( type , url ) ; else return new HessianRemote ( type , url ) ; }
Resolves a remote object .
302
public String readType ( ) throws IOException { int code = read ( ) ; if ( code != 't' ) { _peek = code ; return "" ; } _isLastChunk = true ; _chunkLength = ( read ( ) << 8 ) + read ( ) ; _sbuf . setLength ( 0 ) ; int ch ; while ( ( ch = parseChar ( ) ) >= 0 ) _sbuf . append ( ( char ) ch ) ; return _sbuf . toString ( ) ; }
Parses a type from the stream .
303
private int parseInt ( ) throws IOException { int b32 = read ( ) ; int b24 = read ( ) ; int b16 = read ( ) ; int b8 = read ( ) ; return ( b32 << 24 ) + ( b24 << 16 ) + ( b16 << 8 ) + b8 ; }
Parses a 32 - bit integer value from the stream .
304
private long parseLong ( ) throws IOException { long b64 = read ( ) ; long b56 = read ( ) ; long b48 = read ( ) ; long b40 = read ( ) ; long b32 = read ( ) ; long b24 = read ( ) ; long b16 = read ( ) ; long b8 = read ( ) ; return ( ( b64 << 56 ) + ( b56 << 48 ) + ( b48 << 40 ) + ( b40 << 32 ) + ( b32 << 24 ) + ( b24 << 16 ) + ( b16 << 8 ) + b8 ) ; }
Parses a 64 - bit long value from the stream .
305
private double parseDouble ( ) throws IOException { long b64 = read ( ) ; long b56 = read ( ) ; long b48 = read ( ) ; long b40 = read ( ) ; long b32 = read ( ) ; long b24 = read ( ) ; long b16 = read ( ) ; long b8 = read ( ) ; long bits = ( ( b64 << 56 ) + ( b56 << 48 ) + ( b48 << 40 ) + ( b40 << 32 ) + ( b32 << 24 ) + ( b24 << 16 ) + ( b16 << 8 ) + b8 ) ; return Double . longBitsToDouble ( bits ) ; }
Parses a 64 - bit double value from the stream .
306
private int parseChar ( ) throws IOException { while ( _chunkLength <= 0 ) { if ( _isLastChunk ) return - 1 ; int code = read ( ) ; switch ( code ) { case 's' : case 'x' : _isLastChunk = false ; _chunkLength = ( read ( ) << 8 ) + read ( ) ; break ; case 'S' : case 'X' : _isLastChunk = true ; _chunkLength = ( read ( ) << 8 ) + read ( ) ; break ; default : throw expect ( "string" , code ) ; } } _chunkLength -- ; return parseUTF8Char ( ) ; }
Reads a character from the underlying stream .
307
private int parseUTF8Char ( ) throws IOException { int ch = read ( ) ; if ( ch < 0x80 ) return ch ; else if ( ( ch & 0xe0 ) == 0xc0 ) { int ch1 = read ( ) ; int v = ( ( ch & 0x1f ) << 6 ) + ( ch1 & 0x3f ) ; return v ; } else if ( ( ch & 0xf0 ) == 0xe0 ) { int ch1 = read ( ) ; int ch2 = read ( ) ; int v = ( ( ch & 0x0f ) << 12 ) + ( ( ch1 & 0x3f ) << 6 ) + ( ch2 & 0x3f ) ; return v ; } else throw error ( "bad utf-8 encoding at " + codeName ( ch ) ) ; }
Parses a single UTF8 character .
308
private int parseByte ( ) throws IOException { while ( _chunkLength <= 0 ) { if ( _isLastChunk ) { return - 1 ; } int code = read ( ) ; switch ( code ) { case 'b' : _isLastChunk = false ; _chunkLength = ( read ( ) << 8 ) + read ( ) ; break ; case 'B' : _isLastChunk = true ; _chunkLength = ( read ( ) << 8 ) + read ( ) ; break ; default : throw expect ( "byte[]" , code ) ; } } _chunkLength -- ; return read ( ) ; }
Reads a byte from the underlying stream .
309
public InputStream readInputStream ( ) throws IOException { int tag = read ( ) ; switch ( tag ) { case 'N' : return null ; case 'B' : case 'b' : _isLastChunk = tag == 'B' ; _chunkLength = ( read ( ) << 8 ) + read ( ) ; break ; default : throw expect ( "inputStream" , tag ) ; } return new InputStream ( ) { boolean _isClosed = false ; public int read ( ) throws IOException { if ( _isClosed || _is == null ) return - 1 ; int ch = parseByte ( ) ; if ( ch < 0 ) _isClosed = true ; return ch ; } public int read ( byte [ ] buffer , int offset , int length ) throws IOException { if ( _isClosed || _is == null ) return - 1 ; int len = HessianInput . this . read ( buffer , offset , length ) ; if ( len < 0 ) _isClosed = true ; return len ; } public void close ( ) throws IOException { while ( read ( ) >= 0 ) { } _isClosed = true ; } } ; }
Reads bytes based on an input stream .
310
int read ( byte [ ] buffer , int offset , int length ) throws IOException { int readLength = 0 ; while ( length > 0 ) { while ( _chunkLength <= 0 ) { if ( _isLastChunk ) return readLength == 0 ? - 1 : readLength ; int code = read ( ) ; switch ( code ) { case 'b' : _isLastChunk = false ; _chunkLength = ( read ( ) << 8 ) + read ( ) ; break ; case 'B' : _isLastChunk = true ; _chunkLength = ( read ( ) << 8 ) + read ( ) ; break ; default : throw expect ( "byte[]" , code ) ; } } int sublen = _chunkLength ; if ( length < sublen ) sublen = length ; sublen = _is . read ( buffer , offset , sublen ) ; offset += sublen ; readLength += sublen ; length -= sublen ; _chunkLength -= sublen ; } return readLength ; }
Reads bytes from the underlying stream .
311
protected OutputStream getOutputStream ( ) throws IOException { if ( os == null && server != null ) os = server . writeChannel ( channel ) ; return os ; }
Gets the raw output stream . Clients will normally not call this .
312
public void write ( int ch ) throws IOException { OutputStream os = getOutputStream ( ) ; os . write ( 'D' ) ; os . write ( 0 ) ; os . write ( 1 ) ; os . write ( ch ) ; }
Writes a data byte to the output stream .
313
public void write ( byte [ ] buffer , int offset , int length ) throws IOException { OutputStream os = getOutputStream ( ) ; for ( ; length > 0x8000 ; length -= 0x8000 ) { os . write ( 'D' ) ; os . write ( 0x80 ) ; os . write ( 0x00 ) ; os . write ( buffer , offset , 0x8000 ) ; offset += 0x8000 ; } os . write ( 'D' ) ; os . write ( length >> 8 ) ; os . write ( length ) ; os . write ( buffer , offset , length ) ; }
Writes data to the output stream .
314
public void close ( ) throws IOException { if ( server != null ) { OutputStream os = getOutputStream ( ) ; this . os = null ; MuxServer server = this . server ; this . server = null ; server . close ( channel ) ; } }
Complete writing to the stream closing the channel .
315
protected void writeUTF ( int code , String string ) throws IOException { OutputStream os = getOutputStream ( ) ; os . write ( code ) ; int charLength = string . length ( ) ; int length = 0 ; for ( int i = 0 ; i < charLength ; i ++ ) { char ch = string . charAt ( i ) ; if ( ch < 0x80 ) length ++ ; else if ( ch < 0x800 ) length += 2 ; else length += 3 ; } os . write ( length >> 8 ) ; os . write ( length ) ; for ( int i = 0 ; i < length ; i ++ ) { char ch = string . charAt ( i ) ; if ( ch < 0x80 ) os . write ( ch ) ; else if ( ch < 0x800 ) { os . write ( 0xc0 + ( ch >> 6 ) & 0x1f ) ; os . write ( 0x80 + ( ch & 0x3f ) ) ; } else { os . write ( 0xe0 + ( ch >> 12 ) & 0xf ) ; os . write ( 0x80 + ( ( ch >> 6 ) & 0x3f ) ) ; os . write ( 0x80 + ( ch & 0x3f ) ) ; } } }
Writes a UTF - 8 string .
316
public boolean readToOutputStream ( OutputStream os ) throws IOException { InputStream is = readInputStream ( ) ; if ( is == null ) return false ; if ( _buffer == null ) _buffer = new byte [ 256 ] ; try { int len ; while ( ( len = is . read ( _buffer , 0 , _buffer . length ) ) > 0 ) { os . write ( _buffer , 0 , len ) ; } return true ; } finally { is . close ( ) ; } }
Reads data to an output stream .
317
public Object writeReplace ( Object obj ) { Calendar cal = ( Calendar ) obj ; return new CalendarHandle ( cal . getClass ( ) , cal . getTimeInMillis ( ) ) ; }
java . util . Calendar serializes to com . caucho . hessian . io . CalendarHandle
318
public static String mangleName ( Method method , boolean isFull ) { StringBuffer sb = new StringBuffer ( ) ; sb . append ( method . getName ( ) ) ; Class [ ] params = method . getParameterTypes ( ) ; for ( int i = 0 ; i < params . length ; i ++ ) { sb . append ( '_' ) ; sb . append ( mangleClass ( params [ i ] , isFull ) ) ; } return sb . toString ( ) ; }
Creates a unique mangled method name based on the method name and the method parameters .
319
public static String mangleClass ( Class cl , boolean isFull ) { String name = cl . getName ( ) ; if ( name . equals ( "boolean" ) || name . equals ( "java.lang.Boolean" ) ) return "boolean" ; else if ( name . equals ( "int" ) || name . equals ( "java.lang.Integer" ) || name . equals ( "short" ) || name . equals ( "java.lang.Short" ) || name . equals ( "byte" ) || name . equals ( "java.lang.Byte" ) ) return "int" ; else if ( name . equals ( "long" ) || name . equals ( "java.lang.Long" ) ) return "long" ; else if ( name . equals ( "float" ) || name . equals ( "java.lang.Float" ) || name . equals ( "double" ) || name . equals ( "java.lang.Double" ) ) return "double" ; else if ( name . equals ( "java.lang.String" ) || name . equals ( "com.caucho.util.CharBuffer" ) || name . equals ( "char" ) || name . equals ( "java.lang.Character" ) || name . equals ( "java.io.Reader" ) ) return "string" ; else if ( name . equals ( "java.util.Date" ) || name . equals ( "com.caucho.util.QDate" ) ) return "date" ; else if ( InputStream . class . isAssignableFrom ( cl ) || name . equals ( "[B" ) ) return "binary" ; else if ( cl . isArray ( ) ) { return "[" + mangleClass ( cl . getComponentType ( ) , isFull ) ; } else if ( name . equals ( "org.w3c.dom.Node" ) || name . equals ( "org.w3c.dom.Element" ) || name . equals ( "org.w3c.dom.Document" ) ) return "xml" ; else if ( isFull ) return name ; else { int p = name . lastIndexOf ( '.' ) ; if ( p > 0 ) return name . substring ( p + 1 ) ; else return name ; } }
Mangles a classname .
320
public void addHeader ( String key , String value ) { _conn . setRequestProperty ( key , value ) ; }
Adds a HTTP header .
321
public void sendRequest ( ) throws IOException { if ( _conn instanceof HttpURLConnection ) { HttpURLConnection httpConn = ( HttpURLConnection ) _conn ; _statusCode = 500 ; try { _statusCode = httpConn . getResponseCode ( ) ; } catch ( Exception e ) { } parseResponseHeaders ( httpConn ) ; InputStream is = null ; if ( _statusCode != 200 ) { StringBuffer sb = new StringBuffer ( ) ; int ch ; try { is = httpConn . getInputStream ( ) ; if ( is != null ) { while ( ( ch = is . read ( ) ) >= 0 ) sb . append ( ( char ) ch ) ; is . close ( ) ; } is = httpConn . getErrorStream ( ) ; if ( is != null ) { while ( ( ch = is . read ( ) ) >= 0 ) sb . append ( ( char ) ch ) ; } _statusMessage = sb . toString ( ) ; } catch ( FileNotFoundException e ) { throw new HessianConnectionException ( "HessianProxy cannot connect to '" + _url , e ) ; } catch ( IOException e ) { if ( is == null ) throw new HessianConnectionException ( _statusCode + ": " + e , e ) ; else throw new HessianConnectionException ( _statusCode + ": " + sb , e ) ; } if ( is != null ) is . close ( ) ; throw new HessianConnectionException ( _statusCode + ": " + sb . toString ( ) ) ; } } }
Sends the request
322
public void destroy ( ) { close ( ) ; URLConnection conn = _conn ; _conn = null ; if ( conn instanceof HttpURLConnection ) ( ( HttpURLConnection ) conn ) . disconnect ( ) ; }
Disconnect the connection
323
protected InputStream getInputStream ( ) throws IOException { if ( is == null && server != null ) is = server . readChannel ( channel ) ; return is ; }
Gets the raw input stream . Clients will normally not call this .
324
private void skipToEnd ( ) throws IOException { InputStream is = getInputStream ( ) ; if ( is == null ) return ; if ( chunkLength > 0 ) is . skip ( chunkLength ) ; for ( int tag = is . read ( ) ; tag >= 0 ; tag = is . read ( ) ) { switch ( tag ) { case 'Y' : server . freeReadLock ( ) ; this . is = is = server . readChannel ( channel ) ; if ( is == null ) { this . server = null ; return ; } break ; case 'Q' : server . freeReadLock ( ) ; this . is = null ; this . server = null ; return ; case - 1 : server . freeReadLock ( ) ; this . is = null ; this . server = null ; return ; default : int length = ( is . read ( ) << 8 ) + is . read ( ) ; is . skip ( length ) ; break ; } } }
Skips data until the end of the channel .
325
void readToData ( boolean returnOnYield ) throws IOException { InputStream is = getInputStream ( ) ; if ( is == null ) return ; for ( int tag = is . read ( ) ; tag >= 0 ; tag = is . read ( ) ) { switch ( tag ) { case 'Y' : server . freeReadLock ( ) ; if ( returnOnYield ) return ; server . readChannel ( channel ) ; break ; case 'Q' : server . freeReadLock ( ) ; this . is = null ; this . server = null ; return ; case 'U' : this . url = readUTF ( ) ; break ; case 'D' : chunkLength = ( is . read ( ) << 8 ) + is . read ( ) ; return ; default : readTag ( tag ) ; break ; } } }
Reads tags until getting data .
326
protected void readTag ( int tag ) throws IOException { int length = ( is . read ( ) << 8 ) + is . read ( ) ; is . skip ( length ) ; }
Subclasses will extend this to read values .
327
protected String readUTF ( ) throws IOException { int len = ( is . read ( ) << 8 ) + is . read ( ) ; StringBuffer sb = new StringBuffer ( ) ; while ( len > 0 ) { int d1 = is . read ( ) ; if ( d1 < 0 ) return sb . toString ( ) ; else if ( d1 < 0x80 ) { len -- ; sb . append ( ( char ) d1 ) ; } else if ( ( d1 & 0xe0 ) == 0xc0 ) { len -= 2 ; sb . append ( ( ( d1 & 0x1f ) << 6 ) + ( is . read ( ) & 0x3f ) ) ; } else if ( ( d1 & 0xf0 ) == 0xe0 ) { len -= 3 ; sb . append ( ( ( d1 & 0x0f ) << 12 ) + ( ( is . read ( ) & 0x3f ) << 6 ) + ( is . read ( ) & 0x3f ) ) ; } else throw new IOException ( "utf-8 encoding error" ) ; } return sb . toString ( ) ; }
Reads a UTF - 8 string .
328
public Object getObjectInstance ( Object obj , Name name , Context nameCtx , Hashtable < ? , ? > environment ) throws Exception { Reference ref = ( Reference ) obj ; String api = null ; String url = null ; for ( int i = 0 ; i < ref . size ( ) ; i ++ ) { RefAddr addr = ref . get ( i ) ; String type = addr . getType ( ) ; String value = ( String ) addr . getContent ( ) ; if ( type . equals ( "type" ) ) api = value ; else if ( type . equals ( "url" ) ) url = value ; else if ( type . equals ( "user" ) ) setUser ( value ) ; else if ( type . equals ( "password" ) ) setPassword ( value ) ; } if ( url == null ) throw new NamingException ( "`url' must be configured for HessianProxyFactory." ) ; if ( api == null ) throw new NamingException ( "`type' must be configured for HessianProxyFactory." ) ; Class apiClass = Class . forName ( api , false , _loader ) ; return create ( apiClass , url ) ; }
JNDI object factory so the proxy can be used as a resource .
329
private String base64 ( String value ) { StringBuffer cb = new StringBuffer ( ) ; int i = 0 ; for ( i = 0 ; i + 2 < value . length ( ) ; i += 3 ) { long chunk = ( int ) value . charAt ( i ) ; chunk = ( chunk << 8 ) + ( int ) value . charAt ( i + 1 ) ; chunk = ( chunk << 8 ) + ( int ) value . charAt ( i + 2 ) ; cb . append ( encode ( chunk >> 18 ) ) ; cb . append ( encode ( chunk >> 12 ) ) ; cb . append ( encode ( chunk >> 6 ) ) ; cb . append ( encode ( chunk ) ) ; } if ( i + 1 < value . length ( ) ) { long chunk = ( int ) value . charAt ( i ) ; chunk = ( chunk << 8 ) + ( int ) value . charAt ( i + 1 ) ; chunk <<= 8 ; cb . append ( encode ( chunk >> 18 ) ) ; cb . append ( encode ( chunk >> 12 ) ) ; cb . append ( encode ( chunk >> 6 ) ) ; cb . append ( '=' ) ; } else if ( i < value . length ( ) ) { long chunk = ( int ) value . charAt ( i ) ; chunk <<= 16 ; cb . append ( encode ( chunk >> 18 ) ) ; cb . append ( encode ( chunk >> 12 ) ) ; cb . append ( '=' ) ; cb . append ( '=' ) ; } return cb . toString ( ) ; }
Creates the Base64 value .
330
public void writeObject ( Object obj , AbstractHessianOutput out ) throws IOException { if ( out . addRef ( obj ) ) { return ; } int ref = out . writeObjectBegin ( getClassName ( obj ) ) ; if ( ref < - 1 ) { out . writeString ( "value" ) ; InputStream is = null ; try { is = getInputStream ( obj ) ; } catch ( Exception e ) { log . log ( Level . WARNING , e . toString ( ) , e ) ; } if ( is != null ) { try { out . writeByteStream ( is ) ; } finally { is . close ( ) ; } } else { out . writeNull ( ) ; } out . writeMapEnd ( ) ; } else { if ( ref == - 1 ) { out . writeClassFieldLength ( 1 ) ; out . writeString ( "value" ) ; out . writeObjectBegin ( getClassName ( obj ) ) ; } InputStream is = null ; try { is = getInputStream ( obj ) ; } catch ( Exception e ) { log . log ( Level . WARNING , e . toString ( ) , e ) ; } try { if ( is != null ) out . writeByteStream ( is ) ; else out . writeNull ( ) ; } finally { if ( is != null ) is . close ( ) ; } } }
Writes the object to the output stream .
331
protected Object readObjectImpl ( Class cl ) throws IOException { try { Object obj = cl . newInstance ( ) ; if ( _refs == null ) _refs = new ArrayList ( ) ; _refs . add ( obj ) ; HashMap fieldMap = getFieldMap ( cl ) ; int code = read ( ) ; for ( ; code >= 0 && code != 'z' ; code = read ( ) ) { unread ( ) ; Object key = readObject ( ) ; Field field = ( Field ) fieldMap . get ( key ) ; if ( field != null ) { Object value = readObject ( field . getType ( ) ) ; field . set ( obj , value ) ; } else { Object value = readObject ( ) ; } } if ( code != 'z' ) throw expect ( "map" , code ) ; try { Method method = cl . getMethod ( "readResolve" , new Class [ 0 ] ) ; return method . invoke ( obj , new Object [ 0 ] ) ; } catch ( Exception e ) { } return obj ; } catch ( IOException e ) { throw e ; } catch ( Exception e ) { throw new IOExceptionWrapper ( e ) ; } }
Reads an object from the input stream . cl is known not to be a Map .
332
public void setSendCollectionType ( boolean isSendType ) { if ( _collectionSerializer == null ) _collectionSerializer = new CollectionSerializer ( ) ; _collectionSerializer . setSendJavaType ( isSendType ) ; if ( _mapSerializer == null ) _mapSerializer = new MapSerializer ( ) ; _mapSerializer . setSendJavaType ( isSendType ) ; }
Set true if the collection serializer should send the java type .
333
public Object readList ( AbstractHessianInput in , int length , String type ) throws HessianProtocolException , IOException { Deserializer deserializer = getDeserializer ( type ) ; if ( deserializer != null ) return deserializer . readList ( in , length ) ; else return new CollectionDeserializer ( ArrayList . class ) . readList ( in , length ) ; }
Reads the object as a list .
334
public Object readMap ( AbstractHessianInput in ) throws IOException { Object value = null ; while ( ! in . isEnd ( ) ) { String key = in . readString ( ) ; if ( key . equals ( "value" ) ) value = readStreamValue ( in ) ; else in . readObject ( ) ; } in . readMapEnd ( ) ; return value ; }
Reads the Hessian 1 . 0 style map .
335
public void service ( ServletRequest request , ServletResponse response ) throws IOException , ServletException { HttpServletRequest req = ( HttpServletRequest ) request ; HttpServletResponse res = ( HttpServletResponse ) response ; if ( ! req . getMethod ( ) . equals ( "POST" ) ) { res . setStatus ( 500 ) ; PrintWriter out = res . getWriter ( ) ; res . setContentType ( "text/html" ) ; out . println ( "<h1>Hessian Requires POST</h1>" ) ; return ; } String serviceId = req . getPathInfo ( ) ; String objectId = req . getParameter ( "id" ) ; if ( objectId == null ) objectId = req . getParameter ( "ejbid" ) ; ServiceContext . begin ( req , res , serviceId , objectId ) ; try { InputStream is = request . getInputStream ( ) ; OutputStream os = response . getOutputStream ( ) ; response . setContentType ( "x-application/hessian" ) ; SerializerFactory serializerFactory = getSerializerFactory ( ) ; invoke ( is , os , objectId , serializerFactory ) ; } catch ( RuntimeException e ) { throw e ; } catch ( ServletException e ) { throw e ; } catch ( Throwable e ) { throw new ServletException ( e ) ; } finally { ServiceContext . end ( ) ; } }
Execute a request . The path - info of the request selects the bean . Once the bean s selected it will be applied .
336
public void writeObjectImpl ( Object obj ) throws IOException { Class cl = obj . getClass ( ) ; try { Method method = cl . getMethod ( "writeReplace" , new Class [ 0 ] ) ; Object repl = method . invoke ( obj , new Object [ 0 ] ) ; writeObject ( repl ) ; return ; } catch ( Exception e ) { } try { writeMapBegin ( cl . getName ( ) ) ; for ( ; cl != null ; cl = cl . getSuperclass ( ) ) { Field [ ] fields = cl . getDeclaredFields ( ) ; for ( int i = 0 ; i < fields . length ; i ++ ) { Field field = fields [ i ] ; if ( Modifier . isTransient ( field . getModifiers ( ) ) || Modifier . isStatic ( field . getModifiers ( ) ) ) continue ; field . setAccessible ( true ) ; writeString ( field . getName ( ) ) ; writeObject ( field . get ( obj ) ) ; } } writeMapEnd ( ) ; } catch ( IllegalAccessException e ) { throw new IOExceptionWrapper ( e ) ; } }
Applications which override this can do custom serialization .
337
public boolean checkDuplicate ( T obj ) { int top = _top . get ( ) ; for ( int i = top - 1 ; i >= 0 ; i -- ) { if ( _freeStack . get ( i ) == obj ) return true ; } return false ; }
Debugging to see if the object has already been freed .
338
public Serializer getSerializer ( String className ) { Serializer serializer = _serializerClassMap . get ( className ) ; if ( serializer == AbstractSerializer . NULL ) return null ; else return serializer ; }
Returns the serializer for a given class .
339
public Deserializer getDeserializer ( String className ) { Deserializer deserializer = _deserializerClassMap . get ( className ) ; if ( deserializer == AbstractDeserializer . NULL ) return null ; else return deserializer ; }
Returns the deserializer for a given class .
340
public Deserializer getCustomDeserializer ( Class cl ) { Deserializer deserializer = _customDeserializerMap . get ( cl . getName ( ) ) ; if ( deserializer == AbstractDeserializer . NULL ) return null ; else if ( deserializer != null ) return deserializer ; try { Class serClass = Class . forName ( cl . getName ( ) + "HessianDeserializer" , false , cl . getClassLoader ( ) ) ; Deserializer ser = ( Deserializer ) serClass . newInstance ( ) ; _customDeserializerMap . put ( cl . getName ( ) , ser ) ; return ser ; } catch ( ClassNotFoundException e ) { log . log ( Level . ALL , e . toString ( ) , e ) ; } catch ( Exception e ) { throw new HessianException ( e ) ; } _customDeserializerMap . put ( cl . getName ( ) , AbstractDeserializer . NULL ) ; return null ; }
Returns a custom deserializer the class
341
private void init ( ) { if ( _parent != null ) { _serializerFiles . addAll ( _parent . _serializerFiles ) ; _deserializerFiles . addAll ( _parent . _deserializerFiles ) ; _serializerClassMap . putAll ( _parent . _serializerClassMap ) ; _deserializerClassMap . putAll ( _parent . _deserializerClassMap ) ; } if ( _parent == null ) { _serializerClassMap . putAll ( _staticSerializerMap ) ; _deserializerClassMap . putAll ( _staticDeserializerMap ) ; _deserializerClassNameMap . putAll ( _staticClassNameMap ) ; } HashMap < Class , Class > classMap ; classMap = new HashMap < Class , Class > ( ) ; initSerializerFiles ( "META-INF/hessian/serializers" , _serializerFiles , classMap , Serializer . class ) ; for ( Map . Entry < Class , Class > entry : classMap . entrySet ( ) ) { try { Serializer ser = ( Serializer ) entry . getValue ( ) . newInstance ( ) ; if ( entry . getKey ( ) . isInterface ( ) ) _serializerInterfaceMap . put ( entry . getKey ( ) , ser ) ; else _serializerClassMap . put ( entry . getKey ( ) . getName ( ) , ser ) ; } catch ( Exception e ) { throw new HessianException ( e ) ; } } classMap = new HashMap < Class , Class > ( ) ; initSerializerFiles ( "META-INF/hessian/deserializers" , _deserializerFiles , classMap , Deserializer . class ) ; for ( Map . Entry < Class , Class > entry : classMap . entrySet ( ) ) { try { Deserializer ser = ( Deserializer ) entry . getValue ( ) . newInstance ( ) ; if ( entry . getKey ( ) . isInterface ( ) ) _deserializerInterfaceMap . put ( entry . getKey ( ) , ser ) ; else { _deserializerClassMap . put ( entry . getKey ( ) . getName ( ) , ser ) ; } } catch ( Exception e ) { throw new HessianException ( e ) ; } } }
Initialize the factory
342
protected HessianConnection sendRequest ( String methodName , Object [ ] args ) throws IOException { HessianConnection conn = null ; conn = _factory . getConnectionFactory ( ) . open ( _url ) ; boolean isValid = false ; try { addRequestHeaders ( conn ) ; OutputStream os = null ; try { os = conn . getOutputStream ( ) ; } catch ( Exception e ) { throw new HessianRuntimeException ( e ) ; } if ( log . isLoggable ( Level . FINEST ) ) { PrintWriter dbg = new PrintWriter ( new LogWriter ( log ) ) ; HessianDebugOutputStream dOs = new HessianDebugOutputStream ( os , dbg ) ; dOs . startTop2 ( ) ; os = dOs ; } AbstractHessianOutput out = _factory . getHessianOutput ( os ) ; out . call ( methodName , args ) ; out . flush ( ) ; conn . sendRequest ( ) ; isValid = true ; return conn ; } finally { if ( ! isValid && conn != null ) conn . destroy ( ) ; } }
Sends the HTTP request to the Hessian connection .
343
protected void addRequestHeaders ( HessianConnection conn ) { conn . addHeader ( "Content-Type" , "x-application/hessian" ) ; conn . addHeader ( "Accept-Encoding" , "deflate" ) ; String basicAuth = _factory . getBasicAuth ( ) ; if ( basicAuth != null ) conn . addHeader ( "Authorization" , basicAuth ) ; }
Method that allows subclasses to add request headers such as cookies . Default implementation is empty .
344
public HessianConnection open ( URL url ) throws IOException { if ( log . isLoggable ( Level . FINER ) ) log . finer ( this + " open(" + url + ")" ) ; URLConnection conn = url . openConnection ( ) ; long connectTimeout = _proxyFactory . getConnectTimeout ( ) ; if ( connectTimeout >= 0 ) conn . setConnectTimeout ( ( int ) connectTimeout ) ; conn . setDoOutput ( true ) ; long readTimeout = _proxyFactory . getReadTimeout ( ) ; if ( readTimeout > 0 ) { try { conn . setReadTimeout ( ( int ) readTimeout ) ; } catch ( Throwable e ) { } } return new HessianURLConnection ( url , conn ) ; }
Opens a new or recycled connection to the HTTP server .
345
public static void begin ( ServletRequest request , ServletResponse response , String serviceName , String objectId ) throws ServletException { ServiceContext context = ( ServiceContext ) _localContext . get ( ) ; if ( context == null ) { context = new ServiceContext ( ) ; _localContext . set ( context ) ; } context . _request = request ; context . _response = response ; context . _serviceName = serviceName ; context . _objectId = objectId ; context . _count ++ ; }
Sets the request object prior to calling the service s method .
346
public static Object getContextHeader ( String header ) { ServiceContext context = ( ServiceContext ) _localContext . get ( ) ; if ( context != null ) return context . getHeader ( header ) ; else return null ; }
Gets a header from the context .
347
public static void end ( ) { ServiceContext context = ( ServiceContext ) _localContext . get ( ) ; if ( context != null && -- context . _count == 0 ) { context . _request = null ; context . _response = null ; context . _headers . clear ( ) ; _localContext . set ( null ) ; } }
Cleanup at the end of a request .
348
private String getArrayType ( Class cl ) { if ( cl . isArray ( ) ) return '[' + getArrayType ( cl . getComponentType ( ) ) ; String name = cl . getName ( ) ; if ( name . equals ( "java.lang.String" ) ) return "string" ; else if ( name . equals ( "java.lang.Object" ) ) return "object" ; else if ( name . equals ( "java.util.Date" ) ) return "date" ; else return name ; }
Returns the &lt ; type > name for a &lt ; list > .
349
public String doLayout ( ILoggingEvent event ) { String msg = super . doLayout ( event ) . trim ( ) ; msg = preventLogForging ( msg ) ; IThrowableProxy throwableProxy = event . getThrowableProxy ( ) ; if ( throwableProxy != null ) { StackTraceElementProxy [ ] s = throwableProxy . getStackTraceElementProxyArray ( ) ; if ( s != null && s . length > 0 ) { StringBuilder sb = new StringBuilder ( s . length * BUFFER_PER_LINE ) ; sb . append ( msg ) ; int len = s . length ; for ( int i = 0 ; i < len ; i ++ ) { sb . append ( LINE_SEP ) . append ( s [ i ] ) ; } msg = sb . toString ( ) ; } } return msg + NEWLINE ; }
Creates formatted String using conversion pattern .
350
private String preventLogForging ( String logMsg ) { String result = logMsg ; result = LINEBREAK_PATTERN . matcher ( logMsg ) . replaceAll ( SingleLinePatternLayout . LINE_SEP ) ; return result ; }
Method to prevent log forging .
351
public void initialize ( ) { if ( this . pojoDescriptorBuilderFactory == null ) { this . pojoDescriptorBuilderFactory = PojoDescriptorBuilderFactoryImpl . getInstance ( ) ; } if ( this . pojoDescriptorBuilder == null ) { this . pojoDescriptorBuilder = this . pojoDescriptorBuilderFactory . createPrivateFieldDescriptorBuilder ( ) ; } this . descriptor = this . pojoDescriptorBuilder . getDescriptor ( EntityTo . class ) ; }
Initializes this class to be functional .
352
protected Response handleSecurityError ( Throwable exception , Throwable catched ) { NlsRuntimeException error ; if ( ( exception == catched ) && ( exception instanceof NlsRuntimeException ) ) { error = ( NlsRuntimeException ) exception ; } else { error = new SecurityErrorUserException ( catched ) ; } LOG . error ( "Service failed due to security error" , error ) ; String message ; String code = null ; if ( this . exposeInternalErrorDetails ) { message = getExposedErrorDetails ( error ) ; } else { message = "forbidden" ; } return createResponse ( Status . FORBIDDEN , message , code , error . getUuid ( ) , null ) ; }
Exception handling for security exception .
353
protected Response handleValidationException ( Throwable exception , Throwable catched ) { Throwable t = catched ; Map < String , List < String > > errorsMap = null ; if ( exception instanceof ConstraintViolationException ) { ConstraintViolationException constraintViolationException = ( ConstraintViolationException ) exception ; Set < ConstraintViolation < ? > > violations = constraintViolationException . getConstraintViolations ( ) ; errorsMap = new HashMap < > ( ) ; for ( ConstraintViolation < ? > violation : violations ) { Iterator < Node > it = violation . getPropertyPath ( ) . iterator ( ) ; String fieldName = null ; while ( it . hasNext ( ) ) { fieldName = it . next ( ) . toString ( ) ; } List < String > errorsList = errorsMap . get ( fieldName ) ; if ( errorsList == null ) { errorsList = new ArrayList < > ( ) ; errorsMap . put ( fieldName , errorsList ) ; } errorsList . add ( violation . getMessage ( ) ) ; } t = new ValidationException ( errorsMap . toString ( ) , catched ) ; } ValidationErrorUserException error = new ValidationErrorUserException ( t ) ; return createResponse ( t , error , errorsMap ) ; }
Exception handling for validation exception .
354
protected Response createResponse ( WebApplicationException exception ) { Response response = exception . getResponse ( ) ; int statusCode = response . getStatus ( ) ; Status status = Status . fromStatusCode ( statusCode ) ; NlsRuntimeException error ; if ( exception instanceof ServerErrorException ) { error = new TechnicalErrorUserException ( exception ) ; LOG . error ( "Service failed on server" , error ) ; return createResponse ( status , error , null ) ; } else { UUID uuid = UUID . randomUUID ( ) ; if ( exception instanceof ClientErrorException ) { LOG . warn ( "Service failed due to unexpected request. UUDI: {}, reason: {} " , uuid , exception . getMessage ( ) ) ; } else { LOG . warn ( "Service caused redirect or other error. UUID: {}, reason: {}" , uuid , exception . getMessage ( ) ) ; } return createResponse ( status , exception . getMessage ( ) , String . valueOf ( statusCode ) , uuid , null ) ; } }
Add a response message to an existing response .
355
protected void initialize ( AccessControlSchema config ) { LOG . debug ( "Initializing." ) ; List < AccessControlGroup > groups = config . getGroups ( ) ; if ( groups . size ( ) == 0 ) { throw new IllegalStateException ( "AccessControlSchema is empty - please configure at least one group!" ) ; } Set < AccessControlGroup > toplevelGroups = new HashSet < > ( groups ) ; for ( AccessControlGroup group : groups ) { collectAccessControls ( group , toplevelGroups ) ; List < AccessControlGroup > groupList = new ArrayList < > ( ) ; groupList . add ( group ) ; checkForCyclicDependencies ( group , groupList ) ; } }
Performs the required initialization of this class .
356
@ SuppressWarnings ( "unchecked" ) public < T > T get ( String key , Class < T > targetType , boolean required ) throws WebApplicationException { String value = get ( key ) ; if ( value == null ) { if ( required ) { throw new BadRequestException ( "Missing parameter: " + key ) ; } Object result = null ; if ( targetType . isPrimitive ( ) ) { if ( targetType == boolean . class ) { result = Boolean . FALSE ; } else if ( targetType == int . class ) { result = Integer . valueOf ( 0 ) ; } else if ( targetType == long . class ) { result = Long . valueOf ( 0 ) ; } else if ( targetType == double . class ) { result = Double . valueOf ( 0 ) ; } else if ( targetType == float . class ) { result = Float . valueOf ( 0 ) ; } else if ( targetType == byte . class ) { result = Byte . valueOf ( ( byte ) 0 ) ; } else if ( targetType == short . class ) { result = Short . valueOf ( ( short ) 0 ) ; } else if ( targetType == char . class ) { result = '\0' ; } } return ( T ) result ; } try { return convertValue ( value , targetType ) ; } catch ( WebApplicationException e ) { throw e ; } catch ( Exception e ) { throw new BadRequestException ( "Failed to convert '" + value + "' to type " + targetType ) ; } }
Gets the single parameter in a generic and flexible way .
357
public String suspend ( ) { AtmosphereResource r = ( AtmosphereResource ) req . getAttribute ( "org.atmosphere.cpr.AtmosphereResource" ) ; r . setBroadcaster ( r . getAtmosphereConfig ( ) . getBroadcasterFactory ( ) . lookup ( "/cxf-chat" , true ) ) . suspend ( ) ; return "" ; }
Suspend the response without writing anything back to the client .
358
public void doPost ( AtmosphereResource ar ) { Object msg = ar . getRequest ( ) . getAttribute ( Constants . MESSAGE_OBJECT ) ; if ( msg != null ) { logger . info ( "received RPC post: " + msg . toString ( ) ) ; ar . getAtmosphereConfig ( ) . getBroadcasterFactory ( ) . lookup ( "MyBroadcaster" ) . broadcast ( msg ) ; } }
receive push message from client
359
public void broadcast ( String message ) { AtmosphereResource r = ( AtmosphereResource ) request . getAttribute ( ApplicationConfig . ATMOSPHERE_RESOURCE ) ; if ( r != null ) { r . getBroadcaster ( ) . broadcast ( message ) ; } else { throw new IllegalStateException ( ) ; } }
Echo the chat message . Jackson can clearly be used here but for simplicity we just echo what we receive .
360
public void onReady ( ) { logger . info ( "Browser {} connected" , r . uuid ( ) ) ; logger . info ( "BroadcasterFactory used {}" , factory . getClass ( ) . getName ( ) ) ; logger . info ( "Broadcaster injected {}" , broadcaster . getID ( ) ) ; }
Invoked when the connection has been fully established and suspended that is ready for receiving messages .
361
@ Produces ( "application/xml" ) public Broadcastable publishWithXML ( @ FormParam ( "message" ) String message ) { return new Broadcastable ( new JAXBBean ( message ) , broadcaster ) ; }
Broadcast XML data using JAXB
362
@ Suspend ( period = 60 , timeUnit = TimeUnit . SECONDS , listeners = { EventsLogger . class } ) @ Path ( "timeout" ) public Broadcastable timeout ( ) { return new Broadcastable ( broadcaster ) ; }
Timeout the resource
363
public JSONObject addObject ( JSONObject obj , RequestOptions requestOptions ) throws AlgoliaException { return client . postRequest ( "/1/indexes/" + encodedIndexName , obj . toString ( ) , true , false , requestOptions ) ; }
Add an object in this index
364
public JSONObject addObjects ( List < JSONObject > objects ) throws AlgoliaException { return this . addObjects ( objects , RequestOptions . empty ) ; }
Add several objects
365
public JSONObject saveObject ( JSONObject object , String objectID ) throws AlgoliaException { return this . saveObject ( object , objectID , RequestOptions . empty ) ; }
Override the content of object
366
public JSONObject saveObjects ( List < JSONObject > objects ) throws AlgoliaException { return this . saveObjects ( objects , RequestOptions . empty ) ; }
Override the content of several objects
367
public JSONObject search ( Query params , RequestOptions requestOptions ) throws AlgoliaException { String paramsString = params . getQueryString ( ) ; JSONObject body = new JSONObject ( ) ; try { body . put ( "params" , paramsString ) ; } catch ( JSONException e ) { throw new RuntimeException ( e ) ; } return client . postRequest ( "/1/indexes/" + encodedIndexName + "/query" , body . toString ( ) , false , true , requestOptions ) ; }
Search inside the index
368
public IndexBrowser browseFrom ( Query params , String cursor , RequestOptions requestOptions ) throws AlgoliaException { return new IndexBrowser ( client , encodedIndexName , params , cursor , requestOptions ) ; }
Browse all index content starting from a cursor
369
public JSONObject getSettings ( RequestOptions requestOptions ) throws AlgoliaException { return client . getRequest ( "/1/indexes/" + encodedIndexName + "/settings?getVersion=2" , false , requestOptions ) ; }
Get settings of this index
370
public JSONObject clearIndex ( RequestOptions requestOptions ) throws AlgoliaException { return client . postRequest ( "/1/indexes/" + encodedIndexName + "/clear" , "" , true , false , requestOptions ) ; }
Delete the index content without removing settings and index specific API keys .
371
public JSONObject setSettings ( JSONObject settings , RequestOptions requestOptions ) throws AlgoliaException { return setSettings ( settings , false , requestOptions ) ; }
Set settings for this index
372
public JSONObject getApiKey ( String key , RequestOptions requestOptions ) throws AlgoliaException { return client . getRequest ( "/1/indexes/" + encodedIndexName + "/keys/" + key , false , requestOptions ) ; }
Get ACL of an api key
373
public JSONObject deleteApiKey ( String key , RequestOptions requestOptions ) throws AlgoliaException { return client . deleteRequest ( "/1/indexes/" + encodedIndexName + "/keys/" + key , requestOptions ) ; }
Delete an existing api key
374
public JSONObject clearSynonyms ( boolean forwardToReplicas , RequestOptions requestOptions ) throws AlgoliaException { return client . postRequest ( "/1/indexes/" + encodedIndexName + "/synonyms/clear?forwardToReplicas=" + forwardToReplicas , "" , true , false , requestOptions ) ; }
Delete all synonym set
375
public JSONObject getRule ( String objectID , RequestOptions requestOptions ) throws AlgoliaException { if ( objectID == null || objectID . length ( ) == 0 ) { throw new AlgoliaException ( "Invalid objectID" ) ; } try { return client . getRequest ( "/1/indexes/" + encodedIndexName + "/rules/" + URLEncoder . encode ( objectID , "UTF-8" ) , true , requestOptions ) ; } catch ( UnsupportedEncodingException e ) { throw new RuntimeException ( e ) ; } }
Get a query rule
376
public Query setOptionalWords ( List < String > words ) { StringBuilder builder = new StringBuilder ( ) ; for ( String word : words ) { builder . append ( word ) ; builder . append ( "," ) ; } this . optionalWords = builder . toString ( ) ; return this ; }
Set the list of words that should be considered as optional when found in the query .
377
static String getFallbackDomain ( ) { int javaVersion = getJavaVersion ( ) ; boolean javaHasSNI = javaVersion >= 7 ; final VersionInfo vi = VersionInfo . loadVersionInfo ( "org.apache.http.client" , APIClient . class . getClassLoader ( ) ) ; String version = vi . getRelease ( ) ; String [ ] split = version . split ( "\\." ) ; int major = Integer . parseInt ( split [ 0 ] ) ; int minor = Integer . parseInt ( split [ 1 ] ) ; int patch = Integer . parseInt ( split [ 2 ] ) ; boolean apacheClientHasSNI = major > 4 || major == 4 && minor > 3 || major == 4 && minor == 3 && patch >= 2 ; if ( apacheClientHasSNI && javaHasSNI ) { return "algolianet.com" ; } else { return "algolia.net" ; } }
Get the appropriate fallback domain depending on the current SNI support . Checks Java version and Apache HTTP Client s version .
378
public void setUserAgent ( String agent , String agentVersion ) { userAgent = String . format ( "Algolia for Java (%s); JVM (%s); %s (%s)" , version , System . getProperty ( "java.version" ) , agent , agentVersion ) ; }
Allow to modify the user - agent in order to add the user agent of the integration
379
public void enableRateLimitForward ( String adminAPIKey , String endUserIP , String rateLimitAPIKey ) { this . forwardAdminAPIKey = adminAPIKey ; this . forwardEndUserIP = endUserIP ; this . forwardRateLimitAPIKey = rateLimitAPIKey ; }
Allow to use IP rate limit when you have a proxy between end - user and Algolia . This option will set the X - Forwarded - For HTTP header with the client IP and the X - Forwarded - API - Key with the API Key having rate limits .
380
public void changeAnimation ( ViewHolder oldHolder , ViewHolder newHolder , int fromX , int fromY , int toX , int toY ) { final float prevTranslationX = ViewCompat . getTranslationX ( oldHolder . itemView ) ; final float prevTranslationY = ViewCompat . getTranslationY ( oldHolder . itemView ) ; final float prevValue = ViewCompat . getAlpha ( oldHolder . itemView ) ; resetAnimation ( oldHolder ) ; int deltaX = ( int ) ( toX - fromX - prevTranslationX ) ; int deltaY = ( int ) ( toY - fromY - prevTranslationY ) ; ViewCompat . setTranslationX ( oldHolder . itemView , prevTranslationX ) ; ViewCompat . setTranslationY ( oldHolder . itemView , prevTranslationY ) ; ViewCompat . setAlpha ( oldHolder . itemView , prevValue ) ; if ( newHolder != null ) { resetAnimation ( newHolder ) ; ViewCompat . setTranslationX ( newHolder . itemView , - deltaX ) ; ViewCompat . setTranslationY ( newHolder . itemView , - deltaY ) ; ViewCompat . setAlpha ( newHolder . itemView , 0 ) ; } }
the whole change animation if we have to cross animate two views
381
protected long determineBalance ( final IntervalTreeNode node ) { if ( node == null ) { return 0L ; } return ( node . hasLeft ( ) ? node . getLeft ( ) . getHeight ( ) : 0 ) - ( node . hasRight ( ) ? node . getRight ( ) . getHeight ( ) : 0 ) ; }
Get Balance factor of node N
382
protected void fill ( int fromIndex , int endIndex ) { fromIndex = fromIndex == - 1 ? 0 : fromIndex ; endIndex = endIndex == - 1 || endIndex > this . timeSeries . length ? this . timeSeries . length : endIndex ; final T val ; if ( applyZero ( ) ) { val = zero ( ) ; } else { val = null ; } for ( int i = fromIndex ; i < endIndex ; i ++ ) { set ( i , val ) ; } }
Resets the values from [ fromIndex endIndex ) .
383
public BucketEndPoints getEndPoints ( final int bucketsFromNow ) throws IllegalTimePoint { if ( currentNowIdx == - 1 || now == null ) { throw new IllegalTimePoint ( "The now is not set yet, thus no end-points can be returned" ) ; } return now . move ( bucketsFromNow ) ; }
Gets the end - points by an offset to now i . e . 0 means to get the now bucket - 1 gets the previous bucket and + 1 will get the next bucket .
384
public int getBucketSize ( final long diffInSeconds ) { final long secondsPerBucket = TimeUnit . SECONDS . convert ( config . getBucketSize ( ) , config . getTimeUnit ( ) ) ; return ( int ) Math . ceil ( ( double ) diffInSeconds / secondsPerBucket ) ; }
Determines the number of buckets used to cover the seconds .
385
public void setNow ( final long unixTimeStamp ) throws IllegalTimePointMovement { if ( this . currentNowIdx == - 1 || this . now == null ) { this . currentNowIdx = 0 ; this . now = normalizeUnixTimeStamp ( unixTimeStamp ) ; } else { final BucketEndPoints newNow = normalizeUnixTimeStamp ( unixTimeStamp ) ; final long diff = this . now . diff ( newNow ) ; if ( diff < 0 ) { throw new IllegalTimePointMovement ( String . format ( "Cannot move to the past (current: %s, update: %s)" , this . now , newNow ) ) ; } else if ( diff > 0 ) { final int newCurrentNowIdx = idx ( currentNowIdx - diff ) ; if ( diff >= config . getTimeSeriesSize ( ) ) { fill ( - 1 , - 1 ) ; } else if ( newCurrentNowIdx > currentNowIdx ) { fill ( 0 , currentNowIdx ) ; fill ( newCurrentNowIdx , - 1 ) ; } else { fill ( newCurrentNowIdx , currentNowIdx ) ; } this . currentNowIdx = newCurrentNowIdx ; this . now = newNow ; } } }
Modifies the now unix time stamp of the time - series . This modifies the time - series i . e . data might be removed if the data is pushed .
386
public SerIterable createIterable ( String metaTypeDescription , JodaBeanSer settings , Map < String , Class < ? > > knownTypes ) { if ( metaTypeDescription . equals ( "Set" ) ) { return set ( Object . class , EMPTY_VALUE_TYPES ) ; } if ( metaTypeDescription . equals ( "List" ) ) { return list ( Object . class , EMPTY_VALUE_TYPES ) ; } if ( metaTypeDescription . equals ( "Collection" ) ) { return list ( Object . class , EMPTY_VALUE_TYPES ) ; } if ( metaTypeDescription . equals ( "Map" ) ) { return map ( Object . class , Object . class , EMPTY_VALUE_TYPES ) ; } if ( metaTypeDescription . endsWith ( "[][][]" ) ) { throw new IllegalArgumentException ( "Three-dimensional arrays cannot be parsed" ) ; } if ( metaTypeDescription . endsWith ( "[][]" ) ) { Class < ? > type = META_TYPE_MAP . get ( metaTypeDescription ) ; if ( type != null ) { return array ( type ) ; } String clsStr = metaTypeDescription . substring ( 0 , metaTypeDescription . length ( ) - 4 ) ; try { Class < ? > cls = SerTypeMapper . decodeType ( clsStr , settings , null , knownTypes ) ; String compound = "[L" + cls . getName ( ) + ";" ; return array ( Class . forName ( compound ) ) ; } catch ( ClassNotFoundException ex ) { throw new RuntimeException ( ex ) ; } } if ( metaTypeDescription . endsWith ( "[]" ) ) { Class < ? > type = META_TYPE_MAP . get ( metaTypeDescription ) ; if ( type == null ) { String clsStr = metaTypeDescription . substring ( 0 , metaTypeDescription . length ( ) - 2 ) ; try { type = SerTypeMapper . decodeType ( clsStr , settings , null , knownTypes ) ; } catch ( ClassNotFoundException ex ) { throw new RuntimeException ( ex ) ; } } return type . isPrimitive ( ) ? arrayPrimitive ( type ) : array ( type ) ; } return null ; }
Creates an iterator wrapper for a meta - type description .
387
public SerIterable createIterable ( SerIterable iterable ) { List < Class < ? > > valueTypeTypes = iterable . valueTypeTypes ( ) ; if ( valueTypeTypes . size ( ) > 0 ) { Class < ? > valueType = iterable . valueType ( ) ; if ( NavigableSet . class . isAssignableFrom ( valueType ) ) { return navigableSet ( valueTypeTypes . get ( 0 ) , EMPTY_VALUE_TYPES ) ; } if ( SortedSet . class . isAssignableFrom ( valueType ) ) { return sortedSet ( valueTypeTypes . get ( 0 ) , EMPTY_VALUE_TYPES ) ; } if ( Set . class . isAssignableFrom ( valueType ) ) { return set ( valueTypeTypes . get ( 0 ) , EMPTY_VALUE_TYPES ) ; } if ( Collection . class . isAssignableFrom ( valueType ) ) { return list ( valueTypeTypes . get ( 0 ) , EMPTY_VALUE_TYPES ) ; } if ( NavigableMap . class . isAssignableFrom ( valueType ) ) { if ( valueTypeTypes . size ( ) == 2 ) { return navigableMap ( valueTypeTypes . get ( 0 ) , valueTypeTypes . get ( 1 ) , EMPTY_VALUE_TYPES ) ; } return navigableMap ( Object . class , Object . class , EMPTY_VALUE_TYPES ) ; } if ( SortedMap . class . isAssignableFrom ( valueType ) ) { if ( valueTypeTypes . size ( ) == 2 ) { return sortedMap ( valueTypeTypes . get ( 0 ) , valueTypeTypes . get ( 1 ) , EMPTY_VALUE_TYPES ) ; } return sortedMap ( Object . class , Object . class , EMPTY_VALUE_TYPES ) ; } if ( Map . class . isAssignableFrom ( valueType ) ) { if ( valueTypeTypes . size ( ) == 2 ) { return map ( valueTypeTypes . get ( 0 ) , valueTypeTypes . get ( 1 ) , EMPTY_VALUE_TYPES ) ; } return map ( Object . class , Object . class , EMPTY_VALUE_TYPES ) ; } if ( valueType . isArray ( ) ) { if ( valueType . getComponentType ( ) . isPrimitive ( ) ) { return arrayPrimitive ( valueType . getComponentType ( ) ) ; } else { return array ( valueType . getComponentType ( ) ) ; } } } return null ; }
Creates an iterator wrapper for a child where there are second level generic parameters .
388
public static final SerIterable array ( final Class < ? > valueType ) { final List < Object > list = new ArrayList < > ( ) ; return new SerIterable ( ) { public SerIterator iterator ( ) { return array ( build ( ) , Object . class , valueType ) ; } public void add ( Object key , Object column , Object value , int count ) { if ( key != null ) { throw new IllegalArgumentException ( "Unexpected key" ) ; } if ( count != 1 ) { throw new IllegalArgumentException ( "Unexpected count" ) ; } for ( int i = 0 ; i < count ; i ++ ) { list . add ( value ) ; } } public Object [ ] build ( ) { Object [ ] array = ( Object [ ] ) Array . newInstance ( valueType , list . size ( ) ) ; return list . toArray ( array ) ; } public Class < ? > valueType ( ) { return valueType ; } public List < Class < ? > > valueTypeTypes ( ) { return EMPTY_VALUE_TYPES ; } } ; }
Gets an iterable wrapper for an object array .
389
public static final SerIterator array ( final Object [ ] array , final Class < ? > declaredType , final Class < ? > valueType ) { return new SerIterator ( ) { private int index = - 1 ; public String metaTypeName ( ) { return metaTypeNameBase ( valueType ) ; } private String metaTypeNameBase ( Class < ? > arrayType ) { if ( arrayType . isArray ( ) ) { return metaTypeNameBase ( arrayType . getComponentType ( ) ) + "[]" ; } if ( arrayType == Object . class ) { return "Object[]" ; } if ( arrayType == String . class ) { return "String[]" ; } return arrayType . getName ( ) + "[]" ; } public boolean metaTypeRequired ( ) { if ( valueType == Object . class ) { return Object [ ] . class . isAssignableFrom ( declaredType ) == false ; } if ( valueType == String . class ) { return String [ ] . class . isAssignableFrom ( declaredType ) == false ; } return true ; } public int size ( ) { return array . length ; } public boolean hasNext ( ) { return ( index + 1 ) < array . length ; } public void next ( ) { index ++ ; } public Class < ? > valueType ( ) { return valueType ; } public List < Class < ? > > valueTypeTypes ( ) { return Collections . emptyList ( ) ; } public Object value ( ) { return array [ index ] ; } } ; }
Gets an iterator wrapper for an object array .
390
private StartElement advanceToStartElement ( ) throws Exception { while ( reader . hasNext ( ) ) { XMLEvent event = nextEvent ( "advnc " ) ; if ( event . isStartElement ( ) ) { return event . asStartElement ( ) ; } } throw new IllegalArgumentException ( "Unexpected end of document" ) ; }
reader can be anywhere but normally at StartDocument
391
private String advanceAndParseText ( ) throws Exception { StringBuilder buf = new StringBuilder ( ) ; while ( reader . hasNext ( ) ) { XMLEvent event = nextEvent ( "text " ) ; if ( event . isCharacters ( ) ) { buf . append ( event . asCharacters ( ) . getData ( ) ) ; } else if ( event . isEndElement ( ) ) { return buf . toString ( ) ; } else if ( event . isStartElement ( ) ) { throw new IllegalArgumentException ( "Unexpected start tag" ) ; } } throw new IllegalArgumentException ( "Unexpected end of document" ) ; }
reader must be at StartElement
392
private XMLEvent nextEvent ( String location ) throws Exception { XMLEvent event = reader . nextEvent ( ) ; return event ; }
provide for debugging
393
public JodaBeanSer withIndent ( String indent ) { JodaBeanUtils . notNull ( indent , "indent" ) ; return new JodaBeanSer ( indent , newLine , converter , iteratorFactory , shortTypes , deserializers , includeDerived ) ; }
Returns a copy of this serializer with the specified pretty print indent .
394
public JodaBeanSer withNewLine ( String newLine ) { JodaBeanUtils . notNull ( newLine , "newLine" ) ; return new JodaBeanSer ( indent , newLine , converter , iteratorFactory , shortTypes , deserializers , includeDerived ) ; }
Returns a copy of this serializer with the specified pretty print new line .
395
public JodaBeanSer withIteratorFactory ( SerIteratorFactory iteratorFactory ) { JodaBeanUtils . notNull ( iteratorFactory , "iteratorFactory" ) ; return new JodaBeanSer ( indent , newLine , converter , iteratorFactory , shortTypes , deserializers , includeDerived ) ; }
Returns a copy of this serializer with the specified iterator factory .
396
public JodaBeanSer withShortTypes ( boolean shortTypes ) { return new JodaBeanSer ( indent , newLine , converter , iteratorFactory , shortTypes , deserializers , includeDerived ) ; }
Returns a copy of this serializer with the short types flag set .
397
public boolean isSerialized ( MetaProperty < ? > prop ) { return prop . style ( ) . isSerializable ( ) || ( prop . style ( ) . isDerived ( ) && includeDerived ) ; }
Checks if the property is serialized .
398
public static < P > BasicProperty < P > of ( Bean bean , MetaProperty < P > metaProperty ) { return new BasicProperty < > ( bean , metaProperty ) ; }
Factory to create a property avoiding duplicate generics .
399
void writeInt ( int value ) throws IOException { if ( ( value & 0xfffffff8 ) == 0 ) { output . append ( ( char ) ( value + 48 ) ) ; } else { output . append ( Integer . toString ( value ) ) ; } }
Writes a JSON int .