idx
int64 0
41.2k
| question
stringlengths 73
5.81k
| target
stringlengths 5
918
|
|---|---|---|
5,500
|
public static AVObject parseAVObject ( String objectString ) { if ( StringUtil . isEmpty ( objectString ) ) { return null ; } objectString = objectString . replaceAll ( "^\\{\\s*\"@type\":\\s*\"[A-Za-z\\.]+\"," , "{" ) ; objectString = objectString . replaceAll ( "\"@type\":\\s*\"com.avos.avoscloud.AVObject\"," , "\"@type\":\"cn.leancloud.AVObject\"," ) ; objectString = objectString . replaceAll ( "\"@type\":\\s*\"com.avos.avoscloud.AVInstallation\"," , "\"@type\":\"cn.leancloud.AVInstallation\"," ) ; objectString = objectString . replaceAll ( "\"@type\":\\s*\"com.avos.avoscloud.AVUser\"," , "\"@type\":\"cn.leancloud.AVUser\"," ) ; objectString = objectString . replaceAll ( "\"@type\":\\s*\"com.avos.avoscloud.AVStatus\"," , "\"@type\":\"cn.leancloud.AVStatus\"," ) ; objectString = objectString . replaceAll ( "\"@type\":\\s*\"com.avos.avoscloud.AVRole\"," , "\"@type\":\"cn.leancloud.AVRole\"," ) ; objectString = objectString . replaceAll ( "\"@type\":\\s*\"com.avos.avoscloud.AVFile\"," , "\"@type\":\"cn.leancloud.AVFile\"," ) ; objectString = objectString . replaceAll ( "\"@type\":\\s*\"com.avos.avoscloud.ops.[A-Za-z]+Op\"," , "" ) ; return JSON . parseObject ( objectString , AVObject . class , Feature . SupportAutoType ) ; }
|
create AVObject instance from json string which generated by AVObject . toString or AVObject . toJSONString .
|
5,501
|
public static AVObject createWithoutData ( String className , String objectId ) { AVObject object = new AVObject ( className ) ; object . setObjectId ( objectId ) ; return object ; }
|
create a new instance with particular classname and objectId .
|
5,502
|
public static < T extends AVObject > T createWithoutData ( Class < T > clazz , String objectId ) throws AVException { try { T obj = clazz . newInstance ( ) ; obj . setClassName ( Transformer . getSubClassName ( clazz ) ) ; obj . setObjectId ( objectId ) ; return obj ; } catch ( Exception ex ) { throw new AVException ( ex ) ; } }
|
create a new instance with particular class and objectId .
|
5,503
|
public void subscribeInBackground ( final AVLiveQuerySubscribeCallback callback ) { Map < String , String > params = query . assembleParameters ( ) ; params . put ( "className" , query . getClassName ( ) ) ; Map < String , Object > dataMap = new HashMap < > ( ) ; dataMap . put ( QUERY , params ) ; String session = getSessionToken ( ) ; if ( ! StringUtil . isEmpty ( session ) ) { dataMap . put ( SESSION_TOKEN , session ) ; } dataMap . put ( SUBSCRIBE_ID , getSubscribeId ( ) ) ; RealtimeClient . getInstance ( ) . subscribeLiveQuery ( dataMap ) . subscribe ( new Observer < JSONObject > ( ) { public void onSubscribe ( Disposable disposable ) { } public void onNext ( JSONObject jsonObject ) { if ( null != jsonObject && jsonObject . containsKey ( QUERY_ID ) ) { queryId = jsonObject . getString ( QUERY_ID ) ; liveQuerySet . add ( AVLiveQuery . this ) ; loginLiveQuery ( callback ) ; } else if ( null != callback ) { callback . internalDone ( new AVException ( AVException . UNKNOWN , "response isn't recognized" ) ) ; } } public void onError ( Throwable throwable ) { if ( null != callback ) { callback . internalDone ( new AVException ( throwable ) ) ; } } public void onComplete ( ) { } } ) ; }
|
subscribe the query
|
5,504
|
public void unsubscribeInBackground ( final AVLiveQuerySubscribeCallback callback ) { Map < String , Object > map = new HashMap < > ( ) ; map . put ( SUBSCRIBE_ID , getSubscribeId ( ) ) ; map . put ( QUERY_ID , queryId ) ; RealtimeClient . getInstance ( ) . unsubscribeLiveQuery ( map ) . subscribe ( new Observer < JSONObject > ( ) { public void onSubscribe ( Disposable disposable ) { } public void onNext ( JSONObject jsonObject ) { liveQuerySet . remove ( AVLiveQuery . this ) ; queryId = "" ; if ( null != callback ) { callback . internalDone ( null ) ; } } public void onError ( Throwable throwable ) { if ( null != callback ) { callback . internalDone ( new AVException ( throwable ) ) ; } } public void onComplete ( ) { } } ) ; }
|
unsubscribe the query
|
5,505
|
protected static AVObject parseAVObject ( String content ) { Map < String , String > contentMap = JSON . parseObject ( content , Map . class ) ; return parseAVObject ( contentMap ) ; }
|
just for serializer test .
|
5,506
|
public static AVIMConversationsQuery or ( List < AVIMConversationsQuery > queries ) { if ( null == queries || 0 == queries . size ( ) ) { throw new IllegalArgumentException ( "Queries cannot be empty" ) ; } AVIMClient client = queries . get ( 0 ) . client ; AVIMConversationsQuery result = new AVIMConversationsQuery ( client ) ; for ( AVIMConversationsQuery query : queries ) { if ( ! client . getClientId ( ) . equals ( query . client . getClientId ( ) ) ) { throw new IllegalArgumentException ( "All queries must be for the same client" ) ; } result . conditions . addOrItems ( new QueryOperation ( "$or" , "$or" , query . conditions . compileWhereOperationMap ( ) ) ) ; } return result ; }
|
Constructs a AVIMConversationsQuery that is the or of the given queries .
|
5,507
|
public void onBackPressed ( ) { File current = this . core . getCurrentFolder ( ) ; if ( ! this . useBackButton || current == null || current . getParent ( ) == null || current . getPath ( ) . compareTo ( this . startFolder . getPath ( ) ) == 0 ) { super . onBackPressed ( ) ; } else { this . core . loadFolder ( current . getParent ( ) ) ; } }
|
Called when the user push the back button .
|
5,508
|
public void setFile ( File file ) { if ( file != null ) { this . file = file ; this . setLabel ( file . getName ( ) ) ; this . updateIcon ( ) ; } }
|
Defines the file represented by this item .
|
5,509
|
private void updateIcon ( ) { int icon = R . drawable . document_gray ; if ( this . selectable ) { icon = ( this . file != null && file . isDirectory ( ) ) ? R . drawable . folder : R . drawable . document ; } this . icon . setImageDrawable ( getResources ( ) . getDrawable ( icon ) ) ; if ( icon != R . drawable . document_gray ) { this . label . setTextColor ( getResources ( ) . getColor ( R . color . daidalos_active_file ) ) ; } else { this . label . setTextColor ( getResources ( ) . getColor ( R . color . daidalos_inactive_file ) ) ; } }
|
Updates the icon according to if the file is a folder and if it can be selected .
|
5,510
|
public static AVIMMessageIntervalBound createBound ( String messageId , long timestamp , boolean closed ) { return new AVIMMessageIntervalBound ( messageId , timestamp , closed ) ; }
|
create query bound
|
5,511
|
public static void turnOnVIVOPush ( final AVCallback < Boolean > callback ) { com . vivo . push . PushClient . getInstance ( AVOSCloud . getContext ( ) ) . turnOnPush ( new com . vivo . push . IPushActionListener ( ) { public void onStateChanged ( int state ) { if ( null == callback ) { AVException exception = null ; if ( 0 != state ) { exception = new AVException ( AVException . UNKNOWN , "VIVO server internal error, state=" + state ) ; } callback . internalDone ( null == exception , exception ) ; } } } ) ; }
|
turn on VIVO push .
|
5,512
|
public static boolean isSupportVIVOPush ( Context context ) { com . vivo . push . PushClient client = com . vivo . push . PushClient . getInstance ( context ) ; if ( null == client ) { return false ; } return client . isSupport ( ) ; }
|
current device support VIVO push or not .
|
5,513
|
public void start ( ) { try { if ( null == recorder ) { recorder = new MediaRecorder ( ) ; recorder . setAudioSource ( MediaRecorder . AudioSource . DEFAULT ) ; recorder . setOutputFormat ( MediaRecorder . OutputFormat . DEFAULT ) ; recorder . setAudioEncoder ( MediaRecorder . AudioEncoder . AAC ) ; recorder . setOutputFile ( this . localPath ) ; recorder . prepare ( ) ; } else { recorder . reset ( ) ; recorder . setOutputFile ( this . localPath ) ; } recorder . start ( ) ; startRecordTime = System . currentTimeMillis ( ) ; if ( null != this . listener ) { this . listener . onStartRecord ( ) ; } } catch ( IOException ex ) { LOGGER . e ( "failed to start MediaRecorder. cause: " , ex ) ; } }
|
Begins capturing and encoding data to the file specified .
|
5,514
|
public static synchronized void subscribe ( android . content . Context context , java . lang . String channel , java . lang . Class < ? extends android . app . Activity > cls ) { startServiceIfRequired ( context , cls ) ; final String finalChannel = channel ; AVInstallation . getCurrentInstallation ( ) . addUnique ( "channels" , finalChannel ) ; _installationSaveHandler . sendMessage ( Message . obtain ( ) ) ; if ( cls != null ) { AVNotificationManager manager = AVPushMessageListener . getInstance ( ) . getNotificationManager ( ) ; manager . addDefaultPushCallback ( channel , cls . getName ( ) ) ; if ( manager . getDefaultPushCallback ( AVOSCloud . getApplicationId ( ) ) == null ) { manager . addDefaultPushCallback ( AVOSCloud . getApplicationId ( ) , cls . getName ( ) ) ; } } }
|
Helper function to subscribe to push notifications with the default application icon .
|
5,515
|
public static void setDefaultPushCallback ( android . content . Context context , java . lang . Class < ? extends android . app . Activity > cls ) { LOGGER . d ( "setDefaultPushCallback cls=" + cls . getName ( ) ) ; startServiceIfRequired ( context , cls ) ; AVPushMessageListener . getInstance ( ) . getNotificationManager ( ) . addDefaultPushCallback ( AVOSCloud . getApplicationId ( ) , cls . getName ( ) ) ; }
|
Provides a default Activity class to handle pushes . Setting a default allows your program to handle pushes that aren t registered with a subscribe call . This can happen when your application changes its subscriptions directly through the AVInstallation or via push - to - query .
|
5,516
|
public static synchronized void unsubscribe ( android . content . Context context , java . lang . String channel ) { if ( channel == null ) { return ; } AVPushMessageListener . getInstance ( ) . getNotificationManager ( ) . removeDefaultPushCallback ( channel ) ; final java . lang . String finalChannel = channel ; if ( StringUtil . isEmpty ( AVInstallation . getCurrentInstallation ( ) . getObjectId ( ) ) ) { AVInstallation . getCurrentInstallation ( ) . saveInBackground ( ) . subscribe ( new Observer < AVObject > ( ) { public void onSubscribe ( Disposable d ) { } public void onNext ( AVObject avObject ) { AVInstallation . getCurrentInstallation ( ) . removeAll ( "channels" , Arrays . asList ( finalChannel ) ) ; _installationSaveHandler . sendMessage ( Message . obtain ( ) ) ; } public void onError ( Throwable e ) { LOGGER . w ( e ) ; } public void onComplete ( ) { } } ) ; } else { AVInstallation . getCurrentInstallation ( ) . removeAll ( "channels" , Arrays . asList ( finalChannel ) ) ; _installationSaveHandler . sendMessage ( Message . obtain ( ) ) ; } }
|
Cancels a previous call to subscribe . If the user is not subscribed to this channel this is a no - op . This call does not require internet access . It returns without blocking
|
5,517
|
public void setReadAccess ( String userId , boolean allowed ) { if ( StringUtil . isEmpty ( userId ) ) { throw new IllegalArgumentException ( "cannot setRead/WriteAccess for null userId" ) ; } boolean writePermission = getWriteAccess ( userId ) ; setPermissionsIfNonEmpty ( userId , allowed , writePermission ) ; }
|
Set whether the given user id is allowed to read this object .
|
5,518
|
public void setWriteAccess ( String userId , boolean allowed ) { if ( StringUtil . isEmpty ( userId ) ) { throw new IllegalArgumentException ( "cannot setRead/WriteAccess for null userId" ) ; } boolean readPermission = getReadAccess ( userId ) ; setPermissionsIfNonEmpty ( userId , readPermission , allowed ) ; }
|
Set whether the given user id is allowed to write this object .
|
5,519
|
@ JSONField ( serialize = false ) public boolean isAuthenticated ( ) { String sessionToken = getSessionToken ( ) ; return ! StringUtil . isEmpty ( sessionToken ) ; }
|
whether user is authenticated or not .
|
5,520
|
public Observable < AVUser > signUpInBackground ( ) { JSONObject paramData = generateChangedParam ( ) ; logger . d ( "signup param: " + paramData . toJSONString ( ) ) ; return PaasClient . getStorageClient ( ) . signUp ( paramData ) . map ( new Function < AVUser , AVUser > ( ) { public AVUser apply ( AVUser avUser ) throws Exception { AVUser . this . mergeRawData ( avUser ) ; return AVUser . this ; } } ) ; }
|
sign up in background .
|
5,521
|
public Observable < Boolean > checkAuthenticatedInBackground ( ) { String sessionToken = getSessionToken ( ) ; if ( StringUtil . isEmpty ( sessionToken ) ) { logger . d ( "sessionToken is not existed." ) ; return Observable . just ( false ) ; } return PaasClient . getStorageClient ( ) . checkAuthenticated ( sessionToken ) ; }
|
Session token operations
|
5,522
|
public static void drop ( HttpExchange req ) throws IOException { setStandardHeaders ( req ) ; req . sendResponseHeaders ( 418 , 0 ) ; try ( OutputStream body = req . getResponseBody ( ) ) { body . write ( ( "apdu4j/" + SCTool . getVersion ( ) ) . getBytes ( StandardCharsets . UTF_8 ) ) ; } }
|
Everything that is not 200 is considered as bad request .
|
5,523
|
public void statusMessage ( String text ) throws IOException { Map < String , Object > m = JSONProtocol . cmd ( "message" ) ; m . put ( "text" , text ) ; pipe . send ( m ) ; if ( ! JSONProtocol . check ( m , pipe . recv ( ) ) ) { throw new IOException ( "Could not display status" ) ; } }
|
Shows a message on the screen
|
5,524
|
public Button dialog ( String message ) throws IOException , UserCancelExcption { Map < String , Object > m = JSONProtocol . cmd ( "dialog" ) ; m . put ( "text" , message ) ; pipe . send ( m ) ; Map < String , Object > r = pipe . recv ( ) ; if ( ! JSONProtocol . check ( m , r ) || ! r . containsKey ( "button" ) ) { throw new IOException ( "Unknown button pressed" ) ; } return Button . valueOf ( ( ( String ) r . get ( "button" ) ) . toUpperCase ( ) ) ; }
|
Shows a dialog message to the user and returns the pressed button .
|
5,525
|
public String input ( String message ) throws IOException , UserCancelExcption { Map < String , Object > m = JSONProtocol . cmd ( "input" ) ; m . put ( "text" , message ) ; pipe . send ( m ) ; Map < String , Object > r = pipe . recv ( ) ; if ( ! JSONProtocol . check ( m , r ) || ! r . containsKey ( "value" ) ) { throw new IOException ( "No value" ) ; } return ( String ) r . get ( "value" ) ; }
|
Asks for input from the user .
|
5,526
|
public Button decrypt ( String message , byte [ ] apdu ) throws IOException , UserCancelExcption { Map < String , Object > m = JSONProtocol . cmd ( "decrypt" ) ; m . put ( "text" , message ) ; m . put ( "bytes" , HexUtils . bin2hex ( apdu ) ) ; pipe . send ( m ) ; Map < String , Object > r = pipe . recv ( ) ; if ( JSONProtocol . check ( m , r ) ) { return Button . valueOf ( ( ( String ) r . get ( "button" ) ) . toUpperCase ( ) ) ; } else { throw new IOException ( "Unknown button pressed" ) ; } }
|
Shows the response of the APDU to the user .
|
5,527
|
public boolean verifyPIN ( int p2 , String text ) throws IOException , UserCancelExcption { Map < String , Object > m = JSONProtocol . cmd ( "verify" ) ; m . put ( "p2" , p2 ) ; m . put ( "text" , text ) ; pipe . send ( m ) ; return JSONProtocol . check ( m , pipe . recv ( ) ) ; }
|
Issues a ISO VERIFY on the remote terminal .
|
5,528
|
private static Map < FEATURE , Integer > tokenize ( byte [ ] tlv ) { HashMap < FEATURE , Integer > m = new HashMap < FEATURE , Integer > ( ) ; if ( tlv . length % 6 != 0 ) { throw new IllegalArgumentException ( "Bad response length: " + tlv . length ) ; } for ( int i = 0 ; i < tlv . length ; i += 6 ) { int ft = tlv [ i + 0 ] & 0xFF ; FEATURE f = FEATURE . fromValue ( ft ) ; byte [ ] c = Arrays . copyOfRange ( tlv , i + 2 , i + 6 ) ; ByteBuffer buffer = ByteBuffer . wrap ( c ) ; buffer . order ( ByteOrder . BIG_ENDIAN ) ; int ci = buffer . getInt ( ) ; m . put ( f , ci ) ; } return m ; }
|
Parse the features into FEATURE - > control code map
|
5,529
|
@ SuppressFBWarnings ( "DP_CREATE_CLASSLOADER_INSIDE_DO_PRIVILEGED" ) public static TerminalFactory loadTerminalFactory ( String jar , String classname , String type , String arg ) throws NoSuchAlgorithmException { try { if ( arg != null ) { arg = URLDecoder . decode ( arg , "UTF-8" ) ; } final TerminalFactory tf ; final Class < ? > cls ; if ( jar != null ) { URLClassLoader loader = new URLClassLoader ( new URL [ ] { new File ( jar ) . toURI ( ) . toURL ( ) } , TerminalManager . class . getClassLoader ( ) ) ; cls = Class . forName ( classname , true , loader ) ; } else { cls = Class . forName ( classname ) ; } Provider p = ( Provider ) cls . getConstructor ( ) . newInstance ( ) ; tf = TerminalFactory . getInstance ( type == null ? "PC/SC" : type , arg , p ) ; return tf ; } catch ( UnsupportedEncodingException | MalformedURLException | ClassNotFoundException | InstantiationException | IllegalAccessException | IllegalArgumentException | InvocationTargetException | NoSuchMethodException | SecurityException e ) { throw new NoSuchAlgorithmException ( "Could not load " + classname + ": " + e . getMessage ( ) ) ; } catch ( NoSuchAlgorithmException e ) { if ( e . getCause ( ) != null ) { Class < ? > cause = e . getCause ( ) . getClass ( ) ; if ( cause . equals ( java . lang . UnsupportedOperationException . class ) ) { throw new NoSuchAlgorithmException ( e . getCause ( ) . getMessage ( ) ) ; } if ( cause . equals ( java . lang . UnsatisfiedLinkError . class ) ) { throw new NoSuchAlgorithmException ( e . getCause ( ) . getMessage ( ) ) ; } } throw e ; } }
|
Load the TerminalFactory possibly from a JAR and with arguments
|
5,530
|
public static CardTerminal getTheReader ( String spec ) throws CardException { try { String msg = "This application expects one and only one card reader (with an inserted card)" ; TerminalFactory tf = getTerminalFactory ( spec ) ; CardTerminals tl = tf . terminals ( ) ; List < CardTerminal > list = tl . list ( State . CARD_PRESENT ) ; if ( list . size ( ) > 1 ) { throw new CardException ( msg ) ; } else if ( list . size ( ) == 1 ) { return list . get ( 0 ) ; } else { List < CardTerminal > wl = tl . list ( State . ALL ) ; if ( wl . size ( ) == 1 ) { CardTerminal t = wl . get ( 0 ) ; System . out . println ( "Waiting for a card insertion to " + t . getName ( ) ) ; if ( t . waitForCardPresent ( 0 ) ) { return t ; } else { throw new CardException ( "Could not find a reader with a card" ) ; } } else { throw new CardException ( msg ) ; } } } catch ( NoSuchAlgorithmException e ) { throw new CardException ( e ) ; } }
|
Returns a card reader that has a card in it . Asks for card insertion if the system only has a single reader .
|
5,531
|
public static Map < String , Object > nok ( Map < String , Object > msg , String error ) { HashMap < String , Object > r = new HashMap < > ( ) ; r . put ( ( String ) msg . get ( "cmd" ) , "NOK" ) ; r . put ( "session" , msg . get ( "session" ) ) ; if ( error != null ) { r . put ( "ERROR" , error ) ; } return r ; }
|
User by client
|
5,532
|
public static Map < String , Object > ok ( Map < String , Object > msg ) { HashMap < String , Object > r = new HashMap < > ( ) ; r . put ( ( String ) msg . get ( "cmd" ) , "OK" ) ; r . put ( "session" , msg . get ( "session" ) ) ; return r ; }
|
Used by client
|
5,533
|
public static Map < String , Object > cmd ( String c ) { HashMap < String , Object > r = new HashMap < > ( ) ; r . put ( "cmd" , c . toUpperCase ( ) ) ; return r ; }
|
Used by server . Server adds session ID transparently .
|
5,534
|
public static boolean check ( Map < String , Object > m , Map < String , Object > r ) { if ( r . get ( m . get ( "cmd" ) ) . equals ( "OK" ) ) { return true ; } return false ; }
|
User by server
|
5,535
|
public static SocketTransport connect ( InetSocketAddress address , X509Certificate pinnedcert ) throws IOException { SSLSocketFactory factory = get_ssl_socket_factory ( pinnedcert ) ; Socket s = factory . createSocket ( address . getHostString ( ) , address . getPort ( ) ) ; return new SocketTransport ( s ) ; }
|
Connects to the mentioned host and port with SSL and checks the certificate against the pinned version .
|
5,536
|
public static ServerSocket make_server ( int port , String pkcs12Path , String pkcs12Pass ) throws IOException , KeyStoreException , NoSuchAlgorithmException , CertificateException , UnrecoverableKeyException , KeyManagementException { try ( InputStream in = new FileInputStream ( pkcs12Path ) ) { return make_server ( port , in , pkcs12Pass ) ; } }
|
Helper class to make a SSL server
|
5,537
|
private static ServerSocket make_server ( int port , InputStream pkcs12stream , String pkcs12Pass ) throws IOException , KeyStoreException , NoSuchAlgorithmException , CertificateException , UnrecoverableKeyException , KeyManagementException { KeyStore ks = KeyStore . getInstance ( "PKCS12" ) ; ks . load ( pkcs12stream , pkcs12Pass . toCharArray ( ) ) ; KeyManagerFactory kmf = KeyManagerFactory . getInstance ( KeyManagerFactory . getDefaultAlgorithm ( ) ) ; kmf . init ( ks , pkcs12Pass . toCharArray ( ) ) ; SSLContext sc = SSLContext . getInstance ( "TLS" ) ; sc . init ( kmf . getKeyManagers ( ) , null , null ) ; return sc . getServerSocketFactory ( ) . createServerSocket ( port ) ; }
|
Helper class to make a SSL socket server
|
5,538
|
BraveSpan currentSpan ( ) { BraveScope scope = currentScopes . get ( ) . peekFirst ( ) ; if ( scope != null ) { return scope . span ( ) ; } else { brave . Span braveSpan = tracer . currentSpan ( ) ; if ( braveSpan != null ) { return new BraveSpan ( tracer , braveSpan ) ; } } return null ; }
|
Attempts to get a span from the current api falling back to brave s native one
|
5,539
|
public < C > void inject ( SpanContext spanContext , Format < C > format , C carrier ) { Injector < TextMap > injector = formatToInjector . get ( format ) ; if ( injector == null ) { throw new UnsupportedOperationException ( format + " not in " + formatToInjector . keySet ( ) ) ; } TraceContext traceContext = ( ( BraveSpanContext ) spanContext ) . unwrap ( ) ; injector . inject ( traceContext , ( TextMap ) carrier ) ; }
|
Injects the underlying context using B3 encoding by default .
|
5,540
|
public < C > BraveSpanContext extract ( Format < C > format , C carrier ) { Extractor < TextMap > extractor = formatToExtractor . get ( format ) ; if ( extractor == null ) { throw new UnsupportedOperationException ( format + " not in " + formatToExtractor . keySet ( ) ) ; } TraceContextOrSamplingFlags extractionResult = extractor . extract ( ( TextMap ) carrier ) ; return BraveSpanContext . create ( extractionResult ) ; }
|
Extracts the underlying context using B3 encoding by default . Null is returned when there is no encoded context in the carrier or upon error extracting it .
|
5,541
|
public < T > JsonReaderI < T > getMapper ( Class < T > type ) { @ SuppressWarnings ( "unchecked" ) JsonReaderI < T > map = ( JsonReaderI < T > ) cache . get ( type ) ; if ( map != null ) return map ; if ( type instanceof Class ) { if ( Map . class . isAssignableFrom ( type ) ) map = new DefaultMapperCollection < T > ( this , type ) ; else if ( List . class . isAssignableFrom ( type ) ) map = new DefaultMapperCollection < T > ( this , type ) ; if ( map != null ) { cache . put ( type , map ) ; return map ; } } if ( type . isArray ( ) ) map = new ArraysMapper . GenericMapper < T > ( this , type ) ; else if ( List . class . isAssignableFrom ( type ) ) map = new CollectionMapper . ListClass < T > ( this , type ) ; else if ( Map . class . isAssignableFrom ( type ) ) map = new CollectionMapper . MapClass < T > ( this , type ) ; else map = new BeansMapper . Bean < T > ( this , type ) ; cache . putIfAbsent ( type , map ) ; return map ; }
|
Get the corresponding mapper Class or create it on first call
|
5,542
|
protected void readNoEnd ( ) throws ParseException { if ( ++ pos >= len ) { this . c = EOI ; throw new ParseException ( pos - 1 , ERROR_UNEXPECTED_EOF , "EOF" ) ; } else this . c = ( char ) in [ pos ] ; }
|
read data can not be EOI
|
5,543
|
protected boolean discardPath ( String pathToEntry , Entry < String , Object > entry ) { if ( ! foundAsPrefix ( pathToEntry ) || ! delim . accept ( entry . getKey ( ) ) ) { return true ; } return false ; }
|
if the full path to the entry is not contained in any of the paths to retain - remove it from the object this step does not remove entries whose full path is contained in a path to retain but are not equal to an entry to retain
|
5,544
|
static public Accessor [ ] getAccessors ( Class < ? > type , FieldFilter filter ) { Class < ? > nextClass = type ; HashMap < String , Accessor > map = new HashMap < String , Accessor > ( ) ; if ( filter == null ) filter = BasicFiledFilter . SINGLETON ; while ( nextClass != Object . class ) { Field [ ] declaredFields = nextClass . getDeclaredFields ( ) ; for ( Field field : declaredFields ) { String fn = field . getName ( ) ; if ( map . containsKey ( fn ) ) continue ; Accessor acc = new Accessor ( nextClass , field , filter ) ; if ( ! acc . isUsable ( ) ) continue ; map . put ( fn , acc ) ; } nextClass = nextClass . getSuperclass ( ) ; } return map . values ( ) . toArray ( new Accessor [ map . size ( ) ] ) ; }
|
Extract all Accessor for the field of the given class .
|
5,545
|
protected static void autoUnBoxing1 ( MethodVisitor mv , Type fieldType ) { switch ( fieldType . getSort ( ) ) { case Type . BOOLEAN : mv . visitTypeInsn ( CHECKCAST , "java/lang/Boolean" ) ; mv . visitMethodInsn ( INVOKEVIRTUAL , "java/lang/Boolean" , "booleanValue" , "()Z" ) ; break ; case Type . BYTE : mv . visitTypeInsn ( CHECKCAST , "java/lang/Byte" ) ; mv . visitMethodInsn ( INVOKEVIRTUAL , "java/lang/Byte" , "byteValue" , "()B" ) ; break ; case Type . CHAR : mv . visitTypeInsn ( CHECKCAST , "java/lang/Character" ) ; mv . visitMethodInsn ( INVOKEVIRTUAL , "java/lang/Character" , "charValue" , "()C" ) ; break ; case Type . SHORT : mv . visitTypeInsn ( CHECKCAST , "java/lang/Short" ) ; mv . visitMethodInsn ( INVOKEVIRTUAL , "java/lang/Short" , "shortValue" , "()S" ) ; break ; case Type . INT : mv . visitTypeInsn ( CHECKCAST , "java/lang/Integer" ) ; mv . visitMethodInsn ( INVOKEVIRTUAL , "java/lang/Integer" , "intValue" , "()I" ) ; break ; case Type . FLOAT : mv . visitTypeInsn ( CHECKCAST , "java/lang/Float" ) ; mv . visitMethodInsn ( INVOKEVIRTUAL , "java/lang/Float" , "floatValue" , "()F" ) ; break ; case Type . LONG : mv . visitTypeInsn ( CHECKCAST , "java/lang/Long" ) ; mv . visitMethodInsn ( INVOKEVIRTUAL , "java/lang/Long" , "longValue" , "()J" ) ; break ; case Type . DOUBLE : mv . visitTypeInsn ( CHECKCAST , "java/lang/Double" ) ; mv . visitMethodInsn ( INVOKEVIRTUAL , "java/lang/Double" , "doubleValue" , "()D" ) ; break ; case Type . ARRAY : mv . visitTypeInsn ( CHECKCAST , fieldType . getInternalName ( ) ) ; break ; default : mv . visitTypeInsn ( CHECKCAST , fieldType . getInternalName ( ) ) ; } }
|
Append the call of proper extract primitive type of an boxed object .
|
5,546
|
public String getAsString ( String key ) { Object obj = this . get ( key ) ; if ( obj == null ) return null ; return obj . toString ( ) ; }
|
A Simple Helper object to String
|
5,547
|
public Number getAsNumber ( String key ) { Object obj = this . get ( key ) ; if ( obj == null ) return null ; if ( obj instanceof Number ) return ( Number ) obj ; return Long . valueOf ( obj . toString ( ) ) ; }
|
A Simple Helper cast an Object to an Number
|
5,548
|
public JSONNavi < T > root ( ) { this . current = this . root ; this . stack . clear ( ) ; this . path . clear ( ) ; this . failure = false ; this . missingKey = null ; this . failureMessage = null ; return this ; }
|
return to root node
|
5,549
|
public JSONNavi < T > add ( Object ... values ) { array ( ) ; if ( failure ) return this ; List < Object > list = a ( current ) ; for ( Object o : values ) list . add ( o ) ; return this ; }
|
add value to the current arrays
|
5,550
|
public String asString ( ) { if ( current == null ) return null ; if ( current instanceof String ) return ( String ) current ; return current . toString ( ) ; }
|
get the current object value as String if the current Object is null return null .
|
5,551
|
public Double asDoubleObj ( ) { if ( current == null ) return null ; if ( current instanceof Number ) { if ( current instanceof Double ) return ( Double ) current ; return Double . valueOf ( ( ( Number ) current ) . doubleValue ( ) ) ; } return Double . NaN ; }
|
get the current object value as Double if the current Double can not be cast as Integer return null .
|
5,552
|
public Float asFloatObj ( ) { if ( current == null ) return null ; if ( current instanceof Number ) { if ( current instanceof Float ) return ( Float ) current ; return Float . valueOf ( ( ( Number ) current ) . floatValue ( ) ) ; } return Float . NaN ; }
|
get the current object value as Float if the current Float can not be cast as Integer return null .
|
5,553
|
public Integer asIntegerObj ( ) { if ( current == null ) return null ; if ( current instanceof Number ) { if ( current instanceof Integer ) return ( Integer ) current ; if ( current instanceof Long ) { Long l = ( Long ) current ; if ( l . longValue ( ) == l . intValue ( ) ) { return Integer . valueOf ( l . intValue ( ) ) ; } } return null ; } return null ; }
|
get the current object value as Integer if the current Object can not be cast as Integer return null .
|
5,554
|
public Long asLongObj ( ) { if ( current == null ) return null ; if ( current instanceof Number ) { if ( current instanceof Long ) return ( Long ) current ; if ( current instanceof Integer ) return Long . valueOf ( ( ( Number ) current ) . longValue ( ) ) ; return null ; } return null ; }
|
get the current object value as Long if the current Object can not be cast as Long return null .
|
5,555
|
public Boolean asBooleanObj ( ) { if ( current == null ) return null ; if ( current instanceof Boolean ) return ( Boolean ) current ; return null ; }
|
get the current object value as Boolean if the current Object is not a Boolean return null .
|
5,556
|
@ SuppressWarnings ( "unchecked" ) public JSONNavi < T > object ( ) { if ( failure ) return this ; if ( current == null && readonly ) failure ( "Can not create Object child in readonly" , null ) ; if ( current != null ) { if ( isObject ( ) ) return this ; if ( isArray ( ) ) failure ( "can not use Object feature on Array." , null ) ; failure ( "Can not use current possition as Object" , null ) ; } else { current = mapper . createObject ( ) ; } if ( root == null ) root = ( T ) current ; else store ( ) ; return this ; }
|
Set current value as Json Object You can also skip this call Objects can be create automatically .
|
5,557
|
@ SuppressWarnings ( "unchecked" ) public JSONNavi < T > array ( ) { if ( failure ) return this ; if ( current == null && readonly ) failure ( "Can not create Array child in readonly" , null ) ; if ( current != null ) { if ( isArray ( ) ) return this ; if ( isObject ( ) ) failure ( "can not use Object feature on Array." , null ) ; failure ( "Can not use current possition as Object" , null ) ; } else { current = mapper . createArray ( ) ; } if ( root == null ) root = ( T ) current ; else store ( ) ; return this ; }
|
Set current value as Json Array You can also skip this call Arrays can be create automatically .
|
5,558
|
private void store ( ) { Object parent = stack . peek ( ) ; if ( isObject ( parent ) ) o ( parent ) . put ( ( String ) missingKey , current ) ; else if ( isArray ( parent ) ) { int index = ( ( Number ) missingKey ) . intValue ( ) ; List < Object > lst = a ( parent ) ; while ( lst . size ( ) <= index ) lst . add ( null ) ; lst . set ( index , current ) ; } }
|
internal store current Object in current non existing localization
|
5,559
|
@ SuppressWarnings ( "unchecked" ) private Map < String , Object > o ( Object obj ) { return ( Map < String , Object > ) obj ; }
|
internal cast to Map
|
5,560
|
public JSONNavi < ? > at ( int index ) { if ( failure ) return this ; if ( ! ( current instanceof List ) ) return failure ( "current node is not an Array" , index ) ; @ SuppressWarnings ( "unchecked" ) List < Object > lst = ( ( List < Object > ) current ) ; if ( index < 0 ) { index = lst . size ( ) + index ; if ( index < 0 ) index = 0 ; } if ( index >= lst . size ( ) ) if ( readonly ) return failure ( "Out of bound exception for index" , index ) ; else { stack . add ( current ) ; path . add ( index ) ; current = null ; missingKey = index ; return this ; } Object next = lst . get ( index ) ; stack . add ( current ) ; path . add ( index ) ; current = next ; return this ; }
|
Access to the index position .
|
5,561
|
public JSONNavi < ? > atNext ( ) { if ( failure ) return this ; if ( ! ( current instanceof List ) ) return failure ( "current node is not an Array" , null ) ; @ SuppressWarnings ( "unchecked" ) List < Object > lst = ( ( List < Object > ) current ) ; return at ( lst . size ( ) ) ; }
|
Access to last + 1 the index position .
|
5,562
|
private JSONNavi < ? > failure ( String err , Object jPathPostfix ) { failure = true ; StringBuilder sb = new StringBuilder ( ) ; sb . append ( "Error: " ) ; sb . append ( err ) ; sb . append ( " at " ) ; sb . append ( getJPath ( ) ) ; if ( jPathPostfix != null ) if ( jPathPostfix instanceof Integer ) sb . append ( '[' ) . append ( jPathPostfix ) . append ( ']' ) ; else sb . append ( '/' ) . append ( jPathPostfix ) ; this . failureMessage = sb . toString ( ) ; return this ; }
|
Internally log errors .
|
5,563
|
@ SuppressWarnings ( "unchecked" ) public T convert ( Object current ) { if ( obj != null ) return obj ; return ( T ) mapper . convert ( current ) ; }
|
Allow a mapper to converte a temprary structure to the final data format .
|
5,564
|
public static Date convertToDate ( Object obj ) { if ( obj == null ) return null ; if ( obj instanceof Date ) return ( Date ) obj ; if ( obj instanceof Number ) return new Date ( ( ( Number ) obj ) . longValue ( ) ) ; if ( obj instanceof String ) { StringTokenizer st = new StringTokenizer ( ( String ) obj , " -/:,.+" ) ; String s1 = "" ; if ( ! st . hasMoreTokens ( ) ) return null ; s1 = st . nextToken ( ) ; if ( s1 . length ( ) == 4 && Character . isDigit ( s1 . charAt ( 0 ) ) ) return getYYYYMMDD ( st , s1 ) ; if ( daysTable . containsKey ( s1 ) ) { if ( ! st . hasMoreTokens ( ) ) return null ; s1 = st . nextToken ( ) ; } if ( monthsTable . containsKey ( s1 ) ) return getMMDDYYYY ( st , s1 ) ; if ( Character . isDigit ( s1 . charAt ( 0 ) ) ) return getDDMMYYYY ( st , s1 ) ; return null ; } throw new RuntimeException ( "Primitive: Can not convert " + obj . getClass ( ) . getName ( ) + " to int" ) ; }
|
try read a Date from a Object
|
5,565
|
private static String trySkip ( StringTokenizer st , String s1 , Calendar cal ) { while ( true ) { TimeZone tz = timeZoneMapping . get ( s1 ) ; if ( tz != null ) { cal . setTimeZone ( tz ) ; if ( ! st . hasMoreTokens ( ) ) return null ; s1 = st . nextToken ( ) ; continue ; } if ( voidData . contains ( s1 ) ) { if ( s1 . equalsIgnoreCase ( "pm" ) ) cal . add ( Calendar . AM_PM , Calendar . PM ) ; if ( s1 . equalsIgnoreCase ( "am" ) ) cal . add ( Calendar . AM_PM , Calendar . AM ) ; if ( ! st . hasMoreTokens ( ) ) return null ; s1 = st . nextToken ( ) ; continue ; } return s1 ; } }
|
Handle some Date Keyword like PST UTC am pm ...
|
5,566
|
public static Object parseKeepingOrder ( Reader in ) { try { return new JSONParser ( DEFAULT_PERMISSIVE_MODE ) . parse ( in , defaultReader . DEFAULT_ORDERED ) ; } catch ( Exception e ) { return null ; } }
|
Parse Json input to a java Object keeping element order
|
5,567
|
public static String compress ( String input , JSONStyle style ) { try { StringBuilder sb = new StringBuilder ( ) ; new JSONParser ( DEFAULT_PERMISSIVE_MODE ) . parse ( input , new CompessorMapper ( defaultReader , sb , style ) ) ; return sb . toString ( ) ; } catch ( Exception e ) { return input ; } }
|
Reformat Json input keeping element order
|
5,568
|
public static boolean isValidJsonStrict ( Reader in ) throws IOException { try { new JSONParser ( MODE_RFC4627 ) . parse ( in , FakeMapper . DEFAULT ) ; return true ; } catch ( ParseException e ) { return false ; } }
|
Check RFC4627 Json Syntax from input Reader
|
5,569
|
public static boolean isValidJsonStrict ( String s ) { try { new JSONParser ( MODE_RFC4627 ) . parse ( s , FakeMapper . DEFAULT ) ; return true ; } catch ( ParseException e ) { return false ; } }
|
check RFC4627 Json Syntax from input String
|
5,570
|
public static boolean isValidJson ( Reader in ) throws IOException { try { new JSONParser ( DEFAULT_PERMISSIVE_MODE ) . parse ( in , FakeMapper . DEFAULT ) ; return true ; } catch ( ParseException e ) { return false ; } }
|
Check Json Syntax from input Reader
|
5,571
|
public static boolean isValidJson ( String s ) { try { new JSONParser ( DEFAULT_PERMISSIVE_MODE ) . parse ( s , FakeMapper . DEFAULT ) ; return true ; } catch ( ParseException e ) { return false ; } }
|
Check Json Syntax from input String
|
5,572
|
public static < T > void remapField ( Class < T > type , String jsonFieldName , String javaFieldName ) { defaultReader . remapField ( type , jsonFieldName , javaFieldName ) ; defaultWriter . remapField ( type , javaFieldName , jsonFieldName ) ; }
|
remap field from java to json .
|
5,573
|
public static < T > void registerWriter ( Class < ? > cls , JsonWriterI < T > writer ) { defaultWriter . registerWriter ( writer , cls ) ; }
|
Register a serializer for a class .
|
5,574
|
public static < T > void registerReader ( Class < T > type , JsonReaderI < T > mapper ) { defaultReader . registerReader ( type , mapper ) ; }
|
register a deserializer for a class .
|
5,575
|
public static void addTypeMapper ( Class < ? > clz , Class < ? > mapper ) { synchronized ( classMapper ) { LinkedHashSet < Class < ? > > h = classMapper . get ( clz ) ; if ( h == null ) { h = new LinkedHashSet < Class < ? > > ( ) ; classMapper . put ( clz , h ) ; } h . add ( mapper ) ; } }
|
Field type convertor for all classes
|
5,576
|
@ SuppressWarnings ( "rawtypes" ) public JsonWriterI getWriterByInterface ( Class < ? > clazz ) { for ( WriterByInterface w : writerInterfaces ) { if ( w . _interface . isAssignableFrom ( clazz ) ) return w . _writer ; } return null ; }
|
try to find a Writer by Cheking implemented interface
|
5,577
|
public void registerWriterInterfaceLast ( Class < ? > interFace , JsonWriterI < ? > writer ) { writerInterfaces . addLast ( new WriterByInterface ( interFace , writer ) ) ; }
|
associate an Writer to a interface With Low priority
|
5,578
|
public void registerWriterInterfaceFirst ( Class < ? > interFace , JsonWriterI < ? > writer ) { writerInterfaces . addFirst ( new WriterByInterface ( interFace , writer ) ) ; }
|
associate an Writer to a interface With Hi priority
|
5,579
|
public < T > void registerWriter ( JsonWriterI < T > writer , Class < ? > ... cls ) { for ( Class < ? > c : cls ) data . put ( c , writer ) ; }
|
associate an Writer to a Class
|
5,580
|
private void internalSetFiled ( MethodVisitor mv , Accessor acc ) { mv . visitVarInsn ( ALOAD , 1 ) ; mv . visitTypeInsn ( CHECKCAST , classNameInternal ) ; mv . visitVarInsn ( ALOAD , 3 ) ; Type fieldType = Type . getType ( acc . getType ( ) ) ; Class < ? > type = acc . getType ( ) ; String destClsName = Type . getInternalName ( type ) ; Method conMtd = convMtds . get ( type ) ; if ( conMtd != null ) { String clsSig = Type . getInternalName ( conMtd . getDeclaringClass ( ) ) ; String mtdName = conMtd . getName ( ) ; String mtdSig = Type . getMethodDescriptor ( conMtd ) ; mv . visitMethodInsn ( INVOKESTATIC , clsSig , mtdName , mtdSig ) ; } else if ( acc . isEnum ( ) ) { Label isNull = new Label ( ) ; mv . visitJumpInsn ( IFNULL , isNull ) ; mv . visitVarInsn ( ALOAD , 3 ) ; mv . visitMethodInsn ( INVOKEVIRTUAL , "java/lang/Object" , "toString" , "()Ljava/lang/String;" ) ; mv . visitMethodInsn ( INVOKESTATIC , destClsName , "valueOf" , "(Ljava/lang/String;)L" + destClsName + ";" ) ; mv . visitVarInsn ( ASTORE , 3 ) ; mv . visitLabel ( isNull ) ; mv . visitFrame ( Opcodes . F_SAME , 0 , null , 0 , null ) ; mv . visitVarInsn ( ALOAD , 1 ) ; mv . visitTypeInsn ( CHECKCAST , this . classNameInternal ) ; mv . visitVarInsn ( ALOAD , 3 ) ; mv . visitTypeInsn ( CHECKCAST , destClsName ) ; } else if ( type . equals ( String . class ) ) { Label isNull = new Label ( ) ; mv . visitJumpInsn ( IFNULL , isNull ) ; mv . visitVarInsn ( ALOAD , 3 ) ; mv . visitMethodInsn ( INVOKEVIRTUAL , "java/lang/Object" , "toString" , "()Ljava/lang/String;" ) ; mv . visitVarInsn ( ASTORE , 3 ) ; mv . visitLabel ( isNull ) ; mv . visitFrame ( Opcodes . F_SAME , 0 , null , 0 , null ) ; mv . visitVarInsn ( ALOAD , 1 ) ; mv . visitTypeInsn ( CHECKCAST , this . classNameInternal ) ; mv . visitVarInsn ( ALOAD , 3 ) ; mv . visitTypeInsn ( CHECKCAST , destClsName ) ; } else { mv . visitTypeInsn ( CHECKCAST , destClsName ) ; } if ( acc . isPublic ( ) ) { mv . visitFieldInsn ( PUTFIELD , classNameInternal , acc . getName ( ) , fieldType . getDescriptor ( ) ) ; } else { String sig = Type . getMethodDescriptor ( acc . setter ) ; mv . visitMethodInsn ( INVOKEVIRTUAL , classNameInternal , acc . setter . getName ( ) , sig ) ; } mv . visitInsn ( RETURN ) ; }
|
Dump Set Field Code
|
5,581
|
private void throwExIntParam ( MethodVisitor mv , Class < ? > exCls ) { String exSig = Type . getInternalName ( exCls ) ; mv . visitTypeInsn ( NEW , exSig ) ; mv . visitInsn ( DUP ) ; mv . visitLdcInsn ( "mapping " + this . className + " failed to map field:" ) ; mv . visitVarInsn ( ILOAD , 2 ) ; mv . visitMethodInsn ( INVOKESTATIC , "java/lang/Integer" , "toString" , "(I)Ljava/lang/String;" ) ; mv . visitMethodInsn ( INVOKEVIRTUAL , "java/lang/String" , "concat" , "(Ljava/lang/String;)Ljava/lang/String;" ) ; mv . visitMethodInsn ( INVOKESPECIAL , exSig , "<init>" , "(Ljava/lang/String;)V" ) ; mv . visitInsn ( ATHROW ) ; }
|
add Throws statement with int param 2
|
5,582
|
private void throwExStrParam ( MethodVisitor mv , Class < ? > exCls ) { String exSig = Type . getInternalName ( exCls ) ; mv . visitTypeInsn ( NEW , exSig ) ; mv . visitInsn ( DUP ) ; mv . visitLdcInsn ( "mapping " + this . className + " failed to map field:" ) ; mv . visitVarInsn ( ALOAD , 2 ) ; mv . visitMethodInsn ( INVOKEVIRTUAL , "java/lang/String" , "concat" , "(Ljava/lang/String;)Ljava/lang/String;" ) ; mv . visitMethodInsn ( INVOKESPECIAL , exSig , "<init>" , "(Ljava/lang/String;)V" ) ; mv . visitInsn ( ATHROW ) ; }
|
add Throws statement with String param 2
|
5,583
|
private void ifNotEqJmp ( MethodVisitor mv , int param , int value , Label label ) { mv . visitVarInsn ( ILOAD , param ) ; if ( value == 0 ) { mv . visitJumpInsn ( IFNE , label ) ; } else if ( value == 1 ) { mv . visitInsn ( ICONST_1 ) ; mv . visitJumpInsn ( IF_ICMPNE , label ) ; } else if ( value == 2 ) { mv . visitInsn ( ICONST_2 ) ; mv . visitJumpInsn ( IF_ICMPNE , label ) ; } else if ( value == 3 ) { mv . visitInsn ( ICONST_3 ) ; mv . visitJumpInsn ( IF_ICMPNE , label ) ; } else if ( value == 4 ) { mv . visitInsn ( ICONST_4 ) ; mv . visitJumpInsn ( IF_ICMPNE , label ) ; } else if ( value == 5 ) { mv . visitInsn ( ICONST_5 ) ; mv . visitJumpInsn ( IF_ICMPNE , label ) ; } else if ( value >= 6 ) { mv . visitIntInsn ( BIPUSH , value ) ; mv . visitJumpInsn ( IF_ICMPNE , label ) ; } else { throw new RuntimeException ( "non supported negative values" ) ; } }
|
dump a Jump if not EQ
|
5,584
|
public void seek ( long position ) throws IOException { if ( position != this . position ) { this . position = position ; blockSize = 0 ; data . seek ( position ) ; } bufPos = 0 ; }
|
It s only valid to seek to known block starts .
|
5,585
|
public static SparkeyWriter createNew ( File file , CompressionType compressionType , int compressionBlockSize ) throws IOException { return SingleThreadedSparkeyWriter . createNew ( file , compressionType , compressionBlockSize ) ; }
|
Creates a new sparkey writer with the specified compression
|
5,586
|
public Iterator < SparkeyReader . Entry > iterator ( ) { try { final BlockPositionedInputStream stream ; { final InputStream stream2 = new BufferedInputStream ( new FileInputStream ( logFile ) , 128 * 1024 ) ; Sparkey . incrOpenFiles ( ) ; stream2 . skip ( start ) ; stream = header . getCompressionType ( ) . createBlockInput ( stream2 , header . getCompressionBlockSize ( ) , start ) ; } return new Iterator < SparkeyReader . Entry > ( ) { private long prevPos ; private long pos = start ; private final byte [ ] keyBuf = new byte [ ( int ) header . getMaxKeyLen ( ) ] ; private final Entry entry = new Entry ( stream , keyBuf ) ; private boolean ready = false ; private int entryIndex ; private boolean closed = false ; public boolean hasNext ( ) { if ( ready ) { return true ; } try { entry . stream . skipRemaining ( ) ; pos = stream . getBlockPosition ( ) ; if ( pos >= end ) { closeStream ( ) ; return false ; } if ( pos == prevPos ) { entryIndex ++ ; } else { entryIndex = 0 ; } prevPos = pos ; entry . position = pos ; entry . entryIndex = entryIndex ; entry . type = null ; entry . keyLen = 0 ; entry . valueLen = 0 ; int first ; try { first = Util . readUnsignedVLQInt ( stream ) ; } catch ( EOFException e ) { closeStream ( ) ; return false ; } int second = Util . readUnsignedVLQInt ( stream ) ; long remaining ; if ( first == 0 ) { entry . type = SparkeyReader . Type . DELETE ; entry . keyLen = second ; entry . valueLen = 0 ; remaining = 0 ; } else { entry . type = SparkeyReader . Type . PUT ; entry . keyLen = first - 1 ; entry . valueLen = second ; remaining = entry . valueLen ; } stream . read ( keyBuf , 0 , entry . keyLen ) ; entry . stream . setRemaining ( remaining ) ; ready = true ; return true ; } catch ( IOException e ) { closeStream ( ) ; throw new RuntimeException ( e ) ; } } private void closeStream ( ) { if ( closed ) { return ; } closed = true ; Sparkey . decrOpenFiles ( ) ; Util . nonThrowingClose ( stream ) ; } public Entry next ( ) { if ( ! hasNext ( ) ) { throw new NoSuchElementException ( ) ; } ready = false ; return entry ; } public void remove ( ) { throw new UnsupportedOperationException ( ) ; } } ; } catch ( IOException e ) { throw new RuntimeException ( e ) ; } }
|
Get an iterator over all the entries in the log file .
|
5,587
|
public CompletionStage < ReloadableSparkeyReader > load ( final File logFile ) { checkArgument ( isValidLogFile ( logFile ) ) ; CompletableFuture < ReloadableSparkeyReader > result = new CompletableFuture < > ( ) ; this . executorService . submit ( ( ) -> { switchReader ( logFile ) ; result . complete ( this ) ; } ) ; return result ; }
|
Load a new log file into this reader .
|
5,588
|
public static void uncompress ( int [ ] in , int tmpinpos , int inlength , int [ ] out , int currentPos , int outlength ) { final int finalpos = tmpinpos + inlength ; while ( tmpinpos < finalpos ) { final int howmany = decompressblock ( out , currentPos , in , tmpinpos , outlength ) ; outlength -= howmany ; currentPos += howmany ; tmpinpos += 1 ; } }
|
Uncompress data from an array to another array .
|
5,589
|
public int [ ] compress ( int [ ] input ) { int [ ] compressed = new int [ input . length + input . length / 100 + 1024 ] ; compressed [ 0 ] = input . length ; IntWrapper outpos = new IntWrapper ( 1 ) ; IntWrapper initvalue = new IntWrapper ( 0 ) ; try { codec . headlessCompress ( input , new IntWrapper ( 0 ) , input . length , compressed , outpos , initvalue ) ; } catch ( IndexOutOfBoundsException ioebe ) { throw new UncompressibleInputException ( "Your input is too poorly compressible with the current codec : " + codec ) ; } compressed = Arrays . copyOf ( compressed , outpos . intValue ( ) ) ; return compressed ; }
|
Compress an array and returns the compressed result as a new array .
|
5,590
|
public int [ ] uncompress ( int [ ] compressed ) { int [ ] decompressed = new int [ compressed [ 0 ] ] ; IntWrapper inpos = new IntWrapper ( 1 ) ; codec . headlessUncompress ( compressed , inpos , compressed . length - inpos . intValue ( ) , decompressed , new IntWrapper ( 0 ) , decompressed . length , new IntWrapper ( 0 ) ) ; return decompressed ; }
|
Uncompress an array and returns the uncompressed result as a new array .
|
5,591
|
protected static final int s16Decompress ( int [ ] out , int outOffset , int [ ] in , int inOffset , int n ) { int numIdx , j = 0 , bits = 0 ; numIdx = in [ inOffset ] >>> S16_BITSSIZE ; int num = S16_NUM [ numIdx ] < n ? S16_NUM [ numIdx ] : n ; for ( j = 0 , bits = 0 ; j < num ; j ++ ) { out [ outOffset + j ] = readBitsForS16 ( in , inOffset , bits , S16_BITS [ numIdx ] [ j ] ) ; bits += S16_BITS [ numIdx ] [ j ] ; } return num ; }
|
Decompress an integer array using Simple16
|
5,592
|
static private int readBitsForS16 ( int [ ] in , final int inIntOffset , final int inWithIntOffset , final int bits ) { final int val = ( in [ inIntOffset ] >>> inWithIntOffset ) ; return val & ( 0xffffffff >>> ( 32 - bits ) ) ; }
|
Read a certain number of bits of a integer on the input array
|
5,593
|
public void basicExampleHeadless ( ) { int [ ] data = new int [ 2342351 ] ; System . out . println ( "Compressing " + data . length + " integers in one go using the headless approach" ) ; for ( int k = 0 ; k < data . length ; ++ k ) data [ k ] = k ; SkippableIntegratedComposition codec = new SkippableIntegratedComposition ( new IntegratedBinaryPacking ( ) , new IntegratedVariableByte ( ) ) ; int [ ] compressed = new int [ data . length + 1024 ] ; IntWrapper inputoffset = new IntWrapper ( 0 ) ; IntWrapper outputoffset = new IntWrapper ( 1 ) ; compressed [ 0 ] = data . length ; codec . headlessCompress ( data , inputoffset , data . length , compressed , outputoffset , new IntWrapper ( 0 ) ) ; System . out . println ( "compressed from " + data . length * 4 / 1024 + "KB to " + outputoffset . intValue ( ) * 4 / 1024 + "KB" ) ; compressed = Arrays . copyOf ( compressed , outputoffset . intValue ( ) ) ; int howmany = compressed [ 0 ] ; int [ ] recovered = new int [ howmany ] ; IntWrapper recoffset = new IntWrapper ( 0 ) ; codec . headlessUncompress ( compressed , new IntWrapper ( 1 ) , compressed . length , recovered , recoffset , howmany , new IntWrapper ( 0 ) ) ; if ( Arrays . equals ( data , recovered ) ) System . out . println ( "data is recovered without loss" ) ; else throw new RuntimeException ( "bug" ) ; System . out . println ( ) ; }
|
Like the basicExample but we store the input array size manually .
|
5,594
|
public static void unsortedExample ( ) { final int N = 1333333 ; int [ ] data = new int [ N ] ; for ( int k = 0 ; k < N ; k += 1 ) data [ k ] = 3 ; for ( int k = 0 ; k < N ; k += 5 ) data [ k ] = 100 ; for ( int k = 0 ; k < N ; k += 533 ) data [ k ] = 10000 ; int [ ] compressed = new int [ N + 1024 ] ; IntegerCODEC codec = new Composition ( new FastPFOR ( ) , new VariableByte ( ) ) ; IntWrapper inputoffset = new IntWrapper ( 0 ) ; IntWrapper outputoffset = new IntWrapper ( 0 ) ; codec . compress ( data , inputoffset , data . length , compressed , outputoffset ) ; System . out . println ( "compressed unsorted integers from " + data . length * 4 / 1024 + "KB to " + outputoffset . intValue ( ) * 4 / 1024 + "KB" ) ; compressed = Arrays . copyOf ( compressed , outputoffset . intValue ( ) ) ; int [ ] recovered = new int [ N ] ; IntWrapper recoffset = new IntWrapper ( 0 ) ; codec . uncompress ( compressed , new IntWrapper ( 0 ) , compressed . length , recovered , recoffset ) ; if ( Arrays . equals ( data , recovered ) ) System . out . println ( "data is recovered without loss" ) ; else throw new RuntimeException ( "bug" ) ; System . out . println ( ) ; }
|
This is an example to show you can compress unsorted integers as long as most are small .
|
5,595
|
public static void advancedExample ( ) { int TotalSize = 2342351 ; int ChunkSize = 16384 ; System . out . println ( "Compressing " + TotalSize + " integers using chunks of " + ChunkSize + " integers (" + ChunkSize * 4 / 1024 + "KB)" ) ; System . out . println ( "(It is often better for applications to work in chunks fitting in CPU cache.)" ) ; int [ ] data = new int [ TotalSize ] ; for ( int k = 0 ; k < data . length ; ++ k ) data [ k ] = k ; IntegratedIntegerCODEC regularcodec = new IntegratedBinaryPacking ( ) ; IntegratedVariableByte ivb = new IntegratedVariableByte ( ) ; IntegratedIntegerCODEC lastcodec = new IntegratedComposition ( regularcodec , ivb ) ; int [ ] compressed = new int [ TotalSize + 1024 ] ; IntWrapper inputoffset = new IntWrapper ( 0 ) ; IntWrapper outputoffset = new IntWrapper ( 0 ) ; for ( int k = 0 ; k < TotalSize / ChunkSize ; ++ k ) regularcodec . compress ( data , inputoffset , ChunkSize , compressed , outputoffset ) ; lastcodec . compress ( data , inputoffset , TotalSize % ChunkSize , compressed , outputoffset ) ; System . out . println ( "compressed from " + data . length * 4 / 1024 + "KB to " + outputoffset . intValue ( ) * 4 / 1024 + "KB" ) ; compressed = Arrays . copyOf ( compressed , outputoffset . intValue ( ) ) ; int [ ] recovered = new int [ ChunkSize ] ; IntWrapper compoff = new IntWrapper ( 0 ) ; IntWrapper recoffset ; int currentpos = 0 ; while ( compoff . get ( ) < compressed . length ) { recoffset = new IntWrapper ( 0 ) ; regularcodec . uncompress ( compressed , compoff , compressed . length - compoff . get ( ) , recovered , recoffset ) ; if ( recoffset . get ( ) < ChunkSize ) { ivb . uncompress ( compressed , compoff , compressed . length - compoff . get ( ) , recovered , recoffset ) ; } for ( int i = 0 ; i < recoffset . get ( ) ; ++ i ) { if ( data [ currentpos + i ] != recovered [ i ] ) throw new RuntimeException ( "bug" ) ; } currentpos += recoffset . get ( ) ; } System . out . println ( "data is recovered without loss" ) ; System . out . println ( ) ; }
|
This is like the basic example but we show how to process larger arrays in chunks .
|
5,596
|
public static int estimateCompressedSize ( int [ ] inputBlock , int bits , int blockSize ) { int maxNoExp = ( 1 << bits ) - 1 ; int outputOffset = HEADER_SIZE + bits * blockSize ; int expNum = 0 ; for ( int i = 0 ; i < blockSize ; ++ i ) { if ( inputBlock [ i ] > maxNoExp ) { expNum ++ ; } } outputOffset += ( expNum << 5 ) ; return outputOffset ; }
|
Estimate the compressed size in ints of a block
|
5,597
|
public static int decompressBBitSlots ( int [ ] outDecompSlots , int [ ] inCompBlock , int blockSize , int bits ) { int compressedBitSize = 0 ; int offset = HEADER_SIZE ; for ( int i = 0 ; i < blockSize ; i ++ ) { outDecompSlots [ i ] = readBits ( inCompBlock , offset , bits ) ; offset += bits ; } compressedBitSize = bits * blockSize ; return compressedBitSize ; }
|
Decompress b - bit slots
|
5,598
|
public static int decompressBlockByS16 ( int [ ] outDecompBlock , int [ ] inCompBlock , int inStartOffsetInBits , int blockSize ) { int inOffset = ( inStartOffsetInBits + 31 ) >>> 5 ; int num , outOffset = 0 , numLeft ; for ( numLeft = blockSize ; numLeft > 0 ; numLeft -= num ) { num = Simple16 . s16Decompress ( outDecompBlock , outOffset , inCompBlock , inOffset , numLeft ) ; outOffset += num ; inOffset ++ ; } int compressedBitSize = ( inOffset << 5 ) - inStartOffsetInBits ; return compressedBitSize ; }
|
Decompress a block of blockSize integers using Simple16 algorithm
|
5,599
|
public static final void writeBits ( int [ ] out , int val , int outOffset , int bits ) { if ( bits == 0 ) return ; final int index = outOffset >>> 5 ; final int skip = outOffset & 0x1f ; val &= ( 0xffffffff >>> ( 32 - bits ) ) ; out [ index ] |= ( val << skip ) ; if ( 32 - skip < bits ) { out [ index + 1 ] |= ( val >>> ( 32 - skip ) ) ; } }
|
Write a certain number of bits of an integer into an integer array starting from the given start offset
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.