public ResourceRepresentation<V> withNamespace(String namespace, String href) {
    if (!rels.containsKey("curies")) {
      rels = rels.put("curies", Rels.collection("curies"));
    }

    final NamespaceManager updatedNamespaceManager =
        namespaceManager.withNamespace(namespace, href);
    return new ResourceRepresentation<>(
        content, links, rels, updatedNamespaceManager, value, resources);
  }

public ResourceRepresentation < V > withNamespace ( String namespace , String href ) { if ( ! rels . containsKey ( "curies" ) ) { rels = rels . put ( "curies" , Rels . collection ( "curies" ) ) ; } final NamespaceManager updatedNamespaceManager = namespaceManager . withNamespace ( namespace , href ) ; return new ResourceRepresentation <> ( content , links , rels , updatedNamespaceManager , value , resources ) ; }

Adds a new namespace.

@param namespace The CURIE prefix for the namespace being added.
@param href The target href of the namespace being added. This may be relative to the
resourceFactories baseref
@return A new instance of a PersistentRepresentation with the namespace included.


public static boolean canDecode(byte[] input, int off, int len)
	{
		try {
			decode(input, off, len);
		} catch (IllegalArgumentException ex) {
			return false;
		}
		return true;
	}

public static boolean canDecode ( byte [ ] input , int off , int len ) { try { decode ( input , off , len ) ; } catch ( IllegalArgumentException ex ) { return false ; } return true ; }

Returns whether the specified range in the given byte array represents
valid UTF-8 encoded characters.

@param input the input buffer.
@param off the start index, inclusive.
@param len the number of bytes to test.

@return whether the specified range in {@code input} represents UTF-8
encoded characters.

@throws NullPointerException if {@code input} is {@code null}.
@throws IndexOutOfBoundsException if {@code off} or {@code len} is
negative or if {@code off + len} is greater than {@code input}'s
length.

Returns whether the specified range in the given byte array represents valid UTF - 8 encoded characters .


public static byte[] encode(String str, int off, int len)
	{
		return encode(str.substring(off, off + len));
	}

public static byte [ ] encode ( String str , int off , int len ) { return encode ( str . substring ( off , off + len ) ) ; }

Returns the UTF-8 encoding of the specified character sequence.

@param str the input {@code String}.
@param off the start index, inclusive.
@param len the number of characters to encode.

@return the UTF-8 encoding of the specified characters.

@throws NullPointerException if {@code str} is {@code null}.
@throws IndexOutOfBoundsException if {@code off} or {@code len} is
negative or if {@code off + len} is greater than {@code str}'s
length.
@throws IllegalArgumentException if {@code str} can't be encoded into
UTF-8.

Returns the UTF - 8 encoding of the specified character sequence .


public static boolean equal(Reader in1, Reader in2) throws IOException
	{
		if (in1 == in2) {
			return true;
		}
		if (in1 == null || in2 == null) {
			return false;
		}
		in1 = buffer(in1);
		in2 = buffer(in2);
		int c1 = in1.read();
		int c2 = in2.read();
		while (c1 != -1 && c2 != -1 && c1 == c2) {
			c1 = in1.read();
			c2 = in2.read();
		}
		return in1.read() == -1 && in2.read() == -1;
	}

public static boolean equal ( Reader in1 , Reader in2 ) throws IOException { if ( in1 == in2 ) { return true ; } if ( in1 == null || in2 == null ) { return false ; } in1 = buffer ( in1 ) ; in2 = buffer ( in2 ) ; int c1 = in1 . read ( ) ; int c2 = in2 . read ( ) ; while ( c1 != - 1 && c2 != - 1 && c1 == c2 ) { c1 = in1 . read ( ) ; c2 = in2 . read ( ) ; } return in1 . read ( ) == - 1 && in2 . read ( ) == - 1 ; }

Returns whether the given streams have the same content.

@param in1 the first stream.
@param in2 the second stream.

@return {@code true} if the streams have the same content.

@throws IOException if an I/O error occurs during the process.

Returns whether the given streams have the same content .


public static void mv(File src, File dst) throws IOException
	{
		Parameters.checkNotNull(dst);
		if (!src.equals(dst)) {
			cp(src, dst);
			try {
				rm(src);
			} catch (IOException e) {
				rm(dst);
				throw new IOException("Can't move " + src, e);
			}
		}
	}

public
static
void
mv
(
File
src
,
File
dst
)
throws
IOException
{
Parameters
.
checkNotNull
(
dst
)
;
if
(
!
src
.
equals
(
dst
)
)
{
cp
(
src
,
dst
)
;
try
{
rm
(
src
)
;
}
catch
(
IOException
e
)
{
rm
(
dst
)
;
throw
new
IOException
(
"Can't move "
+
src
,
e
)
;
}
}
}

Moves a file from one path to another. Named after the Unix command
of the same name.

@param src the original file.
@param dst the destination path.

@throws NullPointerException if one of the arguments is {@code null}.
@throws IllegalArgumentException if {@code src} is a directory and
{@code dst} is a regular file.
@throws IOException if {@code src} can't be moved to {@code dst}.
@throws SecurityException if a security manager exists and denies
read/write access to {@code src}/{@code dst}.

Moves a file from one path to another . Named after the Unix command of the same name .


public static void touch(File... files) throws IOException
	{
		long now = System.currentTimeMillis();
		for (File f : files) {
			if (!f.createNewFile() && !f.setLastModified(now)) {
				throw new IOException("Failed to touch " + f);
			}
		}
	}

public
static
void
touch
(
File
...
files
)
throws
IOException
{
long
now
=
System
.
currentTimeMillis
(
)
;
for
(
File
f
:
files
)
{
if
(
!
f
.
createNewFile
(
)
&&
!
f
.
setLastModified
(
now
)
)
{
throw
new
IOException
(
"Failed to touch "
+
f
)
;
}
}
}

Creates empty files at the specified paths or updates the last
modification time of the files at the specified paths. Named after
the Unix command of the same name.

@param files the files to touch.

@throws IOException if an I/O error occurs during the process.
@throws SecurityException if a security manager exists and denies
read/write access to one of the specified files.

Creates empty files at the specified paths or updates the last modification time of the files at the specified paths . Named after the Unix command of the same name .


public static String getBaseName(File f)
	{
		String fileName = f.getName();
		int index = fileName.lastIndexOf('.');
		return index == -1 ? fileName : fileName.substring(0, index);
	}

