Input: ------------------------------------------------------------- [CODESPLIT] private < T > T invoke ( HttpMethodName httpMethodName , String resourcePath , Object representation , HttpResponseHandler < AmazonWebServiceResponse < T > > responseHandler ) throws AmazonClientException { ExecutionContext executionContext = createExecutionContext ( ) ; AWSRequestMetrics awsRequestMetrics = executionContext . getAwsRequestMetrics ( ) ; awsRequestMetrics . startEvent ( AWSRequestMetrics . Field . RequestMarshallTime . name ( ) ) ; Request request = buildRequest ( httpMethodName , resourcePath , representation ) ; awsRequestMetrics . endEvent ( AWSRequestMetrics . Field . RequestMarshallTime . name ( ) ) ; awsRequestMetrics . startEvent ( AWSRequestMetrics . Field . CredentialsRequestTime . name ( ) ) ; AWSCredentials credentials = awsCredentialsProvider . getCredentials ( ) ; awsRequestMetrics . endEvent ( AWSRequestMetrics . Field . CredentialsRequestTime . name ( ) ) ; executionContext . setCredentials ( credentials ) ; awsRequestMetrics . startEvent ( AWSRequestMetrics . Field . ClientExecuteTime . name ( ) ) ; Response < T > response = client . execute ( request , responseHandler , errorResponseHandler , executionContext ) ; awsRequestMetrics . endEvent ( AWSRequestMetrics . Field . ClientExecuteTime . name ( ) ) ; awsRequestMetrics . log ( ) ; return response . getAwsResponse ( ) ; }


Input: TODO : test w / map of Integer ... [CODESPLIT] @ Override public Object get ( Object key ) { Object value = backingMap . get ( key ) ; // When a value is accessed, it's intended type can either be a // class or some other type (like a ParameterizedType). // // If the target type is a class and the value is of that type, // we return it.  If the value is not of that type, we convert // it and store the converted value (trusting it was converted // properly) back to the backing store. // // If the target type is not a class, it may be ParameterizedType // like List<T> or Map<K, V>.  We check if the value is already // a converting type and if so, we return it.  If the value is // not, we convert it and if it's now a converting type, we store // the new value in the backing store. if ( type instanceof Class ) { if ( ! ( ( Class ) type ) . isInstance ( value ) ) { value = convert ( type , value ) ; //noinspection unchecked backingMap . put ( key , value ) ; } } else { if ( ! ( value instanceof ConvertingMap ) && ! ( value instanceof ConvertingList ) ) { value = convert ( type , value ) ; if ( value instanceof ConvertingMap || value instanceof ConvertingList ) { //noinspection unchecked backingMap . put ( key , value ) ; } } } return value ; }


Input: ------------------------------------------------------------- [CODESPLIT] static Object getObjectForToken ( JsonToken token , JsonUnmarshallerContext context ) throws IOException { switch ( token ) { case VALUE_STRING : return context . getJsonParser ( ) . getText ( ) ; case VALUE_NUMBER_FLOAT : case VALUE_NUMBER_INT : return context . getJsonParser ( ) . getNumberValue ( ) ; case VALUE_FALSE : return Boolean . FALSE ; case VALUE_TRUE : return Boolean . TRUE ; case VALUE_NULL : return null ; default : throw new RuntimeException ( "We expected a VALUE token but got: " + token ) ; } }


Input: ------------------------------------------------------------- [CODESPLIT] @ Override public Map < String , HalLink > unmarshall ( JsonUnmarshallerContext context ) throws Exception { Map < String , HalLink > links = new LinkedHashMap <> ( ) ; JsonToken token = context . getCurrentToken ( ) ; while ( token != null && token != JsonToken . END_OBJECT ) { if ( token == JsonToken . FIELD_NAME ) { if ( context . testExpression ( "curie" ) ) { context . nextToken ( ) ; HalJsonCurieUnmarshaller . getInstance ( ) . unmarshall ( context ) ; } else { String relation = context . readText ( ) ; token = context . nextToken ( ) ; if ( token == JsonToken . START_ARRAY ) { List < HalLink > halLinks = new HalJsonArrayUnmarshaller <> ( HalJsonLinkUnmarshaller . getInstance ( ) ) . unmarshall ( context ) ; int i = 0 ; for ( HalLink halLink : halLinks ) { links . put ( relation + "_" + i ++ , halLink ) ; } } else { links . put ( relation , HalJsonLinkUnmarshaller . getInstance ( ) . unmarshall ( context ) ) ; } } } token = context . nextToken ( ) ; } return links ; }


Input: ------------------------------------------------------------- [CODESPLIT] @ Override public List < T > unmarshall ( JsonUnmarshallerContext context ) throws Exception { List < T > list = new ArrayList <> ( ) ; JsonToken token = context . getCurrentToken ( ) ; while ( token != null && token != END_ARRAY ) { if ( token == JsonToken . START_OBJECT ) { list . add ( itemUnmarshaller . unmarshall ( context ) ) ; } token = context . nextToken ( ) ; } return list ; }


Input: ------------------------------------------------------------- [CODESPLIT] @ Override protected void registerAdditionalMetadataExpressions ( JsonUnmarshallerContext unmarshallerContext ) { Map < String , String > headers = unmarshallerContext . getHttpResponse ( ) . getHeaders ( ) ; if ( headers . containsKey ( "Location" ) ) { location = headers . get ( "Location" ) ; } else if ( headers . containsKey ( "location" ) ) { location = headers . get ( "location" ) ; } }


Input: ------------------------------------------------------------- [CODESPLIT] @ Override public HalResource unmarshall ( JsonUnmarshallerContext context ) throws Exception { HalResource halResource = new HalResource ( ) ; JsonToken token = context . getCurrentToken ( ) ; if ( token == null ) { token = context . nextToken ( ) ; } while ( token != null && token != JsonToken . END_OBJECT ) { if ( token == JsonToken . FIELD_NAME ) { if ( context . testExpression ( "_links" ) ) { context . nextToken ( ) ; halResource . setLinks ( HalJsonLinksUnmarshaller . getInstance ( ) . unmarshall ( context ) ) ; } else if ( context . testExpression ( "_embedded" ) ) { context . nextToken ( ) ; halResource . setEmbedded ( HalJsonEmbeddedUnmarshaller . getInstance ( ) . unmarshall ( context ) ) ; } else { String property = context . readText ( ) ; token = context . nextToken ( ) ; if ( token == JsonToken . START_OBJECT ) { context . nextToken ( ) ; halResource . addProperty ( property , HalJsonMapUnmarshaller . getInstance ( ) . unmarshall ( context ) ) ; } else if ( token == JsonToken . START_ARRAY ) { context . nextToken ( ) ; halResource . addProperty ( property , HalJsonListUnmarshaller . getInstance ( ) . unmarshall ( context ) ) ; } else { halResource . addProperty ( property , JsonUnmarshallerUtil . getObjectForToken ( token , context ) ) ; } } } token = context . nextToken ( ) ; } return halResource ; }


Input: ------------------------------------------------------------- [CODESPLIT] @ Override public Object get ( int index ) { Object value = backingList . get ( index ) ; // When a value is accessed, it's intended type can either be a // class or some other type (like a ParameterizedType). // // If the target type is a class and the value is of that type, // we return it.  If the value is not of that type, we convert // it and store the converted value (trusting it was converted // properly) back to the backing store. // // If the target type is not a class, it may be ParameterizedType // like List<T> or Map<K, V>.  We check if the value is already // a converting type and if so, we return it.  If the value is // not, we convert it and if it's now a converting type, we store // the new value in the backing store. if ( type instanceof Class ) { if ( ! ( ( Class ) type ) . isInstance ( value ) ) { value = convert ( type , value ) ; //noinspection unchecked backingList . set ( index , value ) ; } } else { if ( ! ( value instanceof ConvertingMap ) && ! ( value instanceof ConvertingList ) ) { value = convert ( type , value ) ; if ( value instanceof ConvertingMap || value instanceof ConvertingList ) { //noinspection unchecked backingList . set ( index , value ) ; } } } return value ; }


Input: ------------------------------------------------------------- [CODESPLIT] static Type getCollectionType ( Type type , int index , Class defaultClass ) { if ( type instanceof ParameterizedType ) { ParameterizedType parameterizedType = ( ParameterizedType ) type ; return parameterizedType . getActualTypeArguments ( ) [ index ] ; } else { return defaultClass ; } }


Input: ------------------------------------------------------------- [CODESPLIT] private static Object convertFromNull ( Type type ) { if ( ! ( type instanceof Class ) ) { return null ; } Class < ? > clazz = ( Class ) type ; if ( ! clazz . isPrimitive ( ) ) { return null ; } if ( int . class . isAssignableFrom ( clazz ) ) { return 0 ; } else if ( long . class . isAssignableFrom ( clazz ) ) { return 0L ; } else if ( short . class . isAssignableFrom ( clazz ) ) { return 0 ; } else if ( double . class . isAssignableFrom ( clazz ) ) { return 0.0 ; } else if ( float . class . isAssignableFrom ( clazz ) ) { return 0.0F ; } else if ( boolean . class . isAssignableFrom ( clazz ) ) { return Boolean . FALSE ; } else if ( char . class . isAssignableFrom ( clazz ) ) { return 0 ; } else if ( byte . class . isAssignableFrom ( clazz ) ) { return 0 ; } else { throw new RuntimeException ( "Unexpected primitive type: " + clazz . getSimpleName ( ) ) ; } }


Input: ------------------------------------------------------------- [CODESPLIT] @ Override public HalLink unmarshall ( JsonUnmarshallerContext context ) throws Exception { HalLink halLink = new HalLink ( ) ; JsonToken token = context . getCurrentToken ( ) ; while ( token != null && token != JsonToken . END_OBJECT ) { if ( token == JsonToken . FIELD_NAME ) { if ( context . testExpression ( "href" ) ) { context . nextToken ( ) ; halLink . setHref ( context . readText ( ) ) ; } else if ( context . testExpression ( "name" ) ) { context . nextToken ( ) ; halLink . setName ( context . readText ( ) ) ; } else if ( context . testExpression ( "title" ) ) { context . nextToken ( ) ; halLink . setTitle ( context . readText ( ) ) ; } else if ( context . testExpression ( "templated" ) ) { context . nextToken ( ) ; halLink . setTemplated ( Boolean . valueOf ( context . readText ( ) ) ) ; } else if ( context . testExpression ( "deprecation" ) ) { context . nextToken ( ) ; halLink . setDeprecation ( context . readText ( ) ) ; } else { // Ignore this.  Likely one of hreflang, profile, type context . nextToken ( ) ; } } token = context . nextToken ( ) ; } return halLink ; }


Input: ------------------------------------------------------------- [CODESPLIT] @ Override public HalLink unmarshall ( JsonUnmarshallerContext context ) throws Exception { HalLink halLink = new HalLink ( ) ; JsonToken token = context . getCurrentToken ( ) ; // Ignore curies for now. while ( token != null && token != JsonToken . END_OBJECT ) { token = context . nextToken ( ) ; } return halLink ; }


Input: Fetch a LocationforecastLTS from the MET API based on longitude latitude and altitude . [CODESPLIT] public MeteoData < LocationForecast > fetchContent ( double longitude , double latitude , int altitude ) throws MeteoException { MeteoResponse response = getMeteoClient ( ) . fetchContent ( createServiceUriBuilder ( ) . addParameter ( PARAM_LATITUDE , latitude ) . addParameter ( PARAM_LONGITUDE , longitude ) . addParameter ( PARAM_ALTITUDE , altitude ) . build ( ) ) ; return new MeteoData <> ( parser . parse ( response . getData ( ) ) , response ) ; }


Input: Fetch a Sunrise from the MET API based on a given longitude latitude and date . [CODESPLIT] public MeteoData < Sunrise > fetchContent ( double longitude , double latitude , LocalDate date ) throws MeteoException { MeteoResponse response = getMeteoClient ( ) . fetchContent ( createServiceUriBuilder ( ) . addParameter ( PARAM_LATITUDE , latitude ) . addParameter ( PARAM_LONGITUDE , longitude ) . addParameter ( PARAM_DATE , zonedDateTimeToYyyyMMdd ( date ) ) . build ( ) ) ; return new MeteoData <> ( parser . parse ( response . getData ( ) ) , response ) ; }


Input: Fetch a Sunrise from the MET API based on a given longitude latitude and date range . [CODESPLIT] public MeteoData < Sunrise > fetchContent ( double longitude , double latitude , LocalDate from , LocalDate to ) throws MeteoException { MeteoResponse response = getMeteoClient ( ) . fetchContent ( createServiceUriBuilder ( ) . addParameter ( PARAM_LATITUDE , latitude ) . addParameter ( PARAM_LONGITUDE , longitude ) . addParameter ( PARAM_FROM , zonedDateTimeToYyyyMMdd ( from ) ) . addParameter ( PARAM_TO , zonedDateTimeToYyyyMMdd ( to ) ) . build ( ) ) ; return new MeteoData <> ( parser . parse ( response . getData ( ) ) , response ) ; }


Input: Get all point forecasts from now and to the given hours ahead . [CODESPLIT] public List < MeteoExtrasForecast > findHourlyPointForecastsFromNow ( int hoursAhead ) { List < MeteoExtrasForecast > pointExtrasForecasts = new ArrayList <> ( ) ; ZonedDateTime now = getNow ( ) ; for ( int i = 0 ; i < hoursAhead ; i ++ ) { ZonedDateTime ahead = now . plusHours ( i ) ; Optional < PointForecast > pointForecast = getIndexer ( ) . getPointForecast ( ahead ) ; pointForecast . ifPresent ( pof -> { Optional < PeriodForecast > periodForecast = getIndexer ( ) . getTightestFitPeriodForecast ( pof . getFrom ( ) ) ; periodForecast . ifPresent ( pef -> pointExtrasForecasts . add ( new MeteoExtrasForecast ( pof , pef ) ) ) ; } ) ; } return pointExtrasForecasts ; }


Input: Get the most accurate forecast for the given date . [CODESPLIT] public Optional < MeteoExtrasForecast > findNearestForecast ( ZonedDateTime dateTime ) { ZonedDateTime dt = toZeroMSN ( dateTime . withZoneSameInstant ( METZONE ) ) ; PointForecast chosenForecast = null ; for ( Forecast forecast : getLocationForecast ( ) . getForecasts ( ) ) { if ( forecast instanceof PointForecast ) { PointForecast pointForecast = ( PointForecast ) forecast ; if ( isDateMatch ( dt , cloneZonedDateTime ( pointForecast . getFrom ( ) ) ) ) { chosenForecast = pointForecast ; break ; } else if ( chosenForecast == null ) { chosenForecast = pointForecast ; } else if ( isNearerDate ( pointForecast . getFrom ( ) , dt , chosenForecast . getFrom ( ) ) ) { chosenForecast = pointForecast ; } } } if ( chosenForecast == null ) { return Optional . empty ( ) ; } return Optional . of ( new MeteoExtrasForecast ( chosenForecast , getIndexer ( ) . getWidestFitPeriodForecast ( chosenForecast . getFrom ( ) ) . orElse ( null ) ) ) ; }


Input: Create an instance of { @link JAXBElement } { @code < } { @link Temperature } { @code > }} [CODESPLIT] @ XmlElementDecl ( namespace = "" , name = "maxTemperature" , scope = LocationType . class ) public JAXBElement < Temperature > createLocationTypeMaxTemperature ( Temperature value ) { return new JAXBElement < Temperature > ( _LocationTypeMaxTemperature_QNAME , Temperature . class , LocationType . class , value ) ; }


Input: Create an instance of { @link JAXBElement } { @code < } { @link LocationType . Symbol } { @code > }} [CODESPLIT] @ XmlElementDecl ( namespace = "" , name = "symbol" , scope = LocationType . class ) public JAXBElement < LocationType . Symbol > createLocationTypeSymbol ( LocationType . Symbol value ) { return new JAXBElement < LocationType . Symbol > ( _LocationTypeSymbol_QNAME , LocationType . Symbol . class , LocationType . class , value ) ; }


Input: Create an instance of { @link JAXBElement } { @code < } { @link Temperature } { @code > }} [CODESPLIT] @ XmlElementDecl ( namespace = "" , name = "highestTemperature" , scope = LocationType . class ) public JAXBElement < Temperature > createLocationTypeHighestTemperature ( Temperature value ) { return new JAXBElement < Temperature > ( _LocationTypeHighestTemperature_QNAME , Temperature . class , LocationType . class , value ) ; }


Input: Create an instance of { @link JAXBElement } { @code < } { @link Windspeed } { @code > }} [CODESPLIT] @ XmlElementDecl ( namespace = "" , name = "windGust" , scope = LocationType . class ) public JAXBElement < Windspeed > createLocationTypeWindGust ( Windspeed value ) { return new JAXBElement < Windspeed > ( _LocationTypeWindGust_QNAME , Windspeed . class , LocationType . class , value ) ; }


Input: Create an instance of { @link JAXBElement } { @code < } { @link UnitValue } { @code > }} [CODESPLIT] @ XmlElementDecl ( namespace = "" , name = "currentDirection" , scope = LocationType . class ) public JAXBElement < UnitValue > createLocationTypeCurrentDirection ( UnitValue value ) { return new JAXBElement < UnitValue > ( _LocationTypeCurrentDirection_QNAME , UnitValue . class , LocationType . class , value ) ; }


Input: Create an instance of { @link JAXBElement } { @code < } { @link LocationType . StateOfTheSea } { @code > }} [CODESPLIT] @ XmlElementDecl ( namespace = "" , name = "stateOfTheSea" , scope = LocationType . class ) public JAXBElement < LocationType . StateOfTheSea > createLocationTypeStateOfTheSea ( LocationType . StateOfTheSea value ) { return new JAXBElement < LocationType . StateOfTheSea > ( _LocationTypeStateOfTheSea_QNAME , LocationType . StateOfTheSea . class , LocationType . class , value ) ; }


Input: Create an instance of { @link JAXBElement } { @code < } { @link UnitValue } { @code > }} [CODESPLIT] @ XmlElementDecl ( namespace = "" , name = "meanabsoluteerror" , scope = LocationType . class ) public JAXBElement < UnitValue > createLocationTypeMeanabsoluteerror ( UnitValue value ) { return new JAXBElement < UnitValue > ( _LocationTypeMeanabsoluteerror_QNAME , UnitValue . class , LocationType . class , value ) ; }


