idx
int64
0
165k
question
stringlengths
73
5.81k
target
stringlengths
5
918
129,000
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 .
129,001
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 .
129,002
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 ( replac...
Recursively parse timezone aliases .
129,003
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 ....
Parse the supplemental language aliases map .
129,004
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" ) ; territoryAliase...
Parse the supplemental territory aliases map .
129,005
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 .
129,006
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 , "sh...
Parse unit formatting patterns .
129,007
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 = ...
Parse unit patterns of a given width .
129,008
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 .
129,009
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 .
129,010
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 .
129,011
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 .
129,012
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 .
129,013
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 .
129,014
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 .
129,015
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: '" + t...
Internal method for parsing well - formed language tags .
129,016
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 .
129,017
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 . ge...
Constructs a MetaLocale from a Java Locale object .
129,018
protected void reset ( ) { fields [ LANGUAGE ] = null ; fields [ SCRIPT ] = null ; fields [ TERRITORY ] = null ; fields [ VARIANT ] = null ; }
Resets this locale to full undefined state .
129,019
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 . toS...
Render this locale to a string in compact or expanded form .
129,020
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 .
129,021
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 .
129,022
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 .
129,023
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 .
129,024
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 numberPatt...
Format a unit value .
129,025
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 .
129,026
protected static NumberPattern parse ( String pattern ) { return NUMBER_PATTERN_CACHE . computeIfAbsent ( pattern , s -> new NumberPatternParser ( ) . parse ( s ) ) ; }
Parse a string as a number pattern .
129,027
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...
Formats a number using a pattern and options .
129,028
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 .
129,029
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 ....
For each annotation bound in this configuration find all locales it has been bound to .
129,030
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 .
129,031
< 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 ) . ...
This method tries to load a processor from the application context by class name .
129,032
@ 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 .
129,033
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 .
129,034
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 ( ) ) ) { in...
Feeds a crawl request to the frontier .
129,035
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 ( "?" ) ; S...
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 .
129,036
@ SuppressWarnings ( "checkstyle:MissingSwitchDefault" ) private PriorityQueue < CrawlCandidate > createPriorityQueue ( ) { Function crawlDepthGetter = ( Function < CrawlCandidate , Integer > & Serializable ) CrawlCandidate :: getCrawlDepth ; Function priorityGetter = ( Function < CrawlCandidate , Integer > & Serializa...
Creates a priority queue using the strategy specified in the configuration .
129,037
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 .
129,038
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 .
129,039
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 ( ) . toS...
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 .
129,040
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...
Performs initialization and runs the crawler .
129,041
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 , outStr...
Saves the current state of the crawler to the given output stream .
129,042
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 .
129,043
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 reque...
Feeds a crawl request to the crawler . The crawler should be running otherwise the request has to be added as a crawl seed instead .
129,044
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 ( sour...
Downloads the file specified by the URL .
129,045
private void run ( ) { onStart ( ) ; while ( ! isStopping && crawlFrontier . hasNextCandidate ( ) ) { CrawlCandidate currentCandidate = crawlFrontier . getNextCandidate ( ) ; String candidateUrl = currentCandidate . getRequestUrl ( ) . toString ( ) ; HttpClientContext context = HttpClientContext . create ( ) ; Closeabl...
Defines the workflow of the crawler .
129,046
@ 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 Ad...
Creates the crawl delay mechanism according to the configuration .
129,047
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 .
129,048
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 .
129,049
private void handleRequestRedirect ( final CrawlCandidate currentCrawlCandidate , final String redirectedUrl ) { CrawlRequestBuilder builder = new CrawlRequestBuilder ( redirectedUrl ) . setPriority ( currentCrawlCandidate . getPriority ( ) ) ; currentCrawlCandidate . getMetadata ( ) . ifPresent ( builder :: setMetadat...
Creates a crawl request for the redirected URL feeds it to the crawler and calls the appropriate event callback .
129,050
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 .
129,051
private void performDelay ( ) { try { TimeUnit . MILLISECONDS . sleep ( crawlDelayMechanism . getDelay ( ) ) ; } catch ( InterruptedException ex ) { Thread . currentThread ( ) . interrupt ( ) ; isStopping = true ; } }
Delays the next request .
129,052
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 .
129,053
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 .
129,054
protected void onRequestError ( final RequestErrorEvent event ) { LOGGER . log ( Level . INFO , "onRequestError: {0}" , event . getCrawlCandidate ( ) . getRequestUrl ( ) ) ; }
Callback which gets called when a request error occurs .
129,055
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 .
129,056
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 .
129,057
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 ( ) . equa...
Indicates if this crawl domain contains the specific internet domain .
129,058
public static BasicClientCookie convertToHttpClientCookie ( final Cookie seleniumCookie ) { BasicClientCookie httpClientCookie = new BasicClientCookie ( seleniumCookie . getName ( ) , seleniumCookie . getValue ( ) ) ; httpClientCookie . setDomain ( seleniumCookie . getDomain ( ) ) ; httpClientCookie . setPath ( seleniu...
Converts a Selenium cookie to a HTTP client one .
129,059
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 ( ) ) ; extractedEl...
Returns a list of validated URLs found in the page s HTML source .
129,060
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 ( ) ...
Returns a list of validated URLs found in the attribute s value .
129,061
public < T extends Serializable > T getStateObject ( final Class < T > stateObjectClass ) { return ( T ) stateObjects . get ( stateObjectClass ) ; }
Returns the state object specified by its class .
129,062
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
129,063
public CharSequence format ( Formatter formatter ) { CharSequence input = format ( ) ; return formatter . format ( String . valueOf ( input ) ) ; }
Returns CharSequence formatted with custom formatter implementation
129,064
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
129,065
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 .
129,066
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 .
129,067
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 .
129,068
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 .
129,069
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 .
129,070
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 .
129,071
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 .
129,072
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 .
129,073
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 .
129,074
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 :...
Validate sub entities ensuring the existence of a relationship and if an embedded link then ensure the existence of an href .
129,075
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_R...
Sets field value for an entity s property field .
129,076
@ 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 ( ) ) ...
Sets field value for an entity s sub entities field .
129,077
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 < ? > co...
Handles sub entities .
129,078
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 . getCurre...
Resolves the raw uri by replacing field tokens with the actual data .
129,079
private String handleTokenReplacement ( String str , EntityContext context ) throws Siren4JException { String result = "" ; result = ReflectionUtils . replaceFieldTokens ( context . getParentObject ( ) , str , context . getParentFieldInfo ( ) , true ) ; result = ReflectionUtils . flattenReservedTokens ( ReflectionUtils...
Helper method to do token replacement for strings .
129,080
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 ( field...
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 .
129,081
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 .
129,082
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 .
129,083
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 ( e...
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 .
129,084
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 ) ...
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 .
129,085
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 ...
Evaluates a value against its specified conditional .
129,086
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 ...
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 .
129,087
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 . isNotEmpt...
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 .
129,088
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 ( ) ...
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 .
129,089
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 > en...
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 .
129,090
public boolean isCollection ( Object obj , Field field ) { try { Object val = field . get ( obj ) ; boolean isCollResource = false ; if ( val != null ) { isCollResource = CollectionResource . class . equals ( val . getClass ( ) ) ; } return ( ! isCollResource && ! field . getType ( ) . equals ( CollectionResource . cla...
Determine if the field is a Collection class and not a CollectionResource class which needs special treatment .
129,091
public static Field getGetterField ( Method method ) { if ( method == null ) { throw new IllegalArgumentException ( "method cannot be null." ) ; } Class < ? > clazz = method . getDeclaringClass ( ) ; String fName = stripGetterPrefix ( method . getName ( ) ) ; Field field = null ; try { field = findField ( clazz , fName...
Find the field for the getter method based on the get methods name . It finds the field on the declaring class .
129,092
public static List < ReflectedInfo > getExposedFieldInfo ( final Class < ? > clazz ) { List < ReflectedInfo > results = null ; try { results = fieldInfoCache . get ( clazz , new Callable < List < ReflectedInfo > > ( ) { public List < ReflectedInfo > call ( ) throws Exception { List < ReflectedInfo > exposed = new Array...
Retrieve all fields deemed as Exposed i . e . they are public or have a public accessor method or are marked by an annotation to be exposed .
129,093
public static boolean isGetter ( Method method ) { String name = method . getName ( ) ; String [ ] splitname = StringUtils . splitByCharacterTypeCamelCase ( name ) ; return ! method . getReturnType ( ) . equals ( void . class ) && Modifier . isPublic ( method . getModifiers ( ) ) && ( splitname [ 0 ] . equals ( GETTER_...
Determine if the method is a getter .
129,094
public static boolean isSetter ( Method method ) { String name = method . getName ( ) ; String [ ] splitname = StringUtils . splitByCharacterTypeCamelCase ( name ) ; return method . getReturnType ( ) . equals ( void . class ) && Modifier . isPublic ( method . getModifiers ( ) ) && splitname [ 0 ] . equals ( SETTER_PREF...
Determine if the method is a setter .
129,095
public static String replaceFieldTokens ( Object obj , String str , List < ReflectedInfo > fields , boolean parentMode ) throws Siren4JException { Map < String , Field > index = new HashMap < String , Field > ( ) ; if ( StringUtils . isBlank ( str ) ) { return str ; } if ( fields != null ) { for ( ReflectedInfo info : ...
Replaces field tokens with the actual value in the fields . The field types must be simple property types
129,096
public static String flattenReservedTokens ( String str ) { if ( StringUtils . isBlank ( str ) ) { return str ; } return str . replaceAll ( "\\{\\[" , "{" ) . replaceAll ( "\\]\\}" , "}" ) ; }
Removes the square brackets that signify reserved from inside the tokens in the string .
129,097
public static Set < String > getTokenKeys ( String str ) { Set < String > results = new HashSet < String > ( ) ; String sDelim = "{" ; String eDelim = "}" ; if ( StringUtils . isBlank ( str ) ) { return results ; } int start = - 1 ; int end = 0 ; do { start = str . indexOf ( sDelim , end ) ; if ( start != - 1 ) { end =...
Retrieve all token keys from a string . A token is found by its its start and end delimiters which are open and close curly braces .
129,098
public static ReflectedInfo getFieldInfoByEffectiveName ( List < ReflectedInfo > infoList , String name ) { if ( infoList == null ) { throw new IllegalArgumentException ( "infoList cannot be null." ) ; } if ( StringUtils . isBlank ( name ) ) { throw new IllegalArgumentException ( "name cannot be null or empty." ) ; } R...
Helper method to find the field info by its effective name from the passed in list of info .
129,099
public static ReflectedInfo getFieldInfoByName ( List < ReflectedInfo > infoList , String name ) { if ( infoList == null ) { throw new IllegalArgumentException ( "infoList cannot be null." ) ; } if ( StringUtils . isBlank ( name ) ) { throw new IllegalArgumentException ( "name cannot be null or empty." ) ; } ReflectedI...
Helper method to find the field info by its name from the passed in list of info .