public static String getBaseName ( File f ) { String fileName = f . getName ( ) ; int index = fileName . lastIndexOf ( ' ' ) ; return index == - 1 ? fileName : fileName . substring ( 0 , index ) ; }

Returns the file name without its path or extension. This method is
named after the 'basename' Unix command.

@param f the file to get the base name.

@return {@code f}'s extension-free name.

@throws NullPointerException if {@code f} is {@code null}.

Returns the file name without its path or extension . This method is named after the basename Unix command .


private void addPadding()
	{
		int len = BLOCK_LENGTH - bufferLen;
		if (len < 9) {
			len += BLOCK_LENGTH;
		}
		byte[] buf = new byte[len];
		buf[0] = (byte) 0x80;
		for (int i = 1; i < len - 8; i++) {
			buf[i] = (byte) 0x00;
		}
		counter = (counter + (long) bufferLen) * 8L;
		LittleEndian.encode(counter, buf, len - 8);
		update(buf);
	}

private void addPadding ( ) { int len = BLOCK_LENGTH - bufferLen ; if ( len < 9 ) { len += BLOCK_LENGTH ; } byte [ ] buf = new byte [ len ] ; buf [ 0 ] = ( byte ) 0x80 ; for ( int i = 1 ; i < len - 8 ; i ++ ) { buf [ i ] = ( byte ) 0x00 ; } counter = ( counter + ( long ) bufferLen ) * 8L ; LittleEndian . encode ( counter , buf , len - 8 ) ; update ( buf ) ; }

Adds the padding bits and the message length to the input data.

Adds the padding bits and the message length to the input data .


public static String getShortName(Class<?> c)
	{
		String qname = getQualifiedName(c);
		int start = qname.lastIndexOf('$');
		if (start == -1) {
			start = qname.lastIndexOf('.');
		}
		return qname.substring(start + 1);
	}

public static String getShortName ( Class < ? > c ) { String qname = getQualifiedName ( c ) ; int start = qname . lastIndexOf ( ' ' ) ; if ( start == - 1 ) { start = qname . lastIndexOf ( ' ' ) ; } return qname . substring ( start + 1 ) ; }

Returns only the name of the given class, that is, without its
package name and without its eventual "outer" class name.

@param c the class.

@return the short name of the given class.

@throws NullPointerException if {@code c} is {@code null}.

Returns only the name of the given class that is without its package name and without its eventual outer class name .


public static Set<Class<?>> getSuperTypes(Class<?> c)
	{
		Set<Class<?>> classes = new HashSet<Class<?>>();
		for (Class<?> clazz : c.getInterfaces()) {
			classes.add(clazz);
			classes.addAll(getSuperTypes(clazz));
		}
		Class<?> sup = c.getSuperclass();
		if (sup != null) {
			classes.add(sup);
			classes.addAll(getSuperTypes(sup));
		}
		return Collections.unmodifiableSet(classes);
	}

public static Set < Class < ? > > getSuperTypes ( Class < ? > c ) { Set < Class < ? > > classes = new HashSet < Class < ? > > ( ) ; for ( Class < ? > clazz : c . getInterfaces ( ) ) { classes . add ( clazz ) ; classes . addAll ( getSuperTypes ( clazz ) ) ; } Class < ? > sup = c . getSuperclass ( ) ; if ( sup != null ) { classes . add ( sup ) ; classes . addAll ( getSuperTypes ( sup ) ) ; } return Collections . unmodifiableSet ( classes ) ; }

Returns all the super types of the given class, that is, all the
classes in which any instance of the given class can be cast into.

@param c the class.

@return all the given class's super types.

@throws NullPointerException if {@code c} is {@code null}.

Returns all the super types of the given class that is all the classes in which any instance of the given class can be cast into .


public static boolean verify(String password, byte[] hash)
	{
		byte[] h = Arrays.copyOf(hash, HASH_LENGTH + SALT_LENGTH + 3);
		int n = 1 << (h[HASH_LENGTH + SALT_LENGTH] & 0xFF);
		int r = h[HASH_LENGTH + SALT_LENGTH + 1] & 0xFF;
		int p = h[HASH_LENGTH + SALT_LENGTH + 2] & 0xFF;
		if (n > N || n < N_MIN || r > R || r < R_MIN || p > P || p < P_MIN) {
			n = N;
			r = R;
			p = P;
		}
		byte[] salt = new byte[SALT_LENGTH];
		System.arraycopy(h, HASH_LENGTH, salt, 0, SALT_LENGTH);
		byte[] expected = hash(password, salt, r, n, p);
		int result = 0;
		for (int i = 0; i < h.length; i++) {
			result |= h[i] ^ expected[i];
		}
		return result == 0;
	}

public static boolean verify ( String password , byte [ ] hash ) { byte [ ] h = Arrays . copyOf ( hash , HASH_LENGTH + SALT_LENGTH + 3 ) ; int n = 1 << ( h [ HASH_LENGTH + SALT_LENGTH ] & 0xFF ) ; int r = h [ HASH_LENGTH + SALT_LENGTH + 1 ] & 0xFF ; int p = h [ HASH_LENGTH + SALT_LENGTH + 2 ] & 0xFF ; if ( n > N || n < N_MIN || r > R || r < R_MIN || p > P || p < P_MIN ) { n = N ; r = R ; p = P ; } byte [ ] salt = new byte [ SALT_LENGTH ] ; System . arraycopy ( h , HASH_LENGTH , salt , 0 , SALT_LENGTH ) ; byte [ ] expected = hash ( password , salt , r , n , p ) ; int result = 0 ; for ( int i = 0 ; i < h . length ; i ++ ) { result |= h [ i ] ^ expected [ i ] ; } return result == 0 ; }

Verifies that the given password matches the hashed one.

@param password the password to verify.
@param hash the hashed password.

@return whether the given password matches the hashed one.

@throws NullPointerException if one of the arguments is {@code null}.

Verifies that the given password matches the hashed one .


public static String readString(Charset charset) throws IOException
	{
		Reader in = new InputStreamReader(System.in, charset);
		BufferedReader reader = new BufferedReader(in);
		try {
			return reader.readLine();
		} finally {
			reader.close();
		}
	}

public static String readString ( Charset charset ) throws IOException { Reader in = new InputStreamReader ( System . in , charset ) ; BufferedReader reader = new BufferedReader ( in ) ; try { return reader . readLine ( ) ; } finally { reader . close ( ) ; } }

Reads the next line from the standard input using the given charset.

@param charset the charset to use.

@return the next line read from the standard input.

