idx
int64
0
41.2k
question
stringlengths
83
4.15k
target
stringlengths
5
715
19,300
public JsonParserBuilder options ( JsonParserOption first , JsonParserOption ... rest ) { this . options = EnumSet . of ( first , rest ) ; return this ; }
Sets the parser options . The previous options if any are discarded .
19,301
public JsonParserBuilder applyAdapter ( JsonHandlerBase a ) { boolean applied = false ; if ( a instanceof ObjectStartHandler ) { objectStartHandler ( ( ObjectStartHandler ) a ) ; applied = true ; } if ( a instanceof ObjectEndHandler ) { objectEndHandler ( ( ObjectEndHandler ) a ) ; applied = true ; } if ( a instanceof ArrayStartHandler ) { arrayStartHandler ( ( ArrayStartHandler ) a ) ; applied = true ; } if ( a instanceof ArrayEndHandler ) { arrayEndHandler ( ( ArrayEndHandler ) a ) ; applied = true ; } if ( a instanceof BooleanHandler ) { booleanHandler ( ( BooleanHandler ) a ) ; applied = true ; } if ( a instanceof NullHandler ) { nullHandler ( ( NullHandler ) a ) ; applied = true ; } if ( a instanceof StringValueHandler ) { stringValueHandler ( ( StringValueHandler ) a ) ; applied = true ; } if ( a instanceof ObjectKeyHandler ) { objectKeyHandler ( ( ObjectKeyHandler ) a ) ; applied = true ; } if ( a instanceof NumberHandler ) { numberHandler ( ( NumberHandler ) a ) ; applied = true ; } if ( a instanceof IntegerHandler ) { integerHandler ( ( IntegerHandler ) a ) ; applied = true ; } if ( a instanceof FloatingHandler ) { floatingHandler ( ( FloatingHandler ) a ) ; applied = true ; } if ( a instanceof ResetHook ) { resetHook ( ( ResetHook ) a ) ; applied = true ; } if ( ! applied ) throw new IllegalArgumentException ( a + " isn't an instance of any handler interface" ) ; return this ; }
Convenient method to apply the adapter which implements several handler interfaces in one call .
19,302
public static String camelCase ( String prefix , String name ) { return Strings . camelCase ( prefix , name ) ; }
Format a prefixed name as camelCase . The prefix is kept verbatim while tha name is split on _ chars and joined with each part capitalized .
19,303
public static String macroCase ( String name ) { return Strings . c_case ( name ) . toUpperCase ( Locale . US ) ; }
Format a prefixed name as MACRO_CASE .
19,304
public static void ensure ( boolean condition , String message , Object ... args ) { if ( ! condition ) { throw new EnsureViolation ( format ( message , args ) ) ; } }
Postcondition that supplier are supposed to ensure . Violations are considered to be a programming error on the suppliers part .
19,305
public void reset ( ) { lexer . reset ( ) ; stateStack . clear ( ) ; stateStack . push ( START ) ; parseError = null ; if ( resetHook != null ) resetHook . onReset ( ) ; }
Resets the parser to clear just like after construction state .
19,306
public boolean finish ( ) { if ( ! parse ( finishSpace ( ) ) ) return false ; switch ( stateStack . current ( ) ) { case PARSE_ERROR : case LEXICAL_ERROR : case HANDLER_CANCEL : case HANDLER_EXCEPTION : throw new AssertionError ( "exception should be thrown directly from parse()" ) ; case GOT_VALUE : case PARSE_COMPLETE : return true ; default : return flags . contains ( ALLOW_PARTIAL_VALUES ) || parseError ( "premature EOF" ) ; } }
Processes the last token .
19,307
public static String asString ( byte id ) { switch ( id ) { case STOP : return "stop(0)" ; case VOID : return "void(1)" ; case BOOL : return "bool(2)" ; case BYTE : return "byte(3)" ; case DOUBLE : return "double(4)" ; case I16 : return "i16(6)" ; case I32 : return "i32(8)" ; case I64 : return "i64(10)" ; case STRING : return "string(11)" ; case STRUCT : return "struct(12)" ; case MAP : return "map(13)" ; case SET : return "set(14)" ; case LIST : return "list(15)" ; default : return "unknown(" + id + ")" ; } }
Readable string value for a type ID .
19,308
public MediaItem getMediaItem ( String id ) { DailyMotionUrl url = new DailyMotionUrl ( requestPrefix + id ) ; HttpRequest request ; try { request = requestFactory . buildGetRequest ( url ) ; DailyMotionVideo video = request . execute ( ) . parseAs ( DailyMotionVideo . class ) ; if ( video != null ) { MediaItem mediaItem = new DailyMotionMediaItem ( video ) ; return mediaItem ; } } catch ( Exception e ) { } return null ; }
Returns the retrieved media item
19,309
String toAbsoluteFormat ( long time ) { calendar . setTime ( new Date ( time ) ) ; long hours = calendar . get ( Calendar . HOUR_OF_DAY ) ; StringBuffer buffer = new StringBuffer ( ) ; if ( hours < 10 ) { buffer . append ( '0' ) ; } buffer . append ( hours ) ; buffer . append ( ':' ) ; long minutes = calendar . get ( Calendar . MINUTE ) ; if ( minutes < 10 ) { buffer . append ( '0' ) ; } buffer . append ( minutes ) ; buffer . append ( ':' ) ; long seconds = calendar . get ( Calendar . SECOND ) ; if ( seconds < 10 ) { buffer . append ( '0' ) ; } buffer . append ( seconds ) ; buffer . append ( ',' ) ; long milliseconds = calendar . get ( Calendar . MILLISECOND ) ; if ( milliseconds < 10 ) { buffer . append ( '0' ) ; } buffer . append ( milliseconds ) ; return buffer . toString ( ) ; }
Format as an absolute date time format that is
19,310
public static UserPermissionViewModel newViewModel ( final ApplicationFeatureId featureId , final ApplicationUser user , final ApplicationPermissionValueSet . Evaluation viewingEvaluation , final ApplicationPermissionValueSet . Evaluation changingEvaluation , final DomainObjectContainer container ) { return container . newViewModelInstance ( UserPermissionViewModel . class , asEncodedString ( featureId , user . getUsername ( ) , viewingEvaluation , changingEvaluation ) ) ; }
region > constructors factory methods
19,311
private List < AgigaCoref > parseCorefs ( VTDNav vn ) throws PilotException , NavException { require ( vn . matchElement ( AgigaConstants . DOC ) ) ; List < AgigaCoref > agigaCorefs = new ArrayList < AgigaCoref > ( ) ; if ( ! vn . toElement ( VTDNav . FIRST_CHILD , AgigaConstants . COREFERENCES ) ) { log . finer ( "No corefs found" ) ; return agigaCorefs ; } AutoPilot corefAp = new AutoPilot ( vn ) ; corefAp . selectElement ( AgigaConstants . COREFERENCE ) ; while ( corefAp . iterate ( ) ) { AgigaCoref coref = parseCoref ( vn . cloneNav ( ) ) ; agigaCorefs . add ( coref ) ; } return agigaCorefs ; }
Assumes the position of vn is at a DOC tag
19,312
private String parseHeadline ( VTDNav vn ) throws NavException { require ( vn . matchElement ( AgigaConstants . DOC ) ) ; if ( ! vn . toElement ( VTDNav . FIRST_CHILD , AgigaConstants . HEADLINE ) || vn . getText ( ) == - 1 ) { log . finer ( "No headline found" ) ; return null ; } return vn . toString ( vn . getText ( ) ) . trim ( ) ; }
Parses out the HEADLINE element which is a parse of the dateline if it exists .
19,313
public Level getEffectiveLevel ( ) { Level effectiveLevel = level ; if ( effectiveLevel == null && ! name . equals ( "" ) ) { if ( commonLoggerRepository == null ) { throw new IllegalStateException ( "CommonLoggerRepository has not been set" ) ; } else { effectiveLevel = commonLoggerRepository . getEffectiveLevel ( name ) ; } } return effectiveLevel ; }
Get the effective log level . If we have a hierarchy of loggers this is searched to get the effective level .
19,314
public void setClientID ( String clientID ) { if ( clientID == null || clientID . isEmpty ( ) ) { this . clientID = DEFAULT_CLIENT_ID ; return ; } this . clientID = clientID ; }
Set the client ID .
19,315
synchronized public void addAppender ( Appender appender ) throws IllegalArgumentException { if ( appender == null ) { throw new IllegalArgumentException ( "Appender not allowed to be null" ) ; } for ( Appender p : appenderList ) { if ( p . getClass ( ) == appender . getClass ( ) ) return ; } appenderList . add ( appender ) ; }
Add the specified appender to the output appenders .
19,316
public void removeAppender ( Appender appender ) throws IllegalArgumentException { if ( appender == null ) { throw new IllegalArgumentException ( "The appender must not be null." ) ; } if ( appender . isLogOpen ( ) ) { try { appender . close ( ) ; } catch ( IOException e ) { Log . e ( TAG , "Failed to close appender. " + e ) ; } } appenderList . remove ( appender ) ; }
Remove the specified appender from the appender list .
19,317
public void removeAllAppenders ( ) { ListIterator < Appender > ite = appenderList . listIterator ( ) ; while ( ite . hasNext ( ) ) { Appender appender = ite . next ( ) ; if ( appender != null && appender . isLogOpen ( ) ) { try { appender . close ( ) ; } catch ( IOException e ) { Log . e ( TAG , "Failed to close appender. " + e ) ; } } } appenderList . clear ( ) ; }
Remove all the appenders .
19,318
public Appender getAppender ( int index ) { if ( index < 0 || index >= appenderList . size ( ) ) return null ; return appenderList . get ( index ) ; }
Get the specified appender starting at index = 0 .
19,319
public void log ( Level level , Object message ) throws IllegalArgumentException { log ( level , message , null ) ; }
Log the message at the specified level .
19,320
public void log ( Level level , Object message , Throwable t ) throws IllegalArgumentException { if ( level == null ) { throw new IllegalArgumentException ( "The level must not be null." ) ; } if ( getEffectiveLevel ( ) . toInt ( ) <= level . toInt ( ) && level . toInt ( ) > Level . OFF_INT ) { if ( firstLogEvent == true ) { addDefaultAppender ( ) ; try { open ( ) ; } catch ( IOException e ) { Log . e ( TAG , "Failed to open the log. " + e ) ; } stopWatch . start ( ) ; firstLogEvent = false ; } ListIterator < Appender > ite = appenderList . listIterator ( ) ; while ( ite . hasNext ( ) ) { Appender appender = ite . next ( ) ; if ( appender != null ) appender . doLog ( clientID , name , stopWatch . getCurrentTime ( ) , level , message , t ) ; } } }
Log the message and the Throwable object at the specified level .
19,321
public synchronized void resetLogger ( ) { Logger . appenderList . clear ( ) ; Logger . stopWatch . stop ( ) ; Logger . stopWatch . reset ( ) ; Logger . firstLogEvent = true ; }
Reset the Logger i . e . remove all appenders and set the log level to the default level .
19,322
void open ( ) throws IOException { ListIterator < Appender > ite = appenderList . listIterator ( ) ; while ( ite . hasNext ( ) ) { Appender p = ite . next ( ) ; if ( p != null ) p . open ( ) ; } }
Open the log . The logging is now turned on .
19,323
public void close ( ) throws IOException { ListIterator < Appender > ite = appenderList . listIterator ( ) ; while ( ite . hasNext ( ) ) { Appender p = ite . next ( ) ; if ( p != null ) p . close ( ) ; } stopWatch . stop ( ) ; Logger . firstLogEvent = true ; }
Close the log . From this point on no logging is done .
19,324
private void init ( SSLContextImpl ctx ) { if ( debug != null && Debug . isOn ( "ssl" ) ) { System . out . println ( "Using SSLEngineImpl." ) ; } sslContext = ctx ; sess = SSLSessionImpl . nullSession ; handshakeSession = null ; roleIsServer = true ; connectionState = cs_START ; receivedCCS = false ; readCipher = CipherBox . NULL ; readMAC = MAC . NULL ; writeCipher = CipherBox . NULL ; writeMAC = MAC . NULL ; secureRenegotiation = false ; clientVerifyData = new byte [ 0 ] ; serverVerifyData = new byte [ 0 ] ; enabledCipherSuites = sslContext . getDefaultCipherSuiteList ( roleIsServer ) ; enabledProtocols = sslContext . getDefaultProtocolList ( roleIsServer ) ; wrapLock = new Object ( ) ; unwrapLock = new Object ( ) ; writeLock = new Object ( ) ; acc = AccessController . getContext ( ) ; outputRecord = new EngineOutputRecord ( Record . ct_application_data , this ) ; inputRecord = new EngineInputRecord ( this ) ; inputRecord . enableFormatChecks ( ) ; writer = new EngineWriter ( ) ; }
Initializes the Engine
19,325
public SSLEngineResult unwrap ( ByteBuffer netData , ByteBuffer [ ] appData , int offset , int length ) throws SSLException { EngineArgs ea = new EngineArgs ( netData , appData , offset , length ) ; try { synchronized ( unwrapLock ) { return readNetRecord ( ea ) ; } } catch ( Exception e ) { fatal ( Alerts . alert_internal_error , "problem unwrapping net record" , e ) ; return null ; } finally { ea . resetLim ( ) ; } }
Unwraps a buffer . Does a variety of checks before grabbing the unwrapLock which blocks multiple unwraps from occuring .
19,326
public SSLEngineResult wrap ( ByteBuffer [ ] appData , int offset , int length , ByteBuffer netData ) throws SSLException { EngineArgs ea = new EngineArgs ( appData , offset , length , netData ) ; if ( netData . remaining ( ) < outputRecord . maxRecordSize ) { return new SSLEngineResult ( Status . BUFFER_OVERFLOW , getHSStatus ( null ) , 0 , 0 ) ; } try { synchronized ( wrapLock ) { return writeAppRecord ( ea ) ; } } catch ( Exception e ) { ea . resetPos ( ) ; fatal ( Alerts . alert_internal_error , "problem wrapping app data" , e ) ; return null ; } finally { ea . resetLim ( ) ; } }
Wraps a buffer . Does a variety of checks before grabbing the wrapLock which blocks multiple wraps from occuring .
19,327
private boolean checkSequenceNumber ( MAC mac , byte type ) throws IOException { if ( connectionState >= cs_ERROR || mac == MAC . NULL ) { return false ; } if ( mac . seqNumOverflow ( ) ) { if ( debug != null && Debug . isOn ( "ssl" ) ) { System . out . println ( threadName ( ) + ", sequence number extremely close to overflow " + "(2^64-1 packets). Closing connection." ) ; } fatal ( Alerts . alert_handshake_failure , "sequence number overflow" ) ; return true ; } if ( ( type != Record . ct_handshake ) && mac . seqNumIsHuge ( ) ) { if ( debug != null && Debug . isOn ( "ssl" ) ) { System . out . println ( threadName ( ) + ", request renegotiation " + "to avoid sequence number overflow" ) ; } beginHandshake ( ) ; return true ; } return false ; }
Check the sequence number state
19,328
synchronized public void setEnableSessionCreation ( boolean flag ) { enableSessionCreation = flag ; if ( ( handshaker != null ) && ! handshaker . activated ( ) ) { handshaker . setEnableSessionCreation ( enableSessionCreation ) ; } }
Controls whether new connections may cause creation of new SSL sessions .
19,329
synchronized public void setUseClientMode ( boolean flag ) { switch ( connectionState ) { case cs_START : if ( roleIsServer != ( ! flag ) && sslContext . isDefaultProtocolList ( enabledProtocols ) ) { enabledProtocols = sslContext . getDefaultProtocolList ( ! flag ) ; } roleIsServer = ! flag ; serverModeSet = true ; break ; case cs_HANDSHAKE : assert ( handshaker != null ) ; if ( ! handshaker . activated ( ) ) { if ( roleIsServer != ( ! flag ) && sslContext . isDefaultProtocolList ( enabledProtocols ) ) { enabledProtocols = sslContext . getDefaultProtocolList ( ! flag ) ; } roleIsServer = ! flag ; connectionState = cs_START ; initHandshaker ( ) ; break ; } default : if ( debug != null && Debug . isOn ( "ssl" ) ) { System . out . println ( threadName ( ) + ", setUseClientMode() invoked in state = " + connectionState ) ; } throw new IllegalArgumentException ( "Cannot change mode after SSL traffic has started" ) ; } }
Sets the flag controlling whether the engine is in SSL client or server mode . Must be called before any SSL traffic has started .
19,330
synchronized public SSLParameters getSSLParameters ( ) { SSLParameters params = super . getSSLParameters ( ) ; params . setEndpointIdentificationAlgorithm ( identificationProtocol ) ; params . setAlgorithmConstraints ( algorithmConstraints ) ; return params ; }
Returns the SSLParameters in effect for this SSLEngine .
19,331
synchronized public void setSSLParameters ( SSLParameters params ) { super . setSSLParameters ( params ) ; identificationProtocol = params . getEndpointIdentificationAlgorithm ( ) ; algorithmConstraints = params . getAlgorithmConstraints ( ) ; if ( ( handshaker != null ) && ! handshaker . started ( ) ) { handshaker . setIdentificationProtocol ( identificationProtocol ) ; handshaker . setAlgorithmConstraints ( algorithmConstraints ) ; } }
Applies SSLParameters to this engine .
19,332
public Optional < JField > exceptionMessageField ( ) { String fieldName = getExceptionMessageFieldName ( ) ; return numericalOrderFields ( ) . stream ( ) . filter ( f -> f . name ( ) . equals ( fieldName ) && f . type ( ) == PType . STRING ) . findFirst ( ) ; }
If the message has a string field named message which can be used as the message for exceptions .
19,333
private String getAnnotationValue ( String annotation ) { if ( descriptor instanceof CAnnotatedDescriptor ) { if ( ( ( CAnnotatedDescriptor ) descriptor ) . hasAnnotation ( annotation ) ) { return ( ( CAnnotatedDescriptor ) descriptor ) . getAnnotationValue ( annotation ) ; } } return null ; }
Get the annotation value .
19,334
public List < String > getRoleNames ( final Optional < Subject > subjectOption ) { final List < String > roleNames = new ArrayList < String > ( ) ; subjectOption . ifPresent ( subject -> { final List < ? extends Role > roles = subject . getRoles ( ) ; if ( roles != null ) { for ( Role role : roles ) { if ( role != null ) { roleNames . add ( role . getName ( ) ) ; } } } } ) ; return roleNames ; }
Gets the role name of each role held .
19,335
public void onDestroyView ( ) { mHandler . removeCallbacks ( mRequestFocus ) ; mList = null ; mListShown = false ; mEmptyView = mProgressContainer = mListContainer = null ; mStandardEmptyView = null ; super . onDestroyView ( ) ; }
Detach from list view .
19,336
public void setListAdapter ( ListAdapter adapter ) { boolean hadAdapter = mAdapter != null ; mAdapter = adapter ; if ( mList != null ) { mList . setAdapter ( adapter ) ; if ( ! mListShown && ! hadAdapter ) { setListShown ( true , getView ( ) . getWindowToken ( ) != null ) ; } } }
Provide the cursor for the list view .
19,337
public void setEmptyText ( CharSequence text ) { ensureList ( ) ; if ( mStandardEmptyView == null ) { throw new IllegalStateException ( "Can't be used with a custom content view" ) ; } mStandardEmptyView . setText ( text ) ; if ( mEmptyText == null ) { mList . setEmptyView ( mStandardEmptyView ) ; } mEmptyText = text ; }
The default content for a ListFragment has a TextView that can be shown when the list is empty . If you would like to have it shown call this method to supply the text it should use .
19,338
private void appendCreateMethod ( List < CStructDescriptor > messages ) { writer . appendln ( "@Override" ) . formatln ( "public %s create(int classId) {" , Portable . class . getName ( ) ) . begin ( ) . appendln ( "switch(classId) {" ) . begin ( ) ; for ( CStructDescriptor message : messages ) { writer . formatln ( "case %s: {" , getHazelcastClassId ( message . getName ( ) ) ) . begin ( ) . formatln ( "return new %s.%s();" , message . getName ( ) , HazelcastPortableMessageFormatter . WRAPPER_CLASS_NAME ) . end ( ) . appendln ( "}" ) ; } writer . appendln ( "default: {" ) . begin ( ) . appendln ( "return null;" ) . end ( ) . appendln ( "}" ) . end ( ) ; writer . appendln ( "}" ) . end ( ) . appendln ( "}" ) . newline ( ) ; }
Method to write the create method from implemented PortableFactory
19,339
private void appendPopulateMethod ( List < CStructDescriptor > messages ) { writer . formatln ( "public static final %s populateConfig(%s %s, int %s) {" , Config . class . getName ( ) , Config . class . getName ( ) , CONFIG , PORTABLE_VERSION ) . begin ( ) . formatln ( "%s %s = new %s();" , FACTORY_IMPL , INSTANCE , FACTORY_IMPL ) . formatln ( "%s.getSerializationConfig().addPortableFactory(%s, %s);" , CONFIG , FACTORY_ID , INSTANCE ) . formatln ( "%s.getSerializationConfig().setPortableVersion(%s);" , CONFIG , PORTABLE_VERSION ) . appendln ( ) . formatln ( "%s.getSerializationConfig()" , CONFIG ) . begin ( ) . begin ( ) ; for ( CStructDescriptor struct : messages ) { writer . formatln ( ".addClassDefinition(%s.%s(%s))" , INSTANCE , camelCase ( "get" , struct . getName ( ) + "Definition" ) , PORTABLE_VERSION ) ; } writer . append ( ";" ) . end ( ) . end ( ) . formatln ( "return %s;" , CONFIG ) . end ( ) . appendln ( "}" ) . newline ( ) ; }
Method to append populate methods for the Hazelcast Config .
19,340
private void appendCollectionTypeField ( JField field , PDescriptor descriptor ) { switch ( descriptor . getType ( ) ) { case BYTE : case BINARY : writer . formatln ( ".addByteArrayField(\"%s\")" , field . name ( ) ) ; break ; case BOOL : writer . formatln ( ".addBooleanArrayField(\"%s\")" , field . name ( ) ) ; break ; case DOUBLE : writer . formatln ( ".addDoubleArrayField(\"%s\")" , field . name ( ) ) ; break ; case I16 : writer . formatln ( ".addShortArrayField(\"%s\")" , field . name ( ) ) ; break ; case I32 : case ENUM : writer . formatln ( ".addIntArrayField(\"%s\")" , field . name ( ) ) ; break ; case I64 : writer . formatln ( ".addLongArrayField(\"%s\")" , field . name ( ) ) ; break ; case STRING : writer . formatln ( ".addUTFArrayField(\"%s\")" , field . name ( ) ) ; break ; case MESSAGE : writer . formatln ( ".addPortableArrayField(\"%s\", %s(%s))" , field . name ( ) , camelCase ( "get" , descriptor . getName ( ) + "Definition" ) , PORTABLE_VERSION ) ; break ; default : throw new GeneratorException ( "Not implemented appendCollectionTypeField for list with type: " + descriptor . getType ( ) + " in " + this . getClass ( ) . getSimpleName ( ) ) ; } }
Append a specific list type field to the definition .
19,341
protected boolean objectVisibleToUser ( String objectTenancyPath , String userTenancyPath ) { return objectTenancyPath . startsWith ( userTenancyPath ) || userTenancyPath . startsWith ( objectTenancyPath ) ; }
Protected visibility so can be overridden if required eg using wildcard matches .
19,342
protected Throwable getResponseException ( Throwable e ) { if ( ExecutionException . class . isAssignableFrom ( e . getClass ( ) ) ) { return getResponseException ( e . getCause ( ) ) ; } return e ; }
Get the exception to ge handled on failed requests .
19,343
public static Key JOIN_PROMPT ( String value , Voice voice ) { Map < String , String > map = new HashMap < String , String > ( ) ; map . put ( "value" , value ) ; if ( voice != null ) { map . put ( "voice" , voice . toString ( ) ) ; } return createKey ( "joinPrompt" , map ) ; }
Defines a prompt that plays to all participants of a conference when someone joins the conference . It s possible to define either TTS or an audio URL using additional attributes value and voice
19,344
public List < ApplicationTenancy > findByNameOrPathMatchingCached ( final String search ) { return queryResultsCache . execute ( new Callable < List < ApplicationTenancy > > ( ) { public List < ApplicationTenancy > call ( ) throws Exception { return findByNameOrPathMatching ( search ) ; } } , ApplicationTenancyRepository . class , "findByNameOrPathMatchingCached" , search ) ; }
region > findByNameOrPathMatching
19,345
public ApplicationTenancy findByPathCached ( final String path ) { return queryResultsCache . execute ( new Callable < ApplicationTenancy > ( ) { public ApplicationTenancy call ( ) throws Exception { return findByPath ( path ) ; } } , ApplicationTenancyRepository . class , "findByPathCached" , path ) ; }
region > findByPath
19,346
public ApplicationTenancy newTenancy ( final String name , final String path , final ApplicationTenancy parent ) { ApplicationTenancy tenancy = findByPath ( path ) ; if ( tenancy == null ) { tenancy = getApplicationTenancyFactory ( ) . newApplicationTenancy ( ) ; tenancy . setName ( name ) ; tenancy . setPath ( path ) ; tenancy . setParent ( parent ) ; container . persist ( tenancy ) ; } return tenancy ; }
region > newTenancy
19,347
public List < ApplicationTenancy > allTenancies ( ) { return queryResultsCache . execute ( new Callable < List < ApplicationTenancy > > ( ) { public List < ApplicationTenancy > call ( ) throws Exception { return allTenanciesNoCache ( ) ; } } , ApplicationTenancyRepository . class , "allTenancies" ) ; }
region > allTenancies
19,348
public static < T extends Throwable > Matcher < T > isThrowable ( Class < ? > type ) { return IsThrowable . isThrowable ( type ) ; }
Throwable matcher with only a type argument
19,349
public static < E extends Throwable > void check ( boolean condition , E throwable ) throws E { checkArgument ( throwable != null , "Expected non-null reference" ) ; if ( ! condition ) { throw throwable ; } }
Performs check of the condition .
19,350
public RecursiveTypeRegistry getRegistryForProgramName ( String programName ) { if ( localProgramContext . equals ( programName ) ) return this ; for ( RecursiveTypeRegistry registry : includes . values ( ) ) { if ( registry . getLocalProgramContext ( ) . equals ( programName ) ) { return registry ; } } for ( RecursiveTypeRegistry registry : includes . values ( ) ) { RecursiveTypeRegistry tmp = registry . getRegistryForProgramName ( programName ) ; if ( tmp != null ) { return tmp ; } } return null ; }
Get the registry to be used for the specific program . Search through all the included registries to find the best one .
19,351
public void registerInclude ( String programName , RecursiveTypeRegistry registry ) { if ( registry == this ) { throw new IllegalArgumentException ( "Registering include back to itself: " + programName ) ; } if ( includes . containsKey ( programName ) ) { return ; } includes . put ( programName , registry ) ; }
Register a recursive included registry .
19,352
public static void sleepFor ( long timeout , TimeUnit unit ) { try { unit . sleep ( timeout ) ; } catch ( InterruptedException e ) { Thread . currentThread ( ) . interrupt ( ) ; } }
Interruptible sleep of the current thread
19,353
public static Optional < InterruptedException > uninterruptibleSleepFor ( long timeout , TimeUnit unit ) { try { unit . sleep ( timeout ) ; return Optional . absent ( ) ; } catch ( InterruptedException e ) { return Optional . of ( e ) ; } }
Uninterruptible sleep of the current thread
19,354
public String getContentId ( ) { String [ ] values = getMimeHeader ( "Content-ID" ) ; if ( values != null && values . length > 0 ) return values [ 0 ] ; return null ; }
Gets the value of the MIME header whose name is Content - ID .
19,355
public String getContentType ( ) { String [ ] values = getMimeHeader ( "Content-Type" ) ; if ( values != null && values . length > 0 ) return values [ 0 ] ; return null ; }
Gets the value of the MIME header whose name is Content - Type .
19,356
protected String finalTypename ( String typeName , String programContext ) { String qualifiedName = qualifiedTypenameInternal ( typeName , programContext ) ; if ( typedefs . containsKey ( qualifiedName ) ) { String resolved = typedefs . get ( qualifiedName ) ; return finalTypename ( resolved , programContext ) ; } return qualifiedName ; }
Get the final typename of the given identifier within the context .
19,357
protected static String qualifiedNameFromIdAndContext ( String name , String context ) { if ( ! name . contains ( "." ) ) { return context + "." + name ; } return name ; }
Make a qualified type name from a name identifier string and the program context .
19,358
private void registerListType ( PContainer containerType ) { PDescriptor itemType = containerType . itemDescriptor ( ) ; if ( itemType . getType ( ) == PType . MAP || itemType . getType ( ) == PType . LIST || itemType . getType ( ) == PType . SET ) { registerListType ( ( PContainer ) itemType ) ; } else if ( itemType . getType ( ) == PType . ENUM || itemType . getType ( ) == PType . MESSAGE ) { registerRecursively ( ( PDeclaredDescriptor < ? > ) itemType ) ; } if ( containerType instanceof PMap ) { PDescriptor keyType = ( ( PMap ) containerType ) . keyDescriptor ( ) ; if ( keyType . getType ( ) == PType . ENUM || keyType . getType ( ) == PType . MESSAGE ) { registerRecursively ( ( PDeclaredDescriptor < ? > ) keyType ) ; } } }
Register a list type part of recursive registering .
19,359
protected static < Message extends PMessage < Message , CField > > String asString ( Message message ) { ByteArrayOutputStream baos = new ByteArrayOutputStream ( ) ; PRETTY_SERIALIZER . serialize ( baos , message ) ; return new String ( baos . toByteArray ( ) , UTF_8 ) ; }
Prints a jsonCompact string representation of the message .
19,360
@ SuppressWarnings ( "unchecked" ) private static < T extends Comparable < T > > int compare ( T o1 , T o2 ) { if ( o1 instanceof PMessage && o2 instanceof PMessage ) { return compareMessages ( ( PMessage ) o1 , ( PMessage ) o2 ) ; } return o1 . compareTo ( o2 ) ; }
Compare two values to each other .
19,361
public static < T , E extends RuntimeException > ExceptionSupplier < T , E > throwA ( E exception ) { return new ExceptionSupplier < > ( exception ) ; }
Factory method for usage during variable or field initialisation .
19,362
public static < T , E extends RuntimeException > ExceptionSupplier < T , E > throwA ( @ SuppressWarnings ( "UnusedParameters" ) Class < T > type , E exception ) { return new ExceptionSupplier < > ( exception ) ; }
Factory method for usage inside a method call
19,363
private < Message extends PMessage < Message , Field > , Field extends PField > Message parseMessage ( ThriftTokenizer tokenizer , PMessageDescriptor < Message , Field > type ) throws IOException { PMessageBuilder < Message , Field > builder = type . builder ( ) ; if ( tokenizer . peek ( "checking for empty" ) . isSymbol ( Token . kMessageEnd ) ) { tokenizer . next ( ) ; return builder . build ( ) ; } while ( true ) { Token token = tokenizer . expect ( "message field name" , t -> t . isStringLiteral ( ) || t . strEquals ( ThriftTokenizer . kBlockCommentStart ) || t . strEquals ( ThriftTokenizer . kLineCommentStart ) ) ; if ( token . strEquals ( ThriftTokenizer . kLineCommentStart ) ) { int c ; while ( ( c = tokenizer . read ( ) ) >= 0 ) { if ( c == '\n' ) break ; } continue ; } else if ( token . strEquals ( ThriftTokenizer . kBlockCommentStart ) ) { int c ; while ( ( c = tokenizer . read ( ) ) >= 0 ) { if ( c == '*' ) { c = tokenizer . read ( ) ; if ( c == '/' ) { break ; } } } continue ; } Field field = type . findFieldByName ( token . decodeLiteral ( true ) ) ; if ( field == null ) { throw tokenizer . failure ( token , "No such field in " + type . getQualifiedName ( ) + ": " + token . decodeLiteral ( true ) ) ; } tokenizer . expectSymbol ( "message key-value sep" , Token . kKeyValueSep ) ; builder . set ( field . getId ( ) , parseTypedValue ( tokenizer . expect ( "parsing field value" ) , tokenizer , field . getDescriptor ( ) , false ) ) ; token = tokenizer . peek ( "optional line sep or message end" ) ; if ( token . isSymbol ( Token . kLineSep1 ) || token . isSymbol ( Token . kLineSep2 ) ) { tokenizer . next ( ) ; token = tokenizer . peek ( "optional message end" ) ; } if ( token . isSymbol ( Token . kMessageEnd ) ) { tokenizer . next ( ) ; break ; } } return builder . build ( ) ; }
Parse JSON object as a message .
19,364
public List < FixtureResult > runFixtureScript ( final FixtureScript fixtureScript , @ Parameter ( optionality = Optionality . OPTIONAL ) @ ParameterLayout ( named = "Parameters" , describedAs = "Script-specific parameters (if any). The format depends on the script implementation (eg key=value, CSV, JSON, XML etc)" , multiLine = 10 ) final String parameters ) { return super . runFixtureScript ( fixtureScript , parameters ) ; }
region > runFixtureScript
19,365
@ Action ( semantics = SemanticsOf . NON_IDEMPOTENT , restrictTo = RestrictTo . PROTOTYPING ) @ MemberOrder ( sequence = "20" ) public Object installFixturesAndReturnFirstRole ( ) { final List < FixtureResult > fixtureResultList = findFixtureScriptFor ( SecurityModuleAppSetUp . class ) . run ( null ) ; for ( FixtureResult fixtureResult : fixtureResultList ) { final Object object = fixtureResult . getObject ( ) ; if ( object instanceof ApplicationRole ) { return object ; } } getContainer ( ) . warnUser ( "No rules found in fixture; returning all results" ) ; return fixtureResultList ; }
region > installFixturesAndReturnFirstRole
19,366
public JServiceMethod [ ] methods ( ) { List < CServiceMethod > methods = new ArrayList < > ( service . getMethodsIncludingExtended ( ) ) ; CServiceMethod [ ] ma = methods . toArray ( new CServiceMethod [ methods . size ( ) ] ) ; JServiceMethod [ ] ret = new JServiceMethod [ ma . length ] ; for ( int i = 0 ; i < methods . size ( ) ; ++ i ) { ret [ i ] = new JServiceMethod ( service , ma [ i ] , helper ) ; } return ret ; }
All methods that apply for the service .
19,367
public static < Message extends PMessage < Message , Field > , Field extends PField > Message parseDebugString ( String string , PMessageDescriptor < Message , Field > descriptor ) { try { ByteArrayInputStream bais = new ByteArrayInputStream ( string . getBytes ( UTF_8 ) ) ; return DEBUG_STRING_SERIALIZER . deserialize ( bais , descriptor ) ; } catch ( IOException e ) { throw new UncheckedIOException ( e . getMessage ( ) , e ) ; } }
Parses a pretty formatted string and makes exceptions unchecked .
19,368
@ SuppressWarnings ( "unchecked" ) public static < T > Optional < T > optionalInMessage ( PMessage message , PField ... fields ) { if ( fields == null || fields . length == 0 ) { throw new IllegalArgumentException ( "No fields arguments." ) ; } PField field = fields [ 0 ] ; if ( ! message . has ( field . getId ( ) ) ) { return Optional . empty ( ) ; } if ( fields . length > 1 ) { if ( field . getType ( ) != PType . MESSAGE ) { throw new IllegalArgumentException ( "Field " + field . getName ( ) + " is not a message." ) ; } return optionalInMessage ( ( PMessage ) message . get ( field ) , Arrays . copyOfRange ( fields , 1 , fields . length ) ) ; } else { return Optional . of ( ( T ) message . get ( field . getId ( ) ) ) ; } }
Get a field value from a message with optional chaining . If the field is not set or any message in the chain leading up to the last message is missing it will return an empty optional . Otherwise the leaf field value .
19,369
public java . util . Optional < String > optionalMessage ( ) { return java . util . Optional . ofNullable ( mMessage ) ; }
Exception message .
19,370
public java . util . Optional < net . morimekta . providence . PApplicationExceptionType > optionalId ( ) { return java . util . Optional . ofNullable ( mId ) ; }
The application exception type .
19,371
public Collection < CServiceMethod > getMethodsIncludingExtended ( ) { CService extended = getExtendsService ( ) ; if ( extended == null ) { return getMethods ( ) ; } List < CServiceMethod > out = new ArrayList < > ( ) ; out . addAll ( extended . getMethodsIncludingExtended ( ) ) ; out . addAll ( getMethods ( ) ) ; return ImmutableList . copyOf ( out ) ; }
Get all methods including methods declared in extended services .
19,372
public static TestRule ignoreIfNotUnix ( ) { return ( base , description ) -> new Statement ( ) { public void evaluate ( ) throws Throwable { assumeIsUnix ( ) ; base . evaluate ( ) ; } } ; }
Require Unix like operating system .
19,373
private void appendPrimitive ( JsonWriter writer , Object primitive ) throws SerializerException { if ( primitive instanceof PEnumValue ) { if ( IdType . ID . equals ( enumValueType ) ) { writer . value ( ( ( PEnumValue < ? > ) primitive ) . asInteger ( ) ) ; } else { writer . valueUnescaped ( primitive . toString ( ) ) ; } } else if ( primitive instanceof Boolean ) { writer . value ( ( ( Boolean ) primitive ) ) ; } else if ( primitive instanceof Byte ) { writer . value ( ( ( Byte ) primitive ) ) ; } else if ( primitive instanceof Short ) { writer . value ( ( ( Short ) primitive ) ) ; } else if ( primitive instanceof Integer ) { writer . value ( ( ( Integer ) primitive ) ) ; } else if ( primitive instanceof Long ) { writer . value ( ( ( Long ) primitive ) ) ; } else if ( primitive instanceof Double ) { writer . value ( ( ( Double ) primitive ) ) ; } else if ( primitive instanceof CharSequence ) { writer . value ( ( String ) primitive ) ; } else if ( primitive instanceof Binary ) { writer . value ( ( Binary ) primitive ) ; } else { throw new SerializerException ( "illegal primitive type class " + primitive . getClass ( ) . getSimpleName ( ) ) ; } }
Append a primitive value to json struct .
19,374
String getTimeFileName ( ) { SimpleDateFormat dateFormat = new SimpleDateFormat ( wraper . formatter ) ; return dateFormat . format ( Calendar . getInstance ( ) . getTime ( ) ) ; }
get in parameters date formatted result without file extension .
19,375
public static < Message extends PMessage < Message , Field > , Field extends PField > Stream < Message > stream ( InputStream in , Serializer serializer , PMessageDescriptor < Message , Field > descriptor ) { return StreamSupport . stream ( new MessageSpliterator < > ( in , serializer , descriptor ) , false ) ; }
Read a input stream containing entries of a given type .
19,376
public static < T , R > Function < T , ListenableFuture < R > > futureWith ( final ListeningExecutorService executor , final Function < T , R > task , final FutureCallback < R > callback ) { checkArgument ( executor != null , "Expected non-null executor" ) ; checkArgument ( task != null , "Expected non-null task" ) ; checkArgument ( callback != null , "Expected non-null callback" ) ; return input -> { ListenableFuture < R > future = executor . submit ( ( ) -> task . apply ( input ) ) ; addCallback ( future , callback , executor ) ; return future ; } ; }
Function submits the task with given executor and callback
19,377
public < Message extends PMessage < Message , Field > , Field extends PField > void formatTo ( OutputStream out , Message message ) { IndentedPrintWriter builder = new IndentedPrintWriter ( out , indent , newline ) ; if ( message == null ) { builder . append ( null ) ; } else { builder . append ( message . descriptor ( ) . getQualifiedName ( ) ) . append ( space ) ; appendMessage ( builder , message ) ; } builder . flush ( ) ; }
Format message and write to the output stream .
19,378
public < Message extends PMessage < Message , Field > , Field extends PField > String format ( Message message ) { ByteArrayOutputStream out = new ByteArrayOutputStream ( ) ; formatTo ( out , message ) ; return new String ( out . toByteArray ( ) , StandardCharsets . UTF_8 ) ; }
Format message to a string .
19,379
public Key getKey ( String alias , String password ) { try { return keyStore . getKey ( alias , password . toCharArray ( ) ) ; } catch ( GeneralSecurityException e ) { throw new IllegalStateException ( e ) ; } }
Gets a key from the key store
19,380
public PrivateKey getPrivateKey ( String alias , String password ) { Key key = getKey ( alias , password ) ; if ( key instanceof PrivateKey ) { return ( PrivateKey ) key ; } else { throw new IllegalStateException ( format ( "Key with alias '%s' was not a private key, but was: %s" , alias , key . getClass ( ) . getSimpleName ( ) ) ) ; } }
Gets a asymmetric encryption private key from the key store
19,381
public SecretKey getSecretKey ( String alias , String password ) { Key key = getKey ( alias , password ) ; if ( key instanceof PrivateKey ) { return ( SecretKey ) key ; } else { throw new IllegalStateException ( format ( "Key with alias '%s' was not a secret key, but was: %s" , alias , key . getClass ( ) . getSimpleName ( ) ) ) ; } }
Gets a symmetric encryption secret key from the key store
19,382
public static String colorHeader ( ) { return Color . BOLD + HEADER_L1 + "\n" + new Color ( Color . YELLOW , Color . UNDERLINE ) + HEADER_L2 + " " + Color . CLEAR ; }
Header string that matches the asString output .
19,383
private void appendFactoryId ( JMessage < ? > message ) { writer . appendln ( "@Override" ) . appendln ( "public int getFactoryId() {" ) . begin ( ) . formatln ( "return %s.%s;" , getHazelcastFactory ( message . descriptor ( ) ) , HazelcastPortableProgramFormatter . FACTORY_ID ) . end ( ) . appendln ( "}" ) . newline ( ) ; }
Method to append get factory id from hazelcast_portable .
19,384
private void appendClassId ( JMessage < ? > message ) { writer . appendln ( "@Override" ) . appendln ( "public int getClassId() {" ) . begin ( ) . formatln ( "return %s.%s;" , getHazelcastFactory ( message . descriptor ( ) ) , getHazelcastClassId ( message . descriptor ( ) ) ) . end ( ) . appendln ( "}" ) . newline ( ) ; }
Method to append get class id from hazelcast_portable .
19,385
private void appendPortableWriter ( JMessage < ? > message ) { writer . appendln ( "@Override" ) . formatln ( "public void writePortable(%s %s) throws %s {" , PortableWriter . class . getName ( ) , PORTABLE_WRITER , IOException . class . getName ( ) ) . begin ( ) ; writer . appendln ( "int[] setFields = presentFields().stream()" ) . appendln ( " .mapToInt(_Field::getId)" ) . appendln ( " .toArray();" ) . appendln ( "portableWriter.writeIntArray(\"__fields__\", setFields);" ) ; for ( JField field : message . declaredOrderFields ( ) ) { if ( ! field . alwaysPresent ( ) ) { writer . formatln ( "if( %s() ) {" , field . isSet ( ) ) . begin ( ) ; } writePortableField ( field ) ; if ( ! field . alwaysPresent ( ) ) { writer . end ( ) . appendln ( "} else {" ) . begin ( ) ; writeDefaultPortableField ( field ) ; writer . end ( ) . appendln ( "}" ) ; } } writer . end ( ) . appendln ( "}" ) . newline ( ) ; }
Method to append writePortable from hazelcast_portable .
19,386
private void appendPortableReader ( JMessage < ? > message ) { writer . appendln ( "@Override" ) . formatln ( "public void readPortable(%s %s) throws %s {" , PortableReader . class . getName ( ) , PORTABLE_READER , IOException . class . getName ( ) ) . begin ( ) ; writer . formatln ( "int[] field_ids = %s.readIntArray(\"__fields__\");" , PORTABLE_READER ) . appendln ( ) . appendln ( "for (int id : field_ids) {" ) . begin ( ) . appendln ( "switch (id) {" ) . begin ( ) ; for ( JField field : message . declaredOrderFields ( ) ) { writer . formatln ( "case %d: {" , field . id ( ) ) . begin ( ) ; readPortableField ( field ) ; writer . appendln ( "break;" ) . end ( ) . appendln ( "}" ) ; } writer . end ( ) . appendln ( "}" ) . end ( ) . appendln ( "}" ) . end ( ) . appendln ( "}" ) . newline ( ) ; }
Method to append readPortable from hazelcast_portable .
19,387
public ApplicationRole newRole ( final String name , final String description ) { ApplicationRole role = findByName ( name ) ; if ( role == null ) { role = getApplicationRoleFactory ( ) . newApplicationRole ( ) ; role . setName ( name ) ; role . setDescription ( description ) ; container . persist ( role ) ; } return role ; }
region > newRole
19,388
private void hangOut ( final RequestCallInfo req , GenericJSO hangOut ) { final int hangOutId = hangOut . getIntByIdx ( 0 ) ; JsArrayString tmp = hangOut . getGenericJSOByIdx ( 1 ) . cast ( ) ; String name = tmp . get ( 0 ) ; String type = tmp . get ( 1 ) ; String title = tmp . get ( 2 ) ; String description = tmp . get ( 3 ) ; JavaScriptObject hangOutCurrentData = hangOut . getGenericJSOByIdx ( 2 ) ; callback . hangOut ( title , description , name , type , hangOutCurrentData , new IAsyncCallback < JavaScriptObject > ( ) { public void onSuccess ( JavaScriptObject result ) { JSONArray params = new JSONArray ( ) ; params . set ( 0 , new JSONNumber ( hangOutId ) ) ; params . set ( 1 , new JSONObject ( result ) ) ; req . request = new RequestDesc ( req . request . service , req . request . interfaceChecksum , "_hang_out_reply_" , params ) ; sendRequest ( req . request , req . cookie , req . callback ) ; } } ) ; }
over the network
19,389
private RPCBatchRequestSender getBatchRequestSender ( ) { RPCBatchRequestSender sender = null ; if ( ! batchRequestSenders . isEmpty ( ) ) { sender = batchRequestSenders . get ( batchRequestSenders . size ( ) - 1 ) ; if ( sender . canAddRequest ( ) ) return sender ; } sender = new RPCBatchRequestSender ( ) ; sender . init ( baseUrl , batchSenderCallback ) ; batchRequestSenders . add ( sender ) ; return sender ; }
retrieve a batch request sender that is OK for adding requests
19,390
private Set < ConstraintViolation < Object > > addViolations ( Set < ConstraintViolation < Object > > source , Set < ConstraintViolation < Object > > target ) { if ( supportsConstraintComposition ) { target . addAll ( source ) ; return target ; } for ( final Iterator < ConstraintViolation < Object > > iter = source . iterator ( ) ; iter . hasNext ( ) ; ) { final ConstraintViolation < Object > violation = iter . next ( ) ; final Iterator < Node > nodeIter = violation . getPropertyPath ( ) . iterator ( ) ; if ( ! nodeIter . hasNext ( ) || ( nodeIter . next ( ) != null && ! nodeIter . hasNext ( ) ) ) { target . add ( violation ) ; } } return target ; }
Add the given source violations to the target set and return the target set . This method will skip violations that have a property path depth greater than 1 .
19,391
private void passViolations ( ConstraintValidatorContext context , Set < ConstraintViolation < Object > > source ) { for ( final ConstraintViolation < Object > violation : source ) { final Iterator < Node > nodeIter = violation . getPropertyPath ( ) . iterator ( ) ; final ConstraintViolationBuilder builder = context . buildConstraintViolationWithTemplate ( violation . getMessageTemplate ( ) ) ; ConstraintValidatorContext nodeContext ; if ( nodeIter . hasNext ( ) ) { StringBuilder sb = new StringBuilder ( nodeIter . next ( ) . getName ( ) ) ; if ( supportsConstraintComposition ) { while ( nodeIter . hasNext ( ) ) { sb . append ( '.' ) . append ( nodeIter . next ( ) ) ; } } builder . addNode ( sb . toString ( ) ) . addConstraintViolation ( ) ; } else { builder . addConstraintViolation ( ) ; } } }
Pass the given violations to the given context . This method will skip violations that have a property path depth greater than 1 .
19,392
private void editCell ( Cell cell ) { if ( cell == null || cell == editedCell ) return ; T record = getRecordForRow ( cell . getParentRow ( ) ) ; if ( record == null ) return ; registerCurrentEdition ( cell , record ) ; }
Begin cell edition
19,393
public static String toHawkularFormat ( BasicMessage msg ) { return String . format ( "%s=%s" , msg . getClass ( ) . getSimpleName ( ) , msg . toJSON ( ) ) ; }
Returns a string that encodes the given object as a JSON message but then prefixes that JSON with additional information that a Hawkular client will need to be able to deserialize the JSON .
19,394
public static < T extends BasicMessage > T fromJSON ( String json , Class < T > clazz ) { try { Method buildObjectMapperForDeserializationMethod = findBuildObjectMapperForDeserializationMethod ( clazz ) ; final ObjectMapper mapper = ( ObjectMapper ) buildObjectMapperForDeserializationMethod . invoke ( null ) ; if ( FailOnUnknownProperties . class . isAssignableFrom ( clazz ) ) { mapper . configure ( DeserializationFeature . FAIL_ON_UNKNOWN_PROPERTIES , true ) ; } return mapper . readValue ( json , clazz ) ; } catch ( Exception e ) { throw new IllegalStateException ( "JSON message cannot be converted to object of type [" + clazz + "]" , e ) ; } }
Convenience static method that converts a JSON string to a particular message object .
19,395
public static < T extends BasicMessage > BasicMessageWithExtraData < T > fromJSON ( InputStream in , Class < T > clazz ) { final T obj ; final byte [ ] remainder ; try ( JsonParser parser = new JsonFactory ( ) . configure ( Feature . AUTO_CLOSE_SOURCE , false ) . createParser ( in ) ) { Method buildObjectMapperForDeserializationMethod = findBuildObjectMapperForDeserializationMethod ( clazz ) ; final ObjectMapper mapper = ( ObjectMapper ) buildObjectMapperForDeserializationMethod . invoke ( null ) ; if ( FailOnUnknownProperties . class . isAssignableFrom ( clazz ) ) { mapper . configure ( DeserializationFeature . FAIL_ON_UNKNOWN_PROPERTIES , true ) ; } obj = mapper . readValue ( parser , clazz ) ; final ByteArrayOutputStream remainderStream = new ByteArrayOutputStream ( ) ; final int released = parser . releaseBuffered ( remainderStream ) ; remainder = ( released > 0 ) ? remainderStream . toByteArray ( ) : new byte [ 0 ] ; } catch ( Exception e ) { throw new IllegalArgumentException ( "Stream cannot be converted to JSON object of type [" + clazz + "]" , e ) ; } return new BasicMessageWithExtraData < T > ( obj , new BinaryData ( remainder , in ) ) ; }
Convenience static method that reads a JSON string from the given stream and converts the JSON string to a particular message object . The input stream will remain open so the caller can stream any extra data that might appear after it .
19,396
protected static ObjectMapper buildObjectMapperForDeserialization ( ) { final ObjectMapper mapper = new ObjectMapper ( ) ; mapper . configure ( DeserializationFeature . FAIL_ON_UNKNOWN_PROPERTIES , false ) ; return mapper ; }
This is static so really there is no true overriding it in subclasses . However fromJSON will do the proper reflection in order to invoke the proper method for the class that is being deserialized . So subclasses that want to provide their own ObjectMapper will define their own method that matches the signature of this method and it will be used .
19,397
public String toJSON ( ) { final ObjectMapper mapper = buildObjectMapperForSerialization ( ) ; try { return mapper . writeValueAsString ( this ) ; } catch ( JsonProcessingException e ) { throw new IllegalStateException ( "Object cannot be parsed as JSON." , e ) ; } }
Converts this message to its JSON string representation .
19,398
public void onResponse ( Object cookie , ResponseJSO response , int msgLevel , String msg ) { PendingRequestInfo info = ( PendingRequestInfo ) cookie ; if ( info . fStoreResultInCache ) cache . put ( info . requestKey , response ) ; for ( RequestCallInfo call : info . subscriptions ) call . setResult ( msgLevel , msg , null , response ) ; pendingRequests . remove ( info ) ; checkAnswersToGive ( ) ; }
receives the answer from the ServerComm object
19,399
public static boolean dumpDatabaseSchemaToFile ( DatabaseContext ctx , File file ) { log . info ( "Dumping database schema to file " + file . getAbsolutePath ( ) ) ; DatabaseDescriptionInspector inspector = new DatabaseDescriptionInspector ( ) ; DatabaseDescription dbDesc = inspector . getDatabaseDescription ( ctx . db , ctx . dbh ) ; Gson gson = new Gson ( ) ; String json = gson . toJson ( dbDesc ) ; try { PrintWriter writer ; writer = new PrintWriter ( file ) ; writer . print ( json ) ; writer . close ( ) ; return true ; } catch ( FileNotFoundException e ) { e . printStackTrace ( ) ; return false ; } }
Writes the current database schema to a file in JSON format . This file can be used to update another database .