Input: Create an instance of { @link JAXBElement } { @code < } { @link Precipitation } { @code > }} [CODESPLIT] @ XmlElementDecl ( namespace = "" , name = "maximumPrecipitation" , scope = LocationType . class ) public JAXBElement < Precipitation > createLocationTypeMaximumPrecipitation ( Precipitation value ) { return new JAXBElement < Precipitation > ( _LocationTypeMaximumPrecipitation_QNAME , Precipitation . class , LocationType . class , value ) ; }


Input: Create an instance of { @link JAXBElement } { @code < } { @link Tidalwater } { @code > }} [CODESPLIT] @ XmlElementDecl ( namespace = "" , name = "tidalwater" , scope = LocationType . class ) public JAXBElement < Tidalwater > createLocationTypeTidalwater ( Tidalwater value ) { return new JAXBElement < Tidalwater > ( _LocationTypeTidalwater_QNAME , Tidalwater . class , LocationType . class , value ) ; }


Input: Create an instance of { @link JAXBElement } { @code < } { @link UnitValue } { @code > }} [CODESPLIT] @ XmlElementDecl ( namespace = "" , name = "waveHeight" , scope = LocationType . class ) public JAXBElement < UnitValue > createLocationTypeWaveHeight ( UnitValue value ) { return new JAXBElement < UnitValue > ( _LocationTypeWaveHeight_QNAME , UnitValue . class , LocationType . class , value ) ; }


Input: Create an instance of { @link JAXBElement } { @code < } { @link Precipitation } { @code > }} [CODESPLIT] @ XmlElementDecl ( namespace = "" , name = "precipitation" , scope = LocationType . class ) public JAXBElement < Precipitation > createLocationTypePrecipitation ( Precipitation value ) { return new JAXBElement < Precipitation > ( _LocationTypePrecipitation_QNAME , Precipitation . class , LocationType . class , value ) ; }


Input: Create an instance of { @link JAXBElement } { @code < } { @link Score } { @code > }} [CODESPLIT] @ XmlElementDecl ( namespace = "" , name = "score" , scope = LocationType . class ) public JAXBElement < Score > createLocationTypeScore ( Score value ) { return new JAXBElement < Score > ( _LocationTypeScore_QNAME , Score . class , LocationType . class , value ) ; }


Input: Create an instance of { @link JAXBElement } { @code < } { @link Windspeed } { @code > }} [CODESPLIT] @ XmlElementDecl ( namespace = "" , name = "areaMaxWindSpeed" , scope = LocationType . class ) public JAXBElement < Windspeed > createLocationTypeAreaMaxWindSpeed ( Windspeed value ) { return new JAXBElement < Windspeed > ( _LocationTypeAreaMaxWindSpeed_QNAME , Windspeed . class , LocationType . class , value ) ; }


Input: Create an instance of { @link JAXBElement } { @code < } { @link LocationType . SnowDepth } { @code > }} [CODESPLIT] @ XmlElementDecl ( namespace = "" , name = "snowDepth" , scope = LocationType . class ) public JAXBElement < LocationType . SnowDepth > createLocationTypeSnowDepth ( LocationType . SnowDepth value ) { return new JAXBElement < LocationType . SnowDepth > ( _LocationTypeSnowDepth_QNAME , LocationType . SnowDepth . class , LocationType . class , value ) ; }


Input: Create an instance of { @link JAXBElement } { @code < } { @link Cloudiness } { @code > }} [CODESPLIT] @ XmlElementDecl ( namespace = "" , name = "lowClouds" , scope = LocationType . class ) public JAXBElement < Cloudiness > createLocationTypeLowClouds ( Cloudiness value ) { return new JAXBElement < Cloudiness > ( _LocationTypeLowClouds_QNAME , Cloudiness . class , LocationType . class , value ) ; }


Input: Create an instance of { @link JAXBElement } { @code < } { @link Temperature } { @code > }} [CODESPLIT] @ XmlElementDecl ( namespace = "" , name = "minTemperature" , scope = LocationType . class ) public JAXBElement < Temperature > createLocationTypeMinTemperature ( Temperature value ) { return new JAXBElement < Temperature > ( _LocationTypeMinTemperature_QNAME , Temperature . class , LocationType . class , value ) ; }


Input: Create an instance of { @link JAXBElement } { @code < } { @link UnitValue } { @code > }} [CODESPLIT] @ XmlElementDecl ( namespace = "" , name = "bias" , scope = LocationType . class ) public JAXBElement < UnitValue > createLocationTypeBias ( UnitValue value ) { return new JAXBElement < UnitValue > ( _LocationTypeBias_QNAME , UnitValue . class , LocationType . class , value ) ; }


Input: Create an instance of { @link JAXBElement } { @code < } { @link Temperature } { @code > }} [CODESPLIT] @ XmlElementDecl ( namespace = "" , name = "temperature" , scope = LocationType . class ) public JAXBElement < Temperature > createLocationTypeTemperature ( Temperature value ) { return new JAXBElement < Temperature > ( _LocationTypeTemperature_QNAME , Temperature . class , LocationType . class , value ) ; }


Input: Create an instance of { @link JAXBElement } { @code < } { @link LocationType . Weather } { @code > }} [CODESPLIT] @ XmlElementDecl ( namespace = "" , name = "weather" , scope = LocationType . class ) public JAXBElement < LocationType . Weather > createLocationTypeWeather ( LocationType . Weather value ) { return new JAXBElement < LocationType . Weather > ( _LocationTypeWeather_QNAME , LocationType . Weather . class , LocationType . class , value ) ; }


Input: Create an instance of { @link JAXBElement } { @code < } { @link UnitValue } { @code > }} [CODESPLIT] @ XmlElementDecl ( namespace = "" , name = "humidity" , scope = LocationType . class ) public JAXBElement < UnitValue > createLocationTypeHumidity ( UnitValue value ) { return new JAXBElement < UnitValue > ( _LocationTypeHumidity_QNAME , UnitValue . class , LocationType . class , value ) ; }


Input: Create an instance of { @link JAXBElement } { @code < } { @link UnitValue } { @code > }} [CODESPLIT] @ XmlElementDecl ( namespace = "" , name = "numberofobservations" , scope = LocationType . class ) public JAXBElement < UnitValue > createLocationTypeNumberofobservations ( UnitValue value ) { return new JAXBElement < UnitValue > ( _LocationTypeNumberofobservations_QNAME , UnitValue . class , LocationType . class , value ) ; }


Input: Create an instance of { @link JAXBElement } { @code < } { @link LocationType . WindDirection } { @code > }} [CODESPLIT] @ XmlElementDecl ( namespace = "" , name = "windDirection" , scope = LocationType . class ) public JAXBElement < LocationType . WindDirection > createLocationTypeWindDirection ( LocationType . WindDirection value ) { return new JAXBElement < LocationType . WindDirection > ( _LocationTypeWindDirection_QNAME , LocationType . WindDirection . class , LocationType . class , value ) ; }


Input: Create an instance of { @link JAXBElement } { @code < } { @link Temperature } { @code > }} [CODESPLIT] @ XmlElementDecl ( namespace = "" , name = "maxTemperatureDay" , scope = LocationType . class ) public JAXBElement < Temperature > createLocationTypeMaxTemperatureDay ( Temperature value ) { return new JAXBElement < Temperature > ( _LocationTypeMaxTemperatureDay_QNAME , Temperature . class , LocationType . class , value ) ; }


Input: Create an instance of { @link JAXBElement } { @code < } { @link Windspeed } { @code > }} [CODESPLIT] @ XmlElementDecl ( namespace = "" , name = "windSpeed" , scope = LocationType . class ) public JAXBElement < Windspeed > createLocationTypeWindSpeed ( Windspeed value ) { return new JAXBElement < Windspeed > ( _LocationTypeWindSpeed_QNAME , Windspeed . class , LocationType . class , value ) ; }


Input: Create an instance of { @link JAXBElement } { @code < } { @link UnitValue } { @code > }} [CODESPLIT] @ XmlElementDecl ( namespace = "" , name = "wavePeriod" , scope = LocationType . class ) public JAXBElement < UnitValue > createLocationTypeWavePeriod ( UnitValue value ) { return new JAXBElement < UnitValue > ( _LocationTypeWavePeriod_QNAME , UnitValue . class , LocationType . class , value ) ; }