@throws NullPointerException if {@code charset} is {@code null}.
@throws IOException if the standard input cannot be read.

Reads the next line from the standard input using the given charset .


public ByteBuffer append(byte b)
	{
		int newCount = count + 1;
		ensureCapacity(newCount);
		buf[count] = b;
		count = newCount;
		return this;
	}

public ByteBuffer append ( byte b ) { int newCount = count + 1 ; ensureCapacity ( newCount ) ; buf [ count ] = b ; count = newCount ; return this ; }

Writes the given byte to this buffer.

@param b the byte to write.

@return this object.


public ByteBuffer append(byte[] bytes, int off, int len)
	{
		int newCount = count + len;
		ensureCapacity(newCount);
		System.arraycopy(bytes, off, buf, count, len);
		count = newCount;
		return this;
	}

public ByteBuffer append ( byte [ ] bytes , int off , int len ) { int newCount = count + len ; ensureCapacity ( newCount ) ; System . arraycopy ( bytes , off , buf , count , len ) ; count = newCount ; return this ; }

Writes the given data to this buffer.

@param bytes the data to write.
@param off the offset.
@param len the number of bytes to write.

@return this object.

@throws NullPointerException if {@code bytes} is {@code null}.
@throws IndexOutOfBoundsException if {@code off} or {@code len} is
negative or if {@code off + len} is greater than the length of
the {@code bytes} array.


public static <T> T[] copyOf(T[] original)
	{
		return Arrays.copyOf(original, original.length);
	}

public static < T > T [ ] copyOf ( T [ ] original ) { return Arrays . copyOf ( original , original . length ) ; }

Returns a copy of the given array. The original array and the
returned copy will have identical length and content.

@param <T> the type of the elements in the array to copy.
@param original the array to be copied.

@return a copy of the original array.

@throws NullPointerException if {@code original} is {@code null}.

Returns a copy of the given array . The original array and the returned copy will have identical length and content .


public Fraction plus(Fraction f)
	{
		return new Fraction(n.multiply(f.d).add(f.n.multiply(d)),
			d.multiply(f.d)).reduced();
	}

public Fraction plus ( Fraction f ) { return new Fraction ( n . multiply ( f . d ) . add ( f . n . multiply ( d ) ) , d . multiply ( f . d ) ) . reduced ( ) ; }

Adds the given value to this one and returns the result in reduced
form.

@param f the fraction to add to this one.

@return {@code this + f} in reduced form.

@throws NullPointerException if {@code f} is {@code null}.

Adds the given value to this one and returns the result in reduced form .


public Fraction minus(Fraction f)
	{
		return new Fraction(n.multiply(f.d).subtract(f.n.multiply(d)),
			d.multiply(f.d)).reduced();
	}

public Fraction minus ( Fraction f ) { return new Fraction ( n . multiply ( f . d ) . subtract ( f . n . multiply ( d ) ) , d . multiply ( f . d ) ) . reduced ( ) ; }

Subtracts the given value from this one and returns the result in
reduced form.

@param f the fraction to subtract from this one.

@return {@code this - f} in reduced form.

@throws NullPointerException if {@code f} is {@code null}.

Subtracts the given value from this one and returns the result in reduced form .


public Fraction multipliedBy(Fraction f)
	{
		return new Fraction(n.multiply(f.n), d.multiply(f.d)).reduced();
	}

public Fraction multipliedBy ( Fraction f ) { return new Fraction ( n . multiply ( f . n ) , d . multiply ( f . d ) ) . reduced ( ) ; }

Multiplies this value by the given one and returns the result in
reduced form.

@param f the fraction to multiply this one with.

@return {@code this * f} in reduced form.

@throws NullPointerException if {@code f} is {@code null}.

Multiplies this value by the given one and returns the result in reduced form .


public Fraction dividedBy(Fraction f)
	{
		if (ZERO.equals(f)) {
			throw new ArithmeticException("Division by zero");
		}
		return new Fraction(n.multiply(f.d), d.multiply(f.n)).reduced();
	}

public
Fraction
dividedBy
(
Fraction
f
)
{
if
(
ZERO
.
equals
(
f
)
)
{
throw
new
ArithmeticException
(
"Division by zero"
)
;
}
return
new
Fraction
(
n
.
multiply
(
f
.
d
)
,
d
.
multiply
(
f
.
n
)
)
.
reduced
(
)
;
}

Divides this value by the given one and returns the result in reduced
form.

@param f the fraction to divide this one with.

@return {@code this / f} in reduced form.

@throws NullPointerException if {@code f} is {@code null}.
@throws ArithmeticException if {@code f} equals zero.

Divides this value by the given one and returns the result in reduced form .


public static long max(long... values)
	{
		Parameters.checkCondition(values.length > 0);
		long max = values[0];
		for (int i = 1; i < values.length; i++) {
			max = Math.max(max, values[i]);
		}
		return max;
	}

public static long max ( long ... values ) { Parameters . checkCondition ( values . length > 0 ) ; long max = values [ 0 ] ; for ( int i = 1 ; i < values . length ; i ++ ) { max = Math . max ( max , values [ i ] ) ; } return max ; }

Returns the maximum of the given values.

@param values a non-empty array of {@code long} values.

@return the maximum of the given values.

@throws NullPointerException if {@code values} is {@code null}.
@throws IllegalArgumentException if {@code values} is empty.

Returns the maximum of the given values .


public static long min(long... values)
	{
		Parameters.checkCondition(values.length > 0);
		long min = values[0];
		for (int i = 1; i < values.length; i++) {
			min = Math.min(min, values[i]);
		}
		return min;
	}

public static long min ( long ... values ) { Parameters . checkCondition ( values . length > 0 ) ; long min = values [ 0 ] ; for ( int i = 1 ; i < values . length ; i ++ ) { min = Math . min ( min , values [ i ] ) ; } return min ; }

Returns the minimum of the given values.

@param values a non-empty array of {@code long} values.

@return the minimum of the given values.

@throws NullPointerException if {@code values} is {@code null}.
@throws IllegalArgumentException if {@code values} is empty.

Returns the minimum of the given values .


public static void checkCondition(boolean condition, String msg,
		Object... args)
	{
		if (!condition) {
			throw new IllegalArgumentException(format(msg, args));
		}
	}

public static void checkCondition ( boolean condition , String msg , Object ... args ) { if ( ! condition ) { throw new IllegalArgumentException ( format ( msg , args ) ) ; } }

Checks the truth of the given condition checking parameters validity.

