protected void throwInvalidContextType(final String methodName, final BsonContextType actualContextType,
                                           final BsonContextType... validContextTypes) {
        String validContextTypesString = StringUtils.join(" or ", asList(validContextTypes));
        String message = format("%s can only be called when ContextType is %s, not when ContextType is %s.",
                                methodName, validContextTypesString, actualContextType);
        throw new BsonInvalidOperationException(message);
    }

Throws an InvalidOperationException when the method called is not valid for the current ContextType.

@param methodName        The name of the method.
@param actualContextType The actual ContextType.
@param validContextTypes The valid ContextTypes.
@throws BsonInvalidOperationException when the method called is not valid for the current ContextType.

Throws an InvalidOperationException when the method called is not valid for the current ContextType .


protected void throwInvalidState(final String methodName, final State... validStates) {
        String validStatesString = StringUtils.join(" or ", asList(validStates));
        String message = format("%s can only be called when State is %s, not when State is %s.",
                                methodName, validStatesString, state);
        throw new BsonInvalidOperationException(message);
    }

Throws an InvalidOperationException when the method called is not valid for the current state.

@param methodName  The name of the method.
@param validStates The valid states.
@throws BsonInvalidOperationException when the method called is not valid for the current state.

Throws an InvalidOperationException when the method called is not valid for the current state .


protected void verifyBSONType(final String methodName, final BsonType requiredBsonType) {
        if (state == State.INITIAL || state == State.SCOPE_DOCUMENT || state == State.TYPE) {
            readBsonType();
        }
        if (state == State.NAME) {
            // ignore name
            skipName();
        }
        if (state != State.VALUE) {
            throwInvalidState(methodName, State.VALUE);
        }
        if (currentBsonType != requiredBsonType) {
            throw new BsonInvalidOperationException(format("%s can only be called when CurrentBSONType is %s, "
                                                           + "not when CurrentBSONType is %s.",
                                                           methodName, requiredBsonType, currentBsonType));
        }
    }

Verifies the current state and BSONType of the reader.

@param methodName       The name of the method calling this one.
@param requiredBsonType The required BSON type.

Verifies the current state and BSONType of the reader .


protected void verifyName(final String expectedName) {
        readBsonType();
        String actualName = readName();
        if (!actualName.equals(expectedName)) {
            throw new BsonSerializationException(format("Expected element name to be '%s', not '%s'.",
                                                        expectedName, actualName));
        }
    }

Verifies the name of the current element.

@param expectedName The expected name.
@throws BsonSerializationException when the name read is not the expected name

Verifies the name of the current element .


protected void checkPreconditions(final String methodName, final BsonType type) {
        if (isClosed()) {
            throw new IllegalStateException("BsonWriter is closed");
        }

        verifyBSONType(methodName, type);
    }

protected
void
checkPreconditions
(
final
String
methodName
,
final
BsonType
type
)
{
if
(
isClosed
(
)
)
{
throw
new
IllegalStateException
(
"BsonWriter is closed"
)
;
}
verifyBSONType
(
methodName
,
type
)
;
}

Ensures any conditions are met before reading commences.  Throws exceptions if the conditions are not met.

@param methodName the name of the current method, which will indicate the field being read
@param type       the type of this field

Ensures any conditions are met before reading commences . Throws exceptions if the conditions are not met .


public static Decimal128 parse(final String value) {
        String lowerCasedValue = value.toLowerCase();

        if (NaN_STRINGS.contains(lowerCasedValue)) {
            return NaN;
        }
        if (NEGATIVE_NaN_STRINGS.contains(lowerCasedValue)) {
            return NEGATIVE_NaN;
        }
        if (POSITIVE_INFINITY_STRINGS.contains(lowerCasedValue)) {
            return POSITIVE_INFINITY;
        }
        if (NEGATIVE_INFINITY_STRINGS.contains(lowerCasedValue)) {
            return NEGATIVE_INFINITY;
        }
        return new Decimal128(new BigDecimal(value), value.charAt(0) == '-');
    }

public static Decimal128 parse ( final String value ) { String lowerCasedValue = value . toLowerCase ( ) ; if ( NaN_STRINGS . contains ( lowerCasedValue ) ) { return NaN ; } if ( NEGATIVE_NaN_STRINGS . contains ( lowerCasedValue ) ) { return NEGATIVE_NaN ; } if ( POSITIVE_INFINITY_STRINGS . contains ( lowerCasedValue ) ) { return POSITIVE_INFINITY ; } if ( NEGATIVE_INFINITY_STRINGS . contains ( lowerCasedValue ) ) { return NEGATIVE_INFINITY ; } return new Decimal128 ( new BigDecimal ( value ) , value . charAt ( 0 ) == ' ' ) ; }

Returns a Decimal128 value representing the given String.

@param value the Decimal128 value represented as a String
@return the Decimal128 value representing the given String
@throws NumberFormatException if the value is out of the Decimal128 range
@see

From-String Specification

Returns a Decimal128 value representing the given String .


public BigDecimal bigDecimalValue() {

        if (isNaN()) {
            throw new ArithmeticException("NaN can not be converted to a BigDecimal");
        }

        if (isInfinite()) {
            throw new ArithmeticException("Infinity can not be converted to a BigDecimal");
        }

        BigDecimal bigDecimal = bigDecimalValueNoNegativeZeroCheck();

        // If the BigDecimal is 0, but the Decimal128 is negative, that means we have -0.
        if (isNegative() && bigDecimal.signum() == 0) {
            throw new ArithmeticException("Negative zero can not be converted to a BigDecimal");
        }

        return bigDecimal;
    }

Gets a BigDecimal that is equivalent to this Decimal128.

@return a BigDecimal that is equivalent to this Decimal128
@throws ArithmeticException if the Decimal128 value is NaN, Infinity, -Infinity, or -0, none of which can be represented as a
BigDecimal

Gets a BigDecimal that is equivalent to this Decimal128 .


May have leading zeros.  Strip them before considering making this method public

May have leading zeros . Strip them before considering making this method public


public AggregateExplainOperation hint(final BsonValue hint) {
        isTrueArgument("BsonString or BsonDocument", hint == null || hint.isDocument() || hint.isString());
        this.hint = hint;
        return this;
    }

public
AggregateExplainOperation
hint
(
final
BsonValue
hint
)
{
isTrueArgument
(
"BsonString or BsonDocument"
,
hint
==
||
hint
.
isDocument
(
)
||
hint
.
isString
(
)
)
;
this
.
hint
=
hint
;
return
this
;
}

Sets the hint for which index to use. A null value means no hint is set.

@param hint the hint
@return this
@since 3.6
@mongodb.server.release 3.6

Sets the hint for which index to use . A null value means no hint is set .


public BsonDocument asDocument() {
        BsonDocument collation = new BsonDocument();
        if (locale != null) {
            collation.put("locale", new BsonString(locale));
        }
        if (caseLevel != null) {
            collation.put("caseLevel", new BsonBoolean(caseLevel));
        }
        if (caseFirst != null) {
            collation.put("caseFirst", new BsonString(caseFirst.getValue()));
        }
        if (strength != null) {
            collation.put("strength", new BsonInt32(strength.getIntRepresentation()));
        }
        if (numericOrdering != null) {
            collation.put("numericOrdering", new BsonBoolean(numericOrdering));
        }
        if (alternate != null) {
            collation.put("alternate", new BsonString(alternate.getValue()));
        }
        if (maxVariable != null) {
            collation.put("maxVariable", new BsonString(maxVariable.getValue()));
        }
        if (normalization != null) {
            collation.put("normalization", new BsonBoolean(normalization));
        }
        if (backwards != null) {
            collation.put("backwards", new BsonBoolean(backwards));
        }
        return collation;
    }

public BsonDocument asDocument ( ) { BsonDocument collation = new BsonDocument ( ) ; if ( locale != null ) { collation . put ( "locale" , new BsonString ( locale ) ) ; } if ( caseLevel != null ) { collation . put ( "caseLevel" , new BsonBoolean ( caseLevel ) ) ; } if ( caseFirst != null ) { collation . put ( "caseFirst" , new BsonString ( caseFirst . getValue ( ) ) ) ; } if ( strength != null ) { collation . put ( "strength" , new BsonInt32 ( strength . getIntRepresentation ( ) ) ) ; } if ( numericOrdering != null ) { collation . put ( "numericOrdering" , new BsonBoolean ( numericOrdering ) ) ; } if ( alternate != null ) { collation . put ( "alternate" , new BsonString ( alternate . getValue ( ) ) ) ; } if ( maxVariable != null ) { collation . put ( "maxVariable" , new BsonString ( maxVariable . getValue ( ) ) ) ; } if ( normalization != null ) { collation . put ( "normalization" , new BsonBoolean ( normalization ) ) ; } if ( backwards != null ) { collation . put ( "backwards" , new BsonBoolean ( backwards ) ) ; } return collation ; }

Gets this collation options as a document.

@return The collation options as a BsonDocument

Gets this collation options as a document .


public long writeTo(final File file) throws IOException {
        FileOutputStream out = null;
        try {
            out = new FileOutputStream(file);
            return writeTo(out);
        } finally {
            if (out != null) {
                out.close();
            }
        }
    }

public long writeTo ( final File file ) throws IOException { FileOutputStream out = null ; try { out = new FileOutputStream ( file ) ; return writeTo ( out ) ; } finally { if ( out != null ) { out . close ( ) ; } } }

Writes the file's data to a file on disk.

@param file the File object
@return number of bytes written
@throws IOException if there are problems writing to the {@code file}

Writes the file s data to a file on disk .


public long writeTo(final OutputStream out) throws IOException {
        int nc = numChunks();
        for (int i = 0; i < nc; i++) {
            out.write(getChunk(i));
        }
        return length;
    }

public long writeTo ( final OutputStream out ) throws IOException { int nc = numChunks ( ) ; for ( int i = 0 ; i < nc ; i ++ ) { out . write ( getChunk ( i ) ) ; } return length ; }

Writes the file's data to an OutputStream.

@param out the OutputStream
@return number of bytes written
@throws IOException if there are problems writing to {@code out}

Writes the file s data to an OutputStream .


void remove() {
        fs.getFilesCollection().remove(new BasicDBObject("_id", id));
        fs.getChunksCollection().remove(new BasicDBObject("files_id", id));
    }

void remove ( ) { fs . getFilesCollection ( ) . remove ( new BasicDBObject ( "_id" , id ) ) ; fs . getChunksCollection ( ) . remove ( new BasicDBObject ( "files_id" , id ) ) ; }

Removes file from GridFS i.e. removes documents from files and chunks collections.

Removes file from GridFS i . e . removes documents from files and chunks collections .


public PushOptions sort(@Nullable final Integer sort) {
        if (sortDocument != null) {
            throw new IllegalStateException("sort can not be set if sortDocument already is");
        }
        this.sort = sort;
        return this;
    }

Sets the sort direction for sorting array elements that are not documents.

@param sort the sort direction
@return this
@throws IllegalStateException if sortDocument property is already set
@mongodb.driver.manual reference/operator/update/sort/ $sort
@mongodb.driver.manual reference/operator/update/sort/#sort-array-elements-that-are-not-documents

Sets the sort direction for sorting array elements that are not documents .


public PushOptions sortDocument(@Nullable final Bson sortDocument) {
        if (sort != null) {
            throw new IllegalStateException("sortDocument can not be set if sort already is");
        }
        this.sortDocument = sortDocument;
        return this;
    }

Sets the sort direction for sorting array elements that are documents.

@param sortDocument the sort document
@return this
@throws IllegalStateException if sort property is already set
@mongodb.driver.manual reference/operator/update/sort/ $sort

Sets the sort direction for sorting array elements that are documents .


@BsonIgnore @Nullable
    public MongoNamespace getNamespace() {
        if (namespaceDocument == null) {
            return null;
        }
        if (!namespaceDocument.containsKey("db") || !namespaceDocument.containsKey("coll")) {
            return null;
        }

        return new MongoNamespace(namespaceDocument.getString("db").getValue(), namespaceDocument.getString("coll").getValue());
    }

@ BsonIgnore @ Nullable public MongoNamespace getNamespace ( ) { if ( namespaceDocument == null ) { return null ; } if ( ! namespaceDocument . containsKey ( "db" ) || ! namespaceDocument . containsKey ( "coll" ) ) { return null ; } return new MongoNamespace ( namespaceDocument . getString ( "db" ) . getValue ( ) , namespaceDocument . getString ( "coll" ) . getValue ( ) ) ; }

Returns the namespace