Input: Create an instance of { @link JAXBElement } { @code < } { @link Temperature } { @code > }} [CODESPLIT] @ XmlElementDecl ( namespace = "" , name = "minTemperatureNight" , scope = LocationType . class ) public JAXBElement < Temperature > createLocationTypeMinTemperatureNight ( Temperature value ) { return new JAXBElement < Temperature > ( _LocationTypeMinTemperatureNight_QNAME , Temperature . class , LocationType . class , value ) ; }


Input: Create an instance of { @link JAXBElement } { @code < } { @link Uv } { @code > }} [CODESPLIT] @ XmlElementDecl ( namespace = "" , name = "uv" , scope = LocationType . class ) public JAXBElement < Uv > createLocationTypeUv ( Uv value ) { return new JAXBElement < Uv > ( _LocationTypeUv_QNAME , Uv . class , LocationType . class , value ) ; }


Input: Create an instance of { @link JAXBElement } { @code < } { @link Cloudiness } { @code > }} [CODESPLIT] @ XmlElementDecl ( namespace = "" , name = "highClouds" , scope = LocationType . class ) public JAXBElement < Cloudiness > createLocationTypeHighClouds ( Cloudiness value ) { return new JAXBElement < Cloudiness > ( _LocationTypeHighClouds_QNAME , Cloudiness . class , LocationType . class , value ) ; }


Input: Create an instance of { @link JAXBElement } { @code < } { @link Temperature } { @code > }} [CODESPLIT] @ XmlElementDecl ( namespace = "" , name = "maxTemperatureNight" , scope = LocationType . class ) public JAXBElement < Temperature > createLocationTypeMaxTemperatureNight ( Temperature value ) { return new JAXBElement < Temperature > ( _LocationTypeMaxTemperatureNight_QNAME , Temperature . class , LocationType . class , value ) ; }


Input: Create an instance of { @link JAXBElement } { @code < } { @link UnitValue } { @code > }} [CODESPLIT] @ XmlElementDecl ( namespace = "" , name = "windProbability" , scope = LocationType . class ) public JAXBElement < UnitValue > createLocationTypeWindProbability ( UnitValue value ) { return new JAXBElement < UnitValue > ( _LocationTypeWindProbability_QNAME , UnitValue . class , LocationType . class , value ) ; }


Input: Create an instance of { @link JAXBElement } { @code < } { @link UnitValue } { @code > }} [CODESPLIT] @ XmlElementDecl ( namespace = "" , name = "maxWaveHeight" , scope = LocationType . class ) public JAXBElement < UnitValue > createLocationTypeMaxWaveHeight ( UnitValue value ) { return new JAXBElement < UnitValue > ( _LocationTypeMaxWaveHeight_QNAME , UnitValue . class , LocationType . class , value ) ; }


Input: Create an instance of { @link JAXBElement } { @code < } { @link UnitValue } { @code > }} [CODESPLIT] @ XmlElementDecl ( namespace = "" , name = "surfaceTemperature" , scope = LocationType . class ) public JAXBElement < UnitValue > createLocationTypeSurfaceTemperature ( UnitValue value ) { return new JAXBElement < UnitValue > ( _LocationTypeSurfaceTemperature_QNAME , UnitValue . class , LocationType . class , value ) ; }


Input: Create an instance of { @link JAXBElement } { @code < } { @link Pressure } { @code > }} [CODESPLIT] @ XmlElementDecl ( namespace = "" , name = "pressure" , scope = LocationType . class ) public JAXBElement < Pressure > createLocationTypePressure ( Pressure value ) { return new JAXBElement < Pressure > ( _LocationTypePressure_QNAME , Pressure . class , LocationType . class , value ) ; }


Input: Create an instance of { @link JAXBElement } { @code < } { @link Cloudiness } { @code > }} [CODESPLIT] @ XmlElementDecl ( namespace = "" , name = "cloudiness" , scope = LocationType . class ) public JAXBElement < Cloudiness > createLocationTypeCloudiness ( Cloudiness value ) { return new JAXBElement < Cloudiness > ( _LocationTypeCloudiness_QNAME , Cloudiness . class , LocationType . class , value ) ; }


Input: Create an instance of { @link JAXBElement } { @code < } { @link UnitValue } { @code > }} [CODESPLIT] @ XmlElementDecl ( namespace = "" , name = "waveDirection" , scope = LocationType . class ) public JAXBElement < UnitValue > createLocationTypeWaveDirection ( UnitValue value ) { return new JAXBElement < UnitValue > ( _LocationTypeWaveDirection_QNAME , UnitValue . class , LocationType . class , value ) ; }


Input: Create an instance of { @link JAXBElement } { @code < } { @link UnitValue } { @code > }} [CODESPLIT] @ XmlElementDecl ( namespace = "" , name = "symbolProbability" , scope = LocationType . class ) public JAXBElement < UnitValue > createLocationTypeSymbolProbability ( UnitValue value ) { return new JAXBElement < UnitValue > ( _LocationTypeSymbolProbability_QNAME , UnitValue . class , LocationType . class , value ) ; }


Input: Create an instance of { @link JAXBElement } { @code < } { @link UnitValue } { @code > }} [CODESPLIT] @ XmlElementDecl ( namespace = "" , name = "temperatureProbability" , scope = LocationType . class ) public JAXBElement < UnitValue > createLocationTypeTemperatureProbability ( UnitValue value ) { return new JAXBElement < UnitValue > ( _LocationTypeTemperatureProbability_QNAME , UnitValue . class , LocationType . class , value ) ; }


Input: Create an instance of { @link JAXBElement } { @code < } { @link Groundcover } { @code > }} [CODESPLIT] @ XmlElementDecl ( namespace = "" , name = "groundCover" , scope = LocationType . class ) public JAXBElement < Groundcover > createLocationTypeGroundCover ( Groundcover value ) { return new JAXBElement < Groundcover > ( _LocationTypeGroundCover_QNAME , Groundcover . class , LocationType . class , value ) ; }


Input: Create an instance of { @link JAXBElement } { @code < } { @link Temperature } { @code > }} [CODESPLIT] @ XmlElementDecl ( namespace = "" , name = "minTemperatureDay" , scope = LocationType . class ) public JAXBElement < Temperature > createLocationTypeMinTemperatureDay ( Temperature value ) { return new JAXBElement < Temperature > ( _LocationTypeMinTemperatureDay_QNAME , Temperature . class , LocationType . class , value ) ; }


Input: Create an instance of { @link JAXBElement } { @code < } { @link Windspeed } { @code > }} [CODESPLIT] @ XmlElementDecl ( namespace = "" , name = "maxWindSpeed" , scope = LocationType . class ) public JAXBElement < Windspeed > createLocationTypeMaxWindSpeed ( Windspeed value ) { return new JAXBElement < Windspeed > ( _LocationTypeMaxWindSpeed_QNAME , Windspeed . class , LocationType . class , value ) ; }


Input: Create an instance of { @link JAXBElement } { @code < } { @link LocationType . ForestFire } { @code > }} [CODESPLIT] @ XmlElementDecl ( namespace = "" , name = "forest-fire" , scope = LocationType . class ) public JAXBElement < LocationType . ForestFire > createLocationTypeForestFire ( LocationType . ForestFire value ) { return new JAXBElement < LocationType . ForestFire > ( _LocationTypeForestFire_QNAME , LocationType . ForestFire . class , LocationType . class , value ) ; }


Input: Create an instance of { @link JAXBElement } { @code < } { @link Cloudiness } { @code > }} [CODESPLIT] @ XmlElementDecl ( namespace = "" , name = "mediumClouds" , scope = LocationType . class ) public JAXBElement < Cloudiness > createLocationTypeMediumClouds ( Cloudiness value ) { return new JAXBElement < Cloudiness > ( _LocationTypeMediumClouds_QNAME , Cloudiness . class , LocationType . class , value ) ; }


Input: Create an instance of { @link JAXBElement } { @code < } { @link Temperature } { @code > }} [CODESPLIT] @ XmlElementDecl ( namespace = "" , name = "dewpointTemperature" , scope = LocationType . class ) public JAXBElement < Temperature > createLocationTypeDewpointTemperature ( Temperature value ) { return new JAXBElement < Temperature > ( _LocationTypeDewpointTemperature_QNAME , Temperature . class , LocationType . class , value ) ; }


Input: Create an instance of { @link JAXBElement } { @code < } { @link Temperature } { @code > }} [CODESPLIT] @ XmlElementDecl ( namespace = "" , name = "lowestTemperature" , scope = LocationType . class ) public JAXBElement < Temperature > createLocationTypeLowestTemperature ( Temperature value ) { return new JAXBElement < Temperature > ( _LocationTypeLowestTemperature_QNAME , Temperature . class , LocationType . class , value ) ; }


Input: Create an instance of { @link JAXBElement } { @code < } { @link Cloudiness } { @code > }} [CODESPLIT] @ XmlElementDecl ( namespace = "" , name = "fog" , scope = LocationType . class ) public JAXBElement < Cloudiness > createLocationTypeFog ( Cloudiness value ) { return new JAXBElement < Cloudiness > ( _LocationTypeFog_QNAME , Cloudiness . class , LocationType . class , value ) ; }


Input: Fetch a textforecast for a named forecast [CODESPLIT] public MeteoData < Weather > fetchContent ( ForecastQuery query ) throws MeteoException { MeteoResponse response = getMeteoClient ( ) . fetchContent ( createServiceUriBuilder ( ) . addParameter ( "forecast" , query . getName ( ) ) . addParameter ( "language" , query . getLanguage ( ) . getValue ( ) ) . build ( ) ) ; return new MeteoData <> ( parser . parse ( response . getData ( ) ) , response ) ; }


Input: Create a longterm forecast but only with a small subset of the weather data fields . Typically for use in simple weather reports where you only show the predicted weather icon and temperature and not all the weather details . [CODESPLIT] public MeteoExtrasLongTermForecast createSimpleLongTermForecast ( ) throws MeteoException { List < MeteoExtrasForecastDay > forecastDays = new ArrayList <> ( ) ; ZonedDateTime dt = getNow ( ) ; for ( int i = 0 ; i <= 6 ; i ++ ) { ZonedDateTime dti = dt . plusDays ( i ) ; if ( getIndexer ( ) . hasForecastsForDay ( dti ) ) { MeteoExtrasForecastDay mefd = createSimpleForcastForDay ( dti ) ; if ( mefd != null && mefd . getForecasts ( ) . size ( ) > 0 ) { forecastDays . add ( mefd ) ; } } } return new MeteoExtrasLongTermForecast ( forecastDays ) ; }


Input: Create a longterm forecast . [CODESPLIT] public MeteoExtrasLongTermForecast createLongTermForecast ( ) { List < MeteoExtrasForecastDay > forecastDays = new ArrayList <> ( ) ; ZonedDateTime dt = toZeroHMSN ( getLocationForecast ( ) . getCreated ( ) . plusDays ( 1 ) ) ; for ( int i = 0 ; i < series . getSeries ( ) . size ( ) ; i ++ ) { createLongTermForecastDay ( dt . plusDays ( i ) , series . getSeries ( ) . get ( i ) ) . ifPresent ( forecastDays :: add ) ; } return new MeteoExtrasLongTermForecast ( forecastDays ) ; }


Input: Create an untitled Location from coordinate string . [CODESPLIT] public static Location fromCoordinates ( String coordinates ) { if ( coordinates == null ) { throw new IllegalArgumentException ( "Cannot create Location from null input." ) ; } Matcher m = P . matcher ( coordinates ) ; if ( ! m . matches ( ) ) { throw new IllegalArgumentException ( coordinates + " must be on the pattern (longitude,latitude,altitude) : " + P . pattern ( ) ) ; } try { Double longitude = Double . valueOf ( m . group ( 1 ) ) ; Double latitude = Double . valueOf ( m . group ( 2 ) ) ; Integer altitude = 0 ; if ( m . group ( 3 ) != null ) { altitude = Integer . valueOf ( m . group ( 3 ) . substring ( 1 ) ) ; } return new Location ( longitude , latitude , altitude , "" ) ; } catch ( NumberFormatException e ) { throw new IllegalArgumentException ( coordinates + " must be on the pattern (longitude,latitude,altitude) : " + P . pattern ( ) ) ; } }


Input: Fetch a list of all available textforecasts . [CODESPLIT] public MeteoData < Available > fetchContent ( ) throws MeteoException { MeteoResponse response = getMeteoClient ( ) . fetchContent ( createServiceUriBuilder ( ) . addParameter ( "available" , null ) . skipQuestionMarkInUrl ( ) . build ( ) ) ; return new MeteoData <> ( parser . parse ( response . getData ( ) ) , response ) ; }


Input: Create an instance of { @link JAXBElement } { @code < } { @link Probability } { @code > }} [CODESPLIT] @ XmlElementDecl ( namespace = "" , name = "probability" , scope = LocationType . class ) public JAXBElement < Probability > createLocationTypeProbability ( Probability value ) { return new JAXBElement < Probability > ( _LocationTypeProbability_QNAME , Probability . class , LocationType . class , value ) ; }


Input: Create an instance of { @link JAXBElement } { @code < } { @link String } { @code > }} [CODESPLIT] @ XmlElementDecl ( namespace = "" , name = "productdescription" ) public JAXBElement < String > createProductdescription ( String value ) { return new JAXBElement < String > ( _Productdescription_QNAME , String . class , null , value ) ; }


Input: Create an instance of { @link JAXBElement } { @code < } { @link String } { @code > }} [CODESPLIT] @ XmlElementDecl ( namespace = "" , name = "header" ) public JAXBElement < String > createHeader ( String value ) { return new JAXBElement < String > ( _Header_QNAME , String . class , null , value ) ; }