@param condition the boolean condition to test.
@param msg the error message format string.
@param args the error message arguments.

@throws IllegalArgumentException if the condition is {@code false}.

Checks the truth of the given condition checking parameters validity .


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);
    }

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 ) ; }

Fetch a LocationforecastLTS from the MET API, based on longitude, latitude and altitude.

@param longitude
The longitude of the location where the forecast should be fetched for.
@param latitude
The latitude of the location where the forecast should be fetched for.
@param altitude
The altitude of the location where the forecast should be fetched for.

@return A MeteoData object containing response information and data converted into a LocationForcast object.

@throws MeteoException
If a problem occurred while fetching or parsing the MET data.

Fetch a LocationforecastLTS from the MET API based on longitude latitude and altitude .


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);
    }

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 ) ; }

Fetch a Sunrise from the MET API based on a given longitude, latitude and date.

@param longitude
The longitude of the location where the Sunrise should be fetched from.
@param latitude
The latitude of the location where the Sunrise should be fetched from.
@param date
The date to fetch the Sunrise object for.

@return A MeteoData object containing response information and sunrise result converted into a Sunrise object.

@throws MeteoException
If a problem occurred while fetching or parsing the MET data.

Fetch a Sunrise from the MET API based on a given longitude latitude and date .


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);
    }

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 ) ; }

Fetch a Sunrise from the MET API based on a given longitude, latitude and date range.

@param longitude
The longitude of the location where the Sunrise should be fetched from.
@param latitude
The latitude of the location where the Sunrise should be fetched from.
@param from
The date to fetch the Sunrise object from.
@param to
The date to fetch the Sunrise object to.

@return A MeteoData object containing response information and sunrise result converted into a Sunrise object.

@throws MeteoException
If a problem occurred while fetching or parsing the MET data.

Fetch a Sunrise from the MET API based on a given longitude latitude and date range .


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;
    }

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 ; }

Get all point forecasts from now and to the given hours ahead.

@param hoursAhead
The number of hours to look ahead for point forecasts.

@return List of found forecasts.

Get all point forecasts from now and to the given hours ahead .


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)));
    }

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 ) ) ) ; }

Get the most accurate forecast for the given date.

@param dateTime
The date to get the forecast for.

@return Optional containing the forecast if found, else {@link Optional#empty()}

Get the most accurate forecast for the given date .


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);
    }

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 ) ; }

Fetch a textforecast for a named forecast

@param query
One of the predefined available textforecasts.

@return A MeteoData object containing response information and textforecast converted into an Weather object.

@throws MeteoException
If a problem occurred while fetching or parsing the MET data.


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);
    }

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 ) ; }

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.

@return A long term forecast, which is a week in our view of the world.

@throws MeteoException
If an error occurred while creating the simple longterm forecast.

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 .


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);
    }

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 ) ; }

Create a longterm forecast.

@return A long term forecast, which is a week in our view of the world. But how many days you will get in this
forecast depends on the given location forecast. So from 0-7 can be expected.


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());
        }

    }

Create an untitled Location from coordinate string.

@param coordinates Coordinate string on the format longitude,latitude,altitude. Eg: 20.3,123.3,123 or 20.3,123.3
@return Instance of the location with the coordinates from the input string.

Create an untitled Location from coordinate string .


public MeteoData<Available> fetchContent() throws MeteoException {
        MeteoResponse response = getMeteoClient().fetchContent(
                createServiceUriBuilder().addParameter("available", null).skipQuestionMarkInUrl().build());
        return new MeteoData<>(parser.parse(response.getData()), response);
    }

public MeteoData < Available > fetchContent ( ) throws MeteoException { MeteoResponse response = getMeteoClient ( ) . fetchContent ( createServiceUriBuilder ( ) . addParameter ( "available" , null ) . skipQuestionMarkInUrl ( ) . build ( ) ) ; return new MeteoData <> ( parser . parse ( response . getData ( ) ) , response ) ; }

Fetch a list of all available textforecasts.

@return A MeteoData object containing response information and available textforecasts converted into an
Available object.

@throws MeteoException
If a problem occurred while fetching or parsing the MET data.

Fetch a list of all available textforecasts .


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()));
    }

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 ( ) ) ) ; }

Create name for a wind symbol.

This will be created as a mix of the Beaufort wind speed id and the wind direction. This name can be used to
identify what wind icon that should be used for a forecast.

@param pointForecast
The point forecast to create a wind symbol name for.

@return A wind symbol name. null if wind information was missing from the given point forecast.


public static Optional<BeaufortLevel> findBeaufortLevel(PointForecast pointForecast) {
        if (pointForecast == null || pointForecast.getWindSpeed() == null) {
            return Optional.empty();
        }
        return Optional.ofNullable(findUnitById(pointForecast.getWindSpeed().getBeaufort()));
    }

public static Optional < BeaufortLevel > findBeaufortLevel ( PointForecast pointForecast ) { if ( pointForecast == null || pointForecast . getWindSpeed ( ) == null ) { return Optional . empty ( ) ; } return Optional . ofNullable ( findUnitById ( pointForecast . getWindSpeed ( ) . getBeaufort ( ) ) ) ; }

Find matching Beaufort level for a given point forecast.

This provides you with extra information about the wind speed specified in the forecast.

@param pointForecast
Point forecast containing information about the wind speed.

@return Matching Beaufort level object. null if wind speed information is missing from the given
forecast.

Find matching Beaufort level for a given point forecast .


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);
        }
    }

public
static
URI
createUri
(
String
uri
)
throws
MeteoException
{
if
(
uri
==
)
{
throw
new
MeteoException
(
"URI is null"
)
;
}
try
{
return
new
URI
(
uri
)
;
}
catch
(
URISyntaxException
e
)
{
throw
new
MeteoException
(
e
)
;
}
}

Wrap the construction of URL's to avoid throwing of checked MalformedURLException. Instead MeteoException
is thrown.

@param uri The url string to be used as the spec for the create URL object.
@return URL object created from the given url spec.
@throws no.api.meteo.MeteoException If a URL couldn't be created from the given url spec.

Wrap the construction of URL s to avoid throwing of checked MalformedURLException . Instead MeteoException is thrown .


public boolean isSun(ZonedDateTime currentDate) {
        if (getSun().getNeverRise()) {
            return false;
        } else if (getSun().getNeverSet()) {
            return true;
        }
        return timeWithinPeriod(currentDate);
    }