The invalidate operation type does include a MongoNamespace in the ChangeStreamDocument response. The
dropDatabase operation type includes a MongoNamespace, but does not include a collection name as part
of the namespace.

@return the namespace. If the namespaceDocument is null or if it is missing either the 'db' or 'coll' keys,
then this will return null.


@BsonIgnore @Nullable
    public String getDatabaseName() {
        if (namespaceDocument == null) {
            return null;
        }
        if (!namespaceDocument.containsKey("db")) {
            return null;
        }
        return namespaceDocument.getString("db").getValue();
    }

@ BsonIgnore @ Nullable public String getDatabaseName ( ) { if ( namespaceDocument == null ) { return null ; } if ( ! namespaceDocument . containsKey ( "db" ) ) { return null ; } return namespaceDocument . getString ( "db" ) . getValue ( ) ; }

Returns the database name

@return the databaseName. If the namespaceDocument is null or if it is missing the 'db' key, then this will
return null.
@since 3.8


public static <TFullDocument> Codec<ChangeStreamDocument<TFullDocument>> createCodec(final Class<TFullDocument> fullDocumentClass,
                                                                                final CodecRegistry codecRegistry) {
        return new ChangeStreamDocumentCodec<TFullDocument>(fullDocumentClass, codecRegistry);
    }

public static < TFullDocument > Codec < ChangeStreamDocument < TFullDocument > > createCodec ( final Class < TFullDocument > fullDocumentClass , final CodecRegistry codecRegistry ) { return new ChangeStreamDocumentCodec < TFullDocument > ( fullDocumentClass , codecRegistry ) ; }

Creates the codec for the specific ChangeStreamOutput type

@param fullDocumentClass the class to use to represent the fullDocument
@param codecRegistry the codec registry
@param <TFullDocument> the fullDocument type
@return the codec


public static Builder builder(final ClientSessionOptions options) {
        notNull("options", options);
        Builder builder = new Builder();
        builder.causallyConsistent = options.isCausallyConsistent();
        builder.defaultTransactionOptions = options.getDefaultTransactionOptions();
        return builder;
    }

public static Builder builder ( final ClientSessionOptions options ) { notNull ( "options" , options ) ; Builder builder = new Builder ( ) ; builder . causallyConsistent = options . isCausallyConsistent ( ) ; builder . defaultTransactionOptions = options . getDefaultTransactionOptions ( ) ; return builder ; }

Gets an instance of a builder initialized with the given options

@param options the options with which to initialize the builder
@return a builder instance
@since 3.8


public void reset() {
        connectionsPerHost = 10;
        threadsAllowedToBlockForConnectionMultiplier = 5;
        maxWaitTime = 1000 * 60 * 2;
        connectTimeout = 1000 * 10;
        socketFactory = SocketFactory.getDefault();
        socketTimeout = 0;
        socketKeepAlive = false;
        readPreference = null;
        writeConcern = null;
        safe = false;
        w = 0;
        wtimeout = 0;
        fsync = false;
        j = false;
        dbDecoderFactory = DefaultDBDecoder.FACTORY;
        dbEncoderFactory = DefaultDBEncoder.FACTORY;
        description = null;
        cursorFinalizerEnabled = true;
        alwaysUseMBeans = false;
        requiredReplicaSetName = null;
    }


public MongoOptions copy() {
        MongoOptions m = new MongoOptions();
        m.connectionsPerHost = connectionsPerHost;
        m.threadsAllowedToBlockForConnectionMultiplier = threadsAllowedToBlockForConnectionMultiplier;
        m.maxWaitTime = maxWaitTime;
        m.connectTimeout = connectTimeout;
        m.socketFactory = socketFactory;
        m.socketTimeout = socketTimeout;
        m.socketKeepAlive = socketKeepAlive;
        m.readPreference = readPreference;
        m.writeConcern = writeConcern;
        m.safe = safe;
        m.w = w;
        m.wtimeout = wtimeout;
        m.fsync = fsync;
        m.j = j;
        m.dbDecoderFactory = dbDecoderFactory;
        m.dbEncoderFactory = dbEncoderFactory;
        m.description = description;
        m.cursorFinalizerEnabled = cursorFinalizerEnabled;
        m.alwaysUseMBeans = alwaysUseMBeans;
        m.requiredReplicaSetName = requiredReplicaSetName;
        return m;
    }

Copy this MongoOptions instance into a new instance.

@return the new MongoOptions with the same settings as this instance.

Copy this MongoOptions instance into a new instance .


@SuppressWarnings("deprecation")
    public WriteConcern getWriteConcern() {
        WriteConcern retVal;

        if (writeConcern != null) {
            retVal = writeConcern;
        } else if (w != 0 || wtimeout != 0 || fsync | j) {
            retVal = WriteConcern.ACKNOWLEDGED;
            if (w != 0) {
                retVal = retVal.withW(w);
            }
            if (wtimeout != 0) {
                retVal = retVal.withWTimeout(wtimeout, TimeUnit.MILLISECONDS);
            }
            if (fsync) {
                retVal = retVal.withFsync(fsync);
            }
            if (j) {
                retVal = retVal.withJ(j);
            }
        } else if (safe) {
            retVal = WriteConcern.ACKNOWLEDGED;
        } else {
            retVal = WriteConcern.UNACKNOWLEDGED;
        }
        return retVal;
    }

@ SuppressWarnings ( "deprecation" ) public WriteConcern getWriteConcern ( ) { WriteConcern retVal ; if ( writeConcern != null ) { retVal = writeConcern ; } else if ( w != 0 || wtimeout != 0 || fsync | j ) { retVal = WriteConcern . ACKNOWLEDGED ; if ( w != 0 ) { retVal = retVal . withW ( w ) ; } if ( wtimeout != 0 ) { retVal = retVal . withWTimeout ( wtimeout , TimeUnit . MILLISECONDS ) ; } if ( fsync ) { retVal = retVal . withFsync ( fsync ) ; } if ( j ) { retVal = retVal . withJ ( j ) ; } } else if ( safe ) { retVal = WriteConcern . ACKNOWLEDGED ; } else { retVal = WriteConcern . UNACKNOWLEDGED ; } return retVal ; }

Helper method to return the appropriate WriteConcern instance based on the current related options settings.

@return a WriteConcern for the current MongoOptions.

Helper method to return the appropriate WriteConcern instance based on the current related options settings .


public static String getUserAgent(String serviceName, boolean allowTelemetry) {
        String macAddress = "Not Collected";
        if (allowTelemetry) {
            macAddress = GetHashMac.getHashMac();
        }

        return String.format(serviceName + " MacAddressHash:%s", macAddress);
    }

public
static
String
getUserAgent
(
String
serviceName
,
boolean
allowTelemetry
)
{
String
macAddress
=
"Not Collected"
;
if
(
allowTelemetry
)
{
macAddress
=
GetHashMac
.
getHashMac
(
)
;
}
return
String
.
format
(
serviceName
+
" MacAddressHash:%s"
,
macAddress
)
;
}

Generate UserAgent string for given service.

@param serviceName    Name of the service from which called this method.
@param allowTelemetry Whether allows telemtry
@return generated UserAgent string

Generate UserAgent string for given service .


@SuppressFBWarnings("UWF_FIELD_NOT_INITIALIZED_IN_CONSTRUCTOR")
    private void populateProperties(ConfigurableEnvironment environment, VcapPojo[] pojos) {
        final Map<String, Object> map = new HashMap<>();
        populateDefaultStorageProperties(map,
                findPojoForServiceType(VcapServiceType.AZURE_STORAGE, pojos));
        populateDefaultServiceBusProperties(map,
                findPojoForServiceType(VcapServiceType.AZURE_SERVICEBUS, pojos));
        populateDefaultDocumentDBProperties(map,
                findPojoForServiceType(VcapServiceType.AZURE_DOCUMENTDB, pojos));
        addOrReplace(environment.getPropertySources(), map);
    }

Populates default properties during @EnvironmentPostProcessor processing.
<p>
Note that this class gets invoked before Spring creates the logging
subsystem, so we just use System.out.println instead.


private boolean isMatchingUserGroupKey(final JsonNode node) {
        return node.get(aadAuthenticationProperties.getUserGroup().getKey()).asText()
                .equals(aadAuthenticationProperties.getUserGroup().getValue());
    }

private boolean isMatchingUserGroupKey ( final JsonNode node ) { return node . get ( aadAuthenticationProperties . getUserGroup ( ) . getKey ( ) ) . asText ( ) . equals ( aadAuthenticationProperties . getUserGroup ( ) . getValue ( ) ) ; }

Checks that the JSON Node is a valid User Group to extract User Groups from

@param node - json node to look for a key/value to equate against the {@link UserGroupProperties}

@return true if the json node contains the correct key, and expected value to identify a user group.


public Set<GrantedAuthority> convertGroupsToGrantedAuthorities(final List<UserGroup> groups) {
        // Map the authority information to one or more GrantedAuthority's and add it to mappedAuthorities
        final Set<GrantedAuthority> mappedAuthorities = groups.stream().filter(this::isValidUserGroupToGrantAuthority)
                .map(userGroup -> new SimpleGrantedAuthority(DEFAULT_ROLE_PREFIX + userGroup.getDisplayName()))
                .collect(Collectors.toCollection(LinkedHashSet::new));
        if (mappedAuthorities.isEmpty()) {
            mappedAuthorities.add(DEFAULT_AUTHORITY);
        }

        return mappedAuthorities;
    }

Converts UserGroup list to Set of GrantedAutorities
@param groups
@return


public ServiceEndpoints getServiceEndpoints(String environment) {
        Assert.notEmpty(endpoints, "No service endpoints found");

        if (!endpoints.containsKey(environment)) {
            throw new IllegalArgumentException(environment + " is not found in the configuration," +
                    " only following environments are supported: " + endpoints.keySet());
        }

        return endpoints.get(environment);
    }

Get ServiceEndpoints data for the given environment.

@param environment the environment of the cloud service
@return The ServiceEndpoints data for the given azure service environment

Get ServiceEndpoints data for the given environment .


@Bean
    @Scope(BeanDefinition.SCOPE_SINGLETON)
    @ConditionalOnMissingBean(AADAuthenticationFilter.class)
    public AADAuthenticationFilter azureADJwtTokenFilter() {
        LOG.info("AzureADJwtTokenFilter Constructor.");
        return new AADAuthenticationFilter(aadAuthProps, serviceEndpointsProps, getJWTResourceRetriever());
    }

@
Bean
@
Scope
(
BeanDefinition
.
SCOPE_SINGLETON
)
@
ConditionalOnMissingBean
(
AADAuthenticationFilter
.
class
)
public
AADAuthenticationFilter
azureADJwtTokenFilter
(
)
{
LOG
.
info
(
"AzureADJwtTokenFilter Constructor."
)
;
return
new
AADAuthenticationFilter
(
aadAuthProps
,
serviceEndpointsProps
,
getJWTResourceRetriever
(
)
)
;
}

Declare AADAuthenticationFilter bean.

@return AADAuthenticationFilter bean


@RequestMapping(value = "/api/todolist", method = RequestMethod.GET, produces = {MediaType.APPLICATION_JSON_VALUE})
    public ResponseEntity<List<TodoItem>> getAllTodoItems() {
        return new ResponseEntity<>(todoList, HttpStatus.OK);
    }

@ RequestMapping ( value = "/api/todolist" , method = RequestMethod . GET , produces = { MediaType . APPLICATION_JSON_VALUE } ) public ResponseEntity < List < TodoItem > > getAllTodoItems ( ) { return new ResponseEntity <> ( todoList , HttpStatus . OK ) ; }


public LiveReload register(final Path path, final String... includes) {
    if (Files.exists(path)) {
      paths.add(new Object[]{path, Arrays.asList(includes)});
    }
    return this;
  }

public LiveReload register ( final Path path , final String ... includes ) { if ( Files . exists ( path ) ) { paths . add ( new Object [ ] { path , Arrays . asList ( includes ) } ) ; } return this ; }

Add the given path to the watcher.

@param path Path to watch.
@param includes Glob pattern of matching files.
@return This module.


public Map<String, List<File>> build(final String dist, final File dir) throws Exception {
    log.debug("{} aggregators: {}", dist, aggregators);
    aggregators(aggregators, conf);

    return buildInternal(dist, dir);
  }

public
Map
<
String
,
List
<
File
>
>
build
(
final
String
dist
,
final
File
dir
)
throws
Exception
{
log
.
debug
(
"{} aggregators: {}"
,
dist
,
aggregators
)
;
aggregators
(
aggregators
,
conf
)
;
return
buildInternal
(
dist
,
dir
)
;
}

