idx
int64
0
41.2k
question
stringlengths
74
4.04k
target
stringlengths
7
750
27,900
public void setScalarSerializer ( Class type , ScalarSerializer serializer ) { if ( type == null ) throw new IllegalArgumentException ( "type cannot be null." ) ; if ( serializer == null ) throw new IllegalArgumentException ( "serializer cannot be null." ) ; scalarSerializers . put ( type , serializer ) ; }
Adds a serializer for the specified scalar type .
27,901
public void setPropertyElementType ( Class type , String propertyName , Class elementType ) { if ( type == null ) throw new IllegalArgumentException ( "type cannot be null." ) ; if ( propertyName == null ) throw new IllegalArgumentException ( "propertyName cannot be null." ) ; if ( elementType == null ) throw new IllegalArgumentException ( "propertyType cannot be null." ) ; Property property = Beans . getProperty ( type , propertyName , beanProperties , privateFields , this ) ; if ( property == null ) throw new IllegalArgumentException ( "The class " + type . getName ( ) + " does not have a property named: " + propertyName ) ; if ( ! Collection . class . isAssignableFrom ( property . getType ( ) ) && ! Map . class . isAssignableFrom ( property . getType ( ) ) ) { throw new IllegalArgumentException ( "The '" + propertyName + "' property on the " + type . getName ( ) + " class must be a Collection or Map: " + property . getType ( ) ) ; } propertyToElementType . put ( property , elementType ) ; }
Sets the default type of elements in a Collection or Map property . No tag will be output for elements of this type . This type will be used for each element if no tag is found .
27,902
public void setPropertyDefaultType ( Class type , String propertyName , Class defaultType ) { if ( type == null ) throw new IllegalArgumentException ( "type cannot be null." ) ; if ( propertyName == null ) throw new IllegalArgumentException ( "propertyName cannot be null." ) ; if ( defaultType == null ) throw new IllegalArgumentException ( "defaultType cannot be null." ) ; Property property = Beans . getProperty ( type , propertyName , beanProperties , privateFields , this ) ; if ( property == null ) throw new IllegalArgumentException ( "The class " + type . getName ( ) + " does not have a property named: " + propertyName ) ; propertyToDefaultType . put ( property , defaultType ) ; }
Sets the default type of a property . No tag will be output for values of this type . This type will be used if no tag is found .
27,903
public < T > T read ( Class < T > type ) throws YamlException { return read ( type , null ) ; }
Reads an object of the specified type from YAML .
27,904
public < T > T read ( Class < T > type , Class elementType ) throws YamlException { try { while ( true ) { Event event = parser . getNextEvent ( ) ; if ( event == null ) return null ; if ( event . type == STREAM_END ) return null ; if ( event . type == DOCUMENT_START ) break ; } return ( T ) readValue ( type , elementType , null ) ; } catch ( ParserException ex ) { throw new YamlException ( "Error parsing YAML." , ex ) ; } catch ( TokenizerException ex ) { throw new YamlException ( "Error tokenizing YAML." , ex ) ; } }
Reads an array Map List or Collection object of the specified type from YAML using the specified element type .
27,905
protected Object readValue ( Class type , Class elementType , Class defaultType ) throws YamlException , ParserException , TokenizerException { String tag = null , anchor = null ; Event event = parser . peekNextEvent ( ) ; switch ( event . type ) { case ALIAS : parser . getNextEvent ( ) ; anchor = ( ( AliasEvent ) event ) . anchor ; Object value = anchors . get ( anchor ) ; if ( value == null ) throw new YamlReaderException ( "Unknown anchor: " + anchor ) ; return value ; case MAPPING_START : case SEQUENCE_START : tag = ( ( CollectionStartEvent ) event ) . tag ; anchor = ( ( CollectionStartEvent ) event ) . anchor ; break ; case SCALAR : tag = ( ( ScalarEvent ) event ) . tag ; anchor = ( ( ScalarEvent ) event ) . anchor ; break ; default : } return readValueInternal ( this . chooseType ( tag , defaultType , type ) , elementType , anchor ) ; }
Reads an object from the YAML . Can be overidden to take some action for any of the objects returned .
27,906
protected Object createObject ( Class type ) throws InvocationTargetException { DeferredConstruction deferredConstruction = Beans . getDeferredConstruction ( type , config ) ; if ( deferredConstruction != null ) return deferredConstruction ; return Beans . createObject ( type , config . privateConstructors ) ; }
Returns a new object of the requested type .
27,907
private final void error ( String message , CharSequence identifier ) { if ( badHtmlHandler != Handler . DO_NOTHING ) { badHtmlHandler . handle ( message + " : " + identifier ) ; } }
Called when the series of calls make no sense . May be overridden to throw an unchecked throwable to log or to take some other action .
27,908
static String safeName ( String unsafeElementName ) { String elementName = HtmlLexer . canonicalName ( unsafeElementName ) ; switch ( elementName . length ( ) ) { case 3 : if ( "xmp" . equals ( elementName ) ) { return "pre" ; } break ; case 7 : if ( "listing" . equals ( elementName ) ) { return "pre" ; } break ; case 9 : if ( "plaintext" . equals ( elementName ) ) { return "pre" ; } break ; } return elementName ; }
Canonicalizes the element name and possibly substitutes an alternative that has more consistent semantics .
27,909
public Trie lookup ( char ch ) { int i = Arrays . binarySearch ( childMap , ch ) ; return i >= 0 ? children [ i ] : null ; }
The child corresponding to the given character .
27,910
public Trie lookup ( CharSequence s ) { Trie t = this ; for ( int i = 0 , n = s . length ( ) ; i < n ; ++ i ) { t = t . lookup ( s . charAt ( i ) ) ; if ( null == t ) { break ; } } return t ; }
The descendant of this trie corresponding to the string for this trie appended with s .
27,911
static String normalizeUri ( String s ) { int n = s . length ( ) ; boolean colonsIrrelevant = false ; for ( int i = 0 ; i < n ; ++ i ) { char ch = s . charAt ( i ) ; switch ( ch ) { case '/' : case '#' : case '?' : case ':' : colonsIrrelevant = true ; break ; case '(' : case ')' : case '{' : case '}' : return normalizeUriFrom ( s , i , colonsIrrelevant ) ; case '\u0589' : case '\u05c3' : case '\u2236' : case '\uff1a' : if ( ! colonsIrrelevant ) { return normalizeUriFrom ( s , i , false ) ; } break ; default : if ( ch <= 0x20 ) { return normalizeUriFrom ( s , i , false ) ; } break ; } } return s ; }
Percent encodes anything that looks like a colon or a parenthesis .
27,912
public boolean canContain ( int parent , int child ) { if ( nofeatureElements . get ( parent ) ) { return true ; } return child == TEXT_NODE ? canContainText ( parent ) : canContain . get ( parent , child ) ; }
True if parent can directly contain child .
27,913
int [ ] impliedElements ( int anc , int desc ) { if ( desc == SCRIPT_TAG || desc == STYLE_TAG ) { return ZERO_INTS ; } FreeWrapper wrapper = desc != TEXT_NODE && desc < FREE_WRAPPERS . length ? FREE_WRAPPERS [ desc ] : null ; if ( wrapper != null ) { if ( anc < wrapper . allowedContainers . length && ! wrapper . allowedContainers [ anc ] ) { return wrapper . implied ; } } if ( desc != TEXT_NODE ) { int [ ] implied = impliedElements . getElementIndexList ( anc , desc ) ; if ( implied . length != 0 ) { return implied ; } } int [ ] oneImplied = null ; if ( anc == OL_TAG || anc == UL_TAG ) { oneImplied = LI_TAG_ARR ; } else if ( anc == SELECT_TAG ) { oneImplied = OPTION_TAG_ARR ; } if ( oneImplied != null ) { if ( desc != oneImplied [ 0 ] ) { return LI_TAG_ARR ; } } return ZERO_INTS ; }
Elements in order which are implicitly opened when a descendant tag is lexically nested within an ancestor .
27,914
static String canonicalName ( String elementOrAttribName ) { return elementOrAttribName . indexOf ( ':' ) >= 0 ? elementOrAttribName : Strings . toLowerCase ( elementOrAttribName ) ; }
Normalize case of names that are not name - spaced . This lower - cases HTML element and attribute names but not ones for embedded SVG or MATHML .
27,915
protected HtmlToken produce ( ) { HtmlToken token = readToken ( ) ; if ( token == null ) { return null ; } switch ( token . type ) { case TAGBEGIN : state = State . IN_TAG ; break ; case TAGEND : if ( state == State . SAW_EQ && HtmlTokenType . TAGEND == token . type ) { pushbackToken ( token ) ; state = State . IN_TAG ; return HtmlToken . instance ( token . start , token . start , HtmlTokenType . ATTRVALUE ) ; } state = State . OUTSIDE_TAG ; break ; case IGNORABLE : return produce ( ) ; default : switch ( state ) { case OUTSIDE_TAG : if ( HtmlTokenType . TEXT == token . type || HtmlTokenType . UNESCAPED == token . type ) { token = collapseSubsequent ( token ) ; } break ; case IN_TAG : if ( HtmlTokenType . TEXT == token . type && ! token . tokenInContextMatches ( input , "=" ) ) { token = HtmlInputSplitter . reclassify ( token , HtmlTokenType . ATTRNAME ) ; state = State . SAW_NAME ; } break ; case SAW_NAME : if ( HtmlTokenType . TEXT == token . type ) { if ( token . tokenInContextMatches ( input , "=" ) ) { state = State . SAW_EQ ; return produce ( ) ; } else { token = HtmlInputSplitter . reclassify ( token , HtmlTokenType . ATTRNAME ) ; } } else { state = State . IN_TAG ; } break ; case SAW_EQ : if ( HtmlTokenType . TEXT == token . type || HtmlTokenType . QSTRING == token . type ) { if ( HtmlTokenType . TEXT == token . type ) { token = collapseAttributeName ( token ) ; } token = HtmlInputSplitter . reclassify ( token , HtmlTokenType . ATTRVALUE ) ; state = State . IN_TAG ; } break ; } break ; } return token ; }
Makes sure that this . token contains a token if one is available . This may require fetching and combining multiple tokens from the underlying splitter .
27,916
private HtmlToken collapseSubsequent ( HtmlToken token ) { HtmlToken collapsed = token ; for ( HtmlToken next ; ( next = peekToken ( 0 ) ) != null && next . type == token . type ; readToken ( ) ) { collapsed = join ( collapsed , next ) ; } return collapsed ; }
Collapses all the following tokens of the same type into this . token .
27,917
private static boolean isValuelessAttribute ( String attribName ) { boolean valueless = VALUELESS_ATTRIB_NAMES . contains ( Strings . toLowerCase ( attribName ) ) ; return valueless ; }
Can the attribute appear in HTML without a value .
27,918
protected HtmlToken produce ( ) { HtmlToken token = parseToken ( ) ; if ( null == token ) { return null ; } if ( inEscapeExemptBlock ) { if ( token . type != HtmlTokenType . SERVERCODE ) { token = reclassify ( token , ( this . textEscapingMode == HtmlTextEscapingMode . RCDATA ? HtmlTokenType . TEXT : HtmlTokenType . UNESCAPED ) ) ; } } else { switch ( token . type ) { case TAGBEGIN : { String canonTagName = canonicalName ( token . start + 1 , token . end ) ; if ( HtmlTextEscapingMode . isTagFollowedByLiteralContent ( canonTagName ) ) { this . escapeExemptTagName = canonTagName ; this . textEscapingMode = HtmlTextEscapingMode . getModeForTag ( canonTagName ) ; } break ; } case TAGEND : this . inEscapeExemptBlock = null != this . escapeExemptTagName ; break ; default : break ; } } return token ; }
Make sure that there is a token ready to yield in this . token .
27,919
public HtmlPolicyBuilder allowElements ( ElementPolicy policy , String ... elementNames ) { invalidateCompiledState ( ) ; for ( String elementName : elementNames ) { elementName = HtmlLexer . canonicalName ( elementName ) ; ElementPolicy newPolicy = ElementPolicy . Util . join ( elPolicies . get ( elementName ) , policy ) ; elPolicies . put ( elementName , newPolicy ) ; if ( ! textContainers . containsKey ( elementName ) ) { if ( METADATA . canContainPlainText ( METADATA . indexForName ( elementName ) ) ) { textContainers . put ( elementName , true ) ; } } } return this ; }
Allow the given elements with the given policy .
27,920
public HtmlPolicyBuilder allowWithoutAttributes ( String ... elementNames ) { invalidateCompiledState ( ) ; for ( String elementName : elementNames ) { elementName = HtmlLexer . canonicalName ( elementName ) ; skipIfEmpty . remove ( elementName ) ; } return this ; }
Assuming the given elements are allowed allows them to appear without attributes .
27,921
public HtmlPolicyBuilder disallowWithoutAttributes ( String ... elementNames ) { invalidateCompiledState ( ) ; for ( String elementName : elementNames ) { elementName = HtmlLexer . canonicalName ( elementName ) ; skipIfEmpty . add ( elementName ) ; } return this ; }
Disallows the given elements from appearing without attributes .
27,922
public AttributeBuilder allowAttributes ( String ... attributeNames ) { ImmutableList . Builder < String > b = ImmutableList . builder ( ) ; for ( String attributeName : attributeNames ) { b . add ( HtmlLexer . canonicalName ( attributeName ) ) ; } return new AttributeBuilder ( b . build ( ) ) ; }
Returns an object that lets you associate policies with the given attributes and allow them globally or on specific elements .
27,923
public HtmlPolicyBuilder withPreprocessor ( HtmlStreamEventProcessor pp ) { this . preprocessor = HtmlStreamEventProcessor . Processors . compose ( this . preprocessor , pp ) ; return this ; }
Inserts a pre - processor into the pipeline between the lexer and the policy . Pre - processors receive HTML events before the policy so the policy will be applied to anything they add . Pre - processors are not in the TCB since they cannot bypass the policy .
27,924
public static void main ( String [ ] args ) throws IOException { if ( args . length != 0 ) { System . err . println ( "Reads from STDIN and writes to STDOUT" ) ; System . exit ( - 1 ) ; } System . err . println ( "[Reading from STDIN]" ) ; String html = CharStreams . toString ( new InputStreamReader ( System . in , Charsets . UTF_8 ) ) ; HtmlStreamRenderer renderer = HtmlStreamRenderer . create ( System . out , new Handler < IOException > ( ) { public void handle ( IOException ex ) { throw new AssertionError ( null , ex ) ; } } , new Handler < String > ( ) { public void handle ( String x ) { throw new AssertionError ( x ) ; } } ) ; HtmlSanitizer . sanitize ( html , POLICY_DEFINITION . apply ( renderer ) ) ; }
A test - bed that reads HTML from stdin and writes sanitized content to stdout .
27,925
public static String decodeHtml ( String s ) { int firstAmp = s . indexOf ( '&' ) ; int safeLimit = longestPrefixOfGoodCodeunits ( s ) ; if ( ( firstAmp & safeLimit ) < 0 ) { return s ; } StringBuilder sb ; { int n = s . length ( ) ; sb = new StringBuilder ( n ) ; int pos = 0 ; int amp = firstAmp ; while ( amp >= 0 ) { long endAndCodepoint = HtmlEntities . decodeEntityAt ( s , amp , n ) ; int end = ( int ) ( endAndCodepoint >>> 32 ) ; int codepoint = ( int ) endAndCodepoint ; sb . append ( s , pos , amp ) . appendCodePoint ( codepoint ) ; pos = end ; amp = s . indexOf ( '&' , end ) ; } sb . append ( s , pos , n ) ; } stripBannedCodeunits ( sb , firstAmp < 0 ? safeLimit : safeLimit < 0 ? firstAmp : Math . min ( firstAmp , safeLimit ) ) ; return sb . toString ( ) ; }
Decodes HTML entities to produce a string containing only valid Unicode scalar values .
27,926
static String stripBannedCodeunits ( String s ) { int safeLimit = longestPrefixOfGoodCodeunits ( s ) ; if ( safeLimit < 0 ) { return s ; } StringBuilder sb = new StringBuilder ( s ) ; stripBannedCodeunits ( sb , safeLimit ) ; return sb . toString ( ) ; }
Returns the portion of its input that consists of XML safe chars .
27,927
private static int longestPrefixOfGoodCodeunits ( String s ) { int n = s . length ( ) , i ; for ( i = 0 ; i < n ; ++ i ) { char ch = s . charAt ( i ) ; if ( ch < 0x20 ) { if ( IS_BANNED_ASCII [ ch ] ) { return i ; } } else if ( 0xd800 <= ch ) { if ( ch <= 0xdfff ) { if ( i + 1 < n && Character . isSurrogatePair ( ch , s . charAt ( i + 1 ) ) ) { ++ i ; } else { return i ; } } else if ( ( ch & 0xfffe ) == 0xfffe ) { return i ; } } } return - 1 ; }
The number of code - units at the front of s that form code - points in the XML Character production .
27,928
private boolean canContain ( int child , int container , int containerIndexOnStack ) { Preconditions . checkArgument ( containerIndexOnStack >= 0 ) ; int anc = container ; int ancIndexOnStack = containerIndexOnStack ; while ( true ) { if ( METADATA . canContain ( anc , child ) ) { return true ; } if ( ! TRANSPARENT . get ( anc ) ) { return false ; } if ( ancIndexOnStack == 0 ) { return METADATA . canContain ( BODY_TAG , child ) ; } -- ancIndexOnStack ; anc = openElements . get ( ancIndexOnStack ) ; } }
Takes into account transparency when figuring out what can be contained .
27,929
public static void run ( Appendable out , String ... inputs ) throws IOException { PolicyFactory policyBuilder = new HtmlPolicyBuilder ( ) . allowAttributes ( "src" ) . onElements ( "img" ) . allowAttributes ( "href" ) . onElements ( "a" ) . allowStandardUrlProtocols ( ) . allowElements ( "a" , "label" , "h1" , "h2" , "h3" , "h4" , "h5" , "h6" , "p" , "i" , "b" , "u" , "strong" , "em" , "small" , "big" , "pre" , "code" , "cite" , "samp" , "sub" , "sup" , "strike" , "center" , "blockquote" , "hr" , "br" , "col" , "font" , "span" , "div" , "img" , "ul" , "ol" , "li" , "dd" , "dt" , "dl" , "tbody" , "thead" , "tfoot" , "table" , "td" , "th" , "tr" , "colgroup" , "fieldset" , "legend" ) . withPostprocessor ( new HtmlStreamEventProcessor ( ) { public HtmlStreamEventReceiver wrap ( HtmlStreamEventReceiver sink ) { return new AppendDomainAfterText ( sink ) ; } } ) . toFactory ( ) ; out . append ( policyBuilder . sanitize ( Joiner . on ( '\n' ) . join ( inputs ) ) ) ; }
Sanitizes inputs to out .
27,930
public PolicyFactory and ( PolicyFactory f ) { ImmutableMap . Builder < String , ElementAndAttributePolicies > b = ImmutableMap . builder ( ) ; for ( Map . Entry < String , ElementAndAttributePolicies > e : policies . entrySet ( ) ) { String elName = e . getKey ( ) ; ElementAndAttributePolicies p = e . getValue ( ) ; ElementAndAttributePolicies q = f . policies . get ( elName ) ; if ( q != null ) { p = p . and ( q ) ; } else { p = p . andGlobals ( f . globalAttrPolicies ) ; } b . put ( elName , p ) ; } for ( Map . Entry < String , ElementAndAttributePolicies > e : f . policies . entrySet ( ) ) { String elName = e . getKey ( ) ; if ( ! policies . containsKey ( elName ) ) { ElementAndAttributePolicies p = e . getValue ( ) ; p = p . andGlobals ( globalAttrPolicies ) ; b . put ( elName , p ) ; } } ImmutableSet < String > allTextContainers ; if ( this . textContainers . containsAll ( f . textContainers ) ) { allTextContainers = this . textContainers ; } else if ( f . textContainers . containsAll ( this . textContainers ) ) { allTextContainers = f . textContainers ; } else { allTextContainers = ImmutableSet . < String > builder ( ) . addAll ( this . textContainers ) . addAll ( f . textContainers ) . build ( ) ; } ImmutableMap < String , AttributePolicy > allGlobalAttrPolicies ; if ( f . globalAttrPolicies . isEmpty ( ) ) { allGlobalAttrPolicies = this . globalAttrPolicies ; } else if ( this . globalAttrPolicies . isEmpty ( ) ) { allGlobalAttrPolicies = f . globalAttrPolicies ; } else { ImmutableMap . Builder < String , AttributePolicy > ab = ImmutableMap . builder ( ) ; for ( Map . Entry < String , AttributePolicy > e : this . globalAttrPolicies . entrySet ( ) ) { String attrName = e . getKey ( ) ; ab . put ( attrName , AttributePolicy . Util . join ( e . getValue ( ) , f . globalAttrPolicies . get ( attrName ) ) ) ; } for ( Map . Entry < String , AttributePolicy > e : f . globalAttrPolicies . entrySet ( ) ) { String attrName = e . getKey ( ) ; if ( ! this . globalAttrPolicies . containsKey ( attrName ) ) { ab . put ( attrName , e . getValue ( ) ) ; } } allGlobalAttrPolicies = ab . build ( ) ; } HtmlStreamEventProcessor compositionOfPreprocessors = HtmlStreamEventProcessor . Processors . compose ( this . preprocessor , f . preprocessor ) ; HtmlStreamEventProcessor compositionOfPostprocessors = HtmlStreamEventProcessor . Processors . compose ( this . postprocessor , f . postprocessor ) ; return new PolicyFactory ( b . build ( ) , allTextContainers , allGlobalAttrPolicies , compositionOfPreprocessors , compositionOfPostprocessors ) ; }
Produces a factory that allows the union of the grants and intersects policies where they overlap on a particular granted attribute or element name .
27,931
static String cssContent ( String token ) { int n = token . length ( ) ; int pos = 0 ; StringBuilder sb = null ; if ( n >= 2 ) { char ch0 = token . charAt ( 0 ) ; if ( ch0 == '"' || ch0 == '\'' ) { if ( ch0 == token . charAt ( n - 1 ) ) { pos = 1 ; -- n ; sb = new StringBuilder ( n ) ; } } } for ( int esc ; ( esc = token . indexOf ( '\\' , pos ) ) >= 0 ; ) { int end = esc + 2 ; if ( esc > n ) { break ; } if ( sb == null ) { sb = new StringBuilder ( n ) ; } sb . append ( token , pos , esc ) ; int codepoint = token . charAt ( end - 1 ) ; if ( isHex ( codepoint ) ) { while ( end < n && isHex ( token . charAt ( end ) ) ) { ++ end ; } try { codepoint = Integer . parseInt ( token . substring ( esc + 1 , end ) , 16 ) ; } catch ( RuntimeException ex ) { ignore ( ex ) ; codepoint = 0xfffd ; } if ( end < n ) { char ch = token . charAt ( end ) ; if ( ch == ' ' || ch == '\t' ) { ++ end ; } } } sb . appendCodePoint ( codepoint ) ; pos = end ; } if ( sb == null ) { return token ; } return sb . append ( token , pos , n ) . toString ( ) ; }
Decodes any escape sequences and strips any quotes from the input .
27,932
private static void quickSort ( int [ ] order , double [ ] values , int start , int end , int limit ) { while ( end - start > limit ) { int pivotIndex = start + prng . nextInt ( end - start ) ; double pivotValue = values [ order [ pivotIndex ] ] ; swap ( order , start , pivotIndex ) ; int low = start + 1 ; int high = end ; int i = low ; while ( i < high ) { double vi = values [ order [ i ] ] ; if ( vi == pivotValue ) { if ( low != i ) { swap ( order , low , i ) ; } else { i ++ ; } low ++ ; } else if ( vi > pivotValue ) { high -- ; swap ( order , i , high ) ; } else { i ++ ; } } int from = start ; int to = high - 1 ; for ( i = 0 ; from < low && to >= low ; i ++ ) { swap ( order , from ++ , to -- ) ; } if ( from == low ) { low = to + 1 ; } else { low = from ; } if ( low - start < end - high ) { quickSort ( order , values , start , low , limit ) ; start = high ; } else { quickSort ( order , values , high , end , limit ) ; end = low ; } } }
Standard quick sort except that sorting is done on an index array rather than the values themselves
27,933
private static void quickSort ( double [ ] key , double [ ] [ ] values , int start , int end , int limit ) { while ( end - start > limit ) { int a = start ; int b = ( start + end ) / 2 ; int c = end - 1 ; int pivotIndex ; double pivotValue ; double va = key [ a ] ; double vb = key [ b ] ; double vc = key [ c ] ; if ( va > vb ) { if ( vc > va ) { pivotIndex = a ; pivotValue = va ; } else { if ( vc < vb ) { pivotIndex = b ; pivotValue = vb ; } else { pivotIndex = c ; pivotValue = vc ; } } } else { if ( vc > vb ) { pivotIndex = b ; pivotValue = vb ; } else { if ( vc < va ) { pivotIndex = a ; pivotValue = va ; } else { pivotIndex = c ; pivotValue = vc ; } } } swap ( start , pivotIndex , key , values ) ; int low = start + 1 ; int high = end ; int i = low ; while ( i < high ) { double vi = key [ i ] ; if ( vi == pivotValue ) { if ( low != i ) { swap ( low , i , key , values ) ; } else { i ++ ; } low ++ ; } else if ( vi > pivotValue ) { high -- ; swap ( i , high , key , values ) ; } else { i ++ ; } } int from = start ; int to = high - 1 ; for ( i = 0 ; from < low && to >= low ; i ++ ) { swap ( from ++ , to -- , key , values ) ; } if ( from == low ) { low = to + 1 ; } else { low = from ; } if ( low - start < end - high ) { quickSort ( key , values , start , low , limit ) ; start = high ; } else { quickSort ( key , values , high , end , limit ) ; end = low ; } } }
Standard quick sort except that sorting rearranges parallel arrays
27,934
@ SuppressWarnings ( "SameParameterValue" ) private static void insertionSort ( double [ ] key , double [ ] [ ] values , int start , int end , int limit ) { for ( int i = start + 1 ; i < end ; i ++ ) { double v = key [ i ] ; int m = Math . max ( i - limit , start ) ; for ( int j = i ; j >= m ; j -- ) { if ( j == m || key [ j - 1 ] <= v ) { if ( j < i ) { System . arraycopy ( key , j , key , j + 1 , i - j ) ; key [ j ] = v ; for ( double [ ] value : values ) { double tmp = value [ i ] ; System . arraycopy ( value , j , value , j + 1 , i - j ) ; value [ j ] = tmp ; } } break ; } } } }
Limited range insertion sort . We assume that no element has to move more than limit steps because quick sort has done its thing . This version works on parallel arrays of keys and values .
27,935
@ SuppressWarnings ( "UnusedDeclaration" ) public static void checkPartition ( int [ ] order , double [ ] values , double pivotValue , int start , int low , int high , int end ) { if ( order . length != values . length ) { throw new IllegalArgumentException ( "Arguments must be same size" ) ; } if ( ! ( start >= 0 && low >= start && high >= low && end >= high ) ) { throw new IllegalArgumentException ( String . format ( "Invalid indices %d, %d, %d, %d" , start , low , high , end ) ) ; } for ( int i = 0 ; i < low ; i ++ ) { double v = values [ order [ i ] ] ; if ( v >= pivotValue ) { throw new IllegalArgumentException ( String . format ( "Value greater than pivot at %d" , i ) ) ; } } for ( int i = low ; i < high ; i ++ ) { if ( values [ order [ i ] ] != pivotValue ) { throw new IllegalArgumentException ( String . format ( "Non-pivot at %d" , i ) ) ; } } for ( int i = high ; i < end ; i ++ ) { double v = values [ order [ i ] ] ; if ( v <= pivotValue ) { throw new IllegalArgumentException ( String . format ( "Value less than pivot at %d" , i ) ) ; } } }
Check that a partition step was done correctly . For debugging and testing .
27,936
@ SuppressWarnings ( "SameParameterValue" ) private static void insertionSort ( int [ ] order , double [ ] values , int start , int n , int limit ) { for ( int i = start + 1 ; i < n ; i ++ ) { int t = order [ i ] ; double v = values [ order [ i ] ] ; int m = Math . max ( i - limit , start ) ; for ( int j = i ; j >= m ; j -- ) { if ( j == 0 || values [ order [ j - 1 ] ] <= v ) { if ( j < i ) { System . arraycopy ( order , j , order , j + 1 , i - j ) ; order [ j ] = t ; } break ; } } } }
Limited range insertion sort . We assume that no element has to move more than limit steps because quick sort has done its thing .
27,937
static double quantile ( double index , double previousIndex , double nextIndex , double previousMean , double nextMean ) { final double delta = nextIndex - previousIndex ; final double previousWeight = ( nextIndex - index ) / delta ; final double nextWeight = ( index - previousIndex ) / delta ; return previousMean * previousWeight + nextMean * nextWeight ; }
Computes an interpolated value of a quantile that is between two centroids .
27,938
public void add ( double centroid , int count , List < Double > data ) { this . centroid = centroid ; this . count = count ; this . data = data ; tree . add ( ) ; }
Add the provided centroid to the tree .
27,939
@ SuppressWarnings ( "WeakerAccess" ) public void update ( int node , double centroid , int count , List < Double > data , boolean forceInPlace ) { if ( centroid == centroids [ node ] || forceInPlace ) { centroids [ node ] = centroid ; counts [ node ] = count ; if ( datas != null ) { datas [ node ] = data ; } } else { this . centroid = centroid ; this . count = count ; this . data = data ; tree . update ( node ) ; } }
Update values associated with a node readjusting the tree if necessary .
27,940
public int smallByteSize ( ) { int bound = byteSize ( ) ; ByteBuffer buf = ByteBuffer . allocate ( bound ) ; asSmallBytes ( buf ) ; return buf . position ( ) ; }
Returns an upper bound on the number of bytes that will be required to represent this histogram in the tighter representation .
27,941
public void asBytes ( ByteBuffer buf ) { buf . putInt ( VERBOSE_ENCODING ) ; buf . putDouble ( min ) ; buf . putDouble ( max ) ; buf . putDouble ( ( float ) compression ( ) ) ; buf . putInt ( summary . size ( ) ) ; for ( Centroid centroid : summary ) { buf . putDouble ( centroid . mean ( ) ) ; } for ( Centroid centroid : summary ) { buf . putInt ( centroid . count ( ) ) ; } }
Outputs a histogram as bytes using a particularly cheesy encoding .
27,942
@ SuppressWarnings ( "WeakerAccess" ) public static AVLTreeDigest fromBytes ( ByteBuffer buf ) { int encoding = buf . getInt ( ) ; if ( encoding == VERBOSE_ENCODING ) { double min = buf . getDouble ( ) ; double max = buf . getDouble ( ) ; double compression = buf . getDouble ( ) ; AVLTreeDigest r = new AVLTreeDigest ( compression ) ; r . setMinMax ( min , max ) ; int n = buf . getInt ( ) ; double [ ] means = new double [ n ] ; for ( int i = 0 ; i < n ; i ++ ) { means [ i ] = buf . getDouble ( ) ; } for ( int i = 0 ; i < n ; i ++ ) { r . add ( means [ i ] , buf . getInt ( ) ) ; } return r ; } else if ( encoding == SMALL_ENCODING ) { double min = buf . getDouble ( ) ; double max = buf . getDouble ( ) ; double compression = buf . getDouble ( ) ; AVLTreeDigest r = new AVLTreeDigest ( compression ) ; r . setMinMax ( min , max ) ; int n = buf . getInt ( ) ; double [ ] means = new double [ n ] ; double x = 0 ; for ( int i = 0 ; i < n ; i ++ ) { double delta = buf . getFloat ( ) ; x += delta ; means [ i ] = x ; } for ( int i = 0 ; i < n ; i ++ ) { int z = decode ( buf ) ; r . add ( means [ i ] , z ) ; } return r ; } else { throw new IllegalStateException ( "Invalid format for serialized histogram" ) ; } }
Reads a histogram from a byte buffer
27,943
@ SuppressWarnings ( "WeakerAccess" ) public static double compareChi2 ( TDigest dist1 , TDigest dist2 , double [ ] qCuts ) { double [ ] [ ] count = new double [ 2 ] [ ] ; count [ 0 ] = new double [ qCuts . length + 1 ] ; count [ 1 ] = new double [ qCuts . length + 1 ] ; double oldQ = 0 ; double oldQ2 = 0 ; for ( int i = 0 ; i <= qCuts . length ; i ++ ) { double newQ ; double x ; if ( i == qCuts . length ) { newQ = 1 ; x = Math . max ( dist1 . getMax ( ) , dist2 . getMax ( ) ) + 1 ; } else { newQ = qCuts [ i ] ; x = dist1 . quantile ( newQ ) ; } count [ 0 ] [ i ] = dist1 . size ( ) * ( newQ - oldQ ) ; double q2 = dist2 . cdf ( x ) ; count [ 1 ] [ i ] = dist2 . size ( ) * ( q2 - oldQ2 ) ; oldQ = newQ ; oldQ2 = q2 ; } return llr ( count ) ; }
Use a log - likelihood ratio test to compare two distributions . This is done by estimating counts in quantile ranges from each distribution and then comparing those counts using a multinomial test . The result should be asymptotically chi^2 distributed if the data comes from the same distribution but this isn t so much useful as a traditional test of a null hypothesis as it is just a reasonably well - behaved score that is bigger when the distributions are more different subject to having enough data to tell .
27,944
public int find ( ) { for ( int node = root ; node != NIL ; ) { final int cmp = compare ( node ) ; if ( cmp < 0 ) { node = left ( node ) ; } else if ( cmp > 0 ) { node = right ( node ) ; } else { return node ; } } return NIL ; }
Find a node in this tree .
27,945
public void remove ( int node ) { if ( node == NIL ) { throw new IllegalArgumentException ( ) ; } if ( left ( node ) != NIL && right ( node ) != NIL ) { final int next = next ( node ) ; assert next != NIL ; swap ( node , next ) ; } assert left ( node ) == NIL || right ( node ) == NIL ; final int parent = parent ( node ) ; int child = left ( node ) ; if ( child == NIL ) { child = right ( node ) ; } if ( child == NIL ) { if ( node == root ) { assert size ( ) == 1 : size ( ) ; root = NIL ; } else { if ( node == left ( parent ) ) { left ( parent , NIL ) ; } else { assert node == right ( parent ) ; right ( parent , NIL ) ; } } } else { if ( node == root ) { assert size ( ) == 2 ; root = child ; } else if ( node == left ( parent ) ) { left ( parent , child ) ; } else { assert node == right ( parent ) ; right ( parent , child ) ; } parent ( child , parent ) ; } release ( node ) ; rebalance ( parent ) ; }
Remove the specified node from the tree .
27,946
public String getMessageId ( ) { Object messageId = getHeader ( JmsMessageHeaders . MESSAGE_ID ) ; if ( messageId != null ) { return messageId . toString ( ) ; } return null ; }
Gets the JMS messageId header .
27,947
public String getCorrelationId ( ) { Object correlationId = getHeader ( JmsMessageHeaders . CORRELATION_ID ) ; if ( correlationId != null ) { return correlationId . toString ( ) ; } return null ; }
Gets the JMS correlationId header .
27,948
public Destination getReplyTo ( ) { Object replyTo = getHeader ( JmsMessageHeaders . REPLY_TO ) ; if ( replyTo != null ) { return ( Destination ) replyTo ; } return null ; }
Gets the JMS reply to header .
27,949
public String getRedelivered ( ) { Object redelivered = getHeader ( JmsMessageHeaders . REDELIVERED ) ; if ( redelivered != null ) { return redelivered . toString ( ) ; } return null ; }
Gets the JMS redelivered header .
27,950
public String getType ( ) { Object type = getHeader ( JmsMessageHeaders . TYPE ) ; if ( type != null ) { return type . toString ( ) ; } return null ; }
Gets the JMS type header .
27,951
private void performSchemaValidation ( Message receivedMessage , JsonMessageValidationContext validationContext ) { log . debug ( "Starting Json schema validation ..." ) ; ProcessingReport report = jsonSchemaValidation . validate ( receivedMessage , schemaRepositories , validationContext , applicationContext ) ; if ( ! report . isSuccess ( ) ) { log . error ( "Failed to validate Json schema for message:\n" + receivedMessage . getPayload ( String . class ) ) ; throw new ValidationException ( constructErrorMessage ( report ) ) ; } log . info ( "Json schema validation successful: All values OK" ) ; }
Performs the schema validation for the given message under consideration of the given validation context
27,952
private String constructErrorMessage ( ProcessingReport report ) { StringBuilder stringBuilder = new StringBuilder ( ) ; stringBuilder . append ( "Json validation failed: " ) ; report . forEach ( processingMessage -> stringBuilder . append ( processingMessage . getMessage ( ) ) ) ; return stringBuilder . toString ( ) ; }
Constructs the error message of a failed validation based on the processing report passed from com . github . fge . jsonschema . core . report
27,953
public static boolean isSpringInternalHeader ( String headerName ) { if ( headerName . startsWith ( "springintegration_" ) ) { return true ; } else if ( headerName . equals ( MessageHeaders . ID ) ) { return true ; } else if ( headerName . equals ( MessageHeaders . TIMESTAMP ) ) { return true ; } else if ( headerName . equals ( MessageHeaders . REPLY_CHANNEL ) ) { return true ; } else if ( headerName . equals ( MessageHeaders . ERROR_CHANNEL ) ) { return true ; } else if ( headerName . equals ( MessageHeaders . CONTENT_TYPE ) ) { return true ; } else if ( headerName . equals ( IntegrationMessageHeaderAccessor . PRIORITY ) ) { return true ; } else if ( headerName . equals ( IntegrationMessageHeaderAccessor . CORRELATION_ID ) ) { return true ; } else if ( headerName . equals ( IntegrationMessageHeaderAccessor . ROUTING_SLIP ) ) { return true ; } else if ( headerName . equals ( IntegrationMessageHeaderAccessor . DUPLICATE_MESSAGE ) ) { return true ; } else if ( headerName . equals ( IntegrationMessageHeaderAccessor . SEQUENCE_NUMBER ) ) { return true ; } else if ( headerName . equals ( IntegrationMessageHeaderAccessor . SEQUENCE_SIZE ) ) { return true ; } else if ( headerName . equals ( IntegrationMessageHeaderAccessor . SEQUENCE_DETAILS ) ) { return true ; } else if ( headerName . equals ( IntegrationMessageHeaderAccessor . EXPIRATION_DATE ) ) { return true ; } else if ( headerName . startsWith ( "jms_" ) ) { return true ; } return false ; }
Check if given header name belongs to Spring Integration internal headers .
27,954
public static SoapAttachment parseAttachment ( Element attachmentElement ) { SoapAttachment soapAttachment = new SoapAttachment ( ) ; if ( attachmentElement . hasAttribute ( "content-id" ) ) { soapAttachment . setContentId ( attachmentElement . getAttribute ( "content-id" ) ) ; } if ( attachmentElement . hasAttribute ( "content-type" ) ) { soapAttachment . setContentType ( attachmentElement . getAttribute ( "content-type" ) ) ; } if ( attachmentElement . hasAttribute ( "charset-name" ) ) { soapAttachment . setCharsetName ( attachmentElement . getAttribute ( "charset-name" ) ) ; } if ( attachmentElement . hasAttribute ( "mtom-inline" ) ) { soapAttachment . setMtomInline ( Boolean . parseBoolean ( attachmentElement . getAttribute ( "mtom-inline" ) ) ) ; } if ( attachmentElement . hasAttribute ( "encoding-type" ) ) { soapAttachment . setEncodingType ( attachmentElement . getAttribute ( "encoding-type" ) ) ; } Element attachmentDataElement = DomUtils . getChildElementByTagName ( attachmentElement , "data" ) ; if ( attachmentDataElement != null ) { soapAttachment . setContent ( DomUtils . getTextValue ( attachmentDataElement ) ) ; } Element attachmentResourceElement = DomUtils . getChildElementByTagName ( attachmentElement , "resource" ) ; if ( attachmentResourceElement != null ) { soapAttachment . setContentResourcePath ( attachmentResourceElement . getAttribute ( "file" ) ) ; } return soapAttachment ; }
Parse the attachment element with all children and attributes .
27,955
public ObjectName createObjectName ( ) { try { if ( StringUtils . hasText ( objectName ) ) { return new ObjectName ( objectDomain + ":" + objectName ) ; } if ( type != null ) { if ( StringUtils . hasText ( objectDomain ) ) { return new ObjectName ( objectDomain , "type" , type . getSimpleName ( ) ) ; } return new ObjectName ( type . getPackage ( ) . getName ( ) , "type" , type . getSimpleName ( ) ) ; } return new ObjectName ( objectDomain , "name" , name ) ; } catch ( NullPointerException | MalformedObjectNameException e ) { throw new CitrusRuntimeException ( "Failed to create proper object name for managed bean" , e ) ; } }
Constructs proper object name either from given domain and name property or by evaluating the mbean type class information .
27,956
public MBeanInfo createMBeanInfo ( ) { if ( type != null ) { return new MBeanInfo ( type . getName ( ) , description , getAttributeInfo ( ) , getConstructorInfo ( ) , getOperationInfo ( ) , getNotificationInfo ( ) ) ; } else { return new MBeanInfo ( name , description , getAttributeInfo ( ) , getConstructorInfo ( ) , getOperationInfo ( ) , getNotificationInfo ( ) ) ; } }
Create managed bean info with all constructors operations notifications and attributes .
27,957
private MBeanOperationInfo [ ] getOperationInfo ( ) { final List < MBeanOperationInfo > infoList = new ArrayList < > ( ) ; if ( type != null ) { ReflectionUtils . doWithMethods ( type , new ReflectionUtils . MethodCallback ( ) { public void doWith ( Method method ) throws IllegalArgumentException , IllegalAccessException { infoList . add ( new MBeanOperationInfo ( OPERATION_DESCRIPTION , method ) ) ; } } , new ReflectionUtils . MethodFilter ( ) { public boolean matches ( Method method ) { return method . getDeclaringClass ( ) . equals ( type ) && ! method . getName ( ) . startsWith ( "set" ) && ! method . getName ( ) . startsWith ( "get" ) && ! method . getName ( ) . startsWith ( "is" ) && ! method . getName ( ) . startsWith ( "$jacoco" ) ; } } ) ; } else { for ( ManagedBeanInvocation . Operation operation : operations ) { List < MBeanParameterInfo > parameterInfo = new ArrayList < > ( ) ; int i = 1 ; for ( OperationParam parameter : operation . getParameter ( ) . getParameter ( ) ) { parameterInfo . add ( new MBeanParameterInfo ( "p" + i ++ , parameter . getType ( ) , "Parameter #" + i ) ) ; } infoList . add ( new MBeanOperationInfo ( operation . getName ( ) , OPERATION_DESCRIPTION , parameterInfo . toArray ( new MBeanParameterInfo [ operation . getParameter ( ) . getParameter ( ) . size ( ) ] ) , operation . getReturnType ( ) , MBeanOperationInfo . UNKNOWN ) ) ; } } return infoList . toArray ( new MBeanOperationInfo [ infoList . size ( ) ] ) ; }
Create this managed bean operations info .
27,958
private MBeanConstructorInfo [ ] getConstructorInfo ( ) { final List < MBeanConstructorInfo > infoList = new ArrayList < > ( ) ; if ( type != null ) { for ( Constructor constructor : type . getConstructors ( ) ) { infoList . add ( new MBeanConstructorInfo ( constructor . toGenericString ( ) , constructor ) ) ; } } return infoList . toArray ( new MBeanConstructorInfo [ infoList . size ( ) ] ) ; }
Create this managed bean constructor info .
27,959
private MBeanAttributeInfo [ ] getAttributeInfo ( ) { final List < MBeanAttributeInfo > infoList = new ArrayList < > ( ) ; if ( type != null ) { final List < String > attributes = new ArrayList < > ( ) ; if ( type . isInterface ( ) ) { ReflectionUtils . doWithMethods ( type , new ReflectionUtils . MethodCallback ( ) { public void doWith ( Method method ) throws IllegalArgumentException , IllegalAccessException { String attributeName ; if ( method . getName ( ) . startsWith ( "get" ) ) { attributeName = method . getName ( ) . substring ( 3 ) ; } else if ( method . getName ( ) . startsWith ( "is" ) ) { attributeName = method . getName ( ) . substring ( 2 ) ; } else { attributeName = method . getName ( ) ; } if ( ! attributes . contains ( attributeName ) ) { infoList . add ( new MBeanAttributeInfo ( attributeName , method . getReturnType ( ) . getName ( ) , ATTRIBUTE_DESCRIPTION , true , true , method . getName ( ) . startsWith ( "is" ) ) ) ; attributes . add ( attributeName ) ; } } } , new ReflectionUtils . MethodFilter ( ) { public boolean matches ( Method method ) { return method . getDeclaringClass ( ) . equals ( type ) && ( method . getName ( ) . startsWith ( "get" ) || method . getName ( ) . startsWith ( "is" ) ) ; } } ) ; } else { ReflectionUtils . doWithFields ( type , new ReflectionUtils . FieldCallback ( ) { public void doWith ( Field field ) throws IllegalArgumentException , IllegalAccessException { infoList . add ( new MBeanAttributeInfo ( field . getName ( ) , field . getType ( ) . getName ( ) , ATTRIBUTE_DESCRIPTION , true , true , field . getType ( ) . equals ( Boolean . class ) ) ) ; } } , new ReflectionUtils . FieldFilter ( ) { public boolean matches ( Field field ) { return ! Modifier . isStatic ( field . getModifiers ( ) ) && ! Modifier . isFinal ( field . getModifiers ( ) ) ; } } ) ; } } else { int i = 1 ; for ( ManagedBeanInvocation . Attribute attribute : attributes ) { infoList . add ( new MBeanAttributeInfo ( attribute . getName ( ) , attribute . getType ( ) , ATTRIBUTE_DESCRIPTION , true , true , attribute . getType ( ) . equals ( Boolean . class . getName ( ) ) ) ) ; } } return infoList . toArray ( new MBeanAttributeInfo [ infoList . size ( ) ] ) ; }
Create this managed bean attributes info .
27,960
public void finish ( ) throws IOException { if ( printWriter != null ) { printWriter . close ( ) ; } if ( outputStream != null ) { outputStream . close ( ) ; } }
Finish response stream by closing .
27,961
public void postRegisterUrlHandlers ( Map < String , Object > wsHandlers ) { registerHandlers ( wsHandlers ) ; for ( Object handler : wsHandlers . values ( ) ) { if ( handler instanceof Lifecycle ) { ( ( Lifecycle ) handler ) . start ( ) ; } } }
Workaround for registering the WebSocket request handlers after the spring context has been initialised .
27,962
public AbstractMessageContentBuilder constructMessageBuilder ( Element messageElement ) { AbstractMessageContentBuilder messageBuilder = null ; if ( messageElement != null ) { messageBuilder = parsePayloadTemplateBuilder ( messageElement ) ; if ( messageBuilder == null ) { messageBuilder = parseScriptBuilder ( messageElement ) ; } } if ( messageBuilder == null ) { messageBuilder = new PayloadTemplateMessageBuilder ( ) ; } if ( messageElement != null && messageElement . hasAttribute ( "name" ) ) { messageBuilder . setMessageName ( messageElement . getAttribute ( "name" ) ) ; } return messageBuilder ; }
Static parse method taking care of basic message element parsing .
27,963
private PayloadTemplateMessageBuilder parsePayloadTemplateBuilder ( Element messageElement ) { PayloadTemplateMessageBuilder messageBuilder ; messageBuilder = parsePayloadElement ( messageElement ) ; Element xmlDataElement = DomUtils . getChildElementByTagName ( messageElement , "data" ) ; if ( xmlDataElement != null ) { messageBuilder = new PayloadTemplateMessageBuilder ( ) ; messageBuilder . setPayloadData ( DomUtils . getTextValue ( xmlDataElement ) . trim ( ) ) ; } Element xmlResourceElement = DomUtils . getChildElementByTagName ( messageElement , "resource" ) ; if ( xmlResourceElement != null ) { messageBuilder = new PayloadTemplateMessageBuilder ( ) ; messageBuilder . setPayloadResourcePath ( xmlResourceElement . getAttribute ( "file" ) ) ; if ( xmlResourceElement . hasAttribute ( "charset" ) ) { messageBuilder . setPayloadResourceCharset ( xmlResourceElement . getAttribute ( "charset" ) ) ; } } if ( messageBuilder != null ) { Map < String , String > overwriteXpath = new HashMap < > ( ) ; Map < String , String > overwriteJsonPath = new HashMap < > ( ) ; List < ? > messageValueElements = DomUtils . getChildElementsByTagName ( messageElement , "element" ) ; for ( Iterator < ? > iter = messageValueElements . iterator ( ) ; iter . hasNext ( ) ; ) { Element messageValue = ( Element ) iter . next ( ) ; String pathExpression = messageValue . getAttribute ( "path" ) ; if ( JsonPathMessageValidationContext . isJsonPathExpression ( pathExpression ) ) { overwriteJsonPath . put ( pathExpression , messageValue . getAttribute ( "value" ) ) ; } else { overwriteXpath . put ( pathExpression , messageValue . getAttribute ( "value" ) ) ; } } if ( ! overwriteXpath . isEmpty ( ) ) { XpathMessageConstructionInterceptor interceptor = new XpathMessageConstructionInterceptor ( overwriteXpath ) ; messageBuilder . add ( interceptor ) ; } if ( ! overwriteJsonPath . isEmpty ( ) ) { JsonPathMessageConstructionInterceptor interceptor = new JsonPathMessageConstructionInterceptor ( overwriteJsonPath ) ; messageBuilder . add ( interceptor ) ; } } return messageBuilder ; }
Parses message payload template information given in message element .
27,964
protected void parseHeaderElements ( Element actionElement , AbstractMessageContentBuilder messageBuilder , List < ValidationContext > validationContexts ) { Element headerElement = DomUtils . getChildElementByTagName ( actionElement , "header" ) ; Map < String , Object > messageHeaders = new LinkedHashMap < > ( ) ; if ( headerElement != null ) { List < ? > elements = DomUtils . getChildElementsByTagName ( headerElement , "element" ) ; for ( Iterator < ? > iter = elements . iterator ( ) ; iter . hasNext ( ) ; ) { Element headerValue = ( Element ) iter . next ( ) ; String name = headerValue . getAttribute ( "name" ) ; String value = headerValue . getAttribute ( "value" ) ; String type = headerValue . getAttribute ( "type" ) ; if ( StringUtils . hasText ( type ) ) { value = MessageHeaderType . createTypedValue ( type , value ) ; } messageHeaders . put ( name , value ) ; } List < Element > headerDataElements = DomUtils . getChildElementsByTagName ( headerElement , "data" ) ; for ( Element headerDataElement : headerDataElements ) { messageBuilder . getHeaderData ( ) . add ( DomUtils . getTextValue ( headerDataElement ) . trim ( ) ) ; } List < Element > headerResourceElements = DomUtils . getChildElementsByTagName ( headerElement , "resource" ) ; for ( Element headerResourceElement : headerResourceElements ) { String charset = headerResourceElement . getAttribute ( "charset" ) ; messageBuilder . getHeaderResources ( ) . add ( headerResourceElement . getAttribute ( "file" ) + ( StringUtils . hasText ( charset ) ? FileUtils . FILE_PATH_CHARSET_PARAMETER + charset : "" ) ) ; } List < Element > headerFragmentElements = DomUtils . getChildElementsByTagName ( headerElement , "fragment" ) ; for ( Element headerFragmentElement : headerFragmentElements ) { List < Element > fragment = DomUtils . getChildElements ( headerFragmentElement ) ; if ( ! CollectionUtils . isEmpty ( fragment ) ) { messageBuilder . getHeaderData ( ) . add ( PayloadElementParser . parseMessagePayload ( fragment . get ( 0 ) ) ) ; } } messageBuilder . setMessageHeaders ( messageHeaders ) ; if ( headerElement . hasAttribute ( "ignore-case" ) ) { boolean ignoreCase = Boolean . valueOf ( headerElement . getAttribute ( "ignore-case" ) ) ; validationContexts . stream ( ) . filter ( context -> context instanceof HeaderValidationContext ) . map ( context -> ( HeaderValidationContext ) context ) . forEach ( context -> context . setHeaderNameIgnoreCase ( ignoreCase ) ) ; } } }
Parse message header elements in action and add headers to message content builder .
27,965
protected void parseExtractHeaderElements ( Element element , List < VariableExtractor > variableExtractors ) { Element extractElement = DomUtils . getChildElementByTagName ( element , "extract" ) ; Map < String , String > extractHeaderValues = new HashMap < > ( ) ; if ( extractElement != null ) { List < ? > headerValueElements = DomUtils . getChildElementsByTagName ( extractElement , "header" ) ; for ( Iterator < ? > iter = headerValueElements . iterator ( ) ; iter . hasNext ( ) ; ) { Element headerValue = ( Element ) iter . next ( ) ; extractHeaderValues . put ( headerValue . getAttribute ( "name" ) , headerValue . getAttribute ( "variable" ) ) ; } MessageHeaderVariableExtractor headerVariableExtractor = new MessageHeaderVariableExtractor ( ) ; headerVariableExtractor . setHeaderMappings ( extractHeaderValues ) ; if ( ! CollectionUtils . isEmpty ( extractHeaderValues ) ) { variableExtractors . add ( headerVariableExtractor ) ; } } }
Parses header extract information .
27,966
public String build ( ) { StringBuilder scriptBuilder = new StringBuilder ( ) ; StringBuilder scriptBody = new StringBuilder ( ) ; String importStmt = "import " ; try { if ( scriptCode . contains ( importStmt ) ) { BufferedReader reader = new BufferedReader ( new StringReader ( scriptCode ) ) ; String line ; while ( ( line = reader . readLine ( ) ) != null ) { if ( line . trim ( ) . startsWith ( importStmt ) ) { scriptBuilder . append ( line ) ; scriptBuilder . append ( "\n" ) ; } else { scriptBody . append ( ( scriptBody . length ( ) == 0 ? "" : "\n" ) ) ; scriptBody . append ( line ) ; } } } else { scriptBody . append ( scriptCode ) ; } } catch ( IOException e ) { throw new CitrusRuntimeException ( "Failed to construct script from template" , e ) ; } scriptBuilder . append ( scriptHead ) ; scriptBuilder . append ( scriptBody . toString ( ) ) ; scriptBuilder . append ( scriptTail ) ; return scriptBuilder . toString ( ) ; }
Builds the final script .
27,967
public static TemplateBasedScriptBuilder fromTemplateResource ( Resource scriptTemplateResource ) { try { return new TemplateBasedScriptBuilder ( FileUtils . readToString ( scriptTemplateResource . getInputStream ( ) ) ) ; } catch ( IOException e ) { throw new CitrusRuntimeException ( "Error loading script template from file resource" , e ) ; } }
Static construction method returning a fully qualified instance of this builder .
27,968
private ResponseEntity < ? > handleRequestInternal ( HttpMethod method , HttpEntity < ? > requestEntity ) { HttpMessage request = endpointConfiguration . getMessageConverter ( ) . convertInbound ( requestEntity , endpointConfiguration , null ) ; HttpServletRequest servletRequest = ( ( ServletRequestAttributes ) RequestContextHolder . getRequestAttributes ( ) ) . getRequest ( ) ; UrlPathHelper pathHelper = new UrlPathHelper ( ) ; Enumeration allHeaders = servletRequest . getHeaderNames ( ) ; for ( String headerName : CollectionUtils . toArray ( allHeaders , new String [ ] { } ) ) { if ( request . getHeader ( headerName ) == null ) { String headerValue = servletRequest . getHeader ( headerName ) ; request . header ( headerName , headerValue != null ? headerValue : "" ) ; } } if ( endpointConfiguration . isHandleCookies ( ) ) { request . setCookies ( servletRequest . getCookies ( ) ) ; } if ( endpointConfiguration . isHandleAttributeHeaders ( ) ) { Enumeration < String > attributeNames = servletRequest . getAttributeNames ( ) ; while ( attributeNames . hasMoreElements ( ) ) { String attributeName = attributeNames . nextElement ( ) ; Object attribute = servletRequest . getAttribute ( attributeName ) ; request . setHeader ( attributeName , attribute ) ; } } request . path ( pathHelper . getRequestUri ( servletRequest ) ) . uri ( pathHelper . getRequestUri ( servletRequest ) ) . contextPath ( pathHelper . getContextPath ( servletRequest ) ) . queryParams ( Optional . ofNullable ( pathHelper . getOriginatingQueryString ( servletRequest ) ) . map ( queryString -> queryString . replaceAll ( "&" , "," ) ) . orElse ( "" ) ) . version ( servletRequest . getProtocol ( ) ) . method ( method ) ; Message response = endpointAdapter . handleMessage ( request ) ; ResponseEntity < ? > responseEntity ; if ( response == null ) { responseEntity = new ResponseEntity < > ( HttpStatus . valueOf ( endpointConfiguration . getDefaultStatusCode ( ) ) ) ; } else { HttpMessage httpResponse ; if ( response instanceof HttpMessage ) { httpResponse = ( HttpMessage ) response ; } else { httpResponse = new HttpMessage ( response ) ; } if ( httpResponse . getStatusCode ( ) == null ) { httpResponse . status ( HttpStatus . valueOf ( endpointConfiguration . getDefaultStatusCode ( ) ) ) ; } responseEntity = ( ResponseEntity < ? > ) endpointConfiguration . getMessageConverter ( ) . convertOutbound ( httpResponse , endpointConfiguration , null ) ; if ( endpointConfiguration . isHandleCookies ( ) && httpResponse . getCookies ( ) != null ) { HttpServletResponse servletResponse = ( ( ServletRequestAttributes ) RequestContextHolder . getRequestAttributes ( ) ) . getResponse ( ) ; for ( Cookie cookie : httpResponse . getCookies ( ) ) { servletResponse . addCookie ( cookie ) ; } } } responseCache . add ( responseEntity ) ; return responseEntity ; }
Handles requests with endpoint adapter implementation . Previously sets Http request method as header parameter .
27,969
public Message buildMessageContent ( final TestContext context , final String messageType , final MessageDirection direction ) { final Object payload = buildMessagePayload ( context , messageType ) ; try { Message message = new DefaultMessage ( payload , buildMessageHeaders ( context , messageType ) ) ; message . setName ( messageName ) ; if ( payload != null ) { for ( final MessageConstructionInterceptor interceptor : context . getGlobalMessageConstructionInterceptors ( ) . getMessageConstructionInterceptors ( ) ) { if ( direction . equals ( MessageDirection . UNBOUND ) || interceptor . getDirection ( ) . equals ( MessageDirection . UNBOUND ) || direction . equals ( interceptor . getDirection ( ) ) ) { message = interceptor . interceptMessageConstruction ( message , messageType , context ) ; } } if ( dataDictionary != null ) { message = dataDictionary . interceptMessageConstruction ( message , messageType , context ) ; } for ( final MessageConstructionInterceptor interceptor : messageInterceptors ) { if ( direction . equals ( MessageDirection . UNBOUND ) || interceptor . getDirection ( ) . equals ( MessageDirection . UNBOUND ) || direction . equals ( interceptor . getDirection ( ) ) ) { message = interceptor . interceptMessageConstruction ( message , messageType , context ) ; } } } message . getHeaderData ( ) . addAll ( buildMessageHeaderData ( context ) ) ; return message ; } catch ( final RuntimeException e ) { throw e ; } catch ( final Exception e ) { throw new CitrusRuntimeException ( "Failed to build message content" , e ) ; } }
Constructs the control message with headers and payload coming from subclass implementation .
27,970
public Map < String , Object > buildMessageHeaders ( final TestContext context , final String messageType ) { try { final Map < String , Object > headers = context . resolveDynamicValuesInMap ( messageHeaders ) ; headers . put ( MessageHeaders . MESSAGE_TYPE , messageType ) ; for ( final Map . Entry < String , Object > entry : headers . entrySet ( ) ) { final String value = entry . getValue ( ) . toString ( ) ; if ( MessageHeaderType . isTyped ( value ) ) { final MessageHeaderType type = MessageHeaderType . fromTypedValue ( value ) ; final Constructor < ? > constr = type . getHeaderClass ( ) . getConstructor ( String . class ) ; entry . setValue ( constr . newInstance ( MessageHeaderType . removeTypeDefinition ( value ) ) ) ; } } MessageHeaderUtils . checkHeaderTypes ( headers ) ; return headers ; } catch ( final RuntimeException e ) { throw e ; } catch ( final Exception e ) { throw new CitrusRuntimeException ( "Failed to build message content" , e ) ; } }
Build message headers .
27,971
public List < String > buildMessageHeaderData ( final TestContext context ) { final List < String > headerDataList = new ArrayList < > ( ) ; for ( final String headerResourcePath : headerResources ) { try { headerDataList . add ( context . replaceDynamicContentInString ( FileUtils . readToString ( FileUtils . getFileResource ( headerResourcePath , context ) , FileUtils . getCharset ( headerResourcePath ) ) ) ) ; } catch ( final IOException e ) { throw new CitrusRuntimeException ( "Failed to read message header data resource" , e ) ; } } for ( final String data : headerData ) { headerDataList . add ( context . replaceDynamicContentInString ( data . trim ( ) ) ) ; } return headerDataList ; }
Build message header data .
27,972
public SoapServerFaultResponseActionBuilder attachment ( String contentId , String contentType , String content ) { SoapAttachment attachment = new SoapAttachment ( ) ; attachment . setContentId ( contentId ) ; attachment . setContentType ( contentType ) ; attachment . setContent ( content ) ; getAction ( ) . getAttachments ( ) . add ( attachment ) ; return this ; }
Sets the attachment with string content .
27,973
public SoapServerFaultResponseActionBuilder charset ( String charsetName ) { if ( ! getAction ( ) . getAttachments ( ) . isEmpty ( ) ) { getAction ( ) . getAttachments ( ) . get ( getAction ( ) . getAttachments ( ) . size ( ) - 1 ) . setCharsetName ( charsetName ) ; } return this ; }
Sets the charset name for this send action builder s attachment .
27,974
public SoapServerFaultResponseActionBuilder faultDetailResource ( Resource resource , Charset charset ) { try { getAction ( ) . getFaultDetails ( ) . add ( FileUtils . readToString ( resource , charset ) ) ; } catch ( IOException e ) { throw new CitrusRuntimeException ( "Failed to read fault detail resource" , e ) ; } return this ; }
Adds a fault detail from file resource .
27,975
public static CitrusConfiguration from ( Properties extensionProperties ) { CitrusConfiguration configuration = new CitrusConfiguration ( extensionProperties ) ; configuration . setCitrusVersion ( getProperty ( extensionProperties , "citrusVersion" ) ) ; if ( extensionProperties . containsKey ( "autoPackage" ) ) { configuration . setAutoPackage ( Boolean . valueOf ( getProperty ( extensionProperties , "autoPackage" ) ) ) ; } if ( extensionProperties . containsKey ( "suiteName" ) ) { configuration . setSuiteName ( getProperty ( extensionProperties , "suiteName" ) ) ; } if ( extensionProperties . containsKey ( "configurationClass" ) ) { String configurationClass = getProperty ( extensionProperties , "configurationClass" ) ; try { Class < ? > configType = Class . forName ( configurationClass ) ; if ( CitrusSpringConfig . class . isAssignableFrom ( configType ) ) { configuration . setConfigurationClass ( ( Class < ? extends CitrusSpringConfig > ) configType ) ; } else { log . warn ( String . format ( "Found invalid Citrus configuration class: %s, must be a subclass of %s" , configurationClass , CitrusSpringConfig . class ) ) ; } } catch ( ClassNotFoundException e ) { log . warn ( String . format ( "Unable to access Citrus configuration class: %s" , configurationClass ) , e ) ; } } log . debug ( String . format ( "Using Citrus configuration:%n%s" , configuration . toString ( ) ) ) ; return configuration ; }
Constructs Citrus configuration instance from given property set .
27,976
private static String getProperty ( Properties extensionProperties , String propertyName ) { if ( extensionProperties . containsKey ( propertyName ) ) { Object value = extensionProperties . get ( propertyName ) ; if ( value != null ) { return value . toString ( ) ; } } return null ; }
Try to read property from property set . When not set or null value return null else return String representation of value object .
27,977
private static Properties readPropertiesFromDescriptor ( ArquillianDescriptor descriptor ) { for ( ExtensionDef extension : descriptor . getExtensions ( ) ) { if ( CitrusExtensionConstants . CITRUS_EXTENSION_QUALIFIER . equals ( extension . getExtensionName ( ) ) ) { Properties properties = new Properties ( ) ; properties . putAll ( extension . getExtensionProperties ( ) ) ; return properties ; } } return new Properties ( ) ; }
Find Citrus extension configuration in descriptor and read properties .
27,978
protected Resource loadSchemaResources ( ) { PathMatchingResourcePatternResolver resourcePatternResolver = new PathMatchingResourcePatternResolver ( ) ; for ( String location : schemas ) { try { Resource [ ] findings = resourcePatternResolver . getResources ( location ) ; for ( Resource finding : findings ) { if ( finding . getFilename ( ) . endsWith ( ".xsd" ) || finding . getFilename ( ) . endsWith ( ".wsdl" ) ) { schemaResources . add ( finding ) ; } } } catch ( IOException e ) { throw new CitrusRuntimeException ( "Failed to read schema resources for location: " + location , e ) ; } } return schemaResources . get ( 0 ) ; }
Loads all schema resource files from schema locations .
27,979
public boolean isLast ( ) { Object isLast = getHeader ( WebSocketMessageHeaders . WEB_SOCKET_IS_LAST ) ; if ( isLast != null ) { if ( isLast instanceof String ) { return Boolean . valueOf ( isLast . toString ( ) ) ; } else { return ( Boolean ) isLast ; } } return true ; }
Gets the isLast flag from message headers .
27,980
private OperationResult getOperationResult ( ) { if ( operationResult == null ) { this . operationResult = ( OperationResult ) marshaller . unmarshal ( new StringSource ( getPayload ( String . class ) ) ) ; } return operationResult ; }
Gets the operation result if any or tries to unmarshal String payload representation to an operation result model .
27,981
private Operation getOperation ( ) { if ( operation == null ) { this . operation = ( Operation ) marshaller . unmarshal ( new StringSource ( getPayload ( String . class ) ) ) ; } return operation ; }
Gets the operation if any or tries to unmarshal String payload representation to an operation model .
27,982
String getPayloadAsString ( Message < ? > message ) { if ( message . getPayload ( ) instanceof com . consol . citrus . message . Message ) { return ( ( com . consol . citrus . message . Message ) message . getPayload ( ) ) . getPayload ( String . class ) ; } else { return message . getPayload ( ) . toString ( ) ; } }
Reads message payload as String either from message object directly or from nested Citrus message representation .
27,983
protected boolean evaluate ( String value ) { if ( ValidationMatcherUtils . isValidationMatcherExpression ( matchingValue ) ) { try { ValidationMatcherUtils . resolveValidationMatcher ( selectKey , value , matchingValue , context ) ; return true ; } catch ( ValidationException e ) { return false ; } } else { return value . equals ( matchingValue ) ; } }
Evaluates given value to match this selectors matching condition . Automatically supports validation matcher expressions .
27,984
protected FtpMessage createDir ( CommandType ftpCommand ) { try { sftp . mkdir ( ftpCommand . getArguments ( ) ) ; return FtpMessage . result ( FTPReply . PATHNAME_CREATED , "Pathname created" , true ) ; } catch ( SftpException e ) { throw new CitrusRuntimeException ( "Failed to execute ftp command" , e ) ; } }
Execute mkDir command and create new directory .
27,985
public LSParser createLSParser ( ) { LSParser parser = domImpl . createLSParser ( DOMImplementationLS . MODE_SYNCHRONOUS , null ) ; configureParser ( parser ) ; return parser ; }
Creates basic LSParser instance and sets common properties and configuration parameters .
27,986
protected void configureParser ( LSParser parser ) { for ( Map . Entry < String , Object > setting : parseSettings . entrySet ( ) ) { setParserConfigParameter ( parser , setting . getKey ( ) , setting . getValue ( ) ) ; } }
Set parser configuration based on this configurers settings .
27,987
protected void configureSerializer ( LSSerializer serializer ) { for ( Map . Entry < String , Object > setting : serializeSettings . entrySet ( ) ) { setSerializerConfigParameter ( serializer , setting . getKey ( ) , setting . getValue ( ) ) ; } }
Set serializer configuration based on this configurers settings .
27,988
private void setDefaultParseSettings ( ) { if ( ! parseSettings . containsKey ( CDATA_SECTIONS ) ) { parseSettings . put ( CDATA_SECTIONS , true ) ; } if ( ! parseSettings . containsKey ( SPLIT_CDATA_SECTIONS ) ) { parseSettings . put ( SPLIT_CDATA_SECTIONS , false ) ; } if ( ! parseSettings . containsKey ( VALIDATE_IF_SCHEMA ) ) { parseSettings . put ( VALIDATE_IF_SCHEMA , true ) ; } if ( ! parseSettings . containsKey ( RESOURCE_RESOLVER ) ) { parseSettings . put ( RESOURCE_RESOLVER , createLSResourceResolver ( ) ) ; } if ( ! parseSettings . containsKey ( ELEMENT_CONTENT_WHITESPACE ) ) { parseSettings . put ( ELEMENT_CONTENT_WHITESPACE , false ) ; } }
Sets the default parse settings .
27,989
private void setDefaultSerializeSettings ( ) { if ( ! serializeSettings . containsKey ( ELEMENT_CONTENT_WHITESPACE ) ) { serializeSettings . put ( ELEMENT_CONTENT_WHITESPACE , true ) ; } if ( ! serializeSettings . containsKey ( SPLIT_CDATA_SECTIONS ) ) { serializeSettings . put ( SPLIT_CDATA_SECTIONS , false ) ; } if ( ! serializeSettings . containsKey ( FORMAT_PRETTY_PRINT ) ) { serializeSettings . put ( FORMAT_PRETTY_PRINT , true ) ; } if ( ! serializeSettings . containsKey ( XML_DECLARATION ) ) { serializeSettings . put ( XML_DECLARATION , true ) ; } }
Sets the default serialize settings .
27,990
public void addPart ( AttachmentPart part ) { if ( attachments == null ) { attachments = new BodyPart . Attachments ( ) ; } this . attachments . add ( part ) ; }
Adds new attachment part .
27,991
public static String getBinding ( String resourcePath ) { if ( resourcePath . contains ( "/" ) ) { return resourcePath . substring ( resourcePath . indexOf ( '/' ) + 1 ) ; } return null ; }
Extract service binding information from endpoint resource path . This is usualle the path after the port specification .
27,992
public static String getHost ( String resourcePath ) { String hostSpec ; if ( resourcePath . contains ( ":" ) ) { hostSpec = resourcePath . split ( ":" ) [ 0 ] ; } else { hostSpec = resourcePath ; } if ( hostSpec . contains ( "/" ) ) { hostSpec = hostSpec . substring ( 0 , hostSpec . indexOf ( '/' ) ) ; } return hostSpec ; }
Extract host name from resource path .
27,993
public static SoapAttachment from ( Attachment attachment ) { SoapAttachment soapAttachment = new SoapAttachment ( ) ; String contentId = attachment . getContentId ( ) ; if ( contentId . startsWith ( "<" ) && contentId . endsWith ( ">" ) ) { contentId = contentId . substring ( 1 , contentId . length ( ) - 1 ) ; } soapAttachment . setContentId ( contentId ) ; soapAttachment . setContentType ( attachment . getContentType ( ) ) ; if ( attachment . getContentType ( ) . startsWith ( "text" ) ) { try { soapAttachment . setContent ( FileUtils . readToString ( attachment . getInputStream ( ) ) . trim ( ) ) ; } catch ( IOException e ) { throw new CitrusRuntimeException ( "Failed to read SOAP attachment content" , e ) ; } } else { soapAttachment . setDataHandler ( attachment . getDataHandler ( ) ) ; } soapAttachment . setCharsetName ( Citrus . CITRUS_FILE_ENCODING ) ; return soapAttachment ; }
Static construction method from Spring mime attachment .
27,994
public String getContent ( ) { if ( content != null ) { return context != null ? context . replaceDynamicContentInString ( content ) : content ; } else if ( StringUtils . hasText ( getContentResourcePath ( ) ) && getContentType ( ) . startsWith ( "text" ) ) { try { String fileContent = FileUtils . readToString ( new PathMatchingResourcePatternResolver ( ) . getResource ( getContentResourcePath ( ) ) . getInputStream ( ) , Charset . forName ( charsetName ) ) ; return context != null ? context . replaceDynamicContentInString ( fileContent ) : fileContent ; } catch ( IOException e ) { throw new CitrusRuntimeException ( "Failed to read SOAP attachment file resource" , e ) ; } } else { try { byte [ ] binaryData = FileCopyUtils . copyToByteArray ( getDataHandler ( ) . getInputStream ( ) ) ; if ( encodingType . equals ( SoapAttachment . ENCODING_BASE64_BINARY ) ) { return Base64 . encodeBase64String ( binaryData ) ; } else if ( encodingType . equals ( SoapAttachment . ENCODING_HEX_BINARY ) ) { return Hex . encodeHexString ( binaryData ) . toUpperCase ( ) ; } else { throw new CitrusRuntimeException ( String . format ( "Unsupported encoding type '%s' for SOAP attachment - choose one of %s or %s" , encodingType , SoapAttachment . ENCODING_BASE64_BINARY , SoapAttachment . ENCODING_HEX_BINARY ) ) ; } } catch ( IOException e ) { throw new CitrusRuntimeException ( "Failed to read SOAP attachment data input stream" , e ) ; } } }
Get the content body .
27,995
public String getContentResourcePath ( ) { if ( contentResourcePath != null && context != null ) { return context . replaceDynamicContentInString ( contentResourcePath ) ; } else { return contentResourcePath ; } }
Get the content file resource path .
27,996
public void extractVariables ( Message message , TestContext context ) { if ( CollectionUtils . isEmpty ( headerMappings ) ) { return ; } for ( Entry < String , String > entry : headerMappings . entrySet ( ) ) { String headerElementName = entry . getKey ( ) ; String targetVariableName = entry . getValue ( ) ; if ( message . getHeader ( headerElementName ) == null ) { throw new UnknownElementException ( "Could not find header element " + headerElementName + " in received header" ) ; } context . setVariable ( targetVariableName , message . getHeader ( headerElementName ) . toString ( ) ) ; } }
Reads header information and saves new test variables .
27,997
public < T extends KubernetesCommand > T command ( T command ) { action . setCommand ( command ) ; return command ; }
Use a kubernetes command .
27,998
private Message receive ( TestContext context ) { Endpoint messageEndpoint = getOrCreateEndpoint ( context ) ; return receiveTimeout > 0 ? messageEndpoint . createConsumer ( ) . receive ( context , receiveTimeout ) : messageEndpoint . createConsumer ( ) . receive ( context , messageEndpoint . getEndpointConfiguration ( ) . getTimeout ( ) ) ; }
Receives the message with respective message receiver implementation .
27,999
private Message receiveSelected ( TestContext context , String selectorString ) { if ( log . isDebugEnabled ( ) ) { log . debug ( "Setting message selector: '" + selectorString + "'" ) ; } Endpoint messageEndpoint = getOrCreateEndpoint ( context ) ; Consumer consumer = messageEndpoint . createConsumer ( ) ; if ( consumer instanceof SelectiveConsumer ) { if ( receiveTimeout > 0 ) { return ( ( SelectiveConsumer ) messageEndpoint . createConsumer ( ) ) . receive ( context . replaceDynamicContentInString ( selectorString ) , context , receiveTimeout ) ; } else { return ( ( SelectiveConsumer ) messageEndpoint . createConsumer ( ) ) . receive ( context . replaceDynamicContentInString ( selectorString ) , context , messageEndpoint . getEndpointConfiguration ( ) . getTimeout ( ) ) ; } } else { log . warn ( String . format ( "Unable to receive selective with consumer implementation: '%s'" , consumer . getClass ( ) ) ) ; return receive ( context ) ; } }
Receives the message with the respective message receiver implementation also using a message selector .