public boolean isSun ( ZonedDateTime currentDate ) { if ( getSun ( ) . getNeverRise ( ) ) { return false ; } else if ( getSun ( ) . getNeverSet ( ) ) { return true ; } return timeWithinPeriod ( currentDate ) ; }

Check if the sun is shining for a given time.

@param currentDate
The time (date) to be checked.

@return true if the sun has raised, else false.

Check if the sun is shining for a given time .


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();
    }

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 ( ) ; }

Get the PointForecast that matches the given time.

@param dateTime
Date object used to find a matching PointForecast.

@return A matching PointForecast if found, else null.

Get the PointForecast that matches the given time .


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);
    }

Find the period forecast that has the best fitted forecast for a given period.

This means a forecast covering the requested period, with to and from time closest possible to that period. If
this function only can find a period forecast that covers parts of the requested period, then the forecast
covering the most will be used.

Find the period forecast that has the best fitted forecast for a given period .


public MeteoData<TextLocationWeather> fetchContent(double longitude, double latitude)
            throws MeteoException {
        return fetchContent(longitude, latitude, TextLocationLanguage.NB);

    }

public MeteoData < TextLocationWeather > fetchContent ( double longitude , double latitude ) throws MeteoException { return fetchContent ( longitude , latitude , TextLocationLanguage . NB ) ; }

Fetch textforecasts and warnings for a geographical point or area, in Norwegian.

@param longitude
The longitude for the geographical point.
@param latitude
The latitude for the geographical point.

@return A MeteoData object containing response information and textforecast converted into an TextLocationWeather
object.

@throws MeteoException
If a problem occurred while fetching or parsing the MET data.

Fetch textforecasts and warnings for a geographical point or area in Norwegian .


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);
    }

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 ) ; }

Fetch textforecasts and warnings for a geographical point or area.

@param longitude
The longitude for the geographical point.
@param latitude
The latitude for the geographical point.
@param language
The chosen language for the forecast. Note that textforecasts in english are available for only some
areas and some types ( e.g textforecasts for the coastal areas ).

@return A MeteoData object containing response information and textforecast converted into an TextLocationWeather
object.

@throws MeteoException
If a problem occurred while fetching or parsing the MET data.

Fetch textforecasts and warnings for a geographical point or area .


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.");
            }
        }
    }

Checks connection, retrieves appropriate changelog and performs database update.

@throws SQLException
@throws LiquibaseException

Checks connection retrieves appropriate changelog and performs database update .


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);
    }

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 ) ; }

Calls a method on a script object compiled during a previous script execution, which is retained in the state of the ScriptEngine.

@param jsEngine the JavaScript engine
@param thiz the instance of the class that contains the method to be called
@param name the name of the method to be called
@param args the arguments to pass to the method
@return the value returned by the procedure, which must be a String
@throws NoSuchMethodException if method with given name or matching argument types cannot be found.
@throws ScriptException if an error occurs during invocation of the method.

Calls a method on a script object compiled during a previous script execution which is retained in the state of the ScriptEngine .


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;
    }

public
synchronized
T
acquire
(
final
DataSource
source
)
throws
DataSourceException
{
if
(
object
==
)
{
if
(
getReference
(
)
==
)
{
throw
new
IllegalStateException
(
"No reference or object present"
)
;
}
else
{
object
=
source
.
getObject
(
getReference
(
)
,
objectClass
)
;
}
}
return
object
;
}

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.

@param source the implementation that provides object instances given the provided references
@return the object that this container is wrapping
@throws DataSourceException if the object cannot be acquired
@throws IllegalStateException if there is no object or reference present

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 .


public static <T> ReferencedObject<T> getReferencedObject(final Class<T> clazz, final String ref)
    {
        return new ReferencedObject<>(clazz, ref, null);
    }

public static < T > ReferencedObject < T > getReferencedObject ( final Class < T > clazz , final String ref ) { return new ReferencedObject <> ( clazz , ref , null ) ; }

Create a ReferencedObject that uses a remote reference to data present in an ObjectSource.

@param clazz the class of the referenced object
@param ref the reference to be interpreted by the DataStore
@param <T> the type of the referenced object
@return a new ReferencedObject instance that relates to a remote object via reference

Create a ReferencedObject that uses a remote reference to data present in an ObjectSource .


public static <T> ReferencedObject<T> getWrappedObject(final Class<T> clazz, final T obj)
    {
        return new ReferencedObject<>(clazz, null, obj);
    }

public static < T > ReferencedObject < T > getWrappedObject ( final Class < T > clazz , final T obj ) { return new ReferencedObject <> ( clazz , null , obj ) ; }

Create a ReferencedObject that directly wraps an object without a reference.

@param clazz the class of the object
@param obj the object to wrapper
@param <T> the type of the object
@return a new ReferencedObject instance that directly wraps the object specified

Create a ReferencedObject that directly wraps an object without a reference .


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());
    }

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
(
)
)
;
}

Acquire, decode and decrypt a configuration object from a data stream.

@param configClass the class representing configuration to acquire
@param <T> the class representing configuration to acquire
@return the decoded configuration object
@throws ConfigurationException if the configuration cannot be acquired

Acquire decode and decrypt a configuration object from a data stream .


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);
        }
    }

Checks whether the string substitution functionality should be enabled.

@param bootstrapConfig used to provide basic, initial startup configuration
@return true if the configuration substitution should be performed

Checks whether the string substitution functionality should be enabled .


@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();
    }

@ 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 ( ) ; }

Excludes all com . sun . jersey classes .


@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);
        }
    }

Returns the Decoder that should be used to interpret the configuration files.

@param bootstrap used to provide basic, initial startup configuration
@param defaultDecoder the Decoder to use if one is not configured
@return the Decoder that should be used to interpret the configuration files

Returns the Decoder that should be used to interpret the configuration files .


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;
    }

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 ; }

Get all advertised service implementations of the specified interface.

@param intf the interface to find advertised service implementations of
@param <T> the interface
@return a collection of implementations of the specified interface

Get all advertised service implementations of the specified interface .


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;
    }

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
;
}

Retrieves a module by its simple name, that implements a particular type T

@param interfaceImplemented The interface that 'moduleType' implements and that the result should be returned as.
@param moduleType Represents particular instance of a factory type object e.g. 'ExampleWorkerBuilder'
@return An instance of moduleType as the type T passed in.
@throws NullPointerException If the module cannot be retrieved with the specified moduleType.

Retrieves a module by its simple name that implements a particular type T


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;
    }