Build assets using the given distribution and write output to the provided directory.

Build process is defined as follow:

1. First, it runs all the aggregators (if any)
2. Then iterates each fileset and per each file in the fileset it apply the processor pipeline.
3. Finally, it merge all the files into one file and compressed/optimized if need it.

@param dist Distribution's name (usually dev or dist).
@param dir Output directory.
@return Map with fileset name as key and list of generated assets.
@throws Exception If something goes wrong.

Build assets using the given distribution and write output to the provided directory .


public String summary(Map<String, List<File>> result, Path outDir, String dist, long duration,
      String... extraInfo) {
    StringBuilder buffer = new StringBuilder();

    buffer.append("Summary:\n");
    long seconds = Duration.ofMillis(duration).getSeconds();
    String took = seconds > 0 ? seconds + "s" : duration + "ms";
    buffer.append("Pipeline: ").append(pipeline(dist)).append("\n");
    buffer.append("Time: ").append(took).append("\n");
    buffer.append("Output: ").append(outDir).append("\n");
    Stream.of(extraInfo).forEach(line -> buffer.append(line).append("\n"));
    int w1 = result.keySet().stream()
        .map(it -> it.length() + 2)
        .max(Integer::compareTo)
        .orElse(0);
    int mw1 = Math.max(w1, "Fileset".length() + 2);
    int w2 = result.values().stream()
        .flatMap(List::stream)
        .map(file -> outDir.relativize(file.toPath()).toString())
        .map(String::length)
        .max(Integer::compareTo)
        .orElse(0);
    buffer.append(format(w1, w2, "Fileset", "Output", "Size"));
    result.forEach((fileset, files) -> {
      if (files.size() > 0) {
        // Head
        buffer.append(format(mw1, w2, "  " + fileset, "", ""));
        // Tail
        files.forEach(file -> buffer.append(format(mw1, w2, "", outDir.relativize(file.toPath()),
            AssetCompiler.humanReadableByteCount(file.length()))));
      }
    });
    return buffer.toString();
  }

public
String
summary
(
Map
<
String
,
List
<
File
>
>
result
,
Path
outDir
,
String
dist
,
long
duration
,
String
...
extraInfo
)
{
StringBuilder
buffer
=
new
StringBuilder
(
)
;
buffer
.
append
(
"Summary:\n"
)
;
long
seconds
=
Duration
.
ofMillis
(
duration
)
.
getSeconds
(
)
;
String
took
=
seconds
>
0
seconds
+
"s"
:
duration
+
"ms"
;
buffer
.
append
(
"Pipeline: "
)
.
append
(
pipeline
(
dist
)
)
.
append
(
"\n"
)
;
buffer
.
append
(
"Time: "
)
.
append
(
took
)
.
append
(
"\n"
)
;
buffer
.
append
(
"Output: "
)
.
append
(
outDir
)
.
append
(
"\n"
)
;
Stream
.
of
(
extraInfo
)
.
forEach
(
line
->
buffer
.
append
(
line
)
.
append
(
"\n"
)
)
;
int
w1
=
result
.
keySet
(
)
.
stream
(
)
.
map
(
it
->
it
.
length
(
)
+
2
)
.
max
(
Integer
::
compareTo
)
.
orElse
(
0
)
;
int
mw1
=
Math
.
max
(
w1
,
"Fileset"
.
length
(
)
+
2
)
;
int
w2
=
result
.
values
(
)
.
stream
(
)
.
flatMap
(
List
::
stream
)
.
map
(
file
->
outDir
.
relativize
(
file
.
toPath
(
)
)
.
toString
(
)
)
.
map
(
String
::
length
)
.
max
(
Integer
::
compareTo
)
.
orElse
(
0
)
;
buffer
.
append
(
format
(
w1
,
w2
,
"Fileset"
,
"Output"
,
"Size"
)
)
;
result
.
forEach
(
(
fileset
,
files
)
->
{
if
(
files
.
size
(
)
>
0
)
{
// Head
buffer
.
append
(
format
(
mw1
,
w2
,
"  "
+
fileset
,
""
,
""
)
)
;
// Tail
files
.
forEach
(
file
->
buffer
.
append
(
format
(
mw1
,
w2
,
""
,
outDir
.
relativize
(
file
.
toPath
(
)
)
,
AssetCompiler
.
humanReadableByteCount
(
file
.
length
(
)
)
)
)
)
;
}
}
)
;
return
buffer
.
toString
(
)
;
}

Print a summary of the given results.

@param result Compilation result.
@param outDir Output directory.
@param dist Distribution (dev or prod).
@param duration Execution time in millis.
@param extraInfo Additional information.
@return Summary.


private void register(final Path dir) throws IOException {
    WatchKey key = dir.register(watcher, new Kind[]{ENTRY_CREATE, ENTRY_DELETE, ENTRY_MODIFY }, HIGH);
    keys.put(key, dir);
  }

private void register ( final Path dir ) throws IOException { WatchKey key = dir . register ( watcher , new Kind [ ] { ENTRY_CREATE , ENTRY_DELETE , ENTRY_MODIFY } , HIGH ) ; keys . put ( key , dir ) ; }

Register the given directory with the WatchService


public RamlType newProperty(String name, String type, boolean required, String... values) {
    if (properties == null) {
      properties = new LinkedHashMap<>();
    }
    if (values.length > 0) {
      properties.put(required ? name : name + "?", ImmutableMap.of("enum", values));
    } else {
      properties.put(required ? name : name + "?", type);
    }
    return this;
  }

public RamlType newProperty ( String name , String type , boolean required , String ... values ) { if ( properties == null ) { properties = new LinkedHashMap <> ( ) ; } if ( values . length > 0 ) { properties . put ( required ? name : name + "?" , ImmutableMap . of ( "enum" , values ) ) ; } else { properties . put ( required ? name : name + "?" , type ) ; } return this ; }

Defines a new property.

@param name Property name.
@param type Property type.
@param required True for required.
@param values Enum values.
@return This type.


public static RamlType valueOf(String name) {
    switch (name.toLowerCase()) {
      case "boolean":
        return BOOLEAN;
      case "byte":
      case "short":
      case "int":
      case "integer":
      case "long":
        return INTEGER;
      case "float":
      case "double":
        return NUMBER;
      case "char":
      case "character":
      case "string":
        return STRING;
      case "file":
      case "upload":
      case "path":
      case "binary":
        return FILE;
      case "date":
      case "datetime":
      case "localdatetime":
        return DATE_TIME;
    }
    return new RamlType("object", name);
  }

public static RamlType valueOf ( String name ) { switch ( name . toLowerCase ( ) ) { case "boolean" : return BOOLEAN ; case "byte" : case "short" : case "int" : case "integer" : case "long" : return INTEGER ; case "float" : case "double" : return NUMBER ; case "char" : case "character" : case "string" : return STRING ; case "file" : case "upload" : case "path" : case "binary" : return FILE ; case "date" : case "datetime" : case "localdatetime" : return DATE_TIME ; } return new RamlType ( "object" , name ) ; }

Get a RAML type from string.

@param name String name.
@return RAML type.


public FileEventOptions kind(final WatchEvent.Kind<Path> kind) {
    requireNonNull(kind, "WatchEvent.Kind required.");
    kinds.add(kind);
    return this;
  }

public
FileEventOptions
kind
(
final
WatchEvent
.
Kind
<
Path
>
kind
)
{
requireNonNull
(
kind
,
"WatchEvent.Kind required."
)
;
kinds
.
add
(
kind
)
;
return
this
;
}

Append a kind filter.

