idx
int64 0
41.2k
| question
stringlengths 83
4.15k
| target
stringlengths 5
715
|
|---|---|---|
5,300
|
private Map < String , Integer > parseFirstDays ( JsonObject root ) { JsonObject node = resolve ( root , "supplemental" , "weekData" , "firstDay" ) ; Map < String , Integer > m = new HashMap < > ( ) ; for ( String key : objectKeys ( node ) ) { String value = string ( node , key ) ; m . put ( key , NUMERIC_DAYS . get ( value ) ) ; } return m ; }
|
Parse the first day values . This is the value of the first day of the week in a calendar view .
|
5,301
|
private String [ ] weekdayMap ( JsonObject node ) { String [ ] res = new String [ 7 ] ; for ( int i = 0 ; i < 7 ; i ++ ) { res [ i ] = node . get ( WEEKDAY_KEYS [ i ] ) . getAsString ( ) ; } return res ; }
|
Extract weekday names from a locale s mapping .
|
5,302
|
private void parsePlurals ( JsonObject root , String type , Map < String , PluralData > map ) { JsonObject node = resolve ( root , "supplemental" , type ) ; for ( Map . Entry < String , JsonElement > entry : node . entrySet ( ) ) { String language = entry . getKey ( ) ; PluralData data = new PluralData ( ) ; for ( Map . Entry < String , JsonElement > ruleNode : entry . getValue ( ) . getAsJsonObject ( ) . entrySet ( ) ) { String category = ruleNode . getKey ( ) . replaceFirst ( "^pluralRule-count-" , "" ) ; String value = ruleNode . getValue ( ) . getAsString ( ) ; Maybe < Pair < Node < PluralType > , CharSequence > > result = PluralRuleGrammar . parse ( value ) ; if ( result . isNothing ( ) ) { throw new IllegalArgumentException ( format ( "failed to parse rule: \"%s\"" , StringEscapeUtils . escapeJava ( value ) ) ) ; } Struct < PluralType > rule = result . get ( ) . _1 . asStruct ( ) ; Node < PluralType > conditionNode = findChild ( rule , PluralType . OR_CONDITION ) ; Node < PluralType > sampleNode = findChild ( rule , PluralType . SAMPLE ) ; String sample = sampleNode == null ? "" : ( String ) sampleNode . asAtom ( ) . value ( ) ; data . add ( category , new PluralData . Rule ( value , conditionNode , sample ) ) ; } map . put ( language , data ) ; } }
|
Parse pluralization rules . These rules indicate which pluralization category is in effect based on the value of the plural operands which are computed from an integer or decimal value .
|
5,303
|
private NumberData parseNumberData ( LocaleID id , String code , JsonObject root ) { NumberData data = getNumberData ( id ) ; JsonObject numbers = resolve ( root , "numbers" ) ; data . minimumGroupingDigits = Integer . valueOf ( string ( numbers , "minimumGroupingDigits" ) ) ; JsonObject symbols = resolve ( numbers , "symbols-numberSystem-latn" ) ; data . decimal = string ( symbols , "decimal" ) ; data . group = string ( symbols , "group" ) ; data . percent = string ( symbols , "percentSign" ) ; data . plus = string ( symbols , "plusSign" ) ; data . minus = string ( symbols , "minusSign" ) ; data . exponential = string ( symbols , "exponential" ) ; data . superscriptingExponent = string ( symbols , "superscriptingExponent" ) ; data . perMille = string ( symbols , "perMille" ) ; data . infinity = string ( symbols , "infinity" ) ; data . nan = string ( symbols , "nan" ) ; data . currencyDecimal = string ( symbols , "currencyDecimal" , data . decimal ) ; data . currencyGroup = string ( symbols , "currencyGroup" , data . group ) ; JsonObject decimalFormats = resolve ( numbers , "decimalFormats-numberSystem-latn" ) ; data . decimalFormatStandard = getNumberPattern ( string ( decimalFormats , "standard" ) ) ; data . decimalFormatShort = getPluralNumberPattern ( resolve ( decimalFormats , "short" , "decimalFormat" ) ) ; data . decimalFormatLong = getPluralNumberPattern ( resolve ( decimalFormats , "long" , "decimalFormat" ) ) ; JsonObject percentFormats = resolve ( numbers , "percentFormats-numberSystem-latn" ) ; data . percentFormatStandard = getNumberPattern ( string ( percentFormats , "standard" ) ) ; JsonObject currencyFormats = resolve ( numbers , "currencyFormats-numberSystem-latn" ) ; data . currencyFormatStandard = getNumberPattern ( string ( currencyFormats , "standard" ) ) ; data . currencyFormatAccounting = getNumberPattern ( string ( currencyFormats , "accounting" ) ) ; data . currencyFormatShort = getPluralNumberPattern ( resolve ( currencyFormats , "short" , "standard" ) ) ; data . currencyUnitPattern = new HashMap < > ( ) ; for ( String key : objectKeys ( currencyFormats ) ) { if ( key . startsWith ( "unitPattern-count" ) ) { data . currencyUnitPattern . put ( key , string ( currencyFormats , key ) ) ; } } return data ; }
|
Parse number and some currency data for locale .
|
5,304
|
private void parseCurrencyData ( LocaleID id , String code , JsonObject root ) { NumberData data = getNumberData ( id ) ; data . currencySymbols = new LinkedHashMap < > ( ) ; data . narrowCurrencySymbols = new LinkedHashMap < > ( ) ; data . currencyDisplayName = new LinkedHashMap < > ( ) ; data . currencyDisplayNames = new LinkedHashMap < > ( ) ; JsonObject currencies = resolve ( root , "numbers" , "currencies" ) ; for ( String currencyCode : objectKeys ( currencies ) ) { JsonObject node = resolve ( currencies , currencyCode ) ; data . currencyDisplayName . put ( currencyCode , string ( node , "displayName" ) ) ; String symbol = string ( node , "symbol" ) ; String narrowSymbol = string ( node , "symbol-alt-narrow" ) ; narrowSymbol = narrowSymbol . equals ( "" ) ? symbol : narrowSymbol ; data . currencySymbols . put ( currencyCode , symbol ) ; data . narrowCurrencySymbols . put ( currencyCode , narrowSymbol ) ; Map < String , String > displayNames = new LinkedHashMap < > ( ) ; for ( String key : objectKeys ( node ) ) { if ( key . startsWith ( "displayName-count" ) ) { displayNames . put ( key , node . get ( key ) . getAsString ( ) ) ; } } data . currencyDisplayNames . put ( currencyCode , displayNames ) ; } }
|
Parse locale - specific currency data .
|
5,305
|
private void parseSupplementalCurrencyData ( JsonObject root ) { JsonObject fractions = resolve ( root , "supplemental" , "currencyData" , "fractions" ) ; for ( String code : objectKeys ( fractions ) ) { CurrencyData data = getCurrencyData ( code ) ; JsonObject node = fractions . get ( code ) . getAsJsonObject ( ) ; data . digits = Integer . valueOf ( string ( node , "_digits" ) ) ; } }
|
Parse supplemental currency data .
|
5,306
|
private NumberData getNumberData ( LocaleID id ) { NumberData data = numbers . get ( id ) ; if ( data == null ) { data = new NumberData ( ) ; data . setID ( id ) ; numbers . put ( id , data ) ; } return data ; }
|
Get or create the number data object for this locale .
|
5,307
|
private CurrencyData getCurrencyData ( String code ) { CurrencyData data = currencies . get ( code ) ; if ( data == null ) { data = new CurrencyData ( ) ; data . setCode ( code ) ; currencies . put ( code , data ) ; } return data ; }
|
Get or create the currency data object for this code .
|
5,308
|
private List < TimeZoneInfo > parseTimeZoneInfos ( String code , JsonObject root ) { JsonObject node = resolve ( root , "main" , code , "dates" , "timeZoneNames" , "zone" ) ; return parseTimeZoneInfo ( node , Collections . emptyList ( ) ) ; }
|
Parse timezone names .
|
5,309
|
private List < TimeZoneInfo > parseTimeZoneInfo ( JsonObject root , List < String > prefix ) { List < TimeZoneInfo > zones = new ArrayList < > ( ) ; for ( String label : objectKeys ( root ) ) { JsonObject value = resolve ( root , label ) ; List < String > zone = new ArrayList < > ( prefix ) ; zone . add ( label ) ; if ( isTimeZone ( value ) ) { TimeZoneInfo info = parseTimeZoneObject ( value , zone ) ; zones . add ( info ) ; } else { zones . addAll ( parseTimeZoneInfo ( value , zone ) ) ; } } return zones ; }
|
Recursively parse the zone labels until we get to a zone info object .
|
5,310
|
private boolean isTimeZone ( JsonObject root ) { for ( String key : TIMEZONE_KEYS ) { if ( root . has ( key ) ) { return true ; } } return false ; }
|
Returns true if this object looks like it holds TimeZoneInfo otherwise false .
|
5,311
|
private void parseTimeZoneAliases ( JsonObject root ) { JsonObject node = resolve ( root , "supplemental" , "metadata" , "alias" , "zoneAlias" ) ; parseTimeZoneAlias ( node , Collections . emptyList ( ) ) ; }
|
Parses timezone aliases . These are timezone ids that have been removed for a given reason .
|
5,312
|
private void parseTimeZoneAlias ( JsonObject root , List < String > prefix ) { for ( String label : objectKeys ( root ) ) { JsonObject node = resolve ( root , label ) ; List < String > zone = new ArrayList < > ( prefix ) ; zone . add ( label ) ; String replacement = string ( node , "_replacement" , null ) ; if ( replacement != null ) { String name = StringUtils . join ( zone , '/' ) ; timezoneAliases . put ( name , replacement ) ; } else { parseTimeZoneAlias ( node , zone ) ; } } }
|
Recursively parse timezone aliases .
|
5,313
|
private void parseLanguageAliases ( JsonObject root ) { JsonObject node = resolve ( root , "supplemental" , "metadata" , "alias" , "languageAlias" ) ; for ( String tag : objectKeys ( node ) ) { JsonObject value = node . getAsJsonObject ( tag ) ; String replacement = string ( value , "_replacement" ) ; languageAliases . put ( tag , replacement ) ; } }
|
Parse the supplemental language aliases map .
|
5,314
|
private void parseTerritoryAliases ( JsonObject root ) { JsonObject node = resolve ( root , "supplemental" , "metadata" , "alias" , "territoryAlias" ) ; for ( String tag : objectKeys ( node ) ) { JsonObject value = node . getAsJsonObject ( tag ) ; String replacement = string ( value , "_replacement" ) ; territoryAliases . put ( tag , replacement ) ; } }
|
Parse the supplemental territory aliases map .
|
5,315
|
private void parseMetaZones ( JsonObject root ) { JsonObject node = resolve ( root , "supplemental" , "metaZones" , "metazoneInfo" , "timezone" ) ; for ( MetaZone zone : _parseMetaZones ( node , Collections . emptyList ( ) ) ) { metazones . put ( zone . zone , zone ) ; } }
|
Parse the metazone mapping from supplemental data .
|
5,316
|
private UnitData parseUnitData ( String code , JsonObject root ) { JsonObject node = resolve ( root , "main" , code , "units" ) ; UnitData data = new UnitData ( ) ; data . long_ = parseUnitPatterns ( node , "long" ) ; data . narrow = parseUnitPatterns ( node , "narrow" ) ; data . short_ = parseUnitPatterns ( node , "short" ) ; return data ; }
|
Parse unit formatting patterns .
|
5,317
|
private UnitPatterns parseUnitPatterns ( JsonObject node , String width ) { node = resolve ( node , width ) ; UnitPatterns result = new UnitPatterns ( ) ; result . compoundUnitPattern = string ( resolve ( node , "per" ) , "compoundUnitPattern" ) ; result . coordinatePatterns = new HashMap < > ( ) ; JsonObject parent = resolve ( node , "coordinateUnit" ) ; for ( String direction : objectKeys ( parent ) ) { result . coordinatePatterns . put ( direction , parent . get ( direction ) . getAsString ( ) ) ; } node . remove ( "per" ) ; node . remove ( "coordinateUnit" ) ; Set < PluralCategory > categories = new HashSet < > ( ) ; result . unitPatterns = new EnumMap < Unit , UnitData . UnitPattern > ( Unit . class ) ; for ( String unitKey : objectKeys ( node ) ) { JsonObject obj = node . get ( unitKey ) . getAsJsonObject ( ) ; Unit unit = null ; if ( unitKey . equalsIgnoreCase ( "temperature-generic" ) ) { unit = Unit . TEMPERATURE_GENERIC ; } else { int index = unitKey . indexOf ( '-' ) ; String identifier = unitKey . substring ( index + 1 ) ; unit = Unit . fromIdentifier ( identifier ) ; } if ( unit == null ) { throw new RuntimeException ( "unsupported unit found: " + unitKey ) ; } UnitPattern pattern = new UnitPattern ( ) ; pattern . displayName = string ( obj , "displayName" ) ; pattern . perUnitPattern = string ( obj , "perUnitPattern" , null ) ; pattern . patterns = new HashMap < > ( ) ; for ( String patternKey : objectKeys ( obj ) ) { if ( ! patternKey . startsWith ( "unitPattern-count-" ) ) { continue ; } String value = string ( obj , patternKey ) ; PluralCategory category = PluralCategory . fromString ( patternKey . split ( "-" ) [ 2 ] ) ; categories . add ( category ) ; pattern . patterns . put ( category , value ) ; } result . unitPatterns . put ( unit , pattern ) ; } for ( Unit unit : Unit . values ( ) ) { UnitPattern pattern = result . unitPatterns . get ( unit ) ; String other = pattern . patterns . get ( PluralCategory . OTHER ) ; for ( PluralCategory category : categories ) { if ( pattern . patterns . get ( category ) == null ) { pattern . patterns . put ( category , other ) ; } } } return result ; }
|
Parse unit patterns of a given width .
|
5,318
|
private JsonObject resolve ( JsonObject node , String ... keys ) { for ( String key : keys ) { JsonElement n = node . get ( key ) ; if ( n == null ) { return null ; } node = n . getAsJsonObject ( ) ; } return node ; }
|
Recursively resolve a series of keys against a JSON object . This is used to drill down into a JSON object tree .
|
5,319
|
private String string ( JsonObject node , String key , String default_ ) { JsonElement value = node . get ( key ) ; if ( value != null && value . isJsonPrimitive ( ) ) { return value . getAsString ( ) ; } return default_ ; }
|
Extract a value from a JSON object and convert it to a string .
|
5,320
|
private List < String > objectKeys ( JsonObject obj ) { List < String > keys = new ArrayList < > ( ) ; for ( Map . Entry < String , JsonElement > entry : obj . entrySet ( ) ) { keys . add ( entry . getKey ( ) ) ; } return keys ; }
|
Return a list of the keys on a JSON object .
|
5,321
|
public Rational multiply ( Rational other ) { return new Rational ( numerator . multiply ( other . numerator ) , denominator . multiply ( other . denominator ) ) ; }
|
Multiply this rational by another and return a new rational .
|
5,322
|
public BigDecimal compute ( RoundingMode mode ) { int scale = numerator . precision ( ) + denominator . precision ( ) ; scale = Math . max ( MIN_SCALE , Math . min ( MAX_SCALE , scale ) ) ; return numerator . divide ( denominator , scale , mode ) . stripTrailingZeros ( ) ; }
|
Divide the numerator by the denominator and return the resulting decimal number .
|
5,323
|
public BigDecimal compute ( int scale , RoundingMode mode ) { return numerator . divide ( denominator , scale , mode ) . stripTrailingZeros ( ) ; }
|
Divide the numerator by the denominator using the given scale and rounding mode and return the resulting decimal number .
|
5,324
|
public static boolean sameDay ( ZonedDateTime d1 , ZonedDateTime d2 ) { DateTimeField field = greatestDifference ( d1 , d2 ) ; return ( field != YEAR && field != MONTH && field != DAY ) ; }
|
Returns a boolean indicating the two date times are on the same day .
|
5,325
|
protected static MetaLocale parse ( String tag ) { if ( tag . indexOf ( '_' ) != - 1 ) { tag = tag . replace ( '_' , SEP ) ; } Maybe < Pair < MetaLocale , CharSequence > > result = P_LANGUAGE_TAG . parse ( tag ) ; if ( result . isNothing ( ) ) { throw new IllegalArgumentException ( "Failed to parse language tag: '" + tag + "'" ) ; } return result . get ( ) . _1 ; }
|
Internal method for parsing well - formed language tags .
|
5,326
|
public static MetaLocale fromLanguageTag ( String tag ) { if ( tag . indexOf ( '_' ) != - 1 ) { tag = tag . replace ( '_' , SEP ) ; } return fromJavaLocale ( java . util . Locale . forLanguageTag ( tag ) ) ; }
|
Constructs a MetaLocale from a language tag string .
|
5,327
|
public static MetaLocale fromJavaLocale ( java . util . Locale java ) { String language = java . getLanguage ( ) ; switch ( language ) { case "iw" : language = "he" ; break ; case "in" : language = "id" ; break ; case "ji" : language = "yi" ; break ; } return new MetaLocale ( language , java . getScript ( ) , java . getCountry ( ) , java . getVariant ( ) ) ; }
|
Constructs a MetaLocale from a Java Locale object .
|
5,328
|
protected void reset ( ) { fields [ LANGUAGE ] = null ; fields [ SCRIPT ] = null ; fields [ TERRITORY ] = null ; fields [ VARIANT ] = null ; }
|
Resets this locale to full undefined state .
|
5,329
|
private String render ( boolean compact ) { StringBuilder buf = new StringBuilder ( ) ; render ( buf , LANGUAGE , UNDEF_LANGUAGE , compact ) ; render ( buf , SCRIPT , UNDEF_SCRIPT , compact ) ; render ( buf , TERRITORY , UNDEF_TERRITORY , compact ) ; render ( buf , VARIANT , UNDEF_VARIANT , compact ) ; return buf . toString ( ) ; }
|
Render this locale to a string in compact or expanded form .
|
5,330
|
private void render ( StringBuilder buf , int key , String undef , boolean expanded ) { boolean force = key != VARIANT && ( key == LANGUAGE || expanded ) ; String value = fields [ key ] ; if ( value != null || force ) { if ( buf . length ( ) > 0 ) { buf . append ( SEP ) ; } buf . append ( value == null ? undef : value ) ; } }
|
Render a locale field to the buffer . Language field is always emitted and variant field is always omitted unless it has a value .
|
5,331
|
private String getField ( int key , String undef ) { String value = fields [ key ] ; return value == null ? undef : value ; }
|
Return a field s value or the undefined value .
|
5,332
|
private void setFieldIf ( int key , String value , String undef ) { if ( value == null ) { this . fields [ key ] = value ; } else { if ( key == LANGUAGE && value . equals ( "root" ) ) { this . fields [ key ] = null ; } else { this . fields [ key ] = value . equals ( "" ) || value . equals ( undef ) ? null : value ; } } }
|
All public set methods pass through here .
|
5,333
|
public void formatUnits ( List < UnitValue > values , StringBuilder destination , UnitFormatOptions options ) { int size = values . size ( ) ; for ( int i = 0 ; i < size ; i ++ ) { if ( i > 0 ) { destination . append ( ' ' ) ; } formatUnit ( values . get ( i ) , destination , options ) ; } }
|
Format a sequence of unit values .
|
5,334
|
public void formatUnit ( UnitValue value , StringBuilder destination , UnitFormatOptions options ) { BigDecimal n = value . amount ( ) ; boolean grouping = orDefault ( options . grouping ( ) , false ) ; NumberFormatContext ctx = new NumberFormatContext ( options , NumberFormatMode . DEFAULT ) ; NumberPattern numberPattern = select ( n , unitStandard ) ; ctx . set ( numberPattern ) ; BigDecimal q = ctx . adjust ( n ) ; NumberOperands operands = new NumberOperands ( q . toPlainString ( ) ) ; PluralCategory category = PLURAL_RULES . evalCardinal ( bundleId . language ( ) , operands ) ; Unit unit = value . unit ( ) ; List < FieldPattern . Node > unitPattern = null ; if ( unit != null ) { switch ( options . format ( ) ) { case LONG : unitPattern = getPattern_UNITS_LONG ( unit , category ) ; break ; case NARROW : unitPattern = getPattern_UNITS_NARROW ( unit , category ) ; break ; case SHORT : default : unitPattern = getPattern_UNITS_SHORT ( unit , category ) ; break ; } } DigitBuffer number = new DigitBuffer ( ) ; NumberFormattingUtils . format ( q , number , params , false , grouping , ctx . minIntDigits ( ) , numberPattern . format . primaryGroupingSize ( ) , numberPattern . format . secondaryGroupingSize ( ) ) ; if ( unitPattern == null ) { number . appendTo ( destination ) ; } else { DigitBuffer dbuf = new DigitBuffer ( ) ; for ( FieldPattern . Node node : unitPattern ) { if ( node instanceof FieldPattern . Text ) { dbuf . append ( ( ( FieldPattern . Text ) node ) . text ( ) ) ; } else if ( node instanceof Field ) { Field field = ( Field ) node ; if ( field . ch ( ) == '0' ) { format ( numberPattern , number , dbuf , null , null ) ; } } } dbuf . appendTo ( destination ) ; } }
|
Format a unit value .
|
5,335
|
protected static NumberPattern select ( BigDecimal n , NumberPattern [ ] patterns ) { return n . signum ( ) == - 1 ? patterns [ 1 ] : patterns [ 0 ] ; }
|
Select the appropriate pattern to format a positive or negative number .
|
5,336
|
protected static NumberPattern parse ( String pattern ) { return NUMBER_PATTERN_CACHE . computeIfAbsent ( pattern , s -> new NumberPatternParser ( ) . parse ( s ) ) ; }
|
Parse a string as a number pattern .
|
5,337
|
protected void format ( NumberPattern pattern , DigitBuffer number , DigitBuffer buf , String currency , String percent ) { boolean emitted = false ; List < Node > nodes = pattern . parsed ( ) ; int size = nodes . size ( ) ; for ( int i = 0 ; i < size ; i ++ ) { Node node = nodes . get ( i ) ; if ( node instanceof Text ) { buf . append ( ( ( Text ) node ) . text ( ) ) ; } else if ( node instanceof Format ) { buf . append ( number ) ; emitted = true ; } else if ( node instanceof Symbol ) { switch ( ( Symbol ) node ) { case MINUS : buf . append ( params . minus ) ; break ; case PERCENT : if ( percent != null ) { buf . append ( percent ) ; } break ; case CURRENCY : if ( currency == null || currency . isEmpty ( ) ) { break ; } if ( emitted ) { char firstCh = currency . charAt ( 0 ) ; if ( ! isSymbol ( firstCh ) && Character . isDigit ( buf . last ( ) ) ) { buf . append ( NBSP ) ; } buf . append ( currency ) ; } else { buf . append ( currency ) ; boolean nextFormat = i < ( size - 1 ) && nodes . get ( i + 1 ) instanceof Format ; char lastCh = currency . charAt ( currency . length ( ) - 1 ) ; if ( ! isSymbol ( lastCh ) && nextFormat ) { buf . append ( NBSP ) ; } } break ; } } } }
|
Formats a number using a pattern and options .
|
5,338
|
public static boolean isSymbol ( char ch ) { switch ( Character . getType ( ch ) ) { case Character . MATH_SYMBOL : case Character . CURRENCY_SYMBOL : case Character . MODIFIER_SYMBOL : case Character . OTHER_SYMBOL : return true ; default : return false ; } }
|
Returns true if the character is in any of the symbol categories .
|
5,339
|
Map < Class < ? extends Annotation > , Set < Locale > > getAnnotationToLocaleMapping ( ) { Map < Class < ? extends Annotation > , Set < Locale > > res = new HashMap < Class < ? extends Annotation > , Set < Locale > > ( ) ; for ( Entry < Class < ? extends Annotation > , C10NAnnotationBinder > entry : annotationBinders . entrySet ( ) ) { Set < Locale > locales = getLocales ( entry . getKey ( ) , res ) ; locales . add ( entry . getValue ( ) . getLocale ( ) ) ; } return res ; }
|
For each annotation bound in this configuration find all locales it has been bound to .
|
5,340
|
Set < Locale > getImplLocales ( Class < ? > c10nInterface ) { Set < Locale > res = new HashSet < Locale > ( ) ; C10NImplementationBinder < ? > binder = binders . get ( c10nInterface ) ; if ( binder != null ) { res . addAll ( binder . bindings . keySet ( ) ) ; } return res ; }
|
Find all locales that have explicit implementation class bindings for this c10n interface .
|
5,341
|
< T > T getBeanOrInstantiateProcessor ( final Class < ? extends T > c ) { T rv ; try { rv = this . applicationContext . getBean ( c ) ; } catch ( NoSuchBeanDefinitionException e ) { LOGGER . warn ( "Could not get processor from context, instantiating new instance instead" , e ) ; rv = ( T ) new BeanWrapperImpl ( c ) . getWrappedInstance ( ) ; } return rv ; }
|
This method tries to load a processor from the application context by class name .
|
5,342
|
@ ConditionalOnMissingBean ( CacheStrategy . class ) @ Order ( - 90 ) < K , V > CacheStrategy < K , V > defaultCacheStrategy ( ) { LOGGER . debug ( "Creating cache strategy 'LruMemoryCacheStrategy'" ) ; return new LruMemoryCacheStrategy < > ( ) ; }
|
This is the default Least recently used memory cache strategy of Wro4j which will be configured per default .
|
5,343
|
public long getDelay ( ) { long delayInMillis = ( long ) jsExecutor . executeScript ( DELAY_CALCULATION_JS ) ; if ( delayInMillis < minDelayInMillis ) { return minDelayInMillis ; } else if ( delayInMillis > maxDelayInMillis ) { return maxDelayInMillis ; } return delayInMillis ; }
|
Calculates the page loading time and returns the delay accordingly between the specified min - max range . If the calculated delay is smaller than the minimum it returns the minimum delay . If the calculated delay is higher than the maximum it returns the maximum delay .
|
5,344
|
public void feedRequest ( final CrawlRequest request , final boolean isCrawlSeed ) { if ( config . isOffsiteRequestFilteringEnabled ( ) ) { boolean inCrawlDomain = false ; for ( CrawlDomain allowedCrawlDomain : config . getAllowedCrawlDomains ( ) ) { if ( allowedCrawlDomain . contains ( request . getDomain ( ) ) ) { inCrawlDomain = true ; break ; } } if ( ! inCrawlDomain ) { return ; } } if ( config . isDuplicateRequestFilteringEnabled ( ) ) { String urlFingerprint = createFingerprintForUrl ( request . getRequestUrl ( ) ) ; if ( urlFingerprints . contains ( urlFingerprint ) ) { return ; } urlFingerprints . add ( urlFingerprint ) ; } CrawlCandidateBuilder builder = new CrawlCandidateBuilder ( request ) ; if ( ! isCrawlSeed ) { int crawlDepthLimit = config . getMaximumCrawlDepth ( ) ; int nextCrawlDepth = currentCandidate . getCrawlDepth ( ) + 1 ; if ( crawlDepthLimit != 0 && nextCrawlDepth > crawlDepthLimit ) { return ; } builder = builder . setRefererUrl ( currentCandidate . getRequestUrl ( ) ) . setCrawlDepth ( nextCrawlDepth ) ; } candidates . add ( builder . build ( ) ) ; }
|
Feeds a crawl request to the frontier .
|
5,345
|
private static String createFingerprintForUrl ( final URI url ) { StringBuilder truncatedUrl = new StringBuilder ( url . getHost ( ) ) ; String path = url . getPath ( ) ; if ( path != null ) { truncatedUrl . append ( path ) ; } String query = url . getQuery ( ) ; if ( query != null ) { truncatedUrl . append ( "?" ) ; String [ ] queryParams = url . getQuery ( ) . split ( "&" ) ; List < String > queryParamList = Arrays . asList ( queryParams ) ; queryParamList . stream ( ) . sorted ( String :: compareToIgnoreCase ) . forEachOrdered ( truncatedUrl :: append ) ; } return DigestUtils . sha256Hex ( truncatedUrl . toString ( ) ) ; }
|
Creates the fingerprint of the given URL . If the URL contains query parameters it sorts them . This way URLs with different order of query parameters get the same fingerprint .
|
5,346
|
@ SuppressWarnings ( "checkstyle:MissingSwitchDefault" ) private PriorityQueue < CrawlCandidate > createPriorityQueue ( ) { Function crawlDepthGetter = ( Function < CrawlCandidate , Integer > & Serializable ) CrawlCandidate :: getCrawlDepth ; Function priorityGetter = ( Function < CrawlCandidate , Integer > & Serializable ) CrawlCandidate :: getPriority ; switch ( config . getCrawlStrategy ( ) ) { case BREADTH_FIRST : Comparator breadthFirstComparator = Comparator . comparing ( crawlDepthGetter ) . thenComparing ( priorityGetter , Comparator . reverseOrder ( ) ) ; return new PriorityQueue < > ( breadthFirstComparator ) ; case DEPTH_FIRST : Comparator depthFirstComparator = Comparator . comparing ( crawlDepthGetter , Comparator . reverseOrder ( ) ) . thenComparing ( priorityGetter , Comparator . reverseOrder ( ) ) ; return new PriorityQueue < > ( depthFirstComparator ) ; } throw new IllegalArgumentException ( "Unsupported crawl strategy." ) ; }
|
Creates a priority queue using the strategy specified in the configuration .
|
5,347
|
public < T extends EventObject > void setDefaultEventCallback ( final CrawlEvent event , final Consumer < T > callback ) { defaultCallbacks . put ( event , callback ) ; }
|
Sets the default callback for the specific event .
|
5,348
|
public void addCustomEventCallback ( final CrawlEvent event , final PatternMatchingCallback callback ) { customCallbacks . computeIfAbsent ( event , key -> new ArrayList < > ( ) ) . add ( callback ) ; }
|
Associates a pattern matching callback with the specific event .
|
5,349
|
public < T extends EventObject > void call ( final CrawlEvent event , final T eventObject ) { if ( ! customCallbacks . containsKey ( event ) ) { ( ( Consumer < T > ) defaultCallbacks . get ( event ) ) . accept ( eventObject ) ; return ; } String requestUrl = eventObject . getCrawlCandidate ( ) . getRequestUrl ( ) . toString ( ) ; List < PatternMatchingCallback > applicableCallbacks = customCallbacks . get ( event ) . stream ( ) . filter ( callback -> callback . getUrlPattern ( ) . matcher ( requestUrl ) . matches ( ) ) . collect ( Collectors . toList ( ) ) ; if ( applicableCallbacks . isEmpty ( ) ) { ( ( Consumer < T > ) defaultCallbacks . get ( event ) ) . accept ( eventObject ) ; return ; } applicableCallbacks . stream ( ) . map ( PatternMatchingCallback :: getCallback ) . forEach ( op -> op . accept ( eventObject ) ) ; }
|
Invokes the default callback for the specific event if no custom callbacks are registered for it . Otherwise it calls all the associated callbacks whose pattern matches the URL of the request .
|
5,350
|
private void start ( final WebDriver webDriver , final boolean isResuming ) { try { Validate . validState ( isStopped , "The crawler is already running." ) ; this . webDriver = Validate . notNull ( webDriver , "The webdriver cannot be null." ) ; if ( webDriver instanceof HtmlUnitDriver && config . getCrawlDelayStrategy ( ) . equals ( CrawlDelayStrategy . ADAPTIVE ) ) { webDriver . get ( WebClient . ABOUT_BLANK ) ; } if ( ! isResuming ) { crawlFrontier = new CrawlFrontier ( config ) ; } cookieStore = new BasicCookieStore ( ) ; httpClient = HttpClientBuilder . create ( ) . setDefaultCookieStore ( cookieStore ) . useSystemProperties ( ) . build ( ) ; crawlDelayMechanism = createCrawlDelayMechanism ( ) ; isStopped = false ; run ( ) ; } finally { HttpClientUtils . closeQuietly ( httpClient ) ; if ( this . webDriver != null ) { this . webDriver . quit ( ) ; } isStopping = false ; isStopped = true ; } }
|
Performs initialization and runs the crawler .
|
5,351
|
public final void saveState ( final OutputStream outStream ) { Validate . validState ( crawlFrontier != null , "Cannot save state at this point." ) ; CrawlerState state = new CrawlerState ( ) ; state . putStateObject ( config ) ; state . putStateObject ( crawlFrontier ) ; SerializationUtils . serialize ( state , outStream ) ; }
|
Saves the current state of the crawler to the given output stream .
|
5,352
|
protected final void registerCustomEventCallback ( final CrawlEvent event , final PatternMatchingCallback callback ) { Validate . notNull ( event , "The event cannot be null." ) ; Validate . notNull ( callback , "The callback cannot be null." ) ; callbackManager . addCustomEventCallback ( event , callback ) ; }
|
Registers an operation which is invoked when the specific event occurs and the provided pattern matches the request URL .
|
5,353
|
protected final void crawl ( final CrawlRequest request ) { Validate . validState ( ! isStopped , "The crawler is not started. Maybe you meant to add this request as a crawl seed?" ) ; Validate . validState ( ! isStopping , "Cannot add request when the crawler is stopping." ) ; Validate . notNull ( request , "The request cannot be null." ) ; crawlFrontier . feedRequest ( request , false ) ; }
|
Feeds a crawl request to the crawler . The crawler should be running otherwise the request has to be added as a crawl seed instead .
|
5,354
|
protected final void downloadFile ( final URI source , final File destination ) throws IOException { Validate . validState ( ! isStopped , "Cannot download file when the crawler is not started." ) ; Validate . validState ( ! isStopping , "Cannot download file when the crawler is stopping." ) ; Validate . notNull ( source , "The source URL cannot be null." ) ; Validate . notNull ( destination , "The destination file cannot be null." ) ; HttpGet request = new HttpGet ( source ) ; try ( CloseableHttpResponse response = httpClient . execute ( request ) ) { HttpEntity entity = response . getEntity ( ) ; if ( entity != null ) { FileUtils . copyInputStreamToFile ( entity . getContent ( ) , destination ) ; } } }
|
Downloads the file specified by the URL .
|
5,355
|
private void run ( ) { onStart ( ) ; while ( ! isStopping && crawlFrontier . hasNextCandidate ( ) ) { CrawlCandidate currentCandidate = crawlFrontier . getNextCandidate ( ) ; String candidateUrl = currentCandidate . getRequestUrl ( ) . toString ( ) ; HttpClientContext context = HttpClientContext . create ( ) ; CloseableHttpResponse httpHeadResponse = null ; boolean isUnsuccessfulRequest = false ; try { httpHeadResponse = getHttpHeadResponse ( candidateUrl , context ) ; } catch ( IOException exception ) { callbackManager . call ( CrawlEvent . REQUEST_ERROR , new RequestErrorEvent ( currentCandidate , exception ) ) ; isUnsuccessfulRequest = true ; } if ( ! isUnsuccessfulRequest ) { String responseUrl = getFinalResponseUrl ( context , candidateUrl ) ; if ( responseUrl . equals ( candidateUrl ) ) { String responseMimeType = getResponseMimeType ( httpHeadResponse ) ; if ( responseMimeType . equals ( ContentType . TEXT_HTML . getMimeType ( ) ) ) { boolean isTimedOut = false ; TimeoutException timeoutException = null ; try { webDriver . get ( candidateUrl ) ; } catch ( TimeoutException exception ) { isTimedOut = true ; timeoutException = exception ; } syncHttpClientCookies ( ) ; if ( isTimedOut ) { callbackManager . call ( CrawlEvent . PAGE_LOAD_TIMEOUT , new PageLoadTimeoutEvent ( currentCandidate , timeoutException ) ) ; } else { String loadedPageUrl = webDriver . getCurrentUrl ( ) ; if ( ! loadedPageUrl . equals ( candidateUrl ) ) { handleRequestRedirect ( currentCandidate , loadedPageUrl ) ; } else { callbackManager . call ( CrawlEvent . PAGE_LOAD , new PageLoadEvent ( currentCandidate , webDriver ) ) ; } } } else { callbackManager . call ( CrawlEvent . NON_HTML_CONTENT , new NonHtmlContentEvent ( currentCandidate , responseMimeType ) ) ; } } else { handleRequestRedirect ( currentCandidate , responseUrl ) ; } } HttpClientUtils . closeQuietly ( httpHeadResponse ) ; performDelay ( ) ; } onStop ( ) ; }
|
Defines the workflow of the crawler .
|
5,356
|
@ SuppressWarnings ( "checkstyle:MissingSwitchDefault" ) private CrawlDelayMechanism createCrawlDelayMechanism ( ) { switch ( config . getCrawlDelayStrategy ( ) ) { case FIXED : return new FixedCrawlDelayMechanism ( config ) ; case RANDOM : return new RandomCrawlDelayMechanism ( config ) ; case ADAPTIVE : return new AdaptiveCrawlDelayMechanism ( config , ( JavascriptExecutor ) webDriver ) ; } throw new IllegalArgumentException ( "Unsupported crawl delay strategy." ) ; }
|
Creates the crawl delay mechanism according to the configuration .
|
5,357
|
private CloseableHttpResponse getHttpHeadResponse ( final String destinationUrl , final HttpClientContext context ) throws IOException { HttpHead request = new HttpHead ( destinationUrl ) ; return httpClient . execute ( request , context ) ; }
|
Sends an HTTP HEAD request to the given URL and returns the response .
|
5,358
|
private static String getFinalResponseUrl ( final HttpClientContext context , final String candidateUrl ) { List < URI > redirectLocations = context . getRedirectLocations ( ) ; if ( redirectLocations != null ) { return redirectLocations . get ( redirectLocations . size ( ) - 1 ) . toString ( ) ; } return candidateUrl ; }
|
If the HTTP HEAD request was redirected it returns the final redirected URL . If not it returns the original URL of the candidate .
|
5,359
|
private void handleRequestRedirect ( final CrawlCandidate currentCrawlCandidate , final String redirectedUrl ) { CrawlRequestBuilder builder = new CrawlRequestBuilder ( redirectedUrl ) . setPriority ( currentCrawlCandidate . getPriority ( ) ) ; currentCrawlCandidate . getMetadata ( ) . ifPresent ( builder :: setMetadata ) ; CrawlRequest redirectedRequest = builder . build ( ) ; crawlFrontier . feedRequest ( redirectedRequest , false ) ; callbackManager . call ( CrawlEvent . REQUEST_REDIRECT , new RequestRedirectEvent ( currentCrawlCandidate , redirectedRequest ) ) ; }
|
Creates a crawl request for the redirected URL feeds it to the crawler and calls the appropriate event callback .
|
5,360
|
private void syncHttpClientCookies ( ) { webDriver . manage ( ) . getCookies ( ) . stream ( ) . map ( CookieConverter :: convertToHttpClientCookie ) . forEach ( cookieStore :: addCookie ) ; }
|
Copies all the Selenium cookies for the current domain to the HTTP client cookie store .
|
5,361
|
private void performDelay ( ) { try { TimeUnit . MILLISECONDS . sleep ( crawlDelayMechanism . getDelay ( ) ) ; } catch ( InterruptedException ex ) { Thread . currentThread ( ) . interrupt ( ) ; isStopping = true ; } }
|
Delays the next request .
|
5,362
|
protected void onPageLoad ( final PageLoadEvent event ) { LOGGER . log ( Level . INFO , "onPageLoad: {0}" , event . getCrawlCandidate ( ) . getRequestUrl ( ) ) ; }
|
Callback which gets called when the browser loads the page .
|
5,363
|
protected void onNonHtmlContent ( final NonHtmlContentEvent event ) { LOGGER . log ( Level . INFO , "onNonHtmlContent: {0}" , event . getCrawlCandidate ( ) . getRequestUrl ( ) ) ; }
|
Callback which gets called when the content type is not HTML .
|
5,364
|
protected void onRequestError ( final RequestErrorEvent event ) { LOGGER . log ( Level . INFO , "onRequestError: {0}" , event . getCrawlCandidate ( ) . getRequestUrl ( ) ) ; }
|
Callback which gets called when a request error occurs .
|
5,365
|
protected void onRequestRedirect ( final RequestRedirectEvent event ) { LOGGER . log ( Level . INFO , "onRequestRedirect: {0} -> {1}" , new Object [ ] { event . getCrawlCandidate ( ) . getRequestUrl ( ) , event . getRedirectedCrawlRequest ( ) . getRequestUrl ( ) } ) ; }
|
Callback which gets called when a request is redirected .
|
5,366
|
protected void onPageLoadTimeout ( final PageLoadTimeoutEvent event ) { LOGGER . log ( Level . INFO , "onPageLoadTimeout: {0}" , event . getCrawlCandidate ( ) . getRequestUrl ( ) ) ; }
|
Callback which gets called when the page does not load in the browser within the timeout period .
|
5,367
|
public boolean contains ( final InternetDomainName domain ) { ImmutableList < String > otherDomainParts = domain . parts ( ) ; if ( parts . size ( ) > otherDomainParts . size ( ) ) { return false ; } otherDomainParts = otherDomainParts . reverse ( ) . subList ( 0 , parts . size ( ) ) ; return parts . reverse ( ) . equals ( otherDomainParts ) ; }
|
Indicates if this crawl domain contains the specific internet domain .
|
5,368
|
public static BasicClientCookie convertToHttpClientCookie ( final Cookie seleniumCookie ) { BasicClientCookie httpClientCookie = new BasicClientCookie ( seleniumCookie . getName ( ) , seleniumCookie . getValue ( ) ) ; httpClientCookie . setDomain ( seleniumCookie . getDomain ( ) ) ; httpClientCookie . setPath ( seleniumCookie . getPath ( ) ) ; httpClientCookie . setExpiryDate ( seleniumCookie . getExpiry ( ) ) ; httpClientCookie . setSecure ( seleniumCookie . isSecure ( ) ) ; if ( seleniumCookie . isHttpOnly ( ) ) { httpClientCookie . setAttribute ( HTTP_ONLY_ATTRIBUTE , StringUtils . EMPTY ) ; } return httpClientCookie ; }
|
Converts a Selenium cookie to a HTTP client one .
|
5,369
|
public List < String > findUrlsInPage ( final PageLoadEvent event ) { Set < String > foundUrls = new HashSet < > ( ) ; Set < WebElement > extractedElements = locatingMechanisms . stream ( ) . map ( event . getWebDriver ( ) :: findElements ) . flatMap ( List :: stream ) . collect ( Collectors . toSet ( ) ) ; extractedElements . forEach ( ( WebElement element ) -> { attributes . stream ( ) . map ( element :: getAttribute ) . filter ( StringUtils :: isNotBlank ) . map ( this :: findUrlsInAttributeValue ) . flatMap ( List :: stream ) . forEach ( foundUrls :: add ) ; } ) ; return foundUrls . stream ( ) . collect ( Collectors . toList ( ) ) ; }
|
Returns a list of validated URLs found in the page s HTML source .
|
5,370
|
private List < String > findUrlsInAttributeValue ( final String attributeValue ) { List < String > foundUrls = new ArrayList < > ( ) ; urlPatterns . stream ( ) . map ( ( Pattern urlPattern ) -> urlPattern . matcher ( attributeValue ) ) . forEach ( ( Matcher urlPatternMatcher ) -> { while ( urlPatternMatcher . find ( ) ) { String foundUrl = urlPatternMatcher . group ( ) . trim ( ) ; if ( validator . test ( foundUrl ) ) { foundUrls . add ( foundUrl ) ; } } } ) ; return foundUrls ; }
|
Returns a list of validated URLs found in the attribute s value .
|
5,371
|
public < T extends Serializable > T getStateObject ( final Class < T > stateObjectClass ) { return ( T ) stateObjects . get ( stateObjectClass ) ; }
|
Returns the state object specified by its class .
|
5,372
|
public static void checkNotEmpty ( CharSequence str , String message ) { if ( str == null || str . length ( ) == 0 ) { throw new IllegalArgumentException ( message ) ; } }
|
Throws an exception with a message when CharSequence is null
|
5,373
|
public CharSequence format ( Formatter formatter ) { CharSequence input = format ( ) ; return formatter . format ( String . valueOf ( input ) ) ; }
|
Returns CharSequence formatted with custom formatter implementation
|
5,374
|
public CharSequence format ( ) { if ( pieces . isEmpty ( ) ) { return input ; } String target ; for ( Piece piece : pieces ) { target = BRACE_START + piece . getKey ( ) + BRACE_END ; input = input . replace ( target , String . valueOf ( piece . getValue ( ) ) ) ; } return input ; }
|
Returns formatted CharSequence without additional operations
|
5,375
|
public EntityBuilder setHref ( String href ) { if ( StringUtils . isBlank ( href ) ) { throw new IllegalArgumentException ( "href cannot be null or empty." ) ; } addStep ( "setHref" , new Object [ ] { href } ) ; isEmbedded = true ; return this ; }
|
Set the href of the entity to be built . This method can be called many times but only the value of the last call is used in the built entity . This is a required property if this entity is an embedded link as specified by the Siren specification . If set then this entity will be considered an embedded link .
|
5,376
|
public EntityBuilder addProperty ( String name , Object value ) { if ( StringUtils . isBlank ( name ) ) { throw new IllegalArgumentException ( "name cannot be null or empty." ) ; } addStep ( "_addProperty" , new Object [ ] { name , value } , new Class < ? > [ ] { String . class , Object . class } , true ) ; return this ; }
|
Adds a single property to the entity to be built . Properties are optional according to the Siren specification .
|
5,377
|
public EntityBuilder addProperties ( Map < String , Object > properties ) { if ( MapUtils . isEmpty ( properties ) ) { throw new IllegalArgumentException ( "properties cannot be null or empty." ) ; } for ( String key : properties . keySet ( ) ) { addProperty ( key , properties . get ( key ) ) ; } return this ; }
|
Adds a map of properties to the entity to be built . Properties are optional according to the Siren specification .
|
5,378
|
public EntityBuilder addSubEntity ( Entity subEntity ) { if ( subEntity == null ) { throw new IllegalArgumentException ( "subEntity cannot be null." ) ; } addStep ( "_addEntity" , new Object [ ] { subEntity } , true ) ; return this ; }
|
Add a sub entity to the entity to be built . Sub entities are optional according to the Siren specification .
|
5,379
|
public EntityBuilder addSubEntities ( List < Entity > entities ) { if ( entities == null ) { throw new IllegalArgumentException ( "entities cannot be null." ) ; } for ( Entity entity : entities ) { addSubEntity ( entity ) ; } return this ; }
|
Add a list of sub entities to the entity to be built . Sub entities are optional according to the Siren specification .
|
5,380
|
public EntityBuilder addLink ( Link link ) { if ( link == null ) { throw new IllegalArgumentException ( "link cannot be null." ) ; } addStep ( "_addLink" , new Object [ ] { link } , true ) ; return this ; }
|
Add a link to the entity to be built . Links are optional according to the Siren specification however an entity should always have a self link to be considered HATEAOS compliant .
|
5,381
|
public EntityBuilder addLinks ( List < Link > links ) { if ( links == null ) { throw new IllegalArgumentException ( "links cannot be null." ) ; } for ( Link link : links ) { addLink ( link ) ; } return this ; }
|
Adds list of links to the entity to be built . Links are optional according to the Siren specification however an entity should always have a self link to be considered HATEAOS compliant .
|
5,382
|
public EntityBuilder addAction ( Action action ) { if ( action == null ) { throw new IllegalArgumentException ( "action cannot be null." ) ; } addStep ( "_addAction" , new Object [ ] { action } , true ) ; return this ; }
|
Add an action to the entity to be built . Actions are options according to the Siren specification .
|
5,383
|
public EntityBuilder addActions ( List < Action > actions ) { if ( actions == null ) { throw new IllegalArgumentException ( "actions cannot be null." ) ; } for ( Action action : actions ) { addAction ( action ) ; } return this ; }
|
Add a list of actions to the entity to be built . Actions are options according to the Siren specification .
|
5,384
|
private void validateSubEntities ( Entity obj ) { String relRequired = "Sub entities are required to have a <rel> property set." ; String hrefReqForEmbed = "Sub entities that are embedded links are required to have a <href> property set." ; if ( ! CollectionUtils . isEmpty ( obj . getEntities ( ) ) ) { for ( Entity e : obj . getEntities ( ) ) { if ( e . getRel ( ) == null || ArrayUtils . isEmpty ( e . getRel ( ) ) ) { throw new Siren4JBuilderValidationException ( "entities" , obj . getClass ( ) , relRequired ) ; } if ( ( e instanceof EmbeddedEntityImpl ) && StringUtils . isBlank ( e . getHref ( ) ) ) { throw new Siren4JBuilderValidationException ( "entities" , obj . getClass ( ) , hrefReqForEmbed ) ; } } } }
|
Validate sub entities ensuring the existence of a relationship and if an embedded link then ensure the existence of an href .
|
5,385
|
private void handleSetProperties ( Object obj , Class < ? > clazz , Entity entity , List < ReflectedInfo > fieldInfo ) throws Siren4JConversionException { if ( ! MapUtils . isEmpty ( entity . getProperties ( ) ) ) { for ( String key : entity . getProperties ( ) . keySet ( ) ) { if ( key . startsWith ( Siren4J . CLASS_RESERVED_PROPERTY ) ) { continue ; } ReflectedInfo info = ReflectionUtils . getFieldInfoByEffectiveName ( fieldInfo , key ) ; if ( info == null ) { info = ReflectionUtils . getFieldInfoByName ( fieldInfo , key ) ; } if ( info != null ) { Object val = entity . getProperties ( ) . get ( key ) ; try { ReflectionUtils . setFieldValue ( obj , info , val ) ; } catch ( Siren4JException e ) { throw new Siren4JConversionException ( e ) ; } } else if ( isErrorOnMissingProperty ( ) && ! ( obj instanceof Collection && key . equals ( "size" ) ) ) { throw new Siren4JConversionException ( "Unable to find field: " + key + " for class: " + clazz . getName ( ) ) ; } } } }
|
Sets field value for an entity s property field .
|
5,386
|
@ SuppressWarnings ( { "rawtypes" , "unchecked" } ) private void handleSetSubEntities ( Object obj , Class < ? > clazz , Entity entity , List < ReflectedInfo > fieldInfo ) throws Siren4JConversionException { if ( ! CollectionUtils . isEmpty ( entity . getEntities ( ) ) ) { for ( Entity ent : entity . getEntities ( ) ) { if ( StringUtils . isNotBlank ( ent . getHref ( ) ) ) { continue ; } String [ ] rel = ent . getRel ( ) ; if ( ArrayUtils . isEmpty ( rel ) ) { throw new Siren4JConversionException ( "No relationship set on sub entity. Can't go on." ) ; } String fieldKey = rel . length == 1 ? rel [ 0 ] : ArrayUtils . toString ( rel ) ; ReflectedInfo info = ReflectionUtils . getFieldInfoByEffectiveName ( fieldInfo , fieldKey ) ; if ( info != null ) { try { Object subObj = toObject ( ent ) ; if ( subObj != null ) { if ( subObj . getClass ( ) . equals ( CollectionResource . class ) ) { ReflectionUtils . setFieldValue ( obj , info , subObj ) ; continue ; } if ( isCollection ( obj , info . getField ( ) ) ) { try { Collection coll = ( Collection ) info . getField ( ) . get ( obj ) ; if ( coll == null ) { coll = new CollectionResource ( ) ; ReflectionUtils . setFieldValue ( obj , info , coll ) ; } coll . add ( subObj ) ; } catch ( Exception e ) { throw new Siren4JConversionException ( e ) ; } } else { ReflectionUtils . setFieldValue ( obj , info , subObj ) ; } } } catch ( Siren4JException e ) { throw new Siren4JConversionException ( e ) ; } } else { throw new Siren4JConversionException ( "Unable to find field: " + fieldKey + " for class: " + clazz . getName ( ) ) ; } } } }
|
Sets field value for an entity s sub entities field .
|
5,387
|
private void handleSubEntity ( EntityBuilder builder , Object obj , Field currentField , List < ReflectedInfo > fieldInfo ) throws Siren4JException { Siren4JSubEntity subAnno = getSubEntityAnnotation ( currentField , fieldInfo ) ; if ( subAnno != null ) { if ( isCollection ( obj , currentField ) ) { Collection < ? > coll = ( Collection < ? > ) ReflectionUtils . getFieldValue ( currentField , obj ) ; if ( coll != null ) { for ( Object o : coll ) { builder . addSubEntity ( toEntity ( o , currentField , obj , fieldInfo ) ) ; } } } else { Object subObj = ReflectionUtils . getFieldValue ( currentField , obj ) ; if ( subObj != null ) { builder . addSubEntity ( toEntity ( subObj , currentField , obj , fieldInfo ) ) ; } } } }
|
Handles sub entities .
|
5,388
|
private String resolveUri ( String rawUri , EntityContext context , boolean handleURIOverride ) throws Siren4JException { String resolvedUri = rawUri ; String baseUri = null ; boolean fullyQualified = false ; if ( context . getCurrentObject ( ) instanceof Resource ) { Resource resource = ( Resource ) context . getCurrentObject ( ) ; baseUri = resource . getBaseUri ( ) ; fullyQualified = resource . isFullyQualifiedLinks ( ) == null ? false : resource . isFullyQualifiedLinks ( ) ; String override = resource . getOverrideUri ( ) ; if ( handleURIOverride && StringUtils . isNotBlank ( override ) ) { resolvedUri = override ; } } resolvedUri = handleTokenReplacement ( resolvedUri , context ) ; if ( fullyQualified && StringUtils . isNotBlank ( baseUri ) && ! isAbsoluteUri ( resolvedUri ) ) { StringBuffer sb = new StringBuffer ( ) ; sb . append ( baseUri . endsWith ( "/" ) ? baseUri . substring ( 0 , baseUri . length ( ) - 1 ) : baseUri ) ; sb . append ( resolvedUri . startsWith ( "/" ) ? resolvedUri : "/" + resolvedUri ) ; resolvedUri = sb . toString ( ) ; } return resolvedUri ; }
|
Resolves the raw uri by replacing field tokens with the actual data .
|
5,389
|
private String handleTokenReplacement ( String str , EntityContext context ) throws Siren4JException { String result = "" ; result = ReflectionUtils . replaceFieldTokens ( context . getParentObject ( ) , str , context . getParentFieldInfo ( ) , true ) ; result = ReflectionUtils . flattenReservedTokens ( ReflectionUtils . replaceFieldTokens ( context . getCurrentObject ( ) , result , context . getCurrentFieldInfo ( ) , false ) ) ; return result ; }
|
Helper method to do token replacement for strings .
|
5,390
|
private Siren4JSubEntity getSubEntityAnnotation ( Field currentField , List < ReflectedInfo > fieldInfo ) { Siren4JSubEntity result = null ; result = currentField . getAnnotation ( Siren4JSubEntity . class ) ; if ( result == null && fieldInfo != null ) { ReflectedInfo info = ReflectionUtils . getFieldInfoByName ( fieldInfo , currentField . getName ( ) ) ; if ( info != null && info . getGetter ( ) != null ) { result = info . getGetter ( ) . getAnnotation ( Siren4JSubEntity . class ) ; } } return result ; }
|
Helper to retrieve a sub entity annotation from either the field itself or the getter . If an annotation exists on both then the field wins .
|
5,391
|
private void handleSelfLink ( EntityBuilder builder , String resolvedUri ) { if ( StringUtils . isBlank ( resolvedUri ) ) { return ; } Link link = LinkBuilder . newInstance ( ) . setRelationship ( Link . RELATIONSHIP_SELF ) . setHref ( resolvedUri ) . build ( ) ; builder . addLink ( link ) ; }
|
Add the self link to the entity .
|
5,392
|
private void handleBaseUriLink ( EntityBuilder builder , String baseUri ) { if ( StringUtils . isBlank ( baseUri ) ) { return ; } Link link = LinkBuilder . newInstance ( ) . setRelationship ( Link . RELATIONSHIP_BASEURI ) . setHref ( baseUri ) . build ( ) ; builder . addLink ( link ) ; }
|
Add the baseUri link to the entity if the baseUri is set on the entity .
|
5,393
|
private void handleEntityLinks ( EntityBuilder builder , EntityContext context ) throws Siren4JException { Class < ? > clazz = context . getCurrentObject ( ) . getClass ( ) ; Map < String , Link > links = new HashMap < String , Link > ( ) ; Siren4JEntity entity = clazz . getAnnotation ( Siren4JEntity . class ) ; if ( entity != null && ArrayUtils . isNotEmpty ( entity . links ( ) ) ) { for ( Siren4JLink l : entity . links ( ) ) { if ( evaluateConditional ( l . condition ( ) , context ) ) { links . put ( ArrayUtils . toString ( l . rel ( ) ) , annotationToLink ( l , context ) ) ; } } } if ( context . getParentField ( ) != null ) { Siren4JSubEntity subentity = context . getParentField ( ) . getAnnotation ( Siren4JSubEntity . class ) ; if ( subentity != null && ArrayUtils . isNotEmpty ( subentity . links ( ) ) ) { for ( Siren4JLink l : subentity . links ( ) ) { if ( evaluateConditional ( l . condition ( ) , context ) ) { links . put ( ArrayUtils . toString ( l . rel ( ) ) , annotationToLink ( l , context ) ) ; } } } } Collection < Link > resourceLinks = context . getCurrentObject ( ) instanceof Resource ? ( ( Resource ) context . getCurrentObject ( ) ) . getEntityLinks ( ) : null ; if ( resourceLinks != null ) { for ( Link l : resourceLinks ) { links . put ( ArrayUtils . toString ( l . getRel ( ) ) , l ) ; } } for ( Link l : links . values ( ) ) { l . setHref ( resolveUri ( l . getHref ( ) , context , false ) ) ; builder . addLink ( l ) ; } }
|
Handles getting all entity links both dynamically set and via annotations and merges them together overriding with the proper precedence order which is Dynamic > SubEntity > Entity . Href and uri s are resolved with the correct data bound in .
|
5,394
|
private void handleEntityActions ( EntityBuilder builder , EntityContext context ) throws Siren4JException { Class < ? > clazz = context . getCurrentObject ( ) . getClass ( ) ; Map < String , Action > actions = new HashMap < String , Action > ( ) ; Siren4JEntity entity = clazz . getAnnotation ( Siren4JEntity . class ) ; if ( entity != null && ArrayUtils . isNotEmpty ( entity . actions ( ) ) ) { for ( Siren4JAction a : entity . actions ( ) ) { if ( evaluateConditional ( a . condition ( ) , context ) ) { actions . put ( a . name ( ) , annotationToAction ( a , context ) ) ; } } } if ( context . getParentField ( ) != null ) { Siren4JSubEntity subentity = context . getParentField ( ) . getAnnotation ( Siren4JSubEntity . class ) ; if ( subentity != null && ArrayUtils . isNotEmpty ( subentity . actions ( ) ) ) { for ( Siren4JAction a : subentity . actions ( ) ) { if ( evaluateConditional ( a . condition ( ) , context ) ) { actions . put ( a . name ( ) , annotationToAction ( a , context ) ) ; } } } } Collection < Action > resourceLinks = context . getCurrentObject ( ) instanceof Resource ? ( ( Resource ) context . getCurrentObject ( ) ) . getEntityActions ( ) : null ; if ( resourceLinks != null ) { for ( Action a : resourceLinks ) { actions . put ( a . getName ( ) , a ) ; } } for ( Action a : actions . values ( ) ) { a . setHref ( resolveUri ( a . getHref ( ) , context , false ) ) ; builder . addAction ( a ) ; } }
|
Handles getting all entity actions both dynamically set and via annotations and merges them together overriding with the proper precedence order which is Dynamic > SubEntity > Entity . Href and uri s are resolved with the correct data bound in .
|
5,395
|
private boolean evaluateConditional ( Siren4JCondition condition , EntityContext context ) { boolean result = true ; if ( condition != null && ! ( "null" . equals ( condition . name ( ) ) ) ) { result = false ; Object val = null ; ConditionFactory factory = ConditionFactory . getInstance ( ) ; Condition cond = factory . getCondition ( condition . logic ( ) ) ; Object obj = condition . name ( ) . startsWith ( "parent." ) ? context . getParentObject ( ) : context . getCurrentObject ( ) ; String name = condition . name ( ) . startsWith ( "parent." ) ? condition . name ( ) . substring ( 7 ) : condition . name ( ) ; if ( obj == null ) { throw new Siren4JRuntimeException ( "No object found. Conditional probably references a parent but does not have a parent: " + condition . name ( ) ) ; } if ( condition . type ( ) . equals ( Type . METHOD ) ) { try { Method method = ReflectionUtils . findMethod ( obj . getClass ( ) , name , null ) ; if ( method != null ) { method . setAccessible ( true ) ; val = method . invoke ( obj , new Object [ ] { } ) ; result = cond . evaluate ( val ) ; } else { throw new Siren4JException ( "Method referenced in condition does not exist: " + condition . name ( ) ) ; } } catch ( Exception e ) { throw new Siren4JRuntimeException ( e ) ; } } else { try { Field field = ReflectionUtils . findField ( obj . getClass ( ) , name ) ; if ( field != null ) { field . setAccessible ( true ) ; val = field . get ( obj ) ; result = cond . evaluate ( val ) ; } else { throw new Siren4JException ( "Field referenced in condition does not exist: " + condition . name ( ) ) ; } } catch ( Exception e ) { throw new Siren4JRuntimeException ( e ) ; } } } return result ; }
|
Evaluates a value against its specified conditional .
|
5,396
|
private Link annotationToLink ( Siren4JLink linkAnno , EntityContext context ) { LinkBuilder builder = LinkBuilder . newInstance ( ) . setRelationship ( linkAnno . rel ( ) ) . setHref ( linkAnno . href ( ) ) ; if ( StringUtils . isNotBlank ( linkAnno . title ( ) ) ) { builder . setTitle ( linkAnno . title ( ) ) ; } if ( ArrayUtils . isNotEmpty ( linkAnno . linkClass ( ) ) ) { builder . setComponentClass ( linkAnno . linkClass ( ) ) ; } return builder . build ( ) ; }
|
Convert a link annotation to an actual link . The href will not be resolved in the instantiated link this will need to be post processed .
|
5,397
|
private Action annotationToAction ( Siren4JAction actionAnno , EntityContext context ) throws Siren4JException { ActionBuilder builder = ActionBuilder . newInstance ( ) ; builder . setName ( actionAnno . name ( ) ) . setHref ( actionAnno . href ( ) ) . setMethod ( actionAnno . method ( ) ) ; if ( ArrayUtils . isNotEmpty ( actionAnno . actionClass ( ) ) ) { builder . setComponentClass ( actionAnno . actionClass ( ) ) ; } if ( StringUtils . isNotBlank ( actionAnno . title ( ) ) ) { builder . setTitle ( actionAnno . title ( ) ) ; } if ( StringUtils . isNotBlank ( actionAnno . type ( ) ) ) { builder . setType ( actionAnno . type ( ) ) ; } if ( ArrayUtils . isNotEmpty ( actionAnno . fields ( ) ) ) { for ( Siren4JActionField f : actionAnno . fields ( ) ) { builder . addField ( annotationToField ( f , context ) ) ; } } if ( ArrayUtils . isNotEmpty ( actionAnno . urlParams ( ) ) ) { for ( Siren4JActionField f : actionAnno . urlParams ( ) ) { builder . addUrlParam ( annotationToField ( f , context ) ) ; } } if ( ArrayUtils . isNotEmpty ( actionAnno . headers ( ) ) ) { for ( Siren4JActionField f : actionAnno . headers ( ) ) { builder . addHeader ( annotationToField ( f , context ) ) ; } } if ( ArrayUtils . isNotEmpty ( actionAnno . metaData ( ) ) ) { Map < String , String > metaData = new HashMap ( ) ; for ( Siren4JMetaData mdAnno : actionAnno . metaData ( ) ) { metaData . put ( mdAnno . key ( ) , handleTokenReplacement ( mdAnno . value ( ) , context ) ) ; } builder . setMetaData ( metaData ) ; } return builder . build ( ) ; }
|
Convert an action annotation to an actual action . The href will not be resolved in the instantiated action this will need to be post processed .
|
5,398
|
private boolean skipProperty ( Object obj , Field field ) throws Siren4JException { boolean skip = false ; Class < ? > clazz = obj . getClass ( ) ; Include inc = Include . ALWAYS ; Siren4JInclude typeInclude = clazz . getAnnotation ( Siren4JInclude . class ) ; if ( typeInclude != null ) { inc = typeInclude . value ( ) ; } Siren4JInclude fieldInclude = field . getAnnotation ( Siren4JInclude . class ) ; if ( fieldInclude != null ) { inc = fieldInclude . value ( ) ; } try { Object val = field . get ( obj ) ; switch ( inc ) { case NON_EMPTY : if ( val != null ) { if ( String . class . equals ( field . getType ( ) ) ) { skip = StringUtils . isBlank ( ( String ) val ) ; } else if ( CollectionResource . class . equals ( field . getType ( ) ) ) { skip = ( ( CollectionResource < ? > ) val ) . isEmpty ( ) ; } } else { skip = true ; } break ; case NON_NULL : if ( val == null ) { skip = true ; } break ; case ALWAYS : } } catch ( Exception e ) { throw new Siren4JRuntimeException ( e ) ; } return skip ; }
|
Determine if the property or entity should be skipped based on any existing include policy . The TYPE annotation is checked first and then the field annotation the field annotation takes precedence .
|
5,399
|
public String [ ] getEntityClass ( Object obj , String name , Siren4JEntity entityAnno ) { Class < ? > clazz = obj . getClass ( ) ; String [ ] compClass = entityAnno == null ? null : entityAnno . entityClass ( ) ; if ( compClass != null && ! ArrayUtils . isEmpty ( compClass ) ) { return compClass ; } List < String > entityClass = new ArrayList < String > ( ) ; entityClass . add ( StringUtils . defaultString ( name , clazz . getName ( ) ) ) ; if ( obj instanceof CollectionResource ) { String tag = getCollectionClassTag ( ) ; if ( StringUtils . isNotBlank ( tag ) ) { entityClass . add ( tag ) ; } } return entityClass . toArray ( new String [ ] { } ) ; }
|
Determine entity class by first using the name set on the Siren entity and then if not found using the actual class name though it is preferable to use the first option to not tie to a language specific class .
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.