public
synchronized
InputStream
acquire
(
final
DataSource
source
)
throws
DataSourceException
{
InputStream
ret
;
if
(
data
==
)
{
if
(
getReference
(
)
==
)
{
throw
new
IllegalStateException
(
"No data or reference present"
)
;
}
else
{
ret
=
source
.
getStream
(
getReference
(
)
)
;
}
}
else
{
ret
=
new
ByteArrayInputStream
(
data
)
;
}
return
ret
;
}

Return the referenced data as a stream, potentially performing a remote lookup.

@param source the implementation that provides object instances given the provided references
@return a stream of the data that this container is wrapping
@throws DataSourceException if the data cannot be acquired
@throws IllegalStateException if there is no object or reference present

Return the referenced data as a stream potentially performing a remote lookup .


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;
        }
    }

public
synchronized
long
size
(
final
DataSource
source
)
throws
DataSourceException
{
if
(
data
==
)
{
if
(
getReference
(
)
==
)
{
throw
new
IllegalStateException
(
"No data or reference present"
)
;
}
else
{
return
source
.
getDataSize
(
getReference
(
)
)
;
}
}
else
{
return
data
.
length
;
}
}

Determine the size of the data.

@param source the implementation that provides object instances given the provided references
@return the size of the abstracted data, in bytes
@throws DataSourceException if the size information cannot be acquired


public static ReferencedData getWrappedData(final String ref, final byte[] data)
    {
        return new ReferencedData(Objects.requireNonNull(ref), data);
    }

public static ReferencedData getWrappedData ( final String ref , final byte [ ] data ) { return new ReferencedData ( Objects . requireNonNull ( ref ) , data ) ; }

Create a ReferencedData instance that wraps data but also has a reference.

@param ref the reference to be interpreted by the DataStore
@param data the raw data to wrapper, also accessible via the supplied reference
@return a new ReferencedData instance that wraps and references the data supplied

Create a ReferencedData instance that wraps data but also has a reference .


public String getIndex(final int index)
    {
        if (index < 0 || index >= components.size()) {
            throw new IllegalArgumentException("Index out of bounds");
        }
        return components.get(index);
    }

public
String
getIndex
(
final
int
index
)
{
if
(
index
<
0
||
index
>=
components
.
size
(
)
)
{
throw
new
IllegalArgumentException
(
"Index out of bounds"
)
;
}
return
components
.
get
(
index
)
;
}

Get the components of the Name at the specified numeric index

@param index the index of the token to return, starting from 0
@return the requested Name component
@throws IllegalArgumentException if you request an index that does not exist


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));
    }

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
)
)
;
}

Return a Name that consists of a subsection of the current Name.

@param upperIndex the upper index (exclusive) of components to build the Name from
@return a new Name, that is a sub-set of the current Name
@throws IllegalArgumentException if you request an index that is no in the range of components of this Name

Return a Name that consists of a subsection of the current Name .


boolean colored() {
        return type == Compiler.PLAIN || type == Compiler.AHEAD || type == Compiler.BEHIND;
    }

boolean colored ( ) { return type == Compiler . PLAIN || type == Compiler . AHEAD || type == Compiler . BEHIND ; }

is an arc colored, and hence on a color chain?

is an arc colored and hence on a color chain?


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);
        }
    }

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
!=
)
{
this
.
match
.
clear
(
)
;
}
else
{
this
.
match
=
Lists
.
newArrayList
(
)
;
}
match
.
add
(
)
;
// make room for 1.
if
(
0
!=
(
g
.
info
&
Flags
.
REG_UBACKREF
)
)
{
while
(
match
.
size
(
)
<
g
.
nsub
+
1
)
{
match
.
add
(
)
;
}
}
if
(
mem
!=
&&
mem
.
length
>=
g
.
ntree
)
{
Arrays
.
fill
(
mem
,
0
)
;
}
else
{
mem
=
new
int
[
g
.
ntree
]
;
}
/* do it */
assert
g
.
tree
!=
;
if
(
0
!=
(
g
.
info
&
Flags
.
REG_UBACKREF
)
)
{
return
cfind
(
g
.
tree
.
machine
)
;
}
else
{
return
find
(
g
.
tree
.
machine
)
;
}
}


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;
    }


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));
    }

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 ) ) ; }

subset - set any subexpression relevant to a successful subre


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;
    }

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".

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 .


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 == 'b';
        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);
    }

cbrdissect - determine backref subexpression matches


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);
        }
    }

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 ) ; } }

cloneouts - copy out arcs of a state to another state pair, modifying type

cloneouts - copy out arcs of a state to another state pair modifying type


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);
        }
    }

private
void
optst
(
Subre
t
)
{
if
(
t
==
)
{
return
;
}
/* recurse through children */
if
(
t
.
left
!=
)
{
optst
(
t
.
left
)
;
}
if
(
t
.
right
!=
)
{
optst
(
t
.
right
)
;
}
}


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);
        }
    }

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 ) ; } }


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;
    }

nfanode - do one NFA for nfatree

@return results of {@link Nfa#optimize()}


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;
    }

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
==
;
t
=
branch
.
left
;
branch
.
left
=
;
branches
=
t
;
}
else
if
(
!
messy
(
branches
.
flags
)
)
{
/* no interesting innards */
branches
.
left
=
;
branches
.
right
=
;
branches
.
op
=
'
'
;
}
return
branches
;
}

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.

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 .


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 */
    }

private
void
deltraverse
(
Nfa
nfa
,
State
leftend
,
State
s
)
{
Arc
a
;
State
to
;
if
(
s
.
nouts
==
0
)
{
return
;
/* nothing to do */
}
if
(
s
.
tmp
!=
)
{
return
;
/* already in progress */
}
s
.
tmp
=
s
;
/* mark as in progress */
while
(
(
a
=
s
.
outs
)
!=
)
{
to
=
a
.
to
;
deltraverse
(
nfa
,
leftend
,
to
)
;
assert
to
.
nouts
==
0
||
to
.
tmp
!=
;
nfa
.
freearc
(
a
)
;
if
(
to
.
nins
==
0
&&
to
.
tmp
==
)
{
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
=
;
/* we're done here */
}

deltraverse - the recursive heart of delsub
This routine's basic job is to destroy all out-arcs of the state.

deltraverse - the recursive heart of delsub This routine s basic job is to destroy all out - arcs of the state .


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) */
    }

nonword - generate arcs for non-word-character ahead or behind

nonword - generate arcs for non - word - character ahead or behind


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) */
    }

word - generate arcs for word character ahead or behind


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;
    }

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
;
}

scannum - scan a number