Input: Create name for a wind symbol . [CODESPLIT] public static Optional < String > createWindSymbolName ( PointForecast pointForecast ) { if ( pointForecast == null || pointForecast . getWindDirection ( ) == null || pointForecast . getWindSpeed ( ) == null ) { return Optional . empty ( ) ; } return Optional . of ( pointForecast . getWindDirection ( ) . getName ( ) . toLowerCase ( ) + idFormat . format ( pointForecast . getWindSpeed ( ) . getBeaufort ( ) ) ) ; }


Input: Find matching Beaufort level for a given point forecast . [CODESPLIT] public static Optional < BeaufortLevel > findBeaufortLevel ( PointForecast pointForecast ) { if ( pointForecast == null || pointForecast . getWindSpeed ( ) == null ) { return Optional . empty ( ) ; } return Optional . ofNullable ( findUnitById ( pointForecast . getWindSpeed ( ) . getBeaufort ( ) ) ) ; }


Input: Wrap the construction of URL s to avoid throwing of checked MalformedURLException . Instead MeteoException is thrown . [CODESPLIT] public static URI createUri ( String uri ) throws MeteoException { if ( uri == null ) { throw new MeteoException ( "URI is null" ) ; } try { return new URI ( uri ) ; } catch ( URISyntaxException e ) { throw new MeteoException ( e ) ; } }


Input: Check if the sun is shining for a given time . [CODESPLIT] public boolean isSun ( ZonedDateTime currentDate ) { if ( getSun ( ) . getNeverRise ( ) ) { return false ; } else if ( getSun ( ) . getNeverSet ( ) ) { return true ; } return timeWithinPeriod ( currentDate ) ; }


Input: Get the PointForecast that matches the given time . [CODESPLIT] Optional < PointForecast > getPointForecast ( ZonedDateTime dateTime ) { for ( Forecast forecast : forecasts ) { if ( forecast instanceof PointForecast ) { PointForecast pointForecast = ( PointForecast ) forecast ; if ( createHourIndexKey ( dateTime ) . equals ( createHourIndexKey ( cloneZonedDateTime ( pointForecast . getFrom ( ) ) ) ) ) { return Optional . of ( pointForecast ) ; } } } return Optional . empty ( ) ; }


Input: / * Find the period forecast that is the widest fit for a point forecast . [CODESPLIT] Optional < PeriodForecast > getWidestFitPeriodForecast ( ZonedDateTime from ) { if ( from == null ) { return Optional . empty ( ) ; } return getWidestFitScoreForecast ( from ) . map ( ScoreForecast :: getPeriodForecast ) ; }