The default filter is: {@link StandardWatchEventKinds#ENTRY_CREATE},
{@link StandardWatchEventKinds#ENTRY_DELETE} and {@link StandardWatchEventKinds#ENTRY_MODIFY}.

@param kind Filter type.
@return This options.


public Hbs doWith(final Consumer<Handlebars> callback) {
    requireNonNull(callback, "Configurer is required.");
    return doWith((hbs, conf) -> callback.accept(hbs));
  }

public
Hbs
doWith
(
final
Consumer
<
Handlebars
>
callback
)
{
requireNonNull
(
callback
,
"Configurer is required."
)
;
return
doWith
(
(
hbs
,
conf
)
->
callback
.
accept
(
hbs
)
)
;
}

Set a handlebars callback.

<pre>{@code
{
use(new Hbs().doWith((hbs, conf) -> {
...
});
}
}</pre>
@param callback Configurer callback.
@return This module.


public Micrometer doWith(@Nonnull final Consumer<CompositeMeterRegistry> configurer) {
    return doWith((registry, conf) -> configurer.accept(registry));
  }

public Micrometer doWith ( @ Nonnull final Consumer < CompositeMeterRegistry > configurer ) { return doWith ( ( registry , conf ) -> configurer . accept ( registry ) ) ; }

Advanced configuration of main registry.

@param configurer Configurer callback.
@return This module.

Advanced configuration of main registry .


public Thl doWith(final Consumer<TemplateEngine> callback) {
    requireNonNull(callback, "Callback required.");
    return doWith((e, c) -> callback.accept(e));
  }

public
Thl
doWith
(
final
Consumer
<
TemplateEngine
>
callback
)
{
requireNonNull
(
callback
,
"Callback required."
)
;
return
doWith
(
(
e
,
c
)
->
callback
.
accept
(
e
)
)
;
}

Set a configuration callback.

<pre>{@code
{
use(new Thl().doWith(engine -> {
...
}));
}
}</pre>

@param callback Callback.
@return This module.


public Auth form(final String pattern,
      final Class<? extends Authenticator<UsernamePasswordCredentials>> authenticator) {
    bindings.put(pattern, (binder, conf) -> {
      TypeLiteral<Authenticator<UsernamePasswordCredentials>> usernamePasswordAuthenticator = new TypeLiteral<Authenticator<UsernamePasswordCredentials>>() {
      };
      binder.bind(usernamePasswordAuthenticator.getRawType()).to(authenticator);

      bindProfile(binder, CommonProfile.class);

      Multibinder.newSetBinder(binder, Client.class)
          .addBinding().toProvider(FormAuth.class);

      return new FormFilter(conf.getString("auth.form.loginUrl"),
          conf.getString("application.path") + authCallbackPath(conf));
    });

    return this;
  }

public Auth form ( final String pattern , final Class < ? extends Authenticator < UsernamePasswordCredentials > > authenticator ) { bindings . put ( pattern , ( binder , conf ) -> { TypeLiteral < Authenticator < UsernamePasswordCredentials >> usernamePasswordAuthenticator = new TypeLiteral < Authenticator < UsernamePasswordCredentials > > ( ) { } ; binder . bind ( usernamePasswordAuthenticator . getRawType ( ) ) . to ( authenticator ) ; bindProfile ( binder , CommonProfile . class ) ; Multibinder . newSetBinder ( binder , Client . class ) . addBinding ( ) . toProvider ( FormAuth . class ) ; return new FormFilter ( conf . getString ( "auth.form.loginUrl" ) , conf . getString ( "application.path" ) + authCallbackPath ( conf ) ) ; } ) ; return this ; }

Add a form auth client.

@param pattern URL pattern to protect.
@param authenticator Authenticator to use.
@return This module.


public Auth basic(final String pattern,
      final Class<? extends Authenticator<UsernamePasswordCredentials>> authenticator) {
    bindings.put(pattern, (binder, config) -> {
      TypeLiteral<Authenticator<UsernamePasswordCredentials>> usernamePasswordAuthenticator = new TypeLiteral<Authenticator<UsernamePasswordCredentials>>() {
      };
      binder.bind(usernamePasswordAuthenticator.getRawType()).to(authenticator);

      bindProfile(binder, CommonProfile.class);

      Multibinder.newSetBinder(binder, Client.class)
          .addBinding().toProvider(BasicAuth.class);

      return new AuthFilter(IndirectBasicAuthClient.class, CommonProfile.class);
    });
    return this;
  }

public Auth basic ( final String pattern , final Class < ? extends Authenticator < UsernamePasswordCredentials > > authenticator ) { bindings . put ( pattern , ( binder , config ) -> { TypeLiteral < Authenticator < UsernamePasswordCredentials >> usernamePasswordAuthenticator = new TypeLiteral < Authenticator < UsernamePasswordCredentials > > ( ) { } ; binder . bind ( usernamePasswordAuthenticator . getRawType ( ) ) . to ( authenticator ) ; bindProfile ( binder , CommonProfile . class ) ; Multibinder . newSetBinder ( binder , Client . class ) . addBinding ( ) . toProvider ( BasicAuth . class ) ; return new AuthFilter ( IndirectBasicAuthClient . class , CommonProfile . class ) ; } ) ; return this ; }

Add a basic auth client.

@param pattern URL pattern to protect.
@param authenticator Authenticator to use.
@return This module.


public void resolve(@Nullable final Object value) {
    if (value == null) {
      handler.handle(null, null);
    } else {
      Result result;
      if (value instanceof Result) {
        super.set(value);
        result = (Result) value;
      } else {
        super.set(value);
        result = clone();
      }
      handler.handle(result, null);
    }
  }

public void resolve ( @ Nullable final Object value ) { if ( value == null ) { handler . handle ( null , null ) ; } else { Result result ; if ( value instanceof Result ) { super . set ( value ) ; result = ( Result ) value ; } else { super . set ( value ) ; result = clone ( ) ; } handler . handle ( result , null ) ; } }

Resolve the deferred value and handle it. This method will send the response to a client and
cleanup and close all the resources.

@param value A value for this deferred.

Resolve the deferred value and handle it . This method will send the response to a client and cleanup and close all the resources .


public RamlPath path(String pattern) {
    RamlPath path = resources.get(pattern);
    if (path == null) {
      path = new RamlPath();
      resources.put(pattern, path);
    }
    return path;
  }

public RamlPath path ( String pattern ) { RamlPath path = resources . get ( pattern ) ; if ( path == null ) { path = new RamlPath ( ) ; resources . put ( pattern , path ) ; } return path ; }

Get a path for the given pattern. If the path doesn't exist, a new path will be created.

@param pattern Pattern.
@return Path for the given pattern.

Get a path for the given pattern . If the path doesn t exist a new path will be created .


public RamlType define(Type type) {
    if (types == null) {
      types = new LinkedHashMap<>();
    }
    Type componentType = componentType(type);
    String typeName = MoreTypes.getRawType(componentType).getSimpleName();
    RamlType ramlType = RamlType.valueOf(typeName);
    if (ramlType.isObject()) {
      RamlType existing = types.get(typeName);
      if (existing == null) {
        ModelConverters converter = ModelConverters.getInstance();
        Property property = converter.readAsProperty(componentType);

        Map<PropertyBuilder.PropertyId, Object> args = new EnumMap<>(
            PropertyBuilder.PropertyId.class);
        for (Map.Entry<String, Model> entry : converter.readAll(componentType).entrySet()) {
          define(entry.getKey(), entry.getValue());
        }
        ramlType = define(typeName, PropertyBuilder.toModel(PropertyBuilder.merge(property, args)));
      } else {
        ramlType = existing;
      }
    }

    return type != componentType ? ramlType.toArray() : ramlType;
  }

public RamlType define ( Type type ) { if ( types == null ) { types = new LinkedHashMap <> ( ) ; } Type componentType = componentType ( type ) ; String typeName = MoreTypes . getRawType ( componentType ) . getSimpleName ( ) ; RamlType ramlType = RamlType . valueOf ( typeName ) ; if ( ramlType . isObject ( ) ) { RamlType existing = types . get ( typeName ) ; if ( existing == null ) { ModelConverters converter = ModelConverters . getInstance ( ) ; Property property = converter . readAsProperty ( componentType ) ; Map < PropertyBuilder . PropertyId , Object > args = new EnumMap <> ( PropertyBuilder . PropertyId . class ) ; for ( Map . Entry < String , Model > entry : converter . readAll ( componentType ) . entrySet ( ) ) { define ( entry . getKey ( ) , entry . getValue ( ) ) ; } ramlType = define ( typeName , PropertyBuilder . toModel ( PropertyBuilder . merge ( property , args ) ) ) ; } else { ramlType = existing ; } } return type != componentType ? ramlType . toArray ( ) : ramlType ; }

Register a Java type and produces an equivalent RAML type. It returns an existing RAML type if
the Java type was registered already.

@param type Java type.
@return RAML type.

Register a Java type and produces an equivalent RAML type . It returns an existing RAML type if the Java type was registered already .


public String toYaml() throws IOException {
    YAMLMapper mapper = new YAMLMapper();
    mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
    mapper.configure(YAMLGenerator.Feature.ALWAYS_QUOTE_NUMBERS_AS_STRINGS, false);
    mapper.configure(YAMLGenerator.Feature.MINIMIZE_QUOTES, true);
    return "#%RAML 1.0\n" + mapper.writer().withDefaultPrettyPrinter().writeValueAsString(this);
  }

public
String
toYaml
(
)
throws
IOException
{
YAMLMapper
mapper
=
new
YAMLMapper
(
)
;
mapper
.
setSerializationInclusion
(
JsonInclude
.
Include
.
NON_NULL
)
;
mapper
.
configure
(
YAMLGenerator
.
Feature
.
ALWAYS_QUOTE_NUMBERS_AS_STRINGS
,
false
)
;
mapper
.
configure
(
YAMLGenerator
.
Feature
.
MINIMIZE_QUOTES
,
true
)
;
return
"#%RAML 1.0\n"
+
mapper
.
writer
(
)
.
withDefaultPrettyPrinter
(
)
.
writeValueAsString
(
this
)
;
}

Convert this RAML object to Yaml.

@return Yaml string.
@throws IOException If something goes wrong.


public Map<Integer, String> status() {
    return Optional.ofNullable(status).orElse(ImmutableMap.of());
  }

public Map < Integer , String > status ( ) { return Optional . ofNullable ( status ) . orElse ( ImmutableMap . of ( ) ) ; }

Get status codes.

@return Status codes.


public int statusCode() {
    return status().entrySet().stream()
        .map(it -> it.getKey())
        .filter(code -> code >= 200 && code < 400)
        .findFirst()
        .orElseGet(() -> type() == void.class ? 204 : 200);
  }

public int statusCode ( ) { return status ( ) . entrySet ( ) . stream ( ) . map ( it -> it . getKey ( ) ) . filter ( code -> code >= 200 && code < 400 ) . findFirst ( ) . orElseGet ( ( ) -> type ( ) == void . class ? 204 : 200 ) ; }


public RouteResponse status(final Map<Integer, String> status) {
    if (status != null) {
      if (this.status == null) {
        this.status = new LinkedHashMap<>();
        this.status.putAll(status);
      }
    }
    return this;
  }

public RouteResponse status ( final Map < Integer , String > status ) { if ( status != null ) { if ( this . status == null ) { this . status = new LinkedHashMap <> ( ) ; this . status . putAll ( status ) ; } } return this ; }

Set status code map.

@param status Status code map.
@return This response.


public void setMediaType(final String mediaType, RamlType body) {
    if (this.mediaType == null) {
      this.mediaType = new LinkedHashMap<>();
    }
    this.mediaType.put(mediaType, body);
  }

public void setMediaType ( final String mediaType , RamlType body ) { if ( this . mediaType == null ) { this . mediaType = new LinkedHashMap <> ( ) ; } this . mediaType . put ( mediaType , body ) ; }

Set media type.

@param mediaType Media type.
@param body RAML type.


static Throwing.Runnable runEnhancer() {
    return () -> {
      Set<String> packages = PKG.getAndSet(null);
      if (packages != null) {
        EbeanEnhancer.newEnhancer().run(packages);
      }
    };
  }

static Throwing . Runnable runEnhancer ( ) { return ( ) -> { Set < String > packages = PKG . getAndSet ( null ) ; if ( packages != null ) { EbeanEnhancer . newEnhancer ( ) . run ( packages ) ; } } ; }

package for test.

@return An enhancer task. It runs once per classloader instance.


public void setMediaType(final List<String> mediaType) {
    this.mediaType = mediaType == null ? null : (mediaType.isEmpty() ? null : mediaType);
  }

public void setMediaType ( final List < String > mediaType ) { this . mediaType = mediaType == null ? null : ( mediaType . isEmpty ( ) ? null : mediaType ) ; }

Set media types.

@param mediaType Media types.


public RamlParameter queryParameter(String name) {
    if (queryParameters == null) {
      queryParameters = new LinkedHashMap<>();
    }
    RamlParameter param = queryParameters.get(name);
    if (param == null) {
      param = new RamlParameter(name);
      queryParameters.put(name, param);
    }
    return param;
  }

public RamlParameter queryParameter ( String name ) { if ( queryParameters == null ) { queryParameters = new LinkedHashMap <> ( ) ; } RamlParameter param = queryParameters . get ( name ) ; if ( param == null ) { param = new RamlParameter ( name ) ; queryParameters . put ( name , param ) ; } return param ; }

Get or create a query parameter using the giving name.

@param name Parameter name.
@return Query parameter.

Get or create a query parameter using the giving name .


public RamlParameter formParameter(String name) {
    if (formParameters == null) {
      formParameters = new LinkedHashMap<>();
    }
    RamlParameter param = formParameters.get(name);
    if (param == null) {
      param = new RamlParameter(name);
      formParameters.put(name, param);
    }
    return param;
  }

public RamlParameter formParameter ( String name ) { if ( formParameters == null ) { formParameters = new LinkedHashMap <> ( ) ; } RamlParameter param = formParameters . get ( name ) ; if ( param == null ) { param = new RamlParameter ( name ) ; formParameters . put ( name , param ) ; } return param ; }

Get or create a form parameter using the giving name.

@param name Parameter name.
@return Form parameter.

Get or create a form parameter using the giving name .


public RamlParameter headerParameter(String name) {
    if (headers == null) {
      headers = new LinkedHashMap<>();
    }
    RamlParameter param = headers.get(name);
    if (param == null) {
      param = new RamlParameter(name);
      headers.put(name, param);
    }
    return param;
  }

public RamlParameter headerParameter ( String name ) { if ( headers == null ) { headers = new LinkedHashMap <> ( ) ; } RamlParameter param = headers . get ( name ) ; if ( param == null ) { param = new RamlParameter ( name ) ; headers . put ( name , param ) ; } return param ; }

Get or create a header parameter using the giving name.

@param name Parameter name.
@return Header parameter.

Get or create a header parameter using the giving name .


public RamlResponse response(Integer status) {
    if (responses == null) {
      responses = new LinkedHashMap<>();
    }
    RamlResponse response = responses.get(status);
    if (response == null) {
      response = new RamlResponse();
      responses.put(status, response);
    }
    return response;
  }

public RamlResponse response ( Integer status ) { if ( responses == null ) { responses = new LinkedHashMap <> ( ) ; } RamlResponse response = responses . get ( status ) ; if ( response == null ) { response = new RamlResponse ( ) ; responses . put ( status , response ) ; } return response ; }

Get or create a response using the given status code.

@param status Status code.
@return RAML response.

Get or create a response using the given status code .


public Hbv doWith(final Consumer<HibernateValidatorConfiguration> configurer) {
    requireNonNull(configurer, "Configurer callback is required.");
    this.configurer = (hvc, conf) -> configurer.accept(hvc);
    return this;
  }

public
Hbv
doWith
(
final
Consumer
<
HibernateValidatorConfiguration
>
configurer
)
{
requireNonNull
(
configurer
,
"Configurer callback is required."
)
;
this
.
configurer
=
(
hvc
,
conf
)
->
configurer
.
accept
(
hvc
)
;
return
this
;
}

Setup a configurer callback.

@param configurer Configurer callback.
@return This module.


@Override
  public int read(final byte[] b, int off, int len) throws IOException {
    int read = 0;
    while (len > 0) {
      if (encoderOut.position() > 0) {
        encoderOut.flip();
        int c = Math.min(encoderOut.remaining(), len);
        encoderOut.get(b, off, c);
        off += c;
        len -= c;
        read += c;
        encoderOut.compact();
      } else {
        if (!endOfInput && (lastCoderResult == null || lastCoderResult.isUnderflow())) {
          encoderIn.compact();
          int position = encoderIn.position();
          // We don't use Reader#read(CharBuffer) here because it is more efficient
          // to write directly to the underlying char array (the default implementation
          // copies data to a temporary char array).
          int c = reader.read(encoderIn.array(), position, encoderIn.remaining());
          if (c == -1) {
            endOfInput = true;
          } else {
            encoderIn.position(position + c);
          }
          encoderIn.flip();
        }
        lastCoderResult = encoder.encode(encoderIn, encoderOut, endOfInput);
        if (endOfInput && encoderOut.position() == 0) {
          break;
        }
      }
    }
    return read == 0 && endOfInput ? -1 : read;
  }

Read the specified number of bytes into an array.

@param b the byte array to read into
@param off the offset to start reading bytes into
@param len the number of bytes to read
@return the number of bytes read or <code>-1</code> if the end of the stream has been reached
@throws IOException if an I/O error occurs

Read the specified number of bytes into an array .


public static Requery reactive(final String name, final EntityModel model) {
    return new Requery(name, ReactiveEntityStore.class, model,
        conf -> ReactiveSupport.toReactiveStore(new EntityDataStore<>(conf)));
  }

public static Requery reactive ( final String name , final EntityModel model ) { return new Requery ( name , ReactiveEntityStore . class , model , conf -> ReactiveSupport . toReactiveStore ( new EntityDataStore <> ( conf ) ) ) ; }

Creates a Requery module with RxJava data store.

<pre>{@code
{
use(Requery.reactive(Models.DEFAULT));

get("/", () -> {
ReactiveEntityStore store = require(ReactiveEntityStore.class);
// work with reactive store
});
}
}</pre>

@param name Database name.
@param model Entity model.
@return A new {@link Requery} module.

Creates a Requery module with RxJava data store .


public static Requery reactor(final String name, final EntityModel model) {
    return new Requery(name, ReactorEntityStore.class, model,
        conf -> new ReactorEntityStore<>(new EntityDataStore<>(conf)));
  }

public static Requery reactor ( final String name , final EntityModel model ) { return new Requery ( name , ReactorEntityStore . class , model , conf -> new ReactorEntityStore <> ( new EntityDataStore <> ( conf ) ) ) ; }

Creates a Requery module with Reactor data store.

<pre>{@code
{
use(Requery.reactor(Models.DEFAULT));

get("/", () -> {
ReactorEntityStore store = require(ReactorEntityStore.class);
// work with reactive store
});
}
}</pre>

@param name Database name.
@param model Entity model.
@return A new {@link Requery} module.

Creates a Requery module with Reactor data store .


public static Requery completionStage(final String name, final EntityModel model) {
    return new Requery(name, CompletionStageEntityStore.class, model,
        conf -> new CompletableEntityStore(new EntityDataStore<>(conf)));
  }

public static Requery completionStage ( final String name , final EntityModel model ) { return new Requery ( name , CompletionStageEntityStore . class , model , conf -> new CompletableEntityStore ( new EntityDataStore <> ( conf ) ) ) ; }

Creates an async Requery module with Java 8 data store.

<pre>{@code
{
use(Requery.completionStage(Models.DEFAULT));

get("/", () -> {
CompletionStageEntityStore store = require(CompletionStageEntityStore.class);
// work with reactive store
});
}
}</pre>

@param name Database name.
@param model Entity model.
@return A new {@link Requery} module.

Creates an async Requery module with Java 8 data store .


public static Requery kotlin(final String name, final EntityModel model) {
    return new Requery(name, KotlinEntityDataStore.class, model,
        conf -> new KotlinEntityDataStore<>(conf));
  }

public static Requery kotlin ( final String name , final EntityModel model ) { return new Requery ( name , KotlinEntityDataStore . class , model , conf -> new KotlinEntityDataStore <> ( conf ) ) ; }

Creates a Kotlin Requery module.

<pre>{@code
{
use(Requery.kotlin(Models.DEFAULT));

get("/", () -> {
KotlinEntityDataStore store = require(KotlinEntityDataStore.class);
// work with kotlin store
});
}
}</pre>

@param name Database name.
@param model Entity model.
@return A new {@link Requery} module.


public XSS js(final JavaScriptEscapeType type, final JavaScriptEscapeLevel level) {
    this.jslevel = requireNonNull(level, "Level required.");
    this.jstype = requireNonNull(type, "Type required.");
    return this;
  }

public
XSS
js
(
final
JavaScriptEscapeType
type
,
final
JavaScriptEscapeLevel
level
)
{
this
.
jslevel
=
requireNonNull
(
level
,
"Level required."
)
;
this
.
jstype
=
requireNonNull
(
type
,
"Type required."
)
;
return
this
;
}

Set JavaScript escape type and level.

@param type Type.
@param level Level.
@return This module.


public XSS html(final HtmlEscapeType type, final HtmlEscapeLevel level) {
    this.htmllevel = requireNonNull(level, "Level required.");
    this.htmltype = requireNonNull(type, "Type required.");
    return this;
  }

public
XSS
html
(
final
HtmlEscapeType
type
,
final
HtmlEscapeLevel
level
)
{
this
.
htmllevel
=
requireNonNull
(
level
,
"Level required."
)
;
this
.
htmltype
=
requireNonNull
(
type
,
"Type required."
)
;
return
this
;
}

Set HTML escape type and level.

@param type Type.
@param level Level.
@return This module.


public XSS json(final JsonEscapeType type, final JsonEscapeLevel level) {
    this.jsonlevel = requireNonNull(level, "Level required.");
    this.jsontype = requireNonNull(type, "Type required.");
    return this;
  }

public
XSS
json
(
final
JsonEscapeType
type
,
final
JsonEscapeLevel
level
)
{
this
.
jsonlevel
=
requireNonNull
(
level
,
"Level required."
)
;
this
.
jsontype
=
requireNonNull
(
type
,
"Type required."
)
;
return
this
;
}

Set JSON escape type and level.

@param type Type.
@param level Level.
@return This module.


public XSS css(final CssStringEscapeType type, final CssStringEscapeLevel level) {
    this.csslevel = requireNonNull(level, "Level required.");
    this.csstype = requireNonNull(type, "Type required.");
    return this;
  }

public
XSS
css
(
final
CssStringEscapeType
type
,
final
CssStringEscapeLevel
level
)
{
this
.
csslevel
=
requireNonNull
(
level
,
"Level required."
)
;
this
.
csstype
=
requireNonNull
(
type
,
"Type required."
)
;
return
this
;
}

Set CSS escape type and level.

@param type Type.
@param level Level.
@return This module.


private Map<String, Object> attrs(final String path, final String... without) {
    Map<String, Object> attrs = new LinkedHashMap<>(get(path));
    Arrays.asList(without).forEach(attrs::remove);
    return attrs;
  }

private Map < String , Object > attrs ( final String path , final String ... without ) { Map < String , Object > attrs = new LinkedHashMap <> ( get ( path ) ) ; Arrays . asList ( without ) . forEach ( attrs :: remove ) ; return attrs ; }

Read an object path and optionally filter some child paths.

@param path    Path to read.
@param without Properties to filter.
@return Properties.

Read an object path and optionally filter some child paths .


private CharSequence css(final String id, final Element svg) {
    Throwing.Function<String, Tuple<Tuple<Number, String>, Tuple<Number, String>>> viewBox = Throwing
        .<String, Tuple<Tuple<Number, String>, Tuple<Number, String>>>throwingFunction(name -> {
          String vbox = svg.attr(name);
          String[] dimension = vbox.split("\\s+");
          return new Tuple(parse(dimension[2]), parse(dimension[_3]));
        }).memoized();
    Tuple<Number, String> w = Optional.ofNullable(Strings.emptyToNull(svg.attr("width")))
        .map(this::parse)
        .orElseGet(() -> viewBox.apply("viewBox")._1);
    Tuple<Number, String> h = Optional.ofNullable(Strings.emptyToNull(svg.attr("height")))
        .map(this::parse)
        .orElseGet(() -> viewBox.apply("viewBox")._2);
    StringBuilder css = new StringBuilder();
    css.append(get("css.prefix").toString()).append(".").append(id)
        .append(" {\n  width: ").append(w._1).append(w._2).append(";\n")
        .append("  height: ").append(h._1).append(h._2).append(";\n}");
    return css;
  }

private
CharSequence
css
(
final
String
id
,
final
Element
svg
)
{
Throwing
.
Function
<
String
,
Tuple
<
Tuple
<
Number
,
String
>
,
Tuple
<
Number
,
String
>
>
>
viewBox
=
Throwing
.
<
String
,
Tuple
<
Tuple
<
Number
,
String
>
,
Tuple
<
Number
,
String
>
>
>
throwingFunction
(
name
->
{
String
vbox
=
svg
.
attr
(
name
)
;
String
[
]
dimension
=
vbox
.
split
(
"\\s+"
)
;
return
new
Tuple
(
parse
(
dimension
[
2
]
)
,
parse
(
dimension
[
_3
]
)
)
;
}
)
.
memoized
(
)
;
Tuple
<
Number
,
String
>
w
=
Optional
.
ofNullable
(
Strings
.
emptyToNull
(
svg
.
attr
(
"width"
)
)
)
.
map
(
this
::
parse
)
.
orElseGet
(
(
)
->
viewBox
.
apply
(
"viewBox"
)
.
_1
)
;
Tuple
<
Number
,
String
>
h
=
Optional
.
ofNullable
(
Strings
.
emptyToNull
(
svg
.
attr
(
"height"
)
)
)
.
map
(
this
::
parse
)
.
orElseGet
(
(
)
->
viewBox
.
apply
(
"viewBox"
)
.
_2
)
;
StringBuilder
css
=
new
StringBuilder
(
)
;
css
.
append
(
get
(
"css.prefix"
)
.
toString
(
)
)
.
append
(
"."
)
.
append
(
id
)
.
append
(
" {\n  width: "
)
.
append
(
w
.
_1
)
.
append
(
w
.
_2
)
.
append
(
";\n"
)
.
append
(
"  height: "
)
.
append
(
h
.
_1
)
.
append
(
h
.
_2
)
.
append
(
";\n}"
)
;
return
css
;
}

Generate a CSS rule, it reads the width and height attributes of the svg element or fallback to
viewBox attribute.

@param id  ID to use.
@param svg Svg element to convert.
@return A css rule.

Generate a CSS rule it reads the width and height attributes of the svg element or fallback to viewBox attribute .


private Tuple<Number, String> parse(final String value) {
    Matcher matcher = SIZE.matcher(value);
    if (matcher.find()) {
      String number = matcher.group(1);
      String unit = matcher.group(_3);
      boolean round = get("css.round");
      Number num = Double.parseDouble(number);
      return new Tuple(round ? Math.round(num.doubleValue()) : num, unit);
    }
    return null;
  }

private Tuple < Number , String > parse ( final String value ) { Matcher matcher = SIZE . matcher ( value ) ; if ( matcher . find ( ) ) { String number = matcher . group ( 1 ) ; String unit = matcher . group ( _3 ) ; boolean round = get ( "css.round" ) ; Number num = Double . parseDouble ( number ) ; return new Tuple ( round ? Math . round ( num . doubleValue ( ) ) : num , unit ) ; } return null ; }

Parse a css size unit value, like 10px or 18.919px and optionally round the value to the
closest integer.

@param value Value to parse.
@return A tuple with a number and unit(px, em, etc...)

Parse a css size unit value like 10px or 18 . 919px and optionally round the value to the closest integer .


private void write(final Path path, final List<CharSequence> sequence) throws IOException {
    log.debug("writing: {}", path.normalize().toAbsolutePath());
    path.toFile().getParentFile().mkdirs();
    Files.write(path, sequence);
  }

private
void
write
(
final
Path
path
,
final
List
<
CharSequence
>
sequence
)
throws
IOException
{
log
.
debug
(
"writing: {}"
,
path
.
normalize
(
)
.
toAbsolutePath
(
)
)
;
path
.
toFile
(
)
.
getParentFile
(
)
.
mkdirs
(
)
;
Files
.
write
(
path
,
sequence
)
;
}

Write content to file.

@param path     Target file.
@param sequence File content.
@throws IOException If something goes wrong.


public TransactionalRequest handle(String name) {
    this.handleKey = Key.get(Handle.class, Names.named(name));
    return this;
  }

public TransactionalRequest handle ( String name ) { this . handleKey = Key . get ( Handle . class , Names . named ( name ) ) ; return this ; }

Use a named key for accessing to the request scoped Handle.

@param name Name of request scoped Handle.
@return This object.

Use a named key for accessing to the request scoped Handle .


private Model doModel(Type type, Model model) {
    Map<String, Property> properties = model.getProperties();
    if (properties != null) {
      BeanDescription desc = Json.mapper().getSerializationConfig()
          .introspect(Json.mapper().constructType(type));
      for (BeanPropertyDefinition beanProperty : desc.findProperties()) {
        Property property = properties.get(beanProperty.getName());
        if (property != null) {
          property.setRequired(beanProperty.isRequired());
        }
      }
    }
    return model;
  }

private Model doModel ( Type type , Model model ) { Map < String , Property > properties = model . getProperties ( ) ; if ( properties != null ) { BeanDescription desc = Json . mapper ( ) . getSerializationConfig ( ) . introspect ( Json . mapper ( ) . constructType ( type ) ) ; for ( BeanPropertyDefinition beanProperty : desc . findProperties ( ) ) { Property property = properties . get ( beanProperty . getName ( ) ) ; if ( property != null ) { property . setRequired ( beanProperty . isRequired ( ) ) ; } } } return model ; }

Mostly for kotlin null safe operator and immutable properties.

@param type Target type.
@param model Model.
@return Input model.

Mostly for kotlin null safe operator and immutable properties .


@Nonnull
  public <T> Optional<T> lastEventId(final Class<T> type) {
    return lastEventId.toOptional(type);
  }

@ Nonnull public < T > Optional < T > lastEventId ( final Class < T > type ) { return lastEventId . toOptional ( type ) ; }

Server sent event will send a Last-Event-ID header if the server goes down.

@param type Last event id type.
@param <T> Event id type.
@return Last event id.

Server sent event will send a Last - Event - ID header if the server goes down .


@Nonnull
  public CompletableFuture<Optional<Object>> send(final Object data) {
    return event(data).send();
  }

@ Nonnull public CompletableFuture < Optional < Object > > send ( final Object data ) { return event ( data ) . send ( ) ; }

Send an event.

{@code
sse.send(new MyObject());
}

{@code
sse.send(new MyObject(), "json").whenComplete((id, x) -> {
if (x == null) {
handleSuccess();
} else {
handleError(x);
}
});
}

The id of the success callback correspond to the {@link Event#id()}.

@param data Event data.
@return A future. The success callback contains the {@link Event#id()}.


@Nonnull
  public View put(final String name, final Object value) {
    requireNonNull(name, "Model name is required.");
    model.put(name, value);
    return this;
  }

@
Nonnull
public
View
put
(
final
String
name
,
final
Object
value
)
{
requireNonNull
(
name
,
"Model name is required."
)
;
model
.
put
(
name
,
value
)
;
return
this
;
}

Set a model attribute and override existing attribute.

@param name Attribute's name.
@param value Attribute's value.
@return This view.

Set a model attribute and override existing attribute .


@Nonnull
  public View put(final Map<String, ?> values) {
    values.forEach((k, v) -> model.put(k, v));
    return this;
  }

@ Nonnull public View put ( final Map < String , ? > values ) { values . forEach ( ( k , v ) -> model . put ( k , v ) ) ; return this ; }

Set model attributes and override existing values.

@param values Attribute's value.
@return This view.

Set model attributes and override existing values .


public static ClassLoader classLoader(final ClassLoader parent) throws IOException {
    return classLoader(parent, new File(System.getProperty("user.dir")));
  }

public static ClassLoader classLoader ( final ClassLoader parent ) throws IOException { return classLoader ( parent , new File ( System . getProperty ( "user.dir" ) ) ) ; }

Constructs a new AssetClassLoader that includes the 'public' dir if present in the current working dir

@param parent parent classloader
@return classloader that includes the public dir if present
@throws IOException if an exception occurred

Constructs a new AssetClassLoader that includes the public dir if present in the current working dir


public static ClassLoader classLoader(final ClassLoader parent, File projectDir) throws IOException {
    requireNonNull(parent, "ClassLoader required.");
    File publicDir = new File(projectDir, "public");
    if(publicDir.exists()) {
      return new URLClassLoader(new URL[]{publicDir.toURI().toURL()}, parent);
    }
    return parent;
  }

public
static
ClassLoader
classLoader
(
final
ClassLoader
parent
,
File
projectDir
)
throws
IOException
{
requireNonNull
(
parent
,
"ClassLoader required."
)
;
File
publicDir
=
new
File
(
projectDir
,
"public"
)
;
if
(
publicDir
.
exists
(
)
)
{
return
new
URLClassLoader
(
new
URL
[
]
{
publicDir
.
toURI
(
)
.
toURL
(
)
}
,
parent
)
;
}
return
parent
;
}

Constructs a new AssetClassLoader that includes the 'public' dir if present in the provided working dir

@param parent parent classloader
@param projectDir working dir to use
@return classloader that includes the public dir if present
@throws IOException if an exception occurred

Constructs a new AssetClassLoader that includes the public dir if present in the provided working dir


public RouteMethod attributes(Map<String, Object> attributes) {
    if (attributes != null) {
      if (this.attributes == null) {
        this.attributes = new LinkedHashMap<>();
      }
      this.attributes.putAll(attributes);
    }
    return this;
  }

public RouteMethod attributes ( Map < String , Object > attributes ) { if ( attributes != null ) { if ( this . attributes == null ) { this . attributes = new LinkedHashMap <> ( ) ; } this . attributes . putAll ( attributes ) ; } return this ; }

Set route attributes.

@param attributes Attributes.
@return This method.


public RouteMethod attribute(String name, Object value) {
    if (this.attributes == null) {
      this.attributes = new LinkedHashMap<>();
    }
    this.attributes.put(name, value);
    return this;
  }

public RouteMethod attribute ( String name , Object value ) { if ( this . attributes == null ) { this . attributes = new LinkedHashMap <> ( ) ; } this . attributes . put ( name , value ) ; return this ; }

Set route attribute.

@param name Attribute name.
@param value Attribute value.
@return This method.


public RouteMethod param(String name, Consumer<RouteParameter> customizer) {
    parameters().stream()
        .filter(p -> name.equals(p.name()))
        .findFirst()
        .ifPresent(customizer);
    return this;
  }

public RouteMethod param ( String name , Consumer < RouteParameter > customizer ) { parameters ( ) . stream ( ) . filter ( p -> name . equals ( p . name ( ) ) ) . findFirst ( ) . ifPresent ( customizer ) ; return this ; }

Find a parameter by name and invoke the given callback.

@param name Parameter name.
@param customizer Success callback.
@return This method.

Find a parameter by name and invoke the given callback .


public static Status valueOf(final int statusCode) {
    Integer key = Integer.valueOf(statusCode);
    Status status = statusMap.get(key);
    return status == null? new Status(key, key.toString()) : status;
  }

public static Status valueOf ( final int statusCode ) { Integer key = Integer . valueOf ( statusCode ) ; Status status = statusMap . get ( key ) ; return status == null ? new Status ( key , key . toString ( ) ) : status ; }

Return the enum constant of this type with the specified numeric value.

@param statusCode the numeric value of the enum to be returned
@return the enum constant with the specified numeric value
@throws IllegalArgumentException if this enum has no constant for the specified numeric value

Return the enum constant of this type with the specified numeric value .


public Jdbi3 doWith(Consumer<Jdbi> configurer) {
    return doWith((jdbi, conf) -> configurer.accept(jdbi));
  }

public Jdbi3 doWith ( Consumer < Jdbi > configurer ) { return doWith ( ( jdbi , conf ) -> configurer . accept ( jdbi ) ) ; }

Configurer a jdbi instance.

@param configurer Configurer callback.
@return This module.


@Override
  public RewrittenStatement rewrite(final String sql, final Binding params,
      final StatementContext ctx)
  {
    final ParsedStatement stmt = new ParsedStatement();
    try {
      final String parsedSql = parseString(sql, stmt, params);
      return new MyRewrittenStatement(parsedSql, stmt, ctx);
    } catch (IllegalArgumentException e) {
      throw new UnableToCreateStatementException(
          "Exception parsing for named parameter replacement", e, ctx);
    }

  }

Munge up the SQL as desired. Responsible for figuring out ow to bind any
arguments in to the resultant prepared statement.

@param sql The SQL to rewrite
@param params contains the arguments which have been bound to this statement.
@param ctx The statement context for the statement being executed
@return somethign which can provde the actual SQL to prepare a statement from
and which can bind the correct arguments to that prepared statement

Munge up the SQL as desired . Responsible for figuring out ow to bind any arguments in to the resultant prepared statement .


protected void send(final Request req, final Response rsp, final Asset asset) throws Throwable {
    rsp.send(asset);
  }

protected void send ( final Request req , final Response rsp , final Asset asset ) throws Throwable { rsp . send ( asset ) ; }

Send an asset to the client.

@param req Request.
@param rsp Response.
@param asset Resolve asset.
@throws Exception If send fails.


public Jdbi doWith(Consumer<DBI> configurer) {
    return doWith((dbi, conf) -> configurer.accept(dbi));
  }

public Jdbi doWith ( Consumer < DBI > configurer ) { return doWith ( ( dbi , conf ) -> configurer . accept ( dbi ) ) ; }

Configure DBI instance.

@param configurer Configurer.
@return This module.


public jOOQ doWith(Consumer<Configuration> configurer) {
    return doWith((configuration, conf) -> configurer.accept(configuration));
  }

public jOOQ doWith ( Consumer < Configuration > configurer ) { return doWith ( ( configuration , conf ) -> configurer . accept ( configuration ) ) ; }

Configuration callback.

@param configurer Callback.
@return This module.


public Quartz with(final JobDetail job, final Trigger trigger) {
    requireNonNull(job, "Job is required.");
    requireNonNull(trigger, "Trigger is required.");
    jobMap.put(job, trigger);
    return this;
  }

public
Quartz
with
(
final
JobDetail
job
,
final
Trigger
trigger
)
{
requireNonNull
(
job
,
"Job is required."
)
;
requireNonNull
(
trigger
,
"Trigger is required."
)
;
jobMap
.
put
(
job
,
trigger
)
;
return
this
;
}

Schedule the provided job and trigger.

@param job A job to schedule.
@param trigger A trigger for provided job.
@return This quartz instance.


public Quartz with(final Class<? extends Job> jobClass,
      final BiConsumer<JobBuilder, TriggerBuilder<Trigger>> configurer) {
    requireNonNull(jobClass, "Job class is required.");
    JobBuilder job = JobBuilder.newJob(jobClass)
        .withIdentity(
            JobKey.jobKey(jobClass.getSimpleName(), jobClass.getPackage().getName())
        );
    TriggerBuilder<Trigger> trigger = TriggerBuilder.newTrigger()
        .withIdentity(
            TriggerKey.triggerKey(jobClass.getSimpleName(), jobClass.getPackage().getName())
        );
    configurer.accept(job, trigger);
    return with(job.build(), trigger.build());
  }

public
Quartz
with
(
final
Class
<
extends
Job
>
jobClass
,
final
BiConsumer
<
JobBuilder
,
TriggerBuilder
<
Trigger
>
>
configurer
)
{
requireNonNull
(
jobClass
,
"Job class is required."
)
;
JobBuilder
job
=
JobBuilder
.
newJob
(
jobClass
)
.
withIdentity
(
JobKey
.
jobKey
(
jobClass
.
getSimpleName
(
)
,
jobClass
.
getPackage
(
)
.
getName
(
)
)
)
;
TriggerBuilder
<
Trigger
>
trigger
=
TriggerBuilder
.
newTrigger
(
)
.
withIdentity
(
TriggerKey
.
triggerKey
(
jobClass
.
getSimpleName
(
)
,
jobClass
.
getPackage
(
)
.
getName
(
)
)
)
;
configurer
.
accept
(
job
,
trigger
)
;
return
with
(
job
.
build
(
)
,
trigger
.
build
(
)
)
;
}

Schedule the provided job and trigger. This method will setup a default name and group for
both.

@param jobClass A jobClass to setup and schedule.
@param configurer A callback to setup the job and trigger.
@return This quartz instance.

Schedule the provided job and trigger . This method will setup a default name and group for both .


private void shutdownGracefully(final Iterator<EventExecutorGroup> iterator) {
    if (iterator.hasNext()) {
      EventExecutorGroup group = iterator.next();
      if (!group.isShuttingDown()) {
        group.shutdownGracefully().addListener(future -> {
          if (!future.isSuccess()) {
            log.debug("shutdown of {} resulted in exception", group, future.cause());
          }
          shutdownGracefully(iterator);
        });
      }
    }
  }

private
void
shutdownGracefully
(
final
Iterator
<
EventExecutorGroup
>
iterator
)
{
if
(
iterator
.
hasNext
(
)
)
{
EventExecutorGroup
group
=
iterator
.
next
(
)
;
if
(
!
group
.
isShuttingDown
(
)
)
{
group
.
shutdownGracefully
(
)
.
addListener
(
future
->
{
if
(
!
future
.
isSuccess
(
)
)
{
log
.
debug
(
"shutdown of {} resulted in exception"
,
group
,
future
.
cause
(
)
)
;
}
shutdownGracefully
(
iterator
)
;
}
)
;
}
}
}

Shutdown executor in order.

@param iterator Executors to shutdown.


public Cassandra doWithCluster(final Consumer<Cluster> configurer) {
    requireNonNull(configurer, "Cluster conf callbackrequired.");
    return doWithCluster((cc, c) -> configurer.accept(cc));
  }

public
Cassandra
doWithCluster
(
final
Consumer
<
Cluster
>
configurer
)
{
requireNonNull
(
configurer
,
"Cluster conf callbackrequired."
)
;
return
doWithCluster
(
(
cc
,
c
)
->
configurer
.
accept
(
cc
)
)
;
}

Configure a cluster after creation.

@param configurer Configurer callback.
@return This module.


@Nonnull
  public static Result with(final Status status) {
    requireNonNull(status, "A HTTP status is required.");
    return new Result().status(status);
  }

@
Nonnull
public
static
Result
with
(
final
Status
status
)
{
requireNonNull
(
status
,
"A HTTP status is required."
)
;
return
new
Result
(
)
.
status
(
status
)
;
}

Set the response status.

@param status A status!
@return A new result.


public Jackson module(final Module module) {
    requireNonNull(module, "Jackson Module is required.");
    modules.add(binder -> binder.addBinding().toInstance(module));
    return this;
  }

public
Jackson
module
(
final
Module
module
)
{
requireNonNull
(
module
,
"Jackson Module is required."
)
;
modules
.
add
(
binder
->
binder
.
addBinding
(
)
.
toInstance
(
module
)
)
;
return
this
;
}

Register the provided module.

@param module A module instance.
@return This module.


public Pac4j unauthenticated(Supplier<UserProfile> provider) {
    requireNonNull(provider, "Unauthenticated provider required.");
    return unauthenticated(req -> provider.get());
  }

public
Pac4j
unauthenticated
(
Supplier
<
UserProfile
>
provider
)
{
requireNonNull
(
provider
,
"Unauthenticated provider required."
)
;
return
unauthenticated
(
req
->
provider
.
get
(
)
)
;
}

Set a default action which is execute when no user is logged in.

{@code
{
use(new Pac4j()
.unauthenticated(() -> {
UserProfile anonymous = ...
return anonymous;
})
);

get("/", () -> {
// might or might not be anonymous
UserProfile profile = require(UserProfile.class);
return ...;
}
}
}

The default action throws a 403 error.

@param provider Unauthenticated user provider.
@return This module.

Set a default action which is execute when no user is logged in .


public Pac4j form(String pattern) {
    return clientInternal(pattern, conf -> {
      showDevLogin = true;
      return new FormClient("/login", new SimpleTestUsernamePasswordAuthenticator());
    }, null);
  }

public Pac4j form ( String pattern ) { return clientInternal ( pattern , conf -> { showDevLogin = true ; return new FormClient ( "/login" , new SimpleTestUsernamePasswordAuthenticator ( ) ) ; } , null ) ; }

Add a simple login form. Useful for development and quick startup.

@param pattern Pattern to protect.ver
@return This module.

Add a simple login form . Useful for development and quick startup .


public List<RouteMethod> parse(String application) throws Exception {
    return new BytecodeRouteParser(loader, dir).parse(application).stream()
        .filter(filter)
        .collect(Collectors.toList());
  }

public List < RouteMethod > parse ( String application ) throws Exception { return new BytecodeRouteParser ( loader , dir ) . parse ( application ) . stream ( ) . filter ( filter ) . collect ( Collectors . toList ( ) ) ; }

Parse application bytecode and build route methods from it.

@param application Application to parse.
@return List of route methods.
@throws Exception If something goes wrong.

Parse application bytecode and build route methods from it .


public Scanner scan(final Class<?> type) {
    // standard vs guice annotations
    if (type == Named.class || type == com.google.inject.name.Named.class) {
      serviceTypes.add(Named.class);
      serviceTypes.add(com.google.inject.name.Named.class);
    } else if (type == Singleton.class || type == com.google.inject.Singleton.class) {
      serviceTypes.add(Singleton.class);
      serviceTypes.add(com.google.inject.Singleton.class);
    } else {
      serviceTypes.add(type);
    }
    return this;
  }

public
Scanner
scan
(
final
Class
<
>
type
)
{
// standard vs guice annotations
if
(
type
==
Named
.
class
||
type
==
com
.
google
.
inject
.
name
.
Named
.
class
)
{
serviceTypes
.
add
(
Named
.
class
)
;
serviceTypes
.
add
(
com
.
google
.
inject
.
name
.
Named
.
class
)
;
}
else
if
(
type
==
Singleton
.
class
||
type
==
com
.
google
.
inject
.
Singleton
.
class
)
{
serviceTypes
.
add
(
Singleton
.
class
)
;
serviceTypes
.
add
(
com
.
google
.
inject
.
Singleton
.
class
)
;
}
else
{
serviceTypes
.
add
(
type
)
;
}
return
this
;
}

Add a scan criteria like an annotation, interface or class.

@param type A scan criteria/type.
@return This module.

Add a scan criteria like an annotation interface or class .


public ApiTool swagger(String path, Consumer<Swagger> swagger) {
    return swagger(new Options(path, options), swagger);
  }

public ApiTool swagger ( String path , Consumer < Swagger > swagger ) { return swagger ( new Options ( path , options ) , swagger ) ; }

Mount Swagger at the given path and customize Swagger objects.

@param path Path to mount swagger.
@param swagger Customizer.
@return This tool.

Mount Swagger at the given path and customize Swagger objects .


public ApiTool swagger(Options options, Consumer<Swagger> swagger) {
    this.swaggerOptions = Objects.requireNonNull(options, "Options required.");
    this.swagger = swagger;
    return this;
  }

public
ApiTool
swagger
(
Options
options
,
Consumer
<
Swagger
>
swagger
)
{
this
.
swaggerOptions
=
Objects
.
requireNonNull
(
options
,
"Options required."
)
;
this
.
swagger
=
swagger
;
return
this
;
}

Mount Swagger using the given options.

@param options Swagger options.
@param swagger Customizer.
@return This tool.


public ApiTool raml(String path, Consumer<Raml> raml) {
    return raml(new Options(path, options), raml);
  }

public ApiTool raml ( String path , Consumer < Raml > raml ) { return raml ( new Options ( path , options ) , raml ) ; }

Mount RAML at the given path and customize RAML objects.

@param path Path to mount raml.
@param raml RAML customizer.
@return This tool.

Mount RAML at the given path and customize RAML objects .


public ApiTool raml(Options options, Consumer<Raml> raml) {
    this.ramlOptions = Objects.requireNonNull(options, "Options required.");
    this.raml = raml;
    return this;
  }

public
ApiTool
raml
(
Options
options
,
Consumer
<
Raml
>
raml
)
{
this
.
ramlOptions
=
Objects
.
requireNonNull
(
options
,
"Options required."
)
;
this
.
raml
=
raml
;
return
this
;
}

Mount RAML using the given options.

@param options RAML options.
@param raml RAML customizer.
@return This tool.


public String process(String filename, String source, Config conf) throws Exception {
    return process(filename, source, conf, getClass().getClassLoader());
  }

public String process ( String filename , String source , Config conf ) throws Exception { return process ( filename , source , conf , getClass ( ) . getClassLoader ( ) ) ; }

Method that processes the provided source and returns the processed contents.

@param filename name of the file
@param source   contents of the file
@param conf     application configuration
@return the processed file contents
@throws Exception if any error occurred

Method that processes the provided source and returns the processed contents .


public void receiveResultcteRecepcaoOS(
                    com.fincatto.documentofiscal.cte300.webservices.recepcaoOS.CteRecepcaoOSStub.CteRecepcaoOSResult result
                        ) {
           }

public void receiveResultcteRecepcaoOS ( com . fincatto . documentofiscal . cte300 . webservices . recepcaoOS . CteRecepcaoOSStub . CteRecepcaoOSResult result ) { }

auto generated Axis2 call back method for cteRecepcaoOS method
override this method for handling normal response from cteRecepcaoOS operation


public void receiveResultmdfeRecepcaoLote(
            com.fincatto.documentofiscal.mdfe3.webservices.recepcao.MDFeRecepcaoStub.MdfeRecepcaoLoteResult result
    ) {
    }

public void receiveResultmdfeRecepcaoLote ( com . fincatto . documentofiscal . mdfe3 . webservices . recepcao . MDFeRecepcaoStub . MdfeRecepcaoLoteResult result ) { }

auto generated Axis2 call back method for mdfeRecepcaoLote method
override this method for handling normal response from mdfeRecepcaoLote operation


public void receiveResultcteInutilizacaoCT(
                    com.fincatto.documentofiscal.cte300.webservices.inutilizacao.CteInutilizacaoStub.CteInutilizacaoCTResult result
                        ) {
           }

public void receiveResultcteInutilizacaoCT ( com . fincatto . documentofiscal . cte300 . webservices . inutilizacao . CteInutilizacaoStub . CteInutilizacaoCTResult result ) { }

auto generated Axis2 call back method for cteInutilizacaoCT method
override this method for handling normal response from cteInutilizacaoCT operation


public void receiveResultmdfeRecepcaoEvento(
            com.fincatto.documentofiscal.mdfe3.webservices.recepcaoevento.MDFeRecepcaoEventoStub.MdfeRecepcaoEventoResult result
    ) {
    }

public void receiveResultmdfeRecepcaoEvento ( com . fincatto . documentofiscal . mdfe3 . webservices . recepcaoevento . MDFeRecepcaoEventoStub . MdfeRecepcaoEventoResult result ) { }

auto generated Axis2 call back method for mdfeRecepcaoEvento method
override this method for handling normal response from mdfeRecepcaoEvento operation


public void receiveResultcteConsultaCT(
                    com.fincatto.documentofiscal.cte300.webservices.consulta.CteConsultaStub.CteConsultaCTResult result
                        ) {
           }

public void receiveResultcteConsultaCT ( com . fincatto . documentofiscal . cte300 . webservices . consulta . CteConsultaStub . CteConsultaCTResult result ) { }

auto generated Axis2 call back method for cteConsultaCT method
override this method for handling normal response from cteConsultaCT operation


public void receiveResultmdfeConsNaoEnc(
            com.fincatto.documentofiscal.mdfe3.webservices.consultanaoencerrado.MDFeConsNaoEncStub.MdfeConsNaoEncResult result
    ) {
    }

public void receiveResultmdfeConsNaoEnc ( com . fincatto . documentofiscal . mdfe3 . webservices . consultanaoencerrado . MDFeConsNaoEncStub . MdfeConsNaoEncResult result ) { }

auto generated Axis2 call back method for mdfeConsNaoEnc method
override this method for handling normal response from mdfeConsNaoEnc operation


@SuppressWarnings("unused")
    private org.apache.axiom.soap.SOAPEnvelope toEnvelope(final org.apache.axiom.soap.SOAPFactory factory) {
        return factory.getDefaultEnvelope();
    }

@ SuppressWarnings ( "unused" ) private org . apache . axiom . soap . SOAPEnvelope toEnvelope ( final org . apache . axiom . soap . SOAPFactory factory ) { return factory . getDefaultEnvelope ( ) ; }


private java.util.Map getEnvelopeNamespaces(final org.apache.axiom.soap.SOAPEnvelope env) {
        final java.util.Map returnMap = new java.util.HashMap();
        final java.util.Iterator namespaceIterator = env.getAllDeclaredNamespaces();
        while (namespaceIterator.hasNext()) {
            final org.apache.axiom.om.OMNamespace ns = (org.apache.axiom.om.OMNamespace) namespaceIterator.next();
            returnMap.put(ns.getPrefix(), ns.getNamespaceURI());
        }
        return returnMap;
    }

private java . util . Map getEnvelopeNamespaces ( final org . apache . axiom . soap . SOAPEnvelope env ) { final java . util . Map returnMap = new java . util . HashMap ( ) ; final java . util . Iterator namespaceIterator = env . getAllDeclaredNamespaces ( ) ; while ( namespaceIterator . hasNext ( ) ) { final org . apache . axiom . om . OMNamespace ns = ( org . apache . axiom . om . OMNamespace ) namespaceIterator . next ( ) ; returnMap . put ( ns . getPrefix ( ) , ns . getNamespaceURI ( ) ) ; } return returnMap ; }

A utility method that copies the namepaces from the SOAPEnvelope


public void receiveResultnfeConsultaNF(
    		com.fincatto.documentofiscal.nfe310.webservices.nota.consulta.NfeConsultaStub.NfeConsultaNFResult result) {
    }

public void receiveResultnfeConsultaNF ( com . fincatto . documentofiscal . nfe310 . webservices . nota . consulta . NfeConsultaStub . NfeConsultaNFResult result ) { }

auto generated Axis2 call back method for nfeConsultaNF method
override this method for handling normal response from nfeConsultaNF operation


NFLoteEnvio getLoteAssinado(final NFLoteEnvio lote) throws Exception {
        // adiciona a chave e o dv antes de assinar
        for (final NFNota nota : lote.getNotas()) {
            final NFGeraChave geraChave = new NFGeraChave(nota);
            nota.getInfo().getIdentificacao().setCodigoRandomico(StringUtils.defaultIfBlank(nota.getInfo().getIdentificacao().getCodigoRandomico(), geraChave.geraCodigoRandomico()));
            nota.getInfo().getIdentificacao().setDigitoVerificador(geraChave.getDV());
            nota.getInfo().setIdentificador(geraChave.getChaveAcesso());
        }
        // assina o lote
        final String documentoAssinado = new AssinaturaDigital(this.config).assinarDocumento(lote.toString());
        final NFLoteEnvio loteAssinado = new DFParser().loteParaObjeto(documentoAssinado);

        // verifica se nao tem NFCe junto com NFe no lote e gera qrcode (apos assinar mesmo, eh assim)
        int qtdNF = 0, qtdNFC = 0;
        for (final NFNota nota : loteAssinado.getNotas()) {
            switch (nota.getInfo().getIdentificacao().getModelo()) {
                case NFE:
                    qtdNF++;
                    break;
                case NFCE:
                    final NFGeraQRCode geraQRCode = new NFGeraQRCode(nota, this.config);
                    nota.setInfoSuplementar(new NFNotaInfoSuplementar());
                    nota.getInfoSuplementar().setQrCode(geraQRCode.getQRCode());
                    qtdNFC++;
                    break;
                default:
                    throw new IllegalArgumentException(String.format("Modelo de nota desconhecida: %s", nota.getInfo().getIdentificacao().getModelo()));
            }
        }
        // verifica se todas as notas do lote sao do mesmo modelo
        if ((qtdNF > 0) && (qtdNFC > 0)) {
            throw new IllegalArgumentException("Lote contendo notas de modelos diferentes!");
        }
        return loteAssinado;
    }

Retorna o Lote assinado.
@param lote
@return
@throws Exception


public NFLoteEnvioRetornoDados enviaLote(final NFLoteEnvio lote) throws Exception {
        if (lote.getIndicadorProcessamento().equals(NFLoteIndicadorProcessamento.PROCESSAMENTO_SINCRONO) && lote.getNotas().size() > 1) {
            throw new IllegalArgumentException("Apenas uma nota permitida no modo sincrono!");
        } else if (lote.getNotas().size() == 0) {
            throw new IllegalArgumentException("Nenhuma nota informada no envio do Lote!");
        }
        return this.wsLoteEnvio.enviaLote(lote);
    }

Faz o envio de lote para a Sefaz
@param lote o lote a ser enviado para a Sefaz
@return dados do lote retornado pelo webservice, alem do lote assinado
@throws Exception caso nao consiga gerar o xml ou problema de conexao com o sefaz


public NFStatusServicoConsultaRetorno consultaStatus(final DFUnidadeFederativa uf, final DFModelo modelo) throws Exception {
        return this.wsStatusConsulta.consultaStatus(uf, modelo);
    }

public NFStatusServicoConsultaRetorno consultaStatus ( final DFUnidadeFederativa uf , final DFModelo modelo ) throws Exception { return this . wsStatusConsulta . consultaStatus ( uf , modelo ) ; }

Faz a consulta de status responsavel pela UF
@param uf uf UF que deseja consultar o status do sefaz responsavel
@param modelo modelo da nota (NF-e ou NFC-e)
@return dados da consulta de status retornado pelo webservice
@throws Exception caso nao consiga gerar o xml ou problema de conexao com o sefaz


public NFEnviaEventoRetorno corrigeNota(final String chaveDeAcesso, final String textoCorrecao, final int numeroSequencialEvento) throws Exception {
        return this.wsCartaCorrecao.corrigeNota(chaveDeAcesso, textoCorrecao, numeroSequencialEvento);
    }

public NFEnviaEventoRetorno corrigeNota ( final String chaveDeAcesso , final String textoCorrecao , final int numeroSequencialEvento ) throws Exception { return this . wsCartaCorrecao . corrigeNota ( chaveDeAcesso , textoCorrecao , numeroSequencialEvento ) ; }

Faz a correcao da nota
@param chaveDeAcesso chave de acesso da nota
@param textoCorrecao texto de correcao
@param numeroSequencialEvento numero sequencial de evento, esse numero nao pode ser repetido!
@return dados da correcao da nota retornado pelo webservice
@throws Exception caso nao consiga gerar o xml ou problema de conexao com o sefaz


public NFEnviaEventoRetorno cancelaNota(final String chave, final String numeroProtocolo, final String motivo) throws Exception {
        return this.wsCancelamento.cancelaNota(chave, numeroProtocolo, motivo);
    }

public NFEnviaEventoRetorno cancelaNota ( final String chave , final String numeroProtocolo , final String motivo ) throws Exception { return this . wsCancelamento . cancelaNota ( chave , numeroProtocolo , motivo ) ; }

Faz o cancelamento da nota
@param chave chave de acesso da nota
@param numeroProtocolo numero do protocolo da nota
@param motivo motivo do cancelamento
@return dados do cancelamento da nota retornado pelo webservice
@throws Exception caso nao consiga gerar o xml ou problema de conexao com o sefaz


public NFRetornoEventoInutilizacao inutilizaNota(final int anoInutilizacaoNumeracao, final String cnpjEmitente, final String serie, final String numeroInicial, final String numeroFinal, final String justificativa, final DFModelo modelo) throws Exception {
        return this.wsInutilizacao.inutilizaNota(anoInutilizacaoNumeracao, cnpjEmitente, serie, numeroInicial, numeroFinal, justificativa, modelo);
    }

public NFRetornoEventoInutilizacao inutilizaNota ( final int anoInutilizacaoNumeracao , final String cnpjEmitente , final String serie , final String numeroInicial , final String numeroFinal , final String justificativa , final DFModelo modelo ) throws Exception { return this . wsInutilizacao . inutilizaNota ( anoInutilizacaoNumeracao , cnpjEmitente , serie , numeroInicial , numeroFinal , justificativa , modelo ) ; }

Inutiliza a nota
@param anoInutilizacaoNumeracao ano de inutilizacao
@param cnpjEmitente CNPJ emitente da nota
@param serie serie da nota
@param numeroInicial numero inicial da nota
@param numeroFinal numero final da nota
@param justificativa justificativa da inutilizacao
@param modelo modelo da nota (NF-e ou NFC-e)
@return dados da inutilizacao da nota retornado pelo webservice
@throws Exception caso nao consiga gerar o xml ou problema de conexao com o sefaz


public NFRetornoConsultaCadastro consultaCadastro(final String cnpj, final DFUnidadeFederativa uf) throws Exception {
        return this.wsConsultaCadastro.consultaCadastro(cnpj, uf);
    }

public NFRetornoConsultaCadastro consultaCadastro ( final String cnpj , final DFUnidadeFederativa uf ) throws Exception { return this . wsConsultaCadastro . consultaCadastro ( cnpj , uf ) ; }

Realiza a consulta de cadastro de pessoa juridica com inscricao estadual
@param cnpj CNPJ da pessoa juridica
@param uf UF da pessoa juridica
@return dados da consulta da pessoa juridica retornado pelo webservice
@throws Exception caso nao consiga gerar o xml ou problema de conexao com o sefaz


public void receiveResultcteRecepcaoLote(
                    com.fincatto.documentofiscal.cte300.webservices.recepcao.CteRecepcaoStub.CteRecepcaoLoteResult result
                        ) {
           }

public void receiveResultcteRecepcaoLote ( com . fincatto . documentofiscal . cte300 . webservices . recepcao . CteRecepcaoStub . CteRecepcaoLoteResult result ) { }

auto generated Axis2 call back method for cteRecepcaoLote method
override this method for handling normal response from cteRecepcaoLote operation


public void receiveResultcteRetRecepcao(
                    com.fincatto.documentofiscal.cte300.webservices.retrecepcao.CteRetRecepcaoStub.CteRetRecepcaoResult result
                        ) {
           }

public void receiveResultcteRetRecepcao ( com . fincatto . documentofiscal . cte300 . webservices . retrecepcao . CteRetRecepcaoStub . CteRetRecepcaoResult result ) { }

auto generated Axis2 call back method for cteRetRecepcao method
override this method for handling normal response from cteRetRecepcao operation


public String getXmlAssinado(final String chaveAcesso, final String textoCorrecao, final int numeroSequencialEvento) throws Exception {
        final String cartaCorrecaoXML = this.gerarDadosCartaCorrecao(chaveAcesso, textoCorrecao, numeroSequencialEvento).toString();
        return new AssinaturaDigital(this.config).assinarDocumento(cartaCorrecaoXML);
    }

public String getXmlAssinado ( final String chaveAcesso , final String textoCorrecao , final int numeroSequencialEvento ) throws Exception { final String cartaCorrecaoXML = this . gerarDadosCartaCorrecao ( chaveAcesso , textoCorrecao , numeroSequencialEvento ) . toString ( ) ; return new AssinaturaDigital ( this . config ) . assinarDocumento ( cartaCorrecaoXML ) ; }

Retorna XML assinado para uso externo.
@param chaveAcesso
@param textoCorrecao
@param numeroSequencialEvento
@return
@throws Exception


public void receiveResultcteRecepcaoEvento(
                    com.fincatto.documentofiscal.cte300.webservices.recepcaoevento.RecepcaoEventoStub.CteRecepcaoEventoResult result
                        ) {
           }

public void receiveResultcteRecepcaoEvento ( com . fincatto . documentofiscal . cte300 . webservices . recepcaoevento . RecepcaoEventoStub . CteRecepcaoEventoResult result ) { }

auto generated Axis2 call back method for cteRecepcaoEvento method
override this method for handling normal response from cteRecepcaoEvento operation


public CTeRetornoCancelamento cancelaNota(final String chave, final String numeroProtocolo, final String motivo) throws Exception {
        return this.wsCancelamento.cancelaNota(chave, numeroProtocolo, motivo);
    }

public CTeRetornoCancelamento cancelaNota ( final String chave , final String numeroProtocolo , final String motivo ) throws Exception { return this . wsCancelamento . cancelaNota ( chave , numeroProtocolo , motivo ) ; }

Faz o cancelamento do CTe

@param chave     chave de acesso da nota
@param numeroProtocolo numero do protocolo da nota
@param motivo          motivo do cancelamento
@return dados do cancelamento da nota retornado pelo webservice
@throws Exception caso nao consiga gerar o xml ou problema de conexao com o sefaz


public void receiveResultmdfeConsultaMDF(
            com.fincatto.documentofiscal.mdfe3.webservices.consulta.MDFeConsultaStub.MdfeConsultaMDFResult result
    ) {
    }

public void receiveResultmdfeConsultaMDF ( com . fincatto . documentofiscal . mdfe3 . webservices . consulta . MDFeConsultaStub . MdfeConsultaMDFResult result ) { }

auto generated Axis2 call back method for mdfeConsultaMDF method
override this method for handling normal response from mdfeConsultaMDF operation


public void receiveResultmdfeRetRecepcao(
            com.fincatto.documentofiscal.mdfe3.webservices.retornorecepcao.MDFeRetRecepcaoStub.MdfeRetRecepcaoResult result
    ) {
    }

public void receiveResultmdfeRetRecepcao ( com . fincatto . documentofiscal . mdfe3 . webservices . retornorecepcao . MDFeRetRecepcaoStub . MdfeRetRecepcaoResult result ) { }

auto generated Axis2 call back method for mdfeRetRecepcao method
override this method for handling normal response from mdfeRetRecepcao operation


public MDFeRetorno cancelaMdfe(final String chave, final String numeroProtocolo, final String motivo) throws Exception {
        return this.wsCancelamento.cancelaNota(chave, numeroProtocolo, motivo);
    }

public MDFeRetorno cancelaMdfe ( final String chave , final String numeroProtocolo , final String motivo ) throws Exception { return this . wsCancelamento . cancelaNota ( chave , numeroProtocolo , motivo ) ; }

Faz o cancelamento do MDFe

@param chave chave de acesso da nota
@param numeroProtocolo numero do protocolo da nota
@param motivo motivo do cancelamento
@return dados do cancelamento da nota retornado pelo webservice
@throws Exception caso nao consiga gerar o xml ou problema de conexao com o sefaz