@return value <= DUPMAX


private void bracket(State lp, State rp) throws RegexException {
        assert see('[');
        lex.next();
        while (!see(']') && !see(EOS)) {
            brackpart(lp, rp);
        }
        assert see(']');
        cm.okcolors(nfa);
    }

private void bracket ( State lp , State rp ) throws RegexException { assert see ( ' ' ) ; lex . next ( ) ; while ( ! see ( ' ' ) && ! see ( EOS ) ) { brackpart ( lp , rp ) ; } assert see ( ' ' ) ; cm . okcolors ( nfa ) ; }

bracket - handle non-complemented bracket expression
Also called from cbracket for complemented bracket expressions.

bracket - handle non - complemented bracket expression Also called from cbracket for complemented bracket expressions .


private String scanplain() throws RegexException {
        int startp = now;
        int endp;

        assert see(COLLEL) || see(ECLASS) || see(CCLASS);
        lex.next();

        endp = now;
        while (see(PLAIN)) {
            endp = now;
            lex.next();
        }

        String ret = new String(pattern, startp, endp - startp);
        assert see(END);
        lex.next();

        return ret;
    }

private String scanplain ( ) throws RegexException { int startp = now ; int endp ; assert see ( COLLEL ) || see ( ECLASS ) || see ( CCLASS ) ; lex . next ( ) ; endp = now ; while ( see ( PLAIN ) ) { endp = now ; lex . next ( ) ; } String ret = new String ( pattern , startp , endp - startp ) ; assert see ( END ) ; lex . next ( ) ; return ret ; }