Input: Find the period forecast that has the best fitted forecast for a given period . [CODESPLIT] Optional < PeriodForecast > getBestFitPeriodForecast ( ZonedDateTime from , ZonedDateTime to ) { if ( from == null || to == null ) { return Optional . empty ( ) ; } // Making sure that we remove minutes, seconds and milliseconds from the request timestamps ZonedDateTime requestFrom = toZeroMSN ( from ) ; ZonedDateTime requestTo = toZeroMSN ( to ) ; //  Get list of period forecasts for the requested day. Return empty if date isn't present List < PeriodForecast > forecastsList = dayIndex . get ( new DayIndexKey ( requestFrom ) ) ; if ( forecastsList == null ) { return Optional . empty ( ) ; } PeriodForecast chosenForecast = null ; long score = 0 ; long tmpScore = 0 ; for ( PeriodForecast forecast : forecastsList ) { ZonedDateTime actualFrom = cloneZonedDateTime ( forecast . getFrom ( ) ) ; ZonedDateTime actualTo = cloneZonedDateTime ( forecast . getTo ( ) ) ; if ( requestFrom . equals ( actualFrom ) && requestTo . equals ( actualTo ) ) { return Optional . of ( forecast ) ; } else if ( ( requestFrom . isBefore ( actualFrom ) && requestTo . isBefore ( actualFrom ) ) || ( requestFrom . isAfter ( actualTo ) && requestTo . isAfter ( actualTo ) ) || actualTo . isEqual ( actualFrom ) ) { continue ; // this period is outside the requested period or this is a point forecast. } else if ( requestFrom . isBefore ( actualFrom ) && requestTo . isBefore ( actualTo ) ) { tmpScore = hoursBetween ( requestTo , actualFrom ) ; } else if ( ( actualFrom . isBefore ( requestFrom ) || actualFrom . isEqual ( requestFrom ) ) && actualTo . isBefore ( requestTo ) ) { tmpScore = hoursBetween ( actualTo , requestFrom ) ; } else if ( actualFrom . isAfter ( requestFrom ) && ( actualTo . isBefore ( requestTo ) || actualTo . isEqual ( requestTo ) ) ) { tmpScore = hoursBetween ( actualTo , actualFrom ) ; } else if ( actualFrom . isBefore ( requestFrom ) && actualTo . isAfter ( requestTo ) ) { tmpScore = hoursBetween ( requestTo , requestFrom ) ; } else { DateTimeFormatter formatter = DateTimeFormatter . ofPattern ( "yyyy-MM-dd:HH:mm" ) ; log . warn ( "Unhandled forecast Requested period:" + requestFrom . format ( formatter ) + "--" + requestTo . format ( formatter ) + ", Actual period: " + actualFrom . format ( formatter ) + "--" + actualTo . format ( formatter ) ) ; } tmpScore = Math . abs ( tmpScore ) ; if ( ( score == 0 && tmpScore > 0 ) || tmpScore > score ) { score = tmpScore ; chosenForecast = forecast ; } } return Optional . ofNullable ( chosenForecast ) ; }


Input: Fetch textforecasts and warnings for a geographical point or area in Norwegian . [CODESPLIT] public MeteoData < TextLocationWeather > fetchContent ( double longitude , double latitude ) throws MeteoException { return fetchContent ( longitude , latitude , TextLocationLanguage . NB ) ; }


Input: Fetch textforecasts and warnings for a geographical point or area . [CODESPLIT] public MeteoData < TextLocationWeather > fetchContent ( double longitude , double latitude , TextLocationLanguage language ) throws MeteoException { MeteoResponse response = getMeteoClient ( ) . fetchContent ( createServiceUriBuilder ( ) . addParameter ( "latitude" , latitude ) . addParameter ( "longitude" , longitude ) . addParameter ( "language" , language . getValue ( ) ) . build ( ) ) ; return new MeteoData <> ( parser . parse ( response . getData ( ) ) , response ) ; }


Input: Retrieves the file extensions to use with the specified decoder . <p > If the specified Decoder doesn t have any file extensions explicitly associated with it then a single empty string is returned . [CODESPLIT] private static String [ ] getFileExtensions ( final Decoder decoder ) { final Class < ? extends Decoder > decoderClass = decoder . getClass ( ) ; final FileExtensions fileExtensionsAnnotation = decoderClass . getAnnotation ( FileExtensions . class ) ; return ( fileExtensionsAnnotation == null ) ? new String [ ] { "" } : fileExtensionsAnnotation . value ( ) ; }


Input: Convert a ( partial ) ServicePath into a file name to access . The file names are in the format cfg_group_subgroup_appid_ConfigurationClass [ . ext ] . [CODESPLIT] private String nameToFile ( final Class configClass , final Name servicePath , final String fileNameDelimiter , final String extension ) { StringBuilder builder = new StringBuilder ( "cfg" ) ; for ( final String component : servicePath ) { builder . append ( fileNameDelimiter ) . append ( component ) ; } builder . append ( fileNameDelimiter ) . append ( configClass . getSimpleName ( ) ) ; if ( ! extension . isEmpty ( ) ) { builder . append ( ' ' ) . append ( extension ) ; } return builder . toString ( ) ; }


Input: Checks connection retrieves appropriate changelog and performs database update . [CODESPLIT] private void updateDB ( ) throws SQLException , LiquibaseException { System . out . println ( "About to perform DB update." ) ; try ( BasicDataSource dataSource = new BasicDataSource ( ) ) { dataSource . setUrl ( fullConnectionString ) ; dataSource . setUsername ( username ) ; dataSource . setPassword ( password ) ; try ( java . sql . Connection c = dataSource . getConnection ( ) ) { Database database = DatabaseFactory . getInstance ( ) . findCorrectDatabaseImplementation ( new JdbcConnection ( c ) ) ; // Check that the Database does indeed exist before we try to run the liquibase update. Liquibase liquibase = null ; ClassLoaderResourceAccessor accessor = new ClassLoaderResourceAccessor ( ) ; try { if ( accessor . getResourcesAsStream ( "changelog-master.xml" ) != null ) { liquibase = new Liquibase ( "changelog-master.xml" , new ClassLoaderResourceAccessor ( ) , database ) ; } else if ( accessor . getResourcesAsStream ( "changelog.xml" ) != null ) { liquibase = new Liquibase ( "changelog.xml" , new ClassLoaderResourceAccessor ( ) , database ) ; } else { String errorMessage = "No liquibase changelog-master.xml or changelog.xml could be located" ; Logger . getLogger ( Application . class . getName ( ) ) . log ( Level . SEVERE , errorMessage , this ) ; throw new RuntimeException ( errorMessage ) ; } } catch ( final IOException ioe ) { Logger . getLogger ( Application . class . getName ( ) ) . log ( Level . SEVERE , ioe . getMessage ( ) , ioe ) ; } liquibase . getLog ( ) . setLogLevel ( logLevel ) ; liquibase . update ( new Contexts ( ) ) ; System . out . println ( "DB update finished." ) ; } } }


Input: Executes the specified script . The source of the script is supplied as a UTF - 8 encoded { @code InputStream } . The default { @code ScriptContext } for the { @code ScriptEngine } is used . [CODESPLIT] private static Object evaluateScript ( final ScriptEngine scriptEngine , final InputStream stream ) throws IOException , ScriptException { try ( final InputStreamReader reader = new InputStreamReader ( stream , StandardCharsets . UTF_8 ) ) { return scriptEngine . eval ( reader ) ; } }


Input: Calls a method on a script object compiled during a previous script execution which is retained in the state of the ScriptEngine . [CODESPLIT] private static String invokeStringMethod ( final ScriptEngine jsEngine , final Object thiz , final String name , final Object ... args ) throws NoSuchMethodException , ScriptException { return ( String ) ( ( Invocable ) jsEngine ) . invokeMethod ( thiz , name , args ) ; }


Input: Return the referenced object potentially performing a remote DataStore lookup and deserialisation . If the object is already present or has been previously acquired it is immediately returned . [CODESPLIT] public synchronized T acquire ( final DataSource source ) throws DataSourceException { if ( object == null ) { if ( getReference ( ) == null ) { throw new IllegalStateException ( "No reference or object present" ) ; } else { object = source . getObject ( getReference ( ) , objectClass ) ; } } return object ; }


Input: Create a ReferencedObject that uses a remote reference to data present in an ObjectSource . [CODESPLIT] public static < T > ReferencedObject < T > getReferencedObject ( final Class < T > clazz , final String ref ) { return new ReferencedObject <> ( clazz , ref , null ) ; }


Input: Create a ReferencedObject that directly wraps an object without a reference . [CODESPLIT] public static < T > ReferencedObject < T > getWrappedObject ( final Class < T > clazz , final T obj ) { return new ReferencedObject <> ( clazz , null , obj ) ; }


Input: { @inheritDoc } [CODESPLIT] @ Override protected InputStream getConfigurationStream ( final Class configClass , final Name relativePath ) throws ConfigurationException { try { return remoteCall ( relativePath . toString ( ) , configClass . getSimpleName ( ) ) . getBody ( ) . in ( ) ; } catch ( final HttpConfigurationException e ) { throw new ConfigurationException ( "No configuration at path: " + relativePath , e ) ; } catch ( final IOException | InterruptedException e ) { throw new ConfigurationException ( "Failed to retrieve configuration" , e ) ; } }


Input: Perform exponential backoff / retry of acquiring a data file from an HTTP source . [CODESPLIT] private Response remoteCall ( final String path , final String configName ) throws ConfigurationException , InterruptedException { int i = 0 ; while ( true ) { try { return remote . getRemoteConfiguration ( path , configName ) ; } catch ( final HttpConfigurationException nfe ) { // don't retry if we have an explicit failure from the HTTP server throw nfe ; } catch ( final ConfigurationException e ) { LOG . debug ( "HTTP client call failed, retrying" ) ; if ( i == retries ) { throw e ; } else { Thread . sleep ( ( long ) Math . pow ( 2 , i ) * 1000L ) ; } i ++ ; } } }


Input: Acquire a configuration class from the provider . The requested class will be a simple Java object that when returned and can be interacted with using getters and other standard mechanisms . Configuration classes may themselves contain other configuration objects which will be recursively acquired if marked @Configuration . Any fields marked @Encrypted will be decrypted any fields marked and any validation annotations will be processed . [CODESPLIT] @ Override public final < T > T getConfiguration ( final Class < T > configClass ) throws ConfigurationException { Objects . requireNonNull ( configClass ) ; incrementRequests ( ) ; T config = getCompleteConfig ( configClass ) ; Set < ConstraintViolation < T > > violations = getValidator ( ) . validate ( config ) ; if ( violations . isEmpty ( ) ) { return config ; } else { incrementErrors ( ) ; LOG . error ( "Configuration constraint violations found for {}: {}" , configClass . getSimpleName ( ) , violations ) ; throw new ConfigurationException ( "Configuration validation failed for " + configClass . getSimpleName ( ) ) ; } }


Input: This is the recursive entry point for acquiring a complete configuration class to return . Attempt to acquire a deserialised object representing the configuration class requested and analyse it for declared fields marked @Configuration . If any are found the method recursively calls itself until all configuration is satisfied . [CODESPLIT] private < T > T getCompleteConfig ( final Class < T > configClass ) throws ConfigurationException { T config = getConfig ( configClass ) ; for ( final Field f : configClass . getDeclaredFields ( ) ) { if ( f . isAnnotationPresent ( Configuration . class ) ) { try { Method setter = getMethod ( f . getName ( ) , configClass , PropertyDescriptor :: getWriteMethod ) ; if ( setter != null ) { setter . invoke ( config , getCompleteConfig ( f . getType ( ) ) ) ; } } catch ( final ConfigurationException e ) { LOG . debug ( "Didn't find any overriding configuration" , e ) ; } catch ( final InvocationTargetException | IllegalAccessException e ) { incrementErrors ( ) ; throw new ConfigurationException ( "Failed to get complete configuration for " + configClass . getSimpleName ( ) , e ) ; } } else if ( f . getType ( ) . equals ( String . class ) && f . isAnnotationPresent ( Encrypted . class ) ) { try { Method getter = getMethod ( f . getName ( ) , config . getClass ( ) , PropertyDescriptor :: getReadMethod ) ; Method setter = getMethod ( f . getName ( ) , config . getClass ( ) , PropertyDescriptor :: getWriteMethod ) ; if ( getter != null && setter != null ) { final String configValue = ( String ) getter . invoke ( config ) ; final String encryptedValue = isSubstitutorEnabled ? tokenSubstitutor ( configValue ) : configValue ; setter . invoke ( config , getCipher ( ) . decrypt ( encryptedValue ) ) ; } } catch ( final CipherException | InvocationTargetException | IllegalAccessException e ) { throw new ConfigurationException ( "Failed to decrypt class fields" , e ) ; } } else if ( isSubstitutorEnabled && f . getType ( ) . equals ( String . class ) ) { try { String propertyName = f . getName ( ) ; Method getter = getMethod ( propertyName , config . getClass ( ) , PropertyDescriptor :: getReadMethod ) ; Method setter = getMethod ( propertyName , config . getClass ( ) , PropertyDescriptor :: getWriteMethod ) ; if ( getter != null && setter != null ) { // Property value may contain tokens that require substitution. String propertyValueByToken = tokenSubstitutor ( ( String ) getter . invoke ( config ) ) ; setter . invoke ( config , propertyValueByToken ) ; } } catch ( final InvocationTargetException | IllegalAccessException e ) { throw new ConfigurationException ( "Failed to get complete configuration for " + configClass . getSimpleName ( ) , e ) ; } } } return config ; }


Input: Acquire decode and decrypt a configuration object from a data stream . [CODESPLIT] private < T > T getConfig ( final Class < T > configClass ) throws ConfigurationException { Iterator < Name > it = getServicePath ( ) . descendingPathIterator ( ) ; while ( it . hasNext ( ) ) { try ( InputStream in = getConfigurationStream ( configClass , it . next ( ) ) ) { return decoder . deserialise ( in , configClass ) ; } catch ( final ConfigurationException e ) { LOG . trace ( "No configuration at this path level" , e ) ; } catch ( final CodecException | IOException e ) { incrementErrors ( ) ; throw new ConfigurationException ( "Failed to get configuration for " + configClass . getSimpleName ( ) , e ) ; } } incrementErrors ( ) ; throw new ConfigurationException ( "No configuration found for " + configClass . getSimpleName ( ) ) ; }


Input: Checks whether the string substitution functionality should be enabled . [CODESPLIT] private static boolean getIsSubstitutorEnabled ( final BootstrapConfiguration bootstrapConfig ) { final String ENABLE_SUBSTITUTOR_CONFIG_KEY = "CAF_CONFIG_ENABLE_SUBSTITUTOR" ; final boolean ENABLE_SUBSTITUTOR_CONFIG_DEFAULT = true ; // Return the default if the setting is not configured if ( ! bootstrapConfig . isConfigurationPresent ( ENABLE_SUBSTITUTOR_CONFIG_KEY ) ) { return ENABLE_SUBSTITUTOR_CONFIG_DEFAULT ; } // Return the configured setting. // The ConfigurationException should never happen since isConfigurationPresent() has already been called. try { return bootstrapConfig . getConfigurationBoolean ( ENABLE_SUBSTITUTOR_CONFIG_KEY ) ; } catch ( final ConfigurationException ex ) { throw new RuntimeException ( ex ) ; } }


Input: Excludes all com . sun . jersey classes . [CODESPLIT] @ Override public < T > Iterator < Class < T > > createClassIterator ( final Class < T > service , final String serviceName , final ClassLoader loader , final boolean ignoreOnClassNotFound ) { final Iterator < Class < T > > delegateClassIterator = delegate . createClassIterator ( service , serviceName , loader , ignoreOnClassNotFound ) ; Stream < Class < T > > stream = StreamSupport . stream ( Spliterators . spliteratorUnknownSize ( delegateClassIterator , Spliterator . ORDERED ) , false ) ; return stream . filter ( t -> ! t . getPackage ( ) . getName ( ) . startsWith ( "com.sun.jersey" ) ) . collect ( Collectors . toList ( ) ) . iterator ( ) ; }


Input: Returns the Decoder that should be used to interpret the configuration files . [CODESPLIT] @ Override public Decoder getDecoder ( final BootstrapConfiguration bootstrap , final Decoder defaultDecoder ) { final String DECODER_CONFIG_KEY = "CAF_CONFIG_DECODER" ; final String decoder ; try { // Return the specified default Decoder if none has been configured if ( ! bootstrap . isConfigurationPresent ( DECODER_CONFIG_KEY ) ) { return defaultDecoder ; } // Lookup the Decoder to use decoder = bootstrap . getConfiguration ( DECODER_CONFIG_KEY ) ; } catch ( final ConfigurationException ex ) { // Throw a RuntimeException since this shouldn't happen // (since isConfigurationPresent() has already been called) throw new RuntimeException ( ex ) ; } try { // Retrieve the Decoder using the ModuleProvider return ModuleProvider . getInstance ( ) . getModule ( Decoder . class , decoder ) ; } catch ( final NullPointerException ex ) { throw new RuntimeException ( "Unable to get Decoder using " + DECODER_CONFIG_KEY + " value: " + decoder , ex ) ; } }


Input: Determine the first advertised service implementation for the specified interface . The implementations are advertised via the Java ServiceLoader mechanism . [CODESPLIT] public static < T > T getService ( final Class < T > intf ) throws ModuleLoaderException { return getService ( intf , null ) ; }


Input: Determine the first advertised service implementation for the specified interface . The implementations are advertised via the Java ServiceLoader mechanism . [CODESPLIT] public static < T > T getService ( final Class < T > intf , final Class < ? extends T > defaultImpl ) throws ModuleLoaderException { final T implementation = getServiceOrElse ( intf , null ) ; if ( implementation != null ) { return implementation ; } if ( defaultImpl == null ) { throw new ModuleLoaderException ( "Missing implementation: " + intf ) ; } try { return defaultImpl . getConstructor ( ) . newInstance ( ) ; } catch ( final InstantiationException | IllegalAccessException | InvocationTargetException | NoSuchMethodException e ) { throw new ModuleLoaderException ( "Cannot instantiate class" , e ) ; } }


Input: Determine the first advertised service implementation for the specified interface . The implementations are advertised via the Java ServiceLoader mechanism . [CODESPLIT] public static < T > T getServiceOrElse ( final Class < T > intf , final T defaultObj ) { Objects . requireNonNull ( intf ) ; final T ret ; List < T > implementations = getServices ( intf ) ; if ( implementations . isEmpty ( ) ) { return defaultObj ; } else { ret = implementations . get ( 0 ) ; } if ( implementations . size ( ) > 1 ) { LOG . warn ( "There is more than one implementation of {} available on the classpath, taking the first available" , intf ) ; } LOG . info ( "Detected component implementation {}" , ret . getClass ( ) . getSimpleName ( ) ) ; return ret ; }


Input: Get all advertised service implementations of the specified interface . [CODESPLIT] public static < T > List < T > getServices ( final Class < T > intf ) { Objects . requireNonNull ( intf ) ; List < T > ret = new LinkedList <> ( ) ; for ( final T t : ServiceLoader . load ( intf ) ) { ret . add ( t ) ; } return ret ; }


Input: Retrieves a module by its simple name that implements a particular type T [CODESPLIT] public < T > T getModule ( final Class < T > interfaceImplemented , final String moduleType ) throws NullPointerException { //check for this type in the map Map < String , Object > computedValue = loadedModules . computeIfAbsent ( interfaceImplemented , ModuleProvider :: loadModules ) ; Object moduleInstance = computedValue . get ( moduleType ) ; Objects . requireNonNull ( moduleInstance , "Unable to find implementation of " + interfaceImplemented . getName ( ) + " with moduleType " + moduleType ) ; return ( T ) moduleInstance ; }


Input: Return the referenced data as a stream potentially performing a remote lookup . [CODESPLIT] public synchronized InputStream acquire ( final DataSource source ) throws DataSourceException { InputStream ret ; if ( data == null ) { if ( getReference ( ) == null ) { throw new IllegalStateException ( "No data or reference present" ) ; } else { ret = source . getStream ( getReference ( ) ) ; } } else { ret = new ByteArrayInputStream ( data ) ; } return ret ; }


Input: Determine the size of the data . [CODESPLIT] public synchronized long size ( final DataSource source ) throws DataSourceException { if ( data == null ) { if ( getReference ( ) == null ) { throw new IllegalStateException ( "No data or reference present" ) ; } else { return source . getDataSize ( getReference ( ) ) ; } } else { return data . length ; } }


Input: Create a ReferencedData instance that wraps data but also has a reference . [CODESPLIT] public static ReferencedData getWrappedData ( final String ref , final byte [ ] data ) { return new ReferencedData ( Objects . requireNonNull ( ref ) , data ) ; }


Input: Get the components of the Name at the specified numeric index [CODESPLIT] public String getIndex ( final int index ) { if ( index < 0 || index >= components . size ( ) ) { throw new IllegalArgumentException ( "Index out of bounds" ) ; } return components . get ( index ) ; }


Input: Return a Name that consists of a subsection of the current Name . [CODESPLIT] public Name getPrefix ( final int upperIndex ) { if ( upperIndex < 0 || upperIndex > components . size ( ) ) { throw new IllegalArgumentException ( "Index out of bounds" ) ; } return new Name ( components . subList ( 0 , upperIndex ) ) ; }


Input: is an arc colored and hence on a color chain? [CODESPLIT] boolean colored ( ) { return type == Compiler . PLAIN || type == Compiler . AHEAD || type == Compiler . BEHIND ; }


Input: exec - match regular expression [CODESPLIT] boolean exec ( HsrePattern re , CharSequence data , EnumSet < ExecFlags > execFlags ) throws RegexException { /* sanity checks */ /* setup */ if ( 0 != ( re . guts . info & Flags . REG_UIMPOSSIBLE ) ) { throw new RegexException ( "Regex marked impossible" ) ; } eflags = 0 ; for ( ExecFlags ef : execFlags ) { switch ( ef ) { case NOTBOL : eflags |= Flags . REG_NOTBOL ; break ; case NOTEOL : eflags |= Flags . REG_NOTEOL ; break ; case LOOKING_AT : eflags |= Flags . REG_LOOKING_AT ; break ; default : throw new RuntimeException ( "impossible exec flag" ) ; } } this . re = re ; this . g = re . guts ; this . data = data ; this . dataLength = this . data . length ( ) ; if ( this . match != null ) { this . match . clear ( ) ; } else { this . match = Lists . newArrayList ( ) ; } match . add ( null ) ; // make room for 1. if ( 0 != ( g . info & Flags . REG_UBACKREF ) ) { while ( match . size ( ) < g . nsub + 1 ) { match . add ( null ) ; } } if ( mem != null && mem . length >= g . ntree ) { Arrays . fill ( mem , 0 ) ; } else { mem = new int [ g . ntree ] ; } /* do it */ assert g . tree != null ; if ( 0 != ( g . info & Flags . REG_UBACKREF ) ) { return cfind ( g . tree . machine ) ; } else { return find ( g . tree . machine ) ; } }


Input:
find - find a match for the main NFA ( no - complications case ) <p > First it runs the search machine in non - greedy mode ( shortest ) . The search machine is the NFA with . * added to the front and the back more or less . See makesearch . In many cases running the search machine shortest is considerably faster than running the actual regular expression in greedy ( longest ) . So even though this may seem like it would take extra time doing an extra scan the alternative is much slower . The search machine tells you if the expression can be found anywhere and if so where is the furthest possible end . < / p > <p > If the search machine succeeds the does an iteration to find the exact bounds ; the loop uses longest or shortest as appropriate to the flags . In C there was an option to _only_ run the search machine and return a simple boolean with no bounds . We have no API for that via an ExecFlag . < / p > <p > If the top - level API call is lookingAt we never want to scan down the data looking for matches . But shortest can still be much faster than longest . So the code runs the original machine first . If non - greedy expressions were very common I suppose that it would be faster to omit this step in that case . Thereafter the loop has a check to bail if these is no match at the beginning of the data which is the constraint of lookingAt . < / p > [CODESPLIT] boolean find ( Cnfa cnfa ) { int begin ; int end = - 1 ; int cold ; int open ; /* open and close of range of possible starts */ int close ; boolean hitend ; boolean shorter = 0 != ( g . tree . flags & Subre . SHORTER ) ; boolean lookingAt = 0 != ( eflags & Flags . REG_LOOKING_AT ) ; int [ ] coldp = new int [ 1 ] ; Dfa d = new Dfa ( this , cnfa ) ; if ( lookingAt ) { /*
             * shortest is faster than longest. So, we want to check with it.
             * However, since we aren't making a 'search re' with an extra .* on
             * the front, we don't add an extra requirement to make progress on the
             * very first arc. If the expression has something like a* at the front,
             * it can 'no-progress' consuming the a characters.
             * All of this casts doubts on the 'requireInitialProgress' feature -- at all.
             * These initial calls to shortest should be all the opportunity we need
             * to do 'lookingAt'.
             */ close = d . shortest ( 0 , 0 , data . length ( ) , coldp , null ) ; cold = 0 ; } else { /* First, a shot with the search RE. */ Dfa s = new Dfa ( this , g . search ) ; close = s . shortest ( 0 , 0 , data . length ( ) , coldp , null ) ; cold = coldp [ 0 ] ; } if ( close == - 1 ) { /* not found */ return false ; } /* find starting point and match */ open = cold ; cold = - 1 ; for ( begin = open ; begin <= close ; begin ++ ) { /*
             * if LOOKING_AT, we can't validly have a 'begin' after 'open'.
             * I'm not sure this test can even ever go off, since the 'shortest' test
             * up above should accomplish the same thing.
             */ if ( begin > 0 && lookingAt ) { return false ; } boolean [ ] hitendp = new boolean [ 1 ] ; if ( shorter ) { end = d . shortest ( begin , begin , data . length ( ) , null , hitendp ) ; } else { end = d . longest ( begin , data . length ( ) , hitendp ) ; } hitend = hitendp [ 0 ] ; if ( hitend && cold == - 1 ) { cold = begin ; } if ( end != - 1 ) { /* success */ break ; /* NOTE BREAK OUT */ } } if ( end == - 1 ) { return false ; } /* and pin down details */ match . set ( 0 , new RegMatch ( begin , end ) ) ; // no need to do the work. return re . nsub <= 0 || dissect ( g . tree , begin , end ) ; }


Input: cfind - find a match for the main NFA ( with complications ) [CODESPLIT] private boolean cfind ( Cnfa cnfa ) { int [ ] cold = new int [ 1 ] ; Dfa s = new Dfa ( this , g . search ) ; Dfa d = new Dfa ( this , cnfa ) ; return cfindloop ( d , s , cold ) ; }


Input:
cfindloop - the heart of cfind [CODESPLIT] private boolean cfindloop ( Dfa d , Dfa s , int [ ] coldp ) { int begin ; int end ; int cold ; int open ; /* open and close of range of possible starts */ int close ; int estart ; int estop ; boolean shorter = 0 != ( g . tree . flags & Subre . SHORTER ) ; boolean hitend [ ] = new boolean [ 1 ] ; boolean lookingAt = 0 != ( eflags & Flags . REG_LOOKING_AT ) ; assert d != null && s != null ; close = 0 ; do { int [ ] cold0 = new int [ 1 ] ; /*
             * Call search NFA to see if this is possible at all.
             */ if ( lookingAt ) { // in the looking at case, we use the un-search-ified RE. close = d . shortest ( close , close , data . length ( ) , cold0 , null ) ; cold = 0 ; } else { close = s . shortest ( close , close , data . length ( ) , cold0 , null ) ; cold = cold0 [ 0 ] ; } if ( close == - 1 ) { break ; /* NOTE BREAK */ } assert cold != - 1 ; open = cold ; cold = - 1 ; for ( begin = open ; begin <= close ; begin ++ ) { if ( begin > 0 && lookingAt ) { // Is this possible given the looking-at constraint in the call to shortest above? return false ; } estart = begin ; estop = data . length ( ) ; for ( ; ; ) { if ( shorter ) { end = d . shortest ( begin , estart , estop , null , hitend ) ; } else { end = d . longest ( begin , estop , hitend ) ; } if ( hitend [ 0 ] && cold == - 1 ) { cold = begin ; } if ( end == - 1 ) { break ; /* NOTE BREAK OUT */ } for ( int x = 0 ; x < match . size ( ) ; x ++ ) { match . set ( x , null ) ; } int maxsubno = getMaxSubno ( g . tree , 0 ) ; mem = new int [ maxsubno + 1 ] ; boolean matched = cdissect ( g . tree , begin , end ) ; if ( matched ) { // indicate the full match bounds. match . set ( 0 , new RegMatch ( begin , end ) ) ; coldp [ 0 ] = cold ; return true ; } if ( shorter ? end == estop : end == begin ) { /* no point in trying again */ coldp [ 0 ] = cold ; return false ; } /* go around and try again */ if ( shorter ) { estart = end + 1 ; } else { estop = end - 1 ; } } } } while ( close < data . length ( ) ) ; coldp [ 0 ] = cold ; return false ; }


Input: subset - set any subexpression relevant to a successful subre [CODESPLIT] private void subset ( RuntimeSubexpression sub , int begin , int end ) { int n = sub . number ; assert n > 0 ; while ( match . size ( ) < ( n + 1 ) ) { match . add ( null ) ; } match . set ( n , new RegMatch ( begin , end ) ) ; }


Input: dissect - determine subexpression matches ( uncomplicated case ) [CODESPLIT] private boolean dissect ( RuntimeSubexpression t , int begin , int end ) { switch ( t . op ) { case ' ' : /* terminal node */ assert t . left == null && t . right == null ; return true ; /* no action, parent did the work */ case ' ' : /* alternation */ assert t . left != null ; return altdissect ( t , begin , end ) ; case ' ' : /* back ref -- shouldn't be calling us! */ throw new RuntimeException ( "impossible backref" ) ; case ' ' : /* concatenation */ assert t . left != null && t . right != null ; return condissect ( t , begin , end ) ; case ' ' : /* capturing */ assert t . left != null && t . right == null ; assert t . number > 0 ; subset ( t , begin , end ) ; return dissect ( t . left , begin , end ) ; default : throw new RuntimeException ( "Impossible op" ) ; } }


Input: condissect - determine concatenation subexpression matches ( uncomplicated ) [CODESPLIT] private boolean condissect ( RuntimeSubexpression t , int begin , int end ) { Dfa d ; Dfa d2 ; int mid ; assert t . op == ' ' ; assert t . left != null && t . left . machine . states . length > 0 ; assert t . right != null && t . right . machine . states . length > 0 ; boolean shorter = ( t . left . flags & Subre . SHORTER ) != 0 ; int stop = shorter ? end : begin ; d = new Dfa ( this , t . left . machine ) ; d2 = new Dfa ( this , t . right . machine ) ; /* pick a tentative midpoint */ if ( shorter ) { mid = d . shortest ( begin , begin , end , null , null ) ; } else { mid = d . longest ( begin , end , null ) ; } if ( mid == - 1 ) { throw new RuntimeException ( "Impossible mid." ) ; } /* iterate until satisfaction or failure */ while ( d2 . longest ( mid , end , null ) != end ) { /* that midpoint didn't work, find a new one */ if ( mid == stop ) { /* all possibilities exhausted! */ throw new RuntimeException ( "no midpoint" ) ; } if ( shorter ) { mid = d . shortest ( begin , mid + 1 , end , null , null ) ; } else { mid = d . longest ( begin , mid - 1 , null ) ; } if ( mid == - 1 ) { throw new RuntimeException ( "Failed midpoint" ) ; } } /* satisfaction */ boolean dissectMatch = dissect ( t . left , begin , mid ) ; if ( ! dissectMatch ) { return false ; } return dissect ( t . right , mid , end ) ; }


Input: altdissect - determine alternative subexpression matches ( uncomplicated ) [CODESPLIT] private boolean altdissect ( RuntimeSubexpression t , int begin , int end ) { Dfa d ; assert t != null ; assert t . op == ' ' ; for ( ; t != null ; t = t . right ) { assert t . left != null && t . left . machine . states . length > 0 ; d = new Dfa ( this , t . left . machine ) ; if ( d . longest ( begin , end , null ) == end ) { return dissect ( t . left , begin , end ) ; } } throw new RuntimeException ( "none matched" ) ; }


Input: cdissect - determine subexpression matches ( with complications ) The retry memory stores the offset of the trial midpoint from begin plus 1 so that 0 uniquely means clean slate . [CODESPLIT] private boolean cdissect ( RuntimeSubexpression t , int begin , int end ) { assert t != null ; switch ( t . op ) { case ' ' : /* terminal node */ assert t . left == null && t . right == null ; return true ; /* no action, parent did the work */ case ' ' : /* alternation */ assert t . left != null ; return caltdissect ( t , begin , end ) ; case ' ' : /* back ref -- shouldn't be calling us! */ assert t . left == null && t . right == null ; return cbrdissect ( t , begin , end ) ; case ' ' : /* concatenation */ assert t . left != null && t . right != null ; return ccondissect ( t , begin , end ) ; case ' ' : /* capturing */ assert t . left != null && t . right == null ; assert t . number > 0 ; boolean cdmatch = cdissect ( t . left , begin , end ) ; if ( cdmatch ) { subset ( t , begin , end ) ; } return cdmatch ; default : throw new RuntimeException ( "Impossible op" ) ; } }


Input: crevdissect - determine backref shortest - first subexpression matches The retry memory stores the offset of the trial midpoint from begin plus 1 so that 0 uniquely means clean slate . [CODESPLIT] private boolean crevdissect ( RuntimeSubexpression t , int begin , int end ) { Dfa d ; Dfa d2 ; int mid ; assert t . op == ' ' ; assert t . left != null && t . left . machine . states . length > 0 ; assert t . right != null && t . right . machine . states . length > 0 ; assert 0 != ( t . left . flags & Subre . SHORTER ) ; /* concatenation -- need to split the substring between parts */ d = new Dfa ( this , t . left . machine ) ; d2 = new Dfa ( this , t . right . machine ) ; /* pick a tentative midpoint */ if ( mem [ t . retry ] == 0 ) { mid = d . shortest ( begin , begin , end , null , null ) ; if ( mid == - 1 ) { return false ; } mem [ t . retry ] = ( mid - begin ) + 1 ; } else { mid = begin + ( mem [ t . retry ] - 1 ) ; } /* iterate until satisfaction or failure */ for ( ; ; ) { /* try this midpoint on for size */ boolean cdmatch = cdissect ( t . left , begin , mid ) ; if ( cdmatch && d2 . longest ( mid , end , null ) == end && ( cdissect ( t . right , mid , end ) ) ) { break ; /* NOTE BREAK OUT */ } /* that midpoint didn't work, find a new one */ if ( mid == end ) { /* all possibilities exhausted */ return false ; } mid = d . shortest ( begin , mid + 1 , end , null , null ) ; if ( mid == - 1 ) { /* failed to find a new one */ return false ; } mem [ t . retry ] = ( mid - begin ) + 1 ; zapmem ( t . left ) ; zapmem ( t . right ) ; } /* satisfaction */ return true ; }


Input: cbrdissect - determine backref subexpression matches [CODESPLIT] private boolean cbrdissect ( RuntimeSubexpression t , int begin , int end ) { int i ; int n = t . number ; int len ; int paren ; int p ; int stop ; int min = t . min ; int max = t . max ; assert t . op == ' ' ; assert n >= 0 ; //TODO: could this get be out of range? if ( match . get ( n ) == null ) { return false ; } paren = match . get ( n ) . start ; len = match . get ( n ) . end - match . get ( n ) . start ; /* no room to maneuver -- retries are pointless */ if ( 0 != mem [ t . retry ] ) { return false ; } mem [ t . retry ] = 1 ; /* special-case zero-length string */ if ( len == 0 ) { return begin == end ; } /* and too-short string */ assert end >= begin ; if ( ( end - begin ) < len ) { return false ; } stop = end - len ; /* count occurrences */ i = 0 ; for ( p = begin ; p <= stop && ( i < max || max == Compiler . INFINITY ) ; p += len ) { // paren is index of if ( g . compare . compare ( data , paren , p , len ) != 0 ) { break ; } i ++ ; } /* and sort it out */ if ( p != end ) { /* didn't consume all of it */ return false ; } return min <= i && ( i <= max || max == Compiler . INFINITY ) ; }


Input: / * - caltdissect - determine alternative subexpression matches ( w . complications ) ^ static int caltdissect ( struct vars * struct Subre int int ) ; [CODESPLIT] private boolean caltdissect ( RuntimeSubexpression t , int begin , int end ) { Dfa d ; if ( t == null ) { return false ; } assert t . op == ' ' ; if ( mem [ t . retry ] == TRIED ) { return caltdissect ( t . right , begin , end ) ; } if ( mem [ t . retry ] == UNTRIED ) { d = new Dfa ( this , t . left . machine ) ; if ( d . longest ( begin , end , null ) != end ) { mem [ t . retry ] = TRIED ; return caltdissect ( t . right , begin , end ) ; } mem [ t . retry ] = TRYING ; } boolean cdmatch = cdissect ( t . left , begin , end ) ; if ( cdmatch ) { return true ; } mem [ t . retry ] = TRIED ; return caltdissect ( t . right , begin , end ) ; }


Input:
makesearch - turn an NFA into a search NFA ( implicit prepend of . * ? ) NFA must have been optimize () d already . [CODESPLIT] private void makesearch ( Nfa nfa ) { Arc a ; Arc b ; State pre = nfa . pre ; State s ; State s2 ; State slist ; /* no loops are needed if it's anchored */ for ( a = pre . outs ; a != null ; a = a . outchain ) { assert a . type == PLAIN ; if ( a . co != nfa . bos [ 0 ] && a . co != nfa . bos [ 1 ] ) { break ; } } if ( a != null ) { /* add implicit .* in front */ cm . rainbow ( nfa , PLAIN , Constants . COLORLESS , pre , pre ) ; /* and ^* and \A* too -- not always necessary, but harmless */ nfa . newarc ( PLAIN , nfa . bos [ 0 ] , pre , pre ) ; nfa . newarc ( PLAIN , nfa . bos [ 1 ] , pre , pre ) ; } /*
     * Now here's the subtle part.  Because many REs have no lookback
     * constraints, often knowing when you were in the pre state tells
     * you little; it's the next state(s) that are informative.  But
     * some of them may have other inarcs, i.e. it may be possible to
     * make actual progress and then return to one of them.  We must
     * de-optimize such cases, splitting each such state into progress
     * and no-progress states.
     */ /* first, make a list of the states */ slist = null ; for ( a = pre . outs ; a != null ; a = a . outchain ) { s = a . to ; for ( b = s . ins ; b != null ; b = b . inchain ) { if ( b . from != pre ) { break ; } } if ( b != null ) { /* must be split */ if ( s . tmp == null ) { /* if not already in the list */ /* (fixes bugs 505048, 230589, */ /* 840258, 504785) */ s . tmp = slist ; slist = s ; } } } /* do the splits */ for ( s = slist ; s != null ; s = s2 ) { s2 = nfa . newstate ( ) ; copyouts ( nfa , s , s2 ) ; for ( a = s . ins ; a != null ; a = b ) { b = a . inchain ; if ( a . from != pre ) { cparc ( nfa , a , a . from , s2 ) ; nfa . freearc ( a ) ; } } s2 = s . tmp ; s . tmp = null ; /* clean up while we're at it */ } }


Input: cloneouts - copy out arcs of a state to another state pair modifying type [CODESPLIT] private void cloneouts ( Nfa nfa , State old , State from , State to , int type ) { Arc a ; assert old != from ; for ( a = old . outs ; a != null ; a = a . outchain ) { nfa . newarc ( type , a . co , from , to ) ; } }


Input: optst - optimize a subRE subtree [CODESPLIT] private void optst ( Subre t ) { if ( t == null ) { return ; } /* recurse through children */ if ( t . left != null ) { optst ( t . left ) ; } if ( t . right != null ) { optst ( t . right ) ; } }


Input: numst - number tree nodes ( assigning retry indexes ) [CODESPLIT] private int numst ( Subre t , int start ) { int i ; assert t != null ; i = start ; t . retry = ( short ) i ++ ; if ( t . left != null ) { i = numst ( t . left , i ) ; } if ( t . right != null ) { i = numst ( t . right , i ) ; } return i ; }


Input: markst - mark tree nodes as INUSE [CODESPLIT] private void markst ( Subre t ) { assert t != null ; t . flags |= Subre . INUSE ; if ( t . left != null ) { markst ( t . left ) ; } if ( t . right != null ) { markst ( t . right ) ; } }


Input: / * optimize results from top node [CODESPLIT] private long nfatree ( Subre t ) throws RegexException { assert t != null && t . begin != null ; if ( t . left != null ) { nfatree ( t . left ) ; } if ( t . right != null ) { nfatree ( t . right ) ; } return nfanode ( t ) ; }


Input: nfanode - do one NFA for nfatree [CODESPLIT] private long nfanode ( Subre t ) throws RegexException { long ret ; assert t . begin != null ; if ( LOG . isDebugEnabled ( ) && IS_DEBUG ) { LOG . debug ( String . format ( "========= TREE NODE %s ==========" , t . shortId ( ) ) ) ; } Nfa newNfa = new Nfa ( nfa ) ; newNfa . dupnfa ( t . begin , t . end , newNfa . init , newNfa . finalState ) ; newNfa . specialcolors ( ) ; ret = newNfa . optimize ( ) ; t . cnfa = newNfa . compact ( ) ; // freenfa ... depend on our friend the GC. return ret ; }


Input: parse - parse an RE This is actually just the top level which parses a bunch of branches tied together with | . They appear in the tree as the left children of a chain of | subres . [CODESPLIT] private Subre parse ( int stopper , int type , State initState , State finalState ) throws RegexException { State left ; /* scaffolding for branch */ State right ; Subre branches ; /* top level */ Subre branch ; /* current branch */ Subre t ; /* temporary */ int firstbranch ; /* is this the first branch? */ assert stopper == ' ' || stopper == EOS ; branches = new Subre ( ' ' , Subre . LONGER , initState , finalState ) ; branch = branches ; firstbranch = 1 ; do { /* a branch */ if ( 0 == firstbranch ) { /* need a place to hang it */ branch . right = new Subre ( ' ' , Subre . LONGER , initState , finalState ) ; branch = branch . right ; } firstbranch = 0 ; left = nfa . newstate ( ) ; right = nfa . newstate ( ) ; nfa . emptyarc ( initState , left ) ; nfa . emptyarc ( right , finalState ) ; branch . left = parsebranch ( stopper , type , left , right , false ) ; branch . flags |= up ( branch . flags | branch . left . flags ) ; if ( ( branch . flags & ~ branches . flags ) != 0 ) /* new flags */ { for ( t = branches ; t != branch ; t = t . right ) { t . flags |= branch . flags ; } } } while ( eat ( ' ' ) ) ; assert see ( stopper ) || see ( EOS ) ; if ( ! see ( stopper ) ) { assert stopper == ' ' && see ( EOS ) ; //ERR(REG_EPAREN); throw new RegexException ( "Unbalanced parentheses." ) ; } /* optimize out simple cases */ if ( branch == branches ) { /* only one branch */ assert branch . right == null ; t = branch . left ; branch . left = null ; branches = t ; } else if ( ! messy ( branches . flags ) ) { /* no interesting innards */ branches . left = null ; branches . right = null ; branches . op = ' ' ; } return branches ; }


Input: parsebranch - parse one branch of an RE This mostly manages concatenation working closely with parseqatom () . Concatenated things are bundled up as much as possible with separate nodes introduced only when necessary due to substructure . [CODESPLIT] private Subre parsebranch ( int stopper , int type , State left , State right , boolean partial ) throws RegexException { State lp ; /* left end of current construct */ boolean seencontent = false ; /* is there anything in this branch yet? */ Subre t ; lp = left ; t = new Subre ( ' ' , 0 , left , right ) ; /* op '=' is tentative */ while ( ! see ( ' ' ) && ! see ( stopper ) && ! see ( EOS ) ) { if ( seencontent ) { /* implicit concat operator */ lp = nfa . newstate ( ) ; moveins ( nfa , right , lp ) ; } seencontent = true ; /* NB, recursion in parseqatom() may swallow rest of branch */ parseqatom ( stopper , type , lp , right , t ) ; } if ( ! seencontent ) { /* empty branch */ if ( ! partial ) { note ( Flags . REG_UUNSPEC ) ; } nfa . emptyarc ( left , right ) ; } return t ; }


Input:
CHECKSTYLE : OFF [CODESPLIT] private void parseqatom ( int stopper , int type , State lp , State rp , Subre top ) throws RegexException { State s ; /* temporaries for new states */ State s2 ; int m ; int n ; Subre atom ; /* atom's subtree */ Subre t ; boolean cap ; /* capturing parens? */ int pos ; /* positive lookahead? */ int subno ; /* capturing-parens or backref number */ int atomtype ; int qprefer ; /* quantifier short/long preference */ int f ; AtomSetter atomp ; /* initial bookkeeping */ atom = null ; assert lp . nouts == 0 ; /* must string new code */ assert rp . nins == 0 ; /*  between lp and rp */ subno = 0 ; /* just to shut lint up */ /* an atom or constraint... */ atomtype = nexttype ; switch ( atomtype ) { /* first, constraints, which end by returning */ case ' ' : nfa . newarc ( ' ' , ( short ) 1 , lp , rp ) ; if ( 0 != ( cflags & Flags . REG_NLANCH ) ) { nfa . newarc ( BEHIND , nlcolor , lp , rp ) ; } lex . next ( ) ; return ; case ' ' : nfa . newarc ( ' ' , ( short ) 1 , lp , rp ) ; if ( 0 != ( cflags & Flags . REG_NLANCH ) ) { nfa . newarc ( AHEAD , nlcolor , lp , rp ) ; } lex . next ( ) ; return ; case SBEGIN : nfa . newarc ( ' ' , ( short ) 1 , lp , rp ) ; /* BOL */ nfa . newarc ( ' ' , ( short ) 0 , lp , rp ) ; /* or BOS */ lex . next ( ) ; return ; case SEND : nfa . newarc ( ' ' , ( short ) 1 , lp , rp ) ; /* EOL */ nfa . newarc ( ' ' , ( short ) 0 , lp , rp ) ; /* or EOS */ lex . next ( ) ; return ; case ' ' : wordchrs ( ) ; /* does next() */ s = nfa . newstate ( ) ; nonword ( BEHIND , lp , s ) ; word ( AHEAD , s , rp ) ; return ; case ' ' : wordchrs ( ) ; /* does next() */ s = nfa . newstate ( ) ; word ( BEHIND , lp , s ) ; nonword ( AHEAD , s , rp ) ; return ; case WBDRY : wordchrs ( ) ; /* does next() */ s = nfa . newstate ( ) ; nonword ( BEHIND , lp , s ) ; word ( AHEAD , s , rp ) ; s = nfa . newstate ( ) ; word ( BEHIND , lp , s ) ; nonword ( AHEAD , s , rp ) ; return ; case NWBDRY : wordchrs ( ) ; /* does next() */ s = nfa . newstate ( ) ; word ( BEHIND , lp , s ) ; word ( AHEAD , s , rp ) ; s = nfa . newstate ( ) ; nonword ( BEHIND , lp , s ) ; nonword ( AHEAD , s , rp ) ; return ; case LACON : /* lookahead constraint */ pos = nextvalue ; lex . next ( ) ; s = nfa . newstate ( ) ; s2 = nfa . newstate ( ) ; parse ( ' ' , LACON , s , s2 ) ; // parse for side-effect. assert see ( ' ' ) ; lex . next ( ) ; n = newlacon ( s , s2 , pos ) ; nfa . newarc ( LACON , ( short ) n , lp , rp ) ; return ; /* then errors, to get them out of the way */ case ' ' : case ' ' : case ' ' : case ' ' : throw new RegexException ( "Pattern syntax error (*+?} misplaced)." ) ; /* then plain characters, and minor variants on that theme */ case ' ' : /* unbalanced paren */ if ( ( cflags & Flags . REG_ADVANCED ) != Flags . REG_EXTENDED ) { throw new RegexException ( "Unbalanced parenthesis." ) ; } /* legal in EREs due to specification botch */ note ( Flags . REG_UPBOTCH ) ; /* fallthrough into case PLAIN */ case PLAIN : // look out for surrogates as ordinary chars. if ( nextvalue < Character . MAX_VALUE && Character . isHighSurrogate ( ( char ) nextvalue ) ) { char high = ( char ) nextvalue ; lex . next ( ) ; char low = ( char ) nextvalue ; int codepoint = Character . toCodePoint ( high , low ) ; onechr ( codepoint , lp , rp ) ; } else { onechr ( nextvalue , lp , rp ) ; } cm . okcolors ( nfa ) ; lex . next ( ) ; break ; case ' ' : if ( nextvalue == 1 ) { bracket ( lp , rp ) ; } else { cbracket ( lp , rp ) ; } assert see ( ' ' ) ; lex . next ( ) ; break ; case ' ' : cm . rainbow ( nfa , PLAIN , ( 0 != ( cflags & Flags . REG_NLSTOP ) ) ? nlcolor : Constants . COLORLESS , lp , rp ) ; lex . next ( ) ; break ; /* and finally the ugly stuff */ case ' ' : /* value flags as capturing or non */ if ( type == LACON ) { cap = false ; } else { cap = nextvalue != 0 ; } if ( cap ) { subno = subs . size ( ) + 1 ; // first subno is 1. /*
                 * This recurses via a call to parse just below.
                 * So, the size() just above has to reflect this new sub,
                 * even though we won't create the object until a little further
                 * down.
                 */ subs . add ( null ) ; } else { atomtype = PLAIN ; /* something that's not '(' */ } lex . next ( ) ; /* need new endpoints because tree will contain pointers */ s = nfa . newstate ( ) ; s2 = nfa . newstate ( ) ; nfa . emptyarc ( lp , s ) ; nfa . emptyarc ( s2 , rp ) ; atom = parse ( ' ' , PLAIN , s , s2 ) ; assert see ( ' ' ) ; lex . next ( ) ; if ( cap ) { // we can't assert anything about the size of 'subs', recursion may have added to it. // but we can check that nothing has used our slot. assert subs . get ( subno - 1 ) == null ; subs . set ( subno - 1 , atom ) ; t = new Subre ( ' ' , atom . flags | Subre . CAP , lp , rp ) ; t . subno = subno ; t . left = atom ; atom = t ; } /* postpone everything else pending possible {0} */ break ; case BACKREF : /* the Feature From The Black Lagoon */ if ( type == LACON ) { throw new RegexException ( "REG_ESUBREG" ) ; } if ( nextvalue > subs . size ( ) ) { throw new RegexException ( String . format ( "Backreference to %d out of range of defined subexpressions (%d)" , nextvalue , subs . size ( ) ) ) ; } if ( subs . get ( nextvalue - 1 ) == null ) { // \1 is first backref, living in slot 0. throw new RegexException ( String . format ( "Backreference to %d refers to non-capturing group." , nextvalue ) ) ; } assert nextvalue > 0 ; atom = new Subre ( ' ' , Subre . BACKR , lp , rp ) ; subno = nextvalue ; atom . subno = subno ; nfa . emptyarc ( lp , rp ) ; /* temporarily, so there's something */ lex . next ( ) ; break ; default : throw new RuntimeException ( "Impossible type in lex" ) ; } /* ...and an atom may be followed by a quantifier */ switch ( nexttype ) { case ' ' : m = 0 ; n = INFINITY ; qprefer = ( nextvalue != 0 ) ? Subre . LONGER : Subre . SHORTER ; lex . next ( ) ; break ; case ' ' : m = 1 ; n = INFINITY ; qprefer = ( nextvalue != 0 ) ? Subre . LONGER : Subre . SHORTER ; lex . next ( ) ; break ; case ' ' : m = 0 ; n = 1 ; qprefer = ( nextvalue != 0 ) ? Subre . LONGER : Subre . SHORTER ; lex . next ( ) ; break ; case ' ' : lex . next ( ) ; m = scannum ( ) ; if ( eat ( ' ' ) ) { if ( see ( DIGIT ) ) { n = scannum ( ) ; } else { n = INFINITY ; } if ( m > n ) { throw new RegexException ( "First quantity is larger than second quantity in {m,n} quantifier." ) ; } /* {m,n} exercises preference, even if it's {m,m} */ qprefer = ( nextvalue != 0 ) ? Subre . LONGER : Subre . SHORTER ; } else { n = m ; /* {m} passes operand's preference through */ qprefer = 0 ; } if ( ! see ( ' ' ) ) { /* catches errors too */ throw new RegexException ( "Invalid syntax for {m,n} quantifier." ) ; } lex . next ( ) ; break ; default : /* no quantifier */ m = 1 ; n = 1 ; qprefer = 0 ; break ; } /* annoying special case:  {0} or {0,0} cancels everything */ if ( m == 0 && n == 0 ) { if ( atomtype == ' ' ) { assert subno == subs . size ( ) - 1 ; subs . remove ( subs . size ( ) - 1 ) ; } delsub ( nfa , lp , rp ) ; nfa . emptyarc ( lp , rp ) ; return ; } /* if not a messy case, avoid hard part */ assert ! messy ( top . flags ) ; f = top . flags | qprefer | ( ( atom != null ) ? atom . flags : 0 ) ; if ( atomtype != ' ' && atomtype != BACKREF && ! messy ( up ( f ) ) ) { if ( ! ( m == 1 && n == 1 ) ) { repeat ( lp , rp , m , n ) ; } top . flags = f ; return ; } /*
     * hard part:  something messy
     * That is, capturing parens, back reference, short/long clash, or
     * an atom with substructure containing one of those.
     */ /* now we'll need a subre for the contents even if they're boring */ if ( atom == null ) { atom = new Subre ( ' ' , 0 , lp , rp ) ; } /*
     * prepare a general-purpose state skeleton
     *
     *    --. [s] ---prefix--. [begin] ---atom--. [end] ----rest--. [rp]
     *   /                                            /
     * [lp] ---. [s2] ----bypass---------------------
     *
     * where bypass is an empty, and prefix is some repetitions of atom
     */ s = nfa . newstate ( ) ; /* first, new endpoints for the atom */ s2 = nfa . newstate ( ) ; nfa . moveouts ( lp , s ) ; nfa . moveins ( rp , s2 ) ; atom . begin = s ; atom . end = s2 ; s = nfa . newstate ( ) ; /* and spots for prefix and bypass */ s2 = nfa . newstate ( ) ; nfa . emptyarc ( lp , s ) ; nfa . emptyarc ( lp , s2 ) ; /* break remaining subRE into x{...} and what follows */ t = new Subre ( ' ' , Subre . combine ( qprefer , atom . flags ) , lp , rp ) ; t . left = atom ; final Subre target = t ; atomp = new AtomSetter ( ) { @ Override public void set ( Subre s ) { target . left = s ; } } ; /* here we should recurse... but we must postpone that to the end */ /* split top into prefix and remaining */ assert top . op == ' ' && top . left == null && top . right == null ; top . left = new Subre ( ' ' , top . flags , top . begin , lp ) ; top . op = ' ' ; top . right = t ; /* if it's a backref, now is the time to replicate the subNFA */ if ( atomtype == BACKREF ) { assert atom . begin . nouts == 1 ; /* just the EMPTY */ delsub ( nfa , atom . begin , atom . end ) ; assert subs . get ( subno - 1 ) != null ; /* and here's why the recursion got postponed:  it must */ /* wait until the skeleton is filled in, because it may */ /* hit a backref that wants to copy the filled-in skeleton */ nfa . dupnfa ( subs . get ( subno - 1 ) . begin , subs . get ( subno - 1 ) . end , atom . begin , atom . end ) ; } /* it's quantifier time; first, turn x{0,...} into x{1,...}|empty */ if ( m == 0 ) { nfa . emptyarc ( s2 , atom . end ) ; /* the bypass */ assert Subre . pref ( qprefer ) != 0 ; f = Subre . combine ( qprefer , atom . flags ) ; t = new Subre ( ' ' , f , lp , atom . end ) ; t . left = atom ; t . right = new Subre ( ' ' , Subre . pref ( f ) , s2 , atom . end ) ; t . right . left = new Subre ( ' ' , 0 , s2 , atom . end ) ; atomp . set ( t ) ; final Subre target2 = t ; atomp = new AtomSetter ( ) { @ Override public void set ( Subre s ) { target2 . left = s ; } } ; m = 1 ; } /* deal with the rest of the quantifier */ if ( atomtype == BACKREF ) { /* special case:  backrefs have internal quantifiers */ nfa . emptyarc ( s , atom . begin ) ; /* empty prefix */ /* just stuff everything into atom */ repeat ( atom . begin , atom . end , m , n ) ; atom . min = ( short ) m ; atom . max = ( short ) n ; atom . flags |= Subre . combine ( qprefer , atom . flags ) ; } else if ( m == 1 && n == 1 ) { /* no/vacuous quantifier:  done */ nfa . emptyarc ( s , atom . begin ) ; /* empty prefix */ } else { /* turn x{m,n} into x{m-1,n-1}x, with capturing */ /*  parens in only second x */ nfa . dupnfa ( atom . begin , atom . end , s , atom . begin ) ; assert m >= 1 && m != INFINITY && n >= 1 ; repeat ( s , atom . begin , m - 1 , ( n == INFINITY ) ? n : n - 1 ) ; f = Subre . combine ( qprefer , atom . flags ) ; t = new Subre ( ' ' , f , s , atom . end ) ; /* prefix and atom */ t . left = new Subre ( ' ' , Subre . pref ( f ) , s , atom . begin ) ; t . right = atom ; atomp . set ( t ) ; } /* and finally, look after that postponed recursion */ t = top . right ; if ( ! ( see ( ' ' ) || see ( stopper ) || see ( EOS ) ) ) { t . right = parsebranch ( stopper , type , atom . end , rp , true ) ; } else { nfa . emptyarc ( atom . end , rp ) ; t . right = new Subre ( ' ' , 0 , atom . end , rp ) ; } assert see ( ' ' ) || see ( stopper ) || see ( EOS ) ; t . flags |= Subre . combine ( t . flags , t . right . flags ) ; top . flags |= Subre . combine ( top . flags , t . flags ) ; }


Input: CHECKSTYLE : ON [CODESPLIT] private void delsub ( Nfa nfa , State lp , State rp ) { rp . tmp = rp ; deltraverse ( nfa , lp , lp ) ; assert lp . nouts == 0 && rp . nins == 0 ; /* did the job */ assert lp . no != State . FREESTATE && rp . no != State . FREESTATE ; /* no more */ lp . tmp = null ; rp . tmp = null ; }


Input: deltraverse - the recursive heart of delsub This routine s basic job is to destroy all out - arcs of the state . [CODESPLIT] private void deltraverse ( Nfa nfa , State leftend , State s ) { Arc a ; State to ; if ( s . nouts == 0 ) { return ; /* nothing to do */ } if ( s . tmp != null ) { return ; /* already in progress */ } s . tmp = s ; /* mark as in progress */ while ( ( a = s . outs ) != null ) { to = a . to ; deltraverse ( nfa , leftend , to ) ; assert to . nouts == 0 || to . tmp != null ; nfa . freearc ( a ) ; if ( to . nins == 0 && to . tmp == null ) { assert to . nouts == 0 ; nfa . freestate ( to ) ; } } assert s . no != State . FREESTATE ; /* we're still here */ assert s == leftend || s . nins != 0 ; /* and still reachable */ assert s . nouts == 0 ; /* but have no outarcs */ s . tmp = null ; /* we're done here */ }


Input: nonword - generate arcs for non - word - character ahead or behind [CODESPLIT] private void nonword ( int dir , State lp , State rp ) { int anchor = ( dir == AHEAD ) ? ' ' : ' ' ; assert dir == AHEAD || dir == BEHIND ; nfa . newarc ( anchor , ( short ) 1 , lp , rp ) ; nfa . newarc ( anchor , ( short ) 0 , lp , rp ) ; cm . colorcomplement ( nfa , dir , wordchrs , lp , rp ) ; /* (no need for special attention to \n) */ }


Input: word - generate arcs for word character ahead or behind [CODESPLIT] private void word ( int dir , State lp , State rp ) { assert dir == AHEAD || dir == BEHIND ; cloneouts ( nfa , wordchrs , lp , rp , dir ) ; /* (no need for special attention to \n) */ }


Input: scannum - scan a number [CODESPLIT] private int scannum ( ) throws RegexException { int n = 0 ; while ( see ( DIGIT ) && n < DUPMAX ) { n = n * 10 + nextvalue ; lex . next ( ) ; } if ( see ( DIGIT ) || n > DUPMAX ) { throw new RegexException ( "Unvalid reference number." ) ; } return n ; }


Input: repeat - replicate subNFA for quantifiers The duplication sequences used here are chosen carefully so that any pointers starting out pointing into the subexpression end up pointing into the last occurrence . ( Note that it may not be strung between the same left and right end states however! ) This used to be important for the subRE tree although the important bits are now handled by the in - line code in parse () and when this is called it doesn t matter any more . [CODESPLIT] private void repeat ( State lp , State rp , int m , int n ) throws RegexException { final int rm = reduce ( m ) ; final int rn = reduce ( n ) ; State s ; State s2 ; switch ( pair ( rm , rn ) ) { // pair(0, 0) case 0 : /* empty string */ // never get here; other code optimizes this out. delsub ( nfa , lp , rp ) ; nfa . emptyarc ( lp , rp ) ; break ; //case PAIR(0, 1):      /* do as x| */ case 1 : nfa . emptyarc ( lp , rp ) ; break ; //case PAIR(0, SOME):       /* do as x{1,n}| */ case SOME : repeat ( lp , rp , 1 , n ) ; nfa . emptyarc ( lp , rp ) ; break ; //case PAIR(0, INF):        /* loop x around */ case INF : s = nfa . newstate ( ) ; nfa . moveouts ( lp , s ) ; nfa . moveins ( rp , s ) ; nfa . emptyarc ( lp , s ) ; nfa . emptyarc ( s , rp ) ; break ; //case PAIR(1, 1):      /* no action required */ case 4 * 1 + 1 : break ; //case PAIR(1, SOME):       /* do as x{0,n-1}x = (x{1,n-1}|)x */ case 4 * 1 + SOME : s = nfa . newstate ( ) ; nfa . moveouts ( lp , s ) ; nfa . dupnfa ( s , rp , lp , s ) ; repeat ( lp , s , 1 , n - 1 ) ; nfa . emptyarc ( lp , s ) ; break ; //case PAIR(1, INF):        /* add loopback arc */ case 4 * 1 + INF : s = nfa . newstate ( ) ; s2 = nfa . newstate ( ) ; nfa . moveouts ( lp , s ) ; nfa . moveins ( rp , s2 ) ; nfa . emptyarc ( lp , s ) ; nfa . emptyarc ( s2 , rp ) ; nfa . emptyarc ( s2 , s ) ; break ; //case PAIR(SOME, SOME):        /* do as x{m-1,n-1}x */ case 4 * SOME + SOME : s = nfa . newstate ( ) ; nfa . moveouts ( lp , s ) ; nfa . dupnfa ( s , rp , lp , s ) ; repeat ( lp , s , m - 1 , n - 1 ) ; break ; //case PAIR(SOME, INF):     /* do as x{m-1,}x */ case 4 * SOME + INF : s = nfa . newstate ( ) ; nfa . moveouts ( lp , s ) ; nfa . dupnfa ( s , rp , lp , s ) ; repeat ( lp , s , m - 1 , n ) ; break ; default : throw new RuntimeException ( "Impossible quantification" ) ; } }