scanplain - scan PLAIN contents of [. etc.
Certain bits of trickery in lex.c know that this code does not try
to look past the final bracket of the [. etc.

@return the string. It can't return a pos; a nested pattern is popped by
the last lex.next() in here and so the offsets don't work.

scanplain - scan PLAIN contents of [ . etc . Certain bits of trickery in lex . c know that this code does not try to look past the final bracket of the [ . etc .


private int newlacon(State begin, State end, int pos) {
        if (lacons.size() == 0) {
            // skip 0
            lacons.add(null);
        }
        Subre sub = new Subre((char)0, 0, begin, end);
        sub.subno = pos;
        lacons.add(sub);
        return lacons.size() - 1; // it's the index into the array, -1.
    }

private
int
newlacon
(
State
begin
,
State
end
,
int
pos
)
{
if
(
lacons
.
size
(
)
==
0
)
{
// skip 0
lacons
.
add
(
)
;
}
Subre
sub
=
new
Subre
(
(
char
)
0
,
0
,
begin
,
end
)
;
sub
.
subno
=
pos
;
lacons
.
add
(
sub
)
;
return
lacons
.
size
(
)
1
;
// it's the index into the array, -1.
}

newlacon - allocate a lookahead-constraint subRE

@return lacon number

newlacon - allocate a lookahead - constraint subRE


private void onechr(int c, State lp, State rp) throws RegexException {
        if (0 == (cflags & Flags.REG_ICASE)) {
            nfa.newarc(PLAIN, cm.subcolor(c), lp, rp);
            return;
        }

    /* rats, need general case anyway... */
        dovec(Locale.allcases(c), lp, rp);
    }

private
void
onechr
(
int
c
,
State
lp
,
State
rp
)
throws
RegexException
{
if
(
0
==
(
cflags
&
Flags
.
REG_ICASE
)
)
{
nfa
.
newarc
(
PLAIN
,
cm
.
subcolor
(
c
)
,
lp
,
rp
)
;
return
;
}
/* rats, need general case anyway... */
dovec
(
Locale
.
allcases
(
c
)
,
lp
,
rp
)
;
}

onechr - fill in arcs for a plain character, and possible case complements
This is mostly a shortcut for efficient handling of the common case.

onechr - fill in arcs for a plain character and possible case complements This is mostly a shortcut for efficient handling of the common case .


private void dovec(UnicodeSet set, State lp, State rp) throws RegexException {

        int rangeCount = set.getRangeCount();
        for (int rx = 0; rx < rangeCount; rx++) {
            int rangeStart = set.getRangeStart(rx);
            int rangeEnd = set.getRangeEnd(rx);
            /*
             * Note: ICU operates in UTF-32 here, and the ColorMap is happy to play along.
             */
            if (LOG.isDebugEnabled() && IS_DEBUG) {
                LOG.debug(String.format("%s %d %4x %4x", set, rx, rangeStart, rangeEnd));
            }
            //TODO: this arc is probably redundant.
            if (rangeStart == rangeEnd) {
                nfa.newarc(PLAIN, cm.subcolor(rangeStart), lp, rp);
            }
            cm.subrange(rangeStart, rangeEnd, lp, rp);
        }
    }

dovec - fill in arcs for each element of a cvec
all kinds of MCCE complexity removed.

dovec - fill in arcs for each element of a cvec all kinds of MCCE complexity removed .


private short getcolor(int c) {
        try {
            return map.get(c);
        } catch (NullPointerException npe) {
            throw new RegexRuntimeException(String.format("Failed to map codepoint U+%08X.", c));
        }
    }

private
short
getcolor
(
int
c
)
{
try
{
return
map
.
get
(
c
)
;
}
catch
(
NullPointerException
npe
)
{
throw
new
RegexRuntimeException
(
String
.
format
(
"Failed to map codepoint U+%08X."
,
c
)
)
;
}
}

Retrieve the color for a character.
@param c input char.
@return output color.


short pseudocolor() {
        short co = newcolor();
        ColorDesc cd = colorDescs.get(co);
        cd.setNChars(1);
        cd.markPseudo();
        return co;
    }

short pseudocolor ( ) { short co = newcolor ( ) ; ColorDesc cd = colorDescs . get ( co ) ; cd . setNChars ( 1 ) ; cd . markPseudo ( ) ; return co ; }

pseudocolor - allocate a false color to be managed by other means.

@return a color, otherwise unused.

pseudocolor - allocate a false color to be managed by other means .


void subrange(int from, int to, State lp, State rp) throws RegexException {
        /* Avoid one call to map.get() for each character in the range.
         * This map will usually contain one item, but in complex cases more.
         * For example, if we had [a-f][g-h] and then someone asked for [f-g], there
         * would be two. Each of these new ranges will get a new color via subcolor.
         */
        Map<Range<Integer>, Short> curColors = map.subRangeMap(Range.closed(from, to)).asMapOfRanges();
        /*
         * To avoid concurrent mod problems, we need to copy the ranges we are working from.
         */
        List<Range<Integer>> ranges = Lists.newArrayList(curColors.keySet());
        for (Range<Integer> rangeToProcess : ranges) {
            // bound management here irritating.
            int start = rangeToProcess.lowerEndpoint();
            if (rangeToProcess.lowerBoundType() == BoundType.OPEN) {
                start++;
            }
            int end = rangeToProcess.upperEndpoint();
            if (rangeToProcess.upperBoundType() == BoundType.CLOSED) {
                end++;
            }
            // allocate a new subcolor and account it owning the entire range.
            short color = subcolor(start, end - start);
            compiler.getNfa().newarc(Compiler.PLAIN, color, lp, rp);
        }
    }

subrange - allocate new subcolors to this range of chars, fill in arcs.
The range will overlap existing ranges; even in the simplest case,
it will overlap the initial WHITE range. For each existing range that
it overlaps, allocate a new color, mark the range as mapping to that color,
and add an arc between the states for that color.

subrange - allocate new subcolors to this range of chars fill in arcs . The range will overlap existing ranges ; even in the simplest case it will overlap the initial WHITE range . For each existing range that it overlaps allocate a new color mark the range as mapping to that color and add an arc between the states for that color .


void okcolors(Nfa nfa) {
        ColorDesc cd;
        ColorDesc scd;
        Arc a;
        short sco;

        for (short co = 0; co < colorDescs.size(); co++) {
            cd = colorDescs.get(co);
            if (cd == null) {
                continue; // not in use at all, so can't have a subcolor.
            }

            sco = cd.sub;

            if (sco == Constants.NOSUB) {
            /* has no subcolor, no further action */
            } else if (sco == co) {
            /* is subcolor, let parent deal with it */
            } else if (cd.getNChars() == 0) {
            /* parent empty, its arcs change color to subcolor */
                cd.sub = Constants.NOSUB;
                scd = colorDescs.get(sco);

                assert scd.getNChars() > 0;
                assert scd.sub == sco;

                scd.sub = Constants.NOSUB;
                while ((a = cd.arcs) != null) {
                    assert a.co == co;
                    cd.arcs = a.colorchain;
                    a.setColor(sco);
                    a.colorchain = scd.arcs;
                    scd.arcs = a;
                }
                freecolor(co);
            } else {
                /* parent's arcs must gain parallel subcolor arcs */
                cd.sub = Constants.NOSUB;
                scd = colorDescs.get(sco);

                assert scd.getNChars() > 0;
                assert scd.sub == sco;

                scd.sub = Constants.NOSUB;

                for (a = cd.arcs; a != null; a = a.colorchain) {
                    assert a.co == co;
                    nfa.newarc(a.type, sco, a.from, a.to);
                }
            }
        }
    }

okcolors - promote subcolors to full colors


void colorchain(Arc a) {
        ColorDesc cd = colorDescs.get(a.co);
        a.colorchain = cd.arcs;
        cd.arcs = a;
    }

void colorchain ( Arc a ) { ColorDesc cd = colorDescs . get ( a . co ) ; a . colorchain = cd . arcs ; cd . arcs = a ; }

colorchain - add this arc to the color chain of its color


void uncolorchain(Arc a) {
        ColorDesc cd = colorDescs.get(a.co);
        Arc aa;

        aa = cd.arcs;
        if (aa == a) {      /* easy case */
            cd.arcs = a.colorchain;
        } else {
            for (; aa != null && aa.colorchain != a; aa = aa.colorchain) {
                //
            }
            assert aa != null;
            aa.colorchain = a.colorchain;
        }

        a.colorchain = null;    /* paranoia */
    }

void
uncolorchain
(
Arc
a
)
{
ColorDesc
cd
=
colorDescs
.
get
(
a
.
co
)
;
Arc
aa
;
aa
=
cd
.
arcs
;
if
(
aa
==
a
)
{
/* easy case */
cd
.
arcs
=
a
.
colorchain
;
}
else
{
for
(
;
aa
!=
&&
aa
.
colorchain
!=
a
;
aa
=
aa
.
colorchain
)
{
//
}
assert
aa
!=
;
aa
.
colorchain
=
a
.
colorchain
;
}
a
.
colorchain
=
;
/* paranoia */
}

uncolorchain - delete this arc from the color chain of its color


void dumpcolors() {
        /*
         * we want to organize this by colors.
         */
        for (int co = 0; co < colorDescs.size(); co++) {
            ColorDesc cd = colorDescs.get(co);
            if (cd != null) {
                dumpcolor(co, cd);
            }
        }
    }


void lexstart() throws RegexException {
        prefixes();         /* may turn on new type bits etc. */

        if (0 != (v.cflags & Flags.REG_QUOTE)) {
            assert 0 == (v.cflags & (Flags.REG_ADVANCED | Flags.REG_EXPANDED | Flags.REG_NEWLINE));
            intocon(L_Q);
        } else if (0 != (v.cflags & Flags.REG_EXTENDED)) {
            assert 0 == (v.cflags & Flags.REG_QUOTE);
            intocon(L_ERE);
        } else {
            assert 0 == (v.cflags & (Flags.REG_QUOTE | Flags.REG_ADVF));
            intocon(L_BRE);
        }

        v.nexttype = Compiler.EMPTY;        /* remember we were at the start */
        next();         /* set up the first token */
    }

void
lexstart
(
)
throws
RegexException
{
prefixes
(
)
;
/* may turn on new type bits etc. */
if
(
0
!=
(
v
.
cflags
&
Flags
.
REG_QUOTE
)
)
{
assert
0
==
(
v
.
cflags
&
(
Flags
.
REG_ADVANCED
|
Flags
.
REG_EXPANDED
|
Flags
.
REG_NEWLINE
)
)
;
intocon
(
L_Q
)
;
}
else
if
(
0
!=
(
v
.
cflags
&
Flags
.
REG_EXTENDED
)
)
{
assert
0
==
(
v
.
cflags
&
Flags
.
REG_QUOTE
)
;
intocon
(
L_ERE
)
;
}
else
{
assert
0
==
(
v
.
cflags
&
(
Flags
.
REG_QUOTE
|
Flags
.
REG_ADVF
)
)
;
intocon
(
L_BRE
)
;
}
v
.
nexttype
=
Compiler
.
EMPTY
;
/* remember we were at the start */
next
(
)
;
/* set up the first token */
}

lexstart - set up lexical stuff, scan leading options

lexstart - set up lexical stuff scan leading options