text,length,is_long_context,metric_val,label_metric "[[_auth_spi]] == Authentication SPI {project_name} includes a range of different authentication mechanisms: kerberos, password, otp and others. These mechanisms may not meet all of your requirements and you may want to plug in your own custom ones. {project_name} provides an authentication SPI that you can use to write new plugins. The admin console supports applying, ordering, and configuring these new mechanisms. {project_name} also supports a simple registration form. Different aspects of this form can be enabled and disabled i.e. Recaptcha support can be turned off and on. The same authentication SPI can be used to add another page to the registration flow or reimplement it entirely. There's also an additional fine-grained SPI you can use to add specific validations and user extensions to the built in registration form. A required action in {project_name} is an action that a user has to perform after he authenticates. After the action is performed successfully, the user doesn't have to perform the action again. {project_name} comes with some built in required actions like ""reset password"". This action forces the user to change their password after they have logged in. You can write and plug in your own required actions. WARNING: If your authenticator or required action implementation is using some user attributes as the metadata attributes for linking/establishing the user identity, then please make sure that users are not able to edit the attributes and the corresponding attributes are read-only. See the details in the link:{adminguide_link}#_read_only_user_attributes[Threat model mitigation chapter]. === Terms To first learn about the Authentication SPI, let's go over some of the terms used to describe it. Authentication Flow:: A flow is a container for all authentications that must happen during login or registration. If you go to the admin console authentication page, you can view all the defined flows in the system and what authenticators they are made up of. Flows can contain other flows. You can also bind a new different flow for browser login, direct grant access, and registration. Authenticator:: An authenticator is a pluggable component that hold the logic for performing the authentication or action within a flow. It is usually a singleton. Execution:: An execution is an object that binds the authenticator to the flow and the authenticator to the configuration of the authenticator. Flows contain execution entries. Execution Requirement:: Each execution defines how an authenticator behaves in a flow. The requirement defines whether the authenticator is enabled, disabled, conditional, required, or an alternative. An alternative requirement means that the authenticator is enough to validate the flow it's in, but isn't necessary. For example, in the built-in browser flow, cookie authentication, the Identity Provider Redirector, and the set of all authenticators in the forms subflow are all alternative. As they are executed in a sequential top-to-bottom order, if one of them is successful, the flow is successful, and any following execution in the flow (or sub-flow) is not evaluated. Authenticator Config:: This object defines the configuration for the Authenticator for a specific execution within an authentication flow. Each execution can have a different config. Required Action:: After authentication completes, the user might have one or more one-time actions he must complete before he is allowed to login. The user might be required to set up an OTP token generator or reset an expired password or even accept a Terms and Conditions document. === Algorithm Overview Let's talk about how this all works for browser login. Let's assume the following flows, executions and sub flows. [source] ---- Cookie - ALTERNATIVE Kerberos - ALTERNATIVE Forms subflow - ALTERNATIVE Username/Password Form - REQUIRED Conditional OTP subflow - CONDITIONAL Condition - User Configured - REQUIRED OTP Form - REQUIRED ---- In the top level of the form we have 3 executions of which all are alternatively required. This means that if any of these are successful, then the others do not have to execute. The Username/Password form is not executed if there is an SSO Cookie set or a successful Kerberos login. Let's walk through the steps from when a client first redirects to keycloak to authenticate the user. . The OpenID Connect or SAML protocol provider unpacks relevant data, verifies the client and any signatures. It creates an AuthenticationSessionModel. It looks up what the browser flow should be, then starts executing the flow. . The flow looks at the cookie execution and sees that it is an alternative. It loads the cookie provider. It checks to see if the cookie provider requires that a user already be associated with the authentication session. Cookie provider does not require a user. If it did, the flow would abort and the user would see an error screen. Cookie provider then executes. Its purpose is to see if there is an SSO cookie set. If there is one set, it is validated and the UserSessionModel is verified and associated with the AuthenticationSessionModel. The Cookie provider returns a success() status if the SSO cookie exists and is validated. Since the cookie provider returned success and each execution at this level of the flow is ALTERNATIVE, no other execution is executed and this results in a successful login. If there is no SSO cookie, the cookie provider returns with a status of attempted(). This means there was no error condition, but no success either. The provider tried, but the request just wasn't set up to handle this authenticator. . Next the flow looks at the Kerberos execution. This is also an alternative. The kerberos provider also does not require a user to be already set up and associated with the AuthenticationSessionModel so this provider is executed. Kerberos uses the SPNEGO browser protocol. This requires a series of challenge/responses between the server and client exchanging negotiation headers. The kerberos provider does not see any negotiate header, so it assumes that this is the first interaction between the server and client. It therefore creates an HTTP challenge response to the client and sets a forceChallenge() status. A forceChallenge() means that this HTTP response cannot be ignored by the flow and must be returned to the client. If instead the provider returned a challenge() status, the flow would hold the challenge response until all other alternatives are attempted. So, in this initial phase, the flow would stop and the challenge response would be sent back to the browser. If the browser then responds with a successful negotiate header, the provider associates the user with the AuthenticationSession and the flow ends because the rest of the executions on this level of the flow are all alternatives. Otherwise, again, the kerberos provider sets an attempted() status and the flow continues. . The next execution is a subflow called Forms. The executions for this subflow are loaded and the same processing logic occurs. . The first execution in the Forms subflow is the UsernamePassword provider. This provider also does not require for a user to already be associated with the flow. This provider creates a challenge HTTP response and sets its status to challenge(). This execution is required, so the flow honors this challenge and sends the HTTP response back to the browser. This response is a rendering of the Username/Password HTML page. The user enters in their username and password and clicks submit. This HTTP request is directed to the UsernamePassword provider. If the user entered an invalid username or password, a new challenge response is created and a status of failureChallenge() is set for this execution. A failureChallenge() means that there is a challenge, but that the flow should log this as an error in the error log. This error log can be used to lock accounts or IP Addresses that have had too many login failures. If the username and password is valid, the provider associated the UserModel with the AuthenticationSessionModel and returns a status of success(). . The next execution is a subflow called Conditional OTP. The executions for this subflow are loaded and the same processing logic occurs. Its Requirement is Conditional. This means that the flow will first evaluate all conditional executors that it contains. Conditional executors are authenticators that implement `ConditionalAuthenticator`, and must implement the method `boolean matchCondition(AuthenticationFlowContext context)`. A conditional subflow will call the `matchCondition` method of all conditional executions it contains, and if all of them evaluate to true, it will act as if it was a required subflow. If not, it will act as if it was a disabled subflow. Conditional authenticators are only used for this purpose, and are not used as authenticators. This means that even if the conditional authenticator evaluates to ""true"", then this will not mark a flow or subflow as successful. For example, a flow containing only a Conditional subflow with only a conditional authenticator will never allow a user to log in. . The first execution of the Conditional OTP subflow is the Condition - User Configured. This provider requires that a user has been associated with the flow. This requirement is satisfied because the UsernamePassword provider already associated the user with the flow. This provider's `matchCondition` method will evaluate the `configuredFor` method for all other Authenticators in its current subflow. If the subflow contains executors with their Requirement set to required, then the `matchCondition` method will only evaluate to true if all the required authenticators' `configuredFor` method evaluate to true. Otherwise, the `matchCondition` method will evaluate to true if any alternative authenticator evaluates to true. . The next execution is the OTP Form. This provider also requires that a user has been associated with the flow. This requirement is satisfied because the UsernamePassword provider already associated the user with the flow. Since a user is required for this provider, the provider is also asked if the user is configured to use this provider. If user is not configured, then the flow will then set up a required action that the user must perform after authentication is complete. For OTP, this means the OTP setup page. If the user is configured, he will be asked to enter his otp code. In our scenario, because of the conditional sub-flow, the user will never see the OTP login page, unless the Conditional OTP subflow is set to Required. . After the flow is complete, the authentication processor creates a UserSessionModel and associates it with the AuthenticationSessionModel. It then checks to see if the user is required to complete any required actions before logging in. . First, each required action's evaluateTriggers() method is called. This allows the required action provider to figure out if there is some state that might trigger the action to be fired. For example, if your realm has a password expiration policy, it might be triggered by this method. . Each required action associated with the user that has its requiredActionChallenge() method called. Here the provider sets up an HTTP response which renders the page for the required action. This is done by setting a challenge status. . If the required action is ultimately successful, then the required action is removed from the user's required actions list. . After all required actions have been resolved, the user is finally logged in. [[_auth_spi_walkthrough]] === Authenticator SPI Walk Through In this section, we'll take a look at the Authenticator interface. For this, we are going to implement an authenticator that requires that a user enter in the answer to a secret question like ""What is your mother's maiden name?"". This example is fully implemented and contained in the examples/providers/authenticator directory of the demo distribution of {project_name}. To create an authenticator, you must at minimum implement the org.keycloak.authentication.AuthenticatorFactory and Authenticator interfaces. The Authenticator interface defines the logic. The AuthenticatorFactory is responsible for creating instances of an Authenticator. They both extend a more generic Provider and ProviderFactory set of interfaces that other {project_name} components like User Federation do. Some authenticators, like the CookieAuthenticator don't rely on a Credential that the user has or knows to authenticate the user. However, some authenticators, such as the PasswordForm authenticator or the OTPFormAuthenticator rely on the user inputting some information and verifying that information against some information in the database. For the PasswordForm for example, the authenticator will verify the hash of the password against a hash stored in the database, while the OTPFormAuthenticator will verify the OTP received against the one generated from the shared secret stored in the database. These types of authenticators are called CredentialValidators, and will require you to implement a few more classes: * A class that extends org.keycloak.credential.CredentialModel, and that can generate the correct format of the credential in the database * A class implementing the org.keycloak.credential.CredentialProvider and interface, and a class implementing its CredentialProviderFactory factory interface. The SecretQuestionAuthenticator we'll see in this walk through is a CredentialValidator, so we'll see how to implement all these classes. ==== Packaging Classes and Deployment You will package your classes within a single jar. This jar must contain a file named `org.keycloak.authentication.AuthenticatorFactory` and must be contained in the `META-INF/services/` directory of your jar. This file must list the fully qualified class name of each AuthenticatorFactory implementation you have in the jar. For example: [source,java] ---- org.keycloak.examples.authenticator.SecretQuestionAuthenticatorFactory org.keycloak.examples.authenticator.AnotherProviderFactory ---- This services/ file is used by {project_name} to scan the providers it has to load into the system. To deploy this jar, just copy it to the providers directory. ==== Extending the CredentialModel class In {project_name}, credentials are stored in the database in the Credentials table. It has the following structure: ---- ----------------------------- | ID | ----------------------------- | user_ID | ----------------------------- | credential_type | ----------------------------- | created_date | ----------------------------- | user_label | ----------------------------- | secret_data | ----------------------------- | credential_data | ----------------------------- | priority | ----------------------------- ---- Where: * `ID` is the primary key of the credential. * `user_ID` is the foreign key linking the credential to a user. * `credential_type` is a string set during the creation that must reference an existing credential type. * `created_date` is the creation timestamp (in long format) of the credential. * `user_label` is the editable name of the credential by the user * `secret_data` contains a static json with the information that cannot be transmitted outside of {project_name} * `credential_data` contains a json with the static information of the credential that can be shared in the admin console or via the REST API. * `priority` defines how ""preferred"" a credential is for a user, to determine which credential to present when a user has multiple choices. As the secret_data and credential_data fields are designed to contain json, it is up to you to determine how to structure, read and write into these fields, allowing you a lot of flexibility. For this example, we are going to use a very simple credential data, containing only the question asked to the user: [source] ---- { ""question"":""aQuestion"" } ---- with an equally simple secret data, containing only the secret answer: [source] ---- { ""answer"":""anAnswer"" } ---- Here the answer will be kept in plain text in the database for the sake of simplicity, but it would also be possible to have a salted hash for the answer, as is the case for passwords in {project_name}. In this case, the secret data would also have to contain a field for the salt, and the credential data information about the algorithm such as the type of algorithm used and the number of iterations used. For more details you can consult the implementation of the `org.keycloak.models.credential.PasswordCredentialModel` class. In our case we create the class `SecretQuestionCredentialModel`: [source,java] ---- public class SecretQuestionCredentialModel extends CredentialModel { public static final String TYPE = ""SECRET_QUESTION""; private final SecretQuestionCredentialData credentialData; private final SecretQuestionSecretData secretData; ---- Where `TYPE` is the credential_type we write in the database. For consistency, we make sure that this String is always the one referenced when getting the type for this credential. The classes `SecretQuestionCredentialData` and `SecretQuestionSecretData` are used to marshal and unmarshal the json: [source,java] ---- public class SecretQuestionCredentialData { private final String question; @JsonCreator public SecretQuestionCredentialData(@JsonProperty(""question"") String question) { this.question = question; } public String getQuestion() { return question; } } ---- [source,java] ---- public class SecretQuestionSecretData { private final String answer; @JsonCreator public SecretQuestionSecretData(@JsonProperty(""answer"") String answer) { this.answer = answer; } public String getAnswer() { return answer; } } ---- To be fully usable, the `SecretQuestionCredentialModel` objects must both contain the raw json data from its parent class, and the unmarshalled objects in its own attributes. This leads us to create a method which reads from a simple CredentialModel, such as is created when reading from the database, to make a `SecretQuestionCredentialModel`: [source,java] ---- private SecretQuestionCredentialModel(SecretQuestionCredentialData credentialData, SecretQuestionSecretData secretData) { this.credentialData = credentialData; this.secretData = secretData; } public static SecretQuestionCredentialModel createFromCredentialModel(CredentialModel credentialModel){ try { SecretQuestionCredentialData credentialData = JsonSerialization.readValue(credentialModel.getCredentialData(), SecretQuestionCredentialData.class); SecretQuestionSecretData secretData = JsonSerialization.readValue(credentialModel.getSecretData(), SecretQuestionSecretData.class); SecretQuestionCredentialModel secretQuestionCredentialModel = new SecretQuestionCredentialModel(credentialData, secretData); secretQuestionCredentialModel.setUserLabel(credentialModel.getUserLabel()); secretQuestionCredentialModel.setCreatedDate(credentialModel.getCreatedDate()); secretQuestionCredentialModel.setType(TYPE); secretQuestionCredentialModel.setId(credentialModel.getId()); secretQuestionCredentialModel.setSecretData(credentialModel.getSecretData()); secretQuestionCredentialModel.setCredentialData(credentialModel.getCredentialData()); return secretQuestionCredentialModel; } catch (IOException e){ throw new RuntimeException(e); } } ---- And a method to create a `SecretQuestionCredentialModel` from the question and answer: [source,java] ---- private SecretQuestionCredentialModel(String question, String answer) { credentialData = new SecretQuestionCredentialData(question); secretData = new SecretQuestionSecretData(answer); } public static SecretQuestionCredentialModel createSecretQuestion(String question, String answer) { SecretQuestionCredentialModel credentialModel = new SecretQuestionCredentialModel(question, answer); credentialModel.fillCredentialModelFields(); return credentialModel; } private void fillCredentialModelFields(){ try { setCredentialData(JsonSerialization.writeValueAsString(credentialData)); setSecretData(JsonSerialization.writeValueAsString(secretData)); setType(TYPE); setCreatedDate(Time.currentTimeMillis()); } catch (IOException e) { throw new RuntimeException(e); } } ---- ==== Implementing a CredentialProvider As with all Providers, to allow {project_name} to generate the CredentialProvider, we require a CredentialProviderFactory. For this requirement we create the SecretQuestionCredentialProviderFactory, whose `create` method will be called when a SecretQuestionCredentialProvider is asked for: [source,java] ---- public class SecretQuestionCredentialProviderFactory implements CredentialProviderFactory { public static final String PROVIDER_ID = ""secret-question""; @Override public String getId() { return PROVIDER_ID; } @Override public CredentialProvider create(KeycloakSession session) { return new SecretQuestionCredentialProvider(session); } } ---- The CredentialProvider interface takes a generic parameter that extends a CredentialModel. In our case we to use the SecretQuestionCredentialModel we created: [source,java] ---- public class SecretQuestionCredentialProvider implements CredentialProvider, CredentialInputValidator { private static final Logger logger = Logger.getLogger(SecretQuestionCredentialProvider.class); protected KeycloakSession session; public SecretQuestionCredentialProvider(KeycloakSession session) { this.session = session; } private UserCredentialStore getCredentialStore() { return session.userCredentialManager(); } ---- We also want to implement the CredentialInputValidator interface, as this allows {project_name} to know that this provider can also be used to validate a credential for an Authenticator. For the CredentialProvider interface, the first method that needs to be implemented is the `getType()` method. This will simply return the `SecretQuestionCredentialModel`'s TYPE String: [source,java] ---- @Override public String getType() { return SecretQuestionCredentialModel.TYPE; } ---- The second method is to create a `SecretQuestionCredentialModel` from a `CredentialModel`. For this method we simply call the existing static method from `SecretQuestionCredentialModel`: [source,java] ---- @Override public SecretQuestionCredentialModel getCredentialFromModel(CredentialModel model) { return SecretQuestionCredentialModel.createFromCredentialModel(model); } ---- Finally, we have the methods to create a credential and delete a credential. These methods call the KeycloakSession's `userCredentialManager`, which is responsible for knowing where to read or write the credential, for example local storage or federated storage. [source,java] ---- @Override public CredentialModel createCredential(RealmModel realm, UserModel user, SecretQuestionCredentialModel credentialModel) { if (credentialModel.getCreatedDate() == null) { credentialModel.setCreatedDate(Time.currentTimeMillis()); } return getCredentialStore().createCredential(realm, user, credentialModel); } @Override public boolean deleteCredential(RealmModel realm, UserModel user, String credentialId) { return getCredentialStore().removeStoredCredential(realm, user, credentialId); } ---- For the CredentialInputValidator, the main method to implement is the `isValid`, which tests whether a credential is valid for a given user in a given realm. This is the method that is called by the Authenticator when it seeks to validate the user's input. Here we simply need to check that the input String is the one recorded in the Credential: [source,java] ---- @Override public boolean isValid(RealmModel realm, UserModel user, CredentialInput input) { if (!(input instanceof UserCredentialModel)) { logger.debug(""Expected instance of UserCredentialModel for CredentialInput""); return false; } if (!input.getType().equals(getType())) { return false; } String challengeResponse = input.getChallengeResponse(); if (challengeResponse == null) { return false; } CredentialModel credentialModel = getCredentialStore().getStoredCredentialById(realm, user, input.getCredentialId()); SecretQuestionCredentialModel sqcm = getCredentialFromModel(credentialModel); return sqcm.getSecretQuestionSecretData().getAnswer().equals(challengeResponse); } ---- The other two methods to implement are a test if the CredentialProvider supports the given credential type and a test to check if the credential type is configured for a given user. For our case, the latter test simply means checking if the user has a credential of the SECRET_QUESTION type: [source,java] ---- @Override public boolean supportsCredentialType(String credentialType) { return getType().equals(credentialType); } @Override public boolean isConfiguredFor(RealmModel realm, UserModel user, String credentialType) { if (!supportsCredentialType(credentialType)) return false; return !getCredentialStore().getStoredCredentialsByType(realm, user, credentialType).isEmpty(); } ---- ==== Implementing an Authenticator When implementing an authenticator that uses Credentials to authenticate a user, you should have the authenticator implement the CredentialValidator interface. This interfaces takes a class extending a CredentialProvider as a parameter, and will allow {project_name} to directly call the methods from the CredentialProvider. The only method that needs to be implemented is `getCredentialProvider` method, which in our example allows the SecretQuestionAuthenticator to retrieve the SecretQuestionCredentialProvider: [source,java] ---- public SecretQuestionCredentialProvider getCredentialProvider(KeycloakSession session) { return (SecretQuestionCredentialProvider)session.getProvider(CredentialProvider.class, SecretQuestionCredentialProviderFactory.PROVIDER_ID); } ---- When implementing the Authenticator interface, the first method that needs to be implemented is the requiresUser() method. For our example, this method must return true as we need to validate the secret question associated with the user. A provider like kerberos would return false from this method as it can resolve a user from the negotiate header. This example, however, is validating a specific credential of a specific user. The next method to implement is the configuredFor() method. This method is responsible for determining if the user is configured for this particular authenticator. In our case, we can just call the method implemented in the SecretQuestionCredentialProvider [source,java] ---- @Override public boolean configuredFor(KeycloakSession session, RealmModel realm, UserModel user) { return getCredentialProvider(session).isConfiguredFor(realm, user, getType(session)); } ---- The next method to implement on the Authenticator is setRequiredActions(). If configuredFor() returns false and our example authenticator is required within the flow, this method will be called, but only if the associated AuthenticatorFactory's `isUserSetupAllowed` method returns true. The setRequiredActions() method is responsible for registering any required actions that must be performed by the user. In our example, we need to register a required action that will force the user to set up the answer to the secret question. We will implement this required action provider later in this chapter. Here is the implementation of the setRequiredActions() method. [source,java] ---- @Override public void setRequiredActions(KeycloakSession session, RealmModel realm, UserModel user) { user.addRequiredAction(""SECRET_QUESTION_CONFIG""); } ---- Now we are getting into the meat of the Authenticator implementation. The next method to implement is authenticate(). This is the initial method the flow invokes when the execution is first visited. What we want is that if a user has answered the secret question already on their browser's machine, then the user doesn't have to answer the question again, making that machine ""trusted"". The authenticate() method isn't responsible for processing the secret question form. Its sole purpose is to render the page or to continue the flow. [source,java] ---- @Override public void authenticate(AuthenticationFlowContext context) { if (hasCookie(context)) { context.success(); return; } Response challenge = context.form() .createForm(""secret-question.ftl""); context.challenge(challenge); } protected boolean hasCookie(AuthenticationFlowContext context) { Cookie cookie = context.getHttpRequest().getHttpHeaders().getCookies().get(""SECRET_QUESTION_ANSWERED""); boolean result = cookie != null; if (result) { System.out.println(""Bypassing secret question because cookie is set""); } return result; } ---- The hasCookie() method checks to see if there is already a cookie set on the browser which indicates that the secret question has already been answered. If that returns true, we just mark this execution's status as SUCCESS using the AuthenticationFlowContext.success() method and returning from the authentication() method. If the hasCookie() method returns false, we must return a response that renders the secret question HTML form. AuthenticationFlowContext has a form() method that initializes a Freemarker page builder with appropriate base information needed to build the form. This page builder is called `org.keycloak.login.LoginFormsProvider`. The LoginFormsProvider.createForm() method loads a Freemarker template file from your login theme. Additionally you can call the LoginFormsProvider.setAttribute() method if you want to pass additional information to the Freemarker template. We'll go over this later. Calling LoginFormsProvider.createForm() returns a JAX-RS Response object. We then call AuthenticationFlowContext.challenge() passing in this response. This sets the status of the execution as CHALLENGE and if the execution is Required, this JAX-RS Response object will be sent to the browser. So, the HTML page asking for the answer to a secret question is displayed to the user and the user enters in the answer and clicks submit. The action URL of the HTML form will send an HTTP request to the flow. The flow will end up invoking the action() method of our Authenticator implementation. [source,java] ---- @Override public void action(AuthenticationFlowContext context) { boolean validated = validateAnswer(context); if (!validated) { Response challenge = context.form() .setError(""badSecret"") .createForm(""secret-question.ftl""); context.failureChallenge(AuthenticationFlowError.INVALID_CREDENTIALS, challenge); return; } setCookie(context); context.success(); } ---- If the answer is not valid, we rebuild the HTML Form with an additional error message. We then call AuthenticationFlowContext.failureChallenge() passing in the reason for the value and the JAX-RS response. failureChallenge() works the same as challenge(), but it also records the failure so it can be analyzed by any attack detection service. If validation is successful, then we set a cookie to remember that the secret question has been answered and we call AuthenticationFlowContext.success(). The validation itself gets the data that was received from the form, and calls the isValid method from the SecretQuestionCredentialProvider. You'll notice that there's a section of the code concerning getting the credential Id. This is because if {project_name} is configured to allow multiple types of alternative authenticators, or if the user could record multiple credentials of the SECRET_QUESTION type (for example if we allowed to choose from several questions, and we allowed the user to have answers for more than one of those questions), then {project_name} needs to know which credential is being used to log the user. In case there is more than one credential, {project_name} allows the user to choose during the login which credential is being used, and the information is transmitted by the form to the Authenticator. In case the form doesn't present this information, credential id used is given by the CredentialProvider's `default getDefaultCredential` method, which will return the ""most preferred"" credential of the correct type of the user, [source,java] ---- protected boolean validateAnswer(AuthenticationFlowContext context) { MultivaluedMap formData = context.getHttpRequest().getDecodedFormParameters(); String secret = formData.getFirst(""secret_answer""); String credentialId = formData.getFirst(""credentialId""); if (credentialId == null || credentialId.isEmpty()) { credentialId = getCredentialProvider(context.getSession()) .getDefaultCredential(context.getSession(), context.getRealm(), context.getUser()).getId(); } UserCredentialModel input = new UserCredentialModel(credentialId, getType(context.getSession()), secret); return getCredentialProvider(context.getSession()).isValid(context.getRealm(), context.getUser(), input); } ---- Next method is the setCookie(). This is an example of providing configuration for the Authenticator. In this case we want the max age of the cookie to be configurable. [source,java] ---- protected void setCookie(AuthenticationFlowContext context) { AuthenticatorConfigModel config = context.getAuthenticatorConfig(); int maxCookieAge = 60 * 60 * 24 * 30; // 30 days if (config != null) { maxCookieAge = Integer.valueOf(config.getConfig().get(""cookie.max.age"")); } URI uri = context.getUriInfo().getBaseUriBuilder().path(""realms"").path(context.getRealm().getName()).build(); addCookie(context, ""SECRET_QUESTION_ANSWERED"", ""true"", uri.getRawPath(), null, null, maxCookieAge, false, true); } ---- We obtain an AuthenticatorConfigModel from the AuthenticationFlowContext.getAuthenticatorConfig() method. If configuration exists we pull the max age config out of it. We will see how we can define what should be configured when we talk about the AuthenticatorFactory implementation. The config values can be defined within the admin console if you set up config definitions in your AuthenticatorFactory implementation. [source,java] ---- @Override public CredentialTypeMetadata getCredentialTypeMetadata() { return CredentialTypeMetadata.builder() .type(getType()) .category(CredentialTypeMetadata.Category.TWO_FACTOR) .displayName(SecretQuestionCredentialProviderFactory.PROVIDER_ID) .helpText(""secret-question-text"") .createAction(SecretQuestionAuthenticatorFactory.PROVIDER_ID) .removeable(false) .build(session); } ---- Last method in SecretQuestionCredentialProvider class is getCredentialTypeMetadata(), which is an abstract method of CredentialProvider interface. Each Credential provider has to provide and implement this method. The method returns an instance of CredentialTypeMetadata, which should at least include type and category of authenticator, displayName and removable item. In this example, the builder takes type of authenticator from method getType(), category is Two Factor (the authenticator can be used as second factor of authentication) and removable, which is set up to false (user can't remove some previously registered credentials). Other items of builder are helpText (will be shown to the user on various screens), createAction (the providerID of the required action, which can be used by the user to create new credential) or updateAction (same as createAction, but instead of creating the new credential, it will update the credential). ==== Implementing an AuthenticatorFactory The next step in this process is to implement an AuthenticatorFactory. This factory is responsible for instantiating an Authenticator. It also provides deployment and configuration metadata about the Authenticator. The getId() method is just the unique name of the component. The create() method is called by the runtime to allocate and process the Authenticator. [source,java] ---- public class SecretQuestionAuthenticatorFactory implements AuthenticatorFactory, ConfigurableAuthenticatorFactory { public static final String PROVIDER_ID = ""secret-question-authenticator""; private static final SecretQuestionAuthenticator SINGLETON = new SecretQuestionAuthenticator(); @Override public String getId() { return PROVIDER_ID; } @Override public Authenticator create(KeycloakSession session) { return SINGLETON; } ---- The next thing the factory is responsible for is to specify the allowed requirement switches. While there are four different requirement types: ALTERNATIVE, REQUIRED, CONDITIONAL, DISABLED, AuthenticatorFactory implementations can limit which requirement options are shown in the admin console when defining a flow. CONDITIONAL should only always be used for subflows, and unless there's a good reason for doing otherwise, the requirement on a authenticator should be REQUIRED, ALTERNATIVE and DISABLED: [source,java] ---- private static AuthenticationExecutionModel.Requirement[] REQUIREMENT_CHOICES = { AuthenticationExecutionModel.Requirement.REQUIRED, AuthenticationExecutionModel.Requirement.ALTERNATIVE, AuthenticationExecutionModel.Requirement.DISABLED }; @Override public AuthenticationExecutionModel.Requirement[] getRequirementChoices() { return REQUIREMENT_CHOICES; } ---- The AuthenticatorFactory.isUserSetupAllowed() is a flag that tells the flow manager whether or not Authenticator.setRequiredActions() method will be called. If an Authenticator is not configured for a user, the flow manager checks isUserSetupAllowed(). If it is false, then the flow aborts with an error. If it returns true, then the flow manager will invoke Authenticator.setRequiredActions(). [source,java] ---- @Override public boolean isUserSetupAllowed() { return true; } ---- The next few methods define how the Authenticator can be configured. The isConfigurable() method is a flag which specifies to the admin console on whether the Authenticator can be configured within a flow. The getConfigProperties() method returns a list of ProviderConfigProperty objects. These objects define a specific configuration attribute. [source,java] ---- @Override public List getConfigProperties() { return configProperties; } private static final List configProperties = new ArrayList(); static { ProviderConfigProperty property; property = new ProviderConfigProperty(); property.setName(""cookie.max.age""); property.setLabel(""Cookie Max Age""); property.setType(ProviderConfigProperty.STRING_TYPE); property.setHelpText(""Max age in seconds of the SECRET_QUESTION_COOKIE.""); configProperties.add(property); } ---- Each ProviderConfigProperty defines the name of the config property. This is the key used in the config map stored in AuthenticatorConfigModel. The label defines how the config option will be displayed in the admin console. The type defines if it is a String, Boolean, or other type. The admin console will display different UI inputs depending on the type. The help text is what will be shown in the tooltip for the config attribute in the admin console. Read the javadoc of ProviderConfigProperty for more detail. The rest of the methods are for the admin console. getHelpText() is the tooltip text that will be shown when you are picking the Authenticator you want to bind to an execution. getDisplayType() is the text that will be shown in the admin console when listing the Authenticator. getReferenceCategory() is just a category the Authenticator belongs to. ==== Adding Authenticator Form {project_name} comes with a Freemarker <<_themes,theme and template engine>>. The createForm() method you called within authenticate() of your Authenticator class, builds an HTML page from a file within your login theme: `secret-question.ftl`. This file should be added to the `theme-resources/templates` in your JAR, see <<_theme_resource,Theme Resource Provider>> for more details. Let's take a bigger look at secret-question.ftl Here's a small code snippet: [source,java] ----
---- Any piece of text enclosed in `${}` corresponds to an attribute or template funtion. If you see the form's action, you see it points to `${url.loginAction}`. This value is automatically generated when you invoke the AuthenticationFlowContext.form() method. You can also obtain this value by calling the AuthenticationFlowContext.getActionURL() method in Java code. You'll also see `${properties.someValue}`. These correspond to properties defined in your theme.properties file of our theme. `${msg(""someValue"")}` corresponds to the internationalized message bundles (.properties files) included with the login theme messages/ directory. If you're just using english, you can just add the value of the `loginSecretQuestion`. This should be the question you want to ask the user. When you call AuthenticationFlowContext.form() this gives you a LoginFormsProvider instance. If you called, `LoginFormsProvider.setAttribute(""foo"", ""bar"")`, the value of ""foo"" would be available for reference in your form as `${foo}`. The value of an attribute can be any Java bean as well. If you look at the top of the file, you'll see that we are importing a template: [source,java] ---- <#import ""select.ftl"" as layout> ---- Importing this template, instead of the standard `template.ftl` allows {project_name} to display a dropdown box that allows the user to select a different credential or execution. [[_adding_authenticator]] ==== Adding Authenticator to a Flow Adding an Authenticator to a flow must be done in the admin console. If you go to the Authentication menu item and go to the Flow tab, you will be able to view the currently defined flows. You cannot modify built in flows, so, to add the Authenticator we've created you have to copy an existing flow or create your own. Our hope is that the user interface is sufficiently clear so that you can determine how to create a flow and add the Authenticator. For more details, see the `Authentication Flows` chapter in link:{adminguide_link}[{adminguide_name}] . After you've created your flow, you have to bind it to the login action you want to bind it to. If you go to the Authentication menu and go to the Bindings tab you will see options to bind a flow to the browser, registration, or direct grant flow. === Required Action Walkthrough In this section we will discuss how to define a required action. In the Authenticator section you may have wondered, ""How will we get the user's answer to the secret question entered into the system?"". As we showed in the example, if the answer is not set up, a required action will be triggered. This section discusses how to implement the required action for the Secret Question Authenticator. ==== Packaging Classes and Deployment You will package your classes within a single jar. This jar does not have to be separate from other provider classes but it must contain a file named `org.keycloak.authentication.RequiredActionFactory` and must be contained in the `META-INF/services/` directory of your jar. This file must list the fully qualified classname of each RequiredActionFactory implementation you have in the jar. For example: [source,java] ---- org.keycloak.examples.authenticator.SecretQuestionRequiredActionFactory ---- This services/ file is used by {project_name} to scan the providers it has to load into the system. To deploy this jar, just copy it to the `standalone/deployments` directory. ==== Implement the RequiredActionProvider Required actions must first implement the RequiredActionProvider interface. The RequiredActionProvider.requiredActionChallenge() is the initial call by the flow manager into the required action. This method is responsible for rendering the HTML form that will drive the required action. [source,java] ---- @Override public void requiredActionChallenge(RequiredActionContext context) { Response challenge = context.form().createForm(""secret_question_config.ftl""); context.challenge(challenge); } ---- You see that RequiredActionContext has similar methods to AuthenticationFlowContext. The form() method allows you to render the page from a Freemarker template. The action URL is preset by the call to this form() method. You just need to reference it within your HTML form. I'll show you this later. The challenge() method notifies the flow manager that a required action must be executed. The next method is responsible for processing input from the HTML form of the required action. The action URL of the form will be routed to the RequiredActionProvider.processAction() method [source,java] ---- @Override public void processAction(RequiredActionContext context) { String answer = (context.getHttpRequest().getDecodedFormParameters().getFirst(""answer"")); UserCredentialValueModel model = new UserCredentialValueModel(); model.setValue(answer); model.setType(SecretQuestionAuthenticator.CREDENTIAL_TYPE); context.getUser().updateCredentialDirectly(model); context.success(); } ---- The answer is pulled out of the form post. A UserCredentialValueModel is created and the type and value of the credential are set. Then UserModel.updateCredentialDirectly() is invoked. Finally, RequiredActionContext.success() notifies the container that the required action was successful. ==== Implement the RequiredActionFactory This class is really simple. It is just responsible for creating the required action provider instance. [source,java] ---- public class SecretQuestionRequiredActionFactory implements RequiredActionFactory { private static final SecretQuestionRequiredAction SINGLETON = new SecretQuestionRequiredAction(); @Override public RequiredActionProvider create(KeycloakSession session) { return SINGLETON; } @Override public String getId() { return SecretQuestionRequiredAction.PROVIDER_ID; } @Override public String getDisplayText() { return ""Secret Question""; } ---- The getDisplayText() method is just for the admin console when it wants to display a friendly name for the required action. ==== Enable Required Action The final thing you have to do is go into the admin console. Click on the Authentication left menu. Click on the Required Actions tab. Click on the Register button and choose your new Required Action. Your new required action should now be displayed and enabled in the required actions list. === Modifying/Extending the Registration Form It is entirely possible for you to implement your own flow with a set of Authenticators to totally change how registration is done in {project_name}. But what you'll usually want to do is just add a little bit of validation to the out of the box registration page. An additional SPI was created to be able to do this. It basically allows you to add validation of form elements on the page as well as to initialize UserModel attributes and data after the user has been registered. We'll look at both the implementation of the user profile registration processing as well as the registration Google Recaptcha plugin. ==== Implementation FormAction Interface The core interface you have to implement is the FormAction interface. A FormAction is responsible for rendering and processing a portion of the page. Rendering is done in the buildPage() method, validation is done in the validate() method, post validation operations are done in success(). Let's first take a look at buildPage() method of the Recaptcha plugin. [source,java] ---- @Override public void buildPage(FormContext context, LoginFormsProvider form) { AuthenticatorConfigModel captchaConfig = context.getAuthenticatorConfig(); if (captchaConfig == null || captchaConfig.getConfig() == null || captchaConfig.getConfig().get(SITE_KEY) == null || captchaConfig.getConfig().get(SITE_SECRET) == null ) { form.addError(new FormMessage(null, Messages.RECAPTCHA_NOT_CONFIGURED)); return; } String siteKey = captchaConfig.getConfig().get(SITE_KEY); form.setAttribute(""recaptchaRequired"", true); form.setAttribute(""recaptchaSiteKey"", siteKey); form.addScript(""https://www.google.com/recaptcha/api.js""); } ---- The Recaptcha buildPage() method is a callback by the form flow to help render the page. It receives a form parameter which is a LoginFormsProvider. You can add additional attributes to the form provider so that they can be displayed in the HTML page generated by the registration Freemarker template. The code above is from the registration recaptcha plugin. Recaptcha requires some specific settings that must be obtained from configuration. FormActions are configured in the exact same as Authenticators are. In this example, we pull the Google Recaptcha site key from configuration and add it as an attribute to the form provider. Our registration template file can read this attribute now. Recaptcha also has the requirement of loading a JavaScript script. You can do this by calling LoginFormsProvider.addScript() passing in the URL. For user profile processing, there is no additional information that it needs to add to the form, so its buildPage() method is empty. The next meaty part of this interface is the validate() method. This is called immediately upon receiving a form post. Let's look at the Recaptcha's plugin first. [source,java] ---- @Override public void validate(ValidationContext context) { MultivaluedMap formData = context.getHttpRequest().getDecodedFormParameters(); List errors = new ArrayList<>(); boolean success = false; String captcha = formData.getFirst(G_RECAPTCHA_RESPONSE); if (!Validation.isBlank(captcha)) { AuthenticatorConfigModel captchaConfig = context.getAuthenticatorConfig(); String secret = captchaConfig.getConfig().get(SITE_SECRET); success = validateRecaptcha(context, success, captcha, secret); } if (success) { context.success(); } else { errors.add(new FormMessage(null, Messages.RECAPTCHA_FAILED)); formData.remove(G_RECAPTCHA_RESPONSE); context.validationError(formData, errors); return; } } ---- Here we obtain the form data that the Recaptcha widget adds to the form. We obtain the Recaptcha secret key from configuration. We then validate the recaptcha. If successful, ValidationContext.success() is called. If not, we invoke ValidationContext.validationError() passing in the formData (so the user doesn't have to re-enter data), we also specify an error message we want displayed. The error message must point to a message bundle property in the internationalized message bundles. For other registration extensions validate() might be validating the format of a form element, i.e. an alternative email attribute. Let's also look at the user profile plugin that is used to validate email address and other user information when registering. [source,java] ---- @Override public void validate(ValidationContext context) { MultivaluedMap formData = context.getHttpRequest().getDecodedFormParameters(); List errors = new ArrayList<>(); String eventError = Errors.INVALID_REGISTRATION; if (Validation.isBlank(formData.getFirst((RegistrationPage.FIELD_FIRST_NAME)))) { errors.add(new FormMessage(RegistrationPage.FIELD_FIRST_NAME, Messages.MISSING_FIRST_NAME)); } if (Validation.isBlank(formData.getFirst((RegistrationPage.FIELD_LAST_NAME)))) { errors.add(new FormMessage(RegistrationPage.FIELD_LAST_NAME, Messages.MISSING_LAST_NAME)); } String email = formData.getFirst(Validation.FIELD_EMAIL); if (Validation.isBlank(email)) { errors.add(new FormMessage(RegistrationPage.FIELD_EMAIL, Messages.MISSING_EMAIL)); } else if (!Validation.isEmailValid(email)) { formData.remove(Validation.FIELD_EMAIL); errors.add(new FormMessage(RegistrationPage.FIELD_EMAIL, Messages.INVALID_EMAIL)); } if (context.getSession().users().getUserByEmail(email, context.getRealm()) != null) { formData.remove(Validation.FIELD_EMAIL); errors.add(new FormMessage(RegistrationPage.FIELD_EMAIL, Messages.EMAIL_EXISTS)); } if (errors.size() > 0) { context.validationError(formData, errors); return; } else { context.success(); } } ---- As you can see, this validate() method of user profile processing makes sure that the email, first, and last name are filled in the form. It also makes sure that email is in the right format. If any of these validations fail, an error message is queued up for rendering. Any fields in error are removed from the form data. Error messages are represented by the FormMessage class. The first parameter of the constructor of this class takes the HTML element id. The input in error will be highlighted when the form is re-rendered. The second parameter is a message reference id. This id must correspond to a property in one of the localized message bundle files. in the theme. After all validations have been processed then, the form flow then invokes the FormAction.success() method. For recaptcha this is a no-op, so we won't go over it. For user profile processing, this method fills in values in the registered user. [source,java] ---- @Override public void success(FormContext context) { UserModel user = context.getUser(); MultivaluedMap formData = context.getHttpRequest().getDecodedFormParameters(); user.setFirstName(formData.getFirst(RegistrationPage.FIELD_FIRST_NAME)); user.setLastName(formData.getFirst(RegistrationPage.FIELD_LAST_NAME)); user.setEmail(formData.getFirst(RegistrationPage.FIELD_EMAIL)); } ---- Pretty simple implementation. The UserModel of the newly registered user is obtained from the FormContext. The appropriate methods are called to initialize UserModel data. Finally, you are also required to define a FormActionFactory class. This class is implemented similarly to AuthenticatorFactory, so we won't go over it. ==== Packaging the Action You will package your classes within a single jar. This jar must contain a file named `org.keycloak.authentication.FormActionFactory` and must be contained in the `META-INF/services/` directory of your jar. This file must list the fully qualified class name of each FormActionFactory implementation you have in the jar. For example: [source] ---- org.keycloak.authentication.forms.RegistrationProfile org.keycloak.authentication.forms.RegistrationRecaptcha ---- This services/ file is used by {project_name} to scan the providers it has to load into the system. To deploy this jar, just copy it to the `standalone/deployments` directory. ==== Adding FormAction to the Registration Flow Adding a FormAction to a registration page flow must be done in the admin console. If you go to the Authentication menu item and go to the Flow tab, you will be able to view the currently defined flows. You cannot modify built in flows, so, to add the Authenticator we've created you have to copy an existing flow or create your own. I'm hoping the UI is intuitive enough so that you can figure out for yourself how to create a flow and add the FormAction. Basically you'll have to copy the registration flow. Then click Actions menu to the right of the Registration Form, and pick ""Add execution"" to add a new execution. You'll pick the FormAction from the selection list. Make sure your FormAction comes after ""Registration User Creation"" by using the down buttons to move it if your FormAction isn't already listed after ""Registration User Creation"". You want your FormAction to come after user creation because the success() method of Registration User Creation is responsible for creating the new UserModel. After you've created your flow, you have to bind it to registration. If you go to the Authentication menu and go to the Bindings tab you will see options to bind a flow to the browser, registration, or direct grant flow. === Modifying Forgot Password/Credential Flow {project_name} also has a specific authentication flow for forgot password, or rather credential reset initiated by a user. If you go to the admin console flows page, there is a ""reset credentials"" flow. By default, {project_name} asks for the email or username of the user and sends an email to them. If the user clicks on the link, then they are able to reset both their password and OTP (if an OTP has been set up). You can disable automatic OTP reset by disabling the ""Reset OTP"" authenticator in the flow. You can add additional functionality to this flow as well. For example, many deployments would like for the user to answer one or more secret questions in additional to sending an email with a link. You could expand on the secret question example that comes with the distro and incorporate it into the reset credential flow. One thing to note if you are extending the reset credentials flow. The first ""authenticator"" is just a page to obtain the username or email. If the username or email exists, then the AuthenticationFlowContext.getUser() will return the located user. Otherwise this will be null. This form *WILL NOT* re-ask the user to enter in an email or username if the previous email or username did not exist. You need to prevent attackers from being able to guess valid users. So, if AuthenticationFlowContext.getUser() returns null, you should proceed with the flow to make it look like a valid user was selected. I suggest that if you want to add secret questions to this flow, you should ask these questions after the email is sent. In other words, add your custom authenticator after the ""Send Reset Email"" authenticator. === Modifying First Broker Login Flow First Broker Login flow is used during first login with some identity provider. Term `First Login` means that there is not yet existing {project_name} account linked with the particular authenticated identity provider account. For more details about this flow see the `Identity Brokering` chapter in link:{adminguide_link}[{adminguide_name}] . [[_client_authentication]] === Authentication of clients {project_name} actually supports pluggable authentication for https://openid.net/specs/openid-connect-core-1_0.html[OpenID Connect] client applications. Authentication of client (application) is used under the hood by the {project_name} adapter during sending any backchannel requests to the {project_name} server (like the request for exchange code to access token after successful authentication or request to refresh token). But the client authentication can be also used directly by you during `Direct Access grants` (represented by OAuth2 `Resource Owner Password Credentials Flow`) or during `Service account` authentication (represented by OAuth2 `Client Credentials Flow`). For more details about {project_name} adapter and OAuth2 flows see link:{adapterguide_link}[{adapterguide_name}]. ==== Default implementations Actually {project_name} has 2 default implementations of client authentication: Traditional authentication with client_id and client_secret:: This is default mechanism mentioned in the https://openid.net/specs/openid-connect-core-1_0.html[OpenID Connect] or https://tools.ietf.org/html/rfc6749[OAuth2] specification and {project_name} supports it since it's early days. The public client needs to include `client_id` parameter with its ID in the POST request (so it's defacto not authenticated) and the confidential client needs to include `Authorization: Basic` header with the clientId and clientSecret used as username and password. Authentication with signed JWT:: This is based on the https://tools.ietf.org/html/rfc7523[JWT Bearer Token Profiles for OAuth 2.0] specification. The client/adapter generates the https://tools.ietf.org/html/rfc7519[JWT] and signs it with his private key. The {project_name} then verifies the signed JWT with the client's public key and authenticates client based on it. See the demo example and especially the `examples/preconfigured-demo/product-app` for the example application showing the application using client authentication with signed JWT. ==== Implement your own client authenticator For plug your own client authenticator, you need to implement few interfaces on both client (adapter) and server side. Client side:: Here you need to implement `org.keycloak.adapters.authentication.ClientCredentialsProvider` and put the implementation either to: * your WAR file into WEB-INF/classes . But in this case, the implementation can be used just for this single WAR application * Some JAR file, which will be added into WEB-INF/lib of your WAR * Some JAR file, which will be used as jboss module and configured in jboss-deployment-structure.xml of your WAR. In all cases, you also need to create the file `META-INF/services/org.keycloak.adapters.authentication.ClientCredentialsProvider` either in the WAR or in your JAR. Server side:: Here you need to implement `org.keycloak.authentication.ClientAuthenticatorFactory` and `org.keycloak.authentication.ClientAuthenticator` . You also need to add the file `META-INF/services/org.keycloak.authentication.ClientAuthenticatorFactory` with the name of the implementation classes. See <<_auth_spi_walkthrough,authenticators>> for more details. ",12478,False,2011.9844242298636,median "#include ""LLVMWrapper.h"" #include ""llvm/IR/DebugInfoMetadata.h"" #include ""llvm/IR/DiagnosticInfo.h"" #include ""llvm/IR/DiagnosticPrinter.h"" #include ""llvm/IR/GlobalVariable.h"" #include ""llvm/IR/Instructions.h"" #include ""llvm/IR/Intrinsics.h"" #include ""llvm/Object/Archive.h"" #include ""llvm/Object/ObjectFile.h"" #include ""llvm/Bitcode/BitcodeWriterPass.h"" #include ""llvm/Support/Signals.h"" #include ""llvm/ADT/Optional.h"" #include //===----------------------------------------------------------------------=== // // This file defines alternate interfaces to core functions that are more // readily callable by Rust's FFI. // //===----------------------------------------------------------------------=== using namespace llvm; using namespace llvm::sys; using namespace llvm::object; // LLVMAtomicOrdering is already an enum - don't create another // one. static AtomicOrdering fromRust(LLVMAtomicOrdering Ordering) { switch (Ordering) { case LLVMAtomicOrderingNotAtomic: return AtomicOrdering::NotAtomic; case LLVMAtomicOrderingUnordered: return AtomicOrdering::Unordered; case LLVMAtomicOrderingMonotonic: return AtomicOrdering::Monotonic; case LLVMAtomicOrderingAcquire: return AtomicOrdering::Acquire; case LLVMAtomicOrderingRelease: return AtomicOrdering::Release; case LLVMAtomicOrderingAcquireRelease: return AtomicOrdering::AcquireRelease; case LLVMAtomicOrderingSequentiallyConsistent: return AtomicOrdering::SequentiallyConsistent; } report_fatal_error(""Invalid LLVMAtomicOrdering value!""); } static LLVM_THREAD_LOCAL char *LastError; // Custom error handler for fatal LLVM errors. // // Notably it exits the process with code 101, unlike LLVM's default of 1. static void FatalErrorHandler(void *UserData, const std::string& Reason, bool GenCrashDiag) { // Do the same thing that the default error handler does. std::cerr << ""LLVM ERROR: "" << Reason << std::endl; // Since this error handler exits the process, we have to run any cleanup that // LLVM would run after handling the error. This might change with an LLVM // upgrade. sys::RunInterruptHandlers(); exit(101); } extern ""C"" void LLVMRustInstallFatalErrorHandler() { install_fatal_error_handler(FatalErrorHandler); } extern ""C"" LLVMMemoryBufferRef LLVMRustCreateMemoryBufferWithContentsOfFile(const char *Path) { ErrorOr> BufOr = MemoryBuffer::getFile(Path, -1, false); if (!BufOr) { LLVMRustSetLastError(BufOr.getError().message().c_str()); return nullptr; } return wrap(BufOr.get().release()); } extern ""C"" char *LLVMRustGetLastError(void) { char *Ret = LastError; LastError = nullptr; return Ret; } extern ""C"" unsigned int LLVMRustGetInstructionCount(LLVMModuleRef M) { return unwrap(M)->getInstructionCount(); } extern ""C"" void LLVMRustSetLastError(const char *Err) { free((void *)LastError); LastError = strdup(Err); } extern ""C"" LLVMContextRef LLVMRustContextCreate(bool shouldDiscardNames) { auto ctx = new LLVMContext(); ctx->setDiscardValueNames(shouldDiscardNames); return wrap(ctx); } extern ""C"" void LLVMRustSetNormalizedTarget(LLVMModuleRef M, const char *Triple) { unwrap(M)->setTargetTriple(Triple::normalize(Triple)); } extern ""C"" void LLVMRustPrintPassTimings() { raw_fd_ostream OS(2, false); // stderr. TimerGroup::printAll(OS); } extern ""C"" LLVMValueRef LLVMRustGetNamedValue(LLVMModuleRef M, const char *Name, size_t NameLen) { return wrap(unwrap(M)->getNamedValue(StringRef(Name, NameLen))); } extern ""C"" LLVMValueRef LLVMRustGetOrInsertFunction(LLVMModuleRef M, const char *Name, size_t NameLen, LLVMTypeRef FunctionTy) { return wrap(unwrap(M) ->getOrInsertFunction(StringRef(Name, NameLen), unwrap(FunctionTy)) #if LLVM_VERSION_GE(9, 0) .getCallee() #endif ); } extern ""C"" LLVMValueRef LLVMRustGetOrInsertGlobal(LLVMModuleRef M, const char *Name, size_t NameLen, LLVMTypeRef Ty) { StringRef NameRef(Name, NameLen); return wrap(unwrap(M)->getOrInsertGlobal(NameRef, unwrap(Ty))); } extern ""C"" LLVMValueRef LLVMRustInsertPrivateGlobal(LLVMModuleRef M, LLVMTypeRef Ty) { return wrap(new GlobalVariable(*unwrap(M), unwrap(Ty), false, GlobalValue::PrivateLinkage, nullptr)); } extern ""C"" LLVMTypeRef LLVMRustMetadataTypeInContext(LLVMContextRef C) { return wrap(Type::getMetadataTy(*unwrap(C))); } static Attribute::AttrKind fromRust(LLVMRustAttribute Kind) { switch (Kind) { case AlwaysInline: return Attribute::AlwaysInline; case ByVal: return Attribute::ByVal; case Cold: return Attribute::Cold; case InlineHint: return Attribute::InlineHint; case MinSize: return Attribute::MinSize; case Naked: return Attribute::Naked; case NoAlias: return Attribute::NoAlias; case NoCapture: return Attribute::NoCapture; case NoInline: return Attribute::NoInline; case NonNull: return Attribute::NonNull; case NoRedZone: return Attribute::NoRedZone; case NoReturn: return Attribute::NoReturn; case NoUnwind: return Attribute::NoUnwind; case OptimizeForSize: return Attribute::OptimizeForSize; case ReadOnly: return Attribute::ReadOnly; case SExt: return Attribute::SExt; case StructRet: return Attribute::StructRet; case UWTable: return Attribute::UWTable; case ZExt: return Attribute::ZExt; case InReg: return Attribute::InReg; case SanitizeThread: return Attribute::SanitizeThread; case SanitizeAddress: return Attribute::SanitizeAddress; case SanitizeMemory: return Attribute::SanitizeMemory; case NonLazyBind: return Attribute::NonLazyBind; case OptimizeNone: return Attribute::OptimizeNone; case ReturnsTwice: return Attribute::ReturnsTwice; case ReadNone: return Attribute::ReadNone; case InaccessibleMemOnly: return Attribute::InaccessibleMemOnly; } report_fatal_error(""bad AttributeKind""); } extern ""C"" void LLVMRustAddCallSiteAttribute(LLVMValueRef Instr, unsigned Index, LLVMRustAttribute RustAttr) { CallBase *Call = unwrap(Instr); Attribute Attr = Attribute::get(Call->getContext(), fromRust(RustAttr)); Call->addAttribute(Index, Attr); } extern ""C"" void LLVMRustAddAlignmentCallSiteAttr(LLVMValueRef Instr, unsigned Index, uint32_t Bytes) { CallBase *Call = unwrap(Instr); AttrBuilder B; B.addAlignmentAttr(Bytes); Call->setAttributes(Call->getAttributes().addAttributes( Call->getContext(), Index, B)); } extern ""C"" void LLVMRustAddDereferenceableCallSiteAttr(LLVMValueRef Instr, unsigned Index, uint64_t Bytes) { CallBase *Call = unwrap(Instr); AttrBuilder B; B.addDereferenceableAttr(Bytes); Call->setAttributes(Call->getAttributes().addAttributes( Call->getContext(), Index, B)); } extern ""C"" void LLVMRustAddDereferenceableOrNullCallSiteAttr(LLVMValueRef Instr, unsigned Index, uint64_t Bytes) { CallBase *Call = unwrap(Instr); AttrBuilder B; B.addDereferenceableOrNullAttr(Bytes); Call->setAttributes(Call->getAttributes().addAttributes( Call->getContext(), Index, B)); } extern ""C"" void LLVMRustAddByValCallSiteAttr(LLVMValueRef Instr, unsigned Index, LLVMTypeRef Ty) { CallBase *Call = unwrap(Instr); #if LLVM_VERSION_GE(9, 0) Attribute Attr = Attribute::getWithByValType(Call->getContext(), unwrap(Ty)); #else Attribute Attr = Attribute::get(Call->getContext(), Attribute::ByVal); #endif Call->addAttribute(Index, Attr); } extern ""C"" void LLVMRustAddFunctionAttribute(LLVMValueRef Fn, unsigned Index, LLVMRustAttribute RustAttr) { Function *A = unwrap(Fn); Attribute Attr = Attribute::get(A->getContext(), fromRust(RustAttr)); AttrBuilder B(Attr); A->addAttributes(Index, B); } extern ""C"" void LLVMRustAddAlignmentAttr(LLVMValueRef Fn, unsigned Index, uint32_t Bytes) { Function *A = unwrap(Fn); AttrBuilder B; B.addAlignmentAttr(Bytes); A->addAttributes(Index, B); } extern ""C"" void LLVMRustAddDereferenceableAttr(LLVMValueRef Fn, unsigned Index, uint64_t Bytes) { Function *A = unwrap(Fn); AttrBuilder B; B.addDereferenceableAttr(Bytes); A->addAttributes(Index, B); } extern ""C"" void LLVMRustAddDereferenceableOrNullAttr(LLVMValueRef Fn, unsigned Index, uint64_t Bytes) { Function *A = unwrap(Fn); AttrBuilder B; B.addDereferenceableOrNullAttr(Bytes); A->addAttributes(Index, B); } extern ""C"" void LLVMRustAddByValAttr(LLVMValueRef Fn, unsigned Index, LLVMTypeRef Ty) { Function *F = unwrap(Fn); #if LLVM_VERSION_GE(9, 0) Attribute Attr = Attribute::getWithByValType(F->getContext(), unwrap(Ty)); #else Attribute Attr = Attribute::get(F->getContext(), Attribute::ByVal); #endif F->addAttribute(Index, Attr); } extern ""C"" void LLVMRustAddFunctionAttrStringValue(LLVMValueRef Fn, unsigned Index, const char *Name, const char *Value) { Function *F = unwrap(Fn); AttrBuilder B; B.addAttribute(Name, Value); F->addAttributes(Index, B); } extern ""C"" void LLVMRustRemoveFunctionAttributes(LLVMValueRef Fn, unsigned Index, LLVMRustAttribute RustAttr) { Function *F = unwrap(Fn); Attribute Attr = Attribute::get(F->getContext(), fromRust(RustAttr)); AttrBuilder B(Attr); auto PAL = F->getAttributes(); auto PALNew = PAL.removeAttributes(F->getContext(), Index, B); F->setAttributes(PALNew); } // enable fpmath flag UnsafeAlgebra extern ""C"" void LLVMRustSetHasUnsafeAlgebra(LLVMValueRef V) { if (auto I = dyn_cast(unwrap(V))) { I->setFast(true); } } extern ""C"" LLVMValueRef LLVMRustBuildAtomicLoad(LLVMBuilderRef B, LLVMValueRef Source, const char *Name, LLVMAtomicOrdering Order) { Value *Ptr = unwrap(Source); Type *Ty = Ptr->getType()->getPointerElementType(); LoadInst *LI = unwrap(B)->CreateLoad(Ty, Ptr, Name); LI->setAtomic(fromRust(Order)); return wrap(LI); } extern ""C"" LLVMValueRef LLVMRustBuildAtomicStore(LLVMBuilderRef B, LLVMValueRef V, LLVMValueRef Target, LLVMAtomicOrdering Order) { StoreInst *SI = unwrap(B)->CreateStore(unwrap(V), unwrap(Target)); SI->setAtomic(fromRust(Order)); return wrap(SI); } // FIXME: Use the C-API LLVMBuildAtomicCmpXchg and LLVMSetWeak // once we raise our minimum support to LLVM 10. extern ""C"" LLVMValueRef LLVMRustBuildAtomicCmpXchg(LLVMBuilderRef B, LLVMValueRef Target, LLVMValueRef Old, LLVMValueRef Source, LLVMAtomicOrdering Order, LLVMAtomicOrdering FailureOrder, LLVMBool Weak) { AtomicCmpXchgInst *ACXI = unwrap(B)->CreateAtomicCmpXchg( unwrap(Target), unwrap(Old), unwrap(Source), fromRust(Order), fromRust(FailureOrder)); ACXI->setWeak(Weak); return wrap(ACXI); } enum class LLVMRustSynchronizationScope { SingleThread, CrossThread, }; static SyncScope::ID fromRust(LLVMRustSynchronizationScope Scope) { switch (Scope) { case LLVMRustSynchronizationScope::SingleThread: return SyncScope::SingleThread; case LLVMRustSynchronizationScope::CrossThread: return SyncScope::System; default: report_fatal_error(""bad SynchronizationScope.""); } } extern ""C"" LLVMValueRef LLVMRustBuildAtomicFence(LLVMBuilderRef B, LLVMAtomicOrdering Order, LLVMRustSynchronizationScope Scope) { return wrap(unwrap(B)->CreateFence(fromRust(Order), fromRust(Scope))); } enum class LLVMRustAsmDialect { Att, Intel, }; static InlineAsm::AsmDialect fromRust(LLVMRustAsmDialect Dialect) { switch (Dialect) { case LLVMRustAsmDialect::Att: return InlineAsm::AD_ATT; case LLVMRustAsmDialect::Intel: return InlineAsm::AD_Intel; default: report_fatal_error(""bad AsmDialect.""); } } extern ""C"" LLVMValueRef LLVMRustInlineAsm(LLVMTypeRef Ty, char *AsmString, size_t AsmStringLen, char *Constraints, size_t ConstraintsLen, LLVMBool HasSideEffects, LLVMBool IsAlignStack, LLVMRustAsmDialect Dialect) { return wrap(InlineAsm::get(unwrap(Ty), StringRef(AsmString, AsmStringLen), StringRef(Constraints, ConstraintsLen), HasSideEffects, IsAlignStack, fromRust(Dialect))); } extern ""C"" bool LLVMRustInlineAsmVerify(LLVMTypeRef Ty, char *Constraints, size_t ConstraintsLen) { return InlineAsm::Verify(unwrap(Ty), StringRef(Constraints, ConstraintsLen)); } extern ""C"" void LLVMRustAppendModuleInlineAsm(LLVMModuleRef M, const char *Asm, size_t AsmLen) { unwrap(M)->appendModuleInlineAsm(StringRef(Asm, AsmLen)); } typedef DIBuilder *LLVMRustDIBuilderRef; template DIT *unwrapDIPtr(LLVMMetadataRef Ref) { return (DIT *)(Ref ? unwrap(Ref) : nullptr); } #define DIDescriptor DIScope #define DIArray DINodeArray #define unwrapDI unwrapDIPtr // These values **must** match debuginfo::DIFlags! They also *happen* // to match LLVM, but that isn't required as we do giant sets of // matching below. The value shouldn't be directly passed to LLVM. enum class LLVMRustDIFlags : uint32_t { FlagZero = 0, FlagPrivate = 1, FlagProtected = 2, FlagPublic = 3, FlagFwdDecl = (1 << 2), FlagAppleBlock = (1 << 3), FlagBlockByrefStruct = (1 << 4), FlagVirtual = (1 << 5), FlagArtificial = (1 << 6), FlagExplicit = (1 << 7), FlagPrototyped = (1 << 8), FlagObjcClassComplete = (1 << 9), FlagObjectPointer = (1 << 10), FlagVector = (1 << 11), FlagStaticMember = (1 << 12), FlagLValueReference = (1 << 13), FlagRValueReference = (1 << 14), FlagExternalTypeRef = (1 << 15), FlagIntroducedVirtual = (1 << 18), FlagBitField = (1 << 19), FlagNoReturn = (1 << 20), // Do not add values that are not supported by the minimum LLVM // version we support! see llvm/include/llvm/IR/DebugInfoFlags.def }; inline LLVMRustDIFlags operator&(LLVMRustDIFlags A, LLVMRustDIFlags B) { return static_cast(static_cast(A) & static_cast(B)); } inline LLVMRustDIFlags operator|(LLVMRustDIFlags A, LLVMRustDIFlags B) { return static_cast(static_cast(A) | static_cast(B)); } inline LLVMRustDIFlags &operator|=(LLVMRustDIFlags &A, LLVMRustDIFlags B) { return A = A | B; } inline bool isSet(LLVMRustDIFlags F) { return F != LLVMRustDIFlags::FlagZero; } inline LLVMRustDIFlags visibility(LLVMRustDIFlags F) { return static_cast(static_cast(F) & 0x3); } static DINode::DIFlags fromRust(LLVMRustDIFlags Flags) { DINode::DIFlags Result = DINode::DIFlags::FlagZero; switch (visibility(Flags)) { case LLVMRustDIFlags::FlagPrivate: Result |= DINode::DIFlags::FlagPrivate; break; case LLVMRustDIFlags::FlagProtected: Result |= DINode::DIFlags::FlagProtected; break; case LLVMRustDIFlags::FlagPublic: Result |= DINode::DIFlags::FlagPublic; break; default: // The rest are handled below break; } if (isSet(Flags & LLVMRustDIFlags::FlagFwdDecl)) { Result |= DINode::DIFlags::FlagFwdDecl; } if (isSet(Flags & LLVMRustDIFlags::FlagAppleBlock)) { Result |= DINode::DIFlags::FlagAppleBlock; } #if LLVM_VERSION_LT(10, 0) if (isSet(Flags & LLVMRustDIFlags::FlagBlockByrefStruct)) { Result |= DINode::DIFlags::FlagBlockByrefStruct; } #endif if (isSet(Flags & LLVMRustDIFlags::FlagVirtual)) { Result |= DINode::DIFlags::FlagVirtual; } if (isSet(Flags & LLVMRustDIFlags::FlagArtificial)) { Result |= DINode::DIFlags::FlagArtificial; } if (isSet(Flags & LLVMRustDIFlags::FlagExplicit)) { Result |= DINode::DIFlags::FlagExplicit; } if (isSet(Flags & LLVMRustDIFlags::FlagPrototyped)) { Result |= DINode::DIFlags::FlagPrototyped; } if (isSet(Flags & LLVMRustDIFlags::FlagObjcClassComplete)) { Result |= DINode::DIFlags::FlagObjcClassComplete; } if (isSet(Flags & LLVMRustDIFlags::FlagObjectPointer)) { Result |= DINode::DIFlags::FlagObjectPointer; } if (isSet(Flags & LLVMRustDIFlags::FlagVector)) { Result |= DINode::DIFlags::FlagVector; } if (isSet(Flags & LLVMRustDIFlags::FlagStaticMember)) { Result |= DINode::DIFlags::FlagStaticMember; } if (isSet(Flags & LLVMRustDIFlags::FlagLValueReference)) { Result |= DINode::DIFlags::FlagLValueReference; } if (isSet(Flags & LLVMRustDIFlags::FlagRValueReference)) { Result |= DINode::DIFlags::FlagRValueReference; } if (isSet(Flags & LLVMRustDIFlags::FlagIntroducedVirtual)) { Result |= DINode::DIFlags::FlagIntroducedVirtual; } if (isSet(Flags & LLVMRustDIFlags::FlagBitField)) { Result |= DINode::DIFlags::FlagBitField; } if (isSet(Flags & LLVMRustDIFlags::FlagNoReturn)) { Result |= DINode::DIFlags::FlagNoReturn; } return Result; } // These values **must** match debuginfo::DISPFlags! They also *happen* // to match LLVM, but that isn't required as we do giant sets of // matching below. The value shouldn't be directly passed to LLVM. enum class LLVMRustDISPFlags : uint32_t { SPFlagZero = 0, SPFlagVirtual = 1, SPFlagPureVirtual = 2, SPFlagLocalToUnit = (1 << 2), SPFlagDefinition = (1 << 3), SPFlagOptimized = (1 << 4), SPFlagMainSubprogram = (1 << 5), // Do not add values that are not supported by the minimum LLVM // version we support! see llvm/include/llvm/IR/DebugInfoFlags.def // (In LLVM < 8, createFunction supported these as separate bool arguments.) }; inline LLVMRustDISPFlags operator&(LLVMRustDISPFlags A, LLVMRustDISPFlags B) { return static_cast(static_cast(A) & static_cast(B)); } inline LLVMRustDISPFlags operator|(LLVMRustDISPFlags A, LLVMRustDISPFlags B) { return static_cast(static_cast(A) | static_cast(B)); } inline LLVMRustDISPFlags &operator|=(LLVMRustDISPFlags &A, LLVMRustDISPFlags B) { return A = A | B; } inline bool isSet(LLVMRustDISPFlags F) { return F != LLVMRustDISPFlags::SPFlagZero; } inline LLVMRustDISPFlags virtuality(LLVMRustDISPFlags F) { return static_cast(static_cast(F) & 0x3); } static DISubprogram::DISPFlags fromRust(LLVMRustDISPFlags SPFlags) { DISubprogram::DISPFlags Result = DISubprogram::DISPFlags::SPFlagZero; switch (virtuality(SPFlags)) { case LLVMRustDISPFlags::SPFlagVirtual: Result |= DISubprogram::DISPFlags::SPFlagVirtual; break; case LLVMRustDISPFlags::SPFlagPureVirtual: Result |= DISubprogram::DISPFlags::SPFlagPureVirtual; break; default: // The rest are handled below break; } if (isSet(SPFlags & LLVMRustDISPFlags::SPFlagLocalToUnit)) { Result |= DISubprogram::DISPFlags::SPFlagLocalToUnit; } if (isSet(SPFlags & LLVMRustDISPFlags::SPFlagDefinition)) { Result |= DISubprogram::DISPFlags::SPFlagDefinition; } if (isSet(SPFlags & LLVMRustDISPFlags::SPFlagOptimized)) { Result |= DISubprogram::DISPFlags::SPFlagOptimized; } #if LLVM_VERSION_GE(9, 0) if (isSet(SPFlags & LLVMRustDISPFlags::SPFlagMainSubprogram)) { Result |= DISubprogram::DISPFlags::SPFlagMainSubprogram; } #endif return Result; } enum class LLVMRustDebugEmissionKind { NoDebug, FullDebug, LineTablesOnly, }; static DICompileUnit::DebugEmissionKind fromRust(LLVMRustDebugEmissionKind Kind) { switch (Kind) { case LLVMRustDebugEmissionKind::NoDebug: return DICompileUnit::DebugEmissionKind::NoDebug; case LLVMRustDebugEmissionKind::FullDebug: return DICompileUnit::DebugEmissionKind::FullDebug; case LLVMRustDebugEmissionKind::LineTablesOnly: return DICompileUnit::DebugEmissionKind::LineTablesOnly; default: report_fatal_error(""bad DebugEmissionKind.""); } } enum class LLVMRustChecksumKind { None, MD5, SHA1, }; static Optional fromRust(LLVMRustChecksumKind Kind) { switch (Kind) { case LLVMRustChecksumKind::None: return None; case LLVMRustChecksumKind::MD5: return DIFile::ChecksumKind::CSK_MD5; case LLVMRustChecksumKind::SHA1: return DIFile::ChecksumKind::CSK_SHA1; default: report_fatal_error(""bad ChecksumKind.""); } } extern ""C"" uint32_t LLVMRustDebugMetadataVersion() { return DEBUG_METADATA_VERSION; } extern ""C"" uint32_t LLVMRustVersionMinor() { return LLVM_VERSION_MINOR; } extern ""C"" uint32_t LLVMRustVersionMajor() { return LLVM_VERSION_MAJOR; } extern ""C"" void LLVMRustAddModuleFlag(LLVMModuleRef M, const char *Name, uint32_t Value) { unwrap(M)->addModuleFlag(Module::Warning, Name, Value); } extern ""C"" LLVMValueRef LLVMRustMetadataAsValue(LLVMContextRef C, LLVMMetadataRef MD) { return wrap(MetadataAsValue::get(*unwrap(C), unwrap(MD))); } extern ""C"" LLVMRustDIBuilderRef LLVMRustDIBuilderCreate(LLVMModuleRef M) { return new DIBuilder(*unwrap(M)); } extern ""C"" void LLVMRustDIBuilderDispose(LLVMRustDIBuilderRef Builder) { delete Builder; } extern ""C"" void LLVMRustDIBuilderFinalize(LLVMRustDIBuilderRef Builder) { Builder->finalize(); } extern ""C"" LLVMMetadataRef LLVMRustDIBuilderCreateCompileUnit( LLVMRustDIBuilderRef Builder, unsigned Lang, LLVMMetadataRef FileRef, const char *Producer, size_t ProducerLen, bool isOptimized, const char *Flags, unsigned RuntimeVer, const char *SplitName, size_t SplitNameLen, LLVMRustDebugEmissionKind Kind) { auto *File = unwrapDI(FileRef); return wrap(Builder->createCompileUnit(Lang, File, StringRef(Producer, ProducerLen), isOptimized, Flags, RuntimeVer, StringRef(SplitName, SplitNameLen), fromRust(Kind))); } extern ""C"" LLVMMetadataRef LLVMRustDIBuilderCreateFile( LLVMRustDIBuilderRef Builder, const char *Filename, size_t FilenameLen, const char *Directory, size_t DirectoryLen, LLVMRustChecksumKind CSKind, const char *Checksum, size_t ChecksumLen) { Optional llvmCSKind = fromRust(CSKind); Optional> CSInfo{}; if (llvmCSKind) CSInfo.emplace(*llvmCSKind, StringRef{Checksum, ChecksumLen}); return wrap(Builder->createFile(StringRef(Filename, FilenameLen), StringRef(Directory, DirectoryLen), CSInfo)); } extern ""C"" LLVMMetadataRef LLVMRustDIBuilderCreateSubroutineType(LLVMRustDIBuilderRef Builder, LLVMMetadataRef ParameterTypes) { return wrap(Builder->createSubroutineType( DITypeRefArray(unwrap(ParameterTypes)))); } extern ""C"" LLVMMetadataRef LLVMRustDIBuilderCreateFunction( LLVMRustDIBuilderRef Builder, LLVMMetadataRef Scope, const char *Name, size_t NameLen, const char *LinkageName, size_t LinkageNameLen, LLVMMetadataRef File, unsigned LineNo, LLVMMetadataRef Ty, unsigned ScopeLine, LLVMRustDIFlags Flags, LLVMRustDISPFlags SPFlags, LLVMValueRef Fn, LLVMMetadataRef TParam, LLVMMetadataRef Decl) { DITemplateParameterArray TParams = DITemplateParameterArray(unwrap(TParam)); DISubprogram::DISPFlags llvmSPFlags = fromRust(SPFlags); DINode::DIFlags llvmFlags = fromRust(Flags); #if LLVM_VERSION_LT(9, 0) if (isSet(SPFlags & LLVMRustDISPFlags::SPFlagMainSubprogram)) llvmFlags |= DINode::DIFlags::FlagMainSubprogram; #endif DISubprogram *Sub = Builder->createFunction( unwrapDI(Scope), StringRef(Name, NameLen), StringRef(LinkageName, LinkageNameLen), unwrapDI(File), LineNo, unwrapDI(Ty), ScopeLine, llvmFlags, llvmSPFlags, TParams, unwrapDIPtr(Decl)); unwrap(Fn)->setSubprogram(Sub); return wrap(Sub); } extern ""C"" LLVMMetadataRef LLVMRustDIBuilderCreateBasicType( LLVMRustDIBuilderRef Builder, const char *Name, size_t NameLen, uint64_t SizeInBits, unsigned Encoding) { return wrap(Builder->createBasicType(StringRef(Name, NameLen), SizeInBits, Encoding)); } extern ""C"" LLVMMetadataRef LLVMRustDIBuilderCreateTypedef( LLVMRustDIBuilderRef Builder, LLVMMetadataRef Type, const char *Name, size_t NameLen, LLVMMetadataRef File, unsigned LineNo, LLVMMetadataRef Scope) { return wrap(Builder->createTypedef( unwrap(Type), StringRef(Name, NameLen), unwrap(File), LineNo, unwrap(Scope))); } extern ""C"" LLVMMetadataRef LLVMRustDIBuilderCreatePointerType( LLVMRustDIBuilderRef Builder, LLVMMetadataRef PointeeTy, uint64_t SizeInBits, uint32_t AlignInBits, unsigned AddressSpace, const char *Name, size_t NameLen) { return wrap(Builder->createPointerType(unwrapDI(PointeeTy), SizeInBits, AlignInBits, AddressSpace, StringRef(Name, NameLen))); } extern ""C"" LLVMMetadataRef LLVMRustDIBuilderCreateStructType( LLVMRustDIBuilderRef Builder, LLVMMetadataRef Scope, const char *Name, size_t NameLen, LLVMMetadataRef File, unsigned LineNumber, uint64_t SizeInBits, uint32_t AlignInBits, LLVMRustDIFlags Flags, LLVMMetadataRef DerivedFrom, LLVMMetadataRef Elements, unsigned RunTimeLang, LLVMMetadataRef VTableHolder, const char *UniqueId, size_t UniqueIdLen) { return wrap(Builder->createStructType( unwrapDI(Scope), StringRef(Name, NameLen), unwrapDI(File), LineNumber, SizeInBits, AlignInBits, fromRust(Flags), unwrapDI(DerivedFrom), DINodeArray(unwrapDI(Elements)), RunTimeLang, unwrapDI(VTableHolder), StringRef(UniqueId, UniqueIdLen))); } extern ""C"" LLVMMetadataRef LLVMRustDIBuilderCreateVariantPart( LLVMRustDIBuilderRef Builder, LLVMMetadataRef Scope, const char *Name, size_t NameLen, LLVMMetadataRef File, unsigned LineNumber, uint64_t SizeInBits, uint32_t AlignInBits, LLVMRustDIFlags Flags, LLVMMetadataRef Discriminator, LLVMMetadataRef Elements, const char *UniqueId, size_t UniqueIdLen) { return wrap(Builder->createVariantPart( unwrapDI(Scope), StringRef(Name, NameLen), unwrapDI(File), LineNumber, SizeInBits, AlignInBits, fromRust(Flags), unwrapDI(Discriminator), DINodeArray(unwrapDI(Elements)), StringRef(UniqueId, UniqueIdLen))); } extern ""C"" LLVMMetadataRef LLVMRustDIBuilderCreateMemberType( LLVMRustDIBuilderRef Builder, LLVMMetadataRef Scope, const char *Name, size_t NameLen, LLVMMetadataRef File, unsigned LineNo, uint64_t SizeInBits, uint32_t AlignInBits, uint64_t OffsetInBits, LLVMRustDIFlags Flags, LLVMMetadataRef Ty) { return wrap(Builder->createMemberType(unwrapDI(Scope), StringRef(Name, NameLen), unwrapDI(File), LineNo, SizeInBits, AlignInBits, OffsetInBits, fromRust(Flags), unwrapDI(Ty))); } extern ""C"" LLVMMetadataRef LLVMRustDIBuilderCreateVariantMemberType( LLVMRustDIBuilderRef Builder, LLVMMetadataRef Scope, const char *Name, size_t NameLen, LLVMMetadataRef File, unsigned LineNo, uint64_t SizeInBits, uint32_t AlignInBits, uint64_t OffsetInBits, LLVMValueRef Discriminant, LLVMRustDIFlags Flags, LLVMMetadataRef Ty) { llvm::ConstantInt* D = nullptr; if (Discriminant) { D = unwrap(Discriminant); } return wrap(Builder->createVariantMemberType(unwrapDI(Scope), StringRef(Name, NameLen), unwrapDI(File), LineNo, SizeInBits, AlignInBits, OffsetInBits, D, fromRust(Flags), unwrapDI(Ty))); } extern ""C"" LLVMMetadataRef LLVMRustDIBuilderCreateLexicalBlock( LLVMRustDIBuilderRef Builder, LLVMMetadataRef Scope, LLVMMetadataRef File, unsigned Line, unsigned Col) { return wrap(Builder->createLexicalBlock(unwrapDI(Scope), unwrapDI(File), Line, Col)); } extern ""C"" LLVMMetadataRef LLVMRustDIBuilderCreateLexicalBlockFile(LLVMRustDIBuilderRef Builder, LLVMMetadataRef Scope, LLVMMetadataRef File) { return wrap(Builder->createLexicalBlockFile(unwrapDI(Scope), unwrapDI(File))); } extern ""C"" LLVMMetadataRef LLVMRustDIBuilderCreateStaticVariable( LLVMRustDIBuilderRef Builder, LLVMMetadataRef Context, const char *Name, size_t NameLen, const char *LinkageName, size_t LinkageNameLen, LLVMMetadataRef File, unsigned LineNo, LLVMMetadataRef Ty, bool IsLocalToUnit, LLVMValueRef V, LLVMMetadataRef Decl = nullptr, uint32_t AlignInBits = 0) { llvm::GlobalVariable *InitVal = cast(unwrap(V)); llvm::DIExpression *InitExpr = nullptr; if (llvm::ConstantInt *IntVal = llvm::dyn_cast(InitVal)) { InitExpr = Builder->createConstantValueExpression( IntVal->getValue().getSExtValue()); } else if (llvm::ConstantFP *FPVal = llvm::dyn_cast(InitVal)) { InitExpr = Builder->createConstantValueExpression( FPVal->getValueAPF().bitcastToAPInt().getZExtValue()); } llvm::DIGlobalVariableExpression *VarExpr = Builder->createGlobalVariableExpression( unwrapDI(Context), StringRef(Name, NameLen), StringRef(LinkageName, LinkageNameLen), unwrapDI(File), LineNo, unwrapDI(Ty), IsLocalToUnit, #if LLVM_VERSION_GE(10, 0) /* isDefined */ true, #endif InitExpr, unwrapDIPtr(Decl), /* templateParams */ nullptr, AlignInBits); InitVal->setMetadata(""dbg"", VarExpr); return wrap(VarExpr); } extern ""C"" LLVMMetadataRef LLVMRustDIBuilderCreateVariable( LLVMRustDIBuilderRef Builder, unsigned Tag, LLVMMetadataRef Scope, const char *Name, size_t NameLen, LLVMMetadataRef File, unsigned LineNo, LLVMMetadataRef Ty, bool AlwaysPreserve, LLVMRustDIFlags Flags, unsigned ArgNo, uint32_t AlignInBits) { if (Tag == 0x100) { // DW_TAG_auto_variable return wrap(Builder->createAutoVariable( unwrapDI(Scope), StringRef(Name, NameLen), unwrapDI(File), LineNo, unwrapDI(Ty), AlwaysPreserve, fromRust(Flags), AlignInBits)); } else { return wrap(Builder->createParameterVariable( unwrapDI(Scope), StringRef(Name, NameLen), ArgNo, unwrapDI(File), LineNo, unwrapDI(Ty), AlwaysPreserve, fromRust(Flags))); } } extern ""C"" LLVMMetadataRef LLVMRustDIBuilderCreateArrayType(LLVMRustDIBuilderRef Builder, uint64_t Size, uint32_t AlignInBits, LLVMMetadataRef Ty, LLVMMetadataRef Subscripts) { return wrap( Builder->createArrayType(Size, AlignInBits, unwrapDI(Ty), DINodeArray(unwrapDI(Subscripts)))); } extern ""C"" LLVMMetadataRef LLVMRustDIBuilderGetOrCreateSubrange(LLVMRustDIBuilderRef Builder, int64_t Lo, int64_t Count) { return wrap(Builder->getOrCreateSubrange(Lo, Count)); } extern ""C"" LLVMMetadataRef LLVMRustDIBuilderGetOrCreateArray(LLVMRustDIBuilderRef Builder, LLVMMetadataRef *Ptr, unsigned Count) { Metadata **DataValue = unwrap(Ptr); return wrap( Builder->getOrCreateArray(ArrayRef(DataValue, Count)).get()); } extern ""C"" LLVMValueRef LLVMRustDIBuilderInsertDeclareAtEnd( LLVMRustDIBuilderRef Builder, LLVMValueRef V, LLVMMetadataRef VarInfo, int64_t *AddrOps, unsigned AddrOpsCount, LLVMValueRef DL, LLVMBasicBlockRef InsertAtEnd) { return wrap(Builder->insertDeclare( unwrap(V), unwrap(VarInfo), Builder->createExpression(llvm::ArrayRef(AddrOps, AddrOpsCount)), DebugLoc(cast(unwrap(DL)->getMetadata())), unwrap(InsertAtEnd))); } extern ""C"" LLVMMetadataRef LLVMRustDIBuilderCreateEnumerator( LLVMRustDIBuilderRef Builder, const char *Name, size_t NameLen, int64_t Value, bool IsUnsigned) { return wrap(Builder->createEnumerator(StringRef(Name, NameLen), Value, IsUnsigned)); } extern ""C"" LLVMMetadataRef LLVMRustDIBuilderCreateEnumerationType( LLVMRustDIBuilderRef Builder, LLVMMetadataRef Scope, const char *Name, size_t NameLen, LLVMMetadataRef File, unsigned LineNumber, uint64_t SizeInBits, uint32_t AlignInBits, LLVMMetadataRef Elements, LLVMMetadataRef ClassTy, bool IsScoped) { return wrap(Builder->createEnumerationType( unwrapDI(Scope), StringRef(Name, NameLen), unwrapDI(File), LineNumber, SizeInBits, AlignInBits, DINodeArray(unwrapDI(Elements)), unwrapDI(ClassTy), """", IsScoped)); } extern ""C"" LLVMMetadataRef LLVMRustDIBuilderCreateUnionType( LLVMRustDIBuilderRef Builder, LLVMMetadataRef Scope, const char *Name, size_t NameLen, LLVMMetadataRef File, unsigned LineNumber, uint64_t SizeInBits, uint32_t AlignInBits, LLVMRustDIFlags Flags, LLVMMetadataRef Elements, unsigned RunTimeLang, const char *UniqueId, size_t UniqueIdLen) { return wrap(Builder->createUnionType( unwrapDI(Scope), StringRef(Name, NameLen), unwrapDI(File), LineNumber, SizeInBits, AlignInBits, fromRust(Flags), DINodeArray(unwrapDI(Elements)), RunTimeLang, StringRef(UniqueId, UniqueIdLen))); } extern ""C"" LLVMMetadataRef LLVMRustDIBuilderCreateTemplateTypeParameter( LLVMRustDIBuilderRef Builder, LLVMMetadataRef Scope, const char *Name, size_t NameLen, LLVMMetadataRef Ty) { #if LLVM_VERSION_GE(11, 0) bool IsDefault = false; // FIXME: should we ever set this true? return wrap(Builder->createTemplateTypeParameter( unwrapDI(Scope), StringRef(Name, NameLen), unwrapDI(Ty), IsDefault)); #else return wrap(Builder->createTemplateTypeParameter( unwrapDI(Scope), StringRef(Name, NameLen), unwrapDI(Ty))); #endif } extern ""C"" LLVMMetadataRef LLVMRustDIBuilderCreateNameSpace( LLVMRustDIBuilderRef Builder, LLVMMetadataRef Scope, const char *Name, size_t NameLen, bool ExportSymbols) { return wrap(Builder->createNameSpace( unwrapDI(Scope), StringRef(Name, NameLen), ExportSymbols )); } extern ""C"" void LLVMRustDICompositeTypeReplaceArrays(LLVMRustDIBuilderRef Builder, LLVMMetadataRef CompositeTy, LLVMMetadataRef Elements, LLVMMetadataRef Params) { DICompositeType *Tmp = unwrapDI(CompositeTy); Builder->replaceArrays(Tmp, DINodeArray(unwrap(Elements)), DINodeArray(unwrap(Params))); } extern ""C"" LLVMValueRef LLVMRustDIBuilderCreateDebugLocation(LLVMContextRef ContextRef, unsigned Line, unsigned Column, LLVMMetadataRef Scope, LLVMMetadataRef InlinedAt) { LLVMContext &Context = *unwrap(ContextRef); DebugLoc debug_loc = DebugLoc::get(Line, Column, unwrapDIPtr(Scope), unwrapDIPtr(InlinedAt)); return wrap(MetadataAsValue::get(Context, debug_loc.getAsMDNode())); } extern ""C"" int64_t LLVMRustDIBuilderCreateOpDeref() { return dwarf::DW_OP_deref; } extern ""C"" int64_t LLVMRustDIBuilderCreateOpPlusUconst() { return dwarf::DW_OP_plus_uconst; } extern ""C"" void LLVMRustWriteTypeToString(LLVMTypeRef Ty, RustStringRef Str) { RawRustStringOstream OS(Str); unwrap(Ty)->print(OS); } extern ""C"" void LLVMRustWriteValueToString(LLVMValueRef V, RustStringRef Str) { RawRustStringOstream OS(Str); if (!V) { OS << ""(null)""; } else { OS << ""(""; unwrap(V)->getType()->print(OS); OS << "":""; unwrap(V)->print(OS); OS << "")""; } } // Note that the two following functions look quite similar to the // LLVMGetSectionName function. Sadly, it appears that this function only // returns a char* pointer, which isn't guaranteed to be null-terminated. The // function provided by LLVM doesn't return the length, so we've created our own // function which returns the length as well as the data pointer. // // For an example of this not returning a null terminated string, see // lib/Object/COFFObjectFile.cpp in the getSectionName function. One of the // branches explicitly creates a StringRef without a null terminator, and then // that's returned. inline section_iterator *unwrap(LLVMSectionIteratorRef SI) { return reinterpret_cast(SI); } extern ""C"" size_t LLVMRustGetSectionName(LLVMSectionIteratorRef SI, const char **Ptr) { #if LLVM_VERSION_GE(10, 0) auto NameOrErr = (*unwrap(SI))->getName(); if (!NameOrErr) report_fatal_error(NameOrErr.takeError()); *Ptr = NameOrErr->data(); return NameOrErr->size(); #else StringRef Ret; if (std::error_code EC = (*unwrap(SI))->getName(Ret)) report_fatal_error(EC.message()); *Ptr = Ret.data(); return Ret.size(); #endif } // LLVMArrayType function does not support 64-bit ElementCount extern ""C"" LLVMTypeRef LLVMRustArrayType(LLVMTypeRef ElementTy, uint64_t ElementCount) { return wrap(ArrayType::get(unwrap(ElementTy), ElementCount)); } DEFINE_SIMPLE_CONVERSION_FUNCTIONS(Twine, LLVMTwineRef) extern ""C"" void LLVMRustWriteTwineToString(LLVMTwineRef T, RustStringRef Str) { RawRustStringOstream OS(Str); unwrap(T)->print(OS); } extern ""C"" void LLVMRustUnpackOptimizationDiagnostic( LLVMDiagnosticInfoRef DI, RustStringRef PassNameOut, LLVMValueRef *FunctionOut, unsigned* Line, unsigned* Column, RustStringRef FilenameOut, RustStringRef MessageOut) { // Undefined to call this not on an optimization diagnostic! llvm::DiagnosticInfoOptimizationBase *Opt = static_cast(unwrap(DI)); RawRustStringOstream PassNameOS(PassNameOut); PassNameOS << Opt->getPassName(); *FunctionOut = wrap(&Opt->getFunction()); RawRustStringOstream FilenameOS(FilenameOut); DiagnosticLocation loc = Opt->getLocation(); if (loc.isValid()) { *Line = loc.getLine(); *Column = loc.getColumn(); FilenameOS << loc.getAbsolutePath(); } RawRustStringOstream MessageOS(MessageOut); MessageOS << Opt->getMsg(); } enum class LLVMRustDiagnosticLevel { Error, Warning, Note, Remark, }; extern ""C"" void LLVMRustUnpackInlineAsmDiagnostic(LLVMDiagnosticInfoRef DI, LLVMRustDiagnosticLevel *LevelOut, unsigned *CookieOut, LLVMTwineRef *MessageOut, LLVMValueRef *InstructionOut) { // Undefined to call this not on an inline assembly diagnostic! llvm::DiagnosticInfoInlineAsm *IA = static_cast(unwrap(DI)); *CookieOut = IA->getLocCookie(); *MessageOut = wrap(&IA->getMsgStr()); *InstructionOut = wrap(IA->getInstruction()); switch (IA->getSeverity()) { case DS_Error: *LevelOut = LLVMRustDiagnosticLevel::Error; break; case DS_Warning: *LevelOut = LLVMRustDiagnosticLevel::Warning; break; case DS_Note: *LevelOut = LLVMRustDiagnosticLevel::Note; break; case DS_Remark: *LevelOut = LLVMRustDiagnosticLevel::Remark; break; default: report_fatal_error(""Invalid LLVMRustDiagnosticLevel value!""); } } extern ""C"" void LLVMRustWriteDiagnosticInfoToString(LLVMDiagnosticInfoRef DI, RustStringRef Str) { RawRustStringOstream OS(Str); DiagnosticPrinterRawOStream DP(OS); unwrap(DI)->print(DP); } enum class LLVMRustDiagnosticKind { Other, InlineAsm, StackSize, DebugMetadataVersion, SampleProfile, OptimizationRemark, OptimizationRemarkMissed, OptimizationRemarkAnalysis, OptimizationRemarkAnalysisFPCommute, OptimizationRemarkAnalysisAliasing, OptimizationRemarkOther, OptimizationFailure, PGOProfile, Linker, }; static LLVMRustDiagnosticKind toRust(DiagnosticKind Kind) { switch (Kind) { case DK_InlineAsm: return LLVMRustDiagnosticKind::InlineAsm; case DK_StackSize: return LLVMRustDiagnosticKind::StackSize; case DK_DebugMetadataVersion: return LLVMRustDiagnosticKind::DebugMetadataVersion; case DK_SampleProfile: return LLVMRustDiagnosticKind::SampleProfile; case DK_OptimizationRemark: return LLVMRustDiagnosticKind::OptimizationRemark; case DK_OptimizationRemarkMissed: return LLVMRustDiagnosticKind::OptimizationRemarkMissed; case DK_OptimizationRemarkAnalysis: return LLVMRustDiagnosticKind::OptimizationRemarkAnalysis; case DK_OptimizationRemarkAnalysisFPCommute: return LLVMRustDiagnosticKind::OptimizationRemarkAnalysisFPCommute; case DK_OptimizationRemarkAnalysisAliasing: return LLVMRustDiagnosticKind::OptimizationRemarkAnalysisAliasing; case DK_PGOProfile: return LLVMRustDiagnosticKind::PGOProfile; case DK_Linker: return LLVMRustDiagnosticKind::Linker; default: return (Kind >= DK_FirstRemark && Kind <= DK_LastRemark) ? LLVMRustDiagnosticKind::OptimizationRemarkOther : LLVMRustDiagnosticKind::Other; } } extern ""C"" LLVMRustDiagnosticKind LLVMRustGetDiagInfoKind(LLVMDiagnosticInfoRef DI) { return toRust((DiagnosticKind)unwrap(DI)->getKind()); } // This is kept distinct from LLVMGetTypeKind, because when // a new type kind is added, the Rust-side enum must be // updated or UB will result. extern ""C"" LLVMTypeKind LLVMRustGetTypeKind(LLVMTypeRef Ty) { switch (unwrap(Ty)->getTypeID()) { case Type::VoidTyID: return LLVMVoidTypeKind; case Type::HalfTyID: return LLVMHalfTypeKind; case Type::FloatTyID: return LLVMFloatTypeKind; case Type::DoubleTyID: return LLVMDoubleTypeKind; case Type::X86_FP80TyID: return LLVMX86_FP80TypeKind; case Type::FP128TyID: return LLVMFP128TypeKind; case Type::PPC_FP128TyID: return LLVMPPC_FP128TypeKind; case Type::LabelTyID: return LLVMLabelTypeKind; case Type::MetadataTyID: return LLVMMetadataTypeKind; case Type::IntegerTyID: return LLVMIntegerTypeKind; case Type::FunctionTyID: return LLVMFunctionTypeKind; case Type::StructTyID: return LLVMStructTypeKind; case Type::ArrayTyID: return LLVMArrayTypeKind; case Type::PointerTyID: return LLVMPointerTypeKind; #if LLVM_VERSION_GE(11, 0) case Type::FixedVectorTyID: return LLVMVectorTypeKind; #else case Type::VectorTyID: return LLVMVectorTypeKind; #endif case Type::X86_MMXTyID: return LLVMX86_MMXTypeKind; case Type::TokenTyID: return LLVMTokenTypeKind; #if LLVM_VERSION_GE(11, 0) case Type::ScalableVectorTyID: return LLVMScalableVectorTypeKind; case Type::BFloatTyID: return LLVMBFloatTypeKind; #endif } report_fatal_error(""Unhandled TypeID.""); } DEFINE_SIMPLE_CONVERSION_FUNCTIONS(SMDiagnostic, LLVMSMDiagnosticRef) extern ""C"" void LLVMRustSetInlineAsmDiagnosticHandler( LLVMContextRef C, LLVMContext::InlineAsmDiagHandlerTy H, void *CX) { unwrap(C)->setInlineAsmDiagnosticHandler(H, CX); } extern ""C"" bool LLVMRustUnpackSMDiagnostic(LLVMSMDiagnosticRef DRef, RustStringRef MessageOut, RustStringRef BufferOut, LLVMRustDiagnosticLevel* LevelOut, unsigned* LocOut, unsigned* RangesOut, size_t* NumRanges) { SMDiagnostic& D = *unwrap(DRef); RawRustStringOstream MessageOS(MessageOut); MessageOS << D.getMessage(); switch (D.getKind()) { case SourceMgr::DK_Error: *LevelOut = LLVMRustDiagnosticLevel::Error; break; case SourceMgr::DK_Warning: *LevelOut = LLVMRustDiagnosticLevel::Warning; break; case SourceMgr::DK_Note: *LevelOut = LLVMRustDiagnosticLevel::Note; break; case SourceMgr::DK_Remark: *LevelOut = LLVMRustDiagnosticLevel::Remark; break; default: report_fatal_error(""Invalid LLVMRustDiagnosticLevel value!""); } if (D.getLoc() == SMLoc()) return false; const SourceMgr &LSM = *D.getSourceMgr(); const MemoryBuffer *LBuf = LSM.getMemoryBuffer(LSM.FindBufferContainingLoc(D.getLoc())); LLVMRustStringWriteImpl(BufferOut, LBuf->getBufferStart(), LBuf->getBufferSize()); *LocOut = D.getLoc().getPointer() - LBuf->getBufferStart(); *NumRanges = std::min(*NumRanges, D.getRanges().size()); size_t LineStart = *LocOut - (size_t)D.getColumnNo(); for (size_t i = 0; i < *NumRanges; i++) { RangesOut[i * 2] = LineStart + D.getRanges()[i].first; RangesOut[i * 2 + 1] = LineStart + D.getRanges()[i].second; } return true; } extern ""C"" LLVMValueRef LLVMRustBuildCleanupPad(LLVMBuilderRef B, LLVMValueRef ParentPad, unsigned ArgCount, LLVMValueRef *LLArgs, const char *Name) { Value **Args = unwrap(LLArgs); if (ParentPad == nullptr) { Type *Ty = Type::getTokenTy(unwrap(B)->getContext()); ParentPad = wrap(Constant::getNullValue(Ty)); } return wrap(unwrap(B)->CreateCleanupPad( unwrap(ParentPad), ArrayRef(Args, ArgCount), Name)); } extern ""C"" LLVMValueRef LLVMRustBuildCleanupRet(LLVMBuilderRef B, LLVMValueRef CleanupPad, LLVMBasicBlockRef UnwindBB) { CleanupPadInst *Inst = cast(unwrap(CleanupPad)); return wrap(unwrap(B)->CreateCleanupRet(Inst, unwrap(UnwindBB))); } extern ""C"" LLVMValueRef LLVMRustBuildCatchPad(LLVMBuilderRef B, LLVMValueRef ParentPad, unsigned ArgCount, LLVMValueRef *LLArgs, const char *Name) { Value **Args = unwrap(LLArgs); return wrap(unwrap(B)->CreateCatchPad( unwrap(ParentPad), ArrayRef(Args, ArgCount), Name)); } extern ""C"" LLVMValueRef LLVMRustBuildCatchRet(LLVMBuilderRef B, LLVMValueRef Pad, LLVMBasicBlockRef BB) { return wrap(unwrap(B)->CreateCatchRet(cast(unwrap(Pad)), unwrap(BB))); } extern ""C"" LLVMValueRef LLVMRustBuildCatchSwitch(LLVMBuilderRef B, LLVMValueRef ParentPad, LLVMBasicBlockRef BB, unsigned NumHandlers, const char *Name) { if (ParentPad == nullptr) { Type *Ty = Type::getTokenTy(unwrap(B)->getContext()); ParentPad = wrap(Constant::getNullValue(Ty)); } return wrap(unwrap(B)->CreateCatchSwitch(unwrap(ParentPad), unwrap(BB), NumHandlers, Name)); } extern ""C"" void LLVMRustAddHandler(LLVMValueRef CatchSwitchRef, LLVMBasicBlockRef Handler) { Value *CatchSwitch = unwrap(CatchSwitchRef); cast(CatchSwitch)->addHandler(unwrap(Handler)); } extern ""C"" OperandBundleDef *LLVMRustBuildOperandBundleDef(const char *Name, LLVMValueRef *Inputs, unsigned NumInputs) { return new OperandBundleDef(Name, makeArrayRef(unwrap(Inputs), NumInputs)); } extern ""C"" void LLVMRustFreeOperandBundleDef(OperandBundleDef *Bundle) { delete Bundle; } extern ""C"" LLVMValueRef LLVMRustBuildCall(LLVMBuilderRef B, LLVMValueRef Fn, LLVMValueRef *Args, unsigned NumArgs, OperandBundleDef *Bundle) { Value *Callee = unwrap(Fn); FunctionType *FTy = cast(Callee->getType()->getPointerElementType()); unsigned Len = Bundle ? 1 : 0; ArrayRef Bundles = makeArrayRef(Bundle, Len); return wrap(unwrap(B)->CreateCall( FTy, Callee, makeArrayRef(unwrap(Args), NumArgs), Bundles)); } extern ""C"" LLVMValueRef LLVMRustGetInstrProfIncrementIntrinsic(LLVMModuleRef M) { return wrap(llvm::Intrinsic::getDeclaration(unwrap(M), (llvm::Intrinsic::ID)llvm::Intrinsic::instrprof_increment)); } extern ""C"" LLVMValueRef LLVMRustBuildMemCpy(LLVMBuilderRef B, LLVMValueRef Dst, unsigned DstAlign, LLVMValueRef Src, unsigned SrcAlign, LLVMValueRef Size, bool IsVolatile) { #if LLVM_VERSION_GE(10, 0) return wrap(unwrap(B)->CreateMemCpy( unwrap(Dst), MaybeAlign(DstAlign), unwrap(Src), MaybeAlign(SrcAlign), unwrap(Size), IsVolatile)); #else return wrap(unwrap(B)->CreateMemCpy( unwrap(Dst), DstAlign, unwrap(Src), SrcAlign, unwrap(Size), IsVolatile)); #endif } extern ""C"" LLVMValueRef LLVMRustBuildMemMove(LLVMBuilderRef B, LLVMValueRef Dst, unsigned DstAlign, LLVMValueRef Src, unsigned SrcAlign, LLVMValueRef Size, bool IsVolatile) { #if LLVM_VERSION_GE(10, 0) return wrap(unwrap(B)->CreateMemMove( unwrap(Dst), MaybeAlign(DstAlign), unwrap(Src), MaybeAlign(SrcAlign), unwrap(Size), IsVolatile)); #else return wrap(unwrap(B)->CreateMemMove( unwrap(Dst), DstAlign, unwrap(Src), SrcAlign, unwrap(Size), IsVolatile)); #endif } extern ""C"" LLVMValueRef LLVMRustBuildMemSet(LLVMBuilderRef B, LLVMValueRef Dst, unsigned DstAlign, LLVMValueRef Val, LLVMValueRef Size, bool IsVolatile) { #if LLVM_VERSION_GE(10, 0) return wrap(unwrap(B)->CreateMemSet( unwrap(Dst), unwrap(Val), unwrap(Size), MaybeAlign(DstAlign), IsVolatile)); #else return wrap(unwrap(B)->CreateMemSet( unwrap(Dst), unwrap(Val), unwrap(Size), DstAlign, IsVolatile)); #endif } extern ""C"" LLVMValueRef LLVMRustBuildInvoke(LLVMBuilderRef B, LLVMValueRef Fn, LLVMValueRef *Args, unsigned NumArgs, LLVMBasicBlockRef Then, LLVMBasicBlockRef Catch, OperandBundleDef *Bundle, const char *Name) { Value *Callee = unwrap(Fn); FunctionType *FTy = cast(Callee->getType()->getPointerElementType()); unsigned Len = Bundle ? 1 : 0; ArrayRef Bundles = makeArrayRef(Bundle, Len); return wrap(unwrap(B)->CreateInvoke(FTy, Callee, unwrap(Then), unwrap(Catch), makeArrayRef(unwrap(Args), NumArgs), Bundles, Name)); } extern ""C"" void LLVMRustPositionBuilderAtStart(LLVMBuilderRef B, LLVMBasicBlockRef BB) { auto Point = unwrap(BB)->getFirstInsertionPt(); unwrap(B)->SetInsertPoint(unwrap(BB), Point); } extern ""C"" void LLVMRustSetComdat(LLVMModuleRef M, LLVMValueRef V, const char *Name, size_t NameLen) { Triple TargetTriple(unwrap(M)->getTargetTriple()); GlobalObject *GV = unwrap(V); if (!TargetTriple.isOSBinFormatMachO()) { StringRef NameRef(Name, NameLen); GV->setComdat(unwrap(M)->getOrInsertComdat(NameRef)); } } extern ""C"" void LLVMRustUnsetComdat(LLVMValueRef V) { GlobalObject *GV = unwrap(V); GV->setComdat(nullptr); } enum class LLVMRustLinkage { ExternalLinkage = 0, AvailableExternallyLinkage = 1, LinkOnceAnyLinkage = 2, LinkOnceODRLinkage = 3, WeakAnyLinkage = 4, WeakODRLinkage = 5, AppendingLinkage = 6, InternalLinkage = 7, PrivateLinkage = 8, ExternalWeakLinkage = 9, CommonLinkage = 10, }; static LLVMRustLinkage toRust(LLVMLinkage Linkage) { switch (Linkage) { case LLVMExternalLinkage: return LLVMRustLinkage::ExternalLinkage; case LLVMAvailableExternallyLinkage: return LLVMRustLinkage::AvailableExternallyLinkage; case LLVMLinkOnceAnyLinkage: return LLVMRustLinkage::LinkOnceAnyLinkage; case LLVMLinkOnceODRLinkage: return LLVMRustLinkage::LinkOnceODRLinkage; case LLVMWeakAnyLinkage: return LLVMRustLinkage::WeakAnyLinkage; case LLVMWeakODRLinkage: return LLVMRustLinkage::WeakODRLinkage; case LLVMAppendingLinkage: return LLVMRustLinkage::AppendingLinkage; case LLVMInternalLinkage: return LLVMRustLinkage::InternalLinkage; case LLVMPrivateLinkage: return LLVMRustLinkage::PrivateLinkage; case LLVMExternalWeakLinkage: return LLVMRustLinkage::ExternalWeakLinkage; case LLVMCommonLinkage: return LLVMRustLinkage::CommonLinkage; default: report_fatal_error(""Invalid LLVMRustLinkage value!""); } } static LLVMLinkage fromRust(LLVMRustLinkage Linkage) { switch (Linkage) { case LLVMRustLinkage::ExternalLinkage: return LLVMExternalLinkage; case LLVMRustLinkage::AvailableExternallyLinkage: return LLVMAvailableExternallyLinkage; case LLVMRustLinkage::LinkOnceAnyLinkage: return LLVMLinkOnceAnyLinkage; case LLVMRustLinkage::LinkOnceODRLinkage: return LLVMLinkOnceODRLinkage; case LLVMRustLinkage::WeakAnyLinkage: return LLVMWeakAnyLinkage; case LLVMRustLinkage::WeakODRLinkage: return LLVMWeakODRLinkage; case LLVMRustLinkage::AppendingLinkage: return LLVMAppendingLinkage; case LLVMRustLinkage::InternalLinkage: return LLVMInternalLinkage; case LLVMRustLinkage::PrivateLinkage: return LLVMPrivateLinkage; case LLVMRustLinkage::ExternalWeakLinkage: return LLVMExternalWeakLinkage; case LLVMRustLinkage::CommonLinkage: return LLVMCommonLinkage; } report_fatal_error(""Invalid LLVMRustLinkage value!""); } extern ""C"" LLVMRustLinkage LLVMRustGetLinkage(LLVMValueRef V) { return toRust(LLVMGetLinkage(V)); } extern ""C"" void LLVMRustSetLinkage(LLVMValueRef V, LLVMRustLinkage RustLinkage) { LLVMSetLinkage(V, fromRust(RustLinkage)); } // Returns true if both high and low were successfully set. Fails in case constant wasn’t any of // the common sizes (1, 8, 16, 32, 64, 128 bits) extern ""C"" bool LLVMRustConstInt128Get(LLVMValueRef CV, bool sext, uint64_t *high, uint64_t *low) { auto C = unwrap(CV); if (C->getBitWidth() > 128) { return false; } APInt AP; if (sext) { AP = C->getValue().sextOrSelf(128); } else { AP = C->getValue().zextOrSelf(128); } *low = AP.getLoBits(64).getZExtValue(); *high = AP.getHiBits(64).getZExtValue(); return true; } enum class LLVMRustVisibility { Default = 0, Hidden = 1, Protected = 2, }; static LLVMRustVisibility toRust(LLVMVisibility Vis) { switch (Vis) { case LLVMDefaultVisibility: return LLVMRustVisibility::Default; case LLVMHiddenVisibility: return LLVMRustVisibility::Hidden; case LLVMProtectedVisibility: return LLVMRustVisibility::Protected; } report_fatal_error(""Invalid LLVMRustVisibility value!""); } static LLVMVisibility fromRust(LLVMRustVisibility Vis) { switch (Vis) { case LLVMRustVisibility::Default: return LLVMDefaultVisibility; case LLVMRustVisibility::Hidden: return LLVMHiddenVisibility; case LLVMRustVisibility::Protected: return LLVMProtectedVisibility; } report_fatal_error(""Invalid LLVMRustVisibility value!""); } extern ""C"" LLVMRustVisibility LLVMRustGetVisibility(LLVMValueRef V) { return toRust(LLVMGetVisibility(V)); } // Oh hey, a binding that makes sense for once? (because LLVM’s own do not) extern ""C"" LLVMValueRef LLVMRustBuildIntCast(LLVMBuilderRef B, LLVMValueRef Val, LLVMTypeRef DestTy, bool isSigned) { return wrap(unwrap(B)->CreateIntCast(unwrap(Val), unwrap(DestTy), isSigned, """")); } extern ""C"" void LLVMRustSetVisibility(LLVMValueRef V, LLVMRustVisibility RustVisibility) { LLVMSetVisibility(V, fromRust(RustVisibility)); } struct LLVMRustModuleBuffer { std::string data; }; extern ""C"" LLVMRustModuleBuffer* LLVMRustModuleBufferCreate(LLVMModuleRef M) { #if LLVM_VERSION_GE(10, 0) auto Ret = std::make_unique(); #else auto Ret = llvm::make_unique(); #endif { raw_string_ostream OS(Ret->data); { legacy::PassManager PM; PM.add(createBitcodeWriterPass(OS)); PM.run(*unwrap(M)); } } return Ret.release(); } extern ""C"" void LLVMRustModuleBufferFree(LLVMRustModuleBuffer *Buffer) { delete Buffer; } extern ""C"" const void* LLVMRustModuleBufferPtr(const LLVMRustModuleBuffer *Buffer) { return Buffer->data.data(); } extern ""C"" size_t LLVMRustModuleBufferLen(const LLVMRustModuleBuffer *Buffer) { return Buffer->data.length(); } extern ""C"" uint64_t LLVMRustModuleCost(LLVMModuleRef M) { auto f = unwrap(M)->functions(); return std::distance(std::begin(f), std::end(f)); } // Vector reductions: extern ""C"" LLVMValueRef LLVMRustBuildVectorReduceFAdd(LLVMBuilderRef B, LLVMValueRef Acc, LLVMValueRef Src) { return wrap(unwrap(B)->CreateFAddReduce(unwrap(Acc),unwrap(Src))); } extern ""C"" LLVMValueRef LLVMRustBuildVectorReduceFMul(LLVMBuilderRef B, LLVMValueRef Acc, LLVMValueRef Src) { return wrap(unwrap(B)->CreateFMulReduce(unwrap(Acc),unwrap(Src))); } extern ""C"" LLVMValueRef LLVMRustBuildVectorReduceAdd(LLVMBuilderRef B, LLVMValueRef Src) { return wrap(unwrap(B)->CreateAddReduce(unwrap(Src))); } extern ""C"" LLVMValueRef LLVMRustBuildVectorReduceMul(LLVMBuilderRef B, LLVMValueRef Src) { return wrap(unwrap(B)->CreateMulReduce(unwrap(Src))); } extern ""C"" LLVMValueRef LLVMRustBuildVectorReduceAnd(LLVMBuilderRef B, LLVMValueRef Src) { return wrap(unwrap(B)->CreateAndReduce(unwrap(Src))); } extern ""C"" LLVMValueRef LLVMRustBuildVectorReduceOr(LLVMBuilderRef B, LLVMValueRef Src) { return wrap(unwrap(B)->CreateOrReduce(unwrap(Src))); } extern ""C"" LLVMValueRef LLVMRustBuildVectorReduceXor(LLVMBuilderRef B, LLVMValueRef Src) { return wrap(unwrap(B)->CreateXorReduce(unwrap(Src))); } extern ""C"" LLVMValueRef LLVMRustBuildVectorReduceMin(LLVMBuilderRef B, LLVMValueRef Src, bool IsSigned) { return wrap(unwrap(B)->CreateIntMinReduce(unwrap(Src), IsSigned)); } extern ""C"" LLVMValueRef LLVMRustBuildVectorReduceMax(LLVMBuilderRef B, LLVMValueRef Src, bool IsSigned) { return wrap(unwrap(B)->CreateIntMaxReduce(unwrap(Src), IsSigned)); } extern ""C"" LLVMValueRef LLVMRustBuildVectorReduceFMin(LLVMBuilderRef B, LLVMValueRef Src, bool NoNaN) { return wrap(unwrap(B)->CreateFPMinReduce(unwrap(Src), NoNaN)); } extern ""C"" LLVMValueRef LLVMRustBuildVectorReduceFMax(LLVMBuilderRef B, LLVMValueRef Src, bool NoNaN) { return wrap(unwrap(B)->CreateFPMaxReduce(unwrap(Src), NoNaN)); } extern ""C"" LLVMValueRef LLVMRustBuildMinNum(LLVMBuilderRef B, LLVMValueRef LHS, LLVMValueRef RHS) { return wrap(unwrap(B)->CreateMinNum(unwrap(LHS),unwrap(RHS))); } extern ""C"" LLVMValueRef LLVMRustBuildMaxNum(LLVMBuilderRef B, LLVMValueRef LHS, LLVMValueRef RHS) { return wrap(unwrap(B)->CreateMaxNum(unwrap(LHS),unwrap(RHS))); } ",16242,True,2920.570536152692,median "// Copyright 2017 the original author or authors. // // Licensed under the Apache License, Version 2.0 (the ""License""); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an ""AS IS"" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. [[native_software]] = Building native software [CAUTION] ==== The https://blog.gradle.org/state-and-future-of-the-gradle-software-model[software model] is being retired and the plugins mentioned in this chapter will eventually be deprecated and removed. We recommend new projects looking to build C++ applications and libraries use the newer <>. ==== The native software plugins add support for building native software components, such as executables or shared libraries, from code written in C++, C and other languages. While many excellent build tools exist for this space of software development, Gradle offers developers its trademark power and flexibility together with dependency management practices more traditionally found in the JVM development space. The native software plugins make use of the Gradle <>. [[sec:native_features]] == Features The native software plugins provide: * Support for building native libraries and applications on Windows, Linux, macOS and other platforms. * Support for several source languages. * Support for building different variants of the same software, for different architectures, operating systems, or for any purpose. * Incremental parallel compilation, precompiled headers. * Dependency management between native software components. * Unit test execution. * Generate Visual studio solution and project files. * Deep integration with various tool chain, including discovery of installed tool chains. [[sec:supported_languages]] == Supported languages The following source languages are currently supported: * C * C++ * Objective-C * Objective-C++ * Assembly * Windows resources [[native-binaries:tool-chain-support]] == Tool chain support Gradle offers the ability to execute the same build using different tool chains. When you build a native binary, Gradle will attempt to locate a tool chain installed on your machine that can build the binary. You can fine tune exactly how this works, see <<#native_binaries:tool_chain,Tool chain support>> for details. The following tool chains are supported: [%header%autowidth,compact] |=== | Operating System | Tool Chain | Notes | Linux | http://gcc.gnu.org/[GCC] | | Linux | http://clang.llvm.org[Clang] | | macOS | XCode | Uses the Clang tool chain bundled with XCode. | Windows | https://visualstudio.microsoft.com/[Visual C++] | Windows XP and later, Visual C++ 2010/2012/2013/2015/2017. | Windows | http://gcc.gnu.org/[GCC] with http://cygwin.com[Cygwin 32 and Cygwin 64] | Windows XP and later. | Windows | http://gcc.gnu.org/[GCC] with http://www.mingw.org/[MinGW] and https://mingw-w64.org/doku.php[MinGW64] | Windows XP and later. |=== The following tool chains are unofficially supported. They generally work fine, but are not tested continuously: [%header%autowidth,compact] |=== | Operating System | Tool Chain | Notes | macOS | http://gcc.gnu.org/[GCC] from Macports | | macOS | http://clang.llvm.org[Clang] from Macports | | UNIX-like | http://gcc.gnu.org/[GCC] | | UNIX-like | http://clang.llvm.org[Clang] | |=== [[sec:tool_chain_installation]] == Tool chain installation [NOTE] ==== Note that if you are using GCC then you currently need to install support for C+\\+, even if you are not building from C++ source. This restriction will be removed in a future Gradle version. ==== To build native software, you will need to have a compatible tool chain installed: [[sec:windows]] === Windows To build on Windows, install a compatible version of Visual Studio. The native plugins will discover the Visual Studio installations and select the latest version. There is no need to mess around with environment variables or batch scripts. This works fine from a Cygwin shell or the Windows command-line. Alternatively, you can install Cygwin with GCC or MinGW. Clang is currently not supported. [[sec:macOS]] === macOS To build on macOS, you should install XCode. The native plugins will discover the XCode installation using the system PATH. The native plugins also work with GCC and Clang bundled with Macports. To use one of the Macports tool chains, you will need to make the tool chain the default using the `port select` command and add Macports to the system PATH. [[sec:linux]] === Linux To build on Linux, install a compatible version of GCC or Clang. The native plugins will discover GCC or Clang using the system PATH. [[sec:native_software_model]] == Native software model The native software model builds on the base Gradle <>. To build native software using Gradle, your project should define one or more _native components_. Each component represents either an executable or a library that Gradle should build. A project can define any number of components. Gradle does not define any components by default. For each component, Gradle defines a _source set_ for each language that the component can be built from. A source set is essentially just a set of source directories containing source files. For example, when you apply the `c` plugin and define a library called `helloworld`, Gradle will define, by default, a source set containing the C source files in the `src/helloworld/c` directory. It will use these source files to build the `helloworld` library. This is described in more detail below. For each component, Gradle defines one or more _binaries_ as output. To build a binary, Gradle will take the source files defined for the component, compile them as appropriate for the source language, and link the result into a binary file. For an executable component, Gradle can produce executable binary files. For a library component, Gradle can produce both static and shared library binary files. For example, when you define a library called `helloworld` and build on Linux, Gradle will, by default, produce `libhelloworld.so` and `libhelloworld.a` binaries. In many cases, more than one binary can be produced for a component. These binaries may vary based on the tool chain used to build, the compiler/linker flags supplied, the dependencies provided, or additional source files provided. Each native binary produced for a component is referred to as a _variant_. Binary variants are discussed in detail below. [[sec:parallel_compilation]] == Parallel Compilation Gradle uses the single build worker pool to concurrently compile and link native components, by default. No special configuration is required to enable concurrent building. By default, the worker pool size is determined by the number of available processors on the build machine (as reported to the build JVM). To explicitly set the number of workers use the `--max-workers` command-line option or `org.gradle.workers.max` system property. There is generally no need to change this setting from its default. The build worker pool is shared across all build tasks. This means that when using <>, the maximum number of concurrent individual compilation operations does not increase. For example, if the build machine has 4 processing cores and 10 projects are compiling in parallel, Gradle will only use 4 total workers, not 40. [[sec:building_a_library]] == Building a library To build either a static or shared native library, you define a library component in the `components` container. The following sample defines a library called `hello`: === Example: Defining a library component [source.multi-language-sample,groovy] .build.gradle ---- include::{samplesPath}/native-binaries/c/build.gradle[tag=libraries] ---- A library component is represented using link:{javadocPath}/org/gradle/nativeplatform/NativeLibrarySpec.html[NativeLibrarySpec]. Each library component can produce at least one shared library binary (link:{javadocPath}/org/gradle/nativeplatform/SharedLibraryBinarySpec.html[SharedLibraryBinarySpec]) and at least one static library binary (link:{javadocPath}/org/gradle/nativeplatform/StaticLibraryBinarySpec.html[StaticLibraryBinarySpec]). [[sec:building_an_executable]] == Building an executable To build a native executable, you define an executable component in the `components` container. The following sample defines an executable called `main`: === Example: Defining executable components [source.multi-language-sample,groovy] .build.gradle ---- include::{samplesPath}/native-binaries/c/build.gradle[tag=executables] ---- An executable component is represented using link:{javadocPath}/org/gradle/nativeplatform/NativeExecutableSpec.html[NativeExecutableSpec]. Each executable component can produce at least one executable binary (link:{javadocPath}/org/gradle/nativeplatform/NativeExecutableBinarySpec.html[NativeExecutableBinarySpec]). For each component defined, Gradle adds a link:{javadocPath}/org/gradle/language/base/FunctionalSourceSet.html[FunctionalSourceSet] with the same name. Each of these functional source sets will contain a language-specific source set for each of the languages supported by the project. [[sec:dependents]] == Assembling or building dependents Sometimes, you may need to _assemble_ (compile and link) or _build_ (compile, link and test) a component or binary and its _dependents_ (things that depend upon the component or binary). The native software model provides tasks that enable this capability. First, the _dependent components_ report gives insight about the relationships between each component. Second, the _build and assemble dependents_ tasks allow you to assemble or build a component and its dependents in one step. In the following example, the build file defines `OpenSSL` as a dependency of `libUtil` and `libUtil` as a dependency of `LinuxApp` and `WindowsApp`. Test suites are treated similarly. Dependents can be thought of as reverse dependencies. .Dependent Components Example image::nativeDependents.png[] [NOTE] ==== By following the dependencies backwards, you can see `LinuxApp` and `WindowsApp` are _dependents_ of `libUtil`. When `libUtil` is changed, Gradle will need to recompile or relink `LinuxApp` and `WindowsApp`. ==== When you _assemble_ dependents of a component, the component and all of its dependents are compiled and linked, including any test suite binaries. Gradle's up-to-date checks are used to only compile or link if something has changed. For instance, if you have changed source files in a way that do not affect the headers of your project, Gradle will be able to skip compilation for dependent components and only need to re-link with the new library. Tests are not run when assembling a component. When you _build_ dependents of a component, the component and all of its dependent binaries are compiled, linked _and checked_. Checking components means running any <<#sec:check_tasks,check task>> including executing any test suites, so tests _are_ run when building a component. In the following sections, we will demonstrate the usage of the `assembleDependents\\*`, `buildDependents*` and `dependentComponents` tasks with a sample build that contains a CUnit test suite. The build script for the sample is the following: === Example: Sample build [source.multi-language-sample,groovy] .build.gradle ---- include::{samplesPath}/native-binaries/cunit/build.gradle[tag=terse-example] ---- NOTE: The code for this example can be found at **`samples/native-binaries/cunit`** in the ‘-all’ distribution of Gradle. [[sec:dependents_report]] === Dependent components report Gradle provides a report that you can run from the command-line that shows a graph of components in your project and components that depend upon them. The following is an example of running `gradle dependentComponents` on the sample project: === Example: Dependent components report .Output of **`gradle dependentComponents`** ---- > gradle dependentComponents include::{samplesPath}/native-binaries/cunit/dependentComponentsReport.out[] ---- [NOTE] ==== See link:{groovyDslPath}/org.gradle.api.reporting.dependents.DependentComponentsReport.html[DependentComponentsReport] API documentation for more details. ==== By default, non-buildable binaries and test suites are hidden from the report. The `dependentComponents` task provides options that allow you to see all dependents by using the `--all` option: === Example: Dependent components report .Output of **`gradle dependentComponents --all`** ---- > gradle dependentComponents --all include::{samplesPath}/native-binaries/cunit/dependentComponentsReportAll.out[] ---- Here is the corresponding report for the `operators` component, showing dependents of all its binaries: === Example: Report of components that depends on the operators component .Output of **`gradle dependentComponents --component operators`** ---- > gradle dependentComponents --component operators include::{samplesPath}/native-binaries/cunit/assembleDependentComponentsReport.out[] ---- Here is the corresponding report for the `operators` component, showing dependents of all its binaries, including test suites: === Example: Report of components that depends on the operators component, including test suites .Output of **`gradle dependentComponents --test-suites --component operators`** ---- > gradle dependentComponents --test-suites --component operators include::{samplesPath}/native-binaries/cunit/buildDependentComponentsReport.out[] ---- [[sec:assemble_dependents]] === Assembling dependents For each link:{javadocPath}/org/gradle/nativeplatform/NativeBinarySpec.html[NativeBinarySpec], Gradle will create a task named `assembleDependents__${component.name}${binary.variant}__` that _assembles_ (compile and link) the binary and all of its dependent binaries. For each link:{javadocPath}/org/gradle/nativeplatform/NativeComponentSpec.html[NativeComponentSpec], Gradle will create a task named `assembleDependents__${component.name}__` that _assembles_ all the binaries of the component and all of their dependent binaries. For example, to assemble the dependents of the ""passing"" flavor of the ""static"" library binary of the ""operators"" component, you would run the `assembleDependentsOperatorsPassingStaticLibrary` task: === Example: Assemble components that depends on the passing/static binary of the operators component .Output of **`gradle assembleDependentsOperatorsPassingStaticLibrary --max-workers=1`** ---- > gradle assembleDependentsOperatorsPassingStaticLibrary --max-workers=1 include::{samplesPath}/native-binaries/cunit/assembleDependentComponents.out[] ---- In the output above, the targeted binary gets assembled as well as the test suite binary that depends on it. You can also assemble _all_ of the dependents of a component (i.e. of all its binaries/variants) using the corresponding component task, e.g. `assembleDependentsOperators`. This is useful if you have many combinations of build types, flavors and platforms and want to assemble all of them. [[sec:build_dependents]] === Building dependents For each link:{javadocPath}/org/gradle/nativeplatform/NativeBinarySpec.html[NativeBinarySpec], Gradle will create a task named `buildDependents__${component.name}${binary.variant}__` that _builds_ (compile, link and check) the binary and all of its dependent binaries. For each link:{javadocPath}/org/gradle/nativeplatform/NativeComponentSpec.html[NativeComponentSpec], Gradle will create a task named `buildDependents__${component.name}__` that _builds_ all the binaries of the component and all of their dependent binaries. For example, to build the dependents of the ""passing"" flavor of the ""static"" library binary of the ""operators"" component, you would run the `buildDependentsOperatorsPassingStaticLibrary` task: === Example: Build components that depends on the passing/static binary of the operators component .Output of **`gradle buildDependentsOperatorsPassingStaticLibrary --max-workers=1`** ---- > gradle buildDependentsOperatorsPassingStaticLibrary --max-workers=1 include::{samplesPath}/native-binaries/cunit/buildDependentComponents.out[] ---- In the output above, the targeted binary as well as the test suite binary that depends on it are built and the test suite has run. You can also build _all_ of the dependents of a component (i.e. of all its binaries/variants) using the corresponding component task, e.g. `buildDependentsOperators`. [[sec:native_tasks]] == Tasks For each link:{javadocPath}/org/gradle/nativeplatform/NativeBinarySpec.html[NativeBinarySpec] that can be produced by a build, a single _lifecycle task_ is constructed that can be used to create that binary, together with a set of other tasks that do the actual work of compiling, linking or assembling the binary. `__${component.name}__Executable`:: Component Type;; link:{javadocPath}/org/gradle/nativeplatform/NativeExecutableSpec.html[NativeExecutableSpec] Native Binary Type;; link:{javadocPath}/org/gradle/nativeplatform/NativeExecutableBinarySpec.html[NativeExecutableBinarySpec] Location of created binary;; `__${project.buildDir}__/exe/__${component.name}__/__${component.name}__` `__${component.name}__SharedLibrary`:: Component Type;; link:{javadocPath}/org/gradle/nativeplatform/NativeLibrarySpec.html[NativeLibrarySpec] Native Binary Type;; link:{javadocPath}/org/gradle/nativeplatform/SharedLibraryBinarySpec.html[SharedLibraryBinarySpec] Location of created binary;; `__${project.buildDir}__/libs/__${component.name}__/shared/lib__${component.name}__.so` `__${component.name}__StaticLibrary`:: Component Type;; link:{javadocPath}/org/gradle/nativeplatform/NativeLibrarySpec.html[NativeLibrarySpec] Native Binary Type;; link:{javadocPath}/org/gradle/nativeplatform/StaticLibraryBinarySpec.html[StaticLibraryBinarySpec] Location of created binary;; `__${project.buildDir}__/libs/__${component.name}__/static/__${component.name}__.a` [[sec:check_tasks]] === Check tasks For each link:{javadocPath}/org/gradle/nativeplatform/NativeBinarySpec.html[NativeBinarySpec] that can be produced by a build, a single _check task_ is constructed that can be used to assemble and check that binary. `check__${component.name}__Executable`:: Component Type;; link:{javadocPath}/org/gradle/nativeplatform/NativeExecutableSpec.html[NativeExecutableSpec] Native Binary Type;; link:{javadocPath}/org/gradle/nativeplatform/NativeExecutableBinarySpec.html[NativeExecutableBinarySpec] `check__${component.name}__SharedLibrary`:: Component Type;; link:{javadocPath}/org/gradle/nativeplatform/NativeLibrarySpec.html[NativeLibrarySpec] Native Binary Type;; link:{javadocPath}/org/gradle/nativeplatform/SharedLibraryBinarySpec.html[SharedLibraryBinarySpec] `check__${component.name}__StaticLibrary`:: Component Type;; link:{javadocPath}/org/gradle/nativeplatform/NativeLibrarySpec.html[NativeLibrarySpec] Native Binary Type;; link:{javadocPath}/org/gradle/nativeplatform/SharedLibraryBinarySpec.html[SharedLibraryBinarySpec] The built-in `check` task depends on all the _check tasks_ for binaries in the project. Without either <<#native_binaries:cunit,CUnit>> or <<#native_binaries:google_test,GoogleTest>> plugins, the binary check task only depends on the _lifecycle task_ that assembles the binary, see <<#sec:native_tasks,Native tasks>>. When the <<#native_binaries:cunit,CUnit>> or <<#native_binaries:google_test,GoogleTest>> plugins are applied, the task that executes the test suites for a component are automatically wired to the appropriate _check task_. You can also add custom check tasks as follows: === Example: Adding a custom check task [source.multi-language-sample,groovy] .build.gradle ---- include::{samplesPath}/native-binaries/custom-check/build.gradle[tag=custom-check] ---- NOTE: The code for this example can be found at **`samples/native-binaries/custom-check`** in the ‘-all’ distribution of Gradle. Now, running `check` or any of the _check tasks_ for the `hello` binaries will run the custom check task: === Example: Running checks for a given binary .Output of **`gradle checkHelloSharedLibrary`** ---- > gradle checkHelloSharedLibrary include::{samplesPath}/native-binaries/custom-check/nativeComponentCustomCheckOutput.out[] ---- [[sec:working_with_shared_libraries]] === Working with shared libraries For each executable binary produced, the `cpp` plugin provides an `install${binary.name}` task, which creates a development install of the executable, along with the shared libraries it requires. This allows you to run the executable without needing to install the shared libraries in their final locations. [[sec:finding_out_more_about_your_project]] == Finding out more about your project Gradle provides a report that you can run from the command-line that shows some details about the components and binaries that your project produces. To use this report, just run `gradle components`. Below is an example of running this report for one of the sample projects: === Example: The components report .Output of **`gradle components`** ---- > gradle components include::{samplesPath}/native-binaries/cpp/nativeComponentReport.out[] ---- [[native_binaries:languages]] == Language support Presently, Gradle supports building native software from any combination of source languages listed below. A native binary project will contain one or more named `FunctionalSourceSet` instances (eg 'main', 'test', etc), each of which can contain ``LanguageSourceSet``s containing source files, one for each language. * C * C++ * Objective-C * Objective-C++ * Assembly * Windows resources [[sec:cpp_sources]] === C++ sources C++ language support is provided by means of the `'cpp'` plugin. === Example: The 'cpp' plugin [source.multi-language-sample,groovy] .build.gradle ---- include::{samplesPath}/native-binaries/cpp/build.gradle[tag=apply-plugin] ---- $$C++$$ sources to be included in a native binary are provided via a link:{groovyDslPath}/org.gradle.language.cpp.CppSourceSet.html[CppSourceSet], which defines a set of C++ source files and optionally a set of exported header files (for a library). By default, for any named component the link:{groovyDslPath}/org.gradle.language.cpp.CppSourceSet.html[CppSourceSet] contains `.cpp` source files in `src/${name}/cpp`, and header files in `src/${name}/headers`. While the `cpp` plugin defines these default locations for each link:{groovyDslPath}/org.gradle.language.cpp.CppSourceSet.html[CppSourceSet], it is possible to extend or override these defaults to allow for a different project layout. === Example: C++ source set [source.multi-language-sample,groovy,indent=0] .build.gradle ---- include::{samplesPath}/native-binaries/custom-layout/build.gradle[tag=cpp-sources] ---- For a library named 'main', header files in `src/main/headers` are considered the ""public"" or ""exported"" headers. Header files that should not be exported should be placed inside the `src/main/cpp` directory (though be aware that such header files should always be referenced in a manner relative to the file including them). [[sec:c_sources]] === C sources C language support is provided by means of the `'c'` plugin. === Example: The 'c' plugin [source.multi-language-sample,groovy] .build.gradle ---- include::{samplesPath}/native-binaries/c/build.gradle[tag=apply-plugin] ---- C sources to be included in a native binary are provided via a link:{groovyDslPath}/org.gradle.language.c.CSourceSet.html[CSourceSet], which defines a set of C source files and optionally a set of exported header files (for a library). By default, for any named component the link:{groovyDslPath}/org.gradle.language.c.CSourceSet.html[CSourceSet] contains `.c` source files in `src/${name}/c`, and header files in `src/${name}/headers`. While the `c` plugin defines these default locations for each link:{groovyDslPath}/org.gradle.language.c.CSourceSet.html[CSourceSet], it is possible to extend or override these defaults to allow for a different project layout. === Example: C source set [source.multi-language-sample,groovy,indent=0] .build.gradle ---- include::{samplesPath}/native-binaries/custom-layout/build.gradle[tag=c-sources] ---- For a library named 'main', header files in `src/main/headers` are considered the ""public"" or ""exported"" headers. Header files that should not be exported should be placed inside the `src/main/c` directory (though be aware that such header files should always be referenced in a manner relative to the file including them). [[sec:assembler_sources]] === Assembler sources Assembly language support is provided by means of the `'assembler'` plugin. === Example: The 'assembler' plugin [source.multi-language-sample,groovy] .build.gradle ---- include::{samplesPath}/native-binaries/assembler/build.gradle[tag=apply-plugin] ---- Assembler sources to be included in a native binary are provided via a link:{groovyDslPath}/org.gradle.language.assembler.AssemblerSourceSet.html[AssemblerSourceSet], which defines a set of Assembler source files. By default, for any named component the link:{groovyDslPath}/org.gradle.language.assembler.AssemblerSourceSet.html[AssemblerSourceSet] contains `.s` source files under `src/${name}/asm`. [[sec:objectivec_sources]] === Objective-C sources Objective-C language support is provided by means of the `'objective-c'` plugin. === Example: The 'objective-c' plugin [source.multi-language-sample,groovy] .build.gradle ---- include::{samplesPath}/native-binaries/objective-c/build.gradle[tag=apply-plugin] ---- Objective-C sources to be included in a native binary are provided via a link:{groovyDslPath}/org.gradle.language.objectivec.ObjectiveCSourceSet.html[ObjectiveCSourceSet], which defines a set of Objective-C source files. By default, for any named component the link:{groovyDslPath}/org.gradle.language.objectivec.ObjectiveCSourceSet.html[ObjectiveCSourceSet] contains `.m` source files under `src/${name}/objectiveC`. [[sec:objectivecpp_sources]] === Objective-C++ sources Objective-C++ language support is provided by means of the `'objective-cpp'` plugin. === Example: The 'objective-cpp' plugin [source.multi-language-sample,groovy] .build.gradle ---- include::{samplesPath}/native-binaries/objective-cpp/build.gradle[tag=apply-plugin] ---- Objective-C$$++$$ sources to be included in a native binary are provided via a link:{groovyDslPath}/org.gradle.language.objectivecpp.ObjectiveCppSourceSet.html[ObjectiveCppSourceSet], which defines a set of Objective-C++ source files. By default, for any named component the link:{groovyDslPath}/org.gradle.language.objectivecpp.ObjectiveCppSourceSet.html[ObjectiveCppSourceSet] contains `.mm` source files under `src/${name}/objectiveCpp`. [[sec:configuring_the_compiler_assembler_and_linker]] == Configuring the compiler, assembler and linker Each binary to be produced is associated with a set of compiler and linker settings, which include command-line arguments as well as macro definitions. These settings can be applied to all binaries, an individual binary, or selectively to a group of binaries based on some criteria. === Example: Settings that apply to all binaries [source.multi-language-sample,groovy] .build.gradle ---- include::{samplesPath}/native-binaries/cpp/build.gradle[tag=all-binaries] ---- Each binary is associated with a particular link:{javadocPath}/org/gradle/nativeplatform/toolchain/NativeToolChain.html[NativeToolChain], allowing settings to be targeted based on this value. It is easy to apply settings to all binaries of a particular type: === Example: Settings that apply to all shared libraries [source.multi-language-sample,groovy] .build.gradle ---- include::{samplesPath}/native-binaries/c/build.gradle[tag=all-shared-libraries] ---- Furthermore, it is possible to specify settings that apply to all binaries produced for a particular `executable` or `library` component: === Example: Settings that apply to all binaries produced for the 'main' executable component [source.multi-language-sample,groovy] .build.gradle ---- include::{samplesPath}/native-binaries/assembler/build.gradle[tag=assembler-args] ---- The example above will apply the supplied configuration to all `executable` binaries built. Similarly, settings can be specified to target binaries for a component that are of a particular type: eg all shared libraries for the main library component. === Example: Settings that apply only to shared libraries produced for the 'main' library component [source.multi-language-sample,groovy] .build.gradle ---- include::{samplesPath}/native-binaries/cpp-lib/build.gradle[tag=args] ---- [[native_binaries:windows-resources]] == Windows Resources When using the link:{groovyDslPath}/org.gradle.nativeplatform.toolchain.VisualCpp.html[VisualCpp] tool chain, Gradle is able to compile Window Resource (`rc`) files and link them into a native binary. This functionality is provided by the `'windows-resources'` plugin. === Example: The 'windows-resources' plugin [source.multi-language-sample,groovy] .build.gradle ---- include::{samplesPath}/native-binaries/windows-resources/build.gradle[tag=apply-plugin] ---- Windows resources to be included in a native binary are provided via a link:{groovyDslPath}/org.gradle.language.rc.WindowsResourceSet.html[WindowsResourceSet], which defines a set of Windows Resource source files. By default, for any named component the link:{groovyDslPath}/org.gradle.language.rc.WindowsResourceSet.html[WindowsResourceSet] contains `.rc` source files under `src/${name}/rc`. As with other source types, you can configure the location of the windows resources that should be included in the binary. === Example: Configuring the location of Windows resource sources [source.multi-language-sample,groovy,indent=0] .build-resource-only-dll.gradle ---- include::{samplesPath}/native-binaries/windows-resources/build-resource-only-dll.gradle[tag=windows-resource-set] ---- You are able to construct a resource-only library by providing Windows Resource sources with no other language sources, and configure the linker as appropriate: === Example: Building a resource-only dll [source.multi-language-sample,groovy] .build-resource-only-dll.gradle ---- include::{samplesPath}/native-binaries/windows-resources/build-resource-only-dll.gradle[tag=resource-only-library] ---- The example above also demonstrates the mechanism of passing extra command-line arguments to the resource compiler. The `rcCompiler` extension is of type link:{javadocPath}/org/gradle/nativeplatform/PreprocessingTool.html[PreprocessingTool]. [[sec:library_dependencies]] == Library Dependencies Dependencies for native components are binary libraries that export header files. The header files are used during compilation, with the compiled binary dependency being used during linking and execution. Header files should be organized into subdirectories to prevent clashes of commonly named headers. For instance, if your `mylib` project has a `logging.h` header, it will make it less likely the wrong header is used if you include it as `""mylib/logging.h""` instead of `""logging.h""`. [[sec:dependencies_within_the_same_project]] === Dependencies within the same project A set of sources may depend on header files provided by another binary component within the same project. A common example is a native executable component that uses functions provided by a separate native library component. Such a library dependency can be added to a source set associated with the `executable` component: === Example: Providing a library dependency to the source set [source.multi-language-sample,groovy,indent=0] .build.gradle ---- include::{samplesPath}/native-binaries/cpp/build.gradle[tag=source-library] ---- Alternatively, a library dependency can be provided directly to the `NativeExecutableBinarySpec` for the `executable`. === Example: Providing a library dependency to the binary [source.multi-language-sample,groovy] .build.gradle ---- include::{samplesPath}/native-binaries/custom-layout/build.gradle[tag=binary-library] ---- [[sec:project_dependencies]] === Project Dependencies For a component produced in a different Gradle project, the notation is similar. === Example: Declaring project dependencies [source.multi-language-sample,groovy] .build.gradle ---- include::{samplesPath}/native-binaries/multi-project/build.gradle[tag=project-dependencies] ---- [[native_binaries:preCompiledHeaders]] == Precompiled Headers Precompiled headers are a performance optimization that reduces the cost of compiling widely used headers multiple times. This feature _precompiles_ a header such that the compiled object file can be reused when compiling each source file rather than recompiling the header each time. This support is available for C, C+\\+, Objective-C, and Objective-C++ builds. To configure a precompiled header, first a header file needs to be defined that includes all of the headers that should be precompiled. It must be specified as the first included header in every source file where the precompiled header should be used. It is assumed that this header file, and any headers it contains, make use of header guards so that they can be included in an idempotent manner. If header guards are not used in a header file, it is possible the header could be compiled more than once and could potentially lead to a broken build. === Example: Creating a precompiled header file [source.multi-language-sample,c] .src/hello/headers/pch.h ---- include::{samplesPath}/native-binaries/pre-compiled-headers/src/hello/headers/pch.h[] ---- === Example: Including a precompiled header file in a source file [source.multi-language-sample,cpp] .src/hello/cpp/hello.cpp ---- include::{samplesPath}/native-binaries/pre-compiled-headers/src/hello/cpp/hello.cpp[] ---- Precompiled headers are specified on a source set. Only one precompiled header file can be specified on a given source set and will be applied to all source files that declare it as the first include. If a source files does not include this header file as the first header, the file will be compiled in the normal manner (without making use of the precompiled header object file). The string provided should be the same as that which is used in the ""#include"" directive in the source files. === Example: Configuring a precompiled header [source.multi-language-sample,groovy] .build.gradle ---- include::{samplesPath}/native-binaries/pre-compiled-headers/build.gradle[tag=libraries] ---- A precompiled header must be included in the same way for all files that use it. Usually, this means the header file should exist in the source set ""headers"" directory or in a directory included on the compiler include path. [[native_binaries:variants]] == Native Binary Variants For each executable or library defined, Gradle is able to build a number of different native binary variants. Examples of different variants include debug vs release binaries, 32-bit vs 64-bit binaries, and binaries produced with different custom preprocessor flags. Binaries produced by Gradle can be differentiated on <<#native_binaries:build_type,build type>>, <<#native_binaries:platform,platform>>, and <<#native_binaries:flavor,flavor>>. For each of these 'variant dimensions', it is possible to specify a set of available values as well as target each component at one, some or all of these. For example, a plugin may define a range of support platforms, but you may choose to only target Windows-x86 for a particular component. [[native_binaries:build_type]] === Build types A `build type` determines various non-functional aspects of a binary, such as whether debug information is included, or what optimisation level the binary is compiled with. Typical build types are 'debug' and 'release', but a project is free to define any set of build types. === Example: Defining build types [source.multi-language-sample,groovy] .build.gradle ---- include::{samplesPath}/native-binaries/variants/build.gradle[tag=build-types] ---- If no build types are defined in a project, then a single, default build type called 'debug' is added. For a build type, a Gradle project will typically define a set of compiler/linker flags per tool chain. === Example: Configuring debug binaries [source.multi-language-sample,groovy] .build.gradle ---- include::{samplesPath}/native-binaries/variants/build.gradle[tag=build-type-config] ---- [NOTE] ==== At this stage, it is completely up to the build script to configure the relevant compiler/linker flags for each build type. Future versions of Gradle will automatically include the appropriate debug flags for any 'debug' build type, and may be aware of various levels of optimisation as well. ==== [[native_binaries:platform]] === Platform An executable or library can be built to run on different operating systems and cpu architectures, with a variant being produced for each platform. Gradle defines each OS/architecture combination as a link:{groovyDslPath}/org.gradle.nativeplatform.platform.NativePlatform.html[NativePlatform], and a project may define any number of platforms. If no platforms are defined in a project, then a single, default platform 'current' is added. [NOTE] ==== Presently, a `Platform` consists of a defined operating system and architecture. As we continue to develop the native binary support in Gradle, the concept of Platform will be extended to include things like C-runtime version, Windows SDK, ABI, etc. Sophisticated builds may use the extensibility of Gradle to apply additional attributes to each platform, which can then be queried to specify particular includes, preprocessor macros or compiler arguments for a native binary. ==== === Example: Defining platforms [source.multi-language-sample,groovy] .build.gradle ---- include::{samplesPath}/native-binaries/variants/build.gradle[tag=platforms] ---- For a given variant, Gradle will attempt to find a link:{javadocPath}/org/gradle/nativeplatform/toolchain/NativeToolChain.html[NativeToolChain] that is able to build for the target platform. Available tool chains are searched in the order defined. See the <<#native_binaries:tool_chain,tool chains>> section below for more details. [[native_binaries:flavor]] === Flavor Each component can have a set of named `flavors`, and a separate binary variant can be produced for each flavor. While the `build type` and `target platform` variant dimensions have a defined meaning in Gradle, each project is free to define any number of flavors and apply meaning to them in any way. An example of component flavors might differentiate between 'demo', 'paid' and 'enterprise' editions of the component, where the same set of sources is used to produce binaries with different functions. === Example: Defining flavors [source.multi-language-sample,groovy] .build.gradle ---- include::{samplesPath}/native-binaries/flavors/build.gradle[tag=flavors] ---- In the example above, a library is defined with a 'english' and 'french' flavor. When compiling the 'french' variant, a separate macro is defined which leads to a different binary being produced. If no flavor is defined for a component, then a single default flavor named 'default' is used. [[sec:selecting_the_build_types_platforms_and_flavors_for_a_component]] === Selecting the build types, platforms and flavors for a component For a default component, Gradle will attempt to create a native binary variant for each and every combination of `buildType` and `flavor` defined for the project. It is possible to override this on a per-component basis, by specifying the set of `targetBuildTypes` and/or `targetFlavors`. By default, Gradle will build for the default platform, see <<#native_binaries:platform,above>>, unless specified explicitly on a per-component basis by specifying a set of `targetPlatforms`. === Example: Targeting a component at particular platforms [source.multi-language-sample,groovy] .build.gradle ---- include::{samplesPath}/native-binaries/variants/build.gradle[tag=target-platforms] ---- Here you can see that the link:{groovyDslPath}/org.gradle.nativeplatform.TargetedNativeComponent.html#org.gradle.nativeplatform.TargetedNativeComponent:targetPlatform(java.lang.String)[TargetedNativeComponent.targetPlatform(java.lang.String)] method is used to specify a platform that the `NativeExecutableSpec` named `main` should be built for. A similar mechanism exists for selecting link:{groovyDslPath}/org.gradle.nativeplatform.TargetedNativeComponent.html#org.gradle.nativeplatform.TargetedNativeComponent:targetBuildTypes(java.lang.String++[]++)[TargetedNativeComponent.targetBuildTypes(java.lang.String...)] and link:{groovyDslPath}/org.gradle.nativeplatform.TargetedNativeComponent.html#org.gradle.nativeplatform.TargetedNativeComponent:targetFlavors(java.lang.String++[]++)[TargetedNativeComponent.targetFlavors(java.lang.String...)]. [[sec:building_all_possible_variants]] === Building all possible variants When a set of build types, target platforms, and flavors is defined for a component, a link:{javadocPath}/org/gradle/nativeplatform/NativeBinarySpec.html[NativeBinarySpec] model element is created for every possible combination of these. However, in many cases it is not possible to build a particular variant, perhaps because no tool chain is available to build for a particular platform. If a binary variant cannot be built for any reason, then the link:{javadocPath}/org/gradle/nativeplatform/NativeBinarySpec.html[NativeBinarySpec] associated with that variant will not be `buildable`. It is possible to use this property to create a task to generate all possible variants on a particular machine. === Example: Building all possible variants [source.multi-language-sample,groovy] .build.gradle ---- include::{samplesPath}/native-binaries/tool-chains/build.gradle[tag=buildable] ---- [[native_binaries:tool_chain]] == Tool chains A single build may utilize different tool chains to build variants for different platforms. To this end, the core 'native-binary' plugins will attempt to locate and make available supported tool chains. However, the set of tool chains for a project may also be explicitly defined, allowing additional cross-compilers to be configured as well as allowing the install directories to be specified. [[sec:defining_tool_chains]] === Defining tool chains The supported tool chain types are: * link:{groovyDslPath}/org.gradle.nativeplatform.toolchain.Gcc.html[Gcc] * link:{groovyDslPath}/org.gradle.nativeplatform.toolchain.Clang.html[Clang] * link:{groovyDslPath}/org.gradle.nativeplatform.toolchain.VisualCpp.html[VisualCpp] === Example: Defining tool chains [source.multi-language-sample,groovy] .build.gradle ---- include::{samplesPath}/native-binaries/tool-chains/build.gradle[tag=toolChains] ---- Each tool chain implementation allows for a certain degree of configuration (see the API documentation for more details). [[sec:using_tool_chains]] === Using tool chains It is not necessary or possible to specify the tool chain that should be used to build. For a given variant, Gradle will attempt to locate a link:{javadocPath}/org/gradle/nativeplatform/toolchain/NativeToolChain.html[NativeToolChain] that is able to build for the target platform. Available tool chains are searched in the order defined. [NOTE] ==== When a platform does not define an architecture or operating system, the default target of the tool chain is assumed. So if a platform does not define a value for `operatingSystem`, Gradle will find the first available tool chain that can build for the specified `architecture`. ==== The core Gradle tool chains are able to target the following architectures out of the box. In each case, the tool chain will target the current operating system. See the next section for information on cross-compiling for other operating systems. [cols=""a,a"", options=""header""] |=== | Tool Chain | Architectures | GCC | x86, x86_64 | Clang | x86, x86_64 | Visual C++ | x86, x86_64, ia-64 |=== So for GCC running on linux, the supported target platforms are 'linux/x86' and 'linux/x86_64'. For GCC running on Windows via Cygwin, platforms 'windows/x86' and 'windows/x86_64' are supported. (The Cygwin POSIX runtime is not yet modelled as part of the platform, but will be in the future.) If no target platforms are defined for a project, then all binaries are built to target a default platform named 'current'. This default platform does not specify any `architecture` or `operatingSystem` value, hence using the default values of the first available tool chain. Gradle provides a _hook_ that allows the build author to control the exact set of arguments passed to a tool chain executable. This enables the build author to work around any limitations in Gradle, or assumptions that Gradle makes. The arguments hook should be seen as a 'last-resort' mechanism, with preference given to truly modelling the underlying domain. === Example: Reconfigure tool arguments [source.multi-language-sample,groovy] .build.gradle ---- include::{samplesPath}/native-binaries/tool-chains/build.gradle[tag=withArguments] ---- [[sec:crosscompiling_with_gcc]] === Cross-compiling with GCC Cross-compiling is possible with the link:{groovyDslPath}/org.gradle.nativeplatform.toolchain.Gcc.html[Gcc] and link:{groovyDslPath}/org.gradle.nativeplatform.toolchain.Clang.html[Clang] tool chains, by adding support for additional target platforms. This is done by specifying a target platform for a toolchain. For each target platform a custom configuration can be specified. === Example: Defining target platforms [source.multi-language-sample,groovy] .build.gradle ---- include::{samplesPath}/native-binaries/target-platforms/build.gradle[tag=targetplatforms] ---- [[native_binaries:visual_studio]] == Visual Studio IDE integration Gradle has the ability to generate Visual Studio project and solution files for the native components defined in your build. This ability is added by the `visual-studio` plugin. For a multi-project build, all projects with native components (and the root project) should have this plugin applied. When the `visual-studio` plugin is applied to the root project, a task named `visualStudio` is created, which will generate a Visual Studio solution file containing all components in the build. This solution will include a Visual Studio project for each component, as well as configuring each component to build using Gradle. A task named `openVisualStudio` is also created by the `visual-studio` plugin when the project is the root project. This task generates the Visual Studio solution and then opens the solution in Visual Studio. This means you can simply run `gradlew openVisualStudio` from the root project to generate and open the Visual Studio solution in one convenient step. The content of the generated visual studio files can be modified via API hooks, provided by the `visualStudio` extension. Take a look at the 'visual-studio' sample, or see link:{groovyDslPath}/org.gradle.ide.visualstudio.VisualStudioExtension.html#org.gradle.ide.visualstudio.VisualStudioExtension:projects[VisualStudioExtension.getProjects()] and link:{groovyDslPath}/org.gradle.ide.visualstudio.VisualStudioRootExtension.html#org.gradle.ide.visualstudio.VisualStudioRootExtension:solution[VisualStudioRootExtension.getSolution()] in the API documentation for more details. [[native_binaries:cunit]] == CUnit support The Gradle `cunit` plugin provides support for compiling and executing CUnit tests in your native-binary project. For each link:{javadocPath}/org/gradle/nativeplatform/NativeExecutableSpec.html[NativeExecutableSpec] and link:{javadocPath}/org/gradle/nativeplatform/NativeLibrarySpec.html[NativeLibrarySpec] defined in your project, Gradle will create a matching link:{groovyDslPath}/org.gradle.nativeplatform.test.cunit.CUnitTestSuiteSpec.html[CUnitTestSuiteSpec] component, named `${component.name}Test`. [[sec:cunit_sources]] === CUnit sources Gradle will create a link:{groovyDslPath}/org.gradle.language.c.CSourceSet.html[CSourceSet] named 'cunit' for each link:{groovyDslPath}/org.gradle.nativeplatform.test.cunit.CUnitTestSuiteSpec.html[CUnitTestSuiteSpec] component in the project. This source set should contain the cunit test files for the component under test. Source files can be located in the conventional location (`src/${component.name}Test/cunit`) or can be configured like any other source set. Gradle initialises the CUnit test registry and executes the tests, utilising some generated CUnit launcher sources. Gradle will expect and call a function with the signature `void gradle_cunit_register()` that you can use to configure the actual CUnit suites and tests to execute. === Example: Registering CUnit tests [source.multi-language-sample,c] .suite_operators.c ---- include::{samplesPath}/native-binaries/cunit/src/operatorsTest/c/suite_operators.c[] ---- [NOTE] ==== Due to this mechanism, your CUnit sources may not contain a `main` method since this will clash with the method provided by Gradle. ==== [[sec:building_cunit_executables]] === Building CUnit executables A link:{groovyDslPath}/org.gradle.nativeplatform.test.cunit.CUnitTestSuiteSpec.html[CUnitTestSuiteSpec] component has an associated link:{javadocPath}/org/gradle/nativeplatform/NativeExecutableSpec.html[NativeExecutableSpec] or link:{javadocPath}/org/gradle/nativeplatform/NativeLibrarySpec.html[NativeLibrarySpec] component. For each link:{javadocPath}/org/gradle/nativeplatform/NativeBinarySpec.html[NativeBinarySpec] configured for the main component, a matching link:{groovyDslPath}/org.gradle.nativeplatform.test.cunit.CUnitTestSuiteBinarySpec.html[CUnitTestSuiteBinarySpec] will be configured on the test suite component. These test suite binaries can be configured in a similar way to any other binary instance: === Example: Configuring CUnit tests [source.multi-language-sample,groovy] .build.gradle ---- include::{samplesPath}/native-binaries/cunit/build.gradle[tag=configure-test-binary] ---- [NOTE] ==== Both the CUnit sources provided by your project and the generated launcher require the core CUnit headers and libraries. Presently, this library dependency must be provided by your project for each link:{groovyDslPath}/org.gradle.nativeplatform.test.cunit.CUnitTestSuiteBinarySpec.html[CUnitTestSuiteBinarySpec]. ==== [[sec:running_cunit_tests]] === Running CUnit tests For each link:{groovyDslPath}/org.gradle.nativeplatform.test.cunit.CUnitTestSuiteBinarySpec.html[CUnitTestSuiteBinarySpec], Gradle will create a task to execute this binary, which will run all of the registered CUnit tests. Test results will be found in the `__${build.dir}__/test-results` directory. === Example: Running CUnit tests [source.multi-language-sample,groovy] .build.gradle ---- include::{samplesPath}/native-binaries/cunit/build.gradle[tag=complete-example] ---- .Output of `gradle -q runOperatorsTestFailingCUnitExe` ---- > gradle -q runOperatorsTestFailingCUnitExe include::{samplesPath}/native-binaries/cunit/completeCUnitExample.out[] ---- NOTE: The code for this example can be found at **`samples/native-binaries/cunit`** in the ‘-all’ distribution of Gradle. [NOTE] ==== The current support for CUnit is quite rudimentary. Plans for future integration include: * Allow tests to be declared with Javadoc-style annotations. * Improved HTML reporting, similar to that available for JUnit. * Real-time feedback for test execution. * Support for additional test frameworks. ==== [[native_binaries:google_test]] == GoogleTest support The Gradle `google-test` plugin provides support for compiling and executing GoogleTest tests in your native-binary project. For each link:{javadocPath}/org/gradle/nativeplatform/NativeExecutableSpec.html[NativeExecutableSpec] and link:{javadocPath}/org/gradle/nativeplatform/NativeLibrarySpec.html[NativeLibrarySpec] defined in your project, Gradle will create a matching link:{groovyDslPath}/org.gradle.nativeplatform.test.googletest.GoogleTestTestSuiteSpec.html[GoogleTestTestSuiteSpec] component, named `${component.name}Test`. [[sec:googletest_sources]] === GoogleTest sources Gradle will create a link:{groovyDslPath}/org.gradle.language.cpp.CppSourceSet.html[CppSourceSet] named 'cpp' for each link:{groovyDslPath}/org.gradle.nativeplatform.test.googletest.GoogleTestTestSuiteSpec.html[GoogleTestTestSuiteSpec] component in the project. This source set should contain the GoogleTest test files for the component under test. Source files can be located in the conventional location (`src/${component.name}Test/cpp`) or can be configured like any other source set. [[sec:building_googletest_executables]] === Building GoogleTest executables A link:{groovyDslPath}/org.gradle.nativeplatform.test.googletest.GoogleTestTestSuiteSpec.html[GoogleTestTestSuiteSpec] component has an associated link:{javadocPath}/org/gradle/nativeplatform/NativeExecutableSpec.html[NativeExecutableSpec] or link:{javadocPath}/org/gradle/nativeplatform/NativeLibrarySpec.html[NativeLibrarySpec] component. For each link:{javadocPath}/org/gradle/nativeplatform/NativeBinarySpec.html[NativeBinarySpec] configured for the main component, a matching link:{groovyDslPath}/org.gradle.nativeplatform.test.googletest.GoogleTestTestSuiteBinarySpec.html[GoogleTestTestSuiteBinarySpec] will be configured on the test suite component. These test suite binaries can be configured in a similar way to any other binary instance: === Example: Registering GoogleTest tests [source.multi-language-sample,groovy] .build.gradle ---- include::{samplesPath}/native-binaries/google-test/build.gradle[tag=configure-test-binary] ---- NOTE: The code for this example can be found at **`samples/native-binaries/google-test`** in the ‘-all’ distribution of Gradle. [NOTE] ==== The GoogleTest sources provided by your project require the core GoogleTest headers and libraries. Presently, this library dependency must be provided by your project for each link:{groovyDslPath}/org.gradle.nativeplatform.test.googletest.GoogleTestTestSuiteBinarySpec.html[GoogleTestTestSuiteBinarySpec]. ==== [[sec:running_googletest_tests]] === Running GoogleTest tests For each link:{groovyDslPath}/org.gradle.nativeplatform.test.googletest.GoogleTestTestSuiteBinarySpec.html[GoogleTestTestSuiteBinarySpec], Gradle will create a task to execute this binary, which will run all of the registered GoogleTest tests. Test results will be found in the `__${build.dir}__/test-results` directory. [NOTE] ==== The current support for GoogleTest is quite rudimentary. Plans for future integration include: * Improved HTML reporting, similar to that available for JUnit. * Real-time feedback for test execution. * Support for additional test frameworks. ==== ",12113,False,2317.355330594968,median "// Copyright 2017 the original author or authors. // // Licensed under the Apache License, Version 2.0 (the ""License""); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an ""AS IS"" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. [[native_software]] = Building native software [CAUTION] ==== The https://blog.gradle.org/state-and-future-of-the-gradle-software-model[software model] is being retired and the plugins mentioned in this chapter will eventually be deprecated and removed. We recommend new projects looking to build C++ applications and libraries use the newer <>. ==== The native software plugins add support for building native software components, such as executables or shared libraries, from code written in C++, C and other languages. While many excellent build tools exist for this space of software development, Gradle offers developers its trademark power and flexibility together with dependency management practices more traditionally found in the JVM development space. The native software plugins make use of the Gradle <>. [[sec:native_features]] == Features The native software plugins provide: * Support for building native libraries and applications on Windows, Linux, macOS and other platforms. * Support for several source languages. * Support for building different variants of the same software, for different architectures, operating systems, or for any purpose. * Incremental parallel compilation, precompiled headers. * Dependency management between native software components. * Unit test execution. * Generate Visual studio solution and project files. * Deep integration with various tool chain, including discovery of installed tool chains. [[sec:supported_languages]] == Supported languages The following source languages are currently supported: * C * C++ * Objective-C * Objective-C++ * Assembly * Windows resources [[native-binaries:tool-chain-support]] == Tool chain support Gradle offers the ability to execute the same build using different tool chains. When you build a native binary, Gradle will attempt to locate a tool chain installed on your machine that can build the binary. You can fine tune exactly how this works, see <<#native_binaries:tool_chain,Tool chain support>> for details. The following tool chains are supported: [%header%autowidth,compact] |=== | Operating System | Tool Chain | Notes | Linux | http://gcc.gnu.org/[GCC] | | Linux | http://clang.llvm.org[Clang] | | macOS | XCode | Uses the Clang tool chain bundled with XCode. | Windows | https://visualstudio.microsoft.com/[Visual C++] | Windows XP and later, Visual C++ 2010/2012/2013/2015/2017/2019. | Windows | http://gcc.gnu.org/[GCC] with http://cygwin.com[Cygwin 32 and Cygwin 64] | Windows XP and later. | Windows | http://gcc.gnu.org/[GCC] with http://www.mingw.org/[MinGW] and https://mingw-w64.org/doku.php[MinGW64] | Windows XP and later. |=== The following tool chains are unofficially supported. They generally work fine, but are not tested continuously: [%header%autowidth,compact] |=== | Operating System | Tool Chain | Notes | macOS | http://gcc.gnu.org/[GCC] from Macports | | macOS | http://clang.llvm.org[Clang] from Macports | | UNIX-like | http://gcc.gnu.org/[GCC] | | UNIX-like | http://clang.llvm.org[Clang] | |=== [[sec:tool_chain_installation]] == Tool chain installation [NOTE] ==== Note that if you are using GCC then you currently need to install support for C+\\+, even if you are not building from C++ source. This restriction will be removed in a future Gradle version. ==== To build native software, you will need to have a compatible tool chain installed: [[sec:windows]] === Windows To build on Windows, install a compatible version of Visual Studio. The native plugins will discover the Visual Studio installations and select the latest version. There is no need to mess around with environment variables or batch scripts. This works fine from a Cygwin shell or the Windows command-line. Alternatively, you can install Cygwin with GCC or MinGW. Clang is currently not supported. [[sec:macOS]] === macOS To build on macOS, you should install XCode. The native plugins will discover the XCode installation using the system PATH. The native plugins also work with GCC and Clang bundled with Macports. To use one of the Macports tool chains, you will need to make the tool chain the default using the `port select` command and add Macports to the system PATH. [[sec:linux]] === Linux To build on Linux, install a compatible version of GCC or Clang. The native plugins will discover GCC or Clang using the system PATH. [[sec:native_software_model]] == Native software model The native software model builds on the base Gradle <>. To build native software using Gradle, your project should define one or more _native components_. Each component represents either an executable or a library that Gradle should build. A project can define any number of components. Gradle does not define any components by default. For each component, Gradle defines a _source set_ for each language that the component can be built from. A source set is essentially just a set of source directories containing source files. For example, when you apply the `c` plugin and define a library called `helloworld`, Gradle will define, by default, a source set containing the C source files in the `src/helloworld/c` directory. It will use these source files to build the `helloworld` library. This is described in more detail below. For each component, Gradle defines one or more _binaries_ as output. To build a binary, Gradle will take the source files defined for the component, compile them as appropriate for the source language, and link the result into a binary file. For an executable component, Gradle can produce executable binary files. For a library component, Gradle can produce both static and shared library binary files. For example, when you define a library called `helloworld` and build on Linux, Gradle will, by default, produce `libhelloworld.so` and `libhelloworld.a` binaries. In many cases, more than one binary can be produced for a component. These binaries may vary based on the tool chain used to build, the compiler/linker flags supplied, the dependencies provided, or additional source files provided. Each native binary produced for a component is referred to as a _variant_. Binary variants are discussed in detail below. [[sec:parallel_compilation]] == Parallel Compilation Gradle uses the single build worker pool to concurrently compile and link native components, by default. No special configuration is required to enable concurrent building. By default, the worker pool size is determined by the number of available processors on the build machine (as reported to the build JVM). To explicitly set the number of workers use the `--max-workers` command-line option or `org.gradle.workers.max` system property. There is generally no need to change this setting from its default. The build worker pool is shared across all build tasks. This means that when using <>, the maximum number of concurrent individual compilation operations does not increase. For example, if the build machine has 4 processing cores and 10 projects are compiling in parallel, Gradle will only use 4 total workers, not 40. [[sec:building_a_library]] == Building a library To build either a static or shared native library, you define a library component in the `components` container. The following sample defines a library called `hello`: === Example: Defining a library component [source.multi-language-sample,groovy] .build.gradle ---- include::{snippets-dir}/native-binaries/c/groovy/build.gradle[tag=libraries] ---- A library component is represented using link:{javadocPath}/org/gradle/nativeplatform/NativeLibrarySpec.html[NativeLibrarySpec]. Each library component can produce at least one shared library binary (link:{javadocPath}/org/gradle/nativeplatform/SharedLibraryBinarySpec.html[SharedLibraryBinarySpec]) and at least one static library binary (link:{javadocPath}/org/gradle/nativeplatform/StaticLibraryBinarySpec.html[StaticLibraryBinarySpec]). [[sec:building_an_executable]] == Building an executable To build a native executable, you define an executable component in the `components` container. The following sample defines an executable called `main`: === Example: Defining executable components [source.multi-language-sample,groovy] .build.gradle ---- include::{snippets-dir}/native-binaries/c/groovy/build.gradle[tag=executables] ---- An executable component is represented using link:{javadocPath}/org/gradle/nativeplatform/NativeExecutableSpec.html[NativeExecutableSpec]. Each executable component can produce at least one executable binary (link:{javadocPath}/org/gradle/nativeplatform/NativeExecutableBinarySpec.html[NativeExecutableBinarySpec]). For each component defined, Gradle adds a link:{javadocPath}/org/gradle/language/base/FunctionalSourceSet.html[FunctionalSourceSet] with the same name. Each of these functional source sets will contain a language-specific source set for each of the languages supported by the project. [[sec:dependents]] == Assembling or building dependents Sometimes, you may need to _assemble_ (compile and link) or _build_ (compile, link and test) a component or binary and its _dependents_ (things that depend upon the component or binary). The native software model provides tasks that enable this capability. First, the _dependent components_ report gives insight about the relationships between each component. Second, the _build and assemble dependents_ tasks allow you to assemble or build a component and its dependents in one step. In the following example, the build file defines `OpenSSL` as a dependency of `libUtil` and `libUtil` as a dependency of `LinuxApp` and `WindowsApp`. Test suites are treated similarly. Dependents can be thought of as reverse dependencies. .Dependent Components Example image::{image-dir}/nativeDependents.png[] [NOTE] ==== By following the dependencies backwards, you can see `LinuxApp` and `WindowsApp` are _dependents_ of `libUtil`. When `libUtil` is changed, Gradle will need to recompile or relink `LinuxApp` and `WindowsApp`. ==== When you _assemble_ dependents of a component, the component and all of its dependents are compiled and linked, including any test suite binaries. Gradle's up-to-date checks are used to only compile or link if something has changed. For instance, if you have changed source files in a way that do not affect the headers of your project, Gradle will be able to skip compilation for dependent components and only need to re-link with the new library. Tests are not run when assembling a component. When you _build_ dependents of a component, the component and all of its dependent binaries are compiled, linked _and checked_. Checking components means running any <<#sec:check_tasks,check task>> including executing any test suites, so tests _are_ run when building a component. In the following sections, we will demonstrate the usage of the `assembleDependents\\*`, `buildDependents*` and `dependentComponents` tasks with a sample build that contains a CUnit test suite. The build script for the sample is the following: === Example: Sample build [source.multi-language-sample,groovy] .build.gradle ---- include::{snippets-dir}/native-binaries/cunit/groovy/build.gradle[tag=terse-example] ---- [[sec:dependents_report]] === Dependent components report Gradle provides a report that you can run from the command-line that shows a graph of components in your project and components that depend upon them. The following is an example of running `gradle dependentComponents` on the sample project: === Example: Dependent components report .**`gradle dependentComponents`** 的输出 ---- > gradle dependentComponents include::{snippets-dir}/native-binaries/cunit/tests/dependentComponentsReport.out[] ---- [NOTE] ==== See link:{groovyDslPath}/org.gradle.api.reporting.dependents.DependentComponentsReport.html[DependentComponentsReport] API documentation for more details. ==== By default, non-buildable binaries and test suites are hidden from the report. The `dependentComponents` task provides options that allow you to see all dependents by using the `--all` option: === Example: Dependent components report .**`gradle dependentComponents --all`** 的输出 ---- > gradle dependentComponents --all include::{snippets-dir}/native-binaries/cunit/tests/dependentComponentsReportAll.out[] ---- Here is the corresponding report for the `operators` component, showing dependents of all its binaries: === Example: Report of components that depends on the operators component .**`gradle dependentComponents --component operators`** 的输出 ---- > gradle dependentComponents --component operators include::{snippets-dir}/native-binaries/cunit/tests/assembleDependentComponentsReport.out[] ---- Here is the corresponding report for the `operators` component, showing dependents of all its binaries, including test suites: === Example: Report of components that depends on the operators component, including test suites .**`gradle dependentComponents --test-suites --component operators`** 的输出 ---- > gradle dependentComponents --test-suites --component operators include::{snippets-dir}/native-binaries/cunit/tests/buildDependentComponentsReport.out[] ---- [[sec:assemble_dependents]] === Assembling dependents For each link:{javadocPath}/org/gradle/nativeplatform/NativeBinarySpec.html[NativeBinarySpec], Gradle will create a task named `assembleDependents__${component.name}${binary.variant}__` that _assembles_ (compile and link) the binary and all of its dependent binaries. For each link:{javadocPath}/org/gradle/nativeplatform/NativeComponentSpec.html[NativeComponentSpec], Gradle will create a task named `assembleDependents__${component.name}__` that _assembles_ all the binaries of the component and all of their dependent binaries. For example, to assemble the dependents of the ""passing"" flavor of the ""static"" library binary of the ""operators"" component, you would run the `assembleDependentsOperatorsPassingStaticLibrary` task: === Example: Assemble components that depends on the passing/static binary of the operators component .**`gradle assembleDependentsOperatorsPassingStaticLibrary --max-workers=1`** 的输出 ---- > gradle assembleDependentsOperatorsPassingStaticLibrary --max-workers=1 include::{snippets-dir}/native-binaries/cunit/tests/assembleDependentComponents.out[] ---- In the output above, the targeted binary gets assembled as well as the test suite binary that depends on it. You can also assemble _all_ of the dependents of a component (i.e. of all its binaries/variants) using the corresponding component task, e.g. `assembleDependentsOperators`. This is useful if you have many combinations of build types, flavors and platforms and want to assemble all of them. [[sec:build_dependents]] === Building dependents For each link:{javadocPath}/org/gradle/nativeplatform/NativeBinarySpec.html[NativeBinarySpec], Gradle will create a task named `buildDependents__${component.name}${binary.variant}__` that _builds_ (compile, link and check) the binary and all of its dependent binaries. For each link:{javadocPath}/org/gradle/nativeplatform/NativeComponentSpec.html[NativeComponentSpec], Gradle will create a task named `buildDependents__${component.name}__` that _builds_ all the binaries of the component and all of their dependent binaries. For example, to build the dependents of the ""passing"" flavor of the ""static"" library binary of the ""operators"" component, you would run the `buildDependentsOperatorsPassingStaticLibrary` task: === Example: Build components that depends on the passing/static binary of the operators component .**`gradle buildDependentsOperatorsPassingStaticLibrary --max-workers=1`** 的输出 ---- > gradle buildDependentsOperatorsPassingStaticLibrary --max-workers=1 include::{snippets-dir}/native-binaries/cunit/tests/buildDependentComponents.out[] ---- In the output above, the targeted binary as well as the test suite binary that depends on it are built and the test suite has run. You can also build _all_ of the dependents of a component (i.e. of all its binaries/variants) using the corresponding component task, e.g. `buildDependentsOperators`. [[sec:native_tasks]] == Tasks For each link:{javadocPath}/org/gradle/nativeplatform/NativeBinarySpec.html[NativeBinarySpec] that can be produced by a build, a single _lifecycle task_ is constructed that can be used to create that binary, together with a set of other tasks that do the actual work of compiling, linking or assembling the binary. `__${component.name}__Executable`:: Component Type;; link:{javadocPath}/org/gradle/nativeplatform/NativeExecutableSpec.html[NativeExecutableSpec] Native Binary Type;; link:{javadocPath}/org/gradle/nativeplatform/NativeExecutableBinarySpec.html[NativeExecutableBinarySpec] Location of created binary;; `__${project.buildDir}__/exe/__${component.name}__/__${component.name}__` `__${component.name}__SharedLibrary`:: Component Type;; link:{javadocPath}/org/gradle/nativeplatform/NativeLibrarySpec.html[NativeLibrarySpec] Native Binary Type;; link:{javadocPath}/org/gradle/nativeplatform/SharedLibraryBinarySpec.html[SharedLibraryBinarySpec] Location of created binary;; `__${project.buildDir}__/libs/__${component.name}__/shared/lib__${component.name}__.so` `__${component.name}__StaticLibrary`:: Component Type;; link:{javadocPath}/org/gradle/nativeplatform/NativeLibrarySpec.html[NativeLibrarySpec] Native Binary Type;; link:{javadocPath}/org/gradle/nativeplatform/StaticLibraryBinarySpec.html[StaticLibraryBinarySpec] Location of created binary;; `__${project.buildDir}__/libs/__${component.name}__/static/__${component.name}__.a` [[sec:check_tasks]] === Check tasks For each link:{javadocPath}/org/gradle/nativeplatform/NativeBinarySpec.html[NativeBinarySpec] that can be produced by a build, a single _check task_ is constructed that can be used to assemble and check that binary. `check__${component.name}__Executable`:: Component Type;; link:{javadocPath}/org/gradle/nativeplatform/NativeExecutableSpec.html[NativeExecutableSpec] Native Binary Type;; link:{javadocPath}/org/gradle/nativeplatform/NativeExecutableBinarySpec.html[NativeExecutableBinarySpec] `check__${component.name}__SharedLibrary`:: Component Type;; link:{javadocPath}/org/gradle/nativeplatform/NativeLibrarySpec.html[NativeLibrarySpec] Native Binary Type;; link:{javadocPath}/org/gradle/nativeplatform/SharedLibraryBinarySpec.html[SharedLibraryBinarySpec] `check__${component.name}__StaticLibrary`:: Component Type;; link:{javadocPath}/org/gradle/nativeplatform/NativeLibrarySpec.html[NativeLibrarySpec] Native Binary Type;; link:{javadocPath}/org/gradle/nativeplatform/SharedLibraryBinarySpec.html[SharedLibraryBinarySpec] The built-in `check` task depends on all the _check tasks_ for binaries in the project. Without either <<#native_binaries:cunit,CUnit>> or <<#native_binaries:google_test,GoogleTest>> plugins, the binary check task only depends on the _lifecycle task_ that assembles the binary, see <<#sec:native_tasks,Native tasks>>. When the <<#native_binaries:cunit,CUnit>> or <<#native_binaries:google_test,GoogleTest>> plugins are applied, the task that executes the test suites for a component are automatically wired to the appropriate _check task_. You can also add custom check tasks as follows: === Example: Adding a custom check task [source.multi-language-sample,groovy] .build.gradle ---- include::{snippets-dir}/native-binaries/custom-check/groovy/build.gradle[tag=custom-check] ---- Now, running `check` or any of the _check tasks_ for the `hello` binaries will run the custom check task: === Example: Running checks for a given binary .**`gradle checkHelloSharedLibrary`** 的输出 ---- > gradle checkHelloSharedLibrary include::{snippets-dir}/native-binaries/custom-check/tests/nativeComponentCustomCheckOutput.out[] ---- [[sec:working_with_shared_libraries]] === Working with shared libraries For each executable binary produced, the `cpp` plugin provides an `install${binary.name}` task, which creates a development install of the executable, along with the shared libraries it requires. This allows you to run the executable without needing to install the shared libraries in their final locations. [[sec:finding_out_more_about_your_project]] == Finding out more about your project Gradle provides a report that you can run from the command-line that shows some details about the components and binaries that your project produces. To use this report, just run `gradle components`. Below is an example of running this report for one of the sample projects: === Example: The components report .**`gradle components`** 的输出 ---- > gradle components include::{snippets-dir}/native-binaries/cpp/tests/nativeComponentReport.out[] ---- [[native_binaries:languages]] == Language support Presently, Gradle supports building native software from any combination of source languages listed below. A native binary project will contain one or more named `FunctionalSourceSet` instances (e.g. 'main', 'test', etc), each of which can contain ``LanguageSourceSet``s containing source files, one for each language. * C * C++ * Objective-C * Objective-C++ * Assembly * Windows resources [[sec:cpp_sources]] === C++ sources C++ language support is provided by means of the `'cpp'` plugin. === Example: The 'cpp' plugin [source.multi-language-sample,groovy] .build.gradle ---- include::{snippets-dir}/native-binaries/cpp/groovy/build.gradle[tag=apply-plugin] ---- $$C++$$ sources to be included in a native binary are provided via a link:{groovyDslPath}/org.gradle.language.cpp.CppSourceSet.html[CppSourceSet], which defines a set of C++ source files and optionally a set of exported header files (for a library). By default, for any named component the link:{groovyDslPath}/org.gradle.language.cpp.CppSourceSet.html[CppSourceSet] contains `.cpp` source files in `src/${name}/cpp`, and header files in `src/${name}/headers`. While the `cpp` plugin defines these default locations for each link:{groovyDslPath}/org.gradle.language.cpp.CppSourceSet.html[CppSourceSet], it is possible to extend or override these defaults to allow for a different project layout. === Example: C++ source set [source.multi-language-sample,groovy,indent=0] .build.gradle ---- include::{snippets-dir}/native-binaries/custom-layout/groovy/build.gradle[tag=cpp-sources] ---- For a library named 'main', header files in `src/main/headers` are considered the ""public"" or ""exported"" headers. Header files that should not be exported should be placed inside the `src/main/cpp` directory (though be aware that such header files should always be referenced in a manner relative to the file including them). [[sec:c_sources]] === C sources C language support is provided by means of the `'c'` plugin. === Example: The 'c' plugin [source.multi-language-sample,groovy] .build.gradle ---- include::{snippets-dir}/native-binaries/c/groovy/build.gradle[tag=apply-plugin] ---- C sources to be included in a native binary are provided via a link:{groovyDslPath}/org.gradle.language.c.CSourceSet.html[CSourceSet], which defines a set of C source files and optionally a set of exported header files (for a library). By default, for any named component the link:{groovyDslPath}/org.gradle.language.c.CSourceSet.html[CSourceSet] contains `.c` source files in `src/${name}/c`, and header files in `src/${name}/headers`. While the `c` plugin defines these default locations for each link:{groovyDslPath}/org.gradle.language.c.CSourceSet.html[CSourceSet], it is possible to extend or override these defaults to allow for a different project layout. === Example: C source set [source.multi-language-sample,groovy,indent=0] .build.gradle ---- include::{snippets-dir}/native-binaries/custom-layout/groovy/build.gradle[tag=c-sources] ---- For a library named 'main', header files in `src/main/headers` are considered the ""public"" or ""exported"" headers. Header files that should not be exported should be placed inside the `src/main/c` directory (though be aware that such header files should always be referenced in a manner relative to the file including them). [[sec:assembler_sources]] === Assembler sources Assembly language support is provided by means of the `'assembler'` plugin. === Example: The 'assembler' plugin [source.multi-language-sample,groovy] .build.gradle ---- include::{snippets-dir}/native-binaries/assembler/groovy/build.gradle[tag=apply-plugin] ---- Assembler sources to be included in a native binary are provided via a link:{groovyDslPath}/org.gradle.language.assembler.AssemblerSourceSet.html[AssemblerSourceSet], which defines a set of Assembler source files. By default, for any named component the link:{groovyDslPath}/org.gradle.language.assembler.AssemblerSourceSet.html[AssemblerSourceSet] contains `.s` source files under `src/${name}/asm`. [[sec:objectivec_sources]] === Objective-C sources Objective-C language support is provided by means of the `'objective-c'` plugin. === Example: The 'objective-c' plugin [source.multi-language-sample,groovy] .build.gradle ---- include::{snippets-dir}/native-binaries/objective-c/groovy/build.gradle[tag=apply-plugin] ---- Objective-C sources to be included in a native binary are provided via a link:{groovyDslPath}/org.gradle.language.objectivec.ObjectiveCSourceSet.html[ObjectiveCSourceSet], which defines a set of Objective-C source files. By default, for any named component the link:{groovyDslPath}/org.gradle.language.objectivec.ObjectiveCSourceSet.html[ObjectiveCSourceSet] contains `.m` source files under `src/${name}/objectiveC`. [[sec:objectivecpp_sources]] === Objective-C++ sources Objective-C++ language support is provided by means of the `'objective-cpp'` plugin. === Example: The 'objective-cpp' plugin [source.multi-language-sample,groovy] .build.gradle ---- include::{snippets-dir}/native-binaries/objective-cpp/groovy/build.gradle[tag=apply-plugin] ---- Objective-C$$++$$ sources to be included in a native binary are provided via a link:{groovyDslPath}/org.gradle.language.objectivecpp.ObjectiveCppSourceSet.html[ObjectiveCppSourceSet], which defines a set of Objective-C++ source files. By default, for any named component the link:{groovyDslPath}/org.gradle.language.objectivecpp.ObjectiveCppSourceSet.html[ObjectiveCppSourceSet] contains `.mm` source files under `src/${name}/objectiveCpp`. [[sec:configuring_the_compiler_assembler_and_linker]] == Configuring the compiler, assembler and linker Each binary to be produced is associated with a set of compiler and linker settings, which include command-line arguments as well as macro definitions. These settings can be applied to all binaries, an individual binary, or selectively to a group of binaries based on some criteria. === Example: Settings that apply to all binaries [source.multi-language-sample,groovy] .build.gradle ---- include::{snippets-dir}/native-binaries/cpp/groovy/build.gradle[tag=all-binaries] ---- Each binary is associated with a particular link:{javadocPath}/org/gradle/nativeplatform/toolchain/NativeToolChain.html[NativeToolChain], allowing settings to be targeted based on this value. It is easy to apply settings to all binaries of a particular type: === Example: Settings that apply to all shared libraries [source.multi-language-sample,groovy] .build.gradle ---- include::{snippets-dir}/native-binaries/c/groovy/build.gradle[tag=all-shared-libraries] ---- Furthermore, it is possible to specify settings that apply to all binaries produced for a particular `executable` or `library` component: === Example: Settings that apply to all binaries produced for the 'main' executable component [source.multi-language-sample,groovy] .build.gradle ---- include::{snippets-dir}/native-binaries/assembler/groovy/build.gradle[tag=assembler-args] ---- The example above will apply the supplied configuration to all `executable` binaries built. Similarly, settings can be specified to target binaries for a component that are of a particular type: e.g. all shared libraries for the main library component. === Example: Settings that apply only to shared libraries produced for the 'main' library component [source.multi-language-sample,groovy] .build.gradle ---- include::{snippets-dir}/native-binaries/cpp-lib/groovy/build.gradle[tag=args] ---- [[native_binaries:windows-resources]] == Windows Resources When using the link:{groovyDslPath}/org.gradle.nativeplatform.toolchain.VisualCpp.html[VisualCpp] tool chain, Gradle is able to compile Window Resource (`rc`) files and link them into a native binary. This functionality is provided by the `'windows-resources'` plugin. === Example: The 'windows-resources' plugin [source.multi-language-sample,groovy] .build.gradle ---- include::{snippets-dir}/native-binaries/windows-resources/groovy/build.gradle[tag=apply-plugin] ---- Windows resources to be included in a native binary are provided via a link:{groovyDslPath}/org.gradle.language.rc.WindowsResourceSet.html[WindowsResourceSet], which defines a set of Windows Resource source files. By default, for any named component the link:{groovyDslPath}/org.gradle.language.rc.WindowsResourceSet.html[WindowsResourceSet] contains `.rc` source files under `src/${name}/rc`. As with other source types, you can configure the location of the windows resources that should be included in the binary. === Example: Configuring the location of Windows resource sources [source.multi-language-sample,groovy,indent=0] .build-resource-only-dll.gradle ---- include::{snippets-dir}/native-binaries/windows-resources/groovy/build-resource-only-dll.gradle[tag=windows-resource-set] ---- You are able to construct a resource-only library by providing Windows Resource sources with no other language sources, and configure the linker as appropriate: === Example: Building a resource-only dll [source.multi-language-sample,groovy] .build-resource-only-dll.gradle ---- include::{snippets-dir}/native-binaries/windows-resources/groovy/build-resource-only-dll.gradle[tag=resource-only-library] ---- The example above also demonstrates the mechanism of passing extra command-line arguments to the resource compiler. The `rcCompiler` extension is of type link:{javadocPath}/org/gradle/nativeplatform/PreprocessingTool.html[PreprocessingTool]. [[sec:library_dependencies]] == Library Dependencies Dependencies for native components are binary libraries that export header files. The header files are used during compilation, with the compiled binary dependency being used during linking and execution. Header files should be organized into subdirectories to prevent clashes of commonly named headers. For instance, if your `mylib` project has a `logging.h` header, it will make it less likely the wrong header is used if you include it as `""mylib/logging.h""` instead of `""logging.h""`. [[sec:dependencies_within_the_same_project]] === Dependencies within the same project A set of sources may depend on header files provided by another binary component within the same project. A common example is a native executable component that uses functions provided by a separate native library component. Such a library dependency can be added to a source set associated with the `executable` component: === Example: Providing a library dependency to the source set [source.multi-language-sample,groovy,indent=0] .build.gradle ---- include::{snippets-dir}/native-binaries/cpp/groovy/build.gradle[tag=source-library] ---- Alternatively, a library dependency can be provided directly to the `NativeExecutableBinarySpec` for the `executable`. === Example: Providing a library dependency to the binary [source.multi-language-sample,groovy] .build.gradle ---- include::{snippets-dir}/native-binaries/custom-layout/groovy/build.gradle[tag=binary-library] ---- [[sec:project_dependencies]] === Project Dependencies For a component produced in a different Gradle project, the notation is similar. === Example: Declaring project dependencies [source.multi-language-sample,groovy] .lib/build.gradle ---- include::{snippets-dir}/native-binaries/multi-project/groovy/lib/build.gradle[] ---- [source.multi-language-sample,groovy] .exe/build.gradle ---- include::{snippets-dir}/native-binaries/multi-project/groovy/exe/build.gradle[] ---- [[native_binaries:preCompiledHeaders]] == Precompiled Headers Precompiled headers are a performance optimization that reduces the cost of compiling widely used headers multiple times. This feature _precompiles_ a header such that the compiled object file can be reused when compiling each source file rather than recompiling the header each time. This support is available for C, C+\\+, Objective-C, and Objective-C++ builds. To configure a precompiled header, first a header file needs to be defined that includes all of the headers that should be precompiled. It must be specified as the first included header in every source file where the precompiled header should be used. It is assumed that this header file, and any headers it contains, make use of header guards so that they can be included in an idempotent manner. If header guards are not used in a header file, it is possible the header could be compiled more than once and could potentially lead to a broken build. === Example: Creating a precompiled header file [source.multi-language-sample,c] .src/hello/headers/pch.h ---- include::{snippets-dir}/native-binaries/pre-compiled-headers/groovy/src/hello/headers/pch.h[] ---- === Example: Including a precompiled header file in a source file [source.multi-language-sample,cpp] .src/hello/cpp/hello.cpp ---- include::{snippets-dir}/native-binaries/pre-compiled-headers/groovy/src/hello/cpp/hello.cpp[] ---- Precompiled headers are specified on a source set. Only one precompiled header file can be specified on a given source set and will be applied to all source files that declare it as the first include. If a source files does not include this header file as the first header, the file will be compiled in the normal manner (without making use of the precompiled header object file). The string provided should be the same as that which is used in the ""#include"" directive in the source files. === Example: Configuring a precompiled header [source.multi-language-sample,groovy] .build.gradle ---- include::{snippets-dir}/native-binaries/pre-compiled-headers/groovy/build.gradle[tag=libraries] ---- A precompiled header must be included in the same way for all files that use it. Usually, this means the header file should exist in the source set ""headers"" directory or in a directory included on the compiler include path. [[native_binaries:variants]] == Native Binary Variants For each executable or library defined, Gradle is able to build a number of different native binary variants. Examples of different variants include debug vs release binaries, 32-bit vs 64-bit binaries, and binaries produced with different custom preprocessor flags. Binaries produced by Gradle can be differentiated on <<#native_binaries:build_type,build type>>, <<#native_binaries:platform,platform>>, and <<#native_binaries:flavor,flavor>>. For each of these 'variant dimensions', it is possible to specify a set of available values as well as target each component at one, some or all of these. For example, a plugin may define a range of support platforms, but you may choose to only target Windows-x86 for a particular component. [[native_binaries:build_type]] === Build types A `build type` determines various non-functional aspects of a binary, such as whether debug information is included, or what optimisation level the binary is compiled with. Typical build types are 'debug' and 'release', but a project is free to define any set of build types. === Example: Defining build types [source.multi-language-sample,groovy] .build.gradle ---- include::{snippets-dir}/native-binaries/variants/groovy/build.gradle[tag=build-types] ---- If no build types are defined in a project, then a single, default build type called 'debug' is added. For a build type, a Gradle project will typically define a set of compiler/linker flags per tool chain. === Example: Configuring debug binaries [source.multi-language-sample,groovy] .build.gradle ---- include::{snippets-dir}/native-binaries/variants/groovy/build.gradle[tag=build-type-config] ---- [NOTE] ==== At this stage, it is completely up to the build script to configure the relevant compiler/linker flags for each build type. Future versions of Gradle will automatically include the appropriate debug flags for any 'debug' build type, and may be aware of various levels of optimisation as well. ==== [[native_binaries:platform]] === Platform An executable or library can be built to run on different operating systems and cpu architectures, with a variant being produced for each platform. Gradle defines each OS/architecture combination as a link:{groovyDslPath}/org.gradle.nativeplatform.platform.NativePlatform.html[NativePlatform], and a project may define any number of platforms. If no platforms are defined in a project, then a single, default platform 'current' is added. [NOTE] ==== Presently, a `Platform` consists of a defined operating system and architecture. As we continue to develop the native binary support in Gradle, the concept of Platform will be extended to include things like C-runtime version, Windows SDK, ABI, etc. Sophisticated builds may use the extensibility of Gradle to apply additional attributes to each platform, which can then be queried to specify particular includes, preprocessor macros or compiler arguments for a native binary. ==== === Example: Defining platforms [source.multi-language-sample,groovy] .build.gradle ---- include::{snippets-dir}/native-binaries/variants/groovy/build.gradle[tag=platforms] ---- For a given variant, Gradle will attempt to find a link:{javadocPath}/org/gradle/nativeplatform/toolchain/NativeToolChain.html[NativeToolChain] that is able to build for the target platform. Available tool chains are searched in the order defined. See the <<#native_binaries:tool_chain,tool chains>> section below for more details. [[native_binaries:flavor]] === Flavor Each component can have a set of named `flavors`, and a separate binary variant can be produced for each flavor. While the `build type` and `target platform` variant dimensions have a defined meaning in Gradle, each project is free to define any number of flavors and apply meaning to them in any way. An example of component flavors might differentiate between 'demo', 'paid' and 'enterprise' editions of the component, where the same set of sources is used to produce binaries with different functions. === Example: Defining flavors [source.multi-language-sample,groovy] .build.gradle ---- include::{snippets-dir}/native-binaries/flavors/groovy/build.gradle[tag=flavors] ---- In the example above, a library is defined with a 'english' and 'french' flavor. When compiling the 'french' variant, a separate macro is defined which leads to a different binary being produced. If no flavor is defined for a component, then a single default flavor named 'default' is used. [[sec:selecting_the_build_types_platforms_and_flavors_for_a_component]] === Selecting the build types, platforms and flavors for a component For a default component, Gradle will attempt to create a native binary variant for each and every combination of `buildType` and `flavor` defined for the project. It is possible to override this on a per-component basis, by specifying the set of `targetBuildTypes` and/or `targetFlavors`. By default, Gradle will build for the default platform, see <<#native_binaries:platform,above>>, unless specified explicitly on a per-component basis by specifying a set of `targetPlatforms`. === Example: Targeting a component at particular platforms [source.multi-language-sample,groovy] .build.gradle ---- include::{snippets-dir}/native-binaries/variants/groovy/build.gradle[tag=target-platforms] ---- Here you can see that the link:{groovyDslPath}/org.gradle.nativeplatform.TargetedNativeComponent.html#org.gradle.nativeplatform.TargetedNativeComponent:targetPlatform(java.lang.String)[TargetedNativeComponent.targetPlatform(java.lang.String)] method is used to specify a platform that the `NativeExecutableSpec` named `main` should be built for. A similar mechanism exists for selecting link:{groovyDslPath}/org.gradle.nativeplatform.TargetedNativeComponent.html#org.gradle.nativeplatform.TargetedNativeComponent:targetBuildTypes(java.lang.String++[]++)[TargetedNativeComponent.targetBuildTypes(java.lang.String...)] and link:{groovyDslPath}/org.gradle.nativeplatform.TargetedNativeComponent.html#org.gradle.nativeplatform.TargetedNativeComponent:targetFlavors(java.lang.String++[]++)[TargetedNativeComponent.targetFlavors(java.lang.String...)]. [[sec:building_all_possible_variants]] === Building all possible variants When a set of build types, target platforms, and flavors is defined for a component, a link:{javadocPath}/org/gradle/nativeplatform/NativeBinarySpec.html[NativeBinarySpec] model element is created for every possible combination of these. However, in many cases it is not possible to build a particular variant, perhaps because no tool chain is available to build for a particular platform. If a binary variant cannot be built for any reason, then the link:{javadocPath}/org/gradle/nativeplatform/NativeBinarySpec.html[NativeBinarySpec] associated with that variant will not be `buildable`. It is possible to use this property to create a task to generate all possible variants on a particular machine. === Example: Building all possible variants [source.multi-language-sample,groovy] .build.gradle ---- include::{snippets-dir}/native-binaries/tool-chains/groovy/build.gradle[tag=buildable] ---- [[native_binaries:tool_chain]] == Tool chains A single build may utilize different tool chains to build variants for different platforms. To this end, the core 'native-binary' plugins will attempt to locate and make available supported tool chains. However, the set of tool chains for a project may also be explicitly defined, allowing additional cross-compilers to be configured as well as allowing the install directories to be specified. [[sec:defining_tool_chains]] === Defining tool chains The supported tool chain types are: * link:{groovyDslPath}/org.gradle.nativeplatform.toolchain.Gcc.html[Gcc] * link:{groovyDslPath}/org.gradle.nativeplatform.toolchain.Clang.html[Clang] * link:{groovyDslPath}/org.gradle.nativeplatform.toolchain.VisualCpp.html[VisualCpp] === Example: Defining tool chains [source.multi-language-sample,groovy] .build.gradle ---- include::{snippets-dir}/native-binaries/tool-chains/groovy/build.gradle[tag=toolChains] ---- Each tool chain implementation allows for a certain degree of configuration (see the API documentation for more details). [[sec:using_tool_chains]] === Using tool chains It is not necessary or possible to specify the tool chain that should be used to build. For a given variant, Gradle will attempt to locate a link:{javadocPath}/org/gradle/nativeplatform/toolchain/NativeToolChain.html[NativeToolChain] that is able to build for the target platform. Available tool chains are searched in the order defined. [NOTE] ==== When a platform does not define an architecture or operating system, the default target of the tool chain is assumed. So if a platform does not define a value for `operatingSystem`, Gradle will find the first available tool chain that can build for the specified `architecture`. ==== The core Gradle tool chains are able to target the following architectures out of the box. In each case, the tool chain will target the current operating system. See the next section for information on cross-compiling for other operating systems. [cols=""a,a"", options=""header""] |=== | Tool Chain | Architectures | GCC | x86, x86_64 | Clang | x86, x86_64 | Visual C++ | x86, x86_64, ia-64 |=== So for GCC running on linux, the supported target platforms are 'linux/x86' and 'linux/x86_64'. For GCC running on Windows via Cygwin, platforms 'windows/x86' and 'windows/x86_64' are supported. (The Cygwin POSIX runtime is not yet modelled as part of the platform, but will be in the future.) If no target platforms are defined for a project, then all binaries are built to target a default platform named 'current'. This default platform does not specify any `architecture` or `operatingSystem` value, hence using the default values of the first available tool chain. Gradle provides a _hook_ that allows the build author to control the exact set of arguments passed to a tool chain executable. This enables the build author to work around any limitations in Gradle, or assumptions that Gradle makes. The arguments hook should be seen as a 'last-resort' mechanism, with preference given to truly modelling the underlying domain. === Example: Reconfigure tool arguments [source.multi-language-sample,groovy] .build.gradle ---- include::{snippets-dir}/native-binaries/tool-chains/groovy/build.gradle[tag=withArguments] ---- [[sec:crosscompiling_with_gcc]] === Cross-compiling with GCC Cross-compiling is possible with the link:{groovyDslPath}/org.gradle.nativeplatform.toolchain.Gcc.html[Gcc] and link:{groovyDslPath}/org.gradle.nativeplatform.toolchain.Clang.html[Clang] tool chains, by adding support for additional target platforms. This is done by specifying a target platform for a toolchain. For each target platform a custom configuration can be specified. === Example: Defining target platforms [source.multi-language-sample,groovy] .build.gradle ---- include::{snippets-dir}/native-binaries/target-platforms/groovy/build.gradle[tag=targetplatforms] ---- [[native_binaries:visual_studio]] == Visual Studio IDE integration Gradle has the ability to generate Visual Studio project and solution files for the native components defined in your build. This ability is added by the `visual-studio` plugin. For a multi-project build, all projects with native components (and the root project) should have this plugin applied. When the `visual-studio` plugin is applied to the root project, a task named `visualStudio` is created, which will generate a Visual Studio solution file containing all components in the build. This solution will include a Visual Studio project for each component, as well as configuring each component to build using Gradle. A task named `openVisualStudio` is also created by the `visual-studio` plugin when the project is the root project. This task generates the Visual Studio solution and then opens the solution in Visual Studio. This means you can simply run `gradlew openVisualStudio` from the root project to generate and open the Visual Studio solution in one convenient step. The content of the generated visual studio files can be modified via API hooks, provided by the `visualStudio` extension. Take a look at the 'visual-studio' sample, or see link:{groovyDslPath}/org.gradle.ide.visualstudio.VisualStudioExtension.html#org.gradle.ide.visualstudio.VisualStudioExtension:projects[VisualStudioExtension.getProjects()] and link:{groovyDslPath}/org.gradle.ide.visualstudio.VisualStudioRootExtension.html#org.gradle.ide.visualstudio.VisualStudioRootExtension:solution[VisualStudioRootExtension.getSolution()] in the API documentation for more details. [[native_binaries:cunit]] == CUnit support The Gradle `cunit` plugin provides support for compiling and executing CUnit tests in your native-binary project. For each link:{javadocPath}/org/gradle/nativeplatform/NativeExecutableSpec.html[NativeExecutableSpec] and link:{javadocPath}/org/gradle/nativeplatform/NativeLibrarySpec.html[NativeLibrarySpec] defined in your project, Gradle will create a matching link:{groovyDslPath}/org.gradle.nativeplatform.test.cunit.CUnitTestSuiteSpec.html[CUnitTestSuiteSpec] component, named `${component.name}Test`. [[sec:cunit_sources]] === CUnit sources Gradle will create a link:{groovyDslPath}/org.gradle.language.c.CSourceSet.html[CSourceSet] named 'cunit' for each link:{groovyDslPath}/org.gradle.nativeplatform.test.cunit.CUnitTestSuiteSpec.html[CUnitTestSuiteSpec] component in the project. This source set should contain the cunit test files for the component under test. Source files can be located in the conventional location (`src/${component.name}Test/cunit`) or can be configured like any other source set. Gradle initialises the CUnit test registry and executes the tests, utilising some generated CUnit launcher sources. Gradle will expect and call a function with the signature `void gradle_cunit_register()` that you can use to configure the actual CUnit suites and tests to execute. === Example: Registering CUnit tests [source.multi-language-sample,c] .suite_operators.c ---- include::{snippets-dir}/native-binaries/cunit/groovy/src/operatorsTest/c/suite_operators.c[] ---- [NOTE] ==== Due to this mechanism, your CUnit sources may not contain a `main` method since this will clash with the method provided by Gradle. ==== [[sec:building_cunit_executables]] === Building CUnit executables A link:{groovyDslPath}/org.gradle.nativeplatform.test.cunit.CUnitTestSuiteSpec.html[CUnitTestSuiteSpec] component has an associated link:{javadocPath}/org/gradle/nativeplatform/NativeExecutableSpec.html[NativeExecutableSpec] or link:{javadocPath}/org/gradle/nativeplatform/NativeLibrarySpec.html[NativeLibrarySpec] component. For each link:{javadocPath}/org/gradle/nativeplatform/NativeBinarySpec.html[NativeBinarySpec] configured for the main component, a matching link:{groovyDslPath}/org.gradle.nativeplatform.test.cunit.CUnitTestSuiteBinarySpec.html[CUnitTestSuiteBinarySpec] will be configured on the test suite component. These test suite binaries can be configured in a similar way to any other binary instance: === Example: Configuring CUnit tests [source.multi-language-sample,groovy] .build.gradle ---- include::{snippets-dir}/native-binaries/cunit/groovy/build.gradle[tag=configure-test-binary] ---- [NOTE] ==== Both the CUnit sources provided by your project and the generated launcher require the core CUnit headers and libraries. Presently, this library dependency must be provided by your project for each link:{groovyDslPath}/org.gradle.nativeplatform.test.cunit.CUnitTestSuiteBinarySpec.html[CUnitTestSuiteBinarySpec]. ==== [[sec:running_cunit_tests]] === Running CUnit tests For each link:{groovyDslPath}/org.gradle.nativeplatform.test.cunit.CUnitTestSuiteBinarySpec.html[CUnitTestSuiteBinarySpec], Gradle will create a task to execute this binary, which will run all of the registered CUnit tests. Test results will be found in the `__${build.dir}__/test-results` directory. === Example: Running CUnit tests [source.multi-language-sample,groovy] .build.gradle ---- include::{snippets-dir}/native-binaries/cunit/groovy/build.gradle[tag=complete-example] ---- .`gradle -q runOperatorsTestFailingCUnitExe` 的输出 ---- > gradle -q runOperatorsTestFailingCUnitExe include::{snippets-dir}/native-binaries/cunit/tests/completeCUnitExample.out[] ---- [NOTE] ==== The current support for CUnit is quite rudimentary. Plans for future integration include: * Allow tests to be declared with Javadoc-style annotations. * Improved HTML reporting, similar to that available for JUnit. * Real-time feedback for test execution. * Support for additional test frameworks. ==== [[native_binaries:google_test]] == GoogleTest support The Gradle `google-test` plugin provides support for compiling and executing GoogleTest tests in your native-binary project. For each link:{javadocPath}/org/gradle/nativeplatform/NativeExecutableSpec.html[NativeExecutableSpec] and link:{javadocPath}/org/gradle/nativeplatform/NativeLibrarySpec.html[NativeLibrarySpec] defined in your project, Gradle will create a matching link:{groovyDslPath}/org.gradle.nativeplatform.test.googletest.GoogleTestTestSuiteSpec.html[GoogleTestTestSuiteSpec] component, named `${component.name}Test`. [[sec:googletest_sources]] === GoogleTest sources Gradle will create a link:{groovyDslPath}/org.gradle.language.cpp.CppSourceSet.html[CppSourceSet] named 'cpp' for each link:{groovyDslPath}/org.gradle.nativeplatform.test.googletest.GoogleTestTestSuiteSpec.html[GoogleTestTestSuiteSpec] component in the project. This source set should contain the GoogleTest test files for the component under test. Source files can be located in the conventional location (`src/${component.name}Test/cpp`) or can be configured like any other source set. [[sec:building_googletest_executables]] === Building GoogleTest executables A link:{groovyDslPath}/org.gradle.nativeplatform.test.googletest.GoogleTestTestSuiteSpec.html[GoogleTestTestSuiteSpec] component has an associated link:{javadocPath}/org/gradle/nativeplatform/NativeExecutableSpec.html[NativeExecutableSpec] or link:{javadocPath}/org/gradle/nativeplatform/NativeLibrarySpec.html[NativeLibrarySpec] component. For each link:{javadocPath}/org/gradle/nativeplatform/NativeBinarySpec.html[NativeBinarySpec] configured for the main component, a matching link:{groovyDslPath}/org.gradle.nativeplatform.test.googletest.GoogleTestTestSuiteBinarySpec.html[GoogleTestTestSuiteBinarySpec] will be configured on the test suite component. These test suite binaries can be configured in a similar way to any other binary instance: === Example: Registering GoogleTest tests [source.multi-language-sample,groovy] .build.gradle ---- include::{snippets-dir}/native-binaries/google-test/groovy/build.gradle[tag=configure-test-binary] ---- [NOTE] ==== The GoogleTest sources provided by your project require the core GoogleTest headers and libraries. Presently, this library dependency must be provided by your project for each link:{groovyDslPath}/org.gradle.nativeplatform.test.googletest.GoogleTestTestSuiteBinarySpec.html[GoogleTestTestSuiteBinarySpec]. ==== [[sec:running_googletest_tests]] === Running GoogleTest tests For each link:{groovyDslPath}/org.gradle.nativeplatform.test.googletest.GoogleTestTestSuiteBinarySpec.html[GoogleTestTestSuiteBinarySpec], Gradle will create a task to execute this binary, which will run all of the registered GoogleTest tests. Test results will be found in the `__${build.dir}__/test-results` directory. [NOTE] ==== The current support for GoogleTest is quite rudimentary. Plans for future integration include: * Improved HTML reporting, similar to that available for JUnit. * Real-time feedback for test execution. * Support for additional test frameworks. ==== ",12216,False,2330.3936620140908,median "//// AUTOGENERATED FILE - this file was generated via https://github.com/jboss-container-images/jboss-kie-modules/tree/master/tools/gen-template-doc/tools/gen_template_docs.py. Changes to .adoc or HTML files may be overwritten! Please change the generator or the input template (https://github.com/jboss-container-images/jboss-kie-modules/tree/master/tools/gen-template-doc/*.in) //// [id='rhdm74-authoring-ha-ref'] = rhdm74-authoring-ha.yaml template Application template for a HA persistent authoring environment, for Red Hat Decision Manager 7.4 == Parameters Templates allow you to define parameters which take on a value. That value is then substituted wherever the parameter is referenced. References can be defined in any text field in the objects list field. Refer to the https://access.redhat.com/documentation/en-us/openshift_container_platform/3.11/html-single/developer_guide/#dev-guide-templates[Openshift documentation] for more information. |======================================================================= |Variable name |Image Environment Variable |Description |Example value |Required |`APPLICATION_NAME` | -- | The name for the application. | myapp | True |`KIE_ADMIN_USER` | `KIE_ADMIN_USER` | KIE administrator username. | adminUser | False |`KIE_ADMIN_PWD` | `KIE_ADMIN_PWD` | KIE administrator password. | -- | False |`KIE_SERVER_CONTROLLER_USER` | `KIE_SERVER_CONTROLLER_USER` | KIE server controller username. (Sets the org.kie.server.controller.user system property) | controllerUser | False |`KIE_SERVER_CONTROLLER_PWD` | `KIE_SERVER_CONTROLLER_PWD` | KIE server controller password. (Sets the org.kie.server.controller.pwd system property) | -- | False |`KIE_SERVER_CONTROLLER_TOKEN` | `KIE_SERVER_CONTROLLER_TOKEN` | KIE server controller token for bearer authentication. (Sets the org.kie.server.controller.token system property) | -- | False |`KIE_SERVER_USER` | `KIE_SERVER_USER` | KIE server username. (Sets the org.kie.server.user system property) | executionUser | False |`KIE_SERVER_PWD` | `KIE_SERVER_PWD` | KIE server password. (Sets the org.kie.server.pwd system property) | -- | False |`KIE_SERVER_BYPASS_AUTH_USER` | `KIE_SERVER_BYPASS_AUTH_USER` | Allows the KIE server to bypass the authenticated user for task related operations e.g. queries. (Sets the org.kie.server.bypass.auth.user system property) | false | False |`KIE_SERVER_MODE` | `KIE_SERVER_MODE` | The KIE Server mode. Valid values are 'DEVELOPMENT' or 'PRODUCTION'. In production mode, you can not deploy SNAPSHOT versions of artifacts on the KIE server and can not change the version of an artifact in an existing container. (Sets the org.kie.server.mode system property). | `DEVELOPMENT` | False |`KIE_MBEANS` | `KIE_MBEANS` | KIE server mbeans enabled/disabled. (Sets the kie.mbeans and kie.scanner.mbeans system properties) | enabled | False |`DROOLS_SERVER_FILTER_CLASSES` | `DROOLS_SERVER_FILTER_CLASSES` | KIE server class filtering. (Sets the org.drools.server.filter.classes system property) | true | False |`PROMETHEUS_SERVER_EXT_DISABLED` | `PROMETHEUS_SERVER_EXT_DISABLED` | If set to false, the prometheus server extension will be enabled. (Sets the org.kie.prometheus.server.ext.disabled system property) | false | False |`DECISION_CENTRAL_HOSTNAME_HTTP` | `HOSTNAME_HTTP` | Custom hostname for http service route for Decision Central. Leave blank for default hostname, e.g.: insecure--rhdmcentr-. | -- | False |`DECISION_CENTRAL_HOSTNAME_HTTPS` | `HOSTNAME_HTTPS` | Custom hostname for https service route for Decision Central. Leave blank for default hostname, e.g.: -rhdmcentr-. | -- | False |`KIE_SERVER_HOSTNAME_HTTP` | `HOSTNAME_HTTP` | Custom hostname for http service route for KIE Server. Leave blank for default hostname, e.g.: insecure--kieserver-. | -- | False |`KIE_SERVER_HOSTNAME_HTTPS` | `HOSTNAME_HTTPS` | Custom hostname for https service route for KIE Server. Leave blank for default hostname, e.g.: -kieserver-. | -- | False |`DECISION_CENTRAL_HTTPS_SECRET` | -- | The name of the secret containing the keystore file for Decision Central. | decisioncentral-app-secret | True |`DECISION_CENTRAL_HTTPS_KEYSTORE` | `HTTPS_KEYSTORE` | The name of the keystore file within the secret for Decision Central. | keystore.jks | False |`DECISION_CENTRAL_HTTPS_NAME` | `HTTPS_NAME` | The name associated with the server certificate for Decision Central. | jboss | False |`DECISION_CENTRAL_HTTPS_PASSWORD` | `HTTPS_PASSWORD` | The password for the keystore and certificate for Decision Central. | mykeystorepass | False |`KIE_SERVER_HTTPS_SECRET` | -- | The name of the secret containing the keystore file for KIE Server. | kieserver-app-secret | True |`KIE_SERVER_HTTPS_KEYSTORE` | `HTTPS_KEYSTORE` | The name of the keystore file within the secret for KIE Server. | keystore.jks | False |`KIE_SERVER_HTTPS_NAME` | `HTTPS_NAME` | The name associated with the server certificate for KIE Server. | jboss | False |`KIE_SERVER_HTTPS_PASSWORD` | `HTTPS_PASSWORD` | The password for the keystore and certificate for KIE Server. | mykeystorepass | False |`APPFORMER_JMS_BROKER_USER` | `APPFORMER_JMS_BROKER_USER` | The username to connect to the JMS broker. | jmsBrokerUser | True |`APPFORMER_JMS_BROKER_PASSWORD` | `APPFORMER_JMS_BROKER_PASSWORD` | The password to connect to the JMS broker. | -- | True |`DATAGRID_IMAGE` | -- | DataGrid image. | registry.redhat.io/jboss-datagrid-7/datagrid73-openshift:1.1 | True |`DATAGRID_MEMORY_LIMIT` | -- | DataGrid Container memory limit. | 512Mi | True |`DATAGRID_VOLUME_CAPACITY` | -- | Size of the persistent storage for DataGrid's runtime data. | 1Gi | True |`AMQ_SCALEDOWN_CONTROLLER_IMAGE_STREAM_NAMESPACE` | -- | Namespace in which the ImageStream for the AMQ Scaledown Controller image is installed. Default is ""openshift"". | openshift | True |`AMQ_SCALEDOWN_CONTROLLER_IMAGE_STREAM_NAME` | -- | The name of the image stream to use for the AMQ Scaledown Controller. Default is ""amq-broker-72-scaledown-controller-openshift"". | amq-broker-72-scaledown-controller-openshift | True |`AMQ_SCALEDOWN_CONTROLLER_IMAGE_STREAM_TAG` | -- | The AMQ scaledown controller image stream tag. Default is ""1.0"". | 1.0 | True |`AMQ_BROKER_IMAGE` | -- | AMQ Broker Image | registry.redhat.io/amq-broker-7/amq-broker-73-openshift:7.3 | True |`AMQ_ROLE` | -- | User role for standard broker user. | admin | True |`AMQ_NAME` | -- | The name of the broker. | broker | True |`AMQ_GLOBAL_MAX_SIZE` | -- | Specifies the maximum amount of memory that message data can consume. If no value is specified, half of the system's memory is allocated. | 10 gb | False |`AMQ_VOLUME_CAPACITY` | -- | Size of persistent storage for AMQ broker volume. | 1Gi | True |`KIE_SERVER_CONTROLLER_OPENSHIFT_GLOBAL_DISCOVERY_ENABLED` | `KIE_SERVER_CONTROLLER_OPENSHIFT_GLOBAL_DISCOVERY_ENABLED` | If set to true, turns on KIE server global discovery feature (Sets the org.kie.server.controller.openshift.global.discovery.enabled system property) | false | False |`KIE_SERVER_CONTROLLER_OPENSHIFT_PREFER_KIESERVER_SERVICE` | `KIE_SERVER_CONTROLLER_OPENSHIFT_PREFER_KIESERVER_SERVICE` | If OpenShift integration of Business Central is turned on, setting this parameter to true enables connection to KIE Server via an OpenShift internal Service endpoint. (Sets the org.kie.server.controller.openshift.prefer.kieserver.service system property) | true | False |`KIE_SERVER_CONTROLLER_TEMPLATE_CACHE_TTL` | `KIE_SERVER_CONTROLLER_TEMPLATE_CACHE_TTL` | KIE ServerTemplate Cache TTL in milliseconds. (Sets the org.kie.server.controller.template.cache.ttl system property) | 60000 | False |`IMAGE_STREAM_NAMESPACE` | -- | Namespace in which the ImageStreams for Red Hat Middleware images are installed. These ImageStreams are normally installed in the openshift namespace. You should only need to modify this if you installed the ImageStreams in a different namespace/project. | openshift | True |`DECISION_CENTRAL_IMAGE_STREAM_NAME` | -- | The name of the image stream to use for Decision Central. Default is ""rhdm74-decisioncentral-openshift"". | rhdm74-decisioncentral-openshift | True |`KIE_SERVER_IMAGE_STREAM_NAME` | -- | The name of the image stream to use for KIE server. Default is ""rhdm74-kieserver-openshift"". | rhdm74-kieserver-openshift | True |`IMAGE_STREAM_TAG` | -- | A named pointer to an image in an image stream. Default is ""1.0"". | 1.0 | True |`MAVEN_MIRROR_URL` | `MAVEN_MIRROR_URL` | Maven mirror that Decision Central and KIE server must use. If you configure a mirror, this mirror must contain all artifacts that are required for building and deploying your services. | -- | False |`MAVEN_MIRROR_OF` | `MAVEN_MIRROR_OF` | Maven mirror configuration for KIE server. | external:*,!repo-rhdmcentr | False |`MAVEN_REPO_ID` | `MAVEN_REPO_ID` | The id to use for the maven repository. If set, it can be excluded from the optionally configured mirror by adding it to MAVEN_MIRROR_OF. For example: external:*,!repo-rhdmcentr,!repo-custom. If MAVEN_MIRROR_URL is set but MAVEN_MIRROR_ID is not set, an id will be generated randomly, but won't be usable in MAVEN_MIRROR_OF. | repo-custom | False |`MAVEN_REPO_URL` | `MAVEN_REPO_URL` | Fully qualified URL to a Maven repository or service. | http://nexus.nexus-project.svc.cluster.local:8081/nexus/content/groups/public/ | False |`MAVEN_REPO_USERNAME` | `MAVEN_REPO_USERNAME` | Username to access the Maven repository, if required. | -- | False |`MAVEN_REPO_PASSWORD` | `MAVEN_REPO_PASSWORD` | Password to access the Maven repository, if required. | -- | False |`DECISION_CENTRAL_MAVEN_USERNAME` | `KIE_MAVEN_USER` | Username to access the Maven service hosted by Decision Central inside EAP. | mavenUser | True |`DECISION_CENTRAL_MAVEN_PASSWORD` | `KIE_MAVEN_PWD` | Password to access the Maven service hosted by Decision Central inside EAP. | -- | True |`GIT_HOOKS_DIR` | `GIT_HOOKS_DIR` | The directory to use for git hooks, if required. | `/opt/kie/data/git/hooks` | False |`DECISION_CENTRAL_VOLUME_CAPACITY` | -- | Size of the persistent storage for Decision Central's runtime data. | 1Gi | True |`DECISION_CENTRAL_MEMORY_LIMIT` | -- | Decision Central Container memory limit. | 2Gi | False |`KIE_SERVER_MEMORY_LIMIT` | -- | KIE server Container memory limit. | 1Gi | False |`SSO_URL` | `SSO_URL` | RH-SSO URL. | https://rh-sso.example.com/auth | False |`SSO_REALM` | `SSO_REALM` | RH-SSO Realm name. | -- | False |`DECISION_CENTRAL_SSO_CLIENT` | `SSO_CLIENT` | Decision Central RH-SSO Client name. | -- | False |`DECISION_CENTRAL_SSO_SECRET` | `SSO_SECRET` | Decision Central RH-SSO Client Secret. | 252793ed-7118-4ca8-8dab-5622fa97d892 | False |`KIE_SERVER_SSO_CLIENT` | `SSO_CLIENT` | KIE Server RH-SSO Client name. | -- | False |`KIE_SERVER_SSO_SECRET` | `SSO_SECRET` | KIE Server RH-SSO Client Secret. | 252793ed-7118-4ca8-8dab-5622fa97d892 | False |`SSO_USERNAME` | `SSO_USERNAME` | RH-SSO Realm Admin Username used to create the Client if it doesn't exist. | -- | False |`SSO_PASSWORD` | `SSO_PASSWORD` | RH-SSO Realm Admin Password used to create the Client. | -- | False |`SSO_DISABLE_SSL_CERTIFICATE_VALIDATION` | `SSO_DISABLE_SSL_CERTIFICATE_VALIDATION` | RH-SSO Disable SSL Certificate Validation. | false | False |`SSO_PRINCIPAL_ATTRIBUTE` | `SSO_PRINCIPAL_ATTRIBUTE` | RH-SSO Principal Attribute to use as username. | preferred_username | False |`AUTH_LDAP_URL` | `AUTH_LDAP_URL` | LDAP Endpoint to connect for authentication. | ldap://myldap.example.com | False |`AUTH_LDAP_BIND_DN` | `AUTH_LDAP_BIND_DN` | Bind DN used for authentication. | uid=admin,ou=users,ou=exmample,ou=com | False |`AUTH_LDAP_BIND_CREDENTIAL` | `AUTH_LDAP_BIND_CREDENTIAL` | LDAP Credentials used for authentication. | Password | False |`AUTH_LDAP_JAAS_SECURITY_DOMAIN` | `AUTH_LDAP_JAAS_SECURITY_DOMAIN` | The JMX ObjectName of the JaasSecurityDomain used to decrypt the password. | -- | False |`AUTH_LDAP_BASE_CTX_DN` | `AUTH_LDAP_BASE_CTX_DN` | LDAP Base DN of the top-level context to begin the user search. | ou=users,ou=example,ou=com | False |`AUTH_LDAP_BASE_FILTER` | `AUTH_LDAP_BASE_FILTER` | LDAP search filter used to locate the context of the user to authenticate. The input username or userDN obtained from the login module callback is substituted into the filter anywhere a {0} expression is used. A common example for the search filter is (uid={0}). | (uid={0}) | False |`AUTH_LDAP_SEARCH_SCOPE` | `AUTH_LDAP_SEARCH_SCOPE` | The search scope to use. | `SUBTREE_SCOPE` | False |`AUTH_LDAP_SEARCH_TIME_LIMIT` | `AUTH_LDAP_SEARCH_TIME_LIMIT` | The timeout in milliseconds for user or role searches. | 10000 | False |`AUTH_LDAP_DISTINGUISHED_NAME_ATTRIBUTE` | `AUTH_LDAP_DISTINGUISHED_NAME_ATTRIBUTE` | The name of the attribute in the user entry that contains the DN of the user. This may be necessary if the DN of the user itself contains special characters, backslash for example, that prevent correct user mapping. If the attribute does not exist, the entry's DN is used. | distinguishedName | False |`AUTH_LDAP_PARSE_USERNAME` | `AUTH_LDAP_PARSE_USERNAME` | A flag indicating if the DN is to be parsed for the username. If set to true, the DN is parsed for the username. If set to false the DN is not parsed for the username. This option is used together with usernameBeginString and usernameEndString. | true | False |`AUTH_LDAP_USERNAME_BEGIN_STRING` | `AUTH_LDAP_USERNAME_BEGIN_STRING` | Defines the String which is to be removed from the start of the DN to reveal the username. This option is used together with usernameEndString and only taken into account if parseUsername is set to true. | -- | False |`AUTH_LDAP_USERNAME_END_STRING` | `AUTH_LDAP_USERNAME_END_STRING` | Defines the String which is to be removed from the end of the DN to reveal the username. This option is used together with usernameEndString and only taken into account if parseUsername is set to true. | -- | False |`AUTH_LDAP_ROLE_ATTRIBUTE_ID` | `AUTH_LDAP_ROLE_ATTRIBUTE_ID` | Name of the attribute containing the user roles. | memberOf | False |`AUTH_LDAP_ROLES_CTX_DN` | `AUTH_LDAP_ROLES_CTX_DN` | The fixed DN of the context to search for user roles. This is not the DN where the actual roles are, but the DN where the objects containing the user roles are. For example, in a Microsoft Active Directory server, this is the DN where the user account is. | ou=groups,ou=example,ou=com | False |`AUTH_LDAP_ROLE_FILTER` | `AUTH_LDAP_ROLE_FILTER` | A search filter used to locate the roles associated with the authenticated user. The input username or userDN obtained from the login module callback is substituted into the filter anywhere a {0} expression is used. The authenticated userDN is substituted into the filter anywhere a {1} is used. An example search filter that matches on the input username is (member={0}). An alternative that matches on the authenticated userDN is (member={1}). | (memberOf={1}) | False |`AUTH_LDAP_ROLE_RECURSION` | `AUTH_LDAP_ROLE_RECURSION` | The number of levels of recursion the role search will go below a matching context. Disable recursion by setting this to 0. | 1 | False |`AUTH_LDAP_DEFAULT_ROLE` | `AUTH_LDAP_DEFAULT_ROLE` | A role included for all authenticated users | user | False |`AUTH_LDAP_ROLE_NAME_ATTRIBUTE_ID` | `AUTH_LDAP_ROLE_NAME_ATTRIBUTE_ID` | Name of the attribute within the roleCtxDN context which contains the role name. If the roleAttributeIsDN property is set to true, this property is used to find the role object's name attribute. | name | False |`AUTH_LDAP_PARSE_ROLE_NAME_FROM_DN` | `AUTH_LDAP_PARSE_ROLE_NAME_FROM_DN` | A flag indicating if the DN returned by a query contains the roleNameAttributeID. If set to true, the DN is checked for the roleNameAttributeID. If set to false, the DN is not checked for the roleNameAttributeID. This flag can improve the performance of LDAP queries. | false | False |`AUTH_LDAP_ROLE_ATTRIBUTE_IS_DN` | `AUTH_LDAP_ROLE_ATTRIBUTE_IS_DN` | Whether or not the roleAttributeID contains the fully-qualified DN of a role object. If false, the role name is taken from the value of the roleNameAttributeId attribute of the context name. Certain directory schemas, such as Microsoft Active Directory, require this attribute to be set to true. | false | False |`AUTH_LDAP_REFERRAL_USER_ATTRIBUTE_ID_TO_CHECK` | `AUTH_LDAP_REFERRAL_USER_ATTRIBUTE_ID_TO_CHECK` | If you are not using referrals, you can ignore this option. When using referrals, this option denotes the attribute name which contains users defined for a certain role, for example member, if the role object is inside the referral. Users are checked against the content of this attribute name. If this option is not set, the check will always fail, so role objects cannot be stored in a referral tree. | -- | False |`AUTH_ROLE_MAPPER_ROLES_PROPERTIES` | `AUTH_ROLE_MAPPER_ROLES_PROPERTIES` | When present, the RoleMapping Login Module will be configured to use the provided file. This parameter defines the fully-qualified file path and name of a properties file or resource which maps roles to replacement roles. The format is original_role=role1,role2,role3 | -- | False |`AUTH_ROLE_MAPPER_REPLACE_ROLE` | `AUTH_ROLE_MAPPER_REPLACE_ROLE` | Whether to add to the current roles, or replace the current roles with the mapped ones. Replaces if set to true. | -- | False |======================================================================= == Objects The CLI supports various object types. A list of these object types as well as their abbreviations can be found in the https://access.redhat.com/documentation/en-us/openshift_container_platform/3.11/html/cli_reference/cli-reference-basic-cli-operations#object-types[Openshift documentation]. === Services A service is an abstraction which defines a logical set of pods and a policy by which to access them. Refer to the https://cloud.google.com/container-engine/docs/services/[container-engine documentation] for more information. |============= |Service |Port |Name | Description .3+| `${APPLICATION_NAME}-rhdmcentr` |8080 | http .3+| All the Decision Central web server's ports. |8443 | https |8001 | git-ssh .1+| `${APPLICATION_NAME}-rhdmcentr-ping` |8888 | ping .1+| The JGroups ping port for rhdmcentr clustering. .1+| `${APPLICATION_NAME}-datagrid-ping` |8888 | ping .1+| Provides a ping service for clustered applications. .1+| `${APPLICATION_NAME}-datagrid` |11222 | hotrod .1+| Provides a service for accessing the application over Hot Rod protocol. .2+| `${APPLICATION_NAME}-kieserver` |8080 | http .2+| All the KIE server web server's ports. |8443 | https .1+| `${APPLICATION_NAME}-amq-tcp` |61616 | -- .1+| The broker's OpenWire port. .1+| `ping` |8888 | -- .1+| The JGroups ping port for amq clustering. |============= === Routes A route is a way to expose a service by giving it an externally-reachable hostname such as `www.example.com`. A defined route and the endpoints identified by its service can be consumed by a router to provide named connectivity from external clients to your applications. Each route consists of a route name, service selector, and (optionally) security configuration. Refer to the https://access.redhat.com/documentation/en-us/openshift_enterprise/3.2/html/architecture/core-concepts#architecture-core-concepts-routes[Openshift documentation] for more information. |============= | Service | Security | Hostname |insecure-${APPLICATION_NAME}-rhdmcentr-http | none | `${DECISION_CENTRAL_HOSTNAME_HTTP}` |`${APPLICATION_NAME}-rhdmcentr-https` | TLS passthrough | `${DECISION_CENTRAL_HOSTNAME_HTTPS}` |insecure-${APPLICATION_NAME}-kieserver-http | none | `${KIE_SERVER_HOSTNAME_HTTP}` |`${APPLICATION_NAME}-kieserver-https` | TLS passthrough | `${KIE_SERVER_HOSTNAME_HTTPS}` |============= === Deployment Configurations A deployment in OpenShift is a replication controller based on a user defined template called a deployment configuration. Deployments are created manually or in response to triggered events. Refer to the https://access.redhat.com/documentation/en-us/openshift_container_platform/3.11/html/developer_guide/deployments#dev-guide-how-deployments-work[Openshift documentation] for more information. ==== Triggers A trigger drives the creation of new deployments in response to events, both inside and outside OpenShift. Refer to the https://access.redhat.com/documentation/en-us/openshift_container_platform/3.11/html/developer_guide/deployments#triggers[Openshift documentation] for more information. |============ |Deployment | Triggers |`${APPLICATION_NAME}-rhdmcentr` | ImageChange |`${APPLICATION_NAME}-kieserver` | ImageChange |`${APPLICATION_NAME}-amq-scaledown-controller` | ImageChange |============ ==== Replicas A replication controller ensures that a specified number of pod ""replicas"" are running at any one time. If there are too many, the replication controller kills some pods. If there are too few, it starts more. Refer to the https://cloud.google.com/container-engine/docs/replicationcontrollers/[container-engine documentation] for more information. |============ |Deployment | Replicas |`${APPLICATION_NAME}-rhdmcentr` | 2 |`${APPLICATION_NAME}-kieserver` | 2 |`${APPLICATION_NAME}-amq-scaledown-controller` | 1 |============ ==== Pod Template ===== Service Accounts Service accounts are API objects that exist within each project. They can be created or deleted like any other API object. Refer to the https://access.redhat.com/documentation/en-us/openshift_container_platform/3.11/html/developer_guide/dev-guide-service-accounts#dev-managing-service-accounts[Openshift documentation] for more information. |============ |Deployment | Service Account |`${APPLICATION_NAME}-rhdmcentr` | `${APPLICATION_NAME}-rhdmsvc` |`${APPLICATION_NAME}-kieserver` | `${APPLICATION_NAME}-rhdmsvc` |`${APPLICATION_NAME}-amq-scaledown-controller` | `${APPLICATION_NAME}-amq-scaledown-controller-sa` |============ ===== Image |============ |Deployment | Image |`${APPLICATION_NAME}-rhdmcentr` | `${DECISION_CENTRAL_IMAGE_STREAM_NAME}` |`${APPLICATION_NAME}-kieserver` | `${KIE_SERVER_IMAGE_STREAM_NAME}` |`${APPLICATION_NAME}-amq-scaledown-controller` | `${AMQ_SCALEDOWN_CONTROLLER_IMAGE_STREAM_NAME}` |============ ===== Readiness Probe .${APPLICATION_NAME}-rhdmcentr ---- Http Get on http://localhost:8080/rest/ready ---- .${APPLICATION_NAME}-kieserver ---- Http Get on http://localhost:8080/services/rest/server/readycheck ---- ===== Liveness Probe .${APPLICATION_NAME}-rhdmcentr ---- Http Get on http://localhost:8080/rest/healthy ---- .${APPLICATION_NAME}-kieserver ---- Http Get on http://localhost:8080/services/rest/server/healthcheck ---- ===== Exposed Ports |============= |Deployments | Name | Port | Protocol .5+| `${APPLICATION_NAME}-rhdmcentr` |jolokia | 8778 | `TCP` |http | 8080 | `TCP` |https | 8443 | `TCP` |git-ssh | 8001 | `TCP` |ping | 8888 | `TCP` .3+| `${APPLICATION_NAME}-kieserver` |jolokia | 8778 | `TCP` |http | 8080 | `TCP` |https | 8443 | `TCP` |============= ===== Image Environment Variables |======================================================================= |Deployment |Variable name |Description |Example value .68+| `${APPLICATION_NAME}-rhdmcentr` |`KIE_ADMIN_USER` | KIE administrator username. | `${KIE_ADMIN_USER}` |`KIE_ADMIN_PWD` | KIE administrator password. | `${KIE_ADMIN_PWD}` |`KIE_MBEANS` | KIE server mbeans enabled/disabled. (Sets the kie.mbeans and kie.scanner.mbeans system properties) | `${KIE_MBEANS}` |`KIE_SERVER_CONTROLLER_OPENSHIFT_GLOBAL_DISCOVERY_ENABLED` | If set to true, turns on KIE server global discovery feature (Sets the org.kie.server.controller.openshift.global.discovery.enabled system property) | `${KIE_SERVER_CONTROLLER_OPENSHIFT_GLOBAL_DISCOVERY_ENABLED}` |`KIE_SERVER_CONTROLLER_OPENSHIFT_PREFER_KIESERVER_SERVICE` | If OpenShift integration of Business Central is turned on, setting this parameter to true enables connection to KIE Server via an OpenShift internal Service endpoint. (Sets the org.kie.server.controller.openshift.prefer.kieserver.service system property) | `${KIE_SERVER_CONTROLLER_OPENSHIFT_PREFER_KIESERVER_SERVICE}` |`KIE_SERVER_CONTROLLER_TEMPLATE_CACHE_TTL` | KIE ServerTemplate Cache TTL in milliseconds. (Sets the org.kie.server.controller.template.cache.ttl system property) | `${KIE_SERVER_CONTROLLER_TEMPLATE_CACHE_TTL}` |`KIE_WORKBENCH_CONTROLLER_OPENSHIFT_ENABLED` | -- | true |`KIE_SERVER_CONTROLLER_USER` | KIE server controller username. (Sets the org.kie.server.controller.user system property) | `${KIE_SERVER_CONTROLLER_USER}` |`KIE_SERVER_CONTROLLER_PWD` | KIE server controller password. (Sets the org.kie.server.controller.pwd system property) | `${KIE_SERVER_CONTROLLER_PWD}` |`KIE_SERVER_CONTROLLER_TOKEN` | KIE server controller token for bearer authentication. (Sets the org.kie.server.controller.token system property) | `${KIE_SERVER_CONTROLLER_TOKEN}` |`KIE_SERVER_USER` | KIE server username. (Sets the org.kie.server.user system property) | `${KIE_SERVER_USER}` |`KIE_SERVER_PWD` | KIE server password. (Sets the org.kie.server.pwd system property) | `${KIE_SERVER_PWD}` |`WORKBENCH_ROUTE_NAME` | -- | `${APPLICATION_NAME}-rhdmcentr` |`MAVEN_MIRROR_URL` | Maven mirror that Decision Central and KIE server must use. If you configure a mirror, this mirror must contain all artifacts that are required for building and deploying your services. | `${MAVEN_MIRROR_URL}` |`MAVEN_REPO_ID` | The id to use for the maven repository. If set, it can be excluded from the optionally configured mirror by adding it to MAVEN_MIRROR_OF. For example: external:*,!repo-rhdmcentr,!repo-custom. If MAVEN_MIRROR_URL is set but MAVEN_MIRROR_ID is not set, an id will be generated randomly, but won't be usable in MAVEN_MIRROR_OF. | `${MAVEN_REPO_ID}` |`MAVEN_REPO_URL` | Fully qualified URL to a Maven repository or service. | `${MAVEN_REPO_URL}` |`MAVEN_REPO_USERNAME` | Username to access the Maven repository, if required. | `${MAVEN_REPO_USERNAME}` |`MAVEN_REPO_PASSWORD` | Password to access the Maven repository, if required. | `${MAVEN_REPO_PASSWORD}` |`KIE_MAVEN_USER` | Username to access the Maven service hosted by Decision Central inside EAP. | `${DECISION_CENTRAL_MAVEN_USERNAME}` |`KIE_MAVEN_PWD` | Password to access the Maven service hosted by Decision Central inside EAP. | `${DECISION_CENTRAL_MAVEN_PASSWORD}` |`GIT_HOOKS_DIR` | The directory to use for git hooks, if required. | `${GIT_HOOKS_DIR}` |`HTTPS_KEYSTORE_DIR` | -- | `/etc/decisioncentral-secret-volume` |`HTTPS_KEYSTORE` | The name of the keystore file within the secret for Decision Central. | `${DECISION_CENTRAL_HTTPS_KEYSTORE}` |`HTTPS_NAME` | The name associated with the server certificate for Decision Central. | `${DECISION_CENTRAL_HTTPS_NAME}` |`HTTPS_PASSWORD` | The password for the keystore and certificate for Decision Central. | `${DECISION_CENTRAL_HTTPS_PASSWORD}` |`JGROUPS_PING_PROTOCOL` | -- | openshift.DNS_PING |`OPENSHIFT_DNS_PING_SERVICE_NAME` | -- | `${APPLICATION_NAME}-rhdmcentr-ping` |`OPENSHIFT_DNS_PING_SERVICE_PORT` | -- | 8888 |`APPFORMER_INFINISPAN_SERVICE_NAME` | -- | `${APPLICATION_NAME}-datagrid` |`APPFORMER_INFINISPAN_PORT` | -- | 11222 |`APPFORMER_JMS_BROKER_ADDRESS` | -- | `${APPLICATION_NAME}-amq-tcp` |`APPFORMER_JMS_BROKER_PORT` | -- | 61616 |`APPFORMER_JMS_BROKER_USER` | The username to connect to the JMS broker. | `${APPFORMER_JMS_BROKER_USER}` |`APPFORMER_JMS_BROKER_PASSWORD` | The password to connect to the JMS broker. | `${APPFORMER_JMS_BROKER_PASSWORD}` |`SSO_URL` | RH-SSO URL. | `${SSO_URL}` |`SSO_OPENIDCONNECT_DEPLOYMENTS` | -- | ROOT.war |`SSO_REALM` | RH-SSO Realm name. | `${SSO_REALM}` |`SSO_SECRET` | Decision Central RH-SSO Client Secret. | `${DECISION_CENTRAL_SSO_SECRET}` |`SSO_CLIENT` | Decision Central RH-SSO Client name. | `${DECISION_CENTRAL_SSO_CLIENT}` |`SSO_USERNAME` | RH-SSO Realm Admin Username used to create the Client if it doesn't exist. | `${SSO_USERNAME}` |`SSO_PASSWORD` | RH-SSO Realm Admin Password used to create the Client. | `${SSO_PASSWORD}` |`SSO_DISABLE_SSL_CERTIFICATE_VALIDATION` | RH-SSO Disable SSL Certificate Validation. | `${SSO_DISABLE_SSL_CERTIFICATE_VALIDATION}` |`SSO_PRINCIPAL_ATTRIBUTE` | RH-SSO Principal Attribute to use as username. | `${SSO_PRINCIPAL_ATTRIBUTE}` |`HOSTNAME_HTTP` | Custom hostname for http service route for Decision Central. Leave blank for default hostname, e.g.: insecure--rhdmcentr-. | `${DECISION_CENTRAL_HOSTNAME_HTTP}` |`HOSTNAME_HTTPS` | Custom hostname for https service route for Decision Central. Leave blank for default hostname, e.g.: -rhdmcentr-. | `${DECISION_CENTRAL_HOSTNAME_HTTPS}` |`AUTH_LDAP_URL` | LDAP Endpoint to connect for authentication. | `${AUTH_LDAP_URL}` |`AUTH_LDAP_BIND_DN` | Bind DN used for authentication. | `${AUTH_LDAP_BIND_DN}` |`AUTH_LDAP_BIND_CREDENTIAL` | LDAP Credentials used for authentication. | `${AUTH_LDAP_BIND_CREDENTIAL}` |`AUTH_LDAP_JAAS_SECURITY_DOMAIN` | The JMX ObjectName of the JaasSecurityDomain used to decrypt the password. | `${AUTH_LDAP_JAAS_SECURITY_DOMAIN}` |`AUTH_LDAP_BASE_CTX_DN` | LDAP Base DN of the top-level context to begin the user search. | `${AUTH_LDAP_BASE_CTX_DN}` |`AUTH_LDAP_BASE_FILTER` | LDAP search filter used to locate the context of the user to authenticate. The input username or userDN obtained from the login module callback is substituted into the filter anywhere a {0} expression is used. A common example for the search filter is (uid={0}). | `${AUTH_LDAP_BASE_FILTER}` |`AUTH_LDAP_SEARCH_SCOPE` | The search scope to use. | `${AUTH_LDAP_SEARCH_SCOPE}` |`AUTH_LDAP_SEARCH_TIME_LIMIT` | The timeout in milliseconds for user or role searches. | `${AUTH_LDAP_SEARCH_TIME_LIMIT}` |`AUTH_LDAP_DISTINGUISHED_NAME_ATTRIBUTE` | The name of the attribute in the user entry that contains the DN of the user. This may be necessary if the DN of the user itself contains special characters, backslash for example, that prevent correct user mapping. If the attribute does not exist, the entry's DN is used. | `${AUTH_LDAP_DISTINGUISHED_NAME_ATTRIBUTE}` |`AUTH_LDAP_PARSE_USERNAME` | A flag indicating if the DN is to be parsed for the username. If set to true, the DN is parsed for the username. If set to false the DN is not parsed for the username. This option is used together with usernameBeginString and usernameEndString. | `${AUTH_LDAP_PARSE_USERNAME}` |`AUTH_LDAP_USERNAME_BEGIN_STRING` | Defines the String which is to be removed from the start of the DN to reveal the username. This option is used together with usernameEndString and only taken into account if parseUsername is set to true. | `${AUTH_LDAP_USERNAME_BEGIN_STRING}` |`AUTH_LDAP_USERNAME_END_STRING` | Defines the String which is to be removed from the end of the DN to reveal the username. This option is used together with usernameEndString and only taken into account if parseUsername is set to true. | `${AUTH_LDAP_USERNAME_END_STRING}` |`AUTH_LDAP_ROLE_ATTRIBUTE_ID` | Name of the attribute containing the user roles. | `${AUTH_LDAP_ROLE_ATTRIBUTE_ID}` |`AUTH_LDAP_ROLES_CTX_DN` | The fixed DN of the context to search for user roles. This is not the DN where the actual roles are, but the DN where the objects containing the user roles are. For example, in a Microsoft Active Directory server, this is the DN where the user account is. | `${AUTH_LDAP_ROLES_CTX_DN}` |`AUTH_LDAP_ROLE_FILTER` | A search filter used to locate the roles associated with the authenticated user. The input username or userDN obtained from the login module callback is substituted into the filter anywhere a {0} expression is used. The authenticated userDN is substituted into the filter anywhere a {1} is used. An example search filter that matches on the input username is (member={0}). An alternative that matches on the authenticated userDN is (member={1}). | `${AUTH_LDAP_ROLE_FILTER}` |`AUTH_LDAP_ROLE_RECURSION` | The number of levels of recursion the role search will go below a matching context. Disable recursion by setting this to 0. | `${AUTH_LDAP_ROLE_RECURSION}` |`AUTH_LDAP_DEFAULT_ROLE` | A role included for all authenticated users | `${AUTH_LDAP_DEFAULT_ROLE}` |`AUTH_LDAP_ROLE_NAME_ATTRIBUTE_ID` | Name of the attribute within the roleCtxDN context which contains the role name. If the roleAttributeIsDN property is set to true, this property is used to find the role object's name attribute. | `${AUTH_LDAP_ROLE_NAME_ATTRIBUTE_ID}` |`AUTH_LDAP_PARSE_ROLE_NAME_FROM_DN` | A flag indicating if the DN returned by a query contains the roleNameAttributeID. If set to true, the DN is checked for the roleNameAttributeID. If set to false, the DN is not checked for the roleNameAttributeID. This flag can improve the performance of LDAP queries. | `${AUTH_LDAP_PARSE_ROLE_NAME_FROM_DN}` |`AUTH_LDAP_ROLE_ATTRIBUTE_IS_DN` | Whether or not the roleAttributeID contains the fully-qualified DN of a role object. If false, the role name is taken from the value of the roleNameAttributeId attribute of the context name. Certain directory schemas, such as Microsoft Active Directory, require this attribute to be set to true. | `${AUTH_LDAP_ROLE_ATTRIBUTE_IS_DN}` |`AUTH_LDAP_REFERRAL_USER_ATTRIBUTE_ID_TO_CHECK` | If you are not using referrals, you can ignore this option. When using referrals, this option denotes the attribute name which contains users defined for a certain role, for example member, if the role object is inside the referral. Users are checked against the content of this attribute name. If this option is not set, the check will always fail, so role objects cannot be stored in a referral tree. | `${AUTH_LDAP_REFERRAL_USER_ATTRIBUTE_ID_TO_CHECK}` |`AUTH_ROLE_MAPPER_ROLES_PROPERTIES` | When present, the RoleMapping Login Module will be configured to use the provided file. This parameter defines the fully-qualified file path and name of a properties file or resource which maps roles to replacement roles. The format is original_role=role1,role2,role3 | `${AUTH_ROLE_MAPPER_ROLES_PROPERTIES}` |`AUTH_ROLE_MAPPER_REPLACE_ROLE` | Whether to add to the current roles, or replace the current roles with the mapped ones. Replaces if set to true. | `${AUTH_ROLE_MAPPER_REPLACE_ROLE}` .63+| `${APPLICATION_NAME}-kieserver` |`WORKBENCH_SERVICE_NAME` | -- | `${APPLICATION_NAME}-rhdmcentr` |`KIE_ADMIN_USER` | KIE administrator username. | `${KIE_ADMIN_USER}` |`KIE_ADMIN_PWD` | KIE administrator password. | `${KIE_ADMIN_PWD}` |`KIE_SERVER_MODE` | The KIE Server mode. Valid values are 'DEVELOPMENT' or 'PRODUCTION'. In production mode, you can not deploy SNAPSHOT versions of artifacts on the KIE server and can not change the version of an artifact in an existing container. (Sets the org.kie.server.mode system property). | `${KIE_SERVER_MODE}` |`KIE_MBEANS` | KIE server mbeans enabled/disabled. (Sets the kie.mbeans and kie.scanner.mbeans system properties) | `${KIE_MBEANS}` |`DROOLS_SERVER_FILTER_CLASSES` | KIE server class filtering. (Sets the org.drools.server.filter.classes system property) | `${DROOLS_SERVER_FILTER_CLASSES}` |`PROMETHEUS_SERVER_EXT_DISABLED` | If set to false, the prometheus server extension will be enabled. (Sets the org.kie.prometheus.server.ext.disabled system property) | `${PROMETHEUS_SERVER_EXT_DISABLED}` |`KIE_SERVER_BYPASS_AUTH_USER` | Allows the KIE server to bypass the authenticated user for task related operations e.g. queries. (Sets the org.kie.server.bypass.auth.user system property) | `${KIE_SERVER_BYPASS_AUTH_USER}` |`KIE_SERVER_ID` | -- | -- |`KIE_SERVER_ROUTE_NAME` | -- | `${APPLICATION_NAME}-kieserver` |`KIE_SERVER_STARTUP_STRATEGY` | -- | OpenShiftStartupStrategy |`KIE_SERVER_PWD` | KIE server password. (Sets the org.kie.server.pwd system property) | `${KIE_SERVER_PWD}` |`KIE_SERVER_USER` | KIE server username. (Sets the org.kie.server.user system property) | `${KIE_SERVER_USER}` |`MAVEN_MIRROR_URL` | Maven mirror that Decision Central and KIE server must use. If you configure a mirror, this mirror must contain all artifacts that are required for building and deploying your services. | `${MAVEN_MIRROR_URL}` |`MAVEN_MIRROR_OF` | Maven mirror configuration for KIE server. | `${MAVEN_MIRROR_OF}` |`MAVEN_REPOS` | -- | RHDMCENTR,EXTERNAL |`RHDMCENTR_MAVEN_REPO_ID` | -- | repo-rhdmcentr |`RHDMCENTR_MAVEN_REPO_SERVICE` | -- | `${APPLICATION_NAME}-rhdmcentr` |`RHDMCENTR_MAVEN_REPO_PATH` | -- | `/maven2/` |`RHDMCENTR_MAVEN_REPO_USERNAME` | Username to access the Maven service hosted by Decision Central inside EAP. | `${DECISION_CENTRAL_MAVEN_USERNAME}` |`RHDMCENTR_MAVEN_REPO_PASSWORD` | Password to access the Maven service hosted by Decision Central inside EAP. | `${DECISION_CENTRAL_MAVEN_PASSWORD}` |`EXTERNAL_MAVEN_REPO_ID` | The id to use for the maven repository. If set, it can be excluded from the optionally configured mirror by adding it to MAVEN_MIRROR_OF. For example: external:*,!repo-rhdmcentr,!repo-custom. If MAVEN_MIRROR_URL is set but MAVEN_MIRROR_ID is not set, an id will be generated randomly, but won't be usable in MAVEN_MIRROR_OF. | `${MAVEN_REPO_ID}` |`EXTERNAL_MAVEN_REPO_URL` | Fully qualified URL to a Maven repository or service. | `${MAVEN_REPO_URL}` |`EXTERNAL_MAVEN_REPO_USERNAME` | Username to access the Maven repository, if required. | `${MAVEN_REPO_USERNAME}` |`EXTERNAL_MAVEN_REPO_PASSWORD` | Password to access the Maven repository, if required. | `${MAVEN_REPO_PASSWORD}` |`HTTPS_KEYSTORE_DIR` | -- | `/etc/kieserver-secret-volume` |`HTTPS_KEYSTORE` | The name of the keystore file within the secret for KIE Server. | `${KIE_SERVER_HTTPS_KEYSTORE}` |`HTTPS_NAME` | The name associated with the server certificate for KIE Server. | `${KIE_SERVER_HTTPS_NAME}` |`HTTPS_PASSWORD` | The password for the keystore and certificate for KIE Server. | `${KIE_SERVER_HTTPS_PASSWORD}` |`SSO_URL` | RH-SSO URL. | `${SSO_URL}` |`SSO_OPENIDCONNECT_DEPLOYMENTS` | -- | ROOT.war |`SSO_REALM` | RH-SSO Realm name. | `${SSO_REALM}` |`SSO_SECRET` | KIE Server RH-SSO Client Secret. | `${KIE_SERVER_SSO_SECRET}` |`SSO_CLIENT` | KIE Server RH-SSO Client name. | `${KIE_SERVER_SSO_CLIENT}` |`SSO_USERNAME` | RH-SSO Realm Admin Username used to create the Client if it doesn't exist. | `${SSO_USERNAME}` |`SSO_PASSWORD` | RH-SSO Realm Admin Password used to create the Client. | `${SSO_PASSWORD}` |`SSO_DISABLE_SSL_CERTIFICATE_VALIDATION` | RH-SSO Disable SSL Certificate Validation. | `${SSO_DISABLE_SSL_CERTIFICATE_VALIDATION}` |`SSO_PRINCIPAL_ATTRIBUTE` | RH-SSO Principal Attribute to use as username. | `${SSO_PRINCIPAL_ATTRIBUTE}` |`HOSTNAME_HTTP` | Custom hostname for http service route for KIE Server. Leave blank for default hostname, e.g.: insecure--kieserver-. | `${KIE_SERVER_HOSTNAME_HTTP}` |`HOSTNAME_HTTPS` | Custom hostname for https service route for KIE Server. Leave blank for default hostname, e.g.: -kieserver-. | `${KIE_SERVER_HOSTNAME_HTTPS}` |`AUTH_LDAP_URL` | LDAP Endpoint to connect for authentication. | `${AUTH_LDAP_URL}` |`AUTH_LDAP_BIND_DN` | Bind DN used for authentication. | `${AUTH_LDAP_BIND_DN}` |`AUTH_LDAP_BIND_CREDENTIAL` | LDAP Credentials used for authentication. | `${AUTH_LDAP_BIND_CREDENTIAL}` |`AUTH_LDAP_JAAS_SECURITY_DOMAIN` | The JMX ObjectName of the JaasSecurityDomain used to decrypt the password. | `${AUTH_LDAP_JAAS_SECURITY_DOMAIN}` |`AUTH_LDAP_BASE_CTX_DN` | LDAP Base DN of the top-level context to begin the user search. | `${AUTH_LDAP_BASE_CTX_DN}` |`AUTH_LDAP_BASE_FILTER` | LDAP search filter used to locate the context of the user to authenticate. The input username or userDN obtained from the login module callback is substituted into the filter anywhere a {0} expression is used. A common example for the search filter is (uid={0}). | `${AUTH_LDAP_BASE_FILTER}` |`AUTH_LDAP_SEARCH_SCOPE` | The search scope to use. | `${AUTH_LDAP_SEARCH_SCOPE}` |`AUTH_LDAP_SEARCH_TIME_LIMIT` | The timeout in milliseconds for user or role searches. | `${AUTH_LDAP_SEARCH_TIME_LIMIT}` |`AUTH_LDAP_DISTINGUISHED_NAME_ATTRIBUTE` | The name of the attribute in the user entry that contains the DN of the user. This may be necessary if the DN of the user itself contains special characters, backslash for example, that prevent correct user mapping. If the attribute does not exist, the entry's DN is used. | `${AUTH_LDAP_DISTINGUISHED_NAME_ATTRIBUTE}` |`AUTH_LDAP_PARSE_USERNAME` | A flag indicating if the DN is to be parsed for the username. If set to true, the DN is parsed for the username. If set to false the DN is not parsed for the username. This option is used together with usernameBeginString and usernameEndString. | `${AUTH_LDAP_PARSE_USERNAME}` |`AUTH_LDAP_USERNAME_BEGIN_STRING` | Defines the String which is to be removed from the start of the DN to reveal the username. This option is used together with usernameEndString and only taken into account if parseUsername is set to true. | `${AUTH_LDAP_USERNAME_BEGIN_STRING}` |`AUTH_LDAP_USERNAME_END_STRING` | Defines the String which is to be removed from the end of the DN to reveal the username. This option is used together with usernameEndString and only taken into account if parseUsername is set to true. | `${AUTH_LDAP_USERNAME_END_STRING}` |`AUTH_LDAP_ROLE_ATTRIBUTE_ID` | Name of the attribute containing the user roles. | `${AUTH_LDAP_ROLE_ATTRIBUTE_ID}` |`AUTH_LDAP_ROLES_CTX_DN` | The fixed DN of the context to search for user roles. This is not the DN where the actual roles are, but the DN where the objects containing the user roles are. For example, in a Microsoft Active Directory server, this is the DN where the user account is. | `${AUTH_LDAP_ROLES_CTX_DN}` |`AUTH_LDAP_ROLE_FILTER` | A search filter used to locate the roles associated with the authenticated user. The input username or userDN obtained from the login module callback is substituted into the filter anywhere a {0} expression is used. The authenticated userDN is substituted into the filter anywhere a {1} is used. An example search filter that matches on the input username is (member={0}). An alternative that matches on the authenticated userDN is (member={1}). | `${AUTH_LDAP_ROLE_FILTER}` |`AUTH_LDAP_ROLE_RECURSION` | The number of levels of recursion the role search will go below a matching context. Disable recursion by setting this to 0. | `${AUTH_LDAP_ROLE_RECURSION}` |`AUTH_LDAP_DEFAULT_ROLE` | A role included for all authenticated users | `${AUTH_LDAP_DEFAULT_ROLE}` |`AUTH_LDAP_ROLE_NAME_ATTRIBUTE_ID` | Name of the attribute within the roleCtxDN context which contains the role name. If the roleAttributeIsDN property is set to true, this property is used to find the role object's name attribute. | `${AUTH_LDAP_ROLE_NAME_ATTRIBUTE_ID}` |`AUTH_LDAP_PARSE_ROLE_NAME_FROM_DN` | A flag indicating if the DN returned by a query contains the roleNameAttributeID. If set to true, the DN is checked for the roleNameAttributeID. If set to false, the DN is not checked for the roleNameAttributeID. This flag can improve the performance of LDAP queries. | `${AUTH_LDAP_PARSE_ROLE_NAME_FROM_DN}` |`AUTH_LDAP_ROLE_ATTRIBUTE_IS_DN` | Whether or not the roleAttributeID contains the fully-qualified DN of a role object. If false, the role name is taken from the value of the roleNameAttributeId attribute of the context name. Certain directory schemas, such as Microsoft Active Directory, require this attribute to be set to true. | `${AUTH_LDAP_ROLE_ATTRIBUTE_IS_DN}` |`AUTH_LDAP_REFERRAL_USER_ATTRIBUTE_ID_TO_CHECK` | If you are not using referrals, you can ignore this option. When using referrals, this option denotes the attribute name which contains users defined for a certain role, for example member, if the role object is inside the referral. Users are checked against the content of this attribute name. If this option is not set, the check will always fail, so role objects cannot be stored in a referral tree. | `${AUTH_LDAP_REFERRAL_USER_ATTRIBUTE_ID_TO_CHECK}` |`AUTH_ROLE_MAPPER_ROLES_PROPERTIES` | When present, the RoleMapping Login Module will be configured to use the provided file. This parameter defines the fully-qualified file path and name of a properties file or resource which maps roles to replacement roles. The format is original_role=role1,role2,role3 | `${AUTH_ROLE_MAPPER_ROLES_PROPERTIES}` |`AUTH_ROLE_MAPPER_REPLACE_ROLE` | Whether to add to the current roles, or replace the current roles with the mapped ones. Replaces if set to true. | `${AUTH_ROLE_MAPPER_REPLACE_ROLE}` |======================================================================= ===== Volumes |============= |Deployment |Name | mountPath | Purpose | readOnly |`${APPLICATION_NAME}-rhdmcentr` | decisioncentral-keystore-volume | `/etc/decisioncentral-secret-volume` | ssl certs | True |`${APPLICATION_NAME}-kieserver` | kieserver-keystore-volume | `/etc/kieserver-secret-volume` | ssl certs | True |============= === External Dependencies ==== Volume Claims A `PersistentVolume` object is a storage resource in an OpenShift cluster. Storage is provisioned by an administrator by creating `PersistentVolume` objects from sources such as GCE Persistent Disks, AWS Elastic Block Stores (EBS), and NFS mounts. Refer to the https://access.redhat.com/documentation/en-us/openshift_container_platform/3.11/html/developer_guide/dev-guide-persistent-volumes[Openshift documentation] for more information. |============= |Name | Access Mode |`${APPLICATION_NAME}-rhdmcentr-claim` | ReadWriteMany |============= ==== Secrets This template requires the following secrets to be installed for the application to run. decisioncentral-app-secret kieserver-app-secret [[clustering]] ==== Clustering Clustering in OpenShift EAP is achieved through one of two discovery mechanisms: Kubernetes or DNS. This is done by configuring the JGroups protocol stack in standalone-openshift.xml with either the `` or `` elements. The templates are configured to use `DNS_PING`, however `KUBE_PING`is the default used by the image. The discovery mechanism used is specified by the `JGROUPS_PING_PROTOCOL` environment variable which can be set to either `openshift.DNS_PING` or `openshift.KUBE_PING`. `openshift.KUBE_PING` is the default used by the image if no value is specified for `JGROUPS_PING_PROTOCOL`. For DNS_PING to work, the following steps must be taken: . The `OPENSHIFT_DNS_PING_SERVICE_NAME` environment variable must be set to the name of the ping service for the cluster (see table above). If not set, the server will act as if it is a single-node cluster (a ""cluster of one""). . The `OPENSHIFT_DNS_PING_SERVICE_PORT` environment variables should be set to the port number on which the ping service is exposed (see table above). The `DNS_PING` protocol will attempt to discern the port from the SRV records, if it can, otherwise it will default to 8888. . A ping service which exposes the ping port must be defined. This service should be ""headless"" (ClusterIP=None) and must have the following: .. The port must be named for port discovery to work. .. It must be annotated with `service.alpha.kubernetes.io/tolerate-unready-endpoints` set to `""true""`. Omitting this annotation will result in each node forming their own ""cluster of one"" during startup, then merging their cluster into the other nodes' clusters after startup (as the other nodes are not detected until after they have started). .Example ping service for use with DNS_PING [source,yaml] ---- kind: Service apiVersion: v1 spec: clusterIP: None ports: - name: ping port: 8888 selector: deploymentConfig: eap-app metadata: name: eap-app-ping annotations: service.alpha.kubernetes.io/tolerate-unready-endpoints: ""true"" description: ""The JGroups ping port for clustering."" ---- For `KUBE_PING` to work, the following steps must be taken: . The `OPENSHIFT_KUBE_PING_NAMESPACE` environment variable must be set (see table above). If not set, the server will act as if it is a single-node cluster (a ""cluster of one""). . The `OPENSHIFT_KUBE_PING_LABELS` environment variables should be set (see table above). If not set, pods outside of your application (albeit in your namespace) will try to join. . Authorization must be granted to the service account the pod is running under to be allowed to access Kubernetes' REST api. This is done on the command line. .Policy commands ==== Using the default service account in the myproject namespace: .... oc policy add-role-to-user view system:serviceaccount:myproject:default -n myproject .... Using the eap-service-account in the myproject namespace: .... oc policy add-role-to-user view system:serviceaccount:myproject:eap-service-account -n myproject .... ==== ",12473,True,2715.395485806213,median "// Automatically generated by 'openshift-apidocs-gen'. Do not edit. :_content-type: ASSEMBLY [id=""statefulset-apps-v1""] = StatefulSet [apps/v1] ifdef::product-title[] include::modules/common-attributes.adoc[] endif::[] toc::[] Description:: + -- StatefulSet represents a set of pods with consistent identities. Identities are defined as: - Network: A single stable DNS and hostname. - Storage: As many VolumeClaims as requested. The StatefulSet guarantees that a given network identity will always map to the same storage identity. -- Type:: `object` == Specification [cols=""1,1,1"",options=""header""] |=== | Property | Type | Description | `apiVersion` | `string` | APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources | `kind` | `string` | Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds | `metadata` | xref:../objects/index.adoc#io.k8s.apimachinery.pkg.apis.meta.v1.ObjectMeta[`ObjectMeta`] | Standard object's metadata. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata | `spec` | `object` | A StatefulSetSpec is the specification of a StatefulSet. | `status` | `object` | StatefulSetStatus represents the current state of a StatefulSet. |=== === .spec Description:: + -- A StatefulSetSpec is the specification of a StatefulSet. -- Type:: `object` Required:: - `selector` - `template` - `serviceName` [cols=""1,1,1"",options=""header""] |=== | Property | Type | Description | `minReadySeconds` | `integer` | Minimum number of seconds for which a newly created pod should be ready without any of its container crashing for it to be considered available. Defaults to 0 (pod will be considered available as soon as it is ready) This is an alpha field and requires enabling StatefulSetMinReadySeconds feature gate. | `podManagementPolicy` | `string` | podManagementPolicy controls how pods are created during initial scale up, when replacing pods on nodes, or when scaling down. The default policy is `OrderedReady`, where pods are created in increasing order (pod-0, then pod-1, etc) and the controller will wait until each pod is ready before continuing. When scaling down, the pods are removed in the opposite order. The alternative policy is `Parallel` which will create pods in parallel to match the desired scale without waiting, and on scale down will delete all pods at once. | `replicas` | `integer` | replicas is the desired number of replicas of the given Template. These are replicas in the sense that they are instantiations of the same Template, but individual replicas also have a consistent identity. If unspecified, defaults to 1. | `revisionHistoryLimit` | `integer` | revisionHistoryLimit is the maximum number of revisions that will be maintained in the StatefulSet's revision history. The revision history consists of all revisions not represented by a currently applied StatefulSetSpec version. The default value is 10. | `selector` | xref:../objects/index.adoc#io.k8s.apimachinery.pkg.apis.meta.v1.LabelSelector[`LabelSelector`] | selector is a label query over pods that should match the replica count. It must match the pod template's labels. More info: https://kubernetes.io/docs/concepts/overview/working-with-objects/labels/#label-selectors | `serviceName` | `string` | serviceName is the name of the service that governs this StatefulSet. This service must exist before the StatefulSet, and is responsible for the network identity of the set. Pods get DNS/hostnames that follow the pattern: pod-specific-string.serviceName.default.svc.cluster.local where ""pod-specific-string"" is managed by the StatefulSet controller. | `template` | xref:../objects/index.adoc#io.k8s.api.core.v1.PodTemplateSpec[`PodTemplateSpec`] | template is the object that describes the pod that will be created if insufficient replicas are detected. Each pod stamped out by the StatefulSet will fulfill this Template, but have a unique identity from the rest of the StatefulSet. | `updateStrategy` | `object` | StatefulSetUpdateStrategy indicates the strategy that the StatefulSet controller will use to perform updates. It includes any additional parameters necessary to perform the update for the indicated strategy. | `volumeClaimTemplates` | xref:../storage_apis/persistentvolumeclaim-v1.adoc#persistentvolumeclaim-v1[`array (PersistentVolumeClaim)`] | volumeClaimTemplates is a list of claims that pods are allowed to reference. The StatefulSet controller is responsible for mapping network identities to claims in a way that maintains the identity of a pod. Every claim in this list must have at least one matching (by name) volumeMount in one container in the template. A claim in this list takes precedence over any volumes in the template, with the same name. |=== === .spec.updateStrategy Description:: + -- StatefulSetUpdateStrategy indicates the strategy that the StatefulSet controller will use to perform updates. It includes any additional parameters necessary to perform the update for the indicated strategy. -- Type:: `object` [cols=""1,1,1"",options=""header""] |=== | Property | Type | Description | `rollingUpdate` | `object` | RollingUpdateStatefulSetStrategy is used to communicate parameter for RollingUpdateStatefulSetStrategyType. | `type` | `string` | Type indicates the type of the StatefulSetUpdateStrategy. Default is RollingUpdate. |=== === .spec.updateStrategy.rollingUpdate Description:: + -- RollingUpdateStatefulSetStrategy is used to communicate parameter for RollingUpdateStatefulSetStrategyType. -- Type:: `object` [cols=""1,1,1"",options=""header""] |=== | Property | Type | Description | `partition` | `integer` | Partition indicates the ordinal at which the StatefulSet should be partitioned. Default value is 0. |=== === .status Description:: + -- StatefulSetStatus represents the current state of a StatefulSet. -- Type:: `object` Required:: - `replicas` [cols=""1,1,1"",options=""header""] |=== | Property | Type | Description | `availableReplicas` | `integer` | Total number of available pods (ready for at least minReadySeconds) targeted by this statefulset. This is an alpha field and requires enabling StatefulSetMinReadySeconds feature gate. Remove omitempty when graduating to beta | `collisionCount` | `integer` | collisionCount is the count of hash collisions for the StatefulSet. The StatefulSet controller uses this field as a collision avoidance mechanism when it needs to create the name for the newest ControllerRevision. | `conditions` | `array` | Represents the latest available observations of a statefulset's current state. | `conditions[]` | `object` | StatefulSetCondition describes the state of a statefulset at a certain point. | `currentReplicas` | `integer` | currentReplicas is the number of Pods created by the StatefulSet controller from the StatefulSet version indicated by currentRevision. | `currentRevision` | `string` | currentRevision, if not empty, indicates the version of the StatefulSet used to generate Pods in the sequence [0,currentReplicas). | `observedGeneration` | `integer` | observedGeneration is the most recent generation observed for this StatefulSet. It corresponds to the StatefulSet's generation, which is updated on mutation by the API Server. | `readyReplicas` | `integer` | readyReplicas is the number of Pods created by the StatefulSet controller that have a Ready Condition. | `replicas` | `integer` | replicas is the number of Pods created by the StatefulSet controller. | `updateRevision` | `string` | updateRevision, if not empty, indicates the version of the StatefulSet used to generate Pods in the sequence [replicas-updatedReplicas,replicas) | `updatedReplicas` | `integer` | updatedReplicas is the number of Pods created by the StatefulSet controller from the StatefulSet version indicated by updateRevision. |=== === .status.conditions Description:: + -- Represents the latest available observations of a statefulset's current state. -- Type:: `array` === .status.conditions[] Description:: + -- StatefulSetCondition describes the state of a statefulset at a certain point. -- Type:: `object` Required:: - `type` - `status` [cols=""1,1,1"",options=""header""] |=== | Property | Type | Description | `lastTransitionTime` | xref:../objects/index.adoc#io.k8s.apimachinery.pkg.apis.meta.v1.Time[`Time`] | Last time the condition transitioned from one status to another. | `message` | `string` | A human readable message indicating details about the transition. | `reason` | `string` | The reason for the condition's last transition. | `status` | `string` | Status of the condition, one of True, False, Unknown. | `type` | `string` | Type of statefulset condition. |=== == API endpoints The following API endpoints are available: * `/apis/apps/v1/statefulsets` - `GET`: list or watch objects of kind StatefulSet * `/apis/apps/v1/watch/statefulsets` - `GET`: watch individual changes to a list of StatefulSet. deprecated: use the 'watch' parameter with a list operation instead. * `/apis/apps/v1/namespaces/{namespace}/statefulsets` - `DELETE`: delete collection of StatefulSet - `GET`: list or watch objects of kind StatefulSet - `POST`: create a StatefulSet * `/apis/apps/v1/watch/namespaces/{namespace}/statefulsets` - `GET`: watch individual changes to a list of StatefulSet. deprecated: use the 'watch' parameter with a list operation instead. * `/apis/apps/v1/namespaces/{namespace}/statefulsets/{name}` - `DELETE`: delete a StatefulSet - `GET`: read the specified StatefulSet - `PATCH`: partially update the specified StatefulSet - `PUT`: replace the specified StatefulSet * `/apis/apps/v1/watch/namespaces/{namespace}/statefulsets/{name}` - `GET`: watch changes to an object of kind StatefulSet. deprecated: use the 'watch' parameter with a list operation instead, filtered to a single item with the 'fieldSelector' parameter. * `/apis/apps/v1/namespaces/{namespace}/statefulsets/{name}/status` - `GET`: read status of the specified StatefulSet - `PATCH`: partially update status of the specified StatefulSet - `PUT`: replace status of the specified StatefulSet === /apis/apps/v1/statefulsets .Global query parameters [cols=""1,1,2"",options=""header""] |=== | Parameter | Type | Description | `allowWatchBookmarks` | `boolean` | allowWatchBookmarks requests watch events with type "BOOKMARK". Servers that do not implement bookmarks may ignore this flag and bookmarks are sent at the server's discretion. Clients should not assume bookmarks are returned at any specific interval, nor may they assume the server will send any BOOKMARK event during a session. If this is not a watch, this field is ignored. | `continue` | `string` | The continue option should be set when retrieving more results from the server. Since this value is server defined, clients may only use the continue value from a previous query result with identical query parameters (except for the value of continue) and the server may reject a continue value it does not recognize. If the specified continue value is no longer valid whether due to expiration (generally five to fifteen minutes) or a configuration change on the server, the server will respond with a 410 ResourceExpired error together with a continue token. If the client needs a consistent list, it must restart their list without the continue field. Otherwise, the client may send another list request with the token received with the 410 error, the server will respond with a list starting from the next key, but from the latest snapshot, which is inconsistent from the previous list results - objects that are created, modified, or deleted after the first list request will be included in the response, as long as their keys are after the "next key". This field is not supported when watch is true. Clients may start a watch from the last resourceVersion value returned by the server and not miss any modifications. | `fieldSelector` | `string` | A selector to restrict the list of returned objects by their fields. Defaults to everything. | `labelSelector` | `string` | A selector to restrict the list of returned objects by their labels. Defaults to everything. | `limit` | `integer` | limit is a maximum number of responses to return for a list call. If more items exist, the server will set the `continue` field on the list metadata to a value that can be used with the same initial query to retrieve the next set of results. Setting a limit may return fewer than the requested amount of items (up to zero items) in the event all requested objects are filtered out and clients should only use the presence of the continue field to determine whether more results are available. Servers may choose not to support the limit argument and will return all of the available results. If limit is specified and the continue field is empty, clients may assume that no more results are available. This field is not supported if watch is true. The server guarantees that the objects returned when using continue will be identical to issuing a single list call without a limit - that is, no objects created, modified, or deleted after the first request is issued will be included in any subsequent continued requests. This is sometimes referred to as a consistent snapshot, and ensures that a client that is using limit to receive smaller chunks of a very large result can ensure they see all possible objects. If objects are updated during a chunked list the version of the object that was present at the time the first list result was calculated is returned. | `pretty` | `string` | If 'true', then the output is pretty printed. | `resourceVersion` | `string` | resourceVersion sets a constraint on what resource versions a request may be served from. See https://kubernetes.io/docs/reference/using-api/api-concepts/#resource-versions for details. Defaults to unset | `resourceVersionMatch` | `string` | resourceVersionMatch determines how resourceVersion is applied to list calls. It is highly recommended that resourceVersionMatch be set for list calls where resourceVersion is set See https://kubernetes.io/docs/reference/using-api/api-concepts/#resource-versions for details. Defaults to unset | `timeoutSeconds` | `integer` | Timeout for the list/watch call. This limits the duration of the call, regardless of any activity or inactivity. | `watch` | `boolean` | Watch for changes to the described resources and return them as a stream of add, update, and remove notifications. Specify resourceVersion. |=== HTTP method:: `GET` Description:: list or watch objects of kind StatefulSet .HTTP responses [cols=""1,1"",options=""header""] |=== | HTTP code | Reponse body | 200 - OK | xref:../objects/index.adoc#io.k8s.api.apps.v1.StatefulSetList[`StatefulSetList`] schema | 401 - Unauthorized | Empty |=== === /apis/apps/v1/watch/statefulsets .Global query parameters [cols=""1,1,2"",options=""header""] |=== | Parameter | Type | Description | `allowWatchBookmarks` | `boolean` | allowWatchBookmarks requests watch events with type "BOOKMARK". Servers that do not implement bookmarks may ignore this flag and bookmarks are sent at the server's discretion. Clients should not assume bookmarks are returned at any specific interval, nor may they assume the server will send any BOOKMARK event during a session. If this is not a watch, this field is ignored. | `continue` | `string` | The continue option should be set when retrieving more results from the server. Since this value is server defined, clients may only use the continue value from a previous query result with identical query parameters (except for the value of continue) and the server may reject a continue value it does not recognize. If the specified continue value is no longer valid whether due to expiration (generally five to fifteen minutes) or a configuration change on the server, the server will respond with a 410 ResourceExpired error together with a continue token. If the client needs a consistent list, it must restart their list without the continue field. Otherwise, the client may send another list request with the token received with the 410 error, the server will respond with a list starting from the next key, but from the latest snapshot, which is inconsistent from the previous list results - objects that are created, modified, or deleted after the first list request will be included in the response, as long as their keys are after the "next key". This field is not supported when watch is true. Clients may start a watch from the last resourceVersion value returned by the server and not miss any modifications. | `fieldSelector` | `string` | A selector to restrict the list of returned objects by their fields. Defaults to everything. | `labelSelector` | `string` | A selector to restrict the list of returned objects by their labels. Defaults to everything. | `limit` | `integer` | limit is a maximum number of responses to return for a list call. If more items exist, the server will set the `continue` field on the list metadata to a value that can be used with the same initial query to retrieve the next set of results. Setting a limit may return fewer than the requested amount of items (up to zero items) in the event all requested objects are filtered out and clients should only use the presence of the continue field to determine whether more results are available. Servers may choose not to support the limit argument and will return all of the available results. If limit is specified and the continue field is empty, clients may assume that no more results are available. This field is not supported if watch is true. The server guarantees that the objects returned when using continue will be identical to issuing a single list call without a limit - that is, no objects created, modified, or deleted after the first request is issued will be included in any subsequent continued requests. This is sometimes referred to as a consistent snapshot, and ensures that a client that is using limit to receive smaller chunks of a very large result can ensure they see all possible objects. If objects are updated during a chunked list the version of the object that was present at the time the first list result was calculated is returned. | `pretty` | `string` | If 'true', then the output is pretty printed. | `resourceVersion` | `string` | resourceVersion sets a constraint on what resource versions a request may be served from. See https://kubernetes.io/docs/reference/using-api/api-concepts/#resource-versions for details. Defaults to unset | `resourceVersionMatch` | `string` | resourceVersionMatch determines how resourceVersion is applied to list calls. It is highly recommended that resourceVersionMatch be set for list calls where resourceVersion is set See https://kubernetes.io/docs/reference/using-api/api-concepts/#resource-versions for details. Defaults to unset | `timeoutSeconds` | `integer` | Timeout for the list/watch call. This limits the duration of the call, regardless of any activity or inactivity. | `watch` | `boolean` | Watch for changes to the described resources and return them as a stream of add, update, and remove notifications. Specify resourceVersion. |=== HTTP method:: `GET` Description:: watch individual changes to a list of StatefulSet. deprecated: use the 'watch' parameter with a list operation instead. .HTTP responses [cols=""1,1"",options=""header""] |=== | HTTP code | Reponse body | 200 - OK | xref:../objects/index.adoc#io.k8s.apimachinery.pkg.apis.meta.v1.WatchEvent[`WatchEvent`] schema | 401 - Unauthorized | Empty |=== === /apis/apps/v1/namespaces/{namespace}/statefulsets .Global path parameters [cols=""1,1,2"",options=""header""] |=== | Parameter | Type | Description | `namespace` | `string` | object name and auth scope, such as for teams and projects |=== .Global query parameters [cols=""1,1,2"",options=""header""] |=== | Parameter | Type | Description | `pretty` | `string` | If 'true', then the output is pretty printed. |=== HTTP method:: `DELETE` Description:: delete collection of StatefulSet .Query parameters [cols=""1,1,2"",options=""header""] |=== | Parameter | Type | Description | `continue` | `string` | The continue option should be set when retrieving more results from the server. Since this value is server defined, clients may only use the continue value from a previous query result with identical query parameters (except for the value of continue) and the server may reject a continue value it does not recognize. If the specified continue value is no longer valid whether due to expiration (generally five to fifteen minutes) or a configuration change on the server, the server will respond with a 410 ResourceExpired error together with a continue token. If the client needs a consistent list, it must restart their list without the continue field. Otherwise, the client may send another list request with the token received with the 410 error, the server will respond with a list starting from the next key, but from the latest snapshot, which is inconsistent from the previous list results - objects that are created, modified, or deleted after the first list request will be included in the response, as long as their keys are after the "next key". This field is not supported when watch is true. Clients may start a watch from the last resourceVersion value returned by the server and not miss any modifications. | `dryRun` | `string` | When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed | `fieldSelector` | `string` | A selector to restrict the list of returned objects by their fields. Defaults to everything. | `gracePeriodSeconds` | `integer` | The duration in seconds before the object should be deleted. Value must be non-negative integer. The value zero indicates delete immediately. If this value is nil, the default grace period for the specified type will be used. Defaults to a per object value if not specified. zero means delete immediately. | `labelSelector` | `string` | A selector to restrict the list of returned objects by their labels. Defaults to everything. | `limit` | `integer` | limit is a maximum number of responses to return for a list call. If more items exist, the server will set the `continue` field on the list metadata to a value that can be used with the same initial query to retrieve the next set of results. Setting a limit may return fewer than the requested amount of items (up to zero items) in the event all requested objects are filtered out and clients should only use the presence of the continue field to determine whether more results are available. Servers may choose not to support the limit argument and will return all of the available results. If limit is specified and the continue field is empty, clients may assume that no more results are available. This field is not supported if watch is true. The server guarantees that the objects returned when using continue will be identical to issuing a single list call without a limit - that is, no objects created, modified, or deleted after the first request is issued will be included in any subsequent continued requests. This is sometimes referred to as a consistent snapshot, and ensures that a client that is using limit to receive smaller chunks of a very large result can ensure they see all possible objects. If objects are updated during a chunked list the version of the object that was present at the time the first list result was calculated is returned. | `orphanDependents` | `boolean` | Deprecated: please use the PropagationPolicy, this field will be deprecated in 1.7. Should the dependent objects be orphaned. If true/false, the "orphan" finalizer will be added to/removed from the object's finalizers list. Either this field or PropagationPolicy may be set, but not both. | `propagationPolicy` | `string` | Whether and how garbage collection will be performed. Either this field or OrphanDependents may be set, but not both. The default policy is decided by the existing finalizer set in the metadata.finalizers and the resource-specific default policy. Acceptable values are: 'Orphan' - orphan the dependents; 'Background' - allow the garbage collector to delete the dependents in the background; 'Foreground' - a cascading policy that deletes all dependents in the foreground. | `resourceVersion` | `string` | resourceVersion sets a constraint on what resource versions a request may be served from. See https://kubernetes.io/docs/reference/using-api/api-concepts/#resource-versions for details. Defaults to unset | `resourceVersionMatch` | `string` | resourceVersionMatch determines how resourceVersion is applied to list calls. It is highly recommended that resourceVersionMatch be set for list calls where resourceVersion is set See https://kubernetes.io/docs/reference/using-api/api-concepts/#resource-versions for details. Defaults to unset | `timeoutSeconds` | `integer` | Timeout for the list/watch call. This limits the duration of the call, regardless of any activity or inactivity. |=== .Body parameters [cols=""1,1,2"",options=""header""] |=== | Parameter | Type | Description | `body` | xref:../objects/index.adoc#io.k8s.apimachinery.pkg.apis.meta.v1.DeleteOptions[`DeleteOptions`] schema | |=== .HTTP responses [cols=""1,1"",options=""header""] |=== | HTTP code | Reponse body | 200 - OK | xref:../objects/index.adoc#io.k8s.apimachinery.pkg.apis.meta.v1.Status[`Status`] schema | 401 - Unauthorized | Empty |=== HTTP method:: `GET` Description:: list or watch objects of kind StatefulSet .Query parameters [cols=""1,1,2"",options=""header""] |=== | Parameter | Type | Description | `allowWatchBookmarks` | `boolean` | allowWatchBookmarks requests watch events with type "BOOKMARK". Servers that do not implement bookmarks may ignore this flag and bookmarks are sent at the server's discretion. Clients should not assume bookmarks are returned at any specific interval, nor may they assume the server will send any BOOKMARK event during a session. If this is not a watch, this field is ignored. | `continue` | `string` | The continue option should be set when retrieving more results from the server. Since this value is server defined, clients may only use the continue value from a previous query result with identical query parameters (except for the value of continue) and the server may reject a continue value it does not recognize. If the specified continue value is no longer valid whether due to expiration (generally five to fifteen minutes) or a configuration change on the server, the server will respond with a 410 ResourceExpired error together with a continue token. If the client needs a consistent list, it must restart their list without the continue field. Otherwise, the client may send another list request with the token received with the 410 error, the server will respond with a list starting from the next key, but from the latest snapshot, which is inconsistent from the previous list results - objects that are created, modified, or deleted after the first list request will be included in the response, as long as their keys are after the "next key". This field is not supported when watch is true. Clients may start a watch from the last resourceVersion value returned by the server and not miss any modifications. | `fieldSelector` | `string` | A selector to restrict the list of returned objects by their fields. Defaults to everything. | `labelSelector` | `string` | A selector to restrict the list of returned objects by their labels. Defaults to everything. | `limit` | `integer` | limit is a maximum number of responses to return for a list call. If more items exist, the server will set the `continue` field on the list metadata to a value that can be used with the same initial query to retrieve the next set of results. Setting a limit may return fewer than the requested amount of items (up to zero items) in the event all requested objects are filtered out and clients should only use the presence of the continue field to determine whether more results are available. Servers may choose not to support the limit argument and will return all of the available results. If limit is specified and the continue field is empty, clients may assume that no more results are available. This field is not supported if watch is true. The server guarantees that the objects returned when using continue will be identical to issuing a single list call without a limit - that is, no objects created, modified, or deleted after the first request is issued will be included in any subsequent continued requests. This is sometimes referred to as a consistent snapshot, and ensures that a client that is using limit to receive smaller chunks of a very large result can ensure they see all possible objects. If objects are updated during a chunked list the version of the object that was present at the time the first list result was calculated is returned. | `resourceVersion` | `string` | resourceVersion sets a constraint on what resource versions a request may be served from. See https://kubernetes.io/docs/reference/using-api/api-concepts/#resource-versions for details. Defaults to unset | `resourceVersionMatch` | `string` | resourceVersionMatch determines how resourceVersion is applied to list calls. It is highly recommended that resourceVersionMatch be set for list calls where resourceVersion is set See https://kubernetes.io/docs/reference/using-api/api-concepts/#resource-versions for details. Defaults to unset | `timeoutSeconds` | `integer` | Timeout for the list/watch call. This limits the duration of the call, regardless of any activity or inactivity. | `watch` | `boolean` | Watch for changes to the described resources and return them as a stream of add, update, and remove notifications. Specify resourceVersion. |=== .HTTP responses [cols=""1,1"",options=""header""] |=== | HTTP code | Reponse body | 200 - OK | xref:../objects/index.adoc#io.k8s.api.apps.v1.StatefulSetList[`StatefulSetList`] schema | 401 - Unauthorized | Empty |=== HTTP method:: `POST` Description:: create a StatefulSet .Query parameters [cols=""1,1,2"",options=""header""] |=== | Parameter | Type | Description | `dryRun` | `string` | When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed | `fieldManager` | `string` | fieldManager is a name associated with the actor or entity that is making these changes. The value must be less than or 128 characters long, and only contain printable characters, as defined by https://golang.org/pkg/unicode/#IsPrint. |=== .Body parameters [cols=""1,1,2"",options=""header""] |=== | Parameter | Type | Description | `body` | xref:../workloads_apis/statefulset-apps-v1.adoc#statefulset-apps-v1[`StatefulSet`] schema | |=== .HTTP responses [cols=""1,1"",options=""header""] |=== | HTTP code | Reponse body | 200 - OK | xref:../workloads_apis/statefulset-apps-v1.adoc#statefulset-apps-v1[`StatefulSet`] schema | 201 - Created | xref:../workloads_apis/statefulset-apps-v1.adoc#statefulset-apps-v1[`StatefulSet`] schema | 202 - Accepted | xref:../workloads_apis/statefulset-apps-v1.adoc#statefulset-apps-v1[`StatefulSet`] schema | 401 - Unauthorized | Empty |=== === /apis/apps/v1/watch/namespaces/{namespace}/statefulsets .Global path parameters [cols=""1,1,2"",options=""header""] |=== | Parameter | Type | Description | `namespace` | `string` | object name and auth scope, such as for teams and projects |=== .Global query parameters [cols=""1,1,2"",options=""header""] |=== | Parameter | Type | Description | `allowWatchBookmarks` | `boolean` | allowWatchBookmarks requests watch events with type "BOOKMARK". Servers that do not implement bookmarks may ignore this flag and bookmarks are sent at the server's discretion. Clients should not assume bookmarks are returned at any specific interval, nor may they assume the server will send any BOOKMARK event during a session. If this is not a watch, this field is ignored. | `continue` | `string` | The continue option should be set when retrieving more results from the server. Since this value is server defined, clients may only use the continue value from a previous query result with identical query parameters (except for the value of continue) and the server may reject a continue value it does not recognize. If the specified continue value is no longer valid whether due to expiration (generally five to fifteen minutes) or a configuration change on the server, the server will respond with a 410 ResourceExpired error together with a continue token. If the client needs a consistent list, it must restart their list without the continue field. Otherwise, the client may send another list request with the token received with the 410 error, the server will respond with a list starting from the next key, but from the latest snapshot, which is inconsistent from the previous list results - objects that are created, modified, or deleted after the first list request will be included in the response, as long as their keys are after the "next key". This field is not supported when watch is true. Clients may start a watch from the last resourceVersion value returned by the server and not miss any modifications. | `fieldSelector` | `string` | A selector to restrict the list of returned objects by their fields. Defaults to everything. | `labelSelector` | `string` | A selector to restrict the list of returned objects by their labels. Defaults to everything. | `limit` | `integer` | limit is a maximum number of responses to return for a list call. If more items exist, the server will set the `continue` field on the list metadata to a value that can be used with the same initial query to retrieve the next set of results. Setting a limit may return fewer than the requested amount of items (up to zero items) in the event all requested objects are filtered out and clients should only use the presence of the continue field to determine whether more results are available. Servers may choose not to support the limit argument and will return all of the available results. If limit is specified and the continue field is empty, clients may assume that no more results are available. This field is not supported if watch is true. The server guarantees that the objects returned when using continue will be identical to issuing a single list call without a limit - that is, no objects created, modified, or deleted after the first request is issued will be included in any subsequent continued requests. This is sometimes referred to as a consistent snapshot, and ensures that a client that is using limit to receive smaller chunks of a very large result can ensure they see all possible objects. If objects are updated during a chunked list the version of the object that was present at the time the first list result was calculated is returned. | `pretty` | `string` | If 'true', then the output is pretty printed. | `resourceVersion` | `string` | resourceVersion sets a constraint on what resource versions a request may be served from. See https://kubernetes.io/docs/reference/using-api/api-concepts/#resource-versions for details. Defaults to unset | `resourceVersionMatch` | `string` | resourceVersionMatch determines how resourceVersion is applied to list calls. It is highly recommended that resourceVersionMatch be set for list calls where resourceVersion is set See https://kubernetes.io/docs/reference/using-api/api-concepts/#resource-versions for details. Defaults to unset | `timeoutSeconds` | `integer` | Timeout for the list/watch call. This limits the duration of the call, regardless of any activity or inactivity. | `watch` | `boolean` | Watch for changes to the described resources and return them as a stream of add, update, and remove notifications. Specify resourceVersion. |=== HTTP method:: `GET` Description:: watch individual changes to a list of StatefulSet. deprecated: use the 'watch' parameter with a list operation instead. .HTTP responses [cols=""1,1"",options=""header""] |=== | HTTP code | Reponse body | 200 - OK | xref:../objects/index.adoc#io.k8s.apimachinery.pkg.apis.meta.v1.WatchEvent[`WatchEvent`] schema | 401 - Unauthorized | Empty |=== === /apis/apps/v1/namespaces/{namespace}/statefulsets/{name} .Global path parameters [cols=""1,1,2"",options=""header""] |=== | Parameter | Type | Description | `name` | `string` | name of the StatefulSet | `namespace` | `string` | object name and auth scope, such as for teams and projects |=== .Global query parameters [cols=""1,1,2"",options=""header""] |=== | Parameter | Type | Description | `pretty` | `string` | If 'true', then the output is pretty printed. |=== HTTP method:: `DELETE` Description:: delete a StatefulSet .Query parameters [cols=""1,1,2"",options=""header""] |=== | Parameter | Type | Description | `dryRun` | `string` | When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed | `gracePeriodSeconds` | `integer` | The duration in seconds before the object should be deleted. Value must be non-negative integer. The value zero indicates delete immediately. If this value is nil, the default grace period for the specified type will be used. Defaults to a per object value if not specified. zero means delete immediately. | `orphanDependents` | `boolean` | Deprecated: please use the PropagationPolicy, this field will be deprecated in 1.7. Should the dependent objects be orphaned. If true/false, the "orphan" finalizer will be added to/removed from the object's finalizers list. Either this field or PropagationPolicy may be set, but not both. | `propagationPolicy` | `string` | Whether and how garbage collection will be performed. Either this field or OrphanDependents may be set, but not both. The default policy is decided by the existing finalizer set in the metadata.finalizers and the resource-specific default policy. Acceptable values are: 'Orphan' - orphan the dependents; 'Background' - allow the garbage collector to delete the dependents in the background; 'Foreground' - a cascading policy that deletes all dependents in the foreground. |=== .Body parameters [cols=""1,1,2"",options=""header""] |=== | Parameter | Type | Description | `body` | xref:../objects/index.adoc#io.k8s.apimachinery.pkg.apis.meta.v1.DeleteOptions[`DeleteOptions`] schema | |=== .HTTP responses [cols=""1,1"",options=""header""] |=== | HTTP code | Reponse body | 200 - OK | xref:../objects/index.adoc#io.k8s.apimachinery.pkg.apis.meta.v1.Status[`Status`] schema | 202 - Accepted | xref:../objects/index.adoc#io.k8s.apimachinery.pkg.apis.meta.v1.Status[`Status`] schema | 401 - Unauthorized | Empty |=== HTTP method:: `GET` Description:: read the specified StatefulSet .HTTP responses [cols=""1,1"",options=""header""] |=== | HTTP code | Reponse body | 200 - OK | xref:../workloads_apis/statefulset-apps-v1.adoc#statefulset-apps-v1[`StatefulSet`] schema | 401 - Unauthorized | Empty |=== HTTP method:: `PATCH` Description:: partially update the specified StatefulSet .Query parameters [cols=""1,1,2"",options=""header""] |=== | Parameter | Type | Description | `dryRun` | `string` | When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed | `fieldManager` | `string` | fieldManager is a name associated with the actor or entity that is making these changes. The value must be less than or 128 characters long, and only contain printable characters, as defined by https://golang.org/pkg/unicode/#IsPrint. This field is required for apply requests (application/apply-patch) but optional for non-apply patch types (JsonPatch, MergePatch, StrategicMergePatch). | `force` | `boolean` | Force is going to "force" Apply requests. It means user will re-acquire conflicting fields owned by other people. Force flag must be unset for non-apply patch requests. |=== .Body parameters [cols=""1,1,2"",options=""header""] |=== | Parameter | Type | Description | `body` | xref:../objects/index.adoc#io.k8s.apimachinery.pkg.apis.meta.v1.Patch[`Patch`] schema | |=== .HTTP responses [cols=""1,1"",options=""header""] |=== | HTTP code | Reponse body | 200 - OK | xref:../workloads_apis/statefulset-apps-v1.adoc#statefulset-apps-v1[`StatefulSet`] schema | 201 - Created | xref:../workloads_apis/statefulset-apps-v1.adoc#statefulset-apps-v1[`StatefulSet`] schema | 401 - Unauthorized | Empty |=== HTTP method:: `PUT` Description:: replace the specified StatefulSet .Query parameters [cols=""1,1,2"",options=""header""] |=== | Parameter | Type | Description | `dryRun` | `string` | When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed | `fieldManager` | `string` | fieldManager is a name associated with the actor or entity that is making these changes. The value must be less than or 128 characters long, and only contain printable characters, as defined by https://golang.org/pkg/unicode/#IsPrint. |=== .Body parameters [cols=""1,1,2"",options=""header""] |=== | Parameter | Type | Description | `body` | xref:../workloads_apis/statefulset-apps-v1.adoc#statefulset-apps-v1[`StatefulSet`] schema | |=== .HTTP responses [cols=""1,1"",options=""header""] |=== | HTTP code | Reponse body | 200 - OK | xref:../workloads_apis/statefulset-apps-v1.adoc#statefulset-apps-v1[`StatefulSet`] schema | 201 - Created | xref:../workloads_apis/statefulset-apps-v1.adoc#statefulset-apps-v1[`StatefulSet`] schema | 401 - Unauthorized | Empty |=== === /apis/apps/v1/watch/namespaces/{namespace}/statefulsets/{name} .Global path parameters [cols=""1,1,2"",options=""header""] |=== | Parameter | Type | Description | `name` | `string` | name of the StatefulSet | `namespace` | `string` | object name and auth scope, such as for teams and projects |=== .Global query parameters [cols=""1,1,2"",options=""header""] |=== | Parameter | Type | Description | `allowWatchBookmarks` | `boolean` | allowWatchBookmarks requests watch events with type "BOOKMARK". Servers that do not implement bookmarks may ignore this flag and bookmarks are sent at the server's discretion. Clients should not assume bookmarks are returned at any specific interval, nor may they assume the server will send any BOOKMARK event during a session. If this is not a watch, this field is ignored. | `continue` | `string` | The continue option should be set when retrieving more results from the server. Since this value is server defined, clients may only use the continue value from a previous query result with identical query parameters (except for the value of continue) and the server may reject a continue value it does not recognize. If the specified continue value is no longer valid whether due to expiration (generally five to fifteen minutes) or a configuration change on the server, the server will respond with a 410 ResourceExpired error together with a continue token. If the client needs a consistent list, it must restart their list without the continue field. Otherwise, the client may send another list request with the token received with the 410 error, the server will respond with a list starting from the next key, but from the latest snapshot, which is inconsistent from the previous list results - objects that are created, modified, or deleted after the first list request will be included in the response, as long as their keys are after the "next key". This field is not supported when watch is true. Clients may start a watch from the last resourceVersion value returned by the server and not miss any modifications. | `fieldSelector` | `string` | A selector to restrict the list of returned objects by their fields. Defaults to everything. | `labelSelector` | `string` | A selector to restrict the list of returned objects by their labels. Defaults to everything. | `limit` | `integer` | limit is a maximum number of responses to return for a list call. If more items exist, the server will set the `continue` field on the list metadata to a value that can be used with the same initial query to retrieve the next set of results. Setting a limit may return fewer than the requested amount of items (up to zero items) in the event all requested objects are filtered out and clients should only use the presence of the continue field to determine whether more results are available. Servers may choose not to support the limit argument and will return all of the available results. If limit is specified and the continue field is empty, clients may assume that no more results are available. This field is not supported if watch is true. The server guarantees that the objects returned when using continue will be identical to issuing a single list call without a limit - that is, no objects created, modified, or deleted after the first request is issued will be included in any subsequent continued requests. This is sometimes referred to as a consistent snapshot, and ensures that a client that is using limit to receive smaller chunks of a very large result can ensure they see all possible objects. If objects are updated during a chunked list the version of the object that was present at the time the first list result was calculated is returned. | `pretty` | `string` | If 'true', then the output is pretty printed. | `resourceVersion` | `string` | resourceVersion sets a constraint on what resource versions a request may be served from. See https://kubernetes.io/docs/reference/using-api/api-concepts/#resource-versions for details. Defaults to unset | `resourceVersionMatch` | `string` | resourceVersionMatch determines how resourceVersion is applied to list calls. It is highly recommended that resourceVersionMatch be set for list calls where resourceVersion is set See https://kubernetes.io/docs/reference/using-api/api-concepts/#resource-versions for details. Defaults to unset | `timeoutSeconds` | `integer` | Timeout for the list/watch call. This limits the duration of the call, regardless of any activity or inactivity. | `watch` | `boolean` | Watch for changes to the described resources and return them as a stream of add, update, and remove notifications. Specify resourceVersion. |=== HTTP method:: `GET` Description:: watch changes to an object of kind StatefulSet. deprecated: use the 'watch' parameter with a list operation instead, filtered to a single item with the 'fieldSelector' parameter. .HTTP responses [cols=""1,1"",options=""header""] |=== | HTTP code | Reponse body | 200 - OK | xref:../objects/index.adoc#io.k8s.apimachinery.pkg.apis.meta.v1.WatchEvent[`WatchEvent`] schema | 401 - Unauthorized | Empty |=== === /apis/apps/v1/namespaces/{namespace}/statefulsets/{name}/status .Global path parameters [cols=""1,1,2"",options=""header""] |=== | Parameter | Type | Description | `name` | `string` | name of the StatefulSet | `namespace` | `string` | object name and auth scope, such as for teams and projects |=== .Global query parameters [cols=""1,1,2"",options=""header""] |=== | Parameter | Type | Description | `pretty` | `string` | If 'true', then the output is pretty printed. |=== HTTP method:: `GET` Description:: read status of the specified StatefulSet .HTTP responses [cols=""1,1"",options=""header""] |=== | HTTP code | Reponse body | 200 - OK | xref:../workloads_apis/statefulset-apps-v1.adoc#statefulset-apps-v1[`StatefulSet`] schema | 401 - Unauthorized | Empty |=== HTTP method:: `PATCH` Description:: partially update status of the specified StatefulSet .Query parameters [cols=""1,1,2"",options=""header""] |=== | Parameter | Type | Description | `dryRun` | `string` | When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed | `fieldManager` | `string` | fieldManager is a name associated with the actor or entity that is making these changes. The value must be less than or 128 characters long, and only contain printable characters, as defined by https://golang.org/pkg/unicode/#IsPrint. This field is required for apply requests (application/apply-patch) but optional for non-apply patch types (JsonPatch, MergePatch, StrategicMergePatch). | `force` | `boolean` | Force is going to "force" Apply requests. It means user will re-acquire conflicting fields owned by other people. Force flag must be unset for non-apply patch requests. |=== .Body parameters [cols=""1,1,2"",options=""header""] |=== | Parameter | Type | Description | `body` | xref:../objects/index.adoc#io.k8s.apimachinery.pkg.apis.meta.v1.Patch[`Patch`] schema | |=== .HTTP responses [cols=""1,1"",options=""header""] |=== | HTTP code | Reponse body | 200 - OK | xref:../workloads_apis/statefulset-apps-v1.adoc#statefulset-apps-v1[`StatefulSet`] schema | 201 - Created | xref:../workloads_apis/statefulset-apps-v1.adoc#statefulset-apps-v1[`StatefulSet`] schema | 401 - Unauthorized | Empty |=== HTTP method:: `PUT` Description:: replace status of the specified StatefulSet .Query parameters [cols=""1,1,2"",options=""header""] |=== | Parameter | Type | Description | `dryRun` | `string` | When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed | `fieldManager` | `string` | fieldManager is a name associated with the actor or entity that is making these changes. The value must be less than or 128 characters long, and only contain printable characters, as defined by https://golang.org/pkg/unicode/#IsPrint. |=== .Body parameters [cols=""1,1,2"",options=""header""] |=== | Parameter | Type | Description | `body` | xref:../workloads_apis/statefulset-apps-v1.adoc#statefulset-apps-v1[`StatefulSet`] schema | |=== .HTTP responses [cols=""1,1"",options=""header""] |=== | HTTP code | Reponse body | 200 - OK | xref:../workloads_apis/statefulset-apps-v1.adoc#statefulset-apps-v1[`StatefulSet`] schema | 201 - Created | xref:../workloads_apis/statefulset-apps-v1.adoc#statefulset-apps-v1[`StatefulSet`] schema | 401 - Unauthorized | Empty |=== ",12201,True,3039.2138706375436,median "/*******************************************************************\\ Module: GOTO Programs Author: Daniel Kroening, kroening@kroening.com \\*******************************************************************/ /// \\file /// GOTO Programs #include ""goto_check.h"" #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include ""guard.h"" #include ""local_bitvector_analysis.h"" class goto_checkt { public: goto_checkt( const namespacet &_ns, const optionst &_options): ns(_ns), local_bitvector_analysis(nullptr) { no_enum_check = false; enable_bounds_check=_options.get_bool_option(""bounds-check""); enable_pointer_check=_options.get_bool_option(""pointer-check""); enable_memory_leak_check=_options.get_bool_option(""memory-leak-check""); enable_div_by_zero_check=_options.get_bool_option(""div-by-zero-check""); enable_enum_range_check = _options.get_bool_option(""enum-range-check""); enable_signed_overflow_check= _options.get_bool_option(""signed-overflow-check""); enable_unsigned_overflow_check= _options.get_bool_option(""unsigned-overflow-check""); enable_pointer_overflow_check= _options.get_bool_option(""pointer-overflow-check""); enable_conversion_check=_options.get_bool_option(""conversion-check""); enable_undefined_shift_check= _options.get_bool_option(""undefined-shift-check""); enable_float_overflow_check= _options.get_bool_option(""float-overflow-check""); enable_simplify=_options.get_bool_option(""simplify""); enable_nan_check=_options.get_bool_option(""nan-check""); retain_trivial=_options.get_bool_option(""retain-trivial""); enable_assert_to_assume=_options.get_bool_option(""assert-to-assume""); enable_assertions=_options.get_bool_option(""assertions""); enable_built_in_assertions=_options.get_bool_option(""built-in-assertions""); enable_assumptions=_options.get_bool_option(""assumptions""); error_labels=_options.get_list_option(""error-label""); enable_pointer_primitive_check = _options.get_bool_option(""pointer-primitive-check""); } typedef goto_functionst::goto_functiont goto_functiont; void goto_check( const irep_idt &function_identifier, goto_functiont &goto_function); /// Fill the list of allocations \\ref allocationst with for /// every allocation instruction. Also check that each allocation is /// well-formed. /// \\param goto_functions: goto functions from which the allocations are to be /// collected void collect_allocations(const goto_functionst &goto_functions); protected: const namespacet &ns; std::unique_ptr local_bitvector_analysis; goto_programt::const_targett current_target; guard_managert guard_manager; bool no_enum_check; /// Check an address-of expression: /// if it is a dereference then check the pointer /// if it is an index then address-check the array and then check the index /// \\param expr: the expression to be checked /// \\param guard: the condition for the check (unmodified here) void check_rec_address(const exprt &expr, guardt &guard); /// Check a logical operation: check each operand in separation while /// extending the guarding condition as follows. /// a /\\ b /\\ c ==> check(a, TRUE), check(b, a), check (c, a /\\ b) /// a \\/ b \\/ c ==> check(a, TRUE), check(b, ~a), check (c, ~a /\\ ~b) /// \\param expr: the expression to be checked /// \\param guard: the condition for the check (extended with the previous /// operands (or their negations) for recursively calls) void check_rec_logical_op(const exprt &expr, guardt &guard); /// Check an if expression: check the if-condition alone, and then check the /// true/false-cases with the guard extended with if-condition and it's /// negation, respectively. /// \\param if_expr: the expression to be checked /// \\param guard: the condition for the check (extended with the (negation of /// the) if-condition for recursively calls) void check_rec_if(const if_exprt &if_expr, guardt &guard); /// Check that a member expression is valid: /// - check the structure this expression is a member of (via pointer of its /// dereference) /// - run pointer-validity check on `*(s+member_offset)' instead of /// `s->member' to avoid checking safety of `s' /// - check all operands of the expression /// \\param member: the expression to be checked /// \\param guard: the condition for the check (unmodified here) /// \\return true if no more checks are required for \\p member or its /// sub-expressions bool check_rec_member(const member_exprt &member, guardt &guard); /// Check that a division is valid: check for division by zero, overflow and /// NaN (for floating point numbers). /// \\param div_expr: the expression to be checked /// \\param guard: the condition for the check (unmodified here) void check_rec_div(const div_exprt &div_expr, guardt &guard); /// Check that an arithmetic operation is valid: overflow check, NaN-check /// (for floating point numbers), and pointer overflow check. /// \\param expr: the expression to be checked /// \\param guard: the condition for the check (unmodified here) void check_rec_arithmetic_op(const exprt &expr, guardt &guard); /// Recursively descend into \\p expr and run the appropriate check for each /// sub-expression, while collecting the condition for the check in \\p /// guard. /// \\param expr: the expression to be checked /// \\param guard: the condition for when the check should be made void check_rec(const exprt &expr, guardt &guard); /// Initiate the recursively analysis of \\p expr with its `guard' set to TRUE. /// \\param expr: the expression to be checked void check(const exprt &expr); struct conditiont { conditiont(const exprt &_assertion, const std::string &_description) : assertion(_assertion), description(_description) { } exprt assertion; std::string description; }; using conditionst = std::list; void bounds_check(const index_exprt &, const guardt &); void div_by_zero_check(const div_exprt &, const guardt &); void mod_by_zero_check(const mod_exprt &, const guardt &); void mod_overflow_check(const mod_exprt &, const guardt &); void enum_range_check(const exprt &, const guardt &); void undefined_shift_check(const shift_exprt &, const guardt &); void pointer_rel_check(const binary_relation_exprt &, const guardt &); void pointer_overflow_check(const exprt &, const guardt &); /// Generates VCCs for the validity of the given dereferencing operation. /// \\param expr the expression to be checked /// \\param src_expr The expression as found in the program, /// prior to any rewriting /// \\param guard the condition under which the operation happens void pointer_validity_check( const dereference_exprt &expr, const exprt &src_expr, const guardt &guard); /// Generates VCCs to check that pointers passed to pointer primitives are /// either null or valid /// /// \\param expr: the pointer primitive expression /// \\param guard: the condition under which the operation happens void pointer_primitive_check(const exprt &expr, const guardt &guard); /// Returns true if the given expression is a pointer primitive such as /// __CPROVER_r_ok() /// /// \\param expr expression /// \\return true if the given expression is a pointer primitive bool is_pointer_primitive(const exprt &expr); optionalt get_pointer_is_null_condition(const exprt &address, const exprt &size); conditionst get_pointer_points_to_valid_memory_conditions( const exprt &address, const exprt &size); exprt is_in_bounds_of_some_explicit_allocation( const exprt &pointer, const exprt &size); conditionst get_pointer_dereferenceable_conditions( const exprt &address, const exprt &size); void integer_overflow_check(const exprt &, const guardt &); void conversion_check(const exprt &, const guardt &); void float_overflow_check(const exprt &, const guardt &); void nan_check(const exprt &, const guardt &); optionalt rw_ok_check(exprt); std::string array_name(const exprt &); /// Include the \\p asserted_expr in the code conditioned by the \\p guard. /// \\param asserted_expr: expression to be asserted /// \\param comment: human readable comment /// \\param property_class: classification of the property /// \\param source_location: the source location of the original expression /// \\param src_expr: the original expression to be included in the comment /// \\param guard: the condition under which the asserted expression should be /// taken into account void add_guarded_property( const exprt &asserted_expr, const std::string &comment, const std::string &property_class, const source_locationt &source_location, const exprt &src_expr, const guardt &guard); goto_programt new_code; typedef std::set assertionst; assertionst assertions; /// Remove all assertions containing the symbol in \\p lhs as well as all /// assertions containing dereference. /// \\param lhs: the left-hand-side expression whose symbol should be /// invalidated void invalidate(const exprt &lhs); bool enable_bounds_check; bool enable_pointer_check; bool enable_memory_leak_check; bool enable_div_by_zero_check; bool enable_enum_range_check; bool enable_signed_overflow_check; bool enable_unsigned_overflow_check; bool enable_pointer_overflow_check; bool enable_conversion_check; bool enable_undefined_shift_check; bool enable_float_overflow_check; bool enable_simplify; bool enable_nan_check; bool retain_trivial; bool enable_assert_to_assume; bool enable_assertions; bool enable_built_in_assertions; bool enable_assumptions; bool enable_pointer_primitive_check; typedef optionst::value_listt error_labelst; error_labelst error_labels; // the first element of the pair is the base address, // and the second is the size of the region typedef std::pair allocationt; typedef std::list allocationst; allocationst allocations; irep_idt mode; }; void goto_checkt::collect_allocations( const goto_functionst &goto_functions) { if(!enable_pointer_check && !enable_bounds_check) return; forall_goto_functions(itf, goto_functions) forall_goto_program_instructions(it, itf->second.body) { const goto_programt::instructiont &instruction=*it; if(!instruction.is_function_call()) continue; const code_function_callt &call= to_code_function_call(instruction.code); if(call.function().id()!=ID_symbol || to_symbol_expr(call.function()).get_identifier()!= CPROVER_PREFIX ""allocated_memory"") continue; const code_function_callt::argumentst &args= call.arguments(); if(args.size()!=2 || args[0].type().id()!=ID_unsignedbv || args[1].type().id()!=ID_unsignedbv) throw ""expected two unsigned arguments to "" CPROVER_PREFIX ""allocated_memory""; assert(args[0].type()==args[1].type()); allocations.push_back({args[0], args[1]}); } } void goto_checkt::invalidate(const exprt &lhs) { if(lhs.id()==ID_index) invalidate(to_index_expr(lhs).array()); else if(lhs.id()==ID_member) invalidate(to_member_expr(lhs).struct_op()); else if(lhs.id()==ID_symbol) { // clear all assertions about 'symbol' find_symbols_sett find_symbols_set{to_symbol_expr(lhs).get_identifier()}; for(auto it = assertions.begin(); it != assertions.end();) { if(has_symbol(*it, find_symbols_set) || has_subexpr(*it, ID_dereference)) it = assertions.erase(it); else ++it; } } else { // give up, clear all assertions.clear(); } } void goto_checkt::div_by_zero_check( const div_exprt &expr, const guardt &guard) { if(!enable_div_by_zero_check) return; // add divison by zero subgoal exprt zero=from_integer(0, expr.op1().type()); const notequal_exprt inequality(expr.op1(), std::move(zero)); add_guarded_property( inequality, ""division by zero"", ""division-by-zero"", expr.find_source_location(), expr, guard); } void goto_checkt::enum_range_check(const exprt &expr, const guardt &guard) { if(!enable_enum_range_check || no_enum_check) return; const c_enum_tag_typet &c_enum_tag_type = to_c_enum_tag_type(expr.type()); symbolt enum_type = ns.lookup(c_enum_tag_type.get_identifier()); const c_enum_typet &c_enum_type = to_c_enum_type(enum_type.type); const c_enum_typet::memberst enum_values = c_enum_type.members(); std::vector disjuncts; for(const auto &enum_value : enum_values) { const constant_exprt val{enum_value.get_value(), c_enum_tag_type}; disjuncts.push_back(equal_exprt(expr, val)); } const exprt check = disjunction(disjuncts); add_guarded_property( check, ""enum range check"", ""enum-range-check"", expr.find_source_location(), expr, guard); } void goto_checkt::undefined_shift_check( const shift_exprt &expr, const guardt &guard) { if(!enable_undefined_shift_check) return; // Undefined for all types and shifts if distance exceeds width, // and also undefined for negative distances. const typet &distance_type = expr.distance().type(); if(distance_type.id()==ID_signedbv) { binary_relation_exprt inequality( expr.distance(), ID_ge, from_integer(0, distance_type)); add_guarded_property( inequality, ""shift distance is negative"", ""undefined-shift"", expr.find_source_location(), expr, guard); } const typet &op_type = expr.op().type(); if(op_type.id()==ID_unsignedbv || op_type.id()==ID_signedbv) { exprt width_expr= from_integer(to_bitvector_type(op_type).get_width(), distance_type); add_guarded_property( binary_relation_exprt(expr.distance(), ID_lt, std::move(width_expr)), ""shift distance too large"", ""undefined-shift"", expr.find_source_location(), expr, guard); if(op_type.id()==ID_signedbv && expr.id()==ID_shl) { binary_relation_exprt inequality( expr.op(), ID_ge, from_integer(0, op_type)); add_guarded_property( inequality, ""shift operand is negative"", ""undefined-shift"", expr.find_source_location(), expr, guard); } } else { add_guarded_property( false_exprt(), ""shift of non-integer type"", ""undefined-shift"", expr.find_source_location(), expr, guard); } } void goto_checkt::mod_by_zero_check( const mod_exprt &expr, const guardt &guard) { if(!enable_div_by_zero_check || mode == ID_java) return; // add divison by zero subgoal exprt zero=from_integer(0, expr.op1().type()); const notequal_exprt inequality(expr.op1(), std::move(zero)); add_guarded_property( inequality, ""division by zero"", ""division-by-zero"", expr.find_source_location(), expr, guard); } /// check a mod expression for the case INT_MIN % -1 void goto_checkt::mod_overflow_check(const mod_exprt &expr, const guardt &guard) { if(!enable_signed_overflow_check) return; const auto &type = expr.type(); if(type.id() == ID_signedbv) { // INT_MIN % -1 is, in principle, defined to be zero in // ANSI C, C99, C++98, and C++11. Most compilers, however, // fail to produce 0, and in some cases generate an exception. // C11 explicitly makes this case undefined. notequal_exprt int_min_neq( expr.op0(), to_signedbv_type(type).smallest_expr()); notequal_exprt minus_one_neq( expr.op1(), from_integer(-1, expr.op1().type())); add_guarded_property( or_exprt(int_min_neq, minus_one_neq), ""result of signed mod is not representable"", ""overflow"", expr.find_source_location(), expr, guard); } } void goto_checkt::conversion_check( const exprt &expr, const guardt &guard) { if(!enable_conversion_check) return; // First, check type. const typet &type = expr.type(); if(type.id()!=ID_signedbv && type.id()!=ID_unsignedbv) return; if(expr.id()==ID_typecast) { const auto &op = to_typecast_expr(expr).op(); // conversion to signed int may overflow const typet &old_type = op.type(); if(type.id()==ID_signedbv) { std::size_t new_width=to_signedbv_type(type).get_width(); if(old_type.id()==ID_signedbv) // signed -> signed { std::size_t old_width=to_signedbv_type(old_type).get_width(); if(new_width>=old_width) return; // always ok const binary_relation_exprt no_overflow_upper( op, ID_le, from_integer(power(2, new_width - 1) - 1, old_type)); const binary_relation_exprt no_overflow_lower( op, ID_ge, from_integer(-power(2, new_width - 1), old_type)); add_guarded_property( and_exprt(no_overflow_lower, no_overflow_upper), ""arithmetic overflow on signed type conversion"", ""overflow"", expr.find_source_location(), expr, guard); } else if(old_type.id()==ID_unsignedbv) // unsigned -> signed { std::size_t old_width=to_unsignedbv_type(old_type).get_width(); if(new_width>=old_width+1) return; // always ok const binary_relation_exprt no_overflow_upper( op, ID_le, from_integer(power(2, new_width - 1) - 1, old_type)); add_guarded_property( no_overflow_upper, ""arithmetic overflow on unsigned to signed type conversion"", ""overflow"", expr.find_source_location(), expr, guard); } else if(old_type.id()==ID_floatbv) // float -> signed { // Note that the fractional part is truncated! ieee_floatt upper(to_floatbv_type(old_type)); upper.from_integer(power(2, new_width-1)); const binary_relation_exprt no_overflow_upper( op, ID_lt, upper.to_expr()); ieee_floatt lower(to_floatbv_type(old_type)); lower.from_integer(-power(2, new_width-1)-1); const binary_relation_exprt no_overflow_lower( op, ID_gt, lower.to_expr()); add_guarded_property( and_exprt(no_overflow_lower, no_overflow_upper), ""arithmetic overflow on float to signed integer type conversion"", ""overflow"", expr.find_source_location(), expr, guard); } } else if(type.id()==ID_unsignedbv) { std::size_t new_width=to_unsignedbv_type(type).get_width(); if(old_type.id()==ID_signedbv) // signed -> unsigned { std::size_t old_width=to_signedbv_type(old_type).get_width(); if(new_width>=old_width-1) { // only need lower bound check const binary_relation_exprt no_overflow_lower( op, ID_ge, from_integer(0, old_type)); add_guarded_property( no_overflow_lower, ""arithmetic overflow on signed to unsigned type conversion"", ""overflow"", expr.find_source_location(), expr, guard); } else { // need both const binary_relation_exprt no_overflow_upper( op, ID_le, from_integer(power(2, new_width) - 1, old_type)); const binary_relation_exprt no_overflow_lower( op, ID_ge, from_integer(0, old_type)); add_guarded_property( and_exprt(no_overflow_lower, no_overflow_upper), ""arithmetic overflow on signed to unsigned type conversion"", ""overflow"", expr.find_source_location(), expr, guard); } } else if(old_type.id()==ID_unsignedbv) // unsigned -> unsigned { std::size_t old_width=to_unsignedbv_type(old_type).get_width(); if(new_width>=old_width) return; // always ok const binary_relation_exprt no_overflow_upper( op, ID_le, from_integer(power(2, new_width) - 1, old_type)); add_guarded_property( no_overflow_upper, ""arithmetic overflow on unsigned to unsigned type conversion"", ""overflow"", expr.find_source_location(), expr, guard); } else if(old_type.id()==ID_floatbv) // float -> unsigned { // Note that the fractional part is truncated! ieee_floatt upper(to_floatbv_type(old_type)); upper.from_integer(power(2, new_width)-1); const binary_relation_exprt no_overflow_upper( op, ID_lt, upper.to_expr()); ieee_floatt lower(to_floatbv_type(old_type)); lower.from_integer(-1); const binary_relation_exprt no_overflow_lower( op, ID_gt, lower.to_expr()); add_guarded_property( and_exprt(no_overflow_lower, no_overflow_upper), ""arithmetic overflow on float to unsigned integer type conversion"", ""overflow"", expr.find_source_location(), expr, guard); } } } } void goto_checkt::integer_overflow_check( const exprt &expr, const guardt &guard) { if(!enable_signed_overflow_check && !enable_unsigned_overflow_check) return; // First, check type. const typet &type = expr.type(); if(type.id()==ID_signedbv && !enable_signed_overflow_check) return; if(type.id()==ID_unsignedbv && !enable_unsigned_overflow_check) return; // add overflow subgoal if(expr.id()==ID_div) { // undefined for signed division INT_MIN/-1 if(type.id()==ID_signedbv) { const auto &div_expr = to_div_expr(expr); equal_exprt int_min_eq( div_expr.dividend(), to_signedbv_type(type).smallest_expr()); equal_exprt minus_one_eq(div_expr.divisor(), from_integer(-1, type)); add_guarded_property( not_exprt(and_exprt(int_min_eq, minus_one_eq)), ""arithmetic overflow on signed division"", ""overflow"", expr.find_source_location(), expr, guard); } return; } else if(expr.id()==ID_unary_minus) { if(type.id()==ID_signedbv) { // overflow on unary- can only happen with the smallest // representable number 100....0 equal_exprt int_min_eq( to_unary_minus_expr(expr).op(), to_signedbv_type(type).smallest_expr()); add_guarded_property( not_exprt(int_min_eq), ""arithmetic overflow on signed unary minus"", ""overflow"", expr.find_source_location(), expr, guard); } return; } else if(expr.id() == ID_shl) { if(type.id() == ID_signedbv) { const auto &shl_expr = to_shl_expr(expr); const auto &op = shl_expr.op(); const auto &op_type = to_signedbv_type(type); const auto op_width = op_type.get_width(); const auto &distance = shl_expr.distance(); const auto &distance_type = distance.type(); // a left shift of a negative value is undefined; // yet this isn't an overflow exprt neg_value_shift; if(op_type.id() == ID_unsignedbv) neg_value_shift = false_exprt(); else neg_value_shift = binary_relation_exprt(op, ID_lt, from_integer(0, op_type)); // a shift with negative distance is undefined; // yet this isn't an overflow exprt neg_dist_shift; if(distance_type.id() == ID_unsignedbv) neg_dist_shift = false_exprt(); else neg_dist_shift = binary_relation_exprt(op, ID_lt, from_integer(0, distance_type)); // shifting a non-zero value by more than its width is undefined; // yet this isn't an overflow const exprt dist_too_large = binary_predicate_exprt( distance, ID_gt, from_integer(op_width, distance_type)); const exprt op_zero = equal_exprt(op, from_integer(0, op_type)); auto new_type = to_bitvector_type(op_type); new_type.set_width(op_width * 2); const exprt op_ext = typecast_exprt(op, new_type); const exprt op_ext_shifted = shl_exprt(op_ext, distance); // The semantics of signed left shifts are contentious for the case // that a '1' is shifted into the signed bit. // Assuming 32-bit integers, 1<<31 is implementation-defined // in ANSI C and C++98, but is explicitly undefined by C99, // C11 and C++11. bool allow_shift_into_sign_bit = true; if(mode == ID_C) { if( config.ansi_c.c_standard == configt::ansi_ct::c_standardt::C99 || config.ansi_c.c_standard == configt::ansi_ct::c_standardt::C11) { allow_shift_into_sign_bit = false; } } else if(mode == ID_cpp) { if( config.cpp.cpp_standard == configt::cppt::cpp_standardt::CPP11 || config.cpp.cpp_standard == configt::cppt::cpp_standardt::CPP14) { allow_shift_into_sign_bit = false; } } const unsigned number_of_top_bits = allow_shift_into_sign_bit ? op_width : op_width + 1; const exprt top_bits = extractbits_exprt( op_ext_shifted, new_type.get_width() - 1, new_type.get_width() - number_of_top_bits, unsignedbv_typet(number_of_top_bits)); const exprt top_bits_zero = equal_exprt(top_bits, from_integer(0, top_bits.type())); // a negative distance shift isn't an overflow; // a negative value shift isn't an overflow; // a shift that's too far isn't an overflow; // a shift of zero isn't overflow; // else check the top bits add_guarded_property( disjunction({neg_value_shift, neg_dist_shift, dist_too_large, op_zero, top_bits_zero}), ""arithmetic overflow on signed shl"", ""overflow"", expr.find_source_location(), expr, guard); } return; } multi_ary_exprt overflow( ""overflow-"" + expr.id_string(), expr.operands(), bool_typet()); if(expr.operands().size()>=3) { // The overflow checks are binary! // We break these up. for(std::size_t i=1; i=3) { assert(expr.id()!=ID_minus); // break up float_overflow_check(make_binary(expr), guard); return; } } } void goto_checkt::nan_check( const exprt &expr, const guardt &guard) { if(!enable_nan_check) return; // first, check type if(expr.type().id()!=ID_floatbv) return; if(expr.id()!=ID_plus && expr.id()!=ID_mult && expr.id()!=ID_div && expr.id()!=ID_minus) return; // add NaN subgoal exprt isnan; if(expr.id()==ID_div) { const auto &div_expr = to_div_expr(expr); // there a two ways to get a new NaN on division: // 0/0 = NaN and x/inf = NaN // (note that x/0 = +-inf for x!=0 and x!=inf) const and_exprt zero_div_zero( ieee_float_equal_exprt( div_expr.op0(), from_integer(0, div_expr.dividend().type())), ieee_float_equal_exprt( div_expr.op1(), from_integer(0, div_expr.divisor().type()))); const isinf_exprt div_inf(div_expr.op1()); isnan=or_exprt(zero_div_zero, div_inf); } else if(expr.id()==ID_mult) { if(expr.operands().size()>=3) return nan_check(make_binary(expr), guard); const auto &mult_expr = to_mult_expr(expr); // Inf * 0 is NaN const and_exprt inf_times_zero( isinf_exprt(mult_expr.op0()), ieee_float_equal_exprt( mult_expr.op1(), from_integer(0, mult_expr.op1().type()))); const and_exprt zero_times_inf( ieee_float_equal_exprt( mult_expr.op1(), from_integer(0, mult_expr.op1().type())), isinf_exprt(mult_expr.op0())); isnan=or_exprt(inf_times_zero, zero_times_inf); } else if(expr.id()==ID_plus) { if(expr.operands().size()>=3) return nan_check(make_binary(expr), guard); const auto &plus_expr = to_plus_expr(expr); // -inf + +inf = NaN and +inf + -inf = NaN, // i.e., signs differ ieee_float_spect spec = ieee_float_spect(to_floatbv_type(plus_expr.type())); exprt plus_inf=ieee_floatt::plus_infinity(spec).to_expr(); exprt minus_inf=ieee_floatt::minus_infinity(spec).to_expr(); isnan = or_exprt( and_exprt( equal_exprt(plus_expr.op0(), minus_inf), equal_exprt(plus_expr.op1(), plus_inf)), and_exprt( equal_exprt(plus_expr.op0(), plus_inf), equal_exprt(plus_expr.op1(), minus_inf))); } else if(expr.id()==ID_minus) { // +inf - +inf = NaN and -inf - -inf = NaN, // i.e., signs match const auto &minus_expr = to_minus_expr(expr); ieee_float_spect spec = ieee_float_spect(to_floatbv_type(minus_expr.type())); exprt plus_inf=ieee_floatt::plus_infinity(spec).to_expr(); exprt minus_inf=ieee_floatt::minus_infinity(spec).to_expr(); isnan = or_exprt( and_exprt( equal_exprt(minus_expr.lhs(), plus_inf), equal_exprt(minus_expr.rhs(), plus_inf)), and_exprt( equal_exprt(minus_expr.lhs(), minus_inf), equal_exprt(minus_expr.rhs(), minus_inf))); } else UNREACHABLE; add_guarded_property( boolean_negate(isnan), ""NaN on "" + expr.id_string(), ""NaN"", expr.find_source_location(), expr, guard); } void goto_checkt::pointer_rel_check( const binary_relation_exprt &expr, const guardt &guard) { if(!enable_pointer_check) return; if(expr.op0().type().id()==ID_pointer && expr.op1().type().id()==ID_pointer) { // add same-object subgoal if(enable_pointer_check) { exprt same_object=::same_object(expr.op0(), expr.op1()); add_guarded_property( same_object, ""same object violation"", ""pointer"", expr.find_source_location(), expr, guard); } } } void goto_checkt::pointer_overflow_check( const exprt &expr, const guardt &guard) { if(!enable_pointer_overflow_check) return; if(expr.id() != ID_plus && expr.id() != ID_minus) return; DATA_INVARIANT( expr.operands().size() == 2, ""pointer arithmetic expected to have exactly 2 operands""); exprt overflow(""overflow-"" + expr.id_string(), bool_typet()); overflow.operands() = expr.operands(); add_guarded_property( not_exprt(overflow), ""pointer arithmetic overflow on "" + expr.id_string(), ""overflow"", expr.find_source_location(), expr, guard); } void goto_checkt::pointer_validity_check( const dereference_exprt &expr, const exprt &src_expr, const guardt &guard) { if(!enable_pointer_check) return; const exprt &pointer=expr.pointer(); exprt size; if(expr.type().id() == ID_empty) { // a dereference *p (with p being a pointer to void) is valid if p points to // valid memory (of any size). the smallest possible size of the memory // segment p could be pointing to is 1, hence we use this size for the // address check size = from_integer(1, size_type()); } else { auto size_of_expr_opt = size_of_expr(expr.type(), ns); CHECK_RETURN(size_of_expr_opt.has_value()); size = size_of_expr_opt.value(); } auto conditions = get_pointer_dereferenceable_conditions(pointer, size); for(const auto &c : conditions) { add_guarded_property( c.assertion, ""dereference failure: "" + c.description, ""pointer dereference"", src_expr.find_source_location(), src_expr, guard); } } void goto_checkt::pointer_primitive_check( const exprt &expr, const guardt &guard) { if(!enable_pointer_primitive_check) return; if(expr.source_location().is_built_in()) return; const exprt pointer = (expr.id() == ID_r_ok || expr.id() == ID_w_ok) ? to_binary_expr(expr).lhs() : to_unary_expr(expr).op(); CHECK_RETURN(pointer.type().id() == ID_pointer); if(pointer.id() == ID_symbol) { const auto &symbol_expr = to_symbol_expr(pointer); if(has_prefix(id2string(symbol_expr.get_identifier()), CPROVER_PREFIX)) return; } const auto size_of_expr_opt = size_of_expr(pointer.type().subtype(), ns); const exprt size = !size_of_expr_opt.has_value() ? from_integer(1, size_type()) : size_of_expr_opt.value(); const conditionst &conditions = get_pointer_points_to_valid_memory_conditions(pointer, size); for(const auto &c : conditions) { add_guarded_property( or_exprt{null_object(pointer), c.assertion}, c.description, ""pointer primitives"", expr.source_location(), expr, guard); } } bool goto_checkt::is_pointer_primitive(const exprt &expr) { // we don't need to include the __CPROVER_same_object primitive here as it // is replaced by lower level primitives in the special function handling // during typechecking (see c_typecheck_expr.cpp) return expr.id() == ID_pointer_object || expr.id() == ID_pointer_offset || expr.id() == ID_object_size || expr.id() == ID_r_ok || expr.id() == ID_w_ok || expr.id() == ID_is_dynamic_object; } goto_checkt::conditionst goto_checkt::get_pointer_dereferenceable_conditions( const exprt &address, const exprt &size) { auto conditions = get_pointer_points_to_valid_memory_conditions(address, size); if(auto maybe_null_condition = get_pointer_is_null_condition(address, size)) { conditions.push_front(*maybe_null_condition); } return conditions; } std::string goto_checkt::array_name(const exprt &expr) { return ::array_name(ns, expr); } void goto_checkt::bounds_check( const index_exprt &expr, const guardt &guard) { if(!enable_bounds_check) return; if(expr.find(""bounds_check"").is_not_nil() && !expr.get_bool(""bounds_check"")) return; typet array_type = expr.array().type(); if(array_type.id()==ID_pointer) throw ""index got pointer as array type""; else if(array_type.id()!=ID_array && array_type.id()!=ID_vector) throw ""bounds check expected array or vector type, got "" +array_type.id_string(); std::string name=array_name(expr.array()); const exprt &index=expr.index(); object_descriptor_exprt ode; ode.build(expr, ns); if(index.type().id()!=ID_unsignedbv) { // we undo typecasts to signedbv if( index.id() == ID_typecast && to_typecast_expr(index).op().type().id() == ID_unsignedbv) { // ok } else { const auto i = numeric_cast(index); if(!i.has_value() || *i < 0) { exprt effective_offset=ode.offset(); if(ode.root_object().id()==ID_dereference) { exprt p_offset=pointer_offset( to_dereference_expr(ode.root_object()).pointer()); assert(p_offset.type()==effective_offset.type()); effective_offset=plus_exprt(p_offset, effective_offset); } exprt zero=from_integer(0, ode.offset().type()); // the final offset must not be negative binary_relation_exprt inequality( effective_offset, ID_ge, std::move(zero)); add_guarded_property( inequality, name + "" lower bound"", ""array bounds"", expr.find_source_location(), expr, guard); } } } exprt type_matches_size=true_exprt(); if(ode.root_object().id()==ID_dereference) { const exprt &pointer= to_dereference_expr(ode.root_object()).pointer(); const if_exprt size( dynamic_object(pointer), typecast_exprt(dynamic_size(ns), object_size(pointer).type()), object_size(pointer)); const plus_exprt effective_offset(ode.offset(), pointer_offset(pointer)); assert(effective_offset.op0().type()==effective_offset.op1().type()); const auto size_casted = typecast_exprt::conditional_cast(size, effective_offset.type()); binary_relation_exprt inequality(effective_offset, ID_lt, size_casted); exprt::operandst alloc_disjuncts; for(const auto &a : allocations) { typecast_exprt int_ptr{pointer, a.first.type()}; binary_relation_exprt lower_bound_check{a.first, ID_le, int_ptr}; plus_exprt upper_bound{ int_ptr, typecast_exprt::conditional_cast(ode.offset(), int_ptr.type())}; binary_relation_exprt upper_bound_check{ std::move(upper_bound), ID_lt, plus_exprt{a.first, a.second}}; alloc_disjuncts.push_back( and_exprt{std::move(lower_bound_check), std::move(upper_bound_check)}); } exprt in_bounds_of_some_explicit_allocation = disjunction(alloc_disjuncts); or_exprt precond( std::move(in_bounds_of_some_explicit_allocation), and_exprt(dynamic_object(pointer), not_exprt(malloc_object(pointer, ns))), inequality); add_guarded_property( precond, name + "" dynamic object upper bound"", ""array bounds"", expr.find_source_location(), expr, guard); auto type_size_opt = size_of_expr(ode.root_object().type(), ns); if(type_size_opt.has_value()) { // Build a predicate that evaluates to true iff the size reported by // sizeof (i.e., compile-time size) matches the actual run-time size. The // run-time size for a dynamic (i.e., heap-allocated) object is determined // by the dynamic_size(ns) expression, which can only be used when // malloc_object(pointer, ns) evaluates to true for a given pointer. type_matches_size = if_exprt{ dynamic_object(pointer), and_exprt{malloc_object(pointer, ns), equal_exprt{typecast_exprt::conditional_cast( dynamic_size(ns), type_size_opt->type()), *type_size_opt}}, equal_exprt{typecast_exprt::conditional_cast( object_size(pointer), type_size_opt->type()), *type_size_opt}}; } } const exprt &size=array_type.id()==ID_array ? to_array_type(array_type).size() : to_vector_type(array_type).size(); if(size.is_nil()) { // Linking didn't complete, we don't have a size. // Not clear what to do. } else if(size.id()==ID_infinity) { } else if(size.is_zero() && expr.array().id()==ID_member) { // a variable sized struct member // // Excerpt from the C standard on flexible array members: // However, when a . (or ->) operator has a left operand that is (a pointer // to) a structure with a flexible array member and the right operand names // that member, it behaves as if that member were replaced with the longest // array (with the same element type) that would not make the structure // larger than the object being accessed; [...] const auto type_size_opt = size_of_expr(ode.root_object().type(), ns); CHECK_RETURN(type_size_opt.has_value()); binary_relation_exprt inequality( typecast_exprt::conditional_cast( ode.offset(), type_size_opt.value().type()), ID_lt, type_size_opt.value()); add_guarded_property( implies_exprt(type_matches_size, inequality), name + "" upper bound"", ""array bounds"", expr.find_source_location(), expr, guard); } else { binary_relation_exprt inequality(index, ID_lt, size); // typecast size inequality.op1() = typecast_exprt::conditional_cast( inequality.op1(), inequality.op0().type()); add_guarded_property( implies_exprt(type_matches_size, inequality), name + "" upper bound"", ""array bounds"", expr.find_source_location(), expr, guard); } } void goto_checkt::add_guarded_property( const exprt &asserted_expr, const std::string &comment, const std::string &property_class, const source_locationt &source_location, const exprt &src_expr, const guardt &guard) { // first try simplifier on it exprt simplified_expr = enable_simplify ? simplify_expr(asserted_expr, ns) : asserted_expr; // throw away trivial properties? if(!retain_trivial && simplified_expr.is_true()) return; // add the guard exprt guarded_expr = guard.is_true() ? std::move(simplified_expr) : implies_exprt{guard.as_expr(), std::move(simplified_expr)}; if(assertions.insert(guarded_expr).second) { auto t = new_code.add( enable_assert_to_assume ? goto_programt::make_assumption( std::move(guarded_expr), source_location) : goto_programt::make_assertion( std::move(guarded_expr), source_location)); std::string source_expr_string; get_language_from_mode(mode)->from_expr(src_expr, source_expr_string, ns); t->source_location.set_comment(comment + "" in "" + source_expr_string); t->source_location.set_property_class(property_class); } } void goto_checkt::check_rec_address(const exprt &expr, guardt &guard) { // we don't look into quantifiers if(expr.id() == ID_exists || expr.id() == ID_forall) return; if(expr.id() == ID_dereference) { check_rec(to_dereference_expr(expr).pointer(), guard); } else if(expr.id() == ID_index) { const index_exprt &index_expr = to_index_expr(expr); check_rec_address(index_expr.array(), guard); check_rec(index_expr.index(), guard); } else { for(const auto &operand : expr.operands()) check_rec_address(operand, guard); } } void goto_checkt::check_rec_logical_op(const exprt &expr, guardt &guard) { INVARIANT( expr.is_boolean(), ""'"" + expr.id_string() + ""' must be Boolean, but got "" + expr.pretty()); guardt old_guard = guard; for(const auto &op : expr.operands()) { INVARIANT( op.is_boolean(), ""'"" + expr.id_string() + ""' takes Boolean operands only, but got "" + op.pretty()); check_rec(op, guard); guard.add(expr.id() == ID_or ? boolean_negate(op) : op); } guard = std::move(old_guard); } void goto_checkt::check_rec_if(const if_exprt &if_expr, guardt &guard) { INVARIANT( if_expr.cond().is_boolean(), ""first argument of if must be boolean, but got "" + if_expr.cond().pretty()); check_rec(if_expr.cond(), guard); { guardt old_guard = guard; guard.add(if_expr.cond()); check_rec(if_expr.true_case(), guard); guard = std::move(old_guard); } { guardt old_guard = guard; guard.add(not_exprt{if_expr.cond()}); check_rec(if_expr.false_case(), guard); guard = std::move(old_guard); } } bool goto_checkt::check_rec_member(const member_exprt &member, guardt &guard) { const dereference_exprt &deref = to_dereference_expr(member.struct_op()); check_rec(deref.pointer(), guard); // avoid building the following expressions when pointer_validity_check // would return immediately anyway if(!enable_pointer_check) return true; // we rewrite s->member into *(s+member_offset) // to avoid requiring memory safety of the entire struct auto member_offset_opt = member_offset_expr(member, ns); if(member_offset_opt.has_value()) { pointer_typet new_pointer_type = to_pointer_type(deref.pointer().type()); new_pointer_type.subtype() = member.type(); const exprt char_pointer = typecast_exprt::conditional_cast( deref.pointer(), pointer_type(char_type())); const exprt new_address_casted = typecast_exprt::conditional_cast( plus_exprt{char_pointer, typecast_exprt::conditional_cast( member_offset_opt.value(), pointer_diff_type())}, new_pointer_type); dereference_exprt new_deref{new_address_casted}; new_deref.add_source_location() = deref.source_location(); pointer_validity_check(new_deref, member, guard); return true; } return false; } void goto_checkt::check_rec_div(const div_exprt &div_expr, guardt &guard) { div_by_zero_check(to_div_expr(div_expr), guard); if(div_expr.type().id() == ID_signedbv) integer_overflow_check(div_expr, guard); else if(div_expr.type().id() == ID_floatbv) { nan_check(div_expr, guard); float_overflow_check(div_expr, guard); } } void goto_checkt::check_rec_arithmetic_op(const exprt &expr, guardt &guard) { if(expr.type().id() == ID_signedbv || expr.type().id() == ID_unsignedbv) { integer_overflow_check(expr, guard); } else if(expr.type().id() == ID_floatbv) { nan_check(expr, guard); float_overflow_check(expr, guard); } else if(expr.type().id() == ID_pointer) { pointer_overflow_check(expr, guard); } } void goto_checkt::check_rec(const exprt &expr, guardt &guard) { // we don't look into quantifiers if(expr.id() == ID_exists || expr.id() == ID_forall) return; if(expr.id() == ID_address_of) { check_rec_address(to_address_of_expr(expr).object(), guard); return; } else if(expr.id() == ID_and || expr.id() == ID_or) { check_rec_logical_op(expr, guard); return; } else if(expr.id() == ID_if) { check_rec_if(to_if_expr(expr), guard); return; } else if( expr.id() == ID_member && to_member_expr(expr).struct_op().id() == ID_dereference) { if(check_rec_member(to_member_expr(expr), guard)) return; } forall_operands(it, expr) check_rec(*it, guard); if(expr.type().id() == ID_c_enum_tag) enum_range_check(expr, guard); if(expr.id()==ID_index) { bounds_check(to_index_expr(expr), guard); } else if(expr.id()==ID_div) { check_rec_div(to_div_expr(expr), guard); } else if(expr.id()==ID_shl || expr.id()==ID_ashr || expr.id()==ID_lshr) { undefined_shift_check(to_shift_expr(expr), guard); if(expr.id()==ID_shl && expr.type().id()==ID_signedbv) integer_overflow_check(expr, guard); } else if(expr.id()==ID_mod) { mod_by_zero_check(to_mod_expr(expr), guard); mod_overflow_check(to_mod_expr(expr), guard); } else if(expr.id()==ID_plus || expr.id()==ID_minus || expr.id()==ID_mult || expr.id()==ID_unary_minus) { check_rec_arithmetic_op(expr, guard); } else if(expr.id()==ID_typecast) conversion_check(expr, guard); else if(expr.id()==ID_le || expr.id()==ID_lt || expr.id()==ID_ge || expr.id()==ID_gt) pointer_rel_check(to_binary_relation_expr(expr), guard); else if(expr.id()==ID_dereference) { pointer_validity_check(to_dereference_expr(expr), expr, guard); } else if(is_pointer_primitive(expr)) { pointer_primitive_check(expr, guard); } } void goto_checkt::check(const exprt &expr) { guardt guard{true_exprt{}, guard_manager}; check_rec(expr, guard); } /// expand the r_ok and w_ok predicates optionalt goto_checkt::rw_ok_check(exprt expr) { bool modified = false; for(auto &op : expr.operands()) { auto op_result = rw_ok_check(op); if(op_result.has_value()) { op = *op_result; modified = true; } } if(expr.id() == ID_r_ok || expr.id() == ID_w_ok) { // these get an address as first argument and a size as second DATA_INVARIANT( expr.operands().size() == 2, ""r/w_ok must have two operands""); const auto conditions = get_pointer_dereferenceable_conditions( to_binary_expr(expr).op0(), to_binary_expr(expr).op1()); exprt::operandst conjuncts; for(const auto &c : conditions) conjuncts.push_back(c.assertion); return conjunction(conjuncts); } else if(modified) return std::move(expr); else return {}; } /// Set a Boolean flag to a new value (via `set_flag`) and restore the previous /// value when the entire object goes out of scope. class flag_resett { public: /// Store the current value of \\p flag and then set its value to \\p new_value. void set_flag(bool &flag, bool new_value) { if(flag != new_value) { flags_to_reset.emplace_back(&flag, flag); flag = new_value; } } /// Restore the values of all flags that have been modified via `set_flag`. ~flag_resett() { for(const auto &flag_pair : flags_to_reset) *flag_pair.first = flag_pair.second; } private: std::list> flags_to_reset; }; void goto_checkt::goto_check( const irep_idt &function_identifier, goto_functiont &goto_function) { assertions.clear(); const auto &function_symbol = ns.lookup(function_identifier); mode = function_symbol.mode; bool did_something = false; local_bitvector_analysis = util_make_unique(goto_function, ns); goto_programt &goto_program=goto_function.body; Forall_goto_program_instructions(it, goto_program) { current_target = it; goto_programt::instructiont &i=*it; flag_resett flag_resetter; const auto &pragmas = i.source_location.get_pragmas(); for(const auto &d : pragmas) { if(d.first == ""disable:bounds-check"") flag_resetter.set_flag(enable_bounds_check, false); else if(d.first == ""disable:pointer-check"") flag_resetter.set_flag(enable_pointer_check, false); else if(d.first == ""disable:memory-leak-check"") flag_resetter.set_flag(enable_memory_leak_check, false); else if(d.first == ""disable:div-by-zero-check"") flag_resetter.set_flag(enable_div_by_zero_check, false); else if(d.first == ""disable:enum-range-check"") flag_resetter.set_flag(enable_enum_range_check, false); else if(d.first == ""disable:signed-overflow-check"") flag_resetter.set_flag(enable_signed_overflow_check, false); else if(d.first == ""disable:unsigned-overflow-check"") flag_resetter.set_flag(enable_unsigned_overflow_check, false); else if(d.first == ""disable:pointer-overflow-check"") flag_resetter.set_flag(enable_pointer_overflow_check, false); else if(d.first == ""disable:float-overflow-check"") flag_resetter.set_flag(enable_float_overflow_check, false); else if(d.first == ""disable:conversion-check"") flag_resetter.set_flag(enable_conversion_check, false); else if(d.first == ""disable:undefined-shift-check"") flag_resetter.set_flag(enable_undefined_shift_check, false); else if(d.first == ""disable:nan-check"") flag_resetter.set_flag(enable_nan_check, false); else if(d.first == ""disable:pointer-primitive-check"") flag_resetter.set_flag(enable_pointer_primitive_check, false); } new_code.clear(); // we clear all recorded assertions if // 1) we want to generate all assertions or // 2) the instruction is a branch target if(retain_trivial || i.is_target()) assertions.clear(); if(i.has_condition()) { check(i.get_condition()); if(has_subexpr(i.get_condition(), [](const exprt &expr) { return expr.id() == ID_r_ok || expr.id() == ID_w_ok; })) { auto rw_ok_cond = rw_ok_check(i.get_condition()); if(rw_ok_cond.has_value()) i.set_condition(*rw_ok_cond); } } // magic ERROR label? for(const auto &label : error_labels) { if(std::find(i.labels.begin(), i.labels.end(), label)!=i.labels.end()) { auto t = new_code.add( enable_assert_to_assume ? goto_programt::make_assumption(false_exprt{}, i.source_location) : goto_programt::make_assertion(false_exprt{}, i.source_location)); t->source_location.set_property_class(""error label""); t->source_location.set_comment(""error label ""+label); t->source_location.set(""user-provided"", true); } } if(i.is_other()) { const auto &code = i.get_other(); const irep_idt &statement = code.get_statement(); if(statement==ID_expression) { check(code); } else if(statement==ID_printf) { for(const auto &op : code.operands()) check(op); } } else if(i.is_assign()) { const code_assignt &code_assign=to_code_assign(i.code); // Reset the no_enum_check with the flag reset for exception // safety { flag_resett no_enum_check_flag_resetter; no_enum_check_flag_resetter.set_flag(no_enum_check, true); check(code_assign.lhs()); } check(code_assign.rhs()); // the LHS might invalidate any assertion invalidate(code_assign.lhs()); if(has_subexpr(code_assign.rhs(), [](const exprt &expr) { return expr.id() == ID_r_ok || expr.id() == ID_w_ok; })) { exprt &rhs = to_code_assign(i.code).rhs(); auto rw_ok_cond = rw_ok_check(rhs); if(rw_ok_cond.has_value()) rhs = *rw_ok_cond; } } else if(i.is_function_call()) { const code_function_callt &code_function_call= to_code_function_call(i.code); // for Java, need to check whether 'this' is null // on non-static method invocations if(mode==ID_java && enable_pointer_check && !code_function_call.arguments().empty() && code_function_call.function().type().id()==ID_code && to_code_type(code_function_call.function().type()).has_this()) { exprt pointer=code_function_call.arguments()[0]; local_bitvector_analysist::flagst flags = local_bitvector_analysis->get(current_target, pointer); if(flags.is_unknown() || flags.is_null()) { notequal_exprt not_eq_null( pointer, null_pointer_exprt(to_pointer_type(pointer.type()))); add_guarded_property( not_eq_null, ""this is null on method invocation"", ""pointer dereference"", i.source_location, pointer, guardt(true_exprt(), guard_manager)); } } for(const auto &op : code_function_call.operands()) check(op); // the call might invalidate any assertion assertions.clear(); } else if(i.is_return()) { if(i.code.operands().size()==1) { const code_returnt &code_return = to_code_return(i.code); check(code_return.return_value()); // the return value invalidate any assertion invalidate(code_return.return_value()); if(has_subexpr(code_return.return_value(), [](const exprt &expr) { return expr.id() == ID_r_ok || expr.id() == ID_w_ok; })) { exprt &return_value = to_code_return(i.code).return_value(); auto rw_ok_cond = rw_ok_check(return_value); if(rw_ok_cond.has_value()) return_value = *rw_ok_cond; } } } else if(i.is_throw()) { if(i.code.get_statement()==ID_expression && i.code.operands().size()==1 && i.code.op0().operands().size()==1) { // must not throw NULL exprt pointer = to_unary_expr(i.code.op0()).op(); const notequal_exprt not_eq_null( pointer, null_pointer_exprt(to_pointer_type(pointer.type()))); add_guarded_property( not_eq_null, ""throwing null"", ""pointer dereference"", i.source_location, pointer, guardt(true_exprt(), guard_manager)); } // this has no successor assertions.clear(); } else if(i.is_assert()) { bool is_user_provided=i.source_location.get_bool(""user-provided""); if((is_user_provided && !enable_assertions && i.source_location.get_property_class()!=""error label"") || (!is_user_provided && !enable_built_in_assertions)) { i.turn_into_skip(); did_something = true; } } else if(i.is_assume()) { if(!enable_assumptions) { i.turn_into_skip(); did_something = true; } } else if(i.is_dead()) { if(enable_pointer_check || enable_pointer_primitive_check) { assert(i.code.operands().size()==1); const symbol_exprt &variable=to_symbol_expr(i.code.op0()); // is it dirty? if(local_bitvector_analysis->dirty(variable)) { // need to mark the dead variable as dead exprt lhs=ns.lookup(CPROVER_PREFIX ""dead_object"").symbol_expr(); exprt address_of_expr = typecast_exprt::conditional_cast( address_of_exprt(variable), lhs.type()); if_exprt rhs( side_effect_expr_nondett(bool_typet(), i.source_location), std::move(address_of_expr), lhs); goto_programt::targett t = new_code.add(goto_programt::make_assignment( std::move(lhs), std::move(rhs), i.source_location)); t->code.add_source_location()=i.source_location; } } } else if(i.is_end_function()) { if( function_identifier == goto_functionst::entry_point() && enable_memory_leak_check) { const symbolt &leak=ns.lookup(CPROVER_PREFIX ""memory_leak""); const symbol_exprt leak_expr=leak.symbol_expr(); // add self-assignment to get helpful counterexample output new_code.add(goto_programt::make_assignment(leak_expr, leak_expr)); source_locationt source_location; source_location.set_function(function_identifier); equal_exprt eq( leak_expr, null_pointer_exprt(to_pointer_type(leak.type))); add_guarded_property( eq, ""dynamically allocated memory never freed"", ""memory-leak"", source_location, eq, guardt(true_exprt(), guard_manager)); } } Forall_goto_program_instructions(i_it, new_code) { if(i_it->source_location.is_nil()) { i_it->source_location.id(irep_idt()); if(!it->source_location.get_file().empty()) i_it->source_location.set_file(it->source_location.get_file()); if(!it->source_location.get_line().empty()) i_it->source_location.set_line(it->source_location.get_line()); if(!it->source_location.get_function().empty()) i_it->source_location.set_function( it->source_location.get_function()); if(!it->source_location.get_column().empty()) i_it->source_location.set_column(it->source_location.get_column()); if(!it->source_location.get_java_bytecode_index().empty()) i_it->source_location.set_java_bytecode_index( it->source_location.get_java_bytecode_index()); } } // insert new instructions -- make sure targets are not moved did_something |= !new_code.instructions.empty(); while(!new_code.instructions.empty()) { goto_program.insert_before_swap(it, new_code.instructions.front()); new_code.instructions.pop_front(); it++; } } if(did_something) remove_skip(goto_program); } goto_checkt::conditionst goto_checkt::get_pointer_points_to_valid_memory_conditions( const exprt &address, const exprt &size) { PRECONDITION(local_bitvector_analysis); PRECONDITION(address.type().id() == ID_pointer); local_bitvector_analysist::flagst flags = local_bitvector_analysis->get(current_target, address); conditionst conditions; if(mode == ID_java) { // The following conditions don’t apply to Java return conditions; } const exprt in_bounds_of_some_explicit_allocation = is_in_bounds_of_some_explicit_allocation(address, size); const bool unknown = flags.is_unknown() || flags.is_uninitialized(); if(unknown) { conditions.push_back(conditiont{ not_exprt{is_invalid_pointer_exprt{address}}, ""pointer invalid""}); } if(unknown || flags.is_dynamic_heap()) { conditions.push_back(conditiont( or_exprt( in_bounds_of_some_explicit_allocation, not_exprt(deallocated(address, ns))), ""deallocated dynamic object"")); } if(unknown || flags.is_dynamic_local()) { conditions.push_back(conditiont( or_exprt( in_bounds_of_some_explicit_allocation, not_exprt(dead_object(address, ns))), ""dead object"")); } if(unknown || flags.is_dynamic_heap()) { const or_exprt object_bounds_violation( object_lower_bound(address, nil_exprt()), object_upper_bound(address, size)); conditions.push_back(conditiont( or_exprt( in_bounds_of_some_explicit_allocation, implies_exprt( dynamic_object(address), not_exprt(object_bounds_violation))), ""pointer outside dynamic object bounds"")); } if(unknown || flags.is_dynamic_local() || flags.is_static_lifetime()) { const or_exprt object_bounds_violation( object_lower_bound(address, nil_exprt()), object_upper_bound(address, size)); conditions.push_back(conditiont( or_exprt( in_bounds_of_some_explicit_allocation, implies_exprt( not_exprt(dynamic_object(address)), not_exprt(object_bounds_violation))), ""pointer outside object bounds"")); } if(unknown || flags.is_integer_address()) { conditions.push_back(conditiont( implies_exprt( integer_address(address), in_bounds_of_some_explicit_allocation), ""invalid integer address"")); } return conditions; } optionalt goto_checkt::get_pointer_is_null_condition( const exprt &address, const exprt &size) { PRECONDITION(local_bitvector_analysis); PRECONDITION(address.type().id() == ID_pointer); const auto &pointer_type = to_pointer_type(address.type()); local_bitvector_analysist::flagst flags = local_bitvector_analysis->get(current_target, address); if(mode == ID_java) { if(flags.is_unknown() || flags.is_null()) { notequal_exprt not_eq_null(address, null_pointer_exprt{pointer_type}); return {conditiont{not_eq_null, ""reference is null""}}; } } else if(flags.is_unknown() || flags.is_uninitialized() || flags.is_null()) { return {conditiont{ or_exprt{is_in_bounds_of_some_explicit_allocation(address, size), not_exprt(null_pointer(address))}, ""pointer NULL""}}; } return {}; } exprt goto_checkt::is_in_bounds_of_some_explicit_allocation( const exprt &pointer, const exprt &size) { exprt::operandst alloc_disjuncts; for(const auto &a : allocations) { typecast_exprt int_ptr(pointer, a.first.type()); binary_relation_exprt lb_check(a.first, ID_le, int_ptr); plus_exprt ub{int_ptr, size}; binary_relation_exprt ub_check(ub, ID_le, plus_exprt(a.first, a.second)); alloc_disjuncts.push_back(and_exprt(lb_check, ub_check)); } return disjunction(alloc_disjuncts); } void goto_check( const irep_idt &function_identifier, goto_functionst::goto_functiont &goto_function, const namespacet &ns, const optionst &options) { goto_checkt goto_check(ns, options); goto_check.goto_check(function_identifier, goto_function); } void goto_check( const namespacet &ns, const optionst &options, goto_functionst &goto_functions) { goto_checkt goto_check(ns, options); goto_check.collect_allocations(goto_functions); Forall_goto_functions(it, goto_functions) { goto_check.goto_check(it->first, it->second); } } void goto_check( const optionst &options, goto_modelt &goto_model) { const namespacet ns(goto_model.symbol_table); goto_check(ns, options, goto_model.goto_functions); } ",16134,True,3115.3169899223617,median "/********************************************************************** * * Project: CPL - Common Portability Library * Purpose: Implementation of MiniXML Parser and handling. * Author: Frank Warmerdam, warmerdam@pobox.com * ********************************************************************** * Copyright (c) 2001, Frank Warmerdam * Copyright (c) 2007-2013, Even Rouault * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the ""Software""), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED ""AS IS"", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. ********************************************************************** * * Independent Security Audit 2003/04/05 Andrey Kiselev: * Completed audit of this module. Any documents may be parsed without * buffer overflows and stack corruptions. * * Security Audit 2003/03/28 warmerda: * Completed security audit. I believe that this module may be safely used * to parse, and serialize arbitrary documents provided by a potentially * hostile source. * */ #include ""cpl_minixml.h"" #include #include #include #include #include #include #include ""cpl_conv.h"" #include ""cpl_error.h"" #include ""cpl_string.h"" #include ""cpl_vsi.h"" CPL_CVSID(""$Id$"") typedef enum { TNone, TString, TOpen, TClose, TEqual, TToken, TSlashClose, TQuestionClose, TComment, TLiteral } XMLTokenType; typedef struct { CPLXMLNode *psFirstNode; CPLXMLNode *psLastChild; } StackContext; typedef struct { const char *pszInput; int nInputOffset; int nInputLine; bool bInElement; XMLTokenType eTokenType; char *pszToken; size_t nTokenMaxSize; size_t nTokenSize; int nStackMaxSize; int nStackSize; StackContext *papsStack; CPLXMLNode *psFirstNode; CPLXMLNode *psLastNode; } ParseContext; static CPLXMLNode *_CPLCreateXMLNode( CPLXMLNode *poParent, CPLXMLNodeType eType, const char *pszText ); /************************************************************************/ /* ReadChar() */ /************************************************************************/ static CPL_INLINE char ReadChar( ParseContext *psContext ) { const char chReturn = psContext->pszInput[psContext->nInputOffset++]; if( chReturn == '\\0' ) psContext->nInputOffset--; else if( chReturn == 10 ) psContext->nInputLine++; return chReturn; } /************************************************************************/ /* UnreadChar() */ /************************************************************************/ static CPL_INLINE void UnreadChar( ParseContext *psContext, char chToUnread ) { if( chToUnread == '\\0' ) return; CPLAssert( chToUnread == psContext->pszInput[psContext->nInputOffset-1] ); psContext->nInputOffset--; if( chToUnread == 10 ) psContext->nInputLine--; } /************************************************************************/ /* ReallocToken() */ /************************************************************************/ static bool ReallocToken( ParseContext *psContext ) { if( psContext->nTokenMaxSize > INT_MAX / 2 ) { CPLError(CE_Failure, CPLE_OutOfMemory, ""Out of memory allocating %d*2 bytes"", static_cast(psContext->nTokenMaxSize)); VSIFree(psContext->pszToken); psContext->pszToken = nullptr; return false; } psContext->nTokenMaxSize *= 2; char* pszToken = static_cast( VSIRealloc(psContext->pszToken, psContext->nTokenMaxSize)); if( pszToken == nullptr ) { CPLError(CE_Failure, CPLE_OutOfMemory, ""Out of memory allocating %d bytes"", static_cast(psContext->nTokenMaxSize)); VSIFree(psContext->pszToken); psContext->pszToken = nullptr; return false; } psContext->pszToken = pszToken; return true; } /************************************************************************/ /* AddToToken() */ /************************************************************************/ static CPL_INLINE bool _AddToToken( ParseContext *psContext, char chNewChar ) { if( psContext->nTokenSize >= psContext->nTokenMaxSize - 2 ) { if( !ReallocToken(psContext) ) return false; } psContext->pszToken[psContext->nTokenSize++] = chNewChar; psContext->pszToken[psContext->nTokenSize] = '\\0'; return true; } // TODO(schwehr): Remove the goto. #define AddToToken(psContext, chNewChar) \\ if( !_AddToToken(psContext, chNewChar)) goto fail; /************************************************************************/ /* ReadToken() */ /************************************************************************/ static XMLTokenType ReadToken( ParseContext *psContext, CPLErr& eLastErrorType ) { psContext->nTokenSize = 0; psContext->pszToken[0] = '\\0'; char chNext = ReadChar( psContext ); while( isspace(static_cast(chNext)) ) chNext = ReadChar( psContext ); /* -------------------------------------------------------------------- */ /* Handle comments. */ /* -------------------------------------------------------------------- */ if( chNext == '<' && STARTS_WITH_CI(psContext->pszInput+psContext->nInputOffset, ""!--"") ) { psContext->eTokenType = TComment; // Skip ""!--"" characters. ReadChar(psContext); ReadChar(psContext); ReadChar(psContext); while( !STARTS_WITH_CI(psContext->pszInput+psContext->nInputOffset, ""-->"") && (chNext = ReadChar(psContext)) != '\\0' ) AddToToken( psContext, chNext ); // Skip ""-->"" characters. ReadChar(psContext); ReadChar(psContext); ReadChar(psContext); } /* -------------------------------------------------------------------- */ /* Handle DOCTYPE. */ /* -------------------------------------------------------------------- */ else if( chNext == '<' && STARTS_WITH_CI(psContext->pszInput+psContext->nInputOffset, ""!DOCTYPE"") ) { bool bInQuotes = false; psContext->eTokenType = TLiteral; AddToToken( psContext, '<' ); do { chNext = ReadChar(psContext); if( chNext == '\\0' ) { eLastErrorType = CE_Failure; CPLError( eLastErrorType, CPLE_AppDefined, ""Parse error in DOCTYPE on or before line %d, "" ""reached end of file without '>'."", psContext->nInputLine ); break; } /* The markup declaration block within a DOCTYPE tag consists of: * - a left square bracket [ * - a list of declarations * - a right square bracket ] * Example: * */ if( chNext == '[' ) { AddToToken( psContext, chNext ); do { chNext = ReadChar( psContext ); if( chNext == ']' ) break; AddToToken( psContext, chNext ); } while( chNext != '\\0' && !STARTS_WITH_CI( psContext->pszInput+psContext->nInputOffset, ""]>"") ); if( chNext == '\\0' ) { eLastErrorType = CE_Failure; CPLError( eLastErrorType, CPLE_AppDefined, ""Parse error in DOCTYPE on or before line %d, "" ""reached end of file without ']'."", psContext->nInputLine ); break; } if( chNext != ']' ) { chNext = ReadChar( psContext ); AddToToken( psContext, chNext ); // Skip "">"" character, will be consumed below. chNext = ReadChar( psContext ); } } if( chNext == '\\""' ) bInQuotes = !bInQuotes; if( chNext == '>' && !bInQuotes ) { AddToToken( psContext, '>' ); break; } AddToToken( psContext, chNext ); } while( true ); } /* -------------------------------------------------------------------- */ /* Handle CDATA. */ /* -------------------------------------------------------------------- */ else if( chNext == '<' && STARTS_WITH_CI( psContext->pszInput+psContext->nInputOffset, ""![CDATA["") ) { psContext->eTokenType = TString; // Skip !CDATA[ ReadChar( psContext ); ReadChar( psContext ); ReadChar( psContext ); ReadChar( psContext ); ReadChar( psContext ); ReadChar( psContext ); ReadChar( psContext ); ReadChar( psContext ); while( !STARTS_WITH_CI(psContext->pszInput+psContext->nInputOffset, ""]]>"") && (chNext = ReadChar(psContext)) != '\\0' ) AddToToken( psContext, chNext ); // Skip ""]]>"" characters. ReadChar(psContext); ReadChar(psContext); ReadChar(psContext); } /* -------------------------------------------------------------------- */ /* Simple single tokens of interest. */ /* -------------------------------------------------------------------- */ else if( chNext == '<' && !psContext->bInElement ) { psContext->eTokenType = TOpen; psContext->bInElement = true; } else if( chNext == '>' && psContext->bInElement ) { psContext->eTokenType = TClose; psContext->bInElement = false; } else if( chNext == '=' && psContext->bInElement ) { psContext->eTokenType = TEqual; } else if( chNext == '\\0' ) { psContext->eTokenType = TNone; } /* -------------------------------------------------------------------- */ /* Handle the /> token terminator. */ /* -------------------------------------------------------------------- */ else if( chNext == '/' && psContext->bInElement && psContext->pszInput[psContext->nInputOffset] == '>' ) { chNext = ReadChar( psContext ); CPLAssert( chNext == '>' ); psContext->eTokenType = TSlashClose; psContext->bInElement = false; } /* -------------------------------------------------------------------- */ /* Handle the ?> token terminator. */ /* -------------------------------------------------------------------- */ else if( chNext == '?' && psContext->bInElement && psContext->pszInput[psContext->nInputOffset] == '>' ) { chNext = ReadChar( psContext ); CPLAssert( chNext == '>' ); psContext->eTokenType = TQuestionClose; psContext->bInElement = false; } /* -------------------------------------------------------------------- */ /* Collect a quoted string. */ /* -------------------------------------------------------------------- */ else if( psContext->bInElement && chNext == '""' ) { psContext->eTokenType = TString; while( (chNext = ReadChar(psContext)) != '""' && chNext != '\\0' ) AddToToken( psContext, chNext ); if( chNext != '""' ) { psContext->eTokenType = TNone; eLastErrorType = CE_Failure; CPLError( eLastErrorType, CPLE_AppDefined, ""Parse error on line %d, reached EOF before closing quote."", psContext->nInputLine); } // Do we need to unescape it? if( strchr(psContext->pszToken, '&') != nullptr ) { int nLength = 0; char *pszUnescaped = CPLUnescapeString( psContext->pszToken, &nLength, CPLES_XML ); strcpy( psContext->pszToken, pszUnescaped ); CPLFree( pszUnescaped ); psContext->nTokenSize = strlen(psContext->pszToken ); } } else if( psContext->bInElement && chNext == '\\'' ) { psContext->eTokenType = TString; while( (chNext = ReadChar(psContext)) != '\\'' && chNext != '\\0' ) AddToToken( psContext, chNext ); if( chNext != '\\'' ) { psContext->eTokenType = TNone; eLastErrorType = CE_Failure; CPLError( eLastErrorType, CPLE_AppDefined, ""Parse error on line %d, reached EOF before closing quote."", psContext->nInputLine); } // Do we need to unescape it? if( strchr(psContext->pszToken, '&') != nullptr ) { int nLength = 0; char *pszUnescaped = CPLUnescapeString( psContext->pszToken, &nLength, CPLES_XML ); strcpy( psContext->pszToken, pszUnescaped ); CPLFree( pszUnescaped ); psContext->nTokenSize = strlen(psContext->pszToken ); } } /* -------------------------------------------------------------------- */ /* Collect an unquoted string, terminated by a open angle */ /* bracket. */ /* -------------------------------------------------------------------- */ else if( !psContext->bInElement ) { psContext->eTokenType = TString; AddToToken( psContext, chNext ); while( (chNext = ReadChar(psContext)) != '<' && chNext != '\\0' ) AddToToken( psContext, chNext ); UnreadChar( psContext, chNext ); // Do we need to unescape it? if( strchr(psContext->pszToken, '&') != nullptr ) { int nLength = 0; char *pszUnescaped = CPLUnescapeString( psContext->pszToken, &nLength, CPLES_XML ); strcpy( psContext->pszToken, pszUnescaped ); CPLFree( pszUnescaped ); psContext->nTokenSize = strlen(psContext->pszToken ); } } /* -------------------------------------------------------------------- */ /* Collect a regular token terminated by white space, or */ /* special character(s) like an equal sign. */ /* -------------------------------------------------------------------- */ else { psContext->eTokenType = TToken; // Add the first character to the token regardless of what it is. AddToToken( psContext, chNext ); for( chNext = ReadChar(psContext); (chNext >= 'A' && chNext <= 'Z') || (chNext >= 'a' && chNext <= 'z') || chNext == '-' || chNext == '_' || chNext == '.' || chNext == ':' || (chNext >= '0' && chNext <= '9'); chNext = ReadChar(psContext) ) { AddToToken( psContext, chNext ); } UnreadChar(psContext, chNext); } return psContext->eTokenType; fail: psContext->eTokenType = TNone; return TNone; } /************************************************************************/ /* PushNode() */ /************************************************************************/ static bool PushNode( ParseContext *psContext, CPLXMLNode *psNode, CPLErr& eLastErrorType ) { if( psContext->nStackMaxSize <= psContext->nStackSize ) { // Somewhat arbitrary number. if( psContext->nStackMaxSize >= 10000 ) { eLastErrorType = CE_Failure; CPLError(CE_Failure, CPLE_NotSupported, ""XML element depth beyond 10000. Giving up""); VSIFree(psContext->papsStack); psContext->papsStack = nullptr; return false; } psContext->nStackMaxSize += 10; StackContext* papsStack = static_cast( VSIRealloc(psContext->papsStack, sizeof(StackContext) * psContext->nStackMaxSize)); if( papsStack == nullptr ) { eLastErrorType = CE_Failure; CPLError(CE_Failure, CPLE_OutOfMemory, ""Out of memory allocating %d bytes"", static_cast(sizeof(StackContext)) * psContext->nStackMaxSize); VSIFree(psContext->papsStack); psContext->papsStack = nullptr; return false; } psContext->papsStack = papsStack; } #ifdef DEBUG // To make Coverity happy, but cannot happen. if( psContext->papsStack == nullptr ) return false; #endif psContext->papsStack[psContext->nStackSize].psFirstNode = psNode; psContext->papsStack[psContext->nStackSize].psLastChild = nullptr; psContext->nStackSize++; return true; } /************************************************************************/ /* AttachNode() */ /* */ /* Attach the passed node as a child of the current node. */ /* Special handling exists for adding siblings to psFirst if */ /* there is nothing on the stack. */ /************************************************************************/ static void AttachNode( ParseContext *psContext, CPLXMLNode *psNode ) { if( psContext->psFirstNode == nullptr ) { psContext->psFirstNode = psNode; psContext->psLastNode = psNode; } else if( psContext->nStackSize == 0 ) { psContext->psLastNode->psNext = psNode; psContext->psLastNode = psNode; } else { if( psContext->papsStack[psContext->nStackSize-1].psFirstNode->psChild == nullptr ) { psContext->papsStack[psContext->nStackSize-1].psFirstNode->psChild = psNode; } else { psContext->papsStack[psContext->nStackSize-1].psLastChild->psNext = psNode; } psContext->papsStack[psContext->nStackSize-1].psLastChild = psNode; } } /************************************************************************/ /* CPLParseXMLString() */ /************************************************************************/ /** * \\brief Parse an XML string into tree form. * * The passed document is parsed into a CPLXMLNode tree representation. * If the document is not well formed XML then NULL is returned, and errors * are reported via CPLError(). No validation beyond wellformedness is * done. The CPLParseXMLFile() convenience function can be used to parse * from a file. * * The returned document tree is owned by the caller and should be freed * with CPLDestroyXMLNode() when no longer needed. * * If the document has more than one ""root level"" element then those after the * first will be attached to the first as siblings (via the psNext pointers) * even though there is no common parent. A document with no XML structure * (no angle brackets for instance) would be considered well formed, and * returned as a single CXT_Text node. * * @param pszString the document to parse. * * @return parsed tree or NULL on error. */ CPLXMLNode *CPLParseXMLString( const char *pszString ) { if( pszString == nullptr ) { CPLError( CE_Failure, CPLE_AppDefined, ""CPLParseXMLString() called with NULL pointer."" ); return nullptr; } // Save back error context. const CPLErr eErrClass = CPLGetLastErrorType(); const CPLErrorNum nErrNum = CPLGetLastErrorNo(); const CPLString osErrMsg = CPLGetLastErrorMsg(); // Reset it now. CPLErrorReset(); /* -------------------------------------------------------------------- */ /* Check for a UTF-8 BOM and skip if found */ /* */ /* TODO: BOM is variable-length parameter and depends on encoding. */ /* Add BOM detection for other encodings. */ /* -------------------------------------------------------------------- */ // Used to skip to actual beginning of XML data. if( ( static_cast(pszString[0]) == 0xEF ) && ( static_cast(pszString[1]) == 0xBB ) && ( static_cast(pszString[2]) == 0xBF) ) { pszString += 3; } /* -------------------------------------------------------------------- */ /* Initialize parse context. */ /* -------------------------------------------------------------------- */ ParseContext sContext; sContext.pszInput = pszString; sContext.nInputOffset = 0; sContext.nInputLine = 0; sContext.bInElement = false; sContext.nTokenMaxSize = 10; sContext.pszToken = static_cast(VSIMalloc(sContext.nTokenMaxSize)); if( sContext.pszToken == nullptr ) return nullptr; sContext.nTokenSize = 0; sContext.eTokenType = TNone; sContext.nStackMaxSize = 0; sContext.nStackSize = 0; sContext.papsStack = nullptr; sContext.psFirstNode = nullptr; sContext.psLastNode = nullptr; #ifdef DEBUG bool bRecoverableError = true; #endif CPLErr eLastErrorType = CE_None; /* ==================================================================== */ /* Loop reading tokens. */ /* ==================================================================== */ while( ReadToken( &sContext, eLastErrorType ) != TNone ) { /* -------------------------------------------------------------------- */ /* Create a new element. */ /* -------------------------------------------------------------------- */ if( sContext.eTokenType == TOpen ) { if( ReadToken(&sContext, eLastErrorType) != TToken ) { eLastErrorType = CE_Failure; CPLError( eLastErrorType, CPLE_AppDefined, ""Line %d: Didn't find element token after "" ""open angle bracket."", sContext.nInputLine ); break; } CPLXMLNode *psElement = nullptr; if( sContext.pszToken[0] != '/' ) { psElement = _CPLCreateXMLNode( nullptr, CXT_Element, sContext.pszToken ); if( !psElement ) break; AttachNode( &sContext, psElement ); if( !PushNode( &sContext, psElement, eLastErrorType ) ) break; } else { if( sContext.nStackSize == 0 || !EQUAL(sContext.pszToken+1, sContext.papsStack[sContext.nStackSize-1]. psFirstNode->pszValue) ) { #ifdef DEBUG // Makes life of fuzzers easier if we accept somewhat // corrupted XML like ... . if( CPLTestBool(CPLGetConfigOption(""CPL_MINIXML_RELAXED"", ""FALSE"")) ) { eLastErrorType = CE_Warning; CPLError( eLastErrorType, CPLE_AppDefined, ""Line %d: <%.500s> doesn't have matching <%.500s>."", sContext.nInputLine, sContext.pszToken, sContext.pszToken + 1 ); if( sContext.nStackSize == 0 ) break; goto end_processing_close; } else #endif { eLastErrorType = CE_Failure; CPLError( eLastErrorType, CPLE_AppDefined, ""Line %d: <%.500s> doesn't have matching <%.500s>."", sContext.nInputLine, sContext.pszToken, sContext.pszToken + 1 ); break; } } else { if( strcmp(sContext.pszToken + 1, sContext.papsStack[sContext.nStackSize-1]. psFirstNode->pszValue) != 0) { // TODO: At some point we could just error out like any // other sane XML parser would do. eLastErrorType = CE_Warning; CPLError( eLastErrorType, CPLE_AppDefined, ""Line %d: <%.500s> matches <%.500s>, but the case "" ""isn't the same. Going on, but this is invalid "" ""XML that might be rejected in future versions."", sContext.nInputLine, sContext.papsStack[sContext.nStackSize-1]. psFirstNode->pszValue, sContext.pszToken ); } #ifdef DEBUG end_processing_close: #endif if( ReadToken(&sContext, eLastErrorType) != TClose ) { eLastErrorType = CE_Failure; CPLError( eLastErrorType, CPLE_AppDefined, ""Line %d: Missing close angle bracket "" ""after <%.500s."", sContext.nInputLine, sContext.pszToken ); break; } // Pop element off stack sContext.nStackSize--; } } } /* -------------------------------------------------------------------- */ /* Add an attribute to a token. */ /* -------------------------------------------------------------------- */ else if( sContext.eTokenType == TToken ) { CPLXMLNode *psAttr = _CPLCreateXMLNode(nullptr, CXT_Attribute, sContext.pszToken); if( !psAttr ) break; AttachNode( &sContext, psAttr ); if( ReadToken(&sContext, eLastErrorType) != TEqual ) { // Parse stuff like if( sContext.nStackSize > 0 && sContext.papsStack[sContext.nStackSize - 1] .psFirstNode->pszValue[0] == '?' && sContext.papsStack[sContext.nStackSize - 1] .psFirstNode->psChild == psAttr ) { CPLDestroyXMLNode(psAttr); sContext.papsStack[sContext.nStackSize - 1] .psFirstNode->psChild = nullptr; sContext.papsStack[sContext.nStackSize - 1].psLastChild = nullptr; sContext.papsStack[sContext.nStackSize - 1] .psFirstNode->pszValue = static_cast(CPLRealloc( sContext.papsStack[sContext.nStackSize - 1] .psFirstNode->pszValue, strlen(sContext.papsStack[sContext.nStackSize - 1] .psFirstNode->pszValue) + 1 + strlen(sContext.pszToken) + 1)); strcat(sContext.papsStack[sContext.nStackSize - 1] .psFirstNode->pszValue, "" ""); strcat(sContext.papsStack[sContext.nStackSize - 1] .psFirstNode->pszValue, sContext.pszToken); continue; } eLastErrorType = CE_Failure; CPLError( eLastErrorType, CPLE_AppDefined, ""Line %d: Didn't find expected '=' for value of "" ""attribute '%.500s'."", sContext.nInputLine, psAttr->pszValue ); #ifdef DEBUG // Accepting an attribute without child text // would break too much assumptions in driver code bRecoverableError = false; #endif break; } if( ReadToken(&sContext, eLastErrorType) == TToken ) { /* TODO: at some point we could just error out like any other */ /* sane XML parser would do */ eLastErrorType = CE_Warning; CPLError( eLastErrorType, CPLE_AppDefined, ""Line %d: Attribute value should be single or double "" ""quoted. Going on, but this is invalid XML that "" ""might be rejected in future versions."", sContext.nInputLine ); } else if( sContext.eTokenType != TString ) { eLastErrorType = CE_Failure; CPLError( eLastErrorType, CPLE_AppDefined, ""Line %d: Didn't find expected attribute value."", sContext.nInputLine ); #ifdef DEBUG // Accepting an attribute without child text // would break too much assumptions in driver code bRecoverableError = false; #endif break; } if( !_CPLCreateXMLNode( psAttr, CXT_Text, sContext.pszToken ) ) break; } /* -------------------------------------------------------------------- */ /* Close the start section of an element. */ /* -------------------------------------------------------------------- */ else if( sContext.eTokenType == TClose ) { if( sContext.nStackSize == 0 ) { eLastErrorType = CE_Failure; CPLError( eLastErrorType, CPLE_AppDefined, ""Line %d: Found unbalanced '>'."", sContext.nInputLine ); break; } } /* -------------------------------------------------------------------- */ /* Close the start section of an element, and pop it */ /* immediately. */ /* -------------------------------------------------------------------- */ else if( sContext.eTokenType == TSlashClose ) { if( sContext.nStackSize == 0 ) { eLastErrorType = CE_Failure; CPLError( eLastErrorType, CPLE_AppDefined, ""Line %d: Found unbalanced '/>'."", sContext.nInputLine ); break; } sContext.nStackSize--; } /* -------------------------------------------------------------------- */ /* Close the start section of a element, and pop it */ /* immediately. */ /* -------------------------------------------------------------------- */ else if( sContext.eTokenType == TQuestionClose ) { if( sContext.nStackSize == 0 ) { eLastErrorType = CE_Failure; CPLError( eLastErrorType, CPLE_AppDefined, ""Line %d: Found unbalanced '?>'."", sContext.nInputLine ); break; } else if( sContext.papsStack[sContext.nStackSize-1]. psFirstNode->pszValue[0] != '?' ) { eLastErrorType = CE_Failure; CPLError( eLastErrorType, CPLE_AppDefined, ""Line %d: Found '?>' without matching ' 0 && sContext.papsStack != nullptr ) { #ifdef DEBUG // Makes life of fuzzers easier if we accept somewhat corrupted XML // like ... if( bRecoverableError && CPLTestBool(CPLGetConfigOption(""CPL_MINIXML_RELAXED"", ""FALSE"")) ) { eLastErrorType = CE_Warning; } else #endif { eLastErrorType = CE_Failure; } CPLError( eLastErrorType, CPLE_AppDefined, ""Parse error at EOF, not all elements have been closed, "" ""starting with %.500s"", sContext.papsStack[sContext.nStackSize-1]. psFirstNode->pszValue ); } /* -------------------------------------------------------------------- */ /* Cleanup */ /* -------------------------------------------------------------------- */ CPLFree( sContext.pszToken ); if( sContext.papsStack != nullptr ) CPLFree( sContext.papsStack ); // We do not trust CPLGetLastErrorType() as if CPLTurnFailureIntoWarning() // has been set we would never get failures if( eLastErrorType == CE_Failure ) { CPLDestroyXMLNode( sContext.psFirstNode ); sContext.psFirstNode = nullptr; sContext.psLastNode = nullptr; } if( eLastErrorType == CE_None ) { // Restore initial error state. CPLErrorSetState(eErrClass, nErrNum, osErrMsg); } return sContext.psFirstNode; } /************************************************************************/ /* _GrowBuffer() */ /************************************************************************/ static bool _GrowBuffer( size_t nNeeded, char **ppszText, size_t *pnMaxLength ) { if( nNeeded+1 >= *pnMaxLength ) { *pnMaxLength = std::max(*pnMaxLength * 2, nNeeded + 1); char* pszTextNew = static_cast(VSIRealloc(*ppszText, *pnMaxLength)); if( pszTextNew == nullptr ) return false; *ppszText = pszTextNew; } return true; } /************************************************************************/ /* CPLSerializeXMLNode() */ /************************************************************************/ // TODO(schwehr): Rewrite this whole thing using C++ string. // CPLSerializeXMLNode has buffer overflows. static bool CPLSerializeXMLNode( const CPLXMLNode *psNode, int nIndent, char **ppszText, size_t *pnLength, size_t *pnMaxLength ) { if( psNode == nullptr ) return true; /* -------------------------------------------------------------------- */ /* Ensure the buffer is plenty large to hold this additional */ /* string. */ /* -------------------------------------------------------------------- */ *pnLength += strlen(*ppszText + *pnLength); if( !_GrowBuffer( strlen(psNode->pszValue) + *pnLength + 40 + nIndent, ppszText, pnMaxLength ) ) return false; /* -------------------------------------------------------------------- */ /* Text is just directly emitted. */ /* -------------------------------------------------------------------- */ if( psNode->eType == CXT_Text ) { char *pszEscaped = CPLEscapeString( psNode->pszValue, -1, CPLES_XML_BUT_QUOTES ); CPLAssert( psNode->psChild == nullptr ); // Escaped text might be bigger than expected. if( !_GrowBuffer( strlen(pszEscaped) + *pnLength, ppszText, pnMaxLength ) ) { CPLFree( pszEscaped ); return false; } strcat( *ppszText + *pnLength, pszEscaped ); CPLFree( pszEscaped ); } /* -------------------------------------------------------------------- */ /* Attributes require a little formatting. */ /* -------------------------------------------------------------------- */ else if( psNode->eType == CXT_Attribute ) { CPLAssert( psNode->psChild != nullptr && psNode->psChild->eType == CXT_Text ); snprintf( *ppszText + *pnLength, *pnMaxLength - *pnLength, "" %s=\\"""", psNode->pszValue ); *pnLength += strlen(*ppszText + *pnLength); char *pszEscaped = CPLEscapeString( psNode->psChild->pszValue, -1, CPLES_XML ); if( !_GrowBuffer( strlen(pszEscaped) + *pnLength, ppszText, pnMaxLength ) ) { CPLFree( pszEscaped ); return false; } strcat( *ppszText + *pnLength, pszEscaped ); CPLFree( pszEscaped ); *pnLength += strlen(*ppszText + *pnLength); if( !_GrowBuffer( 3 + *pnLength, ppszText, pnMaxLength ) ) return false; strcat( *ppszText + *pnLength, ""\\"""" ); } /* -------------------------------------------------------------------- */ /* Handle comment output. */ /* -------------------------------------------------------------------- */ else if( psNode->eType == CXT_Comment ) { CPLAssert( psNode->psChild == nullptr ); for( int i = 0; i < nIndent; i++ ) (*ppszText)[(*pnLength)++] = ' '; snprintf( *ppszText + *pnLength, *pnMaxLength - *pnLength, ""\\n"", psNode->pszValue ); } /* -------------------------------------------------------------------- */ /* Handle literal output (like ) */ /* -------------------------------------------------------------------- */ else if( psNode->eType == CXT_Literal ) { CPLAssert( psNode->psChild == nullptr ); for( int i = 0; i < nIndent; i++ ) (*ppszText)[(*pnLength)++] = ' '; strcpy( *ppszText + *pnLength, psNode->pszValue ); strcat( *ppszText + *pnLength, ""\\n"" ); } /* -------------------------------------------------------------------- */ /* Elements actually have to deal with general children, and */ /* various formatting issues. */ /* -------------------------------------------------------------------- */ else if( psNode->eType == CXT_Element ) { bool bHasNonAttributeChildren = false; if( nIndent ) memset( *ppszText + *pnLength, ' ', nIndent ); *pnLength += nIndent; (*ppszText)[*pnLength] = '\\0'; snprintf( *ppszText + *pnLength, *pnMaxLength - *pnLength, ""<%s"", psNode->pszValue ); // Serialize *all* the attribute children, regardless of order CPLXMLNode *psChild = nullptr; for( psChild = psNode->psChild; psChild != nullptr; psChild = psChild->psNext ) { if( psChild->eType == CXT_Attribute ) { if( !CPLSerializeXMLNode( psChild, 0, ppszText, pnLength, pnMaxLength ) ) return false; } else bHasNonAttributeChildren = true; } if( !bHasNonAttributeChildren ) { if( !_GrowBuffer( *pnLength + 40, ppszText, pnMaxLength ) ) return false; if( psNode->pszValue[0] == '?' ) strcat( *ppszText + *pnLength, ""?>\\n"" ); else strcat( *ppszText + *pnLength, "" />\\n"" ); } else { bool bJustText = true; strcat( *ppszText + *pnLength, "">"" ); for( psChild = psNode->psChild; psChild != nullptr; psChild = psChild->psNext ) { if( psChild->eType == CXT_Attribute ) continue; if( psChild->eType != CXT_Text && bJustText ) { bJustText = false; *pnLength += strlen(*ppszText + *pnLength); if( !_GrowBuffer( 1 + *pnLength, ppszText, pnMaxLength ) ) return false; strcat( *ppszText + *pnLength, ""\\n"" ); } if( !CPLSerializeXMLNode( psChild, nIndent + 2, ppszText, pnLength, pnMaxLength ) ) return false; } *pnLength += strlen(*ppszText + *pnLength); if( !_GrowBuffer( strlen(psNode->pszValue) + *pnLength + 40 + nIndent, ppszText, pnMaxLength ) ) return false; if( !bJustText ) { if( nIndent ) memset( *ppszText + *pnLength, ' ', nIndent ); *pnLength += nIndent; (*ppszText)[*pnLength] = '\\0'; } *pnLength += strlen(*ppszText + *pnLength); snprintf( *ppszText + *pnLength, *pnMaxLength - *pnLength, ""\\n"", psNode->pszValue ); } } return true; } /************************************************************************/ /* CPLSerializeXMLTree() */ /************************************************************************/ /** * \\brief Convert tree into string document. * * This function converts a CPLXMLNode tree representation of a document * into a flat string representation. White space indentation is used * visually preserve the tree structure of the document. The returned * document becomes owned by the caller and should be freed with CPLFree() * when no longer needed. * * @param psNode the node to serialize. * * @return the document on success or NULL on failure. */ char *CPLSerializeXMLTree( const CPLXMLNode *psNode ) { size_t nMaxLength = 100; char *pszText = static_cast(CPLCalloc(nMaxLength, sizeof(char))); if( pszText == nullptr ) return nullptr; size_t nLength = 0; for( const CPLXMLNode *psThis = psNode; psThis != nullptr; psThis = psThis->psNext ) { if( !CPLSerializeXMLNode( psThis, 0, &pszText, &nLength, &nMaxLength ) ) { VSIFree(pszText); return nullptr; } } return pszText; } /************************************************************************/ /* CPLCreateXMLNode() */ /************************************************************************/ #ifdef DEBUG static CPLXMLNode* psDummyStaticNode; #endif /** * \\brief Create an document tree item. * * Create a single CPLXMLNode object with the desired value and type, and * attach it as a child of the indicated parent. * * @param poParent the parent to which this node should be attached as a * child. May be NULL to keep as free standing. * @param eType the type of the newly created node * @param pszText the value of the newly created node * * @return the newly created node, now owned by the caller (or parent node). */ CPLXMLNode *CPLCreateXMLNode( CPLXMLNode *poParent, CPLXMLNodeType eType, const char *pszText ) { auto ret = _CPLCreateXMLNode(poParent, eType, pszText); if( !ret ) { CPLError(CE_Fatal, CPLE_OutOfMemory, ""CPLCreateXMLNode() failed""); } return ret; } /************************************************************************/ /* _CPLCreateXMLNode() */ /************************************************************************/ /* Same as CPLCreateXMLNode() but can return NULL in case of out-of-memory */ /* situation */ static CPLXMLNode *_CPLCreateXMLNode( CPLXMLNode *poParent, CPLXMLNodeType eType, const char *pszText ) { /* -------------------------------------------------------------------- */ /* Create new node. */ /* -------------------------------------------------------------------- */ CPLXMLNode *psNode = static_cast(VSICalloc(sizeof(CPLXMLNode), 1)); if( psNode == nullptr ) { CPLError(CE_Failure, CPLE_OutOfMemory, ""Cannot allocate CPLXMLNode""); return nullptr; } psNode->eType = eType; psNode->pszValue = VSIStrdup( pszText ? pszText : """" ); if( psNode->pszValue == nullptr ) { CPLError(CE_Failure, CPLE_OutOfMemory, ""Cannot allocate psNode->pszValue""); VSIFree(psNode); return nullptr; } /* -------------------------------------------------------------------- */ /* Attach to parent, if provided. */ /* -------------------------------------------------------------------- */ if( poParent != nullptr ) { if( poParent->psChild == nullptr ) poParent->psChild = psNode; else { CPLXMLNode *psLink = poParent->psChild; if( psLink->psNext == nullptr && eType == CXT_Attribute && psLink->eType == CXT_Text ) { psNode->psNext = psLink; poParent->psChild = psNode; } else { while( psLink->psNext != nullptr ) { if( eType == CXT_Attribute && psLink->psNext->eType == CXT_Text ) { psNode->psNext = psLink->psNext; break; } psLink = psLink->psNext; } psLink->psNext = psNode; } } } #ifdef DEBUG else { // Coverity sometimes doesn't realize that this function is passed // with a non NULL parent and thinks that this branch is taken, leading // to creating object being leak by caller. This ugly hack hopefully // makes it believe that someone will reference it. psDummyStaticNode = psNode; } #endif return psNode; } /************************************************************************/ /* CPLDestroyXMLNode() */ /************************************************************************/ /** * \\brief Destroy a tree. * * This function frees resources associated with a CPLXMLNode and all its * children nodes. * * @param psNode the tree to free. */ void CPLDestroyXMLNode( CPLXMLNode *psNode ) { while( psNode != nullptr ) { if( psNode->pszValue != nullptr ) CPLFree( psNode->pszValue ); if( psNode->psChild != nullptr ) { CPLXMLNode* psNext = psNode->psNext; psNode->psNext = psNode->psChild; // Move the child and its siblings as the next // siblings of the current node. if( psNext != nullptr ) { CPLXMLNode* psIter = psNode->psChild; while( psIter->psNext != nullptr ) psIter = psIter->psNext; psIter->psNext = psNext; } } CPLXMLNode* psNext = psNode->psNext; CPLFree( psNode ); psNode = psNext; } } /************************************************************************/ /* CPLSearchXMLNode() */ /************************************************************************/ /** * \\brief Search for a node in document. * * Searches the children (and potentially siblings) of the documented * passed in for the named element or attribute. To search following * siblings as well as children, prefix the pszElement name with an equal * sign. This function does an in-order traversal of the document tree. * So it will first match against the current node, then its first child, * that child's first child, and so on. * * Use CPLGetXMLNode() to find a specific child, or along a specific * node path. * * @param psRoot the subtree to search. This should be a node of type * CXT_Element. NULL is safe. * * @param pszElement the name of the element or attribute to search for. * * @return The matching node or NULL on failure. */ CPLXMLNode *CPLSearchXMLNode( CPLXMLNode *psRoot, const char *pszElement ) { if( psRoot == nullptr || pszElement == nullptr ) return nullptr; bool bSideSearch = false; if( *pszElement == '=' ) { bSideSearch = true; pszElement++; } /* -------------------------------------------------------------------- */ /* Does this node match? */ /* -------------------------------------------------------------------- */ if( (psRoot->eType == CXT_Element || psRoot->eType == CXT_Attribute) && EQUAL(pszElement, psRoot->pszValue) ) return psRoot; /* -------------------------------------------------------------------- */ /* Search children. */ /* -------------------------------------------------------------------- */ CPLXMLNode *psChild = nullptr; for( psChild = psRoot->psChild; psChild != nullptr; psChild = psChild->psNext) { if( (psChild->eType == CXT_Element || psChild->eType == CXT_Attribute) && EQUAL(pszElement, psChild->pszValue) ) return psChild; if( psChild->psChild != nullptr ) { CPLXMLNode *psResult = CPLSearchXMLNode( psChild, pszElement ); if( psResult != nullptr ) return psResult; } } /* -------------------------------------------------------------------- */ /* Search siblings if we are in side search mode. */ /* -------------------------------------------------------------------- */ if( bSideSearch ) { for( psRoot = psRoot->psNext; psRoot != nullptr; psRoot = psRoot->psNext ) { CPLXMLNode *psResult = CPLSearchXMLNode( psRoot, pszElement ); if( psResult != nullptr ) return psResult; } } return nullptr; } /************************************************************************/ /* CPLGetXMLNode() */ /************************************************************************/ /** * \\brief Find node by path. * * Searches the document or subdocument indicated by psRoot for an element * (or attribute) with the given path. The path should consist of a set of * element names separated by dots, not including the name of the root * element (psRoot). If the requested element is not found NULL is returned. * * Attribute names may only appear as the last item in the path. * * The search is done from the root nodes children, but all intermediate * nodes in the path must be specified. Searching for ""name"" would only find * a name element or attribute if it is a direct child of the root, not at any * level in the subdocument. * * If the pszPath is prefixed by ""="" then the search will begin with the * root node, and its siblings, instead of the root nodes children. This * is particularly useful when searching within a whole document which is * often prefixed by one or more ""junk"" nodes like the declaration. * * @param psRoot the subtree in which to search. This should be a node of * type CXT_Element. NULL is safe. * * @param pszPath the list of element names in the path (dot separated). * * @return the requested element node, or NULL if not found. */ CPLXMLNode *CPLGetXMLNode( CPLXMLNode *psRoot, const char *pszPath ) { if( psRoot == nullptr || pszPath == nullptr ) return nullptr; bool bSideSearch = false; if( *pszPath == '=' ) { bSideSearch = true; pszPath++; } char *apszTokens[2] = { const_cast(pszPath), nullptr }; // Slight optimization: avoid using CSLTokenizeStringComplex that // does memory allocations when it is not really necessary. char **papszTokens = strchr(pszPath, '.') ? CSLTokenizeStringComplex( pszPath, ""."", FALSE, FALSE ) : apszTokens; int iToken = 0; while( papszTokens[iToken] != nullptr && psRoot != nullptr ) { CPLXMLNode *psChild = nullptr; if( bSideSearch ) { psChild = psRoot; bSideSearch = false; } else psChild = psRoot->psChild; for( ; psChild != nullptr; psChild = psChild->psNext ) { if( psChild->eType != CXT_Text && EQUAL(papszTokens[iToken], psChild->pszValue) ) break; } if( psChild == nullptr ) { psRoot = nullptr; break; } psRoot = psChild; iToken++; } if( papszTokens != apszTokens ) CSLDestroy( papszTokens ); return psRoot; } /************************************************************************/ /* CPLGetXMLValue() */ /************************************************************************/ /** * \\brief Fetch element/attribute value. * * Searches the document for the element/attribute value associated with * the path. The corresponding node is internally found with CPLGetXMLNode() * (see there for details on path handling). Once found, the value is * considered to be the first CXT_Text child of the node. * * If the attribute/element search fails, or if the found node has no * value then the passed default value is returned. * * The returned value points to memory within the document tree, and should * not be altered or freed. * * @param psRoot the subtree in which to search. This should be a node of * type CXT_Element. NULL is safe. * * @param pszPath the list of element names in the path (dot separated). An * empty path means get the value of the psRoot node. * * @param pszDefault the value to return if a corresponding value is not * found, may be NULL. * * @return the requested value or pszDefault if not found. */ const char *CPLGetXMLValue( const CPLXMLNode *psRoot, const char *pszPath, const char *pszDefault ) { const CPLXMLNode *psTarget = nullptr; if( pszPath == nullptr || *pszPath == '\\0' ) psTarget = psRoot; else psTarget = CPLGetXMLNode( psRoot, pszPath ); if( psTarget == nullptr ) return pszDefault; if( psTarget->eType == CXT_Attribute ) { CPLAssert( psTarget->psChild != nullptr && psTarget->psChild->eType == CXT_Text ); return psTarget->psChild->pszValue; } if( psTarget->eType == CXT_Element ) { // Find first non-attribute child, and verify it is a single text // with no siblings. psTarget = psTarget->psChild; while( psTarget != nullptr && psTarget->eType == CXT_Attribute ) psTarget = psTarget->psNext; if( psTarget != nullptr && psTarget->eType == CXT_Text && psTarget->psNext == nullptr ) return psTarget->pszValue; } return pszDefault; } /************************************************************************/ /* CPLAddXMLChild() */ /************************************************************************/ /** * \\brief Add child node to parent. * * The passed child is added to the list of children of the indicated * parent. Normally the child is added at the end of the parents child * list, but attributes (CXT_Attribute) will be inserted after any other * attributes but before any other element type. Ownership of the child * node is effectively assumed by the parent node. If the child has * siblings (its psNext is not NULL) they will be trimmed, but if the child * has children they are carried with it. * * @param psParent the node to attach the child to. May not be NULL. * * @param psChild the child to add to the parent. May not be NULL. Should * not be a child of any other parent. */ void CPLAddXMLChild( CPLXMLNode *psParent, CPLXMLNode *psChild ) { if( psParent->psChild == nullptr ) { psParent->psChild = psChild; return; } // Insert at head of list if first child is not attribute. if( psChild->eType == CXT_Attribute && psParent->psChild->eType != CXT_Attribute ) { psChild->psNext = psParent->psChild; psParent->psChild = psChild; return; } // Search for end of list. CPLXMLNode *psSib = nullptr; for( psSib = psParent->psChild; psSib->psNext != nullptr; psSib = psSib->psNext ) { // Insert attributes if the next node is not an attribute. if( psChild->eType == CXT_Attribute && psSib->psNext != nullptr && psSib->psNext->eType != CXT_Attribute ) { psChild->psNext = psSib->psNext; psSib->psNext = psChild; return; } } psSib->psNext = psChild; } /************************************************************************/ /* CPLRemoveXMLChild() */ /************************************************************************/ /** * \\brief Remove child node from parent. * * The passed child is removed from the child list of the passed parent, * but the child is not destroyed. The child retains ownership of its * own children, but is cleanly removed from the child list of the parent. * * @param psParent the node to the child is attached to. * * @param psChild the child to remove. * * @return TRUE on success or FALSE if the child was not found. */ int CPLRemoveXMLChild( CPLXMLNode *psParent, CPLXMLNode *psChild ) { if( psParent == nullptr ) return FALSE; CPLXMLNode *psLast = nullptr; CPLXMLNode *psThis = nullptr; for( psThis = psParent->psChild; psThis != nullptr; psLast = psThis, psThis = psThis->psNext ) { if( psThis == psChild ) { if( psLast == nullptr ) psParent->psChild = psThis->psNext; else psLast->psNext = psThis->psNext; psThis->psNext = nullptr; return TRUE; } } return FALSE; } /************************************************************************/ /* CPLAddXMLSibling() */ /************************************************************************/ /** * \\brief Add new sibling. * * The passed psNewSibling is added to the end of siblings of the * psOlderSibling node. That is, it is added to the end of the psNext * chain. There is no special handling if psNewSibling is an attribute. * If this is required, use CPLAddXMLChild(). * * @param psOlderSibling the node to attach the sibling after. * * @param psNewSibling the node to add at the end of psOlderSiblings psNext * chain. */ void CPLAddXMLSibling( CPLXMLNode *psOlderSibling, CPLXMLNode *psNewSibling ) { if( psOlderSibling == nullptr ) return; while( psOlderSibling->psNext != nullptr ) psOlderSibling = psOlderSibling->psNext; psOlderSibling->psNext = psNewSibling; } /************************************************************************/ /* CPLCreateXMLElementAndValue() */ /************************************************************************/ /** * \\brief Create an element and text value. * * This is function is a convenient short form for: * * \\code * CPLXMLNode *psTextNode; * CPLXMLNode *psElementNode; * * psElementNode = CPLCreateXMLNode( psParent, CXT_Element, pszName ); * psTextNode = CPLCreateXMLNode( psElementNode, CXT_Text, pszValue ); * * return psElementNode; * \\endcode * * It creates a CXT_Element node, with a CXT_Text child, and * attaches the element to the passed parent. * * @param psParent the parent node to which the resulting node should * be attached. May be NULL to keep as freestanding. * * @param pszName the element name to create. * @param pszValue the text to attach to the element. Must not be NULL. * * @return the pointer to the new element node. */ CPLXMLNode *CPLCreateXMLElementAndValue( CPLXMLNode *psParent, const char *pszName, const char *pszValue ) { CPLXMLNode *psElementNode = CPLCreateXMLNode( psParent, CXT_Element, pszName ); CPLCreateXMLNode( psElementNode, CXT_Text, pszValue ); return psElementNode; } /************************************************************************/ /* CPLCreateXMLElementAndValue() */ /************************************************************************/ /** * \\brief Create an attribute and text value. * * This is function is a convenient short form for: * * \\code * CPLXMLNode *psAttributeNode; * * psAttributeNode = CPLCreateXMLNode( psParent, CXT_Attribute, pszName ); * CPLCreateXMLNode( psAttributeNode, CXT_Text, pszValue ); * \\endcode * * It creates a CXT_Attribute node, with a CXT_Text child, and * attaches the element to the passed parent. * * @param psParent the parent node to which the resulting node should * be attached. Must not be NULL. * @param pszName the attribute name to create. * @param pszValue the text to attach to the attribute. Must not be NULL. * * @since GDAL 2.0 */ void CPLAddXMLAttributeAndValue( CPLXMLNode *psParent, const char *pszName, const char *pszValue ) { CPLAssert(psParent != nullptr); CPLXMLNode *psAttributeNode = CPLCreateXMLNode( psParent, CXT_Attribute, pszName ); CPLCreateXMLNode( psAttributeNode, CXT_Text, pszValue ); } /************************************************************************/ /* CPLCloneXMLTree() */ /************************************************************************/ /** * \\brief Copy tree. * * Creates a deep copy of a CPLXMLNode tree. * * @param psTree the tree to duplicate. * * @return a copy of the whole tree. */ CPLXMLNode *CPLCloneXMLTree( const CPLXMLNode *psTree ) { CPLXMLNode *psPrevious = nullptr; CPLXMLNode *psReturn = nullptr; while( psTree != nullptr ) { CPLXMLNode *psCopy = CPLCreateXMLNode( nullptr, psTree->eType, psTree->pszValue ); if( psReturn == nullptr ) psReturn = psCopy; if( psPrevious != nullptr ) psPrevious->psNext = psCopy; if( psTree->psChild != nullptr ) psCopy->psChild = CPLCloneXMLTree( psTree->psChild ); psPrevious = psCopy; psTree = psTree->psNext; } return psReturn; } /************************************************************************/ /* CPLSetXMLValue() */ /************************************************************************/ /** * \\brief Set element value by path. * * Find (or create) the target element or attribute specified in the * path, and assign it the indicated value. * * Any path elements that do not already exist will be created. The target * nodes value (the first CXT_Text child) will be replaced with the provided * value. * * If the target node is an attribute instead of an element, the name * should be prefixed with a #. * * Example: * CPLSetXMLValue( ""Citation.Id.Description"", ""DOQ dataset"" ); * CPLSetXMLValue( ""Citation.Id.Description.#name"", ""doq"" ); * * @param psRoot the subdocument to be updated. * * @param pszPath the dot separated path to the target element/attribute. * * @param pszValue the text value to assign. * * @return TRUE on success. */ int CPLSetXMLValue( CPLXMLNode *psRoot, const char *pszPath, const char *pszValue ) { char **papszTokens = CSLTokenizeStringComplex( pszPath, ""."", FALSE, FALSE ); int iToken = 0; while( papszTokens[iToken] != nullptr ) { bool bIsAttribute = false; const char *pszName = papszTokens[iToken]; if( pszName[0] == '#' ) { bIsAttribute = true; pszName++; } if( psRoot->eType != CXT_Element ) { CSLDestroy( papszTokens ); return FALSE; } CPLXMLNode *psChild = nullptr; for( psChild = psRoot->psChild; psChild != nullptr; psChild = psChild->psNext ) { if( psChild->eType != CXT_Text && EQUAL(pszName, psChild->pszValue) ) break; } if( psChild == nullptr ) { if( bIsAttribute ) psChild = CPLCreateXMLNode( psRoot, CXT_Attribute, pszName ); else psChild = CPLCreateXMLNode( psRoot, CXT_Element, pszName ); } psRoot = psChild; iToken++; } CSLDestroy( papszTokens ); /* -------------------------------------------------------------------- */ /* Find the ""text"" child if there is one. */ /* -------------------------------------------------------------------- */ CPLXMLNode *psTextChild = psRoot->psChild; while( psTextChild != nullptr && psTextChild->eType != CXT_Text ) psTextChild = psTextChild->psNext; /* -------------------------------------------------------------------- */ /* Now set a value node under this node. */ /* -------------------------------------------------------------------- */ if( psTextChild == nullptr ) CPLCreateXMLNode( psRoot, CXT_Text, pszValue ); else { CPLFree( psTextChild->pszValue ); psTextChild->pszValue = CPLStrdup( pszValue ); } return TRUE; } /************************************************************************/ /* CPLStripXMLNamespace() */ /************************************************************************/ /** * \\brief Strip indicated namespaces. * * The subdocument (psRoot) is recursively examined, and any elements * with the indicated namespace prefix will have the namespace prefix * stripped from the element names. If the passed namespace is NULL, then * all namespace prefixes will be stripped. * * Nodes other than elements should remain unaffected. The changes are * made ""in place"", and should not alter any node locations, only the * pszValue field of affected nodes. * * @param psRoot the document to operate on. * @param pszNamespace the name space prefix (not including colon), or NULL. * @param bRecurse TRUE to recurse over whole document, or FALSE to only * operate on the passed node. */ void CPLStripXMLNamespace( CPLXMLNode *psRoot, const char *pszNamespace, int bRecurse ) { size_t nNameSpaceLen = (pszNamespace) ? strlen(pszNamespace) : 0; while( psRoot != nullptr ) { if( psRoot->eType == CXT_Element || psRoot->eType == CXT_Attribute ) { if( pszNamespace != nullptr ) { if( EQUALN(pszNamespace, psRoot->pszValue, nNameSpaceLen) && psRoot->pszValue[nNameSpaceLen] == ':' ) { memmove(psRoot->pszValue, psRoot->pszValue+nNameSpaceLen+1, strlen(psRoot->pszValue+nNameSpaceLen+1) + 1); } } else { for( const char *pszCheck = psRoot->pszValue; *pszCheck != '\\0'; pszCheck++ ) { if( *pszCheck == ':' ) { memmove(psRoot->pszValue, pszCheck + 1, strlen(pszCheck + 1) + 1); break; } } } } if( bRecurse ) { if( psRoot->psChild != nullptr ) CPLStripXMLNamespace( psRoot->psChild, pszNamespace, 1 ); psRoot = psRoot->psNext; } else { break; } } } /************************************************************************/ /* CPLParseXMLFile() */ /************************************************************************/ /** * \\brief Parse XML file into tree. * * The named file is opened, loaded into memory as a big string, and * parsed with CPLParseXMLString(). Errors in reading the file or parsing * the XML will be reported by CPLError(). * * The ""large file"" API is used, so XML files can come from virtualized * files. * * @param pszFilename the file to open. * * @return NULL on failure, or the document tree on success. */ CPLXMLNode *CPLParseXMLFile( const char *pszFilename ) { /* -------------------------------------------------------------------- */ /* Ingest the file. */ /* -------------------------------------------------------------------- */ GByte *pabyOut = nullptr; if( !VSIIngestFile( nullptr, pszFilename, &pabyOut, nullptr, -1 ) ) return nullptr; char *pszDoc = reinterpret_cast(pabyOut); /* -------------------------------------------------------------------- */ /* Parse it. */ /* -------------------------------------------------------------------- */ CPLXMLNode *psTree = CPLParseXMLString( pszDoc ); CPLFree( pszDoc ); return psTree; } /************************************************************************/ /* CPLSerializeXMLTreeToFile() */ /************************************************************************/ /** * \\brief Write document tree to a file. * * The passed document tree is converted into one big string (with * CPLSerializeXMLTree()) and then written to the named file. Errors writing * the file will be reported by CPLError(). The source document tree is * not altered. If the output file already exists it will be overwritten. * * @param psTree the document tree to write. * @param pszFilename the name of the file to write to. * @return TRUE on success, FALSE otherwise. */ int CPLSerializeXMLTreeToFile( const CPLXMLNode *psTree, const char *pszFilename ) { /* -------------------------------------------------------------------- */ /* Serialize document. */ /* -------------------------------------------------------------------- */ char *pszDoc = CPLSerializeXMLTree( psTree ); if( pszDoc == nullptr ) return FALSE; const vsi_l_offset nLength = strlen(pszDoc); /* -------------------------------------------------------------------- */ /* Create file. */ /* -------------------------------------------------------------------- */ VSILFILE *fp = VSIFOpenL( pszFilename, ""wt"" ); if( fp == nullptr ) { CPLError( CE_Failure, CPLE_OpenFailed, ""Failed to open %.500s to write."", pszFilename ); CPLFree( pszDoc ); return FALSE; } /* -------------------------------------------------------------------- */ /* Write file. */ /* -------------------------------------------------------------------- */ if( VSIFWriteL(pszDoc, 1, static_cast(nLength), fp ) != nLength ) { CPLError( CE_Failure, CPLE_FileIO, ""Failed to write whole XML document (%.500s)."", pszFilename ); CPL_IGNORE_RET_VAL(VSIFCloseL( fp )); CPLFree( pszDoc ); return FALSE; } /* -------------------------------------------------------------------- */ /* Cleanup */ /* -------------------------------------------------------------------- */ const bool bRet = VSIFCloseL( fp ) == 0; if( !bRet ) { CPLError( CE_Failure, CPLE_FileIO, ""Failed to write whole XML document (%.500s)."", pszFilename ); } CPLFree( pszDoc ); return bRet; } /************************************************************************/ /* CPLCleanXMLElementName() */ /************************************************************************/ /** * \\brief Make string into safe XML token. * * Modifies a string in place to try and make it into a legal * XML token that can be used as an element name. This is accomplished * by changing any characters not legal in a token into an underscore. * * NOTE: This function should implement the rules in section 2.3 of * http://www.w3.org/TR/xml11/ but it doesn't yet do that properly. We * only do a rough approximation of that. * * @param pszTarget the string to be adjusted. It is altered in place. */ void CPLCleanXMLElementName( char *pszTarget ) { if( pszTarget == nullptr ) return; for( ; *pszTarget != '\\0'; pszTarget++ ) { if( (*(reinterpret_cast(pszTarget)) & 0x80) || isalnum( *pszTarget ) || *pszTarget == '_' || *pszTarget == '.' ) { // Ok. } else { *pszTarget = '_'; } } } /************************************************************************/ /* CPLXMLTreeCloser::getDocumentElement() */ /************************************************************************/ CPLXMLNode* CPLXMLTreeCloser::getDocumentElement() { CPLXMLNode *doc = get(); // skip the Declaration and assume the next is the root element while (doc != nullptr && (doc->eType != CXT_Element || doc->pszValue[0] == '?') ) { doc = doc->psNext; } return doc; } ",16293,True,2883.732919270331,median "//// // To add a release, copy and paste the following text, uncomment the relevant // sections, and add a link to the new section in the list of releases at the // top of the page. Note that release subheads must be floated and sections // cannot be empty. // TEMPLATE // [[release-notes-n.n.n]] // == {es} n.n.n //[float] [[breaking-n.n.n]] //=== Breaking Changes //[float] //=== Breaking Java Changes //[float] //=== Deprecations //[float] //=== New Features //[float] //=== Enhancements //[float] //=== Bug Fixes //[float] //=== Regressions //[float] //=== Known Issues //// [[release-notes-6.2.4]] == {es} version 6.2.4 //[float] //[[breaking-6.2.4]] //=== Breaking Changes //[float] //=== Breaking Java Changes //[float] //=== Deprecations //[float] //=== New Features //[float] //=== Enhancements [float] === Bug Fixes Engine:: * Harden periodically check to avoid endless flush loop {pull}29125[#29125] (issues: {issue}28350[#28350], {issue}29097[#29097]) Ingest:: * Don't allow referencing the pattern bank name in the pattern bank {pull}29295[#29295] (issue: {issue}29257[#29257]) [float] === Regressions Fail snapshot operations early when creating or deleting a snapshot on a repository that has been written to by an older Elasticsearch after writing to it with a newer Elasticsearch version. ({pull}30140[#30140]) Java High Level REST Client:: * Bulk processor#awaitClose to close scheduler {pull}29263[#29263] Fix NPE when CumulativeSum agg encounters null value/empty bucket ({pull}29641[#29641]) Do not fail snapshot when deleting a missing snapshotted file ({pull}30332[#30332]) Java Low Level REST Client:: * REST client: hosts marked dead for the first time should not be immediately retried {pull}29230[#29230] Machine Learning:: * Prevents failed jobs from mistakenly re-opening after node loss recovery. * Returns an error when an operation cannot be submitted because the process was killed. * Respects the datafeed frequency when it is less or equal to the `query_delay` setting. Network:: * Cross-cluster search and default connections can get crossed [OPEN] [ISSUE] {pull}29321[#29321] Percolator:: * Fixed bug when non percolator docs end up in the search hits {pull}29447[#29447] (issue: {issue}29429[#29429]) * Fixed a msm accounting error that can occur during analyzing a percolator query {pull}29415[#29415] (issue: {issue}29393[#29393]) * Fix more query extraction bugs. {pull}29388[#29388] (issues: {issue}28353[#28353], {issue}29376[#29376]) * Fix some query extraction bugs. {pull}29283[#29283] Plugins:: * Plugins: Fix native controller confirmation for non-meta plugin {pull}29434[#29434] Search:: * Propagate ignore_unmapped to inner_hits {pull}29261[#29261] (issue: {issue}29071[#29071]) Security/Authentication:: * Adds missing `idp.use_single_logout` and `populate_user_metadata` SAML realm settings. See <>. Settings:: * Archive unknown or invalid settings on updates {pull}28888[#28888] (issue: {issue}28609[#28609]) Watcher:: * Re-enables `smtp.*` account configuration properties in the notification settings. See <>. * Ensures starting and stopping {watcher} is properly acknowledged as a master node action. * Refrains from appending a question mark to an HTTP request if no parameters are used. //[float] //=== Known Issues [[release-notes-6.2.3]] == {es} version 6.2.3 //[float] //[[breaking-6.2.3]] //=== Breaking Changes //[float] //=== Breaking Java Changes [float] === Deprecations Deprecated multi-argument versions of the request methods in the RestClient. Prefer the ""Request"" object flavored methods. ({pull}30315[#30315]) //[float] //=== New Features A new analysis plugin called `analysis_nori` that exposes the Lucene Korean analysis module. ({pull}30397[#30397]) [float] === Enhancements Highlighting:: * Limit analyzed text for highlighting (improvements) {pull}28808[#28808] (issues: {issue}16764[#16764], {issue}27934[#27934]) {ref-64}/breaking_64_api_changes.html#copy-source-settings-on-resize[Allow copying source settings on index resize operations] ({pull}30255[#30255]) {ref-64}/breaking_64_api_changes.html#copy-source-settings-on-resize[Allow copying source settings on index resize operations] ({pull}30255[#30255], {pull}30404[#30404]) Added new ""Request"" object flavored request methods in the RestClient. Prefer these instead of the multi-argument versions. ({pull}29623[#29623]) Recovery:: * Require translogUUID when reading global checkpoint {pull}28587[#28587] (issue: {issue}28435[#28435]) Added `setJsonEntity` to `Request` object so it is marginally easier to send JSON. ({pull}30447[#30447]) Watcher HTTP client used in watches now allows more parallel connections to the same endpoint and evicts long running connections. ({pull}30130[#30130]) The cluster state listener to decide if watcher should be stopped/started/paused now runs far less code in an executor but is more synchronous and predictable. Also the trigger engine thread is only started on data nodes. And the Execute Watch API can be triggered regardless is watcher is started or stopped. ({pull}30118[#30118]) Added put index template API to the high level rest client ({pull}30400[#30400]) Add ability to filter coordinating-only nodes when interacting with cluster APIs. ({pull}30313[#30313]) [float] === Bug Fixes Core:: * Remove special handling for _all in nodes info {pull}28971[#28971] (issue: {issue}28797[#28797]) Engine:: * Avoid class cast exception from index writer {pull}28989[#28989] * Maybe die before failing engine {pull}28973[#28973] (issues: {issue}27265[#27265], {issue}28967[#28967]) * Never block on key in `LiveVersionMap#pruneTombstones` {pull}28736[#28736] (issue: {issue}28714[#28714]) Ingest:: * Continue registering pipelines after one pipeline parse failure. {pull}28752[#28752] (issue: {issue}28269[#28269]) Java High Level REST Client:: * REST high-level client: encode path parts {pull}28663[#28663] (issue: {issue}28625[#28625]) Machine Learning:: * Fixed the <> such that it returns only machine learning-specific node attributes. Monitoring:: * Aligned reporting of index statistics that exist in the current cluster state. This fix avoids subtle race conditions in stats reporting. Packaging:: * Delay path expansion on Windows {pull}28753[#28753] (issues: {issue}27675[#27675], {issue}28748[#28748]) Percolator:: * Fix percolator query analysis for function_score query {pull}28854[#28854] * Improved percolator's random candidate query duel test {pull}28840[#28840] Security:: * Fixed handling of comments in XML documents [ESA-2018-07]. * Fixed auditing such that when you use a local audit index, it maintains the mappings automatically. Maintenance is necessary, for example, when new fields are introduced or document types change. * Added and changed settings for the SAML NameID policy. For example, added the `nameid.allow_create` setting and changed the default value for the SPNameQualifier setting to blank. See {stack-ov}/saml-realm.html[SAML Authentication]. * Fixed handling of an Assertion Consumer Service (ACS) URL with existing query parameters. See {stack-ov}/saml-realm.html[SAML Authentication]. * Fixed the PKI realm bootstrap check such that it works with secure settings. For more information, see <>. Snapshot/Restore:: * Fix NPE when using deprecated Azure settings {pull}28769[#28769] (issues: {issue}23518[#23518], {issue}28299[#28299]) Stats:: * Fix AdaptiveSelectionStats serialization bug {pull}28718[#28718] (issue: {issue}28713[#28713]) Watcher:: * Fixed the serialization of failed hipchat messages, such that it no longer tries to write the status field twice. * Fixed TransformInput toXContent serialization errors. For more information, see {stack-ov}/input-chain.html#_transforming_chained_input_data[Transforming Chained Input Data]. Allocation:: Auto-expand replicas when adding or removing nodes to prevent shard copies from being dropped and resynced when a data node rejoins the cluster ({pull}30423[#30423]) //[float] //=== Regressions //[float] //=== Known Issues [[release-notes-6.2.2]] == {es} version 6.2.2 //[float] //[[breaking-6.2.2]] //=== Breaking Changes //[float] //=== Breaking Java Changes //[float] //=== Deprecations //[float] //=== New Features [float] === Enhancements Recovery:: * Synced-flush should not seal index of out of sync replicas {pull}28464[#28464] (issue: {issue}10032[#10032]) [float] === Bug Fixes Core:: * Handle throws on tasks submitted to thread pools {pull}28667[#28667] * Fix size blocking queue to not lie about its weight {pull}28557[#28557] (issue: {issue}28547[#28547]) Ingest:: * Guard accessDeclaredMembers for Tika on JDK 10 {pull}28603[#28603] (issue: {issue}28602[#28602]) * Fix for bug that prevents pipelines to load that use stored scripts after a restart {pull}28588[#28588] Java High Level REST Client:: * Fix parsing of script fields {pull}28395[#28395] (issue: {issue}28380[#28380]) * Move to POST when calling API to retrieve which support request body {pull}28342[#28342] (issue: {issue}28326[#28326]) Machine Learning:: * Fixed an exception that occurred when a categorization field contained an empty string. Monitoring:: * Properly registered `xpack.monitoring.exporters.*.headers.*` settings, which were broken in 6.2.0 and 6.2.1. For more information, see <>. Packaging:: * Fix using relative custom config path {pull}28700[#28700] (issue: {issue}27610[#27610]) * Disable console logging in the Windows service {pull}28618[#28618] (issue: {issue}20422[#20422]) Percolator:: * Do not take duplicate query extractions into account for minimum_should_match attribute {pull}28353[#28353] (issue: {issue}28315[#28315]) Recovery:: * Fsync directory after cleanup {pull}28604[#28604] (issue: {issue}28435[#28435]) Security:: * Added CachingRealm to published artifacts so it can be used in custom realm extensions. * If the realm uses native role mappings and the security index health changes, the realm caches are cleared. For example, they are cleared when the index recovers from a red state, when the index is deleted, when the index becomes outdated, and when the index becomes up-to-date. * Fixed a bug that could prevent auditing to a remote index if the remote cluster was re-started at the same time as the audited cluster. * Removed AuthorityKeyIdentifier's Issuer and Serial number from certificates generated by `certgen` and `certutil`. This improves compatibility with certificate verification in {kib}. Watcher:: * Proxies now use HTTP by default, which was the default prior to 6.0. This fixes issues with HTTPS requests that tried to access proxies via HTTP. * Fixed the HTML sanitizer settings (`xpack.notification.email.html.sanitization.*`), which were broken in 6.2. For more information, see <>. //[float] //=== Regressions //[float] //=== Known Issues [[release-notes-6.2.1]] == {es} version 6.2.1 //[float] //[[breaking-6.2.1]] //=== Breaking Changes //[float] //=== Breaking Java Changes //[float] //=== Deprecations //[float] //=== New Features //[float] //=== Enhancements The cluster state listener to decide if watcher should be stopped/started/paused now runs far less code in an executor but is more synchronous and predictable. Also the trigger engine thread is only started on data nodes. And the Execute Watch API can be triggered regardless is watcher is started or stopped. ({pull}30118[#30118]) [float] === Bug Fixes Plugin Lang Painless:: * Painless: Fix For Loop NullPointerException {pull}28506[#28506] (issue: {issue}28501[#28501]) Plugins:: * Fix the ability to remove old plugin {pull}28540[#28540] (issue: {issue}28538[#28538]) Security:: * Fixed missing dependencies for x-pack-transport. * Fixed `saml-metadata` env file such that it sources the appropriate environment file. Machine Learning:: * Account for gaps in data counts after job is reopened ({pull}30294[#30294]) [[release-notes-6.2.0]] == {es} version 6.2.0 [float] [[breaking-6.2.0]] === Breaking Changes Aggregations:: * Add a new cluster setting to limit the total number of buckets returned by a request {pull}27581[#27581] (issues: {issue}26012[#26012], {issue}27452[#27452]) Core:: * Forbid granting the all permission in production {pull}27548[#27548] Highlighting:: * Limit the analyzed text for highlighting {pull}27934[#27934] (issue: {issue}27517[#27517]) Rollover:: * Fail rollover if duplicated alias found in templates {pull}28110[#28110] (issue: {issue}26976[#26976]) Search:: * Introduce limit to the number of terms in Terms Query {pull}27968[#27968] (issue: {issue}18829[#18829]) [float] === Breaking Java Changes Java API:: * Remove `operationThreaded` from Java API {pull}27836[#27836] Java High Level REST Client:: * REST high-level client: remove index suffix from indices client method names {pull}28263[#28263] [float] === Deprecations Analysis:: * Backport delimited payload filter renaming {pull}27535[#27535] (issue: {issue}26625[#26625]) Suggesters:: * deprecating `jarowinkler` in favor of `jaro_winkler` {pull}27526[#27526] * Deprecating `levenstein` in favor of `levensHtein` {pull}27409[#27409] (issue: {issue}27325[#27325]) [float] === New Features Machine Learning:: * Added the ability to identify scheduled events and prevent anomaly detection during these periods. For more information, see {stack-ov}/ml-calendars.html[Calendars and Scheduled Events]. Plugin Ingest GeoIp:: * Enable ASN support for Ingest GeoIP plugin. {pull}27958[#27958] (issue: {issue}27849[#27849]) Plugin Lang Painless:: * Painless: Add spi jar that will be published for extending whitelists {pull}28302[#28302] * Painless: Add a simple cache for whitelist methods and fields. {pull}28142[#28142] Plugins:: * Add the ability to bundle multiple plugins into a meta plugin {pull}28022[#28022] (issue: {issue}27316[#27316]) Rank Evaluation:: * Backport of ranking evaluation API (#27478) {pull}27844[#27844] (issue: {issue}27478[#27478]) Recovery:: * Backport for using lastSyncedGlobalCheckpoint in deletion policy {pull}27866[#27866] (issue: {issue}27826[#27826]) Reindex API:: * Add scroll parameter to _reindex API {pull}28041[#28041] (issue: {issue}27555[#27555]) Security:: * {security} now supports user authentication using SAML Single Sign on. For more information, see {stack-ov}/saml-realm.html[SAML authentication]. Watcher:: * Added a transform input for chained input. For more information, see {stack-ov}/input-chain.html#_transforming_chained_input_data[Transforming Chained Input Data]. [float] === Enhancements Allocation:: * Fix cluster.routing.allocation.enable and cluster.routing.rebalance.enable case {pull}28037[#28037] (issue: {issue}28007[#28007]) * Add node id to shard failure message {pull}28024[#28024] (issue: {issue}28018[#28018]) Analysis:: * Limit the analyzed text for highlighting (#27934) {pull}28176[#28176] (issue: {issue}27517[#27517]) * Allow TrimFilter to be used in custom normalizers {pull}27758[#27758] (issue: {issue}27310[#27310]) Circuit Breakers:: * Add accounting circuit breaker and track segment memory usage {pull}27116[#27116] (issue: {issue}27044[#27044]) Cluster:: * Adds wait_for_no_initializing_shards to cluster health API {pull}27489[#27489] (issue: {issue}25623[#25623]) Core:: * Introduce elasticsearch-core jar {pull}28191[#28191] (issue: {issue}27933[#27933]) * Rename core module to server {pull}28190[#28190] (issue: {issue}27933[#27933]) * Rename core module to server {pull}28180[#28180] (issue: {issue}27933[#27933]) * Introduce elasticsearch-core jar {pull}28178[#28178] (issue: {issue}27933[#27933]) * Add Writeable.Reader support to TransportResponseHandler {pull}28010[#28010] (issue: {issue}26315[#26315]) * Simplify rejected execution exception {pull}27664[#27664] (issue: {issue}27663[#27663]) * Add node name to thread pool executor name {pull}27663[#27663] (issues: {issue}26007[#26007], {issue}26835[#26835]) Discovery:: * Add information when master node left to DiscoveryNodes' shortSummary() {pull}28197[#28197] (issue: {issue}28169[#28169]) Engine:: * Move uid lock into LiveVersionMap {pull}27905[#27905] * Optimize version map for append-only indexing {pull}27752[#27752] Geo:: * [GEO] Add WKT Support to GeoBoundingBoxQueryBuilder {pull}27692[#27692] (issues: {issue}27690[#27690], {issue}9120[#9120]) * [Geo] Add Well Known Text (WKT) Parsing Support to ShapeBuilders {pull}27417[#27417] (issue: {issue}9120[#9120]) Highlighting:: * Include all sentences smaller than fragment_size in the unified highlighter {pull}28132[#28132] (issue: {issue}28089[#28089]) Ingest:: * Enable convert processor to support Long and Double {pull}27891[#27891] (issues: {issue}23085[#23085], {issue}23423[#23423]) Internal:: * Make KeyedLock reentrant {pull}27920[#27920] * Make AbstractQueryBuilder.declareStandardFields to be protected (#27865) {pull}27894[#27894] (issue: {issue}27865[#27865]) * Tighten the CountedBitSet class {pull}27632[#27632] * Avoid doing redundant work when checking for self references. {pull}26927[#26927] (issue: {issue}26907[#26907]) Java API:: * Add missing delegate methods to NodeIndicesStats {pull}28092[#28092] * Java api clean-up : consistency for `shards_acknowledged` getters {pull}27819[#27819] (issue: {issue}27784[#27784]) Java High Level REST Client:: * add toString implementation for UpdateRequest. {pull}27997[#27997] (issue: {issue}27986[#27986]) * Add Close Index API to the high level REST client {pull}27734[#27734] (issue: {issue}27205[#27205]) * Add Open Index API to the high level REST client {pull}27574[#27574] (issue: {issue}27205[#27205]) * Added Create Index support to high-level REST client {pull}27351[#27351] (issue: {issue}27205[#27205]) * Add multi get api to the high level rest client {pull}27337[#27337] (issue: {issue}27205[#27205]) * Add msearch api to high level client {pull}27274[#27274] Machine Learning:: * Increased tokenization flexibility for categorization. Now all {es} analyzer functionality is available, which opens up the possibility of sensibly categorizing non-English log messages. For more information, see {stack-ov}/ml-configuring-categories.html#ml-configuring-analyzer[Customizing the Categorization Analyzer]. * Improved the sensitivity of the analysis to high variance data with lots of values near zero. * Improved the decay rate of the model memory by using a weighted moving average. * Machine learning indices created after upgrading to 6.2 have the `auto_expand_replicas: 0-1` setting rather than a fixed setting of 1 replica. As a result, {ml} indices created after upgrading to 6.2 can have a green status on single node clusters. There is no impact in multi-node clusters. * Changed the credentials that are used by {dfeeds}. When {security} is enabled, a {dfeed} stores the roles of the user who created or updated the {dfeed} **at that time**. This means that if those roles are updated, the {dfeed} subsequently runs with the new permissions that are associated with the roles. However, if the user's roles are adjusted after creating or updating the {dfeed} then the {dfeed} continues to run with the permissions that are associated with the original roles. For more information, see {stack-ov}/ml-dfeeds.html[Datafeeds]. * Added a new `scheduled` forecast status, which indicates that the forecast has not started yet. Mapping:: * Allow `_doc` as a type. {pull}27816[#27816] (issues: {issue}27750[#27750], {issue}27751[#27751]) Monitoring:: * {monitoring} indices (`.monitoring`) created after upgrading to 6.2 have the `auto_expand_replicas: 0-1` setting rather than a fixed setting of 1 replica. As a result, monitoring indices created after upgrading to 6.2 can have a green status on single node clusters. There is no impact in multi-node clusters. * Added a cluster alert that triggers whenever a node is added, removed, or restarted. Network:: * Add NioGroup for use in different transports {pull}27737[#27737] (issue: {issue}27260[#27260]) * Add read timeouts to http module {pull}27713[#27713] * Implement byte array reusage in `NioTransport` {pull}27696[#27696] (issue: {issue}27563[#27563]) * Introduce resizable inbound byte buffer {pull}27551[#27551] (issue: {issue}27563[#27563]) * Decouple nio constructs from the tcp transport {pull}27484[#27484] (issue: {issue}27260[#27260]) Packaging:: * Extend JVM options to support multiple versions {pull}27675[#27675] (issue: {issue}27646[#27646]) * Add explicit coreutils dependency {pull}27660[#27660] (issue: {issue}27609[#27609]) * Detect mktemp from coreutils {pull}27659[#27659] (issues: {issue}27609[#27609], {issue}27643[#27643]) * Enable GC logs by default {pull}27610[#27610] * Use private directory for temporary files {pull}27609[#27609] (issues: {issue}14372[#14372], {issue}27144[#27144]) Percolator:: * also extract match_all queries when indexing percolator queries {pull}27585[#27585] Plugin Lang Painless:: * Painless: Add whitelist extensions {pull}28161[#28161] * Painless: Modify Loader to Load Classes Directly from Definition {pull}28088[#28088] * Clean Up Painless Cast Object {pull}27794[#27794] * Painless: Only allow Painless type names to be the same as the equivalent Java class. {pull}27264[#27264] Plugins:: * Add client actions to action plugin {pull}28280[#28280] (issue: {issue}27759[#27759]) * Plugins: Add validation to plugin descriptor parsing {pull}27951[#27951] * Plugins: Add plugin extension capabilities {pull}27881[#27881] * Add support for filtering mappings fields {pull}27603[#27603] Rank Evaluation:: * Simplify RankEvalResponse output {pull}28266[#28266] Recovery:: * Truncate tlog cli should assign global checkpoint {pull}28192[#28192] (issue: {issue}28181[#28181]) * Replica starts peer recovery with safe commit {pull}28181[#28181] (issue: {issue}10708[#10708]) * Primary send safe commit in file-based recovery {pull}28038[#28038] (issue: {issue}10708[#10708]) * Fail resync-failed shards in subsequent writes {pull}28005[#28005] * Introduce promoting index shard state {pull}28004[#28004] (issue: {issue}24841[#24841]) * Non-peer recovery should set the global checkpoint {pull}27965[#27965] * Persist global checkpoint when finalizing a peer recovery {pull}27947[#27947] (issue: {issue}27861[#27861]) * Rollback a primary before recovering from translog {pull}27804[#27804] (issue: {issue}10708[#10708]) Search:: * Use typeName() to check field type in GeoShapeQueryBuilder {pull}27730[#27730] * Optimize search_after when sorting in index sort order {pull}26401[#26401] Security:: * Added the ability to refresh tokens that were created by the token API. The API provides information about a refresh token, which you can use within 24 hours of its creation to extend the life of a token. For more information, see <>. * Added principal and role information to `access_granted`, `access_denied`, `run_as_granted`, and `run_as_denied` audit events. For more information about these events, see {stack-ov}/auditing.html[Auditing Security Events]. * Added audit event ignore policies, which are a way to tune the verbosity of an audit trail. These policies define rules for ignoring audit events that match specific attribute values. For more information, see {stack-ov}/audit-log-output.html#audit-log-ignore-policy[Logfile Audit Events Ignore Policies]. * Added a certificates API, which enables you to retrieve information about the X.509 certificates that are used to encrypt communications in your {es} cluster. For more information, see <>. Sequence IDs:: * Do not keep 5.x commits when having 6.x commits {pull}28188[#28188] (issues: {issue}27606[#27606], {issue}28038[#28038]) * Use lastSyncedGlobalCheckpoint in deletion policy {pull}27826[#27826] (issue: {issue}27606[#27606]) * Use CountedBitSet in LocalCheckpointTracker {pull}27793[#27793] * Only fsync global checkpoint if needed {pull}27652[#27652] * Keep commits and translog up to the global checkpoint {pull}27606[#27606] * Adjust CombinedDeletionPolicy for multiple commits {pull}27456[#27456] (issues: {issue}10708[#10708], {issue}27367[#27367]) * Keeps index commits up to the current global checkpoint {pull}27367[#27367] (issue: {issue}10708[#10708]) * Dedup translog operations by reading in reverse {pull}27268[#27268] (issue: {issue}10708[#10708]) Settings:: * Add validation of keystore setting names {pull}27626[#27626] Snapshot/Restore:: * Use AmazonS3.doesObjectExist() method in S3BlobContainer {pull}27723[#27723] * Remove XContentType auto detection in BlobStoreRepository {pull}27480[#27480] * Include include_global_state in Snapshot status API (#22423) {pull}26853[#26853] (issue: {issue}22423[#22423]) Task Manager:: * Add ability to associate an ID with tasks {pull}27764[#27764] (issue: {issue}23250[#23250]) Translog:: * Simplify MultiSnapshot#SeqNoset {pull}27547[#27547] (issue: {issue}27268[#27268]) * Enclose CombinedDeletionPolicy in SnapshotDeletionPolicy {pull}27528[#27528] (issues: {issue}27367[#27367], {issue}27456[#27456]) Watcher:: * Added the ability to set the `index` and `doc_type` dynamically in an index action. For more information, see {stack-ov}/actions-index.html[Index Action]. * Added a `refresh` index action attribute, which enables you to set the refresh policy of the write request. For more information, see {stack-ov}/actions-index.html[Index Action]. * Added support for actions in slack attachments, which enables you to add buttons that can be clicked in slack messages. For more information, see {stack-ov}/actions-slack.html[Slack Action]. * {watcher} indices (`.watch*` and `triggered_watches`) created after upgrading to 6.2 have the `auto_expand_replicas: 0-1` setting rather than a fixed setting of 1 replica. As a result, {watcher} indices created after upgrading to 6.2 can have a green status on single node clusters. There is no impact in multi-node clusters. [float] === Bug Fixes Aggregations:: * Adds metadata to rewritten aggregations {pull}28185[#28185] (issue: {issue}28170[#28170]) * Fix NPE on composite aggregation with sub-aggregations that need scores {pull}28129[#28129] * StringTerms.Bucket.getKeyAsNumber detection type {pull}28118[#28118] (issue: {issue}28012[#28012]) * Fix incorrect results for aggregations nested under a nested aggregation {pull}27946[#27946] (issue: {issue}27912[#27912]) * Fix global aggregation that requires breadth first and scores {pull}27942[#27942] (issues: {issue}22321[#22321], {issue}27928[#27928]) * Fix composite aggregation when after term is missing in the shard {pull}27936[#27936] * Fix preserving FiltersAggregationBuilder#keyed field on rewrite {pull}27900[#27900] (issue: {issue}27841[#27841]) * Using DocValueFormat::parseBytesRef for parsing missing value parameter {pull}27855[#27855] (issue: {issue}27788[#27788]) * Fix illegal cast of the ""low cardinality"" optimization of the `terms` aggregation. {pull}27543[#27543] * Always include the _index and _id for nested search hits. {pull}27201[#27201] (issue: {issue}27053[#27053]) Allocation:: * Do not open indices with broken settings {pull}26995[#26995] Core:: * Fix lock accounting in releasable lock {pull}28202[#28202] * Fixes ByteSizeValue to serialise correctly {pull}27702[#27702] (issue: {issue}27568[#27568]) * Do not set data paths on no local storage required {pull}27587[#27587] (issue: {issue}27572[#27572]) * Ensure threadcontext is preserved when refresh listeners are invoked {pull}27565[#27565] * Ensure logging is configured for CLI commands {pull}27523[#27523] (issue: {issue}27521[#27521]) Engine:: * Replica recovery could go into an endless flushing loop {pull}28350[#28350] * Use `_refresh` to shrink the version map on inactivity {pull}27918[#27918] (issue: {issue}27852[#27852]) * Allow resize version map under lock even if there are pending operations {pull}27870[#27870] (issue: {issue}27852[#27852]) * Reset LiveVersionMap on sync commit {pull}27534[#27534] (issue: {issue}27516[#27516]) Geo:: * Correct two equality checks on incomparable types {pull}27688[#27688] * Handle case where the hole vertex is south of the containing polygon(s) {pull}27685[#27685] (issue: {issue}25933[#25933]) Highlighting:: * Fix highlighting on a keyword field that defines a normalizer {pull}27604[#27604] Inner Hits:: * Add version support for inner hits in field collapsing (#27822) {pull}27833[#27833] (issue: {issue}27822[#27822]) Internal:: * Never return null from Strings.tokenizeToStringArray {pull}28224[#28224] (issue: {issue}28213[#28213]) * Fallback to TransportMasterNodeAction for cluster health retries {pull}28195[#28195] (issue: {issue}28169[#28169]) * Retain originalIndex info when rewriting FieldCapabilities requests {pull}27761[#27761] Java REST Client:: * Do not use system properties when building the HttpAsyncClient {pull}27829[#27829] (issue: {issue}27827[#27827]) Machine Learning:: * Improved error reporting for crashes and resource problems on Linux. * Improved the detection of seasonal trends in bucket spans longer than 1 hour. * Updated the forecast API to wait for validation and return an error if the validation fails. * Set the actual bucket value to 0 in model plots for empty buckets for count and sum functions. The count and sum functions treat empty buckets as 0 rather than unknown for anomaly detection, so it was inconsistent not to do the same for model plots. This inconsistency resulted in problems plotting these buckets in {kib}. Mapping:: * Ignore null value for range field (#27845) {pull}28116[#28116] (issue: {issue}27845[#27845]) * Pass `java.locale.providers=COMPAT` to Java 9 onwards {pull}28080[#28080] (issue: {issue}10984[#10984]) * Allow update of `eager_global_ordinals` on `_parent`. {pull}28014[#28014] (issue: {issue}24407[#24407]) * Fix merging of _meta field {pull}27352[#27352] (issue: {issue}27323[#27323]) Network:: * Only bind loopback addresses when binding to local {pull}28029[#28029] (issue: {issue}1877[#1877]) * Remove potential nio selector leak {pull}27825[#27825] * Fix issue where the incorrect buffers are written {pull}27695[#27695] (issue: {issue}27551[#27551]) * Throw UOE from compressible bytes stream reset {pull}27564[#27564] (issue: {issue}24927[#24927]) * Bubble exceptions when closing compressible streams {pull}27542[#27542] (issue: {issue}27540[#27540]) Packaging:: * Allow custom service names when installing on windows {pull}25255[#25255] (issue: {issue}25231[#25231]) Percolator:: * Avoid TooManyClauses exception if number of terms / ranges is exactly equal to 1024 {pull}27519[#27519] (issue: {issue}1[#1]) Plugin Analysis ICU:: * Catch InvalidPathException in IcuCollationTokenFilterFactory {pull}27202[#27202] Plugin Analysis Phonetic:: * Fix daitch_mokotoff phonetic filter to use the dedicated Lucene filter {pull}28225[#28225] (issue: {issue}28211[#28211]) Plugin Lang Painless:: * Painless: Fix variable scoping issue in lambdas {pull}27571[#27571] (issue: {issue}26760[#26760]) * Painless: Fix errors allowing void to be assigned to def. {pull}27460[#27460] (issue: {issue}27210[#27210]) Plugin Repository HDFS:: * Fix SecurityException when HDFS Repository used against HA Namenodes {pull}27196[#27196] Plugins:: * Make sure that we don't detect files as maven coordinate when installing a plugin {pull}28163[#28163] * Fix upgrading indices which use a custom similarity plugin. {pull}26985[#26985] (issue: {issue}25350[#25350]) Recovery:: * Open engine should keep only starting commit {pull}28228[#28228] (issues: {issue}27804[#27804], {issue}28181[#28181]) * Allow shrinking of indices from a previous major {pull}28076[#28076] (issue: {issue}28061[#28061]) * Set global checkpoint before open engine from store {pull}27972[#27972] (issues: {issue}27965[#27965], {issue}27970[#27970]) * Check and repair index under the store metadata lock {pull}27768[#27768] (issues: {issue}24481[#24481], {issue}24787[#24787], {issue}27731[#27731]) * Flush old indices on primary promotion and relocation {pull}27580[#27580] (issue: {issue}27536[#27536]) Rollover:: * Make index rollover action atomic {pull}28039[#28039] (issue: {issue}26976[#26976]) Scripting:: * Ensure we protect Collections obtained from scripts from self-referencing {pull}28335[#28335] Scroll:: * Reject scroll query if size is 0 (#22552) {pull}27842[#27842] (issue: {issue}22552[#22552]) * Fix scroll query with a sort that is a prefix of the index sort {pull}27498[#27498] Search:: * Fix simple_query_string on invalid input {pull}28219[#28219] (issue: {issue}28204[#28204]) * Use the underlying connection version for CCS connections {pull}28093[#28093] * Fix synonym phrase query expansion for cross_fields parsing {pull}28045[#28045] * Carry forward weights, etc on rescore rewrite {pull}27981[#27981] (issue: {issue}27979[#27979]) * Fix routing with leading or trailing whitespace {pull}27712[#27712] (issue: {issue}27708[#27708]) Security:: * Updated the `setup-passwords` command to generate passwords with characters `A-Z`, `a-z`, and `0-9`, so that they are safe to use in shell scripts. For more information about this command, see <>. * Improved the error messages that occur if the `x-pack` directory is missing when you run <>. * Fixed the ordering of realms in a realm chain, which determines the order in which the realms are consulted. For more information, see {stack-ov}/realms.html[Realms]. Sequence IDs:: * Recovery from snapshot may leave seq# gaps {pull}27850[#27850] * No longer unidle shard during recovery {pull}27757[#27757] (issue: {issue}26591[#26591]) * Obey translog durability in global checkpoint sync {pull}27641[#27641] Settings:: * Settings: Introduce settings updater for a list of settings {pull}28338[#28338] (issue: {issue}28047[#28047]) * Fix setting notification for complex setting (affixMap settings) that could cause transient settings to be ignored {pull}28317[#28317] (issue: {issue}28316[#28316]) * Fix environment variable substitutions in list setting {pull}28106[#28106] (issue: {issue}27926[#27926]) * Allow index settings to be reset by wildcards {pull}27671[#27671] (issue: {issue}27537[#27537]) Snapshot/Restore:: * Consistent updates of IndexShardSnapshotStatus {pull}28130[#28130] (issue: {issue}26480[#26480]) * Avoid concurrent snapshot finalizations when deleting an INIT snapshot {pull}28078[#28078] (issues: {issue}27214[#27214], {issue}27931[#27931], {issue}27974[#27974]) * Do not start snapshots that are deleted during initialization {pull}27931[#27931] * Do not swallow exception in ChecksumBlobStoreFormat.writeAtomic() {pull}27597[#27597] * Consistent update of stage and failure message in IndexShardSnapshotStatus {pull}27557[#27557] (issue: {issue}26480[#26480]) * Fail restore when the shard allocations max retries count is reached {pull}27493[#27493] (issue: {issue}26865[#26865]) * Delete shard store files before restoring a snapshot {pull}27476[#27476] (issues: {issue}20220[#20220], {issue}26865[#26865]) Stats:: * Fixes DocStats to properly deal with shards that report -1 index size {pull}27863[#27863] * Include internal refreshes in refresh stats {pull}27615[#27615] Term Vectors:: * Fix term vectors generator with keyword and normalizer {pull}27608[#27608] (issue: {issue}27320[#27320]) Watcher:: * Replaced group settings with affix key settings where filters are needed. For more information, see https://github.com/elastic/elasticsearch/pull/28338. //[float] //=== Regressions //[float] //=== Known Issues [float] === Upgrades Core:: * Dependencies: Update joda time to 2.9.9 {pull}28261[#28261] * upgrade to lucene 7.2.1 {pull}28218[#28218] (issue: {issue}28044[#28044]) * Upgrade jna from 4.4.0-1 to 4.5.1 {pull}28183[#28183] (issue: {issue}28172[#28172]) Ingest:: * update ingest-attachment to use Tika 1.17 and newer deps {pull}27824[#27824] ",12154,True,2858.8208194256913,median "[[jdbc]] == JDBC Support Spring Integration provides channel adapters for receiving and sending messages by using database queries. Through those adapters, Spring Integration supports not only plain JDBC SQL queries but also stored procedure and stored function calls. You need to include this dependency into your project: ==== [source, xml, subs=""normal"", role=""primary""] .Maven ---- org.springframework.integration spring-integration-jdbc {project-version} ---- [source, groovy, subs=""normal"", role=""secondary""] .Gradle ---- compile ""org.springframework.integration:spring-integration-jdbc:{project-version}"" ---- ==== By default, the following JDBC components are available: * <> * <> * <> * <> * <> * <> The Spring Integration JDBC Module also provides a <>. [[jdbc-inbound-channel-adapter]] === Inbound Channel Adapter The main function of an inbound channel adapter is to execute a SQL `SELECT` query and turn the result set into a message. The message payload is the whole result set (expressed as a `List`), and the types of the items in the list depend on the row-mapping strategy. The default strategy is a generic mapper that returns a `Map` for each row in the query result. Optionally, you can change this by adding a reference to a `RowMapper` instance (see the https://docs.spring.io/spring/docs/current/spring-framework-reference/html/jdbc.html[Spring JDBC] documentation for more detailed information about row mapping). NOTE: If you want to convert rows in the `SELECT` query result to individual messages, you can use a downstream splitter. The inbound adapter also requires a reference to either a `JdbcTemplate` instance or a `DataSource`. As well as the `SELECT` statement to generate the messages, the adapter also has an `UPDATE` statement that marks the records as processed so that they do not show up in the next poll. The update can be parameterized by the list of IDs from the original select. By default, this is done through a naming convention (a column in the input result set called `id` is translated into a list in the parameter map for the update called `id`). The following example defines an inbound channel adapter with an update query and a `DataSource` reference. ==== [source,xml] ---- ---- ==== NOTE: The parameters in the update query are specified with a colon (`:`) prefix to the name of a parameter (which, in the preceding example, is an expression to be applied to each of the rows in the polled result set). This is a standard feature of the named parameter JDBC support in Spring JDBC, combined with a convention (projection onto the polled result list) adopted in Spring Integration. The underlying Spring JDBC features limit the available expressions (for example, most special characters other than a period are disallowed), but since the target is usually a list of objects (possibly a list of one) that are addressable by bean paths this is not unduly restrictive. To change the parameter generation strategy, you can inject a `SqlParameterSourceFactory` into the adapter to override the default behavior (the adapter has a `sql-parameter-source-factory` attribute). Spring Integration provides `ExpressionEvaluatingSqlParameterSourceFactory`, which creates a SpEL-based parameter source, with the results of the query as the `#root` object. (If `update-per-row` is true, the root object is the row). If the same parameter name appears multiple times in the update query, it is evaluated only once, and its result is cached. You can also use a parameter source for the select query. In this case, since there is no ""`result`"" object to evaluate against, a single parameter source is used each time (rather than using a parameter source factory). Starting with version 4.0, you can use Spring to create a SpEL based parameter source, as the following example shows: ==== [source,xml] ---- ---- ==== The `value` in each parameter expression can be any valid SpEL expression. The `#root` object for the expression evaluation is the constructor argument defined on the `parameterSource` bean. It is static for all evaluations (in the preceding example, an empty `String`). Starting with version 5.0, you ca supply `ExpressionEvaluatingSqlParameterSourceFactory` with `sqlParameterTypes` to specify the target SQL type for the particular parameter. The following example provides SQL types for the parameters being used in the query: ==== [source,xml] ---- ---- ==== IMPORTANT: Use the `createParameterSourceNoCache` factory method. Otherwise, the parameter source caches the result of the evaluation. Also note that, because caching is disabled, if the same parameter name appears in the select query multiple times, it is re-evaluated for each occurrence. [[jdbc-polling-transactions]] ==== Polling and Transactions The inbound adapter accepts a regular Spring Integration poller as a child element. Consequently, the frequency of the polling can be controlled (among other uses). An important feature of the poller for JDBC usage is the option to wrap the poll operation in a transaction, as the following example shows: ==== [source,xml] ---- ---- ==== NOTE: If you do not explicitly specify a poller, a default value is used. As is normal with Spring Integration, it can be defined as a top-level bean). In the preceding example, the database is polled every 1000 milliseconds (or once a second), and the update and select queries are both executed in the same transaction. The transaction manager configuration is not shown. However, as long as it is aware of the data source, the poll is transactional. A common use case is for the downstream channels to be direct channels (the default), so that the endpoints are invoked in the same thread and, hence, the same transaction. That way, if any of them fail, the transaction rolls back and the input data is reverted to its original state. [[jdbc-max-rows-versus-max-messages-per-poll]] ==== `max-rows` Versus `max-messages-per-poll` The JDBC inbound channel adapter defines an attribute called `max-rows`. When you specify the adapter's poller, you can also define a property called `max-messages-per-poll`. While these two attributes look similar, their meaning is quite different. `max-messages-per-poll` specifies the number of times the query is executed per polling interval, whereas `max-rows` specifies the number of rows returned for each execution. Under normal circumstances, you would likely not want to set the poller's `max-messages-per-poll` property when you use the JDBC inbound channel adapter. Its default value is `1`, which means that the JDBC inbound channel adapter's https://docs.spring.io/spring-integration/api/org/springframework/integration/jdbc/JdbcPollingChannelAdapter.html#receive()[`receive()`] method is executed exactly once for each poll interval. Setting the `max-messages-per-poll` attribute to a larger value means that the query is executed that many times back to back. For more information regarding the `max-messages-per-poll` attribute, see <<./channel-adapter.adoc#channel-adapter-namespace-inbound,Configuring An Inbound Channel Adapter>>. In contrast, the `max-rows` attribute, if greater than `0`, specifies the maximum number of rows to be used from the query result set created by the `receive()` method. If the attribute is set to `0`, all rows are included in the resulting message. The attribute defaults to `0`. NOTE: It is recommended to use result set limiting via vendor-specific query options, for example MySQL `LIMIT` or SQL Server `TOP` or Oracle's `ROWNUM`. See the particular vendor documentation for more information. [[jdbc-outbound-channel-adapter]] === Outbound Channel Adapter The outbound channel adapter is the inverse of the inbound: its role is to handle a message and use it to execute a SQL query. By default, the message payload and headers are available as input parameters to the query, as the following example shows: ==== [source,xml] ---- ---- ==== In the preceding example, messages arriving at the channel labelled `input` have a payload of a map with a key of `something`, so the `[]` operator dereferences that value from the map. The headers are also accessed as a map. NOTE: The parameters in the preceding query are bean property expressions on the incoming message (not SpEL expressions). This behavior is part of the `SqlParameterSource`, which is the default source created by the outbound adapter. You can inject a different `SqlParameterSourceFactory` to get different behavior. The outbound adapter requires a reference to either a `DataSource` or a `JdbcTemplate`. You can also inject a `SqlParameterSourceFactory` to control the binding of each incoming message to a query. If the input channel is a direct channel, the outbound adapter runs its query in the same thread and, therefore, the same transaction (if there is one) as the sender of the message. ==== Passing Parameters by Using SpEL Expressions A common requirement for most JDBC channel adapters is to pass parameters as part of SQL queries or stored procedures or functions. As mentioned earlier, these parameters are by default bean property expressions, not SpEL expressions. However, if you need to pass SpEL expression as parameters, you must explicitly inject a `SqlParameterSourceFactory`. The following example uses a `ExpressionEvaluatingSqlParameterSourceFactory` to achieve that requirement: ==== [source,xml] ---- ---- ==== For further information, see <>. ==== Using the `PreparedStatement` Callback Sometimes, the flexibility and loose-coupling of `SqlParameterSourceFactory` does not do what we need for the target `PreparedStatement` or we need to do some low-level JDBC work. The Spring JDBC module provides APIs to configure the execution environment (such as `ConnectionCallback` or `PreparedStatementCreator`) and manipulate parameter values (such as `SqlParameterSource`). It can even access APIs for low-level operations, such as `StatementCallback`. Starting with Spring Integration 4.2, `MessagePreparedStatementSetter` allows the specification of parameters on the `PreparedStatement` manually, in the `requestMessage` context. This class plays exactly the same role as `PreparedStatementSetter` in the standard Spring JDBC API. Actually, it is invoked directly from an inline `PreparedStatementSetter` implementation when the `JdbcMessageHandler` invokes `execute` on the `JdbcTemplate`. This functional interface option is mutually exclusive with `sqlParameterSourceFactory` and can be used as a more powerful alternative to populate parameters of the `PreparedStatement` from the `requestMessage`. For example, it is useful when we need to store `File` data to the DataBase `BLOB` column in a streaming manner. The following example shows how to do so: ==== [source,java] ---- @Bean @ServiceActivator(inputChannel = ""storeFileChannel"") public MessageHandler jdbcMessageHandler(DataSource dataSource) { JdbcMessageHandler jdbcMessageHandler = new JdbcMessageHandler(dataSource, ""INSERT INTO imagedb (image_name, content, description) VALUES (?, ?, ?)""); jdbcMessageHandler.setPreparedStatementSetter((ps, m) -> { ps.setString(1, m.getHeaders().get(FileHeaders.FILENAME)); try (FileInputStream inputStream = new FileInputStream((File) m.getPayload()); ) { ps.setBlob(2, inputStream); } catch (Exception e) { throw new MessageHandlingException(m, e); } ps.setClob(3, new StringReader(m.getHeaders().get(""description"", String.class))); }); return jdbcMessageHandler; } ---- ==== From the XML configuration perspective, the `prepared-statement-setter` attribute is available on the `` component. It lets you specify a `MessagePreparedStatementSetter` bean reference. ==== Batch Update Starting with version 5.1, the `JdbcMessageHandler` performs a `JdbcOperations.batchUpdate()` if the payload of the request message is an `Iterable` instance. Each element of the `Iterable` is wrapped to a `Message` with the headers from the request message. In the case of regular `SqlParameterSourceFactory`-based configuration these messages are used to build an `SqlParameterSource[]` for an argument used in the mentioned `JdbcOperations.batchUpdate()` function. When a `MessagePreparedStatementSetter` configuration is applied, a `BatchPreparedStatementSetter` variant is used to iterate over those messages for each item and the provided `MessagePreparedStatementSetter` is called against them. The batch update is not supported when `keysGenerated` mode is selected. [[jdbc-outbound-gateway]] === Outbound Gateway The outbound gateway is like a combination of the outbound and inbound adapters: Its role is to handle a message and use it to execute a SQL query and then respond with the result by sending it to a reply channel. By default, the message payload and headers are available as input parameters to the query, as the following example shows: ==== [source,xml] ---- ---- ==== The result of the preceding example is to insert a record into the `mythings` table and return a message that indicates the number of rows affected (the payload is a map: `{UPDATED=1}`) to the output channel . If the update query is an insert with auto-generated keys, you can populate the reply message with the generated keys by adding `keys-generated=""true""` to the preceding example (this is not the default because it is not supported by some database platforms). The following example shows the changed configuration: ==== [source,xml] ---- ---- ==== Instead of the update count or the generated keys, you can also provide a select query to execute and generate a reply message from the result (such as the inbound adapter), as the following example shows: ==== [source,xml] ---- ---- ==== Since Spring Integration 2.2, the update SQL query is no longer mandatory. You can now provide only a select query, by using either the `query` attribute or the `query` element. This is extremely useful if you need to actively retrieve data by using, for example, a generic gateway or a payload enricher. The reply message is then generated from the result (similar to how the inbound adapter works) and passed to the reply channel. The following example show to use the `query` attribute: ==== [source,xml] ---- ---- ==== [IMPORTANT] ==== By default, the component for the `SELECT` query returns only one (the first) row from the cursor. You can adjust this behavior with the `max-rows` option. If you need to return all the rows from the SELECT, consider specifying `max-rows=""0""`. ==== As with the channel adapters, you can also provide `SqlParameterSourceFactory` instances for request and reply. The default is the same as for the outbound adapter, so the request message is available as the root of an expression. If `keys-generated=""true""`, the root of the expression is the generated keys (a map if there is only one or a list of maps if multi-valued). The outbound gateway requires a reference to either a `DataSource` or a `JdbcTemplate`. It can also have a `SqlParameterSourceFactory` injected to control the binding of the incoming message to the query. Starting with the version 4.2, the `request-prepared-statement-setter` attribute is available on the `` as an alternative to `request-sql-parameter-source-factory`. It lets you specify a `MessagePreparedStatementSetter` bean reference, which implements more sophisticated `PreparedStatement` preparation before its execution. See <> for more information about `MessagePreparedStatementSetter`. [[jdbc-message-store]] === JDBC Message Store Spring Integration provides two JDBC specific message store implementations. The `JdbcMessageStore` is suitable for use with aggregators and the claim check pattern. The `JdbcChannelMessageStore` implementation provides a more targeted and scalable implementation specifically for message channel. Note that you can use a `JdbcMessageStore` to back a message channel, `JdbcChannelMessageStore` is optimized for that purpose. IMPORTANT: Starting with versions 5.0.11, 5.1.2, the indexes for the `JdbcChannelMessageStore` have been optimized. If you have large message groups in such a store, you may wish to alter the indexes. Furthermore, the index for `PriorityChannel` is commented out because it is not needed unless you are using such channels backed by JDBC. NOTE: When using the `OracleChannelMessageStoreQueryProvider`, the priority channel index **must** be added because it is included in a hint in the query. ==== Initializing the Database Before starting to use JDBC message store components, you should provision a target database with the appropriate objects. Spring Integration ships with some sample scripts that can be used to initialize a database. In the `spring-integration-jdbc` JAR file, you can find scripts in the `org.springframework.integration.jdbc` package. It provides an example create and an example drop script for a range of common database platforms. A common way to use these scripts is to reference them in a https://docs.spring.io/spring/docs/current/spring-framework-reference/html/jdbc.html#jdbc-intializing-datasource[Spring JDBC data source initializer]. Note that the scripts are provided as samples and as specifications of the required table and column names. You may find that you need to enhance them for production use (for, example, by adding index declarations). [[jdbc-message-store-generic]] ==== The Generic JDBC Message Store The JDBC module provides an implementation of the Spring Integration `MessageStore` (important in the claim check pattern) and `MessageGroupStore` (important in stateful patterns such as an aggregator) backed by a database. Both interfaces are implemented by the `JdbcMessageStore`, and there is support for configuring store instances in XML, as the following example shows: ==== [source,xml] ---- ---- ==== You can specify a `JdbcTemplate` instead of a `DataSource`. The following example shows some other optional attributes: ==== [source,xml] ---- ---- ==== In the preceding example, we have specified a `LobHandler` for dealing with messages as large objects (which is often necessary for Oracle) and a prefix for the table names in the queries generated by the store. The table name prefix defaults to `INT_`. [[jdbc-message-store-channels]] ==== Backing Message Channels If you intend to back message channels with JDBC, we recommend using the `JdbcChannelMessageStore` implementation. It works only in conjunction with Message Channels. ===== Supported Databases The `JdbcChannelMessageStore` uses database-specific SQL queries to retrieve messages from the database. Therefore, you must set the `ChannelMessageStoreQueryProvider` property on the `JdbcChannelMessageStore`. This `channelMessageStoreQueryProvider` provides the SQL queries for the particular database you specify. Spring Integration provides support for the following relational databases: * PostgreSQL * HSQLDB * MySQL * Oracle * Derby * H2 * SqlServer * Sybase * DB2 If your database is not listed, you can extend the `AbstractChannelMessageStoreQueryProvider` class and provide your own custom queries. Version 4.0 added the `MESSAGE_SEQUENCE` column to the table to ensure first-in-first-out (FIFO) queueing even when messages are stored in the same millisecond. ===== Custom Message Insertion Since version 5.0, by overloading the `ChannelMessageStorePreparedStatementSetter` class, you can provide a custom implementation for message insertion in the `JdbcChannelMessageStore`. You can use it to set different columns or change the table structure or serialization strategy. For example, instead of default serialization to `byte[]`, you can store its structure as a JSON string. The following example uses the default implementation of `setValues` to store common columns and overrides the behavior to store the message payload as a `varchar`: ==== [source,java] ---- public class JsonPreparedStatementSetter extends ChannelMessageStorePreparedStatementSetter { @Override public void setValues(PreparedStatement preparedStatement, Message requestMessage, Object groupId, String region, boolean priorityEnabled) throws SQLException { // Populate common columns super.setValues(preparedStatement, requestMessage, groupId, region, priorityEnabled); // Store message payload as varchar preparedStatement.setString(6, requestMessage.getPayload().toString()); } } ---- ==== [IMPORTANT] ==== Generally, we do not recommend using a relational database for queuing. Instead, if possible, consider using either JMS- or AMQP-backed channels instead. For further reference, see the following resource: * https://mikehadlow.blogspot.com/2012/04/database-as-queue-anti-pattern.html[The Database As Queue Anti-Pattern]. ==== ===== Concurrent Polling When polling a message channel, you have the option to configure the associated `Poller` with a `TaskExecutor` reference. [IMPORTANT] ==== Keep in mind, though, that if you use a JDBC backed message channel and you plan to poll the channel and consequently the message store transactionally with multiple threads, you should ensure that you use a relational database that supports https://en.wikipedia.org/wiki/Multiversion_concurrency_control[Multiversion Concurrency Control] (MVCC). Otherwise, locking may be an issue and the performance, when using multiple threads, may not materialize as expected. For example, Apache Derby is problematic in that regard. To achieve better JDBC queue throughput and avoid issues when different threads may poll the same `Message` from the queue, it is *important* to set the `usingIdCache` property of `JdbcChannelMessageStore` to `true` when using databases that do not support MVCC. The following example shows how to do so: [source,xml] ---- ---- ==== ===== Priority Channel Starting with version 4.0, `JdbcChannelMessageStore` implements `PriorityCapableChannelMessageStore` and provides the `priorityEnabled` option, letting it be used as a `message-store` reference for `priority-queue` instances. For this purpose, the `INT_CHANNEL_MESSAGE` table has a `MESSAGE_PRIORITY` column to store the value of `PRIORITY` message headers. In addition, a new `MESSAGE_SEQUENCE` column lets us achieve a robust first-in-first-out (FIFO) polling mechanism, even when multiple messages are stored with the same priority in the same millisecond. Messages are polled (selected) from the database with `order by MESSAGE_PRIORITY DESC NULLS LAST, CREATED_DATE, MESSAGE_SEQUENCE`. NOTE: We do not recommend using the same `JdbcChannelMessageStore` bean for priority and non-priority queue channels, because the `priorityEnabled` option applies to the entire store and proper FIFO queue semantics are not retained for the queue channel. However, the same `INT_CHANNEL_MESSAGE` table (and even `region`) can be used for both `JdbcChannelMessageStore` types. To configure that scenario, you can extend one message store bean from the other, as the following example shows: ==== [source,xml] ---- ---- ==== ==== Partitioning a Message Store It is common to use a `JdbcMessageStore` as a global store for a group of applications or nodes in the same application. To provide some protection against name clashes and to give control over the database meta-data configuration, the message store lets the tables be partitioned in two ways. One way is to use separate table names, by changing the prefix (as <>). The other way is to specify a `region` name for partitioning data within a single table. An important use case for the second approach is when the `MessageStore` is managing persistent queues that back a Spring Integration Message Channel. The message data for a persistent channel is keyed in the store on the channel name. Consequently, if the channel names are not globally unique, the channels can pick up data that is not intended for them. To avoid this danger, you can use the message store `region` to keep data separate for different physical channels that have the same logical name. [[stored-procedures]] === Stored Procedures In certain situations, plain JDBC support is not sufficient. Maybe you deal with legacy relational database schemas or you have complex data processing needs, but, ultimately, you have to use https://en.wikipedia.org/wiki/Stored_procedure[stored procedures] or stored functions. Since Spring Integration 2.1, we provide three components to execute stored procedures or stored functions: * Stored Procedures Inbound Channel Adapter * Stored Procedures Outbound Channel Adapter * Stored Procedures Outbound Gateway [[sp-supported-databases]] ==== Supported Databases In order to enable calls to stored procedures and stored functions, the stored procedure components use the https://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/jdbc/core/simple/SimpleJdbcCall.html[`org.springframework.jdbc.core.simple.SimpleJdbcCall`] class. Consequently, the following databases are fully supported for executing stored procedures: * Apache Derby * DB2 * MySQL * Microsoft SQL Server * Oracle * PostgreSQL * Sybase If you want to execute stored functions instead, the following databases are fully supported: * MySQL * Microsoft SQL Server * Oracle * PostgreSQL [NOTE] ===== Even though your particular database may not be fully supported, chances are that you can use the stored procedure Spring Integration components quite successfully anyway, provided your RDBMS supports stored procedures or stored functions. As a matter of fact, some provided integration tests use the https://www.h2database.com/[H2 database]. Nevertheless, it is very important to thoroughly test those usage scenarios. ===== [[sp-configuration]] ==== Configuration The stored procedure components provide full XML Namespace support, and configuring the components is similar as for the general purpose JDBC components discussed earlier. [[sp-common-config-params]] ==== Common Configuration Attributes All stored procedure components share certain configuration parameters: * `auto-startup`: Lifecycle attribute signaling whether this component should be started during application context startup. It defaults to `true`. Optional. * `data-source`: Reference to a `javax.sql.DataSource`, which is used to access the database. Required. * `id`: Identifies the underlying Spring bean definition, which is an instance of either `EventDrivenConsumer` or `PollingConsumer`, depending on whether the outbound channel adapter's `channel` attribute references a `SubscribableChannel` or a `PollableChannel`. Optional. * `ignore-column-meta-data`: For fully supported databases, the underlying https://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/jdbc/core/simple/SimpleJdbcCall.html[`SimpleJdbcCall`] class can automatically retrieve the parameter information for the stored procedure or stored function from the JDBC metadata. + However, if the database does not support metadata lookups or if you need to provide customized parameter definitions, this flag can be set to `true`. It defaults to `false`. Optional. * `is-function`: If `true`, a SQL Function is called. In that case, the `stored-procedure-name` or `stored-procedure-name-expression` attributes define the name of the called function. It defaults to `false`. Optional. * `stored-procedure-name`: This attribute specifies the name of the stored procedure. If the `is-function` attribute is set to `true`, this attribute specifies the function name instead. Either this property or `stored-procedure-name-expression` must be specified. * `stored-procedure-name-expression`: This attribute specifies the name of the stored procedure by using a SpEL expression. By using SpEL, you have access to the full message (if available), including its headers and payload. You can use this attribute to invoke different stored procedures at runtime. For example, you can provide stored procedure names that you would like to execute as a message header. The expression must resolve to a `String`. + If the `is-function` attribute is set to `true`, this attribute specifies a stored function. Either this property or `stored-procedure-name` must be specified. * `jdbc-call-operations-cache-size`: Defines the maximum number of cached `SimpleJdbcCallOperations` instances. Basically, for each stored procedure name, a new https://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/jdbc/core/simple/SimpleJdbcCallOperations.html[`SimpleJdbcCallOperations`] instance is created that, in return, is cached. + NOTE: Spring Integration 2.2 added the `stored-procedure-name-expression` attribute and the `jdbc-call-operations-cache-size` attribute. + The default cache size is `10`. A value of `0` disables caching. Negative values are not permitted. + If you enable JMX, statistical information about the `jdbc-call-operations-cache` is exposed as an MBean. See <<./jmx.adoc#jmx-mbean-exporter,MBean Exporter>> for more information. * `sql-parameter-source-factory`: (Not available for the stored procedure inbound channel adapter.) Reference to a `SqlParameterSourceFactory`. By default, bean properties of the passed in `Message` payload are used as a source for the stored procedure's input parameters by using a `BeanPropertySqlParameterSourceFactory`. + This may suffice for basic use cases. For more sophisticated options, consider passing in one or more `ProcedureParameter` values. See <>. Optional. * `use-payload-as-parameter-source`: (Not available for the stored procedure inbound channel adapter.) If set to `true`, the payload of the `Message` is used as a source for providing parameters. If set to `false`, however, the entire `Message` is available as a source for parameters. + If no procedure parameters are passed in, this property defaults to `true`. This means that, by using a default `BeanPropertySqlParameterSourceFactory`, the bean properties of the payload are used as a source for parameter values for the stored procedure or stored function. + However, if procedure parameters are passed in, this property (by default) evaluates to `false`. `ProcedureParameter` lets SpEL Expressions be provided. Therefore, it is highly beneficial to have access to the entire `Message`. The property is set on the underlying `StoredProcExecutor`. Optional. [[sp-common-config-subelements]] ==== Common Configuration Sub-Elements The stored procedure components share a common set of child elements that you can use to define and pass parameters to stored procedures or stored functions. The following elements are available: * `parameter` * `returning-resultset` * `sql-parameter-definition` * `poller` * `parameter`: Provides a mechanism to provide stored procedure parameters. Parameters can be either static or provided by using a SpEL Expressions. + ==== [source,xml] ---- type="""" <2> value=""""/> <3> <4> ---- + <1> The name of the parameter to be passed into the Stored Procedure or Stored Function. Required. <2> This attribute specifies the type of the value. If nothing is provided, this attribute defaults to `java.lang.String`. This attribute is used only when the `value` attribute is used. Optional. <3> The value of the parameter. You must provide either this attribute or the `expression` attribute. Optional. <4> Instead of the `value` attribute, you can specify a SpEL expression for passing the value of the parameter. If you specify the `expression`, the `value` attribute is not allowed. Optional. ==== Optional. + * `returning-resultset`: Stored procedures may return multiple result sets. By setting one or more `returning-resultset` elements, you can specify `RowMappers` to convert each returned `ResultSet` to meaningful objects. Optional. + ==== [source,xml] ---- ---- ==== * `sql-parameter-definition`: If you use a database that is fully supported, you typically do not have to specify the stored procedure parameter definitions. Instead, those parameters can be automatically derived from the JDBC metadata. However, if you use databases that are not fully supported, you must set those parameters explicitly by using the `sql-parameter-definition` element. + You can also choose to turn off any processing of parameter metadata information obtained through JDBC by using the `ignore-column-meta-data` attribute. + ==== [source,xml] ---- direction=""IN"" <2> type=""STRING"" <3> scale=""5"" <4> type-name=""FOO_STRUCT"" <5> return-type=""fooSqlReturnType""/> <6> ---- <1> Specifies the name of the SQL parameter. Required. <2> Specifies the direction of the SQL parameter definition. Defaults to `IN`. Valid values are: `IN`, `OUT`, and `INOUT`. If your procedure is returning result sets, use the `returning-resultset` element. Optional. <3> The SQL type used for this SQL parameter definition. Translates into an integer value, as defined by `java.sql.Types`. Alternatively, you can provide the integer value as well. If this attribute is not explicitly set, it defaults to 'VARCHAR'. Optional. <4> The scale of the SQL parameter. Only used for numeric and decimal parameters. Optional. <5> The `typeName` for types that are user-named, such as: `STRUCT`, `DISTINCT`, `JAVA_OBJECT`, and named array types. This attribute is mutually exclusive with the `scale` attribute. Optional. <6> The reference to a custom value handler for complex types. An implementation of https://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/jdbc/core/SqlReturnType.html[`SqlReturnType`]. This attribute is mutually exclusive with the `scale` attribute and is only applicable for OUT and INOUT parameters. Optional. ==== * `poller`: Lets you configure a message poller if this endpoint is a `PollingConsumer`. Optional. [[sp-defining-parameter-sources]] ==== Defining Parameter Sources Parameter sources govern the techniques of retrieving and mapping the Spring Integration message properties to the relevant stored procedure input parameters. The stored procedure components follow certain rules. By default, the bean properties of the `Message` payload are used as a source for the stored procedure's input parameters. In that case, a `BeanPropertySqlParameterSourceFactory` is used. This may suffice for basic use cases. The next example illustrates that default behavior. IMPORTANT: For the ""`automatic`"" lookup of bean properties by using the `BeanPropertySqlParameterSourceFactory` to work, your bean properties must be defined in lower case. This is due to the fact that in `org.springframework.jdbc.core.metadata.CallMetaDataContext` (the Java method is `matchInParameterValuesWithCallParameters()`), the retrieved stored procedure parameter declarations are converted to lower case. As a result, if you have camel-case bean properties (such as `lastName`), the lookup fails. In that case, provide an explicit `ProcedureParameter`. Suppose we have a payload that consists of a simple bean with the following three properties: `id`, `name`, and `description`. Furthermore, we have a simplistic Stored Procedure called `INSERT_COFFEE` that accepts three input parameters: `id`, `name`, and `description`. We also use a fully supported database. In that case, the following configuration for a stored procedure outbound adapter suffices: ==== [source,xml] ---- ---- ==== For more sophisticated options, consider passing in one or more `ProcedureParameter` values. If you do provide `ProcedureParameter` values explicitly, by default, an `ExpressionEvaluatingSqlParameterSourceFactory` is used for parameter processing, to enable the full power of SpEL expressions. If you need even more control over how parameters are retrieved, consider passing in a custom implementation of `SqlParameterSourceFactory` by using the `sql-parameter-source-factory` attribute. [[stored-procedure-inbound-channel-adapter]] ==== Stored Procedure Inbound Channel Adapter The following listing calls out the attributes that matter for a stored procedure inbound channel adapter: ==== [source,xml] ---- stored-procedure-name="""" data-source="""" auto-startup=""true"" id="""" ignore-column-meta-data=""false"" is-function=""false"" skip-undeclared-results="""" <2> return-value-required=""false"" <3> ---- <1> Channel to which polled messages are sent. If the stored procedure or function does not return any data, the payload of the `Message` is null. Required. <2> If this attribute is set to `true`, all results from a stored procedure call that do not have a corresponding `SqlOutParameter` declaration are bypassed. For example, stored procedures can return an update count value, even though your stored procedure declared only a single result parameter. The exact behavior depends on the database implementation. The value is set on the underlying `JdbcTemplate`. The value defaults to `true`. Optional. <3> Indicates whether this procedure's return value should be included. Since Spring Integration 3.0. Optional. ==== [[stored-procedure-outbound-channel-adapter]] ==== Stored Procedure Outbound Channel Adapter The following listing calls out the attributes that matter for a stored procedure outbound channel adapter: ==== [source,xml] ---- stored-procedure-name="""" data-source="""" auto-startup=""true"" id="""" ignore-column-meta-data=""false"" order="""" <2> sql-parameter-source-factory="""" use-payload-as-parameter-source=""""> ---- <1> The receiving message channel of this endpoint. Required. <2> Specifies the order for invocation when this endpoint is connected as a subscriber to a channel. This is particularly relevant when that channel is using a `failover` dispatching strategy. It has no effect when this endpoint is itself a polling consumer for a channel with a queue. Optional. ==== [[stored-procedure-outbound-gateway]] ==== Stored Procedure Outbound Gateway The following listing calls out the attributes that matter for a stored procedure outbound channel adapter: ==== [source,xml] ---- stored-procedure-name="""" data-source="""" auto-startup=""true"" id="""" ignore-column-meta-data=""false"" is-function=""false"" order="""" reply-channel="""" <2> reply-timeout="""" <3> return-value-required=""false"" <4> skip-undeclared-results="""" <5> sql-parameter-source-factory="""" use-payload-as-parameter-source=""""> ---- <1> The receiving message channel of this endpoint. Required. <2> Message channel to which replies should be sent after receiving the database response. Optional. <3> Lets you specify how long this gateway waits for the reply message to be sent successfully before throwing an exception. Keep in mind that, when sending to a `DirectChannel`, the invocation occurs in the sender's thread. Consequently, the failing of the send operation may be caused by other components further downstream. By default, the gateway waits indefinitely. The value is specified in milliseconds. Optional. <4> Indicates whether this procedure's return value should be included. Optional. <5> If the `skip-undeclared-results` attribute is set to `true`, all results from a stored procedure call that do not have a corresponding `SqlOutParameter` declaration are bypassed. For example, stored procedures may return an update count value, even though your stored procedure only declared a single result parameter. The exact behavior depends on the database. The value is set on the underlying `JdbcTemplate`. The value defaults to `true`. Optional. ==== [[sp-examples]] ==== Examples This section contains two examples that call https://db.apache.org/derby/[Apache Derby] stored procedures. The first procedure calls a stored procedure that returns a `ResultSet`. By using a `RowMapper`, the data is converted into a domain object, which then becomes the Spring Integration message payload. In the second sample, we call a stored procedure that uses output parameters to return data instead. [NOTE] ===== Have a look at the https://github.com/spring-projects/spring-integration-samples[Spring Integration Samples project]. The project contains the Apache Derby example referenced here, as well as instructions on how to run it. The Spring Integration Samples project also provides an https://github.com/spring-projects/spring-integration-samples/tree/main/intermediate/stored-procedures-oracle[example] of using Oracle stored procedures. ===== In the first example, we call a stored procedure named `FIND_ALL_COFFEE_BEVERAGES` that does not define any input parameters but that returns a `ResultSet`. In Apache Derby, stored procedures are implemented in Java. The following listing shows the method signature: ==== [source,java] ---- public static void findAllCoffeeBeverages(ResultSet[] coffeeBeverages) throws SQLException { ... } ---- ==== The following listing shows the corresponding SQL: ==== [source,sql] ---- CREATE PROCEDURE FIND_ALL_COFFEE_BEVERAGES() \\ PARAMETER STYLE JAVA LANGUAGE JAVA MODIFIES SQL DATA DYNAMIC RESULT SETS 1 \\ EXTERNAL NAME 'o.s.i.jdbc.storedproc.derby.DerbyStoredProcedures.findAllCoffeeBeverages'; ---- ==== In Spring Integration, you can now call this stored procedure by using, for example, a `stored-proc-outbound-gateway`, as the following example shows: ==== [source,xml] ---- ---- ==== In the second example, we call a stored procedure named `FIND_COFFEE` that has one input parameter. Instead of returning a `ResultSet`, it uses an output parameter. The following example shows the method signature: ==== [source,java] ---- public static void findCoffee(int coffeeId, String[] coffeeDescription) throws SQLException { ... } ---- ==== The following listing shows the corresponding SQL: ==== [source,sql] ---- CREATE PROCEDURE FIND_COFFEE(IN ID INTEGER, OUT COFFEE_DESCRIPTION VARCHAR(200)) \\ PARAMETER STYLE JAVA LANGUAGE JAVA EXTERNAL NAME \\ 'org.springframework.integration.jdbc.storedproc.derby.DerbyStoredProcedures.findCoffee'; ---- ==== In Spring Integration, you can now call this Stored Procedure by using, for example, a `stored-proc-outbound-gateway`, as the following example shows: ==== [source,xml] ---- ---- ==== [[jdbc-lock-registry]] === JDBC Lock Registry Version 4.3 introduced the `JdbcLockRegistry`. Certain components (for example, aggregator and resequencer) use a lock obtained from a `LockRegistry` instance to ensure that only one thread manipulates a group at a time. The `DefaultLockRegistry` performs this function within a single component. You can now configure an external lock registry on these components. When used with a shared `MessageGroupStore`, you can use the `JdbcLockRegistry` to provide this functionality across multiple application instances, such that only one instance can manipulate the group at a time. When a lock is released by a local thread, another local thread can generally acquire the lock immediately. If a lock is released by a thread that uses a different registry instance, it can take up to 100ms to acquire the lock. The `JdbcLockRegistry` is based on the `LockRepository` abstraction, which has a `DefaultLockRepository` implementation. The database schema scripts are located in the `org.springframework.integration.jdbc` package, which is divided for the particular RDBMS vendors. For example, the following listing shows the H2 DDL for the lock table: ==== [source,sql] ---- CREATE TABLE INT_LOCK ( LOCK_KEY CHAR(36), REGION VARCHAR(100), CLIENT_ID CHAR(36), CREATED_DATE TIMESTAMP NOT NULL, constraint INT_LOCK_PK primary key (LOCK_KEY, REGION) ); ---- ==== The `INT_` can be changed according to the target database design requirements. Therefore, you must use `prefix` property on the `DefaultLockRepository` bean definition. Sometimes, one application has moved to such a state that it cannot release the distributed lock and remove the particular record in the database. For this purpose, such dead-locks can be expired by the other application on the next locking invocation. The `timeToLive` (TTL) option on the `DefaultLockRepository` is provided for this purpose. You may also want to specify `CLIENT_ID` for the locks stored for a given `DefaultLockRepository` instance. If so, you can specify the `id` to be associated with the `DefaultLockRepository` as a constructor parameter. Starting with version 5.1.8, the `JdbcLockRegistry` can be configured with the `idleBetweenTries` - a `Duration` to sleep between lock record insert/update executions. By default, it is `100` milliseconds and in some environments non-leaders pollute connections with data source too often. Starting with version 5.4, the `RenewableLockRegistry` interface has been introduced and added to `JdbcLockRegistry`. The `renewLock()` method must be called during locked process in case of the locked process would be longer than time to live of the lock. So the time to live can be highly reduce and deployments can retake a lost lock quickly. NOTE: The lock renewal can be done only if the lock is held by the current thread. String with version 5.5.6, the `JdbcLockRegistry` is support automatically clean up cache for JdbcLock in `JdbcLockRegistry.locks` via `JdbcLockRegistry.setCacheCapacity()`. See its JavaDocs for more information. String with version 6.0, the `DefaultLockRepository` can be supplied with a `PlatformTransactionManager` instead of relying on the primary bean from the application context. [[jdbc-metadata-store]] === JDBC Metadata Store Version 5.0 introduced the JDBC `MetadataStore` (see <<./meta-data-store.adoc#metadata-store,Metadata Store>>) implementation. You can use the `JdbcMetadataStore` to maintain the metadata state across application restarts. This `MetadataStore` implementation can be used with adapters such as the following: * <<./feed.adoc#feed-inbound-channel-adapter,Feed inbound channel adapters>> * <<./file.adoc#file-reading,File inbound channel adapters>> * <<./ftp.adoc#ftp-inbound,FTP inbound channel adapters>> * <<./sftp.adoc#sftp-inbound,SFTP inbound channel adapters>> To configure these adapters to use the `JdbcMetadataStore`, declare a Spring bean by using a bean name of `metadataStore`. The Feed inbound channel adapter and the feed inbound channel adapter both automatically pick up and use the declared `JdbcMetadataStore`, as the following example shows: ==== [source,java] ---- @Bean public MetadataStore metadataStore(DataSource dataSource) { return new JdbcMetadataStore(dataSource); } ---- ==== The `org.springframework.integration.jdbc` package has Database schema scripts for several RDMBS vendors. For example, the following listing shows the H2 DDL for the metadata table: ==== [source,sql] ---- CREATE TABLE INT_METADATA_STORE ( METADATA_KEY VARCHAR(255) NOT NULL, METADATA_VALUE VARCHAR(4000), REGION VARCHAR(100) NOT NULL, constraint INT_METADATA_STORE_PK primary key (METADATA_KEY, REGION) ); ---- ==== You can change the `INT_` prefix to match the target database design requirements. You can also configure `JdbcMetadataStore` to use the custom prefix. The `JdbcMetadataStore` implements `ConcurrentMetadataStore`, letting it be reliably shared across multiple application instances, where only one instance can store or modify a key's value. All of these operations are atomic, thanks to transaction guarantees. Transaction management must use `JdbcMetadataStore`. Inbound channel adapters can be supplied with a reference to the `TransactionManager` in the poller configuration. Unlike non-transactional `MetadataStore` implementations, with `JdbcMetadataStore`, the entry appears in the target table only after the transaction commits. When a rollback occurs, no entries are added to the `INT_METADATA_STORE` table. Since version 5.0.7, you can configure the `JdbcMetadataStore` with the RDBMS vendor-specific `lockHint` option for lock-based queries on metadata store entries. By default, it is `FOR UPDATE` and can be configured with an empty string if the target database does not support row locking functionality. Consult with your vendor for particular and possible hints in the `SELECT` expression for locking rows before updates. ",12059,False,2157.9301638652946,median "//-------------------------------------------------------------------------------------- // File: DDSTextureLoader.cpp // // Functions for loading a DDS texture and creating a Direct3D runtime resource for it // // Note these functions are useful as a light-weight runtime loader for DDS files. For // a full-featured DDS file reader, writer, and texture processing pipeline see // the 'Texconv' sample and the 'DirectXTex' library. // // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. // // http://go.microsoft.com/fwlink/?LinkId=248926 // http://go.microsoft.com/fwlink/?LinkId=248929 //-------------------------------------------------------------------------------------- #include ""DDSTextureLoader.h"" #include #include #include #if !defined(NO_D3D11_DEBUG_NAME) && ( defined(_DEBUG) || defined(PROFILE) ) #pragma comment(lib,""dxguid.lib"") #endif using namespace DirectX; //-------------------------------------------------------------------------------------- // Macros //-------------------------------------------------------------------------------------- #ifndef MAKEFOURCC #define MAKEFOURCC(ch0, ch1, ch2, ch3) \\ ((uint32_t)(uint8_t)(ch0) | ((uint32_t)(uint8_t)(ch1) << 8) | \\ ((uint32_t)(uint8_t)(ch2) << 16) | ((uint32_t)(uint8_t)(ch3) << 24 )) #endif /* defined(MAKEFOURCC) */ //-------------------------------------------------------------------------------------- // DDS file structure definitions // // See DDS.h in the 'Texconv' sample and the 'DirectXTex' library //-------------------------------------------------------------------------------------- #pragma pack(push,1) const uint32_t DDS_MAGIC = 0x20534444; // ""DDS "" struct DDS_PIXELFORMAT { uint32_t size; uint32_t flags; uint32_t fourCC; uint32_t RGBBitCount; uint32_t RBitMask; uint32_t GBitMask; uint32_t BBitMask; uint32_t ABitMask; }; #define DDS_FOURCC 0x00000004 // DDPF_FOURCC #define DDS_RGB 0x00000040 // DDPF_RGB #define DDS_LUMINANCE 0x00020000 // DDPF_LUMINANCE #define DDS_ALPHA 0x00000002 // DDPF_ALPHA #define DDS_BUMPDUDV 0x00080000 // DDPF_BUMPDUDV #define DDS_HEADER_FLAGS_VOLUME 0x00800000 // DDSD_DEPTH #define DDS_HEIGHT 0x00000002 // DDSD_HEIGHT #define DDS_WIDTH 0x00000004 // DDSD_WIDTH #define DDS_CUBEMAP_POSITIVEX 0x00000600 // DDSCAPS2_CUBEMAP | DDSCAPS2_CUBEMAP_POSITIVEX #define DDS_CUBEMAP_NEGATIVEX 0x00000a00 // DDSCAPS2_CUBEMAP | DDSCAPS2_CUBEMAP_NEGATIVEX #define DDS_CUBEMAP_POSITIVEY 0x00001200 // DDSCAPS2_CUBEMAP | DDSCAPS2_CUBEMAP_POSITIVEY #define DDS_CUBEMAP_NEGATIVEY 0x00002200 // DDSCAPS2_CUBEMAP | DDSCAPS2_CUBEMAP_NEGATIVEY #define DDS_CUBEMAP_POSITIVEZ 0x00004200 // DDSCAPS2_CUBEMAP | DDSCAPS2_CUBEMAP_POSITIVEZ #define DDS_CUBEMAP_NEGATIVEZ 0x00008200 // DDSCAPS2_CUBEMAP | DDSCAPS2_CUBEMAP_NEGATIVEZ #define DDS_CUBEMAP_ALLFACES ( DDS_CUBEMAP_POSITIVEX | DDS_CUBEMAP_NEGATIVEX |\\ DDS_CUBEMAP_POSITIVEY | DDS_CUBEMAP_NEGATIVEY |\\ DDS_CUBEMAP_POSITIVEZ | DDS_CUBEMAP_NEGATIVEZ ) #define DDS_CUBEMAP 0x00000200 // DDSCAPS2_CUBEMAP enum DDS_MISC_FLAGS2 { DDS_MISC_FLAGS2_ALPHA_MODE_MASK = 0x7L, }; struct DDS_HEADER { uint32_t size; uint32_t flags; uint32_t height; uint32_t width; uint32_t pitchOrLinearSize; uint32_t depth; // only if DDS_HEADER_FLAGS_VOLUME is set in flags uint32_t mipMapCount; uint32_t reserved1[11]; DDS_PIXELFORMAT ddspf; uint32_t caps; uint32_t caps2; uint32_t caps3; uint32_t caps4; uint32_t reserved2; }; struct DDS_HEADER_DXT10 { DXGI_FORMAT dxgiFormat; uint32_t resourceDimension; uint32_t miscFlag; // see D3D11_RESOURCE_MISC_FLAG uint32_t arraySize; uint32_t miscFlags2; }; #pragma pack(pop) //-------------------------------------------------------------------------------------- namespace { struct handle_closer { void operator()(HANDLE h) { if (h) CloseHandle(h); } }; typedef std::unique_ptr ScopedHandle; inline HANDLE safe_handle( HANDLE h ) { return (h == INVALID_HANDLE_VALUE) ? nullptr : h; } template inline void SetDebugObjectName(_In_ ID3D11DeviceChild* resource, _In_ const char (&name)[TNameLength]) { #if defined(_DEBUG) || defined(PROFILE) resource->SetPrivateData(WKPDID_D3DDebugObjectName, TNameLength - 1, name); #else UNREFERENCED_PARAMETER(resource); UNREFERENCED_PARAMETER(name); #endif } //-------------------------------------------------------------------------------------- HRESULT LoadTextureDataFromFile( _In_z_ const wchar_t* fileName, std::unique_ptr& ddsData, const DDS_HEADER** header, const uint8_t** bitData, size_t* bitSize) { if (!header || !bitData || !bitSize) { return E_POINTER; } // open the file #if (_WIN32_WINNT >= _WIN32_WINNT_WIN8) ScopedHandle hFile(safe_handle(CreateFile2(fileName, GENERIC_READ, FILE_SHARE_READ, OPEN_EXISTING, nullptr))); #else ScopedHandle hFile(safe_handle(CreateFileW(fileName, GENERIC_READ, FILE_SHARE_READ, nullptr, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, nullptr))); #endif if (!hFile) { return HRESULT_FROM_WIN32(GetLastError()); } // Get the file size FILE_STANDARD_INFO fileInfo; if (!GetFileInformationByHandleEx(hFile.get(), FileStandardInfo, &fileInfo, sizeof(fileInfo))) { return HRESULT_FROM_WIN32(GetLastError()); } // File is too big for 32-bit allocation, so reject read if (fileInfo.EndOfFile.HighPart > 0) { return E_FAIL; } // Need at least enough data to fill the header and magic number to be a valid DDS if (fileInfo.EndOfFile.LowPart < (sizeof(DDS_HEADER) + sizeof(uint32_t))) { return E_FAIL; } // create enough space for the file data ddsData.reset(new (std::nothrow) uint8_t[fileInfo.EndOfFile.LowPart]); if (!ddsData) { return E_OUTOFMEMORY; } // read the data in DWORD BytesRead = 0; if (!ReadFile(hFile.get(), ddsData.get(), fileInfo.EndOfFile.LowPart, &BytesRead, nullptr )) { return HRESULT_FROM_WIN32(GetLastError()); } if (BytesRead < fileInfo.EndOfFile.LowPart) { return E_FAIL; } // DDS files always start with the same magic number (""DDS "") uint32_t dwMagicNumber = *reinterpret_cast(ddsData.get()); if (dwMagicNumber != DDS_MAGIC) { return E_FAIL; } auto hdr = reinterpret_cast(ddsData.get() + sizeof(uint32_t)); // Verify header to validate DDS file if (hdr->size != sizeof(DDS_HEADER) || hdr->ddspf.size != sizeof(DDS_PIXELFORMAT)) { return E_FAIL; } // Check for DX10 extension bool bDXT10Header = false; if ((hdr->ddspf.flags & DDS_FOURCC) && (MAKEFOURCC('D', 'X', '1', '0') == hdr->ddspf.fourCC)) { // Must be long enough for both headers and magic value if (fileInfo.EndOfFile.LowPart < (sizeof(DDS_HEADER) + sizeof(uint32_t) + sizeof(DDS_HEADER_DXT10))) { return E_FAIL; } bDXT10Header = true; } // setup the pointers in the process request *header = hdr; ptrdiff_t offset = sizeof(uint32_t) + sizeof(DDS_HEADER) + (bDXT10Header ? sizeof(DDS_HEADER_DXT10) : 0); *bitData = ddsData.get() + offset; *bitSize = fileInfo.EndOfFile.LowPart - offset; return S_OK; } //-------------------------------------------------------------------------------------- // Return the BPP for a particular format //-------------------------------------------------------------------------------------- size_t BitsPerPixel(_In_ DXGI_FORMAT fmt) { switch (fmt) { case DXGI_FORMAT_R32G32B32A32_TYPELESS: case DXGI_FORMAT_R32G32B32A32_FLOAT: case DXGI_FORMAT_R32G32B32A32_UINT: case DXGI_FORMAT_R32G32B32A32_SINT: return 128; case DXGI_FORMAT_R32G32B32_TYPELESS: case DXGI_FORMAT_R32G32B32_FLOAT: case DXGI_FORMAT_R32G32B32_UINT: case DXGI_FORMAT_R32G32B32_SINT: return 96; case DXGI_FORMAT_R16G16B16A16_TYPELESS: case DXGI_FORMAT_R16G16B16A16_FLOAT: case DXGI_FORMAT_R16G16B16A16_UNORM: case DXGI_FORMAT_R16G16B16A16_UINT: case DXGI_FORMAT_R16G16B16A16_SNORM: case DXGI_FORMAT_R16G16B16A16_SINT: case DXGI_FORMAT_R32G32_TYPELESS: case DXGI_FORMAT_R32G32_FLOAT: case DXGI_FORMAT_R32G32_UINT: case DXGI_FORMAT_R32G32_SINT: case DXGI_FORMAT_R32G8X24_TYPELESS: case DXGI_FORMAT_D32_FLOAT_S8X24_UINT: case DXGI_FORMAT_R32_FLOAT_X8X24_TYPELESS: case DXGI_FORMAT_X32_TYPELESS_G8X24_UINT: case DXGI_FORMAT_Y416: case DXGI_FORMAT_Y210: case DXGI_FORMAT_Y216: return 64; case DXGI_FORMAT_R10G10B10A2_TYPELESS: case DXGI_FORMAT_R10G10B10A2_UNORM: case DXGI_FORMAT_R10G10B10A2_UINT: case DXGI_FORMAT_R11G11B10_FLOAT: case DXGI_FORMAT_R8G8B8A8_TYPELESS: case DXGI_FORMAT_R8G8B8A8_UNORM: case DXGI_FORMAT_R8G8B8A8_UNORM_SRGB: case DXGI_FORMAT_R8G8B8A8_UINT: case DXGI_FORMAT_R8G8B8A8_SNORM: case DXGI_FORMAT_R8G8B8A8_SINT: case DXGI_FORMAT_R16G16_TYPELESS: case DXGI_FORMAT_R16G16_FLOAT: case DXGI_FORMAT_R16G16_UNORM: case DXGI_FORMAT_R16G16_UINT: case DXGI_FORMAT_R16G16_SNORM: case DXGI_FORMAT_R16G16_SINT: case DXGI_FORMAT_R32_TYPELESS: case DXGI_FORMAT_D32_FLOAT: case DXGI_FORMAT_R32_FLOAT: case DXGI_FORMAT_R32_UINT: case DXGI_FORMAT_R32_SINT: case DXGI_FORMAT_R24G8_TYPELESS: case DXGI_FORMAT_D24_UNORM_S8_UINT: case DXGI_FORMAT_R24_UNORM_X8_TYPELESS: case DXGI_FORMAT_X24_TYPELESS_G8_UINT: case DXGI_FORMAT_R9G9B9E5_SHAREDEXP: case DXGI_FORMAT_R8G8_B8G8_UNORM: case DXGI_FORMAT_G8R8_G8B8_UNORM: case DXGI_FORMAT_B8G8R8A8_UNORM: case DXGI_FORMAT_B8G8R8X8_UNORM: case DXGI_FORMAT_R10G10B10_XR_BIAS_A2_UNORM: case DXGI_FORMAT_B8G8R8A8_TYPELESS: case DXGI_FORMAT_B8G8R8A8_UNORM_SRGB: case DXGI_FORMAT_B8G8R8X8_TYPELESS: case DXGI_FORMAT_B8G8R8X8_UNORM_SRGB: case DXGI_FORMAT_AYUV: case DXGI_FORMAT_Y410: case DXGI_FORMAT_YUY2: return 32; case DXGI_FORMAT_P010: case DXGI_FORMAT_P016: return 24; case DXGI_FORMAT_R8G8_TYPELESS: case DXGI_FORMAT_R8G8_UNORM: case DXGI_FORMAT_R8G8_UINT: case DXGI_FORMAT_R8G8_SNORM: case DXGI_FORMAT_R8G8_SINT: case DXGI_FORMAT_R16_TYPELESS: case DXGI_FORMAT_R16_FLOAT: case DXGI_FORMAT_D16_UNORM: case DXGI_FORMAT_R16_UNORM: case DXGI_FORMAT_R16_UINT: case DXGI_FORMAT_R16_SNORM: case DXGI_FORMAT_R16_SINT: case DXGI_FORMAT_B5G6R5_UNORM: case DXGI_FORMAT_B5G5R5A1_UNORM: case DXGI_FORMAT_A8P8: case DXGI_FORMAT_B4G4R4A4_UNORM: return 16; case DXGI_FORMAT_NV12: case DXGI_FORMAT_420_OPAQUE: case DXGI_FORMAT_NV11: return 12; case DXGI_FORMAT_R8_TYPELESS: case DXGI_FORMAT_R8_UNORM: case DXGI_FORMAT_R8_UINT: case DXGI_FORMAT_R8_SNORM: case DXGI_FORMAT_R8_SINT: case DXGI_FORMAT_A8_UNORM: case DXGI_FORMAT_AI44: case DXGI_FORMAT_IA44: case DXGI_FORMAT_P8: return 8; case DXGI_FORMAT_R1_UNORM: return 1; case DXGI_FORMAT_BC1_TYPELESS: case DXGI_FORMAT_BC1_UNORM: case DXGI_FORMAT_BC1_UNORM_SRGB: case DXGI_FORMAT_BC4_TYPELESS: case DXGI_FORMAT_BC4_UNORM: case DXGI_FORMAT_BC4_SNORM: return 4; case DXGI_FORMAT_BC2_TYPELESS: case DXGI_FORMAT_BC2_UNORM: case DXGI_FORMAT_BC2_UNORM_SRGB: case DXGI_FORMAT_BC3_TYPELESS: case DXGI_FORMAT_BC3_UNORM: case DXGI_FORMAT_BC3_UNORM_SRGB: case DXGI_FORMAT_BC5_TYPELESS: case DXGI_FORMAT_BC5_UNORM: case DXGI_FORMAT_BC5_SNORM: case DXGI_FORMAT_BC6H_TYPELESS: case DXGI_FORMAT_BC6H_UF16: case DXGI_FORMAT_BC6H_SF16: case DXGI_FORMAT_BC7_TYPELESS: case DXGI_FORMAT_BC7_UNORM: case DXGI_FORMAT_BC7_UNORM_SRGB: return 8; default: return 0; } } //-------------------------------------------------------------------------------------- // Get surface information for a particular format //-------------------------------------------------------------------------------------- HRESULT GetSurfaceInfo( _In_ size_t width, _In_ size_t height, _In_ DXGI_FORMAT fmt, size_t* outNumBytes, _Out_opt_ size_t* outRowBytes, _Out_opt_ size_t* outNumRows) { uint64_t numBytes = 0; uint64_t rowBytes = 0; uint64_t numRows = 0; bool bc = false; bool packed = false; bool planar = false; size_t bpe = 0; switch (fmt) { case DXGI_FORMAT_BC1_TYPELESS: case DXGI_FORMAT_BC1_UNORM: case DXGI_FORMAT_BC1_UNORM_SRGB: case DXGI_FORMAT_BC4_TYPELESS: case DXGI_FORMAT_BC4_UNORM: case DXGI_FORMAT_BC4_SNORM: bc = true; bpe = 8; break; case DXGI_FORMAT_BC2_TYPELESS: case DXGI_FORMAT_BC2_UNORM: case DXGI_FORMAT_BC2_UNORM_SRGB: case DXGI_FORMAT_BC3_TYPELESS: case DXGI_FORMAT_BC3_UNORM: case DXGI_FORMAT_BC3_UNORM_SRGB: case DXGI_FORMAT_BC5_TYPELESS: case DXGI_FORMAT_BC5_UNORM: case DXGI_FORMAT_BC5_SNORM: case DXGI_FORMAT_BC6H_TYPELESS: case DXGI_FORMAT_BC6H_UF16: case DXGI_FORMAT_BC6H_SF16: case DXGI_FORMAT_BC7_TYPELESS: case DXGI_FORMAT_BC7_UNORM: case DXGI_FORMAT_BC7_UNORM_SRGB: bc = true; bpe = 16; break; case DXGI_FORMAT_R8G8_B8G8_UNORM: case DXGI_FORMAT_G8R8_G8B8_UNORM: case DXGI_FORMAT_YUY2: packed = true; bpe = 4; break; case DXGI_FORMAT_Y210: case DXGI_FORMAT_Y216: packed = true; bpe = 8; break; case DXGI_FORMAT_NV12: case DXGI_FORMAT_420_OPAQUE: planar = true; bpe = 2; break; case DXGI_FORMAT_P010: case DXGI_FORMAT_P016: planar = true; bpe = 4; break; default: break; } if (bc) { uint64_t numBlocksWide = 0; if (width > 0) { numBlocksWide = std::max(1u, (uint64_t(width) + 3u) / 4u); } uint64_t numBlocksHigh = 0; if (height > 0) { numBlocksHigh = std::max(1u, (uint64_t(height) + 3u) / 4u); } rowBytes = numBlocksWide * bpe; numRows = numBlocksHigh; numBytes = rowBytes * numBlocksHigh; } else if (packed) { rowBytes = ((uint64_t(width) + 1u) >> 1) * bpe; numRows = uint64_t(height); numBytes = rowBytes * height; } else if (fmt == DXGI_FORMAT_NV11) { rowBytes = ((uint64_t(width) + 3u) >> 2) * 4u; numRows = uint64_t(height) * 2u; // Direct3D makes this simplifying assumption, although it is larger than the 4:1:1 data numBytes = rowBytes * numRows; } else if (planar) { rowBytes = ((uint64_t(width) + 1u) >> 1) * bpe; numBytes = (rowBytes * uint64_t(height)) + ((rowBytes * uint64_t(height) + 1u) >> 1); numRows = height + ((uint64_t(height) + 1u) >> 1); } else { size_t bpp = BitsPerPixel(fmt); if (!bpp) return E_INVALIDARG; rowBytes = (uint64_t(width) * bpp + 7u) / 8u; // round up to nearest byte numRows = uint64_t(height); numBytes = rowBytes * height; } #if defined(_M_IX86) || defined(_M_ARM) || defined(_M_HYBRID_X86_ARM64) static_assert(sizeof(size_t) == 4, ""Not a 32-bit platform!""); if (numBytes > UINT32_MAX || rowBytes > UINT32_MAX || numRows > UINT32_MAX) return HRESULT_FROM_WIN32(ERROR_ARITHMETIC_OVERFLOW); #else static_assert(sizeof(size_t) == 8, ""Not a 64-bit platform!""); #endif if (outNumBytes) { *outNumBytes = static_cast(numBytes); } if (outRowBytes) { *outRowBytes = static_cast(rowBytes); } if (outNumRows) { *outNumRows = static_cast(numRows); } return S_OK; } //-------------------------------------------------------------------------------------- #define ISBITMASK( r,g,b,a ) ( ddpf.RBitMask == r && ddpf.GBitMask == g && ddpf.BBitMask == b && ddpf.ABitMask == a ) DXGI_FORMAT GetDXGIFormat(const DDS_PIXELFORMAT& ddpf) { if (ddpf.flags & DDS_RGB) { // Note that sRGB formats are written using the ""DX10"" extended header switch (ddpf.RGBBitCount) { case 32: if (ISBITMASK(0x000000ff, 0x0000ff00, 0x00ff0000, 0xff000000)) { return DXGI_FORMAT_R8G8B8A8_UNORM; } if (ISBITMASK(0x00ff0000, 0x0000ff00, 0x000000ff, 0xff000000)) { return DXGI_FORMAT_B8G8R8A8_UNORM; } if (ISBITMASK(0x00ff0000, 0x0000ff00, 0x000000ff, 0x00000000)) { return DXGI_FORMAT_B8G8R8X8_UNORM; } // No DXGI format maps to ISBITMASK(0x000000ff,0x0000ff00,0x00ff0000,0x00000000) aka D3DFMT_X8B8G8R8 // Note that many common DDS reader/writers (including D3DX) swap the // the RED/BLUE masks for 10:10:10:2 formats. We assume // below that the 'backwards' header mask is being used since it is most // likely written by D3DX. The more robust solution is to use the 'DX10' // header extension and specify the DXGI_FORMAT_R10G10B10A2_UNORM format directly // For 'correct' writers, this should be 0x000003ff,0x000ffc00,0x3ff00000 for RGB data if (ISBITMASK(0x3ff00000, 0x000ffc00, 0x000003ff, 0xc0000000)) { return DXGI_FORMAT_R10G10B10A2_UNORM; } // No DXGI format maps to ISBITMASK(0x000003ff,0x000ffc00,0x3ff00000,0xc0000000) aka D3DFMT_A2R10G10B10 if (ISBITMASK(0x0000ffff, 0xffff0000, 0x00000000, 0x00000000)) { return DXGI_FORMAT_R16G16_UNORM; } if (ISBITMASK(0xffffffff, 0x00000000, 0x00000000, 0x00000000)) { // Only 32-bit color channel format in D3D9 was R32F return DXGI_FORMAT_R32_FLOAT; // D3DX writes this out as a FourCC of 114 } break; case 24: // No 24bpp DXGI formats aka D3DFMT_R8G8B8 break; case 16: if (ISBITMASK(0x7c00, 0x03e0, 0x001f, 0x8000)) { return DXGI_FORMAT_B5G5R5A1_UNORM; } if (ISBITMASK(0xf800, 0x07e0, 0x001f, 0x0000)) { return DXGI_FORMAT_B5G6R5_UNORM; } // No DXGI format maps to ISBITMASK(0x7c00,0x03e0,0x001f,0x0000) aka D3DFMT_X1R5G5B5 if (ISBITMASK(0x0f00, 0x00f0, 0x000f, 0xf000)) { return DXGI_FORMAT_B4G4R4A4_UNORM; } // No DXGI format maps to ISBITMASK(0x0f00,0x00f0,0x000f,0x0000) aka D3DFMT_X4R4G4B4 // No 3:3:2, 3:3:2:8, or paletted DXGI formats aka D3DFMT_A8R3G3B2, D3DFMT_R3G3B2, D3DFMT_P8, D3DFMT_A8P8, etc. break; } } else if (ddpf.flags & DDS_LUMINANCE) { if (8 == ddpf.RGBBitCount) { if (ISBITMASK(0x000000ff, 0x00000000, 0x00000000, 0x00000000)) { return DXGI_FORMAT_R8_UNORM; // D3DX10/11 writes this out as DX10 extension } // No DXGI format maps to ISBITMASK(0x0f,0x00,0x00,0xf0) aka D3DFMT_A4L4 if (ISBITMASK(0x000000ff, 0x00000000, 0x00000000, 0x0000ff00)) { return DXGI_FORMAT_R8G8_UNORM; // Some DDS writers assume the bitcount should be 8 instead of 16 } } if (16 == ddpf.RGBBitCount) { if (ISBITMASK(0x0000ffff, 0x00000000, 0x00000000, 0x00000000)) { return DXGI_FORMAT_R16_UNORM; // D3DX10/11 writes this out as DX10 extension } if (ISBITMASK(0x000000ff, 0x00000000, 0x00000000, 0x0000ff00)) { return DXGI_FORMAT_R8G8_UNORM; // D3DX10/11 writes this out as DX10 extension } } } else if (ddpf.flags & DDS_ALPHA) { if (8 == ddpf.RGBBitCount) { return DXGI_FORMAT_A8_UNORM; } } else if (ddpf.flags & DDS_BUMPDUDV) { if (16 == ddpf.RGBBitCount) { if (ISBITMASK(0x00ff, 0xff00, 0x0000, 0x0000)) { return DXGI_FORMAT_R8G8_SNORM; // D3DX10/11 writes this out as DX10 extension } } if (32 == ddpf.RGBBitCount) { if (ISBITMASK(0x000000ff, 0x0000ff00, 0x00ff0000, 0xff000000)) { return DXGI_FORMAT_R8G8B8A8_SNORM; // D3DX10/11 writes this out as DX10 extension } if (ISBITMASK(0x0000ffff, 0xffff0000, 0x00000000, 0x00000000)) { return DXGI_FORMAT_R16G16_SNORM; // D3DX10/11 writes this out as DX10 extension } // No DXGI format maps to ISBITMASK(0x3ff00000, 0x000ffc00, 0x000003ff, 0xc0000000) aka D3DFMT_A2W10V10U10 } } else if (ddpf.flags & DDS_FOURCC) { if (MAKEFOURCC('D', 'X', 'T', '1') == ddpf.fourCC) { return DXGI_FORMAT_BC1_UNORM; } if (MAKEFOURCC('D', 'X', 'T', '3') == ddpf.fourCC) { return DXGI_FORMAT_BC2_UNORM; } if (MAKEFOURCC('D', 'X', 'T', '5') == ddpf.fourCC) { return DXGI_FORMAT_BC3_UNORM; } // While pre-multiplied alpha isn't directly supported by the DXGI formats, // they are basically the same as these BC formats so they can be mapped if (MAKEFOURCC('D', 'X', 'T', '2') == ddpf.fourCC) { return DXGI_FORMAT_BC2_UNORM; } if (MAKEFOURCC('D', 'X', 'T', '4') == ddpf.fourCC) { return DXGI_FORMAT_BC3_UNORM; } if (MAKEFOURCC('A', 'T', 'I', '1') == ddpf.fourCC) { return DXGI_FORMAT_BC4_UNORM; } if (MAKEFOURCC('B', 'C', '4', 'U') == ddpf.fourCC) { return DXGI_FORMAT_BC4_UNORM; } if (MAKEFOURCC('B', 'C', '4', 'S') == ddpf.fourCC) { return DXGI_FORMAT_BC4_SNORM; } if (MAKEFOURCC('A', 'T', 'I', '2') == ddpf.fourCC) { return DXGI_FORMAT_BC5_UNORM; } if (MAKEFOURCC('B', 'C', '5', 'U') == ddpf.fourCC) { return DXGI_FORMAT_BC5_UNORM; } if (MAKEFOURCC('B', 'C', '5', 'S') == ddpf.fourCC) { return DXGI_FORMAT_BC5_SNORM; } // BC6H and BC7 are written using the ""DX10"" extended header if (MAKEFOURCC('R', 'G', 'B', 'G') == ddpf.fourCC) { return DXGI_FORMAT_R8G8_B8G8_UNORM; } if (MAKEFOURCC('G', 'R', 'G', 'B') == ddpf.fourCC) { return DXGI_FORMAT_G8R8_G8B8_UNORM; } if (MAKEFOURCC('Y', 'U', 'Y', '2') == ddpf.fourCC) { return DXGI_FORMAT_YUY2; } // Check for D3DFORMAT enums being set here switch (ddpf.fourCC) { case 36: // D3DFMT_A16B16G16R16 return DXGI_FORMAT_R16G16B16A16_UNORM; case 110: // D3DFMT_Q16W16V16U16 return DXGI_FORMAT_R16G16B16A16_SNORM; case 111: // D3DFMT_R16F return DXGI_FORMAT_R16_FLOAT; case 112: // D3DFMT_G16R16F return DXGI_FORMAT_R16G16_FLOAT; case 113: // D3DFMT_A16B16G16R16F return DXGI_FORMAT_R16G16B16A16_FLOAT; case 114: // D3DFMT_R32F return DXGI_FORMAT_R32_FLOAT; case 115: // D3DFMT_G32R32F return DXGI_FORMAT_R32G32_FLOAT; case 116: // D3DFMT_A32B32G32R32F return DXGI_FORMAT_R32G32B32A32_FLOAT; } } return DXGI_FORMAT_UNKNOWN; } //-------------------------------------------------------------------------------------- DXGI_FORMAT MakeSRGB(_In_ DXGI_FORMAT format) { switch (format) { case DXGI_FORMAT_R8G8B8A8_UNORM: return DXGI_FORMAT_R8G8B8A8_UNORM_SRGB; case DXGI_FORMAT_BC1_UNORM: return DXGI_FORMAT_BC1_UNORM_SRGB; case DXGI_FORMAT_BC2_UNORM: return DXGI_FORMAT_BC2_UNORM_SRGB; case DXGI_FORMAT_BC3_UNORM: return DXGI_FORMAT_BC3_UNORM_SRGB; case DXGI_FORMAT_B8G8R8A8_UNORM: return DXGI_FORMAT_B8G8R8A8_UNORM_SRGB; case DXGI_FORMAT_B8G8R8X8_UNORM: return DXGI_FORMAT_B8G8R8X8_UNORM_SRGB; case DXGI_FORMAT_BC7_UNORM: return DXGI_FORMAT_BC7_UNORM_SRGB; default: return format; } } //-------------------------------------------------------------------------------------- HRESULT FillInitData( _In_ size_t width, _In_ size_t height, _In_ size_t depth, _In_ size_t mipCount, _In_ size_t arraySize, _In_ DXGI_FORMAT format, _In_ size_t maxsize, _In_ size_t bitSize, _In_reads_bytes_(bitSize) const uint8_t* bitData, _Out_ size_t& twidth, _Out_ size_t& theight, _Out_ size_t& tdepth, _Out_ size_t& skipMip, _Out_writes_(mipCount*arraySize) D3D11_SUBRESOURCE_DATA* initData) { if (!bitData || !initData) { return E_POINTER; } skipMip = 0; twidth = 0; theight = 0; tdepth = 0; size_t NumBytes = 0; size_t RowBytes = 0; const uint8_t* pSrcBits = bitData; const uint8_t* pEndBits = bitData + bitSize; size_t index = 0; for (size_t j = 0; j < arraySize; j++) { size_t w = width; size_t h = height; size_t d = depth; for (size_t i = 0; i < mipCount; i++) { HRESULT hr = GetSurfaceInfo(w, h, format, &NumBytes, &RowBytes, nullptr); if (FAILED(hr)) return hr; if (NumBytes > UINT32_MAX || RowBytes > UINT32_MAX) return HRESULT_FROM_WIN32(ERROR_ARITHMETIC_OVERFLOW); if ((mipCount <= 1) || !maxsize || (w <= maxsize && h <= maxsize && d <= maxsize)) { if (!twidth) { twidth = w; theight = h; tdepth = d; } assert(index < mipCount * arraySize); _Analysis_assume_(index < mipCount * arraySize); initData[index].pSysMem = (const void*)pSrcBits; initData[index].SysMemPitch = static_cast(RowBytes); initData[index].SysMemSlicePitch = static_cast(NumBytes); ++index; } else if (!j) { // Count number of skipped mipmaps (first item only) ++skipMip; } if (pSrcBits + (NumBytes*d) > pEndBits) { return HRESULT_FROM_WIN32(ERROR_HANDLE_EOF); } pSrcBits += NumBytes * d; w = w >> 1; h = h >> 1; d = d >> 1; if (w == 0) { w = 1; } if (h == 0) { h = 1; } if (d == 0) { d = 1; } } } return (index > 0) ? S_OK : E_FAIL; } //-------------------------------------------------------------------------------------- HRESULT CreateD3DResources( _In_ ID3D11Device* d3dDevice, _In_ uint32_t resDim, _In_ size_t width, _In_ size_t height, _In_ size_t depth, _In_ size_t mipCount, _In_ size_t arraySize, _In_ DXGI_FORMAT format, _In_ D3D11_USAGE usage, _In_ unsigned int bindFlags, _In_ unsigned int cpuAccessFlags, _In_ unsigned int miscFlags, _In_ bool forceSRGB, _In_ bool isCubeMap, _In_reads_opt_(mipCount*arraySize) D3D11_SUBRESOURCE_DATA* initData, _Outptr_opt_ ID3D11Resource** texture, _Outptr_opt_ ID3D11ShaderResourceView** textureView) { if (!d3dDevice) return E_POINTER; HRESULT hr = E_FAIL; if (forceSRGB) { format = MakeSRGB(format); } switch (resDim) { case D3D11_RESOURCE_DIMENSION_TEXTURE1D: { D3D11_TEXTURE1D_DESC desc; desc.Width = static_cast(width); desc.MipLevels = static_cast(mipCount); desc.ArraySize = static_cast(arraySize); desc.Format = format; desc.Usage = usage; desc.BindFlags = bindFlags; desc.CPUAccessFlags = cpuAccessFlags; desc.MiscFlags = miscFlags & ~D3D11_RESOURCE_MISC_TEXTURECUBE; ID3D11Texture1D* tex = nullptr; hr = d3dDevice->CreateTexture1D(&desc, initData, &tex ); if (SUCCEEDED(hr) && tex) { if (textureView) { D3D11_SHADER_RESOURCE_VIEW_DESC SRVDesc = {}; SRVDesc.Format = format; if (arraySize > 1) { SRVDesc.ViewDimension = D3D11_SRV_DIMENSION_TEXTURE1DARRAY; SRVDesc.Texture1DArray.MipLevels = (!mipCount) ? -1 : desc.MipLevels; SRVDesc.Texture1DArray.ArraySize = static_cast(arraySize); } else { SRVDesc.ViewDimension = D3D11_SRV_DIMENSION_TEXTURE1D; SRVDesc.Texture1D.MipLevels = (!mipCount) ? -1 : desc.MipLevels; } hr = d3dDevice->CreateShaderResourceView(tex, &SRVDesc, textureView ); if (FAILED(hr)) { tex->Release(); return hr; } } if (texture) { *texture = tex; } else { SetDebugObjectName(tex, ""DDSTextureLoader""); tex->Release(); } } } break; case D3D11_RESOURCE_DIMENSION_TEXTURE2D: { D3D11_TEXTURE2D_DESC desc; desc.Width = static_cast(width); desc.Height = static_cast(height); desc.MipLevels = static_cast(mipCount); desc.ArraySize = static_cast(arraySize); desc.Format = format; desc.SampleDesc.Count = 1; desc.SampleDesc.Quality = 0; desc.Usage = usage; desc.BindFlags = bindFlags; desc.CPUAccessFlags = cpuAccessFlags; if (isCubeMap) { desc.MiscFlags = miscFlags | D3D11_RESOURCE_MISC_TEXTURECUBE; } else { desc.MiscFlags = miscFlags & ~D3D11_RESOURCE_MISC_TEXTURECUBE; } ID3D11Texture2D* tex = nullptr; hr = d3dDevice->CreateTexture2D(&desc, initData, &tex ); if (SUCCEEDED(hr) && tex) { if (textureView) { D3D11_SHADER_RESOURCE_VIEW_DESC SRVDesc = {}; SRVDesc.Format = format; if (isCubeMap) { if (arraySize > 6) { SRVDesc.ViewDimension = D3D11_SRV_DIMENSION_TEXTURECUBEARRAY; SRVDesc.TextureCubeArray.MipLevels = (!mipCount) ? -1 : desc.MipLevels; // Earlier we set arraySize to (NumCubes * 6) SRVDesc.TextureCubeArray.NumCubes = static_cast(arraySize / 6); } else { SRVDesc.ViewDimension = D3D11_SRV_DIMENSION_TEXTURECUBE; SRVDesc.TextureCube.MipLevels = (!mipCount) ? -1 : desc.MipLevels; } } else if (arraySize > 1) { SRVDesc.ViewDimension = D3D11_SRV_DIMENSION_TEXTURE2DARRAY; SRVDesc.Texture2DArray.MipLevels = (!mipCount) ? -1 : desc.MipLevels; SRVDesc.Texture2DArray.ArraySize = static_cast(arraySize); } else { SRVDesc.ViewDimension = D3D11_SRV_DIMENSION_TEXTURE2D; SRVDesc.Texture2D.MipLevels = (!mipCount) ? -1 : desc.MipLevels; } hr = d3dDevice->CreateShaderResourceView(tex, &SRVDesc, textureView ); if (FAILED(hr)) { tex->Release(); return hr; } } if (texture) { *texture = tex; } else { SetDebugObjectName(tex, ""DDSTextureLoader""); tex->Release(); } } } break; case D3D11_RESOURCE_DIMENSION_TEXTURE3D: { D3D11_TEXTURE3D_DESC desc; desc.Width = static_cast(width); desc.Height = static_cast(height); desc.Depth = static_cast(depth); desc.MipLevels = static_cast(mipCount); desc.Format = format; desc.Usage = usage; desc.BindFlags = bindFlags; desc.CPUAccessFlags = cpuAccessFlags; desc.MiscFlags = miscFlags & ~D3D11_RESOURCE_MISC_TEXTURECUBE; ID3D11Texture3D* tex = nullptr; hr = d3dDevice->CreateTexture3D(&desc, initData, &tex ); if (SUCCEEDED(hr) && tex) { if (textureView) { D3D11_SHADER_RESOURCE_VIEW_DESC SRVDesc = {}; SRVDesc.Format = format; SRVDesc.ViewDimension = D3D11_SRV_DIMENSION_TEXTURE3D; SRVDesc.Texture3D.MipLevels = (!mipCount) ? -1 : desc.MipLevels; hr = d3dDevice->CreateShaderResourceView(tex, &SRVDesc, textureView ); if (FAILED(hr)) { tex->Release(); return hr; } } if (texture) { *texture = tex; } else { SetDebugObjectName(tex, ""DDSTextureLoader""); tex->Release(); } } } break; } return hr; } //-------------------------------------------------------------------------------------- HRESULT CreateTextureFromDDS( _In_ ID3D11Device* d3dDevice, _In_opt_ ID3D11DeviceContext* d3dContext, _In_ const DDS_HEADER* header, _In_reads_bytes_(bitSize) const uint8_t* bitData, _In_ size_t bitSize, _In_ size_t maxsize, _In_ D3D11_USAGE usage, _In_ unsigned int bindFlags, _In_ unsigned int cpuAccessFlags, _In_ unsigned int miscFlags, _In_ bool forceSRGB, _Outptr_opt_ ID3D11Resource** texture, _Outptr_opt_ ID3D11ShaderResourceView** textureView) { HRESULT hr = S_OK; UINT width = header->width; UINT height = header->height; UINT depth = header->depth; uint32_t resDim = D3D11_RESOURCE_DIMENSION_UNKNOWN; UINT arraySize = 1; DXGI_FORMAT format = DXGI_FORMAT_UNKNOWN; bool isCubeMap = false; size_t mipCount = header->mipMapCount; if (0 == mipCount) { mipCount = 1; } if ((header->ddspf.flags & DDS_FOURCC) && (MAKEFOURCC('D', 'X', '1', '0') == header->ddspf.fourCC)) { auto d3d10ext = reinterpret_cast((const char*)header + sizeof(DDS_HEADER)); arraySize = d3d10ext->arraySize; if (arraySize == 0) { return HRESULT_FROM_WIN32(ERROR_INVALID_DATA); } switch (d3d10ext->dxgiFormat) { case DXGI_FORMAT_AI44: case DXGI_FORMAT_IA44: case DXGI_FORMAT_P8: case DXGI_FORMAT_A8P8: return HRESULT_FROM_WIN32(ERROR_NOT_SUPPORTED); default: if (BitsPerPixel(d3d10ext->dxgiFormat) == 0) { return HRESULT_FROM_WIN32(ERROR_NOT_SUPPORTED); } } format = d3d10ext->dxgiFormat; switch (d3d10ext->resourceDimension) { case D3D11_RESOURCE_DIMENSION_TEXTURE1D: // D3DX writes 1D textures with a fixed Height of 1 if ((header->flags & DDS_HEIGHT) && height != 1) { return HRESULT_FROM_WIN32(ERROR_INVALID_DATA); } height = depth = 1; break; case D3D11_RESOURCE_DIMENSION_TEXTURE2D: if (d3d10ext->miscFlag & D3D11_RESOURCE_MISC_TEXTURECUBE) { arraySize *= 6; isCubeMap = true; } depth = 1; break; case D3D11_RESOURCE_DIMENSION_TEXTURE3D: if (!(header->flags & DDS_HEADER_FLAGS_VOLUME)) { return HRESULT_FROM_WIN32(ERROR_INVALID_DATA); } if (arraySize > 1) { return HRESULT_FROM_WIN32(ERROR_NOT_SUPPORTED); } break; default: return HRESULT_FROM_WIN32(ERROR_NOT_SUPPORTED); } resDim = d3d10ext->resourceDimension; } else { format = GetDXGIFormat(header->ddspf); if (format == DXGI_FORMAT_UNKNOWN) { return HRESULT_FROM_WIN32(ERROR_NOT_SUPPORTED); } if (header->flags & DDS_HEADER_FLAGS_VOLUME) { resDim = D3D11_RESOURCE_DIMENSION_TEXTURE3D; } else { if (header->caps2 & DDS_CUBEMAP) { // We require all six faces to be defined if ((header->caps2 & DDS_CUBEMAP_ALLFACES) != DDS_CUBEMAP_ALLFACES) { return HRESULT_FROM_WIN32(ERROR_NOT_SUPPORTED); } arraySize = 6; isCubeMap = true; } depth = 1; resDim = D3D11_RESOURCE_DIMENSION_TEXTURE2D; // Note there's no way for a legacy Direct3D 9 DDS to express a '1D' texture } assert(BitsPerPixel(format) != 0); } // Bound sizes (for security purposes we don't trust DDS file metadata larger than the D3D 11.x hardware requirements) if (mipCount > D3D11_REQ_MIP_LEVELS) { return HRESULT_FROM_WIN32(ERROR_NOT_SUPPORTED); } switch (resDim) { case D3D11_RESOURCE_DIMENSION_TEXTURE1D: if ((arraySize > D3D11_REQ_TEXTURE1D_ARRAY_AXIS_DIMENSION) || (width > D3D11_REQ_TEXTURE1D_U_DIMENSION)) { return HRESULT_FROM_WIN32(ERROR_NOT_SUPPORTED); } break; case D3D11_RESOURCE_DIMENSION_TEXTURE2D: if (isCubeMap) { // This is the right bound because we set arraySize to (NumCubes*6) above if ((arraySize > D3D11_REQ_TEXTURE2D_ARRAY_AXIS_DIMENSION) || (width > D3D11_REQ_TEXTURECUBE_DIMENSION) || (height > D3D11_REQ_TEXTURECUBE_DIMENSION)) { return HRESULT_FROM_WIN32(ERROR_NOT_SUPPORTED); } } else if ((arraySize > D3D11_REQ_TEXTURE2D_ARRAY_AXIS_DIMENSION) || (width > D3D11_REQ_TEXTURE2D_U_OR_V_DIMENSION) || (height > D3D11_REQ_TEXTURE2D_U_OR_V_DIMENSION)) { return HRESULT_FROM_WIN32(ERROR_NOT_SUPPORTED); } break; case D3D11_RESOURCE_DIMENSION_TEXTURE3D: if ((arraySize > 1) || (width > D3D11_REQ_TEXTURE3D_U_V_OR_W_DIMENSION) || (height > D3D11_REQ_TEXTURE3D_U_V_OR_W_DIMENSION) || (depth > D3D11_REQ_TEXTURE3D_U_V_OR_W_DIMENSION)) { return HRESULT_FROM_WIN32(ERROR_NOT_SUPPORTED); } break; default: return HRESULT_FROM_WIN32(ERROR_NOT_SUPPORTED); } bool autogen = false; if (mipCount == 1 && d3dContext && textureView) // Must have context and shader-view to auto generate mipmaps { // See if format is supported for auto-gen mipmaps (varies by feature level) UINT fmtSupport = 0; hr = d3dDevice->CheckFormatSupport(format, &fmtSupport); if (SUCCEEDED(hr) && (fmtSupport & D3D11_FORMAT_SUPPORT_MIP_AUTOGEN)) { // 10level9 feature levels do not support auto-gen mipgen for volume textures if ((resDim != D3D11_RESOURCE_DIMENSION_TEXTURE3D) || (d3dDevice->GetFeatureLevel() >= D3D_FEATURE_LEVEL_10_0)) { autogen = true; } } } if (autogen) { // Create texture with auto-generated mipmaps ID3D11Resource* tex = nullptr; hr = CreateD3DResources(d3dDevice, resDim, width, height, depth, 0, arraySize, format, usage, bindFlags | D3D11_BIND_RENDER_TARGET, cpuAccessFlags, miscFlags | D3D11_RESOURCE_MISC_GENERATE_MIPS, forceSRGB, isCubeMap, nullptr, &tex, textureView); if (SUCCEEDED(hr)) { size_t numBytes = 0; size_t rowBytes = 0; hr = GetSurfaceInfo(width, height, format, &numBytes, &rowBytes, nullptr); if (FAILED(hr)) return hr; if (numBytes > bitSize) { (*textureView)->Release(); *textureView = nullptr; tex->Release(); return HRESULT_FROM_WIN32(ERROR_HANDLE_EOF); } if (numBytes > UINT32_MAX || rowBytes > UINT32_MAX) return HRESULT_FROM_WIN32(ERROR_ARITHMETIC_OVERFLOW); D3D11_SHADER_RESOURCE_VIEW_DESC desc; (*textureView)->GetDesc(&desc); UINT mipLevels = 1; switch (desc.ViewDimension) { case D3D_SRV_DIMENSION_TEXTURE1D: mipLevels = desc.Texture1D.MipLevels; break; case D3D_SRV_DIMENSION_TEXTURE1DARRAY: mipLevels = desc.Texture1DArray.MipLevels; break; case D3D_SRV_DIMENSION_TEXTURE2D: mipLevels = desc.Texture2D.MipLevels; break; case D3D_SRV_DIMENSION_TEXTURE2DARRAY: mipLevels = desc.Texture2DArray.MipLevels; break; case D3D_SRV_DIMENSION_TEXTURECUBE: mipLevels = desc.TextureCube.MipLevels; break; case D3D_SRV_DIMENSION_TEXTURECUBEARRAY:mipLevels = desc.TextureCubeArray.MipLevels; break; case D3D_SRV_DIMENSION_TEXTURE3D: mipLevels = desc.Texture3D.MipLevels; break; default: (*textureView)->Release(); *textureView = nullptr; tex->Release(); return E_UNEXPECTED; } if (arraySize > 1) { const uint8_t* pSrcBits = bitData; const uint8_t* pEndBits = bitData + bitSize; for (UINT item = 0; item < arraySize; ++item) { if ((pSrcBits + numBytes) > pEndBits) { (*textureView)->Release(); *textureView = nullptr; tex->Release(); return HRESULT_FROM_WIN32(ERROR_HANDLE_EOF); } UINT res = D3D11CalcSubresource(0, item, mipLevels); d3dContext->UpdateSubresource(tex, res, nullptr, pSrcBits, static_cast(rowBytes), static_cast(numBytes)); pSrcBits += numBytes; } } else { d3dContext->UpdateSubresource(tex, 0, nullptr, bitData, static_cast(rowBytes), static_cast(numBytes)); } d3dContext->GenerateMips(*textureView); if (texture) { *texture = tex; } else { tex->Release(); } } } else { // Create the texture std::unique_ptr initData(new (std::nothrow) D3D11_SUBRESOURCE_DATA[mipCount * arraySize]); if (!initData) { return E_OUTOFMEMORY; } size_t skipMip = 0; size_t twidth = 0; size_t theight = 0; size_t tdepth = 0; hr = FillInitData(width, height, depth, mipCount, arraySize, format, maxsize, bitSize, bitData, twidth, theight, tdepth, skipMip, initData.get()); if (SUCCEEDED(hr)) { hr = CreateD3DResources(d3dDevice, resDim, twidth, theight, tdepth, mipCount - skipMip, arraySize, format, usage, bindFlags, cpuAccessFlags, miscFlags, forceSRGB, isCubeMap, initData.get(), texture, textureView); if (FAILED(hr) && !maxsize && (mipCount > 1)) { // Retry with a maxsize determined by feature level switch (d3dDevice->GetFeatureLevel()) { case D3D_FEATURE_LEVEL_9_1: case D3D_FEATURE_LEVEL_9_2: if (isCubeMap) { maxsize = 512 /*D3D_FL9_1_REQ_TEXTURECUBE_DIMENSION*/; } else { maxsize = (resDim == D3D11_RESOURCE_DIMENSION_TEXTURE3D) ? 256 /*D3D_FL9_1_REQ_TEXTURE3D_U_V_OR_W_DIMENSION*/ : 2048 /*D3D_FL9_1_REQ_TEXTURE2D_U_OR_V_DIMENSION*/; } break; case D3D_FEATURE_LEVEL_9_3: maxsize = (resDim == D3D11_RESOURCE_DIMENSION_TEXTURE3D) ? 256 /*D3D_FL9_1_REQ_TEXTURE3D_U_V_OR_W_DIMENSION*/ : 4096 /*D3D_FL9_3_REQ_TEXTURE2D_U_OR_V_DIMENSION*/; break; default: // D3D_FEATURE_LEVEL_10_0 & D3D_FEATURE_LEVEL_10_1 maxsize = (resDim == D3D11_RESOURCE_DIMENSION_TEXTURE3D) ? 2048 /*D3D10_REQ_TEXTURE3D_U_V_OR_W_DIMENSION*/ : 8192 /*D3D10_REQ_TEXTURE2D_U_OR_V_DIMENSION*/; break; } hr = FillInitData(width, height, depth, mipCount, arraySize, format, maxsize, bitSize, bitData, twidth, theight, tdepth, skipMip, initData.get()); if (SUCCEEDED(hr)) { hr = CreateD3DResources(d3dDevice, resDim, twidth, theight, tdepth, mipCount - skipMip, arraySize, format, usage, bindFlags, cpuAccessFlags, miscFlags, forceSRGB, isCubeMap, initData.get(), texture, textureView); } } } } return hr; } //-------------------------------------------------------------------------------------- DDS_ALPHA_MODE GetAlphaMode(_In_ const DDS_HEADER* header) { if (header->ddspf.flags & DDS_FOURCC) { if (MAKEFOURCC('D', 'X', '1', '0') == header->ddspf.fourCC) { auto d3d10ext = reinterpret_cast((const char*)header + sizeof(DDS_HEADER)); auto mode = static_cast(d3d10ext->miscFlags2 & DDS_MISC_FLAGS2_ALPHA_MODE_MASK); switch (mode) { case DDS_ALPHA_MODE_STRAIGHT: case DDS_ALPHA_MODE_PREMULTIPLIED: case DDS_ALPHA_MODE_OPAQUE: case DDS_ALPHA_MODE_CUSTOM: return mode; } } else if ((MAKEFOURCC('D', 'X', 'T', '2') == header->ddspf.fourCC) || (MAKEFOURCC('D', 'X', 'T', '4') == header->ddspf.fourCC)) { return DDS_ALPHA_MODE_PREMULTIPLIED; } } return DDS_ALPHA_MODE_UNKNOWN; } } // anonymous namespace //-------------------------------------------------------------------------------------- _Use_decl_annotations_ HRESULT DirectX::CreateDDSTextureFromMemory(ID3D11Device* d3dDevice, const uint8_t* ddsData, size_t ddsDataSize, ID3D11Resource** texture, ID3D11ShaderResourceView** textureView, size_t maxsize, DDS_ALPHA_MODE* alphaMode) { return CreateDDSTextureFromMemoryEx(d3dDevice, nullptr, ddsData, ddsDataSize, maxsize, D3D11_USAGE_DEFAULT, D3D11_BIND_SHADER_RESOURCE, 0, 0, false, texture, textureView, alphaMode); } _Use_decl_annotations_ HRESULT DirectX::CreateDDSTextureFromMemory(ID3D11Device* d3dDevice, ID3D11DeviceContext* d3dContext, const uint8_t* ddsData, size_t ddsDataSize, ID3D11Resource** texture, ID3D11ShaderResourceView** textureView, size_t maxsize, DDS_ALPHA_MODE* alphaMode) { return CreateDDSTextureFromMemoryEx(d3dDevice, d3dContext, ddsData, ddsDataSize, maxsize, D3D11_USAGE_DEFAULT, D3D11_BIND_SHADER_RESOURCE, 0, 0, false, texture, textureView, alphaMode); } _Use_decl_annotations_ HRESULT DirectX::CreateDDSTextureFromMemoryEx(ID3D11Device* d3dDevice, const uint8_t* ddsData, size_t ddsDataSize, size_t maxsize, D3D11_USAGE usage, unsigned int bindFlags, unsigned int cpuAccessFlags, unsigned int miscFlags, bool forceSRGB, ID3D11Resource** texture, ID3D11ShaderResourceView** textureView, DDS_ALPHA_MODE* alphaMode) { return CreateDDSTextureFromMemoryEx(d3dDevice, nullptr, ddsData, ddsDataSize, maxsize, usage, bindFlags, cpuAccessFlags, miscFlags, forceSRGB, texture, textureView, alphaMode); } _Use_decl_annotations_ HRESULT DirectX::CreateDDSTextureFromMemoryEx(ID3D11Device* d3dDevice, ID3D11DeviceContext* d3dContext, const uint8_t* ddsData, size_t ddsDataSize, size_t maxsize, D3D11_USAGE usage, unsigned int bindFlags, unsigned int cpuAccessFlags, unsigned int miscFlags, bool forceSRGB, ID3D11Resource** texture, ID3D11ShaderResourceView** textureView, DDS_ALPHA_MODE* alphaMode) { if (texture) { *texture = nullptr; } if (textureView) { *textureView = nullptr; } if (alphaMode) { *alphaMode = DDS_ALPHA_MODE_UNKNOWN; } if (!d3dDevice || !ddsData || (!texture && !textureView)) { return E_INVALIDARG; } // Validate DDS file in memory if (ddsDataSize < (sizeof(uint32_t) + sizeof(DDS_HEADER))) { return E_FAIL; } uint32_t dwMagicNumber = *(const uint32_t*)(ddsData); if (dwMagicNumber != DDS_MAGIC) { return E_FAIL; } auto header = reinterpret_cast(ddsData + sizeof(uint32_t)); // Verify header to validate DDS file if (header->size != sizeof(DDS_HEADER) || header->ddspf.size != sizeof(DDS_PIXELFORMAT)) { return E_FAIL; } // Check for DX10 extension bool bDXT10Header = false; if ((header->ddspf.flags & DDS_FOURCC) && (MAKEFOURCC('D', 'X', '1', '0') == header->ddspf.fourCC)) { // Must be long enough for both headers and magic value if (ddsDataSize < (sizeof(DDS_HEADER) + sizeof(uint32_t) + sizeof(DDS_HEADER_DXT10))) { return E_FAIL; } bDXT10Header = true; } ptrdiff_t offset = sizeof(uint32_t) + sizeof(DDS_HEADER) + (bDXT10Header ? sizeof(DDS_HEADER_DXT10) : 0); HRESULT hr = CreateTextureFromDDS(d3dDevice, d3dContext, header, ddsData + offset, ddsDataSize - offset, maxsize, usage, bindFlags, cpuAccessFlags, miscFlags, forceSRGB, texture, textureView); if (SUCCEEDED(hr)) { if (texture && *texture) { SetDebugObjectName(*texture, ""DDSTextureLoader""); } if (textureView && *textureView) { SetDebugObjectName(*textureView, ""DDSTextureLoader""); } if (alphaMode) *alphaMode = GetAlphaMode(header); } return hr; } //-------------------------------------------------------------------------------------- _Use_decl_annotations_ HRESULT DirectX::CreateDDSTextureFromFile(ID3D11Device* d3dDevice, const wchar_t* fileName, ID3D11Resource** texture, ID3D11ShaderResourceView** textureView, size_t maxsize, DDS_ALPHA_MODE* alphaMode) { return CreateDDSTextureFromFileEx(d3dDevice, nullptr, fileName, maxsize, D3D11_USAGE_DEFAULT, D3D11_BIND_SHADER_RESOURCE, 0, 0, false, texture, textureView, alphaMode); } _Use_decl_annotations_ HRESULT DirectX::CreateDDSTextureFromFile(ID3D11Device* d3dDevice, ID3D11DeviceContext* d3dContext, const wchar_t* fileName, ID3D11Resource** texture, ID3D11ShaderResourceView** textureView, size_t maxsize, DDS_ALPHA_MODE* alphaMode) { return CreateDDSTextureFromFileEx(d3dDevice, d3dContext, fileName, maxsize, D3D11_USAGE_DEFAULT, D3D11_BIND_SHADER_RESOURCE, 0, 0, false, texture, textureView, alphaMode); } _Use_decl_annotations_ HRESULT DirectX::CreateDDSTextureFromFileEx(ID3D11Device* d3dDevice, const wchar_t* fileName, size_t maxsize, D3D11_USAGE usage, unsigned int bindFlags, unsigned int cpuAccessFlags, unsigned int miscFlags, bool forceSRGB, ID3D11Resource** texture, ID3D11ShaderResourceView** textureView, DDS_ALPHA_MODE* alphaMode) { return CreateDDSTextureFromFileEx(d3dDevice, nullptr, fileName, maxsize, usage, bindFlags, cpuAccessFlags, miscFlags, forceSRGB, texture, textureView, alphaMode); } _Use_decl_annotations_ HRESULT DirectX::CreateDDSTextureFromFileEx(ID3D11Device* d3dDevice, ID3D11DeviceContext* d3dContext, const wchar_t* fileName, size_t maxsize, D3D11_USAGE usage, unsigned int bindFlags, unsigned int cpuAccessFlags, unsigned int miscFlags, bool forceSRGB, ID3D11Resource** texture, ID3D11ShaderResourceView** textureView, DDS_ALPHA_MODE* alphaMode) { if (texture) { *texture = nullptr; } if (textureView) { *textureView = nullptr; } if (alphaMode) { *alphaMode = DDS_ALPHA_MODE_UNKNOWN; } if (!d3dDevice || !fileName || (!texture && !textureView)) { return E_INVALIDARG; } const DDS_HEADER* header = nullptr; const uint8_t* bitData = nullptr; size_t bitSize = 0; std::unique_ptr ddsData; HRESULT hr = LoadTextureDataFromFile(fileName, ddsData, &header, &bitData, &bitSize ); if (FAILED(hr)) { return hr; } hr = CreateTextureFromDDS(d3dDevice, d3dContext, header, bitData, bitSize, maxsize, usage, bindFlags, cpuAccessFlags, miscFlags, forceSRGB, texture, textureView); if (SUCCEEDED(hr)) { #if !defined(NO_D3D11_DEBUG_NAME) && ( defined(_DEBUG) || defined(PROFILE) ) if (texture || textureView) { CHAR strFileA[MAX_PATH]; int result = WideCharToMultiByte(CP_UTF8, WC_NO_BEST_FIT_CHARS, fileName, -1, strFileA, MAX_PATH, nullptr, FALSE ); if (result > 0) { const CHAR* pstrName = strrchr(strFileA, '\\\\'); if (!pstrName) { pstrName = strFileA; } else { pstrName++; } if (texture && *texture) { (*texture)->SetPrivateData(WKPDID_D3DDebugObjectName, static_cast(strnlen_s(pstrName, MAX_PATH)), pstrName ); } if (textureView && *textureView) { (*textureView)->SetPrivateData(WKPDID_D3DDebugObjectName, static_cast(strnlen_s(pstrName, MAX_PATH)), pstrName ); } } } #endif if (alphaMode) *alphaMode = GetAlphaMode(header); } return hr; } ",16179,True,3101.956692775563,median "[[webflux]] = Spring WebFlux [[webflux-introduction]] == Introduction The original web framework included in the Spring Framework, Spring Web MVC, was purpose built for the Servlet API and Servlet containers. The reactive stack, web framework, Spring WebFlux, was added later in version 5.0. It is fully non-blocking, supports http://www.reactive-streams.org/[Reactive Streams] back pressure, and runs on servers such as Netty, Undertow, and Servlet 3.1+ containers. Both web frameworks mirror the names of their source modules https://github.com/spring-projects/spring-framework/tree/master/spring-webmvc[spring-webmvc] and https://github.com/spring-projects/spring-framework/tree/master/spring-webflux[spring-webflux] and co-exist side by side in the Spring Framework. Each module is optional. Applications may use one or the other module, or in some cases both -- e.g. Spring MVC controllers with the reactive `WebClient`. [[webflux-new-framework]] === Why a new web framework? Part of the answer is the need for a non-blocking web stack to handle concurrency with a small number of threads and scale with less hardware resources. Servlet 3.1 did provide an API for non-blocking I/O. However, using it leads away from the rest of the Servlet API where contracts are synchronous (`Filter`, `Servlet`) or blocking (`getParameter`, `getPart`). This was the motivation for a new common API to serve as a foundation across any non-blocking runtime. That is important because of servers such as Netty that are well established in the async, non-blocking space. The other part of the answer is functional programming. Much like the addition of annotations in Java 5 created opportunities -- e.g. annotated REST controllers or unit tests, the addition of lambda expressions in Java 8 created opportunities for functional APIs in Java. This is a boon for non-blocking applications and continuation style APIs -- as popularized by `CompletableFuture` and http://reactivex.io/[ReactiveX], that allow declarative composition of asynchronous logic. At the programming model level Java 8 enabled Spring WebFlux to offer functional web endpoints alongside with annotated controllers. [[webflux-why-reactive]] === Reactive: what and why? We touched on non-blocking and functional but why reactive and what do we mean? The term ""reactive"" refers to programming models that are built around reacting to change -- network component reacting to I/O events, UI controller reacting to mouse events, etc. In that sense non-blocking is reactive because instead of being blocked we are now in the mode of reacting to notifications as operations complete or data becomes available. There is also another important mechanism that we on the Spring team associate with ""reactive"" and that is non-blocking back pressure. In synchronous, imperative code, blocking calls serve as a natural form of back pressure that forces the caller to wait. In non-blocking code it becomes important to control the rate of events so that a fast producer does not overwhelm its destination. Reactive Streams is a https://github.com/reactive-streams/reactive-streams-jvm/blob/v1.0.1/README.md#specification[small spec], also http://download.java.net/java/jdk9/docs/api/java/util/concurrent/Flow.html[adopted] in Java 9, that defines the interaction between asynchronous components with back pressure. For example a data repository -- acting as http://www.reactive-streams.org/reactive-streams-1.0.1-javadoc/org/reactivestreams/Publisher.html[Publisher], can produce data that an HTTP server -- acting as http://www.reactive-streams.org/reactive-streams-1.0.1-javadoc/org/reactivestreams/Subscriber.html[Subscriber], can then write to the response. The main purpose of Reactive Streams is to allow the subscriber to control how fast or how slow the publisher will produce data. [NOTE] ==== *Common question: what if a publisher can't slow down?* + The purpose of Reactive Streams is only to establish the mechanism and a boundary. If a publisher can't slow down then it has to decide whether to buffer, drop, or fail. ==== [[webflux-reactive-api]] === Reactive API Reactive Streams plays an important role for interoperability. It is of interest to libraries and infrastructure components but less useful as an application API because it is too low level. What applications need is a higher level and richer, functional API to compose async logic -- similar to the Java 8 `Stream` API but not only for collections. This is the role that reactive libraries play. https://github.com/reactor/reactor[Reactor] is the reactive library of choice for Spring WebFlux. It provides the https://projectreactor.io/docs/core/release/api/reactor/core/publisher/Mono.html[Mono] and https://projectreactor.io/docs/core/release/api/reactor/core/publisher/Flux.html[Flux] API types to work on data sequences of 0..1 and 0..N through a rich set of operators aligned with the ReactiveX http://reactivex.io/documentation/operators.html[vocabulary of operators]. Reactor is a Reactive Streams library and therefore all of its operators support non-blocking back pressure. Reactor has a strong focus on server-side Java. It is developed in close collaboration with Spring. WebFlux requires Reactor as a core dependency but it is interoperable with other reactive libraries via Reactive Streams. As a general rule WebFlux APIs accept a plain `Publisher` as input, adapt it to Reactor types internally, use those, and then return either `Flux` or `Mono` as output. So you can pass any `Publisher` as input and you can apply operations on the output, but you'll need to adapt the output for use with another reactive library. Whenever feasible -- e.g. annotated controllers, WebFlux adapts transparently to the use of RxJava or other reactive library. See <> for more details. [[webflux-programming-models]] === Programming models The `spring-web` module contains the reactive foundation that underlies Spring WebFlux -- HTTP abstractions, Reactive Streams server adapters, reactive codecs, and a core Web API whose role is comparable to the Servlet API but with non-blocking semantics. On that foundation Spring WebFlux provides a choice of two programming models: - <> -- consistent with Spring MVC, and based on the same annotations from the `spring-web` module. Both Spring MVC and WebFlux controllers support reactive (Reactor, RxJava) return types and as a result it is not easy to tell them apart. One notable difference is that WebFlux also supports reactive `@RequestBody` arguments. - <> -- lambda-based, lightweight, functional programming model. Think of this as a small library or a set of utilities that an application can use to route and handle requests. The big difference with annotated controllers is that the application is in charge of request handling from start to finish vs declaring intent through annotations and being called back. [[webflux-framework-choice]] === Choosing a web framework Should you use Spring MVC or WebFlux? Let's cover a few different perspectives. If you have a Spring MVC application that works fine, there is no need to change. Imperative programming is the easiest way to write, understand, and debug code. You have maximum choice of libraries since historically most are blocking. If you are already shopping for a non-blocking web stack, Spring WebFlux offers the same execution model benefits as others in this space and also provides a choice of servers -- Netty, Tomcat, Jetty, Undertow, Servlet 3.1+ containers, a choice of programming models -- annotated controllers and functional web endpoints, and a choice of reactive libraries -- Reactor, RxJava, or other. If you are interested in a lightweight, functional web framework for use with Java 8 lambdas or Kotlin then use the Spring WebFlux functional web endpoints. That can also be a good choice for smaller applications or microservices with less complex requirements that can benefit from greater transparency and control. In a microservice architecture you can have a mix of applications with either Spring MVC or Spring WebFlux controllers, or with Spring WebFlux functional endpoints. Having support for the same annotation-based programming model in both frameworks makes it easier to re-use knowledge while also selecting the right tool for the right job. A simple way to evaluate an application is to check its dependencies. If you have blocking persistence APIs (JPA, JDBC), or networking APIs to use, then Spring MVC is the best choice for common architectures at least. It is technically feasible with both Reactor and RxJava to perform blocking calls on a separate thread but you wouldn't be making the most of a non-blocking web stack. If you have a Spring MVC application with calls to remote services, try the reactive `WebClient`. You can return reactive types (Reactor, RxJava, <>) directly from Spring MVC controller methods. The greater the latency per call, or the interdependency among calls, the more dramatic the benefits. Spring MVC controllers can call other reactive components too. If you have a large team, keep in mind the steep learning curve in the shift to non-blocking, functional, and declarative programming. A practical way to start without a full switch is to use the reactive `WebClient`. Beyond that start small and measure the benefits. We expect that for a wide range of applications the shift is unnecessary. If you are unsure what benefits to look for, start by learning about how non-blocking I/O works (e.g. concurrency on single-threaded Node.js is not an oxymoron) and its effects. The tag line is ""scale with less hardware"" but that effect is not guaranteed, not without some network I/O that can be slow or unpredictable. This Netflix https://medium.com/netflix-techblog/zuul-2-the-netflix-journey-to-asynchronous-non-blocking-systems-45947377fb5c[blog post] is a good resource. [[webflux-server-choice]] === Choosing a server Spring WebFlux is supported on Netty, Undertow, Tomcat, Jetty, and Servlet 3.1+ containers. Each server is adapted to a common Reactive Streams API. The Spring WebFlux programming models are built on that common API. [NOTE] ==== *Common question: how can Tomcat and Jetty be used in both stacks?* + Tomcat and Jetty are non-blocking at their core. It's the Servlet API that adds a blocking facade. Starting in version 3.1 the Servlet API adds a choice for non-blocking I/O. However its use requires care to avoid other synchronous and blocking parts. For this reason Spring's reactive web stack has a low-level Servlet adapter to bridge to Reactive Streams but the Servlet API is otherwise not exposed for direct use. ==== Spring Boot 2 uses Netty by default with WebFlux because Netty is more widely used in the async, non-blocking space and also provides both client and server that can share resources. By comparison Servlet 3.1 non-blocking I/O hasn't seen much use because the bar to use it is so high. Spring WebFlux opens one practical path to adoption. The default server choice in Spring Boot is mainly about the out-of-the-box experience. Applications can still choose any of the other supported servers which are also highly optimized for performance, fully non-blocking, and adapted to Reactive Streams back pressure. In Spring Boot it is trivial to make the switch. [[webflux-performance]] === Performance vs scale Performance has many characteristics and meanings. Reactive and non-blocking generally do not make applications run faster. They can, in some cases, for example if using the `WebClient` to execute remote calls in parallel. On the whole it requires more work to do things the non-blocking way and that can increase slightly the required processing time. The key expected benefit of reactive and non-blocking is the ability to scale with a small, fixed number of threads and less memory. That makes applications more resilient under load because they scale in a more predictable way. In order to observe those benefits however you need to have some latency including a mix of slow and unpredictable network I/O. That's where the reactive stack begins to show its strengths and the differences can be dramatic. [[webflux-reactive-spring-web]] == Reactive Spring Web The `spring-web` module provides low level infrastructure and HTTP abstractions -- client and server, to build reactive web applications. All public APIs are build around Reactive Streams with Reactor as a backing implementation. Server support is organized in two layers: * <> and server adapters -- the most basic, common API for HTTP request handling with Reactive Streams back pressure. * <> -- slightly higher level but still general purpose server web API with filter chain style processing. [[webflux-httphandler]] === HttpHandler Every HTTP server has some API for HTTP request handling. {api-spring-framework}/http/server/reactive/HttpHandler.html[HttpHandler] is a simple contract with one method to handle a request and response. It is intentionally minimal. Its main purpose is to provide a common, Reactive Streams based API for HTTP request handling over different servers. The `spring-web` module contains adapters for every supported server. The table below shows the server APIs are used and where Reactive Streams support comes from: [cols=""1,2,2"", options=""header""] |=== |Server name|Server API used|Reactive Streams support |Netty |Netty API |https://github.com/reactor/reactor-netty[Reactor Netty] |Undertow |Undertow API |spring-web: Undertow to Reactive Streams bridge |Tomcat |Servlet 3.1 non-blocking I/O; Tomcat API to read and write ByteBuffers vs byte[] |spring-web: Servlet 3.1 non-blocking I/O to Reactive Streams bridge |Jetty |Servlet 3.1 non-blocking I/O; Jetty API to write ByteBuffers vs byte[] |spring-web: Servlet 3.1 non-blocking I/O to Reactive Streams bridge |Servlet 3.1 container |Servlet 3.1 non-blocking I/O |spring-web: Servlet 3.1 non-blocking I/O to Reactive Streams bridge |=== Here are required dependencies, https://github.com/spring-projects/spring-framework/wiki/What%27s-New-in-the-Spring-Framework[supported versions], and code snippets for each server: |=== |Server name|Group id|Artifact name |Reactor Netty |io.projectreactor.ipc |reactor-netty |Undertow |io.undertow |undertow-core |Tomcat |org.apache.tomcat.embed |tomcat-embed-core |Jetty |org.eclipse.jetty |jetty-server, jetty-servlet |=== Reactor Netty: [source,java,indent=0] [subs=""verbatim,quotes""] ---- HttpHandler handler = ... ReactorHttpHandlerAdapter adapter = new ReactorHttpHandlerAdapter(handler); HttpServer.create(host, port).newHandler(adapter).block(); ---- Undertow: [source,java,indent=0] [subs=""verbatim,quotes""] ---- HttpHandler handler = ... UndertowHttpHandlerAdapter adapter = new UndertowHttpHandlerAdapter(handler); Undertow server = Undertow.builder().addHttpListener(port, host).setHandler(adapter).build(); server.start(); ---- Tomcat: [source,java,indent=0] [subs=""verbatim,quotes""] ---- HttpHandler handler = ... Servlet servlet = new TomcatHttpHandlerAdapter(handler); Tomcat server = new Tomcat(); File base = new File(System.getProperty(""java.io.tmpdir"")); Context rootContext = server.addContext("""", base.getAbsolutePath()); Tomcat.addServlet(rootContext, ""main"", servlet); rootContext.addServletMappingDecoded(""/"", ""main""); server.setHost(host); server.setPort(port); server.start(); ---- Jetty: [source,java,indent=0] [subs=""verbatim,quotes""] ---- HttpHandler handler = ... Servlet servlet = new JettyHttpHandlerAdapter(handler); Server server = new Server(); ServletContextHandler contextHandler = new ServletContextHandler(server, """"); contextHandler.addServlet(new ServletHolder(servlet), ""/""); contextHandler.start(); ServerConnector connector = new ServerConnector(server); connector.setHost(host); connector.setPort(port); server.addConnector(connector); server.start(); ---- [NOTE] ==== To deploy as a WAR to a Servlet 3.1+ container, wrap `HttpHandler` with `ServletHttpHandlerAdapter` and register that as a `Servlet`. This can be automated through the use of {api-spring-framework}/web/server/adapter/AbstractReactiveWebInitializer.html[AbstractReactiveWebInitializer]. ==== [[webflux-web-handler-api]] === WebHandler API `HttpHandler` is the basis for running on different servers. On that base the WebHandler API provides a slightly higher level processing chain of exception handlers ({api-spring-framework}/web/server/WebExceptionHandler.html[WebExceptionHandler]), filters ({api-spring-framework}/web/server/WebFilter.html[WebFilter]), and a target handler ({api-spring-framework}/web/server/WebHandler.html[WebHandler]). All components work on `ServerWebExchange` -- a container for the HTTP request and response that also adds request attributes, session attributes, access to form data, multipart data, and more. The processing chain can be put together with `WebHttpHandlerBuilder` which builds an `HttpHandler` that in turn can be run with a <>. To use the builder either add components individually or point to an `ApplicationContext` to have the following detected: [cols=""2,2,1,3"", options=""header""] |=== |Bean name|Bean type|Count|Description |""webHandler"" |WebHandler |1 |Target handler after filters | |WebFilter |0..N |Filters | |WebExceptionHandler |0..N |Exception handlers after filter chain |""webSessionManager"" |WebSessionManager |0..1 |Custom session manager; `DefaultWebSessionManager` by default |""serverCodecConfigurer"" |ServerCodecConfigurer |0..1 |Custom form and multipart data decoders; `ServerCodecConfigurer.create()` by default |""localeContextResolver"" |LocaleContextResolver |0..1 |Custom resolver for `LocaleContext`; `AcceptHeaderLocaleContextResolver` by default |=== [[webflux-codecs]] === Codecs The `spring-web` module provides {api-spring-framework}/http/codec/HttpMessageReader.html[HttpMessageReader] and {api-spring-framework}/http/codec/HttpMessageWriter.html[HttpMessageWriter] for encoding and decoding the HTTP request and response body with Reactive Streams. It builds on lower level contracts from `spring-core`: * {api-spring-framework}/core/io/buffer/DataBuffer.html[DataBuffer] -- abstraction for byte buffers -- e.g. Netty `ByteBuf`, `java.nio.ByteBuffer`, see <>. * {api-spring-framework}/core/codec/Encoder.html[Encoder] -- serialize a stream of Objects to a stream of data buffers * {api-spring-framework}/core/codec/Decoder.html[Decoder] -- deserialize a stream of data buffers into a stream of Objects Basic `Encoder` and `Decoder` implementations exist in `spring-core` but `spring-web` adds more for JSON, XML, and other formats. You can wrap any `Encoder` and `Decoder` as a reader or writer with `EncoderHttpMessageWriter` and `DecoderHttpMessageReader`. There are some additional, web-only reader and writer implementations for server-sent events, form data, and more. Finally, `ClientCodecConfigurer` and `ServerCodecConfigurer` can be used to initialize a list of readers and writers. They include support for classpath detection and a of defaults along with the ability to override or replace those defaults. [[webflux-dispatcher-handler]] == DispatcherHandler [.small]#<># Spring WebFlux, like Spring MVC, is designed around the front controller pattern where a central `WebHandler`, the `DispatcherHandler`, provides a shared algorithm for request processing while actual work is performed by configurable, delegate components. This model is flexible and supports diverse workflows. `DispatcherHandler` discovers the delegate components it needs from Spring configuration. It is also designed to be a Spring bean itself and implements `ApplicationContextAware` for access to the context it runs in. If `DispatcherHandler` is declared with the bean name ""webHandler"" it is in turn discovered by {api-spring-framework}/web/server/adapter/WebHttpHandlerBuilder.html[WebHttpHandlerBuilder] which puts together a request processing chain as described in <>. Spring configuration in a WebFlux application typically contains: * `DispatcherHandler` with the bean name ""webHandler"" * `WebFilter` and `WebExceptionHandler` beans * <> * Others The configuration is given to `WebHttpHandlerBuilder` to build the processing chain: [source,java,indent=0] [subs=""verbatim,quotes""] ---- ApplicationContext context = ... HttpHandler handler = WebHttpHandlerBuilder.applicationContext(context); ---- The resulting `HttpHandler` is ready for use with a <>. [[webflux-special-bean-types]] === Special bean types [.small]#<># The `DispatcherHandler` delegates to special beans to process requests and render the appropriate responses. By ""special beans"" we mean Spring-managed Object instances that implement one of the framework contracts listed in the table below. Spring WebFlux provides built-in implementations of these contracts but you can also customize, extend, or replace them. [[webflux-special-beans-table]] [cols=""1,2"", options=""header""] |=== | Bean type| Explanation | HandlerMapping | Map a request to a handler. The mapping is based on some criteria the details of which vary by `HandlerMapping` implementation -- annotated controllers, simple URL pattern mappings, etc. The main `HandlerMapping` implementations are `RequestMappingHandlerMapping` based on `@RequestMapping` annotated methods, `RouterFunctionMapping` based on functional endpoint routes, and `SimpleUrlHandlerMapping` based on explicit registrations of URI path patterns to handlers. | HandlerAdapter | Help the `DispatcherHandler` to invoke a handler mapped to a request regardless of how the handler is actually invoked. For example invoking an annotated controller requires resolving annotations. The main purpose of a `HandlerAdapter` is to shield the `DispatcherHandler` from such details. | HandlerResultHandler | Process the result from the handler invocation and finalize the response. The built-in `HandlerResultHandler` implementations are `ResponseEntityResultHandler` supporting `ResponseEntity` return values, `ResponseBodyResultHandler` supporting `@ResponseBody` methods, `ServerResponseResultHandler` supporting the `ServerResponse` returned from functional endpoints, and `ViewResolutionResultHandler` supporting rendering with a view and a model. |=== [[webflux-framework-config]] === Framework Config [.small]#<># The `DispatcherHandler` detects the special beans it needs in the `ApplicationContext`. Applications can declare the special beans they wish to have. However most applications will find a better starting point in the WebFlux Java config which provide a higher level configuration API that in turn make the necessary bean declarations. See <> for more details. [[webflux-dispatcher-handler-sequence]] === Processing [.small]#<># The `DispatcherHandler` processes requests as follows: * Each `HandlerMapping` is asked to find a matching handler and the first match is used. * If a handler is found, it is executed through an appropriate `HandlerAdapter` which exposes the return value from the execution as `HandlerResult`. * The `HandlerResult` is given to an appropriate `HandlerResultHandler` to complete processing by writing to the response directly or using a view to render. [[webflux-controller]] == Annotated Controllers [.small]#<># Spring WebFlux provides an annotation-based programming model where `@Controller` and `@RestController` components use annotations to express request mappings, request input, exception handling, and more. Annotated controllers have flexible method signatures and do not have to extend base classes nor implement specific interfaces. Here is a basic example: [source,java,indent=0] [subs=""verbatim,quotes""] ---- @RestController public class HelloController { @GetMapping(""/hello"") public String handle() { return ""Hello WebFlux""; } } ---- In this example the methods returns a String to be written to the response body. [[webflux-ann-controller]] === @Controller [.small]#<># You can define controller beans using a standard Spring bean definition. The `@Controller` stereotype allows for auto-detection, aligned with Spring general support for detecting `@Component` classes in the classpath and auto-registering bean definitions for them. It also acts as a stereotype for the annotated class, indicating its role as a web component. To enable auto-detection of such `@Controller` beans, you can add component scanning to your Java configuration: [source,java,indent=0] [subs=""verbatim,quotes""] ---- @Configuration @ComponentScan(""org.example.web"") public class WebConfig { // ... } ---- `@RestController` is a composed annotation that is itself annotated with `@Controller` and `@ResponseBody` indicating a controller whose every method inherits the type-level `@ResponseBody` annotation and therefore writes to the response body (vs model-and-vew rendering). [[webflux-ann-requestmapping]] === Request Mapping [.small]#<># The `@RequestMapping` annotation is used to map requests to controllers methods. It has various attributes to match by URL, HTTP method, request parameters, headers, and media types. It can be used at the class-level to express shared mappings or at the method level to narrow down to a specific endpoint mapping. There are also HTTP method specific shortcut variants of `@RequestMapping`: - `@GetMapping` - `@PostMapping` - `@PutMapping` - `@DeleteMapping` - `@PatchMapping` The shortcut variants are https://github.com/spring-projects/spring-framework/wiki/Spring-Annotation-Programming-Model#composed-annotations[composed annotations] -- themselves annotated with `@RequestMapping`. They are commonly used at the method level. At the class level an `@RequestMapping` is more useful for expressing shared mappings. [source,java,indent=0] [subs=""verbatim,quotes""] ---- @RestController @RequestMapping(""/persons"") class PersonController { @GetMapping(""/{id}"") public Person getPerson(@PathVariable Long id) { // ... } @PostMapping @ResponseStatus(HttpStatus.CREATED) public void add(@RequestBody Person person) { // ... } } ---- [[webflux-ann-requestmapping-uri-templates]] ==== URI Patterns [.small]#<># You can map requests using glob patterns and wildcards: * `?` matches one character * `*` matches zero or more characters within a path segment * `**` match zero or more path segments You can also declare URI variables and access their values with `@PathVariable`: [source,java,indent=0] [subs=""verbatim,quotes""] ---- @GetMapping(""/owners/{ownerId}/pets/{petId}"") public Pet findPet(@PathVariable Long ownerId, @PathVariable Long petId) { // ... } ---- URI variables can be declared at the class and method level: [source,java,intent=0] [subs=""verbatim,quotes""] ---- @Controller @RequestMapping(""/owners/{ownerId}"") public class OwnerController { @GetMapping(""/pets/{petId}"") public Pet findPet(@PathVariable Long ownerId, @PathVariable Long petId) { // ... } } ---- URI variables are automatically converted to the appropriate type or`TypeMismatchException` is raised. Simple types -- `int`, `long`, `Date`, are supported by default and you can register support for any other data type. // TODO: see <> and <>. URI variables can be named explicitly -- e.g. `@PathVariable(""customId"")`, but you can leave that detail out if the names are the same and your code is compiled with debugging information or with the `-parameters` compiler flag on Java 8. The syntax `{*varName}` declares a URI variable that matches zero or more remaining path segments. For example `/resources/{*path}` matches all files `/resources/` and the `""path""` variable captures the complete relative path. The syntax `{varName:regex}` declares a URI variable with a regular expressions with the syntax `{varName:regex}` -- e.g. given URL `""/spring-web-3.0.5 .jar""`, the below method extracts the name, version, and file extension: [source,java,indent=0] [subs=""verbatim,quotes""] ---- @GetMapping(""/{name:[a-z-]+}-{version:\\\\d\\\\.\\\\d\\\\.\\\\d}{ext:\\\\.[a-z]+}"") public void handle(@PathVariable String version, @PathVariable String ext) { // ... } ---- URI path patterns can also have embedded `${...}` placeholders that are resolved on startup via `PropertyPlaceHolderConfigurer` against local, system, environment, and other property sources. This can be used for example to parameterize a base URL based on some external configuration. [NOTE] ==== Spring WebFlux uses `PathPattern` and the `PathPatternParser` for URI path matching support both of which are located in `spring-web` and expressly designed for use with HTTP URL paths in web applications where a large number of URI path patterns are matched at runtime. ==== Spring WebFlux does not support suffix pattern matching -- unlike Spring MVC, where a mapping such as `/person` also matches to `/person.{asterisk}`. For URL based content negotiation, if needed, we recommend using a query parameter, which is simpler, more explicit, and less vulnerable to URL path based exploits. [[webflux-ann-requestmapping-pattern-comparison]] ==== Pattern Comparison [.small]#<># When multiple patterns match a URL, they must be compared to find the best match. This is done with `PathPattern.SPECIFICITY_COMPARATOR` which looks for patterns that more specific. For every pattern, a score is computed based the number of URI variables and wildcards where a URI variable scores lower than a wildcard. A pattern with a lower total score wins. If two patterns have the same score, then the longer is chosen. Catch-all patterns, e.g. `**`, `{*varName}`, are excluded from the scoring and are always sorted last instead. If two patterns are both catch-all, the longer is chosen. [[webflux-ann-requestmapping-consumes]] ==== Consumable Media Types [.small]#<># You can narrow the request mapping based on the `Content-Type` of the request: [source,java,indent=0] [subs=""verbatim,quotes""] ---- @PostMapping(path = ""/pets"", **consumes = ""application/json""**) public void addPet(@RequestBody Pet pet) { // ... } ---- The consumes attribute also supports negation expressions -- e.g. `!text/plain` means any content type other than ""text/plain"". You can declare a shared consumes attribute at the class level. Unlike most other request mapping attributes however when used at the class level, a method-level consumes attribute will overrides rather than extend the class level declaration. [TIP] ==== `MediaType` provides constants for commonly used media types -- e.g. `APPLICATION_JSON_VALUE`, `APPLICATION_JSON_UTF8_VALUE`. ==== [[webflux-ann-requestmapping-produces]] ==== Producible Media Types [.small]#<># You can narrow the request mapping based on the `Accept` request header and the list of content types that a controller method produces: [source,java,indent=0] [subs=""verbatim,quotes""] ---- @GetMapping(path = ""/pets/{petId}"", **produces = ""application/json;charset=UTF-8""**) @ResponseBody public Pet getPet(@PathVariable String petId) { // ... } ---- The media type can specify a character set. Negated expressions are supported -- e.g. `!text/plain` means any content type other than ""text/plain"". You can declare a shared produces attribute at the class level. Unlike most other request mapping attributes however when used at the class level, a method-level produces attribute will overrides rather than extend the class level declaration. [TIP] ==== `MediaType` provides constants for commonly used media types -- e.g. `APPLICATION_JSON_VALUE`, `APPLICATION_JSON_UTF8_VALUE`. ==== [[webflux-ann-requestmapping-params-and-headers]] ==== Parameters and Headers [.small]#<># You can narrow request mappings based on query parameter conditions. You can test for the presence of a query parameter (`""myParam""`), for the absence (`""!myParam""`), or for a specific value (`""myParam=myValue""`): [source,java,indent=0] [subs=""verbatim,quotes""] ---- @GetMapping(path = ""/pets/{petId}"", **params = ""myParam=myValue""**) public void findPet(@PathVariable String petId) { // ... } ---- You can also use the same with request header conditions: [source,java,indent=0] [subs=""verbatim,quotes""] ---- @GetMapping(path = ""/pets"", **headers = ""myHeader=myValue""**) public void findPet(@PathVariable String petId) { // ... } ---- [[webflux-ann-requestmapping-head-options]] ==== HTTP HEAD, OPTIONS [.small]#<># `@GetMapping` -- and also `@RequestMapping(method=HttpMethod.GET)`, support HTTP HEAD transparently for request mapping purposes. Controller methods don't need to change. A response wrapper, applied in the `HttpHandler` server adapter, ensures a `""Content-Length""` header is set to the number of bytes written and without actually writing to the response. By default HTTP OPTIONS is handled by setting the ""Allow"" response header to the list of HTTP methods listed in all `@RequestMapping` methods with matching URL patterns. For a `@RequestMapping` without HTTP method declarations, the ""Allow"" header is set to `""GET,HEAD,POST,PUT,PATCH,DELETE,OPTIONS""`. Controller methods should always declare the supported HTTP methods for example by using the HTTP method specific variants -- `@GetMapping`, `@PostMapping`, etc. `@RequestMapping` method can be explicitly mapped to HTTP HEAD and HTTP OPTIONS, but that is not necessary in the common case. [[webflux-ann-methods]] === Handler methods [.small]#<># `@RequestMapping` handler methods have a flexible signature and can choose from a range of supported controller method arguments and return values. [[webflux-ann-arguments]] ==== Method arguments [.small]#<># The table below shows supported controller method arguments. Reactive types (Reactor, RxJava, <>) are supported on arguments that require blocking I/O, e.g. reading the request body, to be resolved. This is marked in the description column. Reactive types are not expected on arguments that don't require blocking. JDK 1.8's `java.util.Optional` is supported as a method argument in combination with annotations that have a `required` attribute -- e.g. `@RequestParam`, `@RequestHeader`, etc, and is equivalent to `required=false`. [cols=""1,2"", options=""header""] |=== |Controller method argument|Description |`ServerWebExchange` |Access to the full `ServerWebExchange` -- container for the HTTP request and response, request and session attributes, `checkNotModified` methods, and others. |`ServerHttpRequest`, `ServerHttpResponse` |Access to the HTTP request or response. |`WebSession` |Access to the session; this does not forcing the start of a new session unless attributes are added. Supports reactive types. |`java.security.Principal` |Currently authenticated user; possibly a specific `Principal` implementation class if known. Supports reactive types. |`org.springframework.http.HttpMethod` |The HTTP method of the request. |`java.util.Locale` |The current request locale, determined by the most specific `LocaleResolver` available, in effect, the configured `LocaleResolver`/`LocaleContextResolver`. |Java 6+: `java.util.TimeZone` + Java 8+: `java.time.ZoneId` |The time zone associated with the current request, as determined by a `LocaleContextResolver`. |`@PathVariable` |For access to URI template variables. // TODO: See <>. |`@MatrixVariable` |For access to name-value pairs in URI path segments. // TODO: See <>. |`@RequestParam` |For access to Servlet request parameters. Parameter values are converted to the declared method argument type. // TODO: See <>. |`@RequestHeader` |For access to request headers. Header values are converted to the declared method argument type. // TODO: See <>. |`@RequestBody` |For access to the HTTP request body. Body content is converted to the declared method argument type using ``HttpMessageReader``'s. Supports reactive types. // TODO: See <>. |`HttpEntity` |For access to request headers and body. The body is converted with ``HttpMessageReader``'s. Supports reactive types. // TODO: See <>. |`@RequestPart` |For access to a part in a ""multipart/form-data"" request. Supports reactive types. // TODO: See <> and <>. |`java.util.Map`, `org.springframework.ui.Model`, `org.springframework.ui.ModelMap` |For access and updates of the implicit model that is exposed to the web view. |Command or form object (with optional `@ModelAttribute`) |Command object whose properties to bind to request parameters -- via setters or directly to fields, with customizable type conversion, depending on `@InitBinder` methods and/or the HandlerAdapter configuration (see the `webBindingInitializer` property on `RequestMappingHandlerAdapter`). Command objects along with their validation results are exposed as model attributes, by default using the command class name - e.g. model attribute ""orderAddress"" for a command object of type ""some.package.OrderAddress"". `@ModelAttribute` can be used to customize the model attribute name. Supports reactive types. |`Errors`, `BindingResult` |Validation results for the command/form object data binding; this argument must be declared immediately after the command/form object in the controller method signature. |`SessionStatus` |For marking form processing complete which triggers cleanup of session attributes declared through a class-level `@SessionAttributes` annotation. |`UriComponentsBuilder` |For preparing a URL relative to the current request's host, port, scheme, context path, and the literal part of the servlet mapping also taking into account `Forwarded` and `X-Forwarded-*` headers. |`@SessionAttribute` |For access to any session attribute; in contrast to model attributes stored in the session as a result of a class-level `@SessionAttributes` declaration. |`@RequestAttribute` |For access to request attributes. |=== [[webflux-ann-return-types]] ==== Return values [.small]#<># The table below shows supported controller method return values. Reactive types -- Reactor, RxJava, <> are supported for all return values. [cols=""1,2"", options=""header""] |=== |Controller method return value|Description |`@ResponseBody` |The return value is encoded through ``HttpMessageWriter``s and written to the response. // TODO: See <>. |`HttpEntity`, `ResponseEntity` |The return value specifies the full response including HTTP headers and body be encoded through ``HttpMessageWriter``s and written to the response. // TODO: See <>. |`HttpHeaders` |For returning a response with headers and no body. |`String` |A view name to be resolved with ``ViewResolver``'s and used together with the implicit model -- determined through command objects and `@ModelAttribute` methods. The handler method may also programmatically enrich the model by declaring a `Model` argument (see above). |`View` |A `View` instance to use for rendering together with the implicit model -- determined through command objects and `@ModelAttribute` methods. The handler method may also programmatically enrich the model by declaring a `Model` argument (see above). |`java.util.Map`, `org.springframework.ui.Model` |Attributes to be added to the implicit model with the view name implicitly determined from the request path. |`Rendering` |An API for model and view rendering scenarios. |`void` |A method with a `void`, possibly async (e.g. `Mono`), return type (or a `null` return value) is considered to have fully handled the response if it also has a `ServerHttpResponse`, or a `ServerWebExchange` argument, or an `@ResponseStatus` annotation. The same is true also if the controller has made a positive ETag or lastModified timestamp check. // TODO (see <> for details) If none of the above is true, a `void` return type may also indicate ""no response body"" for REST controllers, or default view name selection for HTML controllers. |`Flux`, `Observable`, or other reactive type |Emit server-sent events; the `SeverSentEvent` wrapper can be omitted when only data needs to be written (however `text/event-stream` must be requested or declared in the mapping through the produces attribute). |Any other return type |A single model attribute to be added to the implicit model with the view name implicitly determined through a `RequestToViewNameTranslator`; the attribute name may be specified through a method-level `@ModelAttribute` or otherwise a name is selected based on the class name of the return type. |=== include::webflux-functional.adoc[leveloffset=+1] [[webflux-config]] == WebFlux Java Config [.small]#<># The WebFlux Java config provides default configuration suitable for most applications along with a configuration API to customize it. For more advanced customizations, not available in the configuration API, see <>. You do not need to understand the underlying beans created by the Java config, but it's easy to seem them in `WebFluxConfigurationSupport`, and if you want to learn more, see <>. [[webflux-config-enable]] === Enable WebFlux config [.small]#<># Use the `@EnableWebFlux` annotation in your Java config: [source,java,indent=0] [subs=""verbatim,quotes""] ---- @Configuration @EnableWebFlux public class WebConfig { } ---- The above registers a number of Spring WebFlux <> also adapting to dependencies available on the classpath -- for JSON, XML, etc. [[webflux-config-customize]] === WebFlux config API [.small]#<># In your Java config implement the `WebFluxConfigurer` interface: [source,java,indent=0] [subs=""verbatim,quotes""] ---- @Configuration @EnableWebFlux public class WebConfig implements WebFluxConfigurer { // Implement configuration methods... } ---- [[webflux-config-conversion]] === Conversion, formatting [.small]#<># By default formatters for `Number` and `Date` types are installed, including support for the `@NumberFormat` and `@DateTimeFormat` annotations. Full support for the Joda Time formatting library is also installed if Joda Time is present on the classpath. To register custom formatters and converters: [source,java,indent=0] [subs=""verbatim,quotes""] ---- @Configuration @EnableWebFlux public class WebConfig implements WebFluxConfigurer { @Override public void addFormatters(FormatterRegistry registry) { // ... } } ---- [NOTE] ==== See <> and the `FormattingConversionServiceFactoryBean` for more information on when to use FormatterRegistrars. ==== [[webflux-config-validation]] === Validation [.small]#<># By default if <> is present on the classpath -- e.g. Hibernate Validator, the `LocalValidatorFactoryBean` is registered as a global <> for use with `@Valid` and `Validated` on `@Controller` method arguments. In your Java config, you can customize the global `Validator` instance: [source,java,indent=0] [subs=""verbatim,quotes""] ---- @Configuration @EnableWebFlux public class WebConfig implements WebFluxConfigurer { @Override public Validator getValidator(); { // ... } } ---- Note that you can also register ``Validator``'s locally: [source,java,indent=0] [subs=""verbatim,quotes""] ---- @Controller public class MyController { @InitBinder protected void initBinder(WebDataBinder binder) { binder.addValidators(new FooValidator()); } } ---- [TIP] ==== If you need to have a `LocalValidatorFactoryBean` injected somewhere, create a bean and mark it with `@Primary` in order to avoid conflict with the one declared in the MVC config. ==== [[webflux-config-content-negotiation]] === Content type resolvers [.small]#<># You can configure how Spring WebFlux determines the requested media types for ``@Controller``'s from the request. By default only the ""Accept"" header is checked but you can also enable a query parameter based strategy. To customize the requested content type resolution: [source,java,indent=0] [subs=""verbatim,quotes""] ---- @Configuration @EnableWebFlux public class WebConfig implements WebFluxConfigurer { @Override public void configureContentTypeResolver(RequestedContentTypeResolverBuilder builder) { // ... } } ---- [[webflux-config-message-codecs]] === HTTP message codecs [.small]#<># To customize how the request and response body are read and written: [source,java,indent=0] [subs=""verbatim,quotes""] ---- @Configuration @EnableWebFlux public class WebConfig implements WebFluxConfigurer { @Override public void configureHttpMessageCodecs(ServerCodecConfigurer configurer) { // ... } } ---- `ServerCodecConfigurer` provides a set of default readers and writers. You can use it to add more readers and writers, customize the default ones, or replace the default ones completely. For Jackson JSON and XML, consider using the {api-spring-framework}/http/converter/json/Jackson2ObjectMapperBuilder.html[Jackson2ObjectMapperBuilder] which customizes Jackson's default properties with the following ones: . http://fasterxml.github.io/jackson-databind/javadoc/2.6/com/fasterxml/jackson/databind/DeserializationFeature.html#FAIL_ON_UNKNOWN_PROPERTIES[`DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES`] is disabled. . http://fasterxml.github.io/jackson-databind/javadoc/2.6/com/fasterxml/jackson/databind/MapperFeature.html#DEFAULT_VIEW_INCLUSION[`MapperFeature.DEFAULT_VIEW_INCLUSION`] is disabled. It also automatically registers the following well-known modules if they are detected on the classpath: . https://github.com/FasterXML/jackson-datatype-jdk7[jackson-datatype-jdk7]: support for Java 7 types like `java.nio.file.Path`. . https://github.com/FasterXML/jackson-datatype-joda[jackson-datatype-joda]: support for Joda-Time types. . https://github.com/FasterXML/jackson-datatype-jsr310[jackson-datatype-jsr310]: support for Java 8 Date & Time API types. . https://github.com/FasterXML/jackson-datatype-jdk8[jackson-datatype-jdk8]: support for other Java 8 types like `Optional`. [[webflux-config-view-resolvers]] === View resolvers [.small]#<># To configure view resolution: [source,java,indent=0] [subs=""verbatim,quotes""] ---- @Configuration @EnableWebFlux public class WebConfig implements WebFluxConfigurer { @Override public void configureViewResolvers(ViewResolverRegistry registry) { // ... } } ---- Note that FreeMarker also requires configuration of the underlying view technology: [source,java,indent=0] [subs=""verbatim,quotes""] ---- @Configuration @EnableWebFlux public class WebConfig implements WebFluxConfigurer { // ... @Bean public FreeMarkerConfigurer freeMarkerConfigurer() { FreeMarkerConfigurer configurer = new FreeMarkerConfigurer(); configurer.setTemplateLoaderPath(""classpath:/templates""); return configurer; } } ---- [[webflux-config-static-resources]] === Static resources [.small]#<># This option provides a convenient way to serve static resources from a list of {api-spring-framework}/core/io/Resource.html[Resource]-based locations. In the example below, given a request that starts with `""/resources""`, the relative path is used to find and serve static resources relative to `""/static""` on the classpath. Resources will be served with a 1-year future expiration to ensure maximum use of the browser cache and a reduction in HTTP requests made by the browser. The `Last-Modified` header is also evaluated and if present a `304` status code is returned. [source,java,indent=0] [subs=""verbatim""] ---- @Configuration @EnableWebFlux public class WebConfig implements WebFluxConfigurer { @Override public void addResourceHandlers(ResourceHandlerRegistry registry) { registry.addResourceHandler(""/resources/**"") .addResourceLocations(""/public"", ""classpath:/static/"") .setCachePeriod(31556926); } } ---- // TODO: // See also <>. The resource handler also supports a chain of {api-spring-framework}/web/reactive/resource/ResourceResolver.html[ResourceResolver]'s and {api-spring-framework}/web/reactive/resource/ResourceTransformer.html[ResourceTransformer]'s. which can be used to create a toolchain for working with optimized resources. The `VersionResourceResolver` can be used for versioned resource URLs based on an MD5 hash computed from the content, a fixed application version, or other. A `ContentVersionStrategy` (MD5 hash) is a good choice with some notable exceptions such as JavaScript resources used with a module loader. For example in your Java config; [source,java,indent=0] [subs=""verbatim""] ---- @Configuration @EnableWebFlux public class WebConfig implements WebFluxConfigurer { @Override public void addResourceHandlers(ResourceHandlerRegistry registry) { registry.addResourceHandler(""/resources/**"") .addResourceLocations(""/public/"") .resourceChain(true) .addResolver(new VersionResourceResolver().addContentVersionStrategy(""/**"")); } } ---- You can use `ResourceUrlProvider` to rewrite URLs and apply the full chain of resolvers and transformers -- e.g. to insert versions. The WebFlux config provides a `ResourceUrlProvider` so it can be injected into others. Unlike Spring MVC at present in WebFlux there is no way to transparely rewrite static resource URLs since the are no view technologies that can make use of a non-blocking chain of resolvers and transformers (e.g. resources on Amazon S3). When serving only local resources the workaround is to use `ResourceUrlProvider` directly (e.g. through a custom tag) and block for 0 seconds. http://www.webjars.org/documentation[WebJars] is also supported via `WebJarsResourceResolver` and automatically registered when `""org.webjars:webjars-locator""` is present on the classpath. The resolver can re-write URLs to include the version of the jar and can also match to incoming URLs without versions -- e.g. `""/jquery/jquery.min.js""` to `""/jquery/1.2.0/jquery.min.js""`. [[webflux-config-path-matching]] === Path Matching [.small]#<># Spring WebFlux uses parsed representation of path patterns -- i.e. `PathPattern`, and also the incoming request path -- i.e. `RequestPath`, which eliminates the need to indicate whether to decode the request path, or remove semicolon content, since `PathPattern` can now access decoded path segment values and match safely. Spring WebFlux also does not support suffix pattern matching so effectively there are only two minor options to customize related to path matching -- whether to match trailing slashes (`true` by default) and whether the match is case-sensitive (`false`). To customize those options: [source,java,indent=0] [subs=""verbatim,quotes""] ---- @Configuration @EnableWebFlux public class WebConfig implements WebFluxConfigurer { @Override public void configurePathMatch(PathMatchConfigurer configurer) { // ... } } ---- [[webflux-config-advanced-java]] === Advanced config mode [.small]#<># `@EnableWebFlux` imports `DelegatingWebFluxConfiguration` that (1) provides default Spring configuration for WebFlux applications and (2) detects and delegates to ``WebFluxConfigurer``'s to customize that configuration. For advanced mode, remove `@EnableWebFlux` and extend directly from `DelegatingWebFluxConfiguration` instead of implementing `WebFluxConfigurer`: [source,java,indent=0] [subs=""verbatim,quotes""] ---- @Configuration public class WebConfig extends DelegatingWebFluxConfiguration { // ... } ---- You can keep existing methods in `WebConfig` but you can now also override bean declarations from the base class and you can still have any number of other ``WebMvcConfigurer``'s on the classpath. include::webflux-cors.adoc[leveloffset=+1] [[webflux-http2]] == HTTP/2 [.small]#<># Servlet 4 containers are required to support HTTP/2 and Spring Framework 5 is compatible with Servlet API 4. From a programming model perspective there is nothing specific that applications need to do. However there are considerations related to server configuration. For more details please check out the https://github.com/spring-projects/spring-framework/wiki/HTTP-2-support[HTTP/2 wiki page]. Currently Spring WebFlux does not support HTTP/2 with Netty. There is also no support for pushing resources programmatically to the client. ",12494,False,1966.7805269211672,median " #include ""Globals.h"" // NOTE: MSVC stupidness requires this to be the same across all modules #ifndef _WIN32 #include #endif #include ""Chunk.h"" #include ""BlockInfo.h"" #include ""World.h"" #include ""ClientHandle.h"" #include ""Server.h"" #include ""Defines.h"" #include ""BlockEntities/BeaconEntity.h"" #include ""BlockEntities/BedEntity.h"" #include ""BlockEntities/BrewingstandEntity.h"" #include ""BlockEntities/ChestEntity.h"" #include ""BlockEntities/CommandBlockEntity.h"" #include ""BlockEntities/DispenserEntity.h"" #include ""BlockEntities/DropperEntity.h"" #include ""BlockEntities/FlowerPotEntity.h"" #include ""BlockEntities/FurnaceEntity.h"" #include ""BlockEntities/HopperEntity.h"" #include ""BlockEntities/JukeboxEntity.h"" #include ""BlockEntities/MobHeadEntity.h"" #include ""BlockEntities/MobSpawnerEntity.h"" #include ""BlockEntities/NoteEntity.h"" #include ""BlockEntities/SignEntity.h"" #include ""Entities/Pickup.h"" #include ""Item.h"" #include ""Noise/Noise.h"" #include ""Root.h"" #include ""Entities/Player.h"" #include ""BlockArea.h"" #include ""Bindings/PluginManager.h"" #include ""Blocks/BlockHandler.h"" #include ""Simulator/FluidSimulator.h"" #include ""MobCensus.h"" #include ""MobSpawner.h"" #include ""BlockInServerPluginInterface.h"" #include ""SetChunkData.h"" #include ""BoundingBox.h"" #include ""Blocks/ChunkInterface.h"" #include ""json/json.h"" //////////////////////////////////////////////////////////////////////////////// // cChunk: cChunk::cChunk( int a_ChunkX, int a_ChunkZ, cChunkMap * a_ChunkMap, cWorld * a_World, cAllocationPool & a_Pool ): m_Presence(cpInvalid), m_IsLightValid(false), m_IsDirty(false), m_IsSaving(false), m_HasLoadFailed(false), m_StayCount(0), m_PosX(a_ChunkX), m_PosZ(a_ChunkZ), m_World(a_World), m_ChunkMap(a_ChunkMap), m_ChunkData(a_Pool), m_WaterSimulatorData(a_World->GetWaterSimulator()->CreateChunkData()), m_LavaSimulatorData (a_World->GetLavaSimulator ()->CreateChunkData()), m_RedstoneSimulatorData(a_World->GetRedstoneSimulator()->CreateChunkData()), m_AlwaysTicked(0) { m_NeighborXM = a_ChunkMap->FindChunk(a_ChunkX - 1, a_ChunkZ); m_NeighborXP = a_ChunkMap->FindChunk(a_ChunkX + 1, a_ChunkZ); m_NeighborZM = a_ChunkMap->FindChunk(a_ChunkX, a_ChunkZ - 1); m_NeighborZP = a_ChunkMap->FindChunk(a_ChunkX, a_ChunkZ + 1); if (m_NeighborXM != nullptr) { m_NeighborXM->m_NeighborXP = this; } if (m_NeighborXP != nullptr) { m_NeighborXP->m_NeighborXM = this; } if (m_NeighborZM != nullptr) { m_NeighborZM->m_NeighborZP = this; } if (m_NeighborZP != nullptr) { m_NeighborZP->m_NeighborZM = this; } } cChunk::~cChunk() { // LOGINFO(""### delete cChunk() (%i, %i) from %p, thread 0x%x ###"", m_PosX, m_PosZ, this, GetCurrentThreadId()); // Inform our neighbours that we're no longer valid: if (m_NeighborXM != nullptr) { m_NeighborXM->m_NeighborXP = nullptr; } if (m_NeighborXP != nullptr) { m_NeighborXP->m_NeighborXM = nullptr; } if (m_NeighborZM != nullptr) { m_NeighborZM->m_NeighborZP = nullptr; } if (m_NeighborZP != nullptr) { m_NeighborZP->m_NeighborZM = nullptr; } delete m_WaterSimulatorData; m_WaterSimulatorData = nullptr; delete m_LavaSimulatorData; m_LavaSimulatorData = nullptr; delete m_RedstoneSimulatorData; m_RedstoneSimulatorData = nullptr; } void cChunk::SetPresence(cChunk::ePresence a_Presence) { m_Presence = a_Presence; if (a_Presence == cpPresent) { m_World->GetChunkMap()->ChunkValidated(); } } void cChunk::MarkRegenerating(void) { // Set as queued again: SetPresence(cpQueued); // Tell all clients attached to this chunk that they want this chunk: for (auto ClientHandle : m_LoadedByClient) { ClientHandle->AddWantedChunk(m_PosX, m_PosZ); } // for itr - m_LoadedByClient[] } bool cChunk::HasPlayerEntities() const { return std::any_of( m_Entities.begin(), m_Entities.end(), [](const auto & Entity) { return Entity->IsPlayer(); } ); } bool cChunk::CanUnload(void) const { return m_LoadedByClient.empty() && // The chunk is not used by any client !HasPlayerEntities() && // Ensure not only the absence of ClientHandlers, but also of cPlayer objects !m_IsDirty && // The chunk has been saved properly or hasn't been touched since the load / gen (m_StayCount == 0) && // The chunk is not in a ChunkStay (m_Presence != cpQueued) ; // The chunk is not queued for loading / generating (otherwise multi-load / multi-gen could occur) } bool cChunk::CanUnloadAfterSaving(void) const { return m_LoadedByClient.empty() && // The chunk is not used by any client !HasPlayerEntities() && // Ensure not only the absence of ClientHandlers, but also of cPlayer objects m_IsDirty && // The chunk is dirty (m_StayCount == 0) && // The chunk is not in a ChunkStay (m_Presence != cpQueued) ; // The chunk is not queued for loading / generating (otherwise multi-load / multi-gen could occur) } void cChunk::OnUnload() { // Note: this is only called during normal operation, not during shutdown // Notify all entities of imminent unload: for (auto & Entity : m_Entities) { // Chunks cannot be unloaded when they still contain players: ASSERT(!Entity->IsPlayer()); // Notify the entity: Entity->OnRemoveFromWorld(*Entity->GetWorld()); } // Notify all block entities of imminent unload: for (auto & BlockEntity : m_BlockEntities) { BlockEntity.second->OnRemoveFromWorld(); } } void cChunk::MarkSaving(void) { m_IsSaving = true; } void cChunk::MarkSaved(void) { if (!m_IsSaving) { return; } m_IsDirty = false; } void cChunk::MarkLoaded(void) { m_IsDirty = false; SetPresence(cpPresent); } void cChunk::MarkLoadFailed(void) { ASSERT(m_Presence == cpQueued); // Mark dirty before generating, so that we get saved and don't have to later generate again: MarkDirty(); // The chunk is always needed, generate it: m_World->GetGenerator().QueueGenerateChunk({m_PosX, m_PosZ}, false); } void cChunk::GetAllData(cChunkDataCallback & a_Callback) const { ASSERT(m_Presence == cpPresent); a_Callback.HeightMap(&m_HeightMap); a_Callback.BiomeData(&m_BiomeMap); a_Callback.LightIsValid(m_IsLightValid); a_Callback.ChunkData(m_ChunkData); for (const auto & Entity : m_Entities) { a_Callback.Entity(Entity.get()); } for (auto & KeyPair : m_BlockEntities) { a_Callback.BlockEntity(KeyPair.second.get()); } } void cChunk::SetAllData(cSetChunkData & a_SetChunkData) { ASSERT(a_SetChunkData.IsHeightMapValid()); ASSERT(a_SetChunkData.AreBiomesValid()); memcpy(m_BiomeMap, a_SetChunkData.GetBiomes(), sizeof(m_BiomeMap)); memcpy(m_HeightMap, a_SetChunkData.GetHeightMap(), sizeof(m_HeightMap)); m_ChunkData.Assign(std::move(a_SetChunkData.GetChunkData())); m_IsLightValid = a_SetChunkData.IsLightValid(); // Entities need some extra steps to destroy, so here we're keeping the old ones. // Move the entities already in the chunk, including player entities, so that we don't lose any: a_SetChunkData.GetEntities().insert( a_SetChunkData.GetEntities().end(), std::make_move_iterator(m_Entities.begin()), std::make_move_iterator(m_Entities.end()) ); // Store the augmented result: m_Entities = std::move(a_SetChunkData.GetEntities()); // Set all the entity variables again: for (const auto & Entity : m_Entities) { Entity->SetWorld(m_World); Entity->SetParentChunk(this); Entity->SetIsTicking(true); } // Clear the block entities present - either the loader / saver has better, or we'll create empty ones: m_BlockEntities = std::move(a_SetChunkData.GetBlockEntities()); // Check that all block entities have a valid blocktype at their respective coords (DEBUG-mode only): #ifdef _DEBUG for (auto & KeyPair : m_BlockEntities) { cBlockEntity * Block = KeyPair.second.get(); BLOCKTYPE EntityBlockType = Block->GetBlockType(); BLOCKTYPE WorldBlockType = GetBlock(Block->GetRelX(), Block->GetPosY(), Block->GetRelZ()); ASSERT(WorldBlockType == EntityBlockType); } // for KeyPair - m_BlockEntities #endif // _DEBUG // Set all block entities' World variable: for (auto & KeyPair : m_BlockEntities) { KeyPair.second->SetWorld(m_World); } // Set the chunk data as valid. This may be needed for some simulators that perform actions upon block adding (Vaporize) SetPresence(cpPresent); if (a_SetChunkData.ShouldMarkDirty()) { MarkDirty(); } // Wake up all simulators for their respective blocks: WakeUpSimulators(); m_HasLoadFailed = false; } void cChunk::SetLight( const cChunkDef::BlockNibbles & a_BlockLight, const cChunkDef::BlockNibbles & a_SkyLight ) { // TODO: We might get cases of wrong lighting when a chunk changes in the middle of a lighting calculation. // Postponing until we see how bad it is :) m_ChunkData.SetBlockLight(a_BlockLight); m_ChunkData.SetSkyLight(a_SkyLight); MarkDirty(); m_IsLightValid = true; } void cChunk::GetBlockTypes(BLOCKTYPE * a_BlockTypes) { m_ChunkData.CopyBlockTypes(a_BlockTypes); } void cChunk::WriteBlockArea(cBlockArea & a_Area, int a_MinBlockX, int a_MinBlockY, int a_MinBlockZ, int a_DataTypes) { if ((a_DataTypes & (cBlockArea::baTypes | cBlockArea::baMetas)) != (cBlockArea::baTypes | cBlockArea::baMetas)) { LOGWARNING(""cChunk::WriteBlockArea(): unsupported datatype request, can write only types + metas together (0x%x), requested 0x%x. Ignoring."", (cBlockArea::baTypes | cBlockArea::baMetas), a_DataTypes & (cBlockArea::baTypes | cBlockArea::baMetas) ); return; } // SizeX, SizeZ are the dimensions of the block data to copy to the chunk (size of the geometric union) int BlockStartX = std::max(a_MinBlockX, m_PosX * cChunkDef::Width); int BlockEndX = std::min(a_MinBlockX + a_Area.GetSizeX(), (m_PosX + 1) * cChunkDef::Width); int BlockStartZ = std::max(a_MinBlockZ, m_PosZ * cChunkDef::Width); int BlockEndZ = std::min(a_MinBlockZ + a_Area.GetSizeZ(), (m_PosZ + 1) * cChunkDef::Width); int SizeX = BlockEndX - BlockStartX; // Size of the union int SizeZ = BlockEndZ - BlockStartZ; int SizeY = std::min(a_Area.GetSizeY(), cChunkDef::Height - a_MinBlockY); int OffX = BlockStartX - m_PosX * cChunkDef::Width; // Offset within the chunk where the union starts int OffZ = BlockStartZ - m_PosZ * cChunkDef::Width; int BaseX = BlockStartX - a_MinBlockX; // Offset within the area where the union starts int BaseZ = BlockStartZ - a_MinBlockZ; // Copy blocktype and blockmeta: BLOCKTYPE * AreaBlockTypes = a_Area.GetBlockTypes(); NIBBLETYPE * AreaBlockMetas = a_Area.GetBlockMetas(); for (int y = 0; y < SizeY; y++) { int ChunkY = a_MinBlockY + y; int AreaY = y; for (int z = 0; z < SizeZ; z++) { int ChunkZ = OffZ + z; int AreaZ = BaseZ + z; for (int x = 0; x < SizeX; x++) { int ChunkX = OffX + x; int AreaX = BaseX + x; auto idx = a_Area.MakeIndex(AreaX, AreaY, AreaZ); BLOCKTYPE BlockType = AreaBlockTypes[idx]; NIBBLETYPE BlockMeta = AreaBlockMetas[idx]; FastSetBlock(ChunkX, ChunkY, ChunkZ, BlockType, BlockMeta); } // for x } // for z } // for y // Erase all affected block entities: cCuboid affectedArea( // In world coordinates {BlockStartX, a_MinBlockY, BlockStartZ}, {BlockEndX, a_MinBlockY + SizeY - 1, BlockEndZ} ); for (auto itr = m_BlockEntities.begin(); itr != m_BlockEntities.end();) { if (affectedArea.IsInside(itr->second->GetPos())) { itr->second->Destroy(); itr->second->OnRemoveFromWorld(); itr = m_BlockEntities.erase(itr); } else { ++itr; } } // Clone block entities from a_Area into this chunk: if ((a_DataTypes & cBlockArea::baBlockEntities) != 0) { for (const auto & keyPair: a_Area.GetBlockEntities()) { auto & be = keyPair.second; auto posX = be->GetPosX() + a_MinBlockX; auto posY = be->GetPosY() + a_MinBlockY; auto posZ = be->GetPosZ() + a_MinBlockZ; if ( (posX < m_PosX * cChunkDef::Width) || (posX >= m_PosX * cChunkDef::Width + cChunkDef::Width) || (posZ < m_PosZ * cChunkDef::Width) || (posZ >= m_PosZ * cChunkDef::Width + cChunkDef::Width) ) { continue; } // This block entity is inside the chunk, clone it (and remove any that is there currently): auto idx = static_cast(cChunkDef::MakeIndex(posX - m_PosX * cChunkDef::Width, posY, posZ - m_PosZ * cChunkDef::Width)); auto itr = m_BlockEntities.find(idx); if (itr != m_BlockEntities.end()) { m_BlockEntities.erase(itr); } auto clone = be->Clone({posX, posY, posZ}); clone->SetWorld(m_World); AddBlockEntity(std::move(clone)); m_World->BroadcastBlockEntity({posX, posY, posZ}); } } } bool cChunk::HasBlockEntityAt(Vector3i a_BlockPos) { return (GetBlockEntity(a_BlockPos) != nullptr); } void cChunk::Stay(bool a_Stay) { if (a_Stay) { m_StayCount++; } else { ASSERT(m_StayCount != 0); m_StayCount--; } } void cChunk::CollectMobCensus(cMobCensus & toFill) { toFill.CollectSpawnableChunk(*this); std::vector PlayerPositions; PlayerPositions.reserve(m_LoadedByClient.size()); for (auto ClientHandle : m_LoadedByClient) { const cPlayer * currentPlayer = ClientHandle->GetPlayer(); PlayerPositions.push_back(currentPlayer->GetPosition()); } Vector3d currentPosition; for (auto & entity : m_Entities) { // LOGD(""Counting entity #%i (%s)"", (*itr)->GetUniqueID(), (*itr)->GetClass()); if (entity->IsMob()) { auto & Monster = static_cast(*entity); currentPosition = Monster.GetPosition(); for (const auto & PlayerPos : PlayerPositions) { toFill.CollectMob(Monster, *this, (currentPosition - PlayerPos).SqrLength()); } } } // for itr - m_Entitites[] } void cChunk::GetThreeRandomNumbers(int & a_X, int & a_Y, int & a_Z, int a_MaxX, int a_MaxY, int a_MaxZ) { ASSERT( (a_MaxX > 0) && (a_MaxY > 0) && (a_MaxZ > 0) && (a_MaxX <= std::numeric_limits::max() / a_MaxY) && // a_MaxX * a_MaxY doesn't overflow (a_MaxX * a_MaxY <= std::numeric_limits::max() / a_MaxZ) // a_MaxX * a_MaxY * a_MaxZ doesn't overflow ); // MTRand gives an inclusive range [0, Max] but this gives the exclusive range [0, Max) int OverallMax = (a_MaxX * a_MaxY * a_MaxZ) - 1; int Random = m_World->GetTickRandomNumber(OverallMax); a_X = Random % a_MaxX; a_Y = (Random / a_MaxX) % a_MaxY; a_Z = ((Random / a_MaxX) / a_MaxY) % a_MaxZ; } void cChunk::GetRandomBlockCoords(int & a_X, int & a_Y, int & a_Z) { // MG TODO : check if this kind of optimization (only one random call) is still needed // MG TODO : if so propagate it GetThreeRandomNumbers(a_X, a_Y, a_Z, cChunkDef::Width, cChunkDef::Height - 2, cChunkDef::Width); a_Y++; } void cChunk::SpawnMobs(cMobSpawner & a_MobSpawner) { int CenterX, CenterY, CenterZ; GetRandomBlockCoords(CenterX, CenterY, CenterZ); BLOCKTYPE PackCenterBlock = GetBlock(CenterX, CenterY, CenterZ); if (!a_MobSpawner.CheckPackCenter(PackCenterBlock)) { return; } a_MobSpawner.NewPack(); int NumberOfTries = 0; int NumberOfSuccess = 0; int MaxNbOfSuccess = 4; // This can be changed during the process for Wolves and Ghasts while ((NumberOfTries < 12) && (NumberOfSuccess < MaxNbOfSuccess)) { const int HorizontalRange = 20; // MG TODO : relocate const int VerticalRange = 0; // MG TODO : relocate int TryX, TryY, TryZ; GetThreeRandomNumbers(TryX, TryY, TryZ, 2 * HorizontalRange + 1, 2 * VerticalRange + 1, 2 * HorizontalRange + 1); TryX -= HorizontalRange; TryY -= VerticalRange; TryZ -= HorizontalRange; TryX += CenterX; TryY += CenterY; TryZ += CenterZ; ASSERT(TryY > 0); ASSERT(TryY < cChunkDef::Height - 1); int WorldX, WorldY, WorldZ; PositionToWorldPosition(TryX, TryY, TryZ, WorldX, WorldY, WorldZ); // MG TODO : // Moon cycle (for slime) // check player and playerspawn presence < 24 blocks // check mobs presence on the block // MG TODO : check that ""Level"" really means Y /* NIBBLETYPE SkyLight = 0; NIBBLETYPE BlockLight = 0; */ NumberOfTries++; Vector3i Try(TryX, TryY, TryZ); const auto Chunk = GetRelNeighborChunkAdjustCoords(Try); if ((Chunk == nullptr) || !Chunk->IsValid() || !Chunk->IsLightValid()) { continue; } auto newMob = a_MobSpawner.TryToSpawnHere(this, Try, GetBiomeAt(Try.x, Try.z), MaxNbOfSuccess); if (newMob == nullptr) { continue; } double ActualX = WorldX + 0.5; double ActualZ = WorldZ + 0.5; newMob->SetPosition(ActualX, WorldY, ActualZ); FLOGD(""Spawning {0} #{1} at {2}"", newMob->GetClass(), newMob->GetUniqueID(), Vector3i{WorldX, WorldY, WorldZ}); NumberOfSuccess++; } // while (retry) } void cChunk::Tick(std::chrono::milliseconds a_Dt) { const auto ShouldTick = ShouldBeTicked(); // If we are not valid, tick players and bailout if (!ShouldTick) { for (const auto & Entity : m_Entities) { if (Entity->IsPlayer()) { Entity->Tick(a_Dt, *this); } } return; } TickBlocks(); // Tick all block entities in this chunk: for (auto & KeyPair : m_BlockEntities) { m_IsDirty = KeyPair.second->Tick(a_Dt, *this) | m_IsDirty; } for (auto itr = m_Entities.begin(); itr != m_Entities.end();) { // Do not tick mobs that are detached from the world. They're either scheduled for teleportation or for removal. if (!(*itr)->IsTicking()) { ++itr; continue; } if (!((*itr)->IsMob())) // Mobs are ticked inside cWorld::TickMobs() (as we don't have to tick them if they are far away from players) { // Tick all entities in this chunk (except mobs): ASSERT((*itr)->GetParentChunk() == this); (*itr)->Tick(a_Dt, *this); ASSERT((*itr)->GetParentChunk() == this); } // Do not move mobs that are detached from the world to neighbors. They're either scheduled for teleportation or for removal. // Because the schedulded destruction is going to look for them in this chunk. See cEntity::destroy. if (!(*itr)->IsTicking()) { ++itr; continue; } if ( ((*itr)->GetChunkX() != m_PosX) || ((*itr)->GetChunkZ() != m_PosZ) ) { // Mark as dirty if it was a server-generated entity: if (!(*itr)->IsPlayer()) { MarkDirty(); } // This block is very similar to RemoveEntity, except it uses an iterator to avoid scanning the whole m_Entities // The entity moved out of the chunk, move it to the neighbor (*itr)->SetParentChunk(nullptr); MoveEntityToNewChunk(std::move(*itr)); itr = m_Entities.erase(itr); } else { ++itr; } } // for itr - m_Entitites[] ApplyWeatherToTop(); // Tick simulators: m_World->GetSimulatorManager()->SimulateChunk(a_Dt, m_PosX, m_PosZ, this); // Check blocks after everything else to apply at least one round of queued ticks (i.e. cBlockHandler::Check) this tick: CheckBlocks(); // Finally, tell the client about all block changes: BroadcastPendingBlockChanges(); } void cChunk::TickBlock(const Vector3i a_RelPos) { cChunkInterface ChunkInterface(this->GetWorld()->GetChunkMap()); cBlockInServerPluginInterface PluginInterface(*this->GetWorld()); cBlockHandler::For(GetBlock(a_RelPos)).OnUpdate(ChunkInterface, *this->GetWorld(), PluginInterface, *this, a_RelPos); } void cChunk::MoveEntityToNewChunk(OwnedEntity a_Entity) { cChunk * Neighbor = GetNeighborChunk(a_Entity->GetChunkX() * cChunkDef::Width, a_Entity->GetChunkZ() * cChunkDef::Width); if (Neighbor == nullptr) { LOGWARNING(""%s: Entity at %p (%s, ID %d) moving to a non-existent chunk."", __FUNCTION__, static_cast(a_Entity.get()), a_Entity->GetClass(), a_Entity->GetUniqueID() ); Neighbor = &m_ChunkMap->ConstructChunk(a_Entity->GetChunkX(), a_Entity->GetChunkZ()); } ASSERT(Neighbor != this); // Moving into the same chunk? wtf? auto & Entity = *a_Entity; Neighbor->AddEntity(std::move(a_Entity)); class cMover : public cClientDiffCallback { virtual void Removed(cClientHandle * a_Client) override { a_Client->SendDestroyEntity(m_Entity); } virtual void Added(cClientHandle * a_Client) override { m_Entity.SpawnOn(*a_Client); } cEntity & m_Entity; public: cMover(cEntity & a_CallbackEntity) : m_Entity(a_CallbackEntity) {} } Mover(Entity); m_ChunkMap->CompareChunkClients(this, Neighbor, Mover); } void cChunk::BroadcastPendingBlockChanges(void) { if (m_PendingSendBlocks.empty()) { return; } if (m_PendingSendBlocks.size() >= 10240) { // Resend the full chunk for (auto ClientHandle : m_LoadedByClient) { m_World->ForceSendChunkTo(m_PosX, m_PosZ, cChunkSender::Priority::Medium, ClientHandle); } } else { // Only send block changes for (auto ClientHandle : m_LoadedByClient) { ClientHandle->SendBlockChanges(m_PosX, m_PosZ, m_PendingSendBlocks); } } m_PendingSendBlocks.clear(); } void cChunk::CheckBlocks() { cChunkInterface ChunkInterface(m_World->GetChunkMap()); cBlockInServerPluginInterface PluginInterface(*m_World); // Process a limited number of blocks since cBlockHandler::Check may queue more to tick auto Count = m_ToTickBlocks.size(); while (Count != 0) { const auto Pos = m_ToTickBlocks.front(); m_ToTickBlocks.pop(); Count--; cBlockHandler::For(GetBlock(Pos)).Check(ChunkInterface, PluginInterface, Pos, *this); } } void cChunk::TickBlocks(void) { cChunkInterface ChunkInterface(this->GetWorld()->GetChunkMap()); cBlockInServerPluginInterface PluginInterface(*this->GetWorld()); // Tick random blocks, but the first one should be m_BlockToTick (so that SetNextBlockToTick() works) auto Idx = cChunkDef::MakeIndexNoCheck(m_BlockToTick); auto & Random = GetRandomProvider(); for (int i = 0; i < 50; ++i) { auto Pos = cChunkDef::IndexToCoordinate(static_cast(Idx)); Idx = Random.RandInt(cChunkDef::NumBlocks - 1); if (Pos.y > cChunkDef::GetHeight(m_HeightMap, Pos.x, Pos.z)) { continue; // It's all air up here } cBlockHandler::For(GetBlock(Pos)).OnUpdate(ChunkInterface, *this->GetWorld(), PluginInterface, *this, Pos); } // for i // Set a new random coord for the next tick: m_BlockToTick = cChunkDef::IndexToCoordinate(static_cast(Idx)); } void cChunk::ApplyWeatherToTop() { if ( (GetRandomProvider().RandBool(0.99)) || ( (m_World->GetWeather() != eWeather_Rain) && (m_World->GetWeather() != eWeather_ThunderStorm) ) ) { // Not the right weather, or not at this tick; bail out return; } int X = m_World->GetTickRandomNumber(15); int Z = m_World->GetTickRandomNumber(15); int Height = GetHeight(X, Z); if (GetSnowStartHeight(GetBiomeAt(X, Z)) > Height) { return; } if (GetBlockLight(X, Height, Z) > 10) { // Snow only generates on blocks with a block light level of 10 or less. // Ref: https://minecraft.gamepedia.com/Snow_(layer)#Snowfall return; } BLOCKTYPE TopBlock = GetBlock(X, Height, Z); NIBBLETYPE TopMeta = GetMeta (X, Height, Z); if (m_World->IsDeepSnowEnabled() && (TopBlock == E_BLOCK_SNOW)) { int MaxSize = 7; BLOCKTYPE BlockType[4]; NIBBLETYPE BlockMeta[4]; UnboundedRelGetBlock(X - 1, Height, Z, BlockType[0], BlockMeta[0]); UnboundedRelGetBlock(X + 1, Height, Z, BlockType[1], BlockMeta[1]); UnboundedRelGetBlock(X, Height, Z - 1, BlockType[2], BlockMeta[2]); UnboundedRelGetBlock(X, Height, Z + 1, BlockType[3], BlockMeta[3]); for (int i = 0; i < 4; i++) { switch (BlockType[i]) { case E_BLOCK_AIR: { MaxSize = 0; break; } case E_BLOCK_SNOW: { MaxSize = std::min(BlockMeta[i] + 1, MaxSize); break; } } } if (TopMeta < MaxSize) { FastSetBlock(X, Height, Z, E_BLOCK_SNOW, TopMeta + 1); } else if (TopMeta > MaxSize) { FastSetBlock(X, Height, Z, E_BLOCK_SNOW, TopMeta - 1); } } else if (cBlockInfo::IsSnowable(TopBlock) && (Height < cChunkDef::Height - 1)) { SetBlock({X, Height + 1, Z}, E_BLOCK_SNOW, 0); } else if (IsBlockWater(TopBlock) && (TopMeta == 0)) { SetBlock({X, Height, Z}, E_BLOCK_ICE, 0); } else if ( (m_World->IsDeepSnowEnabled()) && ( (TopBlock == E_BLOCK_RED_ROSE) || (TopBlock == E_BLOCK_YELLOW_FLOWER) || (TopBlock == E_BLOCK_RED_MUSHROOM) || (TopBlock == E_BLOCK_BROWN_MUSHROOM) ) ) { SetBlock({X, Height, Z}, E_BLOCK_SNOW, 0); } } cItems cChunk::PickupsFromBlock(Vector3i a_RelPos, const cEntity * a_Digger, const cItem * a_Tool) { BLOCKTYPE BlockType; NIBBLETYPE BlockMeta; GetBlockTypeMeta(a_RelPos, BlockType, BlockMeta); cItems Pickups; const auto BlockEntity = GetBlockEntityRel(a_RelPos); const auto ToolHandler = (a_Tool != nullptr) ? a_Tool->GetHandler() : cItemHandler::GetItemHandler(E_ITEM_EMPTY); if (ToolHandler->CanHarvestBlock(BlockType)) { Pickups = cBlockHandler::For(BlockType).ConvertToPickups(BlockMeta, a_Digger, a_Tool); if (BlockEntity != nullptr) { auto BlockEntityPickups = BlockEntity->ConvertToPickups(); Pickups.insert(Pickups.end(), std::make_move_iterator(BlockEntityPickups.begin()), std::make_move_iterator(BlockEntityPickups.end())); } } // TODO: this should be in cWorld::DropBlockAsPickups. When it's here we can't check the return value and cancel spawning: cRoot::Get()->GetPluginManager()->CallHookBlockToPickups( *m_World, cChunkDef::RelativeToAbsolute(a_RelPos, GetPos()), BlockType, BlockMeta, BlockEntity, a_Digger, a_Tool, Pickups ); return Pickups; } int cChunk::GrowPlantAt(Vector3i a_RelPos, int a_NumStages) { return cBlockHandler::For(GetBlock(a_RelPos)).Grow(*this, a_RelPos, a_NumStages); } bool cChunk::UnboundedRelGetBlock(Vector3i a_RelPos, BLOCKTYPE & a_BlockType, NIBBLETYPE & a_BlockMeta) const { if (!cChunkDef::IsValidHeight(a_RelPos.y)) { LOGWARNING(""%s: requesting a block with a_RelY out of range: %d"", __FUNCTION__, a_RelPos.y); return false; } auto chunk = GetRelNeighborChunkAdjustCoords(a_RelPos); if ((chunk == nullptr) || !chunk->IsValid()) { // The chunk is not available, bail out return false; } chunk->GetBlockTypeMeta(a_RelPos, a_BlockType, a_BlockMeta); return true; } bool cChunk::UnboundedRelGetBlockType(Vector3i a_RelPos, BLOCKTYPE & a_BlockType) const { if (!cChunkDef::IsValidHeight(a_RelPos.y)) { LOGWARNING(""%s: requesting a block with a_RelY out of range: %d"", __FUNCTION__, a_RelPos.y); return false; } auto chunk = GetRelNeighborChunkAdjustCoords(a_RelPos); if ((chunk == nullptr) || !chunk->IsValid()) { // The chunk is not available, bail out return false; } a_BlockType = chunk->GetBlock(a_RelPos); return true; } bool cChunk::UnboundedRelGetBlockMeta(Vector3i a_RelPos, NIBBLETYPE & a_BlockMeta) const { if (!cChunkDef::IsValidHeight(a_RelPos.y)) { LOGWARNING(""%s: requesting a block with a_RelY out of range: %d"", __FUNCTION__, a_RelPos.y); return false; } auto chunk = GetRelNeighborChunkAdjustCoords(a_RelPos); if ((chunk == nullptr) || !chunk->IsValid()) { // The chunk is not available, bail out return false; } a_BlockMeta = chunk->GetMeta(a_RelPos); return true; } bool cChunk::UnboundedRelGetBlockBlockLight(Vector3i a_RelPos, NIBBLETYPE & a_BlockBlockLight) const { if (!cChunkDef::IsValidHeight(a_RelPos.y)) { LOGWARNING(""%s: requesting a block with a_RelY out of range: %d"", __FUNCTION__, a_RelPos.y); return false; } auto chunk = GetRelNeighborChunkAdjustCoords(a_RelPos); if ((chunk == nullptr) || !chunk->IsValid()) { // The chunk is not available, bail out return false; } a_BlockBlockLight = chunk->GetBlockLight(a_RelPos); return true; } bool cChunk::UnboundedRelGetBlockSkyLight(Vector3i a_RelPos, NIBBLETYPE & a_BlockSkyLight) const { if (!cChunkDef::IsValidHeight(a_RelPos.y)) { LOGWARNING(""%s: requesting a block with a_RelY out of range: %d"", __FUNCTION__, a_RelPos.y); return false; } auto chunk = GetRelNeighborChunkAdjustCoords(a_RelPos); if ((chunk == nullptr) || !chunk->IsValid()) { // The chunk is not available, bail out return false; } a_BlockSkyLight = chunk->GetSkyLight(a_RelPos); return true; } bool cChunk::UnboundedRelGetBlockLights(Vector3i a_RelPos, NIBBLETYPE & a_BlockLight, NIBBLETYPE & a_SkyLight) const { if (!cChunkDef::IsValidHeight(a_RelPos.y)) { LOGWARNING(""%s: requesting a block with a_RelY out of range: %d"", __FUNCTION__, a_RelPos.y); return false; } auto chunk = GetRelNeighborChunkAdjustCoords(a_RelPos); if ((chunk == nullptr) || !chunk->IsValid()) { // The chunk is not available, bail out return false; } a_BlockLight = chunk->GetBlockLight(a_RelPos); a_SkyLight = chunk->GetSkyLight (a_RelPos); return true; } bool cChunk::UnboundedRelSetBlock(Vector3i a_RelPos, BLOCKTYPE a_BlockType, NIBBLETYPE a_BlockMeta) { if (!cChunkDef::IsValidHeight(a_RelPos.y)) { LOGWARNING(""%s: requesting a block with a_RelY out of range: %d"", __FUNCTION__, a_RelPos.y); return false; } auto chunk = GetRelNeighborChunkAdjustCoords(a_RelPos); if ((chunk == nullptr) || !chunk->IsValid()) { // The chunk is not available, bail out return false; } chunk->SetBlock(a_RelPos, a_BlockType, a_BlockMeta); return true; } bool cChunk::UnboundedRelFastSetBlock(Vector3i a_RelPos, BLOCKTYPE a_BlockType, NIBBLETYPE a_BlockMeta) { if (!cChunkDef::IsValidHeight(a_RelPos.y)) { LOGWARNING(""%s: requesting a block with a_RelY out of range: %d"", __FUNCTION__, a_RelPos.y); return false; } auto chunk = GetRelNeighborChunkAdjustCoords(a_RelPos); if ((chunk == nullptr) || !chunk->IsValid()) { // The chunk is not available, bail out return false; } chunk->FastSetBlock(a_RelPos, a_BlockType, a_BlockMeta); return true; } int cChunk::GetHeight(int a_X, int a_Z) const { ASSERT((a_X >= 0) && (a_X < cChunkDef::Width) && (a_Z >= 0) && (a_Z < cChunkDef::Width)); return m_HeightMap[a_X + a_Z * cChunkDef::Width]; } bool cChunk::IsWeatherSunnyAt(int a_RelX, int a_RelZ) const { return m_World->IsWeatherSunny() || IsBiomeNoDownfall(GetBiomeAt(a_RelX, a_RelZ)); } bool cChunk::IsWeatherWetAt(const int a_RelX, const int a_RelZ) const { const auto Biome = GetBiomeAt(a_RelX, a_RelZ); return m_World->IsWeatherWet() && !IsBiomeNoDownfall(Biome) && !IsBiomeCold(Biome); } bool cChunk::IsWeatherWetAt(const Vector3i a_Position) const { if ((a_Position.y < 0) || !IsWeatherWetAt(a_Position.x, a_Position.z)) { return false; } if (a_Position.y >= cChunkDef::Height) { return true; } for (int y = GetHeight(a_Position.x, a_Position.z); y >= a_Position.y; y--) { if (cBlockInfo::IsRainBlocker(GetBlock({ a_Position.x, y, a_Position.z }))) { return false; } } return true; } void cChunk::WakeUpSimulators(void) { auto * WaterSimulator = m_World->GetWaterSimulator(); auto * LavaSimulator = m_World->GetLavaSimulator(); auto * RedstoneSimulator = m_World->GetRedstoneSimulator(); for (size_t SectionIdx = 0; SectionIdx != cChunkData::NumSections; ++SectionIdx) { const auto * Section = m_ChunkData.GetSection(SectionIdx); if (Section == nullptr) { continue; } for (size_t BlockIdx = 0; BlockIdx != cChunkData::SectionBlockCount; ++BlockIdx) { const auto BlockType = Section->m_BlockTypes[BlockIdx]; auto Position = cChunkDef::IndexToCoordinate(BlockIdx); Position.y += static_cast(SectionIdx * cChunkData::SectionHeight); RedstoneSimulator->AddBlock(*this, Position, BlockType); WaterSimulator->AddBlock(*this, Position, BlockType); LavaSimulator->AddBlock(*this, Position, BlockType); } } } void cChunk::SetBlock(Vector3i a_RelPos, BLOCKTYPE a_BlockType, NIBBLETYPE a_BlockMeta) { FastSetBlock(a_RelPos, a_BlockType, a_BlockMeta); // Tick this block's neighbors via cBlockHandler::Check: m_ToTickBlocks.push(a_RelPos); // Wake up the simulators for this block: GetWorld()->GetSimulatorManager()->WakeUp(*this, a_RelPos); // If there was a block entity, remove it: cBlockEntity * BlockEntity = GetBlockEntityRel(a_RelPos); if (BlockEntity != nullptr) { BlockEntity->Destroy(); BlockEntity->OnRemoveFromWorld(); RemoveBlockEntity(BlockEntity); } // If the new block is a block entity, create the entity object: if (cBlockEntity::IsBlockEntityBlockType(a_BlockType)) { AddBlockEntity(cBlockEntity::CreateByBlockType(a_BlockType, a_BlockMeta, RelativeToAbsolute(a_RelPos), m_World)); } } void cChunk::FastSetBlock(int a_RelX, int a_RelY, int a_RelZ, BLOCKTYPE a_BlockType, BLOCKTYPE a_BlockMeta) { ASSERT(!((a_RelX < 0) || (a_RelX >= cChunkDef::Width) || (a_RelY < 0) || (a_RelY >= cChunkDef::Height) || (a_RelZ < 0) || (a_RelZ >= cChunkDef::Width))); ASSERT(IsValid()); const BLOCKTYPE OldBlockType = GetBlock(a_RelX, a_RelY, a_RelZ); const BLOCKTYPE OldBlockMeta = m_ChunkData.GetMeta({ a_RelX, a_RelY, a_RelZ }); if ((OldBlockType == a_BlockType) && (OldBlockMeta == a_BlockMeta)) { return; } bool ReplacingLiquids = ( ((OldBlockType == E_BLOCK_STATIONARY_WATER) && (a_BlockType == E_BLOCK_WATER)) || // Replacing stationary water with water ((OldBlockType == E_BLOCK_WATER) && (a_BlockType == E_BLOCK_STATIONARY_WATER)) || // Replacing water with stationary water ((OldBlockType == E_BLOCK_STATIONARY_LAVA) && (a_BlockType == E_BLOCK_LAVA)) || // Replacing stationary lava with lava ((OldBlockType == E_BLOCK_LAVA) && (a_BlockType == E_BLOCK_STATIONARY_LAVA)) // Replacing lava with stationary lava ); if (!ReplacingLiquids) { MarkDirty(); } m_ChunkData.SetBlock({ a_RelX, a_RelY, a_RelZ }, a_BlockType); // Queue block to be sent only if ... if ( !( // ... the old and new blocktypes AREN'T leaves (because the client doesn't need meta updates) ((OldBlockType == E_BLOCK_LEAVES) && (a_BlockType == E_BLOCK_LEAVES)) || ((OldBlockType == E_BLOCK_NEW_LEAVES) && (a_BlockType == E_BLOCK_NEW_LEAVES)) ) && // ... AND ... ( (OldBlockMeta != a_BlockMeta) || (!ReplacingLiquids) ) ) { m_PendingSendBlocks.push_back(sSetBlock(m_PosX, m_PosZ, a_RelX, a_RelY, a_RelZ, a_BlockType, a_BlockMeta)); } m_ChunkData.SetMeta({ a_RelX, a_RelY, a_RelZ }, a_BlockMeta); // ONLY recalculate lighting if it's necessary! if ( (cBlockInfo::GetLightValue (OldBlockType) != cBlockInfo::GetLightValue (a_BlockType)) || (cBlockInfo::GetSpreadLightFalloff(OldBlockType) != cBlockInfo::GetSpreadLightFalloff(a_BlockType)) || (cBlockInfo::IsTransparent (OldBlockType) != cBlockInfo::IsTransparent (a_BlockType)) ) { m_IsLightValid = false; } // Update heightmap, if needed: if (a_RelY >= m_HeightMap[a_RelX + a_RelZ * cChunkDef::Width]) { if (a_BlockType != E_BLOCK_AIR) { m_HeightMap[a_RelX + a_RelZ * cChunkDef::Width] = static_cast(a_RelY); } else { for (int y = a_RelY - 1; y > 0; --y) { if (GetBlock(a_RelX, y, a_RelZ) != E_BLOCK_AIR) { m_HeightMap[a_RelX + a_RelZ * cChunkDef::Width] = static_cast(y); break; } } // for y - column in m_BlockData } } } void cChunk::SendBlockTo(int a_RelX, int a_RelY, int a_RelZ, cClientHandle * a_Client) { if (a_Client == nullptr) { // Queue the block for all clients in the chunk (will be sent in Tick()) m_PendingSendBlocks.push_back(sSetBlock(m_PosX, m_PosZ, a_RelX, a_RelY, a_RelZ, GetBlock(a_RelX, a_RelY, a_RelZ), GetMeta(a_RelX, a_RelY, a_RelZ))); return; } Vector3i wp = PositionToWorldPosition(a_RelX, a_RelY, a_RelZ); a_Client->SendBlockChange(wp.x, wp.y, wp.z, GetBlock(a_RelX, a_RelY, a_RelZ), GetMeta(a_RelX, a_RelY, a_RelZ)); // FS #268 - if a BlockEntity digging is cancelled by a plugin, the entire block entity must be re-sent to the client: cBlockEntity * Block = GetBlockEntity(wp.x, wp.y, wp.z); if (Block != nullptr) { Block->SendTo(*a_Client); } } void cChunk::AddBlockEntity(OwnedBlockEntity a_BlockEntity) { [[maybe_unused]] const auto Result = m_BlockEntities.emplace( cChunkDef::MakeIndex(a_BlockEntity->GetRelX(), a_BlockEntity->GetPosY(), a_BlockEntity->GetRelZ()), std::move(a_BlockEntity) ); ASSERT(Result.second); // No block entity already at this position } cBlockEntity * cChunk::GetBlockEntity(Vector3i a_AbsPos) { const auto relPos = cChunkDef::AbsoluteToRelative(a_AbsPos); if (!cChunkDef::IsValidRelPos(relPos)) { // Coordinates are outside outside this chunk, no block entities here return nullptr; } auto itr = m_BlockEntities.find(static_cast(cChunkDef::MakeIndexNoCheck(relPos))); return (itr == m_BlockEntities.end()) ? nullptr : itr->second.get(); } cBlockEntity * cChunk::GetBlockEntityRel(Vector3i a_RelPos) { ASSERT(cChunkDef::IsValidRelPos(a_RelPos)); auto itr = m_BlockEntities.find(static_cast(cChunkDef::MakeIndexNoCheck(a_RelPos))); return (itr == m_BlockEntities.end()) ? nullptr : itr->second.get(); } bool cChunk::ShouldBeTicked(void) const { return IsValid() && (HasAnyClients() || (m_AlwaysTicked > 0)); } void cChunk::SetAlwaysTicked(bool a_AlwaysTicked) { if (a_AlwaysTicked) { m_AlwaysTicked += 1; Stay(a_AlwaysTicked); } else { m_AlwaysTicked -= 1; Stay(a_AlwaysTicked); } } bool cChunk::UseBlockEntity(cPlayer * a_Player, int a_X, int a_Y, int a_Z) { cBlockEntity * be = GetBlockEntity(a_X, a_Y, a_Z); if (be != nullptr) { return be->UsedBy(a_Player); } return false; } void cChunk::SetBiomeAt(int a_RelX, int a_RelZ, EMCSBiome a_Biome) { cChunkDef::SetBiome(m_BiomeMap, a_RelX, a_RelZ, a_Biome); MarkDirty(); } void cChunk::SetAreaBiome(int a_MinRelX, int a_MaxRelX, int a_MinRelZ, int a_MaxRelZ, EMCSBiome a_Biome) { for (int z = a_MinRelZ; z <= a_MaxRelZ; z++) { for (int x = a_MinRelX; x <= a_MaxRelX; x++) { cChunkDef::SetBiome(m_BiomeMap, x, z, a_Biome); } } MarkDirty(); // Re-send the chunk to all clients: for (auto ClientHandle : m_LoadedByClient) { m_World->ForceSendChunkTo(m_PosX, m_PosZ, cChunkSender::Priority::Medium, ClientHandle); } // for itr - m_LoadedByClient[] } bool cChunk::SetSignLines(int a_PosX, int a_PosY, int a_PosZ, const AString & a_Line1, const AString & a_Line2, const AString & a_Line3, const AString & a_Line4) { // Also sends update packets to all clients in the chunk auto Entity = GetBlockEntity(a_PosX, a_PosY, a_PosZ); if (Entity == nullptr) { return false; // Not a block entity } if ( (Entity->GetBlockType() != E_BLOCK_WALLSIGN) && (Entity->GetBlockType() != E_BLOCK_SIGN_POST) ) { return false; // Not a sign } MarkDirty(); auto Sign = static_cast(Entity); Sign->SetLines(a_Line1, a_Line2, a_Line3, a_Line4); m_World->BroadcastBlockEntity({a_PosX, a_PosY, a_PosZ}); return true; } void cChunk::RemoveBlockEntity(cBlockEntity * a_BlockEntity) { MarkDirty(); ASSERT(a_BlockEntity != nullptr); auto idx = static_cast(cChunkDef::MakeIndex(a_BlockEntity->GetRelX(), a_BlockEntity->GetPosY(), a_BlockEntity->GetRelZ())); m_BlockEntities.erase(idx); } bool cChunk::AddClient(cClientHandle * a_Client) { if (std::find(m_LoadedByClient.begin(), m_LoadedByClient.end(), a_Client) != m_LoadedByClient.end()) { // Already there, nothing needed return false; } m_LoadedByClient.push_back(a_Client); return true; } void cChunk::RemoveClient(cClientHandle * a_Client) { auto itr = std::remove(m_LoadedByClient.begin(), m_LoadedByClient.end(), a_Client); // We should always remove at most one client. ASSERT(std::distance(itr, m_LoadedByClient.end()) <= 1); // Note: itr can equal m_LoadedByClient.end() m_LoadedByClient.erase(itr, m_LoadedByClient.end()); if (!a_Client->IsDestroyed()) { for (auto & Entity : m_Entities) { /* // DEBUG: LOGD(""chunk [%i, %i] destroying entity #%i for player \\""%s\\"""", m_PosX, m_PosZ, (*itr)->GetUniqueID(), a_Client->GetUsername().c_str() ); */ a_Client->SendDestroyEntity(*Entity); } } } bool cChunk::HasClient(cClientHandle * a_Client) { return std::find(m_LoadedByClient.begin(), m_LoadedByClient.end(), a_Client) != m_LoadedByClient.end(); } bool cChunk::HasAnyClients(void) const { return !m_LoadedByClient.empty(); } void cChunk::AddEntity(OwnedEntity a_Entity) { if (!a_Entity->IsPlayer()) { MarkDirty(); } auto EntityPtr = a_Entity.get(); ASSERT(std::find(m_Entities.begin(), m_Entities.end(), a_Entity) == m_Entities.end()); // Not there already m_Entities.emplace_back(std::move(a_Entity)); ASSERT(EntityPtr->GetParentChunk() == nullptr); EntityPtr->SetParentChunk(this); } OwnedEntity cChunk::RemoveEntity(cEntity & a_Entity) { ASSERT(a_Entity.GetParentChunk() == this); ASSERT(!a_Entity.IsTicking()); a_Entity.SetParentChunk(nullptr); // Mark as dirty if it was a server-generated entity: if (!a_Entity.IsPlayer()) { MarkDirty(); } OwnedEntity Removed; m_Entities.erase( std::remove_if( m_Entities.begin(), m_Entities.end(), [&a_Entity, &Removed](decltype(m_Entities)::value_type & a_Value) { if (a_Value.get() == &a_Entity) { ASSERT(!Removed); Removed = std::move(a_Value); return true; } return false; } ), m_Entities.end() ); return Removed; } bool cChunk::HasEntity(UInt32 a_EntityID) const { for (const auto & Entity : m_Entities) { if (Entity->GetUniqueID() == a_EntityID) { return true; } } return false; } bool cChunk::ForEachEntity(cEntityCallback a_Callback) const { // The entity list is locked by the parent chunkmap's CS for (const auto & Entity : m_Entities) { if (Entity->IsTicking() && a_Callback(*Entity)) { return false; } } // for itr - m_Entitites[] return true; } bool cChunk::ForEachEntityInBox(const cBoundingBox & a_Box, cEntityCallback a_Callback) const { // The entity list is locked by the parent chunkmap's CS for (const auto & Entity : m_Entities) { if (!Entity->IsTicking()) { continue; } if (!Entity->GetBoundingBox().DoesIntersect(a_Box)) { // The entity is not in the specified box continue; } if (a_Callback(*Entity)) { return false; } } // for itr - m_Entitites[] return true; } bool cChunk::DoWithEntityByID(UInt32 a_EntityID, cEntityCallback a_Callback, bool & a_CallbackResult) const { // The entity list is locked by the parent chunkmap's CS for (const auto & Entity : m_Entities) { if ((Entity->GetUniqueID() == a_EntityID) && (Entity->IsTicking())) { a_CallbackResult = a_Callback(*Entity); return true; } } // for itr - m_Entitites[] return false; } template bool cChunk::GenericForEachBlockEntity(cFunctionRef a_Callback) { // The blockentity list is locked by the parent chunkmap's CS for (auto & KeyPair : m_BlockEntities) { cBlockEntity * Block = KeyPair.second.get(); if ( (sizeof...(tBlocktype) == 0) || // Let empty list mean all block entities (IsOneOf(Block->GetBlockType())) ) { if (a_Callback(*static_cast(Block))) { return false; } } } // for KeyPair - m_BlockEntitites[] return true; } bool cChunk::ForEachBlockEntity(cBlockEntityCallback a_Callback) { return GenericForEachBlockEntity(a_Callback); } bool cChunk::ForEachBrewingstand(cBrewingstandCallback a_Callback) { return GenericForEachBlockEntity(a_Callback); } bool cChunk::ForEachChest(cChestCallback a_Callback) { return GenericForEachBlockEntity(a_Callback); } bool cChunk::ForEachDispenser(cDispenserCallback a_Callback) { return GenericForEachBlockEntity(a_Callback); } bool cChunk::ForEachDropper(cDropperCallback a_Callback) { return GenericForEachBlockEntity(a_Callback); } bool cChunk::ForEachDropSpenser(cDropSpenserCallback a_Callback) { return GenericForEachBlockEntity(a_Callback); } bool cChunk::ForEachFurnace(cFurnaceCallback a_Callback) { return GenericForEachBlockEntity(a_Callback); } template bool cChunk::GenericDoWithBlockEntityAt(Vector3i a_Position, cFunctionRef a_Callback) { // The blockentity list is locked by the parent chunkmap's CS cBlockEntity * Block = GetBlockEntityRel(a_Position); if (Block == nullptr) { return false; // No block entity here } if ( (sizeof...(tBlocktype) != 0) && // Let empty list mean all block entities (!IsOneOf(Block->GetBlockType())) ) { return false; // Not any of the given tBlocktypes } return !a_Callback(*static_cast(Block)); } bool cChunk::DoWithBlockEntityAt(Vector3i a_Position, cBlockEntityCallback a_Callback) { return GenericDoWithBlockEntityAt(a_Position, a_Callback); } bool cChunk::DoWithBeaconAt(Vector3i a_Position, cBeaconCallback a_Callback) { return GenericDoWithBlockEntityAt(a_Position, a_Callback); } bool cChunk::DoWithBedAt(Vector3i a_Position, cBedCallback a_Callback) { return GenericDoWithBlockEntityAt(a_Position, a_Callback); } bool cChunk::DoWithBrewingstandAt(Vector3i a_Position, cBrewingstandCallback a_Callback) { return GenericDoWithBlockEntityAt(a_Position, a_Callback); } bool cChunk::DoWithChestAt(Vector3i a_Position, cChestCallback a_Callback) { return GenericDoWithBlockEntityAt(a_Position, a_Callback); } bool cChunk::DoWithDispenserAt(Vector3i a_Position, cDispenserCallback a_Callback) { return GenericDoWithBlockEntityAt(a_Position, a_Callback); } bool cChunk::DoWithDropperAt(Vector3i a_Position, cDropperCallback a_Callback) { return GenericDoWithBlockEntityAt(a_Position, a_Callback); } bool cChunk::DoWithDropSpenserAt(Vector3i a_Position, cDropSpenserCallback a_Callback) { return GenericDoWithBlockEntityAt(a_Position, a_Callback); } bool cChunk::DoWithFurnaceAt(Vector3i a_Position, cFurnaceCallback a_Callback) { return GenericDoWithBlockEntityAt(a_Position, a_Callback); } bool cChunk::DoWithHopperAt(Vector3i a_Position, cHopperCallback a_Callback) { return GenericDoWithBlockEntityAt(a_Position, a_Callback); } bool cChunk::DoWithNoteBlockAt(Vector3i a_Position, cNoteBlockCallback a_Callback) { return GenericDoWithBlockEntityAt(a_Position, a_Callback); } bool cChunk::DoWithCommandBlockAt(Vector3i a_Position, cCommandBlockCallback a_Callback) { return GenericDoWithBlockEntityAt(a_Position, a_Callback); } bool cChunk::DoWithMobHeadAt(Vector3i a_Position, cMobHeadCallback a_Callback) { return GenericDoWithBlockEntityAt(a_Position, a_Callback); } bool cChunk::DoWithFlowerPotAt(Vector3i a_Position, cFlowerPotCallback a_Callback) { return GenericDoWithBlockEntityAt(a_Position, a_Callback); } bool cChunk::GetSignLines(Vector3i a_Position, AString & a_Line1, AString & a_Line2, AString & a_Line3, AString & a_Line4) { // The blockentity list is locked by the parent chunkmap's CS auto Entity = GetBlockEntity(a_Position); if (Entity == nullptr) { return false; // Not a block entity } if ( (Entity->GetBlockType() != E_BLOCK_WALLSIGN) && (Entity->GetBlockType() != E_BLOCK_SIGN_POST) ) { return false; // Not a sign } auto Sign = static_cast(Entity); a_Line1 = Sign->GetLine(0); a_Line2 = Sign->GetLine(1); a_Line3 = Sign->GetLine(2); a_Line4 = Sign->GetLine(3); return true; } void cChunk::GetBlockTypeMeta(Vector3i a_RelPos, BLOCKTYPE & a_BlockType, NIBBLETYPE & a_BlockMeta) const { a_BlockType = GetBlock(a_RelPos); a_BlockMeta = GetMeta(a_RelPos); } void cChunk::GetBlockInfo(Vector3i a_RelPos, BLOCKTYPE & a_BlockType, NIBBLETYPE & a_Meta, NIBBLETYPE & a_SkyLight, NIBBLETYPE & a_BlockLight) const { a_BlockType = GetBlock(a_RelPos); a_Meta = m_ChunkData.GetMeta(a_RelPos); a_SkyLight = m_ChunkData.GetSkyLight(a_RelPos); a_BlockLight = m_ChunkData.GetBlockLight(a_RelPos); } bool cChunk::GetChunkAndRelByAbsolute(const Vector3d & a_Position, cChunk ** a_Chunk, Vector3i & a_Rel) { return GetChunkAndRelByAbsolute(Vector3i(FloorC(a_Position.x), FloorC(a_Position.y), FloorC(a_Position.z)), a_Chunk, a_Rel); } bool cChunk::GetChunkAndRelByAbsolute(const Vector3i & a_Position, cChunk ** a_Chunk, Vector3i & a_Rel) { *a_Chunk = this->GetNeighborChunk(a_Position.x, a_Position.z); if ((*a_Chunk == nullptr) || !(*a_Chunk)->IsValid()) { return false; } a_Rel.x = a_Position.x - (*a_Chunk)->GetPosX() * cChunkDef::Width; a_Rel.y = a_Position.y; a_Rel.z = a_Position.z - (*a_Chunk)->GetPosZ() * cChunkDef::Width; return true; } cChunk * cChunk::GetNeighborChunk(int a_BlockX, int a_BlockZ) { // Convert coords to relative, then call the relative version: a_BlockX -= m_PosX * cChunkDef::Width; a_BlockZ -= m_PosZ * cChunkDef::Width; return GetRelNeighborChunk(a_BlockX, a_BlockZ); } cChunk * cChunk::GetRelNeighborChunk(int a_RelX, int a_RelZ) { // If the relative coords are too far away, use the parent's chunk lookup instead: if ((a_RelX < -128) || (a_RelX > 128) || (a_RelZ < -128) || (a_RelZ > 128)) { int BlockX = m_PosX * cChunkDef::Width + a_RelX; int BlockZ = m_PosZ * cChunkDef::Width + a_RelZ; int ChunkX, ChunkZ; cChunkDef::BlockToChunk(BlockX, BlockZ, ChunkX, ChunkZ); return m_ChunkMap->FindChunk(ChunkX, ChunkZ); } // Walk the neighbors: bool ReturnThis = true; if (a_RelX < 0) { if (m_NeighborXM != nullptr) { cChunk * Candidate = m_NeighborXM->GetRelNeighborChunk(a_RelX + cChunkDef::Width, a_RelZ); if (Candidate != nullptr) { return Candidate; } } // Going X first failed, but if the request is crossing Z as well, let's try the Z first later on. ReturnThis = false; } else if (a_RelX >= cChunkDef::Width) { if (m_NeighborXP != nullptr) { cChunk * Candidate = m_NeighborXP->GetRelNeighborChunk(a_RelX - cChunkDef::Width, a_RelZ); if (Candidate != nullptr) { return Candidate; } } // Going X first failed, but if the request is crossing Z as well, let's try the Z first later on. ReturnThis = false; } if (a_RelZ < 0) { if (m_NeighborZM != nullptr) { return m_NeighborZM->GetRelNeighborChunk(a_RelX, a_RelZ + cChunkDef::Width); // For requests crossing both X and Z, the X-first way has been already tried } return nullptr; } else if (a_RelZ >= cChunkDef::Width) { if (m_NeighborZP != nullptr) { return m_NeighborZP->GetRelNeighborChunk(a_RelX, a_RelZ - cChunkDef::Width); // For requests crossing both X and Z, the X-first way has been already tried } return nullptr; } return (ReturnThis ? this : nullptr); } cChunk * cChunk::GetRelNeighborChunkAdjustCoords(Vector3i & a_RelPos) const { cChunk * ToReturn = const_cast(this); // The most common case: inside this chunk: if ( (a_RelPos.x >= 0) && (a_RelPos.x < cChunkDef::Width) && (a_RelPos.z >= 0) && (a_RelPos.z < cChunkDef::Width) ) { return ToReturn; } // Request for a different chunk, calculate chunk offset: int RelX = a_RelPos.x; // Make a local copy of the coords (faster access) int RelZ = a_RelPos.z; while ((RelX >= cChunkDef::Width) && (ToReturn != nullptr)) { RelX -= cChunkDef::Width; ToReturn = ToReturn->m_NeighborXP; } while ((RelX < 0) && (ToReturn != nullptr)) { RelX += cChunkDef::Width; ToReturn = ToReturn->m_NeighborXM; } while ((RelZ >= cChunkDef::Width) && (ToReturn != nullptr)) { RelZ -= cChunkDef::Width; ToReturn = ToReturn->m_NeighborZP; } while ((RelZ < 0) && (ToReturn != nullptr)) { RelZ += cChunkDef::Width; ToReturn = ToReturn->m_NeighborZM; } if (ToReturn != nullptr) { a_RelPos.x = RelX; a_RelPos.z = RelZ; return ToReturn; } // The chunk cannot be walked through neighbors, find it through the chunkmap: int AbsX = a_RelPos.x + m_PosX * cChunkDef::Width; int AbsZ = a_RelPos.z + m_PosZ * cChunkDef::Width; int DstChunkX, DstChunkZ; cChunkDef::BlockToChunk(AbsX, AbsZ, DstChunkX, DstChunkZ); ToReturn = m_ChunkMap->FindChunk(DstChunkX, DstChunkZ); a_RelPos.x = AbsX - DstChunkX * cChunkDef::Width; a_RelPos.z = AbsZ - DstChunkZ * cChunkDef::Width; return ToReturn; } void cChunk::SendBlockEntity(int a_BlockX, int a_BlockY, int a_BlockZ, cClientHandle & a_Client) { cBlockEntity * Entity = GetBlockEntity(a_BlockX, a_BlockY, a_BlockZ); if (Entity == nullptr) { return; } Entity->SendTo(a_Client); } void cChunk::PositionToWorldPosition(int a_RelX, int a_RelY, int a_RelZ, int & a_BlockX, int & a_BlockY, int & a_BlockZ) { a_BlockY = a_RelY; a_BlockX = m_PosX * cChunkDef::Width + a_RelX; a_BlockZ = m_PosZ * cChunkDef::Width + a_RelZ; } Vector3i cChunk::PositionToWorldPosition(int a_RelX, int a_RelY, int a_RelZ) { return Vector3i(m_PosX * cChunkDef::Width + a_RelX, a_RelY, m_PosZ * cChunkDef::Width + a_RelZ); } NIBBLETYPE cChunk::GetTimeAlteredLight(NIBBLETYPE a_Skylight) const { a_Skylight -= m_World->GetSkyDarkness(); // Because NIBBLETYPE is unsigned, we clamp it to 0 .. 15 by checking for values above 15 return (a_Skylight < 16)? a_Skylight : 0; } ",16165,True,3107.3635607401025,median "/* * Copyright 2002,2003-2004 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the ""License""); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an ""AS IS"" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* * $Id: WFXMLScanner.cpp 191707 2005-06-21 19:01:55Z cargilld $ */ // --------------------------------------------------------------------------- // Includes // --------------------------------------------------------------------------- #include #include #include #include #include #include #include #include #include #include #include XERCES_CPP_NAMESPACE_BEGIN // --------------------------------------------------------------------------- // WFXMLScanner: Constructors and Destructor // --------------------------------------------------------------------------- typedef JanitorMemFunCall CleanupType; typedef JanitorMemFunCall ReaderMgrResetType; WFXMLScanner::WFXMLScanner( XMLValidator* const valToAdopt , GrammarResolver* const grammarResolver , MemoryManager* const manager) : XMLScanner(valToAdopt, grammarResolver, manager) , fElementIndex(0) , fElements(0) , fEntityTable(0) , fAttrNameHashList(0) , fAttrNSList(0) , fElementLookup(0) { CleanupType cleanup(this, &WFXMLScanner::cleanUp); try { commonInit(); } catch(const OutOfMemoryException&) { // Don't cleanup when out of memory, since executing the // code can cause problems. cleanup.release(); throw; } cleanup.release(); } WFXMLScanner::WFXMLScanner( XMLDocumentHandler* const docHandler , DocTypeHandler* const docTypeHandler , XMLEntityHandler* const entityHandler , XMLErrorReporter* const errHandler , XMLValidator* const valToAdopt , GrammarResolver* const grammarResolver , MemoryManager* const manager) : XMLScanner(docHandler, docTypeHandler, entityHandler, errHandler, valToAdopt, grammarResolver, manager) , fElementIndex(0) , fElements(0) , fEntityTable(0) , fAttrNameHashList(0) , fAttrNSList(0) , fElementLookup(0) { CleanupType cleanup(this, &WFXMLScanner::cleanUp); try { commonInit(); } catch(const OutOfMemoryException&) { // Don't cleanup when out of memory, since executing the // code can cause problems. cleanup.release(); throw; } cleanup.release(); } WFXMLScanner::~WFXMLScanner() { cleanUp(); } // --------------------------------------------------------------------------- // XMLScanner: Getter methods // --------------------------------------------------------------------------- NameIdPool* WFXMLScanner::getEntityDeclPool() { return 0; } const NameIdPool* WFXMLScanner::getEntityDeclPool() const { return 0; } // --------------------------------------------------------------------------- // WFXMLScanner: Main entry point to scan a document // --------------------------------------------------------------------------- void WFXMLScanner::scanDocument(const InputSource& src) { // Bump up the sequence id for this parser instance. This will invalidate // any previous progressive scan tokens. fSequenceId++; ReaderMgrResetType resetReaderMgr(&fReaderMgr, &ReaderMgr::reset); try { // Reset the scanner and its plugged in stuff for a new run. This // resets all the data structures, creates the initial reader and // pushes it on the stack, and sets up the base document path. scanReset(src); // If we have a document handler, then call the start document if (fDocHandler) fDocHandler->startDocument(); // Scan the prolog part, which is everything before the root element // including the DTD subsets. scanProlog(); // If we got to the end of input, then its not a valid XML file. // Else, go on to scan the content. if (fReaderMgr.atEOF()) { emitError(XMLErrs::EmptyMainEntity); } else { // Scan content, and tell it its not an external entity if (scanContent()) { // That went ok, so scan for any miscellaneous stuff if (!fReaderMgr.atEOF()) scanMiscellaneous(); } } // If we have a document handler, then call the end document if (fDocHandler) fDocHandler->endDocument(); } // NOTE: // // In all of the error processing below, the emitError() call MUST come // before the flush of the reader mgr, or it will fail because it tries // to find out the position in the XML source of the error. catch(const XMLErrs::Codes) { // This is a 'first failure' exception, so fall through } catch(const XMLValid::Codes) { // This is a 'first fatal error' type exit, so fall through } catch(const XMLException& excToCatch) { // Emit the error and catch any user exception thrown from here. Make // sure in all cases we flush the reader manager. fInException = true; try { if (excToCatch.getErrorType() == XMLErrorReporter::ErrType_Warning) emitError ( XMLErrs::XMLException_Warning , excToCatch.getType() , excToCatch.getMessage() ); else if (excToCatch.getErrorType() >= XMLErrorReporter::ErrType_Fatal) emitError ( XMLErrs::XMLException_Fatal , excToCatch.getType() , excToCatch.getMessage() ); else emitError ( XMLErrs::XMLException_Error , excToCatch.getType() , excToCatch.getMessage() ); } catch(const OutOfMemoryException&) { // This is a special case for out-of-memory // conditions, because resetting the ReaderMgr // can be problematic. resetReaderMgr.release(); throw; } } catch(const OutOfMemoryException&) { // This is a special case for out-of-memory // conditions, because resetting the ReaderMgr // can be problematic. resetReaderMgr.release(); throw; } } bool WFXMLScanner::scanNext(XMLPScanToken& token) { // Make sure this token is still legal if (!isLegalToken(token)) ThrowXMLwithMemMgr(RuntimeException, XMLExcepts::Scan_BadPScanToken, fMemoryManager); // Find the next token and remember the reader id unsigned int orgReader; XMLTokens curToken; bool retVal = true; ReaderMgrResetType resetReaderMgr(&fReaderMgr, &ReaderMgr::reset); try { while (true) { // We have to handle any end of entity exceptions that happen here. // We could be at the end of X nested entities, each of which will // generate an end of entity exception as we try to move forward. try { curToken = senseNextToken(orgReader); break; } catch(const EndOfEntityException& toCatch) { // Send an end of entity reference event if (fDocHandler) fDocHandler->endEntityReference(toCatch.getEntity()); } } if (curToken == Token_CharData) { scanCharData(fCDataBuf); } else if (curToken == Token_EOF) { if (!fElemStack.isEmpty()) { const ElemStack::StackElem* topElem = fElemStack.popTop(); emitError ( XMLErrs::EndedWithTagsOnStack , topElem->fThisElement->getFullName() ); } retVal = false; } else { // Its some sort of markup bool gotData = true; switch(curToken) { case Token_CData : // Make sure we are within content if (fElemStack.isEmpty()) emitError(XMLErrs::CDATAOutsideOfContent); scanCDSection(); break; case Token_Comment : scanComment(); break; case Token_EndTag : scanEndTag(gotData); break; case Token_PI : scanPI(); break; case Token_StartTag : if (fDoNamespaces) scanStartTagNS(gotData); else scanStartTag(gotData); break; default : fReaderMgr.skipToChar(chOpenAngle); break; } if (orgReader != fReaderMgr.getCurrentReaderNum()) emitError(XMLErrs::PartialMarkupInEntity); // If we hit the end, then do the miscellaneous part if (!gotData) { // That went ok, so scan for any miscellaneous stuff scanMiscellaneous(); if (fDocHandler) fDocHandler->endDocument(); } } } // NOTE: // // In all of the error processing below, the emitError() call MUST come // before the flush of the reader mgr, or it will fail because it tries // to find out the position in the XML source of the error. catch(const XMLErrs::Codes) { // This is a 'first failure' exception, so return failure retVal = false; } catch(const XMLValid::Codes) { // This is a 'first fatal error' type exit, so return failure retVal = false; } catch(const XMLException& excToCatch) { // Emit the error and catch any user exception thrown from here. Make // sure in all cases we flush the reader manager. fInException = true; try { if (excToCatch.getErrorType() == XMLErrorReporter::ErrType_Warning) emitError ( XMLErrs::XMLException_Warning , excToCatch.getType() , excToCatch.getMessage() ); else if (excToCatch.getErrorType() >= XMLErrorReporter::ErrType_Fatal) emitError ( XMLErrs::XMLException_Fatal , excToCatch.getType() , excToCatch.getMessage() ); else emitError ( XMLErrs::XMLException_Error , excToCatch.getType() , excToCatch.getMessage() ); } catch(const OutOfMemoryException&) { // This is a special case for out-of-memory // conditions, because resetting the ReaderMgr // can be problematic. resetReaderMgr.release(); throw; } // Return failure retVal = false; } catch(const OutOfMemoryException&) { throw; } // If we are not at the end, release the object that will // reset the ReaderMgr. if (retVal) resetReaderMgr.release(); return retVal; } // --------------------------------------------------------------------------- // WFXMLScanner: Private helper methods. // --------------------------------------------------------------------------- // This method handles the common initialization, to avoid having to do // it redundantly in multiple constructors. void WFXMLScanner::commonInit() { fEntityTable = new (fMemoryManager) ValueHashTableOf(11, fMemoryManager); fAttrNameHashList = new (fMemoryManager)ValueVectorOf(16, fMemoryManager); fAttrNSList = new (fMemoryManager) ValueVectorOf(8, fMemoryManager); fElements = new (fMemoryManager) RefVectorOf(32, true, fMemoryManager); fElementLookup = new (fMemoryManager) RefHashTableOf(109, false, fMemoryManager); // Add the default entity entries for the character refs that must always // be present. fEntityTable->put((void*) XMLUni::fgAmp, chAmpersand); fEntityTable->put((void*) XMLUni::fgLT, chOpenAngle); fEntityTable->put((void*) XMLUni::fgGT, chCloseAngle); fEntityTable->put((void*) XMLUni::fgQuot, chDoubleQuote); fEntityTable->put((void*) XMLUni::fgApos, chSingleQuote); } void WFXMLScanner::cleanUp() { delete fEntityTable; delete fAttrNameHashList; delete fAttrNSList; delete fElementLookup; delete fElements; } unsigned int WFXMLScanner::resolvePrefix(const XMLCh* const prefix , const ElemStack::MapModes mode) { // Watch for the special namespace prefixes. We always map these to // special URIs. 'xml' gets mapped to the official URI that its defined // to map to by the NS spec. xmlns gets mapped to a special place holder // URI that we define (so that it maps to something checkable.) if (XMLString::equals(prefix, XMLUni::fgXMLNSString)) return fXMLNSNamespaceId; else if (XMLString::equals(prefix, XMLUni::fgXMLString)) return fXMLNamespaceId; // Ask the element stack to search up itself for a mapping for the // passed prefix. bool unknown; unsigned int uriId = fElemStack.mapPrefixToURI(prefix, mode, unknown); // If it was unknown, then the URI was faked in but we have to issue an error if (unknown) emitError(XMLErrs::UnknownPrefix, prefix); return uriId; } // This method will reset the scanner data structures, and related plugged // in stuff, for a new scan session. We get the input source for the primary // XML entity, create the reader for it, and push it on the stack so that // upon successful return from here we are ready to go. void WFXMLScanner::scanReset(const InputSource& src) { // For all installed handlers, send reset events. This gives them // a chance to flush any cached data. if (fDocHandler) fDocHandler->resetDocument(); if (fEntityHandler) fEntityHandler->resetEntities(); if (fErrorReporter) fErrorReporter->resetErrors(); // Reset the element stack, and give it the latest ids for the special // URIs it has to know about. fElemStack.reset ( fEmptyNamespaceId , fUnknownNamespaceId , fXMLNamespaceId , fXMLNSNamespaceId ); // Reset some status flags fInException = false; fStandalone = false; fErrorCount = 0; fHasNoDTD = true; fElementIndex = 0; // Reset elements lookup table fElementLookup->removeAll(); // Handle the creation of the XML reader object for this input source. // This will provide us with transcoding and basic lexing services. XMLReader* newReader = fReaderMgr.createReader ( src , true , XMLReader::RefFrom_NonLiteral , XMLReader::Type_General , XMLReader::Source_External , fCalculateSrcOfs ); if (!newReader) { if (src.getIssueFatalErrorIfNotFound()) ThrowXMLwithMemMgr1(RuntimeException, XMLExcepts::Scan_CouldNotOpenSource, src.getSystemId(), fMemoryManager); else ThrowXMLwithMemMgr1(RuntimeException, XMLExcepts::Scan_CouldNotOpenSource_Warning, src.getSystemId(), fMemoryManager); } // Push this read onto the reader manager fReaderMgr.pushReader(newReader, 0); // and reset security-related things if necessary: if(fSecurityManager != 0) { fEntityExpansionLimit = fSecurityManager->getEntityExpansionLimit(); fEntityExpansionCount = 0; } } // This method is called between markup in content. It scans for character // data that is sent to the document handler. It watches for any markup // characters that would indicate that the character data has ended. It also // handles expansion of general and character entities. // // sendData() is a local static helper for this method which handles some // code that must be done in three different places here. void WFXMLScanner::sendCharData(XMLBuffer& toSend) { // If no data in the buffer, then nothing to do if (toSend.isEmpty()) return; // Always assume its just char data if not validating if (fDocHandler) fDocHandler->docCharacters(toSend.getRawBuffer(), toSend.getLen(), false); // Reset buffer toSend.reset(); } // --------------------------------------------------------------------------- // WFXMLScanner: Private scanning methods // --------------------------------------------------------------------------- // This method will kick off the scanning of the primary content of the // document, i.e. the elements. bool WFXMLScanner::scanContent() { // Go into a loop until we hit the end of the root element, or we fall // out because there is no root element. // // We have to do kind of a deeply nested double loop here in order to // avoid doing the setup/teardown of the exception handler on each // round. Doing it this way we only do it when an exception actually // occurs. bool gotData = true; bool inMarkup = false; while (gotData) { try { while (gotData) { // Sense what the next top level token is. According to what // this tells us, we will call something to handle that kind // of thing. unsigned int orgReader; const XMLTokens curToken = senseNextToken(orgReader); // Handle character data and end of file specially. Char data // is not markup so we don't want to handle it in the loop // below. if (curToken == Token_CharData) { // Scan the character data and call appropriate events. Let // him use our local character data buffer for efficiency. scanCharData(fCDataBuf); continue; } else if (curToken == Token_EOF) { // The element stack better be empty at this point or we // ended prematurely before all elements were closed. if (!fElemStack.isEmpty()) { const ElemStack::StackElem* topElem = fElemStack.popTop(); emitError ( XMLErrs::EndedWithTagsOnStack , topElem->fThisElement->getFullName() ); } // Its the end of file, so clear the got data flag gotData = false; continue; } // We are in some sort of markup now inMarkup = true; // According to the token we got, call the appropriate // scanning method. switch(curToken) { case Token_CData : // Make sure we are within content if (fElemStack.isEmpty()) emitError(XMLErrs::CDATAOutsideOfContent); scanCDSection(); break; case Token_Comment : scanComment(); break; case Token_EndTag : scanEndTag(gotData); break; case Token_PI : scanPI(); break; case Token_StartTag : if (fDoNamespaces) scanStartTagNS(gotData); else scanStartTag(gotData); break; default : fReaderMgr.skipToChar(chOpenAngle); break; } if (orgReader != fReaderMgr.getCurrentReaderNum()) emitError(XMLErrs::PartialMarkupInEntity); // And we are back out of markup again inMarkup = false; } } catch(const EndOfEntityException& toCatch) { // If we were in some markup when this happened, then its a // partial markup error. if (inMarkup) emitError(XMLErrs::PartialMarkupInEntity); // Send an end of entity reference event if (fDocHandler) fDocHandler->endEntityReference(toCatch.getEntity()); inMarkup = false; } } // It went ok, so return success return true; } void WFXMLScanner::scanEndTag(bool& gotData) { // Assume we will still have data until proven otherwise. It will only // ever be false if this is the end of the root element. gotData = true; // Check if the element stack is empty. If so, then this is an unbalanced // element (i.e. more ends than starts, perhaps because of bad text // causing one to be skipped.) if (fElemStack.isEmpty()) { emitError(XMLErrs::MoreEndThanStartTags); fReaderMgr.skipPastChar(chCloseAngle); ThrowXMLwithMemMgr(RuntimeException, XMLExcepts::Scan_UnbalancedStartEnd, fMemoryManager); } // Pop the stack of the element we are supposed to be ending. Remember // that we don't own this. The stack just keeps them and reuses them. unsigned int uriId = (fDoNamespaces) ? fElemStack.getCurrentURI() : fEmptyNamespaceId; const ElemStack::StackElem* topElem = fElemStack.popTop(); // See if it was the root element, to avoid multiple calls below const bool isRoot = fElemStack.isEmpty(); // Make sure that its the end of the element that we expect if (!fReaderMgr.skippedString(topElem->fThisElement->getFullName())) { emitError ( XMLErrs::ExpectedEndOfTagX , topElem->fThisElement->getFullName() ); fReaderMgr.skipPastChar(chCloseAngle); return; } // Make sure we are back on the same reader as where we started if (topElem->fReaderNum != fReaderMgr.getCurrentReaderNum()) emitError(XMLErrs::PartialTagMarkupError); // Skip optional whitespace fReaderMgr.skipPastSpaces(); // Make sure we find the closing bracket if (!fReaderMgr.skippedChar(chCloseAngle)) { emitError ( XMLErrs::UnterminatedEndTag , topElem->fThisElement->getFullName() ); } // If we have a doc handler, tell it about the end tag if (fDocHandler) { fDocHandler->endElement ( *topElem->fThisElement , uriId , isRoot , topElem->fThisElement->getElementName()->getPrefix() ); } // If this was the root, then done with content gotData = !isRoot; } void WFXMLScanner::scanDocTypeDecl() { // Just skips over it // REVISIT: Should we issue a warning static const XMLCh doctypeIE[] = { chOpenSquare, chCloseAngle, chNull }; XMLCh nextCh = fReaderMgr.skipUntilIn(doctypeIE); if (nextCh == chOpenSquare) fReaderMgr.skipPastChar(chCloseSquare); fReaderMgr.skipPastChar(chCloseAngle); } bool WFXMLScanner::scanStartTag(bool& gotData) { // Assume we will still have data until proven otherwise. It will only // ever be false if this is the root and its empty. gotData = true; // Get the QName. In this case, we are not doing namespaces, so we just // use it as is and don't have to break it into parts. if (!fReaderMgr.getName(fQNameBuf)) { emitError(XMLErrs::ExpectedElementName); fReaderMgr.skipToChar(chOpenAngle); return false; } // Assume it won't be an empty tag bool isEmpty = false; // See if its the root element const bool isRoot = fElemStack.isEmpty(); // Lets try to look up the element const XMLCh* qnameRawBuf = fQNameBuf.getRawBuffer(); XMLElementDecl* elemDecl = fElementLookup->get(qnameRawBuf); if (!elemDecl) { if (fElementIndex < fElements->size()) { elemDecl = fElements->elementAt(fElementIndex); } else { elemDecl = new (fGrammarPoolMemoryManager) DTDElementDecl ( fGrammarPoolMemoryManager ); fElements->addElement(elemDecl); } elemDecl->setElementName(XMLUni::fgZeroLenString, qnameRawBuf, fEmptyNamespaceId); fElementLookup->put((void*)elemDecl->getFullName(), elemDecl); fElementIndex++; } // Expand the element stack and add the new element fElemStack.addLevel(elemDecl, fReaderMgr.getCurrentReaderNum()); // Skip any whitespace after the name fReaderMgr.skipPastSpaces(); // We loop until we either see a /> or >, handling attribute/value // pairs until we get there. unsigned int attCount = 0; unsigned int curAttListSize = fAttrList->size(); while (true) { // And get the next non-space character XMLCh nextCh = fReaderMgr.peekNextChar(); // If the next character is not a slash or closed angle bracket, // then it must be whitespace, since whitespace is required // between the end of the last attribute and the name of the next // one. if (attCount) { if ((nextCh != chForwardSlash) && (nextCh != chCloseAngle)) { if (fReaderMgr.getCurrentReader()->isWhitespace(nextCh)) { // Ok, skip by them and peek another char fReaderMgr.skipPastSpaces(); nextCh = fReaderMgr.peekNextChar(); } else { // Emit the error but keep on going emitError(XMLErrs::ExpectedWhitespace); } } } // Ok, here we first check for any of the special case characters. // If its not one, then we do the normal case processing, which // assumes that we've hit an attribute value, Otherwise, we do all // the special case checks. if (!fReaderMgr.getCurrentReader()->isSpecialStartTagChar(nextCh)) { // Assume its going to be an attribute, so get a name from // the input. if (!fReaderMgr.getName(fAttNameBuf)) { emitError(XMLErrs::ExpectedAttrName); fReaderMgr.skipPastChar(chCloseAngle); return false; } // And next must be an equal sign if (!scanEq()) { static const XMLCh tmpList[] = { chSingleQuote, chDoubleQuote, chCloseAngle , chOpenAngle, chForwardSlash, chNull }; emitError(XMLErrs::ExpectedEqSign); // Try to sync back up by skipping forward until we either // hit something meaningful. const XMLCh chFound = fReaderMgr.skipUntilInOrWS(tmpList); if ((chFound == chCloseAngle) || (chFound == chForwardSlash)) { // Jump back to top for normal processing of these continue; } else if ((chFound == chSingleQuote) || (chFound == chDoubleQuote) || fReaderMgr.getCurrentReader()->isWhitespace(chFound)) { // Just fall through assuming that the value is to follow } else if (chFound == chOpenAngle) { // Assume a malformed tag and that new one is starting emitError(XMLErrs::UnterminatedStartTag, qnameRawBuf); return false; } else { // Something went really wrong return false; } } // See if this attribute is declared more than one for this element. const XMLCh* attNameRawBuf = fAttNameBuf.getRawBuffer(); unsigned int attNameHash = XMLString::hash(attNameRawBuf, 109, fMemoryManager); if (attCount) { for (unsigned int k=0; k < attCount; k++) { if (fAttrNameHashList->elementAt(k) == attNameHash) { if ( XMLString::equals ( fAttrList->elementAt(k)->getName() , attNameRawBuf ) ) { emitError ( XMLErrs::AttrAlreadyUsedInSTag , attNameRawBuf , qnameRawBuf ); break; } } } } // Skip any whitespace before the value and then scan the att // value. This will come back normalized with entity refs and // char refs expanded. fReaderMgr.skipPastSpaces(); if (!scanAttValue(attNameRawBuf, fAttValueBuf)) { static const XMLCh tmpList[] = { chCloseAngle, chOpenAngle, chForwardSlash, chNull }; emitError(XMLErrs::ExpectedAttrValue); // It failed, so lets try to get synced back up. We skip // forward until we find some whitespace or one of the // chars in our list. const XMLCh chFound = fReaderMgr.skipUntilInOrWS(tmpList); if ((chFound == chCloseAngle) || (chFound == chForwardSlash) || fReaderMgr.getCurrentReader()->isWhitespace(chFound)) { // Just fall through and process this attribute, though // the value will be """". } else if (chFound == chOpenAngle) { // Assume a malformed tag and that new one is starting emitError(XMLErrs::UnterminatedStartTag, qnameRawBuf); return false; } else { // Something went really wrong return false; } } // Add this attribute to the attribute list that we use to // pass them to the handler. We reuse its existing elements // but expand it as required. XMLAttr* curAtt; if (attCount >= curAttListSize) { curAtt = new (fMemoryManager) XMLAttr ( 0 , attNameRawBuf , XMLUni::fgZeroLenString , fAttValueBuf.getRawBuffer() , XMLAttDef::CData , true , fMemoryManager ); fAttrList->addElement(curAtt); fAttrNameHashList->addElement(attNameHash); } else { curAtt = fAttrList->elementAt(attCount); curAtt->set ( 0 , attNameRawBuf , XMLUni::fgZeroLenString , fAttValueBuf.getRawBuffer() ); curAtt->setSpecified(true); fAttrNameHashList->setElementAt(attNameHash, attCount); } attCount++; // And jump back to the top of the loop continue; } // It was some special case character so do all of the checks and // deal with it. if (!nextCh) ThrowXMLwithMemMgr(UnexpectedEOFException, XMLExcepts::Gen_UnexpectedEOF, fMemoryManager); if (nextCh == chForwardSlash) { fReaderMgr.getNextChar(); isEmpty = true; if (!fReaderMgr.skippedChar(chCloseAngle)) emitError(XMLErrs::UnterminatedStartTag, qnameRawBuf); break; } else if (nextCh == chCloseAngle) { fReaderMgr.getNextChar(); break; } else if (nextCh == chOpenAngle) { // Check for this one specially, since its going to be common // and it is kind of auto-recovering since we've already hit the // next open bracket, which is what we would have seeked to (and // skipped this whole tag.) emitError(XMLErrs::UnterminatedStartTag, elemDecl->getFullName()); break; } else if ((nextCh == chSingleQuote) || (nextCh == chDoubleQuote)) { // Check for this one specially, which is probably a missing // attribute name, e.g. =""value"". Just issue expected name // error and eat the quoted string, then jump back to the // top again. emitError(XMLErrs::ExpectedAttrName); fReaderMgr.getNextChar(); fReaderMgr.skipQuotedString(nextCh); fReaderMgr.skipPastSpaces(); continue; } } // If empty, validate content right now if we are validating and then // pop the element stack top. Else, we have to update the current stack // top's namespace mapping elements. if (isEmpty) { // Pop the element stack back off since it'll never be used now fElemStack.popTop(); // If the elem stack is empty, then it was an empty root if (isRoot) gotData = false; } // If we have a document handler, then tell it about this start tag. We // don't have any URI id to send along, so send fEmptyNamespaceId. We also do not send // any prefix since its just one big name if we are not doing namespaces. if (fDocHandler) { fDocHandler->startElement ( *elemDecl , fEmptyNamespaceId , 0 , *fAttrList , attCount , isEmpty , isRoot ); } return true; } // This method is called to scan a start tag when we are processing // namespaces. There are two different versions of this method, one for // namespace aware processing an done for non-namespace aware processing. // // This method is called after we've scanned the < of a start tag. So we // have to get the element name, then scan the attributes, after which // we are either going to see >, />, or attributes followed by one of those // sequences. bool WFXMLScanner::scanStartTagNS(bool& gotData) { // Assume we will still have data until proven otherwise. It will only // ever be false if this is the root and its empty. gotData = true; // The current position is after the open bracket, so we need to read in // in the element name. int colonPosition; if (!fReaderMgr.getQName(fQNameBuf, &colonPosition)) { if (fQNameBuf.isEmpty()) emitError(XMLErrs::ExpectedElementName); else emitError(XMLErrs::InvalidElementName, fQNameBuf.getRawBuffer()); fReaderMgr.skipToChar(chOpenAngle); return false; } // See if its the root element const bool isRoot = fElemStack.isEmpty(); // Assume it won't be an empty tag bool isEmpty = false; // Skip any whitespace after the name fReaderMgr.skipPastSpaces(); // Lets try to look up the element const XMLCh* qnameRawBuf = fQNameBuf.getRawBuffer(); XMLElementDecl* elemDecl = fElementLookup->get(qnameRawBuf); if (!elemDecl) { if (!XMLString::compareNString(qnameRawBuf, XMLUni::fgXMLNSColonString, 6)) emitError(XMLErrs::NoXMLNSAsElementPrefix, qnameRawBuf); if (fElementIndex < fElements->size()) { elemDecl = fElements->elementAt(fElementIndex); } else { elemDecl = new (fGrammarPoolMemoryManager) DTDElementDecl ( fGrammarPoolMemoryManager ); fElements->addElement(elemDecl); } elemDecl->setElementName(qnameRawBuf, fEmptyNamespaceId); fElementLookup->put((void*)elemDecl->getFullName(), elemDecl); fElementIndex++; } // Expand the element stack and add the new element fElemStack.addLevel(elemDecl, fReaderMgr.getCurrentReaderNum()); // reset NS attribute list fAttrNSList->removeAllElements(); // We loop until we either see a /> or >, handling attribute/value // pairs until we get there. unsigned int attCount = 0; unsigned int curAttListSize = fAttrList->size(); while (true) { // And get the next non-space character XMLCh nextCh = fReaderMgr.peekNextChar(); // If the next character is not a slash or closed angle bracket, // then it must be whitespace, since whitespace is required // between the end of the last attribute and the name of the next // one. if (attCount) { if ((nextCh != chForwardSlash) && (nextCh != chCloseAngle)) { if (fReaderMgr.getCurrentReader()->isWhitespace(nextCh)) { // Ok, skip by them and peek another char fReaderMgr.skipPastSpaces(); nextCh = fReaderMgr.peekNextChar(); } else { // Emit the error but keep on going emitError(XMLErrs::ExpectedWhitespace); } } } // Ok, here we first check for any of the special case characters. // If its not one, then we do the normal case processing, which // assumes that we've hit an attribute value, Otherwise, we do all // the special case checks. if (!fReaderMgr.getCurrentReader()->isSpecialStartTagChar(nextCh)) { // Assume its going to be an attribute, so get a name from // the input. int colonPosition; if (!fReaderMgr.getQName(fAttNameBuf, &colonPosition)) { if (fAttNameBuf.isEmpty()) emitError(XMLErrs::ExpectedAttrName); else emitError(XMLErrs::InvalidAttrName, fAttNameBuf.getRawBuffer()); fReaderMgr.skipPastChar(chCloseAngle); return false; } // And next must be an equal sign if (!scanEq()) { static const XMLCh tmpList[] = { chSingleQuote, chDoubleQuote, chCloseAngle , chOpenAngle, chForwardSlash, chNull }; emitError(XMLErrs::ExpectedEqSign); // Try to sync back up by skipping forward until we either // hit something meaningful. const XMLCh chFound = fReaderMgr.skipUntilInOrWS(tmpList); if ((chFound == chCloseAngle) || (chFound == chForwardSlash)) { // Jump back to top for normal processing of these continue; } else if ((chFound == chSingleQuote) || (chFound == chDoubleQuote) || fReaderMgr.getCurrentReader()->isWhitespace(chFound)) { // Just fall through assuming that the value is to follow } else if (chFound == chOpenAngle) { // Assume a malformed tag and that new one is starting emitError(XMLErrs::UnterminatedStartTag, qnameRawBuf); return false; } else { // Something went really wrong return false; } } // See if this attribute is declared more than one for this element. const XMLCh* attNameRawBuf = fAttNameBuf.getRawBuffer(); unsigned int attNameHash = XMLString::hash(attNameRawBuf, 109, fMemoryManager); if (attCount) { for (unsigned int k=0; k < attCount; k++) { if (fAttrNameHashList->elementAt(k) == attNameHash) { if (XMLString::equals( fAttrList->elementAt(k)->getQName() , attNameRawBuf)) { emitError ( XMLErrs::AttrAlreadyUsedInSTag , attNameRawBuf , qnameRawBuf ); break; } } } } // Skip any whitespace before the value and then scan the att // value. This will come back normalized with entity refs and // char refs expanded. fReaderMgr.skipPastSpaces(); if (!scanAttValue(attNameRawBuf, fAttValueBuf)) { static const XMLCh tmpList[] = { chCloseAngle, chOpenAngle, chForwardSlash, chNull }; emitError(XMLErrs::ExpectedAttrValue); // It failed, so lets try to get synced back up. We skip // forward until we find some whitespace or one of the // chars in our list. const XMLCh chFound = fReaderMgr.skipUntilInOrWS(tmpList); if ((chFound == chCloseAngle) || (chFound == chForwardSlash) || fReaderMgr.getCurrentReader()->isWhitespace(chFound)) { // Just fall through and process this attribute, though // the value will be """". } else if (chFound == chOpenAngle) { // Assume a malformed tag and that new one is starting emitError(XMLErrs::UnterminatedStartTag, qnameRawBuf); return false; } else { // Something went really wrong return false; } } // Add this attribute to the attribute list that we use to // pass them to the handler. We reuse its existing elements // but expand it as required. const XMLCh* attValueRawBuf = fAttValueBuf.getRawBuffer(); XMLAttr* curAtt = 0; if (attCount >= curAttListSize) { curAtt = new (fMemoryManager) XMLAttr ( fEmptyNamespaceId , attNameRawBuf , attValueRawBuf , XMLAttDef::CData , true , fMemoryManager ); fAttrList->addElement(curAtt); fAttrNameHashList->addElement(attNameHash); } else { curAtt = fAttrList->elementAt(attCount); curAtt->set ( fEmptyNamespaceId , attNameRawBuf , attValueRawBuf ); curAtt->setSpecified(true); fAttrNameHashList->setElementAt(attNameHash, attCount); } // Map prefix to namespace const XMLCh* attPrefix = curAtt->getPrefix(); const XMLCh* attLocalName = curAtt->getName(); const XMLCh* namespaceURI = fAttValueBuf.getRawBuffer(); if (attPrefix && *attPrefix) { if (XMLString::equals(attPrefix, XMLUni::fgXMLString)) { curAtt->setURIId(fXMLNamespaceId); } else if (XMLString::equals(attPrefix, XMLUni::fgXMLNSString)) { if (XMLString::equals(attLocalName, XMLUni::fgXMLNSString)) emitError(XMLErrs::NoUseOfxmlnsAsPrefix); else if (XMLString::equals(attLocalName, XMLUni::fgXMLString)) { if (!XMLString::equals(namespaceURI, XMLUni::fgXMLURIName)) emitError(XMLErrs::PrefixXMLNotMatchXMLURI); } if (!namespaceURI) emitError(XMLErrs::NoEmptyStrNamespace, attNameRawBuf); else if(!*namespaceURI && fXMLVersion == XMLReader::XMLV1_0) emitError(XMLErrs::NoEmptyStrNamespace, attNameRawBuf); fElemStack.addPrefix ( attLocalName , fURIStringPool->addOrFind(namespaceURI) ); curAtt->setURIId(fXMLNSNamespaceId); } else { fAttrNSList->addElement(curAtt); } } else { if (XMLString::equals(XMLUni::fgXMLNSString, attLocalName)) { if (XMLString::equals(namespaceURI, XMLUni::fgXMLNSURIName)) emitError(XMLErrs::NoUseOfxmlnsURI); else if (XMLString::equals(namespaceURI, XMLUni::fgXMLURIName)) emitError(XMLErrs::XMLURINotMatchXMLPrefix); fElemStack.addPrefix ( XMLUni::fgZeroLenString , fURIStringPool->addOrFind(namespaceURI) ); } } // increment attribute count attCount++; // And jump back to the top of the loop continue; } // It was some special case character so do all of the checks and // deal with it. if (!nextCh) ThrowXMLwithMemMgr(UnexpectedEOFException, XMLExcepts::Gen_UnexpectedEOF, fMemoryManager); if (nextCh == chForwardSlash) { fReaderMgr.getNextChar(); isEmpty = true; if (!fReaderMgr.skippedChar(chCloseAngle)) emitError(XMLErrs::UnterminatedStartTag, qnameRawBuf); break; } else if (nextCh == chCloseAngle) { fReaderMgr.getNextChar(); break; } else if (nextCh == chOpenAngle) { // Check for this one specially, since its going to be common // and it is kind of auto-recovering since we've already hit the // next open bracket, which is what we would have seeked to (and // skipped this whole tag.) emitError(XMLErrs::UnterminatedStartTag, qnameRawBuf); break; } else if ((nextCh == chSingleQuote) || (nextCh == chDoubleQuote)) { // Check for this one specially, which is probably a missing // attribute name, e.g. =""value"". Just issue expected name // error and eat the quoted string, then jump back to the // top again. emitError(XMLErrs::ExpectedAttrName); fReaderMgr.getNextChar(); fReaderMgr.skipQuotedString(nextCh); fReaderMgr.skipPastSpaces(); continue; } } // Handle provided attributes that we did not map their prefixes for (unsigned int i=0; i < fAttrNSList->size(); i++) { XMLAttr* providedAttr = fAttrNSList->elementAt(i); providedAttr->setURIId ( resolvePrefix ( providedAttr->getPrefix(), ElemStack::Mode_Attribute ) ); } if(attCount) { // // Decide if to use hash table to do duplicate checking // bool toUseHashTable = false; setAttrDupChkRegistry(attCount, toUseHashTable); // check for duplicate namespace attributes: // by checking for qualified names with the same local part and with prefixes // which have been bound to namespace names that are identical. XMLAttr* loopAttr; XMLAttr* curAtt; for (unsigned int attrIndex=0; attrIndex < attCount-1; attrIndex++) { loopAttr = fAttrList->elementAt(attrIndex); if (!toUseHashTable) { for (unsigned int curAttrIndex = attrIndex+1; curAttrIndex < attCount; curAttrIndex++) { curAtt = fAttrList->elementAt(curAttrIndex); if (curAtt->getURIId() == loopAttr->getURIId() && XMLString::equals(curAtt->getName(), loopAttr->getName())) { emitError ( XMLErrs::AttrAlreadyUsedInSTag , curAtt->getName() , elemDecl->getFullName() ); } } } else { if (fAttrDupChkRegistry->containsKey((void*)loopAttr->getName(), loopAttr->getURIId())) { emitError ( XMLErrs::AttrAlreadyUsedInSTag , loopAttr->getName() , elemDecl->getFullName() ); } fAttrDupChkRegistry->put((void*)loopAttr->getName(), loopAttr->getURIId(), loopAttr); } } } // Resolve the qualified name to a URI. unsigned int uriId = resolvePrefix ( elemDecl->getElementName()->getPrefix() , ElemStack::Mode_Element ); // Now we can update the element stack fElemStack.setCurrentURI(uriId); // Tell the document handler about this start tag if (fDocHandler) { fDocHandler->startElement ( *elemDecl , uriId , elemDecl->getElementName()->getPrefix() , *fAttrList , attCount , false , isRoot ); } // If empty, validate content right now if we are validating and then // pop the element stack top. Else, we have to update the current stack // top's namespace mapping elements. if (isEmpty) { // Pop the element stack back off since it'll never be used now fElemStack.popTop(); // If we have a doc handler, tell it about the end tag if (fDocHandler) { fDocHandler->endElement ( *elemDecl , uriId , isRoot , elemDecl->getElementName()->getPrefix() ); } // If the elem stack is empty, then it was an empty root if (isRoot) gotData = false; } return true; } unsigned int WFXMLScanner::resolveQName(const XMLCh* const qName , XMLBuffer& prefixBuf , const short mode , int& prefixColonPos) { // Lets split out the qName into a URI and name buffer first. The URI // can be empty. prefixColonPos = XMLString::indexOf(qName, chColon); if (prefixColonPos == -1) { // Its all name with no prefix, so put the whole thing into the name // buffer. Then map the empty string to a URI, since the empty string // represents the default namespace. This will either return some // explicit URI which the default namespace is mapped to, or the // the default global namespace. bool unknown = false; prefixBuf.reset(); return fElemStack.mapPrefixToURI(XMLUni::fgZeroLenString, (ElemStack::MapModes) mode, unknown); } else { // Copy the chars up to but not including the colon into the prefix // buffer. prefixBuf.set(qName, prefixColonPos); // Watch for the special namespace prefixes. We always map these to // special URIs. 'xml' gets mapped to the official URI that its defined // to map to by the NS spec. xmlns gets mapped to a special place holder // URI that we define (so that it maps to something checkable.) const XMLCh* prefixRawBuf = prefixBuf.getRawBuffer(); if (XMLString::equals(prefixRawBuf, XMLUni::fgXMLNSString)) { // if this is an element, it is an error to have xmlns as prefix if (mode == ElemStack::Mode_Element) emitError(XMLErrs::NoXMLNSAsElementPrefix, qName); return fXMLNSNamespaceId; } else if (XMLString::equals(prefixRawBuf, XMLUni::fgXMLString)) { return fXMLNamespaceId; } else { bool unknown = false; unsigned int uriId = fElemStack.mapPrefixToURI(prefixRawBuf, (ElemStack::MapModes) mode, unknown); if (unknown) emitError(XMLErrs::UnknownPrefix, prefixRawBuf); return uriId; } } } // --------------------------------------------------------------------------- // XMLScanner: Private parsing methods // --------------------------------------------------------------------------- bool WFXMLScanner::scanAttValue(const XMLCh* const attrName , XMLBuffer& toFill) { // Reset the target buffer toFill.reset(); // Get the next char which must be a single or double quote XMLCh quoteCh; if (!fReaderMgr.skipIfQuote(quoteCh)) return false; // We have to get the current reader because we have to ignore closing // quotes until we hit the same reader again. const unsigned int curReader = fReaderMgr.getCurrentReaderNum(); // Loop until we get the attribute value. Note that we use a double // loop here to avoid the setup/teardown overhead of the exception // handler on every round. XMLCh nextCh; XMLCh secondCh = 0; bool gotLeadingSurrogate = false; bool escaped; while (true) { try { while(true) { nextCh = fReaderMgr.getNextChar(); if (!nextCh) ThrowXMLwithMemMgr(UnexpectedEOFException, XMLExcepts::Gen_UnexpectedEOF, fMemoryManager); // Check for our ending quote in the same entity if (nextCh == quoteCh) { if (curReader == fReaderMgr.getCurrentReaderNum()) return true; // Watch for spillover into a previous entity if (curReader > fReaderMgr.getCurrentReaderNum()) { emitError(XMLErrs::PartialMarkupInEntity); return false; } } // Check for an entity ref now, before we let it affect our // whitespace normalization logic below. We ignore the empty flag // in this one. escaped = false; if (nextCh == chAmpersand) { if (scanEntityRef(true, nextCh, secondCh, escaped) != EntityExp_Returned) { gotLeadingSurrogate = false; continue; } } else if ((nextCh >= 0xD800) && (nextCh <= 0xDBFF)) { // Deal with surrogate pairs // Its a leading surrogate. If we already got one, then // issue an error, else set leading flag to make sure that // we look for a trailing next time. if (gotLeadingSurrogate) { emitError(XMLErrs::Expected2ndSurrogateChar); } else gotLeadingSurrogate = true; } else { // If its a trailing surrogate, make sure that we are // prepared for that. Else, its just a regular char so make // sure that we were not expected a trailing surrogate. if ((nextCh >= 0xDC00) && (nextCh <= 0xDFFF)) { // Its trailing, so make sure we were expecting it if (!gotLeadingSurrogate) emitError(XMLErrs::Unexpected2ndSurrogateChar); } else { // Its just a char, so make sure we were not expecting a // trailing surrogate. if (gotLeadingSurrogate) { emitError(XMLErrs::Expected2ndSurrogateChar); } // Its got to at least be a valid XML character else if (!fReaderMgr.getCurrentReader()->isXMLChar(nextCh)) { XMLCh tmpBuf[9]; XMLString::binToText ( nextCh , tmpBuf , 8 , 16 , fMemoryManager ); emitError(XMLErrs::InvalidCharacterInAttrValue, attrName, tmpBuf); } } gotLeadingSurrogate = false; } // If its not escaped, then make sure its not a < character, which // is not allowed in attribute values. if (!escaped) { if (nextCh == chOpenAngle) emitError(XMLErrs::BracketInAttrValue, attrName); else if (fReaderMgr.getCurrentReader()->isWhitespace(nextCh)) nextCh = chSpace; } // Else add it to the buffer toFill.append(nextCh); if (secondCh) { toFill.append(secondCh); secondCh=0; } } } catch(const EndOfEntityException&) { // Just eat it and continue. gotLeadingSurrogate = false; escaped = false; } } return true; } // This method scans a CDATA section. It collects the character into one // of the temp buffers and calls the document handler, if any, with the // characters. It assumes that the docCharacters ( bbCData.getRawBuffer() , bbCData.getLen() , true ); } // And we are done break; } // Make sure its a valid character. But if we've emitted an error // already, don't bother with the overhead since we've already told // them about it. if (!emittedError) { // Deal with surrogate pairs if ((nextCh >= 0xD800) && (nextCh <= 0xDBFF)) { // Its a leading surrogate. If we already got one, then // issue an error, else set leading flag to make sure that // we look for a trailing next time. if (gotLeadingSurrogate) emitError(XMLErrs::Expected2ndSurrogateChar); else gotLeadingSurrogate = true; } else { // If its a trailing surrogate, make sure that we are // prepared for that. Else, its just a regular char so make // sure that we were not expected a trailing surrogate. if ((nextCh >= 0xDC00) && (nextCh <= 0xDFFF)) { // Its trailing, so make sure we were expecting it if (!gotLeadingSurrogate) emitError(XMLErrs::Unexpected2ndSurrogateChar); } else { // Its just a char, so make sure we were not expecting a // trailing surrogate. if (gotLeadingSurrogate) emitError(XMLErrs::Expected2ndSurrogateChar); // Its got to at least be a valid XML character else if (!fReaderMgr.getCurrentReader()->isXMLChar(nextCh)) { XMLCh tmpBuf[9]; XMLString::binToText ( nextCh , tmpBuf , 8 , 16 , fMemoryManager ); emitError(XMLErrs::InvalidCharacter, tmpBuf); emittedError = true; } } gotLeadingSurrogate = false; } } // Add it to the buffer bbCData.append(nextCh); } } void WFXMLScanner::scanCharData(XMLBuffer& toUse) { // We have to watch for the stupid ]]> sequence, which is illegal in // character data. So this is a little state machine that handles that. enum States { State_Waiting , State_GotOne , State_GotTwo }; // Reset the buffer before we start toUse.reset(); // Turn on the 'throw at end' flag of the reader manager ThrowEOEJanitor jan(&fReaderMgr, true); // In order to be more efficient we have to use kind of a deeply nested // set of blocks here. The outer block puts on a try and catches end of // entity exceptions. The inner loop is the per-character loop. If we // put the try inside the inner loop, it would work but would require // the exception handling code setup/teardown code to be invoked for // each character. XMLCh nextCh; XMLCh secondCh = 0; States curState = State_Waiting; bool escaped = false; bool gotLeadingSurrogate = false; bool notDone = true; while (notDone) { try { while (true) { // Eat through as many plain content characters as possible without // needing special handling. Moving most content characters here, // in this one call, rather than running the overall loop once // per content character, is a speed optimization. if (curState == State_Waiting && !gotLeadingSurrogate) { fReaderMgr.movePlainContentChars(toUse); } // Try to get another char from the source // The code from here on down covers all contengencies, if (!fReaderMgr.getNextCharIfNot(chOpenAngle, nextCh)) { // If we were waiting for a trailing surrogate, its an error if (gotLeadingSurrogate) emitError(XMLErrs::Expected2ndSurrogateChar); notDone = false; break; } // Watch for a reference. Note that the escapement mechanism // is ignored in this content. escaped = false; if (nextCh == chAmpersand) { sendCharData(toUse); // Turn off the throwing at the end of entity during this ThrowEOEJanitor jan(&fReaderMgr, false); if (scanEntityRef(false, nextCh, secondCh, escaped) != EntityExp_Returned) { gotLeadingSurrogate = false; continue; } } else if ((nextCh >= 0xD800) && (nextCh <= 0xDBFF)) { // Deal with surrogate pairs // Its a leading surrogate. If we already got one, then // issue an error, else set leading flag to make sure that // we look for a trailing next time. if (gotLeadingSurrogate) { emitError(XMLErrs::Expected2ndSurrogateChar); } else gotLeadingSurrogate = true; } else { // If its a trailing surrogate, make sure that we are // prepared for that. Else, its just a regular char so make // sure that we were not expected a trailing surrogate. if ((nextCh >= 0xDC00) && (nextCh <= 0xDFFF)) { // Its trailing, so make sure we were expecting it if (!gotLeadingSurrogate) emitError(XMLErrs::Unexpected2ndSurrogateChar); } else { // Its just a char, so make sure we were not expecting a // trailing surrogate. if (gotLeadingSurrogate) { emitError(XMLErrs::Expected2ndSurrogateChar); } // Its got to at least be a valid XML character else if (!fReaderMgr.getCurrentReader()->isXMLChar(nextCh)) { XMLCh tmpBuf[9]; XMLString::binToText ( nextCh , tmpBuf , 8 , 16 , fMemoryManager ); emitError(XMLErrs::InvalidCharacter, tmpBuf); } } gotLeadingSurrogate = false; } // Keep the state machine up to date if (!escaped) { if (nextCh == chCloseSquare) { if (curState == State_Waiting) curState = State_GotOne; else if (curState == State_GotOne) curState = State_GotTwo; } else if (nextCh == chCloseAngle) { if (curState == State_GotTwo) emitError(XMLErrs::BadSequenceInCharData); curState = State_Waiting; } else { curState = State_Waiting; } } else { curState = State_Waiting; } // Add this char to the buffer toUse.append(nextCh); if (secondCh) { toUse.append(secondCh); secondCh=0; } } } catch(const EndOfEntityException& toCatch) { // Some entity ended, so we have to send any accumulated // chars and send an end of entity event. sendCharData(toUse); gotLeadingSurrogate = false; if (fDocHandler) fDocHandler->endEntityReference(toCatch.getEntity()); } } // Send any char data that we accumulated into the buffer sendCharData(toUse); } InputSource* WFXMLScanner::resolveSystemId(const XMLCh* const /*sysId*/ ,const XMLCh* const /*pubId*/) { return 0; } // This method will scan a general/character entity ref. It will either // expand a char ref and return it directly, or push a reader for a general // entity. // // The return value indicates whether the char parameters hold the value // or whether the value was pushed as a reader, or that it failed. // // The escaped flag tells the caller whether the returned parameter resulted // from a character reference, which escapes the character in some cases. It // only makes any difference if the return value indicates the value was // returned directly. XMLScanner::EntityExpRes WFXMLScanner::scanEntityRef(const bool , XMLCh& firstCh , XMLCh& secondCh , bool& escaped) { // Assume no escape secondCh = 0; escaped = false; // We have to insure that its all in one entity const unsigned int curReader = fReaderMgr.getCurrentReaderNum(); // If the next char is a pound, then its a character reference and we // need to expand it always. if (fReaderMgr.skippedChar(chPound)) { // Its a character reference, so scan it and get back the numeric // value it represents. if (!scanCharRef(firstCh, secondCh)) return EntityExp_Failed; escaped = true; if (curReader != fReaderMgr.getCurrentReaderNum()) emitError(XMLErrs::PartialMarkupInEntity); return EntityExp_Returned; } // Expand it since its a normal entity ref XMLBufBid bbName(&fBufMgr); if (!fReaderMgr.getName(bbName.getBuffer())) { emitError(XMLErrs::ExpectedEntityRefName); return EntityExp_Failed; } // Next char must be a semi-colon. But if its not, just emit // an error and try to continue. if (!fReaderMgr.skippedChar(chSemiColon)) emitError(XMLErrs::UnterminatedEntityRef, bbName.getRawBuffer()); // Make sure we ended up on the same entity reader as the & char if (curReader != fReaderMgr.getCurrentReaderNum()) emitError(XMLErrs::PartialMarkupInEntity); // Look up the name in the general entity pool // If it does not exist, then obviously an error if (!fEntityTable->containsKey(bbName.getRawBuffer())) { // XML 1.0 Section 4.1 // Well-formedness Constraint for entity not found: // In a document without any DTD, a document with only an internal DTD subset which contains no parameter entity references, // or a document with ""standalone='yes'"", for an entity reference that does not occur within the external subset // or a parameter entity if (fStandalone || fHasNoDTD) emitError(XMLErrs::EntityNotFound, bbName.getRawBuffer()); return EntityExp_Failed; } // here's where we need to check if there's a SecurityManager, // how many entity references we've had if(fSecurityManager != 0 && ++fEntityExpansionCount > fEntityExpansionLimit) { XMLCh expLimStr[16]; XMLString::binToText(fEntityExpansionLimit, expLimStr, 15, 10, fMemoryManager); emitError ( XMLErrs::EntityExpansionLimitExceeded , expLimStr ); // there seems nothing better to be done than to reset the entity expansion counter fEntityExpansionCount = 0; } firstCh = fEntityTable->get(bbName.getRawBuffer()); escaped = true; return EntityExp_Returned; } // --------------------------------------------------------------------------- // WFXMLScanner: Grammar preparsing // --------------------------------------------------------------------------- Grammar* WFXMLScanner::loadGrammar(const InputSource& , const short , const bool) { // REVISIT: emit a warning or throw an exception return 0; } XERCES_CPP_NAMESPACE_END ",16138,True,3222.9574474383694,median "//===--- TUScheduler.cpp -----------------------------------------*-C++-*-===// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// // TUScheduler manages a worker per active file. This ASTWorker processes // updates (modifications to file contents) and reads (actions performed on // preamble/AST) to the file. // // Each ASTWorker owns a dedicated thread to process updates and reads to the // relevant file. Any request gets queued in FIFO order to be processed by that // thread. // // An update request replaces current praser inputs to ensure any subsequent // read sees the version of the file they were requested. It will also issue a // build for new inputs. // // ASTWorker processes the file in two parts, a preamble and a main-file // section. A preamble can be reused between multiple versions of the file until // invalidated by a modification to a header, compile commands or modification // to relevant part of the current file. Such a preamble is called compatible. // An update is considered dead if no read was issued for that version and // diagnostics weren't requested by client or could be generated for a later // version of the file. ASTWorker eliminates such requests as they are // redundant. // // In the presence of stale (non-compatible) preambles, ASTWorker won't publish // diagnostics for update requests. Read requests will be served with ASTs build // with stale preambles, unless the read is picky and requires a compatible // preamble. In such cases it will block until new preamble is built. // // ASTWorker owns a PreambleThread for building preambles. If the preamble gets // invalidated by an update request, a new build will be requested on // PreambleThread. Since PreambleThread only receives requests for newer // versions of the file, in case of multiple requests it will only build the // last one and skip requests in between. Unless client force requested // diagnostics(WantDiagnostics::Yes). // // When a new preamble is built, a ""golden"" AST is immediately built from that // version of the file. This ensures diagnostics get updated even if the queue // is full. // // Some read requests might just need preamble. Since preambles can be read // concurrently, ASTWorker runs these requests on their own thread. These // requests will receive latest build preamble, which might possibly be stale. #include ""TUScheduler.h"" #include ""Compiler.h"" #include ""Diagnostics.h"" #include ""GlobalCompilationDatabase.h"" #include ""ParsedAST.h"" #include ""Preamble.h"" #include ""index/CanonicalIncludes.h"" #include ""support/Cancellation.h"" #include ""support/Context.h"" #include ""support/Logger.h"" #include ""support/MemoryTree.h"" #include ""support/Path.h"" #include ""support/ThreadCrashReporter.h"" #include ""support/Threading.h"" #include ""support/Trace.h"" #include ""clang/Frontend/CompilerInvocation.h"" #include ""clang/Tooling/CompilationDatabase.h"" #include ""llvm/ADT/FunctionExtras.h"" #include ""llvm/ADT/None.h"" #include ""llvm/ADT/Optional.h"" #include ""llvm/ADT/STLExtras.h"" #include ""llvm/ADT/ScopeExit.h"" #include ""llvm/ADT/SmallVector.h"" #include ""llvm/ADT/StringExtras.h"" #include ""llvm/ADT/StringRef.h"" #include ""llvm/Support/Allocator.h"" #include ""llvm/Support/Errc.h"" #include ""llvm/Support/ErrorHandling.h"" #include ""llvm/Support/FormatVariadic.h"" #include ""llvm/Support/Path.h"" #include ""llvm/Support/Threading.h"" #include ""llvm/Support/raw_ostream.h"" #include #include #include #include #include #include #include #include #include #include #include #include #include namespace clang { namespace clangd { using std::chrono::steady_clock; namespace { class ASTWorker; } // namespace static clang::clangd::Key kFileBeingProcessed; llvm::Optional TUScheduler::getFileBeingProcessedInContext() { if (auto *File = Context::current().get(kFileBeingProcessed)) return llvm::StringRef(*File); return None; } /// An LRU cache of idle ASTs. /// Because we want to limit the overall number of these we retain, the cache /// owns ASTs (and may evict them) while their workers are idle. /// Workers borrow ASTs when active, and return them when done. class TUScheduler::ASTCache { public: using Key = const ASTWorker *; ASTCache(unsigned MaxRetainedASTs) : MaxRetainedASTs(MaxRetainedASTs) {} /// Returns result of getUsedBytes() for the AST cached by \\p K. /// If no AST is cached, 0 is returned. std::size_t getUsedBytes(Key K) { std::lock_guard Lock(Mut); auto It = findByKey(K); if (It == LRU.end() || !It->second) return 0; return It->second->getUsedBytes(); } /// Store the value in the pool, possibly removing the last used AST. /// The value should not be in the pool when this function is called. void put(Key K, std::unique_ptr V) { std::unique_lock Lock(Mut); assert(findByKey(K) == LRU.end()); LRU.insert(LRU.begin(), {K, std::move(V)}); if (LRU.size() <= MaxRetainedASTs) return; // We're past the limit, remove the last element. std::unique_ptr ForCleanup = std::move(LRU.back().second); LRU.pop_back(); // Run the expensive destructor outside the lock. Lock.unlock(); ForCleanup.reset(); } /// Returns the cached value for \\p K, or llvm::None if the value is not in /// the cache anymore. If nullptr was cached for \\p K, this function will /// return a null unique_ptr wrapped into an optional. /// If \\p AccessMetric is set records whether there was a hit or miss. llvm::Optional> take(Key K, const trace::Metric *AccessMetric = nullptr) { // Record metric after unlocking the mutex. std::unique_lock Lock(Mut); auto Existing = findByKey(K); if (Existing == LRU.end()) { if (AccessMetric) AccessMetric->record(1, ""miss""); return None; } if (AccessMetric) AccessMetric->record(1, ""hit""); std::unique_ptr V = std::move(Existing->second); LRU.erase(Existing); // GCC 4.8 fails to compile `return V;`, as it tries to call the copy // constructor of unique_ptr, so we call the move ctor explicitly to avoid // this miscompile. return llvm::Optional>(std::move(V)); } private: using KVPair = std::pair>; std::vector::iterator findByKey(Key K) { return llvm::find_if(LRU, [K](const KVPair &P) { return P.first == K; }); } std::mutex Mut; unsigned MaxRetainedASTs; /// Items sorted in LRU order, i.e. first item is the most recently accessed /// one. std::vector LRU; /* GUARDED_BY(Mut) */ }; /// A map from header files to an opened ""proxy"" file that includes them. /// If you open the header, the compile command from the proxy file is used. /// /// This inclusion information could also naturally live in the index, but there /// are advantages to using open files instead: /// - it's easier to achieve a *stable* choice of proxy, which is important /// to avoid invalidating the preamble /// - context-sensitive flags for libraries with multiple configurations /// (e.g. C++ stdlib sensitivity to -std version) /// - predictable behavior, e.g. guarantees that go-to-def landing on a header /// will have a suitable command available /// - fewer scaling problems to solve (project include graphs are big!) /// /// Implementation details: /// - We only record this for mainfiles where the command was trustworthy /// (i.e. not inferred). This avoids a bad inference ""infecting"" other files. /// - Once we've picked a proxy file for a header, we stick with it until the /// proxy file is invalidated *and* a new candidate proxy file is built. /// Switching proxies is expensive, as the compile flags will (probably) /// change and therefore we'll end up rebuilding the header's preamble. /// - We don't capture the actual compile command, but just the filename we /// should query to get it. This avoids getting out of sync with the CDB. /// /// All methods are threadsafe. In practice, update() comes from preamble /// threads, remove()s mostly from the main thread, and get() from ASTWorker. /// Writes are rare and reads are cheap, so we don't expect much contention. class TUScheduler::HeaderIncluderCache { // We should be be a little careful how we store the include graph of open // files, as each can have a large number of transitive headers. // This representation is O(unique transitive source files). llvm::BumpPtrAllocator Arena; struct Association { llvm::StringRef MainFile; // Circular-linked-list of associations with the same mainFile. // Null indicates that the mainfile was removed. Association *Next; }; llvm::StringMap HeaderToMain; llvm::StringMap MainToFirst; std::atomic UsedBytes; // Updated after writes. mutable std::mutex Mu; void invalidate(Association *First) { Association *Current = First; do { Association *Next = Current->Next; Current->Next = nullptr; Current = Next; } while (Current != First); } // Create the circular list and return the head of it. Association *associate(llvm::StringRef MainFile, llvm::ArrayRef Headers) { Association *First = nullptr, *Prev = nullptr; for (const std::string &Header : Headers) { auto &Assoc = HeaderToMain[Header]; if (Assoc.Next) continue; // Already has a valid association. Assoc.MainFile = MainFile; Assoc.Next = Prev; Prev = &Assoc; if (!First) First = &Assoc; } if (First) First->Next = Prev; return First; } void updateMemoryUsage() { auto StringMapHeap = [](const auto &Map) { // StringMap stores the hashtable on the heap. // It contains pointers to the entries, and a hashcode for each. return Map.getNumBuckets() * (sizeof(void *) + sizeof(unsigned)); }; size_t Usage = Arena.getTotalMemory() + StringMapHeap(MainToFirst) + StringMapHeap(HeaderToMain) + sizeof(*this); UsedBytes.store(Usage, std::memory_order_release); } public: HeaderIncluderCache() : HeaderToMain(Arena), MainToFirst(Arena) { updateMemoryUsage(); } // Associate each header with MainFile (unless already associated). // Headers not in the list will have their associations removed. void update(PathRef MainFile, llvm::ArrayRef Headers) { std::lock_guard Lock(Mu); auto It = MainToFirst.try_emplace(MainFile, nullptr); Association *&First = It.first->second; if (First) invalidate(First); First = associate(It.first->first(), Headers); updateMemoryUsage(); } // Mark MainFile as gone. // This will *not* disassociate headers with MainFile immediately, but they // will be eligible for association with other files that get update()d. void remove(PathRef MainFile) { std::lock_guard Lock(Mu); Association *&First = MainToFirst[MainFile]; if (First) { invalidate(First); First = nullptr; } // MainToFirst entry should stay alive, as Associations might be pointing at // its key. } /// Get the mainfile associated with Header, or the empty string if none. std::string get(PathRef Header) const { std::lock_guard Lock(Mu); return HeaderToMain.lookup(Header).MainFile.str(); } size_t getUsedBytes() const { return UsedBytes.load(std::memory_order_acquire); } }; namespace { bool isReliable(const tooling::CompileCommand &Cmd) { return Cmd.Heuristic.empty(); } /// Threadsafe manager for updating a TUStatus and emitting it after each /// update. class SynchronizedTUStatus { public: SynchronizedTUStatus(PathRef FileName, ParsingCallbacks &Callbacks) : FileName(FileName), Callbacks(Callbacks) {} void update(llvm::function_ref Mutator) { std::lock_guard Lock(StatusMu); Mutator(Status); emitStatusLocked(); } /// Prevents emitting of further updates. void stop() { std::lock_guard Lock(StatusMu); CanPublish = false; } private: void emitStatusLocked() { if (CanPublish) Callbacks.onFileUpdated(FileName, Status); } const Path FileName; std::mutex StatusMu; TUStatus Status; bool CanPublish = true; ParsingCallbacks &Callbacks; }; /// Responsible for building preambles. Whenever the thread is idle and the /// preamble is outdated, it starts to build a fresh preamble from the latest /// inputs. If RunSync is true, preambles are built synchronously in update() /// instead. class PreambleThread { public: PreambleThread(llvm::StringRef FileName, ParsingCallbacks &Callbacks, bool StorePreambleInMemory, bool RunSync, SynchronizedTUStatus &Status, TUScheduler::HeaderIncluderCache &HeaderIncluders, ASTWorker &AW) : FileName(FileName), Callbacks(Callbacks), StoreInMemory(StorePreambleInMemory), RunSync(RunSync), Status(Status), ASTPeer(AW), HeaderIncluders(HeaderIncluders) {} /// It isn't guaranteed that each requested version will be built. If there /// are multiple update requests while building a preamble, only the last one /// will be built. void update(std::unique_ptr CI, ParseInputs PI, std::vector CIDiags, WantDiagnostics WantDiags) { Request Req = {std::move(CI), std::move(PI), std::move(CIDiags), WantDiags, Context::current().clone()}; if (RunSync) { build(std::move(Req)); Status.update([](TUStatus &Status) { Status.PreambleActivity = PreambleAction::Idle; }); return; } { std::unique_lock Lock(Mutex); // If NextReq was requested with WantDiagnostics::Yes we cannot just drop // that on the floor. Block until we start building it. This won't // dead-lock as we are blocking the caller thread, while builds continue // on preamble thread. ReqCV.wait(Lock, [this] { return !NextReq || NextReq->WantDiags != WantDiagnostics::Yes; }); NextReq = std::move(Req); } // Let the worker thread know there's a request, notify_one is safe as there // should be a single worker thread waiting on it. ReqCV.notify_all(); } void run() { while (true) { { std::unique_lock Lock(Mutex); assert(!CurrentReq && ""Already processing a request?""); // Wait until stop is called or there is a request. ReqCV.wait(Lock, [this] { return NextReq || Done; }); if (Done) break; CurrentReq = std::move(*NextReq); NextReq.reset(); } { WithContext Guard(std::move(CurrentReq->Ctx)); // Note that we don't make use of the ContextProvider here. // Preamble tasks are always scheduled by ASTWorker tasks, and we // reuse the context/config that was created at that level. // Build the preamble and let the waiters know about it. build(std::move(*CurrentReq)); } bool IsEmpty = false; { std::lock_guard Lock(Mutex); CurrentReq.reset(); IsEmpty = !NextReq.hasValue(); } if (IsEmpty) { // We don't perform this above, before waiting for a request to make // tests more deterministic. As there can be a race between this thread // and client thread(clangdserver). Status.update([](TUStatus &Status) { Status.PreambleActivity = PreambleAction::Idle; }); } ReqCV.notify_all(); } dlog(""Preamble worker for {0} stopped"", FileName); } /// Signals the run loop to exit. void stop() { dlog(""Preamble worker for {0} received stop"", FileName); { std::lock_guard Lock(Mutex); Done = true; NextReq.reset(); } // Let the worker thread know that it should stop. ReqCV.notify_all(); } bool blockUntilIdle(Deadline Timeout) const { std::unique_lock Lock(Mutex); return wait(Lock, ReqCV, Timeout, [&] { return !NextReq && !CurrentReq; }); } private: /// Holds inputs required for building a preamble. CI is guaranteed to be /// non-null. struct Request { std::unique_ptr CI; ParseInputs Inputs; std::vector CIDiags; WantDiagnostics WantDiags; Context Ctx; }; bool isDone() { std::lock_guard Lock(Mutex); return Done; } /// Builds a preamble for \\p Req, might reuse LatestBuild if possible. /// Notifies ASTWorker after build finishes. void build(Request Req); mutable std::mutex Mutex; bool Done = false; /* GUARDED_BY(Mutex) */ llvm::Optional NextReq; /* GUARDED_BY(Mutex) */ llvm::Optional CurrentReq; /* GUARDED_BY(Mutex) */ // Signaled whenever a thread populates NextReq or worker thread builds a // Preamble. mutable std::condition_variable ReqCV; /* GUARDED_BY(Mutex) */ // Accessed only by preamble thread. std::shared_ptr LatestBuild; const Path FileName; ParsingCallbacks &Callbacks; const bool StoreInMemory; const bool RunSync; SynchronizedTUStatus &Status; ASTWorker &ASTPeer; TUScheduler::HeaderIncluderCache &HeaderIncluders; }; class ASTWorkerHandle; /// Owns one instance of the AST, schedules updates and reads of it. /// Also responsible for building and providing access to the preamble. /// Each ASTWorker processes the async requests sent to it on a separate /// dedicated thread. /// The ASTWorker that manages the AST is shared by both the processing thread /// and the TUScheduler. The TUScheduler should discard an ASTWorker when /// remove() is called, but its thread may be busy and we don't want to block. /// So the workers are accessed via an ASTWorkerHandle. Destroying the handle /// signals the worker to exit its run loop and gives up shared ownership of the /// worker. class ASTWorker { friend class ASTWorkerHandle; ASTWorker(PathRef FileName, const GlobalCompilationDatabase &CDB, TUScheduler::ASTCache &LRUCache, TUScheduler::HeaderIncluderCache &HeaderIncluders, Semaphore &Barrier, bool RunSync, const TUScheduler::Options &Opts, ParsingCallbacks &Callbacks); public: /// Create a new ASTWorker and return a handle to it. /// The processing thread is spawned using \\p Tasks. However, when \\p Tasks /// is null, all requests will be processed on the calling thread /// synchronously instead. \\p Barrier is acquired when processing each /// request, it is used to limit the number of actively running threads. static ASTWorkerHandle create(PathRef FileName, const GlobalCompilationDatabase &CDB, TUScheduler::ASTCache &IdleASTs, TUScheduler::HeaderIncluderCache &HeaderIncluders, AsyncTaskRunner *Tasks, Semaphore &Barrier, const TUScheduler::Options &Opts, ParsingCallbacks &Callbacks); ~ASTWorker(); void update(ParseInputs Inputs, WantDiagnostics, bool ContentChanged); void runWithAST(llvm::StringRef Name, llvm::unique_function)> Action, TUScheduler::ASTActionInvalidation); bool blockUntilIdle(Deadline Timeout) const; std::shared_ptr getPossiblyStalePreamble( std::shared_ptr *ASTSignals = nullptr) const; /// Used to inform ASTWorker about a new preamble build by PreambleThread. /// Diagnostics are only published through this callback. This ensures they /// are always for newer versions of the file, as the callback gets called in /// the same order as update requests. void updatePreamble(std::unique_ptr CI, ParseInputs PI, std::shared_ptr Preamble, std::vector CIDiags, WantDiagnostics WantDiags); /// Obtain a preamble reflecting all updates so far. Threadsafe. /// It may be delivered immediately, or later on the worker thread. void getCurrentPreamble( llvm::unique_function)>); /// Returns compile command from the current file inputs. tooling::CompileCommand getCurrentCompileCommand() const; /// Wait for the first build of preamble to finish. Preamble itself can be /// accessed via getPossiblyStalePreamble(). Note that this function will /// return after an unsuccessful build of the preamble too, i.e. result of /// getPossiblyStalePreamble() can be null even after this function returns. void waitForFirstPreamble() const; TUScheduler::FileStats stats() const; bool isASTCached() const; private: // Details of an update request that are relevant to scheduling. struct UpdateType { // Do we want diagnostics from this version? // If Yes, we must always build this version. // If No, we only need to build this version if it's read. // If Auto, we build if it's read or if the debounce expires. WantDiagnostics Diagnostics; // Did the main-file content of the document change? // If so, we're allowed to cancel certain invalidated preceding reads. bool ContentChanged; }; /// Publishes diagnostics for \\p Inputs. It will build an AST or reuse the /// cached one if applicable. Assumes LatestPreamble is compatible for \\p /// Inputs. void generateDiagnostics(std::unique_ptr Invocation, ParseInputs Inputs, std::vector CIDiags); void updateASTSignals(ParsedAST &AST); // Must be called exactly once on processing thread. Will return after // stop() is called on a separate thread and all pending requests are // processed. void run(); /// Signal that run() should finish processing pending requests and exit. void stop(); /// Adds a new task to the end of the request queue. void startTask(llvm::StringRef Name, llvm::unique_function Task, llvm::Optional Update, TUScheduler::ASTActionInvalidation); /// Runs a task synchronously. void runTask(llvm::StringRef Name, llvm::function_ref Task); /// Determines the next action to perform. /// All actions that should never run are discarded. /// Returns a deadline for the next action. If it's expired, run now. /// scheduleLocked() is called again at the deadline, or if requests arrive. Deadline scheduleLocked(); /// Should the first task in the queue be skipped instead of run? bool shouldSkipHeadLocked() const; struct Request { llvm::unique_function Action; std::string Name; steady_clock::time_point AddTime; Context Ctx; llvm::Optional QueueCtx; llvm::Optional Update; TUScheduler::ASTActionInvalidation InvalidationPolicy; Canceler Invalidate; }; /// Handles retention of ASTs. TUScheduler::ASTCache &IdleASTs; TUScheduler::HeaderIncluderCache &HeaderIncluders; const bool RunSync; /// Time to wait after an update to see whether another update obsoletes it. const DebouncePolicy UpdateDebounce; /// File that ASTWorker is responsible for. const Path FileName; /// Callback to create processing contexts for tasks. const std::function ContextProvider; const GlobalCompilationDatabase &CDB; /// Callback invoked when preamble or main file AST is built. ParsingCallbacks &Callbacks; Semaphore &Barrier; /// Whether the 'onMainAST' callback ran for the current FileInputs. bool RanASTCallback = false; /// Guards members used by both TUScheduler and the worker thread. mutable std::mutex Mutex; /// File inputs, currently being used by the worker. /// Writes and reads from unknown threads are locked. Reads from the worker /// thread are not locked, as it's the only writer. ParseInputs FileInputs; /* GUARDED_BY(Mutex) */ /// Times of recent AST rebuilds, used for UpdateDebounce computation. llvm::SmallVector RebuildTimes; /* GUARDED_BY(Mutex) */ /// Set to true to signal run() to finish processing. bool Done; /* GUARDED_BY(Mutex) */ std::deque Requests; /* GUARDED_BY(Mutex) */ llvm::Optional CurrentRequest; /* GUARDED_BY(Mutex) */ /// Signalled whenever a new request has been scheduled or processing of a /// request has completed. mutable std::condition_variable RequestsCV; std::shared_ptr LatestASTSignals; /* GUARDED_BY(Mutex) */ /// Latest build preamble for current TU. /// None means no builds yet, null means there was an error while building. /// Only written by ASTWorker's thread. llvm::Optional> LatestPreamble; std::deque PreambleRequests; /* GUARDED_BY(Mutex) */ /// Signaled whenever LatestPreamble changes state or there's a new /// PreambleRequest. mutable std::condition_variable PreambleCV; /// Guards the callback that publishes results of AST-related computations /// (diagnostics) and file statuses. std::mutex PublishMu; // Used to prevent remove document + add document races that lead to // out-of-order callbacks for publishing results of onMainAST callback. // // The lifetime of the old/new ASTWorkers will overlap, but their handles // don't. When the old handle is destroyed, the old worker will stop reporting // any results to the user. bool CanPublishResults = true; /* GUARDED_BY(PublishMu) */ std::atomic ASTBuildCount = {0}; std::atomic PreambleBuildCount = {0}; SynchronizedTUStatus Status; PreambleThread PreamblePeer; }; /// A smart-pointer-like class that points to an active ASTWorker. /// In destructor, signals to the underlying ASTWorker that no new requests will /// be sent and the processing loop may exit (after running all pending /// requests). class ASTWorkerHandle { friend class ASTWorker; ASTWorkerHandle(std::shared_ptr Worker) : Worker(std::move(Worker)) { assert(this->Worker); } public: ASTWorkerHandle(const ASTWorkerHandle &) = delete; ASTWorkerHandle &operator=(const ASTWorkerHandle &) = delete; ASTWorkerHandle(ASTWorkerHandle &&) = default; ASTWorkerHandle &operator=(ASTWorkerHandle &&) = default; ~ASTWorkerHandle() { if (Worker) Worker->stop(); } ASTWorker &operator*() { assert(Worker && ""Handle was moved from""); return *Worker; } ASTWorker *operator->() { assert(Worker && ""Handle was moved from""); return Worker.get(); } /// Returns an owning reference to the underlying ASTWorker that can outlive /// the ASTWorkerHandle. However, no new requests to an active ASTWorker can /// be schedule via the returned reference, i.e. only reads of the preamble /// are possible. std::shared_ptr lock() { return Worker; } private: std::shared_ptr Worker; }; ASTWorkerHandle ASTWorker::create(PathRef FileName, const GlobalCompilationDatabase &CDB, TUScheduler::ASTCache &IdleASTs, TUScheduler::HeaderIncluderCache &HeaderIncluders, AsyncTaskRunner *Tasks, Semaphore &Barrier, const TUScheduler::Options &Opts, ParsingCallbacks &Callbacks) { std::shared_ptr Worker( new ASTWorker(FileName, CDB, IdleASTs, HeaderIncluders, Barrier, /*RunSync=*/!Tasks, Opts, Callbacks)); if (Tasks) { Tasks->runAsync(""ASTWorker:"" + llvm::sys::path::filename(FileName), [Worker]() { Worker->run(); }); Tasks->runAsync(""PreambleWorker:"" + llvm::sys::path::filename(FileName), [Worker]() { Worker->PreamblePeer.run(); }); } return ASTWorkerHandle(std::move(Worker)); } ASTWorker::ASTWorker(PathRef FileName, const GlobalCompilationDatabase &CDB, TUScheduler::ASTCache &LRUCache, TUScheduler::HeaderIncluderCache &HeaderIncluders, Semaphore &Barrier, bool RunSync, const TUScheduler::Options &Opts, ParsingCallbacks &Callbacks) : IdleASTs(LRUCache), HeaderIncluders(HeaderIncluders), RunSync(RunSync), UpdateDebounce(Opts.UpdateDebounce), FileName(FileName), ContextProvider(Opts.ContextProvider), CDB(CDB), Callbacks(Callbacks), Barrier(Barrier), Done(false), Status(FileName, Callbacks), PreamblePeer(FileName, Callbacks, Opts.StorePreamblesInMemory, RunSync, Status, HeaderIncluders, *this) { // Set a fallback command because compile command can be accessed before // `Inputs` is initialized. Other fields are only used after initialization // from client inputs. FileInputs.CompileCommand = CDB.getFallbackCommand(FileName); } ASTWorker::~ASTWorker() { // Make sure we remove the cached AST, if any. IdleASTs.take(this); #ifndef NDEBUG std::lock_guard Lock(Mutex); assert(Done && ""handle was not destroyed""); assert(Requests.empty() && !CurrentRequest && ""unprocessed requests when destroying ASTWorker""); #endif } void ASTWorker::update(ParseInputs Inputs, WantDiagnostics WantDiags, bool ContentChanged) { std::string TaskName = llvm::formatv(""Update ({0})"", Inputs.Version); auto Task = [=]() mutable { // Get the actual command as `Inputs` does not have a command. // FIXME: some build systems like Bazel will take time to preparing // environment to build the file, it would be nice if we could emit a // ""PreparingBuild"" status to inform users, it is non-trivial given the // current implementation. auto Cmd = CDB.getCompileCommand(FileName); // If we don't have a reliable command for this file, it may be a header. // Try to find a file that includes it, to borrow its command. if (!Cmd || !isReliable(*Cmd)) { std::string ProxyFile = HeaderIncluders.get(FileName); if (!ProxyFile.empty()) { auto ProxyCmd = CDB.getCompileCommand(ProxyFile); if (!ProxyCmd || !isReliable(*ProxyCmd)) { // This command is supposed to be reliable! It's probably gone. HeaderIncluders.remove(ProxyFile); } else { // We have a reliable command for an including file, use it. Cmd = tooling::transferCompileCommand(std::move(*ProxyCmd), FileName); } } } if (Cmd) Inputs.CompileCommand = std::move(*Cmd); else Inputs.CompileCommand = CDB.getFallbackCommand(FileName); bool InputsAreTheSame = std::tie(FileInputs.CompileCommand, FileInputs.Contents) == std::tie(Inputs.CompileCommand, Inputs.Contents); // Cached AST is invalidated. if (!InputsAreTheSame) { IdleASTs.take(this); RanASTCallback = false; } // Update current inputs so that subsequent reads can see them. { std::lock_guard Lock(Mutex); FileInputs = Inputs; } log(""ASTWorker building file {0} version {1} with command {2}\\n[{3}]\\n{4}"", FileName, Inputs.Version, Inputs.CompileCommand.Heuristic, Inputs.CompileCommand.Directory, printArgv(Inputs.CompileCommand.CommandLine)); StoreDiags CompilerInvocationDiagConsumer; std::vector CC1Args; std::unique_ptr Invocation = buildCompilerInvocation( Inputs, CompilerInvocationDiagConsumer, &CC1Args); // Log cc1 args even (especially!) if creating invocation failed. if (!CC1Args.empty()) vlog(""Driver produced command: cc1 {0}"", printArgv(CC1Args)); std::vector CompilerInvocationDiags = CompilerInvocationDiagConsumer.take(); if (!Invocation) { elog(""Could not build CompilerInvocation for file {0}"", FileName); // Remove the old AST if it's still in cache. IdleASTs.take(this); RanASTCallback = false; // Report the diagnostics we collected when parsing the command line. Callbacks.onFailedAST(FileName, Inputs.Version, std::move(CompilerInvocationDiags), [&](llvm::function_ref Publish) { // Ensure we only publish results from the worker // if the file was not removed, making sure there // are not race conditions. std::lock_guard Lock(PublishMu); if (CanPublishResults) Publish(); }); // Note that this might throw away a stale preamble that might still be // useful, but this is how we communicate a build error. LatestPreamble.emplace(); // Make sure anyone waiting for the preamble gets notified it could not be // built. PreambleCV.notify_all(); return; } PreamblePeer.update(std::move(Invocation), std::move(Inputs), std::move(CompilerInvocationDiags), WantDiags); std::unique_lock Lock(Mutex); PreambleCV.wait(Lock, [this] { // Block until we reiceve a preamble request, unless a preamble already // exists, as patching an empty preamble would imply rebuilding it from // scratch. // We block here instead of the consumer to prevent any deadlocks. Since // LatestPreamble is only populated by ASTWorker thread. return LatestPreamble || !PreambleRequests.empty() || Done; }); return; }; startTask(TaskName, std::move(Task), UpdateType{WantDiags, ContentChanged}, TUScheduler::NoInvalidation); } void ASTWorker::runWithAST( llvm::StringRef Name, llvm::unique_function)> Action, TUScheduler::ASTActionInvalidation Invalidation) { // Tracks ast cache accesses for read operations. static constexpr trace::Metric ASTAccessForRead( ""ast_access_read"", trace::Metric::Counter, ""result""); auto Task = [=, Action = std::move(Action)]() mutable { if (auto Reason = isCancelled()) return Action(llvm::make_error(Reason)); llvm::Optional> AST = IdleASTs.take(this, &ASTAccessForRead); if (!AST) { StoreDiags CompilerInvocationDiagConsumer; std::unique_ptr Invocation = buildCompilerInvocation(FileInputs, CompilerInvocationDiagConsumer); // Try rebuilding the AST. vlog(""ASTWorker rebuilding evicted AST to run {0}: {1} version {2}"", Name, FileName, FileInputs.Version); // FIXME: We might need to build a patched ast once preamble thread starts // running async. Currently getPossiblyStalePreamble below will always // return a compatible preamble as ASTWorker::update blocks. llvm::Optional NewAST; if (Invocation) { NewAST = ParsedAST::build(FileName, FileInputs, std::move(Invocation), CompilerInvocationDiagConsumer.take(), getPossiblyStalePreamble()); ++ASTBuildCount; } AST = NewAST ? std::make_unique(std::move(*NewAST)) : nullptr; } // Make sure we put the AST back into the LRU cache. auto _ = llvm::make_scope_exit( [&AST, this]() { IdleASTs.put(this, std::move(*AST)); }); // Run the user-provided action. if (!*AST) return Action(error(llvm::errc::invalid_argument, ""invalid AST"")); vlog(""ASTWorker running {0} on version {2} of {1}"", Name, FileName, FileInputs.Version); Action(InputsAndAST{FileInputs, **AST}); }; startTask(Name, std::move(Task), /*Update=*/None, Invalidation); } /// To be called from ThreadCrashReporter's signal handler. static void crashDumpCompileCommand(llvm::raw_ostream &OS, const tooling::CompileCommand &Command) { OS << "" Filename: "" << Command.Filename << ""\\n""; OS << "" Directory: "" << Command.Directory << ""\\n""; OS << "" Command Line:""; for (auto &Arg : Command.CommandLine) { OS << "" "" << Arg; } OS << ""\\n""; } /// To be called from ThreadCrashReporter's signal handler. static void crashDumpFileContents(llvm::raw_ostream &OS, const std::string &Contents) { // Avoid flooding the terminal with source code by default, but allow clients // to opt in. Use an env var to preserve backwards compatibility of the // command line interface, while allowing it to be set outside the clangd // launch site for more flexibility. if (getenv(""CLANGD_CRASH_DUMP_SOURCE"")) { OS << "" Contents:\\n""; OS << Contents << ""\\n""; } } /// To be called from ThreadCrashReporter's signal handler. static void crashDumpParseInputs(llvm::raw_ostream &OS, const ParseInputs &FileInputs) { auto &Command = FileInputs.CompileCommand; crashDumpCompileCommand(OS, Command); OS << "" Version: "" << FileInputs.Version << ""\\n""; crashDumpFileContents(OS, FileInputs.Contents); } void PreambleThread::build(Request Req) { assert(Req.CI && ""Got preamble request with null compiler invocation""); const ParseInputs &Inputs = Req.Inputs; bool ReusedPreamble = false; Status.update([&](TUStatus &Status) { Status.PreambleActivity = PreambleAction::Building; }); auto _ = llvm::make_scope_exit([this, &Req, &ReusedPreamble] { ASTPeer.updatePreamble(std::move(Req.CI), std::move(Req.Inputs), LatestBuild, std::move(Req.CIDiags), std::move(Req.WantDiags)); if (!ReusedPreamble) Callbacks.onPreamblePublished(FileName); }); if (!LatestBuild || Inputs.ForceRebuild) { vlog(""Building first preamble for {0} version {1}"", FileName, Inputs.Version); } else if (isPreambleCompatible(*LatestBuild, Inputs, FileName, *Req.CI)) { vlog(""Reusing preamble version {0} for version {1} of {2}"", LatestBuild->Version, Inputs.Version, FileName); ReusedPreamble = true; return; } else { vlog(""Rebuilding invalidated preamble for {0} version {1} (previous was "" ""version {2})"", FileName, Inputs.Version, LatestBuild->Version); } ThreadCrashReporter ScopedReporter([&Inputs]() { llvm::errs() << ""Signalled while building preamble\\n""; crashDumpParseInputs(llvm::errs(), Inputs); }); LatestBuild = clang::clangd::buildPreamble( FileName, *Req.CI, Inputs, StoreInMemory, [this, Version(Inputs.Version)](ASTContext &Ctx, std::shared_ptr PP, const CanonicalIncludes &CanonIncludes) { Callbacks.onPreambleAST(FileName, Version, Ctx, std::move(PP), CanonIncludes); }); if (LatestBuild && isReliable(LatestBuild->CompileCommand)) HeaderIncluders.update(FileName, LatestBuild->Includes.allHeaders()); } void ASTWorker::updatePreamble(std::unique_ptr CI, ParseInputs PI, std::shared_ptr Preamble, std::vector CIDiags, WantDiagnostics WantDiags) { llvm::StringLiteral TaskName = ""Build AST""; // Store preamble and build diagnostics with new preamble if requested. auto Task = [this, Preamble = std::move(Preamble), CI = std::move(CI), PI = std::move(PI), CIDiags = std::move(CIDiags), WantDiags = std::move(WantDiags)]() mutable { // Update the preamble inside ASTWorker queue to ensure atomicity. As a task // running inside ASTWorker assumes internals won't change until it // finishes. if (!LatestPreamble || Preamble != *LatestPreamble) { ++PreambleBuildCount; // Cached AST is no longer valid. IdleASTs.take(this); RanASTCallback = false; std::lock_guard Lock(Mutex); // LatestPreamble might be the last reference to old preamble, do not // trigger destructor while holding the lock. if (LatestPreamble) std::swap(*LatestPreamble, Preamble); else LatestPreamble = std::move(Preamble); } // Notify anyone waiting for a preamble. PreambleCV.notify_all(); // Give up our ownership to old preamble before starting expensive AST // build. Preamble.reset(); // We only need to build the AST if diagnostics were requested. if (WantDiags == WantDiagnostics::No) return; // Report diagnostics with the new preamble to ensure progress. Otherwise // diagnostics might get stale indefinitely if user keeps invalidating the // preamble. generateDiagnostics(std::move(CI), std::move(PI), std::move(CIDiags)); }; if (RunSync) { runTask(TaskName, Task); return; } { std::lock_guard Lock(Mutex); PreambleRequests.push_back({std::move(Task), std::string(TaskName), steady_clock::now(), Context::current().clone(), llvm::None, llvm::None, TUScheduler::NoInvalidation, nullptr}); } PreambleCV.notify_all(); RequestsCV.notify_all(); } void ASTWorker::updateASTSignals(ParsedAST &AST) { auto Signals = std::make_shared(ASTSignals::derive(AST)); // Existing readers of ASTSignals will have their copy preserved until the // read is completed. The last reader deletes the old ASTSignals. { std::lock_guard Lock(Mutex); std::swap(LatestASTSignals, Signals); } } void ASTWorker::generateDiagnostics( std::unique_ptr Invocation, ParseInputs Inputs, std::vector CIDiags) { // Tracks ast cache accesses for publishing diags. static constexpr trace::Metric ASTAccessForDiag( ""ast_access_diag"", trace::Metric::Counter, ""result""); assert(Invocation); assert(LatestPreamble); // No need to rebuild the AST if we won't send the diagnostics. { std::lock_guard Lock(PublishMu); if (!CanPublishResults) return; } // Used to check whether we can update AST cache. bool InputsAreLatest = std::tie(FileInputs.CompileCommand, FileInputs.Contents) == std::tie(Inputs.CompileCommand, Inputs.Contents); // Take a shortcut and don't report the diagnostics, since they should be the // same. All the clients should handle the lack of OnUpdated() call anyway to // handle empty result from buildAST. // FIXME: the AST could actually change if non-preamble includes changed, // but we choose to ignore it. if (InputsAreLatest && RanASTCallback) return; // Get the AST for diagnostics, either build it or use the cached one. std::string TaskName = llvm::formatv(""Build AST ({0})"", Inputs.Version); Status.update([&](TUStatus &Status) { Status.ASTActivity.K = ASTAction::Building; Status.ASTActivity.Name = std::move(TaskName); }); // We might be able to reuse the last we've built for a read request. // FIXME: It might be better to not reuse this AST. That way queued AST builds // won't be required for diags. llvm::Optional> AST = IdleASTs.take(this, &ASTAccessForDiag); if (!AST || !InputsAreLatest) { auto RebuildStartTime = DebouncePolicy::clock::now(); llvm::Optional NewAST = ParsedAST::build( FileName, Inputs, std::move(Invocation), CIDiags, *LatestPreamble); auto RebuildDuration = DebouncePolicy::clock::now() - RebuildStartTime; ++ASTBuildCount; // Try to record the AST-build time, to inform future update debouncing. // This is best-effort only: if the lock is held, don't bother. std::unique_lock Lock(Mutex, std::try_to_lock); if (Lock.owns_lock()) { // Do not let RebuildTimes grow beyond its small-size (i.e. // capacity). if (RebuildTimes.size() == RebuildTimes.capacity()) RebuildTimes.erase(RebuildTimes.begin()); RebuildTimes.push_back(RebuildDuration); Lock.unlock(); } Status.update([&](TUStatus &Status) { Status.Details.ReuseAST = false; Status.Details.BuildFailed = !NewAST.hasValue(); }); AST = NewAST ? std::make_unique(std::move(*NewAST)) : nullptr; } else { log(""Skipping rebuild of the AST for {0}, inputs are the same."", FileName); Status.update([](TUStatus &Status) { Status.Details.ReuseAST = true; Status.Details.BuildFailed = false; }); } // Publish diagnostics. auto RunPublish = [&](llvm::function_ref Publish) { // Ensure we only publish results from the worker if the file was not // removed, making sure there are not race conditions. std::lock_guard Lock(PublishMu); if (CanPublishResults) Publish(); }; if (*AST) { trace::Span Span(""Running main AST callback""); Callbacks.onMainAST(FileName, **AST, RunPublish); updateASTSignals(**AST); } else { // Failed to build the AST, at least report diagnostics from the // command line if there were any. // FIXME: we might have got more errors while trying to build the // AST, surface them too. Callbacks.onFailedAST(FileName, Inputs.Version, CIDiags, RunPublish); } // AST might've been built for an older version of the source, as ASTWorker // queue raced ahead while we were waiting on the preamble. In that case the // queue can't reuse the AST. if (InputsAreLatest) { RanASTCallback = *AST != nullptr; IdleASTs.put(this, std::move(*AST)); } } std::shared_ptr ASTWorker::getPossiblyStalePreamble( std::shared_ptr *ASTSignals) const { std::lock_guard Lock(Mutex); if (ASTSignals) *ASTSignals = LatestASTSignals; return LatestPreamble ? *LatestPreamble : nullptr; } void ASTWorker::waitForFirstPreamble() const { std::unique_lock Lock(Mutex); PreambleCV.wait(Lock, [this] { return LatestPreamble.hasValue() || Done; }); } tooling::CompileCommand ASTWorker::getCurrentCompileCommand() const { std::unique_lock Lock(Mutex); return FileInputs.CompileCommand; } TUScheduler::FileStats ASTWorker::stats() const { TUScheduler::FileStats Result; Result.ASTBuilds = ASTBuildCount; Result.PreambleBuilds = PreambleBuildCount; // Note that we don't report the size of ASTs currently used for processing // the in-flight requests. We used this information for debugging purposes // only, so this should be fine. Result.UsedBytesAST = IdleASTs.getUsedBytes(this); if (auto Preamble = getPossiblyStalePreamble()) Result.UsedBytesPreamble = Preamble->Preamble.getSize(); return Result; } bool ASTWorker::isASTCached() const { return IdleASTs.getUsedBytes(this) != 0; } void ASTWorker::stop() { { std::lock_guard Lock(PublishMu); CanPublishResults = false; } { std::lock_guard Lock(Mutex); assert(!Done && ""stop() called twice""); Done = true; } PreamblePeer.stop(); // We are no longer going to build any preambles, let the waiters know that. PreambleCV.notify_all(); Status.stop(); RequestsCV.notify_all(); } void ASTWorker::runTask(llvm::StringRef Name, llvm::function_ref Task) { ThreadCrashReporter ScopedReporter([this, Name]() { llvm::errs() << ""Signalled during AST worker action: "" << Name << ""\\n""; crashDumpParseInputs(llvm::errs(), FileInputs); }); trace::Span Tracer(Name); WithContext WithProvidedContext(ContextProvider(FileName)); Task(); } void ASTWorker::startTask(llvm::StringRef Name, llvm::unique_function Task, llvm::Optional Update, TUScheduler::ASTActionInvalidation Invalidation) { if (RunSync) { assert(!Done && ""running a task after stop()""); runTask(Name, Task); return; } { std::lock_guard Lock(Mutex); assert(!Done && ""running a task after stop()""); // Cancel any requests invalidated by this request. if (Update && Update->ContentChanged) { for (auto &R : llvm::reverse(Requests)) { if (R.InvalidationPolicy == TUScheduler::InvalidateOnUpdate) R.Invalidate(); if (R.Update && R.Update->ContentChanged) break; // Older requests were already invalidated by the older update. } } // Allow this request to be cancelled if invalidated. Context Ctx = Context::current().derive(kFileBeingProcessed, FileName); Canceler Invalidate = nullptr; if (Invalidation) { WithContext WC(std::move(Ctx)); std::tie(Ctx, Invalidate) = cancelableTask( /*Reason=*/static_cast(ErrorCode::ContentModified)); } // Trace the time the request spends in the queue, and the requests that // it's going to wait for. llvm::Optional QueueCtx; if (trace::enabled()) { // Tracers that follow threads and need strict nesting will see a tiny // instantaneous event ""we're enqueueing"", and sometime later it runs. WithContext WC(Ctx.clone()); trace::Span Tracer(""Queued:"" + Name); if (Tracer.Args) { if (CurrentRequest) SPAN_ATTACH(Tracer, ""CurrentRequest"", CurrentRequest->Name); llvm::json::Array PreambleRequestsNames; for (const auto &Req : PreambleRequests) PreambleRequestsNames.push_back(Req.Name); SPAN_ATTACH(Tracer, ""PreambleRequestsNames"", std::move(PreambleRequestsNames)); llvm::json::Array RequestsNames; for (const auto &Req : Requests) RequestsNames.push_back(Req.Name); SPAN_ATTACH(Tracer, ""RequestsNames"", std::move(RequestsNames)); } // For tracers that follow contexts, keep the trace span's context alive // until we dequeue the request, so they see the full duration. QueueCtx = Context::current().clone(); } Requests.push_back({std::move(Task), std::string(Name), steady_clock::now(), std::move(Ctx), std::move(QueueCtx), Update, Invalidation, std::move(Invalidate)}); } RequestsCV.notify_all(); } void ASTWorker::run() { while (true) { { std::unique_lock Lock(Mutex); assert(!CurrentRequest && ""A task is already running, multiple workers?""); for (auto Wait = scheduleLocked(); !Wait.expired(); Wait = scheduleLocked()) { assert(PreambleRequests.empty() && ""Preamble updates should be scheduled immediately""); if (Done) { if (Requests.empty()) return; // Even though Done is set, finish pending requests. break; // However, skip delays to shutdown fast. } // Tracing: we have a next request, attribute this sleep to it. llvm::Optional Ctx; llvm::Optional Tracer; if (!Requests.empty()) { Ctx.emplace(Requests.front().Ctx.clone()); Tracer.emplace(""Debounce""); SPAN_ATTACH(*Tracer, ""next_request"", Requests.front().Name); if (!(Wait == Deadline::infinity())) { Status.update([&](TUStatus &Status) { Status.ASTActivity.K = ASTAction::Queued; Status.ASTActivity.Name = Requests.front().Name; }); SPAN_ATTACH(*Tracer, ""sleep_ms"", std::chrono::duration_cast( Wait.time() - steady_clock::now()) .count()); } } wait(Lock, RequestsCV, Wait); } // Any request in ReceivedPreambles is at least as old as the // Requests.front(), so prefer them first to preserve LSP order. if (!PreambleRequests.empty()) { CurrentRequest = std::move(PreambleRequests.front()); PreambleRequests.pop_front(); } else { CurrentRequest = std::move(Requests.front()); Requests.pop_front(); } } // unlock Mutex // Inform tracing that the request was dequeued. CurrentRequest->QueueCtx.reset(); // It is safe to perform reads to CurrentRequest without holding the lock as // only writer is also this thread. { std::unique_lock Lock(Barrier, std::try_to_lock); if (!Lock.owns_lock()) { Status.update([&](TUStatus &Status) { Status.ASTActivity.K = ASTAction::Queued; Status.ASTActivity.Name = CurrentRequest->Name; }); Lock.lock(); } WithContext Guard(std::move(CurrentRequest->Ctx)); Status.update([&](TUStatus &Status) { Status.ASTActivity.K = ASTAction::RunningAction; Status.ASTActivity.Name = CurrentRequest->Name; }); runTask(CurrentRequest->Name, CurrentRequest->Action); } bool IsEmpty = false; { std::lock_guard Lock(Mutex); CurrentRequest.reset(); IsEmpty = Requests.empty() && PreambleRequests.empty(); } if (IsEmpty) { Status.update([&](TUStatus &Status) { Status.ASTActivity.K = ASTAction::Idle; Status.ASTActivity.Name = """"; }); } RequestsCV.notify_all(); } } Deadline ASTWorker::scheduleLocked() { // Process new preambles immediately. if (!PreambleRequests.empty()) return Deadline::zero(); if (Requests.empty()) return Deadline::infinity(); // Wait for new requests. // Handle cancelled requests first so the rest of the scheduler doesn't. for (auto I = Requests.begin(), E = Requests.end(); I != E; ++I) { if (!isCancelled(I->Ctx)) { // Cancellations after the first read don't affect current scheduling. if (I->Update == None) break; continue; } // Cancelled reads are moved to the front of the queue and run immediately. if (I->Update == None) { Request R = std::move(*I); Requests.erase(I); Requests.push_front(std::move(R)); return Deadline::zero(); } // Cancelled updates are downgraded to auto-diagnostics, and may be elided. if (I->Update->Diagnostics == WantDiagnostics::Yes) I->Update->Diagnostics = WantDiagnostics::Auto; } while (shouldSkipHeadLocked()) { vlog(""ASTWorker skipping {0} for {1}"", Requests.front().Name, FileName); Requests.pop_front(); } assert(!Requests.empty() && ""skipped the whole queue""); // Some updates aren't dead yet, but never end up being used. // e.g. the first keystroke is live until obsoleted by the second. // We debounce ""maybe-unused"" writes, sleeping in case they become dead. // But don't delay reads (including updates where diagnostics are needed). for (const auto &R : Requests) if (R.Update == None || R.Update->Diagnostics == WantDiagnostics::Yes) return Deadline::zero(); // Front request needs to be debounced, so determine when we're ready. Deadline D(Requests.front().AddTime + UpdateDebounce.compute(RebuildTimes)); return D; } // Returns true if Requests.front() is a dead update that can be skipped. bool ASTWorker::shouldSkipHeadLocked() const { assert(!Requests.empty()); auto Next = Requests.begin(); auto Update = Next->Update; if (!Update) // Only skip updates. return false; ++Next; // An update is live if its AST might still be read. // That is, if it's not immediately followed by another update. if (Next == Requests.end() || !Next->Update) return false; // The other way an update can be live is if its diagnostics might be used. switch (Update->Diagnostics) { case WantDiagnostics::Yes: return false; // Always used. case WantDiagnostics::No: return true; // Always dead. case WantDiagnostics::Auto: // Used unless followed by an update that generates diagnostics. for (; Next != Requests.end(); ++Next) if (Next->Update && Next->Update->Diagnostics != WantDiagnostics::No) return true; // Prefer later diagnostics. return false; } llvm_unreachable(""Unknown WantDiagnostics""); } bool ASTWorker::blockUntilIdle(Deadline Timeout) const { auto WaitUntilASTWorkerIsIdle = [&] { std::unique_lock Lock(Mutex); return wait(Lock, RequestsCV, Timeout, [&] { return PreambleRequests.empty() && Requests.empty() && !CurrentRequest; }); }; // Make sure ASTWorker has processed all requests, which might issue new // updates to PreamblePeer. if (!WaitUntilASTWorkerIsIdle()) return false; // Now that ASTWorker processed all requests, ensure PreamblePeer has served // all update requests. This might create new PreambleRequests for the // ASTWorker. if (!PreamblePeer.blockUntilIdle(Timeout)) return false; assert(Requests.empty() && ""No new normal tasks can be scheduled concurrently with "" ""blockUntilIdle(): ASTWorker isn't threadsafe""); // Finally make sure ASTWorker has processed all of the preamble updates. return WaitUntilASTWorkerIsIdle(); } // Render a TUAction to a user-facing string representation. // TUAction represents clangd-internal states, we don't intend to expose them // to users (say C++ programmers) directly to avoid confusion, we use terms that // are familiar by C++ programmers. std::string renderTUAction(const PreambleAction PA, const ASTAction &AA) { llvm::SmallVector Result; switch (PA) { case PreambleAction::Building: Result.push_back(""parsing includes""); break; case PreambleAction::Idle: // We handle idle specially below. break; } switch (AA.K) { case ASTAction::Queued: Result.push_back(""file is queued""); break; case ASTAction::RunningAction: Result.push_back(""running "" + AA.Name); break; case ASTAction::Building: Result.push_back(""parsing main file""); break; case ASTAction::Idle: // We handle idle specially below. break; } if (Result.empty()) return ""idle""; return llvm::join(Result, "", ""); } } // namespace unsigned getDefaultAsyncThreadsCount() { return llvm::heavyweight_hardware_concurrency().compute_thread_count(); } FileStatus TUStatus::render(PathRef File) const { FileStatus FStatus; FStatus.uri = URIForFile::canonicalize(File, /*TUPath=*/File); FStatus.state = renderTUAction(PreambleActivity, ASTActivity); return FStatus; } struct TUScheduler::FileData { /// Latest inputs, passed to TUScheduler::update(). std::string Contents; ASTWorkerHandle Worker; }; TUScheduler::TUScheduler(const GlobalCompilationDatabase &CDB, const Options &Opts, std::unique_ptr Callbacks) : CDB(CDB), Opts(Opts), Callbacks(Callbacks ? move(Callbacks) : std::make_unique()), Barrier(Opts.AsyncThreadsCount), QuickRunBarrier(Opts.AsyncThreadsCount), IdleASTs( std::make_unique(Opts.RetentionPolicy.MaxRetainedASTs)), HeaderIncluders(std::make_unique()) { // Avoid null checks everywhere. if (!Opts.ContextProvider) { this->Opts.ContextProvider = [](llvm::StringRef) { return Context::current().clone(); }; } if (0 < Opts.AsyncThreadsCount) { PreambleTasks.emplace(); WorkerThreads.emplace(); } } TUScheduler::~TUScheduler() { // Notify all workers that they need to stop. Files.clear(); // Wait for all in-flight tasks to finish. if (PreambleTasks) PreambleTasks->wait(); if (WorkerThreads) WorkerThreads->wait(); } bool TUScheduler::blockUntilIdle(Deadline D) const { for (auto &File : Files) if (!File.getValue()->Worker->blockUntilIdle(D)) return false; if (PreambleTasks) if (!PreambleTasks->wait(D)) return false; return true; } bool TUScheduler::update(PathRef File, ParseInputs Inputs, WantDiagnostics WantDiags) { std::unique_ptr &FD = Files[File]; bool NewFile = FD == nullptr; bool ContentChanged = false; if (!FD) { // Create a new worker to process the AST-related tasks. ASTWorkerHandle Worker = ASTWorker::create(File, CDB, *IdleASTs, *HeaderIncluders, WorkerThreads ? WorkerThreads.getPointer() : nullptr, Barrier, Opts, *Callbacks); FD = std::unique_ptr( new FileData{Inputs.Contents, std::move(Worker)}); ContentChanged = true; } else if (FD->Contents != Inputs.Contents) { ContentChanged = true; FD->Contents = Inputs.Contents; } FD->Worker->update(std::move(Inputs), WantDiags, ContentChanged); // There might be synthetic update requests, don't change the LastActiveFile // in such cases. if (ContentChanged) LastActiveFile = File.str(); return NewFile; } void TUScheduler::remove(PathRef File) { bool Removed = Files.erase(File); if (!Removed) elog(""Trying to remove file from TUScheduler that is not tracked: {0}"", File); // We don't call HeaderIncluders.remove(File) here. // If we did, we'd avoid potentially stale header/mainfile associations. // However, it would mean that closing a mainfile could invalidate the // preamble of several open headers. } void TUScheduler::run(llvm::StringRef Name, llvm::StringRef Path, llvm::unique_function Action) { runWithSemaphore(Name, Path, std::move(Action), Barrier); } void TUScheduler::runQuick(llvm::StringRef Name, llvm::StringRef Path, llvm::unique_function Action) { // Use QuickRunBarrier to serialize quick tasks: we are ignoring // the parallelism level set by the user, don't abuse it runWithSemaphore(Name, Path, std::move(Action), QuickRunBarrier); } void TUScheduler::runWithSemaphore(llvm::StringRef Name, llvm::StringRef Path, llvm::unique_function Action, Semaphore &Sem) { if (Path.empty()) Path = LastActiveFile; else LastActiveFile = Path.str(); if (!PreambleTasks) { WithContext WithProvidedContext(Opts.ContextProvider(Path)); return Action(); } PreambleTasks->runAsync(Name, [this, &Sem, Ctx = Context::current().clone(), Path(Path.str()), Action = std::move(Action)]() mutable { std::lock_guard BarrierLock(Sem); WithContext WC(std::move(Ctx)); WithContext WithProvidedContext(Opts.ContextProvider(Path)); Action(); }); } void TUScheduler::runWithAST( llvm::StringRef Name, PathRef File, llvm::unique_function)> Action, TUScheduler::ASTActionInvalidation Invalidation) { auto It = Files.find(File); if (It == Files.end()) { Action(llvm::make_error( ""trying to get AST for non-added document"", ErrorCode::InvalidParams)); return; } LastActiveFile = File.str(); It->second->Worker->runWithAST(Name, std::move(Action), Invalidation); } void TUScheduler::runWithPreamble(llvm::StringRef Name, PathRef File, PreambleConsistency Consistency, Callback Action) { auto It = Files.find(File); if (It == Files.end()) { Action(llvm::make_error( ""trying to get preamble for non-added document"", ErrorCode::InvalidParams)); return; } LastActiveFile = File.str(); if (!PreambleTasks) { trace::Span Tracer(Name); SPAN_ATTACH(Tracer, ""file"", File); std::shared_ptr Signals; std::shared_ptr Preamble = It->second->Worker->getPossiblyStalePreamble(&Signals); WithContext WithProvidedContext(Opts.ContextProvider(File)); Action(InputsAndPreamble{It->second->Contents, It->second->Worker->getCurrentCompileCommand(), Preamble.get(), Signals.get()}); return; } std::shared_ptr Worker = It->second->Worker.lock(); auto Task = [Worker, Consistency, Name = Name.str(), File = File.str(), Contents = It->second->Contents, Command = Worker->getCurrentCompileCommand(), Ctx = Context::current().derive(kFileBeingProcessed, std::string(File)), Action = std::move(Action), this]() mutable { ThreadCrashReporter ScopedReporter([&Name, &Contents, &Command]() { llvm::errs() << ""Signalled during preamble action: "" << Name << ""\\n""; crashDumpCompileCommand(llvm::errs(), Command); crashDumpFileContents(llvm::errs(), Contents); }); std::shared_ptr Preamble; if (Consistency == PreambleConsistency::Stale) { // Wait until the preamble is built for the first time, if preamble // is required. This avoids extra work of processing the preamble // headers in parallel multiple times. Worker->waitForFirstPreamble(); } std::shared_ptr Signals; Preamble = Worker->getPossiblyStalePreamble(&Signals); std::lock_guard BarrierLock(Barrier); WithContext Guard(std::move(Ctx)); trace::Span Tracer(Name); SPAN_ATTACH(Tracer, ""file"", File); WithContext WithProvidedContext(Opts.ContextProvider(File)); Action(InputsAndPreamble{Contents, Command, Preamble.get(), Signals.get()}); }; PreambleTasks->runAsync(""task:"" + llvm::sys::path::filename(File), std::move(Task)); } llvm::StringMap TUScheduler::fileStats() const { llvm::StringMap Result; for (const auto &PathAndFile : Files) Result.try_emplace(PathAndFile.first(), PathAndFile.second->Worker->stats()); return Result; } std::vector TUScheduler::getFilesWithCachedAST() const { std::vector Result; for (auto &&PathAndFile : Files) { if (!PathAndFile.second->Worker->isASTCached()) continue; Result.push_back(std::string(PathAndFile.first())); } return Result; } DebouncePolicy::clock::duration DebouncePolicy::compute(llvm::ArrayRef History) const { assert(Min <= Max && ""Invalid policy""); if (History.empty()) return Max; // Arbitrary. // Base the result on the median rebuild. // nth_element needs a mutable array, take the chance to bound the data size. History = History.take_back(15); llvm::SmallVector Recent(History.begin(), History.end()); auto Median = Recent.begin() + Recent.size() / 2; std::nth_element(Recent.begin(), Median, Recent.end()); clock::duration Target = std::chrono::duration_cast(RebuildRatio * *Median); if (Target > Max) return Max; if (Target < Min) return Min; return Target; } DebouncePolicy DebouncePolicy::fixed(clock::duration T) { DebouncePolicy P; P.Min = P.Max = T; return P; } void TUScheduler::profile(MemoryTree &MT) const { for (const auto &Elem : fileStats()) { MT.detail(Elem.first()) .child(""preamble"") .addUsage(Opts.StorePreamblesInMemory ? Elem.second.UsedBytesPreamble : 0); MT.detail(Elem.first()).child(""ast"").addUsage(Elem.second.UsedBytesAST); MT.child(""header_includer_cache"").addUsage(HeaderIncluders->getUsedBytes()); } } } // namespace clangd } // namespace clang ",16239,True,3014.4475277404317,median "[[analysis-lang-analyzer]] === Language Analyzers A set of analyzers aimed at analyzing specific language text. The following types are supported: <>, <>, <>, <>, <>, <>, <>, <>, <>, <>, <>, <>, <>, <>, <>, <>, <>, <>, <>, <>, <>, <>, <>, <>, <>, <>, <>, <>, <>, <>, <>, <>, <>, <>. ==== Configuring language analyzers ===== Stopwords All analyzers support setting custom `stopwords` either internally in the config, or by using an external stopwords file by setting `stopwords_path`. Check <> for more details. ===== Excluding words from stemming The `stem_exclusion` parameter allows you to specify an array of lowercase words that should not be stemmed. Internally, this functionality is implemented by adding the <> with the `keywords` set to the value of the `stem_exclusion` parameter. The following analyzers support setting custom `stem_exclusion` list: `arabic`, `armenian`, `basque`, `bengali`, `bulgarian`, `catalan`, `czech`, `dutch`, `english`, `finnish`, `french`, `galician`, `german`, `hindi`, `hungarian`, `indonesian`, `irish`, `italian`, `latvian`, `lithuanian`, `norwegian`, `portuguese`, `romanian`, `russian`, `sorani`, `spanish`, `swedish`, `turkish`. ==== Reimplementing language analyzers The built-in language analyzers can be reimplemented as `custom` analyzers (as described below) in order to customize their behaviour. NOTE: If you do not intend to exclude words from being stemmed (the equivalent of the `stem_exclusion` parameter above), then you should remove the `keyword_marker` token filter from the custom analyzer configuration. [[arabic-analyzer]] ===== `arabic` analyzer The `arabic` analyzer could be reimplemented as a `custom` analyzer as follows: [source,js] ---------------------------------------------------- PUT /arabic_example { ""settings"": { ""analysis"": { ""filter"": { ""arabic_stop"": { ""type"": ""stop"", ""stopwords"": ""_arabic_"" <1> }, ""arabic_keywords"": { ""type"": ""keyword_marker"", ""keywords"": [""مثال""] <2> }, ""arabic_stemmer"": { ""type"": ""stemmer"", ""language"": ""arabic"" } }, ""analyzer"": { ""rebuilt_arabic"": { ""tokenizer"": ""standard"", ""filter"": [ ""lowercase"", ""decimal_digit"", ""arabic_stop"", ""arabic_normalization"", ""arabic_keywords"", ""arabic_stemmer"" ] } } } } } ---------------------------------------------------- // CONSOLE // TEST[s/""arabic_keywords"",//] // TEST[s/\\n$/\\nstartyaml\\n - compare_analyzers: {index: arabic_example, first: arabic, second: rebuilt_arabic}\\nendyaml\\n/] <1> The default stopwords can be overridden with the `stopwords` or `stopwords_path` parameters. <2> This filter should be removed unless there are words which should be excluded from stemming. [[armenian-analyzer]] ===== `armenian` analyzer The `armenian` analyzer could be reimplemented as a `custom` analyzer as follows: [source,js] ---------------------------------------------------- PUT /armenian_example { ""settings"": { ""analysis"": { ""filter"": { ""armenian_stop"": { ""type"": ""stop"", ""stopwords"": ""_armenian_"" <1> }, ""armenian_keywords"": { ""type"": ""keyword_marker"", ""keywords"": [""օրինակ""] <2> }, ""armenian_stemmer"": { ""type"": ""stemmer"", ""language"": ""armenian"" } }, ""analyzer"": { ""rebuilt_armenian"": { ""tokenizer"": ""standard"", ""filter"": [ ""lowercase"", ""armenian_stop"", ""armenian_keywords"", ""armenian_stemmer"" ] } } } } } ---------------------------------------------------- // CONSOLE // TEST[s/""armenian_keywords"",//] // TEST[s/\\n$/\\nstartyaml\\n - compare_analyzers: {index: armenian_example, first: armenian, second: rebuilt_armenian}\\nendyaml\\n/] <1> The default stopwords can be overridden with the `stopwords` or `stopwords_path` parameters. <2> This filter should be removed unless there are words which should be excluded from stemming. [[basque-analyzer]] ===== `basque` analyzer The `basque` analyzer could be reimplemented as a `custom` analyzer as follows: [source,js] ---------------------------------------------------- PUT /basque_example { ""settings"": { ""analysis"": { ""filter"": { ""basque_stop"": { ""type"": ""stop"", ""stopwords"": ""_basque_"" <1> }, ""basque_keywords"": { ""type"": ""keyword_marker"", ""keywords"": [""Adibidez""] <2> }, ""basque_stemmer"": { ""type"": ""stemmer"", ""language"": ""basque"" } }, ""analyzer"": { ""rebuilt_basque"": { ""tokenizer"": ""standard"", ""filter"": [ ""lowercase"", ""basque_stop"", ""basque_keywords"", ""basque_stemmer"" ] } } } } } ---------------------------------------------------- // CONSOLE // TEST[s/""basque_keywords"",//] // TEST[s/\\n$/\\nstartyaml\\n - compare_analyzers: {index: basque_example, first: basque, second: rebuilt_basque}\\nendyaml\\n/] <1> The default stopwords can be overridden with the `stopwords` or `stopwords_path` parameters. <2> This filter should be removed unless there are words which should be excluded from stemming. [[bengali-analyzer]] ===== `bengali` analyzer The `bengali` analyzer could be reimplemented as a `custom` analyzer as follows: [source,js] ---------------------------------------------------- PUT /bengali_example { ""settings"": { ""analysis"": { ""filter"": { ""bengali_stop"": { ""type"": ""stop"", ""stopwords"": ""_bengali_"" <1> }, ""bengali_keywords"": { ""type"": ""keyword_marker"", ""keywords"": [""উদাহরণ""] <2> }, ""bengali_stemmer"": { ""type"": ""stemmer"", ""language"": ""bengali"" } }, ""analyzer"": { ""rebuilt_bengali"": { ""tokenizer"": ""standard"", ""filter"": [ ""lowercase"", ""decimal_digit"", ""bengali_keywords"", ""indic_normalization"", ""bengali_normalization"", ""bengali_stop"", ""bengali_stemmer"" ] } } } } } ---------------------------------------------------- // CONSOLE // TEST[s/""bengali_keywords"",//] // TEST[s/\\n$/\\nstartyaml\\n - compare_analyzers: {index: bengali_example, first: bengali, second: rebuilt_bengali}\\nendyaml\\n/] <1> The default stopwords can be overridden with the `stopwords` or `stopwords_path` parameters. <2> This filter should be removed unless there are words which should be excluded from stemming. [[brazilian-analyzer]] ===== `brazilian` analyzer The `brazilian` analyzer could be reimplemented as a `custom` analyzer as follows: [source,js] ---------------------------------------------------- PUT /brazilian_example { ""settings"": { ""analysis"": { ""filter"": { ""brazilian_stop"": { ""type"": ""stop"", ""stopwords"": ""_brazilian_"" <1> }, ""brazilian_keywords"": { ""type"": ""keyword_marker"", ""keywords"": [""exemplo""] <2> }, ""brazilian_stemmer"": { ""type"": ""stemmer"", ""language"": ""brazilian"" } }, ""analyzer"": { ""rebuilt_brazilian"": { ""tokenizer"": ""standard"", ""filter"": [ ""lowercase"", ""brazilian_stop"", ""brazilian_keywords"", ""brazilian_stemmer"" ] } } } } } ---------------------------------------------------- // CONSOLE // TEST[s/""brazilian_keywords"",//] // TEST[s/\\n$/\\nstartyaml\\n - compare_analyzers: {index: brazilian_example, first: brazilian, second: rebuilt_brazilian}\\nendyaml\\n/] <1> The default stopwords can be overridden with the `stopwords` or `stopwords_path` parameters. <2> This filter should be removed unless there are words which should be excluded from stemming. [[bulgarian-analyzer]] ===== `bulgarian` analyzer The `bulgarian` analyzer could be reimplemented as a `custom` analyzer as follows: [source,js] ---------------------------------------------------- PUT /bulgarian_example { ""settings"": { ""analysis"": { ""filter"": { ""bulgarian_stop"": { ""type"": ""stop"", ""stopwords"": ""_bulgarian_"" <1> }, ""bulgarian_keywords"": { ""type"": ""keyword_marker"", ""keywords"": [""пример""] <2> }, ""bulgarian_stemmer"": { ""type"": ""stemmer"", ""language"": ""bulgarian"" } }, ""analyzer"": { ""rebuilt_bulgarian"": { ""tokenizer"": ""standard"", ""filter"": [ ""lowercase"", ""bulgarian_stop"", ""bulgarian_keywords"", ""bulgarian_stemmer"" ] } } } } } ---------------------------------------------------- // CONSOLE // TEST[s/""bulgarian_keywords"",//] // TEST[s/\\n$/\\nstartyaml\\n - compare_analyzers: {index: bulgarian_example, first: bulgarian, second: rebuilt_bulgarian}\\nendyaml\\n/] <1> The default stopwords can be overridden with the `stopwords` or `stopwords_path` parameters. <2> This filter should be removed unless there are words which should be excluded from stemming. [[catalan-analyzer]] ===== `catalan` analyzer The `catalan` analyzer could be reimplemented as a `custom` analyzer as follows: [source,js] ---------------------------------------------------- PUT /catalan_example { ""settings"": { ""analysis"": { ""filter"": { ""catalan_elision"": { ""type"": ""elision"", ""articles"": [ ""d"", ""l"", ""m"", ""n"", ""s"", ""t""], ""articles_case"": true }, ""catalan_stop"": { ""type"": ""stop"", ""stopwords"": ""_catalan_"" <1> }, ""catalan_keywords"": { ""type"": ""keyword_marker"", ""keywords"": [""exemple""] <2> }, ""catalan_stemmer"": { ""type"": ""stemmer"", ""language"": ""catalan"" } }, ""analyzer"": { ""rebuilt_catalan"": { ""tokenizer"": ""standard"", ""filter"": [ ""catalan_elision"", ""lowercase"", ""catalan_stop"", ""catalan_keywords"", ""catalan_stemmer"" ] } } } } } ---------------------------------------------------- // CONSOLE // TEST[s/""catalan_keywords"",//] // TEST[s/\\n$/\\nstartyaml\\n - compare_analyzers: {index: catalan_example, first: catalan, second: rebuilt_catalan}\\nendyaml\\n/] <1> The default stopwords can be overridden with the `stopwords` or `stopwords_path` parameters. <2> This filter should be removed unless there are words which should be excluded from stemming. [[cjk-analyzer]] ===== `cjk` analyzer NOTE: You may find that `icu_analyzer` in the ICU analysis plugin works better for CJK text than the `cjk` analyzer. Experiment with your text and queries. The `cjk` analyzer could be reimplemented as a `custom` analyzer as follows: [source,js] ---------------------------------------------------- PUT /cjk_example { ""settings"": { ""analysis"": { ""filter"": { ""english_stop"": { ""type"": ""stop"", ""stopwords"": [ <1> ""a"", ""and"", ""are"", ""as"", ""at"", ""be"", ""but"", ""by"", ""for"", ""if"", ""in"", ""into"", ""is"", ""it"", ""no"", ""not"", ""of"", ""on"", ""or"", ""s"", ""such"", ""t"", ""that"", ""the"", ""their"", ""then"", ""there"", ""these"", ""they"", ""this"", ""to"", ""was"", ""will"", ""with"", ""www"" ] } }, ""analyzer"": { ""rebuilt_cjk"": { ""tokenizer"": ""standard"", ""filter"": [ ""cjk_width"", ""lowercase"", ""cjk_bigram"", ""english_stop"" ] } } } } } ---------------------------------------------------- // CONSOLE // TEST[s/""cjk_keywords"",//] // TEST[s/\\n$/\\nstartyaml\\n - compare_analyzers: {index: cjk_example, first: cjk, second: rebuilt_cjk}\\nendyaml\\n/] <1> The default stopwords can be overridden with the `stopwords` or `stopwords_path` parameters. The default stop words are *almost* the same as the `_english_` set, but not exactly the same. [[czech-analyzer]] ===== `czech` analyzer The `czech` analyzer could be reimplemented as a `custom` analyzer as follows: [source,js] ---------------------------------------------------- PUT /czech_example { ""settings"": { ""analysis"": { ""filter"": { ""czech_stop"": { ""type"": ""stop"", ""stopwords"": ""_czech_"" <1> }, ""czech_keywords"": { ""type"": ""keyword_marker"", ""keywords"": [""příklad""] <2> }, ""czech_stemmer"": { ""type"": ""stemmer"", ""language"": ""czech"" } }, ""analyzer"": { ""rebuilt_czech"": { ""tokenizer"": ""standard"", ""filter"": [ ""lowercase"", ""czech_stop"", ""czech_keywords"", ""czech_stemmer"" ] } } } } } ---------------------------------------------------- // CONSOLE // TEST[s/""czech_keywords"",//] // TEST[s/\\n$/\\nstartyaml\\n - compare_analyzers: {index: czech_example, first: czech, second: rebuilt_czech}\\nendyaml\\n/] <1> The default stopwords can be overridden with the `stopwords` or `stopwords_path` parameters. <2> This filter should be removed unless there are words which should be excluded from stemming. [[danish-analyzer]] ===== `danish` analyzer The `danish` analyzer could be reimplemented as a `custom` analyzer as follows: [source,js] ---------------------------------------------------- PUT /danish_example { ""settings"": { ""analysis"": { ""filter"": { ""danish_stop"": { ""type"": ""stop"", ""stopwords"": ""_danish_"" <1> }, ""danish_keywords"": { ""type"": ""keyword_marker"", ""keywords"": [""eksempel""] <2> }, ""danish_stemmer"": { ""type"": ""stemmer"", ""language"": ""danish"" } }, ""analyzer"": { ""rebuilt_danish"": { ""tokenizer"": ""standard"", ""filter"": [ ""lowercase"", ""danish_stop"", ""danish_keywords"", ""danish_stemmer"" ] } } } } } ---------------------------------------------------- // CONSOLE // TEST[s/""danish_keywords"",//] // TEST[s/\\n$/\\nstartyaml\\n - compare_analyzers: {index: danish_example, first: danish, second: rebuilt_danish}\\nendyaml\\n/] <1> The default stopwords can be overridden with the `stopwords` or `stopwords_path` parameters. <2> This filter should be removed unless there are words which should be excluded from stemming. [[dutch-analyzer]] ===== `dutch` analyzer The `dutch` analyzer could be reimplemented as a `custom` analyzer as follows: [source,js] ---------------------------------------------------- PUT /dutch_example { ""settings"": { ""analysis"": { ""filter"": { ""dutch_stop"": { ""type"": ""stop"", ""stopwords"": ""_dutch_"" <1> }, ""dutch_keywords"": { ""type"": ""keyword_marker"", ""keywords"": [""voorbeeld""] <2> }, ""dutch_stemmer"": { ""type"": ""stemmer"", ""language"": ""dutch"" }, ""dutch_override"": { ""type"": ""stemmer_override"", ""rules"": [ ""fiets=>fiets"", ""bromfiets=>bromfiets"", ""ei=>eier"", ""kind=>kinder"" ] } }, ""analyzer"": { ""rebuilt_dutch"": { ""tokenizer"": ""standard"", ""filter"": [ ""lowercase"", ""dutch_stop"", ""dutch_keywords"", ""dutch_override"", ""dutch_stemmer"" ] } } } } } ---------------------------------------------------- // CONSOLE // TEST[s/""dutch_keywords"",//] // TEST[s/\\n$/\\nstartyaml\\n - compare_analyzers: {index: dutch_example, first: dutch, second: rebuilt_dutch}\\nendyaml\\n/] <1> The default stopwords can be overridden with the `stopwords` or `stopwords_path` parameters. <2> This filter should be removed unless there are words which should be excluded from stemming. [[english-analyzer]] ===== `english` analyzer The `english` analyzer could be reimplemented as a `custom` analyzer as follows: [source,js] ---------------------------------------------------- PUT /english_example { ""settings"": { ""analysis"": { ""filter"": { ""english_stop"": { ""type"": ""stop"", ""stopwords"": ""_english_"" <1> }, ""english_keywords"": { ""type"": ""keyword_marker"", ""keywords"": [""example""] <2> }, ""english_stemmer"": { ""type"": ""stemmer"", ""language"": ""english"" }, ""english_possessive_stemmer"": { ""type"": ""stemmer"", ""language"": ""possessive_english"" } }, ""analyzer"": { ""rebuilt_english"": { ""tokenizer"": ""standard"", ""filter"": [ ""english_possessive_stemmer"", ""lowercase"", ""english_stop"", ""english_keywords"", ""english_stemmer"" ] } } } } } ---------------------------------------------------- // CONSOLE // TEST[s/""english_keywords"",//] // TEST[s/\\n$/\\nstartyaml\\n - compare_analyzers: {index: english_example, first: english, second: rebuilt_english}\\nendyaml\\n/] <1> The default stopwords can be overridden with the `stopwords` or `stopwords_path` parameters. <2> This filter should be removed unless there are words which should be excluded from stemming. [[finnish-analyzer]] ===== `finnish` analyzer The `finnish` analyzer could be reimplemented as a `custom` analyzer as follows: [source,js] ---------------------------------------------------- PUT /finnish_example { ""settings"": { ""analysis"": { ""filter"": { ""finnish_stop"": { ""type"": ""stop"", ""stopwords"": ""_finnish_"" <1> }, ""finnish_keywords"": { ""type"": ""keyword_marker"", ""keywords"": [""esimerkki""] <2> }, ""finnish_stemmer"": { ""type"": ""stemmer"", ""language"": ""finnish"" } }, ""analyzer"": { ""rebuilt_finnish"": { ""tokenizer"": ""standard"", ""filter"": [ ""lowercase"", ""finnish_stop"", ""finnish_keywords"", ""finnish_stemmer"" ] } } } } } ---------------------------------------------------- // CONSOLE // TEST[s/""finnish_keywords"",//] // TEST[s/\\n$/\\nstartyaml\\n - compare_analyzers: {index: finnish_example, first: finnish, second: rebuilt_finnish}\\nendyaml\\n/] <1> The default stopwords can be overridden with the `stopwords` or `stopwords_path` parameters. <2> This filter should be removed unless there are words which should be excluded from stemming. [[french-analyzer]] ===== `french` analyzer The `french` analyzer could be reimplemented as a `custom` analyzer as follows: [source,js] ---------------------------------------------------- PUT /french_example { ""settings"": { ""analysis"": { ""filter"": { ""french_elision"": { ""type"": ""elision"", ""articles_case"": true, ""articles"": [ ""l"", ""m"", ""t"", ""qu"", ""n"", ""s"", ""j"", ""d"", ""c"", ""jusqu"", ""quoiqu"", ""lorsqu"", ""puisqu"" ] }, ""french_stop"": { ""type"": ""stop"", ""stopwords"": ""_french_"" <1> }, ""french_keywords"": { ""type"": ""keyword_marker"", ""keywords"": [""Exemple""] <2> }, ""french_stemmer"": { ""type"": ""stemmer"", ""language"": ""light_french"" } }, ""analyzer"": { ""rebuilt_french"": { ""tokenizer"": ""standard"", ""filter"": [ ""french_elision"", ""lowercase"", ""french_stop"", ""french_keywords"", ""french_stemmer"" ] } } } } } ---------------------------------------------------- // CONSOLE // TEST[s/""french_keywords"",//] // TEST[s/\\n$/\\nstartyaml\\n - compare_analyzers: {index: french_example, first: french, second: rebuilt_french}\\nendyaml\\n/] <1> The default stopwords can be overridden with the `stopwords` or `stopwords_path` parameters. <2> This filter should be removed unless there are words which should be excluded from stemming. [[galician-analyzer]] ===== `galician` analyzer The `galician` analyzer could be reimplemented as a `custom` analyzer as follows: [source,js] ---------------------------------------------------- PUT /galician_example { ""settings"": { ""analysis"": { ""filter"": { ""galician_stop"": { ""type"": ""stop"", ""stopwords"": ""_galician_"" <1> }, ""galician_keywords"": { ""type"": ""keyword_marker"", ""keywords"": [""exemplo""] <2> }, ""galician_stemmer"": { ""type"": ""stemmer"", ""language"": ""galician"" } }, ""analyzer"": { ""rebuilt_galician"": { ""tokenizer"": ""standard"", ""filter"": [ ""lowercase"", ""galician_stop"", ""galician_keywords"", ""galician_stemmer"" ] } } } } } ---------------------------------------------------- // CONSOLE // TEST[s/""galician_keywords"",//] // TEST[s/\\n$/\\nstartyaml\\n - compare_analyzers: {index: galician_example, first: galician, second: rebuilt_galician}\\nendyaml\\n/] <1> The default stopwords can be overridden with the `stopwords` or `stopwords_path` parameters. <2> This filter should be removed unless there are words which should be excluded from stemming. [[german-analyzer]] ===== `german` analyzer The `german` analyzer could be reimplemented as a `custom` analyzer as follows: [source,js] ---------------------------------------------------- PUT /german_example { ""settings"": { ""analysis"": { ""filter"": { ""german_stop"": { ""type"": ""stop"", ""stopwords"": ""_german_"" <1> }, ""german_keywords"": { ""type"": ""keyword_marker"", ""keywords"": [""Beispiel""] <2> }, ""german_stemmer"": { ""type"": ""stemmer"", ""language"": ""light_german"" } }, ""analyzer"": { ""rebuilt_german"": { ""tokenizer"": ""standard"", ""filter"": [ ""lowercase"", ""german_stop"", ""german_keywords"", ""german_normalization"", ""german_stemmer"" ] } } } } } ---------------------------------------------------- // CONSOLE // TEST[s/""german_keywords"",//] // TEST[s/\\n$/\\nstartyaml\\n - compare_analyzers: {index: german_example, first: german, second: rebuilt_german}\\nendyaml\\n/] <1> The default stopwords can be overridden with the `stopwords` or `stopwords_path` parameters. <2> This filter should be removed unless there are words which should be excluded from stemming. [[greek-analyzer]] ===== `greek` analyzer The `greek` analyzer could be reimplemented as a `custom` analyzer as follows: [source,js] ---------------------------------------------------- PUT /greek_example { ""settings"": { ""analysis"": { ""filter"": { ""greek_stop"": { ""type"": ""stop"", ""stopwords"": ""_greek_"" <1> }, ""greek_lowercase"": { ""type"": ""lowercase"", ""language"": ""greek"" }, ""greek_keywords"": { ""type"": ""keyword_marker"", ""keywords"": [""παράδειγμα""] <2> }, ""greek_stemmer"": { ""type"": ""stemmer"", ""language"": ""greek"" } }, ""analyzer"": { ""rebuilt_greek"": { ""tokenizer"": ""standard"", ""filter"": [ ""greek_lowercase"", ""greek_stop"", ""greek_keywords"", ""greek_stemmer"" ] } } } } } ---------------------------------------------------- // CONSOLE // TEST[s/""greek_keywords"",//] // TEST[s/\\n$/\\nstartyaml\\n - compare_analyzers: {index: greek_example, first: greek, second: rebuilt_greek}\\nendyaml\\n/] <1> The default stopwords can be overridden with the `stopwords` or `stopwords_path` parameters. <2> This filter should be removed unless there are words which should be excluded from stemming. [[hindi-analyzer]] ===== `hindi` analyzer The `hindi` analyzer could be reimplemented as a `custom` analyzer as follows: [source,js] ---------------------------------------------------- PUT /hindi_example { ""settings"": { ""analysis"": { ""filter"": { ""hindi_stop"": { ""type"": ""stop"", ""stopwords"": ""_hindi_"" <1> }, ""hindi_keywords"": { ""type"": ""keyword_marker"", ""keywords"": [""उदाहरण""] <2> }, ""hindi_stemmer"": { ""type"": ""stemmer"", ""language"": ""hindi"" } }, ""analyzer"": { ""rebuilt_hindi"": { ""tokenizer"": ""standard"", ""filter"": [ ""lowercase"", ""decimal_digit"", ""hindi_keywords"", ""indic_normalization"", ""hindi_normalization"", ""hindi_stop"", ""hindi_stemmer"" ] } } } } } ---------------------------------------------------- // CONSOLE // TEST[s/""hindi_keywords"",//] // TEST[s/\\n$/\\nstartyaml\\n - compare_analyzers: {index: hindi_example, first: hindi, second: rebuilt_hindi}\\nendyaml\\n/] <1> The default stopwords can be overridden with the `stopwords` or `stopwords_path` parameters. <2> This filter should be removed unless there are words which should be excluded from stemming. [[hungarian-analyzer]] ===== `hungarian` analyzer The `hungarian` analyzer could be reimplemented as a `custom` analyzer as follows: [source,js] ---------------------------------------------------- PUT /hungarian_example { ""settings"": { ""analysis"": { ""filter"": { ""hungarian_stop"": { ""type"": ""stop"", ""stopwords"": ""_hungarian_"" <1> }, ""hungarian_keywords"": { ""type"": ""keyword_marker"", ""keywords"": [""példa""] <2> }, ""hungarian_stemmer"": { ""type"": ""stemmer"", ""language"": ""hungarian"" } }, ""analyzer"": { ""rebuilt_hungarian"": { ""tokenizer"": ""standard"", ""filter"": [ ""lowercase"", ""hungarian_stop"", ""hungarian_keywords"", ""hungarian_stemmer"" ] } } } } } ---------------------------------------------------- // CONSOLE // TEST[s/""hungarian_keywords"",//] // TEST[s/\\n$/\\nstartyaml\\n - compare_analyzers: {index: hungarian_example, first: hungarian, second: rebuilt_hungarian}\\nendyaml\\n/] <1> The default stopwords can be overridden with the `stopwords` or `stopwords_path` parameters. <2> This filter should be removed unless there are words which should be excluded from stemming. [[indonesian-analyzer]] ===== `indonesian` analyzer The `indonesian` analyzer could be reimplemented as a `custom` analyzer as follows: [source,js] ---------------------------------------------------- PUT /indonesian_example { ""settings"": { ""analysis"": { ""filter"": { ""indonesian_stop"": { ""type"": ""stop"", ""stopwords"": ""_indonesian_"" <1> }, ""indonesian_keywords"": { ""type"": ""keyword_marker"", ""keywords"": [""contoh""] <2> }, ""indonesian_stemmer"": { ""type"": ""stemmer"", ""language"": ""indonesian"" } }, ""analyzer"": { ""rebuilt_indonesian"": { ""tokenizer"": ""standard"", ""filter"": [ ""lowercase"", ""indonesian_stop"", ""indonesian_keywords"", ""indonesian_stemmer"" ] } } } } } ---------------------------------------------------- // CONSOLE // TEST[s/""indonesian_keywords"",//] // TEST[s/\\n$/\\nstartyaml\\n - compare_analyzers: {index: indonesian_example, first: indonesian, second: rebuilt_indonesian}\\nendyaml\\n/] <1> The default stopwords can be overridden with the `stopwords` or `stopwords_path` parameters. <2> This filter should be removed unless there are words which should be excluded from stemming. [[irish-analyzer]] ===== `irish` analyzer The `irish` analyzer could be reimplemented as a `custom` analyzer as follows: [source,js] ---------------------------------------------------- PUT /irish_example { ""settings"": { ""analysis"": { ""filter"": { ""irish_hyphenation"": { ""type"": ""stop"", ""stopwords"": [ ""h"", ""n"", ""t"" ], ""ignore_case"": true }, ""irish_elision"": { ""type"": ""elision"", ""articles"": [ ""d"", ""m"", ""b"" ], ""articles_case"": true }, ""irish_stop"": { ""type"": ""stop"", ""stopwords"": ""_irish_"" <1> }, ""irish_lowercase"": { ""type"": ""lowercase"", ""language"": ""irish"" }, ""irish_keywords"": { ""type"": ""keyword_marker"", ""keywords"": [""sampla""] <2> }, ""irish_stemmer"": { ""type"": ""stemmer"", ""language"": ""irish"" } }, ""analyzer"": { ""rebuilt_irish"": { ""tokenizer"": ""standard"", ""filter"": [ ""irish_hyphenation"", ""irish_elision"", ""irish_lowercase"", ""irish_stop"", ""irish_keywords"", ""irish_stemmer"" ] } } } } } ---------------------------------------------------- // CONSOLE // TEST[s/""irish_keywords"",//] // TEST[s/\\n$/\\nstartyaml\\n - compare_analyzers: {index: irish_example, first: irish, second: rebuilt_irish}\\nendyaml\\n/] <1> The default stopwords can be overridden with the `stopwords` or `stopwords_path` parameters. <2> This filter should be removed unless there are words which should be excluded from stemming. [[italian-analyzer]] ===== `italian` analyzer The `italian` analyzer could be reimplemented as a `custom` analyzer as follows: [source,js] ---------------------------------------------------- PUT /italian_example { ""settings"": { ""analysis"": { ""filter"": { ""italian_elision"": { ""type"": ""elision"", ""articles"": [ ""c"", ""l"", ""all"", ""dall"", ""dell"", ""nell"", ""sull"", ""coll"", ""pell"", ""gl"", ""agl"", ""dagl"", ""degl"", ""negl"", ""sugl"", ""un"", ""m"", ""t"", ""s"", ""v"", ""d"" ], ""articles_case"": true }, ""italian_stop"": { ""type"": ""stop"", ""stopwords"": ""_italian_"" <1> }, ""italian_keywords"": { ""type"": ""keyword_marker"", ""keywords"": [""esempio""] <2> }, ""italian_stemmer"": { ""type"": ""stemmer"", ""language"": ""light_italian"" } }, ""analyzer"": { ""rebuilt_italian"": { ""tokenizer"": ""standard"", ""filter"": [ ""italian_elision"", ""lowercase"", ""italian_stop"", ""italian_keywords"", ""italian_stemmer"" ] } } } } } ---------------------------------------------------- // CONSOLE // TEST[s/""italian_keywords"",//] // TEST[s/\\n$/\\nstartyaml\\n - compare_analyzers: {index: italian_example, first: italian, second: rebuilt_italian}\\nendyaml\\n/] <1> The default stopwords can be overridden with the `stopwords` or `stopwords_path` parameters. <2> This filter should be removed unless there are words which should be excluded from stemming. [[latvian-analyzer]] ===== `latvian` analyzer The `latvian` analyzer could be reimplemented as a `custom` analyzer as follows: [source,js] ---------------------------------------------------- PUT /latvian_example { ""settings"": { ""analysis"": { ""filter"": { ""latvian_stop"": { ""type"": ""stop"", ""stopwords"": ""_latvian_"" <1> }, ""latvian_keywords"": { ""type"": ""keyword_marker"", ""keywords"": [""piemērs""] <2> }, ""latvian_stemmer"": { ""type"": ""stemmer"", ""language"": ""latvian"" } }, ""analyzer"": { ""rebuilt_latvian"": { ""tokenizer"": ""standard"", ""filter"": [ ""lowercase"", ""latvian_stop"", ""latvian_keywords"", ""latvian_stemmer"" ] } } } } } ---------------------------------------------------- // CONSOLE // TEST[s/""latvian_keywords"",//] // TEST[s/\\n$/\\nstartyaml\\n - compare_analyzers: {index: latvian_example, first: latvian, second: rebuilt_latvian}\\nendyaml\\n/] <1> The default stopwords can be overridden with the `stopwords` or `stopwords_path` parameters. <2> This filter should be removed unless there are words which should be excluded from stemming. [[lithuanian-analyzer]] ===== `lithuanian` analyzer The `lithuanian` analyzer could be reimplemented as a `custom` analyzer as follows: [source,js] ---------------------------------------------------- PUT /lithuanian_example { ""settings"": { ""analysis"": { ""filter"": { ""lithuanian_stop"": { ""type"": ""stop"", ""stopwords"": ""_lithuanian_"" <1> }, ""lithuanian_keywords"": { ""type"": ""keyword_marker"", ""keywords"": [""pavyzdys""] <2> }, ""lithuanian_stemmer"": { ""type"": ""stemmer"", ""language"": ""lithuanian"" } }, ""analyzer"": { ""rebuilt_lithuanian"": { ""tokenizer"": ""standard"", ""filter"": [ ""lowercase"", ""lithuanian_stop"", ""lithuanian_keywords"", ""lithuanian_stemmer"" ] } } } } } ---------------------------------------------------- // CONSOLE // TEST[s/""lithuanian_keywords"",//] // TEST[s/\\n$/\\nstartyaml\\n - compare_analyzers: {index: lithuanian_example, first: lithuanian, second: rebuilt_lithuanian}\\nendyaml\\n/] <1> The default stopwords can be overridden with the `stopwords` or `stopwords_path` parameters. <2> This filter should be removed unless there are words which should be excluded from stemming. [[norwegian-analyzer]] ===== `norwegian` analyzer The `norwegian` analyzer could be reimplemented as a `custom` analyzer as follows: [source,js] ---------------------------------------------------- PUT /norwegian_example { ""settings"": { ""analysis"": { ""filter"": { ""norwegian_stop"": { ""type"": ""stop"", ""stopwords"": ""_norwegian_"" <1> }, ""norwegian_keywords"": { ""type"": ""keyword_marker"", ""keywords"": [""eksempel""] <2> }, ""norwegian_stemmer"": { ""type"": ""stemmer"", ""language"": ""norwegian"" } }, ""analyzer"": { ""rebuilt_norwegian"": { ""tokenizer"": ""standard"", ""filter"": [ ""lowercase"", ""norwegian_stop"", ""norwegian_keywords"", ""norwegian_stemmer"" ] } } } } } ---------------------------------------------------- // CONSOLE // TEST[s/""norwegian_keywords"",//] // TEST[s/\\n$/\\nstartyaml\\n - compare_analyzers: {index: norwegian_example, first: norwegian, second: rebuilt_norwegian}\\nendyaml\\n/] <1> The default stopwords can be overridden with the `stopwords` or `stopwords_path` parameters. <2> This filter should be removed unless there are words which should be excluded from stemming. [[persian-analyzer]] ===== `persian` analyzer The `persian` analyzer could be reimplemented as a `custom` analyzer as follows: [source,js] ---------------------------------------------------- PUT /persian_example { ""settings"": { ""analysis"": { ""char_filter"": { ""zero_width_spaces"": { ""type"": ""mapping"", ""mappings"": [ ""\\\\u200C=>\\\\u0020""] <1> } }, ""filter"": { ""persian_stop"": { ""type"": ""stop"", ""stopwords"": ""_persian_"" <2> } }, ""analyzer"": { ""rebuilt_persian"": { ""tokenizer"": ""standard"", ""char_filter"": [ ""zero_width_spaces"" ], ""filter"": [ ""lowercase"", ""decimal_digit"", ""arabic_normalization"", ""persian_normalization"", ""persian_stop"" ] } } } } } ---------------------------------------------------- // CONSOLE // TEST[s/\\n$/\\nstartyaml\\n - compare_analyzers: {index: persian_example, first: persian, second: rebuilt_persian}\\nendyaml\\n/] <1> Replaces zero-width non-joiners with an ASCII space. <2> The default stopwords can be overridden with the `stopwords` or `stopwords_path` parameters. [[portuguese-analyzer]] ===== `portuguese` analyzer The `portuguese` analyzer could be reimplemented as a `custom` analyzer as follows: [source,js] ---------------------------------------------------- PUT /portuguese_example { ""settings"": { ""analysis"": { ""filter"": { ""portuguese_stop"": { ""type"": ""stop"", ""stopwords"": ""_portuguese_"" <1> }, ""portuguese_keywords"": { ""type"": ""keyword_marker"", ""keywords"": [""exemplo""] <2> }, ""portuguese_stemmer"": { ""type"": ""stemmer"", ""language"": ""light_portuguese"" } }, ""analyzer"": { ""rebuilt_portuguese"": { ""tokenizer"": ""standard"", ""filter"": [ ""lowercase"", ""portuguese_stop"", ""portuguese_keywords"", ""portuguese_stemmer"" ] } } } } } ---------------------------------------------------- // CONSOLE // TEST[s/""portuguese_keywords"",//] // TEST[s/\\n$/\\nstartyaml\\n - compare_analyzers: {index: portuguese_example, first: portuguese, second: rebuilt_portuguese}\\nendyaml\\n/] <1> The default stopwords can be overridden with the `stopwords` or `stopwords_path` parameters. <2> This filter should be removed unless there are words which should be excluded from stemming. [[romanian-analyzer]] ===== `romanian` analyzer The `romanian` analyzer could be reimplemented as a `custom` analyzer as follows: [source,js] ---------------------------------------------------- PUT /romanian_example { ""settings"": { ""analysis"": { ""filter"": { ""romanian_stop"": { ""type"": ""stop"", ""stopwords"": ""_romanian_"" <1> }, ""romanian_keywords"": { ""type"": ""keyword_marker"", ""keywords"": [""exemplu""] <2> }, ""romanian_stemmer"": { ""type"": ""stemmer"", ""language"": ""romanian"" } }, ""analyzer"": { ""rebuilt_romanian"": { ""tokenizer"": ""standard"", ""filter"": [ ""lowercase"", ""romanian_stop"", ""romanian_keywords"", ""romanian_stemmer"" ] } } } } } ---------------------------------------------------- // CONSOLE // TEST[s/""romanian_keywords"",//] // TEST[s/\\n$/\\nstartyaml\\n - compare_analyzers: {index: romanian_example, first: romanian, second: rebuilt_romanian}\\nendyaml\\n/] <1> The default stopwords can be overridden with the `stopwords` or `stopwords_path` parameters. <2> This filter should be removed unless there are words which should be excluded from stemming. [[russian-analyzer]] ===== `russian` analyzer The `russian` analyzer could be reimplemented as a `custom` analyzer as follows: [source,js] ---------------------------------------------------- PUT /russian_example { ""settings"": { ""analysis"": { ""filter"": { ""russian_stop"": { ""type"": ""stop"", ""stopwords"": ""_russian_"" <1> }, ""russian_keywords"": { ""type"": ""keyword_marker"", ""keywords"": [""пример""] <2> }, ""russian_stemmer"": { ""type"": ""stemmer"", ""language"": ""russian"" } }, ""analyzer"": { ""rebuilt_russian"": { ""tokenizer"": ""standard"", ""filter"": [ ""lowercase"", ""russian_stop"", ""russian_keywords"", ""russian_stemmer"" ] } } } } } ---------------------------------------------------- // CONSOLE // TEST[s/""russian_keywords"",//] // TEST[s/\\n$/\\nstartyaml\\n - compare_analyzers: {index: russian_example, first: russian, second: rebuilt_russian}\\nendyaml\\n/] <1> The default stopwords can be overridden with the `stopwords` or `stopwords_path` parameters. <2> This filter should be removed unless there are words which should be excluded from stemming. [[sorani-analyzer]] ===== `sorani` analyzer The `sorani` analyzer could be reimplemented as a `custom` analyzer as follows: [source,js] ---------------------------------------------------- PUT /sorani_example { ""settings"": { ""analysis"": { ""filter"": { ""sorani_stop"": { ""type"": ""stop"", ""stopwords"": ""_sorani_"" <1> }, ""sorani_keywords"": { ""type"": ""keyword_marker"", ""keywords"": [""mînak""] <2> }, ""sorani_stemmer"": { ""type"": ""stemmer"", ""language"": ""sorani"" } }, ""analyzer"": { ""rebuilt_sorani"": { ""tokenizer"": ""standard"", ""filter"": [ ""sorani_normalization"", ""lowercase"", ""decimal_digit"", ""sorani_stop"", ""sorani_keywords"", ""sorani_stemmer"" ] } } } } } ---------------------------------------------------- // CONSOLE // TEST[s/""sorani_keywords"",//] // TEST[s/\\n$/\\nstartyaml\\n - compare_analyzers: {index: sorani_example, first: sorani, second: rebuilt_sorani}\\nendyaml\\n/] <1> The default stopwords can be overridden with the `stopwords` or `stopwords_path` parameters. <2> This filter should be removed unless there are words which should be excluded from stemming. [[spanish-analyzer]] ===== `spanish` analyzer The `spanish` analyzer could be reimplemented as a `custom` analyzer as follows: [source,js] ---------------------------------------------------- PUT /spanish_example { ""settings"": { ""analysis"": { ""filter"": { ""spanish_stop"": { ""type"": ""stop"", ""stopwords"": ""_spanish_"" <1> }, ""spanish_keywords"": { ""type"": ""keyword_marker"", ""keywords"": [""ejemplo""] <2> }, ""spanish_stemmer"": { ""type"": ""stemmer"", ""language"": ""light_spanish"" } }, ""analyzer"": { ""rebuilt_spanish"": { ""tokenizer"": ""standard"", ""filter"": [ ""lowercase"", ""spanish_stop"", ""spanish_keywords"", ""spanish_stemmer"" ] } } } } } ---------------------------------------------------- // CONSOLE // TEST[s/""spanish_keywords"",//] // TEST[s/\\n$/\\nstartyaml\\n - compare_analyzers: {index: spanish_example, first: spanish, second: rebuilt_spanish}\\nendyaml\\n/] <1> The default stopwords can be overridden with the `stopwords` or `stopwords_path` parameters. <2> This filter should be removed unless there are words which should be excluded from stemming. [[swedish-analyzer]] ===== `swedish` analyzer The `swedish` analyzer could be reimplemented as a `custom` analyzer as follows: [source,js] ---------------------------------------------------- PUT /swedish_example { ""settings"": { ""analysis"": { ""filter"": { ""swedish_stop"": { ""type"": ""stop"", ""stopwords"": ""_swedish_"" <1> }, ""swedish_keywords"": { ""type"": ""keyword_marker"", ""keywords"": [""exempel""] <2> }, ""swedish_stemmer"": { ""type"": ""stemmer"", ""language"": ""swedish"" } }, ""analyzer"": { ""rebuilt_swedish"": { ""tokenizer"": ""standard"", ""filter"": [ ""lowercase"", ""swedish_stop"", ""swedish_keywords"", ""swedish_stemmer"" ] } } } } } ---------------------------------------------------- // CONSOLE // TEST[s/""swedish_keywords"",//] // TEST[s/\\n$/\\nstartyaml\\n - compare_analyzers: {index: swedish_example, first: swedish, second: rebuilt_swedish}\\nendyaml\\n/] <1> The default stopwords can be overridden with the `stopwords` or `stopwords_path` parameters. <2> This filter should be removed unless there are words which should be excluded from stemming. [[turkish-analyzer]] ===== `turkish` analyzer The `turkish` analyzer could be reimplemented as a `custom` analyzer as follows: [source,js] ---------------------------------------------------- PUT /turkish_example { ""settings"": { ""analysis"": { ""filter"": { ""turkish_stop"": { ""type"": ""stop"", ""stopwords"": ""_turkish_"" <1> }, ""turkish_lowercase"": { ""type"": ""lowercase"", ""language"": ""turkish"" }, ""turkish_keywords"": { ""type"": ""keyword_marker"", ""keywords"": [""örnek""] <2> }, ""turkish_stemmer"": { ""type"": ""stemmer"", ""language"": ""turkish"" } }, ""analyzer"": { ""rebuilt_turkish"": { ""tokenizer"": ""standard"", ""filter"": [ ""apostrophe"", ""turkish_lowercase"", ""turkish_stop"", ""turkish_keywords"", ""turkish_stemmer"" ] } } } } } ---------------------------------------------------- // CONSOLE // TEST[s/""turkish_keywords"",//] // TEST[s/\\n$/\\nstartyaml\\n - compare_analyzers: {index: turkish_example, first: turkish, second: rebuilt_turkish}\\nendyaml\\n/] <1> The default stopwords can be overridden with the `stopwords` or `stopwords_path` parameters. <2> This filter should be removed unless there are words which should be excluded from stemming. [[thai-analyzer]] ===== `thai` analyzer The `thai` analyzer could be reimplemented as a `custom` analyzer as follows: [source,js] ---------------------------------------------------- PUT /thai_example { ""settings"": { ""analysis"": { ""filter"": { ""thai_stop"": { ""type"": ""stop"", ""stopwords"": ""_thai_"" <1> } }, ""analyzer"": { ""rebuilt_thai"": { ""tokenizer"": ""thai"", ""filter"": [ ""lowercase"", ""decimal_digit"", ""thai_stop"" ] } } } } } ---------------------------------------------------- // CONSOLE // TEST[s/""thai_keywords"",//] // TEST[s/\\n$/\\nstartyaml\\n - compare_analyzers: {index: thai_example, first: thai, second: rebuilt_thai}\\nendyaml\\n/] <1> The default stopwords can be overridden with the `stopwords` or `stopwords_path` parameters. ",12403,True,4129.586235624296,median "= v1beta2.ControllerRevision {product-author} {product-version} :data-uri: :icons: :toc: macro :toc-title: :toclevels: 2 toc::[] == Description [%hardbreaks] DEPRECATED - This group version of ControllerRevision is deprecated by apps/v1/ControllerRevision. See the release notes for more information. ControllerRevision implements an immutable snapshot of state data. Clients are responsible for serializing and deserializing the objects that contain their internal state. Once a ControllerRevision has been successfully created, it can not be updated. The API Server will fail validation of all requests that attempt to mutate the Data field. ControllerRevisions may, however, be deleted. Note that, due to its use by both the DaemonSet and StatefulSet controllers for update and rollback, this object is beta. However, it may be subject to name and representation changes in future releases, and clients should not depend on its stability. It is primarily for internal use by controllers. == Object Schema Expand or mouse-over a field for more information about it. ++++
apiVersion:
data:
Raw:
kind:
metadata:
annotations:
[string]:
clusterName:
creationTimestamp:
deletionGracePeriodSeconds:
deletionTimestamp:
finalizers:
- [string]:
generateName:
generation:
:
pending:
- name:
result:
apiVersion:
code:
details:
causes:
- field:
message:
reason:
group:
kind:
name:
retryAfterSeconds:
uid:
kind:
message:
metadata:
continue:
resourceVersion:
selfLink:
reason:
status:
labels:
[string]:
name:
namespace:
ownerReferences:
- apiVersion:
blockOwnerDeletion:
controller:
kind:
name:
uid:
resourceVersion:
selfLink:
uid:
revision:
++++ == Operations [[Post-apis-apps-v1beta2-controllerrevisions]] === Create a ControllerRevision Create a ControllerRevision ==== HTTP request ---- POST /apis/apps/v1beta2/controllerrevisions HTTP/1.1 Authorization: Bearer $TOKEN Accept: application/json Connection: close Content-Type: application/json' { ""kind"": ""ControllerRevision"", ""apiVersion"": ""apps/v1beta2"", ... } ---- ==== Curl request ---- $ curl -k \\ -X POST \\ -d @- \\ -H ""Authorization: Bearer $TOKEN"" \\ -H 'Accept: application/json' \\ -H 'Content-Type: application/json' \\ https://$ENDPOINT/apis/apps/v1beta2/controllerrevisions <<'EOF' { ""kind"": ""ControllerRevision"", ""apiVersion"": ""apps/v1beta2"", ... } EOF ---- ==== HTTP body [cols=""1,5"", options=""header""] |=== |Parameter|Schema |body|v1beta2.ControllerRevision |=== ==== Query parameters [cols=""1,5"", options=""header""] |=== |Parameter|Description |pretty|If 'true', then the output is pretty printed. |=== ==== Responses [cols=""1,5"", options=""header""] |=== |HTTP Code|Schema |200 OK|v1beta2.ControllerRevision |201 Created|v1beta2.ControllerRevision |202 Accepted|v1beta2.ControllerRevision |401 Unauthorized| |=== ==== Consumes * \\*/* ==== Produces * application/json * application/yaml * application/vnd.kubernetes.protobuf [[Post-apis-apps-v1beta2-namespaces-namespace-controllerrevisions]] === Create a ControllerRevision in a namespace Create a ControllerRevision ==== HTTP request ---- POST /apis/apps/v1beta2/namespaces/$NAMESPACE/controllerrevisions HTTP/1.1 Authorization: Bearer $TOKEN Accept: application/json Connection: close Content-Type: application/json' { ""kind"": ""ControllerRevision"", ""apiVersion"": ""apps/v1beta2"", ... } ---- ==== Curl request ---- $ curl -k \\ -X POST \\ -d @- \\ -H ""Authorization: Bearer $TOKEN"" \\ -H 'Accept: application/json' \\ -H 'Content-Type: application/json' \\ https://$ENDPOINT/apis/apps/v1beta2/namespaces/$NAMESPACE/controllerrevisions <<'EOF' { ""kind"": ""ControllerRevision"", ""apiVersion"": ""apps/v1beta2"", ... } EOF ---- ==== HTTP body [cols=""1,5"", options=""header""] |=== |Parameter|Schema |body|v1beta2.ControllerRevision |=== ==== Path parameters [cols=""1,5"", options=""header""] |=== |Parameter|Description |namespace|object name and auth scope, such as for teams and projects |=== ==== Query parameters [cols=""1,5"", options=""header""] |=== |Parameter|Description |pretty|If 'true', then the output is pretty printed. |=== ==== Responses [cols=""1,5"", options=""header""] |=== |HTTP Code|Schema |200 OK|v1beta2.ControllerRevision |201 Created|v1beta2.ControllerRevision |202 Accepted|v1beta2.ControllerRevision |401 Unauthorized| |=== ==== Consumes * \\*/* ==== Produces * application/json * application/yaml * application/vnd.kubernetes.protobuf [[Get-apis-apps-v1beta2-namespaces-namespace-controllerrevisions-name]] === Get a ControllerRevision in a namespace Read the specified ControllerRevision ==== HTTP request ---- GET /apis/apps/v1beta2/namespaces/$NAMESPACE/controllerrevisions/$NAME HTTP/1.1 Authorization: Bearer $TOKEN Accept: application/json Connection: close ---- ==== Curl request ---- $ curl -k \\ -H ""Authorization: Bearer $TOKEN"" \\ -H 'Accept: application/json' \\ https://$ENDPOINT/apis/apps/v1beta2/namespaces/$NAMESPACE/controllerrevisions/$NAME ---- ==== Path parameters [cols=""1,5"", options=""header""] |=== |Parameter|Description |name|name of the ControllerRevision |namespace|object name and auth scope, such as for teams and projects |=== ==== Query parameters [cols=""1,5"", options=""header""] |=== |Parameter|Description |pretty|If 'true', then the output is pretty printed. |exact|Should the export be exact. Exact export maintains cluster-specific fields like 'Namespace'. |export|Should this value be exported. Export strips fields that a user can not specify. |=== ==== Responses [cols=""1,5"", options=""header""] |=== |HTTP Code|Schema |200 OK|v1beta2.ControllerRevision |401 Unauthorized| |=== ==== Consumes * \\*/* ==== Produces * application/json * application/yaml * application/vnd.kubernetes.protobuf [[Get-apis-apps-v1beta2-controllerrevisions]] === Get all ControllerRevisions List or watch objects of kind ControllerRevision ==== HTTP request ---- GET /apis/apps/v1beta2/controllerrevisions HTTP/1.1 Authorization: Bearer $TOKEN Accept: application/json Connection: close ---- ==== Curl request ---- $ curl -k \\ -H ""Authorization: Bearer $TOKEN"" \\ -H 'Accept: application/json' \\ https://$ENDPOINT/apis/apps/v1beta2/controllerrevisions ---- ==== Query parameters [cols=""1,5"", options=""header""] |=== |Parameter|Description |pretty|If 'true', then the output is pretty printed. |continue|The continue option should be set when retrieving more results from the server. Since this value is server defined, clients may only use the continue value from a previous query result with identical query parameters (except for the value of continue) and the server may reject a continue value it does not recognize. If the specified continue value is no longer valid whether due to expiration (generally five to fifteen minutes) or a configuration change on the server the server will respond with a 410 ResourceExpired error indicating the client must restart their list without the continue field. This field is not supported when watch is true. Clients may start a watch from the last resourceVersion value returned by the server and not miss any modifications. |fieldSelector|A selector to restrict the list of returned objects by their fields. Defaults to everything. |includeUninitialized|If true, partially initialized resources are included in the response. |labelSelector|A selector to restrict the list of returned objects by their labels. Defaults to everything. |limit|limit is a maximum number of responses to return for a list call. If more items exist, the server will set the `continue` field on the list metadata to a value that can be used with the same initial query to retrieve the next set of results. Setting a limit may return fewer than the requested amount of items (up to zero items) in the event all requested objects are filtered out and clients should only use the presence of the continue field to determine whether more results are available. Servers may choose not to support the limit argument and will return all of the available results. If limit is specified and the continue field is empty, clients may assume that no more results are available. This field is not supported if watch is true. The server guarantees that the objects returned when using continue will be identical to issuing a single list call without a limit - that is, no objects created, modified, or deleted after the first request is issued will be included in any subsequent continued requests. This is sometimes referred to as a consistent snapshot, and ensures that a client that is using limit to receive smaller chunks of a very large result can ensure they see all possible objects. If objects are updated during a chunked list the version of the object that was present at the time the first list result was calculated is returned. |resourceVersion|When specified with a watch call, shows changes that occur after that particular version of a resource. Defaults to changes from the beginning of history. When specified for list: - if unset, then the result is returned from remote storage based on quorum-read flag; - if it's 0, then we simply return what we currently have in cache, no guarantee; - if set to non zero, then the result is at least as fresh as given rv. |timeoutSeconds|Timeout for the list/watch call. This limits the duration of the call, regardless of any activity or inactivity. |watch|Watch for changes to the described resources and return them as a stream of add, update, and remove notifications. Specify resourceVersion. |=== ==== Responses [cols=""1,5"", options=""header""] |=== |HTTP Code|Schema |200 OK|v1beta2.ControllerRevisionList |401 Unauthorized| |=== ==== Consumes * \\*/* ==== Produces * application/json * application/yaml * application/vnd.kubernetes.protobuf * application/json;stream=watch * application/vnd.kubernetes.protobuf;stream=watch [[Get-apis-apps-v1beta2-namespaces-namespace-controllerrevisions]] === Get all ControllerRevisions in a namespace List or watch objects of kind ControllerRevision ==== HTTP request ---- GET /apis/apps/v1beta2/namespaces/$NAMESPACE/controllerrevisions HTTP/1.1 Authorization: Bearer $TOKEN Accept: application/json Connection: close ---- ==== Curl request ---- $ curl -k \\ -H ""Authorization: Bearer $TOKEN"" \\ -H 'Accept: application/json' \\ https://$ENDPOINT/apis/apps/v1beta2/namespaces/$NAMESPACE/controllerrevisions ---- ==== Path parameters [cols=""1,5"", options=""header""] |=== |Parameter|Description |namespace|object name and auth scope, such as for teams and projects |=== ==== Query parameters [cols=""1,5"", options=""header""] |=== |Parameter|Description |pretty|If 'true', then the output is pretty printed. |continue|The continue option should be set when retrieving more results from the server. Since this value is server defined, clients may only use the continue value from a previous query result with identical query parameters (except for the value of continue) and the server may reject a continue value it does not recognize. If the specified continue value is no longer valid whether due to expiration (generally five to fifteen minutes) or a configuration change on the server the server will respond with a 410 ResourceExpired error indicating the client must restart their list without the continue field. This field is not supported when watch is true. Clients may start a watch from the last resourceVersion value returned by the server and not miss any modifications. |fieldSelector|A selector to restrict the list of returned objects by their fields. Defaults to everything. |includeUninitialized|If true, partially initialized resources are included in the response. |labelSelector|A selector to restrict the list of returned objects by their labels. Defaults to everything. |limit|limit is a maximum number of responses to return for a list call. If more items exist, the server will set the `continue` field on the list metadata to a value that can be used with the same initial query to retrieve the next set of results. Setting a limit may return fewer than the requested amount of items (up to zero items) in the event all requested objects are filtered out and clients should only use the presence of the continue field to determine whether more results are available. Servers may choose not to support the limit argument and will return all of the available results. If limit is specified and the continue field is empty, clients may assume that no more results are available. This field is not supported if watch is true. The server guarantees that the objects returned when using continue will be identical to issuing a single list call without a limit - that is, no objects created, modified, or deleted after the first request is issued will be included in any subsequent continued requests. This is sometimes referred to as a consistent snapshot, and ensures that a client that is using limit to receive smaller chunks of a very large result can ensure they see all possible objects. If objects are updated during a chunked list the version of the object that was present at the time the first list result was calculated is returned. |resourceVersion|When specified with a watch call, shows changes that occur after that particular version of a resource. Defaults to changes from the beginning of history. When specified for list: - if unset, then the result is returned from remote storage based on quorum-read flag; - if it's 0, then we simply return what we currently have in cache, no guarantee; - if set to non zero, then the result is at least as fresh as given rv. |timeoutSeconds|Timeout for the list/watch call. This limits the duration of the call, regardless of any activity or inactivity. |watch|Watch for changes to the described resources and return them as a stream of add, update, and remove notifications. Specify resourceVersion. |=== ==== Responses [cols=""1,5"", options=""header""] |=== |HTTP Code|Schema |200 OK|v1beta2.ControllerRevisionList |401 Unauthorized| |=== ==== Consumes * \\*/* ==== Produces * application/json * application/yaml * application/vnd.kubernetes.protobuf * application/json;stream=watch * application/vnd.kubernetes.protobuf;stream=watch [[Get-apis-apps-v1beta2-watch-namespaces-namespace-controllerrevisions-name]] === Watch a ControllerRevision in a namespace Watch changes to an object of kind ControllerRevision ==== HTTP request ---- GET /apis/apps/v1beta2/watch/namespaces/$NAMESPACE/controllerrevisions/$NAME HTTP/1.1 Authorization: Bearer $TOKEN Accept: application/json Connection: close ---- ==== Curl request ---- $ curl -k \\ -H ""Authorization: Bearer $TOKEN"" \\ -H 'Accept: application/json' \\ https://$ENDPOINT/apis/apps/v1beta2/watch/namespaces/$NAMESPACE/controllerrevisions/$NAME ---- ==== Path parameters [cols=""1,5"", options=""header""] |=== |Parameter|Description |name|name of the ControllerRevision |namespace|object name and auth scope, such as for teams and projects |=== ==== Query parameters [cols=""1,5"", options=""header""] |=== |Parameter|Description |continue|The continue option should be set when retrieving more results from the server. Since this value is server defined, clients may only use the continue value from a previous query result with identical query parameters (except for the value of continue) and the server may reject a continue value it does not recognize. If the specified continue value is no longer valid whether due to expiration (generally five to fifteen minutes) or a configuration change on the server the server will respond with a 410 ResourceExpired error indicating the client must restart their list without the continue field. This field is not supported when watch is true. Clients may start a watch from the last resourceVersion value returned by the server and not miss any modifications. |fieldSelector|A selector to restrict the list of returned objects by their fields. Defaults to everything. |includeUninitialized|If true, partially initialized resources are included in the response. |labelSelector|A selector to restrict the list of returned objects by their labels. Defaults to everything. |limit|limit is a maximum number of responses to return for a list call. If more items exist, the server will set the `continue` field on the list metadata to a value that can be used with the same initial query to retrieve the next set of results. Setting a limit may return fewer than the requested amount of items (up to zero items) in the event all requested objects are filtered out and clients should only use the presence of the continue field to determine whether more results are available. Servers may choose not to support the limit argument and will return all of the available results. If limit is specified and the continue field is empty, clients may assume that no more results are available. This field is not supported if watch is true. The server guarantees that the objects returned when using continue will be identical to issuing a single list call without a limit - that is, no objects created, modified, or deleted after the first request is issued will be included in any subsequent continued requests. This is sometimes referred to as a consistent snapshot, and ensures that a client that is using limit to receive smaller chunks of a very large result can ensure they see all possible objects. If objects are updated during a chunked list the version of the object that was present at the time the first list result was calculated is returned. |pretty|If 'true', then the output is pretty printed. |resourceVersion|When specified with a watch call, shows changes that occur after that particular version of a resource. Defaults to changes from the beginning of history. When specified for list: - if unset, then the result is returned from remote storage based on quorum-read flag; - if it's 0, then we simply return what we currently have in cache, no guarantee; - if set to non zero, then the result is at least as fresh as given rv. |timeoutSeconds|Timeout for the list/watch call. This limits the duration of the call, regardless of any activity or inactivity. |watch|Watch for changes to the described resources and return them as a stream of add, update, and remove notifications. Specify resourceVersion. |=== ==== Responses [cols=""1,5"", options=""header""] |=== |HTTP Code|Schema |200 OK|v1.WatchEvent |401 Unauthorized| |=== ==== Consumes * \\*/* ==== Produces * application/json * application/yaml * application/vnd.kubernetes.protobuf * application/json;stream=watch * application/vnd.kubernetes.protobuf;stream=watch [[Get-apis-apps-v1beta2-watch-controllerrevisions]] === Watch all ControllerRevisions Watch individual changes to a list of ControllerRevision ==== HTTP request ---- GET /apis/apps/v1beta2/watch/controllerrevisions HTTP/1.1 Authorization: Bearer $TOKEN Accept: application/json Connection: close ---- ==== Curl request ---- $ curl -k \\ -H ""Authorization: Bearer $TOKEN"" \\ -H 'Accept: application/json' \\ https://$ENDPOINT/apis/apps/v1beta2/watch/controllerrevisions ---- ==== Query parameters [cols=""1,5"", options=""header""] |=== |Parameter|Description |continue|The continue option should be set when retrieving more results from the server. Since this value is server defined, clients may only use the continue value from a previous query result with identical query parameters (except for the value of continue) and the server may reject a continue value it does not recognize. If the specified continue value is no longer valid whether due to expiration (generally five to fifteen minutes) or a configuration change on the server the server will respond with a 410 ResourceExpired error indicating the client must restart their list without the continue field. This field is not supported when watch is true. Clients may start a watch from the last resourceVersion value returned by the server and not miss any modifications. |fieldSelector|A selector to restrict the list of returned objects by their fields. Defaults to everything. |includeUninitialized|If true, partially initialized resources are included in the response. |labelSelector|A selector to restrict the list of returned objects by their labels. Defaults to everything. |limit|limit is a maximum number of responses to return for a list call. If more items exist, the server will set the `continue` field on the list metadata to a value that can be used with the same initial query to retrieve the next set of results. Setting a limit may return fewer than the requested amount of items (up to zero items) in the event all requested objects are filtered out and clients should only use the presence of the continue field to determine whether more results are available. Servers may choose not to support the limit argument and will return all of the available results. If limit is specified and the continue field is empty, clients may assume that no more results are available. This field is not supported if watch is true. The server guarantees that the objects returned when using continue will be identical to issuing a single list call without a limit - that is, no objects created, modified, or deleted after the first request is issued will be included in any subsequent continued requests. This is sometimes referred to as a consistent snapshot, and ensures that a client that is using limit to receive smaller chunks of a very large result can ensure they see all possible objects. If objects are updated during a chunked list the version of the object that was present at the time the first list result was calculated is returned. |pretty|If 'true', then the output is pretty printed. |resourceVersion|When specified with a watch call, shows changes that occur after that particular version of a resource. Defaults to changes from the beginning of history. When specified for list: - if unset, then the result is returned from remote storage based on quorum-read flag; - if it's 0, then we simply return what we currently have in cache, no guarantee; - if set to non zero, then the result is at least as fresh as given rv. |timeoutSeconds|Timeout for the list/watch call. This limits the duration of the call, regardless of any activity or inactivity. |watch|Watch for changes to the described resources and return them as a stream of add, update, and remove notifications. Specify resourceVersion. |=== ==== Responses [cols=""1,5"", options=""header""] |=== |HTTP Code|Schema |200 OK|v1.WatchEvent |401 Unauthorized| |=== ==== Consumes * \\*/* ==== Produces * application/json * application/yaml * application/vnd.kubernetes.protobuf * application/json;stream=watch * application/vnd.kubernetes.protobuf;stream=watch [[Get-apis-apps-v1beta2-watch-namespaces-namespace-controllerrevisions]] === Watch all ControllerRevisions in a namespace Watch individual changes to a list of ControllerRevision ==== HTTP request ---- GET /apis/apps/v1beta2/watch/namespaces/$NAMESPACE/controllerrevisions HTTP/1.1 Authorization: Bearer $TOKEN Accept: application/json Connection: close ---- ==== Curl request ---- $ curl -k \\ -H ""Authorization: Bearer $TOKEN"" \\ -H 'Accept: application/json' \\ https://$ENDPOINT/apis/apps/v1beta2/watch/namespaces/$NAMESPACE/controllerrevisions ---- ==== Path parameters [cols=""1,5"", options=""header""] |=== |Parameter|Description |namespace|object name and auth scope, such as for teams and projects |=== ==== Query parameters [cols=""1,5"", options=""header""] |=== |Parameter|Description |continue|The continue option should be set when retrieving more results from the server. Since this value is server defined, clients may only use the continue value from a previous query result with identical query parameters (except for the value of continue) and the server may reject a continue value it does not recognize. If the specified continue value is no longer valid whether due to expiration (generally five to fifteen minutes) or a configuration change on the server the server will respond with a 410 ResourceExpired error indicating the client must restart their list without the continue field. This field is not supported when watch is true. Clients may start a watch from the last resourceVersion value returned by the server and not miss any modifications. |fieldSelector|A selector to restrict the list of returned objects by their fields. Defaults to everything. |includeUninitialized|If true, partially initialized resources are included in the response. |labelSelector|A selector to restrict the list of returned objects by their labels. Defaults to everything. |limit|limit is a maximum number of responses to return for a list call. If more items exist, the server will set the `continue` field on the list metadata to a value that can be used with the same initial query to retrieve the next set of results. Setting a limit may return fewer than the requested amount of items (up to zero items) in the event all requested objects are filtered out and clients should only use the presence of the continue field to determine whether more results are available. Servers may choose not to support the limit argument and will return all of the available results. If limit is specified and the continue field is empty, clients may assume that no more results are available. This field is not supported if watch is true. The server guarantees that the objects returned when using continue will be identical to issuing a single list call without a limit - that is, no objects created, modified, or deleted after the first request is issued will be included in any subsequent continued requests. This is sometimes referred to as a consistent snapshot, and ensures that a client that is using limit to receive smaller chunks of a very large result can ensure they see all possible objects. If objects are updated during a chunked list the version of the object that was present at the time the first list result was calculated is returned. |pretty|If 'true', then the output is pretty printed. |resourceVersion|When specified with a watch call, shows changes that occur after that particular version of a resource. Defaults to changes from the beginning of history. When specified for list: - if unset, then the result is returned from remote storage based on quorum-read flag; - if it's 0, then we simply return what we currently have in cache, no guarantee; - if set to non zero, then the result is at least as fresh as given rv. |timeoutSeconds|Timeout for the list/watch call. This limits the duration of the call, regardless of any activity or inactivity. |watch|Watch for changes to the described resources and return them as a stream of add, update, and remove notifications. Specify resourceVersion. |=== ==== Responses [cols=""1,5"", options=""header""] |=== |HTTP Code|Schema |200 OK|v1.WatchEvent |401 Unauthorized| |=== ==== Consumes * \\*/* ==== Produces * application/json * application/yaml * application/vnd.kubernetes.protobuf * application/json;stream=watch * application/vnd.kubernetes.protobuf;stream=watch [[Put-apis-apps-v1beta2-namespaces-namespace-controllerrevisions-name]] === Update a ControllerRevision in a namespace Replace the specified ControllerRevision ==== HTTP request ---- PUT /apis/apps/v1beta2/namespaces/$NAMESPACE/controllerrevisions/$NAME HTTP/1.1 Authorization: Bearer $TOKEN Accept: application/json Connection: close Content-Type: application/json' { ""kind"": ""ControllerRevision"", ""apiVersion"": ""apps/v1beta2"", ... } ---- ==== Curl request ---- $ curl -k \\ -X PUT \\ -d @- \\ -H ""Authorization: Bearer $TOKEN"" \\ -H 'Accept: application/json' \\ -H 'Content-Type: application/json' \\ https://$ENDPOINT/apis/apps/v1beta2/namespaces/$NAMESPACE/controllerrevisions/$NAME <<'EOF' { ""kind"": ""ControllerRevision"", ""apiVersion"": ""apps/v1beta2"", ... } EOF ---- ==== HTTP body [cols=""1,5"", options=""header""] |=== |Parameter|Schema |body|v1beta2.ControllerRevision |=== ==== Path parameters [cols=""1,5"", options=""header""] |=== |Parameter|Description |name|name of the ControllerRevision |namespace|object name and auth scope, such as for teams and projects |=== ==== Query parameters [cols=""1,5"", options=""header""] |=== |Parameter|Description |pretty|If 'true', then the output is pretty printed. |=== ==== Responses [cols=""1,5"", options=""header""] |=== |HTTP Code|Schema |200 OK|v1beta2.ControllerRevision |201 Created|v1beta2.ControllerRevision |401 Unauthorized| |=== ==== Consumes * \\*/* ==== Produces * application/json * application/yaml * application/vnd.kubernetes.protobuf [[Patch-apis-apps-v1beta2-namespaces-namespace-controllerrevisions-name]] === Patch a ControllerRevision in a namespace Partially update the specified ControllerRevision ==== HTTP request ---- PATCH /apis/apps/v1beta2/namespaces/$NAMESPACE/controllerrevisions/$NAME HTTP/1.1 Authorization: Bearer $TOKEN Accept: application/json Connection: close Content-Type: application/json-patch+json' { ... } ---- ==== Curl request ---- $ curl -k \\ -X PATCH \\ -d @- \\ -H ""Authorization: Bearer $TOKEN"" \\ -H 'Accept: application/json' \\ -H 'Content-Type: application/json-patch+json' \\ https://$ENDPOINT/apis/apps/v1beta2/namespaces/$NAMESPACE/controllerrevisions/$NAME <<'EOF' { ... } EOF ---- ==== HTTP body [cols=""1,5"", options=""header""] |=== |Parameter|Schema |body|v1.Patch |=== ==== Path parameters [cols=""1,5"", options=""header""] |=== |Parameter|Description |name|name of the ControllerRevision |namespace|object name and auth scope, such as for teams and projects |=== ==== Query parameters [cols=""1,5"", options=""header""] |=== |Parameter|Description |pretty|If 'true', then the output is pretty printed. |=== ==== Responses [cols=""1,5"", options=""header""] |=== |HTTP Code|Schema |200 OK|v1beta2.ControllerRevision |401 Unauthorized| |=== ==== Consumes * application/json-patch+json * application/merge-patch+json * application/strategic-merge-patch+json ==== Produces * application/json * application/yaml * application/vnd.kubernetes.protobuf [[Delete-apis-apps-v1beta2-namespaces-namespace-controllerrevisions-name]] === Delete a ControllerRevision in a namespace Delete a ControllerRevision ==== HTTP request ---- DELETE /apis/apps/v1beta2/namespaces/$NAMESPACE/controllerrevisions/$NAME HTTP/1.1 Authorization: Bearer $TOKEN Accept: application/json Connection: close Content-Type: application/json' { ... } ---- ==== Curl request ---- $ curl -k \\ -X DELETE \\ -d @- \\ -H ""Authorization: Bearer $TOKEN"" \\ -H 'Accept: application/json' \\ -H 'Content-Type: application/json' \\ https://$ENDPOINT/apis/apps/v1beta2/namespaces/$NAMESPACE/controllerrevisions/$NAME <<'EOF' { ... } EOF ---- ==== HTTP body [cols=""1,5"", options=""header""] |=== |Parameter|Schema |body|v1.DeleteOptions |=== ==== Path parameters [cols=""1,5"", options=""header""] |=== |Parameter|Description |name|name of the ControllerRevision |namespace|object name and auth scope, such as for teams and projects |=== ==== Query parameters [cols=""1,5"", options=""header""] |=== |Parameter|Description |pretty|If 'true', then the output is pretty printed. |gracePeriodSeconds|The duration in seconds before the object should be deleted. Value must be non-negative integer. The value zero indicates delete immediately. If this value is nil, the default grace period for the specified type will be used. Defaults to a per object value if not specified. zero means delete immediately. |orphanDependents|Deprecated: please use the PropagationPolicy, this field will be deprecated in 1.7. Should the dependent objects be orphaned. If true/false, the ""orphan"" finalizer will be added to/removed from the object's finalizers list. Either this field or PropagationPolicy may be set, but not both. |propagationPolicy|Whether and how garbage collection will be performed. Either this field or OrphanDependents may be set, but not both. The default policy is decided by the existing finalizer set in the metadata.finalizers and the resource-specific default policy. Acceptable values are: 'Orphan' - orphan the dependents; 'Background' - allow the garbage collector to delete the dependents in the background; 'Foreground' - a cascading policy that deletes all dependents in the foreground. |=== ==== Responses [cols=""1,5"", options=""header""] |=== |HTTP Code|Schema |200 OK|v1.Status |401 Unauthorized| |=== ==== Consumes * \\*/* ==== Produces * application/json * application/yaml * application/vnd.kubernetes.protobuf [[Delete-apis-apps-v1beta2-namespaces-namespace-controllerrevisions]] === Delete all ControllerRevisions in a namespace Delete collection of ControllerRevision ==== HTTP request ---- DELETE /apis/apps/v1beta2/namespaces/$NAMESPACE/controllerrevisions HTTP/1.1 Authorization: Bearer $TOKEN Accept: application/json Connection: close ---- ==== Curl request ---- $ curl -k \\ -X DELETE \\ -H ""Authorization: Bearer $TOKEN"" \\ -H 'Accept: application/json' \\ https://$ENDPOINT/apis/apps/v1beta2/namespaces/$NAMESPACE/controllerrevisions ---- ==== Path parameters [cols=""1,5"", options=""header""] |=== |Parameter|Description |namespace|object name and auth scope, such as for teams and projects |=== ==== Query parameters [cols=""1,5"", options=""header""] |=== |Parameter|Description |pretty|If 'true', then the output is pretty printed. |continue|The continue option should be set when retrieving more results from the server. Since this value is server defined, clients may only use the continue value from a previous query result with identical query parameters (except for the value of continue) and the server may reject a continue value it does not recognize. If the specified continue value is no longer valid whether due to expiration (generally five to fifteen minutes) or a configuration change on the server the server will respond with a 410 ResourceExpired error indicating the client must restart their list without the continue field. This field is not supported when watch is true. Clients may start a watch from the last resourceVersion value returned by the server and not miss any modifications. |fieldSelector|A selector to restrict the list of returned objects by their fields. Defaults to everything. |includeUninitialized|If true, partially initialized resources are included in the response. |labelSelector|A selector to restrict the list of returned objects by their labels. Defaults to everything. |limit|limit is a maximum number of responses to return for a list call. If more items exist, the server will set the `continue` field on the list metadata to a value that can be used with the same initial query to retrieve the next set of results. Setting a limit may return fewer than the requested amount of items (up to zero items) in the event all requested objects are filtered out and clients should only use the presence of the continue field to determine whether more results are available. Servers may choose not to support the limit argument and will return all of the available results. If limit is specified and the continue field is empty, clients may assume that no more results are available. This field is not supported if watch is true. The server guarantees that the objects returned when using continue will be identical to issuing a single list call without a limit - that is, no objects created, modified, or deleted after the first request is issued will be included in any subsequent continued requests. This is sometimes referred to as a consistent snapshot, and ensures that a client that is using limit to receive smaller chunks of a very large result can ensure they see all possible objects. If objects are updated during a chunked list the version of the object that was present at the time the first list result was calculated is returned. |resourceVersion|When specified with a watch call, shows changes that occur after that particular version of a resource. Defaults to changes from the beginning of history. When specified for list: - if unset, then the result is returned from remote storage based on quorum-read flag; - if it's 0, then we simply return what we currently have in cache, no guarantee; - if set to non zero, then the result is at least as fresh as given rv. |timeoutSeconds|Timeout for the list/watch call. This limits the duration of the call, regardless of any activity or inactivity. |watch|Watch for changes to the described resources and return them as a stream of add, update, and remove notifications. Specify resourceVersion. |=== ==== Responses [cols=""1,5"", options=""header""] |=== |HTTP Code|Schema |200 OK|v1.Status |401 Unauthorized| |=== ==== Consumes * \\*/* ==== Produces * application/json * application/yaml * application/vnd.kubernetes.protobuf ",12304,False,2442.5115566768472,median "// Copyright 2016 PDFium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // Original code copyright 2014 Foxit Software Inc. http://www.foxitsoftware.com #include ""xfa/fxfa/parser/cxfa_widgetdata.h"" #include ""core/fxcrt/cfx_decimal.h"" #include ""core/fxcrt/fx_extension.h"" #include ""fxbarcode/BC_Library.h"" #include ""third_party/base/stl_util.h"" #include ""xfa/fxfa/cxfa_ffnotify.h"" #include ""xfa/fxfa/parser/cxfa_document.h"" #include ""xfa/fxfa/parser/cxfa_eventdata.h"" #include ""xfa/fxfa/parser/cxfa_localevalue.h"" #include ""xfa/fxfa/parser/cxfa_measurement.h"" #include ""xfa/fxfa/parser/cxfa_node.h"" #include ""xfa/fxfa/parser/xfa_utils.h"" namespace { float GetEdgeThickness(const std::vector& strokes, bool b3DStyle, int32_t nIndex) { float fThickness = 0; if (strokes[nIndex * 2 + 1].GetPresence() == XFA_ATTRIBUTEENUM_Visible) { if (nIndex == 0) fThickness += 2.5f; fThickness += strokes[nIndex * 2 + 1].GetThickness() * (b3DStyle ? 4 : 2); } return fThickness; } bool SplitDateTime(const WideString& wsDateTime, WideString& wsDate, WideString& wsTime) { wsDate = L""""; wsTime = L""""; if (wsDateTime.IsEmpty()) return false; auto nSplitIndex = wsDateTime.Find('T'); if (!nSplitIndex.has_value()) nSplitIndex = wsDateTime.Find(' '); if (!nSplitIndex.has_value()) return false; wsDate = wsDateTime.Left(nSplitIndex.value()); if (!wsDate.IsEmpty()) { if (!std::any_of(wsDate.begin(), wsDate.end(), std::iswdigit)) return false; } wsTime = wsDateTime.Right(wsDateTime.GetLength() - nSplitIndex.value() - 1); if (!wsTime.IsEmpty()) { if (!std::any_of(wsTime.begin(), wsTime.end(), std::iswdigit)) return false; } return true; } CXFA_Node* CreateUIChild(CXFA_Node* pNode, XFA_Element& eWidgetType) { XFA_Element eType = pNode->GetElementType(); eWidgetType = eType; if (eType != XFA_Element::Field && eType != XFA_Element::Draw) return nullptr; eWidgetType = XFA_Element::Unknown; XFA_Element eUIType = XFA_Element::Unknown; CXFA_ValueData defValueData( pNode->JSNode()->GetProperty(0, XFA_Element::Value, true)); XFA_Element eValueType = defValueData.GetChildValueClassID(); switch (eValueType) { case XFA_Element::Boolean: eUIType = XFA_Element::CheckButton; break; case XFA_Element::Integer: case XFA_Element::Decimal: case XFA_Element::Float: eUIType = XFA_Element::NumericEdit; break; case XFA_Element::ExData: case XFA_Element::Text: eUIType = XFA_Element::TextEdit; eWidgetType = XFA_Element::Text; break; case XFA_Element::Date: case XFA_Element::Time: case XFA_Element::DateTime: eUIType = XFA_Element::DateTimeEdit; break; case XFA_Element::Image: eUIType = XFA_Element::ImageEdit; eWidgetType = XFA_Element::Image; break; case XFA_Element::Arc: case XFA_Element::Line: case XFA_Element::Rectangle: eUIType = XFA_Element::DefaultUi; eWidgetType = eValueType; break; default: break; } CXFA_Node* pUIChild = nullptr; CXFA_Node* pUI = pNode->JSNode()->GetProperty(0, XFA_Element::Ui, true); CXFA_Node* pChild = pUI->GetNodeItem(XFA_NODEITEM_FirstChild); for (; pChild; pChild = pChild->GetNodeItem(XFA_NODEITEM_NextSibling)) { XFA_Element eChildType = pChild->GetElementType(); if (eChildType == XFA_Element::Extras || eChildType == XFA_Element::Picture) { continue; } const XFA_PROPERTY* pProperty = XFA_GetPropertyOfElement( XFA_Element::Ui, eChildType, XFA_XDPPACKET_Form); if (pProperty && (pProperty->uFlags & XFA_PROPERTYFLAG_OneOf)) { pUIChild = pChild; break; } } if (eType == XFA_Element::Draw) { XFA_Element eDraw = pUIChild ? pUIChild->GetElementType() : XFA_Element::Unknown; switch (eDraw) { case XFA_Element::TextEdit: eWidgetType = XFA_Element::Text; break; case XFA_Element::ImageEdit: eWidgetType = XFA_Element::Image; break; default: eWidgetType = eWidgetType == XFA_Element::Unknown ? XFA_Element::Text : eWidgetType; break; } } else { if (pUIChild && pUIChild->GetElementType() == XFA_Element::DefaultUi) { eWidgetType = XFA_Element::TextEdit; } else { eWidgetType = pUIChild ? pUIChild->GetElementType() : (eUIType == XFA_Element::Unknown ? XFA_Element::TextEdit : eUIType); } } if (!pUIChild) { if (eUIType == XFA_Element::Unknown) { eUIType = XFA_Element::TextEdit; defValueData.GetNode()->JSNode()->GetProperty(0, XFA_Element::Text, true); } return pUI->JSNode()->GetProperty(0, eUIType, true); } if (eUIType != XFA_Element::Unknown) return pUIChild; switch (pUIChild->GetElementType()) { case XFA_Element::CheckButton: { eValueType = XFA_Element::Text; if (CXFA_Node* pItems = pNode->GetChild(0, XFA_Element::Items, false)) { if (CXFA_Node* pItem = pItems->GetChild(0, XFA_Element::Unknown, false)) eValueType = pItem->GetElementType(); } break; } case XFA_Element::DateTimeEdit: eValueType = XFA_Element::DateTime; break; case XFA_Element::ImageEdit: eValueType = XFA_Element::Image; break; case XFA_Element::NumericEdit: eValueType = XFA_Element::Float; break; case XFA_Element::ChoiceList: { eValueType = (pUIChild->JSNode()->GetEnum(XFA_Attribute::Open) == XFA_ATTRIBUTEENUM_MultiSelect) ? XFA_Element::ExData : XFA_Element::Text; break; } case XFA_Element::Barcode: case XFA_Element::Button: case XFA_Element::PasswordEdit: case XFA_Element::Signature: case XFA_Element::TextEdit: default: eValueType = XFA_Element::Text; break; } defValueData.GetNode()->JSNode()->GetProperty(0, eValueType, true); return pUIChild; } } // namespace CXFA_WidgetData::CXFA_WidgetData(CXFA_Node* pNode) : CXFA_DataData(pNode), m_bIsNull(true), m_bPreNull(true), m_pUiChildNode(nullptr), m_eUIType(XFA_Element::Unknown) {} CXFA_Node* CXFA_WidgetData::GetUIChild() { if (m_eUIType == XFA_Element::Unknown) m_pUiChildNode = CreateUIChild(m_pNode, m_eUIType); return m_pUiChildNode; } XFA_Element CXFA_WidgetData::GetUIType() { GetUIChild(); return m_eUIType; } WideString CXFA_WidgetData::GetRawValue() { return m_pNode->JSNode()->GetContent(false); } int32_t CXFA_WidgetData::GetAccess() { CXFA_Node* pNode = m_pNode; while (pNode) { int32_t iAcc = pNode->JSNode()->GetEnum(XFA_Attribute::Access); if (iAcc != XFA_ATTRIBUTEENUM_Open) return iAcc; pNode = pNode->GetNodeItem(XFA_NODEITEM_Parent, XFA_ObjectType::ContainerNode); } return XFA_ATTRIBUTEENUM_Open; } int32_t CXFA_WidgetData::GetRotate() { pdfium::Optional measure = m_pNode->JSNode()->TryMeasure(XFA_Attribute::Rotate, false); if (!measure) return 0; int32_t iRotate = FXSYS_round(measure->GetValue()); iRotate = XFA_MapRotation(iRotate); return iRotate / 90 * 90; } CXFA_BorderData CXFA_WidgetData::GetBorderData(bool bModified) { return CXFA_BorderData( m_pNode->JSNode()->GetProperty(0, XFA_Element::Border, bModified)); } CXFA_CaptionData CXFA_WidgetData::GetCaptionData() { return CXFA_CaptionData( m_pNode->JSNode()->GetProperty(0, XFA_Element::Caption, false)); } CXFA_FontData CXFA_WidgetData::GetFontData(bool bModified) { return CXFA_FontData( m_pNode->JSNode()->GetProperty(0, XFA_Element::Font, bModified)); } CXFA_MarginData CXFA_WidgetData::GetMarginData() { return CXFA_MarginData( m_pNode->JSNode()->GetProperty(0, XFA_Element::Margin, false)); } CXFA_ParaData CXFA_WidgetData::GetParaData() { return CXFA_ParaData( m_pNode->JSNode()->GetProperty(0, XFA_Element::Para, false)); } std::vector CXFA_WidgetData::GetEventList() { return m_pNode->GetNodeList(0, XFA_Element::Event); } std::vector CXFA_WidgetData::GetEventByActivity(int32_t iActivity, bool bIsFormReady) { std::vector events; for (CXFA_Node* pNode : GetEventList()) { CXFA_EventData eventData(pNode); if (eventData.GetActivity() == iActivity) { if (iActivity == XFA_ATTRIBUTEENUM_Ready) { WideString wsRef; eventData.GetRef(wsRef); if (bIsFormReady) { if (wsRef == WideStringView(L""$form"")) events.push_back(pNode); } else { if (wsRef == WideStringView(L""$layout"")) events.push_back(pNode); } } else { events.push_back(pNode); } } } return events; } CXFA_ValueData CXFA_WidgetData::GetDefaultValueData() { CXFA_Node* pTemNode = m_pNode->GetTemplateNode(); return CXFA_ValueData( pTemNode ? pTemNode->JSNode()->GetProperty(0, XFA_Element::Value, false) : nullptr); } CXFA_ValueData CXFA_WidgetData::GetFormValueData() { return CXFA_ValueData( m_pNode->JSNode()->GetProperty(0, XFA_Element::Value, false)); } CXFA_CalculateData CXFA_WidgetData::GetCalculateData() { return CXFA_CalculateData( m_pNode->JSNode()->GetProperty(0, XFA_Element::Calculate, false)); } CXFA_ValidateData CXFA_WidgetData::GetValidateData(bool bModified) { return CXFA_ValidateData( m_pNode->JSNode()->GetProperty(0, XFA_Element::Validate, bModified)); } CXFA_BindData CXFA_WidgetData::GetBindData() { return CXFA_BindData( m_pNode->JSNode()->GetProperty(0, XFA_Element::Bind, false)); } bool CXFA_WidgetData::GetWidth(float& fWidth) { return TryMeasure(XFA_Attribute::W, fWidth); } bool CXFA_WidgetData::GetHeight(float& fHeight) { return TryMeasure(XFA_Attribute::H, fHeight); } bool CXFA_WidgetData::GetMinWidth(float& fMinWidth) { return TryMeasure(XFA_Attribute::MinW, fMinWidth); } bool CXFA_WidgetData::GetMinHeight(float& fMinHeight) { return TryMeasure(XFA_Attribute::MinH, fMinHeight); } bool CXFA_WidgetData::GetMaxWidth(float& fMaxWidth) { return TryMeasure(XFA_Attribute::MaxW, fMaxWidth); } bool CXFA_WidgetData::GetMaxHeight(float& fMaxHeight) { return TryMeasure(XFA_Attribute::MaxH, fMaxHeight); } CXFA_BorderData CXFA_WidgetData::GetUIBorderData() { CXFA_Node* pUIChild = GetUIChild(); return CXFA_BorderData( pUIChild ? pUIChild->JSNode()->GetProperty(0, XFA_Element::Border, false) : nullptr); } CFX_RectF CXFA_WidgetData::GetUIMargin() { CXFA_Node* pUIChild = GetUIChild(); CXFA_MarginData mgUI = CXFA_MarginData( pUIChild ? pUIChild->JSNode()->GetProperty(0, XFA_Element::Margin, false) : nullptr); if (!mgUI) return CFX_RectF(); CXFA_BorderData borderData = GetUIBorderData(); if (borderData && borderData.GetPresence() != XFA_ATTRIBUTEENUM_Visible) return CFX_RectF(); float fLeftInset, fTopInset, fRightInset, fBottomInset; bool bLeft = mgUI.GetLeftInset(fLeftInset); bool bTop = mgUI.GetTopInset(fTopInset); bool bRight = mgUI.GetRightInset(fRightInset); bool bBottom = mgUI.GetBottomInset(fBottomInset); if (borderData) { bool bVisible = false; float fThickness = 0; borderData.Get3DStyle(bVisible, fThickness); if (!bLeft || !bTop || !bRight || !bBottom) { std::vector strokes = borderData.GetStrokes(); if (!bTop) fTopInset = GetEdgeThickness(strokes, bVisible, 0); if (!bRight) fRightInset = GetEdgeThickness(strokes, bVisible, 1); if (!bBottom) fBottomInset = GetEdgeThickness(strokes, bVisible, 2); if (!bLeft) fLeftInset = GetEdgeThickness(strokes, bVisible, 3); } } return CFX_RectF(fLeftInset, fTopInset, fRightInset, fBottomInset); } XFA_ATTRIBUTEENUM CXFA_WidgetData::GetButtonHighlight() { CXFA_Node* pUIChild = GetUIChild(); if (pUIChild) return pUIChild->JSNode()->GetEnum(XFA_Attribute::Highlight); return XFA_ATTRIBUTEENUM_Inverted; } bool CXFA_WidgetData::GetButtonRollover(WideString& wsRollover, bool& bRichText) { if (CXFA_Node* pItems = m_pNode->GetChild(0, XFA_Element::Items, false)) { CXFA_Node* pText = pItems->GetNodeItem(XFA_NODEITEM_FirstChild); while (pText) { if (pText->JSNode()->GetCData(XFA_Attribute::Name) == L""rollover"") { wsRollover = pText->JSNode()->GetContent(false); bRichText = pText->GetElementType() == XFA_Element::ExData; return !wsRollover.IsEmpty(); } pText = pText->GetNodeItem(XFA_NODEITEM_NextSibling); } } return false; } bool CXFA_WidgetData::GetButtonDown(WideString& wsDown, bool& bRichText) { if (CXFA_Node* pItems = m_pNode->GetChild(0, XFA_Element::Items, false)) { CXFA_Node* pText = pItems->GetNodeItem(XFA_NODEITEM_FirstChild); while (pText) { if (pText->JSNode()->GetCData(XFA_Attribute::Name) == L""down"") { wsDown = pText->JSNode()->GetContent(false); bRichText = pText->GetElementType() == XFA_Element::ExData; return !wsDown.IsEmpty(); } pText = pText->GetNodeItem(XFA_NODEITEM_NextSibling); } } return false; } XFA_ATTRIBUTEENUM CXFA_WidgetData::GetCheckButtonShape() { CXFA_Node* pUIChild = GetUIChild(); if (pUIChild) return pUIChild->JSNode()->GetEnum(XFA_Attribute::Shape); return XFA_ATTRIBUTEENUM_Square; } XFA_ATTRIBUTEENUM CXFA_WidgetData::GetCheckButtonMark() { CXFA_Node* pUIChild = GetUIChild(); if (pUIChild) return pUIChild->JSNode()->GetEnum(XFA_Attribute::Mark); return XFA_ATTRIBUTEENUM_Default; } bool CXFA_WidgetData::IsRadioButton() { CXFA_Node* pParent = m_pNode->GetNodeItem(XFA_NODEITEM_Parent); return pParent && pParent->GetElementType() == XFA_Element::ExclGroup; } float CXFA_WidgetData::GetCheckButtonSize() { CXFA_Node* pUIChild = GetUIChild(); if (pUIChild) { return pUIChild->JSNode() ->GetMeasure(XFA_Attribute::Size) .ToUnit(XFA_Unit::Pt); } return CXFA_Measurement(10, XFA_Unit::Pt).ToUnit(XFA_Unit::Pt); } bool CXFA_WidgetData::IsAllowNeutral() { CXFA_Node* pUIChild = GetUIChild(); return pUIChild && pUIChild->JSNode()->GetBoolean(XFA_Attribute::AllowNeutral); } XFA_CHECKSTATE CXFA_WidgetData::GetCheckState() { WideString wsValue = GetRawValue(); if (wsValue.IsEmpty()) return XFA_CHECKSTATE_Off; if (CXFA_Node* pItems = m_pNode->GetChild(0, XFA_Element::Items, false)) { CXFA_Node* pText = pItems->GetNodeItem(XFA_NODEITEM_FirstChild); int32_t i = 0; while (pText) { pdfium::Optional wsContent = pText->JSNode()->TryContent(false, true); if (wsContent && *wsContent == wsValue) return static_cast(i); i++; pText = pText->GetNodeItem(XFA_NODEITEM_NextSibling); } } return XFA_CHECKSTATE_Off; } void CXFA_WidgetData::SetCheckState(XFA_CHECKSTATE eCheckState, bool bNotify) { CXFA_WidgetData exclGroup(GetExclGroupNode()); if (exclGroup) { WideString wsValue; if (eCheckState != XFA_CHECKSTATE_Off) { if (CXFA_Node* pItems = m_pNode->GetChild(0, XFA_Element::Items, false)) { CXFA_Node* pText = pItems->GetNodeItem(XFA_NODEITEM_FirstChild); if (pText) wsValue = pText->JSNode()->GetContent(false); } } CXFA_Node* pChild = exclGroup.GetNode()->GetNodeItem(XFA_NODEITEM_FirstChild); for (; pChild; pChild = pChild->GetNodeItem(XFA_NODEITEM_NextSibling)) { if (pChild->GetElementType() != XFA_Element::Field) continue; CXFA_Node* pItem = pChild->GetChild(0, XFA_Element::Items, false); if (!pItem) continue; CXFA_Node* pItemchild = pItem->GetNodeItem(XFA_NODEITEM_FirstChild); if (!pItemchild) continue; WideString text = pItemchild->JSNode()->GetContent(false); WideString wsChildValue = text; if (wsValue != text) { pItemchild = pItemchild->GetNodeItem(XFA_NODEITEM_NextSibling); if (pItemchild) wsChildValue = pItemchild->JSNode()->GetContent(false); else wsChildValue.clear(); } CXFA_WidgetData ch(pChild); ch.SyncValue(wsChildValue, bNotify); } exclGroup.SyncValue(wsValue, bNotify); } else { CXFA_Node* pItems = m_pNode->GetChild(0, XFA_Element::Items, false); if (!pItems) return; int32_t i = -1; CXFA_Node* pText = pItems->GetNodeItem(XFA_NODEITEM_FirstChild); WideString wsContent; while (pText) { i++; if (i == eCheckState) { wsContent = pText->JSNode()->GetContent(false); break; } pText = pText->GetNodeItem(XFA_NODEITEM_NextSibling); } SyncValue(wsContent, bNotify); } } CXFA_Node* CXFA_WidgetData::GetExclGroupNode() { CXFA_Node* pExcl = ToNode(m_pNode->GetNodeItem(XFA_NODEITEM_Parent)); if (!pExcl || pExcl->GetElementType() != XFA_Element::ExclGroup) return nullptr; return pExcl; } CXFA_Node* CXFA_WidgetData::GetSelectedMember() { CXFA_Node* pSelectedMember = nullptr; WideString wsState = GetRawValue(); if (wsState.IsEmpty()) return pSelectedMember; for (CXFA_Node* pNode = ToNode(m_pNode->GetNodeItem(XFA_NODEITEM_FirstChild)); pNode; pNode = pNode->GetNodeItem(XFA_NODEITEM_NextSibling)) { CXFA_WidgetData widgetData(pNode); if (widgetData.GetCheckState() == XFA_CHECKSTATE_On) { pSelectedMember = pNode; break; } } return pSelectedMember; } CXFA_Node* CXFA_WidgetData::SetSelectedMember(const WideStringView& wsName, bool bNotify) { uint32_t nameHash = FX_HashCode_GetW(wsName, false); for (CXFA_Node* pNode = ToNode(m_pNode->GetNodeItem(XFA_NODEITEM_FirstChild)); pNode; pNode = pNode->GetNodeItem(XFA_NODEITEM_NextSibling)) { if (pNode->GetNameHash() == nameHash) { CXFA_WidgetData widgetData(pNode); widgetData.SetCheckState(XFA_CHECKSTATE_On, bNotify); return pNode; } } return nullptr; } void CXFA_WidgetData::SetSelectedMemberByValue(const WideStringView& wsValue, bool bNotify, bool bScriptModify, bool bSyncData) { WideString wsExclGroup; for (CXFA_Node* pNode = m_pNode->GetNodeItem(XFA_NODEITEM_FirstChild); pNode; pNode = pNode->GetNodeItem(XFA_NODEITEM_NextSibling)) { if (pNode->GetElementType() != XFA_Element::Field) continue; CXFA_Node* pItem = pNode->GetChild(0, XFA_Element::Items, false); if (!pItem) continue; CXFA_Node* pItemchild = pItem->GetNodeItem(XFA_NODEITEM_FirstChild); if (!pItemchild) continue; WideString wsChildValue = pItemchild->JSNode()->GetContent(false); if (wsValue != wsChildValue) { pItemchild = pItemchild->GetNodeItem(XFA_NODEITEM_NextSibling); if (pItemchild) wsChildValue = pItemchild->JSNode()->GetContent(false); else wsChildValue.clear(); } else { wsExclGroup = wsValue; } pNode->JSNode()->SetContent(wsChildValue, wsChildValue, bNotify, bScriptModify, false); } if (m_pNode) { m_pNode->JSNode()->SetContent(wsExclGroup, wsExclGroup, bNotify, bScriptModify, bSyncData); } } CXFA_Node* CXFA_WidgetData::GetExclGroupFirstMember() { CXFA_Node* pExcl = GetNode(); if (!pExcl) return nullptr; CXFA_Node* pNode = pExcl->GetNodeItem(XFA_NODEITEM_FirstChild); while (pNode) { if (pNode->GetElementType() == XFA_Element::Field) return pNode; pNode = pNode->GetNodeItem(XFA_NODEITEM_NextSibling); } return nullptr; } CXFA_Node* CXFA_WidgetData::GetExclGroupNextMember(CXFA_Node* pNode) { if (!pNode) return nullptr; CXFA_Node* pNodeField = pNode->GetNodeItem(XFA_NODEITEM_NextSibling); while (pNodeField) { if (pNodeField->GetElementType() == XFA_Element::Field) return pNodeField; pNodeField = pNodeField->GetNodeItem(XFA_NODEITEM_NextSibling); } return nullptr; } XFA_ATTRIBUTEENUM CXFA_WidgetData::GetChoiceListCommitOn() { CXFA_Node* pUIChild = GetUIChild(); if (pUIChild) return pUIChild->JSNode()->GetEnum(XFA_Attribute::CommitOn); return XFA_ATTRIBUTEENUM_Select; } bool CXFA_WidgetData::IsChoiceListAllowTextEntry() { CXFA_Node* pUIChild = GetUIChild(); return pUIChild && pUIChild->JSNode()->GetBoolean(XFA_Attribute::TextEntry); } XFA_ATTRIBUTEENUM CXFA_WidgetData::GetChoiceListOpen() { CXFA_Node* pUIChild = GetUIChild(); if (pUIChild) return pUIChild->JSNode()->GetEnum(XFA_Attribute::Open); return XFA_ATTRIBUTEENUM_UserControl; } bool CXFA_WidgetData::IsListBox() { int32_t iOpenMode = GetChoiceListOpen(); return iOpenMode == XFA_ATTRIBUTEENUM_Always || iOpenMode == XFA_ATTRIBUTEENUM_MultiSelect; } int32_t CXFA_WidgetData::CountChoiceListItems(bool bSaveValue) { std::vector pItems; int32_t iCount = 0; for (CXFA_Node* pNode = m_pNode->GetNodeItem(XFA_NODEITEM_FirstChild); pNode; pNode = pNode->GetNodeItem(XFA_NODEITEM_NextSibling)) { if (pNode->GetElementType() != XFA_Element::Items) continue; iCount++; pItems.push_back(pNode); if (iCount == 2) break; } if (iCount == 0) return 0; CXFA_Node* pItem = pItems[0]; if (iCount > 1) { bool bItemOneHasSave = pItems[0]->JSNode()->GetBoolean(XFA_Attribute::Save); bool bItemTwoHasSave = pItems[1]->JSNode()->GetBoolean(XFA_Attribute::Save); if (bItemOneHasSave != bItemTwoHasSave && bSaveValue == bItemTwoHasSave) pItem = pItems[1]; } return pItem->CountChildren(XFA_Element::Unknown, false); } bool CXFA_WidgetData::GetChoiceListItem(WideString& wsText, int32_t nIndex, bool bSaveValue) { wsText.clear(); std::vector pItemsArray; CXFA_Node* pItems = nullptr; int32_t iCount = 0; CXFA_Node* pNode = m_pNode->GetNodeItem(XFA_NODEITEM_FirstChild); for (; pNode; pNode = pNode->GetNodeItem(XFA_NODEITEM_NextSibling)) { if (pNode->GetElementType() != XFA_Element::Items) continue; iCount++; pItemsArray.push_back(pNode); if (iCount == 2) break; } if (iCount == 0) return false; pItems = pItemsArray[0]; if (iCount > 1) { bool bItemOneHasSave = pItemsArray[0]->JSNode()->GetBoolean(XFA_Attribute::Save); bool bItemTwoHasSave = pItemsArray[1]->JSNode()->GetBoolean(XFA_Attribute::Save); if (bItemOneHasSave != bItemTwoHasSave && bSaveValue == bItemTwoHasSave) pItems = pItemsArray[1]; } if (pItems) { CXFA_Node* pItem = pItems->GetChild(nIndex, XFA_Element::Unknown, false); if (pItem) { wsText = pItem->JSNode()->GetContent(false); return true; } } return false; } std::vector CXFA_WidgetData::GetChoiceListItems(bool bSaveValue) { std::vector items; for (CXFA_Node* pNode = m_pNode->GetNodeItem(XFA_NODEITEM_FirstChild); pNode && items.size() < 2; pNode = pNode->GetNodeItem(XFA_NODEITEM_NextSibling)) { if (pNode->GetElementType() == XFA_Element::Items) items.push_back(pNode); } if (items.empty()) return std::vector(); CXFA_Node* pItem = items.front(); if (items.size() > 1) { bool bItemOneHasSave = items[0]->JSNode()->GetBoolean(XFA_Attribute::Save); bool bItemTwoHasSave = items[1]->JSNode()->GetBoolean(XFA_Attribute::Save); if (bItemOneHasSave != bItemTwoHasSave && bSaveValue == bItemTwoHasSave) pItem = items[1]; } std::vector wsTextArray; for (CXFA_Node* pNode = pItem->GetNodeItem(XFA_NODEITEM_FirstChild); pNode; pNode = pNode->GetNodeItem(XFA_NODEITEM_NextSibling)) { wsTextArray.emplace_back(pNode->JSNode()->GetContent(false)); } return wsTextArray; } int32_t CXFA_WidgetData::CountSelectedItems() { std::vector wsValueArray = GetSelectedItemsValue(); if (IsListBox() || !IsChoiceListAllowTextEntry()) return pdfium::CollectionSize(wsValueArray); int32_t iSelected = 0; std::vector wsSaveTextArray = GetChoiceListItems(true); for (const auto& value : wsValueArray) { if (pdfium::ContainsValue(wsSaveTextArray, value)) iSelected++; } return iSelected; } int32_t CXFA_WidgetData::GetSelectedItem(int32_t nIndex) { std::vector wsValueArray = GetSelectedItemsValue(); if (!pdfium::IndexInBounds(wsValueArray, nIndex)) return -1; std::vector wsSaveTextArray = GetChoiceListItems(true); auto it = std::find(wsSaveTextArray.begin(), wsSaveTextArray.end(), wsValueArray[nIndex]); return it != wsSaveTextArray.end() ? it - wsSaveTextArray.begin() : -1; } std::vector CXFA_WidgetData::GetSelectedItems() { std::vector iSelArray; std::vector wsValueArray = GetSelectedItemsValue(); std::vector wsSaveTextArray = GetChoiceListItems(true); for (const auto& value : wsValueArray) { auto it = std::find(wsSaveTextArray.begin(), wsSaveTextArray.end(), value); if (it != wsSaveTextArray.end()) iSelArray.push_back(it - wsSaveTextArray.begin()); } return iSelArray; } std::vector CXFA_WidgetData::GetSelectedItemsValue() { std::vector wsSelTextArray; WideString wsValue = GetRawValue(); if (GetChoiceListOpen() == XFA_ATTRIBUTEENUM_MultiSelect) { if (!wsValue.IsEmpty()) { size_t iStart = 0; size_t iLength = wsValue.GetLength(); auto iEnd = wsValue.Find(L'\\n', iStart); iEnd = (!iEnd.has_value()) ? iLength : iEnd; while (iEnd >= iStart) { wsSelTextArray.push_back(wsValue.Mid(iStart, iEnd.value() - iStart)); iStart = iEnd.value() + 1; if (iStart >= iLength) break; iEnd = wsValue.Find(L'\\n', iStart); if (!iEnd.has_value()) wsSelTextArray.push_back(wsValue.Mid(iStart, iLength - iStart)); } } } else { wsSelTextArray.push_back(wsValue); } return wsSelTextArray; } bool CXFA_WidgetData::GetItemState(int32_t nIndex) { std::vector wsSaveTextArray = GetChoiceListItems(true); return pdfium::IndexInBounds(wsSaveTextArray, nIndex) && pdfium::ContainsValue(GetSelectedItemsValue(), wsSaveTextArray[nIndex]); } void CXFA_WidgetData::SetItemState(int32_t nIndex, bool bSelected, bool bNotify, bool bScriptModify, bool bSyncData) { std::vector wsSaveTextArray = GetChoiceListItems(true); if (!pdfium::IndexInBounds(wsSaveTextArray, nIndex)) return; int32_t iSel = -1; std::vector wsValueArray = GetSelectedItemsValue(); auto it = std::find(wsValueArray.begin(), wsValueArray.end(), wsSaveTextArray[nIndex]); if (it != wsValueArray.end()) iSel = it - wsValueArray.begin(); if (GetChoiceListOpen() == XFA_ATTRIBUTEENUM_MultiSelect) { if (bSelected) { if (iSel < 0) { WideString wsValue = GetRawValue(); if (!wsValue.IsEmpty()) { wsValue += L""\\n""; } wsValue += wsSaveTextArray[nIndex]; m_pNode->JSNode()->SetContent(wsValue, wsValue, bNotify, bScriptModify, bSyncData); } } else if (iSel >= 0) { std::vector iSelArray = GetSelectedItems(); auto it = std::find(iSelArray.begin(), iSelArray.end(), nIndex); if (it != iSelArray.end()) iSelArray.erase(it); SetSelectedItems(iSelArray, bNotify, bScriptModify, bSyncData); } } else { if (bSelected) { if (iSel < 0) { WideString wsSaveText = wsSaveTextArray[nIndex]; WideString wsFormatText(wsSaveText); GetFormatDataValue(wsSaveText, wsFormatText); m_pNode->JSNode()->SetContent(wsSaveText, wsFormatText, bNotify, bScriptModify, bSyncData); } } else if (iSel >= 0) { m_pNode->JSNode()->SetContent(WideString(), WideString(), bNotify, bScriptModify, bSyncData); } } } void CXFA_WidgetData::SetSelectedItems(const std::vector& iSelArray, bool bNotify, bool bScriptModify, bool bSyncData) { WideString wsValue; int32_t iSize = pdfium::CollectionSize(iSelArray); if (iSize >= 1) { std::vector wsSaveTextArray = GetChoiceListItems(true); WideString wsItemValue; for (int32_t i = 0; i < iSize; i++) { wsItemValue = (iSize == 1) ? wsSaveTextArray[iSelArray[i]] : wsSaveTextArray[iSelArray[i]] + L""\\n""; wsValue += wsItemValue; } } WideString wsFormat(wsValue); if (GetChoiceListOpen() != XFA_ATTRIBUTEENUM_MultiSelect) GetFormatDataValue(wsValue, wsFormat); m_pNode->JSNode()->SetContent(wsValue, wsFormat, bNotify, bScriptModify, bSyncData); } void CXFA_WidgetData::ClearAllSelections() { CXFA_Node* pBind = m_pNode->GetBindData(); if (!pBind || GetChoiceListOpen() != XFA_ATTRIBUTEENUM_MultiSelect) { SyncValue(WideString(), false); return; } while (CXFA_Node* pChildNode = pBind->GetNodeItem(XFA_NODEITEM_FirstChild)) pBind->RemoveChild(pChildNode, true); } void CXFA_WidgetData::InsertItem(const WideString& wsLabel, const WideString& wsValue, bool bNotify) { int32_t nIndex = -1; WideString wsNewValue(wsValue); if (wsNewValue.IsEmpty()) wsNewValue = wsLabel; std::vector listitems; for (CXFA_Node* pItem = m_pNode->GetNodeItem(XFA_NODEITEM_FirstChild); pItem; pItem = pItem->GetNodeItem(XFA_NODEITEM_NextSibling)) { if (pItem->GetElementType() == XFA_Element::Items) listitems.push_back(pItem); } if (listitems.empty()) { CXFA_Node* pItems = m_pNode->CreateSamePacketNode(XFA_Element::Items); m_pNode->InsertChild(-1, pItems); InsertListTextItem(pItems, wsLabel, nIndex); CXFA_Node* pSaveItems = m_pNode->CreateSamePacketNode(XFA_Element::Items); m_pNode->InsertChild(-1, pSaveItems); pSaveItems->JSNode()->SetBoolean(XFA_Attribute::Save, true, false); InsertListTextItem(pSaveItems, wsNewValue, nIndex); } else if (listitems.size() > 1) { for (int32_t i = 0; i < 2; i++) { CXFA_Node* pNode = listitems[i]; bool bHasSave = pNode->JSNode()->GetBoolean(XFA_Attribute::Save); if (bHasSave) InsertListTextItem(pNode, wsNewValue, nIndex); else InsertListTextItem(pNode, wsLabel, nIndex); } } else { CXFA_Node* pNode = listitems[0]; pNode->JSNode()->SetBoolean(XFA_Attribute::Save, false, false); pNode->JSNode()->SetEnum(XFA_Attribute::Presence, XFA_ATTRIBUTEENUM_Visible, false); CXFA_Node* pSaveItems = m_pNode->CreateSamePacketNode(XFA_Element::Items); m_pNode->InsertChild(-1, pSaveItems); pSaveItems->JSNode()->SetBoolean(XFA_Attribute::Save, true, false); pSaveItems->JSNode()->SetEnum(XFA_Attribute::Presence, XFA_ATTRIBUTEENUM_Hidden, false); CXFA_Node* pListNode = pNode->GetNodeItem(XFA_NODEITEM_FirstChild); int32_t i = 0; while (pListNode) { InsertListTextItem(pSaveItems, pListNode->JSNode()->GetContent(false), i); ++i; pListNode = pListNode->GetNodeItem(XFA_NODEITEM_NextSibling); } InsertListTextItem(pNode, wsLabel, nIndex); InsertListTextItem(pSaveItems, wsNewValue, nIndex); } if (!bNotify) return; m_pNode->GetDocument()->GetNotify()->OnWidgetListItemAdded( this, wsLabel.c_str(), wsValue.c_str(), nIndex); } void CXFA_WidgetData::GetItemLabel(const WideStringView& wsValue, WideString& wsLabel) { int32_t iCount = 0; std::vector listitems; CXFA_Node* pItems = m_pNode->GetNodeItem(XFA_NODEITEM_FirstChild); for (; pItems; pItems = pItems->GetNodeItem(XFA_NODEITEM_NextSibling)) { if (pItems->GetElementType() != XFA_Element::Items) continue; iCount++; listitems.push_back(pItems); } if (iCount <= 1) { wsLabel = wsValue; return; } CXFA_Node* pLabelItems = listitems[0]; bool bSave = pLabelItems->JSNode()->GetBoolean(XFA_Attribute::Save); CXFA_Node* pSaveItems = nullptr; if (bSave) { pSaveItems = pLabelItems; pLabelItems = listitems[1]; } else { pSaveItems = listitems[1]; } iCount = 0; int32_t iSearch = -1; for (CXFA_Node* pChildItem = pSaveItems->GetNodeItem(XFA_NODEITEM_FirstChild); pChildItem; pChildItem = pChildItem->GetNodeItem(XFA_NODEITEM_NextSibling)) { if (pChildItem->JSNode()->GetContent(false) == wsValue) { iSearch = iCount; break; } iCount++; } if (iSearch < 0) return; CXFA_Node* pText = pLabelItems->GetChild(iSearch, XFA_Element::Unknown, false); if (pText) wsLabel = pText->JSNode()->GetContent(false); } void CXFA_WidgetData::GetItemValue(const WideStringView& wsLabel, WideString& wsValue) { int32_t iCount = 0; std::vector listitems; for (CXFA_Node* pItems = m_pNode->GetNodeItem(XFA_NODEITEM_FirstChild); pItems; pItems = pItems->GetNodeItem(XFA_NODEITEM_NextSibling)) { if (pItems->GetElementType() != XFA_Element::Items) continue; iCount++; listitems.push_back(pItems); } if (iCount <= 1) { wsValue = wsLabel; return; } CXFA_Node* pLabelItems = listitems[0]; bool bSave = pLabelItems->JSNode()->GetBoolean(XFA_Attribute::Save); CXFA_Node* pSaveItems = nullptr; if (bSave) { pSaveItems = pLabelItems; pLabelItems = listitems[1]; } else { pSaveItems = listitems[1]; } iCount = 0; int32_t iSearch = -1; WideString wsContent; CXFA_Node* pChildItem = pLabelItems->GetNodeItem(XFA_NODEITEM_FirstChild); for (; pChildItem; pChildItem = pChildItem->GetNodeItem(XFA_NODEITEM_NextSibling)) { if (pChildItem->JSNode()->GetContent(false) == wsLabel) { iSearch = iCount; break; } iCount++; } if (iSearch < 0) return; CXFA_Node* pText = pSaveItems->GetChild(iSearch, XFA_Element::Unknown, false); if (pText) wsValue = pText->JSNode()->GetContent(false); } bool CXFA_WidgetData::DeleteItem(int32_t nIndex, bool bNotify, bool bScriptModify) { bool bSetValue = false; CXFA_Node* pItems = m_pNode->GetNodeItem(XFA_NODEITEM_FirstChild); for (; pItems; pItems = pItems->GetNodeItem(XFA_NODEITEM_NextSibling)) { if (pItems->GetElementType() != XFA_Element::Items) continue; if (nIndex < 0) { while (CXFA_Node* pNode = pItems->GetNodeItem(XFA_NODEITEM_FirstChild)) { pItems->RemoveChild(pNode, true); } } else { if (!bSetValue && pItems->JSNode()->GetBoolean(XFA_Attribute::Save)) { SetItemState(nIndex, false, true, bScriptModify, true); bSetValue = true; } int32_t i = 0; CXFA_Node* pNode = pItems->GetNodeItem(XFA_NODEITEM_FirstChild); while (pNode) { if (i == nIndex) { pItems->RemoveChild(pNode, true); break; } i++; pNode = pNode->GetNodeItem(XFA_NODEITEM_NextSibling); } } } if (bNotify) m_pNode->GetDocument()->GetNotify()->OnWidgetListItemRemoved(this, nIndex); return true; } int32_t CXFA_WidgetData::GetHorizontalScrollPolicy() { CXFA_Node* pUIChild = GetUIChild(); if (pUIChild) return pUIChild->JSNode()->GetEnum(XFA_Attribute::HScrollPolicy); return XFA_ATTRIBUTEENUM_Auto; } int32_t CXFA_WidgetData::GetNumberOfCells() { CXFA_Node* pUIChild = GetUIChild(); if (!pUIChild) return -1; if (CXFA_Node* pNode = pUIChild->GetChild(0, XFA_Element::Comb, false)) return pNode->JSNode()->GetInteger(XFA_Attribute::NumberOfCells); return -1; } WideString CXFA_WidgetData::GetBarcodeType() { CXFA_Node* pUIChild = GetUIChild(); return pUIChild ? WideString(pUIChild->JSNode()->GetCData(XFA_Attribute::Type)) : WideString(); } bool CXFA_WidgetData::GetBarcodeAttribute_CharEncoding(int32_t* val) { pdfium::Optional wsCharEncoding = GetUIChild()->JSNode()->TryCData(XFA_Attribute::CharEncoding, true); if (!wsCharEncoding) return false; if (wsCharEncoding->CompareNoCase(L""UTF-16"")) { *val = CHAR_ENCODING_UNICODE; return true; } if (wsCharEncoding->CompareNoCase(L""UTF-8"")) { *val = CHAR_ENCODING_UTF8; return true; } return false; } bool CXFA_WidgetData::GetBarcodeAttribute_Checksum(bool* val) { pdfium::Optional checksum = GetUIChild()->JSNode()->TryEnum(XFA_Attribute::Checksum, true); if (!checksum) return false; switch (*checksum) { case XFA_ATTRIBUTEENUM_None: *val = false; return true; case XFA_ATTRIBUTEENUM_Auto: *val = true; return true; case XFA_ATTRIBUTEENUM_1mod10: case XFA_ATTRIBUTEENUM_1mod10_1mod11: case XFA_ATTRIBUTEENUM_2mod10: default: break; } return false; } bool CXFA_WidgetData::GetBarcodeAttribute_DataLength(int32_t* val) { pdfium::Optional wsDataLength = GetUIChild()->JSNode()->TryCData(XFA_Attribute::DataLength, true); if (!wsDataLength) return false; *val = FXSYS_wtoi(wsDataLength->c_str()); return true; } bool CXFA_WidgetData::GetBarcodeAttribute_StartChar(char* val) { pdfium::Optional wsStartEndChar = GetUIChild()->JSNode()->TryCData(XFA_Attribute::StartChar, true); if (!wsStartEndChar || wsStartEndChar->IsEmpty()) return false; *val = static_cast((*wsStartEndChar)[0]); return true; } bool CXFA_WidgetData::GetBarcodeAttribute_EndChar(char* val) { pdfium::Optional wsStartEndChar = GetUIChild()->JSNode()->TryCData(XFA_Attribute::EndChar, true); if (!wsStartEndChar || wsStartEndChar->IsEmpty()) return false; *val = static_cast((*wsStartEndChar)[0]); return true; } bool CXFA_WidgetData::GetBarcodeAttribute_ECLevel(int32_t* val) { pdfium::Optional wsECLevel = GetUIChild()->JSNode()->TryCData( XFA_Attribute::ErrorCorrectionLevel, true); if (!wsECLevel) return false; *val = FXSYS_wtoi(wsECLevel->c_str()); return true; } bool CXFA_WidgetData::GetBarcodeAttribute_ModuleWidth(int32_t* val) { pdfium::Optional moduleWidthHeight = GetUIChild()->JSNode()->TryMeasure(XFA_Attribute::ModuleWidth, true); if (!moduleWidthHeight) return false; *val = static_cast(moduleWidthHeight->ToUnit(XFA_Unit::Pt)); return true; } bool CXFA_WidgetData::GetBarcodeAttribute_ModuleHeight(int32_t* val) { pdfium::Optional moduleWidthHeight = GetUIChild()->JSNode()->TryMeasure(XFA_Attribute::ModuleHeight, true); if (!moduleWidthHeight) return false; *val = static_cast(moduleWidthHeight->ToUnit(XFA_Unit::Pt)); return true; } bool CXFA_WidgetData::GetBarcodeAttribute_PrintChecksum(bool* val) { pdfium::Optional printCheckDigit = GetUIChild()->JSNode()->TryBoolean(XFA_Attribute::PrintCheckDigit, true); if (printCheckDigit) { *val = *printCheckDigit; return true; } return false; } bool CXFA_WidgetData::GetBarcodeAttribute_TextLocation(int32_t* val) { pdfium::Optional textLocation = GetUIChild()->JSNode()->TryEnum(XFA_Attribute::TextLocation, true); if (!textLocation) return false; switch (*textLocation) { case XFA_ATTRIBUTEENUM_None: *val = BC_TEXT_LOC_NONE; return true; case XFA_ATTRIBUTEENUM_Above: *val = BC_TEXT_LOC_ABOVE; return true; case XFA_ATTRIBUTEENUM_Below: *val = BC_TEXT_LOC_BELOW; return true; case XFA_ATTRIBUTEENUM_AboveEmbedded: *val = BC_TEXT_LOC_ABOVEEMBED; return true; case XFA_ATTRIBUTEENUM_BelowEmbedded: *val = BC_TEXT_LOC_BELOWEMBED; return true; default: break; } return false; } bool CXFA_WidgetData::GetBarcodeAttribute_Truncate(bool* val) { pdfium::Optional truncate = GetUIChild()->JSNode()->TryBoolean(XFA_Attribute::Truncate, true); if (!truncate) return false; *val = *truncate; return true; } bool CXFA_WidgetData::GetBarcodeAttribute_WideNarrowRatio(float* val) { pdfium::Optional wsWideNarrowRatio = GetUIChild()->JSNode()->TryCData(XFA_Attribute::WideNarrowRatio, true); if (!wsWideNarrowRatio) return false; pdfium::Optional ptPos = wsWideNarrowRatio->Find(':'); if (!ptPos) { *val = static_cast(FXSYS_wtoi(wsWideNarrowRatio->c_str())); return true; } *val = 0.0f; int32_t fB = FXSYS_wtoi( wsWideNarrowRatio->Right(wsWideNarrowRatio->GetLength() - (*ptPos + 1)) .c_str()); if (!fB) return true; int32_t fA = FXSYS_wtoi(wsWideNarrowRatio->Left(*ptPos).c_str()); *val = static_cast(fA) / static_cast(fB); return true; } void CXFA_WidgetData::GetPasswordChar(WideString& wsPassWord) { CXFA_Node* pUIChild = GetUIChild(); if (!pUIChild) { wsPassWord = L""*""; return; } wsPassWord = pUIChild->JSNode()->GetCData(XFA_Attribute::PasswordChar); } bool CXFA_WidgetData::IsMultiLine() { CXFA_Node* pUIChild = GetUIChild(); return pUIChild && pUIChild->JSNode()->GetBoolean(XFA_Attribute::MultiLine); } XFA_ATTRIBUTEENUM CXFA_WidgetData::GetVerticalScrollPolicy() { CXFA_Node* pUIChild = GetUIChild(); if (pUIChild) return pUIChild->JSNode()->GetEnum(XFA_Attribute::VScrollPolicy); return XFA_ATTRIBUTEENUM_Auto; } int32_t CXFA_WidgetData::GetMaxChars(XFA_Element& eType) { if (CXFA_Node* pNode = m_pNode->GetChild(0, XFA_Element::Value, false)) { if (CXFA_Node* pChild = pNode->GetNodeItem(XFA_NODEITEM_FirstChild)) { switch (pChild->GetElementType()) { case XFA_Element::Text: eType = XFA_Element::Text; return pChild->JSNode()->GetInteger(XFA_Attribute::MaxChars); case XFA_Element::ExData: { eType = XFA_Element::ExData; int32_t iMax = pChild->JSNode()->GetInteger(XFA_Attribute::MaxLength); return iMax < 0 ? 0 : iMax; } default: break; } } } return 0; } bool CXFA_WidgetData::GetFracDigits(int32_t& iFracDigits) { iFracDigits = -1; CXFA_Node* pNode = m_pNode->GetChild(0, XFA_Element::Value, false); if (!pNode) return false; CXFA_Node* pChild = pNode->GetChild(0, XFA_Element::Decimal, false); if (!pChild) return false; pdfium::Optional ret = pChild->JSNode()->TryInteger(XFA_Attribute::FracDigits, true); if (!ret) return false; iFracDigits = *ret; return true; } bool CXFA_WidgetData::GetLeadDigits(int32_t& iLeadDigits) { iLeadDigits = -1; CXFA_Node* pNode = m_pNode->GetChild(0, XFA_Element::Value, false); if (!pNode) return false; CXFA_Node* pChild = pNode->GetChild(0, XFA_Element::Decimal, false); if (!pChild) return false; pdfium::Optional ret = pChild->JSNode()->TryInteger(XFA_Attribute::LeadDigits, true); if (!ret) return false; iLeadDigits = *ret; return true; } bool CXFA_WidgetData::SetValue(const WideString& wsValue, XFA_VALUEPICTURE eValueType) { if (wsValue.IsEmpty()) { SyncValue(wsValue, true); return true; } m_bPreNull = m_bIsNull; m_bIsNull = false; WideString wsNewText(wsValue); WideString wsPicture; GetPictureContent(wsPicture, eValueType); bool bValidate = true; bool bSyncData = false; CXFA_Node* pNode = GetUIChild(); if (!pNode) return true; XFA_Element eType = pNode->GetElementType(); if (!wsPicture.IsEmpty()) { CXFA_LocaleMgr* pLocalMgr = m_pNode->GetDocument()->GetLocalMgr(); IFX_Locale* pLocale = GetLocal(); CXFA_LocaleValue widgetValue = XFA_GetLocaleValue(this); bValidate = widgetValue.ValidateValue(wsValue, wsPicture, pLocale, &wsPicture); if (bValidate) { widgetValue = CXFA_LocaleValue(widgetValue.GetType(), wsNewText, wsPicture, pLocale, pLocalMgr); wsNewText = widgetValue.GetValue(); if (eType == XFA_Element::NumericEdit) { int32_t iLeadDigits = 0; int32_t iFracDigits = 0; GetLeadDigits(iLeadDigits); GetFracDigits(iFracDigits); wsNewText = NumericLimit(wsNewText, iLeadDigits, iFracDigits); } bSyncData = true; } } else { if (eType == XFA_Element::NumericEdit) { if (wsNewText != L""0"") { int32_t iLeadDigits = 0; int32_t iFracDigits = 0; GetLeadDigits(iLeadDigits); GetFracDigits(iFracDigits); wsNewText = NumericLimit(wsNewText, iLeadDigits, iFracDigits); } bSyncData = true; } } if (eType != XFA_Element::NumericEdit || bSyncData) SyncValue(wsNewText, true); return bValidate; } bool CXFA_WidgetData::GetPictureContent(WideString& wsPicture, XFA_VALUEPICTURE ePicture) { if (ePicture == XFA_VALUEPICTURE_Raw) return false; CXFA_LocaleValue widgetValue = XFA_GetLocaleValue(this); switch (ePicture) { case XFA_VALUEPICTURE_Display: { if (CXFA_Node* pFormat = m_pNode->GetChild(0, XFA_Element::Format, false)) { if (CXFA_Node* pPicture = pFormat->GetChild(0, XFA_Element::Picture, false)) { pdfium::Optional picture = pPicture->JSNode()->TryContent(false, true); if (picture) { wsPicture = *picture; return true; } } } IFX_Locale* pLocale = GetLocal(); if (!pLocale) return false; uint32_t dwType = widgetValue.GetType(); switch (dwType) { case XFA_VT_DATE: wsPicture = pLocale->GetDatePattern(FX_LOCALEDATETIMESUBCATEGORY_Medium); break; case XFA_VT_TIME: wsPicture = pLocale->GetTimePattern(FX_LOCALEDATETIMESUBCATEGORY_Medium); break; case XFA_VT_DATETIME: wsPicture = pLocale->GetDatePattern(FX_LOCALEDATETIMESUBCATEGORY_Medium) + L""T"" + pLocale->GetTimePattern(FX_LOCALEDATETIMESUBCATEGORY_Medium); break; case XFA_VT_DECIMAL: case XFA_VT_FLOAT: break; default: break; } return true; } case XFA_VALUEPICTURE_Edit: { CXFA_Node* pUI = m_pNode->GetChild(0, XFA_Element::Ui, false); if (pUI) { if (CXFA_Node* pPicture = pUI->GetChild(0, XFA_Element::Picture, false)) { pdfium::Optional picture = pPicture->JSNode()->TryContent(false, true); if (picture) { wsPicture = *picture; return true; } } } IFX_Locale* pLocale = GetLocal(); if (!pLocale) return false; uint32_t dwType = widgetValue.GetType(); switch (dwType) { case XFA_VT_DATE: wsPicture = pLocale->GetDatePattern(FX_LOCALEDATETIMESUBCATEGORY_Short); break; case XFA_VT_TIME: wsPicture = pLocale->GetTimePattern(FX_LOCALEDATETIMESUBCATEGORY_Short); break; case XFA_VT_DATETIME: wsPicture = pLocale->GetDatePattern(FX_LOCALEDATETIMESUBCATEGORY_Short) + L""T"" + pLocale->GetTimePattern(FX_LOCALEDATETIMESUBCATEGORY_Short); break; default: break; } return true; } case XFA_VALUEPICTURE_DataBind: { CXFA_BindData bindData = GetBindData(); if (bindData) { bindData.GetPicture(wsPicture); return true; } break; } default: break; } return false; } IFX_Locale* CXFA_WidgetData::GetLocal() { if (!m_pNode) return nullptr; WideString wsLocaleName; if (!m_pNode->GetLocaleName(wsLocaleName)) return nullptr; if (wsLocaleName == L""ambient"") return m_pNode->GetDocument()->GetLocalMgr()->GetDefLocale(); return m_pNode->GetDocument()->GetLocalMgr()->GetLocaleByName(wsLocaleName); } bool CXFA_WidgetData::GetValue(WideString& wsValue, XFA_VALUEPICTURE eValueType) { wsValue = m_pNode->JSNode()->GetContent(false); if (eValueType == XFA_VALUEPICTURE_Display) GetItemLabel(wsValue.AsStringView(), wsValue); WideString wsPicture; GetPictureContent(wsPicture, eValueType); CXFA_Node* pNode = GetUIChild(); if (!pNode) return true; switch (GetUIChild()->GetElementType()) { case XFA_Element::ChoiceList: { if (eValueType == XFA_VALUEPICTURE_Display) { int32_t iSelItemIndex = GetSelectedItem(0); if (iSelItemIndex >= 0) { GetChoiceListItem(wsValue, iSelItemIndex, false); wsPicture.clear(); } } } break; case XFA_Element::NumericEdit: if (eValueType != XFA_VALUEPICTURE_Raw && wsPicture.IsEmpty()) { IFX_Locale* pLocale = GetLocal(); if (eValueType == XFA_VALUEPICTURE_Display && pLocale) { WideString wsOutput; NormalizeNumStr(wsValue, wsOutput); FormatNumStr(wsOutput, pLocale, wsOutput); wsValue = wsOutput; } } break; default: break; } if (wsPicture.IsEmpty()) return true; if (IFX_Locale* pLocale = GetLocal()) { CXFA_LocaleValue widgetValue = XFA_GetLocaleValue(this); CXFA_LocaleMgr* pLocalMgr = m_pNode->GetDocument()->GetLocalMgr(); switch (widgetValue.GetType()) { case XFA_VT_DATE: { WideString wsDate, wsTime; if (SplitDateTime(wsValue, wsDate, wsTime)) { CXFA_LocaleValue date(XFA_VT_DATE, wsDate, pLocalMgr); if (date.FormatPatterns(wsValue, wsPicture, pLocale, eValueType)) return true; } break; } case XFA_VT_TIME: { WideString wsDate, wsTime; if (SplitDateTime(wsValue, wsDate, wsTime)) { CXFA_LocaleValue time(XFA_VT_TIME, wsTime, pLocalMgr); if (time.FormatPatterns(wsValue, wsPicture, pLocale, eValueType)) return true; } break; } default: break; } widgetValue.FormatPatterns(wsValue, wsPicture, pLocale, eValueType); } return true; } bool CXFA_WidgetData::GetNormalizeDataValue(const WideString& wsValue, WideString& wsNormalizeValue) { wsNormalizeValue = wsValue; if (wsValue.IsEmpty()) return true; WideString wsPicture; GetPictureContent(wsPicture, XFA_VALUEPICTURE_DataBind); if (wsPicture.IsEmpty()) return true; ASSERT(GetNode()); CXFA_LocaleMgr* pLocalMgr = GetNode()->GetDocument()->GetLocalMgr(); IFX_Locale* pLocale = GetLocal(); CXFA_LocaleValue widgetValue = XFA_GetLocaleValue(this); if (widgetValue.ValidateValue(wsValue, wsPicture, pLocale, &wsPicture)) { widgetValue = CXFA_LocaleValue(widgetValue.GetType(), wsNormalizeValue, wsPicture, pLocale, pLocalMgr); wsNormalizeValue = widgetValue.GetValue(); return true; } return false; } bool CXFA_WidgetData::GetFormatDataValue(const WideString& wsValue, WideString& wsFormattedValue) { wsFormattedValue = wsValue; if (wsValue.IsEmpty()) return true; WideString wsPicture; GetPictureContent(wsPicture, XFA_VALUEPICTURE_DataBind); if (wsPicture.IsEmpty()) return true; if (IFX_Locale* pLocale = GetLocal()) { ASSERT(GetNode()); CXFA_Node* pNodeValue = GetNode()->GetChild(0, XFA_Element::Value, false); if (!pNodeValue) return false; CXFA_Node* pValueChild = pNodeValue->GetNodeItem(XFA_NODEITEM_FirstChild); if (!pValueChild) return false; int32_t iVTType = XFA_VT_NULL; switch (pValueChild->GetElementType()) { case XFA_Element::Decimal: iVTType = XFA_VT_DECIMAL; break; case XFA_Element::Float: iVTType = XFA_VT_FLOAT; break; case XFA_Element::Date: iVTType = XFA_VT_DATE; break; case XFA_Element::Time: iVTType = XFA_VT_TIME; break; case XFA_Element::DateTime: iVTType = XFA_VT_DATETIME; break; case XFA_Element::Boolean: iVTType = XFA_VT_BOOLEAN; break; case XFA_Element::Integer: iVTType = XFA_VT_INTEGER; break; case XFA_Element::Text: iVTType = XFA_VT_TEXT; break; default: iVTType = XFA_VT_NULL; break; } CXFA_LocaleMgr* pLocalMgr = GetNode()->GetDocument()->GetLocalMgr(); CXFA_LocaleValue widgetValue(iVTType, wsValue, pLocalMgr); switch (widgetValue.GetType()) { case XFA_VT_DATE: { WideString wsDate, wsTime; if (SplitDateTime(wsValue, wsDate, wsTime)) { CXFA_LocaleValue date(XFA_VT_DATE, wsDate, pLocalMgr); if (date.FormatPatterns(wsFormattedValue, wsPicture, pLocale, XFA_VALUEPICTURE_DataBind)) { return true; } } break; } case XFA_VT_TIME: { WideString wsDate, wsTime; if (SplitDateTime(wsValue, wsDate, wsTime)) { CXFA_LocaleValue time(XFA_VT_TIME, wsTime, pLocalMgr); if (time.FormatPatterns(wsFormattedValue, wsPicture, pLocale, XFA_VALUEPICTURE_DataBind)) { return true; } } break; } default: break; } widgetValue.FormatPatterns(wsFormattedValue, wsPicture, pLocale, XFA_VALUEPICTURE_DataBind); } return false; } void CXFA_WidgetData::NormalizeNumStr(const WideString& wsValue, WideString& wsOutput) { if (wsValue.IsEmpty()) return; wsOutput = wsValue; wsOutput.TrimLeft('0'); int32_t iFracDigits = 0; if (!wsOutput.IsEmpty() && wsOutput.Contains('.') && (!GetFracDigits(iFracDigits) || iFracDigits != -1)) { wsOutput.TrimRight(L""0""); wsOutput.TrimRight(L"".""); } if (wsOutput.IsEmpty() || wsOutput[0] == '.') wsOutput.InsertAtFront('0'); } void CXFA_WidgetData::FormatNumStr(const WideString& wsValue, IFX_Locale* pLocale, WideString& wsOutput) { if (wsValue.IsEmpty()) return; WideString wsSrcNum = wsValue; WideString wsGroupSymbol = pLocale->GetNumbericSymbol(FX_LOCALENUMSYMBOL_Grouping); bool bNeg = false; if (wsSrcNum[0] == '-') { bNeg = true; wsSrcNum.Delete(0, 1); } auto dot_index = wsSrcNum.Find('.'); dot_index = !dot_index.has_value() ? wsSrcNum.GetLength() : dot_index; if (dot_index.value() >= 1) { size_t nPos = dot_index.value() % 3; wsOutput.clear(); for (size_t i = 0; i < dot_index.value(); i++) { if (i % 3 == nPos && i != 0) wsOutput += wsGroupSymbol; wsOutput += wsSrcNum[i]; } if (dot_index.value() < wsSrcNum.GetLength()) { wsOutput += pLocale->GetNumbericSymbol(FX_LOCALENUMSYMBOL_Decimal); wsOutput += wsSrcNum.Right(wsSrcNum.GetLength() - dot_index.value() - 1); } if (bNeg) { wsOutput = pLocale->GetNumbericSymbol(FX_LOCALENUMSYMBOL_Minus) + wsOutput; } } } void CXFA_WidgetData::SyncValue(const WideString& wsValue, bool bNotify) { if (!m_pNode) return; WideString wsFormatValue(wsValue); CXFA_WidgetData* pContainerWidgetData = m_pNode->GetContainerWidgetData(); if (pContainerWidgetData) pContainerWidgetData->GetFormatDataValue(wsValue, wsFormatValue); m_pNode->JSNode()->SetContent(wsValue, wsFormatValue, bNotify, false, true); } void CXFA_WidgetData::InsertListTextItem(CXFA_Node* pItems, const WideString& wsText, int32_t nIndex) { CXFA_Node* pText = pItems->CreateSamePacketNode(XFA_Element::Text); pItems->InsertChild(nIndex, pText); pText->JSNode()->SetContent(wsText, wsText, false, false, false); } WideString CXFA_WidgetData::NumericLimit(const WideString& wsValue, int32_t iLead, int32_t iTread) const { if ((iLead == -1) && (iTread == -1)) return wsValue; WideString wsRet; int32_t iLead_ = 0, iTread_ = -1; int32_t iCount = wsValue.GetLength(); if (iCount == 0) return wsValue; int32_t i = 0; if (wsValue[i] == L'-') { wsRet += L'-'; i++; } for (; i < iCount; i++) { wchar_t wc = wsValue[i]; if (FXSYS_isDecimalDigit(wc)) { if (iLead >= 0) { iLead_++; if (iLead_ > iLead) return L""0""; } else if (iTread_ >= 0) { iTread_++; if (iTread_ > iTread) { if (iTread != -1) { CFX_Decimal wsDeci = CFX_Decimal(wsValue.AsStringView()); wsDeci.SetScale(iTread); wsRet = wsDeci; } return wsRet; } } } else if (wc == L'.') { iTread_ = 0; iLead = -1; } wsRet += wc; } return wsRet; } ",16263,True,3283.8926708437593,median "= Forum Book - Developer Guide :site-section: DeveloperGuide :toc: :toc-title: :toc-placement: preamble :sectnums: :imagesDir: images :stylesDir: stylesheets :xrefstyle: full ifdef::env-github[] :tip-caption: :bulb: :note-caption: :information_source: :warning-caption: :warning: endif::[] :repoURL: https://github.com/CS2113-AY1819S1-T13-2/main/ By: `Team CS2113 T13-2`      Since: `Aug 2018`      Licence: `MIT` == Setting up === Prerequisites . *JDK `9`* or later + [WARNING] JDK `10` on Windows will fail to run tests in <> due to a https://github.com/javafxports/openjdk-jfx/issues/66[JavaFX bug]. Windows developers are highly recommended to use JDK `9`. . *IntelliJ* IDE + [NOTE] IntelliJ by default has Gradle and JavaFx plugins installed. + Do not disable them. If you have disabled them, go to `File` > `Settings` > `Plugins` to re-enable them. === Setting up the project in your computer . Fork this repo, and clone the fork to your computer . Open IntelliJ (if you are not in the welcome screen, click `File` > `Close Project` to close the existing project dialog first) . Set up the correct JDK version for Gradle .. Click `Configure` > `Project Defaults` > `Project Structure` .. Click `New...` and find the directory of the JDK . Click `Import Project` . Locate the `build.gradle` file and select it. Click `OK` . Click `Open as Project` . Click `OK` to accept the default settings . Open a console and run the command `gradlew processResources` (Mac/Linux: `./gradlew processResources`). It should finish with the `BUILD SUCCESSFUL` message. + This will generate all resources required by the application and tests. === Verifying the setup . Run the `MainApp` and try a few commands . <> to ensure they all pass. === Configurations to do before writing code ==== Configuring the coding style This project follows https://github.com/oss-generic/process/blob/master/docs/CodingStandards.adoc[oss-generic coding standards]. IntelliJ's default style is mostly compliant with ours but it uses a different import order from ours. To rectify, . Go to `File` > `Settings...` (Windows/Linux), or `IntelliJ IDEA` > `Preferences...` (macOS) . Select `Editor` > `Code Style` > `Java` . Click on the `Imports` tab to set the order * For `Class count to use import with '\\*'` and `Names count to use static import with '*'`: Set to `999` to prevent IntelliJ from contracting the import statements * For `Import Layout`: The order is `import static all other imports`, `import java.\\*`, `import javax.*`, `import org.\\*`, `import com.*`, `import all other imports`. Add a `` between each `import` Optionally, you can follow the <> document to configure Intellij to check style-compliance as you write code. ==== Updating documentation to match your fork After forking the repo, the documentation will still have the SE-EDU branding and refer to the `se-edu/addressbook-level4` repo. If you plan to develop this fork as a separate product (i.e. instead of contributing to `se-edu/addressbook-level4`), you should do the following: . Configure the <> in link:{repoURL}/build.gradle[`build.gradle`], such as the `site-name`, to suit your own project. . Replace the URL in the attribute `repoURL` in link:{repoURL}/docs/DeveloperGuide.adoc[`DeveloperGuide.adoc`] and link:{repoURL}/docs/UserGuide.adoc[`UserGuide.adoc`] with the URL of your fork. ==== Setting up CI Set up Travis to perform Continuous Integration (CI) for your fork. See <> to learn how to set it up. After setting up Travis, you can optionally set up coverage reporting for your team fork (see <>). [NOTE] Coverage reporting could be useful for a team repository that hosts the final version but it is not that useful for your personal fork. Optionally, you can set up AppVeyor as a second CI (see <>). [NOTE] Having both Travis and AppVeyor ensures your App works on both Unix-based platforms and Windows-based platforms (Travis is Unix-based and AppVeyor is Windows-based) ==== Getting started with coding When you are ready to start coding, 1. Get some sense of the overall design by reading <>. 2. Take a look at <>. == Design [[Design-Architecture]] === Architecture .Architecture Diagram image::Architecture.png[width=""600""] The *_Architecture Diagram_* given above explains the high-level design of the App. Given below is a quick overview of each component. [TIP] The `.pptx` files used to create diagrams in this document can be found in the link:{repoURL}/docs/diagrams/[diagrams] folder. To update a diagram, modify the diagram in the pptx file, select the objects of the diagram, and choose `Save as picture`. `Main` has only one class called link:{repoURL}/src/main/java/t13g2/forum/MainApp.java[`MainApp`]. It is responsible for, * At app launch: Initializes the components in the correct sequence, and connects them up with each other. * At shut down: Shuts down the components and invokes cleanup method where necessary. <> represents a collection of classes used by multiple other components. Two of those classes play important roles at the architecture level. * `EventsCenter` : This class (written using https://github.com/google/guava/wiki/EventBusExplained[Google's Event Bus library]) is used by components to communicate with other components using events (i.e. a form of _Event Driven_ design) * `LogsCenter` : Used by many classes to write log messages to the App's log file. The rest of the App consists of four components. * <>: The UI of the App. * <>: The command executor. * <>: Holds the data of the App in-memory. * <>: Reads data from, and writes data to, the hard disk. Each of the four components * Defines its _API_ in an `interface` with the same name as the Component. * Exposes its functionality using a `{Component Name}Manager` class. For example, the `Logic` component (see the class diagram given below) defines it's API in the `Logic.java` interface and exposes its functionality using the `LogicManager.java` class. .Class Diagram of the Logic Component image::LogicClassDiagram.png[width=""800""] [discrete] ==== Events-Driven nature of the design The _Sequence Diagram_ below shows how the components interact for the scenario where the user issues the command `deleteModule mCode/CS2113`. .Component interactions for `deleteModule mCode/CS2113` command (part 1) image::SDDeleteModule.png[width=""800""] [NOTE] Note how the `Model` simply raises a `ForumBookChangedEvent` when the Forum Book data are changed, instead of asking the `Storage` to save the updates to the hard disk. The diagram below shows how the `EventsCenter` reacts to that event, which eventually results in the updates being saved to the hard disk and the status bar of the UI being updated to reflect the 'Last Updated' time. .Component interactions for `delete m/CS2113 i/1` command (part 2) image::SDforDeletePersonEventHandling.png[width=""800""] [NOTE] Note how the event is propagated through the `EventsCenter` to the `Storage` and `UI` without `Model` having to be coupled to either of them. This is an example of how this Event Driven approach helps us reduce direct coupling between components. The sections below give more details of each component. [[Design-Ui]] === UI component .Structure of the UI Component image::UiClassDiagram.png[width=""800""] *API* : link:{repoURL}/src/main/java/t13g2/forum/ui/Ui.java[`Ui.java`] The UI consists of a `MainWindow` that is made up of parts e.g.`CommandBox`, `ResultDisplay` etc. All these, including the `MainWindow`, inherit from the abstract `UiPart` class. The `UI` component uses JavaFx UI framework. The layout of these UI parts are defined in matching `.fxml` files that are in the `src/main/resources/view` folder. For example, the layout of the link:{repoURL}/src/main/java/t13g2/forum/ui/MainWindow.java[`MainWindow`] is specified in link:{repoURL}/src/main/resources/view/MainWindow.fxml[`MainWindow.fxml`] The `UI` component, * Executes user commands using the `Logic` component. * Binds itself to some data in the `Model` so that the UI can auto-update when data in the `Model` change. * Responds to events raised from various parts of the App and updates the UI accordingly. [[Design-Logic]] === Logic component [[fig-LogicClassDiagram]] .Structure of the Logic Component image::LogicClassDiagram.png[width=""800""] *API* : link:{repoURL}/src/main/java/t13g2/forum/logic/Logic.java[`Logic.java`] . `Logic` uses the `ForumBookParser` class to parse the user command. . This results in a `Command` object which is executed by the `LogicManager`. . The command execution can affect the `Model` (e.g. adding a person) and/or raise events. . The result of the command execution is encapsulated as a `CommandResult` object which is passed back to the `Ui`. Given below is the Sequence Diagram for interactions within the `Logic` component for the `execute(""deleteModule mCode/CS2113"")` API call. .Interactions Inside the Logic Component for the `deleteModule mCode/CS2113` Command image::DeleteModuleSdForLogic.png[width=""800""] [[Design-Storage]] // tag::storage_component[] === Storage component The `Storage` component, * can save `UserPref` objects in json format and read it back. * can save the Forum Book data in encrypted json format and read it back. // end::storage_component[] [[Design-Commons]] === Common classes Classes used by multiple components are in the `t13g2.forum.commons` package. == Implementation This section describes some noteworthy details on how certain features are implemented. // tag::curd[] === CURD feature ==== Current Implementation CURD refers to `create`, `update`, `read` and `delete`. This feature is implemented to achieve the basic functionalities of the Forum Book. It extends `ForumBook` with various commands and supports the following operations: * `createThread`: Create a new thread under a specific module that exists with comment. * `createComment`: Create a new comment under a specific thread that exists. * `updateThread`: Update an existing thread title created(unblocked) by its user. * `updateComment`: Update an existing comment content created(unblocked) by its user. * `listModule`: List out all the modules in the Forum Book. * `selectModule`: Select a specific module and list out all the threads under the module. * `selectThread`: Select a specific thread and list out all the comments under the thread. * `deleteThread`: Delete a specific thread. * `deleteComment`: Delete a specific comment. Given below is an example usage scenario and how the CURD can be operated by user at each step. Step 1. The user launches the application, executes `createThread mCode/CS2113 tTitle/Exam Information cContent/What is the topic coverage for the final?` to create and add the thread into storage file. The createThread command calls `UnitOfWork.commit()`, saving the modified forum book state into ForumBookStorage. Step 2. The user executes `createComment tId/123 cContent/This is a new comment content` to create and add the comment into storage file. The createComment command calls `UnitOfWork.commit()`, saving the modified forum book state into ForumBookStorage. Step 3. The user executes `updateThread tId/123 tTitle/This is a new thread title` to update the title of the specific thread from storage file. The updateThread command calls `UnitOfWork.getForumThreadRepository().getThread(threadId)`,`forumThread.setTitle()` and lastly `UnitOfWork.commit()`, saving the modified forum book state into ForumBookStorage. Step 4. The user executes `updateComment cId/123 cContent/This is a new comment content` to update the content of the specific comment from storage file. The updateComment command calls `UnitOfWork.getCommentRepository().getComment(commentId)`,`comment.setContent()` and lastly `UnitOfWork.commit()`, saving the modified forum book state into ForumBookStorage. Step 5. The user executes `listModule` to retrieve all the existing modules from storage file. The `listModule` command calls `UnitOfWork.getModuleRepository().getAllModule()` which returns the module list to be shown in the panel. Step 6. The user executes `selectModule mCode/CS2113` to retrieve the module with module code CS2113 and its thread list from storage file. The `selectModule` command calls `UnitOfWork.getModuleRepository().getModuleByCode(moduleCode)` and `UnitOfWork.getForumThreadRepository().getThreadsByModule(module)` to return the module and thread list to be shown in the panel. Step 7. The user executes `selectThread tId/123` to retrieve the thread with ID 123 and its comments from storage file. The `selectModule` command calls `UnitOfWork.getForumThreadRepository().getThread(threadId)` and `UnitOfWork.getCommentRepository().getCommentsByThread(threadId)` to return the thread and comment list to be shown in the panel. Step 8. The user executes `deleteThread tId/123` to delete/remove the thread with ID 123 from storage file. The deleteThread command calls `UnitOfWork.getForumThreadRepository().deleteThread(threadId)` and `UnitOfWork.commit()` to save the modified forum book state. Step 9. The user executes `deleteComment cId/123` to delete/remove the comment with ID 123 from storage file. The deleteComment command calls `UnitOfWork.getCommentRepository().deleteComment(commentId)` and `UnitOfWork.commit()` to save the modified forum book state. [NOTE] If the syntax of a command is wrong, the program will prompt the user to try again and show a suggested command format. // end::curd[] // tag::storage[] === Storage ==== Design Consideration As the basis of the whole program, storage should be robust, efficient and stable at all the time. Data consistency and multi-thread access should be specially taken care of. ==== Overview ForumBook's storage consists of six(6) parts. * User ** Stores user information like username, password, email etc. * Announcement ** Stores announcement set by admin, multiple announcements can be saved in the storage. * Module ** Stores module information like module name, code etc. * ForumThread ** Stores threads posted by users * Comment ** Stores comments under threads * RunningId ** Used for generating auto incremented ID, each the above entity has a unique ID These components are stored separately in six files for performance, see below for detailed process of loading and saving. ==== Storage Structure To avoid unnecessary disk IO, each part of the storage is saved in a file located in `forumData` directory. All data manipulation must be done within an `IUnitOfWork` where developer has to commit if the data should be persistent on disk, or rollback if the exception is thrown somewhere during the transaction. `IStorage` defines interface to access file systems, this handles how our program actually get/read data. By default, we have `JsonFileStorage` which stores and reads data from local hard disk. More storage options can be achieved by implementing this interface. eg: `FtpStorage`. `IEncryptor` defines interface to encrypt application data, it should be injected to `IStorage` providing a encryption/ decryption layer just before data writes and just after data reads. By default, `JsonFileStorage` uses `SimpleEncryptor` which is a simple 'OR' encryptor. A more secure encryption algorithm can be achieved by implementing `IEncryptor` interface. `IForumBookStorage` defines interface to access data entities `I*Repository` defines interface to how we can manipulate different entities. Each entity is managed by a repository, eg: `IUserRepository` `*Storage` is a thin wrapper for the `List` containing data objects, it keeps track of whether the underling list has been modified so that it can save some unnecessary disk IO if nothing changed when a `commit()` is issued. Data are saved in encrypted Json format, the encryption algorithm is provided by `IEncryptor` `RunningId` does not work as the other entities do, it has its own logic to make sure IDs are not repeated. // end::storage[] // tag::UserManagement1[] === User management ==== Current Implementation The user management is facilitated by various commands. It extends `ForumBook` with a user management tool. Additionally, it implements the following operations: * `AddUserCommand` -- Add user to forum book. * `LoginCommand`: login to forum book. * `LogoutCommand`: logout from the forum book. * `UserDeleteCommand`: Self delete a user from the forum book. Given below is an example usage scenario and how the user management behaves at each step. ----------------------------------------------------------------------------------------------------------------------------------------------------- + Given below is an example usage scenario and how the user management can be operated by user at each step. Step 1. The user executes `addUser uName/UserName uPass/password` to add a new user into forum userStorage file. The addUser command calls 'unitOfWork.getUserRepository().getUserByUsername(userToAdd.getUsername())' to check if the name entered by the user is available. If there is not duplicate, User can be registered. If the registration is successful, addUser command calls `UnitOfWork.commit()` to save the modified forum book state into UserStorage. Step 2. The user executes `login uName/UserName uPass/password` to login to the forum. The login command calls 'unitOfWork.getUserRepository().authenticate(userName, userPassword)' to check if the login can be authorise. If success, login command calls `Context.getInstance().setCurrentUser(exist)` to create an instance for the authorised user. Step 3. The user executes `logout` to exit the forum or to switch user, logout command calls 'EventsCenter.getInstance().post(new UserLoginEvent("""", false, false))' to close the instance created by the user. Next/ another user is able to login after a successful logout. ToDo: Step 4. The user executes `UserDeleteComment ` to remove himself/herself from the forum book. User data will be removed from the storage. ----------------------------------------------------------------------------------------------------------------------------------------------------- + // end::UserManagement1[] // tag::adminManagement[] === Admin management ==== Current Implementation The admin management is facilitated by various commands. It extends `ForumBook` with a admin management tool. Additionally, it implements the following operations: * `AnnounceCommand` -- Posts new announcement. * `CheckAnnouncementCommand`: Checks for latest announcement. * `BlockUserFromCreatingCommand`: Blocks an existing user from posting either new threads or comments. * `SetAdminCommand`: Sets an existing user as admin or reverts an existing admin to user. * `CreateModuleCommand`: Creates a module by admin. * `UpdateModuleCommand`: Updates an existing module by admin. * `DeleteModuleCommand`: Deletes an existing module by admin. * `AdminUpdatePasswordCommand`: Updates an existing user's password by admin. * `DeleteUserCommand`: Deletes an existing user by admin. Given below is an example usage scenario and how the admin management behaves at each step. Step 1. The admin launches the application, executes `announce aTitle/Urgent! aContent/System maintenance from 3PM to 6PM.` to add the announcement to storage file. The `announce` command calls `UnitOfWork.getAnnouncementRepository.addAnnouncement(announcement)` and then `UnitOfWork.commit()`, causing a modified forum book state to be saved into `ForumBookStorage` image::SDAnnounce.png[width=""800""] Step 2. The admin/user executes `checkAnnounce` to check for the latest announcement in storage file. The `checkAnnounce` calls the `UnitOfWork.getAnnouncementRepository().getLatestAnnouncement()` which returns an announcement to be shown in the message dialog. image::SDCheckAnnounce.png[width=""800""] Step 3. The admin executes `blockUser uName/john block/true` to block john from creating new threads or comments. The `block` calls `User.setIsBlock(true)` and then `UnitOfWork.commit()`, causing another modified forum book state to be saved into `ForumBookStorage`. image::SDBlockUserFromCreating.png[width=""800""] Step 4. The admin executes `setAdmin uName/john set/true` to set a certain user as admin or to revert an admin to user. The `setAdmin` calls the `User.setAdmin(true)` and then `UnitOfWork.commit()`, causing another modified forum book state to be saved into `ForumBookStorage`. image::SDSetAdmin.png[width=""800""] Step 5. The admin executes `createModule mCode/CS2113 mTitle/Software Engineering and OOP` to create the specific module. The `createModule` calls the `UnitOfWork.getModuleRepository().addModule(module)` and then `UnitOfWork.commit()`, causing another modified forum book state to be save into `ForumBookStorage`. image::SDCreateModule.png[width=""800""] Step 6. The admin executes `updateModule mId/3 mTitle/Software Eng and OOP` to update the specific module. The `updateModule` calls the `UnitOfWork.getModuleRepository().updateModule(module)` and then `UnitOfWork.commit()`, causing another modified forum book state to be save into `ForumBookStorage`. image::SDUpdateModule.png[width=""800""] Step 7. The admin executes `deleteModule mCode/CS2113` to delete specific module. The `deleteModule` calls the `UnitOfWork.getModuleRepository().removeModule(module);` and then `UnitOfWork.commit()`, causing another modified forum book state to be save into `ForumBookStorage`. image::SDDeleteModule.png[width=""800""] Step 8. The admin executes `updatePass uName/john uPass/098` to update the user john's password. The `updatePass` calls the `UnitOfWork.getUserRepository().updateUser(user)` and then `UnitOfWork.commit()`, causing another modified forum book state to be save into `ForumBookStorage`. image::SDUpdatePass.png[width=""800""] Step 9. The admin executes `deleteUser uName/john` to delete the user john. The `deleteUser` calls the ` UnitOfWork.getUserRepository().deleteUser(userToDelete)` and then `UnitOfWork.commit()`, causing another modified forum book state to be save into `ForumBookStorage`. image::SDDeleteUser.png[width=""800""] [NOTE] If the syntax of a command is wrong, the program will prompt the user to try again and show a suggested command format. // end::adminManagement[] // tag::dataencryption[] === Data Encryption Data encryption is done in a transparent layer. All data in this application is encrypted. A very simple, naive, and insecure encryption is implemented in `SimpleEncryptor`, this is only for demoing the ability of encrypting data in this application. However, a more secure algorithm can be easily added into the app by implementing the `IEncryptor` interface and provide it into `IStorage`. // end::dataencryption[] === Logging We are using `java.util.logging` package for logging. The `LogsCenter` class is used to manage the logging levels and logging destinations. * The logging level can be controlled using the `logLevel` setting in the configuration file (See <>) * The `Logger` for a class can be obtained using `LogsCenter.getLogger(Class)` which will log messages according to the specified logging level * Currently log messages are output through: `Console` and to a `.log` file. *Logging Levels* * `SEVERE` : Critical problem detected which may possibly cause the termination of the application * `WARNING` : Can continue, but with caution * `INFO` : Information showing the noteworthy actions by the App * `FINE` : Details that is not usually noteworthy but may be useful in debugging e.g. print the actual list instead of just its size [[Implementation-Configuration]] === Configuration Certain properties of the application can be controlled (e.g App name, logging level) through the configuration file (default: `config.json`). == Documentation We use asciidoc for writing documentation. [NOTE] We chose asciidoc over Markdown because asciidoc, although a bit more complex than Markdown, provides more flexibility in formatting. === Editing Documentation See <> to learn how to render `.adoc` files locally to preview the end result of your edits. Alternatively, you can download the AsciiDoc plugin for IntelliJ, which allows you to preview the changes you have made to your `.adoc` files in real-time. === Publishing Documentation See <> to learn how to deploy GitHub Pages using Travis. === Converting Documentation to PDF format We use https://www.google.com/chrome/browser/desktop/[Google Chrome] for converting documentation to PDF format, as Chrome's PDF engine preserves hyperlinks used in webpages. Here are the steps to convert the project documentation files to PDF format. . Follow the instructions in <> to convert the AsciiDoc files in the `docs/` directory to HTML format. . Go to your generated HTML files in the `build/docs` folder, right click on them and select `Open with` -> `Google Chrome`. . Within Chrome, click on the `Print` option in Chrome's menu. . Set the destination to `Save as PDF`, then click `Save` to save a copy of the file in PDF format. For best results, use the settings indicated in the screenshot below. .Saving documentation as PDF files in Chrome image::chrome_save_as_pdf.png[width=""300""] [[Docs-SiteWideDocSettings]] === Site-wide Documentation Settings The link:{repoURL}/build.gradle[`build.gradle`] file specifies some project-specific https://asciidoctor.org/docs/user-manual/#attributes[asciidoc attributes] which affects how all documentation files within this project are rendered. [TIP] Attributes left unset in the `build.gradle` file will use their *default value*, if any. [cols=""1,2a,1"", options=""header""] .List of site-wide attributes |=== |Attribute name |Description |Default value |`site-name` |The name of the website. If set, the name will be displayed near the top of the page. |_not set_ |`site-githuburl` |URL to the site's repository on https://github.com[GitHub]. Setting this will add a ""View on GitHub"" link in the navigation bar. |_not set_ |=== [[Docs-PerFileDocSettings]] === Per-file Documentation Settings Each `.adoc` file may also specify some file-specific https://asciidoctor.org/docs/user-manual/#attributes[asciidoc attributes] which affects how the file is rendered. Asciidoctor's https://asciidoctor.org/docs/user-manual/#builtin-attributes[built-in attributes] may be specified and used as well. [TIP] Attributes left unset in `.adoc` files will use their *default value*, if any. [cols=""1,2a,1"", options=""header""] .List of per-file attributes, excluding Asciidoctor's built-in attributes |=== |Attribute name |Description |Default value |`site-section` |Site section that the document belongs to. This will cause the associated item in the navigation bar to be highlighted. One of: `UserGuide`, `DeveloperGuide`, ``LearningOutcomes``{asterisk}, `AboutUs`, `ContactUs` |_not set_ |`no-site-header` |Set this attribute to remove the site navigation bar. |_not set_ |=== === Site Template The files in link:{repoURL}/docs/stylesheets[`docs/stylesheets`] are the https://developer.mozilla.org/en-US/docs/Web/CSS[CSS stylesheets] of the site. You can modify them to change some properties of the site's design. The files in link:{repoURL}/docs/templates[`docs/templates`] controls the rendering of `.adoc` files into HTML5. These template files are written in a mixture of https://www.ruby-lang.org[Ruby] and http://slim-lang.com[Slim]. [WARNING] ==== Modifying the template files in link:{repoURL}/docs/templates[`docs/templates`] requires some knowledge and experience with Ruby and Asciidoctor's API. You should only modify them if you need greater control over the site's layout than what stylesheets can provide. The SE-EDU team does not provide support for modified template files. ==== [[Testing]] == Testing === Running Tests There are three ways to run tests. [TIP] The most reliable way to run tests is the 3rd one. The first two methods might fail some GUI tests due to platform/resolution-specific idiosyncrasies. *Method 1: Using IntelliJ JUnit test runner* * To run all tests, right-click on the `src/test/java` folder and choose `Run 'All Tests'` * To run a subset of tests, you can right-click on a test package, test class, or a test and choose `Run 'ABC'` *Method 2: Using Gradle* * Open a console and run the command `gradlew clean allTests` (Mac/Linux: `./gradlew clean allTests`) [NOTE] See <> for more info on how to run tests using Gradle. *Method 3: Using Gradle (headless)* Thanks to the https://github.com/TestFX/TestFX[TestFX] library we use, our GUI tests can be run in the _headless_ mode. In the headless mode, GUI tests do not show up on the screen. That means the developer can do other things on the Computer while the tests are running. To run tests in headless mode, open a console and run the command `gradlew clean headless allTests` (Mac/Linux: `./gradlew clean headless allTests`) === Types of tests We have two types of tests: . *GUI Tests* - These are tests involving the GUI. They include, .. _System Tests_ that test the entire App by simulating user actions on the GUI. These are in the `systemtests` package. .. _Unit tests_ that test the individual components. These are in `t13g2.forum.ui` package. . *Non-GUI Tests* - These are tests not involving the GUI. They include, .. _Unit tests_ targeting the lowest level methods/classes. + e.g. `t13g2.forum.commons.StringUtilTest` .. _Integration tests_ that are checking the integration of multiple code units (those code units are assumed to be working). + e.g. `StorageManagerTest` .. Hybrids of unit and integration tests. These test are checking multiple code units as well as how the are connected together. + e.g. `LogicManagerTest` === Troubleshooting Testing **Problem: `HelpWindowTest` fails with a `NullPointerException`.** * Reason: One of its dependencies, `HelpWindow.html` in `src/main/resources/docs` is missing. * Solution: Execute Gradle task `processResources`. == Dev Ops === Build Automation See <> to learn how to use Gradle for build automation. === Continuous Integration We use https://travis-ci.org/[Travis CI] and https://www.appveyor.com/[AppVeyor] to perform _Continuous Integration_ on our projects. See <> and <> for more details. === Coverage Reporting We use https://coveralls.io/[Coveralls] to track the code coverage of our projects. See <> for more details. === Documentation Previews When a pull request has changes to asciidoc files, you can use https://www.netlify.com/[Netlify] to see a preview of how the HTML version of those asciidoc files will look like when the pull request is merged. See <> for more details. === Making a Release Here are the steps to create a new release. . Update the version number in link:{repoURL}/src/main/java/seedu/address/MainApp.java[`MainApp.java`]. . Generate a JAR file <>. . Tag the repo with the version number. e.g. `v0.1` . https://help.github.com/articles/creating-releases/[Create a new release using GitHub] and upload the JAR file you created. === Managing Dependencies A project often depends on third-party libraries. For example, Address Book depends on the http://wiki.fasterxml.com/JacksonHome[Jackson library] for XML parsing. Managing these _dependencies_ can be automated using Gradle. For example, Gradle can download the dependencies automatically, which is better than these alternatives. + a. Include those libraries in the repo (this bloats the repo size) + b. Require developers to download those libraries manually (this creates extra work for developers) [[GetStartedProgramming]] [appendix] == Product Scope *Target user profile*: * has a need to share and read comments related to modules * prefer desktop apps over other types * can type fast * prefers typing over mouse input * is reasonably comfortable using CLI apps *Value proposition*: Read a share comments faster than a typical mouse/GUI driven app // tag::user_Stories_And_Cases[] [appendix] == User Stories Priorities: High (must have) - `* * \\*`, Medium (nice to have) - `* \\*`, Low (unlikely to have) - `*` [width=""59%"",cols=""22%,<23%,<25%,<30%"",options=""header"",] |======================================================================= |Priority |As a ... |I want to ... |So that I can... |`* * *` |new user |see usage instructions |refer to instructions when I forget how to use the App |`* * *` |student who is taking a certain module in current semester |create a new forumThread |share the exam information with others |`* * *` |student who is going to take a certain module in future semesters |select that module and corresponding threads and comments under the module |learn more about the module in advance |`* * *` |student |list all existing modules |check what modules are available to interact with other students |`* * *` |forum thread owner |update my thread title |correct my typing error in this thread title |`* * *` |forum thread owner |delete my thread |close down the thread for further discussion under this thread |`* * *` |comment owner |update my comment content |correct my typing error or my thoughts in this comment |`* * *` |comment owner |delete my comment | |`* * *` |ForumBook admin |announce |show some important information to users |`* * *` |User |add myself as a user | register and use the forum book |`* * *` |User |login and logout |share my comments in the forum book and exit when i want to |`* * *` |User |delete myself from being a user | |`* * *` |ForumBook admin |block users |prevent users from creating and updating threads and comments |`* *` |ForumBook admin |change user password |help the user to reset the password once they forget their password |`* *` |ForumBook admin |set admin |have more admins to manage the ForumBook better |======================================================================= _{More to be added}_ [appendix] == Use Cases (For all use cases below, the *System* is the `ForumBook` and the *Actor* is the `user`, unless specified otherwise) [discrete] === Use case: List all threads under CS2113 *MSS* 1. User requests to list all modules 2. ForumBook shows a list of modules 3. User requests to list all threads under module CS2113 4. ForumBook shows a list of threads under module CS2113 + Use case ends. *Extensions* [none] * 2a. The list is empty. + Use case ends. * 3a. The given module code is invalid. + [none] ** 3a1. ForumBook shows an error message. + Use case ends. === Use case: Create new thread under CS2113 *MSS* 1. User requests to list all modules 2. ForumBook shows a list of modules 3. User requests to create new thread under module CS2113 4. ForumBook adds the new thread and shows a success message + Use case ends. *Extensions* [none] * 2a. The list is empty. + [none] ** 2a1. ForumBook shows empty list of module + Use case ends. * 3a. The given module code is invalid. + [none] ** 3a1. ForumBook shows an error message. + Use case ends. === Use case: Create new comment *MSS* 1. User requests to list all modules 2. ForumBook shows a list of modules 3. User requests to create new comment 4. ForumBook adds the new comment and shows a success message + Use case ends. *Extensions* [none] * 2a. The list is empty. + [none] ** 2a1. ForumBook shows empty list of module + Use case ends. * 3a. The given thread id is invalid. + [none] ** 3a1. ForumBook shows an error message. + Use case ends. === Use case: Delete thread and comment *MSS* 1. User requests to delete a thread 2. ForumBook deletes the thread and shows success message 3. User requests to delete a comment 4. ForumBook deletes the comment and shows success message + Use case ends. *Extensions* [none] * 2a. current user is not the thread owner. + [none] ** 2a1. ForumBook shows error message + Use case ends. * 3a. current user is not the comment owner. + [none] ** 3a1. ForumBook shows an error message. + Use case ends. === Use case: Update thread and comment *MSS* 1. User requests to update a thread 2. ForumBook updates the thread and shows success message 3. User requests to update a comment 4. ForumBook updates the comment and shows success message + Use case ends. *Extensions* [none] * 2a. current user is not the thread owner. + [none] ** 2a1. ForumBook shows error message + Use case ends. * 3a. current user is not the comment owner. + [none] ** 3a1. ForumBook shows an error message. + Use case ends. _{More to be added}_ // end::user_Stories_And_Cases[] // tag::others[] [appendix] == Non Functional Requirements . Should work on any <> as long as it has Java `9` or higher installed. . Should be able to hold up to 1000 threads with comments without a noticeable sluggishness in performance for typical usage. . A user with above average typing speed for regular English text (i.e. not code, not system admin commands) should be able to accomplish most of the tasks faster using commands than using the mouse. [appendix] == Glossary [[mainstream-os]] Mainstream OS:: Windows, Linux, Unix, OS-X [appendix] == Instructions for Manual Testing Given below are instructions to test the app manually. [NOTE] These instructions only provide a starting point for testers to work on; testers are expected to do more _exploratory_ testing. === Launch and Shutdown . Initial launch .. Download the jar file and copy into an empty folder .. Double-click the jar file + Expected: Shows the GUI with a set of sample contacts. The window size may not be optimum. . Getting sample data file .. Download [https://github.com/CS2113-AY1819S1-T13-2/main/blob/master/sampleData/forumData.zip[sample forumData zip folder]] and unzip .. Replace the default data folder generated by the application with the forumData folder you have downloaded. .. On relaunching the application, new data should be loaded. . Saving window preferences .. Resize the window to an optimum size. Move the window to a different location. Close the window. .. Re-launch the app by double-clicking the jar file. + Expected: The most recent window size and location is retained. // tag::UserManagement2[] === Registering and logging in . Registering a new user .. Prerequisites: username must not be registered before. .. Test case: `addUser uName/john uPass/123` Expected: the user `john` will be added to the UserStorage if there is no duplicate in the UserStorage. . Loggin in .. Test case: `login uName/abcd uPass/123` Expected: Log in with a random username and password that has not been registered. An error message will be shown in the result display panel. .. Test case: `login uName/john uPass/234` Expected: Log in with a registered username and a wrong password. An error message will be shown in the result display panel. .. Test case: `login uName/john uPass/123` Expected: Log in with a registered username and correct password, a success message will be shown in the result display panel. // end::UserManagement2[] === Announcing new announcement . Announcing a new announcement by admin. .. Prerequisites: Current user must login as an admin. .. Test case: `announce aTitle/Urgent! aContent/System Maintenance from 4pm to 5pm.` + Expected: Announcement will show up in a pop up window as well as the result display panel. .. Test case: `announce aTitle/ aContent/` + Expected: No announcement will be posted. Error details shown in the result display panel. === Checking new announcement . Checking for latest announcement. .. Prerequisites: Users have to login in order to do `checkAnnounce` .. Test case: `checkAnnounce` + Expected: The latest announcement will show up in a pop up window and in the result display panel. However, if the latest announcement is null, an error message ""There is no announcement at the moment"" will be shown in the result display panel. === Blocking user from posting . Blocking a given user by admin. .. Prerequisites: Current user must login as an admin. The given user should not be an admin and should be in the UserStorage. .. Test case: `blockUser uName/john block/true` + Expected: The given user will be blocked and a success message will be shown in the result display panel. .. Test case: `blockUser uName/abcd block/true` + Expected: Since the given user has not been added to the UserStorage, an error message will be shown in the result display panel. === Setting a user as admin or setting an admin as user   . Setting a user as admin or revert an admin to a user. .. Prerequisites: Current user must login as an admin. Admin is unable to set/revert himself/herself to admin/user. The given user must not been blocked and must be in UserStorage. .. Test case: `setAdmin uName/john set/true` + Expected: The given user will be set to an admin and the success message will be shown in the result display panel. .. Test case: `setAdmin uName/abcd set/true` + Expected: Since the given user has not been added to the UserStorage, an error message will be shown in the result display panel. === Creating a module . Creating a module by admin. .. Prerequisites: Current user must login as an admin. The module must not be in the ModuleStorage. .. Test case: `createModule mCode/CS2113 mContent/Software Engineering and OOP` + Expected: A new module will be added to the ModuleStorage, and a success message will be shown in the result display panel. .. Test case: `createModule mCode/ mTitle/` + Expected: No module will be added. Error details shown in the result display panel. === Creating a thread . Creating a thread under certain module by user or admin. .. Prerequisites: User must login to proceed. User should not be blocked by admin. .. Test case: `createThread mCode/CS2113 tTitle/Exam Information cContent/All the best for the final guys` + Expected: A new thread will be added to the ForumThreadStorage, and a success message will be shown in the result display panel. .. Test case: `createThread mCode/ tTitle/ cContent/` + Expected: No module will be added. Error details shown in the result display panel. === Creating a comment . Creating a comment under certain forum thread by user or admin. .. Prerequisites: User must login to proceed. User should not be blocked by admin. .. Test case: `createComment tId/1 cContent/This is a new comment` + Expected: A new thread will be added to the CommentStorage, and a success message will be shown in the result display panel. .. Test case: `createComment tId/ cContent/` + Expected: No comment will be added. Error details shown in the result display panel. === Updating a thread title . Updating the title of a forum thread by thread creator or admin. .. Prerequisites: User must login to proceed. User is the owner/creator of the forum thread. .. Test case: (If thread ID 123 is under current module) + `updateThread tId/123 tTitle/This is a new title` + Expected: The new thread title will be updated in the ForumThreadStorage, and a success message will be shown in the result display panel. .. Test case: (If thread ID 123 does not exist in the forum book) + `updateThread tId/123 tTitle/This is a new title` + Expected: No thread title will be updated. Error details of invalid thread id will be shown in the result display panel. .. Test case: (If thread ID 123 is not under current module) + `updateThread tId/123 tTitle/This is a new title` + Expected: No thread title will be updated. Error details of entity is not under scope will be shown in the result display panel. .. Test case: `updateThread tId/ tTitle/` + Expected: No thread title will be updated. Error details shown in the result display panel. === Updating a comment content . Updating the content of a comment by comment creator or admin. .. Prerequisites: User must login to proceed. User is the owner/creator of the comment. .. Test case: (If comment ID 123 is under current forum thread) + `updateThread cId/123 cContent/This is a new content` + Expected: The new comment content will be updated in the CommentStorage, and a success message will be shown in the result display panel. .. Test case: (If comment ID 123 does not exist in the forum book) + `updateThread cId/123 cContent/This is a new content` + Expected: No comment content will be updated. Error details of invalid comment id will be shown in the result display panel. .. Test case: (If comment ID 123 is not under current forum thread) + `updateThread cId/123 cContent/This is a new content` + Expected: No comment content will be updated. Error details of entity is not under scope will be shown in the result display panel. .. Test case: `updateThread cId/ cContent/` + Expected: No comment content will be updated. Error details shown in the result display panel. === Deleting a thread . Deleting a forum thread by thread creator or admin. .. Prerequisites: User must login to proceed. User is the owner/creator of the forum thread. .. Test case: (If thread ID 123 is under current module) + `deleteThread tId/123` + Expected: The new thread title will be deleted in the ForumThreadStorage, and a success message will be shown in the result display panel. .. Test case: (If thread ID 123 does not exist in the forum book) + `deleteThread tId/123` + Expected: No thread title will be deleted. Error details of invalid thread id will be shown in the result display panel. .. Test case: (If thread ID 123 is not under current module) + `deleteThread tId/123` + Expected: No thread title will be deleted. Error details of entity is not under scope will be shown in the result display panel. .. Test case: `deleteThread tId/` + Expected: No thread title will be deleted. Error details shown in the result display panel. === Deleting a comment . Deleting a comment by comment creator or admin. .. Prerequisites: User must login to proceed. User is the owner/creator of the comment. .. Test case: (If comment ID 123 is under current forum thread) + `deleteComment cId/123` + Expected: The new comment content will be deleted in the CommentStorage, and a success message will be shown in the result display panel. .. Test case: (If comment ID 123 does not exist in the forum book) + `deleteComment cId/123` + Expected: No comment content will be deleted. Error details of invalid comment id will be shown in the result display panel. .. Test case: (If comment ID 123 is not under current forum thread) + `deleteComment cId/123` + Expected: No comment content will be deleted. Error details of entity is not under scope will be shown in the result display panel. .. Test case: `deleteComment cId/` + Expected: No comment content will be deleted. Error details shown in the result display panel. === Listing all modules . Listing all the modules in the forun book by user or admin. .. Prerequisites: User must login to proceed. .. Test case: `listModule` + Expected: A list of modules in the ModuleStorage will be shown in the result display panel. === Selecting a module to list all threads . Listing all the forum threads under certain module in the forun book by user or admin. .. Prerequisites: User must login to proceed. The module code entered by user should exist in the ModuleStorage. .. Test case: `selectModule mCode/CS2113` + Expected: A list of forum threads under module CS2113 in the ForumThreadStorage will be shown in the result display panel. .. Test case: `selectModule mCode/` + Expected: No forum thread will be listed out. Error details shown in the result display panel. === Selecting a thread to list all comments . Listing all the comments under certain forum thread in the forun book by user or admin. .. Prerequisites: User must login to proceed. The thread Id entered by user should exist in the ForumThreadStorage. .. Test case: `selectThread tId/123` + Expected: A list of comments under thread ID 123 in the ForumThreadStorage will be shown in the result display panel. .. Test case: `selectModule tId/` + Expected: No comment will be listed out. Error details shown in the result display panel. === Updating a module . Updating a module by admin. .. Prerequisites: Current user must login as an admin. The module must be in ModuleStorage. .. Test case: `updateModule mId/3 mCode/CS1223` + Expected: The module `CS2113` will be updated to take the module code `CS1223`, and an success message will be shown in the result display panel. .. Test case: `updateModule mCode/CS1223` + Expected: Since the module id was not specified, The module will not be updated. This command should raise an error and show in the result display panel. === Deleting a module . Deleting a module by admin. .. Prerequisites: Current user must login as an admin. The module must be in ModuleStorage. .. Test case: `deleteModule mCode/CS2113` + Expected: The module `CS2113` will be deleted from the ModuleStorage, and an success message will be shown in the result display panel. .. Test case: `deleteModule mCode/CS2113` + Expected: Since the module `CS2113` has been deleted. This command should raise an error and show in the result display panel. === Updating password . Updating a given user's password by admin. .. Prerequisites: Current user must login as an admin. The given user must be in UserStorage. .. Test case: `updatePass uName/john uPass/456` + Expected: The user `john`'s password will be updated to `456` .. Test case: `updatePass uName/abcd uPass/123` + Expected: Since the given user `abcd` has not been added to the UserStorage, an error message will be shown in the result display panel. === Deleting a user(Admin) . Deleting a given user by admin. .. Prerequisites: Current user must login as an admin. The given user must be in the UserStorage. .. Test case: `deleteUser uName/john` Expected: The user `john` will be deleted from the UserStorage and a success message will be shown in the result display panel. .. Test case: `deleteUser uName/abcd` Expected: Since the given user `abcd` does not exist in the UserStorage, an error message will be shown in the result display panel. // tag::UserManagement3[] === Deleting a user(User) . Self Deleting a user. .. Prerequisites: User who is interested in removing himself from the forum must login to his account. The given user must be in the UserStorage. .. Test case: `deleteMe` -user logged in Expected Success: The current user will be deleted from the UserStorage and a success message will be shown in the result display panel. .. Test case: `deleteMe` -user not logged in Expected Fail: Since the given user is not logged in, an error message will be shown in the result display panel. // end::UserManagement3[].. _{explain how to simulate a missing/corrupted file and the expected behavior}_ // end::others[] ",12296,False,1977.4761708547696,median "= v1.ControllerRevision {product-author} {product-version} :data-uri: :icons: :toc: macro :toc-title: :toclevels: 2 toc::[] == Description [%hardbreaks] ControllerRevision implements an immutable snapshot of state data. Clients are responsible for serializing and deserializing the objects that contain their internal state. Once a ControllerRevision has been successfully created, it can not be updated. The API Server will fail validation of all requests that attempt to mutate the Data field. ControllerRevisions may, however, be deleted. Note that, due to its use by both the DaemonSet and StatefulSet controllers for update and rollback, this object is beta. However, it may be subject to name and representation changes in future releases, and clients should not depend on its stability. It is primarily for internal use by controllers. == Object Schema Expand or mouse-over a field for more information about it. ++++
apiVersion:
data:
Raw:
kind:
metadata:
annotations:
[string]:
clusterName:
creationTimestamp:
deletionGracePeriodSeconds:
deletionTimestamp:
finalizers:
- [string]:
generateName:
generation:
:
pending:
- name:
result:
apiVersion:
code:
details:
causes:
- field:
message:
reason:
group:
kind:
name:
retryAfterSeconds:
uid:
kind:
message:
metadata:
continue:
resourceVersion:
selfLink:
reason:
status:
labels:
[string]:
name:
namespace:
ownerReferences:
- apiVersion:
blockOwnerDeletion:
controller:
kind:
name:
uid:
resourceVersion:
selfLink:
uid:
revision:
++++ == Operations [[Post-apis-apps-v1-controllerrevisions]] === Create a ControllerRevision Create a ControllerRevision ==== HTTP request ---- POST /apis/apps/v1/controllerrevisions HTTP/1.1 Authorization: Bearer $TOKEN Accept: application/json Connection: close Content-Type: application/json' { ""kind"": ""ControllerRevision"", ""apiVersion"": ""apps/v1"", ... } ---- ==== Curl request ---- $ curl -k \\ -X POST \\ -d @- \\ -H ""Authorization: Bearer $TOKEN"" \\ -H 'Accept: application/json' \\ -H 'Content-Type: application/json' \\ https://$ENDPOINT/apis/apps/v1/controllerrevisions <<'EOF' { ""kind"": ""ControllerRevision"", ""apiVersion"": ""apps/v1"", ... } EOF ---- ==== HTTP body [cols=""1,5"", options=""header""] |=== |Parameter|Schema |body|v1.ControllerRevision |=== ==== Query parameters [cols=""1,5"", options=""header""] |=== |Parameter|Description |pretty|If 'true', then the output is pretty printed. |=== ==== Responses [cols=""1,5"", options=""header""] |=== |HTTP Code|Schema |200 OK|v1.ControllerRevision |201 Created|v1.ControllerRevision |202 Accepted|v1.ControllerRevision |401 Unauthorized| |=== ==== Consumes * \\*/* ==== Produces * application/json * application/yaml * application/vnd.kubernetes.protobuf [[Post-apis-apps-v1-namespaces-namespace-controllerrevisions]] === Create a ControllerRevision in a namespace Create a ControllerRevision ==== HTTP request ---- POST /apis/apps/v1/namespaces/$NAMESPACE/controllerrevisions HTTP/1.1 Authorization: Bearer $TOKEN Accept: application/json Connection: close Content-Type: application/json' { ""kind"": ""ControllerRevision"", ""apiVersion"": ""apps/v1"", ... } ---- ==== Curl request ---- $ curl -k \\ -X POST \\ -d @- \\ -H ""Authorization: Bearer $TOKEN"" \\ -H 'Accept: application/json' \\ -H 'Content-Type: application/json' \\ https://$ENDPOINT/apis/apps/v1/namespaces/$NAMESPACE/controllerrevisions <<'EOF' { ""kind"": ""ControllerRevision"", ""apiVersion"": ""apps/v1"", ... } EOF ---- ==== HTTP body [cols=""1,5"", options=""header""] |=== |Parameter|Schema |body|v1.ControllerRevision |=== ==== Path parameters [cols=""1,5"", options=""header""] |=== |Parameter|Description |namespace|object name and auth scope, such as for teams and projects |=== ==== Query parameters [cols=""1,5"", options=""header""] |=== |Parameter|Description |pretty|If 'true', then the output is pretty printed. |=== ==== Responses [cols=""1,5"", options=""header""] |=== |HTTP Code|Schema |200 OK|v1.ControllerRevision |201 Created|v1.ControllerRevision |202 Accepted|v1.ControllerRevision |401 Unauthorized| |=== ==== Consumes * \\*/* ==== Produces * application/json * application/yaml * application/vnd.kubernetes.protobuf [[Get-apis-apps-v1-namespaces-namespace-controllerrevisions-name]] === Get a ControllerRevision in a namespace Read the specified ControllerRevision ==== HTTP request ---- GET /apis/apps/v1/namespaces/$NAMESPACE/controllerrevisions/$NAME HTTP/1.1 Authorization: Bearer $TOKEN Accept: application/json Connection: close ---- ==== Curl request ---- $ curl -k \\ -H ""Authorization: Bearer $TOKEN"" \\ -H 'Accept: application/json' \\ https://$ENDPOINT/apis/apps/v1/namespaces/$NAMESPACE/controllerrevisions/$NAME ---- ==== Path parameters [cols=""1,5"", options=""header""] |=== |Parameter|Description |name|name of the ControllerRevision |namespace|object name and auth scope, such as for teams and projects |=== ==== Query parameters [cols=""1,5"", options=""header""] |=== |Parameter|Description |pretty|If 'true', then the output is pretty printed. |exact|Should the export be exact. Exact export maintains cluster-specific fields like 'Namespace'. |export|Should this value be exported. Export strips fields that a user can not specify. |=== ==== Responses [cols=""1,5"", options=""header""] |=== |HTTP Code|Schema |200 OK|v1.ControllerRevision |401 Unauthorized| |=== ==== Consumes * \\*/* ==== Produces * application/json * application/yaml * application/vnd.kubernetes.protobuf [[Get-apis-apps-v1-controllerrevisions]] === Get all ControllerRevisions List or watch objects of kind ControllerRevision ==== HTTP request ---- GET /apis/apps/v1/controllerrevisions HTTP/1.1 Authorization: Bearer $TOKEN Accept: application/json Connection: close ---- ==== Curl request ---- $ curl -k \\ -H ""Authorization: Bearer $TOKEN"" \\ -H 'Accept: application/json' \\ https://$ENDPOINT/apis/apps/v1/controllerrevisions ---- ==== Query parameters [cols=""1,5"", options=""header""] |=== |Parameter|Description |pretty|If 'true', then the output is pretty printed. |continue|The continue option should be set when retrieving more results from the server. Since this value is server defined, clients may only use the continue value from a previous query result with identical query parameters (except for the value of continue) and the server may reject a continue value it does not recognize. If the specified continue value is no longer valid whether due to expiration (generally five to fifteen minutes) or a configuration change on the server the server will respond with a 410 ResourceExpired error indicating the client must restart their list without the continue field. This field is not supported when watch is true. Clients may start a watch from the last resourceVersion value returned by the server and not miss any modifications. |fieldSelector|A selector to restrict the list of returned objects by their fields. Defaults to everything. |includeUninitialized|If true, partially initialized resources are included in the response. |labelSelector|A selector to restrict the list of returned objects by their labels. Defaults to everything. |limit|limit is a maximum number of responses to return for a list call. If more items exist, the server will set the `continue` field on the list metadata to a value that can be used with the same initial query to retrieve the next set of results. Setting a limit may return fewer than the requested amount of items (up to zero items) in the event all requested objects are filtered out and clients should only use the presence of the continue field to determine whether more results are available. Servers may choose not to support the limit argument and will return all of the available results. If limit is specified and the continue field is empty, clients may assume that no more results are available. This field is not supported if watch is true. The server guarantees that the objects returned when using continue will be identical to issuing a single list call without a limit - that is, no objects created, modified, or deleted after the first request is issued will be included in any subsequent continued requests. This is sometimes referred to as a consistent snapshot, and ensures that a client that is using limit to receive smaller chunks of a very large result can ensure they see all possible objects. If objects are updated during a chunked list the version of the object that was present at the time the first list result was calculated is returned. |resourceVersion|When specified with a watch call, shows changes that occur after that particular version of a resource. Defaults to changes from the beginning of history. When specified for list: - if unset, then the result is returned from remote storage based on quorum-read flag; - if it's 0, then we simply return what we currently have in cache, no guarantee; - if set to non zero, then the result is at least as fresh as given rv. |timeoutSeconds|Timeout for the list/watch call. |watch|Watch for changes to the described resources and return them as a stream of add, update, and remove notifications. Specify resourceVersion. |=== ==== Responses [cols=""1,5"", options=""header""] |=== |HTTP Code|Schema |200 OK|v1.ControllerRevisionList |401 Unauthorized| |=== ==== Consumes * \\*/* ==== Produces * application/json * application/yaml * application/vnd.kubernetes.protobuf * application/json;stream=watch * application/vnd.kubernetes.protobuf;stream=watch [[Get-apis-apps-v1-namespaces-namespace-controllerrevisions]] === Get all ControllerRevisions in a namespace List or watch objects of kind ControllerRevision ==== HTTP request ---- GET /apis/apps/v1/namespaces/$NAMESPACE/controllerrevisions HTTP/1.1 Authorization: Bearer $TOKEN Accept: application/json Connection: close ---- ==== Curl request ---- $ curl -k \\ -H ""Authorization: Bearer $TOKEN"" \\ -H 'Accept: application/json' \\ https://$ENDPOINT/apis/apps/v1/namespaces/$NAMESPACE/controllerrevisions ---- ==== Path parameters [cols=""1,5"", options=""header""] |=== |Parameter|Description |namespace|object name and auth scope, such as for teams and projects |=== ==== Query parameters [cols=""1,5"", options=""header""] |=== |Parameter|Description |pretty|If 'true', then the output is pretty printed. |continue|The continue option should be set when retrieving more results from the server. Since this value is server defined, clients may only use the continue value from a previous query result with identical query parameters (except for the value of continue) and the server may reject a continue value it does not recognize. If the specified continue value is no longer valid whether due to expiration (generally five to fifteen minutes) or a configuration change on the server the server will respond with a 410 ResourceExpired error indicating the client must restart their list without the continue field. This field is not supported when watch is true. Clients may start a watch from the last resourceVersion value returned by the server and not miss any modifications. |fieldSelector|A selector to restrict the list of returned objects by their fields. Defaults to everything. |includeUninitialized|If true, partially initialized resources are included in the response. |labelSelector|A selector to restrict the list of returned objects by their labels. Defaults to everything. |limit|limit is a maximum number of responses to return for a list call. If more items exist, the server will set the `continue` field on the list metadata to a value that can be used with the same initial query to retrieve the next set of results. Setting a limit may return fewer than the requested amount of items (up to zero items) in the event all requested objects are filtered out and clients should only use the presence of the continue field to determine whether more results are available. Servers may choose not to support the limit argument and will return all of the available results. If limit is specified and the continue field is empty, clients may assume that no more results are available. This field is not supported if watch is true. The server guarantees that the objects returned when using continue will be identical to issuing a single list call without a limit - that is, no objects created, modified, or deleted after the first request is issued will be included in any subsequent continued requests. This is sometimes referred to as a consistent snapshot, and ensures that a client that is using limit to receive smaller chunks of a very large result can ensure they see all possible objects. If objects are updated during a chunked list the version of the object that was present at the time the first list result was calculated is returned. |resourceVersion|When specified with a watch call, shows changes that occur after that particular version of a resource. Defaults to changes from the beginning of history. When specified for list: - if unset, then the result is returned from remote storage based on quorum-read flag; - if it's 0, then we simply return what we currently have in cache, no guarantee; - if set to non zero, then the result is at least as fresh as given rv. |timeoutSeconds|Timeout for the list/watch call. |watch|Watch for changes to the described resources and return them as a stream of add, update, and remove notifications. Specify resourceVersion. |=== ==== Responses [cols=""1,5"", options=""header""] |=== |HTTP Code|Schema |200 OK|v1.ControllerRevisionList |401 Unauthorized| |=== ==== Consumes * \\*/* ==== Produces * application/json * application/yaml * application/vnd.kubernetes.protobuf * application/json;stream=watch * application/vnd.kubernetes.protobuf;stream=watch [[Get-apis-apps-v1-watch-namespaces-namespace-controllerrevisions-name]] === Watch a ControllerRevision in a namespace Watch changes to an object of kind ControllerRevision ==== HTTP request ---- GET /apis/apps/v1/watch/namespaces/$NAMESPACE/controllerrevisions/$NAME HTTP/1.1 Authorization: Bearer $TOKEN Accept: application/json Connection: close ---- ==== Curl request ---- $ curl -k \\ -H ""Authorization: Bearer $TOKEN"" \\ -H 'Accept: application/json' \\ https://$ENDPOINT/apis/apps/v1/watch/namespaces/$NAMESPACE/controllerrevisions/$NAME ---- ==== Path parameters [cols=""1,5"", options=""header""] |=== |Parameter|Description |name|name of the ControllerRevision |namespace|object name and auth scope, such as for teams and projects |=== ==== Query parameters [cols=""1,5"", options=""header""] |=== |Parameter|Description |continue|The continue option should be set when retrieving more results from the server. Since this value is server defined, clients may only use the continue value from a previous query result with identical query parameters (except for the value of continue) and the server may reject a continue value it does not recognize. If the specified continue value is no longer valid whether due to expiration (generally five to fifteen minutes) or a configuration change on the server the server will respond with a 410 ResourceExpired error indicating the client must restart their list without the continue field. This field is not supported when watch is true. Clients may start a watch from the last resourceVersion value returned by the server and not miss any modifications. |fieldSelector|A selector to restrict the list of returned objects by their fields. Defaults to everything. |includeUninitialized|If true, partially initialized resources are included in the response. |labelSelector|A selector to restrict the list of returned objects by their labels. Defaults to everything. |limit|limit is a maximum number of responses to return for a list call. If more items exist, the server will set the `continue` field on the list metadata to a value that can be used with the same initial query to retrieve the next set of results. Setting a limit may return fewer than the requested amount of items (up to zero items) in the event all requested objects are filtered out and clients should only use the presence of the continue field to determine whether more results are available. Servers may choose not to support the limit argument and will return all of the available results. If limit is specified and the continue field is empty, clients may assume that no more results are available. This field is not supported if watch is true. The server guarantees that the objects returned when using continue will be identical to issuing a single list call without a limit - that is, no objects created, modified, or deleted after the first request is issued will be included in any subsequent continued requests. This is sometimes referred to as a consistent snapshot, and ensures that a client that is using limit to receive smaller chunks of a very large result can ensure they see all possible objects. If objects are updated during a chunked list the version of the object that was present at the time the first list result was calculated is returned. |pretty|If 'true', then the output is pretty printed. |resourceVersion|When specified with a watch call, shows changes that occur after that particular version of a resource. Defaults to changes from the beginning of history. When specified for list: - if unset, then the result is returned from remote storage based on quorum-read flag; - if it's 0, then we simply return what we currently have in cache, no guarantee; - if set to non zero, then the result is at least as fresh as given rv. |timeoutSeconds|Timeout for the list/watch call. |watch|Watch for changes to the described resources and return them as a stream of add, update, and remove notifications. Specify resourceVersion. |=== ==== Responses [cols=""1,5"", options=""header""] |=== |HTTP Code|Schema |200 OK|v1.WatchEvent |401 Unauthorized| |=== ==== Consumes * \\*/* ==== Produces * application/json * application/yaml * application/vnd.kubernetes.protobuf * application/json;stream=watch * application/vnd.kubernetes.protobuf;stream=watch [[Get-apis-apps-v1-watch-controllerrevisions]] === Watch all ControllerRevisions Watch individual changes to a list of ControllerRevision ==== HTTP request ---- GET /apis/apps/v1/watch/controllerrevisions HTTP/1.1 Authorization: Bearer $TOKEN Accept: application/json Connection: close ---- ==== Curl request ---- $ curl -k \\ -H ""Authorization: Bearer $TOKEN"" \\ -H 'Accept: application/json' \\ https://$ENDPOINT/apis/apps/v1/watch/controllerrevisions ---- ==== Query parameters [cols=""1,5"", options=""header""] |=== |Parameter|Description |continue|The continue option should be set when retrieving more results from the server. Since this value is server defined, clients may only use the continue value from a previous query result with identical query parameters (except for the value of continue) and the server may reject a continue value it does not recognize. If the specified continue value is no longer valid whether due to expiration (generally five to fifteen minutes) or a configuration change on the server the server will respond with a 410 ResourceExpired error indicating the client must restart their list without the continue field. This field is not supported when watch is true. Clients may start a watch from the last resourceVersion value returned by the server and not miss any modifications. |fieldSelector|A selector to restrict the list of returned objects by their fields. Defaults to everything. |includeUninitialized|If true, partially initialized resources are included in the response. |labelSelector|A selector to restrict the list of returned objects by their labels. Defaults to everything. |limit|limit is a maximum number of responses to return for a list call. If more items exist, the server will set the `continue` field on the list metadata to a value that can be used with the same initial query to retrieve the next set of results. Setting a limit may return fewer than the requested amount of items (up to zero items) in the event all requested objects are filtered out and clients should only use the presence of the continue field to determine whether more results are available. Servers may choose not to support the limit argument and will return all of the available results. If limit is specified and the continue field is empty, clients may assume that no more results are available. This field is not supported if watch is true. The server guarantees that the objects returned when using continue will be identical to issuing a single list call without a limit - that is, no objects created, modified, or deleted after the first request is issued will be included in any subsequent continued requests. This is sometimes referred to as a consistent snapshot, and ensures that a client that is using limit to receive smaller chunks of a very large result can ensure they see all possible objects. If objects are updated during a chunked list the version of the object that was present at the time the first list result was calculated is returned. |pretty|If 'true', then the output is pretty printed. |resourceVersion|When specified with a watch call, shows changes that occur after that particular version of a resource. Defaults to changes from the beginning of history. When specified for list: - if unset, then the result is returned from remote storage based on quorum-read flag; - if it's 0, then we simply return what we currently have in cache, no guarantee; - if set to non zero, then the result is at least as fresh as given rv. |timeoutSeconds|Timeout for the list/watch call. |watch|Watch for changes to the described resources and return them as a stream of add, update, and remove notifications. Specify resourceVersion. |=== ==== Responses [cols=""1,5"", options=""header""] |=== |HTTP Code|Schema |200 OK|v1.WatchEvent |401 Unauthorized| |=== ==== Consumes * \\*/* ==== Produces * application/json * application/yaml * application/vnd.kubernetes.protobuf * application/json;stream=watch * application/vnd.kubernetes.protobuf;stream=watch [[Get-apis-apps-v1-watch-namespaces-namespace-controllerrevisions]] === Watch all ControllerRevisions in a namespace Watch individual changes to a list of ControllerRevision ==== HTTP request ---- GET /apis/apps/v1/watch/namespaces/$NAMESPACE/controllerrevisions HTTP/1.1 Authorization: Bearer $TOKEN Accept: application/json Connection: close ---- ==== Curl request ---- $ curl -k \\ -H ""Authorization: Bearer $TOKEN"" \\ -H 'Accept: application/json' \\ https://$ENDPOINT/apis/apps/v1/watch/namespaces/$NAMESPACE/controllerrevisions ---- ==== Path parameters [cols=""1,5"", options=""header""] |=== |Parameter|Description |namespace|object name and auth scope, such as for teams and projects |=== ==== Query parameters [cols=""1,5"", options=""header""] |=== |Parameter|Description |continue|The continue option should be set when retrieving more results from the server. Since this value is server defined, clients may only use the continue value from a previous query result with identical query parameters (except for the value of continue) and the server may reject a continue value it does not recognize. If the specified continue value is no longer valid whether due to expiration (generally five to fifteen minutes) or a configuration change on the server the server will respond with a 410 ResourceExpired error indicating the client must restart their list without the continue field. This field is not supported when watch is true. Clients may start a watch from the last resourceVersion value returned by the server and not miss any modifications. |fieldSelector|A selector to restrict the list of returned objects by their fields. Defaults to everything. |includeUninitialized|If true, partially initialized resources are included in the response. |labelSelector|A selector to restrict the list of returned objects by their labels. Defaults to everything. |limit|limit is a maximum number of responses to return for a list call. If more items exist, the server will set the `continue` field on the list metadata to a value that can be used with the same initial query to retrieve the next set of results. Setting a limit may return fewer than the requested amount of items (up to zero items) in the event all requested objects are filtered out and clients should only use the presence of the continue field to determine whether more results are available. Servers may choose not to support the limit argument and will return all of the available results. If limit is specified and the continue field is empty, clients may assume that no more results are available. This field is not supported if watch is true. The server guarantees that the objects returned when using continue will be identical to issuing a single list call without a limit - that is, no objects created, modified, or deleted after the first request is issued will be included in any subsequent continued requests. This is sometimes referred to as a consistent snapshot, and ensures that a client that is using limit to receive smaller chunks of a very large result can ensure they see all possible objects. If objects are updated during a chunked list the version of the object that was present at the time the first list result was calculated is returned. |pretty|If 'true', then the output is pretty printed. |resourceVersion|When specified with a watch call, shows changes that occur after that particular version of a resource. Defaults to changes from the beginning of history. When specified for list: - if unset, then the result is returned from remote storage based on quorum-read flag; - if it's 0, then we simply return what we currently have in cache, no guarantee; - if set to non zero, then the result is at least as fresh as given rv. |timeoutSeconds|Timeout for the list/watch call. |watch|Watch for changes to the described resources and return them as a stream of add, update, and remove notifications. Specify resourceVersion. |=== ==== Responses [cols=""1,5"", options=""header""] |=== |HTTP Code|Schema |200 OK|v1.WatchEvent |401 Unauthorized| |=== ==== Consumes * \\*/* ==== Produces * application/json * application/yaml * application/vnd.kubernetes.protobuf * application/json;stream=watch * application/vnd.kubernetes.protobuf;stream=watch [[Put-apis-apps-v1-namespaces-namespace-controllerrevisions-name]] === Update a ControllerRevision in a namespace Replace the specified ControllerRevision ==== HTTP request ---- PUT /apis/apps/v1/namespaces/$NAMESPACE/controllerrevisions/$NAME HTTP/1.1 Authorization: Bearer $TOKEN Accept: application/json Connection: close Content-Type: application/json' { ""kind"": ""ControllerRevision"", ""apiVersion"": ""apps/v1"", ... } ---- ==== Curl request ---- $ curl -k \\ -X PUT \\ -d @- \\ -H ""Authorization: Bearer $TOKEN"" \\ -H 'Accept: application/json' \\ -H 'Content-Type: application/json' \\ https://$ENDPOINT/apis/apps/v1/namespaces/$NAMESPACE/controllerrevisions/$NAME <<'EOF' { ""kind"": ""ControllerRevision"", ""apiVersion"": ""apps/v1"", ... } EOF ---- ==== HTTP body [cols=""1,5"", options=""header""] |=== |Parameter|Schema |body|v1.ControllerRevision |=== ==== Path parameters [cols=""1,5"", options=""header""] |=== |Parameter|Description |name|name of the ControllerRevision |namespace|object name and auth scope, such as for teams and projects |=== ==== Query parameters [cols=""1,5"", options=""header""] |=== |Parameter|Description |pretty|If 'true', then the output is pretty printed. |=== ==== Responses [cols=""1,5"", options=""header""] |=== |HTTP Code|Schema |200 OK|v1.ControllerRevision |201 Created|v1.ControllerRevision |401 Unauthorized| |=== ==== Consumes * \\*/* ==== Produces * application/json * application/yaml * application/vnd.kubernetes.protobuf [[Patch-apis-apps-v1-namespaces-namespace-controllerrevisions-name]] === Patch a ControllerRevision in a namespace Partially update the specified ControllerRevision ==== HTTP request ---- PATCH /apis/apps/v1/namespaces/$NAMESPACE/controllerrevisions/$NAME HTTP/1.1 Authorization: Bearer $TOKEN Accept: application/json Connection: close Content-Type: application/json-patch+json' { ... } ---- ==== Curl request ---- $ curl -k \\ -X PATCH \\ -d @- \\ -H ""Authorization: Bearer $TOKEN"" \\ -H 'Accept: application/json' \\ -H 'Content-Type: application/json-patch+json' \\ https://$ENDPOINT/apis/apps/v1/namespaces/$NAMESPACE/controllerrevisions/$NAME <<'EOF' { ... } EOF ---- ==== HTTP body [cols=""1,5"", options=""header""] |=== |Parameter|Schema |body|v1.Patch |=== ==== Path parameters [cols=""1,5"", options=""header""] |=== |Parameter|Description |name|name of the ControllerRevision |namespace|object name and auth scope, such as for teams and projects |=== ==== Query parameters [cols=""1,5"", options=""header""] |=== |Parameter|Description |pretty|If 'true', then the output is pretty printed. |=== ==== Responses [cols=""1,5"", options=""header""] |=== |HTTP Code|Schema |200 OK|v1.ControllerRevision |401 Unauthorized| |=== ==== Consumes * application/json-patch+json * application/merge-patch+json * application/strategic-merge-patch+json ==== Produces * application/json * application/yaml * application/vnd.kubernetes.protobuf [[Delete-apis-apps-v1-namespaces-namespace-controllerrevisions-name]] === Delete a ControllerRevision in a namespace Delete a ControllerRevision ==== HTTP request ---- DELETE /apis/apps/v1/namespaces/$NAMESPACE/controllerrevisions/$NAME HTTP/1.1 Authorization: Bearer $TOKEN Accept: application/json Connection: close Content-Type: application/json' { ... } ---- ==== Curl request ---- $ curl -k \\ -X DELETE \\ -d @- \\ -H ""Authorization: Bearer $TOKEN"" \\ -H 'Accept: application/json' \\ -H 'Content-Type: application/json' \\ https://$ENDPOINT/apis/apps/v1/namespaces/$NAMESPACE/controllerrevisions/$NAME <<'EOF' { ... } EOF ---- ==== HTTP body [cols=""1,5"", options=""header""] |=== |Parameter|Schema |body|v1.DeleteOptions |=== ==== Path parameters [cols=""1,5"", options=""header""] |=== |Parameter|Description |name|name of the ControllerRevision |namespace|object name and auth scope, such as for teams and projects |=== ==== Query parameters [cols=""1,5"", options=""header""] |=== |Parameter|Description |pretty|If 'true', then the output is pretty printed. |gracePeriodSeconds|The duration in seconds before the object should be deleted. Value must be non-negative integer. The value zero indicates delete immediately. If this value is nil, the default grace period for the specified type will be used. Defaults to a per object value if not specified. zero means delete immediately. |orphanDependents|Deprecated: please use the PropagationPolicy, this field will be deprecated in 1.7. Should the dependent objects be orphaned. If true/false, the ""orphan"" finalizer will be added to/removed from the object's finalizers list. Either this field or PropagationPolicy may be set, but not both. |propagationPolicy|Whether and how garbage collection will be performed. Either this field or OrphanDependents may be set, but not both. The default policy is decided by the existing finalizer set in the metadata.finalizers and the resource-specific default policy. Acceptable values are: 'Orphan' - orphan the dependents; 'Background' - allow the garbage collector to delete the dependents in the background; 'Foreground' - a cascading policy that deletes all dependents in the foreground. |=== ==== Responses [cols=""1,5"", options=""header""] |=== |HTTP Code|Schema |200 OK|v1.Status |401 Unauthorized| |=== ==== Consumes * \\*/* ==== Produces * application/json * application/yaml * application/vnd.kubernetes.protobuf [[Delete-apis-apps-v1-namespaces-namespace-controllerrevisions]] === Delete all ControllerRevisions in a namespace Delete collection of ControllerRevision ==== HTTP request ---- DELETE /apis/apps/v1/namespaces/$NAMESPACE/controllerrevisions HTTP/1.1 Authorization: Bearer $TOKEN Accept: application/json Connection: close ---- ==== Curl request ---- $ curl -k \\ -X DELETE \\ -H ""Authorization: Bearer $TOKEN"" \\ -H 'Accept: application/json' \\ https://$ENDPOINT/apis/apps/v1/namespaces/$NAMESPACE/controllerrevisions ---- ==== Path parameters [cols=""1,5"", options=""header""] |=== |Parameter|Description |namespace|object name and auth scope, such as for teams and projects |=== ==== Query parameters [cols=""1,5"", options=""header""] |=== |Parameter|Description |pretty|If 'true', then the output is pretty printed. |continue|The continue option should be set when retrieving more results from the server. Since this value is server defined, clients may only use the continue value from a previous query result with identical query parameters (except for the value of continue) and the server may reject a continue value it does not recognize. If the specified continue value is no longer valid whether due to expiration (generally five to fifteen minutes) or a configuration change on the server the server will respond with a 410 ResourceExpired error indicating the client must restart their list without the continue field. This field is not supported when watch is true. Clients may start a watch from the last resourceVersion value returned by the server and not miss any modifications. |fieldSelector|A selector to restrict the list of returned objects by their fields. Defaults to everything. |includeUninitialized|If true, partially initialized resources are included in the response. |labelSelector|A selector to restrict the list of returned objects by their labels. Defaults to everything. |limit|limit is a maximum number of responses to return for a list call. If more items exist, the server will set the `continue` field on the list metadata to a value that can be used with the same initial query to retrieve the next set of results. Setting a limit may return fewer than the requested amount of items (up to zero items) in the event all requested objects are filtered out and clients should only use the presence of the continue field to determine whether more results are available. Servers may choose not to support the limit argument and will return all of the available results. If limit is specified and the continue field is empty, clients may assume that no more results are available. This field is not supported if watch is true. The server guarantees that the objects returned when using continue will be identical to issuing a single list call without a limit - that is, no objects created, modified, or deleted after the first request is issued will be included in any subsequent continued requests. This is sometimes referred to as a consistent snapshot, and ensures that a client that is using limit to receive smaller chunks of a very large result can ensure they see all possible objects. If objects are updated during a chunked list the version of the object that was present at the time the first list result was calculated is returned. |resourceVersion|When specified with a watch call, shows changes that occur after that particular version of a resource. Defaults to changes from the beginning of history. When specified for list: - if unset, then the result is returned from remote storage based on quorum-read flag; - if it's 0, then we simply return what we currently have in cache, no guarantee; - if set to non zero, then the result is at least as fresh as given rv. |timeoutSeconds|Timeout for the list/watch call. |watch|Watch for changes to the described resources and return them as a stream of add, update, and remove notifications. Specify resourceVersion. |=== ==== Responses [cols=""1,5"", options=""header""] |=== |HTTP Code|Schema |200 OK|v1.Status |401 Unauthorized| |=== ==== Consumes * \\*/* ==== Produces * application/json * application/yaml * application/vnd.kubernetes.protobuf ",12065,False,2391.552672126306,median "[[flowableApps]] == Flowable applications Flowable provides several ui web applications to demonstrate and leverage the functionality provided by the Flowable project: * Flowable IDM: an Identity Management application that provides single sign-on authentication functionality for all the Flowable UI applications, and, for users with the IDM administrative privilege, it also provides functionality to manage users, groups and privileges. * Flowable Modeler: an application that allows users with modeler privileges to model processes, forms, decision tables and application definitions. * Flowable Task: a runtime task application that provides functionality to start process instances, edit task forms, complete tasks and query on tasks and process instances. * Flowable Admin: an administrative application that allows users with admin privilege to query the BPMN, DMN, form and content engines and provides several options to change process instances, tasks, jobs and so on. The admin application connects to the engines through the REST API that is deployed together with the Flowable Task app and the Flowable REST app. The Flowable IDM is required for all other apps to enable authentication. The WAR files for each app can be deployed to the same servlet container (such as Apache Tomcat), but can also be deployed on different servlet containers. Because the same cookie is used for authentication with each app, the apps need to run on the same domain. Flowable also provides the `flowable-rest.war` which contains the Flowable REST API. More about this can be read in the <> chapter. The apps are Spring Boot 2.0 based, which means that that the WAR files are actually executable and can be run as a normal standalone applications. See https://docs.spring.io/spring-boot/docs/current/reference/html/build-tool-plugins-maven-plugin.html#build-tool-plugins-maven-packaging[The Executable Jar Format] in the Spring Boot reference documentation. [[uiAppInstallation]] === Flowable UI Applications installation As mentioned before, all four UI apps can be deployed together on the same Tomcat server, and to get started this is probably the easiest approach. You can choose to only install the Modeler app, for example, but make sure the Flowable IDM app is always running/deployed as well. For this installation guide we'll describe the installation of all four apps to a Tomcat server. 1. Download a recent stable version of link:$$http://tomcat.apache.org$$[Apache Tomcat]. 2. Download the latest stable link:$$http://www.flowable.org/downloads.html$$[Flowable 6 version]. 3. Copy the flowable-admin.war, flowable-idm.war, flowable-modeler.war and flowable-task.war files from the Flowable distribution __wars__ folder to the Tomcat webapps folder. 4. Startup the Tomcat server by running the bin/startup.sh (Mac OS and Linux) or bin/startup.bat (Windows) script. 5. Open a web browser and go to link:$$http://localhost:8080/flowable-modeler$$[http://localhost:8080/flowable-modeler]. All Flowable UI apps should now be running with an H2 in-memory database and the following login screen should be shown in your web browser: image::images/flowable_idm_login_screen.png[align=""center""] By default, the Flowable IDM application will create an admin user that has privileges to all the Flowable UI apps. You can login with admin/test and the browser should redirect to the Flowable Modeler application: image::images/flowable_modeler_startup_screen.png[align=""center""] Since the UI apps are Spring Boot executable apps it is possible to run them as standalone applications without the need of an application server. Starting single application looks like: ``` java -jar flowable-idm.war ``` Usually, you will want to change the default H2 in-memory database configuration to a MySQL or Postgres (or other persistent database) configuration. You can do this per app by changing the application.properties file in the _WEB-INF/classes/_ directory of each app. However, it is easier to use the Spring Boot https://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-external-config.html[Externalized Configuration]. An example configuration can be found on link:$$https://github.com/flowable/flowable-engine/blob/master/modules/flowable-ui-task/flowable-ui-task-app/src/main/resources/flowable-default.properties$$[Github] To change the default configuration to MySQL the following changes are needed to the properties file: [source,linenums] ---- spring.datasource.driver-class-name=com.mysql.jdbc.Driver spring.datasource.url=jdbc:mysql://127.0.0.1:3306/flowable?characterEncoding=UTF-8 spring.datasource.username=flowable spring.datasource.password=flowable ---- This configuration will expect a flowable database to be present in the MySQL server and the UI apps will automatically generate the necessary database tables. For Postgres the following changes are necessary: [source,linenums] ---- spring.datasource.driver-class-name=org.postgresql.Driver spring.datasource.url=jdbc:postgresql://localhost:5432/flowable spring.datasource.username=flowable spring.datasource.password=flowable ---- In addition to changing the configuration, make sure the database driver is available on the classpath. Again, you could do this for every web application separately by adding the driver JAR file to the WEB-INF/lib folder, but you can also copy the JAR file once to the Tomcat lib folder. For MySQL and Postgres the database drivers can be downloaded from: * MySQL: link:$$https://dev.mysql.com/downloads/connector/j$$[https://dev.mysql.com/downloads/connector/j] * Postgres: link:$$https://jdbc.postgresql.org/$$[https://jdbc.postgresql.org/] When running the apps as standalone applications the database driver can be added by using the `loader.path` property. ``` java -Dloader.path=/location/to/your/driverfolder -jar flowable-idm.war ``` See the https://docs.spring.io/spring-boot/docs/current/reference/html/executable-jar.html#executable-jar-property-launcher-features[`PropertiesLauncher` Features] in the Spring Boot reference documentation for more information. === Flowable UI Applications Configurations As the Flowable UI apps are Spring Boot applications you can use all the properties Spring Boot provides. In order to provide custom configuration for the apps have a look at the https://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-external-config.html[Externalized Configuration] section of the Spring Boot documentation. [TIP] ----- You can also use YAML based properties. ----- .Common UI App Properties [cols=""4*"",options=""header""] |=============== |Property name |Old Property |Default value |Description |flowable.common.app.idm-url |idm.app.url |- |The URL to the IDM application, used for the user info and token info REST GET calls. It's also used as a fallback for the redirect url to the login page in the UI apps. |flowable.common.app.idm-redirect-url |idm.app.redirect.url |- |The redirect URL to the IDM application, used for the login redirect when the cookie isn't set or is invalid. |flowable.common.app.redirect-on-auth-success |app.redirect.url.on.authsuccess |- |The URL to which the redirect should occur after a successful authentication. |flowable.common.app.role-prefix |- |ROLE_ |The default role prefix that needs to be used by Spring Security. |flowable.common.app.tenant-id |- |- |The static tenant id used for the DefaultTenantProvider. The modeler app uses this to determine under which tenant id to store and publish models. When not provided, empty or only contains whitespace it defaults to the user's tenant id if available otherwise it uses no tenant id. |flowable.common.app.cache-login-tokens.max-age |cache.login-tokens.max.age |30 |The max age in seconds after which the entry should be invalidated. |flowable.common.app.cache-login-tokens.max-size |cache.login-tokens.max.size |2048 |The maximum number of entries that the cache should contain. |flowable.common.app.cache-login-users.max-age |cache.login-users.max.age |30 |The max age in seconds after which the entry should be invalidated. |flowable.common.app.cache-login-users.max-size |cache.login-users.max.size |2048 |The maximum number of entries that the cache should contain. |flowable.common.app.cache-users.max-age |cache.users.max.age |30 |The max age in seconds after which the entry should be invalidated. |flowable.common.app.cache-users.max-size |cache.users.max.size |2048 |The maximum number of entries that the cache should contain. |flowable.common.app.idm-admin.password |idm.admin.password |- |The password used for executing the REST calls (with basic auth) to the IDM REST services. Default is test. |flowable.common.app.idm-admin.user |idm.admin.user |admin |The username used for executing the REST calls (with basic auth) to the IDM REST services. Default is admin |flowable.rest.app.authentication-mode |rest.authentication.mode |verify-privilege |Configures the way user credentials are verified when doing a REST API call: 'any-user' : the user needs to exist and the password need to match. Any user is allowed to do the call (this is the pre 6.3.0 behavior) 'verify-privilege' : the user needs to exist, the password needs to match and the user needs to have the 'rest-api' privilege If nothing set, defaults to 'verify-privilege' |=============== Some of the old properties have been moved to be managed by the Flowable Spring Boot starter (or Spring Boot itself) .Old properties managed by the Flowable Spring Boot Starter [cols=""4*"",options=""header""] |=============== |Property name |Old Property |Default value |Description |flowable.async-executor-activate |engine.process.asyncexecutor.activate |true |Whether the async executor should be activated. |flowable.database-schema-update |engine.process.schema.update |true |The strategy that should be used for the database schema. |flowable.history-level |engine.process.history.level |- |The history level that needs to be used. |flowable.process.servlet.name |flowable.rest-api-servlet-name |Flowable BPMN Rest API |The name of the Process servlet. |flowable.process.servlet.path |flowable.rest-api-mapping |/process-api |The context path for the Process rest servlet. |flowable.content.storage.create-root |contentstorage.fs.create-root |true |If the root folder doesn't exist, should it be created? |flowable.content.storage.root-folder |contentstorage.fs.root-folder |- |Root folder location where content files will be stored, for example, task attachments or form file uploads. |flowable.idm.enabled |flowable.db-identity-used |true |Whether the idm engine needs to be started. |flowable.idm.password-encoder |security.passwordencoder |- |The type of the password encoder that needs to be used. |flowable.idm.ldap.base-dn |ldap.basedn |- |The base 'distinguished name' (DN) from which the searches for users and groups are started. Use 'user-base-dn' or 'group-base-dn' when needing to differentiate between user and group base DN. |flowable.idm.ldap.enabled |ldap.enabled |false |Whether to enable LDAP IDM Service. |flowable.idm.ldap.password |ldap.password |- |The password that is used to connect to the LDAP system. |flowable.idm.ldap.port |ldap.port |-1 |The port on which the LDAP system is running. |flowable.idm.ldap.server |ldap.server |- |The server host on which the LDAP system can be reached. For example 'ldap://localhost'. |flowable.idm.ldap.user |ldap.user |- |The user id that is used to connect to the LDAP system. |flowable.idm.ldap.attribute.email |ldap.attribute.email |- |Name of the attribute that matches the user email. This property is used when looking for an 'org.flowable.idm.api.User' object and the mapping between the LDAP object and the Flowable 'org.flowable.idm.api.User' object is done. |flowable.idm.ldap.attribute.first-name |ldap.attribute.firstname |- |Name of the attribute that matches the user first name. This property is used when looking for a 'org.flowable.idm.api.User' object and the mapping between the LDAP object and the Flowable 'org.flowable.idm.api.User' object is done. |flowable.idm.ldap.attribute.group-id |ldap.attribute.groupid |- |Name of the attribute that matches the group id. This property is used when looking for a 'org.flowable.idm.api.Group' object and the mapping between the LDAP object and the Flowable 'org.flowable.idm.api.Group' object is done. |flowable.idm.ldap.attribute.group-name |ldap.attribute.groupname |- |Name of the attribute that matches the group name. This property is used when looking for a 'org.flowable.idm.api.Group' object and the mapping between the LDAP object and the Flowable 'org.flowable.idm.api.Group' object is done. |flowable.idm.ldap.attribute.last-name |ldap.attribute.lastname |- |Name of the attribute that matches the user last name. This property is used when looking for a 'org.flowable.idm.api.User' object and the mapping between the LDAP object and the Flowable 'org.flowable.idm.api.User' object is done. |flowable.idm.ldap.attribute.user-id |ldap.attribute.userid |- |Name of the attribute that matches the user id. This property is used when looking for a 'org.flowable.idm.api.User' object and the mapping between the LDAP object and the Flowable 'org.flowable.idm.api.User' object is done. This property is optional and is only needed if searching for 'org.flowable.idm.api.User' objects using the Flowable API. |flowable.idm.ldap.cache.group-size |ldap.cache.groupsize |-1 |Allows to set the size of the 'org.flowable.ldap.LDAPGroupCache'. This is an LRU cache that caches groups for users and thus avoids hitting the LDAP system each time the groups of a user needs to be known. The cache will not be instantiated if the value is less then zero. By default set to -1, so no caching is done. Note that the group cache is instantiated on the 'org.flowable.ldap.LDAPIdentityServiceImpl'. As such, if you have a custom implementation of the 'org.flowable.ldap.LDAPIdentityServiceImpl', do not forget to add the group cache functionality. |flowable.idm.ldap.query.all-groups |ldap.query.groupall |- |The query that is executed when searching for all groups. |flowable.idm.ldap.query.all-users |ldap.query.userall |- |The query that is executed when searching for all users. |flowable.idm.ldap.query.groups-for-user |ldap.query.groupsforuser |- |The query that is executed when searching for the groups of a specific user. For example: `(&(objectClass=groupOfUniqueNames)(uniqueMember={0}))` Here, all the objects in LDAP with the class 'groupOfUniqueNames' and where the provided DN is a 'uniqueMember' are returned. As shown in the example, the user id is injected by the typical {@link java.text.MessageFormat}, ie by using _{0}_ If setting the query alone is insufficient for your specific LDAP setup, you can alternatively plug in a different `org.flowable.ldap.LDAPQueryBuilder`, which allows for more customization than only the query. |flowable.idm.ldap.query.user-by-full-name-like |ldap.query.userbyname |- |The query that is executed when searching for a user by full name. For example: `(&(objectClass=inetOrgPerson)(\\|({0}=**{1}**)({2}={3})))` Here, all the objects in LDAP with the class 'inetOrgPerson' and who have the matching first name or last name will be returned Several things will be injected in the expression: {0} : the first name attribute {1} : the search text {2} : the last name attribute {3} : the search text If setting the query alone is insufficient for your specific LDAP setup, you can alternatively plug in a different 'org.flowable.ldap.LDAPQueryBuilder', which allows for more customization than only the query. |flowable.idm.ldap.query.user-by-id |ldap.query.userbyid |- |The query that is executed when searching for a user by userId. For example: `(&(objectClass=inetOrgPerson)(uid={0}))` Here, all the objects in LDAP with the class 'inetOrgPerson' and who have the matching 'uid' attribute value will be returned. As shown in the example, the user id is injected by the typical {@link java.text.MessageFormat}, ie by using _{0}_ If setting the query alone is insufficient for your specific LDAP setup, you can alternatively plug in a different 'org.flowable.ldap.LDAPQueryBuilder', which allows for more customization than only the query. |flowable.mail.server.host |email.host |localhost |The host of the mail server. |flowable.mail.server.password |email.password |- |The password for the mail server authentication. |flowable.mail.server.port |email.port |1025 |The port of the mail server. |flowable.mail.server.ssl-port |email.ssl-port |1465 |The SSL port of the mail server. |flowable.mail.server.use-ssl |email.use-ssl |false |Sets whether SSL/TLS encryption should be enabled for the SMTP transport upon connection (SMTPS/POPS). |flowable.mail.server.use-tls |email.use-tls |false |Set or disable the STARTTLS encryption. |flowable.mail.server.username |email.username |- |The username that needs to be used for the mail server authentication. If empty no authentication would be used. |flowable.process.definition-cache-limit |flowable.process-definitions.cache.max |-1 |The maximum amount of process definitions available in the process definition cache. Per default it is -1 (all process definitions). |=============== .Old properties managed by Spring Boot [cols=""4*"",options=""header""] |=============== |Property name |Old Property |Default value |Description |spring.datasource.driver-class-name |datasource.driver |- |Fully qualified name of the JDBC driver. Auto-detected based on the URL by default. |spring.datasource.jndi-name |datasource.jndi.name |- |JNDI location of the datasource. Class, url, username & password are ignored when set. |spring.datasource.password |datasource.password |- |Login password of the database. |spring.datasource.url |datasource.url |- |JDBC URL of the database. |spring.datasource.username |datasource.username |- |Login username of the database. |spring.datasource.hikari.connection-test-query |datasource.preferred-test-query |- |The SQL query to be executed to test the validity of connections. |spring.datasource.hikari.connection-timeout |datasource.connection.timeout |- |The maximum number of milliseconds that a client will wait for a connection from the pool. If this time is exceeded without a connection becoming available, a SQLException will be thrown when getting a connection. |spring.datasource.hikari.idle-timeout |datasource.connection.idletimeout |- |The maximum amount of time (in milliseconds) that a connection is allowed to sit idle in the pool. Whether a connection is retired as idle or not is subject to a maximum variation of +30 seconds, and average variation of +15 seconds. A connection will never be retired as idle before this timeout. A value of 0 means that idle connections are never removed from the pool. |spring.datasource.hikari.max-lifetime |datasource.connection.maxlifetime |- |This property controls the maximum lifetime of a connection in the pool. When a connection reaches this timeout, even if recently used, it will be retired from the pool. An in-use connection will never be retired, only when it is idle will it be removed. |spring.datasource.hikari.maximum-pool-size |datasource.connection.maxpoolsize |- |The property controls the maximum size that the pool is allowed to reach, including both idle and in-use connections. Basically this value will determine the maximum number of actual connections to the database backend. When the pool reaches this size, and no idle connections are available, calls to getConnection() will block for up to connectionTimeout milliseconds before timing out. |spring.datasource.hikari.minimum-idle |datasource.connection.minidle |- |The property controls the minimum number of idle connections that HikariCP tries to maintain in the pool, including both idle and in-use connections. If the idle connections dip below this value, HikariCP will make a best effort to restore them quickly and efficiently. |spring.servlet.multipart.max-file-size |file.upload.max.size |10MB |Max file size. Values can use the suffixes ""MB"" or ""KB"" to indicate megabytes or kilobytes, respectively. |=============== .Not used old properties [cols=""2*"",options=""header""] |=============== |Old property |Description |datasource.jndi.resource-ref |Spring Boot does not support configuring JNDI resourceRef. Use entire resource reference in the name. |email.use-credentials |In case you don't want to use credentials, set the password and user to empty. |=============== [[flowableIDMApp]] === Flowable IDM application The Flowable IDM application is used by all other three Flowable web applications for authentication and authorization and is therefore required to be available when you want to run the Modeler, Task or Admin application. The Flowable IDM application is a simple identity management application and is targeted at providing single sign-on capabilities to the Flowable web applications, including providing a central place to define users, groups and privileges. The IDM application boots the IDM engine at startup and will create the identity tables as defined in the IDM engine in the datasource defined in the properties configuration. When the Flowable IDM application is deployed and started, it will check if there's a user available in the ACT_ID_USER table, and if not it will use the `flowable.common.app.idm-admin.user` property to create a new default admin user in this table. It will also add all available privileges in the Flowable project to the newly created admin user: * access-idm: provides the privilege to manage users, groups and privileges * access-admin: allows the user to login to the Flowable Admin application, manage the Flowable engines and access the Actuator endpoints of all the applications * access-modeler: enables access to the Flowable Modeler application * access-task: provides the privilege to login to the Flowable Task application * access-rest-api: allows the user to do call the REST API. Otherwise a 403 (forbidden) http status will be returned. Note that _flowable.rest.app.authentication-mode_ nees to be set to _verify-privilege_, which is the default. When logging in to link:$$http://localhost:8080/flowable-idm$$[http://localhost:8080/flowable-idm] with admin/test for the first time the following user overview screen is shown: image::images/flowable_idm_startup_screen.png[align=""center""] In this screen users can be added, removed and updated. The groups section can be used to create, delete and update groups. In the group details view you can also add and remove users to and from the group. The privilege screen allows you to add and remove privileges from users and groups: image::images/flowable_idm_privilege_screen.png[align=""center""] There's no option to define new privileges yet, but you can add and remove users and groups for the existing four privileges. This are the IDM UI App specific properties. .IDM UI App Properties [cols=""4*"",options=""header""] |=============== |Property name |Old Property |Default value |Description |flowable.idm.app.bootstrap |idm.bootstrap.enabled |true |Whether the IDM App needs to be bootstrapped. |flowable.idm.app.rest-enabled |rest.idm-app.enabled |true |Enables the REST API (this is not the REST api used by the UI, but an api that's available over basic auth authentication). |flowable.idm.app.admin.email |admin.email |- |The email of the admin user. |flowable.idm.app.admin.first-name |admin.firstname |- |The first name of the admin user. |flowable.idm.app.admin.last-name |admin.lastname |- |The last name of the admin user. |flowable.idm.app.admin.password |admin.password |- |The password for the admin user. |flowable.idm.app.admin.user-id |admin.userid |- |The id of the admin user. |flowable.idm.app.security.remember-me-key |security.rememberme.key |testKey |The hash key that is used by Spring Security to hash the password values in the applications. Make sure that you change the value of this property. |flowable.idm.app.security.user-validity-period |cache.users.recheck.period |30000 |How long should a user be cached before invalidating it in the cache for the cacheable CustomUserDetailsService. |flowable.idm.app.security.cookie.domain |security.cookie.domain |- |The domain for the cookie. |flowable.idm.app.security.cookie.max-age |security.cookie.max-age |2678400 |The max age of the security cookie in seconds. Default is 31 days. |flowable.idm.app.security.cookie.refresh-age |security.cookie.refresh-age |86400 |The refresh age of the cookie in seconds. Default is 1 day. |=============== In addition to the default identity tables, the IDM application can also be configured to use an LDAP server. To connect to a LDAP server, additional properties in the application.properties file (or any other way of configuring the application) are needed: [source,linenums] ---- # # LDAP # flowable.idm.ldap.enabled=true flowable.idm.ldap.server=ldap://localhost flowable.idm.ldap.port=10389 flowable.idm.ldap.user=uid=admin, ou=system flowable.idm.ldap.password=secret flowable.idm.ldap.base-dn=o=flowable flowable.idm.ldap.query.user-by-id=(&(objectClass=inetOrgPerson)(uid={0})) flowable.idm.ldap.query.user-by-full-name-like=(&(objectClass=inetOrgPerson)(|({0}=*{1}*)({2}=*{3}*))) flowable.idm.ldap.query.all-users=(objectClass=inetOrgPerson) flowable.idm.ldap.query.groups-for-user=(&(objectClass=groupOfUniqueNames)(uniqueMember={0})) flowable.idm.ldap.query.all-groups=(objectClass=groupOfUniqueNames) flowable.idm.ldap.query.group-by-id=(&(objectClass=groupOfUniqueNames)(uniqueId={0})) flowable.idm.ldap.attribute.user-id=uid flowable.idm.ldap.attribute.first-name=cn flowable.idm.ldap.attribute.last-name=sn flowable.idm.ldap.attribute.group-id=cn flowable.idm.ldap.attribute.group-name=cn flowable.idm.ldap.cache.group-size=10000 flowable.idm.ldap.cache.group-expiration=180000 ---- When the `flowable.idm.ldap.enabled` property is set to true, the IDM app will expect the other LDAP properties to have been filled-in. In this example configuration the server configuration + LDAP queries for the Apache Directory Server are provided. For other LDAP servers, like Active Directory, other configuration values are needed. When LDAP is configured, authentication and group retrieval for a user will be done through the LDAP server. Only privileges will still be retrieved from the Flowable identity tables. So make sure each LDAP user has the correct privileges defined in the IDM application. If the IDM application is booted with LDAP configuration the bootstrap logic will check if there are already privileges present in the Flowable identity tables. If there are no privileges (only when booting the first time), the 4 default privileges will be created and the `flowable.idm.app.admin.user-id` property value (from application.properties or configured in the environment) will be used as the user id to get all 4 privileges. So make sure that the `flowable.idm.app.admin.user-id` property value is set to a valid LDAP user, otherwise nobody will be able to login to any of the Flowable UI apps. [[flowableModelerApp]] === Flowable Modeler application The Flowable Modeler application can be used to model BPMN processes, DMN decision table, Form definitions and create app definitions. The BPMN modeler uses the same Oryx and Angular foundation as in Flowable 5, but the functionality has now been moved into a separate Modeler application. When using the Flowable Modeler application, make sure the Flowable IDM application is deployed and running as well (for authentication and authorization purposes). When you login to the Modeler application (link:$$http://localhost:8080/flowable-modeler$$[http://localhost:8080/flowable-modeler]) with your user (or the default admin/test user), you will see the process overview screen. From here you can start creating new BPMN process models by clicking on the Create Process or Import Process button. image::images/flowable_modeler_createmodel_popup.png[align=""center"", width=""600""] When creating a process model (but also any other model), it's important to think carefully about the model key value. The model key is a unique identifier for the model across the full model repository. If you choose a model key that already exists in the model repository, an error message is shown and the model is not saved. After creating the model with the popup, the BPMN modeling canvas is shown. The BPMN editor is very similar to the Flowable 5 BPMN editor that was part of the Explorer application. All BPMN elements supported by the Flowable engine are available to be used in the design of a process model. image::images/flowable_modeler_design_screen.png[align=""center""] The BPMN editor is divided into 4 parts: * Palette: the palette of BPMN elements available to design a process model * Toolbar: actions to change the model canvas, such as zooming, layout and saving a model * Model canvas: the modeling canvas on which to drag and drop BPMN elements and design the process model * Properties panel: the properties for the main process model if no element is select and otherwise the properties of the selected BPMN element For a User task element there's a _Referenced form_ property in the properties panel. If you select this property, a popup is opened where you can select a form definition from the repository or create a new form. When creating a new form, a similar create dialog to the process model create dialog is presented. After filling in the name and form model key, the form editor is opened. image::images/flowable_modeler_formdesign_screen.png[align=""center""] Form fields can be dragged from the form palette on to the form canvas. In this example, a name textfield, two date fields and a remarks multiline textfield are added to the form canvas. When editing a form field, the label, id, required status and placeholder can be filled in. image::images/flowable_modeler_editfield_popup.png[align=""center"", width=""600""] The id field is an important value, because a process variable will be created with the form field value using the id property value. When filling in the label property, the id property is automatically filled. If needed, you can also provide the id property value yourself by checking the override id checkbox. After saving the form model and closing the form editor, you are automatically navigated back to the process model (when the form editor was opened via the BPMN editor). When selecting the User task element again and clicking on the _Referenced form_ property you will see that the newly created form definition is now attached to the User task. When clicking on the _Form_ tab in the header of the Modeler application, all form definitions available in the model repository are shown. image::images/flowable_modeler_formoverview_screen.png[align=""center""] You can preview every form definition by opening the details view of a form definition. In the details view, the form name, key and description can be edited and the history of form models is available. You can also duplicate the form definition to create a new form definition with the same form fields. Now let's open the vacation request process model in the BPMN editor again and add a Script task to the process model, that will calculate the number of days between the vacation start and end dates. Click on the _Script format_ property and fill in a value of _groovy_ to instruct the Flowable engine to use the Groovy scripting engine. Now click on the _Script_ property and fill in the script that calculates the number of days. image::images/flowable_modeler_script_popup.png[align=""center"", width=""600""] Now we have a _amountOfVacationDays_ process variable we can add a Decision task to the process model. A decision task can be used to execute a DMN decision table in the Flowable DMN engine. Through the _Decision table reference_ property, a new decision table model can be created and the DMN editor is opened. image::images/flowable_modeler_dmneditor_screen.png[align=""center""] The DMN editor provides a table editor with input columns, where input conditions can be defined with the process variables available in the process context, and output columns, where output variable values can be defined. In this very simple example there's one input column using the _amountOfVacationDays_ variable that checks if it's less than 10 or higher or equal to 10. When the amount of days is less than 10, an output variable _managerApprovalNeeded_ is returned with value false, and otherwise a value of true is returned. You can define multiple input columns and have multiple input conditions per rule. It's also possible to leave an input column empty, which means that it's evaluated to true for that part of the rule. You can define one or multiple output variables. Another important part of the DMN decision table definition is the hit policy. Currently, Flowable supports the First and Any hit policy. With the First hit policy, when the first rule is found that evaluates to true the DMN execution will stop and its output variables are returned. For the Any hit policy, all rules will be executed and the output variables for the last rule that evaluates to true are returned. When the DMN editor is saved and closed, the Modeler application navigates back to the BPMN editor and the newly created DMN decision table is now attached to the Decision task. The decision task will be generated in the BPMN XML like; [source,xml,linenums] ---- ---- With the _managerApprovalNeeded_ variable available in the process instance context, we can now create an exclusive gateway with a sequence flow condition that evaluates the calculated value of the DMN Engine. image::images/flowable_modeler_sequenceflowcondition_popup.png[align=""center"", width=""500""] The full BPMN process model now looks like this: image::images/flowable_modeler_vacationrequest_screen.png[align=""center""] With the process model completed, we can now create an app definition that combines one or more process models with all their associated models (for example, decision tables and form definitions) into a single artifact. An app definition can be exported as a BAR file (zip format) that can be deployed on the Flowable engine. When creating a vacation request app definition, the app editor will look something like the screen below. image::images/flowable_modeler_appeditor_screen.png[align=""center""] In the app editor, an icon and a theme color can be selected that will be used in the Flowable Task application to show the application in the dashboard. The important step is to add the vacation request process model, and by selecting the process model, automatically include any form definitions and DMN decision tables. image::images/flowable_modeler_modelselection_popup.png[align=""center""] A process model can be selected by clicking on the model thumbnail. When one or more models are selected, you can close the popup, save the app definition and close it. When navigating to the details view of the newly created vacation request app definition, the following details screen is shown: image::images/flowable_modeler_appdetails_screen.png[align=""center""] From this view, you can download the app definition in two different formats. The first download button (with the arrow pointing downwards) can be used to download the app definition with the JSON model files for each included model. This makes it easy to share app definitions between different Flowable Modeler applications. The second download button (with the arrow point to upper right) will provide a BAR file of the app definition models, which can be deployed on the Flowable engine. In the BAR file, only the deployable artifacts are included, such as the BPMN 2.0 XML file and the DMN XML file, and not the JSON model files. All files in a BAR file deployed on a Flowable engine are stored in the database, so therefore only the deployable files are included. From the app definition details view, you can also _Publish_ the app definition directly to the Flowable engine. The Flowable Modeler uses the URL defined in the application.properties file with the _flowable.modeler.app.deployment-api-url_ property key. By default, the deployment URL is configured so the app definition will be deployed on the Flowable Task application when it's running. However, this can be changed to use the Flowable REST application, for example. Make sure the Flowable Task application is running and click on the _Publish_ button. The app definition is now deployed as a BAR file to the Flowable Task application. This are the Modeler UI App specific properties. .Modeler UI App Properties [cols=""4*"",options=""header""] |=============== |Property name |Old Property |Default value |Description |flowable.modeler.app.data-source-prefix |datasource.prefix |- |The prefix for the database tables. |flowable.modeler.app.deployment-api-url |deployment.api.url |http://localhost:8080/flowable-task/app-api |The root URI to the REST services of the Flowable engine, used by the Flowable Modeler application to deploy the application definition BAR file to the engine. Default url for the Flowable Task application is http://localhost:8080/flowable-task/app-api |flowable.modeler.app.rest-enabled |rest.modeler-app.enabled |true |Enables the REST API (this is not the REST api used by the UI, but an api that's available over basic auth authentication). |=============== [[flowableTaskApp]] === Flowable Task application The Flowable Task application is the runtime application of the Flowable project and includes the Flowable BPMN, DMN, Form and Content engines by default. With the Flowable Task application, new process instances can be started, tasks can be completed, task forms can be rendered and so on. In the previous section, the vacation request app definition was deployed on the Flowable Task application REST API, and through that deployed on the Flowable engine. If you look in the Flowable database, you can see a new deployment entry has been added to the ACT_RE_DEPLOYMENT table for the BPMN Engine. Also, new entries haven been created in the ACT_DMN_DEPLOYMENT and ACT_FO_FORM_DEPLOYMENT tables for the DMN and Form engines. On the dashboard on link:$$http://localhost:8080/flowable-task$$[http://localhost:8080/flowable-task], you can see a vacation request app in addition to the default Task app, and any other apps that have been deployed to the Flowable engine already. image::images/flowable_task_dashboard_screen.png[align=""center""] When clicking on the vacation request app, the task list for the logged-in user is shown (which is probably empty for now). image::images/flowable_task_tasklist_screen.png[align=""center""] When clicking on the _Processes_ tab you can choose to start a new process instance by clicking on the _Start a process_ button. The list of available process definitions within the context of this app definition is now displayed. In the general Task app this works in a similar way, but in the Task app, all process definitions deployed on the Flowable engine are shown. After selecting the vacation request process definition, the _Start process_ button can be clicked to start a new vacation request process instance. The Flowable Task application automatically navigates to the process instance details view. You can see the _Provide vacation information_ task is active and, for example, comments can be added and the process instance state can be shown diagrammatically using the _Show diagram_ button. image::images/flowable_task_processdetails_screen.png[align=""center""] When navigating to the task list, you can also see the _Provide vacation information_ task listed there as well. The task details are shown in this view, with the vacation info form being rendered. You can also switch to the details view by clicking on the _Show details_ button. In the details view, comments can be added, users can involved in the task and attachments can be added to the task. You can also change the due date and the assignee of a task. image::images/flowable_task_taskdetails_screen.png[align=""center""] Let's fill in the form and complete the task. First, select a start date and end date that have more than 10 days in between, so we can validate that a _Manager approval_ task is being generated. After filling in the vacation info form and clicking the _Complete_ button, the Flowable task app navigates directly to the _Manager approval_ task view. When you also complete this task (without a task form), the process instance is completed. When navigating to the _Processes_ tab and clicking on the _Showing running processes_ section, you can select an option to show completed process instances. The list of completed process instances is now shown and when clicking on the just completed vacation request process you can see the two completed tasks. image::images/flowable_task_processhistory_screen.png[align=""center""] The completed form of each task is stored in the ACT_FO_FORM_INSTANCE table of the Flowable Form engine. So it's possible to look at the values of each completed form when you navigate to the completed task. image::images/flowable_task_completedform_screen.png[align=""center""] Make sure to switch back to showing running processes instead of the completed ones, otherwise you won't see newly started process instances. You can also filter tasks in the task list view. There are options to search on the name of a task, the task state, only tasks for a specific process definition and change the assignment filter. image::images/flowable_task_taskfilter_screen.png[align=""center"", width=""400""] By default, the assignment filter is set to _Tasks where I am involved_. This doesn't show the tasks where you are a candidate, such as tasks that are available to a specific candidate group before they are assigned to a specific person. To show candidate tasks you can select the _Tasks where I am one of the candidates_ assignment filter option. This are the Task UI App specific properties. .Task UI App Properties [cols=""4*"",options=""header""] |=============== |Property name |Old Property |Default value |Description |flowable.experimental.debugger.enabled |debugger.enabled |false |Whether the process debugger should be enabled. |flowable.task.app.rest-enabled |rest.task-app.enabled |true |Enables the REST API (this is not the REST api used by the UI, but an api that's available over basic auth authentication). |flowable.form-field-validation-enabled | |false |Enable form field validation after form submission on the engine side. |=============== [[flowableAdminApp]] === Flowable Admin application The fourth UI application the Flowable project provides is the Flowable Admin application. This application provides ways to, for example, query deployments in the BPMN, DMN and Form Engines, but also shows the active state of a process instance with its active tasks and process variables. It also provides actions to assign a task to a different assignee and to complete an active task. The Flowable Admin application uses the REST API to communicate with the Flowable engines. By default, it is configured to connect to the Flowable Task REST API, but you can easily change this to use the Flowable REST app REST API instead. When going to link:$$http://localhost:8080/flowable-admin$$[http://localhost:8080/flowable-admin], the configuration screen is shown (which is also available by clicking on the arrow at the top right near the Flowable logo). image:images/flowable_admin_configuration_screen.png[align=""center""] For each engine, the REST endpoint can be configured with the basic authentication values. The configuration is done per engine, because it's possible to, for example, deploy the DMN Engine on a separate server from the BPMN Engine. When the configuration is defined with the correct values, the _Process Engine_ can be selected to administer the Flowable BPMN engine. By default, the deployments of the Flowable BPMN engine are shown. image::images/flowable_admin_deployments_screen.png[align=""center""] You can filter the deployments based on name and tenant identifier. In this view, it's also possible to deploy a new BPMN XML file or BAR file to the Flowable engine. When clicking on one of the deployments, the deployment details view is shown. image::images/flowable_admin_deploymentdetails_screen.png[align=""center""] More details of a deployment are shown here and also the process definitions that are part of this deployment on which you click to get more details. It's also possible to delete a deployment here. When you want to delete a deployed app definition, this is also the way to delete the app definition from the Flowable Task app dashboard. When clicking on one of the process definitions, the process definition details view is shown. image::images/flowable_admin_processdefinitiondetails_screen.png[align=""center""] In the process definition details view, the first page of process instances is shown, together with optional decision table definitions and form definitions that are used in the process definition. For the vacation request process definition, there's one connected decision table and one connected form definition. Clicking on the decision table definition navigates the Flowable Admin application to the DMN engine. You can always navigate back to the Process engine by clicking on the _Parent Deployment ID_ link. In addition to the deployments and definitions, you can also query on process instances, tasks, jobs and event subscriptions in the Process engine. The views all work in a similar way to what's already been described. This are the Admin UI App specific properties .Admin UI App Properties [cols=""4*"",options=""header""] |=============== |Property name |Old Property |Default value |Description |flowable.admin.app.data-source-prefix |datasource.prefix | |The prefix for the database tables. |flowable.admin.app.security.encryption.credentials-i-v-spec |security.encryption.credentials-i-v-spec |- |The string that needs to be used to create an IvParameterSpec object using it's the bytes. |flowable.admin.app.security.encryption.credentials-secret-spec |security.encryption.credentials-secret-spec |- |The string that needs to be used to create a SecretKeySpec using it's bytes. |flowable.admin.app.security.preemptive-basic-authentication | |false |Perform a preemptive basic authentication when issuing requests to the flowable REST API. **NB:** This is an experimental property and might be removed without notice. |=============== In addition to these properties, the Flowable admin application has a few more properties. The full content of the properties file can be viewed on {sc-flowable-ui-admin}/flowable-ui-admin-app/src/main/resources/application.properties[Github]. The additional properties are mainly used for defining the initial values for the REST endpoints for the different engines. The Admin application uses the initial values to make a connection to the Flowable engines, but the values can be overridden in the Admin application configuration view and these values are stored in the __ACT\\_ADM\\_SERVER\\_CONFIG__ table. An example of the BPMN Engine REST properties is shown below: [source,linenums] ---- flowable.admin.app.server-config.process.name=Flowable Process app flowable.admin.app.server-config.process.description=Flowable Process REST config flowable.admin.app.server-config.process.server-address=http://localhost flowable.admin.app.server-config.process.port=8080 flowable.admin.app.server-config.process.context-root=flowable-task flowable.admin.app.server-config.process.rest-root=process-api flowable.admin.app.server-config.process.user-name=admin flowable.admin.app.server-config.process.password=test ---- These values can be used when the Flowable Task app (with all the Flowable engines included) is managed by the Flowable Admin application. .Admin UI App Properties managed by Spring Boot [cols=""2*"",options=""header""] |=============== |Old property |Description |message.reloading.enabled |Using Spring Boot MessageSourceAutoConfiguration. Set the duration with `spring.messages.cache-duration`. |=============== === Internationalization The Flowable UI apps support internationalization (i18n). The project maintains the English translations. It is however possible to provide your own translation files in order to support other languages. The link:$$https://github.com/angular-translate/angular-translate[Angular Translate] library tries to load a specific translation file based on the browser's locale located in the _i18n_ folder (present in each UI module). When a matching translation file cannot be loaded the framework will fallback to the English translation. Mapping multiple browser locale keys to specific translations additional configuration can be provided (located in the Angular app config); [source,linenums] ---- // Initialize angular-translate $translateProvider.useStaticFilesLoader({ prefix: './i18n/', suffix: '.json' }) /* This can be used to map multiple browser language keys to a angular translate language key. */ // .registerAvailableLanguageKeys(['en'], { // 'en-*': 'en' // }) .useCookieStorage() .useSanitizeValueStrategy('sanitizeParameters') .uniformLanguageTag('bcp47') .determinePreferredLanguage(); ---- For example; your browser is configured for English (United States) and provides the language key _en-US_. Without the mapping Angular Translate will try to fetch the corresponding translation file _en-US.json_. (If this is not available it will fallback to 'en' and load the _en.json_ translation file) By uncommenting the _.registerAvailableLanguageKeys_ block you can map _en-US_ (and all other _en_ language keys) to the _en.json_ language file. === Production ready endpoints The https://docs.spring.io/spring-boot/docs/current/reference/html/production-ready-endpoints.html[Production ready endpoints] from Spring Boot are present for all applications. To have an overview of all the available Endpoints have a look at the https://docs.spring.io/spring-boot/docs/current/actuator-api/html/[Actuator Web API Documentation]. This properties are set per default: [source,linenums] ----- # Expose all actuator endpoints to the web # They are exposed, but only authenticated users can see /info and /health abd users with access-admin can see the others management.endpoints.web.exposure.include=* # Full health details should only be displayed when a user is authorized management.endpoint.health.show-details=when_authorized # Only users with role access-admin can access full health details management.endpoint.health.roles=access-admin ----- The security is configured in such way that the `info` and `health` endpoint are exposed to all authenticated users. Full details of the `health` endpoint can only be seen by users with the privilege `access-admin`. In case you want to change that you need to configure `management.endpoint.health.show-details`. All the rest of the endpoints are accessing only to users with the `access-admin` privilege. [[custom-bean-deployment]] === Custom bean deployment There are multiple ways of providing custom beans to the Flowable applications. [[custom-bean-deployment-spring-boot-auto]] ==== Using Spring Boot auto configuration The Flowable applications are Spring Boot 2 applications. Which means that normal Spring Boot auto configuration can be used to make the beans to Flowable. This can be done in the following manner ``` package com.your.own.package.configuration; @Configuration @AutoConfigureOrder(Ordered.LOWEST_PRECEDENCE) // Makes sure that this configuration will be processed last by Spring Boot @ConditionalOnBean(type = ""org.flowable.engine.ProcessEngine"") // The configuration will only be used when the ProcessEngine bean is present public class YourOwnConfiguration { @Configuration @ComponentScan (""com.your.own.package.beans"") public static class ComponentScanConfiguration { // This class is needed in order to conditionally perform the component scan (i.e. when the ProcessEngine bean is present) // It is an optional class, in case you don't need component scanning then you don't need to do this } @Bean public CustomBean customBean() { // create your bean } @Bean public EngineConfigurationConfigurer customProcessEngineConfigurationConfigurer() { return engineConfiguration -> { // You can use this to add extra configuration to the process engine } } } ``` Note that when using Spring Boot the configuration class can be under your own package and not under some Flowable package. In order to make this class an auto configuration class a file named `spring.factories` should be created in the `META-INF` folder of your jar. In this file you should add ``` org.springframework.boot.autoconfigure.EnableAutoConfiguration=\\ com.your.own.package.configuration.YourOwnCustomConfiguration ``` In order to use this approach you would need to include your jar in the `WEB-INF/lib` folder of the exploded war. Placing this jar in the lib folder of the servlet container (e.g. Tomcat) is not going to work due to the way Spring proxies the `@Configuration` classes. [[custom-bean-deployment-component-scan]] ==== Component scan Another way to provide custom Spring beans to the Flowable engine is to put them under a certain package and have the Flowable application component scan that package. Based on the used application this package is different: * `org.flowable.rest.app` for the `flowable-rest.war` * `org.flowable.ui.task.application` for the `flowable-task.war` The custom beans can be located in a single JAR and this jar should be present on the classpath when the applications are starting up. Depending where there JAR is placed, the lib folder of the servlet container (e.g. Tomcat) or the `WEB-INF/lib` folder of the exploded war, there are different possibilities. When using the lib folder of the servlet container then the created classes should be self contained, i.e. they should only use classes from within the jar. You can use any of the Spring `@Component` annotations (with the exception of `@Configuration`). The reason for not being able to use `@Configuration` classes is the fact that each configuration class is proxied by Spring with the help of the `ConfigurationClassPostProcessor`. However, the classloader loading the `@Configuration` class does not have access to the needed classes by Spring. When including the jar in the `WEB-INF/lib` folder of the exploded war then `@Configuration` classes and dependencies to other jars is possible. [[custom-bean-deployment-own-spring-boot]] ==== Creating your own Spring Boot application This approach is the most flexible and most powerful approach of all. In order to follow this approach have a look at the <> section of this documentation.",12282,False,2072.059049045821,median "[[channel]] === Message Channels While the `Message` plays the crucial role of encapsulating data, it is the `MessageChannel` that decouples message producers from message consumers. [[channel-interfaces]] ==== The MessageChannel Interface Spring Integration's top-level `MessageChannel` interface is defined as follows: ==== [source,java] ---- public interface MessageChannel { boolean send(Message message); boolean send(Message message, long timeout); } ---- ==== When sending a message, the return value is `true` if the message is sent successfully. If the send call times out or is interrupted, it returns `false`. [[channel-interfaces-pollablechannel]] ===== `PollableChannel` Since message channels may or may not buffer messages (as discussed in the <<./overview.adoc#overview,Spring Integration Overview>>), two sub-interfaces define the buffering (pollable) and non-buffering (subscribable) channel behavior. The following listing shows the definition of the `PollableChannel` interface: ==== [source,java] ---- public interface PollableChannel extends MessageChannel { Message receive(); Message receive(long timeout); } ---- ==== As with the send methods, when receiving a message, the return value is null in the case of a timeout or interrupt. [[channel-interfaces-subscribablechannel]] ===== `SubscribableChannel` The `SubscribableChannel` base interface is implemented by channels that send messages directly to their subscribed `MessageHandler` instances. Therefore, they do not provide receive methods for polling. Instead, they define methods for managing those subscribers. The following listing shows the definition of the `SubscribableChannel` interface: ==== [source,java] ---- public interface SubscribableChannel extends MessageChannel { boolean subscribe(MessageHandler handler); boolean unsubscribe(MessageHandler handler); } ---- ==== [[channel-implementations]] ==== Message Channel Implementations Spring Integration provides different message channel implementations. The following sections briefly describe each one. [[channel-implementations-publishsubscribechannel]] ===== `PublishSubscribeChannel` The `PublishSubscribeChannel` implementation broadcasts any `Message` sent to it to all of its subscribed handlers. This is most often used for sending event messages, whose primary role is notification (as opposed to document messages, which are generally intended to be processed by a single handler). Note that the `PublishSubscribeChannel` is intended for sending only. Since it broadcasts to its subscribers directly when its `send(Message)` method is invoked, consumers cannot poll for messages (it does not implement `PollableChannel` and therefore has no `receive()` method). Instead, any subscriber must itself be a `MessageHandler`, and the subscriber's `handleMessage(Message)` method is invoked in turn. Prior to version 3.0, invoking the `send` method on a `PublishSubscribeChannel` that had no subscribers returned `false`. When used in conjunction with a `MessagingTemplate`, a `MessageDeliveryException` was thrown. Starting with version 3.0, the behavior has changed such that a `send` is always considered successful if at least the minimum subscribers are present (and successfully handle the message). This behavior can be modified by setting the `minSubscribers` property, which defaults to `0`. NOTE: If you use a `TaskExecutor`, only the presence of the correct number of subscribers is used for this determination, because the actual handling of the message is performed asynchronously. [[channel-implementations-queuechannel]] ===== `QueueChannel` The `QueueChannel` implementation wraps a queue. Unlike the `PublishSubscribeChannel`, the `QueueChannel` has point-to-point semantics. In other words, even if the channel has multiple consumers, only one of them should receive any `Message` sent to that channel. It provides a default no-argument constructor (providing an essentially unbounded capacity of `Integer.MAX_VALUE`) as well as a constructor that accepts the queue capacity, as the following listing shows: ==== [source,java] ---- public QueueChannel(int capacity) ---- ==== A channel that has not reached its capacity limit stores messages in its internal queue, and the `send(Message)` method returns immediately, even if no receiver is ready to handle the message. If the queue has reached capacity, the sender blocks until room is available in the queue. Alternatively, if you use the send method that has an additional timeout parameter, the queue blocks until either room is available or the timeout period elapses, whichever occurs first. Similarly, a `receive()` call returns immediately if a message is available on the queue, but, if the queue is empty, then a receive call may block until either a message is available or the timeout, if provided, elapses. In either case, it is possible to force an immediate return regardless of the queue's state by passing a timeout value of 0. Note, however, that calls to the versions of `send()` and `receive()` with no `timeout` parameter block indefinitely. [[channel-implementations-prioritychannel]] ===== `PriorityChannel` Whereas the `QueueChannel` enforces first-in-first-out (FIFO) ordering, the `PriorityChannel` is an alternative implementation that allows for messages to be ordered within the channel based upon a priority. By default, the priority is determined by the `priority` header within each message. However, for custom priority determination logic, a comparator of type `Comparator>` can be provided to the `PriorityChannel` constructor. [[channel-implementations-rendezvouschannel]] ===== `RendezvousChannel` The `RendezvousChannel` enables a ""`direct-handoff`"" scenario, wherein a sender blocks until another party invokes the channel's `receive()` method. The other party blocks until the sender sends the message. Internally, this implementation is quite similar to the `QueueChannel`, except that it uses a `SynchronousQueue` (a zero-capacity implementation of `BlockingQueue`). This works well in situations where the sender and receiver operate in different threads, but asynchronously dropping the message in a queue is not appropriate. In other words, with a `RendezvousChannel`, the sender knows that some receiver has accepted the message, whereas with a `QueueChannel`, the message would have been stored to the internal queue and potentially never received. TIP: Keep in mind that all of these queue-based channels are storing messages in-memory only by default. When persistence is required, you can either provide a 'message-store' attribute within the 'queue' element to reference a persistent `MessageStore` implementation or you can replace the local channel with one that is backed by a persistent broker, such as a JMS-backed channel or channel adapter. The latter option lets you take advantage of any JMS provider's implementation for message persistence, as discussed in <<./jms.adoc#jms,JMS Support>>. However, when buffering in a queue is not necessary, the simplest approach is to rely upon the `DirectChannel`, discussed in the next section. The `RendezvousChannel` is also useful for implementing request-reply operations. The sender can create a temporary, anonymous instance of `RendezvousChannel`, which it then sets as the 'replyChannel' header when building a `Message`. After sending that `Message`, the sender can immediately call `receive` (optionally providing a timeout value) in order to block while waiting for a reply `Message`. This is very similar to the implementation used internally by many of Spring Integration's request-reply components. [[channel-implementations-directchannel]] ===== `DirectChannel` The `DirectChannel` has point-to-point semantics but otherwise is more similar to the `PublishSubscribeChannel` than any of the queue-based channel implementations described earlier. It implements the `SubscribableChannel` interface instead of the `PollableChannel` interface, so it dispatches messages directly to a subscriber. As a point-to-point channel, however, it differs from the `PublishSubscribeChannel` in that it sends each `Message` to a single subscribed `MessageHandler`. In addition to being the simplest point-to-point channel option, one of its most important features is that it enables a single thread to perform the operations on ""`both sides`"" of the channel. For example, if a handler subscribes to a `DirectChannel`, then sending a `Message` to that channel triggers invocation of that handler's `handleMessage(Message)` method directly in the sender's thread, before the `send()` method invocation can return. The key motivation for providing a channel implementation with this behavior is to support transactions that must span across the channel while still benefiting from the abstraction and loose coupling that the channel provides. If the `send()` call is invoked within the scope of a transaction, the outcome of the handler's invocation (for example, updating a database record) plays a role in determining the ultimate result of that transaction (commit or rollback). NOTE: Since the `DirectChannel` is the simplest option and does not add any additional overhead that would be required for scheduling and managing the threads of a poller, it is the default channel type within Spring Integration. The general idea is to define the channels for an application, consider which of those need to provide buffering or to throttle input, and modify those to be queue-based `PollableChannels`. Likewise, if a channel needs to broadcast messages, it should not be a `DirectChannel` but rather a `PublishSubscribeChannel`. Later, we show how each of these channels can be configured. The `DirectChannel` internally delegates to a message dispatcher to invoke its subscribed message handlers, and that dispatcher can have a load-balancing strategy exposed by `load-balancer` or `load-balancer-ref` attributes (mutually exclusive). The load balancing strategy is used by the message dispatcher to help determine how messages are distributed amongst message handlers when multiple message handlers subscribe to the same channel. As a convenience, the `load-balancer` attribute exposes an enumeration of values pointing to pre-existing implementations of `LoadBalancingStrategy`. A `round-robin` (load-balances across the handlers in rotation) and `none` (for the cases where one wants to explicitly disable load balancing) are the only available values. Other strategy implementations may be added in future versions. However, since version 3.0, you can provide your own implementation of the `LoadBalancingStrategy` and inject it by using the `load-balancer-ref` attribute, which should point to a bean that implements `LoadBalancingStrategy`, as the following example shows: A `FixedSubscriberChannel` is a `SubscribableChannel` that only supports a single `MessageHandler` subscriber that cannot be unsubscribed. This is useful for high-throughput performance use-cases when no other subscribers are involved and no channel interceptors are needed. ==== [source,xml] ---- ---- ==== Note that the `load-balancer` and `load-balancer-ref` attributes are mutually exclusive. The load-balancing also works in conjunction with a boolean `failover` property. If the `failover` value is true (the default), the dispatcher falls back to any subsequent handlers (as necessary) when preceding handlers throw exceptions. The order is determined by an optional order value defined on the handlers themselves or, if no such value exists, the order in which the handlers subscribed. If a certain situation requires that the dispatcher always try to invoke the first handler and then fall back in the same fixed order sequence every time an error occurs, no load-balancing strategy should be provided. In other words, the dispatcher still supports the `failover` boolean property even when no load-balancing is enabled. Without load-balancing, however, the invocation of handlers always begins with the first, according to their order. For example, this approach works well when there is a clear definition of primary, secondary, tertiary, and so on. When using the namespace support, the `order` attribute on any endpoint determines the order. NOTE: Keep in mind that load-balancing and `failover` apply only when a channel has more than one subscribed message handler. When using the namespace support, this means that more than one endpoint shares the same channel reference defined in the `input-channel` attribute. Starting with version 5.2, when `failover` is true, a failure of the current handler together with the failed message is logged under `debug` or `info` if configured respectively. [[executor-channel]] ===== `ExecutorChannel` The `ExecutorChannel` is a point-to-point channel that supports the same dispatcher configuration as `DirectChannel` (load-balancing strategy and the `failover` boolean property). The key difference between these two dispatching channel types is that the `ExecutorChannel` delegates to an instance of `TaskExecutor` to perform the dispatch. This means that the send method typically does not block, but it also means that the handler invocation may not occur in the sender's thread. It therefore does not support transactions that span the sender and receiving handler. CAUTION: The sender can sometimes block. For example, when using a `TaskExecutor` with a rejection policy that throttles the client (such as the `ThreadPoolExecutor.CallerRunsPolicy`), the sender's thread can execute the method any time the thread pool is at its maximum capacity and the executor's work queue is full. Since that situation would only occur in a non-predictable way, you should not rely upon it for transactions. [[flux-message-channel]] ===== `FluxMessageChannel` The `FluxMessageChannel` is an `org.reactivestreams.Publisher` implementation for `""sinking""` sent messages into an internal `reactor.core.publisher.Flux` for on demand consumption by reactive subscribers downstream. This channel implementation is neither a `SubscribableChannel`, nor a `PollableChannel`, so only `org.reactivestreams.Subscriber` instances can be used to consume from this channel honoring back-pressure nature of reactive streams. On the other hand, the `FluxMessageChannel` implements a `ReactiveStreamsSubscribableChannel` with its `subscribeTo(Publisher>)` contract allowing receiving events from reactive source publishers, bridging a reactive stream into the integration flow. To achieve fully reactive behavior for the whole integration flow, such a channel must be placed between all the endpoints in the flow. See <<./reactive-streams.adoc#reactive-streams,Reactive Streams Support>> for more information about interaction with Reactive Streams. [[channel-implementations-threadlocalchannel]] ===== Scoped Channel Spring Integration 1.0 provided a `ThreadLocalChannel` implementation, but that has been removed as of 2.0. Now the more general way to handle the same requirement is to add a `scope` attribute to a channel. The value of the attribute can be the name of a scope that is available within the context. For example, in a web environment, certain scopes are available, and any custom scope implementations can be registered with the context. The following example shows a thread-local scope being applied to a channel, including the registration of the scope itself: ==== [source,xml] ---- ---- ==== The channel defined in the previous example also delegates to a queue internally, but the channel is bound to the current thread, so the contents of the queue are similarly bound. That way, the thread that sends to the channel can later receive those same messages, but no other thread would be able to access them. While thread-scoped channels are rarely needed, they can be useful in situations where `DirectChannel` instances are being used to enforce a single thread of operation but any reply messages should be sent to a ""`terminal`"" channel. If that terminal channel is thread-scoped, the original sending thread can collect its replies from the terminal channel. Now, since any channel can be scoped, you can define your own scopes in addition to thread-Local. [[channel-interceptors]] ==== Channel Interceptors One of the advantages of a messaging architecture is the ability to provide common behavior and capture meaningful information about the messages passing through the system in a non-invasive way. Since the `Message` instances are sent to and received from `MessageChannel` instances, those channels provide an opportunity for intercepting the send and receive operations. The `ChannelInterceptor` strategy interface, shown in the following listing, provides methods for each of those operations: ==== [source,java] ---- public interface ChannelInterceptor { Message preSend(Message message, MessageChannel channel); void postSend(Message message, MessageChannel channel, boolean sent); void afterSendCompletion(Message message, MessageChannel channel, boolean sent, Exception ex); boolean preReceive(MessageChannel channel); Message postReceive(Message message, MessageChannel channel); void afterReceiveCompletion(Message message, MessageChannel channel, Exception ex); } ---- ==== After implementing the interface, registering the interceptor with a channel is just a matter of making the following call: ==== [source,java] ---- channel.addInterceptor(someChannelInterceptor); ---- ==== The methods that return a `Message` instance can be used for transforming the `Message` or can return 'null' to prevent further processing (of course, any of the methods can throw a `RuntimeException`). Also, the `preReceive` method can return `false` to prevent the receive operation from proceeding. NOTE: Keep in mind that `receive()` calls are only relevant for `PollableChannels`. In fact, the `SubscribableChannel` interface does not even define a `receive()` method. The reason for this is that when a `Message` is sent to a `SubscribableChannel`, it is sent directly to zero or more subscribers, depending on the type of channel (for example, a `PublishSubscribeChannel` sends to all of its subscribers). Therefore, the `preReceive(...)`, `postReceive(...)`, and `afterReceiveCompletion(...)` interceptor methods are invoked only when the interceptor is applied to a `PollableChannel`. Spring Integration also provides an implementation of the https://www.enterpriseintegrationpatterns.com/WireTap.html[Wire Tap] pattern. It is a simple interceptor that sends the `Message` to another channel without otherwise altering the existing flow. It can be very useful for debugging and monitoring. An example is shown in <>. Because it is rarely necessary to implement all of the interceptor methods, the interface provides no-op methods (those returning `void` method have no code, the `Message`-returning methods return the `Message` as-is, and the `boolean` method returns `true`). TIP: The order of invocation for the interceptor methods depends on the type of channel. As described earlier, the queue-based channels are the only ones where the `receive()` method is intercepted in the first place. Additionally, the relationship between send and receive interception depends on the timing of the separate sender and receiver threads. For example, if a receiver is already blocked while waiting for a message, the order could be as follows: `preSend`, `preReceive`, `postReceive`, `postSend`. However, if a receiver polls after the sender has placed a message on the channel and has already returned, the order would be as follows: `preSend`, `postSend` (some-time-elapses), `preReceive`, `postReceive`. The time that elapses in such a case depends on a number of factors and is therefore generally unpredictable (in fact, the receive may never happen). The type of queue also plays a role (for example, rendezvous versus priority). In short, you cannot rely on the order beyond the fact that `preSend` precedes `postSend` and `preReceive` precedes `postReceive`. Starting with Spring Framework 4.1 and Spring Integration 4.1, the `ChannelInterceptor` provides new methods: `afterSendCompletion()` and `afterReceiveCompletion()`. They are invoked after `send()' and 'receive()` calls, regardless of any exception that is raised, which allow for resource cleanup. Note that the channel invokes these methods on the `ChannelInterceptor` list in the reverse order of the initial `preSend()` and `preReceive()` calls. Starting with version 5.1, global channel interceptors now apply to dynamically registered channels - such as through beans that are initialized by using `beanFactory.initializeBean()` or `IntegrationFlowContext` when using the Java DSL. Previously, interceptors were not applied when beans were created after the application context was refreshed. Also, starting with version 5.1, `ChannelInterceptor.postReceive()` is no longer called when no message is received; it is no longer necessary to check for a `null` `Message`. Previously, the method was called. If you have an interceptor that relies on the previous behavior, implement `afterReceiveCompleted()` instead, since that method is invoked, regardless of whether a message is received or not. NOTE: Starting with version 5.2, the `ChannelInterceptorAware` is deprecated in favor of `InterceptableChannel` from the Spring Messaging module, which it extends now for backward compatibility. [[channel-template]] ==== `MessagingTemplate` When the endpoints and their various configuration options are introduced, Spring Integration provides a foundation for messaging components that enables non-invasive invocation of your application code from the messaging system. However, it is sometimes necessary to invoke the messaging system from your application code. For convenience when implementing such use cases, Spring Integration provides a `MessagingTemplate` that supports a variety of operations across the message channels, including request and reply scenarios. For example, it is possible to send a request and wait for a reply, as follows: ==== [source,java] ---- MessagingTemplate template = new MessagingTemplate(); Message reply = template.sendAndReceive(someChannel, new GenericMessage(""test"")); ---- ==== In the preceding example, a temporary anonymous channel would be created internally by the template. The 'sendTimeout' and 'receiveTimeout' properties may also be set on the template, and other exchange types are also supported. The following listing shows the signatures for such methods: ==== [source,java] ---- public boolean send(final MessageChannel channel, final Message message) { ... } public Message sendAndReceive(final MessageChannel channel, final Message request) { ... } public Message receive(final PollableChannel channel) { ... } ---- ==== NOTE: A less invasive approach that lets you invoke simple interfaces with payload or header values instead of `Message` instances is described in <<./gateway.adoc#gateway-proxy,Enter the `GatewayProxyFactoryBean`>>. [[channel-configuration]] ==== Configuring Message Channels To create a message channel instance, you can use the `` element for xml or `DirectChannel` instance for Java configuration, as follows: ==== [source, java, role=""primary""] .Java ---- @Bean public MessageChannel exampleChannel() { return new DirectChannel(); } ---- [source, xml, role=""secondary""] .XML ---- ---- ==== When you use the `` element without any sub-elements, it creates a `DirectChannel` instance (a `SubscribableChannel`). To create a publish-subscribe channel, use the `` element (the `PublishSubscribeChannel` in Java), as follows: ==== [source, java, role=""primary""] .Java ---- @Bean public MessageChannel exampleChannel() { return new PublishSubscribeChannel(); } ---- [source, xml, role=""secondary""] .XML ---- ---- ==== You can alternatively provide a variety of `` sub-elements to create any of the pollable channel types (as described in <>). The following sections shows examples of each channel type. [[channel-configuration-directchannel]] ===== `DirectChannel` Configuration As mentioned earlier, `DirectChannel` is the default type. The following listing shows who to define one: ==== [source, java, role=""primary""] .Java ---- @Bean public MessageChannel directChannel() { return new DirectChannel(); } ---- [source, xml, role=""secondary""] .XML ---- ---- ==== A default channel has a round-robin load-balancer and also has failover enabled (see <> for more detail). To disable one or both of these, add a `` sub-element (a `LoadBalancingStrategy` constructor of the `DirectChannel`) and configure the attributes as follows: ==== [source, java, role=""primary""] .Java ---- @Bean public MessageChannel failFastChannel() { DirectChannel channel = new DirectChannel(); channel.setFailover(false); return channel; } @Bean public MessageChannel failFastChannel() { return new DirectChannel(null); } ---- [source, xml, role=""secondary""] .XML ---- ---- ==== [[channel-datatype-channel]] ===== Datatype Channel Configuration Sometimes, a consumer can process only a particular type of payload, forcing you to ensure the payload type of the input messages. The first thing that comes to mind may be to use a message filter. However, all that message filter can do is filter out messages that are not compliant with the requirements of the consumer. Another way would be to use a content-based router and route messages with non-compliant data-types to specific transformers to enforce transformation and conversion to the required data type. This would work, but a simpler way to accomplish the same thing is to apply the https://www.enterpriseintegrationpatterns.com/DatatypeChannel.html[Datatype Channel] pattern. You can use separate datatype channels for each specific payload data type. To create a datatype channel that accepts only messages that contain a certain payload type, provide the data type's fully-qualified class name in the channel element's `datatype` attribute, as the following example shows: ==== [source, java, role=""primary""] .Java ---- @Bean public MessageChannel numberChannel() { DirectChannel channel = new DirectChannel(); channel.setDatatypes(Number.class); return channel; } ---- [source, xml, role=""secondary""] .XML ---- ---- ==== Note that the type check passes for any type that is assignable to the channel's datatype. In other words, the `numberChannel` in the preceding example would accept messages whose payload is `java.lang.Integer` or `java.lang.Double`. Multiple types can be provided as a comma-delimited list, as the following example shows: ==== [source, java, role=""primary""] .Java ---- @Bean public MessageChannel numberChannel() { DirectChannel channel = new DirectChannel(); channel.setDatatypes(String.class, Number.class); return channel; } ---- [source, xml, role=""secondary""] .XML ---- ---- ==== So the 'numberChannel' in the preceding example accepts only messages with a data type of `java.lang.Number`. But what happens if the payload of the message is not of the required type? It depends on whether you have defined a bean named `integrationConversionService` that is an instance of Spring's https://docs.spring.io/spring/docs/current/spring-framework-reference/html/validation.html#core-convert-ConversionService-API[Conversion Service]. If not, then an `Exception` would be thrown immediately. However, if you have defined an `integrationConversionService` bean, it is used in an attempt to convert the message's payload to the acceptable type. You can even register custom converters. For example, suppose you send a message with a `String` payload to the 'numberChannel' we configured above. You might handle the message as follows: ==== [source,java] ---- MessageChannel inChannel = context.getBean(""numberChannel"", MessageChannel.class); inChannel.send(new GenericMessage(""5"")); ---- ==== Typically, this would be a perfectly legal operation. However, since we use Datatype Channel, the result of such operation would generate an exception similar to the following: ==== [source] ---- Exception in thread ""main"" org.springframework.integration.MessageDeliveryException: Channel 'numberChannel' expected one of the following datataypes [class java.lang.Number], but received [class java.lang.String] … ---- ==== The exception happens because we require the payload type to be a `Number`, but we sent a `String`. So we need something to convert a `String` to a `Number`. For that, we can implement a converter similar to the following example: ==== [source,java] ---- public static class StringToIntegerConverter implements Converter { public Integer convert(String source) { return Integer.parseInt(source); } } ---- ==== Then we can register it as a converter with the Integration Conversion Service, as the following example shows: ==== [source, java, role=""primary""] .Java ---- @Bean @IntegrationConverter public StringToIntegerConverter strToInt { return new StringToIntegerConverter(); } ---- [source, xml, role=""secondary""] .XML ---- ---- ==== Or on the `StringToIntegerConverter` class when it is marked with the `@Component` annotation for auto-scanning. When the 'converter' element is parsed, it creates the `integrationConversionService` bean if one is not already defined. With that converter in place, the `send` operation would now be successful, because the datatype channel uses that converter to convert the `String` payload to an `Integer`. For more information regarding payload type conversion, see <<./endpoint.adoc#payload-type-conversion,Payload Type Conversion>>. Beginning with version 4.0, the `integrationConversionService` is invoked by the `DefaultDatatypeChannelMessageConverter`, which looks up the conversion service in the application context. To use a different conversion technique, you can specify the `message-converter` attribute on the channel. This must be a reference to a `MessageConverter` implementation. Only the `fromMessage` method is used. It provides the converter with access to the message headers (in case the conversion might need information from the headers, such as `content-type`). The method can return only the converted payload or a full `Message` object. If the latter, the converter must be careful to copy all the headers from the inbound message. Alternatively, you can declare a `` of type `MessageConverter` with an ID of `datatypeChannelMessageConverter`, and that converter is used by all channels with a `datatype`. [[channel-configuration-queuechannel]] ===== `QueueChannel` Configuration To create a `QueueChannel`, use the `` sub-element. You may specify the channel's capacity as follows: ==== [source, java, role=""primary""] .Java ---- @Bean public PollableChannel queueChannel() { return new QueueChannel(25); } ---- [source, xml, role=""secondary""] .XML ---- ---- ==== NOTE: If you do not provide a value for the 'capacity' attribute on this `` sub-element, the resulting queue is unbounded. To avoid issues such as running out of memory, we highly recommend that you set an explicit value for a bounded queue. ====== Persistent `QueueChannel` Configuration Since a `QueueChannel` provides the capability to buffer messages but does so in-memory only by default, it also introduces a possibility that messages could be lost in the event of a system failure. To mitigate this risk, a `QueueChannel` may be backed by a persistent implementation of the `MessageGroupStore` strategy interface. For more details on `MessageGroupStore` and `MessageStore`, see <<./message-store.adoc#message-store,Message Store>>. IMPORTANT: The `capacity` attribute is not allowed when the `message-store` attribute is used. When a `QueueChannel` receives a `Message`, it adds the message to the message store. When a `Message` is polled from a `QueueChannel`, it is removed from the message store. By default, a `QueueChannel` stores its messages in an in-memory queue, which can lead to the lost message scenario mentioned earlier. However, Spring Integration provides persistent stores, such as the `JdbcChannelMessageStore`. You can configure a message store for any `QueueChannel` by adding the `message-store` attribute, as the following example shows: ==== [source,xml] ---- ---- ==== (See samples below for Java/Kotlin Configuration options.) The Spring Integration JDBC module also provides a schema Data Definition Language (DDL) for a number of popular databases. These schemas are located in the org.springframework.integration.jdbc.store.channel package of that module (`spring-integration-jdbc`). IMPORTANT: One important feature is that, with any transactional persistent store (such as `JdbcChannelMessageStore`), as long as the poller has a transaction configured, a message removed from the store can be permanently removed only if the transaction completes successfully. Otherwise, the transaction rolls back, and the `Message` is not lost. Many other implementations of the message store are available as the growing number of Spring projects related to ""`NoSQL`"" data stores come to provide underlying support for these stores. You can also provide your own implementation of the `MessageGroupStore` interface if you cannot find one that meets your particular needs. Since version 4.0, we recommend that `QueueChannel` instances be configured to use a `ChannelMessageStore`, if possible. These are generally optimized for this use, as compared to a general message store. If the `ChannelMessageStore` is a `ChannelPriorityMessageStore`, the messages are received in FIFO within priority order. The notion of priority is determined by the message store implementation. For example, the following example shows the Java configuration for the <<./mongodb.adoc#mongodb-priority-channel-message-store,MongoDB Channel Message Store>>: ==== [source, java, role=""primary""] .Java ---- @Bean public BasicMessageGroupStore mongoDbChannelMessageStore(MongoDbFactory mongoDbFactory) { MongoDbChannelMessageStore store = new MongoDbChannelMessageStore(mongoDbFactory); store.setPriorityEnabled(true); return store; } @Bean public PollableChannel priorityQueue(BasicMessageGroupStore mongoDbChannelMessageStore) { return new PriorityChannel(new MessageGroupQueue(mongoDbChannelMessageStore, ""priorityQueue"")); } ---- [source, java, role=""secondary""] .Java DSL ---- @Bean public IntegrationFlow priorityFlow(PriorityCapableChannelMessageStore mongoDbChannelMessageStore) { return IntegrationFlows.from((Channels c) -> c.priority(""priorityChannel"", mongoDbChannelMessageStore, ""priorityGroup"")) .... .get(); } ---- [source, kotlin, role=""secondary""] .Kotlin DSL ---- @Bean fun priorityFlow(mongoDbChannelMessageStore: PriorityCapableChannelMessageStore) = integrationFlow { channel { priority(""priorityChannel"", mongoDbChannelMessageStore, ""priorityGroup"") } } ---- ==== NOTE: Pay attention to the `MessageGroupQueue` class. That is a `BlockingQueue` implementation to use the `MessageGroupStore` operations. Another option to customize the `QueueChannel` environment is provided by the `ref` attribute of the `` sub-element or its particular constructor. This attribute supplies the reference to any `java.util.Queue` implementation. For example, a Hazelcast distributed https://hazelcast.com/use-cases/imdg/imdg-messaging/[`IQueue`] can be configured as follows: ==== [source,java] ---- @Bean public HazelcastInstance hazelcastInstance() { return Hazelcast.newHazelcastInstance(new Config() .setProperty(""hazelcast.logging.type"", ""log4j"")); } @Bean public PollableChannel distributedQueue() { return new QueueChannel(hazelcastInstance() .getQueue(""springIntegrationQueue"")); } ---- ==== [[channel-configuration-pubsubchannel]] ===== `PublishSubscribeChannel` Configuration To create a `PublishSubscribeChannel`, use the element. When using this element, you can also specify the `task-executor` used for publishing messages (if none is specified, it publishes in the sender's thread), as follows: ==== [source, java, role=""primary""] .Java ---- @Bean public MessageChannel pubsubChannel() { return new PublishSubscribeChannel(someExecutor()); } ---- [source, xml, role=""secondary""] .XML ---- ---- ==== If you provide a resequencer or aggregator downstream from a `PublishSubscribeChannel`, you can set the 'apply-sequence' property on the channel to `true`. Doing so indicates that the channel should set the `sequence-size` and `sequence-number` message headers as well as the correlation ID prior to passing along the messages. For example, if there are five subscribers, the `sequence-size` would be set to `5`, and the messages would have `sequence-number` header values ranging from `1` to `5`. Along with the `Executor`, you can also configure an `ErrorHandler`. By default, the `PublishSubscribeChannel` uses a `MessagePublishingErrorHandler` implementation to send an error to the `MessageChannel` from the `errorChannel` header or into the global `errorChannel` instance. If an `Executor` is not configured, the `ErrorHandler` is ignored and exceptions are thrown directly to the caller's thread. If you provide a `Resequencer` or `Aggregator` downstream from a `PublishSubscribeChannel`, you can set the 'apply-sequence' property on the channel to `true`. Doing so indicates that the channel should set the sequence-size and sequence-number message headers as well as the correlation ID prior to passing along the messages. For example, if there are five subscribers, the sequence-size would be set to `5`, and the messages would have sequence-number header values ranging from `1` to `5`. The following example shows how to set the `apply-sequence` header to `true`: ==== [source, java, role=""primary""] .Java ---- @Bean public MessageChannel pubsubChannel() { PublishSubscribeChannel channel = new PublishSubscribeChannel(); channel.setApplySequence(true); return channel; } ---- [source, xml, role=""secondary""] .XML ---- ---- ==== NOTE: The `apply-sequence` value is `false` by default so that a publish-subscribe channel can send the exact same message instances to multiple outbound channels. Since Spring Integration enforces immutability of the payload and header references, when the flag is set to `true`, the channel creates new `Message` instances with the same payload reference but different header values. Starting with version 5.4.3, the `PublishSubscribeChannel` can also be configured with the `requireSubscribers` option of its `BroadcastingDispatcher` to indicate that this channel will not ignore a message silently when it has no subscribers. A `MessageDispatchingException` with a `Dispatcher has no subscribers` message is thrown when there are no subscribers and this option is set to `true`. [[channel-configuration-executorchannel]] ===== `ExecutorChannel` To create an `ExecutorChannel`, add the `` sub-element with a `task-executor` attribute. The attribute's value can reference any `TaskExecutor` within the context. For example, doing so enables configuration of a thread pool for dispatching messages to subscribed handlers. As mentioned earlier, doing so breaks the single-threaded execution context between sender and receiver so that any active transaction context is not shared by the invocation of the handler (that is, the handler may throw an `Exception`, but the `send` invocation has already returned successfully). The following example shows how to use the `dispatcher` element and specify an executor in the `task-executor` attribute: ==== [source, java, role=""primary""] .Java ---- @Bean public MessageChannel executorChannel() { return new ExecutorChannel(someExecutor()); } ---- [source, xml, role=""secondary""] .XML ---- ---- ==== [NOTE] ===== The `load-balancer` and `failover` options are also both available on the sub-element, as described earlier in <>. The same defaults apply. Consequently, the channel has a round-robin load-balancing strategy with failover enabled unless explicit configuration is provided for one or both of those attributes, as the following example shows: ==== [source,xml] ---- ---- ==== ===== [[channel-configuration-prioritychannel]] ===== `PriorityChannel` Configuration To create a `PriorityChannel`, use the `` sub-element, as the following example shows: ==== [source, java, role=""primary""] .Java ---- @Bean public PollableChannel priorityChannel() { return new PriorityChannel(20); } ---- [source, xml, role=""secondary""] .XML ---- ---- ==== By default, the channel consults the `priority` header of the message. However, you can instead provide a custom `Comparator` reference. Also, note that the `PriorityChannel` (like the other types) does support the `datatype` attribute. As with the `QueueChannel`, it also supports a `capacity` attribute. The following example demonstrates all of these: ==== [source, java, role=""primary""] .Java ---- @Bean public PollableChannel priorityChannel() { PriorityChannel channel = new PriorityChannel(20, widgetComparator()); channel.setDatatypes(example.Widget.class); return channel; } ---- [source, xml, role=""secondary""] .XML ---- ---- ==== Since version 4.0, the `priority-channel` child element supports the `message-store` option (`comparator` and `capacity` are not allowed in that case). The message store must be a `PriorityCapableChannelMessageStore`. Implementations of the `PriorityCapableChannelMessageStore` are currently provided for `Redis`, `JDBC`, and `MongoDB`. See <> and <<./message-store.adoc#message-store,Message Store>> for more information. You can find sample configuration in <<./jdbc.adoc#jdbc-message-store-channels,Backing Message Channels>>. [[channel-configuration-rendezvouschannel]] ===== `RendezvousChannel` Configuration A `RendezvousChannel` is created when the queue sub-element is a ``. It does not provide any additional configuration options to those described earlier, and its queue does not accept any capacity value, since it is a zero-capacity direct handoff queue. The following example shows how to declare a `RendezvousChannel`: ==== [source, java, role=""primary""] .Java ---- @Bean public PollableChannel rendezvousChannel() { return new RendezvousChannel(); } ---- [source, xml, role=""secondary""] .XML ---- ---- ==== [[channel-configuration-threadlocalchannel]] ===== Scoped Channel Configuration Any channel can be configured with a `scope` attribute, as the following example shows: ==== [source,xml] ---- ---- ==== // TODO What scope values are available? Can I create my own? [[channel-configuration-interceptors]] ===== Channel Interceptor Configuration Message channels may also have interceptors, as described in <>. The `` sub-element can be added to a `` (or the more specific element types). You can provide the `ref` attribute to reference any Spring-managed object that implements the `ChannelInterceptor` interface, as the following example shows: ==== [source,xml] ---- ---- ==== In general, we recommend defining the interceptor implementations in a separate location, since they usually provide common behavior that can be reused across multiple channels. [[global-channel-configuration-interceptors]] ===== Global Channel Interceptor Configuration Channel interceptors provide a clean and concise way of applying cross-cutting behavior per individual channel. If the same behavior should be applied on multiple channels, configuring the same set of interceptors for each channel would not be the most efficient way. To avoid repeated configuration while also enabling interceptors to apply to multiple channels, Spring Integration provides global interceptors. Consider the following pair of examples: ==== [source,xml] ---- ---- [source,xml] ---- ---- ==== Each `` element lets you define a global interceptor, which is applied on all channels that match any patterns defined by the `pattern` attribute. In the preceding case, the global interceptor is applied on the 'thing1' channel and all other channels that begin with 'thing2' or 'input' but not to channels starting with 'thing3' (since version 5.0). WARNING: The addition of this syntax to the pattern causes one possible (though perhaps unlikely) problem. If you have a bean named `!thing1` and you included a pattern of `!thing1` in your channel interceptor's `pattern` patterns, it no longer matches. The pattern now matches all beans not named `thing1`. In this case, you can escape the `!` in the pattern with `\\`. The pattern `\\!thing1` matches a bean named `!thing1`. The order attribute lets you manage where this interceptor is injected when there are multiple interceptors on a given channel. For example, channel 'inputChannel' could have individual interceptors configured locally (see below), as the following example shows: ==== [source,xml] ---- ---- ==== A reasonable question is ""`how is a global interceptor injected in relation to other interceptors configured locally or through other global interceptor definitions?`"" The current implementation provides a simple mechanism for defining the order of interceptor execution. A positive number in the `order` attribute ensures interceptor injection after any existing interceptors, while a negative number ensures that the interceptor is injected before existing interceptors. This means that, in the preceding example, the global interceptor is injected after (since its `order` is greater than `0`) the 'wire-tap' interceptor configured locally. If there were another global interceptor with a matching `pattern`, its order would be determined by comparing the values of both interceptors' `order` attributes. To inject a global interceptor before the existing interceptors, use a negative value for the `order` attribute. NOTE: Note that both the `order` and `pattern` attributes are optional. The default value for `order` will be 0 and for `pattern`, the default is '*' (to match all channels). [[channel-wiretap]] ===== Wire Tap As mentioned earlier, Spring Integration provides a simple wire tap interceptor. You can configure a wire tap on any channel within an `` element. Doing so is especially useful for debugging and can be used in conjunction with Spring Integration's logging channel adapter as follows: ==== [source,xml] ---- ---- ==== TIP: The 'logging-channel-adapter' also accepts an 'expression' attribute so that you can evaluate a SpEL expression against the 'payload' and 'headers' variables. Alternatively, to log the full message `toString()` result, provide a value of `true` for the 'log-full-message' attribute. By default, it is `false` so that only the payload is logged. Setting it to `true` enables logging of all headers in addition to the payload. The 'expression' option provides the most flexibility (for example, `expression=""payload.user.name""`). One of the common misconceptions about the wire tap and other similar components (<<./message-publishing.adoc#message-publishing-config,Message Publishing Configuration>>) is that they are automatically asynchronous in nature. By default, wire tap as a component is not invoked asynchronously. Instead, Spring Integration focuses on a single unified approach to configuring asynchronous behavior: the message channel. What makes certain parts of the message flow synchronous or asynchronous is the type of Message Channel that has been configured within that flow. That is one of the primary benefits of the message channel abstraction. From the inception of the framework, we have always emphasized the need and the value of the message channel as a first-class citizen of the framework. It is not just an internal, implicit realization of the EIP pattern. It is fully exposed as a configurable component to the end user. So, the wire tap component is only responsible for performing the following tasks: * Intercept a message flow by tapping into a channel (for example, `channelA`) * Grab each message * Send the message to another channel (for example, `channelB`) It is essentially a variation of the bridge pattern, but it is encapsulated within a channel definition (and hence easier to enable and disable without disrupting a flow). Also, unlike the bridge, it basically forks another message flow. Is that flow synchronous or asynchronous? The answer depends on the type of message channel that 'channelB' is. We have the following options: direct channel, pollable channel, and executor channel. The last two break the thread boundary, making communication over such channels asynchronous, because the dispatching of the message from that channel to its subscribed handlers happens on a different thread than the one used to send the message to that channel. That is what is going to make your wire-tap flow synchronous or asynchronous. It is consistent with other components within the framework (such as message publisher) and adds a level of consistency and simplicity by sparing you from worrying in advance (other than writing thread-safe code) about whether a particular piece of code should be implemented as synchronous or asynchronous. The actual wiring of two pieces of code (say, component A and component B) over a message channel is what makes their collaboration synchronous or asynchronous. You may even want to change from synchronous to asynchronous in the future, and message channel lets you do it swiftly without ever touching the code. One final point regarding the wire tap is that, despite the rationale provided above for not being asynchronous by default, you should keep in mind that it is usually desirable to hand off the message as soon as possible. Therefore, it would be quite common to use an asynchronous channel option as the wire tap's outbound channel. However, the asynchronous behavior is not enforced by default. There are a number of use cases that would break if we did, including that you might not want to break a transactional boundary. Perhaps you use the wire tap pattern for auditing purposes, and you do want the audit messages to be sent within the original transaction. As an example, you might connect the wire tap to a JMS outbound channel adapter. That way, you get the best of both worlds: 1) the sending of a JMS Message can occur within the transaction while 2) it is still a ""`fire-and-forget`"" action, thereby preventing any noticeable delay in the main message flow. IMPORTANT: Starting with version 4.0, it is important to avoid circular references when an interceptor (such as the https://docs.spring.io/autorepo/docs/spring-integration/current/api/org/springframework/integration/channel/interceptor/WireTap.html[`WireTap` class]) references a channel. You need to exclude such channels from those being intercepted by the current interceptor. This can be done with appropriate patterns or programmatically. If you have a custom `ChannelInterceptor` that references a `channel`, consider implementing `VetoCapableInterceptor`. That way, the framework asks the interceptor if it is OK to intercept each channel that is a candidate, based on the supplied pattern. You can also add runtime protection in the interceptor methods to ensure that the channel is not one that is referenced by the interceptor. The `WireTap` uses both of these techniques. Starting with version 4.3, the `WireTap` has additional constructors that take a `channelName` instead of a `MessageChannel` instance. This can be convenient for Java configuration and when channel auto-creation logic is being used. The target `MessageChannel` bean is resolved from the provided `channelName` later, on the first interaction with the interceptor. IMPORTANT: Channel resolution requires a `BeanFactory`, so the wire tap instance must be a Spring-managed bean. This late-binding approach also allows simplification of typical wire-tapping patterns with Java DSL configuration, as the following example shows: ==== [source,java] ---- @Bean public PollableChannel myChannel() { return MessageChannels.queue() .wireTap(""loggingFlow.input"") .get(); } @Bean public IntegrationFlow loggingFlow() { return f -> f.log(); } ---- ==== [[conditional-wiretap]] ===== Conditional Wire Taps Wire taps can be made conditional by using the `selector` or `selector-expression` attributes. The `selector` references a `MessageSelector` bean, which can determine at runtime whether the message should go to the tap channel. Similarly, the `selector-expression` is a boolean SpEL expression that performs the same purpose: If the expression evaluates to `true`, the message is sent to the tap channel. [[channel-global-wiretap]] ===== Global Wire Tap Configuration It is possible to configure a global wire tap as a special case of the <>. To do so, configure a top level `wire-tap` element. Now, in addition to the normal `wire-tap` namespace support, the `pattern` and `order` attributes are supported and work in exactly the same way as they do for the `channel-interceptor`. The following example shows how to configure a global wire tap: ==== [source, java, role=""primary""] .Java ---- @Bean @GlobalChannelInterceptor(patterns = ""input*,thing2*,thing1"", order = 3) public WireTap wireTap(MessageChannel wiretapChannel) { return new WireTap(wiretapChannel); } ---- [source, xml, role=""secondary""] .XML ---- ---- ==== TIP: A global wire tap provides a convenient way to configure a single-channel wire tap externally without modifying the existing channel configuration. To do so, set the `pattern` attribute to the target channel name. For example, you can use this technique to configure a test case to verify messages on a channel. [[channel-special-channels]] ==== Special Channels Two special channels are defined within the application context by default: `errorChannel` and `nullChannel`. The 'nullChannel' (an instance of `NullChannel`) acts like `/dev/null`, logging any message sent to it at the `DEBUG` level and returning immediately. The special treatment is applied for an `org.reactivestreams.Publisher` payload of a transmitted message: it is subscribed to in this channel immediately, to initiate reactive stream processing, although the data is discarded. An error thrown from a reactive stream processing (see `Subscriber.onError(Throwable)`) is logged under the `warn` level for possible investigation. If there is need to do anything with such an error, the `<<./handler-advice.adoc#reactive-advice,ReactiveRequestHandlerAdvice>>` with a `Mono.doOnError()` customization can be applied to the message handler producing `Mono` reply into this `nullChannel`. Any time you face channel resolution errors for a reply that you do not care about, you can set the affected component's `output-channel` attribute to 'nullChannel' (the name, 'nullChannel', is reserved within the application context). The 'errorChannel' is used internally for sending error messages and may be overridden with a custom configuration. This is discussed in greater detail in <<./error-handling.adoc#error-handling,Error Handling>>. See also <<./dsl.adoc#java-dsl-channels,Message Channels>> in the Java DSL chapter for more information about message channel and interceptors. ",12170,False,2401.2718176511335,median "[[analysis-lang-analyzer]] === Language Analyzers A set of analyzers aimed at analyzing specific language text. The following types are supported: <>, <>, <>, <>, <>, <>, <>, <>, <>, <>, <>, <>, <>, <>, <>, <>, <>, <>, <>, <>, <>, <>, <>, <>, <>, <>, <>, <>, <>, <>, <>, <>, <>, <>. ==== Configuring language analyzers ===== Stopwords All analyzers support setting custom `stopwords` either internally in the config, or by using an external stopwords file by setting `stopwords_path`. Check <> for more details. ===== Excluding words from stemming The `stem_exclusion` parameter allows you to specify an array of lowercase words that should not be stemmed. Internally, this functionality is implemented by adding the <> with the `keywords` set to the value of the `stem_exclusion` parameter. The following analyzers support setting custom `stem_exclusion` list: `arabic`, `armenian`, `basque`, `bengali`, `bulgarian`, `catalan`, `czech`, `dutch`, `english`, `finnish`, `french`, `galician`, `german`, `hindi`, `hungarian`, `indonesian`, `irish`, `italian`, `latvian`, `lithuanian`, `norwegian`, `portuguese`, `romanian`, `russian`, `sorani`, `spanish`, `swedish`, `turkish`. ==== Reimplementing language analyzers The built-in language analyzers can be reimplemented as `custom` analyzers (as described below) in order to customize their behaviour. NOTE: If you do not intend to exclude words from being stemmed (the equivalent of the `stem_exclusion` parameter above), then you should remove the `keyword_marker` token filter from the custom analyzer configuration. [[arabic-analyzer]] ===== `arabic` analyzer The `arabic` analyzer could be reimplemented as a `custom` analyzer as follows: [source,console] ---------------------------------------------------- PUT /arabic_example { ""settings"": { ""analysis"": { ""filter"": { ""arabic_stop"": { ""type"": ""stop"", ""stopwords"": ""_arabic_"" <1> }, ""arabic_keywords"": { ""type"": ""keyword_marker"", ""keywords"": [""مثال""] <2> }, ""arabic_stemmer"": { ""type"": ""stemmer"", ""language"": ""arabic"" } }, ""analyzer"": { ""rebuilt_arabic"": { ""tokenizer"": ""standard"", ""filter"": [ ""lowercase"", ""decimal_digit"", ""arabic_stop"", ""arabic_normalization"", ""arabic_keywords"", ""arabic_stemmer"" ] } } } } } ---------------------------------------------------- // TEST[s/""arabic_keywords"",//] // TEST[s/\\n$/\\nstartyaml\\n - compare_analyzers: {index: arabic_example, first: arabic, second: rebuilt_arabic}\\nendyaml\\n/] <1> The default stopwords can be overridden with the `stopwords` or `stopwords_path` parameters. <2> This filter should be removed unless there are words which should be excluded from stemming. [[armenian-analyzer]] ===== `armenian` analyzer The `armenian` analyzer could be reimplemented as a `custom` analyzer as follows: [source,console] ---------------------------------------------------- PUT /armenian_example { ""settings"": { ""analysis"": { ""filter"": { ""armenian_stop"": { ""type"": ""stop"", ""stopwords"": ""_armenian_"" <1> }, ""armenian_keywords"": { ""type"": ""keyword_marker"", ""keywords"": [""օրինակ""] <2> }, ""armenian_stemmer"": { ""type"": ""stemmer"", ""language"": ""armenian"" } }, ""analyzer"": { ""rebuilt_armenian"": { ""tokenizer"": ""standard"", ""filter"": [ ""lowercase"", ""armenian_stop"", ""armenian_keywords"", ""armenian_stemmer"" ] } } } } } ---------------------------------------------------- // TEST[s/""armenian_keywords"",//] // TEST[s/\\n$/\\nstartyaml\\n - compare_analyzers: {index: armenian_example, first: armenian, second: rebuilt_armenian}\\nendyaml\\n/] <1> The default stopwords can be overridden with the `stopwords` or `stopwords_path` parameters. <2> This filter should be removed unless there are words which should be excluded from stemming. [[basque-analyzer]] ===== `basque` analyzer The `basque` analyzer could be reimplemented as a `custom` analyzer as follows: [source,console] ---------------------------------------------------- PUT /basque_example { ""settings"": { ""analysis"": { ""filter"": { ""basque_stop"": { ""type"": ""stop"", ""stopwords"": ""_basque_"" <1> }, ""basque_keywords"": { ""type"": ""keyword_marker"", ""keywords"": [""Adibidez""] <2> }, ""basque_stemmer"": { ""type"": ""stemmer"", ""language"": ""basque"" } }, ""analyzer"": { ""rebuilt_basque"": { ""tokenizer"": ""standard"", ""filter"": [ ""lowercase"", ""basque_stop"", ""basque_keywords"", ""basque_stemmer"" ] } } } } } ---------------------------------------------------- // TEST[s/""basque_keywords"",//] // TEST[s/\\n$/\\nstartyaml\\n - compare_analyzers: {index: basque_example, first: basque, second: rebuilt_basque}\\nendyaml\\n/] <1> The default stopwords can be overridden with the `stopwords` or `stopwords_path` parameters. <2> This filter should be removed unless there are words which should be excluded from stemming. [[bengali-analyzer]] ===== `bengali` analyzer The `bengali` analyzer could be reimplemented as a `custom` analyzer as follows: [source,console] ---------------------------------------------------- PUT /bengali_example { ""settings"": { ""analysis"": { ""filter"": { ""bengali_stop"": { ""type"": ""stop"", ""stopwords"": ""_bengali_"" <1> }, ""bengali_keywords"": { ""type"": ""keyword_marker"", ""keywords"": [""উদাহরণ""] <2> }, ""bengali_stemmer"": { ""type"": ""stemmer"", ""language"": ""bengali"" } }, ""analyzer"": { ""rebuilt_bengali"": { ""tokenizer"": ""standard"", ""filter"": [ ""lowercase"", ""decimal_digit"", ""bengali_keywords"", ""indic_normalization"", ""bengali_normalization"", ""bengali_stop"", ""bengali_stemmer"" ] } } } } } ---------------------------------------------------- // TEST[s/""bengali_keywords"",//] // TEST[s/\\n$/\\nstartyaml\\n - compare_analyzers: {index: bengali_example, first: bengali, second: rebuilt_bengali}\\nendyaml\\n/] <1> The default stopwords can be overridden with the `stopwords` or `stopwords_path` parameters. <2> This filter should be removed unless there are words which should be excluded from stemming. [[brazilian-analyzer]] ===== `brazilian` analyzer The `brazilian` analyzer could be reimplemented as a `custom` analyzer as follows: [source,console] ---------------------------------------------------- PUT /brazilian_example { ""settings"": { ""analysis"": { ""filter"": { ""brazilian_stop"": { ""type"": ""stop"", ""stopwords"": ""_brazilian_"" <1> }, ""brazilian_keywords"": { ""type"": ""keyword_marker"", ""keywords"": [""exemplo""] <2> }, ""brazilian_stemmer"": { ""type"": ""stemmer"", ""language"": ""brazilian"" } }, ""analyzer"": { ""rebuilt_brazilian"": { ""tokenizer"": ""standard"", ""filter"": [ ""lowercase"", ""brazilian_stop"", ""brazilian_keywords"", ""brazilian_stemmer"" ] } } } } } ---------------------------------------------------- // TEST[s/""brazilian_keywords"",//] // TEST[s/\\n$/\\nstartyaml\\n - compare_analyzers: {index: brazilian_example, first: brazilian, second: rebuilt_brazilian}\\nendyaml\\n/] <1> The default stopwords can be overridden with the `stopwords` or `stopwords_path` parameters. <2> This filter should be removed unless there are words which should be excluded from stemming. [[bulgarian-analyzer]] ===== `bulgarian` analyzer The `bulgarian` analyzer could be reimplemented as a `custom` analyzer as follows: [source,console] ---------------------------------------------------- PUT /bulgarian_example { ""settings"": { ""analysis"": { ""filter"": { ""bulgarian_stop"": { ""type"": ""stop"", ""stopwords"": ""_bulgarian_"" <1> }, ""bulgarian_keywords"": { ""type"": ""keyword_marker"", ""keywords"": [""пример""] <2> }, ""bulgarian_stemmer"": { ""type"": ""stemmer"", ""language"": ""bulgarian"" } }, ""analyzer"": { ""rebuilt_bulgarian"": { ""tokenizer"": ""standard"", ""filter"": [ ""lowercase"", ""bulgarian_stop"", ""bulgarian_keywords"", ""bulgarian_stemmer"" ] } } } } } ---------------------------------------------------- // TEST[s/""bulgarian_keywords"",//] // TEST[s/\\n$/\\nstartyaml\\n - compare_analyzers: {index: bulgarian_example, first: bulgarian, second: rebuilt_bulgarian}\\nendyaml\\n/] <1> The default stopwords can be overridden with the `stopwords` or `stopwords_path` parameters. <2> This filter should be removed unless there are words which should be excluded from stemming. [[catalan-analyzer]] ===== `catalan` analyzer The `catalan` analyzer could be reimplemented as a `custom` analyzer as follows: [source,console] ---------------------------------------------------- PUT /catalan_example { ""settings"": { ""analysis"": { ""filter"": { ""catalan_elision"": { ""type"": ""elision"", ""articles"": [ ""d"", ""l"", ""m"", ""n"", ""s"", ""t""], ""articles_case"": true }, ""catalan_stop"": { ""type"": ""stop"", ""stopwords"": ""_catalan_"" <1> }, ""catalan_keywords"": { ""type"": ""keyword_marker"", ""keywords"": [""example""] <2> }, ""catalan_stemmer"": { ""type"": ""stemmer"", ""language"": ""catalan"" } }, ""analyzer"": { ""rebuilt_catalan"": { ""tokenizer"": ""standard"", ""filter"": [ ""catalan_elision"", ""lowercase"", ""catalan_stop"", ""catalan_keywords"", ""catalan_stemmer"" ] } } } } } ---------------------------------------------------- // TEST[s/""catalan_keywords"",//] // TEST[s/\\n$/\\nstartyaml\\n - compare_analyzers: {index: catalan_example, first: catalan, second: rebuilt_catalan}\\nendyaml\\n/] <1> The default stopwords can be overridden with the `stopwords` or `stopwords_path` parameters. <2> This filter should be removed unless there are words which should be excluded from stemming. [[cjk-analyzer]] ===== `cjk` analyzer NOTE: You may find that `icu_analyzer` in the ICU analysis plugin works better for CJK text than the `cjk` analyzer. Experiment with your text and queries. The `cjk` analyzer could be reimplemented as a `custom` analyzer as follows: [source,console] ---------------------------------------------------- PUT /cjk_example { ""settings"": { ""analysis"": { ""filter"": { ""english_stop"": { ""type"": ""stop"", ""stopwords"": [ <1> ""a"", ""and"", ""are"", ""as"", ""at"", ""be"", ""but"", ""by"", ""for"", ""if"", ""in"", ""into"", ""is"", ""it"", ""no"", ""not"", ""of"", ""on"", ""or"", ""s"", ""such"", ""t"", ""that"", ""the"", ""their"", ""then"", ""there"", ""these"", ""they"", ""this"", ""to"", ""was"", ""will"", ""with"", ""www"" ] } }, ""analyzer"": { ""rebuilt_cjk"": { ""tokenizer"": ""standard"", ""filter"": [ ""cjk_width"", ""lowercase"", ""cjk_bigram"", ""english_stop"" ] } } } } } ---------------------------------------------------- // TEST[s/""cjk_keywords"",//] // TEST[s/\\n$/\\nstartyaml\\n - compare_analyzers: {index: cjk_example, first: cjk, second: rebuilt_cjk}\\nendyaml\\n/] <1> The default stopwords can be overridden with the `stopwords` or `stopwords_path` parameters. The default stop words are *almost* the same as the `_english_` set, but not exactly the same. [[czech-analyzer]] ===== `czech` analyzer The `czech` analyzer could be reimplemented as a `custom` analyzer as follows: [source,console] ---------------------------------------------------- PUT /czech_example { ""settings"": { ""analysis"": { ""filter"": { ""czech_stop"": { ""type"": ""stop"", ""stopwords"": ""_czech_"" <1> }, ""czech_keywords"": { ""type"": ""keyword_marker"", ""keywords"": [""příklad""] <2> }, ""czech_stemmer"": { ""type"": ""stemmer"", ""language"": ""czech"" } }, ""analyzer"": { ""rebuilt_czech"": { ""tokenizer"": ""standard"", ""filter"": [ ""lowercase"", ""czech_stop"", ""czech_keywords"", ""czech_stemmer"" ] } } } } } ---------------------------------------------------- // TEST[s/""czech_keywords"",//] // TEST[s/\\n$/\\nstartyaml\\n - compare_analyzers: {index: czech_example, first: czech, second: rebuilt_czech}\\nendyaml\\n/] <1> The default stopwords can be overridden with the `stopwords` or `stopwords_path` parameters. <2> This filter should be removed unless there are words which should be excluded from stemming. [[danish-analyzer]] ===== `danish` analyzer The `danish` analyzer could be reimplemented as a `custom` analyzer as follows: [source,console] ---------------------------------------------------- PUT /danish_example { ""settings"": { ""analysis"": { ""filter"": { ""danish_stop"": { ""type"": ""stop"", ""stopwords"": ""_danish_"" <1> }, ""danish_keywords"": { ""type"": ""keyword_marker"", ""keywords"": [""eksempel""] <2> }, ""danish_stemmer"": { ""type"": ""stemmer"", ""language"": ""danish"" } }, ""analyzer"": { ""rebuilt_danish"": { ""tokenizer"": ""standard"", ""filter"": [ ""lowercase"", ""danish_stop"", ""danish_keywords"", ""danish_stemmer"" ] } } } } } ---------------------------------------------------- // TEST[s/""danish_keywords"",//] // TEST[s/\\n$/\\nstartyaml\\n - compare_analyzers: {index: danish_example, first: danish, second: rebuilt_danish}\\nendyaml\\n/] <1> The default stopwords can be overridden with the `stopwords` or `stopwords_path` parameters. <2> This filter should be removed unless there are words which should be excluded from stemming. [[dutch-analyzer]] ===== `dutch` analyzer The `dutch` analyzer could be reimplemented as a `custom` analyzer as follows: [source,console] ---------------------------------------------------- PUT /dutch_example { ""settings"": { ""analysis"": { ""filter"": { ""dutch_stop"": { ""type"": ""stop"", ""stopwords"": ""_dutch_"" <1> }, ""dutch_keywords"": { ""type"": ""keyword_marker"", ""keywords"": [""voorbeeld""] <2> }, ""dutch_stemmer"": { ""type"": ""stemmer"", ""language"": ""dutch"" }, ""dutch_override"": { ""type"": ""stemmer_override"", ""rules"": [ ""fiets=>fiets"", ""bromfiets=>bromfiets"", ""ei=>eier"", ""kind=>kinder"" ] } }, ""analyzer"": { ""rebuilt_dutch"": { ""tokenizer"": ""standard"", ""filter"": [ ""lowercase"", ""dutch_stop"", ""dutch_keywords"", ""dutch_override"", ""dutch_stemmer"" ] } } } } } ---------------------------------------------------- // TEST[s/""dutch_keywords"",//] // TEST[s/\\n$/\\nstartyaml\\n - compare_analyzers: {index: dutch_example, first: dutch, second: rebuilt_dutch}\\nendyaml\\n/] <1> The default stopwords can be overridden with the `stopwords` or `stopwords_path` parameters. <2> This filter should be removed unless there are words which should be excluded from stemming. [[english-analyzer]] ===== `english` analyzer The `english` analyzer could be reimplemented as a `custom` analyzer as follows: [source,console] ---------------------------------------------------- PUT /english_example { ""settings"": { ""analysis"": { ""filter"": { ""english_stop"": { ""type"": ""stop"", ""stopwords"": ""_english_"" <1> }, ""english_keywords"": { ""type"": ""keyword_marker"", ""keywords"": [""example""] <2> }, ""english_stemmer"": { ""type"": ""stemmer"", ""language"": ""english"" }, ""english_possessive_stemmer"": { ""type"": ""stemmer"", ""language"": ""possessive_english"" } }, ""analyzer"": { ""rebuilt_english"": { ""tokenizer"": ""standard"", ""filter"": [ ""english_possessive_stemmer"", ""lowercase"", ""english_stop"", ""english_keywords"", ""english_stemmer"" ] } } } } } ---------------------------------------------------- // TEST[s/""english_keywords"",//] // TEST[s/\\n$/\\nstartyaml\\n - compare_analyzers: {index: english_example, first: english, second: rebuilt_english}\\nendyaml\\n/] <1> The default stopwords can be overridden with the `stopwords` or `stopwords_path` parameters. <2> This filter should be removed unless there are words which should be excluded from stemming. [[finnish-analyzer]] ===== `finnish` analyzer The `finnish` analyzer could be reimplemented as a `custom` analyzer as follows: [source,console] ---------------------------------------------------- PUT /finnish_example { ""settings"": { ""analysis"": { ""filter"": { ""finnish_stop"": { ""type"": ""stop"", ""stopwords"": ""_finnish_"" <1> }, ""finnish_keywords"": { ""type"": ""keyword_marker"", ""keywords"": [""esimerkki""] <2> }, ""finnish_stemmer"": { ""type"": ""stemmer"", ""language"": ""finnish"" } }, ""analyzer"": { ""rebuilt_finnish"": { ""tokenizer"": ""standard"", ""filter"": [ ""lowercase"", ""finnish_stop"", ""finnish_keywords"", ""finnish_stemmer"" ] } } } } } ---------------------------------------------------- // TEST[s/""finnish_keywords"",//] // TEST[s/\\n$/\\nstartyaml\\n - compare_analyzers: {index: finnish_example, first: finnish, second: rebuilt_finnish}\\nendyaml\\n/] <1> The default stopwords can be overridden with the `stopwords` or `stopwords_path` parameters. <2> This filter should be removed unless there are words which should be excluded from stemming. [[french-analyzer]] ===== `french` analyzer The `french` analyzer could be reimplemented as a `custom` analyzer as follows: [source,console] ---------------------------------------------------- PUT /french_example { ""settings"": { ""analysis"": { ""filter"": { ""french_elision"": { ""type"": ""elision"", ""articles_case"": true, ""articles"": [ ""l"", ""m"", ""t"", ""qu"", ""n"", ""s"", ""j"", ""d"", ""c"", ""jusqu"", ""quoiqu"", ""lorsqu"", ""puisqu"" ] }, ""french_stop"": { ""type"": ""stop"", ""stopwords"": ""_french_"" <1> }, ""french_keywords"": { ""type"": ""keyword_marker"", ""keywords"": [""Example""] <2> }, ""french_stemmer"": { ""type"": ""stemmer"", ""language"": ""light_french"" } }, ""analyzer"": { ""rebuilt_french"": { ""tokenizer"": ""standard"", ""filter"": [ ""french_elision"", ""lowercase"", ""french_stop"", ""french_keywords"", ""french_stemmer"" ] } } } } } ---------------------------------------------------- // TEST[s/""french_keywords"",//] // TEST[s/\\n$/\\nstartyaml\\n - compare_analyzers: {index: french_example, first: french, second: rebuilt_french}\\nendyaml\\n/] <1> The default stopwords can be overridden with the `stopwords` or `stopwords_path` parameters. <2> This filter should be removed unless there are words which should be excluded from stemming. [[galician-analyzer]] ===== `galician` analyzer The `galician` analyzer could be reimplemented as a `custom` analyzer as follows: [source,console] ---------------------------------------------------- PUT /galician_example { ""settings"": { ""analysis"": { ""filter"": { ""galician_stop"": { ""type"": ""stop"", ""stopwords"": ""_galician_"" <1> }, ""galician_keywords"": { ""type"": ""keyword_marker"", ""keywords"": [""exemplo""] <2> }, ""galician_stemmer"": { ""type"": ""stemmer"", ""language"": ""galician"" } }, ""analyzer"": { ""rebuilt_galician"": { ""tokenizer"": ""standard"", ""filter"": [ ""lowercase"", ""galician_stop"", ""galician_keywords"", ""galician_stemmer"" ] } } } } } ---------------------------------------------------- // TEST[s/""galician_keywords"",//] // TEST[s/\\n$/\\nstartyaml\\n - compare_analyzers: {index: galician_example, first: galician, second: rebuilt_galician}\\nendyaml\\n/] <1> The default stopwords can be overridden with the `stopwords` or `stopwords_path` parameters. <2> This filter should be removed unless there are words which should be excluded from stemming. [[german-analyzer]] ===== `german` analyzer The `german` analyzer could be reimplemented as a `custom` analyzer as follows: [source,console] ---------------------------------------------------- PUT /german_example { ""settings"": { ""analysis"": { ""filter"": { ""german_stop"": { ""type"": ""stop"", ""stopwords"": ""_german_"" <1> }, ""german_keywords"": { ""type"": ""keyword_marker"", ""keywords"": [""Beispiel""] <2> }, ""german_stemmer"": { ""type"": ""stemmer"", ""language"": ""light_german"" } }, ""analyzer"": { ""rebuilt_german"": { ""tokenizer"": ""standard"", ""filter"": [ ""lowercase"", ""german_stop"", ""german_keywords"", ""german_normalization"", ""german_stemmer"" ] } } } } } ---------------------------------------------------- // TEST[s/""german_keywords"",//] // TEST[s/\\n$/\\nstartyaml\\n - compare_analyzers: {index: german_example, first: german, second: rebuilt_german}\\nendyaml\\n/] <1> The default stopwords can be overridden with the `stopwords` or `stopwords_path` parameters. <2> This filter should be removed unless there are words which should be excluded from stemming. [[greek-analyzer]] ===== `greek` analyzer The `greek` analyzer could be reimplemented as a `custom` analyzer as follows: [source,console] ---------------------------------------------------- PUT /greek_example { ""settings"": { ""analysis"": { ""filter"": { ""greek_stop"": { ""type"": ""stop"", ""stopwords"": ""_greek_"" <1> }, ""greek_lowercase"": { ""type"": ""lowercase"", ""language"": ""greek"" }, ""greek_keywords"": { ""type"": ""keyword_marker"", ""keywords"": [""παράδειγμα""] <2> }, ""greek_stemmer"": { ""type"": ""stemmer"", ""language"": ""greek"" } }, ""analyzer"": { ""rebuilt_greek"": { ""tokenizer"": ""standard"", ""filter"": [ ""greek_lowercase"", ""greek_stop"", ""greek_keywords"", ""greek_stemmer"" ] } } } } } ---------------------------------------------------- // TEST[s/""greek_keywords"",//] // TEST[s/\\n$/\\nstartyaml\\n - compare_analyzers: {index: greek_example, first: greek, second: rebuilt_greek}\\nendyaml\\n/] <1> The default stopwords can be overridden with the `stopwords` or `stopwords_path` parameters. <2> This filter should be removed unless there are words which should be excluded from stemming. [[hindi-analyzer]] ===== `hindi` analyzer The `hindi` analyzer could be reimplemented as a `custom` analyzer as follows: [source,console] ---------------------------------------------------- PUT /hindi_example { ""settings"": { ""analysis"": { ""filter"": { ""hindi_stop"": { ""type"": ""stop"", ""stopwords"": ""_hindi_"" <1> }, ""hindi_keywords"": { ""type"": ""keyword_marker"", ""keywords"": [""उदाहरण""] <2> }, ""hindi_stemmer"": { ""type"": ""stemmer"", ""language"": ""hindi"" } }, ""analyzer"": { ""rebuilt_hindi"": { ""tokenizer"": ""standard"", ""filter"": [ ""lowercase"", ""decimal_digit"", ""hindi_keywords"", ""indic_normalization"", ""hindi_normalization"", ""hindi_stop"", ""hindi_stemmer"" ] } } } } } ---------------------------------------------------- // TEST[s/""hindi_keywords"",//] // TEST[s/\\n$/\\nstartyaml\\n - compare_analyzers: {index: hindi_example, first: hindi, second: rebuilt_hindi}\\nendyaml\\n/] <1> The default stopwords can be overridden with the `stopwords` or `stopwords_path` parameters. <2> This filter should be removed unless there are words which should be excluded from stemming. [[hungarian-analyzer]] ===== `hungarian` analyzer The `hungarian` analyzer could be reimplemented as a `custom` analyzer as follows: [source,console] ---------------------------------------------------- PUT /hungarian_example { ""settings"": { ""analysis"": { ""filter"": { ""hungarian_stop"": { ""type"": ""stop"", ""stopwords"": ""_hungarian_"" <1> }, ""hungarian_keywords"": { ""type"": ""keyword_marker"", ""keywords"": [""példa""] <2> }, ""hungarian_stemmer"": { ""type"": ""stemmer"", ""language"": ""hungarian"" } }, ""analyzer"": { ""rebuilt_hungarian"": { ""tokenizer"": ""standard"", ""filter"": [ ""lowercase"", ""hungarian_stop"", ""hungarian_keywords"", ""hungarian_stemmer"" ] } } } } } ---------------------------------------------------- // TEST[s/""hungarian_keywords"",//] // TEST[s/\\n$/\\nstartyaml\\n - compare_analyzers: {index: hungarian_example, first: hungarian, second: rebuilt_hungarian}\\nendyaml\\n/] <1> The default stopwords can be overridden with the `stopwords` or `stopwords_path` parameters. <2> This filter should be removed unless there are words which should be excluded from stemming. [[indonesian-analyzer]] ===== `indonesian` analyzer The `indonesian` analyzer could be reimplemented as a `custom` analyzer as follows: [source,console] ---------------------------------------------------- PUT /indonesian_example { ""settings"": { ""analysis"": { ""filter"": { ""indonesian_stop"": { ""type"": ""stop"", ""stopwords"": ""_indonesian_"" <1> }, ""indonesian_keywords"": { ""type"": ""keyword_marker"", ""keywords"": [""contoh""] <2> }, ""indonesian_stemmer"": { ""type"": ""stemmer"", ""language"": ""indonesian"" } }, ""analyzer"": { ""rebuilt_indonesian"": { ""tokenizer"": ""standard"", ""filter"": [ ""lowercase"", ""indonesian_stop"", ""indonesian_keywords"", ""indonesian_stemmer"" ] } } } } } ---------------------------------------------------- // TEST[s/""indonesian_keywords"",//] // TEST[s/\\n$/\\nstartyaml\\n - compare_analyzers: {index: indonesian_example, first: indonesian, second: rebuilt_indonesian}\\nendyaml\\n/] <1> The default stopwords can be overridden with the `stopwords` or `stopwords_path` parameters. <2> This filter should be removed unless there are words which should be excluded from stemming. [[irish-analyzer]] ===== `irish` analyzer The `irish` analyzer could be reimplemented as a `custom` analyzer as follows: [source,console] ---------------------------------------------------- PUT /irish_example { ""settings"": { ""analysis"": { ""filter"": { ""irish_hyphenation"": { ""type"": ""stop"", ""stopwords"": [ ""h"", ""n"", ""t"" ], ""ignore_case"": true }, ""irish_elision"": { ""type"": ""elision"", ""articles"": [ ""d"", ""m"", ""b"" ], ""articles_case"": true }, ""irish_stop"": { ""type"": ""stop"", ""stopwords"": ""_irish_"" <1> }, ""irish_lowercase"": { ""type"": ""lowercase"", ""language"": ""irish"" }, ""irish_keywords"": { ""type"": ""keyword_marker"", ""keywords"": [""sampla""] <2> }, ""irish_stemmer"": { ""type"": ""stemmer"", ""language"": ""irish"" } }, ""analyzer"": { ""rebuilt_irish"": { ""tokenizer"": ""standard"", ""filter"": [ ""irish_hyphenation"", ""irish_elision"", ""irish_lowercase"", ""irish_stop"", ""irish_keywords"", ""irish_stemmer"" ] } } } } } ---------------------------------------------------- // TEST[s/""irish_keywords"",//] // TEST[s/\\n$/\\nstartyaml\\n - compare_analyzers: {index: irish_example, first: irish, second: rebuilt_irish}\\nendyaml\\n/] <1> The default stopwords can be overridden with the `stopwords` or `stopwords_path` parameters. <2> This filter should be removed unless there are words which should be excluded from stemming. [[italian-analyzer]] ===== `italian` analyzer The `italian` analyzer could be reimplemented as a `custom` analyzer as follows: [source,console] ---------------------------------------------------- PUT /italian_example { ""settings"": { ""analysis"": { ""filter"": { ""italian_elision"": { ""type"": ""elision"", ""articles"": [ ""c"", ""l"", ""all"", ""dall"", ""dell"", ""nell"", ""sull"", ""coll"", ""pell"", ""gl"", ""agl"", ""dagl"", ""degl"", ""negl"", ""sugl"", ""un"", ""m"", ""t"", ""s"", ""v"", ""d"" ], ""articles_case"": true }, ""italian_stop"": { ""type"": ""stop"", ""stopwords"": ""_italian_"" <1> }, ""italian_keywords"": { ""type"": ""keyword_marker"", ""keywords"": [""esempio""] <2> }, ""italian_stemmer"": { ""type"": ""stemmer"", ""language"": ""light_italian"" } }, ""analyzer"": { ""rebuilt_italian"": { ""tokenizer"": ""standard"", ""filter"": [ ""italian_elision"", ""lowercase"", ""italian_stop"", ""italian_keywords"", ""italian_stemmer"" ] } } } } } ---------------------------------------------------- // TEST[s/""italian_keywords"",//] // TEST[s/\\n$/\\nstartyaml\\n - compare_analyzers: {index: italian_example, first: italian, second: rebuilt_italian}\\nendyaml\\n/] <1> The default stopwords can be overridden with the `stopwords` or `stopwords_path` parameters. <2> This filter should be removed unless there are words which should be excluded from stemming. [[latvian-analyzer]] ===== `latvian` analyzer The `latvian` analyzer could be reimplemented as a `custom` analyzer as follows: [source,console] ---------------------------------------------------- PUT /latvian_example { ""settings"": { ""analysis"": { ""filter"": { ""latvian_stop"": { ""type"": ""stop"", ""stopwords"": ""_latvian_"" <1> }, ""latvian_keywords"": { ""type"": ""keyword_marker"", ""keywords"": [""piemērs""] <2> }, ""latvian_stemmer"": { ""type"": ""stemmer"", ""language"": ""latvian"" } }, ""analyzer"": { ""rebuilt_latvian"": { ""tokenizer"": ""standard"", ""filter"": [ ""lowercase"", ""latvian_stop"", ""latvian_keywords"", ""latvian_stemmer"" ] } } } } } ---------------------------------------------------- // TEST[s/""latvian_keywords"",//] // TEST[s/\\n$/\\nstartyaml\\n - compare_analyzers: {index: latvian_example, first: latvian, second: rebuilt_latvian}\\nendyaml\\n/] <1> The default stopwords can be overridden with the `stopwords` or `stopwords_path` parameters. <2> This filter should be removed unless there are words which should be excluded from stemming. [[lithuanian-analyzer]] ===== `lithuanian` analyzer The `lithuanian` analyzer could be reimplemented as a `custom` analyzer as follows: [source,console] ---------------------------------------------------- PUT /lithuanian_example { ""settings"": { ""analysis"": { ""filter"": { ""lithuanian_stop"": { ""type"": ""stop"", ""stopwords"": ""_lithuanian_"" <1> }, ""lithuanian_keywords"": { ""type"": ""keyword_marker"", ""keywords"": [""pavyzdys""] <2> }, ""lithuanian_stemmer"": { ""type"": ""stemmer"", ""language"": ""lithuanian"" } }, ""analyzer"": { ""rebuilt_lithuanian"": { ""tokenizer"": ""standard"", ""filter"": [ ""lowercase"", ""lithuanian_stop"", ""lithuanian_keywords"", ""lithuanian_stemmer"" ] } } } } } ---------------------------------------------------- // TEST[s/""lithuanian_keywords"",//] // TEST[s/\\n$/\\nstartyaml\\n - compare_analyzers: {index: lithuanian_example, first: lithuanian, second: rebuilt_lithuanian}\\nendyaml\\n/] <1> The default stopwords can be overridden with the `stopwords` or `stopwords_path` parameters. <2> This filter should be removed unless there are words which should be excluded from stemming. [[norwegian-analyzer]] ===== `norwegian` analyzer The `norwegian` analyzer could be reimplemented as a `custom` analyzer as follows: [source,console] ---------------------------------------------------- PUT /norwegian_example { ""settings"": { ""analysis"": { ""filter"": { ""norwegian_stop"": { ""type"": ""stop"", ""stopwords"": ""_norwegian_"" <1> }, ""norwegian_keywords"": { ""type"": ""keyword_marker"", ""keywords"": [""eksempel""] <2> }, ""norwegian_stemmer"": { ""type"": ""stemmer"", ""language"": ""norwegian"" } }, ""analyzer"": { ""rebuilt_norwegian"": { ""tokenizer"": ""standard"", ""filter"": [ ""lowercase"", ""norwegian_stop"", ""norwegian_keywords"", ""norwegian_stemmer"" ] } } } } } ---------------------------------------------------- // TEST[s/""norwegian_keywords"",//] // TEST[s/\\n$/\\nstartyaml\\n - compare_analyzers: {index: norwegian_example, first: norwegian, second: rebuilt_norwegian}\\nendyaml\\n/] <1> The default stopwords can be overridden with the `stopwords` or `stopwords_path` parameters. <2> This filter should be removed unless there are words which should be excluded from stemming. [[persian-analyzer]] ===== `persian` analyzer The `persian` analyzer could be reimplemented as a `custom` analyzer as follows: [source,console] ---------------------------------------------------- PUT /persian_example { ""settings"": { ""analysis"": { ""char_filter"": { ""zero_width_spaces"": { ""type"": ""mapping"", ""mappings"": [ ""\\\\u200C=>\\\\u0020""] <1> } }, ""filter"": { ""persian_stop"": { ""type"": ""stop"", ""stopwords"": ""_persian_"" <2> } }, ""analyzer"": { ""rebuilt_persian"": { ""tokenizer"": ""standard"", ""char_filter"": [ ""zero_width_spaces"" ], ""filter"": [ ""lowercase"", ""decimal_digit"", ""arabic_normalization"", ""persian_normalization"", ""persian_stop"" ] } } } } } ---------------------------------------------------- // TEST[s/\\n$/\\nstartyaml\\n - compare_analyzers: {index: persian_example, first: persian, second: rebuilt_persian}\\nendyaml\\n/] <1> Replaces zero-width non-joiners with an ASCII space. <2> The default stopwords can be overridden with the `stopwords` or `stopwords_path` parameters. [[portuguese-analyzer]] ===== `portuguese` analyzer The `portuguese` analyzer could be reimplemented as a `custom` analyzer as follows: [source,console] ---------------------------------------------------- PUT /portuguese_example { ""settings"": { ""analysis"": { ""filter"": { ""portuguese_stop"": { ""type"": ""stop"", ""stopwords"": ""_portuguese_"" <1> }, ""portuguese_keywords"": { ""type"": ""keyword_marker"", ""keywords"": [""exemplo""] <2> }, ""portuguese_stemmer"": { ""type"": ""stemmer"", ""language"": ""light_portuguese"" } }, ""analyzer"": { ""rebuilt_portuguese"": { ""tokenizer"": ""standard"", ""filter"": [ ""lowercase"", ""portuguese_stop"", ""portuguese_keywords"", ""portuguese_stemmer"" ] } } } } } ---------------------------------------------------- // TEST[s/""portuguese_keywords"",//] // TEST[s/\\n$/\\nstartyaml\\n - compare_analyzers: {index: portuguese_example, first: portuguese, second: rebuilt_portuguese}\\nendyaml\\n/] <1> The default stopwords can be overridden with the `stopwords` or `stopwords_path` parameters. <2> This filter should be removed unless there are words which should be excluded from stemming. [[romanian-analyzer]] ===== `romanian` analyzer The `romanian` analyzer could be reimplemented as a `custom` analyzer as follows: [source,console] ---------------------------------------------------- PUT /romanian_example { ""settings"": { ""analysis"": { ""filter"": { ""romanian_stop"": { ""type"": ""stop"", ""stopwords"": ""_romanian_"" <1> }, ""romanian_keywords"": { ""type"": ""keyword_marker"", ""keywords"": [""exemplu""] <2> }, ""romanian_stemmer"": { ""type"": ""stemmer"", ""language"": ""romanian"" } }, ""analyzer"": { ""rebuilt_romanian"": { ""tokenizer"": ""standard"", ""filter"": [ ""lowercase"", ""romanian_stop"", ""romanian_keywords"", ""romanian_stemmer"" ] } } } } } ---------------------------------------------------- // TEST[s/""romanian_keywords"",//] // TEST[s/\\n$/\\nstartyaml\\n - compare_analyzers: {index: romanian_example, first: romanian, second: rebuilt_romanian}\\nendyaml\\n/] <1> The default stopwords can be overridden with the `stopwords` or `stopwords_path` parameters. <2> This filter should be removed unless there are words which should be excluded from stemming. [[russian-analyzer]] ===== `russian` analyzer The `russian` analyzer could be reimplemented as a `custom` analyzer as follows: [source,console] ---------------------------------------------------- PUT /russian_example { ""settings"": { ""analysis"": { ""filter"": { ""russian_stop"": { ""type"": ""stop"", ""stopwords"": ""_russian_"" <1> }, ""russian_keywords"": { ""type"": ""keyword_marker"", ""keywords"": [""пример""] <2> }, ""russian_stemmer"": { ""type"": ""stemmer"", ""language"": ""russian"" } }, ""analyzer"": { ""rebuilt_russian"": { ""tokenizer"": ""standard"", ""filter"": [ ""lowercase"", ""russian_stop"", ""russian_keywords"", ""russian_stemmer"" ] } } } } } ---------------------------------------------------- // TEST[s/""russian_keywords"",//] // TEST[s/\\n$/\\nstartyaml\\n - compare_analyzers: {index: russian_example, first: russian, second: rebuilt_russian}\\nendyaml\\n/] <1> The default stopwords can be overridden with the `stopwords` or `stopwords_path` parameters. <2> This filter should be removed unless there are words which should be excluded from stemming. [[sorani-analyzer]] ===== `sorani` analyzer The `sorani` analyzer could be reimplemented as a `custom` analyzer as follows: [source,console] ---------------------------------------------------- PUT /sorani_example { ""settings"": { ""analysis"": { ""filter"": { ""sorani_stop"": { ""type"": ""stop"", ""stopwords"": ""_sorani_"" <1> }, ""sorani_keywords"": { ""type"": ""keyword_marker"", ""keywords"": [""mînak""] <2> }, ""sorani_stemmer"": { ""type"": ""stemmer"", ""language"": ""sorani"" } }, ""analyzer"": { ""rebuilt_sorani"": { ""tokenizer"": ""standard"", ""filter"": [ ""sorani_normalization"", ""lowercase"", ""decimal_digit"", ""sorani_stop"", ""sorani_keywords"", ""sorani_stemmer"" ] } } } } } ---------------------------------------------------- // TEST[s/""sorani_keywords"",//] // TEST[s/\\n$/\\nstartyaml\\n - compare_analyzers: {index: sorani_example, first: sorani, second: rebuilt_sorani}\\nendyaml\\n/] <1> The default stopwords can be overridden with the `stopwords` or `stopwords_path` parameters. <2> This filter should be removed unless there are words which should be excluded from stemming. [[spanish-analyzer]] ===== `spanish` analyzer The `spanish` analyzer could be reimplemented as a `custom` analyzer as follows: [source,console] ---------------------------------------------------- PUT /spanish_example { ""settings"": { ""analysis"": { ""filter"": { ""spanish_stop"": { ""type"": ""stop"", ""stopwords"": ""_spanish_"" <1> }, ""spanish_keywords"": { ""type"": ""keyword_marker"", ""keywords"": [""ejemplo""] <2> }, ""spanish_stemmer"": { ""type"": ""stemmer"", ""language"": ""light_spanish"" } }, ""analyzer"": { ""rebuilt_spanish"": { ""tokenizer"": ""standard"", ""filter"": [ ""lowercase"", ""spanish_stop"", ""spanish_keywords"", ""spanish_stemmer"" ] } } } } } ---------------------------------------------------- // TEST[s/""spanish_keywords"",//] // TEST[s/\\n$/\\nstartyaml\\n - compare_analyzers: {index: spanish_example, first: spanish, second: rebuilt_spanish}\\nendyaml\\n/] <1> The default stopwords can be overridden with the `stopwords` or `stopwords_path` parameters. <2> This filter should be removed unless there are words which should be excluded from stemming. [[swedish-analyzer]] ===== `swedish` analyzer The `swedish` analyzer could be reimplemented as a `custom` analyzer as follows: [source,console] ---------------------------------------------------- PUT /swedish_example { ""settings"": { ""analysis"": { ""filter"": { ""swedish_stop"": { ""type"": ""stop"", ""stopwords"": ""_swedish_"" <1> }, ""swedish_keywords"": { ""type"": ""keyword_marker"", ""keywords"": [""exempel""] <2> }, ""swedish_stemmer"": { ""type"": ""stemmer"", ""language"": ""swedish"" } }, ""analyzer"": { ""rebuilt_swedish"": { ""tokenizer"": ""standard"", ""filter"": [ ""lowercase"", ""swedish_stop"", ""swedish_keywords"", ""swedish_stemmer"" ] } } } } } ---------------------------------------------------- // TEST[s/""swedish_keywords"",//] // TEST[s/\\n$/\\nstartyaml\\n - compare_analyzers: {index: swedish_example, first: swedish, second: rebuilt_swedish}\\nendyaml\\n/] <1> The default stopwords can be overridden with the `stopwords` or `stopwords_path` parameters. <2> This filter should be removed unless there are words which should be excluded from stemming. [[turkish-analyzer]] ===== `turkish` analyzer The `turkish` analyzer could be reimplemented as a `custom` analyzer as follows: [source,console] ---------------------------------------------------- PUT /turkish_example { ""settings"": { ""analysis"": { ""filter"": { ""turkish_stop"": { ""type"": ""stop"", ""stopwords"": ""_turkish_"" <1> }, ""turkish_lowercase"": { ""type"": ""lowercase"", ""language"": ""turkish"" }, ""turkish_keywords"": { ""type"": ""keyword_marker"", ""keywords"": [""örnek""] <2> }, ""turkish_stemmer"": { ""type"": ""stemmer"", ""language"": ""turkish"" } }, ""analyzer"": { ""rebuilt_turkish"": { ""tokenizer"": ""standard"", ""filter"": [ ""apostrophe"", ""turkish_lowercase"", ""turkish_stop"", ""turkish_keywords"", ""turkish_stemmer"" ] } } } } } ---------------------------------------------------- // TEST[s/""turkish_keywords"",//] // TEST[s/\\n$/\\nstartyaml\\n - compare_analyzers: {index: turkish_example, first: turkish, second: rebuilt_turkish}\\nendyaml\\n/] <1> The default stopwords can be overridden with the `stopwords` or `stopwords_path` parameters. <2> This filter should be removed unless there are words which should be excluded from stemming. [[thai-analyzer]] ===== `thai` analyzer The `thai` analyzer could be reimplemented as a `custom` analyzer as follows: [source,console] ---------------------------------------------------- PUT /thai_example { ""settings"": { ""analysis"": { ""filter"": { ""thai_stop"": { ""type"": ""stop"", ""stopwords"": ""_thai_"" <1> } }, ""analyzer"": { ""rebuilt_thai"": { ""tokenizer"": ""thai"", ""filter"": [ ""lowercase"", ""decimal_digit"", ""thai_stop"" ] } } } } } ---------------------------------------------------- // TEST[s/""thai_keywords"",//] // TEST[s/\\n$/\\nstartyaml\\n - compare_analyzers: {index: thai_example, first: thai, second: rebuilt_thai}\\nendyaml\\n/] <1> The default stopwords can be overridden with the `stopwords` or `stopwords_path` parameters. ",12266,True,4115.462492122191,median "[[oauth2resourceserver]] == OAuth 2.0 Resource Server Spring Security supports protecting endpoints using two forms of OAuth 2.0 https://tools.ietf.org/html/rfc6750.html[Bearer Tokens]: * https://tools.ietf.org/html/rfc7519[JWT] * Opaque Tokens This is handy in circumstances where an application has delegated its authority management to an https://tools.ietf.org/html/rfc6749[authorization server] (for example, Okta or Ping Identity). This authorization server can be consulted by resource servers to authorize requests. [NOTE] ==== Working samples for both {gh-samples-url}/boot/oauth2resourceserver[JWTs] and {gh-samples-url}/boot/oauth2resourceserver-opaque[Opaque Tokens] are available in the {gh-samples-url}[Spring Security repository]. ==== === Dependencies Most Resource Server support is collected into `spring-security-oauth2-resource-server`. However, the support for decoding and verifying JWTs is in `spring-security-oauth2-jose`, meaning that both are necessary in order to have a working resource server that supports JWT-encoded Bearer Tokens. [[oauth2resourceserver-jwt-minimalconfiguration]] === Minimal Configuration for JWTs When using https://spring.io/projects/spring-boot[Spring Boot], configuring an application as a resource server consists of two basic steps. First, include the needed dependencies and second, indicate the location of the authorization server. ==== Specifying the Authorization Server In a Spring Boot application, to specify which authorization server to use, simply do: [source,yml] ---- spring: security: oauth2: resourceserver: jwt: issuer-uri: https://idp.example.com/issuer ---- Where `https://idp.example.com/issuer` is the value contained in the `iss` claim for JWT tokens that the authorization server will issue. Resource Server will use this property to further self-configure, discover the authorization server's public keys, and subsequently validate incoming JWTs. [NOTE] To use the `issuer-uri` property, it must also be true that one of `https://idp.example.com/issuer/.well-known/openid-configuration`, `https://idp.example.com/.well-known/openid-configuration/issuer`, or `https://idp.example.com/.well-known/oauth-authorization-server/issuer` is a supported endpoint for the authorization server. This endpoint is referred to as a https://openid.net/specs/openid-connect-discovery-1_0.html#ProviderConfig[Provider Configuration] endpoint or a https://tools.ietf.org/html/rfc8414#section-3[Authorization Server Metadata] endpoint. And that's it! ==== Startup Expectations When this property and these dependencies are used, Resource Server will automatically configure itself to validate JWT-encoded Bearer Tokens. It achieves this through a deterministic startup process: 1. Hit the Provider Configuration or Authorization Server Metadata endpoint, processing the response for the `jwks_url` property 2. Configure the validation strategy to query `jwks_url` for valid public keys 3. Configure the validation strategy to validate each JWTs `iss` claim against `https://idp.example.com`. A consequence of this process is that the authorization server must be up and receiving requests in order for Resource Server to successfully start up. [NOTE] If the authorization server is down when Resource Server queries it (given appropriate timeouts), then startup will fail. ==== Runtime Expectations Once the application is started up, Resource Server will attempt to process any request containing an `Authorization: Bearer` header: [source,html] ---- GET / HTTP/1.1 Authorization: Bearer some-token-value # Resource Server will process this ---- So long as this scheme is indicated, Resource Server will attempt to process the request according to the Bearer Token specification. Given a well-formed JWT, Resource Server will: 1. Validate its signature against a public key obtained from the `jwks_url` endpoint during startup and matched against the JWT 2. Validate the JWT's `exp` and `nbf` timestamps and the JWT's `iss` claim, and 3. Map each scope to an authority with the prefix `SCOPE_`. [NOTE] As the authorization server makes available new keys, Spring Security will automatically rotate the keys used to validate JWTs. The resulting `Authentication#getPrincipal`, by default, is a Spring Security `Jwt` object, and `Authentication#getName` maps to the JWT's `sub` property, if one is present. From here, consider jumping to: <> <> [[oauth2resourceserver-jwt-jwkseturi]] === Specifying the Authorization Server JWK Set Uri Directly If the authorization server doesn't support any configuration endpoints, or if Resource Server must be able to start up independently from the authorization server, then the `jwk-set-uri` can be supplied as well: [source,yaml] ---- spring: security: oauth2: resourceserver: jwt: issuer-uri: https://idp.example.com jwk-set-uri: https://idp.example.com/.well-known/jwks.json ---- [NOTE] The JWK Set uri is not standardized, but can typically be found in the authorization server's documentation Consequently, Resource Server will not ping the authorization server at startup. We still specify the `issuer-uri` so that Resource Server still validates the `iss` claim on incoming JWTs. [NOTE] This property can also be supplied directly on the <>. [[oauth2resourceserver-jwt-sansboot]] === Overriding or Replacing Boot Auto Configuration There are two `@Bean` s that Spring Boot generates on Resource Server's behalf. The first is a `WebSecurityConfigurerAdapter` that configures the app as a resource server. When including `spring-security-oauth2-jose`, this `WebSecurityConfigurerAdapter` looks like: [source,java] ---- protected void configure(HttpSecurity http) { http .authorizeRequests() .anyRequest().authenticated() .and() .oauth2ResourceServer(OAuth2ResourceServerConfigurer::jwt) } ---- If the application doesn't expose a `WebSecurityConfigurerAdapter` bean, then Spring Boot will expose the above default one. Replacing this is as simple as exposing the bean within the application: [source,java] ---- @EnableWebSecurity public class MyCustomSecurityConfiguration extends WebSecurityConfigurerAdapter { protected void configure(HttpSecurity http) { http .authorizeRequests() .mvcMatchers(""/messages/**"").hasAuthority(""SCOPE_message:read"") .anyRequest().authenticated() .and() .oauth2ResourceServer() .jwt() .jwtAuthenticationConverter(myConverter()); } } ---- The above requires the scope of `message:read` for any URL that starts with `/messages/`. Methods on the `oauth2ResourceServer` DSL will also override or replace auto configuration. For example, the second `@Bean` Spring Boot creates is a `JwtDecoder`, which decodes `String` tokens into validated instances of `Jwt`: [source,java] ---- @Bean public JwtDecoder jwtDecoder() { return JwtDecoders.fromIssuerLocation(issuerUri); } ---- [NOTE] Calling `{security-api-url}org/springframework/security/oauth2/jwt/JwtDecoders.html#fromIssuerLocation-java.lang.String-[JwtDecoders#fromIssuerLocation]` is what invokes the Provider Configuration or Authorization Server Metadata endpoint in order to derive the JWK Set Uri. If the application doesn't expose a `JwtDecoder` bean, then Spring Boot will expose the above default one. And its configuration can be overridden using `jwkSetUri()` or replaced using `decoder()`. [[oauth2resourceserver-jwt-jwkseturi-dsl]] ==== Using `jwkSetUri()` An authorization server's JWK Set Uri can be configured <> or it can be supplied in the DSL: [source,java] ---- @EnableWebSecurity public class DirectlyConfiguredJwkSetUri extends WebSecurityConfigurerAdapter { protected void configure(HttpSecurity http) { http .authorizeRequests() .anyRequest().authenticated() .and() .oauth2ResourceServer() .jwt() .jwkSetUri(""https://idp.example.com/.well-known/jwks.json""); } } ---- Using `jwkSetUri()` takes precedence over any configuration property. [[oauth2resourceserver-jwt-decoder-dsl]] ==== Using `decoder()` More powerful than `jwkSetUri()` is `decoder()`, which will completely replace any Boot auto configuration of `JwtDecoder`: [source,java] ---- @EnableWebSecurity public class DirectlyConfiguredJwtDecoder extends WebSecurityConfigurerAdapter { protected void configure(HttpSecurity http) { http .authorizeRequests() .anyRequest().authenticated() .and() .oauth2ResourceServer() .jwt() .decoder(myCustomDecoder()); } } ---- This is handy when deeper configuration, like <>, <>, or <>, is necessary. [[oauth2resourceserver-jwt-decoder-bean]] ==== Exposing a `JwtDecoder` `@Bean` Or, exposing a `JwtDecoder` `@Bean` has the same effect as `decoder()`: [source,java] ---- @Bean public JwtDecoder jwtDecoder() { return NimbusJwtDecoder.withJwkSetUri(jwkSetUri).build(); } ---- [[oauth2resourceserver-jwt-decoder-algorithm]] === Configuring Trusted Algorithms By default, `NimbusJwtDecoder`, and hence Resource Server, will only trust and verify tokens using `RS256`. You can customize this via <>, <>, or from the <>. [[oauth2resourceserver-jwt-boot-algorithm]] ==== Via Spring Boot The simplest way to set the algorithm is as a property: [source,yaml] ---- spring: security: oauth2: resourceserver: jwt: jws-algorithm: RS512 jwk-set-uri: https://idp.example.org/.well-known/jwks.json ---- [[oauth2resourceserver-jwt-decoder-builder]] ==== Using a Builder For greater power, though, we can use a builder that ships with `NimbusJwtDecoder`: [source,java] ---- @Bean JwtDecoder jwtDecoder() { return NimbusJwtDecoder.fromJwkSetUri(this.jwkSetUri) .jwsAlgorithm(RS512).build(); } ---- Calling `jwsAlgorithm` more than once will configure `NimbusJwtDecoder` to trust more than one algorithm, like so: [source,java] ---- @Bean JwtDecoder jwtDecoder() { return NimbusJwtDecoder.fromJwkSetUri(this.jwkSetUri) .jwsAlgorithm(RS512).jwsAlgorithm(EC512).build(); } ---- Or, you can call `jwsAlgorithms`: [source,java] ---- @Bean JwtDecoder jwtDecoder() { return NimbusJwtDecoder.fromJwkSetUri(this.jwkSetUri) .jwsAlgorithms(algorithms -> { algorithms.add(RS512); algorithms.add(EC512); }).build(); } ---- [[oauth2resourceserver-jwt-decoder-jwk-response]] ==== From JWK Set response Since Spring Security's JWT support is based off of Nimbus, you can use all it's great features as well. For example, Nimbus has a `JWSKeySelector` implementation that will select the set of algorithms based on the JWK Set URI response. You can use it to generate a `NimbusJwtDecoder` like so: ```java @Bean public JwtDecoder jwtDecoder() { // makes a request to the JWK Set endpoint JWSKeySelector jwsKeySelector = JWSAlgorithmFamilyJWSKeySelector.fromJWKSetURL(this.jwkSetUrl); DefaultJWTProcessor jwtProcessor = new DefaultJWTProcessor<>(); jwtProcessor.setJWSKeySelector(jwsKeySelector); return new NimbusJwtDecoder(jwtProcessor); } ``` [[oauth2resourceserver-jwt-decoder-public-key]] === Trusting a Single Asymmetric Key Simpler than backing a Resource Server with a JWK Set endpoint is to hard-code an RSA public key. The public key can be provided via <> or by <>. [[oauth2resourceserver-jwt-decoder-public-key-boot]] ==== Via Spring Boot Specifying a key via Spring Boot is quite simple. The key's location can be specified like so: [source,yaml] ---- spring: security: oauth2: resourceserver: jwt: public-key-location: classpath:my-key.pub ---- Or, to allow for a more sophisticated lookup, you can post-process the `RsaKeyConversionServicePostProcessor`: [source,java] ---- @Bean BeanFactoryPostProcessor conversionServiceCustomizer() { return beanFactory -> beanFactory.getBean(RsaKeyConversionServicePostProcessor.class) .setResourceLoader(new CustomResourceLoader()); } ---- Specify your key's location: ```yaml key.location: hfds://my-key.pub ``` And then autowire the value: ```java @Value(""${key.location}"") RSAPublicKey key; ``` [[oauth2resourceserver-jwt-decoder-public-key-builder]] ==== Using a Builder To wire an `RSAPublicKey` directly, you can simply use the appropriate `NimbusJwtDecoder` builder, like so: ```java @Bean public JwtDecoder jwtDecoder() { return NimbusJwtDecoder.withPublicKey(this.key).build(); } ``` [[oauth2resourceserver-jwt-decoder-secret-key]] === Trusting a Single Symmetric Key Using a single symmetric key is also simple. You can simply load in your `SecretKey` and use the appropriate `NimbusJwtDecoder` builder, like so: [source,java] ---- @Bean public JwtDecoder jwtDecoder() { return NimbusJwtDecoder.withSecretKey(this.key).build(); } ---- [[oauth2resourceserver-jwt-authorization]] === Configuring Authorization A JWT that is issued from an OAuth 2.0 Authorization Server will typically either have a `scope` or `scp` attribute, indicating the scopes (or authorities) it's been granted, for example: `{ ..., ""scope"" : ""messages contacts""}` When this is the case, Resource Server will attempt to coerce these scopes into a list of granted authorities, prefixing each scope with the string ""SCOPE_"". This means that to protect an endpoint or method with a scope derived from a JWT, the corresponding expressions should include this prefix: [source,java] ---- @EnableWebSecurity public class DirectlyConfiguredJwkSetUri extends WebSecurityConfigurerAdapter { protected void configure(HttpSecurity http) { http .authorizeRequests(authorizeRequests -> authorizeRequests .mvcMatchers(""/contacts/**"").hasAuthority(""SCOPE_contacts"") .mvcMatchers(""/messages/**"").hasAuthority(""SCOPE_messages"") .anyRequest().authenticated() ) .oauth2ResourceServer(OAuth2ResourceServerConfigurer::jwt); } } ---- Or similarly with method security: [source,java] ---- @PreAuthorize(""hasAuthority('SCOPE_messages')"") public List getMessages(...) {} ---- [[oauth2resourceserver-jwt-authorization-extraction]] ==== Extracting Authorities Manually However, there are a number of circumstances where this default is insufficient. For example, some authorization servers don't use the `scope` attribute, but instead have their own custom attribute. Or, at other times, the resource server may need to adapt the attribute or a composition of attributes into internalized authorities. To this end, the DSL exposes `jwtAuthenticationConverter()`: [source,java] ---- @EnableWebSecurity public class DirectlyConfiguredJwkSetUri extends WebSecurityConfigurerAdapter { protected void configure(HttpSecurity http) { http .authorizeRequests() .anyRequest().authenticated() .and() .oauth2ResourceServer() .jwt() .jwtAuthenticationConverter(grantedAuthoritiesExtractor()); } } Converter grantedAuthoritiesExtractor() { JwtAuthenticationConverter jwtAuthenticationConverter = new JwtAuthenticationConverter(); jwtAuthenticationConverter.setJwtGrantedAuthoritiesConverter (new GrantedAuthoritiesExtractor()); return jwtAuthenticationConverter; } ---- which is responsible for converting a `Jwt` into an `Authentication`. As part of its configuration, we can supply a subsidiary converter to go from `Jwt` to a `Collection` of granted authorities. That final converter might be something like `GrantedAuthoritiesExtractor` below: [source,java] ---- static class GrantedAuthoritiesExtractor implements Converter> { public Collection convert(Jwt jwt) { Collection authorities = (Collection) jwt.getClaims().get(""mycustomclaim""); return authorities.stream() .map(SimpleGrantedAuthority::new) .collect(Collectors.toList()); } } ---- For more flexibility, the DSL supports entirely replacing the converter with any class that implements `Converter`: [source,java] ---- static class CustomAuthenticationConverter implements Converter { public AbstractAuthenticationToken convert(Jwt jwt) { return new CustomAuthenticationToken(jwt); } } ---- [[oauth2resourceserver-jwt-validation]] === Configuring Validation Using <>, indicating the authorization server's issuer uri, Resource Server will default to verifying the `iss` claim as well as the `exp` and `nbf` timestamp claims. In circumstances where validation needs to be customized, Resource Server ships with two standard validators and also accepts custom `OAuth2TokenValidator` instances. [[oauth2resourceserver-jwt-validation-clockskew]] ==== Customizing Timestamp Validation JWT's typically have a window of validity, with the start of the window indicated in the `nbf` claim and the end indicated in the `exp` claim. However, every server can experience clock drift, which can cause tokens to appear expired to one server, but not to another. This can cause some implementation heartburn as the number of collaborating servers increases in a distributed system. Resource Server uses `JwtTimestampValidator` to verify a token's validity window, and it can be configured with a `clockSkew` to alleviate the above problem: [source,java] ---- @Bean JwtDecoder jwtDecoder() { NimbusJwtDecoder jwtDecoder = (NimbusJwtDecoder) JwtDecoders.fromIssuerLocation(issuerUri); OAuth2TokenValidator withClockSkew = new DelegatingOAuth2TokenValidator<>( new JwtTimestampValidator(Duration.ofSeconds(60)), new IssuerValidator(issuerUri)); jwtDecoder.setJwtValidator(withClockSkew); return jwtDecoder; } ---- [NOTE] By default, Resource Server configures a clock skew of 30 seconds. [[oauth2resourceserver-jwt-validation-custom]] ==== Configuring a Custom Validator Adding a check for the `aud` claim is simple with the `OAuth2TokenValidator` API: [source,java] ---- public class AudienceValidator implements OAuth2TokenValidator { OAuth2Error error = new OAuth2Error(""invalid_token"", ""The required audience is missing"", null); public OAuth2TokenValidatorResult validate(Jwt jwt) { if (jwt.getAudience().contains(""messaging"")) { return OAuth2TokenValidatorResult.success(); } else { return OAuth2TokenValidatorResult.failure(error); } } } ---- Then, to add into a resource server, it's a matter of specifying the `JwtDecoder` instance: [source,java] ---- @Bean JwtDecoder jwtDecoder() { NimbusJwtDecoder jwtDecoder = (NimbusJwtDecoder) JwtDecoders.fromIssuerLocation(issuerUri); OAuth2TokenValidator audienceValidator = new AudienceValidator(); OAuth2TokenValidator withIssuer = JwtValidators.createDefaultWithIssuer(issuerUri); OAuth2TokenValidator withAudience = new DelegatingOAuth2TokenValidator<>(withIssuer, audienceValidator); jwtDecoder.setJwtValidator(withAudience); return jwtDecoder; } ---- [[oauth2resourceserver-jwt-claimsetmapping]] === Configuring Claim Set Mapping Spring Security uses the https://bitbucket.org/connect2id/nimbus-jose-jwt/wiki/Home[Nimbus] library for parsing JWTs and validating their signatures. Consequently, Spring Security is subject to Nimbus's interpretation of each field value and how to coerce each into a Java type. For example, because Nimbus remains Java 7 compatible, it doesn't use `Instant` to represent timestamp fields. And it's entirely possible to use a different library or for JWT processing, which may make its own coercion decisions that need adjustment. Or, quite simply, a resource server may want to add or remove claims from a JWT for domain-specific reasons. For these purposes, Resource Server supports mapping the JWT claim set with `MappedJwtClaimSetConverter`. [[oauth2resourceserver-jwt-claimsetmapping-singleclaim]] ==== Customizing the Conversion of a Single Claim By default, `MappedJwtClaimSetConverter` will attempt to coerce claims into the following types: |============ | Claim | Java Type | `aud` | `Collection` | `exp` | `Instant` | `iat` | `Instant` | `iss` | `String` | `jti` | `String` | `nbf` | `Instant` | `sub` | `String` |============ An individual claim's conversion strategy can be configured using `MappedJwtClaimSetConverter.withDefaults`: ```java @Bean JwtDecoder jwtDecoder() { NimbusJwtDecoder jwtDecoder = NimbusJwtDecoder.withJwkSetUri(jwkSetUri).build(); MappedJwtClaimSetConverter converter = MappedJwtClaimSetConverter .withDefaults(Collections.singletonMap(""sub"", this::lookupUserIdBySub)); jwtDecoder.setClaimSetConverter(converter); return jwtDecoder; } ``` This will keep all the defaults, except it will override the default claim converter for `sub`. [[oauth2resourceserver-jwt-claimsetmapping-add]] ==== Adding a Claim `MappedJwtClaimSetConverter` can also be used to add a custom claim, for example, to adapt to an existing system: ```java MappedJwtClaimSetConverter.withDefaults(Collections.singletonMap(""custom"", custom -> ""value"")); ``` [[oauth2resourceserver-jwt-claimsetmapping-remove]] ==== Removing a Claim And removing a claim is also simple, using the same API: ```java MappedJwtClaimSetConverter.withDefaults(Collections.singletonMap(""legacyclaim"", legacy -> null)); ``` [[oauth2resourceserver-jwt-claimsetmapping-rename]] ==== Renaming a Claim In more sophisticated scenarios, like consulting multiple claims at once or renaming a claim, Resource Server accepts any class that implements `Converter, Map>`: ```java public class UsernameSubClaimAdapter implements Converter, Map> { private final MappedJwtClaimSetConverter delegate = MappedJwtClaimSetConverter.withDefaults(Collections.emptyMap()); public Map convert(Map claims) { Map convertedClaims = this.delegate.convert(claims); String username = (String) convertedClaims.get(""user_name""); convertedClaims.put(""sub"", username); return convertedClaims; } } ``` And then, the instance can be supplied like normal: ```java @Bean JwtDecoder jwtDecoder() { NimbusJwtDecoder jwtDecoder = NimbusJwtDecoder.withJwkSetUri(jwkSetUri).build(); jwtDecoder.setClaimSetConverter(new UsernameSubClaimAdapter()); return jwtDecoder; } ``` [[oauth2resourceserver-jwt-timeouts]] === Configuring Timeouts By default, Resource Server uses connection and socket timeouts of 30 seconds each for coordinating with the authorization server. This may be too short in some scenarios. Further, it doesn't take into account more sophisticated patterns like back-off and discovery. To adjust the way in which Resource Server connects to the authorization server, `NimbusJwtDecoder` accepts an instance of `RestOperations`: ```java @Bean public JwtDecoder jwtDecoder(RestTemplateBuilder builder) { RestOperations rest = builder .setConnectionTimeout(60000) .setReadTimeout(60000) .build(); NimbusJwtDecoder jwtDecoder = NimbusJwtDecoder.withJwkSetUri(jwkSetUri).restOperations(rest).build(); return jwtDecoder; } ``` [[oauth2resourceserver-opaque-minimalconfiguration]] === Minimal Configuration for Introspection Typically, an opaque token can be verified via an https://tools.ietf.org/html/rfc7662[OAuth 2.0 Introspection Endpoint], hosted by the authorization server. This can be handy when revocation is a requirement. When using https://spring.io/projects/spring-boot[Spring Boot], configuring an application as a resource server that uses introspection consists of two basic steps. First, include the needed dependencies and second, indicate the introspection endpoint details. ==== Specifying the Authorization Server To specify where the introspection endpoint is, simply do: [source,yaml] ---- security: oauth2: resourceserver: opaque-token: introspection-uri: https://idp.example.com/introspect client-id: client client-secret: secret ---- Where `https://idp.example.com/introspect` is the introspection endpoint hosted by your authorization server and `client-id` and `client-secret` are the credentials needed to hit that endpoint. Resource Server will use these properties to further self-configure and subsequently validate incoming JWTs. [NOTE] When using introspection, the authorization server's word is the law. If the authorization server responses that the token is valid, then it is. And that's it! ==== Startup Expectations When this property and these dependencies are used, Resource Server will automatically configure itself to validate Opaque Bearer Tokens. This startup process is quite a bit simpler than for JWTs since no endpoints need to be discovered and no additional validation rules get added. ==== Runtime Expectations Once the application is started up, Resource Server will attempt to process any request containing an `Authorization: Bearer` header: ```http GET / HTTP/1.1 Authorization: Bearer some-token-value # Resource Server will process this ``` So long as this scheme is indicated, Resource Server will attempt to process the request according to the Bearer Token specification. Given an Opaque Token, Resource Server will 1. Query the provided introspection endpoint using the provided credentials and the token 2. Inspect the response for an `{ 'active' : true }` attribute 3. Map each scope to an authority with the prefix `SCOPE_` The resulting `Authentication#getPrincipal`, by default, is a Spring Security `{security-api-url}org/springframework/security/oauth2/core/OAuth2AuthenticatedPrincipal.html[OAuth2AuthenticatedPrincipal]` object, and `Authentication#getName` maps to the token's `sub` property, if one is present. From here, you may want to jump to: * <> * <> * <> [[oauth2resourceserver-opaque-attributes]] === Looking Up Attributes Post-Authentication Once a token is authenticated, an instance of `BearerTokenAuthentication` is set in the `SecurityContext`. This means that it's available in `@Controller` methods when using `@EnableWebMvc` in your configuration: [source,java] ---- @GetMapping(""/foo"") public String foo(BearerTokenAuthentication authentication) { return authentication.getTokenAttributes().get(""sub"") + "" is the subject""; } ---- Since `BearerTokenAuthentication` holds an `OAuth2AuthenticatedPrincipal`, that also means that it's available to controller methods, too: [source,java] ---- @GetMapping(""/foo"") public String foo(@AuthenticationPrincipal OAuth2AuthenticatedPrincipal principal) { return principal.getAttribute(""sub"") + "" is the subject""; } ---- ==== Looking Up Attributes Via SpEL Of course, this also means that attributes can be accessed via SpEL. For example, if using `@EnableGlobalMethodSecurity` so that you can use `@PreAuthorize` annotations, you can do: ```java @PreAuthorize(""principal?.attributes['sub'] == 'foo'"") public String forFoosEyesOnly() { return ""foo""; } ``` [[oauth2resourceserver-opaque-sansboot]] === Overriding or Replacing Boot Auto Configuration There are two `@Bean` s that Spring Boot generates on Resource Server's behalf. The first is a `WebSecurityConfigurerAdapter` that configures the app as a resource server. When use Opaque Token, this `WebSecurityConfigurerAdapter` looks like: [source,java] ---- protected void configure(HttpSecurity http) { http .authorizeRequests() .anyRequest().authenticated() .and() .oauth2ResourceServer(OAuth2ResourceServerConfigurer::opaqueToken) } ---- If the application doesn't expose a `WebSecurityConfigurerAdapter` bean, then Spring Boot will expose the above default one. Replacing this is as simple as exposing the bean within the application: [source,java] ---- @EnableWebSecurity public class MyCustomSecurityConfiguration extends WebSecurityConfigurerAdapter { protected void configure(HttpSecurity http) { http .authorizeRequests() .mvcMatchers(""/messages/**"").hasAuthority(""SCOPE_message:read"") .anyRequest().authenticated() .and() .oauth2ResourceServer() .opaqueToken() .introspector(myIntrospector()); } } ---- The above requires the scope of `message:read` for any URL that starts with `/messages/`. Methods on the `oauth2ResourceServer` DSL will also override or replace auto configuration. For example, the second `@Bean` Spring Boot creates is an `OpaqueTokenIntrospector`, which decodes `String` tokens into validated instances of `OAuth2AuthenticatedPrincipal`: [source,java] ---- @Bean public OpaqueTokenIntrospector introspector() { return new NimbusOpaqueTokenIntrospector(introspectionUri, clientId, clientSecret); } ---- If the application doesn't expose a `OpaqueTokenIntrospector` bean, then Spring Boot will expose the above default one. And its configuration can be overridden using `introspectionUri()` and `introspectionClientCredentials()` or replaced using `introspector()`. [[oauth2resourceserver-opaque-introspectionuri-dsl]] ==== Using `introspectionUri()` An authorization server's Introspection Uri can be configured <> or it can be supplied in the DSL: [source,java] ---- @EnableWebSecurity public class DirectlyConfiguredIntrospectionUri extends WebSecurityConfigurerAdapter { protected void configure(HttpSecurity http) { http .authorizeRequests() .anyRequest().authenticated() .and() .oauth2ResourceServer() .opaqueToken() .introspectionUri(""https://idp.example.com/introspect"") .introspectionClientCredentials(""client"", ""secret""); } } ---- Using `introspectionUri()` takes precedence over any configuration property. [[oauth2resourceserver-opaque-introspector-dsl]] ==== Using `introspector()` More powerful than `introspectionUri()` is `introspector()`, which will completely replace any Boot auto configuration of `OpaqueTokenIntrospector`: [source,java] ---- @EnableWebSecurity public class DirectlyConfiguredIntrospector extends WebSecurityConfigurerAdapter { protected void configure(HttpSecurity http) { http .authorizeRequests() .anyRequest().authenticated() .and() .oauth2ResourceServer() .opaqueToken() .introspector(myCustomIntrospector()); } } ---- This is handy when deeper configuration, like <>, <>, or <>, is necessary. [[oauth2resourceserver-opaque-introspector-bean]] ==== Exposing a `OpaqueTokenIntrospector` `@Bean` Or, exposing a `OpaqueTokenIntrospector` `@Bean` has the same effect as `introspector()`: [source,java] ---- @Bean public OpaqueTokenIntrospector introspector() { return new NimbusOpaqueTokenIntrospector(introspectionUri, clientId, clientSecret); } ---- [[oauth2resourceserver-opaque-authorization]] === Configuring Authorization An OAuth 2.0 Introspection endpoint will typically return a `scope` attribute, indicating the scopes (or authorities) it's been granted, for example: `{ ..., ""scope"" : ""messages contacts""}` When this is the case, Resource Server will attempt to coerce these scopes into a list of granted authorities, prefixing each scope with the string ""SCOPE_"". This means that to protect an endpoint or method with a scope derived from an Opaque Token, the corresponding expressions should include this prefix: ```java @EnableWebSecurity public class MappedAuthorities extends WebSecurityConfigurerAdapter { protected void configure(HttpSecurity http) { http .authorizeRequests(authorizeRequests -> authorizeRequests .mvcMatchers(""/contacts/**"").hasAuthority(""SCOPE_contacts"") .mvcMatchers(""/messages/**"").hasAuthority(""SCOPE_messages"") .anyRequest().authenticated() ) .oauth2ResourceServer(OAuth2ResourceServerConfigurer::opaqueToken); } } ``` Or similarly with method security: ```java @PreAuthorize(""hasAuthority('SCOPE_messages')"") public List getMessages(...) {} ``` [[oauth2resourceserver-opaque-authorization-extraction]] ==== Extracting Authorities Manually By default, Opaque Token support will extract the scope claim from an introspection response and parse it into individual `GrantedAuthority` instances. For example, if the introspection response were: [source,json] ---- { ""active"" : true, ""scope"" : ""message:read message:write"" } ---- Then Resource Server would generate an `Authentication` with two authorities, one for `message:read` and the other for `message:write`. This can, of course, be customized using a custom `OpaqueTokenIntrospector` that takes a look at the attribute set and converts in its own way: [source,java] ---- public class CustomAuthoritiesOpaqueTokenIntrospector implements OpaqueTokenIntrospector { private OpaqueTokenIntrospector delegate = new NimbusOpaqueTokenIntrospector(""https://idp.example.org/introspect"", ""client"", ""secret""); public OAuth2AuthenticatedPrincipal introspect(String token) { OAuth2AuthenticatedPrincipal principal = this.delegate.introspect(token); return new DefaultOAuth2AuthenticatedPrincipal( principal.getName(), principal.getAttributes(), extractAuthorities(principal)); } private Collection extractAuthorities(OAuth2AuthenticatedPrincipal principal) { List scopes = principal.getAttribute(OAuth2IntrospectionClaimNames.SCOPE); return scopes.stream() .map(SimpleGrantedAuthority::new) .collect(Collectors.toList()); } } ---- Thereafter, this custom introspector can be configured simply by exposing it as a `@Bean`: [source,java] ---- @Bean public OpaqueTokenIntrospector introspector() { return new CustomAuthoritiesOpaqueTokenIntrospector(); } ---- [[oauth2resourceserver-opaque-timeouts]] === Configuring Timeouts By default, Resource Server uses connection and socket timeouts of 30 seconds each for coordinating with the authorization server. This may be too short in some scenarios. Further, it doesn't take into account more sophisticated patterns like back-off and discovery. To adjust the way in which Resource Server connects to the authorization server, `NimbusOpaqueTokenIntrospector` accepts an instance of `RestOperations`: ```java @Bean public OpaqueTokenIntrospector introspector(RestTemplateBuilder builder) { RestOperations rest = builder .basicAuthentication(clientId, clientSecret) .setConnectionTimeout(60000) .setReadTimeout(60000) .build(); return new NimbusOpaqueTokenIntrospector(introspectionUri, rest); } ``` [[oauth2resourceserver-opaque-jwt-introspector]] === Using Introspection with JWTs A common question is whether or not introspection is compatible with JWTs. Spring Security's Opaque Token support has been designed to not care about the format of the token -- it will gladly pass any token to the introspection endpoint provided. So, let's say that you've got a requirement that requires you to check with the authorization server on each request, in case the JWT has been revoked. Even though you are using the JWT format for the token, your validation method is introspection, meaning you'd want to do: [source,yaml] ---- spring: security: oauth2: resourceserver: opaque-token: introspection-uri: https://idp.example.org/introspection client-id: client client-secret: secret ---- In this case, the resulting `Authentication` would be `BearerTokenAuthentication`. Any attributes in the corresponding `OAuth2AuthenticatedPrincipal` would be whatever was returned by the introspection endpoint. But, let's say that, oddly enough, the introspection endpoint only returns whether or not the token is active. Now what? In this case, you can create a custom `OpaqueTokenIntrospector` that still hits the endpoint, but then updates the returned principal to have the JWTs claims as the attributes: [source,java] ---- public class JwtOpaqueTokenIntrospector implements OpaqueTokenIntrospector { private OpaqueTokenIntrospector delegate = new NimbusOpaqueTokenIntrospector(""https://idp.example.org/introspect"", ""client"", ""secret""); private JwtDecoder jwtDecoder = new NimbusJwtDecoder(new ParseOnlyJWTProcessor()); public OAuth2AuthenticatedPrincipal introspect(String token) { OAuth2AuthenticatedPrincipal principal = this.delegate.introspect(token); try { Jwt jwt = this.jwtDecoder.decode(token); return new DefaultOAuth2AuthenticatedPrincipal(jwt.getClaims(), NO_AUTHORITIES); } catch (JwtException e) { throw new OAuth2IntrospectionException(e); } } private static class ParseOnlyJWTProcessor extends DefaultJWTProcessor { JWTClaimsSet process(SignedJWT jwt, SecurityContext context) throws JOSEException { return jwt.getJWTClaimSet(); } } } ---- Thereafter, this custom introspector can be configured simply by exposing it as a `@Bean`: [source,java] ---- @Bean public OpaqueTokenIntrospector introspector() { return new JwtOpaqueTokenIntropsector(); } ---- [[oauth2resourceserver-opaque-userinfo]] === Calling a `/userinfo` Endpoint Generally speaking, a Resource Server doesn't care about the underlying user, but instead about the authorities that have been granted. That said, at times it can be valuable to tie the authorization statement back to a user. If an application is also using `spring-security-oauth2-client`, having set up the appropriate `ClientRegistrationRepository`, then this is quite simple with a custom `OpaqueTokenIntrospector`. This implementation below does three things: * Delegates to the introspection endpoint, to affirm the token's validity * Looks up the appropriate client registration associated with the `/userinfo` endpoint * Invokes and returns the response from the `/userinfo` endpoint [source,java] ---- public class UserInfoOpaqueTokenIntrospector implements OpaqueTokenIntrospector { private final OpaqueTokenIntrospector delegate = new NimbusOpaqueTokenIntrospector(""https://idp.example.org/introspect"", ""client"", ""secret""); private final OAuth2UserService oauth2UserService = new DefaultOAuth2UserService(); private final ClientRegistrationRepository repository; // ... constructor @Override public OAuth2AuthenticatedPrincipal introspect(String token) { OAuth2AuthenticatedPrincipal authorized = this.delegate.introspect(token); Instant issuedAt = authorized.getAttribute(ISSUED_AT); Instant expiresAt = authorized.getAttribute(EXPIRES_AT); ClientRegistration clientRegistration = this.repository.findByRegistrationId(""registration-id""); OAuth2AccessToken token = new OAuth2AccessToken(BEARER, token, issuedAt, expiresAt); OAuth2UserRequest oauth2UserRequest = new OAuth2UserRequest(clientRegistration, token); return this.oauth2UserService.loadUser(oauth2UserRequest); } } ---- If you aren't using `spring-security-oauth2-client`, it's still quite simple. You will simply need to invoke the `/userinfo` with your own instance of `WebClient`: [source,java] ---- public class UserInfoOpaqueTokenIntrospector implements OpaqueTokenIntrospector { private final OpaqueTokenIntrospector delegate = new NimbusOpaqueTokenIntrospector(""https://idp.example.org/introspect"", ""client"", ""secret""); private final WebClient rest = WebClient.create(); @Override public OAuth2AuthenticatedPrincipal introspect(String token) { OAuth2AuthenticatedPrincipal authorized = this.delegate.introspect(token); return makeUserInfoRequest(authorized); } } ---- Either way, having created your `OpaqueTokenIntrospector`, you should publish it as a `@Bean` to override the defaults: [source,java] ---- @Bean OpaqueTokenIntrospector introspector() { return new UserInfoOpaqueTokenIntrospector(...); } ---- [[oauth2reourceserver-opaqueandjwt]] === Supporting both JWT and Opaque Token In some cases, you may have a need to access both kinds of tokens. For example, you may support more than one tenant where one tenant issues JWTs and the other issues opaque tokens. If this decision must be made at request-time, then you can use an `AuthenticationManagerResolver` to achieve it, like so: [source,java] ---- @Bean AuthenticationManagerResolver tokenAuthenticationManagerResolver() { BearerTokenResolver bearerToken = new DefaultBearerTokenResolver(); JwtAuthenticationProvider jwt = jwt(); OpaqueTokenAuthenticationProvider opaqueToken = opaqueToken(); return request -> { String token = bearerToken.resolve(request); if (isAJwt(token)) { return jwt::authenticate; } else { return opaqueToken::authenticate; } } } ---- And then specify this `AuthenticationManagerResolver` in the DSL: [source,java] ---- http .authorizeRequests() .anyRequest().authenticated() .and() .oauth2ResourceServer() .authenticationManagerResolver(this.tokenAuthenticationManagerResolver); ---- [[oauth2resourceserver-multitenancy]] === Multi-tenancy A resource server is considered multi-tenant when there are multiple strategies for verifying a bearer token, keyed by some tenant identifier. For example, your resource server may accept bearer tokens from two different authorization servers. Or, your authorization server may represent a multiplicity of issuers. In each case, there are two things that need to be done and trade-offs associated with how you choose to do them: 1. Resolve the tenant 2. Propagate the tenant ==== Resolving the Tenant By Request Material Resolving the tenant by request material can be done my implementing an `AuthenticationManagerResolver`, which determines the `AuthenticationManager` at runtime, like so: [source,java] ---- @Component public class TenantAuthenticationManagerResolver implements AuthenticationManagerResolver { private final BearerTokenResolver resolver = new DefaultBearerTokenResolver(); private final TenantRepository tenants; <1> private final Map authenticationManagers = new ConcurrentHashMap<>(); <2> public TenantAuthenticationManagerResolver(TenantRepository tenants) { this.tenants = tenants; } @Override public AuthenticationManager resolve(HttpServletRequest request) { return this.authenticationManagers.computeIfAbsent(toTenant(request), this::fromTenant); } private String toTenant(HttpServletRequest request) { String[] pathParts = request.getRequestURI().split(""/""); return pathParts.length > 0 ? pathParts[1] : null; } private AuthenticationManager fromTenant(String tenant) { return Optional.ofNullable(this.tenants.get(tenant)) <3> .map(JwtDecoders::fromIssuerLocation) <4> .map(JwtAuthenticationProvider::new) .orElseThrow(() -> new IllegalArgumentException(""unknown tenant""))::authenticate; } } ---- <1> A hypothetical source for tenant information <2> A cache for `AuthenticationManager`s, keyed by tenant identifier <3> Looking up the tenant is more secure than simply computing the issuer location on the fly - the lookup acts as a tenant whitelist <4> Create a `JwtDecoder` via the discovery endpoint - the lazy lookup here means that you don't need to configure all tenants at startup And then specify this `AuthenticationManagerResolver` in the DSL: [source,java] ---- http .authorizeRequests() .anyRequest().authenticated() .and() .oauth2ResourceServer() .authenticationManagerResolver(this.tenantAuthenticationManagerResolver); ---- ==== Resolving the Tenant By Claim Resolving the tenant by claim is similar to doing so by request material. The only real difference is the `toTenant` method implementation: [source,java] ---- @Component public class TenantAuthenticationManagerResolver implements AuthenticationManagerResolver { private final BearerTokenResolver resolver = new DefaultBearerTokenResolver(); private final TenantRepository tenants; <1> private final Map authenticationManagers = new ConcurrentHashMap<>(); <2> public TenantAuthenticationManagerResolver(TenantRepository tenants) { this.tenants = tenants; } @Override public AuthenticationManager resolve(HttpServletRequest request) { return this.authenticationManagers.computeIfAbsent(toTenant(request), this::fromTenant); <3> } private String toTenant(HttpServletRequest request) { try { String token = this.resolver.resolve(request); return (String) JWTParser.parse(token).getJWTClaimsSet().getIssuer(); } catch (Exception e) { throw new IllegalArgumentException(e); } } private AuthenticationManager fromTenant(String tenant) { return Optional.ofNullable(this.tenants.get(tenant)) <3> .map(JwtDecoders::fromIssuerLocation) <4> .map(JwtAuthenticationProvider::new) .orElseThrow(() -> new IllegalArgumentException(""unknown tenant""))::authenticate; } } ---- <1> A hypothetical source for tenant information <2> A cache for `AuthenticationManager`s, keyed by tenant identifier <3> Looking up the tenant is more secure than simply computing the issuer location on the fly - the lookup acts as a tenant whitelist <4> Create a `JwtDecoder` via the discovery endpoint - the lazy lookup here means that you don't need to configure all tenants at startup [source,java] ---- http .authorizeRequests() .anyRequest().authenticated() .and() .oauth2ResourceServer() .authenticationManagerResolver(this.tenantAuthenticationManagerResolver); ---- ==== Parsing the Claim Only Once You may have observed that this strategy, while simple, comes with the trade-off that the JWT is parsed once by the `AuthenticationManagerResolver` and then again by the `JwtDecoder`. This extra parsing can be alleviated by configuring the `JwtDecoder` directly with a `JWTClaimSetAwareJWSKeySelector` from Nimbus: [source,java] ---- @Component public class TenantJWSKeySelector implements JWTClaimSetAwareJWSKeySelector { private final TenantRepository tenants; <1> private final Map> selectors = new ConcurrentHashMap<>(); <2> public TenantJWSKeySelector(TenantRepository tenants) { this.tenants = tenants; } @Override public List selectKeys(JWSHeader jwsHeader, JWTClaimsSet jwtClaimsSet, SecurityContext securityContext) throws KeySourceException { return this.selectors.computeIfAbsent(toTenant(jwtClaimsSet), this::fromTenant) .selectJWSKeys(jwsHeader, securityContext); } private String toTenant(JWTClaimsSet claimSet) { return (String) claimSet.getClaim(""iss""); } private JWSKeySelector fromTenant(String tenant) { return Optional.ofNullable(this.tenantRepository.findById(tenant)) <3> .map(t -> t.getAttrbute(""jwks_uri"")) .map(this::fromUri) .orElseThrow(() -> new IllegalArgumentException(""unknown tenant"")); } private JWSKeySelector fromUri(String uri) { try { return JWSAlgorithmFamilyJWSKeySelector.fromJWKSetURL(new URL(uri)); <4> } catch (Exception e) { throw new IllegalArgumentException(e); } } } ---- <1> A hypothetical source for tenant information <2> A cache for `JWKKeySelector`s, keyed by tenant identifier <3> Looking up the tenant is more secure than simply calculating the JWK Set endpoint on the fly - the lookup acts as a tenant whitelist <4> Create a `JWSKeySelector` via the types of keys that come back from the JWK Set endpoint - the lazy lookup here means that you don't need to configure all tenants at startup The above key selector is a composition of many key selectors. It chooses which key selector to use based on the `iss` claim in the JWT. NOTE: To use this approach, make sure that the authorization server is configured to include the claim set as part of the token's signature. Without this, you have no guarantee that the issuer hasn't been altered by a bad actor. Next, we can construct a `JWTProcessor`: [source,java] ---- @Bean JWTProcessor jwtProcessor(JWTClaimSetJWSKeySelector keySelector) { ConfigurableJWTProcessor jwtProcessor = new DefaultJWTProcessor(); jwtProcessor.setJWTClaimSetJWSKeySelector(keySelector); return jwtProcessor; } ---- As you are already seeing, the trade-off for moving tenant-awareness down to this level is more configuration. We have just a bit more. Next, we still want to make sure you are validating the issuer. But, since the issuer may be different per JWT, then you'll need a tenant-aware validator, too: [source,java] ---- @Component public class TenantJwtIssuerValidator implements OAuth2TokenValidator { private final TenantRepository tenants; private final Map validators = new ConcurrentHashMap<>(); public TenantJwtIssuerValidator(TenantRepository tenants) { this.tenants = tenants; } @Override public OAuth2TokenValidatorResult validate(Jwt token) { return this.validators.computeIfAbsent(toTenant(token), this::fromTenant) .validate(token); } private String toTenant(Jwt jwt) { return jwt.getIssuer(); } private JwtIssuerValidator fromTenant(String tenant) { return Optional.ofNullable(this.tenants.findById(tenant)) .map(t -> t.getAttribute(""issuer"")) .map(JwtIssuerValidator::new) .orElseThrow(() -> new IllegalArgumentException(""unknown tenant"")); } } ---- Now that we have a tenant-aware processor and a tenant-aware validator, we can proceed with creating our `JwtDecoder`: [source,java] ---- @Bean JwtDecoder jwtDecoder(JWTProcessor jwtProcessor, OAuth2TokenValidator jwtValidator) { NimbusJwtDecoder decoder = new NimbusJwtDecoder(processor); OAuth2TokenValidator validator = new DelegatingOAuth2TokenValidator<> (JwtValidators.createDefault(), this.jwtValidator); decoder.setJwtValidator(validator); return decoder; } ---- We've finished talking about resolving the tenant. If you've chosen to resolve the tenant by request material, then you'll need to make sure you address your downstream resource servers in the same way. For example, if you are resolving it by subdomain, you'll need to address the downstream resource server using the same subdomain. However, if you resolve it by a claim in the bearer token, read on to learn about <>. [[oauth2resourceserver-bearertoken-resolver]] === Bearer Token Resolution By default, Resource Server looks for a bearer token in the `Authorization` header. This, however, can be customized in a couple of ways. ==== Reading the Bearer Token from a Custom Header For example, you may have a need to read the bearer token from a custom header. To achieve this, you can wire a `HeaderBearerTokenResolver` instance into the DSL, as you can see in the following example: [source,java] ---- http .oauth2ResourceServer() .bearerTokenResolver(new HeaderBearerTokenResolver(""x-goog-iap-jwt-assertion"")); ---- ==== Reading the Bearer Token from a Form Parameter Or, you may wish to read the token from a form parameter, which you can do by configuring the `DefaultBearerTokenResolver`, as you can see below: [source,java] ---- DefaultBearerTokenResolver resolver = new DefaultBearerTokenResolver(); resolver.setAllowFormEncodedBodyParameter(true); http .oauth2ResourceServer() .bearerTokenResolver(resolver); ---- === Bearer Token Propagation Now that you're in possession of a bearer token, it might be handy to pass that to downstream services. This is quite simple with `{security-api-url}org/springframework/security/oauth2/server/resource/web/reactive/function/client/ServletBearerExchangeFilterFunction.html[ServletBearerExchangeFilterFunction]`, which you can see in the following example: [source,java] ---- @Bean public WebClient rest() { return WebClient.builder() .filter(new ServletBearerExchangeFilterFunction()) .build(); } ---- When the above `WebClient` is used to perform requests, Spring Security will look up the current `Authentication` and extract any `{security-api-url}org/springframework/security/oauth2/core/AbstractOAuth2Token.html[AbstractOAuth2Token]` credential. Then, it will propagate that token in the `Authorization` header. For example: [source,java] ---- this.rest.get() .uri(""https://other-service.example.com/endpoint"") .retrieve() .bodyToMono(String.class) .block() ---- Will invoke the `https://other-service.example.com/endpoint`, adding the bearer token `Authorization` header for you. In places where you need to override this behavior, it's a simple matter of supplying the header yourself, like so: [source,java] ---- this.rest.get() .uri(""https://other-service.example.com/endpoint"") .headers(headers -> headers.setBearerAuth(overridingToken)) .retrieve() .bodyToMono(String.class) .block() ---- In this case, the filter will fall back and simply forward the request onto the rest of the web filter chain. [NOTE] Unlike the https://docs.spring.io/spring-security/site/docs/current-SNAPSHOT/api/org/springframework/security/oauth2/client/web/reactive/function/client/ServletOAuth2AuthorizedClientExchangeFilterFunction.html[OAuth 2.0 Client filter function], this filter function makes no attempt to renew the token, should it be expired. To obtain this level of support, please use the OAuth 2.0 Client filter. ==== `RestTemplate` support There is no dedicated support for `RestTemplate` at the moment, but you can achieve propagation quite simply with your own interceptor: [source,java] ---- @Bean RestTemplate rest() { RestTemplate rest = new RestTemplate(); rest.getInterceptors().add((request, body, execution) -> { Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); if (authentication == null) { return execution.execute(request, body); } if (!(authentication.getCredentials() instanceof AbstractOAuth2Token)) { return execution.execute(request, body); } AbstractOAuth2Token token = (AbstractOAuth2Token) authentication.getCredentials(); request.getHeaders().setBearerAuth(token.getTokenValue()); return execution.execute(request, body); }); return rest; } ---- ",12093,False,2265.1610387612573,median "[[configuration-interfaces]] == Set traffic capturing options There are two main ways of deploying Packetbeat: * On dedicated servers, getting the traffic from mirror ports or tap devices. * On your existing application servers. The first option has the big advantage that there is no overhead of any kind on your application servers. But it requires dedicated networking gear, which is generally not available on cloud setups. In both cases, the sniffing performance (reading packets passively from the network) is very important. In the case of a dedicated server, better sniffing performance means that less hardware is required. When Packetbeat is installed on an existing application server, better sniffing performance means less overhead. Currently Packetbeat has several options for traffic capturing: * `pcap`, which uses the libpcap library and works on most platforms, but it's not the fastest option. * `af_packet`, which uses memory mapped sniffing. This option is faster than libpcap and doesn't require a kernel module, but it's Linux-specific. The `af_packet` option, also known as ""memory-mapped sniffing,"" makes use of a Linux-specific http://lxr.free-electrons.com/source/Documentation/networking/packet_mmap.txt[feature]. This could be the optimal sniffing mode for both the dedicated server and when Packetbeat is deployed on an existing application server. The way it works is that both the kernel and the user space program map the same memory zone, and a simple circular buffer is organized in this memory zone. The kernel writes packets into the circular buffer, and the user space program reads from it. The poll system call is used for getting a notification for the first packet available, but the remaining available packets can be simply read via memory access. The `af_packet` sniffer can be further tuned to use more memory in exchange for better performance. The larger the size of the circular buffer, the fewer system calls are needed, which means that fewer CPU cycles are consumed. The default size of the buffer is 30 MB, but you can increase it like this: [source,yaml] ------------------------------------------------------------------------------ packetbeat.interfaces.device: eth0 packetbeat.interfaces.type: af_packet packetbeat.interfaces.buffer_size_mb: 100 ------------------------------------------------------------------------------ [float] === Sniffing configuration options You can specify the following options in the `packetbeat.interfaces` section of the +{beatname_lc}.yml+ config file. Here is an example configuration: [source,yaml] ------------------------------------------------------------------------------ packetbeat.interfaces.device: any packetbeat.interfaces.snaplen: 1514 packetbeat.interfaces.type: af_packet packetbeat.interfaces.buffer_size_mb: 100 ------------------------------------------------------------------------------ [float] ==== `device` The network device to capture traffic from. The specified device is set automatically to promiscuous mode, meaning that Packetbeat can capture traffic from other hosts on the same LAN. Example: [source,yaml] ------------------------------------------------------------------------------ packetbeat.interfaces.device: eth0 ------------------------------------------------------------------------------ On Linux, you can specify `any` for the device, and Packetbeat captures all messages sent or received by the server where Packetbeat is installed. NOTE: When you specify `any` for the device, the interfaces are not set to promiscuous mode. The `device` option also accepts specifying the device by its index in the list of devices available for sniffing. To obtain the list of available devices, run Packetbeat with the following command: [""source"",""sh"",subs=""attributes,callouts""] ---------------------------------------------------------------------- packetbeat devices ---------------------------------------------------------------------- This command returns a list that looks something like the following: [""source"",""sh"",subs=""attributes,callouts""] ---------------------------------------------------------------------- 0: en0 (No description available) 1: awdl0 (No description available) 2: bridge0 (No description available) 3: fw0 (No description available) 4: en1 (No description available) 5: en2 (No description available) 6: p2p0 (No description available) 7: en4 (No description available) 8: lo0 (No description available) ---------------------------------------------------------------------- The following example sets up sniffing on the first interface in the list: [source,yaml] ------------------------------------------------------------------------------ packetbeat.interfaces.device: 0 ------------------------------------------------------------------------------ Specifying the index is especially useful on Windows where device names can be long. [float] ==== `snaplen` The maximum size of the packets to capture. The default is 65535, which is large enough for almost all networks and interface types. If you sniff on a physical network interface, the optimal setting is the MTU size. On virtual interfaces, however, it's safer to accept the default value. Example: [source,yaml] ------------------------------------------------------------------------------ packetbeat.interfaces.device: eth0 packetbeat.interfaces.snaplen: 1514 ------------------------------------------------------------------------------ [float] ==== `type` Packetbeat supports these sniffer types: * `pcap`, which uses the libpcap library and works on most platforms, but it's not the fastest option. * `af_packet`, which uses memory-mapped sniffing. This option is faster than libpcap and doesn't require a kernel module, but it's Linux-specific. The default sniffer type is `pcap`. Here is an example configuration that specifies the `af_packet` sniffing type: [source,yaml] ------------------------------------------------------------------------------ packetbeat.interfaces.device: eth0 packetbeat.interfaces.type: af_packet ------------------------------------------------------------------------------ On Linux, if you are trying to optimize the CPU usage of Packetbeat, we recommend trying the `af_packet` option. If you use the `af_packet` sniffer, you can tune its behaviour by specifying the following options: [float] ==== `buffer_size_mb` The maximum size of the shared memory buffer to use between the kernel and user space. A bigger buffer usually results in lower CPU usage, but consumes more memory. This setting is only available for the `af_packet` sniffer type. The default is 30 MB. Example: [source,yaml] ------------------------------------------------------------------------------ packetbeat.interfaces.device: eth0 packetbeat.interfaces.type: af_packet packetbeat.interfaces.buffer_size_mb: 100 ------------------------------------------------------------------------------ [float] ==== `with_vlans` Packetbeat automatically generates a https://en.wikipedia.org/wiki/Berkeley_Packet_Filter[BPF] for capturing only the traffic on ports where it expects to find known protocols. For example, if you have configured port 80 for HTTP and port 3306 for MySQL, Packetbeat generates the following BPF filter: `""port 80 or port 3306""`. However, if the traffic contains https://en.wikipedia.org/wiki/IEEE_802.1Q[VLAN] tags, the filter that Packetbeat generates is ineffective because the offset is moved by four bytes. To fix this, you can enable the `with_vlans` option, which generates a BPF filter that looks like this: `""port 80 or port 3306 or (vlan and (port 80 or port 3306))""`. [float] ==== `bpf_filter` Packetbeat automatically generates a https://en.wikipedia.org/wiki/Berkeley_Packet_Filter[BPF] for capturing only the traffic on ports where it expects to find known protocols. For example, if you have configured port 80 for HTTP and port 3306 for MySQL, Packetbeat generates the following BPF filter: `""port 80 or port 3306""`. You can use the `bpf_filter` setting to overwrite the generated BPF filter. For example: [source,yaml] ------------------------------------------------------------------------------ packetbeat.interfaces.device: eth0 packetbeat.interfaces.bpf_filter: ""net 192.168.238.0/0 and port 80 or port 3306"" ------------------------------------------------------------------------------ NOTE: This setting disables automatic generation of the BPF filter. If you use this setting, it's your responsibility to keep the BPF filters in sync with the ports defined in the `protocols` section. [float] ==== `ignore_outgoing` If the `ignore_outgoing` option is enabled, Packetbeat ignores all the transactions initiated from the server running Packetbeat. This is useful when two Packetbeat instances publish the same transactions. Because one Packetbeat sees the transaction in its outgoing queue and the other sees it in its incoming queue, you can end up with duplicate transactions. To remove the duplicates, you can enable the `packetbeat.ignore_outgoing` option on one of the servers. For example, in the following scenario, you see a 3-server architecture where a Beat is installed on each server. t1 is the transaction exchanged between Server1 and Server2, and t2 is the transaction between Server2 and Server3. image::./images/option_ignore_outgoing.png[Beats Architecture] By default, each transaction is indexed twice because Beat2 sees both transactions. So you would see the following published transactions (when `ignore_outgoing` is false): - Beat1: t1 - Beat2: t1 and t2 - Beat3: t2 To avoid duplicates, you can force your Beats to send only the incoming transactions and ignore the transactions created by the local server. So you would see the following published transactions (when `ignore_outgoing` is true): - Beat1: none - Beat2: t1 - Beat3: t2 [[configuration-flows]] == Set up flows to monitor network traffic You can configure Packetbeat to collect and report statistics on network flows. A _flow_ is a group of packets sent over the same time period that share common properties, such as the same source and destination address and protocol. You can use this feature to analyze network traffic over specific protocols on your network. For each flow, Packetbeat reports the number of packets and the total number of bytes sent from the source to the destination. Each flow event also contains information about the source and destination hosts, such as their IP address. For bi-directional flows, Packetbeat reports statistics for the reverse flow. Packetbeat collects and reports statistics up to and including the transport layer. See <> for more info about the exported data. Here's an example of flow events visualized in the Flows dashboard: image::./images/flows.png[] To configure flows, use the `packetbeat.flows` option in the +{beatname_lc}.yml+ config file. Flows are enabled by default. If this section is missing from the configuration file, network flows are disabled. [source,yaml] -------------------------------------------------------------------------------- packetbeat.flows: timeout: 30s period: 10s -------------------------------------------------------------------------------- Here’s an example of a flow information sent by Packetbeat. See <> for a description of each field. [""source"",""json"",subs=""attributes""] -------------------------------------------------------------------------------- { ""@timestamp"": ""2018-11-15T14:41:24.000Z"", ""agent"": { ""hostname"": ""host.example.com"", ""name"": ""host.example.com"", ""version"": ""{version}"" }, ""destination"": { ""bytes"": 460, ""ip"": ""198.51.100.2"", ""mac"": ""06:05:04:03:02:01"", ""packets"": 2, ""port"": 80 }, ""event"": { ""dataset"": ""flow"", ""duration"": 3000000000, ""end"": ""2018-11-15T14:41:24.000Z"", ""start"": ""2018-11-15T14:41:21.000Z"" }, ""flow"": { ""final"": true, <1> ""id"": ""FQQA/wz/Dv//////Fv8BAQEBAgMEBQYGBQQDAgGrAMsAcQPGM2QC9ZdQAA"", ""vlan"": 171 }, ""network"": { ""bytes"": 470, ""community_id"": ""1:t9T66/2c66NQyftAEsr4aMZv4Hc="", ""packets"": 3, ""transport"": ""tcp"", ""type"": ""ipv4"" }, ""source"": { ""bytes"": 10, ""ip"": ""203.0.113.3"", ""mac"": ""01:02:03:04:05:06"", ""packets"": 1, ""port"": 38901 } } -------------------------------------------------------------------------------- <1> Packetbeat sets the `flow.final` flag to `false` to indicate that the event contains an intermediate report about a flow that it's tracking. When the flow completes, Packetbeat sends one last event with `flow.final` set to `true`. If you want to aggregate sums of traffic, you need to filter on `final:true`, or use some other technique, so that you get only the latest update from each flow. You can disable intermediate reports by setting `period: -1s`. [float] === Configuration options You can specify the following options in the `packetbeat.flows` section of the +{beatname_lc}.yml+ config file: [float] ==== `enabled` Enables flows support if set to true. Set to false to disable network flows support without having to delete or comment out the flows section. The default value is true. [float] ==== `timeout` Timeout configures the lifetime of a flow. If no packets have been received for a flow within the timeout time window, the flow is killed and reported. The default value is 30s. [float] ==== `period` Configure the reporting interval. All flows are reported at the very same point in time. Periodical reporting can be disabled by setting the value to -1. If disabled, flows are still reported once being timed out. The default value is 10s. [float] [[packetbeat-configuration-flows-fields]] ==== `fields` Optional fields that you can specify to add additional information to the output. For example, you might add fields that you can use for filtering log data. Fields can be scalar values, arrays, dictionaries, or any nested combination of these. By default, the fields that you specify here will be grouped under a `fields` sub-dictionary in the output document. To store the custom fields as top-level fields, set the `fields_under_root` option to true. If a duplicate field is declared in the general configuration, then its value will be overwritten by the value declared here. [float] ==== `fields_under_root` If this option is set to true, the custom <> are stored as top-level fields in the output document instead of being grouped under a `fields` sub-dictionary. If the custom field names conflict with other field names added by Packetbeat, then the custom fields overwrite the other fields. [float] ==== `tags` A list of tags that will be sent with the protocol event. This setting is optional. [float] ==== `processors` A list of processors to apply to the data generated by the protocol. See <> for information about specifying processors in your config. [float] ==== `keep_null` If this option is set to true, fields with `null` values will be published in the output document. By default, `keep_null` is set to `false`. [[configuration-protocols]] == Specify which transaction protocols to monitor The `packetbeat.protocols` section of the +{beatname_lc}.yml+ config file contains configuration options for each supported protocol, including common options like `enabled`, `ports`, `send_request`, `send_response`, and options that are protocol-specific. Currently, Packetbeat supports the following protocols: include::./shared-protocol-list.asciidoc[] Example configuration: [source,yaml] ------------------------------------------------------------------------------ packetbeat.protocols: - type: icmp enabled: true - type: dhcpv4 ports: [67, 68] - type: dns ports: [53] - type: http ports: [80, 8080, 8000, 5000, 8002] - type: amqp ports: [5672] - type: cassandra ports: [9042] - type: memcache ports: [11211] - type: mysql ports: [3306,3307] - type: redis ports: [6379] - type: pgsql ports: [5432] - type: thrift ports: [9090] - type: tls ports: [443, 993, 995, 5223, 8443, 8883, 9243] ------------------------------------------------------------------------------ [[common-protocol-options]] === Common protocol options The following options are available for all protocols: [float] ==== `enabled` The enabled setting is a boolean setting to enable or disable protocols without having to comment out configuration sections. If set to false, the protocol is disabled. The default value is true. [float] ==== `ports` Exception: For ICMP the option `enabled` has to be used instead. The ports where Packetbeat will look to capture traffic for specific protocols. Packetbeat installs a https://en.wikipedia.org/wiki/Berkeley_Packet_Filter[BPF] filter based on the ports specified in this section. If a packet doesn't match the filter, very little CPU is required to discard the packet. Packetbeat also uses the ports specified here to determine which parser to use for each packet. [float] [[send-request-option]] ==== `send_request` If this option is enabled, the raw message of the request (`request` field) is sent to Elasticsearch. The default is false. This option is useful when you want to index the whole request. Note that for HTTP, the body is not included by default, only the HTTP headers. [float] [[send-response-option]] ==== `send_response` If this option is enabled, the raw message of the response (`response` field) is sent to Elasticsearch. The default is false. This option is useful when you want to index the whole response. Note that for HTTP, the body is not included by default, only the HTTP headers. [float] [[transaction-timeout-option]] ==== `transaction_timeout` The per protocol transaction timeout. Expired transactions will no longer be correlated to incoming responses, but sent to Elasticsearch immediately. [float] [[packetbeat-configuration-fields]] ==== `fields` Optional fields that you can specify to add additional information to the output. For example, you might add fields that you can use for filtering log data. Fields can be scalar values, arrays, dictionaries, or any nested combination of these. By default, the fields that you specify here will be grouped under a `fields` sub-dictionary in the output document. To store the custom fields as top-level fields, set the `fields_under_root` option to true. If a duplicate field is declared in the general configuration, then its value will be overwritten by the value declared here. [source,yaml] -------------------------------------------------------------------------------- packetbeat.protocols: - type: http ports: [80] fields: service_id: nginx -------------------------------------------------------------------------------- [float] [[packetbeat-fields-under-root]] ==== `fields_under_root` If this option is set to true, the custom <> are stored as top-level fields in the output document instead of being grouped under a `fields` sub-dictionary. If the custom field names conflict with other field names added by Packetbeat, then the custom fields overwrite the other fields. [float] ==== `tags` A list of tags that will be sent with the transaction event. This setting is optional. [float] ==== `processors` A list of processors to apply to the data generated by the protocol. See <> for information about specifying processors in your config. [float] ==== `keep_null` If this option is set to true, fields with `null` values will be published in the output document. By default, `keep_null` is set to `false`. [[packetbeat-icmp-options]] === Capture ICMP traffic ++++ ICMP ++++ The `icmp` section of the +{beatname_lc}.yml+ config file specifies options for the ICMP protocol. Here is a sample configuration section for ICMP: [source,yaml] ------------------------------------------------------------------------------ packetbeat.protocols: - type: icmp enabled: true ------------------------------------------------------------------------------ ==== Configuration options Also see <>. ===== `enabled` The ICMP protocol can be enabled/disabled via this option. The default is true. If enabled Packetbeat will generate the following BPF filter: `""icmp or icmp6""`. [[packetbeat-dns-options]] === Capture DNS traffic ++++ DNS ++++ The `dns` section of the +{beatname_lc}.yml+ config file specifies configuration options for the DNS protocol. The DNS protocol supports processing DNS messages on TCP and UDP. Here is a sample configuration section for DNS: [source,yaml] ------------------------------------------------------------------------------ packetbeat.protocols: - type: dns ports: [53] include_authorities: true include_additionals: true ------------------------------------------------------------------------------ ==== Configuration options Also see <>. ===== `include_authorities` If this option is enabled, dns.authority fields (authority resource records) are added to DNS events. The default is false. ===== `include_additionals` If this option is enabled, dns.additionals fields (additional resource records) are added to DNS events. The default is false. [[packetbeat-http-options]] === Capture HTTP traffic ++++ HTTP ++++ The HTTP protocol has several specific configuration options. Here is a sample configuration for the `http` section of the +{beatname_lc}.yml+ config file: [source,yaml] ------------------------------------------------------------------------------ packetbeat.protocols: - type: http ports: [80, 8080, 8000, 5000, 8002] hide_keywords: [""pass"", ""password"", ""passwd""] send_headers: [""User-Agent"", ""Cookie"", ""Set-Cookie""] split_cookie: true real_ip_header: ""X-Forwarded-For"" ------------------------------------------------------------------------------ ==== Configuration options Also see <>. ===== `hide_keywords` A list of query parameters that Packetbeat will automatically censor in the transactions that it saves. The values associated with these parameters are replaced by `'xxxxx'`. By default, no changes are made to the HTTP messages. Packetbeat has this option because, unlike SQL traffic, which typically only contains the hashes of the passwords, HTTP traffic may contain sensitive data. To reduce security risks, you can configure this option to avoid sending the contents of certain HTTP POST parameters. WARNING: This option replaces query parameters from GET requests and top-level parameters from POST requests. If sensitive data is encoded inside a parameter that you don't specify here, Packetbeat cannot censor it. Also, note that if you configure Packetbeat to save the raw request and response fields (see the <> and the <> options), sensitive data may be present in those fields. ===== `redact_authorization` When this option is enabled, Packetbeat obscures the value of `Authorization` and `Proxy-Authorization` HTTP headers, and censors those strings in the response. You should set this option to true for transactions that use Basic Authentication because they may contain the base64 unencrypted username and password. ===== `send_headers` A list of header names to capture and send to Elasticsearch. These headers are placed under the `headers` dictionary in the resulting JSON. ===== `send_all_headers` Instead of sending a white list of headers to Elasticsearch, you can send all headers by setting this option to true. The default is false. ===== `include_body_for` The list of content types for which Packetbeat exports the full HTTP payload. The HTTP body is available under `http.request.body.content` and `http.response.body.content` for these Content-Types. In addition, if <> option is enabled, then the HTTP body is exported together with the HTTP headers under `response` and if <> enabled, then `request` contains the entire HTTP message including the body. In the following example, the HTML attachments of the HTTP responses are exported under the `response` field and under `http.request.body.content` or `http.response.body.content`: [source,yml] ------------------------------------------------------------------------------ packetbeat.protocols: - type: http ports: [80, 8080] send_response: true include_body_for: [""text/html""] ------------------------------------------------------------------------------ ===== `decode_body` A boolean flag that controls decoding of HTTP payload. It interprets the `Content-Encoding` and `Transfer-Encoding` headers and uncompresses the entity body. Supported encodings are `gzip` and `deflate`. This option is only applicable in the cases where the HTTP payload is exported, that is, when one of the `include_*_body_for` options is specified or a POST request contains url-encoded parameters. ===== `split_cookie` If the `Cookie` or `Set-Cookie` headers are sent, this option controls whether they are split into individual values. For example, with this option set, an HTTP response might result in the following JSON: [source,json] ------------------------------------------------------------------------------ ""response"": { ""code"": 200, ""headers"": { ""connection"": ""close"", ""content-language"": ""en"", ""content-type"": ""text/html; charset=utf-8"", ""date"": ""Fri, 21 Nov 2014 17:07:34 GMT"", ""server"": ""gunicorn/19.1.1"", ""set-cookie"": { <1> ""csrftoken"": ""S9ZuJF8mvIMT5CL4T1Xqn32wkA6ZSeyf"", ""expires"": ""Fri, 20-Nov-2015 17:07:34 GMT"", ""max-age"": ""31449600"", ""path"": ""/"" }, ""vary"": ""Cookie, Accept-Language"" }, ""status_phrase"": ""OK"" } ------------------------------------------------------------------------------ <1> Note that `set-cookie` is a map containing the cookie names as keys. The default is false. ===== `real_ip_header` The header field to extract the real IP from. This setting is useful when you want to capture traffic behind a reverse proxy, but you want to get the geo-location information. If this header is present and contains a valid IP addresses, the information is used for the `network.forwarded_ip` field. ===== `max_message_size` If an individual HTTP message is larger than this setting (in bytes), it will be trimmed to this size. Unless this value is very small (<1.5K), Packetbeat is able to still correctly follow the transaction and create an event for it. The default is 10485760 (10 MB). [[packetbeat-amqp-options]] === Capture AMQP traffic ++++ AMQP ++++ The `amqp` section of the +{beatname_lc}.yml+ config file specifies configuration options for the AMQP 0.9.1 protocol. Here is a sample configuration: [source,yaml] ------------------------------------------------------------------------------ packetbeat.protocols: - type: amqp ports: [5672] max_body_length: 1000 parse_headers: true parse_arguments: false hide_connection_information: true ------------------------------------------------------------------------------ ==== Configuration options Also see <>. ===== `max_body_length` The maximum size in bytes of the message displayed in the request or response fields. Messages that are bigger than the specified size are truncated. Use this option to avoid publishing huge messages when <> or <> is enabled. The default is 1000 bytes. ===== `parse_headers` If set to true, Packetbeat parses the additional arguments specified in the headers field of a message. Those arguments are key-value pairs that specify information such as the content type of the message or the message priority. The default is true. ===== `parse_arguments` If set to true, Packetbeat parses the additional arguments specified in AMQP methods. Those arguments are key-value pairs specified by the user and can be of any length. The default is true. ===== `hide_connection_information` If set to false, the connection layer methods of the protocol are also displayed, such as the opening and closing of connections and channels by clients, or the quality of service negotiation. The default is true. [[configuration-cassandra]] === Capture Cassandra traffic ++++ Cassandra ++++ The following settings are specific to the Cassandra protocol. Here is a sample configuration for the `cassandra` section of the +{beatname_lc}.yml+ config file: [source,yaml] ------------------------------------------------------------------------------ packetbeat.protocols: - type: cassandra send_request_header: true send_response_header: true compressor: ""snappy"" ignored_ops: [""SUPPORTED"",""OPTIONS""] ------------------------------------------------------------------------------ ==== Configuration options Also see <>. ===== `send_request_header` If this option is enabled, the raw message of the response (`cassandra_request.request_headers` field) is sent to Elasticsearch. The default is true. enable `send_request` first before enable this option. ===== `send_response_header` If this option is enabled, the raw message of the response (`cassandra_response.response_headers` field) is included in published events. The default is true. enable `send_response` first before enable this option. ===== `ignored_ops` This option indicates which Operator/Operators captured will be ignored. currently support: `ERROR` ,`STARTUP` ,`READY` ,`AUTHENTICATE` ,`OPTIONS` ,`SUPPORTED` , `QUERY` ,`RESULT` ,`PREPARE` ,`EXECUTE` ,`REGISTER` ,`EVENT` , `BATCH` ,`AUTH_CHALLENGE`,`AUTH_RESPONSE` ,`AUTH_SUCCESS` . ===== `compressor` Configures the default compression algorithm being used to uncompress compressed frames by name. Currently only `snappy` is can be configured. By default no compressor is configured. [[packetbeat-memcache-options]] === Capture Memcache traffic ++++ Memcache ++++ The `memcache` section of the +{beatname_lc}.yml+ config file specifies configuration options for the memcache protocol. Here is a sample configuration section for memcache: [source,yaml] ------------------------------------------------------------------------------ packetbeat.protocols: - type: memcache ports: [11211] parseunknown: false maxvalues: 0 maxbytespervalue: 100 transaction_timeout: 200 udptransactiontimeout: 200 ------------------------------------------------------------------------------ ==== Configuration options Also see <>. ===== `parseunknown` When this option is enabled, it forces the memcache text protocol parser to accept unknown commands. NOTE: The unknown commands MUST NOT contain a data part. ===== `maxvalues` The maximum number of values to store in the message (multi-get). All values will be base64 encoded. The possible settings for this option are: * `maxvalue: -1`, which stores all values (text based protocol multi-get) * `maxvalue: 0`, which stores no values (default) * `maxvalue: N`, which stores up to N values ===== `maxbytespervalue` The maximum number of bytes to be copied for each value element. NOTE: Values will be base64 encoded, so the actual size in the JSON document will be 4 times the value that you specify for `maxbytespervalue`. ===== `udptransactiontimeout` The transaction timeout in milliseconds. The defaults is 10000 milliseconds. NOTE: Quiet messages in UDP binary protocol get responses only if there is an error. The memcache protocol analyzer will wait for the number of milliseconds specified by `udptransactiontimeout` before publishing quiet messages. Non-quiet messages or quiet requests with an error response are published immediately. [[packetbeat-mysql-options]] === Capture MySQL traffic ++++ MySQL ++++ The `mysql` section of the +{beatname_lc}.yml+ config file specifies configuration options for the MySQL protocols. [source,yaml] ------------------------------------------------------------------------------ packetbeat.protocols: - type: mysql ports: [3306,3307] ------------------------------------------------------------------------------ ==== Configuration options Also see <>. ===== `max_rows` The maximum number of rows from the SQL message to publish to Elasticsearch. The default is 10 rows. ===== `max_row_length` The maximum length in bytes of a row from the SQL message to publish to Elasticsearch. The default is 1024 bytes. ==== `statement_timeout` The duration for which prepared statements are cached after their last use. Valid time units are ""ns"", ""us"" (or ""µs""), ""ms"", ""s"", ""m"", ""h"". The default is `1h`. [[packetbeat-pgsql-options]] === Capture PgSQL traffic ++++ PgSQL ++++ The `pgsql` sections of the +{beatname_lc}.yml+ config file specifies configuration options for the PgSQL protocols. [source,yaml] ------------------------------------------------------------------------------ packetbeat.protocols: - type: pgsql ports: [5432] ------------------------------------------------------------------------------ ==== Configuration options Also see <>. ===== `max_rows` The maximum number of rows from the SQL message to publish to Elasticsearch. The default is 10 rows. ===== `max_row_length` The maximum length in bytes of a row from the SQL message to publish to Elasticsearch. The default is 1024 bytes. [[configuration-thrift]] === Capture Thrift traffic ++++ Thrift ++++ https://thrift.apache.org/[Apache Thrift] is a communication protocol and RPC framework initially created at Facebook. It is sometimes used in http://martinfowler.com/articles/microservices.html[microservices] architectures because it provides better performance when compared to the more obvious HTTP/RESTful API choice, while still supporting a wide range of programming languages and frameworks. Packetbeat works based on a copy of the traffic, which means that you get performance management features without having to modify your services in any way and without any latency overhead. Packetbeat captures the transactions from the network and indexes them in Elasticsearch so that they can be analyzed and searched. Packetbeat indexes the method, parameters, return value, and exceptions of each Thrift-RPC call. You can search by and create statistics based on any of these fields. Packetbeat automatically fills in the `status` column with either `OK` or `Error`, so it's easy to find the problematic RPC calls. A transaction is put into the `Error` state if it returned an exception. Packetbeat also indexes the `event.duration` field so you can get performance analytics and find the slow RPC calls. Here is an example performance dashboard: image::./images/thrift-dashboard.png[Thrift-RPC dashboard] Thrift supports multiple http://en.wikipedia.org/wiki/Apache_Thrift[transport and protocol types]. Currently Packetbeat supports the default `TSocket` transport as well as the `TFramed` transport. From the protocol point of view, Packetbeat currently supports only the default `TBinary` protocol. Packetbeat also has several configuration options that allow you to get the right balance between visibility, disk usage, and data protection. You can, for example, choose to obfuscate all strings or to store the requests but not the responses, while still capturing the response time for each of the RPC calls. You can also choose to limit the size of strings and lists to a given number of elements, so you can fine tune how much data you want to have stored in Elasticsearch. The Thrift protocol has several specific configuration options. Here is an example configuration section for the Thrift protocol in the +{beatname_lc}.yml+ config file: [source,yaml] ------------------------------------------------------------------------------ packetbeat.protocols: - type: thrift transport_type: socket protocol_type: binary idl_files: [""tutorial.thrift"", ""shared.thrift""] string_max_size: 200 collection_max_size: 20 capture_reply: true obfuscate_strings: true drop_after_n_struct_fields: 100 ------------------------------------------------------------------------------ Providing the Thrift IDL files to Packetbeat is optional. The binary Thrift messages include the called method name and enough structural information to decode the messages without needing the IDL files. However, if you provide the IDL files, Packetbeat can also resolve the service name, arguments, and exception names. ==== Configuration options Also see <>. ===== `transport_type` The Thrift transport type. Currently this option accepts the values `socket` for TSocket, which is the default Thrift transport, and `framed` for the TFramed Thrift transport. The default is `socket`. ===== `protocol_type` The Thrift protocol type. Currently the only accepted value is `binary` for the TBinary protocol, which is the default Thrift protocol. ===== `idl_files` The Thrift interface description language (IDL) files for the service that Packetbeat is monitoring. Providing the IDL files is optional, because the Thrift messages contain enough information to decode them without having the IDL files. However, providing the IDL enables Packetbeat to include parameter and exception names. ===== `string_max_size` The maximum length for strings in parameters or return values. If a string is longer than this value, the string is automatically truncated to this length. Packetbeat adds dots at the end of the string to mark that it was truncated. The default is 200. ===== `collection_max_size` The maximum number of elements in a Thrift list, set, map, or structure. If a collection has more elements than this value, Packetbeat captures only the specified number of elements. Packetbeat adds a fictive last element `...` to the end of the collection to mark that it was truncated. The default is 15. ===== `capture_reply` If this option is set to false, Packetbeat decodes the method name from the reply and simply skips the rest of the response message. This setting can be useful for performance, disk usage, or data retention reasons. The default is true. ===== `obfuscate_strings` If this option is set to true, Packetbeat replaces all strings found in method parameters, return codes, or exception structures with the `""*""` string. ===== `drop_after_n_struct_fields` The maximum number of fields that a structure can have before Packetbeat ignores the whole transaction. This is a memory protection mechanism (so that Packetbeat's memory doesn't grow indefinitely), so you would typically set this to a relatively high value. The default is 500. [[configuration-mongodb]] === Capture MongoDB traffic ++++ MongoDB ++++ The following settings are specific to the MongoDB protocol. Here is a sample configuration for the `mongodb` section of the +{beatname_lc}.yml+ config file: [source,yaml] ------------------------------------------------------------------------------ packetbeat.protocols: - type: mongodb send_request: true send_response: true max_docs: 0 max_doc_length: 0 ------------------------------------------------------------------------------ ==== Configuration options The `max_docs` and `max_doc_length` settings are useful for limiting the amount of data Packetbeat indexes in the `response` fields. Also see <>. ===== `max_docs` The maximum number of documents from the response to index in the `response` field. The default is 10. You can set this to 0 to index an unlimited number of documents. Packetbeat adds a `[...]` line at the end to signify that there were additional documents that weren't saved because of this setting. ===== `max_doc_length` The maximum number of characters in a single document indexed in the `response` field. The default is 5000. You can set this to 0 to index an unlimited number of characters per document. If the document is trimmed because of this setting, Packetbeat adds the string `...` at the end of the document. Note that limiting documents in this way means that they are no longer correctly formatted JSON objects. [[configuration-tls]] === Capture TLS traffic ++++ TLS ++++ TLS is a cryptographic protocol that provides secure communications on top of an existing application protocol, like HTTP or MySQL. Packetbeat intercepts the initial handshake in a TLS connection and extracts useful information that helps operators diagnose problems and strengthen the security of their network and systems. It does not decrypt any information from the encapsulated protocol, nor does it reveal any sensitive information such as cryptographic keys. TLS versions 1.0 to 1.3 and SSL 3.0 are supported. It works by intercepting the client and server ""hello"" messages, which contain the negotiated parameters for the connection such as cryptographic ciphers and protocol versions. It can also intercept TLS alerts, which are sent by one of the parties to signal a problem with the negotiation, such as an expired certificate or a cryptographic error. An example of indexed event: [source,json] ------------------------------------------------------------------------------ ""tls"": { ""client"": { ""supported_ciphers"": [ ""TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384"", ""TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384"", ""TLS_RSA_WITH_3DES_EDE_CBC_SHA"", ""TLS_EMPTY_RENEGOTIATION_INFO_SCSV"" ], ""ja3"": ""e6573e91e6eb777c0933c5b8f97f10cd"", ""server_name"": ""example.net"" }, ""server"": { ""subject"": ""CN=www.example.org,OU=Technology,O=Internet Corporation for Assigned Names and Numbers,L=Los Angeles,ST=California,C=US"", ""issuer"": ""CN=DigiCert SHA2 Secure Server CA,O=DigiCert Inc,C=US"", ""not_before"": ""2018-11-28T00:00:00.000Z"", ""not_after"": ""2020-12-02T12:00:00.000Z"", ""hash"": { ""sha1"": ""7BB698386970363D2919CC5772846984FFD4A889"" } }, ""version"": ""1.2"", ""version_protocol"": ""tls"", ""cipher"": ""TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256"", ""established"": true, ""next_protocol"": ""h2"", ""detailed"": { ""server_certificate"": { ""subject"": { ""common_name"": ""www.example.org"", ""country"": ""US"", ""organization"": ""Internet Corporation for Assigned Names and Numbers"", ""organizational_unit"": ""Technology"", ""locality"": ""Los Angeles"", ""province"": ""California"" }, ""not_after"": ""2020-12-02T12:00:00.000Z"", ""public_key_size"": 2048, ""alternative_names"": [ ""www.example.org"", ""example.com"", ""example.edu"", ""example.net"", ""example.org"", ""www.example.com"", ""www.example.edu"", ""www.example.net"" ], ""signature_algorithm"": ""SHA256-RSA"", ""version"": 3, ""issuer"": { ""organization"": ""DigiCert Inc"", ""common_name"": ""DigiCert SHA2 Secure Server CA"", ""country"": ""US"" }, ""not_before"": ""2018-11-28T00:00:00.000Z"", ""public_key_algorithm"": ""RSA"", ""serial_number"": ""21020869104500376438182461249190639870"" }, ""server_certificate_chain"": [ { ""public_key_algorithm"": ""RSA"", ""not_before"": ""2013-03-08T12:00:00.000Z"", ""not_after"": ""2023-03-08T12:00:00.000Z"", ""version"": 3, ""serial_number"": ""2646203786665923649276728595390119057"", ""issuer"": { ""organizational_unit"": ""www.digicert.com"", ""common_name"": ""DigiCert Global Root CA"", ""country"": ""US"", ""organization"": ""DigiCert Inc"" }, ""subject"": { ""country"": ""US"", ""organization"": ""DigiCert Inc"", ""common_name"": ""DigiCert SHA2 Secure Server CA"" }, ""public_key_size"": 2048, ""signature_algorithm"": ""SHA256-RSA"" }, { ""public_key_algorithm"": ""RSA"", ""subject"": { ""common_name"": ""DigiCert Global Root CA"", ""country"": ""US"", ""organization"": ""DigiCert Inc"", ""organizational_unit"": ""www.digicert.com"" }, ""issuer"": { ""country"": ""US"", ""organization"": ""DigiCert Inc"", ""organizational_unit"": ""www.digicert.com"", ""common_name"": ""DigiCert Global Root CA"" }, ""signature_algorithm"": ""SHA1-RSA"", ""serial_number"": ""10944719598952040374951832963794454346"", ""not_before"": ""2006-11-10T00:00:00.000Z"", ""not_after"": ""2031-11-10T00:00:00.000Z"", ""public_key_size"": 2048, ""version"": 3 } ], ""client_certificate_requested"": false, ""version"": ""TLS 1.2"", ""client_hello"": { ""version"": ""3.3"", ""supported_compression_methods"": [ ""NULL"" ], ""extensions"": { ""ec_points_formats"": [ ""uncompressed"" ], ""supported_groups"": [ ""x25519"", ""secp256r1"", ""secp384r1"" ], ""signature_algorithms"": [ ""rsa_pkcs1_sha512"", ""ecdsa_secp521r1_sha512"", ""(unknown:0xefef)"", ""rsa_pkcs1_sha384"", ""ecdsa_secp384r1_sha384"", ""rsa_pkcs1_sha256"", ""ecdsa_secp256r1_sha256"", ""(unknown:0xeeee)"", ""(unknown:0xeded)"", ""(unknown:0x0301)"", ""(unknown:0x0303)"", ""rsa_pkcs1_sha1"", ""ecdsa_sha1"" ], ""application_layer_protocol_negotiation"": [ ""h2"", ""http/1.1"" ], ""server_name_indication"": [ ""example.net"" ] } }, ""server_hello"": { ""version"": ""3.3"", ""session_id"": ""23bb2aed5d215e1228220b0a51d7aa220785e9e4b83b4f430229117971e9913f"", ""selected_compression_method"": ""NULL"", ""extensions"": { ""application_layer_protocol_negotiation"": [ ""h2"" ], ""_unparsed_"": [ ""renegotiation_info"", ""server_name_indication"" ], ""ec_points_formats"": [ ""uncompressed"", ""ansiX962_compressed_prime"", ""ansiX962_compressed_char2"" ] } } } } ------------------------------------------------------------------------------ The TLS events generated by {beatname_uc} follow the Elastic Common Schema (ECS) format. See {ecs-ref}/ecs-tls.html[ECS TLS fields] for a description of the populated fields. Detailed information that is not defined in ECS is added under the `tls.detailed` key. The <> configuration flag is used to control whether this information is exported. The fields under `tls.detailed.client_hello` contain the algorithms and extensions supported by the client, as well as the maximum TLS version it supports. Fields under `tls.detailed.server_hello` contain the final settings for the TLS session: The selected cipher, compression method, TLS version to use and other extensions such as application layer protocol negotiation (ALPN). See the <> section for more information. The following settings are specific to the TLS protocol. Here is a sample configuration for the `tls` section of the +{beatname_lc}.yml+ config file: [source,yaml] ------------------------------------------------------------------------------ packetbeat.protocols: - type: tls send_certificates: true include_raw_certificates: false include_detailed_fields: true fingerprints: [ md5, sha1, sha256 ] ------------------------------------------------------------------------------ ==== Configuration options The `send_certificates` and `include_detailed_fields` settings are useful for limiting the amount of data Packetbeat indexes, as multiple certificates are usually exchanged in a single transaction, and those can take a considerable amount of storage. Also see <>. ===== `send_certificates` This setting causes information about the certificates presented by the client and server to be included in the detailed fields. The server's certificate is indexed under `tls.detailed.server_certificate` and its certification chain under `tls.detailed.server_certificate_chain`. For the client, the `client_certificate` and `client_certificate_chain` fields are used. The default is true. ===== `include_raw_certificates` You can set `include_raw_certificates` to include the raw certificate chains encoded in PEM format, under the `tls.server.certificate_chain` and `tls.client.certificate_chain` fields. The default is false. [[include_detailed_fields]] ===== `include_detailed_fields` Controls whether the <> are added to exported documents. When set to `false`, only {ecs-ref}/ecs-tls.html[ECS TLS fields] are included. The default is `true`. ===== `fingerprints` Defines a list of hash algorithms to calculate the certificate's fingerprints. Valid values are `sha1`, `sha256` and `md5`. The default is to output SHA-1 fingerprints. [[packetbeat-redis-options]] === Capture Redis traffic ++++ Redis ++++ The Redis protocol has several specific configuration options. Here is a sample configuration for the `redis` section of the +{beatname_lc}.yml+ config file: [source,yaml] ------------------------------------------------------------------------------ packetbeat.protocols: - type: redis ports: [6379] queue_max_bytes: 1048576 queue_max_messages: 20000 ------------------------------------------------------------------------------ ==== Configuration options Also see <>. ===== `queue_max_bytes` and `queue_max_messages` In order for request/response correlation to work, {beatname_uc} needs to store requests in memory until a response is received. These settings impose a limit on the number of bytes (`queue_max_bytes`) and number of requests (`queue_max_messages`) that can be stored. These limits are per-connection. The default is to queue up to 1MB or 20.000 requests per connection, which allows to use request pipelining while at the same time limiting the amount of memory consumed by replication sessions. [[configuration-processes]] == Specify which processes to monitor This section of the +{beatname_lc}.yml+ config file is optional, but configuring the processes enables Packetbeat to show you not only the servers that the traffic is flowing between, but also the processes. Packetbeat can even show you the traffic between two processes running on the same host, which is particularly useful when you have many services running on the same server. By default, process enrichment is disabled. When Packetbeat starts, and then periodically afterwards, it scans the process table for processes that match the configuration file. For each of these processes, it monitors which file descriptors it has opened. When a new packet is captured, it reads the list of active TCP and UDP connections and matches the corresponding one with the list of file descriptors. All this information is available via system interfaces: The `/proc` file system in Linux and the IP Helper API (`iphlpapi.dll`) on Windows, so {beatname_uc} doesn't need a kernel module. NOTE: Process monitoring is currently only supported on Linux and Windows systems. Packetbeat automatically disables process monitoring when it detects other operating systems. Example configuration: [source,yaml] ------------------------------------------------------------------------------ packetbeat.procs.enabled: true ------------------------------------------------------------------------------ When the process monitor is enabled, it will enrich all the events whose source or destination is a local process. The `source.process` and/or `destination.process` fields will be added to an event, when the server side or client side of the connection belong to a local process, respectively. [float] === Configuration options You can specify the following process monitoring options in the `monitored` section of the +{beatname_lc}.yml+ config file to customize the name of process: [float] ==== `process` The name of the process as it will appear in the published transactions. The name doesn't have to match the name of the executable, so feel free to choose something more descriptive (for example, ""myapp"" instead of ""gunicorn""). [float] ==== `cmdline_grep` The name used to identify the process at run time. When Packetbeat starts, and then periodically afterwards, it scans the process table for processes that match the values specified for this option. The match is done against the process' command line as read from `/proc//cmdline`. [float] [[shutdown-timeout]] ==== `shutdown_timeout` How long Packetbeat waits on shutdown. By default, this option is disabled. Packetbeat will wait for `shutdown_timeout` and then close. It will not track if all events were sent previously. Example configuration: [source,yaml] ------------------------------------------------------------------------------------- packetbeat.shutdown_timeout: 5s ------------------------------------------------------------------------------------- ",12167,False,2102.4634307587703,median "--- title: El Gestor de Volúmenes vinum authors: - author: Greg Lehey --- = El Gestor de Volúmenes vinum :doctype: article :toc: macro :toclevels: 1 :icons: font :sectnums: :sectnumlevels: 6 :source-highlighter: rouge :experimental: include::shared/en/urls.adoc[] ifeval::[""{backend}"" == ""html5""] :imagesdir: ../../../images/articles/vinum/ endif::[] ifeval::[""{backend}"" == ""pdf""] :imagesdir: ../../../../static/images/articles/vinum/ endif::[] ifeval::[""{backend}"" == ""epub3""] :imagesdir: ../../../../static/images/articles/vinum/ endif::[] ''' toc::[] [[vinum-synopsis]] == Sinopsis Independientemente del tipo de disco, siempre hay problemas potenciales. Los discos pueden ser muy pequeños, muy lentos, o muy poco fiables para cumplir con los requisitos del sistema. Aunque los discos crecen, también lo hacen los requisitos de almacenamiento. A menudo se necesita un sistema de ficheros que es mayor que la capacidad del disco. Se han propuesto e implementado varias soluciones a estos problemas. Un método es mediante el uso de múltiples, y a veces redundantes, discos. Además de soportar varias tarjetas y controladores hardware de sistemas de Arrays Redundantes de Discos Independientes RAID , el sistema base de FreeBSD incluye el gestor de volúmenes [.filename]#vinum# , un controlador de dispositivos de bloques que implementa unidades virtuales de disco y que aborda estos tres problemas. [.filename]#vinum# proporciona más flexibilidad, rendimiento, y fiabilidad que el almacenamiento de disco tradicional e implementa los modelos RAID-0, RAID-1, y RAID-5 , tanto individualmente como combinados. Este capítulo proporciona una visión general de los problemas potenciales del almacenamiento tradicional en disco, y una introducción al gestor de volúmenes [.filename]#vinum#. [NOTE] ==== Comenzando con FreeBSD 5, [.filename]#vinum# ha sido reescrito para adaptarlo a la link:{handbook}#geom[arquitectura de GEOM], a la vez que se mantienen las ideas originales, terminología, y metadata en disco. Esta reescritura se llama `gvinum`. El nombre del módulo del kernel ha cambiado del original [.filename]#vinum.ko# a [.filename]#geom_vinum.ko#, y todos los nodos de dispositivo residen bajo [.filename]#/dev/gvinum# en lugar de [.filename]#/dev/vinum#. A partir de FreeBSD 6, la implementación original de [.filename]#vinum# no está disponible en el código base. ==== [[vinum-access-bottlenecks]] == Cuellos de botella de acceso Los sistemas modernos necesitan frecuentemente acceder a los datos de una forma altamente concurrente. Por ejemplo, grandes servidores de FTP o HTTP pueden mantener miles de sesiones concurrents y tener conexiones de 100 Mbit/s al mundo exterior, mucho más que la tasa de transferencia mantenida de la mayoría de los discos. Las unidades de disco actuales pueden transferir datos secuencialmente hasta unos 70 MB/s, pero este valor tiene poca importancia en un entorno en el que muchos procesos independientes acceden a un dispositivo, y donde solo pueden conseguir una fracción de esos valores. En tales casos, es más interesante ver el problema desde el punto de vista del subsistema de disco. El parámetro importante es la carga que una transferencia supone en el subsistema, o el tiempo para el cual la transferencia ocupa los dispositivos involucrados en la misma. En cualquier transferencia de disco, la unidad debe primero posicionar el cabezal, esperar a que el primer sector pase bajo la cabeza de lectura, y después realizar la transferencia. Estas acciones pueden considerarse atómicas y que no tiene sentido interrumpirlas. [[vinum-latency]]Considera una transferencia típica de unos 10 kB: la generación actual de discos de alto rendimiento pueden situar los cabezales en unos 3.5 ms de media. Los discos más rápidos giran a 15,000 rpm, así que la latencia rotacional media (media revolución) es 2 ms. A 70 MB/s, la propia transferencia tarda unos 150 μs, casi nada comparado con el tiempo de posicionamiento. En ese caso, la tasa efectiva de transferencia cae hasta un poco más de 1 MB/s y depende claramente del tamaño de la transferencia. La solución obvia y tradicional a este cuello de botella es ""más agujas"": en lugar de usar un gran disco, usar varios discos pequeños con el mismo espacio de almacenamiento agregado. Cada disco es capaz de posicionar y transferir de forma independiente, así que el rendimiento efectivo aumenta en un factor próximo al número de discos utilizados. La mejora de rendimiento real es menor que el número de discos involucrados. Aunque cada dispositivo es capaz de transferir en paralelo, no hay forma de asegurar que las peticiones se distribuyen de forma equilibrada entre los dispositivos. Inevitablemente la carga en un dispositivo será mayor que en otro. El reparto equitativo de la carga en los discos depende fuertemente de la forma en la que los datos se comparten entre los dispositivos. En la siguiente discusión, es conveniente pensar en el almacenamiento de disco como un número grande de sectores que son direccionables mediante un número, parecido a las páginas de un libro. El método más obvio es dividir el disco virtual en grupos de sectores consecutivos del tamaño de los discos físicos individuales y almacenarlos de este modo, como coger un libro grande y romperlo en secciones pequeñas. Este método se llama _concatenación_ y tiene la ventaja de que los discos no requieren tener ninguna relación específica de tamaño entre ellos. Funciona bien cuando los accesos al disco virtual se reparten equitativamente en su espacio de direcciones. Cuando el acceso se concentra en un área más pequeña, la mejora es menos acentuada. <> ilustra una secuencia en la que las unidades de almacenamiento están asignadas en una organización concatenada. [[vinum-concat]] .Organización Concatenada image::vinum-concat.png[] Un mapeo alternativo es dividir el espacio de direcciones en componentes más pequeños del mismos tamaño y almacenarlos secuencialmente en distintos dispositivos. Por ejemplo, los primeros 256 sectores podrían ser almacenados en el primer disco, los 256 sectores siguientes en el siguiente disco, etc. Después de rellenar el último disco, el proceso se repite hasta que los discos están llenos. Este mapeo se llama _segmentado_ o RAID-0. RAID ofrece varias formas de tolerancia a fallos, aunque RAID-0 es algo engañoso ya que no provee redundancia. El segmentado requiere algo más de esfuerzo para localizar el dato, y puede ocasionar carga de E/S adicional cuando una transferencia está repartida por múltiples discos, pero también puede proporcionar una carga más constante entre los discos. <> ilustra la secuencia en la que las unidades de discos están asignadas en una organización segmentada. [[vinum-striped]] .Organización Segmentada image::vinum-striped.png[] [[vinum-data-integrity]] == Integridad de los Datos El último problema con los discos es que no son fiables. Aunque la fiabilidad se ha incrementado tremendamente en los últimos años, las unidades de disco todavía son el componente central de un servidor más propensos a fallar. Cuando lo hacen, los resultados pueden ser catastróficas y reemplazar una unidad de disco que ha fallado y restaurar los datos puede resultar en tiempo de parada del servidor. Una aproximación a este problema es el _mirroring_, o RAID-1, que mantiene dos copias de los datos en distinto hardware físico. Cualquier escritura en el volumen escribe en ambos discos; una lectura puede ser resuelta por cualquiera, así que si un disco falla, los datos todavía están disponibles en la otra unidad. La configuración en espejo tiene dos problemas: * Requiere el doble de espacio de almacenamiento que una solución sin redundancia. * Las escrituras deben realizarse en las dos unidades, de forma que utilizan el doble de ancho de banda que un volumen sin espejo. Las lecturas no sufren penalización en lectura e incluso pueden ser más rápidas. Una solución alternativa es la _paridad_, implementada en los niveles RAID 2, 3, 4 y 5. De estos, RAID-5 es el más interesante. Como está implementado en [.filename]#vinum#, es una variante en una organización segmentada que dedica un bloque en cada segmento para guardar la paridad de los otros bloques. Tal como está implementado en [.filename]#vinum#, un RAID-5 plex es similar a un plex segmentado, excepto que implementa RAID-5 al incluir un bloque de paridad en cada segmento. Según lo requerido por RAID-5, la localización de este bloque de paridad cambia de un segmento al siguiente. Los números en los bloques de datos indican los números de bloque relativos. [[vinum-raid5-org]] .Organización RAID-5 image::vinum-raid5-org.png[] Comparado con la configuración en espejo, RAID-5 tiene la ventaja de que requiere mucho menos espacio de almacenamiento. El acceso de lectura es similar a una organización segmentada, pero el acceso de escritura es significativamente más lento, aproximadamente el 25% del rendimiento de lectura. Si una unidad falla, el array puede seguir operando en un modo degradado donde una lectura de una de las unidades que quedan accesibles continua normalmente, pero una lectura de una unidad que ha fallado es recalculada a partir de los bloques correspondientes del resto de unidades. [[vinum-objects]] == Objetos [.filename]#vinum# Para abordar estos problemas, [.filename]#vinum# implementa una jerarquía de objetos en cuatro niveles: * El objeto más visible es el disco virtual, llamado _volumen_. Volúmenes tienen esencialmente las mismas propiedades que una unidad de disco UNIX(TM) aunque hay algunas pequeñas diferencias. Una de ellas, que no tienen limitación de tamaño. * Los volúmenes se componen de _plexes_, cada uno de los cuales representa el espacio de direcciones total de un volumen. Este nivel en la jerarquía proporciona redundancia. Piensa en los plexes como en discos individuales en un array replicado en espejo, cada uno conteniendo los mismos datos. * Puesto que [.filename]#vinum# dentro del framework de almacenamiento de disco de UNIX(TM), sería posible utilizar particiones UNIX(TM) como bloques de construcción para plexes multi-disco. En realidad, esto resulta demasiado poco flexible ya que los discos UNIX(TM) sólo pueden tener un número limitado de particiones. En su lugar, [.filename]#vinum# subdivide una única partición UNIX(TM), la _drive_, en areas contiguas llamadas _subdiscos_, los cuales se utilizan como bloques de construcción de plexes. * Los subdiscos residen en _unidades_ [.filename]#vinum#, actualmente particiones UNIX(TM). Las unidades [.filename]#vinum# pueden tener cualquier número de subdiscos. Con la excepción de una pequeña área al comienzo de la unidad, que es utilizada para almacenar información de estado y configuración, la unidad entera está disponible para almacenamiento de datos. Las secciones siguientes describen el modo en el que estos objetos proporcionan la funcionalidad requerida por [.filename]#vinum#. === Consideraciones sobre el Tamaño del Volumen Plexes pueden incluir múltiples subdiscos repartidos por todas las unidades en la configuración de [.filename]#vinum#. Como resultado, el tamaño de una unidad individual no limita el tamaño de un plex o un volumen. === Almacenamiento de Datos Redundante [.filename]#vinum# implementa configuraciones en espejo adjuntando varios plexes a un volumen. Cada plex es una representación de los datos en un volumen. Un volumen puede contener entre uno y ocho plexes. Aunque un plex representa los datos completos de un volumen, es posible que algunas partes de esta representación falten físicamente, bien por diseño (no definiendo un subdisco para algunas partes del plex) o por accidente (como resultado del fallo de una unidad). Mientras un plex pueda proveer los datos para el rango completo de direcciones del volumen, este es plenamente funcional. === ¿Qué Organización Plex? [.filename]#vinum# implementa tanto concatenación como segmentado a nivel de plex: * Un _plex concatenado_ usa el espacio de direcciones de cada subdisco por turnos. Los plexes concatenados son los más flexibles ya que pueden contener cualquier número de subdiscos, y los subidscos pueden ser de distintas longitudes. El plex se puede extender añadiendo subdiscos adicionales. Requieren menos tiempo de CPU que los plexes segmentados, aunque la diferencia en sobrecarga de CPU casi no se nota. Por otro lado, son más susceptibles a los puntos calientes, en donde un disco está muy activo y los otros ociosos. * Un _plex segmentado_ reparte los datos entre los distintos subdiscos. Los subdiscos deben tener todos el mismo tamaño y debe haber al menos dos subdiscos para poder distinguirlo de un plex concatenado. La mayor ventaja de los plexes segmentados es que reducen los puntos calientes. Escogiendo un tamaño óptimo de segmento, alrededor de 256 kB, la carga se puede repartir equitativamente entre las unidades. Extender un plex añadiendo nuevos subdiscos es tan complicado que [.filename]#vinum# no lo implementa. <> resume las ventajas y desventajas de cada organización plex. [[vinum-comparison]] .Organizaciones Plex en [.filename]#vinum# [cols=""1,1,1,1,1"", frame=""none"", options=""header""] |=== | Tipo de plex | Subdiscos mínimos | Puede añadir subdiscos | Deben tener el mismo tamaño | Aplicación |concatenado |1 |si |no |Almacenamiento de grandes cantidades de datos con máxima flexibilidad de colocación y rendimiento moderado |segmentado |2 |no |si |Alto rendimiento combinado con acceso altamente concurrente |=== [[vinum-examples]] == Algunos Ejemplos [.filename]#vinum# mantiene una _base de datos de configuración_ la cual describe los objetos que son conocidos a un sistema individual. Inicialmente, el usuario crea la base de datos de configuración a partir de uno o más ficheros de configuración utilizando man:gvinum[8]. [.filename]#vinum# almacena una copia de su base de datos de configuración en cada _dispositivo_ de disco bajo su control. Esta base de datos se actualiza con cada cambio de estado, de forma que un reinicio restablece de forma precisa el estado de cada objeto de [.filename]#vinum#. === El Fichero de Configuración El fichero de configuración describe objetos de [.filename]#vinum# individuales. La definición de un volumen sencillo podría ser: [.programlisting] .... drive a device /dev/da3h volume myvol plex org concat sd length 512m drive a .... Este fichero describe cuatro objetos [.filename]#vinum#: * La línea _unidad_ describe una partición de disco (_unidad_) y su localización relativa al hardware que hay debajo. Se le da el nombre simbólico _a_. La separación entre los nombres simbólicos y los nombres de dispositivo permite mover discos de un lugar a otro sin confusión. * La línea _volumen_ describe un volumen. El único atributo requerido es el nombre, en este caso _myvol_. * La línea _plex_ define un lex. El único parámetro requerido es la organización, en este caso _concat_. El nombre no es necesario ya que el sistema genera uno automáticamente a partir del nombre del volumen añadiendo el sufijo _.px_, donde _x_ es el número del plex en el volumen. Por lo tanto este plex se llamará _myvol.p0_. * La línea _sd_ describe un subdisco. La especificación mínima incluye el nombre de la unidad en la que almacenarlo, y la longitud del subdisco. El bombre no es necesario ya que el sistema asigna un nombre automáticamente derivado del nombre del plex añadiendo el sufijo _.sx_, donde _x_ es el número del subdisco en el plex. Por lo tanto [.filename]#vinum# asigna a este subdisco el nombre _myvol.p0.s0_. Después de procesar este fichero, man:gvinum[8] produce la siguiente salida: [.programlisting] .... # gvinum -> create config1 Configuration summary Drives: 1 (4 configured) Volumes: 1 (4 configured) Plexes: 1 (8 configured) Subdisks: 1 (16 configured) D a State: up Device /dev/da3h Avail: 2061/2573 MB (80%) V myvol State: up Plexes: 1 Size: 512 MB P myvol.p0 C State: up Subdisks: 1 Size: 512 MB S myvol.p0.s0 State: up PO: 0 B Size: 512 MB .... Esta salida muestra el formato de lista abreviada de man:gvinum[8]. Está representado gráficamente en <>. [[vinum-simple-vol]] .Un Volumen [.filename]#vinum# Sencillo image::vinum-simple-vol.png[] Esta imagen, y las que siguen, representa un volumen, el cual contiene plexes, que a su vez contienen subdiscos. En este ejemplo, el volumen contiene u nplex, y el plex contiene un subdisco. Este volumen en particular no tiene ninguna ventaja sobre una partición de disco convencional. Contiene un solo plex, así que no es redundante. El plex contiene un solo subdisco, así que no hay diferencia en la asignación de almacenamiento respecto a una partición de disco convencional. Las siguientes secciones ilustran varios métodos de configuración más interesantes. === Resiliencia Incrementada: Configuración en Espejo La resiliencia de un volumen puede ser incrementada mediante una configuración en espejo. Cuando se diseña un volumen en espejo, es importante asegurar que los subdiscos de cada plex están en diferentes unidades, de forma que el fallo de una unidad no arrastre ambos plexes. La siguiente configuración crea un espejo de un volumen: [.programlisting] .... drive b device /dev/da4h volume mirror plex org concat sd length 512m drive a plex org concat sd length 512m drive b .... En este ejemplo, no ha sido necesario especificar la definición de la unidad _a_ de nuevo, ya que [.filename]#vinum# hace un seguimiento de todos los objetos en su base de datos de configuración. Después de procesar esta definición, la configuración tiene este aspecto: [.programlisting] .... Drives: 2 (4 configured) Volumes: 2 (4 configured) Plexes: 3 (8 configured) Subdisks: 3 (16 configured) D a State: up Device /dev/da3h Avail: 1549/2573 MB (60%) D b State: up Device /dev/da4h Avail: 2061/2573 MB (80%) V myvol State: up Plexes: 1 Size: 512 MB V mirror State: up Plexes: 2 Size: 512 MB P myvol.p0 C State: up Subdisks: 1 Size: 512 MB P mirror.p0 C State: up Subdisks: 1 Size: 512 MB P mirror.p1 C State: initializing Subdisks: 1 Size: 512 MB S myvol.p0.s0 State: up PO: 0 B Size: 512 MB S mirror.p0.s0 State: up PO: 0 B Size: 512 MB S mirror.p1.s0 State: empty PO: 0 B Size: 512 MB .... <> muestra la estructura gráficamente. [[vinum-mirrored-vol]] .Un Volumen [.filename]#vinum# en Espejo image::vinum-mirrored-vol.png[] En este ejemplo, cada plex contiene los 512 MB del espacio de direcciones completo. Como en el ejemplo anterior, cada plex contiene solo un subdisco. === Optimizando el Rendimiento El volumen en espejo del ejemplo anterior es más resistente a fallos que un volumen que no esté en espejo, pero su rendimiento es menor ya que cada escritura en el volumen requiere una escritura en ambas unidades, usando una mayor porción del ancho de banda total del disco. Las consideraciones de rendimiento requieren una aproximación diferente: en lugar de replicar en espejo, los datos son segmentados en tantas unidades de disco como sea posible. La siguiente configuración muestra un volumen con un plex segmentado en cuatro discos: [.programlisting] .... drive c device /dev/da5h drive d device /dev/da6h volume stripe plex org striped 512k sd length 128m drive a sd length 128m drive b sd length 128m drive c sd length 128m drive d .... Como antes, no es necesario definir las unidades que ya son conocidas por [.filename]#vinum#. Después de procesar esta definición, la configuración tiene este aspecto: [.programlisting] .... Drives: 4 (4 configured) Volumes: 3 (4 configured) Plexes: 4 (8 configured) Subdisks: 7 (16 configured) D a State: up Device /dev/da3h Avail: 1421/2573 MB (55%) D b State: up Device /dev/da4h Avail: 1933/2573 MB (75%) D c State: up Device /dev/da5h Avail: 2445/2573 MB (95%) D d State: up Device /dev/da6h Avail: 2445/2573 MB (95%) V myvol State: up Plexes: 1 Size: 512 MB V mirror State: up Plexes: 2 Size: 512 MB V striped State: up Plexes: 1 Size: 512 MB P myvol.p0 C State: up Subdisks: 1 Size: 512 MB P mirror.p0 C State: up Subdisks: 1 Size: 512 MB P mirror.p1 C State: initializing Subdisks: 1 Size: 512 MB P striped.p1 State: up Subdisks: 1 Size: 512 MB S myvol.p0.s0 State: up PO: 0 B Size: 512 MB S mirror.p0.s0 State: up PO: 0 B Size: 512 MB S mirror.p1.s0 State: empty PO: 0 B Size: 512 MB S striped.p0.s0 State: up PO: 0 B Size: 128 MB S striped.p0.s1 State: up PO: 512 kB Size: 128 MB S striped.p0.s2 State: up PO: 1024 kB Size: 128 MB S striped.p0.s3 State: up PO: 1536 kB Size: 128 MB .... [[vinum-striped-vol]] .Un Volumen [.filename]#vinum# Segmentado image::vinum-striped-vol.png[] Este volumen está representado en <>. El color oscuro de los segmentos indican la posición dentro del espacio de direcciones del plex, donde los segmentos más claros aparecen primero y los más oscuros últimos. === Resiliencia y Rendimiento [[vinum-resilience]]Con suficiente hardware, es posible construir volúmenes que muestren resiliencia aumentada y rendimiento aumentado comparado con particiones UNIX(TM) estándar. Una configuración típica podría ser: [.programlisting] .... volume raid10 plex org striped 512k sd length 102480k drive a sd length 102480k drive b sd length 102480k drive c sd length 102480k drive d sd length 102480k drive e plex org striped 512k sd length 102480k drive c sd length 102480k drive d sd length 102480k drive e sd length 102480k drive a sd length 102480k drive b .... Los subdiscos del segundo plex están desplazados en dos unidades respecto a aquellos en el primer flex. Esto ayuda a garantizar que las escrituras no van al mismo subdisco incluso si la transferencia se realiza sobre dos unidades. <> representa la estructura de este volumen. [[vinum-raid10-vol]] .Un Volumen [.filename]#vinum# Segmentado en Espejo image::vinum-raid10-vol.png[] [[vinum-object-naming]] == Nombrado de Objetos [.filename]#vinum# asigna nombres por defecto a los plexes y los subdiscos, aunque pueden ser modificados. Modificar los nombres por defecto no está recomendado ya que no proprorciona una ventaja significativa y puede provocar confusión. Los nombres pueden contener cualquier carácter que no sea blanco, pero se recomienda restringirlos a letras, dígitos y al carácter subrayado. Los nombres de los volúmenes, plexes y subdiscos pueden tener hasta 64 caracteres de longitud, y los nombres de unidades pueden ser de hasta 32 caracteres de longitud. A los objetos [.filename]#vinum# se les asignan nodos de dispositivo en la jerarquía [.filename]#/dev/gvinum#. La configuración que se muestra arriba haría que [.filename]#vinum# creara los siguientes nodos de dispositivo: * Entradas de dispositivo para cada volumen. Estos son los dispositivos principales utilizados por [.filename]#vinum#. La configuración anterior incluiría los dispositivos [.filename]#/dev/gvinum/myvol#, [.filename]#/dev/gvinum/mirror#, [.filename]#/dev/gvinum/striped#, [.filename]#/dev/gvinum/raid5# y [.filename]#/dev/gvinum/raid10#. * Todos los volúmenes tienen entradas directas bajo [.filename]#/dev/gvinum/#. * Los directorios [.filename]#/dev/gvinum/plex#, y [.filename]#/dev/gvinum/sd#, los cuales contienen nodos de dispositivo para cada plex y para cada subdisco, respectivamente. Por ejemplo, considera el siguiente fichero de configuración: [.programlisting] .... drive drive1 device /dev/sd1h drive drive2 device /dev/sd2h drive drive3 device /dev/sd3h drive drive4 device /dev/sd4h volume s64 setupstate plex org striped 64k sd length 100m drive drive1 sd length 100m drive drive2 sd length 100m drive drive3 sd length 100m drive drive4 .... Después de procesar este fichero, man:gvinum[8] crea la siguiente estructura en [.filename]#/dev/gvinum#: [.programlisting] .... drwxr-xr-x 2 root wheel 512 Apr 13 16:46 plex crwxr-xr-- 1 root wheel 91, 2 Apr 13 16:46 s64 drwxr-xr-x 2 root wheel 512 Apr 13 16:46 sd /dev/vinum/plex: total 0 crwxr-xr-- 1 root wheel 25, 0x10000002 Apr 13 16:46 s64.p0 /dev/vinum/sd: total 0 crwxr-xr-- 1 root wheel 91, 0x20000002 Apr 13 16:46 s64.p0.s0 crwxr-xr-- 1 root wheel 91, 0x20100002 Apr 13 16:46 s64.p0.s1 crwxr-xr-- 1 root wheel 91, 0x20200002 Apr 13 16:46 s64.p0.s2 crwxr-xr-- 1 root wheel 91, 0x20300002 Apr 13 16:46 s64.p0.s3 .... Aunque se recomienda que los plexes y subdiscos no tengan asignados nombres específicos, las unidades de [.filename]#vinum# deben tener nombre. Esto hace posible mover una unidad a una localización diferente y que sea reconocida automáticamente. Los nombres de unidad pueden tener una longitud de hasta 32 caracteres. === Creando Sistemas de Ficheros En el sistema los volúmenes parecen idénticos a los discos, con una excepción. A diferencia de las unidades UNIX(TM), [.filename]#vinum# no particiona los volúmenes, por lo que estos no tienen tabla de particiones. Esto ha requerido modificaciones en algunas utilidades de disco, notablemente de man:newfs[8], de forma que no intente interpretar la última letra de un nombre de volumen [.filename]#vinum#. Por ejemplo, una unidad de disco podría tener un nombre como [.filename]#/dev/ad0a# o [.filename]#/dev/da2h#. Estos nombres representan la primera partición ([.filename]#a#) en el primer (0) disco IDE ([.filename]#ad#) y la octava partición ([.filename]#h#) en el tercer (2) disco SCSI ([.filename]#da#) respectivamente. Por el contrario, un volumen [.filename]#vinum# podría llamarse [.filename]#/dev/gvinum/concat#, que no guarda relación con un nombre de partición. Para crear un sistema de ficheros en este volumen, usa man:newfs[8]: [source,bash] .... # newfs /dev/gvinum/concat .... [[vinum-config]] == Configurando [.filename]#vinum# El kernel [.filename]#GENERIC# no contiene [.filename]#vinum#. Es posible construir un kernel a medida que incluya [.filename]#vinum#, pero no se recomienda. La forma estándar de arrancar [.filename]#vinum# es como un módulo del kernel. man:kldload[8] no es necesario porque cuando man:gvinum[8] arranca, comprueba si el módulo ha sido cargado, y si no es así, lo carga automáticamente. === Arranque [.filename]#vinum# almacena información de configuración en las porciones de disco de forma esencialmente igual a como guarda los ficheros de configuración. Cuando lee de la base de datos de configuración, [.filename]#vinum# reconoce un número de palabras clave que no están permitidas en los ficheros de configuración. Por ejemplo, una configuración de disco podría contener el siguiente texto: [.programlisting] .... volume myvol state up volume bigraid state down plex name myvol.p0 state up org concat vol myvol plex name myvol.p1 state up org concat vol myvol plex name myvol.p2 state init org striped 512b vol myvol plex name bigraid.p0 state initializing org raid5 512b vol bigraid sd name myvol.p0.s0 drive a plex myvol.p0 state up len 1048576b driveoffset 265b plexoffset 0b sd name myvol.p0.s1 drive b plex myvol.p0 state up len 1048576b driveoffset 265b plexoffset 1048576b sd name myvol.p1.s0 drive c plex myvol.p1 state up len 1048576b driveoffset 265b plexoffset 0b sd name myvol.p1.s1 drive d plex myvol.p1 state up len 1048576b driveoffset 265b plexoffset 1048576b sd name myvol.p2.s0 drive a plex myvol.p2 state init len 524288b driveoffset 1048841b plexoffset 0b sd name myvol.p2.s1 drive b plex myvol.p2 state init len 524288b driveoffset 1048841b plexoffset 524288b sd name myvol.p2.s2 drive c plex myvol.p2 state init len 524288b driveoffset 1048841b plexoffset 1048576b sd name myvol.p2.s3 drive d plex myvol.p2 state init len 524288b driveoffset 1048841b plexoffset 1572864b sd name bigraid.p0.s0 drive a plex bigraid.p0 state initializing len 4194304b driveoff set 1573129b plexoffset 0b sd name bigraid.p0.s1 drive b plex bigraid.p0 state initializing len 4194304b driveoff set 1573129b plexoffset 4194304b sd name bigraid.p0.s2 drive c plex bigraid.p0 state initializing len 4194304b driveoff set 1573129b plexoffset 8388608b sd name bigraid.p0.s3 drive d plex bigraid.p0 state initializing len 4194304b driveoff set 1573129b plexoffset 12582912b sd name bigraid.p0.s4 drive e plex bigraid.p0 state initializing len 4194304b driveoff set 1573129b plexoffset 16777216b .... Aquí las diferencias obvias son la presencia de información explícita de localización y nombrado, ambas permitidas pero no recomendadas, y la información de los estados. [.filename]#vinum# no almacena información sobre las unidades en la información de configuración. Encuentra las unidades escaneando las unidades de disco configuradas en busca de particiones con una etiqueta [.filename]#vinum#. Esto posibilita que [.filename]#vinum# identifique las unidades correctamente incluso si se les han asignado identificadores de unidad UNIX(TM) diferentes. [[vinum-rc-startup]] ==== Arranque Automático _Gvinum_ siempre realiza un arranque automático una vez que el módulo del kernel ha sido cargado, via man:loader.conf[5]. Para cargar el módulo de _Gvinum_ en el arranque, añade `geom_vinum_load=""YES""` a [.filename]#/boot/loader.conf#. Cuando [.filename]#vinum# es arrancado con `gvinum start`, [.filename]#vinum# lee la base de datos de configuración de una de las unidades [.filename]#vinum#. En condiciones normales, cada unidad contiene una copia idéntica de la base de datos de configuración, de forma que no importa de qué unidad se lea. Después de una caída, sin embargo, [.filename]#vinum# debe determinar qué unidad fue actualizada más recientemente y leer la configuración de esta unidad. Después actualiza la configuración progresivamente, si es necesario, de unidades más antiguas. [[vinum-root]] == Usando [.filename]#vinum# para el Sistema de Ficheros Raíz Para una máquina que tiene sistemas de ficheros completamente en espejo usando [.filename]#vinum#, es deseable también configurar en espejo el sistema de ficheros raíz. Establecer dicha configuración es menos trivial que configurar en espejo un sistema de ficheros arbitrario porque: * El sistema de ficheros raíz debe estar disponible muy temprano durante el proceso de arranque, por lo que la infraestructura [.filename]#vinum# debe estar disponible en ese momento. * El volumen que contiene el sistema de ficheros raíz, también contiene el sistema de arranque y el kernel. Estos deben ser leídos usando las utilidades nativas del sistema hospedador, como la BIOS, que frecuentemente no puede ser informada de los detalles de [.filename]#vinum#. En las secciones siguientes, el término ""volumen raíz"" se utiliza para describir el volumen [.filename]#vinum# que contiene el sistema de ficheros raíz. === Arrancando [.filename]#vinum# Suficientemente Pronto para el Sistema de Ficheros Raíz [.filename]#vinum# debe estar disponible pronto en el arranque del sistema puesto que man:loader[8] debe ser capaz de cargar el módulo del kernel de vinum antes de arrancar el kernel. Esto se puede conseguir poniendo la siguiente línea en [.filename]#/boot/loader.conf#: [.programlisting] .... geom_vinum_load=""YES"" .... === Haciendo Accesible un Volumen Raíz basado en [.filename]#vinum# en el Código de Arranque El código de arranque de FreeBSD ocupa sólo 7.5 KB y no entiende las estructuras internas de [.filename]#vinum#. Esto significa que no puede parsear los datos de configuración de [.filename]#vinum# o resolver los elementos de un volumen de arranque. Por lo tanto, se necesitan algunas soluciones alternativas para proporcionar al código de arranque con el espejismo de una partición estándar `a` que contiene el sistema de ficheros raíz. Para que esto sea posible, el volumen raíz debe cumplir los siguientes requisitos: * El volumen raíz no debe ser un segmento o RAID-5. * El volumen raíz no debe contener más de un subdisco concatenado por plex. Ten en cuenta que es deseable y posible utilizar múltiples plexes, cada uno conteniendo una réplica del sistema de ficheros raíz. El proceso de arranque sólo utilizará una réplica para encontrar el sistema de arranca y todos los ficheros de arranque, hasta que el kernel monta el sistema de ficheros raíz. Cada subdisco en estos plexes necesita su propio espejismo de partición `a`, para que el dispositivo respectivo sea arrancable. No es estrictamente necesario que cada una de estas particiones `a` simuladas estén localizadas en el mismo desplazamiento en el dispositivo, comparado con otros dispositivos que contienen plexes del volumen raíz. Sin embargo, probablemente sea buena idea crear volúmenes [.filename]#vinum# de ese modo de forma que los dispositivos en espejo sean simétricos, para evitar confusión. Para establecer estas particiones `a` para cada dispositivo que contiene una parte del volumen raíz, se necesite lo siguiente: [.procedure] . La localización, desplazamiento desde el principio del dispositivo, y el tamaño del subdisco del dispositivo que forma parte del volumen raíz necesita ser examinado, usando el siguiente comando: + [source,bash] .... # gvinum l -rv root .... + Los desplazamientos y tamaños en [.filename]#vinum# se miden en bytes. Estos deben ser divididos entre 512 para obtener los números de bloque que van a ser usados por `bsdlabel`. . Ejecuta este comando para cada dispositivo que participa en el volumen raíz: + [source,bash] .... # bsdlabel -e devname .... + _devname_ debe ser o el nombre del disco, como [.filename]#da0# para discos sin una tabla de rebanadas, or el nombre de la rebanada, como [.filename]#ad0s1#. + Si ya hay en el dispositivo una partición `a` de un sistema raíz pre-[.filename]#vinum#, se debería renombrar a algo diferente de forma que se mantenga accesible (por si acaso), pero ya no será utilizado como arranque por defecto del sistema. Un sistema de ficheros raíz que está actualmente montado no puede ser renombrado, así que esto se debe ejecutar arrancando desde un medio ""Fixit"", o en un proceso de dos pasos donde, en una configuración en espejo, el disco que no está siendo arrancando es manipulado primero. + El desplazamiento de la partición [.filename]#vinum# en este dispositivo (si lo hay) se debe añadir al desplazamiento del subdisco del volumen raíz respectivo en este dispositivo.El valor resultante será el valor del `offset` para la nueva partición `a`. El valor de `size` para esta partición se tomará de forma literal del cálculo anterior. El `fstype` debería ser `4.2BSD`. Los valores `fsize`, `bsize`, y `cpg` deberían ser escogidos para que coincidan con el sistema de ficheros real, aunque no son realmente importantes en este contexto. + De ese modo, se establecerá una nueva partición `a` que solapa la partición [.filename]#vinum# en este dispositivo.`bsdlabel` solo permitirá este solapamiento si la partición [.filename]#vinum# ha sido adecuadamente marcada utilizando el fstype `vinum`. . Ahora existe una falsa partición `a` en cada dispositivo que tiene una réplica del volumen raíz. Es altamente recomendable verificar el resultado usando un comando como: + [source,bash] .... # fsck -n /dev/devnamea .... Debería recordarse que todos los ficheros que contienen información de control deben ser relativos al sistema de ficheros raíz en el volumen [.filename]#vinum# que, cuando se establece un nuevo volumen raíz [.filename]#vinum#, podría no coincidir con el sistema de ficheros raíz que está actualmente activo. Así que en concreto, hay que tener cuidado con [.filename]#/etc/fstab# y [.filename]#/boot/loader.conf#. En el siguiente reinicio, el código de arranque debería averiguar la información de control apropiada en el nuevo sistema de ficheros raíz [.filename]#vinum#, y actuar en consecuencia. Al final del proceso de inicialización del kernel, después de que todos los dispositivos han sido anunciados, el aviso destacado que muestra el éxito de esta configuración es un mensaje como este: [source,bash] .... Mounting root from ufs:/dev/gvinum/root .... === Ejemplo de una Configuración Raíz basada en [.filename]#vinum# Después de que el volumen raíz [.filename]#vinum# ha sido configurado, la salida de `gvinum l -rv root` podría ser como: [source,bash] .... ... Subdisk root.p0.s0: Size: 125829120 bytes (120 MB) State: up Plex root.p0 at offset 0 (0 B) Drive disk0 (/dev/da0h) at offset 135680 (132 kB) Subdisk root.p1.s0: Size: 125829120 bytes (120 MB) State: up Plex root.p1 at offset 0 (0 B) Drive disk1 (/dev/da1h) at offset 135680 (132 kB) .... Los valores en los que fijarse son `135680` para el offset, en relación a la partición [.filename]#/dev/da0h#. Esto se traduce en 256 bloques de disco de 512 bytes en términos de `bsdlabel`. De igual modo, el tamaño de este volumen raíz es 245760 bloques de 512 bytes. [.filename]#/dev/da1h#, al contener la segunda réplica de este volumen raíz, tiene una configuración asimétrica. El bsdlabel para estos dispositivos podría parecerse a: [source,bash] .... ... 8 partitions: # size offset fstype [fsize bsize bps/cpg] a: 245760 281 4.2BSD 2048 16384 0 # (Cyl. 0*- 15*) c: 71771688 0 unused 0 0 # (Cyl. 0 - 4467*) h: 71771672 16 vinum # (Cyl. 0*- 4467*) .... Se puede observar que el parámetro `size` para la partición falsa `a` coincide con el valor esbozado arriba, mientras que el parámetro `offset` es la suma del ofset dentro de la partición [.filename]#vinum#`h`, y el offset de esta partición dentro del dispositivo o rebanada. Esta es una configuración típica que es necesaria para evitar el problema descrito en <>. La partición `a` entera está completamente dentro de la partición `h` que contiene todos los datos [.filename]#vinum# para este dispositivo. En el ejemplo de arriba, el dispositivo entero está dedicado a [.filename]#vinum# y no hay una partición raíz pre-[.filename]#vinum# restante. === Solución de problemas La siguiente lista contiene unos pocos problemas conocidos y sus soluciones. ==== El Sistema de Arranque Carga, pero el Sistema No Arranca Si por algún motivo el sistema con continúa con el arranque, el proceso de arranque se puede interrumpir presionandokbd:[espacio] durante el aviso de 10 segundos. La variable del cargador `vinum.autostart` puede examinarse tecleando `show` y manipularse usando `set` o `unset`. Si el módulo del kernel de [.filename]#vinum# no estaba en la lista de módulos que son cargados automáticamente, teclea `load geom_vinum`. Cuando está listo, el proceso de arranque puede continuar tecleando `boot -as -as` solicita al kernel que pregunte por el sistema de ficheros raíz a montar (`-a`) y hacer que el proceso de arranque pare en modo de usuario único (`-s`), donde el sistema de ficheros raíz está montado como solo lectura. De ese modo, incluso si sólo ha sido montado un plex de un volumen multi-plex, no hay riesgo de inconsistencia de datos entre plexes. En el prompt en el que se pregunta por el sistema de ficheros raíz a montar, se puede introducir cualquier dispositivo que contiene un sistema de ficheros raíz válido. Si [.filename]#/etc/fstab# está configurado correctamente, el valor por defecto debería ser algo como `ufs:/dev/gvinum/root`. Una opción alternativa típica sería algo como `ufs:da0d` que podría contener una hipotética partición de un sistema de ficheros raíz pre-[.filename]#vinum#. Ha que tener cuidado si se introduce uno de los alias de las particiones `a`, que en realidad referencia los subdiscos del dispositivo raíz [.filename]#vinum#, porque en una configuración en espejo, esto sólo montaría un trozo del dispositivo raíz en espejo. Si este sistema de ficheros se va a montar como lectura-escritura posteriormente, es necesario eliminar el otro plex(es) del volumen raíz [.filename]#vinum# puesto que de otro modo los plexes tendrían datos inconsistentes. ==== Sólo Carga la Configuración de Arranque Primaria Si [.filename]#/boot/loader# falla al cargar, pero la configuración de arranque primaria todavía carga (visible mediante un sólo guión en la columna de la izquierda de la pantalla justo después de que comience el proceso de arranque), se puede intentar interrumpir el arranque primario presionando kbd:[space]. Esto hará que el proceso de arranque se pare en link:{handbook}#boot-boot1[stage two]. Aquí se puede intentar arrancar desde una partición alternativa, como la partición que contiene sl sistema de ficheros raíz anterior que ha sido movido desde `a`. [[vinum-root-panic]] ==== Nada Arranca, el Proceso de Arranque entra en Pánico Esta situación ocurrirá si el código de arranque ha sido destruido por la instalación de [.filename]#vinum#. Desafortunadamente, [.filename]#vinum# deja por accidente sólo 4KB libres al comienzo de su partición antes de empezar a escribir la información de cabecera de [.filename]#vinum#. Sin embargo, los códigos de arranque de las fases uno y dos más bsdlabel requieren 8 KB. Así que si una partición [.filename]#vinum# empezó en un offset 0 dentro de una rebanada o disco que se pretendía que fuera arrancable, la configuración de [.filename]#vinum# se llevará por delante el código de arranque. De forma similar, si se ha recuperado de la situación anterior, arrancando desde un medio ""Fixit"", y el código de arranque ha sido reinstalado utilizando `bsdlabel -B` como se describe en link:{handbook}#boot-boot1[], el código de arranque destruirá la cabecera [.filename]#vinum#, y [.filename]#vinum# ya no podrá encontrar su(s) disco(s). Aunque ningún volumen [.filename]#vinum# o datos de configuración de [.filename]#vinum# serán destruidos, y sería posible recuperar todos los datos introduciendo de nuevo exactamente los mismos datos de configuración de [.filename]#vinum# la situación es difícil de arreglar. Es necesario mover la partición [.filename]#vinum# entera al menos 4 KB, para que la cabecera [.filename]#vinum# y el código de arranque del sistema ya no colisionen. ",12328,False,2181.140933239522,median "// Generated by the gRPC C++ plugin. // If you make any local change, they will be lost. // source: action/action.proto #include ""action/action.pb.h"" #include ""action/action.grpc.pb.h"" #include #include #include #include #include #include #include #include #include #include #include #include #include namespace mavsdk { namespace rpc { namespace action { static const char* ActionService_method_names[] = { ""/mavsdk.rpc.action.ActionService/Arm"", ""/mavsdk.rpc.action.ActionService/Disarm"", ""/mavsdk.rpc.action.ActionService/Takeoff"", ""/mavsdk.rpc.action.ActionService/Land"", ""/mavsdk.rpc.action.ActionService/Reboot"", ""/mavsdk.rpc.action.ActionService/Shutdown"", ""/mavsdk.rpc.action.ActionService/Kill"", ""/mavsdk.rpc.action.ActionService/ReturnToLaunch"", ""/mavsdk.rpc.action.ActionService/GotoLocation"", ""/mavsdk.rpc.action.ActionService/TransitionToFixedwing"", ""/mavsdk.rpc.action.ActionService/TransitionToMulticopter"", ""/mavsdk.rpc.action.ActionService/GetTakeoffAltitude"", ""/mavsdk.rpc.action.ActionService/SetTakeoffAltitude"", ""/mavsdk.rpc.action.ActionService/GetMaximumSpeed"", ""/mavsdk.rpc.action.ActionService/SetMaximumSpeed"", ""/mavsdk.rpc.action.ActionService/GetReturnToLaunchAltitude"", ""/mavsdk.rpc.action.ActionService/SetReturnToLaunchAltitude"", }; std::unique_ptr< ActionService::Stub> ActionService::NewStub(const std::shared_ptr< ::grpc::ChannelInterface>& channel, const ::grpc::StubOptions& options) { (void)options; std::unique_ptr< ActionService::Stub> stub(new ActionService::Stub(channel)); return stub; } ActionService::Stub::Stub(const std::shared_ptr< ::grpc::ChannelInterface>& channel) : channel_(channel), rpcmethod_Arm_(ActionService_method_names[0], ::grpc::internal::RpcMethod::NORMAL_RPC, channel) , rpcmethod_Disarm_(ActionService_method_names[1], ::grpc::internal::RpcMethod::NORMAL_RPC, channel) , rpcmethod_Takeoff_(ActionService_method_names[2], ::grpc::internal::RpcMethod::NORMAL_RPC, channel) , rpcmethod_Land_(ActionService_method_names[3], ::grpc::internal::RpcMethod::NORMAL_RPC, channel) , rpcmethod_Reboot_(ActionService_method_names[4], ::grpc::internal::RpcMethod::NORMAL_RPC, channel) , rpcmethod_Shutdown_(ActionService_method_names[5], ::grpc::internal::RpcMethod::NORMAL_RPC, channel) , rpcmethod_Kill_(ActionService_method_names[6], ::grpc::internal::RpcMethod::NORMAL_RPC, channel) , rpcmethod_ReturnToLaunch_(ActionService_method_names[7], ::grpc::internal::RpcMethod::NORMAL_RPC, channel) , rpcmethod_GotoLocation_(ActionService_method_names[8], ::grpc::internal::RpcMethod::NORMAL_RPC, channel) , rpcmethod_TransitionToFixedwing_(ActionService_method_names[9], ::grpc::internal::RpcMethod::NORMAL_RPC, channel) , rpcmethod_TransitionToMulticopter_(ActionService_method_names[10], ::grpc::internal::RpcMethod::NORMAL_RPC, channel) , rpcmethod_GetTakeoffAltitude_(ActionService_method_names[11], ::grpc::internal::RpcMethod::NORMAL_RPC, channel) , rpcmethod_SetTakeoffAltitude_(ActionService_method_names[12], ::grpc::internal::RpcMethod::NORMAL_RPC, channel) , rpcmethod_GetMaximumSpeed_(ActionService_method_names[13], ::grpc::internal::RpcMethod::NORMAL_RPC, channel) , rpcmethod_SetMaximumSpeed_(ActionService_method_names[14], ::grpc::internal::RpcMethod::NORMAL_RPC, channel) , rpcmethod_GetReturnToLaunchAltitude_(ActionService_method_names[15], ::grpc::internal::RpcMethod::NORMAL_RPC, channel) , rpcmethod_SetReturnToLaunchAltitude_(ActionService_method_names[16], ::grpc::internal::RpcMethod::NORMAL_RPC, channel) {} ::grpc::Status ActionService::Stub::Arm(::grpc::ClientContext* context, const ::mavsdk::rpc::action::ArmRequest& request, ::mavsdk::rpc::action::ArmResponse* response) { return ::grpc::internal::BlockingUnaryCall(channel_.get(), rpcmethod_Arm_, context, request, response); } void ActionService::Stub::experimental_async::Arm(::grpc::ClientContext* context, const ::mavsdk::rpc::action::ArmRequest* request, ::mavsdk::rpc::action::ArmResponse* response, std::function f) { ::grpc_impl::internal::CallbackUnaryCall(stub_->channel_.get(), stub_->rpcmethod_Arm_, context, request, response, std::move(f)); } void ActionService::Stub::experimental_async::Arm(::grpc::ClientContext* context, const ::grpc::ByteBuffer* request, ::mavsdk::rpc::action::ArmResponse* response, std::function f) { ::grpc_impl::internal::CallbackUnaryCall(stub_->channel_.get(), stub_->rpcmethod_Arm_, context, request, response, std::move(f)); } void ActionService::Stub::experimental_async::Arm(::grpc::ClientContext* context, const ::mavsdk::rpc::action::ArmRequest* request, ::mavsdk::rpc::action::ArmResponse* response, ::grpc::experimental::ClientUnaryReactor* reactor) { ::grpc_impl::internal::ClientCallbackUnaryFactory::Create(stub_->channel_.get(), stub_->rpcmethod_Arm_, context, request, response, reactor); } void ActionService::Stub::experimental_async::Arm(::grpc::ClientContext* context, const ::grpc::ByteBuffer* request, ::mavsdk::rpc::action::ArmResponse* response, ::grpc::experimental::ClientUnaryReactor* reactor) { ::grpc_impl::internal::ClientCallbackUnaryFactory::Create(stub_->channel_.get(), stub_->rpcmethod_Arm_, context, request, response, reactor); } ::grpc::ClientAsyncResponseReader< ::mavsdk::rpc::action::ArmResponse>* ActionService::Stub::AsyncArmRaw(::grpc::ClientContext* context, const ::mavsdk::rpc::action::ArmRequest& request, ::grpc::CompletionQueue* cq) { return ::grpc_impl::internal::ClientAsyncResponseReaderFactory< ::mavsdk::rpc::action::ArmResponse>::Create(channel_.get(), cq, rpcmethod_Arm_, context, request, true); } ::grpc::ClientAsyncResponseReader< ::mavsdk::rpc::action::ArmResponse>* ActionService::Stub::PrepareAsyncArmRaw(::grpc::ClientContext* context, const ::mavsdk::rpc::action::ArmRequest& request, ::grpc::CompletionQueue* cq) { return ::grpc_impl::internal::ClientAsyncResponseReaderFactory< ::mavsdk::rpc::action::ArmResponse>::Create(channel_.get(), cq, rpcmethod_Arm_, context, request, false); } ::grpc::Status ActionService::Stub::Disarm(::grpc::ClientContext* context, const ::mavsdk::rpc::action::DisarmRequest& request, ::mavsdk::rpc::action::DisarmResponse* response) { return ::grpc::internal::BlockingUnaryCall(channel_.get(), rpcmethod_Disarm_, context, request, response); } void ActionService::Stub::experimental_async::Disarm(::grpc::ClientContext* context, const ::mavsdk::rpc::action::DisarmRequest* request, ::mavsdk::rpc::action::DisarmResponse* response, std::function f) { ::grpc_impl::internal::CallbackUnaryCall(stub_->channel_.get(), stub_->rpcmethod_Disarm_, context, request, response, std::move(f)); } void ActionService::Stub::experimental_async::Disarm(::grpc::ClientContext* context, const ::grpc::ByteBuffer* request, ::mavsdk::rpc::action::DisarmResponse* response, std::function f) { ::grpc_impl::internal::CallbackUnaryCall(stub_->channel_.get(), stub_->rpcmethod_Disarm_, context, request, response, std::move(f)); } void ActionService::Stub::experimental_async::Disarm(::grpc::ClientContext* context, const ::mavsdk::rpc::action::DisarmRequest* request, ::mavsdk::rpc::action::DisarmResponse* response, ::grpc::experimental::ClientUnaryReactor* reactor) { ::grpc_impl::internal::ClientCallbackUnaryFactory::Create(stub_->channel_.get(), stub_->rpcmethod_Disarm_, context, request, response, reactor); } void ActionService::Stub::experimental_async::Disarm(::grpc::ClientContext* context, const ::grpc::ByteBuffer* request, ::mavsdk::rpc::action::DisarmResponse* response, ::grpc::experimental::ClientUnaryReactor* reactor) { ::grpc_impl::internal::ClientCallbackUnaryFactory::Create(stub_->channel_.get(), stub_->rpcmethod_Disarm_, context, request, response, reactor); } ::grpc::ClientAsyncResponseReader< ::mavsdk::rpc::action::DisarmResponse>* ActionService::Stub::AsyncDisarmRaw(::grpc::ClientContext* context, const ::mavsdk::rpc::action::DisarmRequest& request, ::grpc::CompletionQueue* cq) { return ::grpc_impl::internal::ClientAsyncResponseReaderFactory< ::mavsdk::rpc::action::DisarmResponse>::Create(channel_.get(), cq, rpcmethod_Disarm_, context, request, true); } ::grpc::ClientAsyncResponseReader< ::mavsdk::rpc::action::DisarmResponse>* ActionService::Stub::PrepareAsyncDisarmRaw(::grpc::ClientContext* context, const ::mavsdk::rpc::action::DisarmRequest& request, ::grpc::CompletionQueue* cq) { return ::grpc_impl::internal::ClientAsyncResponseReaderFactory< ::mavsdk::rpc::action::DisarmResponse>::Create(channel_.get(), cq, rpcmethod_Disarm_, context, request, false); } ::grpc::Status ActionService::Stub::Takeoff(::grpc::ClientContext* context, const ::mavsdk::rpc::action::TakeoffRequest& request, ::mavsdk::rpc::action::TakeoffResponse* response) { return ::grpc::internal::BlockingUnaryCall(channel_.get(), rpcmethod_Takeoff_, context, request, response); } void ActionService::Stub::experimental_async::Takeoff(::grpc::ClientContext* context, const ::mavsdk::rpc::action::TakeoffRequest* request, ::mavsdk::rpc::action::TakeoffResponse* response, std::function f) { ::grpc_impl::internal::CallbackUnaryCall(stub_->channel_.get(), stub_->rpcmethod_Takeoff_, context, request, response, std::move(f)); } void ActionService::Stub::experimental_async::Takeoff(::grpc::ClientContext* context, const ::grpc::ByteBuffer* request, ::mavsdk::rpc::action::TakeoffResponse* response, std::function f) { ::grpc_impl::internal::CallbackUnaryCall(stub_->channel_.get(), stub_->rpcmethod_Takeoff_, context, request, response, std::move(f)); } void ActionService::Stub::experimental_async::Takeoff(::grpc::ClientContext* context, const ::mavsdk::rpc::action::TakeoffRequest* request, ::mavsdk::rpc::action::TakeoffResponse* response, ::grpc::experimental::ClientUnaryReactor* reactor) { ::grpc_impl::internal::ClientCallbackUnaryFactory::Create(stub_->channel_.get(), stub_->rpcmethod_Takeoff_, context, request, response, reactor); } void ActionService::Stub::experimental_async::Takeoff(::grpc::ClientContext* context, const ::grpc::ByteBuffer* request, ::mavsdk::rpc::action::TakeoffResponse* response, ::grpc::experimental::ClientUnaryReactor* reactor) { ::grpc_impl::internal::ClientCallbackUnaryFactory::Create(stub_->channel_.get(), stub_->rpcmethod_Takeoff_, context, request, response, reactor); } ::grpc::ClientAsyncResponseReader< ::mavsdk::rpc::action::TakeoffResponse>* ActionService::Stub::AsyncTakeoffRaw(::grpc::ClientContext* context, const ::mavsdk::rpc::action::TakeoffRequest& request, ::grpc::CompletionQueue* cq) { return ::grpc_impl::internal::ClientAsyncResponseReaderFactory< ::mavsdk::rpc::action::TakeoffResponse>::Create(channel_.get(), cq, rpcmethod_Takeoff_, context, request, true); } ::grpc::ClientAsyncResponseReader< ::mavsdk::rpc::action::TakeoffResponse>* ActionService::Stub::PrepareAsyncTakeoffRaw(::grpc::ClientContext* context, const ::mavsdk::rpc::action::TakeoffRequest& request, ::grpc::CompletionQueue* cq) { return ::grpc_impl::internal::ClientAsyncResponseReaderFactory< ::mavsdk::rpc::action::TakeoffResponse>::Create(channel_.get(), cq, rpcmethod_Takeoff_, context, request, false); } ::grpc::Status ActionService::Stub::Land(::grpc::ClientContext* context, const ::mavsdk::rpc::action::LandRequest& request, ::mavsdk::rpc::action::LandResponse* response) { return ::grpc::internal::BlockingUnaryCall(channel_.get(), rpcmethod_Land_, context, request, response); } void ActionService::Stub::experimental_async::Land(::grpc::ClientContext* context, const ::mavsdk::rpc::action::LandRequest* request, ::mavsdk::rpc::action::LandResponse* response, std::function f) { ::grpc_impl::internal::CallbackUnaryCall(stub_->channel_.get(), stub_->rpcmethod_Land_, context, request, response, std::move(f)); } void ActionService::Stub::experimental_async::Land(::grpc::ClientContext* context, const ::grpc::ByteBuffer* request, ::mavsdk::rpc::action::LandResponse* response, std::function f) { ::grpc_impl::internal::CallbackUnaryCall(stub_->channel_.get(), stub_->rpcmethod_Land_, context, request, response, std::move(f)); } void ActionService::Stub::experimental_async::Land(::grpc::ClientContext* context, const ::mavsdk::rpc::action::LandRequest* request, ::mavsdk::rpc::action::LandResponse* response, ::grpc::experimental::ClientUnaryReactor* reactor) { ::grpc_impl::internal::ClientCallbackUnaryFactory::Create(stub_->channel_.get(), stub_->rpcmethod_Land_, context, request, response, reactor); } void ActionService::Stub::experimental_async::Land(::grpc::ClientContext* context, const ::grpc::ByteBuffer* request, ::mavsdk::rpc::action::LandResponse* response, ::grpc::experimental::ClientUnaryReactor* reactor) { ::grpc_impl::internal::ClientCallbackUnaryFactory::Create(stub_->channel_.get(), stub_->rpcmethod_Land_, context, request, response, reactor); } ::grpc::ClientAsyncResponseReader< ::mavsdk::rpc::action::LandResponse>* ActionService::Stub::AsyncLandRaw(::grpc::ClientContext* context, const ::mavsdk::rpc::action::LandRequest& request, ::grpc::CompletionQueue* cq) { return ::grpc_impl::internal::ClientAsyncResponseReaderFactory< ::mavsdk::rpc::action::LandResponse>::Create(channel_.get(), cq, rpcmethod_Land_, context, request, true); } ::grpc::ClientAsyncResponseReader< ::mavsdk::rpc::action::LandResponse>* ActionService::Stub::PrepareAsyncLandRaw(::grpc::ClientContext* context, const ::mavsdk::rpc::action::LandRequest& request, ::grpc::CompletionQueue* cq) { return ::grpc_impl::internal::ClientAsyncResponseReaderFactory< ::mavsdk::rpc::action::LandResponse>::Create(channel_.get(), cq, rpcmethod_Land_, context, request, false); } ::grpc::Status ActionService::Stub::Reboot(::grpc::ClientContext* context, const ::mavsdk::rpc::action::RebootRequest& request, ::mavsdk::rpc::action::RebootResponse* response) { return ::grpc::internal::BlockingUnaryCall(channel_.get(), rpcmethod_Reboot_, context, request, response); } void ActionService::Stub::experimental_async::Reboot(::grpc::ClientContext* context, const ::mavsdk::rpc::action::RebootRequest* request, ::mavsdk::rpc::action::RebootResponse* response, std::function f) { ::grpc_impl::internal::CallbackUnaryCall(stub_->channel_.get(), stub_->rpcmethod_Reboot_, context, request, response, std::move(f)); } void ActionService::Stub::experimental_async::Reboot(::grpc::ClientContext* context, const ::grpc::ByteBuffer* request, ::mavsdk::rpc::action::RebootResponse* response, std::function f) { ::grpc_impl::internal::CallbackUnaryCall(stub_->channel_.get(), stub_->rpcmethod_Reboot_, context, request, response, std::move(f)); } void ActionService::Stub::experimental_async::Reboot(::grpc::ClientContext* context, const ::mavsdk::rpc::action::RebootRequest* request, ::mavsdk::rpc::action::RebootResponse* response, ::grpc::experimental::ClientUnaryReactor* reactor) { ::grpc_impl::internal::ClientCallbackUnaryFactory::Create(stub_->channel_.get(), stub_->rpcmethod_Reboot_, context, request, response, reactor); } void ActionService::Stub::experimental_async::Reboot(::grpc::ClientContext* context, const ::grpc::ByteBuffer* request, ::mavsdk::rpc::action::RebootResponse* response, ::grpc::experimental::ClientUnaryReactor* reactor) { ::grpc_impl::internal::ClientCallbackUnaryFactory::Create(stub_->channel_.get(), stub_->rpcmethod_Reboot_, context, request, response, reactor); } ::grpc::ClientAsyncResponseReader< ::mavsdk::rpc::action::RebootResponse>* ActionService::Stub::AsyncRebootRaw(::grpc::ClientContext* context, const ::mavsdk::rpc::action::RebootRequest& request, ::grpc::CompletionQueue* cq) { return ::grpc_impl::internal::ClientAsyncResponseReaderFactory< ::mavsdk::rpc::action::RebootResponse>::Create(channel_.get(), cq, rpcmethod_Reboot_, context, request, true); } ::grpc::ClientAsyncResponseReader< ::mavsdk::rpc::action::RebootResponse>* ActionService::Stub::PrepareAsyncRebootRaw(::grpc::ClientContext* context, const ::mavsdk::rpc::action::RebootRequest& request, ::grpc::CompletionQueue* cq) { return ::grpc_impl::internal::ClientAsyncResponseReaderFactory< ::mavsdk::rpc::action::RebootResponse>::Create(channel_.get(), cq, rpcmethod_Reboot_, context, request, false); } ::grpc::Status ActionService::Stub::Shutdown(::grpc::ClientContext* context, const ::mavsdk::rpc::action::ShutdownRequest& request, ::mavsdk::rpc::action::ShutdownResponse* response) { return ::grpc::internal::BlockingUnaryCall(channel_.get(), rpcmethod_Shutdown_, context, request, response); } void ActionService::Stub::experimental_async::Shutdown(::grpc::ClientContext* context, const ::mavsdk::rpc::action::ShutdownRequest* request, ::mavsdk::rpc::action::ShutdownResponse* response, std::function f) { ::grpc_impl::internal::CallbackUnaryCall(stub_->channel_.get(), stub_->rpcmethod_Shutdown_, context, request, response, std::move(f)); } void ActionService::Stub::experimental_async::Shutdown(::grpc::ClientContext* context, const ::grpc::ByteBuffer* request, ::mavsdk::rpc::action::ShutdownResponse* response, std::function f) { ::grpc_impl::internal::CallbackUnaryCall(stub_->channel_.get(), stub_->rpcmethod_Shutdown_, context, request, response, std::move(f)); } void ActionService::Stub::experimental_async::Shutdown(::grpc::ClientContext* context, const ::mavsdk::rpc::action::ShutdownRequest* request, ::mavsdk::rpc::action::ShutdownResponse* response, ::grpc::experimental::ClientUnaryReactor* reactor) { ::grpc_impl::internal::ClientCallbackUnaryFactory::Create(stub_->channel_.get(), stub_->rpcmethod_Shutdown_, context, request, response, reactor); } void ActionService::Stub::experimental_async::Shutdown(::grpc::ClientContext* context, const ::grpc::ByteBuffer* request, ::mavsdk::rpc::action::ShutdownResponse* response, ::grpc::experimental::ClientUnaryReactor* reactor) { ::grpc_impl::internal::ClientCallbackUnaryFactory::Create(stub_->channel_.get(), stub_->rpcmethod_Shutdown_, context, request, response, reactor); } ::grpc::ClientAsyncResponseReader< ::mavsdk::rpc::action::ShutdownResponse>* ActionService::Stub::AsyncShutdownRaw(::grpc::ClientContext* context, const ::mavsdk::rpc::action::ShutdownRequest& request, ::grpc::CompletionQueue* cq) { return ::grpc_impl::internal::ClientAsyncResponseReaderFactory< ::mavsdk::rpc::action::ShutdownResponse>::Create(channel_.get(), cq, rpcmethod_Shutdown_, context, request, true); } ::grpc::ClientAsyncResponseReader< ::mavsdk::rpc::action::ShutdownResponse>* ActionService::Stub::PrepareAsyncShutdownRaw(::grpc::ClientContext* context, const ::mavsdk::rpc::action::ShutdownRequest& request, ::grpc::CompletionQueue* cq) { return ::grpc_impl::internal::ClientAsyncResponseReaderFactory< ::mavsdk::rpc::action::ShutdownResponse>::Create(channel_.get(), cq, rpcmethod_Shutdown_, context, request, false); } ::grpc::Status ActionService::Stub::Kill(::grpc::ClientContext* context, const ::mavsdk::rpc::action::KillRequest& request, ::mavsdk::rpc::action::KillResponse* response) { return ::grpc::internal::BlockingUnaryCall(channel_.get(), rpcmethod_Kill_, context, request, response); } void ActionService::Stub::experimental_async::Kill(::grpc::ClientContext* context, const ::mavsdk::rpc::action::KillRequest* request, ::mavsdk::rpc::action::KillResponse* response, std::function f) { ::grpc_impl::internal::CallbackUnaryCall(stub_->channel_.get(), stub_->rpcmethod_Kill_, context, request, response, std::move(f)); } void ActionService::Stub::experimental_async::Kill(::grpc::ClientContext* context, const ::grpc::ByteBuffer* request, ::mavsdk::rpc::action::KillResponse* response, std::function f) { ::grpc_impl::internal::CallbackUnaryCall(stub_->channel_.get(), stub_->rpcmethod_Kill_, context, request, response, std::move(f)); } void ActionService::Stub::experimental_async::Kill(::grpc::ClientContext* context, const ::mavsdk::rpc::action::KillRequest* request, ::mavsdk::rpc::action::KillResponse* response, ::grpc::experimental::ClientUnaryReactor* reactor) { ::grpc_impl::internal::ClientCallbackUnaryFactory::Create(stub_->channel_.get(), stub_->rpcmethod_Kill_, context, request, response, reactor); } void ActionService::Stub::experimental_async::Kill(::grpc::ClientContext* context, const ::grpc::ByteBuffer* request, ::mavsdk::rpc::action::KillResponse* response, ::grpc::experimental::ClientUnaryReactor* reactor) { ::grpc_impl::internal::ClientCallbackUnaryFactory::Create(stub_->channel_.get(), stub_->rpcmethod_Kill_, context, request, response, reactor); } ::grpc::ClientAsyncResponseReader< ::mavsdk::rpc::action::KillResponse>* ActionService::Stub::AsyncKillRaw(::grpc::ClientContext* context, const ::mavsdk::rpc::action::KillRequest& request, ::grpc::CompletionQueue* cq) { return ::grpc_impl::internal::ClientAsyncResponseReaderFactory< ::mavsdk::rpc::action::KillResponse>::Create(channel_.get(), cq, rpcmethod_Kill_, context, request, true); } ::grpc::ClientAsyncResponseReader< ::mavsdk::rpc::action::KillResponse>* ActionService::Stub::PrepareAsyncKillRaw(::grpc::ClientContext* context, const ::mavsdk::rpc::action::KillRequest& request, ::grpc::CompletionQueue* cq) { return ::grpc_impl::internal::ClientAsyncResponseReaderFactory< ::mavsdk::rpc::action::KillResponse>::Create(channel_.get(), cq, rpcmethod_Kill_, context, request, false); } ::grpc::Status ActionService::Stub::ReturnToLaunch(::grpc::ClientContext* context, const ::mavsdk::rpc::action::ReturnToLaunchRequest& request, ::mavsdk::rpc::action::ReturnToLaunchResponse* response) { return ::grpc::internal::BlockingUnaryCall(channel_.get(), rpcmethod_ReturnToLaunch_, context, request, response); } void ActionService::Stub::experimental_async::ReturnToLaunch(::grpc::ClientContext* context, const ::mavsdk::rpc::action::ReturnToLaunchRequest* request, ::mavsdk::rpc::action::ReturnToLaunchResponse* response, std::function f) { ::grpc_impl::internal::CallbackUnaryCall(stub_->channel_.get(), stub_->rpcmethod_ReturnToLaunch_, context, request, response, std::move(f)); } void ActionService::Stub::experimental_async::ReturnToLaunch(::grpc::ClientContext* context, const ::grpc::ByteBuffer* request, ::mavsdk::rpc::action::ReturnToLaunchResponse* response, std::function f) { ::grpc_impl::internal::CallbackUnaryCall(stub_->channel_.get(), stub_->rpcmethod_ReturnToLaunch_, context, request, response, std::move(f)); } void ActionService::Stub::experimental_async::ReturnToLaunch(::grpc::ClientContext* context, const ::mavsdk::rpc::action::ReturnToLaunchRequest* request, ::mavsdk::rpc::action::ReturnToLaunchResponse* response, ::grpc::experimental::ClientUnaryReactor* reactor) { ::grpc_impl::internal::ClientCallbackUnaryFactory::Create(stub_->channel_.get(), stub_->rpcmethod_ReturnToLaunch_, context, request, response, reactor); } void ActionService::Stub::experimental_async::ReturnToLaunch(::grpc::ClientContext* context, const ::grpc::ByteBuffer* request, ::mavsdk::rpc::action::ReturnToLaunchResponse* response, ::grpc::experimental::ClientUnaryReactor* reactor) { ::grpc_impl::internal::ClientCallbackUnaryFactory::Create(stub_->channel_.get(), stub_->rpcmethod_ReturnToLaunch_, context, request, response, reactor); } ::grpc::ClientAsyncResponseReader< ::mavsdk::rpc::action::ReturnToLaunchResponse>* ActionService::Stub::AsyncReturnToLaunchRaw(::grpc::ClientContext* context, const ::mavsdk::rpc::action::ReturnToLaunchRequest& request, ::grpc::CompletionQueue* cq) { return ::grpc_impl::internal::ClientAsyncResponseReaderFactory< ::mavsdk::rpc::action::ReturnToLaunchResponse>::Create(channel_.get(), cq, rpcmethod_ReturnToLaunch_, context, request, true); } ::grpc::ClientAsyncResponseReader< ::mavsdk::rpc::action::ReturnToLaunchResponse>* ActionService::Stub::PrepareAsyncReturnToLaunchRaw(::grpc::ClientContext* context, const ::mavsdk::rpc::action::ReturnToLaunchRequest& request, ::grpc::CompletionQueue* cq) { return ::grpc_impl::internal::ClientAsyncResponseReaderFactory< ::mavsdk::rpc::action::ReturnToLaunchResponse>::Create(channel_.get(), cq, rpcmethod_ReturnToLaunch_, context, request, false); } ::grpc::Status ActionService::Stub::GotoLocation(::grpc::ClientContext* context, const ::mavsdk::rpc::action::GotoLocationRequest& request, ::mavsdk::rpc::action::GotoLocationResponse* response) { return ::grpc::internal::BlockingUnaryCall(channel_.get(), rpcmethod_GotoLocation_, context, request, response); } void ActionService::Stub::experimental_async::GotoLocation(::grpc::ClientContext* context, const ::mavsdk::rpc::action::GotoLocationRequest* request, ::mavsdk::rpc::action::GotoLocationResponse* response, std::function f) { ::grpc_impl::internal::CallbackUnaryCall(stub_->channel_.get(), stub_->rpcmethod_GotoLocation_, context, request, response, std::move(f)); } void ActionService::Stub::experimental_async::GotoLocation(::grpc::ClientContext* context, const ::grpc::ByteBuffer* request, ::mavsdk::rpc::action::GotoLocationResponse* response, std::function f) { ::grpc_impl::internal::CallbackUnaryCall(stub_->channel_.get(), stub_->rpcmethod_GotoLocation_, context, request, response, std::move(f)); } void ActionService::Stub::experimental_async::GotoLocation(::grpc::ClientContext* context, const ::mavsdk::rpc::action::GotoLocationRequest* request, ::mavsdk::rpc::action::GotoLocationResponse* response, ::grpc::experimental::ClientUnaryReactor* reactor) { ::grpc_impl::internal::ClientCallbackUnaryFactory::Create(stub_->channel_.get(), stub_->rpcmethod_GotoLocation_, context, request, response, reactor); } void ActionService::Stub::experimental_async::GotoLocation(::grpc::ClientContext* context, const ::grpc::ByteBuffer* request, ::mavsdk::rpc::action::GotoLocationResponse* response, ::grpc::experimental::ClientUnaryReactor* reactor) { ::grpc_impl::internal::ClientCallbackUnaryFactory::Create(stub_->channel_.get(), stub_->rpcmethod_GotoLocation_, context, request, response, reactor); } ::grpc::ClientAsyncResponseReader< ::mavsdk::rpc::action::GotoLocationResponse>* ActionService::Stub::AsyncGotoLocationRaw(::grpc::ClientContext* context, const ::mavsdk::rpc::action::GotoLocationRequest& request, ::grpc::CompletionQueue* cq) { return ::grpc_impl::internal::ClientAsyncResponseReaderFactory< ::mavsdk::rpc::action::GotoLocationResponse>::Create(channel_.get(), cq, rpcmethod_GotoLocation_, context, request, true); } ::grpc::ClientAsyncResponseReader< ::mavsdk::rpc::action::GotoLocationResponse>* ActionService::Stub::PrepareAsyncGotoLocationRaw(::grpc::ClientContext* context, const ::mavsdk::rpc::action::GotoLocationRequest& request, ::grpc::CompletionQueue* cq) { return ::grpc_impl::internal::ClientAsyncResponseReaderFactory< ::mavsdk::rpc::action::GotoLocationResponse>::Create(channel_.get(), cq, rpcmethod_GotoLocation_, context, request, false); } ::grpc::Status ActionService::Stub::TransitionToFixedwing(::grpc::ClientContext* context, const ::mavsdk::rpc::action::TransitionToFixedwingRequest& request, ::mavsdk::rpc::action::TransitionToFixedwingResponse* response) { return ::grpc::internal::BlockingUnaryCall(channel_.get(), rpcmethod_TransitionToFixedwing_, context, request, response); } void ActionService::Stub::experimental_async::TransitionToFixedwing(::grpc::ClientContext* context, const ::mavsdk::rpc::action::TransitionToFixedwingRequest* request, ::mavsdk::rpc::action::TransitionToFixedwingResponse* response, std::function f) { ::grpc_impl::internal::CallbackUnaryCall(stub_->channel_.get(), stub_->rpcmethod_TransitionToFixedwing_, context, request, response, std::move(f)); } void ActionService::Stub::experimental_async::TransitionToFixedwing(::grpc::ClientContext* context, const ::grpc::ByteBuffer* request, ::mavsdk::rpc::action::TransitionToFixedwingResponse* response, std::function f) { ::grpc_impl::internal::CallbackUnaryCall(stub_->channel_.get(), stub_->rpcmethod_TransitionToFixedwing_, context, request, response, std::move(f)); } void ActionService::Stub::experimental_async::TransitionToFixedwing(::grpc::ClientContext* context, const ::mavsdk::rpc::action::TransitionToFixedwingRequest* request, ::mavsdk::rpc::action::TransitionToFixedwingResponse* response, ::grpc::experimental::ClientUnaryReactor* reactor) { ::grpc_impl::internal::ClientCallbackUnaryFactory::Create(stub_->channel_.get(), stub_->rpcmethod_TransitionToFixedwing_, context, request, response, reactor); } void ActionService::Stub::experimental_async::TransitionToFixedwing(::grpc::ClientContext* context, const ::grpc::ByteBuffer* request, ::mavsdk::rpc::action::TransitionToFixedwingResponse* response, ::grpc::experimental::ClientUnaryReactor* reactor) { ::grpc_impl::internal::ClientCallbackUnaryFactory::Create(stub_->channel_.get(), stub_->rpcmethod_TransitionToFixedwing_, context, request, response, reactor); } ::grpc::ClientAsyncResponseReader< ::mavsdk::rpc::action::TransitionToFixedwingResponse>* ActionService::Stub::AsyncTransitionToFixedwingRaw(::grpc::ClientContext* context, const ::mavsdk::rpc::action::TransitionToFixedwingRequest& request, ::grpc::CompletionQueue* cq) { return ::grpc_impl::internal::ClientAsyncResponseReaderFactory< ::mavsdk::rpc::action::TransitionToFixedwingResponse>::Create(channel_.get(), cq, rpcmethod_TransitionToFixedwing_, context, request, true); } ::grpc::ClientAsyncResponseReader< ::mavsdk::rpc::action::TransitionToFixedwingResponse>* ActionService::Stub::PrepareAsyncTransitionToFixedwingRaw(::grpc::ClientContext* context, const ::mavsdk::rpc::action::TransitionToFixedwingRequest& request, ::grpc::CompletionQueue* cq) { return ::grpc_impl::internal::ClientAsyncResponseReaderFactory< ::mavsdk::rpc::action::TransitionToFixedwingResponse>::Create(channel_.get(), cq, rpcmethod_TransitionToFixedwing_, context, request, false); } ::grpc::Status ActionService::Stub::TransitionToMulticopter(::grpc::ClientContext* context, const ::mavsdk::rpc::action::TransitionToMulticopterRequest& request, ::mavsdk::rpc::action::TransitionToMulticopterResponse* response) { return ::grpc::internal::BlockingUnaryCall(channel_.get(), rpcmethod_TransitionToMulticopter_, context, request, response); } void ActionService::Stub::experimental_async::TransitionToMulticopter(::grpc::ClientContext* context, const ::mavsdk::rpc::action::TransitionToMulticopterRequest* request, ::mavsdk::rpc::action::TransitionToMulticopterResponse* response, std::function f) { ::grpc_impl::internal::CallbackUnaryCall(stub_->channel_.get(), stub_->rpcmethod_TransitionToMulticopter_, context, request, response, std::move(f)); } void ActionService::Stub::experimental_async::TransitionToMulticopter(::grpc::ClientContext* context, const ::grpc::ByteBuffer* request, ::mavsdk::rpc::action::TransitionToMulticopterResponse* response, std::function f) { ::grpc_impl::internal::CallbackUnaryCall(stub_->channel_.get(), stub_->rpcmethod_TransitionToMulticopter_, context, request, response, std::move(f)); } void ActionService::Stub::experimental_async::TransitionToMulticopter(::grpc::ClientContext* context, const ::mavsdk::rpc::action::TransitionToMulticopterRequest* request, ::mavsdk::rpc::action::TransitionToMulticopterResponse* response, ::grpc::experimental::ClientUnaryReactor* reactor) { ::grpc_impl::internal::ClientCallbackUnaryFactory::Create(stub_->channel_.get(), stub_->rpcmethod_TransitionToMulticopter_, context, request, response, reactor); } void ActionService::Stub::experimental_async::TransitionToMulticopter(::grpc::ClientContext* context, const ::grpc::ByteBuffer* request, ::mavsdk::rpc::action::TransitionToMulticopterResponse* response, ::grpc::experimental::ClientUnaryReactor* reactor) { ::grpc_impl::internal::ClientCallbackUnaryFactory::Create(stub_->channel_.get(), stub_->rpcmethod_TransitionToMulticopter_, context, request, response, reactor); } ::grpc::ClientAsyncResponseReader< ::mavsdk::rpc::action::TransitionToMulticopterResponse>* ActionService::Stub::AsyncTransitionToMulticopterRaw(::grpc::ClientContext* context, const ::mavsdk::rpc::action::TransitionToMulticopterRequest& request, ::grpc::CompletionQueue* cq) { return ::grpc_impl::internal::ClientAsyncResponseReaderFactory< ::mavsdk::rpc::action::TransitionToMulticopterResponse>::Create(channel_.get(), cq, rpcmethod_TransitionToMulticopter_, context, request, true); } ::grpc::ClientAsyncResponseReader< ::mavsdk::rpc::action::TransitionToMulticopterResponse>* ActionService::Stub::PrepareAsyncTransitionToMulticopterRaw(::grpc::ClientContext* context, const ::mavsdk::rpc::action::TransitionToMulticopterRequest& request, ::grpc::CompletionQueue* cq) { return ::grpc_impl::internal::ClientAsyncResponseReaderFactory< ::mavsdk::rpc::action::TransitionToMulticopterResponse>::Create(channel_.get(), cq, rpcmethod_TransitionToMulticopter_, context, request, false); } ::grpc::Status ActionService::Stub::GetTakeoffAltitude(::grpc::ClientContext* context, const ::mavsdk::rpc::action::GetTakeoffAltitudeRequest& request, ::mavsdk::rpc::action::GetTakeoffAltitudeResponse* response) { return ::grpc::internal::BlockingUnaryCall(channel_.get(), rpcmethod_GetTakeoffAltitude_, context, request, response); } void ActionService::Stub::experimental_async::GetTakeoffAltitude(::grpc::ClientContext* context, const ::mavsdk::rpc::action::GetTakeoffAltitudeRequest* request, ::mavsdk::rpc::action::GetTakeoffAltitudeResponse* response, std::function f) { ::grpc_impl::internal::CallbackUnaryCall(stub_->channel_.get(), stub_->rpcmethod_GetTakeoffAltitude_, context, request, response, std::move(f)); } void ActionService::Stub::experimental_async::GetTakeoffAltitude(::grpc::ClientContext* context, const ::grpc::ByteBuffer* request, ::mavsdk::rpc::action::GetTakeoffAltitudeResponse* response, std::function f) { ::grpc_impl::internal::CallbackUnaryCall(stub_->channel_.get(), stub_->rpcmethod_GetTakeoffAltitude_, context, request, response, std::move(f)); } void ActionService::Stub::experimental_async::GetTakeoffAltitude(::grpc::ClientContext* context, const ::mavsdk::rpc::action::GetTakeoffAltitudeRequest* request, ::mavsdk::rpc::action::GetTakeoffAltitudeResponse* response, ::grpc::experimental::ClientUnaryReactor* reactor) { ::grpc_impl::internal::ClientCallbackUnaryFactory::Create(stub_->channel_.get(), stub_->rpcmethod_GetTakeoffAltitude_, context, request, response, reactor); } void ActionService::Stub::experimental_async::GetTakeoffAltitude(::grpc::ClientContext* context, const ::grpc::ByteBuffer* request, ::mavsdk::rpc::action::GetTakeoffAltitudeResponse* response, ::grpc::experimental::ClientUnaryReactor* reactor) { ::grpc_impl::internal::ClientCallbackUnaryFactory::Create(stub_->channel_.get(), stub_->rpcmethod_GetTakeoffAltitude_, context, request, response, reactor); } ::grpc::ClientAsyncResponseReader< ::mavsdk::rpc::action::GetTakeoffAltitudeResponse>* ActionService::Stub::AsyncGetTakeoffAltitudeRaw(::grpc::ClientContext* context, const ::mavsdk::rpc::action::GetTakeoffAltitudeRequest& request, ::grpc::CompletionQueue* cq) { return ::grpc_impl::internal::ClientAsyncResponseReaderFactory< ::mavsdk::rpc::action::GetTakeoffAltitudeResponse>::Create(channel_.get(), cq, rpcmethod_GetTakeoffAltitude_, context, request, true); } ::grpc::ClientAsyncResponseReader< ::mavsdk::rpc::action::GetTakeoffAltitudeResponse>* ActionService::Stub::PrepareAsyncGetTakeoffAltitudeRaw(::grpc::ClientContext* context, const ::mavsdk::rpc::action::GetTakeoffAltitudeRequest& request, ::grpc::CompletionQueue* cq) { return ::grpc_impl::internal::ClientAsyncResponseReaderFactory< ::mavsdk::rpc::action::GetTakeoffAltitudeResponse>::Create(channel_.get(), cq, rpcmethod_GetTakeoffAltitude_, context, request, false); } ::grpc::Status ActionService::Stub::SetTakeoffAltitude(::grpc::ClientContext* context, const ::mavsdk::rpc::action::SetTakeoffAltitudeRequest& request, ::mavsdk::rpc::action::SetTakeoffAltitudeResponse* response) { return ::grpc::internal::BlockingUnaryCall(channel_.get(), rpcmethod_SetTakeoffAltitude_, context, request, response); } void ActionService::Stub::experimental_async::SetTakeoffAltitude(::grpc::ClientContext* context, const ::mavsdk::rpc::action::SetTakeoffAltitudeRequest* request, ::mavsdk::rpc::action::SetTakeoffAltitudeResponse* response, std::function f) { ::grpc_impl::internal::CallbackUnaryCall(stub_->channel_.get(), stub_->rpcmethod_SetTakeoffAltitude_, context, request, response, std::move(f)); } void ActionService::Stub::experimental_async::SetTakeoffAltitude(::grpc::ClientContext* context, const ::grpc::ByteBuffer* request, ::mavsdk::rpc::action::SetTakeoffAltitudeResponse* response, std::function f) { ::grpc_impl::internal::CallbackUnaryCall(stub_->channel_.get(), stub_->rpcmethod_SetTakeoffAltitude_, context, request, response, std::move(f)); } void ActionService::Stub::experimental_async::SetTakeoffAltitude(::grpc::ClientContext* context, const ::mavsdk::rpc::action::SetTakeoffAltitudeRequest* request, ::mavsdk::rpc::action::SetTakeoffAltitudeResponse* response, ::grpc::experimental::ClientUnaryReactor* reactor) { ::grpc_impl::internal::ClientCallbackUnaryFactory::Create(stub_->channel_.get(), stub_->rpcmethod_SetTakeoffAltitude_, context, request, response, reactor); } void ActionService::Stub::experimental_async::SetTakeoffAltitude(::grpc::ClientContext* context, const ::grpc::ByteBuffer* request, ::mavsdk::rpc::action::SetTakeoffAltitudeResponse* response, ::grpc::experimental::ClientUnaryReactor* reactor) { ::grpc_impl::internal::ClientCallbackUnaryFactory::Create(stub_->channel_.get(), stub_->rpcmethod_SetTakeoffAltitude_, context, request, response, reactor); } ::grpc::ClientAsyncResponseReader< ::mavsdk::rpc::action::SetTakeoffAltitudeResponse>* ActionService::Stub::AsyncSetTakeoffAltitudeRaw(::grpc::ClientContext* context, const ::mavsdk::rpc::action::SetTakeoffAltitudeRequest& request, ::grpc::CompletionQueue* cq) { return ::grpc_impl::internal::ClientAsyncResponseReaderFactory< ::mavsdk::rpc::action::SetTakeoffAltitudeResponse>::Create(channel_.get(), cq, rpcmethod_SetTakeoffAltitude_, context, request, true); } ::grpc::ClientAsyncResponseReader< ::mavsdk::rpc::action::SetTakeoffAltitudeResponse>* ActionService::Stub::PrepareAsyncSetTakeoffAltitudeRaw(::grpc::ClientContext* context, const ::mavsdk::rpc::action::SetTakeoffAltitudeRequest& request, ::grpc::CompletionQueue* cq) { return ::grpc_impl::internal::ClientAsyncResponseReaderFactory< ::mavsdk::rpc::action::SetTakeoffAltitudeResponse>::Create(channel_.get(), cq, rpcmethod_SetTakeoffAltitude_, context, request, false); } ::grpc::Status ActionService::Stub::GetMaximumSpeed(::grpc::ClientContext* context, const ::mavsdk::rpc::action::GetMaximumSpeedRequest& request, ::mavsdk::rpc::action::GetMaximumSpeedResponse* response) { return ::grpc::internal::BlockingUnaryCall(channel_.get(), rpcmethod_GetMaximumSpeed_, context, request, response); } void ActionService::Stub::experimental_async::GetMaximumSpeed(::grpc::ClientContext* context, const ::mavsdk::rpc::action::GetMaximumSpeedRequest* request, ::mavsdk::rpc::action::GetMaximumSpeedResponse* response, std::function f) { ::grpc_impl::internal::CallbackUnaryCall(stub_->channel_.get(), stub_->rpcmethod_GetMaximumSpeed_, context, request, response, std::move(f)); } void ActionService::Stub::experimental_async::GetMaximumSpeed(::grpc::ClientContext* context, const ::grpc::ByteBuffer* request, ::mavsdk::rpc::action::GetMaximumSpeedResponse* response, std::function f) { ::grpc_impl::internal::CallbackUnaryCall(stub_->channel_.get(), stub_->rpcmethod_GetMaximumSpeed_, context, request, response, std::move(f)); } void ActionService::Stub::experimental_async::GetMaximumSpeed(::grpc::ClientContext* context, const ::mavsdk::rpc::action::GetMaximumSpeedRequest* request, ::mavsdk::rpc::action::GetMaximumSpeedResponse* response, ::grpc::experimental::ClientUnaryReactor* reactor) { ::grpc_impl::internal::ClientCallbackUnaryFactory::Create(stub_->channel_.get(), stub_->rpcmethod_GetMaximumSpeed_, context, request, response, reactor); } void ActionService::Stub::experimental_async::GetMaximumSpeed(::grpc::ClientContext* context, const ::grpc::ByteBuffer* request, ::mavsdk::rpc::action::GetMaximumSpeedResponse* response, ::grpc::experimental::ClientUnaryReactor* reactor) { ::grpc_impl::internal::ClientCallbackUnaryFactory::Create(stub_->channel_.get(), stub_->rpcmethod_GetMaximumSpeed_, context, request, response, reactor); } ::grpc::ClientAsyncResponseReader< ::mavsdk::rpc::action::GetMaximumSpeedResponse>* ActionService::Stub::AsyncGetMaximumSpeedRaw(::grpc::ClientContext* context, const ::mavsdk::rpc::action::GetMaximumSpeedRequest& request, ::grpc::CompletionQueue* cq) { return ::grpc_impl::internal::ClientAsyncResponseReaderFactory< ::mavsdk::rpc::action::GetMaximumSpeedResponse>::Create(channel_.get(), cq, rpcmethod_GetMaximumSpeed_, context, request, true); } ::grpc::ClientAsyncResponseReader< ::mavsdk::rpc::action::GetMaximumSpeedResponse>* ActionService::Stub::PrepareAsyncGetMaximumSpeedRaw(::grpc::ClientContext* context, const ::mavsdk::rpc::action::GetMaximumSpeedRequest& request, ::grpc::CompletionQueue* cq) { return ::grpc_impl::internal::ClientAsyncResponseReaderFactory< ::mavsdk::rpc::action::GetMaximumSpeedResponse>::Create(channel_.get(), cq, rpcmethod_GetMaximumSpeed_, context, request, false); } ::grpc::Status ActionService::Stub::SetMaximumSpeed(::grpc::ClientContext* context, const ::mavsdk::rpc::action::SetMaximumSpeedRequest& request, ::mavsdk::rpc::action::SetMaximumSpeedResponse* response) { return ::grpc::internal::BlockingUnaryCall(channel_.get(), rpcmethod_SetMaximumSpeed_, context, request, response); } void ActionService::Stub::experimental_async::SetMaximumSpeed(::grpc::ClientContext* context, const ::mavsdk::rpc::action::SetMaximumSpeedRequest* request, ::mavsdk::rpc::action::SetMaximumSpeedResponse* response, std::function f) { ::grpc_impl::internal::CallbackUnaryCall(stub_->channel_.get(), stub_->rpcmethod_SetMaximumSpeed_, context, request, response, std::move(f)); } void ActionService::Stub::experimental_async::SetMaximumSpeed(::grpc::ClientContext* context, const ::grpc::ByteBuffer* request, ::mavsdk::rpc::action::SetMaximumSpeedResponse* response, std::function f) { ::grpc_impl::internal::CallbackUnaryCall(stub_->channel_.get(), stub_->rpcmethod_SetMaximumSpeed_, context, request, response, std::move(f)); } void ActionService::Stub::experimental_async::SetMaximumSpeed(::grpc::ClientContext* context, const ::mavsdk::rpc::action::SetMaximumSpeedRequest* request, ::mavsdk::rpc::action::SetMaximumSpeedResponse* response, ::grpc::experimental::ClientUnaryReactor* reactor) { ::grpc_impl::internal::ClientCallbackUnaryFactory::Create(stub_->channel_.get(), stub_->rpcmethod_SetMaximumSpeed_, context, request, response, reactor); } void ActionService::Stub::experimental_async::SetMaximumSpeed(::grpc::ClientContext* context, const ::grpc::ByteBuffer* request, ::mavsdk::rpc::action::SetMaximumSpeedResponse* response, ::grpc::experimental::ClientUnaryReactor* reactor) { ::grpc_impl::internal::ClientCallbackUnaryFactory::Create(stub_->channel_.get(), stub_->rpcmethod_SetMaximumSpeed_, context, request, response, reactor); } ::grpc::ClientAsyncResponseReader< ::mavsdk::rpc::action::SetMaximumSpeedResponse>* ActionService::Stub::AsyncSetMaximumSpeedRaw(::grpc::ClientContext* context, const ::mavsdk::rpc::action::SetMaximumSpeedRequest& request, ::grpc::CompletionQueue* cq) { return ::grpc_impl::internal::ClientAsyncResponseReaderFactory< ::mavsdk::rpc::action::SetMaximumSpeedResponse>::Create(channel_.get(), cq, rpcmethod_SetMaximumSpeed_, context, request, true); } ::grpc::ClientAsyncResponseReader< ::mavsdk::rpc::action::SetMaximumSpeedResponse>* ActionService::Stub::PrepareAsyncSetMaximumSpeedRaw(::grpc::ClientContext* context, const ::mavsdk::rpc::action::SetMaximumSpeedRequest& request, ::grpc::CompletionQueue* cq) { return ::grpc_impl::internal::ClientAsyncResponseReaderFactory< ::mavsdk::rpc::action::SetMaximumSpeedResponse>::Create(channel_.get(), cq, rpcmethod_SetMaximumSpeed_, context, request, false); } ::grpc::Status ActionService::Stub::GetReturnToLaunchAltitude(::grpc::ClientContext* context, const ::mavsdk::rpc::action::GetReturnToLaunchAltitudeRequest& request, ::mavsdk::rpc::action::GetReturnToLaunchAltitudeResponse* response) { return ::grpc::internal::BlockingUnaryCall(channel_.get(), rpcmethod_GetReturnToLaunchAltitude_, context, request, response); } void ActionService::Stub::experimental_async::GetReturnToLaunchAltitude(::grpc::ClientContext* context, const ::mavsdk::rpc::action::GetReturnToLaunchAltitudeRequest* request, ::mavsdk::rpc::action::GetReturnToLaunchAltitudeResponse* response, std::function f) { ::grpc_impl::internal::CallbackUnaryCall(stub_->channel_.get(), stub_->rpcmethod_GetReturnToLaunchAltitude_, context, request, response, std::move(f)); } void ActionService::Stub::experimental_async::GetReturnToLaunchAltitude(::grpc::ClientContext* context, const ::grpc::ByteBuffer* request, ::mavsdk::rpc::action::GetReturnToLaunchAltitudeResponse* response, std::function f) { ::grpc_impl::internal::CallbackUnaryCall(stub_->channel_.get(), stub_->rpcmethod_GetReturnToLaunchAltitude_, context, request, response, std::move(f)); } void ActionService::Stub::experimental_async::GetReturnToLaunchAltitude(::grpc::ClientContext* context, const ::mavsdk::rpc::action::GetReturnToLaunchAltitudeRequest* request, ::mavsdk::rpc::action::GetReturnToLaunchAltitudeResponse* response, ::grpc::experimental::ClientUnaryReactor* reactor) { ::grpc_impl::internal::ClientCallbackUnaryFactory::Create(stub_->channel_.get(), stub_->rpcmethod_GetReturnToLaunchAltitude_, context, request, response, reactor); } void ActionService::Stub::experimental_async::GetReturnToLaunchAltitude(::grpc::ClientContext* context, const ::grpc::ByteBuffer* request, ::mavsdk::rpc::action::GetReturnToLaunchAltitudeResponse* response, ::grpc::experimental::ClientUnaryReactor* reactor) { ::grpc_impl::internal::ClientCallbackUnaryFactory::Create(stub_->channel_.get(), stub_->rpcmethod_GetReturnToLaunchAltitude_, context, request, response, reactor); } ::grpc::ClientAsyncResponseReader< ::mavsdk::rpc::action::GetReturnToLaunchAltitudeResponse>* ActionService::Stub::AsyncGetReturnToLaunchAltitudeRaw(::grpc::ClientContext* context, const ::mavsdk::rpc::action::GetReturnToLaunchAltitudeRequest& request, ::grpc::CompletionQueue* cq) { return ::grpc_impl::internal::ClientAsyncResponseReaderFactory< ::mavsdk::rpc::action::GetReturnToLaunchAltitudeResponse>::Create(channel_.get(), cq, rpcmethod_GetReturnToLaunchAltitude_, context, request, true); } ::grpc::ClientAsyncResponseReader< ::mavsdk::rpc::action::GetReturnToLaunchAltitudeResponse>* ActionService::Stub::PrepareAsyncGetReturnToLaunchAltitudeRaw(::grpc::ClientContext* context, const ::mavsdk::rpc::action::GetReturnToLaunchAltitudeRequest& request, ::grpc::CompletionQueue* cq) { return ::grpc_impl::internal::ClientAsyncResponseReaderFactory< ::mavsdk::rpc::action::GetReturnToLaunchAltitudeResponse>::Create(channel_.get(), cq, rpcmethod_GetReturnToLaunchAltitude_, context, request, false); } ::grpc::Status ActionService::Stub::SetReturnToLaunchAltitude(::grpc::ClientContext* context, const ::mavsdk::rpc::action::SetReturnToLaunchAltitudeRequest& request, ::mavsdk::rpc::action::SetReturnToLaunchAltitudeResponse* response) { return ::grpc::internal::BlockingUnaryCall(channel_.get(), rpcmethod_SetReturnToLaunchAltitude_, context, request, response); } void ActionService::Stub::experimental_async::SetReturnToLaunchAltitude(::grpc::ClientContext* context, const ::mavsdk::rpc::action::SetReturnToLaunchAltitudeRequest* request, ::mavsdk::rpc::action::SetReturnToLaunchAltitudeResponse* response, std::function f) { ::grpc_impl::internal::CallbackUnaryCall(stub_->channel_.get(), stub_->rpcmethod_SetReturnToLaunchAltitude_, context, request, response, std::move(f)); } void ActionService::Stub::experimental_async::SetReturnToLaunchAltitude(::grpc::ClientContext* context, const ::grpc::ByteBuffer* request, ::mavsdk::rpc::action::SetReturnToLaunchAltitudeResponse* response, std::function f) { ::grpc_impl::internal::CallbackUnaryCall(stub_->channel_.get(), stub_->rpcmethod_SetReturnToLaunchAltitude_, context, request, response, std::move(f)); } void ActionService::Stub::experimental_async::SetReturnToLaunchAltitude(::grpc::ClientContext* context, const ::mavsdk::rpc::action::SetReturnToLaunchAltitudeRequest* request, ::mavsdk::rpc::action::SetReturnToLaunchAltitudeResponse* response, ::grpc::experimental::ClientUnaryReactor* reactor) { ::grpc_impl::internal::ClientCallbackUnaryFactory::Create(stub_->channel_.get(), stub_->rpcmethod_SetReturnToLaunchAltitude_, context, request, response, reactor); } void ActionService::Stub::experimental_async::SetReturnToLaunchAltitude(::grpc::ClientContext* context, const ::grpc::ByteBuffer* request, ::mavsdk::rpc::action::SetReturnToLaunchAltitudeResponse* response, ::grpc::experimental::ClientUnaryReactor* reactor) { ::grpc_impl::internal::ClientCallbackUnaryFactory::Create(stub_->channel_.get(), stub_->rpcmethod_SetReturnToLaunchAltitude_, context, request, response, reactor); } ::grpc::ClientAsyncResponseReader< ::mavsdk::rpc::action::SetReturnToLaunchAltitudeResponse>* ActionService::Stub::AsyncSetReturnToLaunchAltitudeRaw(::grpc::ClientContext* context, const ::mavsdk::rpc::action::SetReturnToLaunchAltitudeRequest& request, ::grpc::CompletionQueue* cq) { return ::grpc_impl::internal::ClientAsyncResponseReaderFactory< ::mavsdk::rpc::action::SetReturnToLaunchAltitudeResponse>::Create(channel_.get(), cq, rpcmethod_SetReturnToLaunchAltitude_, context, request, true); } ::grpc::ClientAsyncResponseReader< ::mavsdk::rpc::action::SetReturnToLaunchAltitudeResponse>* ActionService::Stub::PrepareAsyncSetReturnToLaunchAltitudeRaw(::grpc::ClientContext* context, const ::mavsdk::rpc::action::SetReturnToLaunchAltitudeRequest& request, ::grpc::CompletionQueue* cq) { return ::grpc_impl::internal::ClientAsyncResponseReaderFactory< ::mavsdk::rpc::action::SetReturnToLaunchAltitudeResponse>::Create(channel_.get(), cq, rpcmethod_SetReturnToLaunchAltitude_, context, request, false); } ActionService::Service::Service() { AddMethod(new ::grpc::internal::RpcServiceMethod( ActionService_method_names[0], ::grpc::internal::RpcMethod::NORMAL_RPC, new ::grpc::internal::RpcMethodHandler< ActionService::Service, ::mavsdk::rpc::action::ArmRequest, ::mavsdk::rpc::action::ArmResponse>( std::mem_fn(&ActionService::Service::Arm), this))); AddMethod(new ::grpc::internal::RpcServiceMethod( ActionService_method_names[1], ::grpc::internal::RpcMethod::NORMAL_RPC, new ::grpc::internal::RpcMethodHandler< ActionService::Service, ::mavsdk::rpc::action::DisarmRequest, ::mavsdk::rpc::action::DisarmResponse>( std::mem_fn(&ActionService::Service::Disarm), this))); AddMethod(new ::grpc::internal::RpcServiceMethod( ActionService_method_names[2], ::grpc::internal::RpcMethod::NORMAL_RPC, new ::grpc::internal::RpcMethodHandler< ActionService::Service, ::mavsdk::rpc::action::TakeoffRequest, ::mavsdk::rpc::action::TakeoffResponse>( std::mem_fn(&ActionService::Service::Takeoff), this))); AddMethod(new ::grpc::internal::RpcServiceMethod( ActionService_method_names[3], ::grpc::internal::RpcMethod::NORMAL_RPC, new ::grpc::internal::RpcMethodHandler< ActionService::Service, ::mavsdk::rpc::action::LandRequest, ::mavsdk::rpc::action::LandResponse>( std::mem_fn(&ActionService::Service::Land), this))); AddMethod(new ::grpc::internal::RpcServiceMethod( ActionService_method_names[4], ::grpc::internal::RpcMethod::NORMAL_RPC, new ::grpc::internal::RpcMethodHandler< ActionService::Service, ::mavsdk::rpc::action::RebootRequest, ::mavsdk::rpc::action::RebootResponse>( std::mem_fn(&ActionService::Service::Reboot), this))); AddMethod(new ::grpc::internal::RpcServiceMethod( ActionService_method_names[5], ::grpc::internal::RpcMethod::NORMAL_RPC, new ::grpc::internal::RpcMethodHandler< ActionService::Service, ::mavsdk::rpc::action::ShutdownRequest, ::mavsdk::rpc::action::ShutdownResponse>( std::mem_fn(&ActionService::Service::Shutdown), this))); AddMethod(new ::grpc::internal::RpcServiceMethod( ActionService_method_names[6], ::grpc::internal::RpcMethod::NORMAL_RPC, new ::grpc::internal::RpcMethodHandler< ActionService::Service, ::mavsdk::rpc::action::KillRequest, ::mavsdk::rpc::action::KillResponse>( std::mem_fn(&ActionService::Service::Kill), this))); AddMethod(new ::grpc::internal::RpcServiceMethod( ActionService_method_names[7], ::grpc::internal::RpcMethod::NORMAL_RPC, new ::grpc::internal::RpcMethodHandler< ActionService::Service, ::mavsdk::rpc::action::ReturnToLaunchRequest, ::mavsdk::rpc::action::ReturnToLaunchResponse>( std::mem_fn(&ActionService::Service::ReturnToLaunch), this))); AddMethod(new ::grpc::internal::RpcServiceMethod( ActionService_method_names[8], ::grpc::internal::RpcMethod::NORMAL_RPC, new ::grpc::internal::RpcMethodHandler< ActionService::Service, ::mavsdk::rpc::action::GotoLocationRequest, ::mavsdk::rpc::action::GotoLocationResponse>( std::mem_fn(&ActionService::Service::GotoLocation), this))); AddMethod(new ::grpc::internal::RpcServiceMethod( ActionService_method_names[9], ::grpc::internal::RpcMethod::NORMAL_RPC, new ::grpc::internal::RpcMethodHandler< ActionService::Service, ::mavsdk::rpc::action::TransitionToFixedwingRequest, ::mavsdk::rpc::action::TransitionToFixedwingResponse>( std::mem_fn(&ActionService::Service::TransitionToFixedwing), this))); AddMethod(new ::grpc::internal::RpcServiceMethod( ActionService_method_names[10], ::grpc::internal::RpcMethod::NORMAL_RPC, new ::grpc::internal::RpcMethodHandler< ActionService::Service, ::mavsdk::rpc::action::TransitionToMulticopterRequest, ::mavsdk::rpc::action::TransitionToMulticopterResponse>( std::mem_fn(&ActionService::Service::TransitionToMulticopter), this))); AddMethod(new ::grpc::internal::RpcServiceMethod( ActionService_method_names[11], ::grpc::internal::RpcMethod::NORMAL_RPC, new ::grpc::internal::RpcMethodHandler< ActionService::Service, ::mavsdk::rpc::action::GetTakeoffAltitudeRequest, ::mavsdk::rpc::action::GetTakeoffAltitudeResponse>( std::mem_fn(&ActionService::Service::GetTakeoffAltitude), this))); AddMethod(new ::grpc::internal::RpcServiceMethod( ActionService_method_names[12], ::grpc::internal::RpcMethod::NORMAL_RPC, new ::grpc::internal::RpcMethodHandler< ActionService::Service, ::mavsdk::rpc::action::SetTakeoffAltitudeRequest, ::mavsdk::rpc::action::SetTakeoffAltitudeResponse>( std::mem_fn(&ActionService::Service::SetTakeoffAltitude), this))); AddMethod(new ::grpc::internal::RpcServiceMethod( ActionService_method_names[13], ::grpc::internal::RpcMethod::NORMAL_RPC, new ::grpc::internal::RpcMethodHandler< ActionService::Service, ::mavsdk::rpc::action::GetMaximumSpeedRequest, ::mavsdk::rpc::action::GetMaximumSpeedResponse>( std::mem_fn(&ActionService::Service::GetMaximumSpeed), this))); AddMethod(new ::grpc::internal::RpcServiceMethod( ActionService_method_names[14], ::grpc::internal::RpcMethod::NORMAL_RPC, new ::grpc::internal::RpcMethodHandler< ActionService::Service, ::mavsdk::rpc::action::SetMaximumSpeedRequest, ::mavsdk::rpc::action::SetMaximumSpeedResponse>( std::mem_fn(&ActionService::Service::SetMaximumSpeed), this))); AddMethod(new ::grpc::internal::RpcServiceMethod( ActionService_method_names[15], ::grpc::internal::RpcMethod::NORMAL_RPC, new ::grpc::internal::RpcMethodHandler< ActionService::Service, ::mavsdk::rpc::action::GetReturnToLaunchAltitudeRequest, ::mavsdk::rpc::action::GetReturnToLaunchAltitudeResponse>( std::mem_fn(&ActionService::Service::GetReturnToLaunchAltitude), this))); AddMethod(new ::grpc::internal::RpcServiceMethod( ActionService_method_names[16], ::grpc::internal::RpcMethod::NORMAL_RPC, new ::grpc::internal::RpcMethodHandler< ActionService::Service, ::mavsdk::rpc::action::SetReturnToLaunchAltitudeRequest, ::mavsdk::rpc::action::SetReturnToLaunchAltitudeResponse>( std::mem_fn(&ActionService::Service::SetReturnToLaunchAltitude), this))); } ActionService::Service::~Service() { } ::grpc::Status ActionService::Service::Arm(::grpc::ServerContext* context, const ::mavsdk::rpc::action::ArmRequest* request, ::mavsdk::rpc::action::ArmResponse* response) { (void) context; (void) request; (void) response; return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, """"); } ::grpc::Status ActionService::Service::Disarm(::grpc::ServerContext* context, const ::mavsdk::rpc::action::DisarmRequest* request, ::mavsdk::rpc::action::DisarmResponse* response) { (void) context; (void) request; (void) response; return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, """"); } ::grpc::Status ActionService::Service::Takeoff(::grpc::ServerContext* context, const ::mavsdk::rpc::action::TakeoffRequest* request, ::mavsdk::rpc::action::TakeoffResponse* response) { (void) context; (void) request; (void) response; return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, """"); } ::grpc::Status ActionService::Service::Land(::grpc::ServerContext* context, const ::mavsdk::rpc::action::LandRequest* request, ::mavsdk::rpc::action::LandResponse* response) { (void) context; (void) request; (void) response; return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, """"); } ::grpc::Status ActionService::Service::Reboot(::grpc::ServerContext* context, const ::mavsdk::rpc::action::RebootRequest* request, ::mavsdk::rpc::action::RebootResponse* response) { (void) context; (void) request; (void) response; return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, """"); } ::grpc::Status ActionService::Service::Shutdown(::grpc::ServerContext* context, const ::mavsdk::rpc::action::ShutdownRequest* request, ::mavsdk::rpc::action::ShutdownResponse* response) { (void) context; (void) request; (void) response; return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, """"); } ::grpc::Status ActionService::Service::Kill(::grpc::ServerContext* context, const ::mavsdk::rpc::action::KillRequest* request, ::mavsdk::rpc::action::KillResponse* response) { (void) context; (void) request; (void) response; return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, """"); } ::grpc::Status ActionService::Service::ReturnToLaunch(::grpc::ServerContext* context, const ::mavsdk::rpc::action::ReturnToLaunchRequest* request, ::mavsdk::rpc::action::ReturnToLaunchResponse* response) { (void) context; (void) request; (void) response; return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, """"); } ::grpc::Status ActionService::Service::GotoLocation(::grpc::ServerContext* context, const ::mavsdk::rpc::action::GotoLocationRequest* request, ::mavsdk::rpc::action::GotoLocationResponse* response) { (void) context; (void) request; (void) response; return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, """"); } ::grpc::Status ActionService::Service::TransitionToFixedwing(::grpc::ServerContext* context, const ::mavsdk::rpc::action::TransitionToFixedwingRequest* request, ::mavsdk::rpc::action::TransitionToFixedwingResponse* response) { (void) context; (void) request; (void) response; return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, """"); } ::grpc::Status ActionService::Service::TransitionToMulticopter(::grpc::ServerContext* context, const ::mavsdk::rpc::action::TransitionToMulticopterRequest* request, ::mavsdk::rpc::action::TransitionToMulticopterResponse* response) { (void) context; (void) request; (void) response; return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, """"); } ::grpc::Status ActionService::Service::GetTakeoffAltitude(::grpc::ServerContext* context, const ::mavsdk::rpc::action::GetTakeoffAltitudeRequest* request, ::mavsdk::rpc::action::GetTakeoffAltitudeResponse* response) { (void) context; (void) request; (void) response; return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, """"); } ::grpc::Status ActionService::Service::SetTakeoffAltitude(::grpc::ServerContext* context, const ::mavsdk::rpc::action::SetTakeoffAltitudeRequest* request, ::mavsdk::rpc::action::SetTakeoffAltitudeResponse* response) { (void) context; (void) request; (void) response; return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, """"); } ::grpc::Status ActionService::Service::GetMaximumSpeed(::grpc::ServerContext* context, const ::mavsdk::rpc::action::GetMaximumSpeedRequest* request, ::mavsdk::rpc::action::GetMaximumSpeedResponse* response) { (void) context; (void) request; (void) response; return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, """"); } ::grpc::Status ActionService::Service::SetMaximumSpeed(::grpc::ServerContext* context, const ::mavsdk::rpc::action::SetMaximumSpeedRequest* request, ::mavsdk::rpc::action::SetMaximumSpeedResponse* response) { (void) context; (void) request; (void) response; return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, """"); } ::grpc::Status ActionService::Service::GetReturnToLaunchAltitude(::grpc::ServerContext* context, const ::mavsdk::rpc::action::GetReturnToLaunchAltitudeRequest* request, ::mavsdk::rpc::action::GetReturnToLaunchAltitudeResponse* response) { (void) context; (void) request; (void) response; return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, """"); } ::grpc::Status ActionService::Service::SetReturnToLaunchAltitude(::grpc::ServerContext* context, const ::mavsdk::rpc::action::SetReturnToLaunchAltitudeRequest* request, ::mavsdk::rpc::action::SetReturnToLaunchAltitudeResponse* response) { (void) context; (void) request; (void) response; return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, """"); } } // namespace mavsdk } // namespace rpc } // namespace action ",16220,True,5537.528592107091,median "// tag::HeaderFullDisplayName[] = property.ExtendedProperty_Repo2Sys_level2_Union - V // end::HeaderFullDisplayName[] == existing_properties // tag::existing_properties[] :ExistsProperty--antorareferencedlist: :ExistsProperty--antorareferencinglist: :ExistsProperty--is_repo_managed: :ExistsProperty--is_ssas: :ExistsProperty--pk_index_guid: :ExistsProperty--pk_indexpatterncolumndatatype: :ExistsProperty--pk_indexpatterncolumnname: :ExistsProperty--referencedobjectlist: :ExistsProperty--sql_modules_definition: :ExistsProperty--FK: :ExistsProperty--AntoraIndexList: :ExistsProperty--Columns: // end::existing_properties[] == RepoObject_guid // tag::RepoObject_guid[] 58B33A4A-426D-EB11-84E2-A81E8446D5B0 // end::RepoObject_guid[] == RepoObject_FullDisplayName2 // tag::RepoObject_FullDisplayName2[] property.ExtendedProperty_Repo2Sys_level2_Union // end::RepoObject_FullDisplayName2[] == SysObject_type // tag::SysObject_type[] V // end::SysObject_type[] == SysObject_type_name // tag::SysObject_type_name[] view // end::SysObject_type_name[] == SysObject_id // tag::SysObject_id[] 2088394509 // end::SysObject_id[] == SysObject_modify_date // tag::SysObject_modify_date[] 2021-10-02 13:23:34 // end::SysObject_modify_date[] == AntoraColumnDetails // tag::AntoraColumnDetails[] [discrete] == _ [#column-level0type] === level0type [cols=""d,8a,m,m,m""] |=== |1 |*level0type* |nvarchar(6) |NOT NULL | |=== [#column-level0name] === level0name [cols=""d,8a,m,m,m""] |=== |2 |*level0name* |nvarchar(128) |NOT NULL | |=== [#column-level1type] === level1type [cols=""d,8a,m,m,m""] |=== |3 |*level1type* |varchar(9) |NULL | |=== [#column-level1name] === level1name [cols=""d,8a,m,m,m""] |=== |4 |*level1name* |nvarchar(128) |NOT NULL | |=== [#column-level2type] === level2type [cols=""d,8a,m,m,m""] |=== |5 |*level2type* |nvarchar(10) |NULL | |=== [#column-level2name] === level2name [cols=""d,8a,m,m,m""] |=== |6 |*level2name* |nvarchar(128) |NOT NULL | |=== [#column-propertyunderlinename] === property_name [cols=""d,8a,m,m,m""] |=== |7 |*property_name* |nvarchar(128) |NOT NULL | |=== [#column-propertyunderlinevalue] === property_value [cols=""d,8a,m,m,m""] |=== | |property_value |nvarchar(4000) |NULL | |=== // end::AntoraColumnDetails[] == AntoraPkColumnTableRows // tag::AntoraPkColumnTableRows[] |1 |*<>* |nvarchar(6) |NOT NULL | |2 |*<>* |nvarchar(128) |NOT NULL | |3 |*<>* |varchar(9) |NULL | |4 |*<>* |nvarchar(128) |NOT NULL | |5 |*<>* |nvarchar(10) |NULL | |6 |*<>* |nvarchar(128) |NOT NULL | |7 |*<>* |nvarchar(128) |NOT NULL | // end::AntoraPkColumnTableRows[] == AntoraNonPkColumnTableRows // tag::AntoraNonPkColumnTableRows[] | |<> |nvarchar(4000) |NULL | // end::AntoraNonPkColumnTableRows[] == AntoraIndexList // tag::AntoraIndexList[] [#index-pkunderlineextendedpropertyunderlinerepo2sysunderlinelevel2underlineunion] === PK_ExtendedProperty_Repo2Sys_level2_Union * IndexSemanticGroup: xref:other/indexsemanticgroup.adoc#startbnoblankgroupendb[no_group] + -- * <>; nvarchar(6) * <>; nvarchar(128) * <>; varchar(9) * <>; nvarchar(128) * <>; nvarchar(10) * <>; nvarchar(128) * <>; nvarchar(128) -- * PK, Unique, Real: 1, 1, 0 // end::AntoraIndexList[] == AntoraMeasureDetails // tag::AntoraMeasureDetails[] // end::AntoraMeasureDetails[] == AntoraMeasureDescriptions == AntoraParameterList // tag::AntoraParameterList[] // end::AntoraParameterList[] == AntoraXrefCulturesList // tag::AntoraXrefCulturesList[] * xref:dhw:sqldb:property.extendedproperty_repo2sys_level2_union.adoc[] - // end::AntoraXrefCulturesList[] == cultures_count // tag::cultures_count[] 1 // end::cultures_count[] == Other tags source: property.RepoObjectProperty_cross As rop_cross === additional_reference_csv // tag::additional_reference_csv[] // end::additional_reference_csv[] === AdocUspSteps // tag::adocuspsteps[] // end::adocuspsteps[] === AntoraReferencedList // tag::antorareferencedlist[] * xref:dhw:sqldb:property.extendedproperty_repo2sys_level2_repoobject.adoc[] * xref:dhw:sqldb:property.extendedproperty_repo2sys_level2_repoobjectcolumn.adoc[] // end::antorareferencedlist[] === AntoraReferencingList // tag::antorareferencinglist[] * xref:dhw:sqldb:property.usp_sync_extendedproperties_repo2sys_delete.adoc[] * xref:dhw:sqldb:property.usp_sync_extendedproperties_repo2sys_insertupdate.adoc[] // end::antorareferencinglist[] === Description // tag::description[] // end::description[] === exampleUsage // tag::exampleusage[] // end::exampleusage[] === exampleUsage_2 // tag::exampleusage_2[] // end::exampleusage_2[] === exampleUsage_3 // tag::exampleusage_3[] // end::exampleusage_3[] === exampleUsage_4 // tag::exampleusage_4[] // end::exampleusage_4[] === exampleUsage_5 // tag::exampleusage_5[] // end::exampleusage_5[] === exampleWrong_Usage // tag::examplewrong_usage[] // end::examplewrong_usage[] === has_execution_plan_issue // tag::has_execution_plan_issue[] // end::has_execution_plan_issue[] === has_get_referenced_issue // tag::has_get_referenced_issue[] // end::has_get_referenced_issue[] === has_history // tag::has_history[] // end::has_history[] === has_history_columns // tag::has_history_columns[] // end::has_history_columns[] === InheritanceType // tag::inheritancetype[] // end::inheritancetype[] === is_persistence // tag::is_persistence[] // end::is_persistence[] === is_persistence_check_duplicate_per_pk // tag::is_persistence_check_duplicate_per_pk[] // end::is_persistence_check_duplicate_per_pk[] === is_persistence_check_for_empty_source // tag::is_persistence_check_for_empty_source[] // end::is_persistence_check_for_empty_source[] === is_persistence_delete_changed // tag::is_persistence_delete_changed[] // end::is_persistence_delete_changed[] === is_persistence_delete_missing // tag::is_persistence_delete_missing[] // end::is_persistence_delete_missing[] === is_persistence_insert // tag::is_persistence_insert[] // end::is_persistence_insert[] === is_persistence_truncate // tag::is_persistence_truncate[] // end::is_persistence_truncate[] === is_persistence_update_changed // tag::is_persistence_update_changed[] // end::is_persistence_update_changed[] === is_repo_managed // tag::is_repo_managed[] 0 // end::is_repo_managed[] === is_ssas // tag::is_ssas[] 0 // end::is_ssas[] === microsoft_database_tools_support // tag::microsoft_database_tools_support[] // end::microsoft_database_tools_support[] === MS_Description // tag::ms_description[] // end::ms_description[] === persistence_source_RepoObject_fullname // tag::persistence_source_repoobject_fullname[] // end::persistence_source_repoobject_fullname[] === persistence_source_RepoObject_fullname2 // tag::persistence_source_repoobject_fullname2[] // end::persistence_source_repoobject_fullname2[] === persistence_source_RepoObject_guid // tag::persistence_source_repoobject_guid[] // end::persistence_source_repoobject_guid[] === persistence_source_RepoObject_xref // tag::persistence_source_repoobject_xref[] // end::persistence_source_repoobject_xref[] === pk_index_guid // tag::pk_index_guid[] B6C87AC3-0596-EB11-84F4-A81E8446D5B0 // end::pk_index_guid[] === pk_IndexPatternColumnDatatype // tag::pk_indexpatterncolumndatatype[] nvarchar(6),nvarchar(128),varchar(9),nvarchar(128),nvarchar(10),nvarchar(128),nvarchar(128) // end::pk_indexpatterncolumndatatype[] === pk_IndexPatternColumnName // tag::pk_indexpatterncolumnname[] level0type,level0name,level1type,level1name,level2type,level2name,property_name // end::pk_indexpatterncolumnname[] === pk_IndexSemanticGroup // tag::pk_indexsemanticgroup[] // end::pk_indexsemanticgroup[] === ReferencedObjectList // tag::referencedobjectlist[] * [property].[ExtendedProperty_Repo2Sys_level2_RepoObject] * [property].[ExtendedProperty_Repo2Sys_level2_RepoObjectColumn] // end::referencedobjectlist[] === usp_persistence_RepoObject_guid // tag::usp_persistence_repoobject_guid[] // end::usp_persistence_repoobject_guid[] === UspExamples // tag::uspexamples[] // end::uspexamples[] === uspgenerator_usp_id // tag::uspgenerator_usp_id[] // end::uspgenerator_usp_id[] === UspParameters // tag::uspparameters[] // end::uspparameters[] == Boolean Attributes source: property.RepoObjectProperty WHERE property_int = 1 // tag::boolean_attributes[] // end::boolean_attributes[] == PlantUML diagrams === PlantUML Entity // tag::puml_entity[] [plantuml, entity-{docname}, svg, subs=macros] .... 'Left to right direction top to bottom direction hide circle 'avoide ""."" issues: set namespaceSeparator none skinparam class { BackgroundColor White BackgroundColor<> Yellow BackgroundColor<> Yellow BackgroundColor<> LightGray BackgroundColor<> Yellow BackgroundColor<> Yellow BackgroundColor<

> Aqua BackgroundColor<> Aqua BackgroundColor<> Yellow BackgroundColor<> SlateBlue BackgroundColor<> LightGray BackgroundColor<> Tomato BackgroundColor<> White BackgroundColor<> WhiteSmoke BackgroundColor<> Aqua BackgroundColor<> AliceBlue } entity ""puml-link:dhw:sqldb:property.extendedproperty_repo2sys_level2_union.adoc[]"" as property.ExtendedProperty_Repo2Sys_level2_Union << V >> { - **level0type** : (nvarchar(6)) - **level0name** : (nvarchar(128)) **level1type** : (varchar(9)) - **level1name** : (nvarchar(128)) **level2type** : (nvarchar(10)) - **level2name** : (nvarchar(128)) - **property_name** : (nvarchar(128)) property_value : (nvarchar(4000)) -- } .... // end::puml_entity[] === PlantUML Entity 1 1 FK // tag::puml_entity_1_1_fk[] [plantuml, entity_1_1_fk-{docname}, svg, subs=macros] .... @startuml left to right direction 'top to bottom direction hide circle 'avoide ""."" issues: set namespaceSeparator none skinparam class { BackgroundColor White BackgroundColor<> Yellow BackgroundColor<> Yellow BackgroundColor<> LightGray BackgroundColor<> Yellow BackgroundColor<> Yellow BackgroundColor<

> Aqua BackgroundColor<> Aqua BackgroundColor<> Yellow BackgroundColor<> SlateBlue BackgroundColor<> LightGray BackgroundColor<> Tomato BackgroundColor<> White BackgroundColor<> WhiteSmoke BackgroundColor<> Aqua BackgroundColor<> AliceBlue } entity ""puml-link:dhw:sqldb:property.extendedproperty_repo2sys_level2_union.adoc[]"" as property.ExtendedProperty_Repo2Sys_level2_Union << V >> { - **PK_ExtendedProperty_Repo2Sys_level2_Union** .. level0type; nvarchar(6) level0name; nvarchar(128) level1type; varchar(9) level1name; nvarchar(128) level2type; nvarchar(10) level2name; nvarchar(128) property_name; nvarchar(128) } footer The diagram is interactive and contains links. @enduml .... // end::puml_entity_1_1_fk[] === PlantUML 1 1 ObjectRef // tag::puml_entity_1_1_objectref[] [plantuml, entity_1_1_objectref-{docname}, svg, subs=macros] .... @startuml left to right direction 'top to bottom direction hide circle 'avoide ""."" issues: set namespaceSeparator none skinparam class { BackgroundColor White BackgroundColor<> Yellow BackgroundColor<> Yellow BackgroundColor<> LightGray BackgroundColor<> Yellow BackgroundColor<> Yellow BackgroundColor<

> Aqua BackgroundColor<> Aqua BackgroundColor<> Yellow BackgroundColor<> SlateBlue BackgroundColor<> LightGray BackgroundColor<> Tomato BackgroundColor<> White BackgroundColor<> WhiteSmoke BackgroundColor<> Aqua BackgroundColor<> AliceBlue } entity ""puml-link:dhw:sqldb:property.extendedproperty_repo2sys_level2_repoobject.adoc[]"" as property.ExtendedProperty_Repo2Sys_level2_RepoObject << V >> { - **level0type** : (nvarchar(6)) - **level0name** : (nvarchar(128)) **level1type** : (varchar(9)) - **level1name** : (nvarchar(128)) **level2type** : (varchar(10)) - **level2name** : (nvarchar(128)) - **property_name** : (nvarchar(128)) -- } entity ""puml-link:dhw:sqldb:property.extendedproperty_repo2sys_level2_repoobjectcolumn.adoc[]"" as property.ExtendedProperty_Repo2Sys_level2_RepoObjectColumn << V >> { - **level0type** : (nvarchar(6)) - **level0name** : (nvarchar(128)) **level1type** : (varchar(9)) - **level1name** : (nvarchar(128)) - **level2type** : (nvarchar(6)) - **level2name** : (nvarchar(128)) - **property_name** : (nvarchar(128)) -- } entity ""puml-link:dhw:sqldb:property.extendedproperty_repo2sys_level2_union.adoc[]"" as property.ExtendedProperty_Repo2Sys_level2_Union << V >> { - **level0type** : (nvarchar(6)) - **level0name** : (nvarchar(128)) **level1type** : (varchar(9)) - **level1name** : (nvarchar(128)) **level2type** : (nvarchar(10)) - **level2name** : (nvarchar(128)) - **property_name** : (nvarchar(128)) -- } entity ""puml-link:dhw:sqldb:property.usp_sync_extendedproperties_repo2sys_delete.adoc[]"" as property.usp_sync_ExtendedProperties_Repo2Sys_Delete << P >> { -- } entity ""puml-link:dhw:sqldb:property.usp_sync_extendedproperties_repo2sys_insertupdate.adoc[]"" as property.usp_sync_ExtendedProperties_Repo2Sys_InsertUpdate << P >> { -- } property.ExtendedProperty_Repo2Sys_level2_RepoObject <.. property.ExtendedProperty_Repo2Sys_level2_Union property.ExtendedProperty_Repo2Sys_level2_RepoObjectColumn <.. property.ExtendedProperty_Repo2Sys_level2_Union property.ExtendedProperty_Repo2Sys_level2_Union <.. property.usp_sync_ExtendedProperties_Repo2Sys_InsertUpdate property.ExtendedProperty_Repo2Sys_level2_Union <.. property.usp_sync_ExtendedProperties_Repo2Sys_Delete footer The diagram is interactive and contains links. @enduml .... // end::puml_entity_1_1_objectref[] === PlantUML 30 0 ObjectRef // tag::puml_entity_30_0_objectref[] [plantuml, entity_30_0_objectref-{docname}, svg, subs=macros] .... @startuml 'Left to right direction top to bottom direction hide circle 'avoide ""."" issues: set namespaceSeparator none skinparam class { BackgroundColor White BackgroundColor<> Yellow BackgroundColor<> Yellow BackgroundColor<> LightGray BackgroundColor<> Yellow BackgroundColor<> Yellow BackgroundColor<

> Aqua BackgroundColor<> Aqua BackgroundColor<> Yellow BackgroundColor<> SlateBlue BackgroundColor<> LightGray BackgroundColor<> Tomato BackgroundColor<> White BackgroundColor<> WhiteSmoke BackgroundColor<> Aqua BackgroundColor<> AliceBlue } entity ""puml-link:dhw:sqldb:config.ftv_get_parameter_value.adoc[]"" as config.ftv_get_parameter_value << IF >> { -- } entity ""puml-link:dhw:sqldb:config.parameter.adoc[]"" as config.Parameter << U >> { - **Parameter_name** : (varchar(100)) - **sub_Parameter** : (nvarchar(128)) -- } entity ""puml-link:dhw:sqldb:configt.parameter_default.adoc[]"" as configT.Parameter_default << V >> { - **Parameter_name** : (varchar(52)) - **sub_Parameter** : (nvarchar(26)) -- } entity ""puml-link:dhw:sqldb:configt.spt_values.adoc[]"" as configT.spt_values << U >> { -- } entity ""puml-link:dhw:sqldb:configt.type.adoc[]"" as configT.type << V >> { **type** : (nvarchar(128)) -- } entity ""puml-link:dhw:sqldb:configt.type_level1type_level2type.adoc[]"" as configT.type_level1type_level2type << V >> { **type** : (nvarchar(128)) -- } entity ""puml-link:dhw:sqldb:property.extendedproperty_repo2sys_level2_repoobject.adoc[]"" as property.ExtendedProperty_Repo2Sys_level2_RepoObject << V >> { - **level0type** : (nvarchar(6)) - **level0name** : (nvarchar(128)) **level1type** : (varchar(9)) - **level1name** : (nvarchar(128)) **level2type** : (varchar(10)) - **level2name** : (nvarchar(128)) - **property_name** : (nvarchar(128)) -- } entity ""puml-link:dhw:sqldb:property.extendedproperty_repo2sys_level2_repoobjectcolumn.adoc[]"" as property.ExtendedProperty_Repo2Sys_level2_RepoObjectColumn << V >> { - **level0type** : (nvarchar(6)) - **level0name** : (nvarchar(128)) **level1type** : (varchar(9)) - **level1name** : (nvarchar(128)) - **level2type** : (nvarchar(6)) - **level2name** : (nvarchar(128)) - **property_name** : (nvarchar(128)) -- } entity ""puml-link:dhw:sqldb:property.extendedproperty_repo2sys_level2_union.adoc[]"" as property.ExtendedProperty_Repo2Sys_level2_Union << V >> { - **level0type** : (nvarchar(6)) - **level0name** : (nvarchar(128)) **level1type** : (varchar(9)) - **level1name** : (nvarchar(128)) **level2type** : (nvarchar(10)) - **level2name** : (nvarchar(128)) - **property_name** : (nvarchar(128)) -- } entity ""puml-link:dhw:sqldb:property.external_repoobjectcolumnproperty.adoc[]"" as property.external_RepoObjectColumnProperty << U >> { - **RepoObjectColumn_guid** : (uniqueidentifier) - **property_name** : (nvarchar(128)) -- } entity ""puml-link:dhw:sqldb:property.external_repoobjectproperty.adoc[]"" as property.external_RepoObjectProperty << U >> { - **RepoObject_guid** : (uniqueidentifier) - **property_name** : (nvarchar(128)) -- } entity ""puml-link:dhw:sqldb:property.propertyname_repoobject.adoc[]"" as property.PropertyName_RepoObject << V >> { **property_name** : (nvarchar(128)) -- } entity ""puml-link:dhw:sqldb:property.propertyname_repoobject_t.adoc[]"" as property.PropertyName_RepoObject_T << U >> { **property_name** : (nvarchar(128)) -- } entity ""puml-link:dhw:sqldb:property.repoobjectcolumnproperty.adoc[]"" as property.RepoObjectColumnProperty << U >> { - **RepoObjectColumnProperty_id** : (int) -- } entity ""puml-link:dhw:sqldb:property.repoobjectcolumnproperty_external_src.adoc[]"" as property.RepoObjectColumnProperty_external_src << V >> { - **RepoObjectColumn_guid** : (uniqueidentifier) - **property_name** : (nvarchar(128)) -- } entity ""puml-link:dhw:sqldb:property.repoobjectcolumnproperty_external_tgt.adoc[]"" as property.RepoObjectColumnProperty_external_tgt << V >> { - **RepoObjectColumn_guid** : (uniqueidentifier) - **property_name** : (nvarchar(128)) -- } entity ""puml-link:dhw:sqldb:property.repoobjectproperty.adoc[]"" as property.RepoObjectProperty << U >> { - **RepoObjectProperty_id** : (int) -- } entity ""puml-link:dhw:sqldb:property.repoobjectproperty_external_src.adoc[]"" as property.RepoObjectProperty_external_src << V >> { - **RepoObject_guid** : (uniqueidentifier) - **property_name** : (nvarchar(128)) -- } entity ""puml-link:dhw:sqldb:property.repoobjectproperty_external_tgt.adoc[]"" as property.RepoObjectProperty_external_tgt << V >> { - **RepoObject_guid** : (uniqueidentifier) - **property_name** : (nvarchar(128)) -- } entity ""puml-link:dhw:sqldb:property.repoobjectproperty_selectedpropertyname_split.adoc[]"" as property.RepoObjectProperty_SelectedPropertyName_split << V >> { -- } entity ""puml-link:dhw:sqldb:reference.additional_reference.adoc[]"" as reference.additional_Reference << U >> { - **Id** : (int) -- } entity ""puml-link:dhw:sqldb:reference.additional_reference_from_properties_src.adoc[]"" as reference.additional_Reference_from_properties_src << V >> { **referenced_AntoraComponent** : (nvarchar(max)) **referenced_AntoraModule** : (nvarchar(max)) **referenced_Schema** : (nvarchar(max)) **referenced_Object** : (nvarchar(max)) **referenced_Column** : (nvarchar(max)) **referencing_AntoraComponent** : (nvarchar(max)) **referencing_AntoraModule** : (nvarchar(max)) **referencing_Schema** : (nvarchar(max)) **referencing_Object** : (nvarchar(max)) **referencing_Column** : (nvarchar(max)) -- } entity ""puml-link:dhw:sqldb:reference.additional_reference_from_properties_tgt.adoc[]"" as reference.additional_Reference_from_properties_tgt << V >> { **referenced_AntoraComponent** : (nvarchar(max)) **referenced_AntoraModule** : (nvarchar(max)) **referenced_Schema** : (nvarchar(max)) **referenced_Object** : (nvarchar(max)) **referenced_Column** : (nvarchar(max)) **referencing_AntoraComponent** : (nvarchar(max)) **referencing_AntoraModule** : (nvarchar(max)) **referencing_Schema** : (nvarchar(max)) **referencing_Object** : (nvarchar(max)) **referencing_Column** : (nvarchar(max)) -- } entity ""puml-link:dhw:sqldb:reference.additional_reference_from_ssas_src.adoc[]"" as reference.additional_Reference_from_ssas_src << V >> { **referenced_AntoraComponent** : (nvarchar(128)) **referenced_AntoraModule** : (nvarchar(128)) **referenced_Schema** : (nvarchar(max)) **referenced_Object** : (nvarchar(max)) **referenced_Column** : (nvarchar(500)) **referencing_AntoraComponent** : (nvarchar(max)) **referencing_AntoraModule** : (nvarchar(max)) - **referencing_Schema** : (nvarchar(128)) - **referencing_Object** : (nvarchar(128)) **referencing_Column** : (nvarchar(128)) -- } entity ""puml-link:dhw:sqldb:reference.additional_reference_from_ssas_tgt.adoc[]"" as reference.additional_Reference_from_ssas_tgt << V >> { **referenced_AntoraComponent** : (nvarchar(128)) **referenced_AntoraModule** : (nvarchar(128)) **referenced_Schema** : (nvarchar(max)) **referenced_Object** : (nvarchar(max)) **referenced_Column** : (nvarchar(500)) **referencing_AntoraComponent** : (nvarchar(max)) **referencing_AntoraModule** : (nvarchar(max)) - **referencing_Schema** : (nvarchar(128)) - **referencing_Object** : (nvarchar(128)) **referencing_Column** : (nvarchar(128)) -- } entity ""puml-link:dhw:sqldb:reference.additional_reference_is_external.adoc[]"" as reference.additional_Reference_is_external << V >> { -- } entity ""puml-link:dhw:sqldb:reference.additional_reference_object.adoc[]"" as reference.additional_Reference_Object << V >> { - **AntoraComponent** : (nvarchar(128)) - **AntoraModule** : (nvarchar(128)) - **SchemaName** : (nvarchar(128)) - **ObjectName** : (nvarchar(128)) -- } entity ""puml-link:dhw:sqldb:reference.additional_reference_object_t.adoc[]"" as reference.additional_Reference_Object_T << U >> { - **RepoObject_guid** : (uniqueidentifier) -- } entity ""puml-link:dhw:sqldb:reference.additional_reference_objectcolumn.adoc[]"" as reference.additional_Reference_ObjectColumn << V >> { - **AntoraComponent** : (nvarchar(128)) - **AntoraModule** : (nvarchar(128)) - **SchemaName** : (nvarchar(128)) - **ObjectName** : (nvarchar(128)) **ColumnName** : (nvarchar(128)) -- } entity ""puml-link:dhw:sqldb:reference.additional_reference_objectcolumn_t.adoc[]"" as reference.additional_Reference_ObjectColumn_T << U >> { - **RepoObjectColumn_guid** : (uniqueidentifier) -- } entity ""puml-link:dhw:sqldb:reference.additional_reference_wo_columns_from_properties_src.adoc[]"" as reference.additional_Reference_wo_columns_from_properties_src << V >> { **referenced_AntoraComponent** : (nvarchar(max)) **referenced_AntoraModule** : (nvarchar(max)) **referenced_Schema** : (nvarchar(max)) **referenced_Object** : (nvarchar(max)) **referencing_AntoraComponent** : (nvarchar(max)) **referencing_AntoraModule** : (nvarchar(max)) **referencing_Schema** : (nvarchar(max)) **referencing_Object** : (nvarchar(max)) -- } entity ""puml-link:dhw:sqldb:reference.additional_reference_wo_columns_from_properties_tgt.adoc[]"" as reference.additional_Reference_wo_columns_from_properties_tgt << V >> { **referenced_AntoraComponent** : (nvarchar(max)) **referenced_AntoraModule** : (nvarchar(max)) **referenced_Schema** : (nvarchar(max)) **referenced_Object** : (nvarchar(max)) **referencing_AntoraComponent** : (nvarchar(max)) **referencing_AntoraModule** : (nvarchar(max)) **referencing_Schema** : (nvarchar(max)) **referencing_Object** : (nvarchar(max)) -- } entity ""puml-link:dhw:sqldb:repo.repoobject.adoc[]"" as repo.RepoObject << U >> { - **RepoObject_guid** : (uniqueidentifier) -- } entity ""puml-link:dhw:sqldb:repo.repoobject_external_src.adoc[]"" as repo.RepoObject_external_src << V >> { - **RepoObject_guid** : (uniqueidentifier) -- } entity ""puml-link:dhw:sqldb:repo.repoobject_external_tgt.adoc[]"" as repo.RepoObject_external_tgt << V >> { - **RepoObject_guid** : (uniqueidentifier) -- } entity ""puml-link:dhw:sqldb:repo.repoobject_ssas_src.adoc[]"" as repo.RepoObject_SSAS_src << V >> { - **RepoObject_guid** : (uniqueidentifier) -- } entity ""puml-link:dhw:sqldb:repo.repoobject_ssas_tgt.adoc[]"" as repo.RepoObject_SSAS_tgt << V >> { - **RepoObject_guid** : (uniqueidentifier) -- } entity ""puml-link:dhw:sqldb:repo.repoobjectcolumn.adoc[]"" as repo.RepoObjectColumn << U >> { - **RepoObjectColumn_guid** : (uniqueidentifier) -- } entity ""puml-link:dhw:sqldb:repo.repoobjectcolumn_external_src.adoc[]"" as repo.RepoObjectColumn_external_src << V >> { - **RepoObjectColumn_guid** : (uniqueidentifier) -- } entity ""puml-link:dhw:sqldb:repo.repoobjectcolumn_external_tgt.adoc[]"" as repo.RepoObjectColumn_external_tgt << V >> { - **RepoObjectColumn_guid** : (uniqueidentifier) -- } entity ""puml-link:dhw:sqldb:repo.repoobjectcolumn_ssas_src.adoc[]"" as repo.RepoObjectColumn_SSAS_src << V >> { - **RepoObjectColumn_guid** : (uniqueidentifier) -- } entity ""puml-link:dhw:sqldb:repo.repoobjectcolumn_ssas_tgt.adoc[]"" as repo.RepoObjectColumn_SSAS_tgt << V >> { - **RepoObjectColumn_guid** : (uniqueidentifier) -- } entity ""puml-link:dhw:sqldb:repo.reposchema.adoc[]"" as repo.RepoSchema << U >> { - **RepoSchema_guid** : (uniqueidentifier) -- } entity ""puml-link:dhw:sqldb:repo.reposchema_ssas_src.adoc[]"" as repo.RepoSchema_ssas_src << V >> { - **RepoSchema_name** : (nvarchar(128)) -- } entity ""puml-link:dhw:sqldb:repo.reposchema_ssas_tgt.adoc[]"" as repo.RepoSchema_ssas_tgt << V >> { - **RepoSchema_guid** : (uniqueidentifier) -- } entity ""puml-link:dhw:sqldb:ssas.additional_reference_step1.adoc[]"" as ssas.additional_Reference_step1 << V >> { -- } entity ""puml-link:dhw:sqldb:ssas.model_json.adoc[]"" as ssas.model_json << U >> { - **databasename** : (nvarchar(128)) -- } entity ""puml-link:dhw:sqldb:ssas.model_json_10.adoc[]"" as ssas.model_json_10 << V >> { -- } entity ""puml-link:dhw:sqldb:ssas.model_json_20.adoc[]"" as ssas.model_json_20 << V >> { -- } entity ""puml-link:dhw:sqldb:ssas.model_json_201_descriptions_multiline.adoc[]"" as ssas.model_json_201_descriptions_multiline << V >> { -- } entity ""puml-link:dhw:sqldb:ssas.model_json_2011_descriptions_stragg.adoc[]"" as ssas.model_json_2011_descriptions_StrAgg << V >> { -- } entity ""puml-link:dhw:sqldb:ssas.model_json_31_tables.adoc[]"" as ssas.model_json_31_tables << V >> { - **databasename** : (nvarchar(128)) **tables_name** : (nvarchar(128)) -- } entity ""puml-link:dhw:sqldb:ssas.model_json_31_tables_t.adoc[]"" as ssas.model_json_31_tables_T << U >> { - **databasename** : (nvarchar(128)) **tables_name** : (nvarchar(128)) -- } entity ""puml-link:dhw:sqldb:ssas.model_json_311_tables_columns.adoc[]"" as ssas.model_json_311_tables_columns << V >> { - **databasename** : (nvarchar(128)) - **tables_name** : (nvarchar(128)) **tables_columns_name** : (nvarchar(128)) -- } entity ""puml-link:dhw:sqldb:ssas.model_json_311_tables_columns_t.adoc[]"" as ssas.model_json_311_tables_columns_T << U >> { - **databasename** : (nvarchar(128)) - **tables_name** : (nvarchar(128)) **tables_columns_name** : (nvarchar(128)) -- } entity ""puml-link:dhw:sqldb:ssas.model_json_313_tables_partitions.adoc[]"" as ssas.model_json_313_tables_partitions << V >> { - **databasename** : (nvarchar(128)) - **tables_name** : (nvarchar(128)) **tables_partitions_name** : (nvarchar(500)) -- } entity ""puml-link:dhw:sqldb:ssas.model_json_3131_tables_partitions_source.adoc[]"" as ssas.model_json_3131_tables_partitions_source << V >> { - **databasename** : (nvarchar(128)) - **tables_name** : (nvarchar(128)) **tables_partitions_name** : (nvarchar(500)) **tables_partitions_source_name** : (nvarchar(500)) -- } entity ""puml-link:dhw:sqldb:ssas.model_json_31311_tables_partitions_source_posfrom.adoc[]"" as ssas.model_json_31311_tables_partitions_source_PosFrom << V >> { -- } entity ""puml-link:dhw:sqldb:ssas.model_json_313111_tables_partitions_source_stringfrom.adoc[]"" as ssas.model_json_313111_tables_partitions_source_StringFrom << V >> { -- } entity ""puml-link:dhw:sqldb:ssas.model_json_3131111_tables_partitions_source_posdot.adoc[]"" as ssas.model_json_3131111_tables_partitions_source_PosDot << V >> { -- } entity ""puml-link:dhw:sqldb:ssas.model_json_31311111_tables_partitions_source_part123.adoc[]"" as ssas.model_json_31311111_tables_partitions_source_Part123 << V >> { -- } entity ""puml-link:dhw:sqldb:ssas.model_json_33_datasources.adoc[]"" as ssas.model_json_33_dataSources << V >> { - **databasename** : (nvarchar(128)) **dataSources_name** : (nvarchar(500)) -- } entity ""puml-link:dhw:sqldb:ssas.model_json_33_datasources_t.adoc[]"" as ssas.model_json_33_dataSources_T << U >> { - **databasename** : (nvarchar(128)) **dataSources_name** : (nvarchar(500)) -- } config.ftv_get_parameter_value <.. repo.RepoObject_external_src config.ftv_get_parameter_value <.. reference.additional_Reference_is_external config.ftv_get_parameter_value <.. ssas.additional_Reference_step1 config.Parameter <.. property.PropertyName_RepoObject config.Parameter <.. config.ftv_get_parameter_value configT.Parameter_default <.. config.Parameter configT.spt_values <.. configT.type configT.type <.. configT.type_level1type_level2type configT.type_level1type_level2type <.. property.ExtendedProperty_Repo2Sys_level2_RepoObjectColumn configT.type_level1type_level2type <.. property.ExtendedProperty_Repo2Sys_level2_RepoObject property.ExtendedProperty_Repo2Sys_level2_RepoObject <.. property.ExtendedProperty_Repo2Sys_level2_Union property.ExtendedProperty_Repo2Sys_level2_RepoObjectColumn <.. property.ExtendedProperty_Repo2Sys_level2_Union property.external_RepoObjectColumnProperty <.. property.RepoObjectColumnProperty_external_src property.external_RepoObjectProperty <.. property.RepoObjectProperty_external_src property.PropertyName_RepoObject <.. property.PropertyName_RepoObject_T property.PropertyName_RepoObject_T <.. property.RepoObjectColumnProperty_external_tgt property.PropertyName_RepoObject_T <.. property.RepoObjectProperty_external_tgt property.RepoObjectColumnProperty <.. property.ExtendedProperty_Repo2Sys_level2_RepoObjectColumn property.RepoObjectColumnProperty_external_src <.. property.RepoObjectColumnProperty_external_tgt property.RepoObjectColumnProperty_external_tgt <.. property.RepoObjectColumnProperty property.RepoObjectProperty <.. property.ExtendedProperty_Repo2Sys_level2_RepoObject property.RepoObjectProperty <.. property.RepoObjectProperty_SelectedPropertyName_split property.RepoObjectProperty <.. property.PropertyName_RepoObject property.RepoObjectProperty_external_src <.. property.RepoObjectProperty_external_tgt property.RepoObjectProperty_external_tgt <.. property.RepoObjectProperty property.RepoObjectProperty_SelectedPropertyName_split <.. reference.additional_Reference_from_properties_src property.RepoObjectProperty_SelectedPropertyName_split <.. reference.additional_Reference_wo_columns_from_properties_src reference.additional_Reference <.. reference.additional_Reference_is_external reference.additional_Reference_from_properties_src <.. reference.additional_Reference_from_properties_tgt reference.additional_Reference_from_properties_tgt <.. reference.additional_Reference reference.additional_Reference_from_ssas_src <.. reference.additional_Reference_from_ssas_tgt reference.additional_Reference_from_ssas_tgt <.. reference.additional_Reference reference.additional_Reference_is_external <.. reference.additional_Reference_ObjectColumn reference.additional_Reference_is_external <.. reference.additional_Reference_Object reference.additional_Reference_Object <.. reference.additional_Reference_Object_T reference.additional_Reference_Object_T <.. repo.RepoObject_external_src reference.additional_Reference_Object_T <.. repo.RepoObjectColumn_external_src reference.additional_Reference_ObjectColumn <.. reference.additional_Reference_ObjectColumn_T reference.additional_Reference_ObjectColumn_T <.. repo.RepoObjectColumn_external_src reference.additional_Reference_wo_columns_from_properties_src <.. reference.additional_Reference_wo_columns_from_properties_tgt reference.additional_Reference_wo_columns_from_properties_tgt <.. reference.additional_Reference repo.RepoObject <.. property.ExtendedProperty_Repo2Sys_level2_RepoObjectColumn repo.RepoObject <.. property.ExtendedProperty_Repo2Sys_level2_RepoObject repo.RepoObject <.. repo.RepoObject_external_src repo.RepoObject <.. repo.RepoObjectColumn_external_src repo.RepoObject <.. property.RepoObjectColumnProperty_external_tgt repo.RepoObject <.. property.RepoObjectProperty_external_tgt repo.RepoObject_external_src <.. repo.RepoObject_external_tgt repo.RepoObject_external_tgt <.. repo.RepoObject repo.RepoObject_external_tgt <.. repo.RepoObjectColumn_external_tgt repo.RepoObject_SSAS_src <.. repo.RepoObject_SSAS_tgt repo.RepoObject_SSAS_tgt <.. repo.RepoObjectColumn_SSAS_tgt repo.RepoObject_SSAS_tgt <.. repo.RepoObject repo.RepoObjectColumn <.. property.ExtendedProperty_Repo2Sys_level2_RepoObjectColumn repo.RepoObjectColumn <.. property.RepoObjectColumnProperty_external_tgt repo.RepoObjectColumn_external_src <.. repo.RepoObjectColumn_external_tgt repo.RepoObjectColumn_external_tgt <.. repo.RepoObjectColumn repo.RepoObjectColumn_SSAS_src <.. repo.RepoObjectColumn_SSAS_tgt repo.RepoObjectColumn_SSAS_tgt <.. repo.RepoObjectColumn repo.RepoSchema <.. repo.RepoObject_SSAS_src repo.RepoSchema_ssas_src <.. repo.RepoSchema_ssas_tgt repo.RepoSchema_ssas_tgt <.. repo.RepoSchema ssas.additional_Reference_step1 <.. reference.additional_Reference_from_ssas_src ssas.model_json <.. ssas.model_json_10 ssas.model_json_10 <.. ssas.model_json_20 ssas.model_json_20 <.. repo.RepoSchema_ssas_src ssas.model_json_20 <.. ssas.model_json_201_descriptions_multiline ssas.model_json_20 <.. ssas.model_json_31_tables ssas.model_json_20 <.. ssas.model_json_33_dataSources ssas.model_json_201_descriptions_multiline <.. ssas.model_json_2011_descriptions_StrAgg ssas.model_json_2011_descriptions_StrAgg <.. repo.RepoSchema_ssas_src ssas.model_json_31_tables <.. ssas.model_json_31_tables_T ssas.model_json_31_tables_T <.. repo.RepoObject_SSAS_src ssas.model_json_31_tables_T <.. ssas.model_json_311_tables_columns ssas.model_json_31_tables_T <.. ssas.model_json_313_tables_partitions ssas.model_json_311_tables_columns <.. ssas.model_json_311_tables_columns_T ssas.model_json_311_tables_columns_T <.. repo.RepoObjectColumn_SSAS_src ssas.model_json_311_tables_columns_T <.. ssas.additional_Reference_step1 ssas.model_json_313_tables_partitions <.. ssas.model_json_3131_tables_partitions_source ssas.model_json_3131_tables_partitions_source <.. ssas.model_json_31311_tables_partitions_source_PosFrom ssas.model_json_31311_tables_partitions_source_PosFrom <.. ssas.model_json_313111_tables_partitions_source_StringFrom ssas.model_json_313111_tables_partitions_source_StringFrom <.. ssas.model_json_3131111_tables_partitions_source_PosDot ssas.model_json_3131111_tables_partitions_source_PosDot <.. ssas.model_json_31311111_tables_partitions_source_Part123 ssas.model_json_31311111_tables_partitions_source_Part123 <.. ssas.additional_Reference_step1 ssas.model_json_33_dataSources <.. ssas.model_json_33_dataSources_T ssas.model_json_33_dataSources_T <.. ssas.additional_Reference_step1 footer The diagram is interactive and contains links. @enduml .... // end::puml_entity_30_0_objectref[] === PlantUML 0 30 ObjectRef // tag::puml_entity_0_30_objectref[] [plantuml, entity_0_30_objectref-{docname}, svg, subs=macros] .... @startuml 'Left to right direction top to bottom direction hide circle 'avoide ""."" issues: set namespaceSeparator none skinparam class { BackgroundColor White BackgroundColor<> Yellow BackgroundColor<> Yellow BackgroundColor<> LightGray BackgroundColor<> Yellow BackgroundColor<> Yellow BackgroundColor<

> Aqua BackgroundColor<> Aqua BackgroundColor<> Yellow BackgroundColor<> SlateBlue BackgroundColor<> LightGray BackgroundColor<> Tomato BackgroundColor<> White BackgroundColor<> WhiteSmoke BackgroundColor<> Aqua BackgroundColor<> AliceBlue } entity ""puml-link:dhw:sqldb:property.extendedproperty_repo2sys_level2_union.adoc[]"" as property.ExtendedProperty_Repo2Sys_level2_Union << V >> { - **level0type** : (nvarchar(6)) - **level0name** : (nvarchar(128)) **level1type** : (varchar(9)) - **level1name** : (nvarchar(128)) **level2type** : (nvarchar(10)) - **level2name** : (nvarchar(128)) - **property_name** : (nvarchar(128)) -- } entity ""puml-link:dhw:sqldb:property.usp_sync_extendedproperties_repo2sys_delete.adoc[]"" as property.usp_sync_ExtendedProperties_Repo2Sys_Delete << P >> { -- } entity ""puml-link:dhw:sqldb:property.usp_sync_extendedproperties_repo2sys_insertupdate.adoc[]"" as property.usp_sync_ExtendedProperties_Repo2Sys_InsertUpdate << P >> { -- } property.ExtendedProperty_Repo2Sys_level2_Union <.. property.usp_sync_ExtendedProperties_Repo2Sys_InsertUpdate property.ExtendedProperty_Repo2Sys_level2_Union <.. property.usp_sync_ExtendedProperties_Repo2Sys_Delete footer The diagram is interactive and contains links. @enduml .... // end::puml_entity_0_30_objectref[] === PlantUML 1 1 ColumnRef // tag::puml_entity_1_1_colref[] [plantuml, entity_1_1_colref-{docname}, svg, subs=macros] .... @startuml left to right direction 'top to bottom direction hide circle 'avoide ""."" issues: set namespaceSeparator none skinparam class { BackgroundColor White BackgroundColor<> Yellow BackgroundColor<> Yellow BackgroundColor<> LightGray BackgroundColor<> Yellow BackgroundColor<> Yellow BackgroundColor<

> Aqua BackgroundColor<> Aqua BackgroundColor<> Yellow BackgroundColor<> SlateBlue BackgroundColor<> LightGray BackgroundColor<> Tomato BackgroundColor<> White BackgroundColor<> WhiteSmoke BackgroundColor<> Aqua BackgroundColor<> AliceBlue } entity ""puml-link:dhw:sqldb:property.extendedproperty_repo2sys_level2_repoobject.adoc[]"" as property.ExtendedProperty_Repo2Sys_level2_RepoObject << V >> { - **level0type** : (nvarchar(6)) - **level0name** : (nvarchar(128)) **level1type** : (varchar(9)) - **level1name** : (nvarchar(128)) **level2type** : (varchar(10)) - **level2name** : (nvarchar(128)) - **property_name** : (nvarchar(128)) - parent_RepoObject_guid : (uniqueidentifier) - parent_RepoObject_type : (char(2)) property_value : (nvarchar(4000)) - RepoObject_guid : (uniqueidentifier) - RepoObject_type : (char(2)) -- } entity ""puml-link:dhw:sqldb:property.extendedproperty_repo2sys_level2_repoobjectcolumn.adoc[]"" as property.ExtendedProperty_Repo2Sys_level2_RepoObjectColumn << V >> { - **level0type** : (nvarchar(6)) - **level0name** : (nvarchar(128)) **level1type** : (varchar(9)) - **level1name** : (nvarchar(128)) - **level2type** : (nvarchar(6)) - **level2name** : (nvarchar(128)) - **property_name** : (nvarchar(128)) - parent_RepoObject_guid : (uniqueidentifier) - parent_RepoObject_type : (char(2)) property_value : (nvarchar(4000)) Repo_user_type_fullname : (nvarchar(128)) - RepoObjectColumn_guid : (uniqueidentifier) -- } entity ""puml-link:dhw:sqldb:property.extendedproperty_repo2sys_level2_union.adoc[]"" as property.ExtendedProperty_Repo2Sys_level2_Union << V >> { - **level0type** : (nvarchar(6)) - **level0name** : (nvarchar(128)) **level1type** : (varchar(9)) - **level1name** : (nvarchar(128)) **level2type** : (nvarchar(10)) - **level2name** : (nvarchar(128)) - **property_name** : (nvarchar(128)) property_value : (nvarchar(4000)) -- } entity ""puml-link:dhw:sqldb:property.usp_sync_extendedproperties_repo2sys_delete.adoc[]"" as property.usp_sync_ExtendedProperties_Repo2Sys_Delete << P >> { -- } entity ""puml-link:dhw:sqldb:property.usp_sync_extendedproperties_repo2sys_insertupdate.adoc[]"" as property.usp_sync_ExtendedProperties_Repo2Sys_InsertUpdate << P >> { -- } property.ExtendedProperty_Repo2Sys_level2_RepoObject <.. property.ExtendedProperty_Repo2Sys_level2_Union property.ExtendedProperty_Repo2Sys_level2_RepoObjectColumn <.. property.ExtendedProperty_Repo2Sys_level2_Union property.ExtendedProperty_Repo2Sys_level2_Union <.. property.usp_sync_ExtendedProperties_Repo2Sys_InsertUpdate property.ExtendedProperty_Repo2Sys_level2_Union <.. property.usp_sync_ExtendedProperties_Repo2Sys_Delete footer The diagram is interactive and contains links. @enduml .... // end::puml_entity_1_1_colref[] == sql_modules_definition // tag::sql_modules_definition[] [%collapsible] ======= [source,sql,numbered,indent=0] ---- CREATE View property.ExtendedProperty_Repo2Sys_level2_Union As Select -- property_name , property_value , level0type , level0name , level1type , level1name , level2type , level2name From property.ExtendedProperty_Repo2Sys_level2_RepoObject Union All Select -- property_name , property_value , level0type , level0name , level1type , level1name , level2type , level2name From property.ExtendedProperty_Repo2Sys_level2_RepoObjectColumn ---- ======= // end::sql_modules_definition[] ",12083,True,2704.1918994784783,median "[[features.testing]] == Testing Spring Boot provides a number of utilities and annotations to help when testing your application. Test support is provided by two modules: `spring-boot-test` contains core items, and `spring-boot-test-autoconfigure` supports auto-configuration for tests. Most developers use the `spring-boot-starter-test` ""`Starter`"", which imports both Spring Boot test modules as well as JUnit Jupiter, AssertJ, Hamcrest, and a number of other useful libraries. [TIP] ==== If you have tests that use JUnit 4, JUnit 5's vintage engine can be used to run them. To use the vintage engine, add a dependency on `junit-vintage-engine`, as shown in the following example: [source,xml,indent=0,subs=""verbatim""] ---- org.junit.vintage junit-vintage-engine test org.hamcrest hamcrest-core ---- ==== `hamcrest-core` is excluded in favor of `org.hamcrest:hamcrest` that is part of `spring-boot-starter-test`. [[features.testing.test-scope-dependencies]] === Test Scope Dependencies The `spring-boot-starter-test` ""`Starter`"" (in the `test` `scope`) contains the following provided libraries: * https://junit.org/junit5/[JUnit 5]: The de-facto standard for unit testing Java applications. * {spring-framework-docs}/testing.html#integration-testing[Spring Test] & Spring Boot Test: Utilities and integration test support for Spring Boot applications. * https://assertj.github.io/doc/[AssertJ]: A fluent assertion library. * https://github.com/hamcrest/JavaHamcrest[Hamcrest]: A library of matcher objects (also known as constraints or predicates). * https://site.mockito.org/[Mockito]: A Java mocking framework. * https://github.com/skyscreamer/JSONassert[JSONassert]: An assertion library for JSON. * https://github.com/jayway/JsonPath[JsonPath]: XPath for JSON. We generally find these common libraries to be useful when writing tests. If these libraries do not suit your needs, you can add additional test dependencies of your own. [[features.testing.spring-applications]] === Testing Spring Applications One of the major advantages of dependency injection is that it should make your code easier to unit test. You can instantiate objects by using the `new` operator without even involving Spring. You can also use _mock objects_ instead of real dependencies. Often, you need to move beyond unit testing and start integration testing (with a Spring `ApplicationContext`). It is useful to be able to perform integration testing without requiring deployment of your application or needing to connect to other infrastructure. The Spring Framework includes a dedicated test module for such integration testing. You can declare a dependency directly to `org.springframework:spring-test` or use the `spring-boot-starter-test` ""`Starter`"" to pull it in transitively. If you have not used the `spring-test` module before, you should start by reading the {spring-framework-docs}/testing.html#testing[relevant section] of the Spring Framework reference documentation. [[features.testing.spring-boot-applications]] === Testing Spring Boot Applications A Spring Boot application is a Spring `ApplicationContext`, so nothing very special has to be done to test it beyond what you would normally do with a vanilla Spring context. NOTE: External properties, logging, and other features of Spring Boot are installed in the context by default only if you use `SpringApplication` to create it. Spring Boot provides a `@SpringBootTest` annotation, which can be used as an alternative to the standard `spring-test` `@ContextConfiguration` annotation when you need Spring Boot features. The annotation works by <>. In addition to `@SpringBootTest` a number of other annotations are also provided for <> of an application. TIP: If you are using JUnit 4, don't forget to also add `@RunWith(SpringRunner.class)` to your test, otherwise the annotations will be ignored. If you are using JUnit 5, there's no need to add the equivalent `@ExtendWith(SpringExtension.class)` as `@SpringBootTest` and the other `@...Test` annotations are already annotated with it. By default, `@SpringBootTest` will not start a server. You can use the `webEnvironment` attribute of `@SpringBootTest` to further refine how your tests run: * `MOCK`(Default) : Loads a web `ApplicationContext` and provides a mock web environment. Embedded servers are not started when using this annotation. If a web environment is not available on your classpath, this mode transparently falls back to creating a regular non-web `ApplicationContext`. It can be used in conjunction with <> for mock-based testing of your web application. * `RANDOM_PORT`: Loads a `WebServerApplicationContext` and provides a real web environment. Embedded servers are started and listen on a random port. * `DEFINED_PORT`: Loads a `WebServerApplicationContext` and provides a real web environment. Embedded servers are started and listen on a defined port (from your `application.properties`) or on the default port of `8080`. * `NONE`: Loads an `ApplicationContext` by using `SpringApplication` but does not provide _any_ web environment (mock or otherwise). NOTE: If your test is `@Transactional`, it rolls back the transaction at the end of each test method by default. However, as using this arrangement with either `RANDOM_PORT` or `DEFINED_PORT` implicitly provides a real servlet environment, the HTTP client and server run in separate threads and, thus, in separate transactions. Any transaction initiated on the server does not roll back in this case. NOTE: `@SpringBootTest` with `webEnvironment = WebEnvironment.RANDOM_PORT` will also start the management server on a separate random port if your application uses a different port for the management server. [[features.testing.spring-boot-applications.detecting-web-app-type]] ==== Detecting Web Application Type If Spring MVC is available, a regular MVC-based application context is configured. If you have only Spring WebFlux, we'll detect that and configure a WebFlux-based application context instead. If both are present, Spring MVC takes precedence. If you want to test a reactive web application in this scenario, you must set the configprop:spring.main.web-application-type[] property: [source,java,indent=0,subs=""verbatim""] ---- include::{docs-java}/features/testing/springbootapplications/detectingwebapptype/MyWebFluxTests.java[] ---- [[features.testing.spring-boot-applications.detecting-configuration]] ==== Detecting Test Configuration If you are familiar with the Spring Test Framework, you may be used to using `@ContextConfiguration(classes=...)` in order to specify which Spring `@Configuration` to load. Alternatively, you might have often used nested `@Configuration` classes within your test. When testing Spring Boot applications, this is often not required. Spring Boot's `@*Test` annotations search for your primary configuration automatically whenever you do not explicitly define one. The search algorithm works up from the package that contains the test until it finds a class annotated with `@SpringBootApplication` or `@SpringBootConfiguration`. As long as you <> in a sensible way, your main configuration is usually found. [NOTE] ==== If you use a <>, you should avoid adding configuration settings that are specific to a particular area on the <>. The underlying component scan configuration of `@SpringBootApplication` defines exclude filters that are used to make sure slicing works as expected. If you are using an explicit `@ComponentScan` directive on your `@SpringBootApplication`-annotated class, be aware that those filters will be disabled. If you are using slicing, you should define them again. ==== If you want to customize the primary configuration, you can use a nested `@TestConfiguration` class. Unlike a nested `@Configuration` class, which would be used instead of your application's primary configuration, a nested `@TestConfiguration` class is used in addition to your application's primary configuration. NOTE: Spring's test framework caches application contexts between tests. Therefore, as long as your tests share the same configuration (no matter how it is discovered), the potentially time-consuming process of loading the context happens only once. [[features.testing.spring-boot-applications.excluding-configuration]] ==== Excluding Test Configuration If your application uses component scanning (for example, if you use `@SpringBootApplication` or `@ComponentScan`), you may find top-level configuration classes that you created only for specific tests accidentally get picked up everywhere. As we <>, `@TestConfiguration` can be used on an inner class of a test to customize the primary configuration. When placed on a top-level class, `@TestConfiguration` indicates that classes in `src/test/java` should not be picked up by scanning. You can then import that class explicitly where it is required, as shown in the following example: [source,java,indent=0,subs=""verbatim""] ---- include::{docs-java}/features/testing/springbootapplications/excludingconfiguration/MyTests.java[] ---- NOTE: If you directly use `@ComponentScan` (that is, not through `@SpringBootApplication`) you need to register the `TypeExcludeFilter` with it. See {spring-boot-module-api}/context/TypeExcludeFilter.html[the Javadoc] for details. [[features.testing.spring-boot-applications.using-application-arguments]] ==== Using Application Arguments If your application expects <>, you can have `@SpringBootTest` inject them using the `args` attribute. [source,java,indent=0,subs=""verbatim""] ---- include::{docs-java}/features/testing/springbootapplications/usingapplicationarguments/MyApplicationArgumentTests.java[] ---- [[features.testing.spring-boot-applications.with-mock-environment]] ==== Testing with a mock environment By default, `@SpringBootTest` does not start the server. If you have web endpoints that you want to test against this mock environment, you can additionally configure {spring-framework-docs}/testing.html#spring-mvc-test-framework[`MockMvc`] as shown in the following example: [source,java,indent=0,subs=""verbatim""] ---- include::{docs-java}/features/testing/springbootapplications/withmockenvironment/MyMockMvcTests.java[] ---- TIP: If you want to focus only on the web layer and not start a complete `ApplicationContext`, consider <>. Alternatively, you can configure a {spring-framework-docs}/testing.html#webtestclient-tests[`WebTestClient`] as shown in the following example: [source,java,indent=0,subs=""verbatim""] ---- include::{docs-java}/features/testing/springbootapplications/withmockenvironment/MyMockWebTestClientTests.java[] ---- [TIP] ==== Testing within a mocked environment is usually faster than running with a full Servlet container. However, since mocking occurs at the Spring MVC layer, code that relies on lower-level Servlet container behavior cannot be directly tested with MockMvc. For example, Spring Boot's error handling is based on the ""`error page`"" support provided by the Servlet container. This means that, whilst you can test your MVC layer throws and handles exceptions as expected, you cannot directly test that a specific <> is rendered. If you need to test these lower-level concerns, you can start a fully running server as described in the next section. ==== [[features.testing.spring-boot-applications.with-running-server]] ==== Testing with a running server If you need to start a full running server, we recommend that you use random ports. If you use `@SpringBootTest(webEnvironment=WebEnvironment.RANDOM_PORT)`, an available port is picked at random each time your test runs. The `@LocalServerPort` annotation can be used to <> into your test. For convenience, tests that need to make REST calls to the started server can additionally `@Autowire` a {spring-framework-docs}/testing.html#webtestclient-tests[`WebTestClient`], which resolves relative links to the running server and comes with a dedicated API for verifying responses, as shown in the following example: [source,java,indent=0,subs=""verbatim""] ---- include::{docs-java}/features/testing/springbootapplications/withrunningserver/MyRandomPortWebTestClientTests.java[] ---- This setup requires `spring-webflux` on the classpath. If you can't or won't add webflux, Spring Boot also provides a `TestRestTemplate` facility: [source,java,indent=0,subs=""verbatim""] ---- include::{docs-java}/features/testing/springbootapplications/withrunningserver/MyRandomPortTestRestTemplateTests.java[] ---- [[features.testing.spring-boot-applications.customizing-web-test-client]] ==== Customizing WebTestClient To customize the `WebTestClient` bean, configure a `WebTestClientBuilderCustomizer` bean. Any such beans are called with the `WebTestClient.Builder` that is used to create the `WebTestClient`. [[features.testing.spring-boot-applications.jmx]] ==== Using JMX As the test context framework caches context, JMX is disabled by default to prevent identical components to register on the same domain. If such test needs access to an `MBeanServer`, consider marking it dirty as well: [source,java,indent=0,subs=""verbatim""] ---- include::{docs-java}/features/testing/springbootapplications/jmx/MyJmxTests.java[] ---- [[features.testing.spring-boot-applications.metrics]] ==== Using Metrics Regardless of your classpath, meter registries, except the in-memory backed, are not auto-configured when using `@SpringBootTest`. If you need to export metrics to a different backend as part of an integration test, annotate it with `@AutoConfigureMetrics`. [[features.testing.spring-boot-applications.mocking-beans]] ==== Mocking and Spying Beans When running tests, it is sometimes necessary to mock certain components within your application context. For example, you may have a facade over some remote service that is unavailable during development. Mocking can also be useful when you want to simulate failures that might be hard to trigger in a real environment. Spring Boot includes a `@MockBean` annotation that can be used to define a Mockito mock for a bean inside your `ApplicationContext`. You can use the annotation to add new beans or replace a single existing bean definition. The annotation can be used directly on test classes, on fields within your test, or on `@Configuration` classes and fields. When used on a field, the instance of the created mock is also injected. Mock beans are automatically reset after each test method. [NOTE] ==== If your test uses one of Spring Boot's test annotations (such as `@SpringBootTest`), this feature is automatically enabled. To use this feature with a different arrangement, listeners must be explicitly added, as shown in the following example: [source,java,indent=0,subs=""verbatim""] ---- include::{docs-java}/features/testing/springbootapplications/mockingbeans/listener/MyTests.java[] ---- ==== The following example replaces an existing `RemoteService` bean with a mock implementation: [source,java,indent=0,subs=""verbatim""] ---- include::{docs-java}/features/testing/springbootapplications/mockingbeans/bean/MyTests.java[] ---- NOTE: `@MockBean` cannot be used to mock the behavior of a bean that's exercised during application context refresh. By the time the test is executed, the application context refresh has completed and it is too late to configure the mocked behavior. We recommend using a `@Bean` method to create and configure the mock in this situation. Additionally, you can use `@SpyBean` to wrap any existing bean with a Mockito `spy`. See the {spring-boot-test-module-api}/mock/mockito/SpyBean.html[Javadoc] for full details. NOTE: CGLib proxies, such as those created for scoped beans, declare the proxied methods as `final`. This stops Mockito from functioning correctly as it cannot mock or spy on `final` methods in its default configuration. If you want to mock or spy on such a bean, configure Mockito to use its inline mock maker by adding `org.mockito:mockito-inline` to your application's test dependencies. This allows Mockito to mock and spy on `final` methods. NOTE: While Spring's test framework caches application contexts between tests and reuses a context for tests sharing the same configuration, the use of `@MockBean` or `@SpyBean` influences the cache key, which will most likely increase the number of contexts. TIP: If you are using `@SpyBean` to spy on a bean with `@Cacheable` methods that refer to parameters by name, your application must be compiled with `-parameters`. This ensures that the parameter names are available to the caching infrastructure once the bean has been spied upon. TIP: When you are using `@SpyBean` to spy on a bean that is proxied by Spring, you may need to remove Spring's proxy in some situations, for example when setting expectations using `given` or `when`. Use `AopTestUtils.getTargetObject(yourProxiedSpy)` to do so. [[features.testing.spring-boot-applications.autoconfigured-tests]] ==== Auto-configured Tests Spring Boot's auto-configuration system works well for applications but can sometimes be a little too much for tests. It often helps to load only the parts of the configuration that are required to test a ""`slice`"" of your application. For example, you might want to test that Spring MVC controllers are mapping URLs correctly, and you do not want to involve database calls in those tests, or you might want to test JPA entities, and you are not interested in the web layer when those tests run. The `spring-boot-test-autoconfigure` module includes a number of annotations that can be used to automatically configure such ""`slices`"". Each of them works in a similar way, providing a `@...Test` annotation that loads the `ApplicationContext` and one or more `@AutoConfigure...` annotations that can be used to customize auto-configuration settings. NOTE: Each slice restricts component scan to appropriate components and loads a very restricted set of auto-configuration classes. If you need to exclude one of them, most `@...Test` annotations provide an `excludeAutoConfiguration` attribute. Alternatively, you can use `@ImportAutoConfiguration#exclude`. NOTE: Including multiple ""`slices`"" by using several `@...Test` annotations in one test is not supported. If you need multiple ""`slices`"", pick one of the `@...Test` annotations and include the `@AutoConfigure...` annotations of the other ""`slices`"" by hand. TIP: It is also possible to use the `@AutoConfigure...` annotations with the standard `@SpringBootTest` annotation. You can use this combination if you are not interested in ""`slicing`"" your application but you want some of the auto-configured test beans. [[features.testing.spring-boot-applications.json-tests]] ==== Auto-configured JSON Tests To test that object JSON serialization and deserialization is working as expected, you can use the `@JsonTest` annotation. `@JsonTest` auto-configures the available supported JSON mapper, which can be one of the following libraries: * Jackson `ObjectMapper`, any `@JsonComponent` beans and any Jackson ``Module``s * `Gson` * `Jsonb` TIP: A list of the auto-configurations that are enabled by `@JsonTest` can be <>. If you need to configure elements of the auto-configuration, you can use the `@AutoConfigureJsonTesters` annotation. Spring Boot includes AssertJ-based helpers that work with the JSONAssert and JsonPath libraries to check that JSON appears as expected. The `JacksonTester`, `GsonTester`, `JsonbTester`, and `BasicJsonTester` classes can be used for Jackson, Gson, Jsonb, and Strings respectively. Any helper fields on the test class can be `@Autowired` when using `@JsonTest`. The following example shows a test class for Jackson: [source,java,indent=0,subs=""verbatim""] ---- include::{docs-java}/features/testing/springbootapplications/jsontests/MyJsonTests.java[] ---- NOTE: JSON helper classes can also be used directly in standard unit tests. To do so, call the `initFields` method of the helper in your `@Before` method if you do not use `@JsonTest`. If you're using Spring Boot's AssertJ-based helpers to assert on a number value at a given JSON path, you might not be able to use `isEqualTo` depending on the type. Instead, you can use AssertJ's `satisfies` to assert that the value matches the given condition. For instance, the following example asserts that the actual number is a float value close to `0.15` within an offset of `0.01`. [source,java,indent=0,subs=""verbatim""] ---- include::{docs-java}/features/testing/springbootapplications/jsontests/MyJsonAssertJTests.java[tag=*] ---- [[features.testing.spring-boot-applications.spring-mvc-tests]] ==== Auto-configured Spring MVC Tests To test whether Spring MVC controllers are working as expected, use the `@WebMvcTest` annotation. `@WebMvcTest` auto-configures the Spring MVC infrastructure and limits scanned beans to `@Controller`, `@ControllerAdvice`, `@JsonComponent`, `Converter`, `GenericConverter`, `Filter`, `HandlerInterceptor`, `WebMvcConfigurer`, and `HandlerMethodArgumentResolver`. Regular `@Component` and `@ConfigurationProperties` beans are not scanned when the `@WebMvcTest` annotation is used. `@EnableConfigurationProperties` can be used to include `@ConfigurationProperties` beans. TIP: A list of the auto-configuration settings that are enabled by `@WebMvcTest` can be <>. TIP: If you need to register extra components, such as the Jackson `Module`, you can import additional configuration classes by using `@Import` on your test. Often, `@WebMvcTest` is limited to a single controller and is used in combination with `@MockBean` to provide mock implementations for required collaborators. `@WebMvcTest` also auto-configures `MockMvc`. Mock MVC offers a powerful way to quickly test MVC controllers without needing to start a full HTTP server. TIP: You can also auto-configure `MockMvc` in a non-`@WebMvcTest` (such as `@SpringBootTest`) by annotating it with `@AutoConfigureMockMvc`. The following example uses `MockMvc`: [source,java,indent=0,subs=""verbatim""] ---- include::{docs-java}/features/testing/springbootapplications/springmvctests/MyControllerTests.java[] ---- TIP: If you need to configure elements of the auto-configuration (for example, when servlet filters should be applied) you can use attributes in the `@AutoConfigureMockMvc` annotation. If you use HtmlUnit or Selenium, auto-configuration also provides an HtmlUnit `WebClient` bean and/or a Selenium `WebDriver` bean. The following example uses HtmlUnit: [source,java,indent=0,subs=""verbatim""] ---- include::{docs-java}/features/testing/springbootapplications/springmvctests/MyHtmlUnitTests.java[] ---- NOTE: By default, Spring Boot puts `WebDriver` beans in a special ""`scope`"" to ensure that the driver exits after each test and that a new instance is injected. If you do not want this behavior, you can add `@Scope(""singleton"")` to your `WebDriver` `@Bean` definition. WARNING: The `webDriver` scope created by Spring Boot will replace any user defined scope of the same name. If you define your own `webDriver` scope you may find it stops working when you use `@WebMvcTest`. If you have Spring Security on the classpath, `@WebMvcTest` will also scan `WebSecurityConfigurer` beans. Instead of disabling security completely for such tests, you can use Spring Security's test support. More details on how to use Spring Security's `MockMvc` support can be found in this _<>_ how-to section. TIP: Sometimes writing Spring MVC tests is not enough; Spring Boot can help you run <>. [[features.testing.spring-boot-applications.spring-webflux-tests]] ==== Auto-configured Spring WebFlux Tests To test that {spring-framework-docs}/web-reactive.html[Spring WebFlux] controllers are working as expected, you can use the `@WebFluxTest` annotation. `@WebFluxTest` auto-configures the Spring WebFlux infrastructure and limits scanned beans to `@Controller`, `@ControllerAdvice`, `@JsonComponent`, `Converter`, `GenericConverter`, `WebFilter`, and `WebFluxConfigurer`. Regular `@Component` and `@ConfigurationProperties` beans are not scanned when the `@WebFluxTest` annotation is used. `@EnableConfigurationProperties` can be used to include `@ConfigurationProperties` beans. TIP: A list of the auto-configurations that are enabled by `@WebFluxTest` can be <>. TIP: If you need to register extra components, such as Jackson `Module`, you can import additional configuration classes using `@Import` on your test. Often, `@WebFluxTest` is limited to a single controller and used in combination with the `@MockBean` annotation to provide mock implementations for required collaborators. `@WebFluxTest` also auto-configures {spring-framework-docs}/testing.html#webtestclient[`WebTestClient`], which offers a powerful way to quickly test WebFlux controllers without needing to start a full HTTP server. TIP: You can also auto-configure `WebTestClient` in a non-`@WebFluxTest` (such as `@SpringBootTest`) by annotating it with `@AutoConfigureWebTestClient`. The following example shows a class that uses both `@WebFluxTest` and a `WebTestClient`: [source,java,indent=0,subs=""verbatim""] ---- include::{docs-java}/features/testing/springbootapplications/springwebfluxtests/MyControllerTests.java[] ---- TIP: This setup is only supported by WebFlux applications as using `WebTestClient` in a mocked web application only works with WebFlux at the moment. NOTE: `@WebFluxTest` cannot detect routes registered via the functional web framework. For testing `RouterFunction` beans in the context, consider importing your `RouterFunction` yourself via `@Import` or using `@SpringBootTest`. NOTE: `@WebFluxTest` cannot detect custom security configuration registered via a `@Bean` of type `SecurityWebFilterChain`. To include that in your test, you will need to import the configuration that registers the bean via `@Import` or use `@SpringBootTest`. TIP: Sometimes writing Spring WebFlux tests is not enough; Spring Boot can help you run <>. [[features.testing.spring-boot-applications.autoconfigured-spring-data-cassandra]] ==== Auto-configured Data Cassandra Tests You can use `@DataCassandraTest` to test Cassandra applications. By default, it configures a `CassandraTemplate`, scans for `@Table` classes, and configures Spring Data Cassandra repositories. Regular `@Component` and `@ConfigurationProperties` beans are not scanned when the `@DataCassandraTest` annotation is used. `@EnableConfigurationProperties` can be used to include `@ConfigurationProperties` beans. (For more about using Cassandra with Spring Boot, see ""<>"", earlier in this chapter.) TIP: A list of the auto-configuration settings that are enabled by `@DataCassandraTest` can be <>. The following example shows a typical setup for using Cassandra tests in Spring Boot: [source,java,indent=0,subs=""verbatim""] ---- include::{docs-java}/features/testing/springbootapplications/autoconfiguredspringdatacassandra/MyDataCassandraTests.java[] ---- [[features.testing.spring-boot-applications.autoconfigured-spring-data-jpa]] ==== Auto-configured Data JPA Tests You can use the `@DataJpaTest` annotation to test JPA applications. By default, it scans for `@Entity` classes and configures Spring Data JPA repositories. If an embedded database is available on the classpath, it configures one as well. SQL queries are logged by default by setting the `spring.jpa.show-sql` property to `true`. This can be disabled using the `showSql()` attribute of the annotation. Regular `@Component` and `@ConfigurationProperties` beans are not scanned when the `@DataJpaTest` annotation is used. `@EnableConfigurationProperties` can be used to include `@ConfigurationProperties` beans. TIP: A list of the auto-configuration settings that are enabled by `@DataJpaTest` can be <>. By default, data JPA tests are transactional and roll back at the end of each test. See the {spring-framework-docs}/testing.html#testcontext-tx-enabling-transactions[relevant section] in the Spring Framework Reference Documentation for more details. If that is not what you want, you can disable transaction management for a test or for the whole class as follows: [source,java,indent=0,subs=""verbatim""] ---- include::{docs-java}/features/testing/springbootapplications/autoconfiguredspringdatajpa/MyNonTransactionalTests.java[] ---- Data JPA tests may also inject a {spring-boot-test-autoconfigure-module-code}/orm/jpa/TestEntityManager.java[`TestEntityManager`] bean, which provides an alternative to the standard JPA `EntityManager` that is specifically designed for tests. If you want to use `TestEntityManager` outside of `@DataJpaTest` instances, you can also use the `@AutoConfigureTestEntityManager` annotation. A `JdbcTemplate` is also available if you need that. The following example shows the `@DataJpaTest` annotation in use: [source,java,indent=0,subs=""verbatim""] ---- include::{docs-java}/features/testing/springbootapplications/autoconfiguredspringdatajpa/withoutdb/MyRepositoryTests.java[] ---- In-memory embedded databases generally work well for tests, since they are fast and do not require any installation. If, however, you prefer to run tests against a real database you can use the `@AutoConfigureTestDatabase` annotation, as shown in the following example: [source,java,indent=0,subs=""verbatim""] ---- include::{docs-java}/features/testing/springbootapplications/autoconfiguredspringdatajpa/withdb/MyRepositoryTests.java[] ---- [[features.testing.spring-boot-applications.autoconfigured-jdbc]] ==== Auto-configured JDBC Tests `@JdbcTest` is similar to `@DataJpaTest` but is for tests that only require a `DataSource` and do not use Spring Data JDBC. By default, it configures an in-memory embedded database and a `JdbcTemplate`. Regular `@Component` and `@ConfigurationProperties` beans are not scanned when the `@JdbcTest` annotation is used. `@EnableConfigurationProperties` can be used to include `@ConfigurationProperties` beans. TIP: A list of the auto-configurations that are enabled by `@JdbcTest` can be <>. By default, JDBC tests are transactional and roll back at the end of each test. See the {spring-framework-docs}/testing.html#testcontext-tx-enabling-transactions[relevant section] in the Spring Framework Reference Documentation for more details. If that is not what you want, you can disable transaction management for a test or for the whole class, as follows: [source,java,indent=0,subs=""verbatim""] ---- include::{docs-java}/features/testing/springbootapplications/autoconfiguredjdbc/MyTransactionalTests.java[] ---- If you prefer your test to run against a real database, you can use the `@AutoConfigureTestDatabase` annotation in the same way as for `DataJpaTest`. (See ""<>"".) [[features.testing.spring-boot-applications.autoconfigured-spring-data-jdbc]] ==== Auto-configured Data JDBC Tests `@DataJdbcTest` is similar to `@JdbcTest` but is for tests that use Spring Data JDBC repositories. By default, it configures an in-memory embedded database, a `JdbcTemplate`, and Spring Data JDBC repositories. Regular `@Component` and `@ConfigurationProperties` beans are not scanned when the `@DataJdbcTest` annotation is used. `@EnableConfigurationProperties` can be used to include `@ConfigurationProperties` beans. TIP: A list of the auto-configurations that are enabled by `@DataJdbcTest` can be <>. By default, Data JDBC tests are transactional and roll back at the end of each test. See the {spring-framework-docs}/testing.html#testcontext-tx-enabling-transactions[relevant section] in the Spring Framework Reference Documentation for more details. If that is not what you want, you can disable transaction management for a test or for the whole test class as <>. If you prefer your test to run against a real database, you can use the `@AutoConfigureTestDatabase` annotation in the same way as for `DataJpaTest`. (See ""<>"".) [[features.testing.spring-boot-applications.autoconfigured-jooq]] ==== Auto-configured jOOQ Tests You can use `@JooqTest` in a similar fashion as `@JdbcTest` but for jOOQ-related tests. As jOOQ relies heavily on a Java-based schema that corresponds with the database schema, the existing `DataSource` is used. If you want to replace it with an in-memory database, you can use `@AutoConfigureTestDatabase` to override those settings. (For more about using jOOQ with Spring Boot, see ""<>"", earlier in this chapter.) Regular `@Component` and `@ConfigurationProperties` beans are not scanned when the `@JooqTest` annotation is used. `@EnableConfigurationProperties` can be used to include `@ConfigurationProperties` beans. TIP: A list of the auto-configurations that are enabled by `@JooqTest` can be <>. `@JooqTest` configures a `DSLContext`. The following example shows the `@JooqTest` annotation in use: [source,java,indent=0,subs=""verbatim""] ---- include::{docs-java}/features/testing/springbootapplications/autoconfiguredjooq/MyJooqTests.java[] ---- JOOQ tests are transactional and roll back at the end of each test by default. If that is not what you want, you can disable transaction management for a test or for the whole test class as <>. [[features.testing.spring-boot-applications.autoconfigured-spring-data-mongodb]] ==== Auto-configured Data MongoDB Tests You can use `@DataMongoTest` to test MongoDB applications. By default, it configures an in-memory embedded MongoDB (if available), configures a `MongoTemplate`, scans for `@Document` classes, and configures Spring Data MongoDB repositories. Regular `@Component` and `@ConfigurationProperties` beans are not scanned when the `@DataMongoTest` annotation is used. `@EnableConfigurationProperties` can be used to include `@ConfigurationProperties` beans. (For more about using MongoDB with Spring Boot, see ""<>"", earlier in this chapter.) TIP: A list of the auto-configuration settings that are enabled by `@DataMongoTest` can be <>. The following class shows the `@DataMongoTest` annotation in use: [source,java,indent=0,subs=""verbatim""] ---- include::{docs-java}/features/testing/springbootapplications/autoconfiguredspringdatamongodb/withoutdb/MyDataMongoDbTests.java[] ---- In-memory embedded MongoDB generally works well for tests, since it is fast and does not require any developer installation. If, however, you prefer to run tests against a real MongoDB server, you should exclude the embedded MongoDB auto-configuration, as shown in the following example: [source,java,indent=0,subs=""verbatim""] ---- include::{docs-java}/features/testing/springbootapplications/autoconfiguredspringdatamongodb/withdb/MyDataMongoDbTests.java[] ---- [[features.testing.spring-boot-applications.autoconfigured-spring-data-neo4j]] ==== Auto-configured Data Neo4j Tests You can use `@DataNeo4jTest` to test Neo4j applications. By default, it scans for `@Node` classes, and configures Spring Data Neo4j repositories. Regular `@Component` and `@ConfigurationProperties` beans are not scanned when the `@DataNeo4jTest` annotation is used. `@EnableConfigurationProperties` can be used to include `@ConfigurationProperties` beans. (For more about using Neo4J with Spring Boot, see ""<>"", earlier in this chapter.) TIP: A list of the auto-configuration settings that are enabled by `@DataNeo4jTest` can be <>. The following example shows a typical setup for using Neo4J tests in Spring Boot: [source,java,indent=0,subs=""verbatim""] ---- include::{docs-java}/features/testing/springbootapplications/autoconfiguredspringdataneo4j/propagation/MyDataNeo4jTests.java[] ---- By default, Data Neo4j tests are transactional and roll back at the end of each test. See the {spring-framework-docs}/testing.html#testcontext-tx-enabling-transactions[relevant section] in the Spring Framework Reference Documentation for more details. If that is not what you want, you can disable transaction management for a test or for the whole class, as follows: [source,java,indent=0,subs=""verbatim""] ---- include::{docs-java}/features/testing/springbootapplications/autoconfiguredspringdataneo4j/nopropagation/MyDataNeo4jTests.java[] ---- NOTE: Transactional tests are not supported with reactive access. If you are using this style, you must configure `@DataNeo4jTest` tests as described above. [[features.testing.spring-boot-applications.autoconfigured-spring-data-redis]] ==== Auto-configured Data Redis Tests You can use `@DataRedisTest` to test Redis applications. By default, it scans for `@RedisHash` classes and configures Spring Data Redis repositories. Regular `@Component` and `@ConfigurationProperties` beans are not scanned when the `@DataRedisTest` annotation is used. `@EnableConfigurationProperties` can be used to include `@ConfigurationProperties` beans. (For more about using Redis with Spring Boot, see ""<>"", earlier in this chapter.) TIP: A list of the auto-configuration settings that are enabled by `@DataRedisTest` can be <>. The following example shows the `@DataRedisTest` annotation in use: [source,java,indent=0,subs=""verbatim""] ---- include::{docs-java}/features/testing/springbootapplications/autoconfiguredspringdataredis/MyDataRedisTests.java[] ---- [[features.testing.spring-boot-applications.autoconfigured-spring-data-ldap]] ==== Auto-configured Data LDAP Tests You can use `@DataLdapTest` to test LDAP applications. By default, it configures an in-memory embedded LDAP (if available), configures an `LdapTemplate`, scans for `@Entry` classes, and configures Spring Data LDAP repositories. Regular `@Component` and `@ConfigurationProperties` beans are not scanned when the `@DataLdapTest` annotation is used. `@EnableConfigurationProperties` can be used to include `@ConfigurationProperties` beans. (For more about using LDAP with Spring Boot, see ""<>"", earlier in this chapter.) TIP: A list of the auto-configuration settings that are enabled by `@DataLdapTest` can be <>. The following example shows the `@DataLdapTest` annotation in use: [source,java,indent=0,subs=""verbatim""] ---- include::{docs-java}/features/testing/springbootapplications/autoconfiguredspringdataldap/inmemory/MyDataLdapTests.java[] ---- In-memory embedded LDAP generally works well for tests, since it is fast and does not require any developer installation. If, however, you prefer to run tests against a real LDAP server, you should exclude the embedded LDAP auto-configuration, as shown in the following example: [source,java,indent=0,subs=""verbatim""] ---- include::{docs-java}/features/testing/springbootapplications/autoconfiguredspringdataldap/server/MyDataLdapTests.java[] ---- [[features.testing.spring-boot-applications.autoconfigured-rest-client]] ==== Auto-configured REST Clients You can use the `@RestClientTest` annotation to test REST clients. By default, it auto-configures Jackson, GSON, and Jsonb support, configures a `RestTemplateBuilder`, and adds support for `MockRestServiceServer`. Regular `@Component` and `@ConfigurationProperties` beans are not scanned when the `@RestClientTest` annotation is used. `@EnableConfigurationProperties` can be used to include `@ConfigurationProperties` beans. TIP: A list of the auto-configuration settings that are enabled by `@RestClientTest` can be <>. The specific beans that you want to test should be specified by using the `value` or `components` attribute of `@RestClientTest`, as shown in the following example: [source,java,indent=0,subs=""verbatim""] ---- include::{docs-java}/features/testing/springbootapplications/autoconfiguredrestclient/MyRestClientTests.java[] ---- [[features.testing.spring-boot-applications.autoconfigured-spring-restdocs]] ==== Auto-configured Spring REST Docs Tests You can use the `@AutoConfigureRestDocs` annotation to use {spring-restdocs}[Spring REST Docs] in your tests with Mock MVC, REST Assured, or WebTestClient. It removes the need for the JUnit extension in Spring REST Docs. `@AutoConfigureRestDocs` can be used to override the default output directory (`target/generated-snippets` if you are using Maven or `build/generated-snippets` if you are using Gradle). It can also be used to configure the host, scheme, and port that appears in any documented URIs. [[features.testing.spring-boot-applications.autoconfigured-spring-restdocs.with-mock-mvc]] ===== Auto-configured Spring REST Docs Tests with Mock MVC `@AutoConfigureRestDocs` customizes the `MockMvc` bean to use Spring REST Docs when testing Servlet-based web applications. You can inject it by using `@Autowired` and use it in your tests as you normally would when using Mock MVC and Spring REST Docs, as shown in the following example: [source,java,indent=0,subs=""verbatim""] ---- include::{docs-java}/features/testing/springbootapplications/autoconfiguredspringrestdocs/withmockmvc/MyUserDocumentationTests.java[] ---- If you require more control over Spring REST Docs configuration than offered by the attributes of `@AutoConfigureRestDocs`, you can use a `RestDocsMockMvcConfigurationCustomizer` bean, as shown in the following example: [source,java,indent=0,subs=""verbatim""] ---- include::{docs-java}/features/testing/springbootapplications/autoconfiguredspringrestdocs/withmockmvc/MyRestDocsConfiguration.java[] ---- If you want to make use of Spring REST Docs support for a parameterized output directory, you can create a `RestDocumentationResultHandler` bean. The auto-configuration calls `alwaysDo` with this result handler, thereby causing each `MockMvc` call to automatically generate the default snippets. The following example shows a `RestDocumentationResultHandler` being defined: [source,java,indent=0,subs=""verbatim""] ---- include::{docs-java}/features/testing/springbootapplications/autoconfiguredspringrestdocs/withmockmvc/MyResultHandlerConfiguration.java[] ---- [[features.testing.spring-boot-applications.autoconfigured-spring-restdocs.with-web-test-client]] ===== Auto-configured Spring REST Docs Tests with WebTestClient `@AutoConfigureRestDocs` can also be used with `WebTestClient` when testing reactive web applications. You can inject it by using `@Autowired` and use it in your tests as you normally would when using `@WebFluxTest` and Spring REST Docs, as shown in the following example: [source,java,indent=0,subs=""verbatim""] ---- include::{docs-java}/features/testing/springbootapplications/autoconfiguredspringrestdocs/withwebtestclient/MyUsersDocumentationTests.java[] ---- If you require more control over Spring REST Docs configuration than offered by the attributes of `@AutoConfigureRestDocs`, you can use a `RestDocsWebTestClientConfigurationCustomizer` bean, as shown in the following example: [source,java,indent=0,subs=""verbatim""] ---- include::{docs-java}/features/testing/springbootapplications/autoconfiguredspringrestdocs/withwebtestclient/MyRestDocsConfiguration.java[] ---- [[features.testing.spring-boot-applications.autoconfigured-spring-restdocs.with-rest-assured]] ===== Auto-configured Spring REST Docs Tests with REST Assured `@AutoConfigureRestDocs` makes a `RequestSpecification` bean, preconfigured to use Spring REST Docs, available to your tests. You can inject it by using `@Autowired` and use it in your tests as you normally would when using REST Assured and Spring REST Docs, as shown in the following example: [source,java,indent=0,subs=""verbatim""] ---- include::{docs-java}/features/testing/springbootapplications/autoconfiguredspringrestdocs/withrestassured/MyUserDocumentationTests.java[] ---- If you require more control over Spring REST Docs configuration than offered by the attributes of `@AutoConfigureRestDocs`, a `RestDocsRestAssuredConfigurationCustomizer` bean can be used, as shown in the following example: [source,java,indent=0,subs=""verbatim""] ---- include::{docs-java}/features/testing/springbootapplications/autoconfiguredspringrestdocs/withrestassured/MyRestDocsConfiguration.java[] ---- [[features.testing.spring-boot-applications.autoconfigured-webservices]] ==== Auto-configured Spring Web Services Tests You can use `@WebServiceClientTest` to test applications that use call web services using the Spring Web Services project. By default, it configures a mock `WebServiceServer` bean and automatically customizes your `WebServiceTemplateBuilder`. (For more about using Web Services with Spring Boot, see ""<>"", earlier in this chapter.) TIP: A list of the auto-configuration settings that are enabled by `@WebServiceClientTest` can be <>. The following example shows the `@WebServiceClientTest` annotation in use: [source,java,indent=0,subs=""verbatim""] ---- include::{docs-java}/features/testing/springbootapplications/autoconfiguredwebservices/MyWebServiceClientTests.java[] ---- [[features.testing.spring-boot-applications.additional-autoconfiguration-and-slicing]] ==== Additional Auto-configuration and Slicing Each slice provides one or more `@AutoConfigure...` annotations that namely defines the auto-configurations that should be included as part of a slice. Additional auto-configurations can be added on a test-by-test basis by creating a custom `@AutoConfigure...` annotation or by adding `@ImportAutoConfiguration` to the test as shown in the following example: [source,java,indent=0,subs=""verbatim""] ---- include::{docs-java}/features/testing/springbootapplications/additionalautoconfigurationandslicing/MyJdbcTests.java[] ---- NOTE: Make sure to not use the regular `@Import` annotation to import auto-configurations as they are handled in a specific way by Spring Boot. Alternatively, additional auto-configurations can be added for any use of a slice annotation by registering them in `META-INF/spring.factories` as shown in the following example: [indent=0] ---- org.springframework.boot.test.autoconfigure.jdbc.JdbcTest=com.example.IntegrationAutoConfiguration ---- TIP: A slice or `@AutoConfigure...` annotation can be customized this way as long as it is meta-annotated with `@ImportAutoConfiguration`. [[features.testing.spring-boot-applications.user-configuration-and-slicing]] ==== User Configuration and Slicing If you <> in a sensible way, your `@SpringBootApplication` class is <> as the configuration of your tests. It then becomes important not to litter the application's main class with configuration settings that are specific to a particular area of its functionality. Assume that you are using Spring Batch and you rely on the auto-configuration for it. You could define your `@SpringBootApplication` as follows: [source,java,indent=0,subs=""verbatim""] ---- include::{docs-java}/features/testing/springbootapplications/userconfigurationandslicing/MyApplication.java[] ---- Because this class is the source configuration for the test, any slice test actually tries to start Spring Batch, which is definitely not what you want to do. A recommended approach is to move that area-specific configuration to a separate `@Configuration` class at the same level as your application, as shown in the following example: [source,java,indent=0,subs=""verbatim""] ---- include::{docs-java}/features/testing/springbootapplications/userconfigurationandslicing/MyBatchConfiguration.java[] ---- NOTE: Depending on the complexity of your application, you may either have a single `@Configuration` class for your customizations or one class per domain area. The latter approach lets you enable it in one of your tests, if necessary, with the `@Import` annotation. Test slices exclude `@Configuration` classes from scanning. For example, for a `@WebMvcTest`, the following configuration will not include the given `WebMvcConfigurer` bean in the application context loaded by the test slice: [source,java,indent=0,subs=""verbatim""] ---- include::{docs-java}/features/testing/springbootapplications/userconfigurationandslicing/MyWebConfiguration.java[] ---- The configuration below will, however, cause the custom `WebMvcConfigurer` to be loaded by the test slice. [source,java,indent=0,subs=""verbatim""] ---- include::{docs-java}/features/testing/springbootapplications/userconfigurationandslicing/MyWebMvcConfigurer.java[] ---- Another source of confusion is classpath scanning. Assume that, while you structured your code in a sensible way, you need to scan an additional package. Your application may resemble the following code: [source,java,indent=0,subs=""verbatim""] ---- include::{docs-java}/features/testing/springbootapplications/userconfigurationandslicing/scan/MyApplication.java[] ---- Doing so effectively overrides the default component scan directive with the side effect of scanning those two packages regardless of the slice that you chose. For instance, a `@DataJpaTest` seems to suddenly scan components and user configurations of your application. Again, moving the custom directive to a separate class is a good way to fix this issue. TIP: If this is not an option for you, you can create a `@SpringBootConfiguration` somewhere in the hierarchy of your test so that it is used instead. Alternatively, you can specify a source for your test, which disables the behavior of finding a default one. [[features.testing.spring-boot-applications.spock]] ==== Using Spock to Test Spring Boot Applications Spock 2.x can be used to test a Spring Boot application. To do so, add a dependency on Spock's `spock-spring` module to your application's build. `spock-spring` integrates Spring's test framework into Spock. See https://spockframework.org/spock/docs/2.0/modules.html#_spring_module[the documentation for Spock's Spring module] for further details. [[features.testing.utilities]] === Test Utilities A few test utility classes that are generally useful when testing your application are packaged as part of `spring-boot`. [[features.testing.utilities.config-data-application-context-initializer]] ==== ConfigDataApplicationContextInitializer `ConfigDataApplicationContextInitializer` is an `ApplicationContextInitializer` that you can apply to your tests to load Spring Boot `application.properties` files. You can use it when you do not need the full set of features provided by `@SpringBootTest`, as shown in the following example: [source,java,indent=0,subs=""verbatim""] ---- include::{docs-java}/features/testing/utilities/configdataapplicationcontextinitializer/MyConfigFileTests.java[] ---- NOTE: Using `ConfigDataApplicationContextInitializer` alone does not provide support for `@Value(""${...}"")` injection. Its only job is to ensure that `application.properties` files are loaded into Spring's `Environment`. For `@Value` support, you need to either additionally configure a `PropertySourcesPlaceholderConfigurer` or use `@SpringBootTest`, which auto-configures one for you. [[features.testing.utilities.test-property-values]] ==== TestPropertyValues `TestPropertyValues` lets you quickly add properties to a `ConfigurableEnvironment` or `ConfigurableApplicationContext`. You can call it with `key=value` strings, as follows: [source,java,indent=0,subs=""verbatim""] ---- include::{docs-java}/features/testing/utilities/testpropertyvalues/MyEnvironmentTests.java[] ---- [[features.testing.utilities.output-capture]] ==== OutputCapture `OutputCapture` is a JUnit `Extension` that you can use to capture `System.out` and `System.err` output. To use add `@ExtendWith(OutputCaptureExtension.class)` and inject `CapturedOutput` as an argument to your test class constructor or test method as follows: [source,java,indent=0,subs=""verbatim""] ---- include::{docs-java}/features/testing/utilities/outputcapture/MyOutputCaptureTests.java[] ---- [[features.testing.utilities.test-rest-template]] ==== TestRestTemplate `TestRestTemplate` is a convenience alternative to Spring's `RestTemplate` that is useful in integration tests. You can get a vanilla template or one that sends Basic HTTP authentication (with a username and password). In either case, the template is fault tolerant. This means that it behaves in a test-friendly way by not throwing exceptions on 4xx and 5xx errors. Instead, such errors can be detected via the returned `ResponseEntity` and its status code. TIP: Spring Framework 5.0 provides a new `WebTestClient` that works for <> and both <>. It provides a fluent API for assertions, unlike `TestRestTemplate`. It is recommended, but not mandatory, to use the Apache HTTP Client (version 4.3.2 or better). If you have that on your classpath, the `TestRestTemplate` responds by configuring the client appropriately. If you do use Apache's HTTP client, some additional test-friendly features are enabled: * Redirects are not followed (so you can assert the response location). * Cookies are ignored (so the template is stateless). `TestRestTemplate` can be instantiated directly in your integration tests, as shown in the following example: [source,java,indent=0,subs=""verbatim""] ---- include::{docs-java}/features/testing/utilities/testresttemplate/MyTests.java[] ---- Alternatively, if you use the `@SpringBootTest` annotation with `WebEnvironment.RANDOM_PORT` or `WebEnvironment.DEFINED_PORT`, you can inject a fully configured `TestRestTemplate` and start using it. If necessary, additional customizations can be applied through the `RestTemplateBuilder` bean. Any URLs that do not specify a host and port automatically connect to the embedded server, as shown in the following example: [source,java,indent=0,subs=""verbatim""] ---- include::{docs-java}/features/testing/utilities/testresttemplate/MySpringBootTests.java[] ---- ",12340,True,2620.8843983655297,median "[[netty-component]] = Netty Component //THIS FILE IS COPIED: EDIT THE SOURCE FILE: :page-source: components/camel-netty/src/main/docs/netty-component.adoc :docTitle: Netty :artifactId: camel-netty :description: Socket level networking using TCP or UDP with Netty 4.x. :since: 2.14 :supportLevel: Stable :component-header: Both producer and consumer are supported include::{cq-version}@camel-quarkus:ROOT:partial$reference/components/netty.adoc[opts=optional] *Since Camel {since}* *{component-header}* The Netty component in Camel is a socket communication component, based on the http://netty.io/[Netty] project version 4. + Netty is a NIO client server framework which enables quick and easy development of networkServerInitializerFactory applications such as protocol servers and clients. + Netty greatly simplifies and streamlines network programming such as TCP and UDP socket server. This camel component supports both producer and consumer endpoints. The Netty component has several options and allows fine-grained control of a number of TCP/UDP communication parameters (buffer sizes, keepAlives, tcpNoDelay, etc) and facilitates both In-Only and In-Out communication on a Camel route. Maven users will need to add the following dependency to their `pom.xml` for this component: [source,xml] ---- org.apache.camel camel-netty x.x.x ---- == URI format The URI scheme for a netty component is as follows [source,text] ---- netty:tcp://0.0.0.0:99999[?options] netty:udp://remotehost:99999/[?options] ---- This component supports producer and consumer endpoints for both TCP and UDP. You can append query options to the URI in the following format, `?option=value&option=value&...` == Options // component options: START The Netty component supports 73 options, which are listed below. [width=""100%"",cols=""2,5,^1,2"",options=""header""] |=== | Name | Description | Default | Type | *configuration* (common) | To use the NettyConfiguration as configuration when creating endpoints. | | NettyConfiguration | *disconnect* (common) | Whether or not to disconnect(close) from Netty Channel right after use. Can be used for both consumer and producer. | false | boolean | *keepAlive* (common) | Setting to ensure socket is not closed due to inactivity | true | boolean | *reuseAddress* (common) | Setting to facilitate socket multiplexing | true | boolean | *reuseChannel* (common) | This option allows producers and consumers (in client mode) to reuse the same Netty Channel for the lifecycle of processing the Exchange. This is useful if you need to call a server multiple times in a Camel route and want to use the same network connection. When using this, the channel is not returned to the connection pool until the Exchange is done; or disconnected if the disconnect option is set to true. The reused Channel is stored on the Exchange as an exchange property with the key NettyConstants#NETTY_CHANNEL which allows you to obtain the channel during routing and use it as well. | false | boolean | *sync* (common) | Setting to set endpoint as one-way or request-response | true | boolean | *tcpNoDelay* (common) | Setting to improve TCP protocol performance | true | boolean | *bridgeErrorHandler* (consumer) | Allows for bridging the consumer to the Camel routing Error Handler, which mean any exceptions occurred while the consumer is trying to pickup incoming messages, or the likes, will now be processed as a message and handled by the routing Error Handler. By default the consumer will use the org.apache.camel.spi.ExceptionHandler to deal with exceptions, that will be logged at WARN or ERROR level and ignored. | false | boolean | *broadcast* (consumer) | Setting to choose Multicast over UDP | false | boolean | *clientMode* (consumer) | If the clientMode is true, netty consumer will connect the address as a TCP client. | false | boolean | *reconnect* (consumer) | Used only in clientMode in consumer, the consumer will attempt to reconnect on disconnection if this is enabled | true | boolean | *reconnectInterval* (consumer) | Used if reconnect and clientMode is enabled. The interval in milli seconds to attempt reconnection | 10000 | int | *backlog* (consumer) | Allows to configure a backlog for netty consumer (server). Note the backlog is just a best effort depending on the OS. Setting this option to a value such as 200, 500 or 1000, tells the TCP stack how long the accept queue can be If this option is not configured, then the backlog depends on OS setting. | | int | *bossCount* (consumer) | When netty works on nio mode, it uses default bossCount parameter from Netty, which is 1. User can use this option to override the default bossCount from Netty | 1 | int | *bossGroup* (consumer) | Set the BossGroup which could be used for handling the new connection of the server side across the NettyEndpoint | | EventLoopGroup | *disconnectOnNoReply* (consumer) | If sync is enabled then this option dictates NettyConsumer if it should disconnect where there is no reply to send back. | true | boolean | *executorService* (consumer) | To use the given EventExecutorGroup. | | EventExecutorGroup | *maximumPoolSize* (consumer) | Sets a maximum thread pool size for the netty consumer ordered thread pool. The default size is 2 x cpu_core plus 1. Setting this value to eg 10 will then use 10 threads unless 2 x cpu_core plus 1 is a higher value, which then will override and be used. For example if there are 8 cores, then the consumer thread pool will be 17. This thread pool is used to route messages received from Netty by Camel. We use a separate thread pool to ensure ordering of messages and also in case some messages will block, then nettys worker threads (event loop) wont be affected. | | int | *nettyServerBootstrapFactory* (consumer) | To use a custom NettyServerBootstrapFactory | | NettyServerBootstrapFactory | *networkInterface* (consumer) | When using UDP then this option can be used to specify a network interface by its name, such as eth0 to join a multicast group. | | String | *noReplyLogLevel* (consumer) | If sync is enabled this option dictates NettyConsumer which logging level to use when logging a there is no reply to send back. There are 6 enums and the value can be one of: TRACE, DEBUG, INFO, WARN, ERROR, OFF | WARN | LoggingLevel | *serverClosedChannelException{zwsp}CaughtLogLevel* (consumer) | If the server (NettyConsumer) catches an java.nio.channels.ClosedChannelException then its logged using this logging level. This is used to avoid logging the closed channel exceptions, as clients can disconnect abruptly and then cause a flood of closed exceptions in the Netty server. There are 6 enums and the value can be one of: TRACE, DEBUG, INFO, WARN, ERROR, OFF | DEBUG | LoggingLevel | *serverExceptionCaughtLogLevel* (consumer) | If the server (NettyConsumer) catches an exception then its logged using this logging level. There are 6 enums and the value can be one of: TRACE, DEBUG, INFO, WARN, ERROR, OFF | WARN | LoggingLevel | *serverInitializerFactory* (consumer) | To use a custom ServerInitializerFactory | | ServerInitializerFactory | *usingExecutorService* (consumer) | Whether to use ordered thread pool, to ensure events are processed orderly on the same channel. | true | boolean | *connectTimeout* (producer) | Time to wait for a socket connection to be available. Value is in milliseconds. | 10000 | int | *lazyStartProducer* (producer) | Whether the producer should be started lazy (on the first message). By starting lazy you can use this to allow CamelContext and routes to startup in situations where a producer may otherwise fail during starting and cause the route to fail being started. By deferring this startup to be lazy then the startup failure can be handled during routing messages via Camel's routing error handlers. Beware that when the first message is processed then creating and starting the producer may take a little time and prolong the total processing time of the processing. | false | boolean | *requestTimeout* (producer) | Allows to use a timeout for the Netty producer when calling a remote server. By default no timeout is in use. The value is in milli seconds, so eg 30000 is 30 seconds. The requestTimeout is using Netty's ReadTimeoutHandler to trigger the timeout. | | long | *clientInitializerFactory* (producer) | To use a custom ClientInitializerFactory | | ClientInitializerFactory | *correlationManager* (producer) | To use a custom correlation manager to manage how request and reply messages are mapped when using request/reply with the netty producer. This should only be used if you have a way to map requests together with replies such as if there is correlation ids in both the request and reply messages. This can be used if you want to multiplex concurrent messages on the same channel (aka connection) in netty. When doing this you must have a way to correlate the request and reply messages so you can store the right reply on the inflight Camel Exchange before its continued routed. We recommend extending the TimeoutCorrelationManagerSupport when you build custom correlation managers. This provides support for timeout and other complexities you otherwise would need to implement as well. See also the producerPoolEnabled option for more details. | | NettyCamelStateCorrelationManager | *lazyChannelCreation* (producer) | Channels can be lazily created to avoid exceptions, if the remote server is not up and running when the Camel producer is started. | true | boolean | *producerPoolEnabled* (producer) | Whether producer pool is enabled or not. Important: If you turn this off then a single shared connection is used for the producer, also if you are doing request/reply. That means there is a potential issue with interleaved responses if replies comes back out-of-order. Therefore you need to have a correlation id in both the request and reply messages so you can properly correlate the replies to the Camel callback that is responsible for continue processing the message in Camel. To do this you need to implement NettyCamelStateCorrelationManager as correlation manager and configure it via the correlationManager option. See also the correlationManager option for more details. | true | boolean | *producerPoolMaxActive* (producer) | Sets the cap on the number of objects that can be allocated by the pool (checked out to clients, or idle awaiting checkout) at a given time. Use a negative value for no limit. | -1 | int | *producerPoolMaxIdle* (producer) | Sets the cap on the number of idle instances in the pool. | 100 | int | *producerPoolMinEvictableIdle* (producer) | Sets the minimum amount of time (value in millis) an object may sit idle in the pool before it is eligible for eviction by the idle object evictor. | 300000 | long | *producerPoolMinIdle* (producer) | Sets the minimum number of instances allowed in the producer pool before the evictor thread (if active) spawns new objects. | | int | *udpConnectionlessSending* (producer) | This option supports connection less udp sending which is a real fire and forget. A connected udp send receive the PortUnreachableException if no one is listen on the receiving port. | false | boolean | *useByteBuf* (producer) | If the useByteBuf is true, netty producer will turn the message body into ByteBuf before sending it out. | false | boolean | *hostnameVerification* ( security) | To enable/disable hostname verification on SSLEngine | false | boolean | *allowSerializedHeaders* (advanced) | Only used for TCP when transferExchange is true. When set to true, serializable objects in headers and properties will be added to the exchange. Otherwise Camel will exclude any non-serializable objects and log it at WARN level. | false | boolean | *autowiredEnabled* (advanced) | Whether autowiring is enabled. This is used for automatic autowiring options (the option must be marked as autowired) by looking up in the registry to find if there is a single instance of matching type, which then gets configured on the component. This can be used for automatic configuring JDBC data sources, JMS connection factories, AWS Clients, etc. | true | boolean | *channelGroup* (advanced) | To use a explicit ChannelGroup. | | ChannelGroup | *nativeTransport* (advanced) | Whether to use native transport instead of NIO. Native transport takes advantage of the host operating system and is only supported on some platforms. You need to add the netty JAR for the host operating system you are using. See more details at: \\http://netty.io/wiki/native-transports.html | false | boolean | *options* (advanced) | Allows to configure additional netty options using option. as prefix. For example option.child.keepAlive=false to set the netty option child.keepAlive=false. See the Netty documentation for possible options that can be used. | | Map | *receiveBufferSize* (advanced) | The TCP/UDP buffer sizes to be used during inbound communication. Size is bytes. | 65536 | int | *receiveBufferSizePredictor* (advanced) | Configures the buffer size predictor. See details at Jetty documentation and this mail thread. | | int | *sendBufferSize* (advanced) | The TCP/UDP buffer sizes to be used during outbound communication. Size is bytes. | 65536 | int | *transferExchange* (advanced) | Only used for TCP. You can transfer the exchange over the wire instead of just the body. The following fields are transferred: In body, Out body, fault body, In headers, Out headers, fault headers, exchange properties, exchange exception. This requires that the objects are serializable. Camel will exclude any non-serializable objects and log it at WARN level. | false | boolean | *udpByteArrayCodec* (advanced) | For UDP only. If enabled the using byte array codec instead of Java serialization protocol. | false | boolean | *workerCount* (advanced) | When netty works on nio mode, it uses default workerCount parameter from Netty (which is cpu_core_threads x 2). User can use this option to override the default workerCount from Netty. | | int | *workerGroup* (advanced) | To use a explicit EventLoopGroup as the boss thread pool. For example to share a thread pool with multiple consumers or producers. By default each consumer or producer has their own worker pool with 2 x cpu count core threads. | | EventLoopGroup | *allowDefaultCodec* (codec) | The netty component installs a default codec if both, encoder/decoder is null and textline is false. Setting allowDefaultCodec to false prevents the netty component from installing a default codec as the first element in the filter chain. | true | boolean | *autoAppendDelimiter* (codec) | Whether or not to auto append missing end delimiter when sending using the textline codec. | true | boolean | *decoderMaxLineLength* (codec) | The max line length to use for the textline codec. | 1024 | int | *decoders* (codec) | A list of decoders to be used. You can use a String which have values separated by comma, and have the values be looked up in the Registry. Just remember to prefix the value with # so Camel knows it should lookup. | | List | *delimiter* (codec) | The delimiter to use for the textline codec. Possible values are LINE and NULL. There are 2 enums and the value can be one of: LINE, NULL | LINE | TextLineDelimiter | *encoders* (codec) | A list of encoders to be used. You can use a String which have values separated by comma, and have the values be looked up in the Registry. Just remember to prefix the value with # so Camel knows it should lookup. | | List | *encoding* (codec) | The encoding (a charset name) to use for the textline codec. If not provided, Camel will use the JVM default Charset. | | String | *textline* (codec) | Only used for TCP. If no codec is specified, you can use this flag to indicate a text line based codec; if not specified or the value is false, then Object Serialization is assumed over TCP - however only Strings are allowed to be serialized by default. | false | boolean | *enabledProtocols* (security) | Which protocols to enable when using SSL | TLSv1,TLSv1.1,TLSv1.2 | String | *keyStoreFile* (security) | Client side certificate keystore to be used for encryption | | File | *keyStoreFormat* (security) | Keystore format to be used for payload encryption. Defaults to JKS if not set | | String | *keyStoreResource* (security) | Client side certificate keystore to be used for encryption. Is loaded by default from classpath, but you can prefix with classpath:, file:, or http: to load the resource from different systems. | | String | *needClientAuth* (security) | Configures whether the server needs client authentication when using SSL. | false | boolean | *passphrase* (security) | Password setting to use in order to encrypt/decrypt payloads sent using SSH | | String | *securityProvider* (security) | Security provider to be used for payload encryption. Defaults to SunX509 if not set. | | String | *ssl* (security) | Setting to specify whether SSL encryption is applied to this endpoint | false | boolean | *sslClientCertHeaders* (security) | When enabled and in SSL mode, then the Netty consumer will enrich the Camel Message with headers having information about the client certificate such as subject name, issuer name, serial number, and the valid date range. | false | boolean | *sslContextParameters* (security) | To configure security using SSLContextParameters | | SSLContextParameters | *sslHandler* (security) | Reference to a class that could be used to return an SSL Handler | | SslHandler | *trustStoreFile* (security) | Server side certificate keystore to be used for encryption | | File | *trustStoreResource* (security) | Server side certificate keystore to be used for encryption. Is loaded by default from classpath, but you can prefix with classpath:, file:, or http: to load the resource from different systems. | | String | *useGlobalSslContextParameters* (security) | Enable usage of global SSL context parameters. | false | boolean |=== // component options: END // endpoint options: START The Netty endpoint is configured using URI syntax: ---- netty:protocol://host:port ---- with the following path and query parameters: === Path Parameters (3 parameters): [width=""100%"",cols=""2,5,^1,2"",options=""header""] |=== | Name | Description | Default | Type | *protocol* | *Required* The protocol to use which can be tcp or udp. There are 2 enums and the value can be one of: tcp, udp | | String | *host* | *Required* The hostname. For the consumer the hostname is localhost or 0.0.0.0. For the producer the hostname is the remote host to connect to | | String | *port* | *Required* The host port number | | int |=== === Query Parameters (71 parameters): [width=""100%"",cols=""2,5,^1,2"",options=""header""] |=== | Name | Description | Default | Type | *disconnect* (common) | Whether or not to disconnect(close) from Netty Channel right after use. Can be used for both consumer and producer. | false | boolean | *keepAlive* (common) | Setting to ensure socket is not closed due to inactivity | true | boolean | *reuseAddress* (common) | Setting to facilitate socket multiplexing | true | boolean | *reuseChannel* (common) | This option allows producers and consumers (in client mode) to reuse the same Netty Channel for the lifecycle of processing the Exchange. This is useful if you need to call a server multiple times in a Camel route and want to use the same network connection. When using this, the channel is not returned to the connection pool until the Exchange is done; or disconnected if the disconnect option is set to true. The reused Channel is stored on the Exchange as an exchange property with the key NettyConstants#NETTY_CHANNEL which allows you to obtain the channel during routing and use it as well. | false | boolean | *sync* (common) | Setting to set endpoint as one-way or request-response | true | boolean | *tcpNoDelay* (common) | Setting to improve TCP protocol performance | true | boolean | *bridgeErrorHandler* (consumer) | Allows for bridging the consumer to the Camel routing Error Handler, which mean any exceptions occurred while the consumer is trying to pickup incoming messages, or the likes, will now be processed as a message and handled by the routing Error Handler. By default the consumer will use the org.apache.camel.spi.ExceptionHandler to deal with exceptions, that will be logged at WARN or ERROR level and ignored. | false | boolean | *broadcast* (consumer) | Setting to choose Multicast over UDP | false | boolean | *clientMode* (consumer) | If the clientMode is true, netty consumer will connect the address as a TCP client. | false | boolean | *reconnect* (consumer) | Used only in clientMode in consumer, the consumer will attempt to reconnect on disconnection if this is enabled | true | boolean | *reconnectInterval* (consumer) | Used if reconnect and clientMode is enabled. The interval in milli seconds to attempt reconnection | 10000 | int | *backlog* (consumer) | Allows to configure a backlog for netty consumer (server). Note the backlog is just a best effort depending on the OS. Setting this option to a value such as 200, 500 or 1000, tells the TCP stack how long the accept queue can be If this option is not configured, then the backlog depends on OS setting. | | int | *bossCount* (consumer) | When netty works on nio mode, it uses default bossCount parameter from Netty, which is 1. User can use this option to override the default bossCount from Netty | 1 | int | *bossGroup* (consumer) | Set the BossGroup which could be used for handling the new connection of the server side across the NettyEndpoint | | EventLoopGroup | *disconnectOnNoReply* (consumer) | If sync is enabled then this option dictates NettyConsumer if it should disconnect where there is no reply to send back. | true | boolean | *exceptionHandler* (consumer) | To let the consumer use a custom ExceptionHandler. Notice if the option bridgeErrorHandler is enabled then this option is not in use. By default the consumer will deal with exceptions, that will be logged at WARN or ERROR level and ignored. | | ExceptionHandler | *exchangePattern* (consumer) | Sets the exchange pattern when the consumer creates an exchange. There are 3 enums and the value can be one of: InOnly, InOut, InOptionalOut | | ExchangePattern | *nettyServerBootstrapFactory* (consumer) | To use a custom NettyServerBootstrapFactory | | NettyServerBootstrapFactory | *networkInterface* (consumer) | When using UDP then this option can be used to specify a network interface by its name, such as eth0 to join a multicast group. | | String | *noReplyLogLevel* (consumer) | If sync is enabled this option dictates NettyConsumer which logging level to use when logging a there is no reply to send back. There are 6 enums and the value can be one of: TRACE, DEBUG, INFO, WARN, ERROR, OFF | WARN | LoggingLevel | *serverClosedChannelException{zwsp}CaughtLogLevel* (consumer) | If the server (NettyConsumer) catches an java.nio.channels.ClosedChannelException then its logged using this logging level. This is used to avoid logging the closed channel exceptions, as clients can disconnect abruptly and then cause a flood of closed exceptions in the Netty server. There are 6 enums and the value can be one of: TRACE, DEBUG, INFO, WARN, ERROR, OFF | DEBUG | LoggingLevel | *serverExceptionCaughtLogLevel* (consumer) | If the server (NettyConsumer) catches an exception then its logged using this logging level. There are 6 enums and the value can be one of: TRACE, DEBUG, INFO, WARN, ERROR, OFF | WARN | LoggingLevel | *serverInitializerFactory* (consumer) | To use a custom ServerInitializerFactory | | ServerInitializerFactory | *usingExecutorService* (consumer) | Whether to use ordered thread pool, to ensure events are processed orderly on the same channel. | true | boolean | *connectTimeout* (producer) | Time to wait for a socket connection to be available. Value is in milliseconds. | 10000 | int | *lazyStartProducer* (producer) | Whether the producer should be started lazy (on the first message). By starting lazy you can use this to allow CamelContext and routes to startup in situations where a producer may otherwise fail during starting and cause the route to fail being started. By deferring this startup to be lazy then the startup failure can be handled during routing messages via Camel's routing error handlers. Beware that when the first message is processed then creating and starting the producer may take a little time and prolong the total processing time of the processing. | false | boolean | *requestTimeout* (producer) | Allows to use a timeout for the Netty producer when calling a remote server. By default no timeout is in use. The value is in milli seconds, so eg 30000 is 30 seconds. The requestTimeout is using Netty's ReadTimeoutHandler to trigger the timeout. | | long | *clientInitializerFactory* (producer) | To use a custom ClientInitializerFactory | | ClientInitializerFactory | *correlationManager* (producer) | To use a custom correlation manager to manage how request and reply messages are mapped when using request/reply with the netty producer. This should only be used if you have a way to map requests together with replies such as if there is correlation ids in both the request and reply messages. This can be used if you want to multiplex concurrent messages on the same channel (aka connection) in netty. When doing this you must have a way to correlate the request and reply messages so you can store the right reply on the inflight Camel Exchange before its continued routed. We recommend extending the TimeoutCorrelationManagerSupport when you build custom correlation managers. This provides support for timeout and other complexities you otherwise would need to implement as well. See also the producerPoolEnabled option for more details. | | NettyCamelStateCorrelationManager | *lazyChannelCreation* (producer) | Channels can be lazily created to avoid exceptions, if the remote server is not up and running when the Camel producer is started. | true | boolean | *producerPoolEnabled* (producer) | Whether producer pool is enabled or not. Important: If you turn this off then a single shared connection is used for the producer, also if you are doing request/reply. That means there is a potential issue with interleaved responses if replies comes back out-of-order. Therefore you need to have a correlation id in both the request and reply messages so you can properly correlate the replies to the Camel callback that is responsible for continue processing the message in Camel. To do this you need to implement NettyCamelStateCorrelationManager as correlation manager and configure it via the correlationManager option. See also the correlationManager option for more details. | true | boolean | *producerPoolMaxActive* (producer) | Sets the cap on the number of objects that can be allocated by the pool (checked out to clients, or idle awaiting checkout) at a given time. Use a negative value for no limit. | -1 | int | *producerPoolMaxIdle* (producer) | Sets the cap on the number of idle instances in the pool. | 100 | int | *producerPoolMinEvictableIdle* (producer) | Sets the minimum amount of time (value in millis) an object may sit idle in the pool before it is eligible for eviction by the idle object evictor. | 300000 | long | *producerPoolMinIdle* (producer) | Sets the minimum number of instances allowed in the producer pool before the evictor thread (if active) spawns new objects. | | int | *udpConnectionlessSending* (producer) | This option supports connection less udp sending which is a real fire and forget. A connected udp send receive the PortUnreachableException if no one is listen on the receiving port. | false | boolean | *useByteBuf* (producer) | If the useByteBuf is true, netty producer will turn the message body into ByteBuf before sending it out. | false | boolean | *hostnameVerification* ( security) | To enable/disable hostname verification on SSLEngine | false | boolean | *allowSerializedHeaders* (advanced) | Only used for TCP when transferExchange is true. When set to true, serializable objects in headers and properties will be added to the exchange. Otherwise Camel will exclude any non-serializable objects and log it at WARN level. | false | boolean | *channelGroup* (advanced) | To use a explicit ChannelGroup. | | ChannelGroup | *nativeTransport* (advanced) | Whether to use native transport instead of NIO. Native transport takes advantage of the host operating system and is only supported on some platforms. You need to add the netty JAR for the host operating system you are using. See more details at: \\http://netty.io/wiki/native-transports.html | false | boolean | *options* (advanced) | Allows to configure additional netty options using option. as prefix. For example option.child.keepAlive=false to set the netty option child.keepAlive=false. See the Netty documentation for possible options that can be used. | | Map | *receiveBufferSize* (advanced) | The TCP/UDP buffer sizes to be used during inbound communication. Size is bytes. | 65536 | int | *receiveBufferSizePredictor* (advanced) | Configures the buffer size predictor. See details at Jetty documentation and this mail thread. | | int | *sendBufferSize* (advanced) | The TCP/UDP buffer sizes to be used during outbound communication. Size is bytes. | 65536 | int | *synchronous* (advanced) | Sets whether synchronous processing should be strictly used | false | boolean | *transferExchange* (advanced) | Only used for TCP. You can transfer the exchange over the wire instead of just the body. The following fields are transferred: In body, Out body, fault body, In headers, Out headers, fault headers, exchange properties, exchange exception. This requires that the objects are serializable. Camel will exclude any non-serializable objects and log it at WARN level. | false | boolean | *udpByteArrayCodec* (advanced) | For UDP only. If enabled the using byte array codec instead of Java serialization protocol. | false | boolean | *workerCount* (advanced) | When netty works on nio mode, it uses default workerCount parameter from Netty (which is cpu_core_threads x 2). User can use this option to override the default workerCount from Netty. | | int | *workerGroup* (advanced) | To use a explicit EventLoopGroup as the boss thread pool. For example to share a thread pool with multiple consumers or producers. By default each consumer or producer has their own worker pool with 2 x cpu count core threads. | | EventLoopGroup | *allowDefaultCodec* (codec) | The netty component installs a default codec if both, encoder/decoder is null and textline is false. Setting allowDefaultCodec to false prevents the netty component from installing a default codec as the first element in the filter chain. | true | boolean | *autoAppendDelimiter* (codec) | Whether or not to auto append missing end delimiter when sending using the textline codec. | true | boolean | *decoderMaxLineLength* (codec) | The max line length to use for the textline codec. | 1024 | int | *decoders* (codec) | A list of decoders to be used. You can use a String which have values separated by comma, and have the values be looked up in the Registry. Just remember to prefix the value with # so Camel knows it should lookup. | | List | *delimiter* (codec) | The delimiter to use for the textline codec. Possible values are LINE and NULL. There are 2 enums and the value can be one of: LINE, NULL | LINE | TextLineDelimiter | *encoders* (codec) | A list of encoders to be used. You can use a String which have values separated by comma, and have the values be looked up in the Registry. Just remember to prefix the value with # so Camel knows it should lookup. | | List | *encoding* (codec) | The encoding (a charset name) to use for the textline codec. If not provided, Camel will use the JVM default Charset. | | String | *textline* (codec) | Only used for TCP. If no codec is specified, you can use this flag to indicate a text line based codec; if not specified or the value is false, then Object Serialization is assumed over TCP - however only Strings are allowed to be serialized by default. | false | boolean | *enabledProtocols* (security) | Which protocols to enable when using SSL | TLSv1,TLSv1.1,TLSv1.2 | String | *keyStoreFile* (security) | Client side certificate keystore to be used for encryption | | File | *keyStoreFormat* (security) | Keystore format to be used for payload encryption. Defaults to JKS if not set | | String | *keyStoreResource* (security) | Client side certificate keystore to be used for encryption. Is loaded by default from classpath, but you can prefix with classpath:, file:, or http: to load the resource from different systems. | | String | *needClientAuth* (security) | Configures whether the server needs client authentication when using SSL. | false | boolean | *passphrase* (security) | Password setting to use in order to encrypt/decrypt payloads sent using SSH | | String | *securityProvider* (security) | Security provider to be used for payload encryption. Defaults to SunX509 if not set. | | String | *ssl* (security) | Setting to specify whether SSL encryption is applied to this endpoint | false | boolean | *sslClientCertHeaders* (security) | When enabled and in SSL mode, then the Netty consumer will enrich the Camel Message with headers having information about the client certificate such as subject name, issuer name, serial number, and the valid date range. | false | boolean | *sslContextParameters* (security) | To configure security using SSLContextParameters | | SSLContextParameters | *sslHandler* (security) | Reference to a class that could be used to return an SSL Handler | | SslHandler | *trustStoreFile* (security) | Server side certificate keystore to be used for encryption | | File | *trustStoreResource* (security) | Server side certificate keystore to be used for encryption. Is loaded by default from classpath, but you can prefix with classpath:, file:, or http: to load the resource from different systems. | | String |=== // endpoint options: END == Registry based Options Codec Handlers and SSL Keystores can be enlisted in the Registry, such as in the Spring XML file. The values that could be passed in, are the following: [width=""100%"",cols=""10%,90%"",options=""header"",] |=== |Name |Description |`passphrase` |password setting to use in order to encrypt/decrypt payloads sent using SSH |`keyStoreFormat` |keystore format to be used for payload encryption. Defaults to ""JKS"" if not set |`securityProvider` |Security provider to be used for payload encryption. Defaults to ""SunX509"" if not set. |`keyStoreFile` |*deprecated:* Client side certificate keystore to be used for encryption |`trustStoreFile` |*deprecated:* Server side certificate keystore to be used for encryption |`keyStoreResource` |Client side certificate keystore to be used for encryption. Is loaded by default from classpath, but you can prefix with `""classpath:""`, `""file:""`, or `""http:""` to load the resource from different systems. |`trustStoreResource` |Server side certificate keystore to be used for encryption. Is loaded by default from classpath, but you can prefix with `""classpath:""`, `""file:""`, or `""http:""` to load the resource from different systems. |`sslHandler` |Reference to a class that could be used to return an SSL Handler |`encoder` |A custom `ChannelHandler` class that can be used to perform special marshalling of outbound payloads. Must override io.netty.channel.ChannelInboundHandlerAdapter. |`encoders` |A list of encoders to be used. You can use a String which have values separated by comma, and have the values be looked up in the Registry. Just remember to prefix the value with # so Camel knows it should lookup. |`decoder` |A custom `ChannelHandler` class that can be used to perform special marshalling of inbound payloads. Must override io.netty.channel.ChannelOutboundHandlerAdapter. |`decoders` |A list of decoders to be used. You can use a String which have values separated by comma, and have the values be looked up in the Registry. Just remember to prefix the value with # so Camel knows it should lookup. |=== [NOTE] ==== Read below about using non shareable encoders/decoders. ==== === Using non shareable encoders or decoders If your encoders or decoders are not shareable (e.g. they don't have the @Shareable class annotation), then your encoder/decoder must implement the `org.apache.camel.component.netty.ChannelHandlerFactory` interface, and return a new instance in the `newChannelHandler` method. This is to ensure the encoder/decoder can safely be used. If this is not the case, then the Netty component will log a WARN when an endpoint is created. The Netty component offers a `org.apache.camel.component.netty.ChannelHandlerFactories` factory class, that has a number of commonly used methods. == Sending Messages to/from a Netty endpoint === Netty Producer In Producer mode, the component provides the ability to send payloads to a socket endpoint using either TCP or UDP protocols (with optional SSL support). The producer mode supports both one-way and request-response based operations. === Netty Consumer In Consumer mode, the component provides the ability to: * listen on a specified socket using either TCP or UDP protocols (with optional SSL support), * receive requests on the socket using text/xml, binary and serialized object based payloads and * send them along on a route as message exchanges. The consumer mode supports both one-way and request-response based operations. == Examples === A UDP Netty endpoint using Request-Reply and serialized object payload Note that Object serialization is not allowed by default, and so a decoder must be configured. [source,java] ---- @BindToRegistry(""decoder"") public ChannelHandler getDecoder() throws Exception { return new DefaultChannelHandlerFactory() { @Override public ChannelHandler newChannelHandler() { return new DatagramPacketObjectDecoder(ClassResolvers.weakCachingResolver(null)); } }; } RouteBuilder builder = new RouteBuilder() { public void configure() { from(""netty:udp://0.0.0.0:5155?sync=true&decoders=#decoder"") .process(new Processor() { public void process(Exchange exchange) throws Exception { Poetry poetry = (Poetry) exchange.getIn().getBody(); // Process poetry in some way exchange.getOut().setBody(""Message received); } } } }; ---- === A TCP based Netty consumer endpoint using One-way communication [source,java] ---- RouteBuilder builder = new RouteBuilder() { public void configure() { from(""netty:tcp://0.0.0.0:5150"") .to(""mock:result""); } }; ---- === An SSL/TCP based Netty consumer endpoint using Request-Reply communication [[Netty-UsingtheJSSEConfigurationUtility]] Using the JSSE Configuration Utility The Netty component supports SSL/TLS configuration through the xref:manual::camel-configuration-utilities.adoc[Camel JSSE Configuration Utility]. This utility greatly decreases the amount of component specific code you need to write and is configurable at the endpoint and component levels. The following examples demonstrate how to use the utility with the Netty component. [[Netty-Programmaticconfigurationofthecomponent]] Programmatic configuration of the component [source,java] ---- KeyStoreParameters ksp = new KeyStoreParameters(); ksp.setResource(""/users/home/server/keystore.jks""); ksp.setPassword(""keystorePassword""); KeyManagersParameters kmp = new KeyManagersParameters(); kmp.setKeyStore(ksp); kmp.setKeyPassword(""keyPassword""); SSLContextParameters scp = new SSLContextParameters(); scp.setKeyManagers(kmp); NettyComponent nettyComponent = getContext().getComponent(""netty"", NettyComponent.class); nettyComponent.setSslContextParameters(scp); ---- [[Netty-SpringDSLbasedconfigurationofendpoint]] Spring DSL based configuration of endpoint [source,xml] ---- ... ... ... ... ---- [[Netty-UsingBasicSSLTLSconfigurationontheJettyComponent]] Using Basic SSL/TLS configuration on the Jetty Component [source,java] ---- Registry registry = context.getRegistry(); registry.bind(""password"", ""changeit""); registry.bind(""ksf"", new File(""src/test/resources/keystore.jks"")); registry.bind(""tsf"", new File(""src/test/resources/keystore.jks"")); context.addRoutes(new RouteBuilder() { public void configure() { String netty_ssl_endpoint = ""netty:tcp://0.0.0.0:5150?sync=true&ssl=true&passphrase=#password"" + ""&keyStoreFile=#ksf&trustStoreFile=#tsf""; String return_string = ""When You Go Home, Tell Them Of Us And Say,"" + ""For Your Tomorrow, We Gave Our Today.""; from(netty_ssl_endpoint) .process(new Processor() { public void process(Exchange exchange) throws Exception { exchange.getOut().setBody(return_string); } } } }); ---- [[Netty-GettingaccesstoSSLSessionandtheclientcertificate]] Getting access to SSLSession and the client certificate You can get access to the `javax.net.ssl.SSLSession` if you eg need to get details about the client certificate. When `ssl=true` then the xref:netty-component.adoc[Netty] component will store the `SSLSession` as a header on the Camel Message as shown below: [source,java] ---- SSLSession session = exchange.getIn().getHeader(NettyConstants.NETTY_SSL_SESSION, SSLSession.class); // get the first certificate which is client certificate javax.security.cert.X509Certificate cert = session.getPeerCertificateChain()[0]; Principal principal = cert.getSubjectDN(); ---- Remember to set `needClientAuth=true` to authenticate the client, otherwise `SSLSession` cannot access information about the client certificate, and you may get an exception `javax.net.ssl.SSLPeerUnverifiedException: peer not authenticated`. You may also get this exception if the client certificate is expired or not valid etc. [TIP] ==== The option `sslClientCertHeaders` can be set to `true` which then enriches the Camel Message with headers having details about the client certificate. For example the subject name is readily available in the header `CamelNettySSLClientCertSubjectName`. ==== === Using Multiple Codecs In certain cases it may be necessary to add chains of encoders and decoders to the netty pipeline. To add multpile codecs to a camel netty endpoint the 'encoders' and 'decoders' uri parameters should be used. Like the 'encoder' and 'decoder' parameters they are used to supply references (lists of ChannelUpstreamHandlers and ChannelDownstreamHandlers) that should be added to the pipeline. Note that if encoders is specified then the encoder param will be ignored, similarly for decoders and the decoder param. [NOTE] ==== Read further above about using non shareable encoders/decoders. ==== The lists of codecs need to be added to the Camel's registry so they can be resolved when the endpoint is created. [source,java] ---- ChannelHandlerFactory lengthDecoder = ChannelHandlerFactories.newLengthFieldBasedFrameDecoder(1048576, 0, 4, 0, 4); StringDecoder stringDecoder = new StringDecoder(); registry.bind(""length-decoder"", lengthDecoder); registry.bind(""string-decoder"", stringDecoder); LengthFieldPrepender lengthEncoder = new LengthFieldPrepender(4); StringEncoder stringEncoder = new StringEncoder(); registry.bind(""length-encoder"", lengthEncoder); registry.bind(""string-encoder"", stringEncoder); List decoders = new ArrayList(); decoders.add(lengthDecoder); decoders.add(stringDecoder); List encoders = new ArrayList(); encoders.add(lengthEncoder); encoders.add(stringEncoder); registry.bind(""encoders"", encoders); registry.bind(""decoders"", decoders); ---- Spring's native collections support can be used to specify the codec lists in an application context [source,xml] ---- ---- The bean names can then be used in netty endpoint definitions either as a comma separated list or contained in a List e.g. [source,java] ---- from(""direct:multiple-codec"").to(""netty:tcp://0.0.0.0:{{port}}?encoders=#encoders&sync=false""); from(""netty:tcp://0.0.0.0:{{port}}?decoders=#length-decoder,#string-decoder&sync=false"").to(""mock:multiple-codec""); ---- or via XML. [source,xml] ---- ---- == Closing Channel When Complete When acting as a server you sometimes want to close the channel when, for example, a client conversion is finished. + You can do this by simply setting the endpoint option `disconnect=true`. However you can also instruct Camel on a per message basis as follows. + To instruct Camel to close the channel, you should add a header with the key `CamelNettyCloseChannelWhenComplete` set to a boolean `true` value. + For instance, the example below will close the channel after it has written the bye message back to the client: [source,java] ---- from(""netty:tcp://0.0.0.0:8080"").process(new Processor() { public void process(Exchange exchange) throws Exception { String body = exchange.getIn().getBody(String.class); exchange.getOut().setBody(""Bye "" + body); // some condition which determines if we should close if (close) { exchange.getOut().setHeader(NettyConstants.NETTY_CLOSE_CHANNEL_WHEN_COMPLETE, true); } } }); ---- [[Netty-Addingcustomchannelpipelinefactoriestogaincompletecontroloveracreatedpipeline]] Adding custom channel pipeline factories to gain complete control over a created pipeline == Custom pipeline Custom channel pipelines provide complete control to the user over the handler/interceptor chain by inserting custom handler(s), encoder(s) & decoder(s) without having to specify them in the Netty Endpoint URL in a very simple way. In order to add a custom pipeline, a custom channel pipeline factory must be created and registered with the context via the context registry (Registry, or the camel-spring ApplicationContextRegistry etc). A custom pipeline factory must be constructed as follows * A Producer linked channel pipeline factory must extend the abstract class `ClientPipelineFactory`. * A Consumer linked channel pipeline factory must extend the abstract class `ServerInitializerFactory`. * The classes should override the initChannel() method in order to insert custom handler(s), encoder(s) and decoder(s). Not overriding the `initChannel()` method creates a pipeline with no handlers, encoders or decoders wired to the pipeline. The example below shows how ServerInitializerFactory factory may be created === Using custom pipeline factory [source,java] ---- public class SampleServerInitializerFactory extends ServerInitializerFactory { private int maxLineSize = 1024; protected void initChannel(Channel ch) throws Exception { ChannelPipeline channelPipeline = ch.pipeline(); channelPipeline.addLast(""encoder-SD"", new StringEncoder(CharsetUtil.UTF_8)); channelPipeline.addLast(""decoder-DELIM"", new DelimiterBasedFrameDecoder(maxLineSize, true, Delimiters.lineDelimiter())); channelPipeline.addLast(""decoder-SD"", new StringDecoder(CharsetUtil.UTF_8)); // here we add the default Camel ServerChannelHandler for the consumer, to allow Camel to route the message etc. channelPipeline.addLast(""handler"", new ServerChannelHandler(consumer)); } } ---- The custom channel pipeline factory can then be added to the registry and instantiated/utilized on a camel route in the following way [source,java] ---- Registry registry = camelContext.getRegistry(); ServerInitializerFactory factory = new TestServerInitializerFactory(); registry.bind(""spf"", factory); context.addRoutes(new RouteBuilder() { public void configure() { String netty_ssl_endpoint = ""netty:tcp://0.0.0.0:5150?serverInitializerFactory=#spf"" String return_string = ""When You Go Home, Tell Them Of Us And Say,"" + ""For Your Tomorrow, We Gave Our Today.""; from(netty_ssl_endpoint) .process(new Processor() { public void process(Exchange exchange) throws Exception { exchange.getOut().setBody(return_string); } } } }); ---- == Reusing Netty boss and worker thread pools Netty has two kind of thread pools: boss and worker. By default each Netty consumer and producer has their private thread pools. If you want to reuse these thread pools among multiple consumers or producers then the thread pools must be created and enlisted in the Registry. For example using Spring XML we can create a shared worker thread pool using the `NettyWorkerPoolBuilder` with 2 worker threads as shown below: [source,xml] ---- ---- [TIP] ==== For boss thread pool there is a `org.apache.camel.component.netty.NettyServerBossPoolBuilder` builder for Netty consumers, and a `org.apache.camel.component.netty.NettyClientBossPoolBuilder` for the Netty producers. ==== Then in the Camel routes we can refer to this worker pools by configuring the `workerPool` option in the URI as shown below: [source,xml] ---- ... ---- And if we have another route we can refer to the shared worker pool: [source,xml] ---- ... ---- and so forth. == Multiplexing concurrent messages over a single connection with request/reply When using Netty for request/reply messaging via the netty producer then by default each message is sent via a non-shared connection (pooled). This ensures that replies are automatic being able to map to the correct request thread for further routing in Camel. In other words correlation between request/reply messages happens out-of-the-box because the replies comes back on the same connection that was used for sending the request; and this connection is not shared with others. When the response comes back, the connection is returned back to the connection pool, where it can be reused by others. However if you want to multiplex concurrent request/responses on a single shared connection, then you need to turn off the connection pooling by setting `producerPoolEnabled=false`. Now this means there is a potential issue with interleaved responses if replies comes back out-of-order. Therefore you need to have a correlation id in both the request and reply messages so you can properly correlate the replies to the Camel callback that is responsible for continue processing the message in Camel. To do this you need to implement `NettyCamelStateCorrelationManager` as correlation manager and configure it via the `correlationManager=#myManager` option. [NOTE] ==== We recommend extending the `TimeoutCorrelationManagerSupport` when you build custom correlation managers. This provides support for timeout and other complexities you otherwise would need to implement as well. ==== You can find an example with the Apache Camel source code in the examples directory under the `camel-example-netty-custom-correlation` directory. include::{page-component-version}@camel-spring-boot::page$netty-starter.adoc[] ",12511,False,2349.3535966155887,median "= Runtime Component Operator This generic Operator is capable of deploying any application image and can be imported into any runtime-specific Operator as library of application capabilities. This architecture ensures compatibility and consistency between all runtime Operators, allowing everyone to benefit from the functionality added in this project. This documentation refers to the latest codebase. For documentation and samples of older releases, please check out the link:++https://github.com/application-stacks/runtime-component-operator/releases++[main releases] page and navigate the corresponding tag. == Operator installation Use the instructions for one of the link:++../deploy/releases++[releases] to install the operator into a Kubernetes cluster. The Runtime Component Operator can be installed to: * watch own namespace * watch another namespace * watch multiple namespaces * watch all namespaces in the cluster Appropriate cluster roles and bindings are required to watch another namespace, watch multiple namespaces or watch all namespaces. NOTE: The Runtime Component Operator can only interact with resources it is given permission to interact through link:++https://kubernetes.io/docs/reference/access-authn-authz/rbac/++[Role-based access control (RBAC)]. Some of the operator features described in this document require interacting with resources in other namespaces. In that case, the operator must be installed with correct `ClusterRole` definitions. == Overview The architecture of the Runtime Component Operator follows the basic controller pattern: the Operator container with the controller is deployed into a Pod and listens for incoming resources with `Kind: RuntimeComponent`. Creating a `RuntimeComponent` custom resource (CR) triggers the Runtime Component Operator to create, update or delete Kubernetes resources needed by the application to run on your cluster. Each instance of `RuntimeComponent` CR represents the application to be deployed on the cluster: [source,yaml] ---- apiVersion: app.stacks/v1beta1 kind: RuntimeComponent metadata: name: my-app spec: applicationImage: quay.io/my-repo/my-app:1.0 service: type: ClusterIP port: 9080 expose: true storage: size: 2Gi mountPath: ""/logs"" ---- == Configuration === Custom Resource Definition (CRD) The following table lists configurable parameters of the `RuntimeComponent` CRD. For complete OpenAPI v3 representation of these values please see link:++../deploy/crds/app.stacks_runtimecomponents_crd.yaml++[`RuntimeComponent` CRD]. Each `RuntimeComponent` CR must at least specify the `applicationImage` parameter. Specifying other parameters is optional. .Runtime Component Resource Definition |=== | Parameter | Description | `version` | The current version of the application. Label `app.kubernetes.io/version` will be added to all resources when the version is defined. | `serviceAccountName` | The name of the OpenShift service account to be used during deployment. | `applicationImage` | The Docker image name to be deployed. On OpenShift, it can also be set to `/[:]` to reference an image from an image stream. If `` and `` values are not defined, they default to the namespace of the CR and the value of `latest`, respectively. | `applicationName` | The name of the application this resource is part of. If not specified, it defaults to the name of the CR. | `createAppDefinition` | A boolean to toggle the automatic configuration of Kubernetes resources for the `RuntimeComponent` CR to allow creation of an application definition by link:++https://kappnav.io++[kAppNav]. The default value is `true`. See link:++#kubernetes-application-navigator-kappnav-support++[Application Navigator] for more information. | `pullPolicy` | The policy used when pulling the image. One of: `Always`, `Never`, and `IfNotPresent`. | `pullSecret` | If using a registry that requires authentication, the name of the secret containing credentials. | `initContainers` | The list of link:++https://v1-17.docs.kubernetes.io/docs/reference/generated/kubernetes-api/v1.17/#container-v1-core++[Init Container] definitions. | `sidecarContainers` | The list of `sidecar` containers. These are additional containers to be added to the pods. Note: Sidecar containers should not be named `app`. | `architecture` | An array of architectures to be considered for deployment. Their position in the array indicates preference. | `bindings.embedded` | A YAML object that represents a `ServiceBindingRequest` custom resource. | `bindings.autoDetect` | A boolean to toggle whether the operator should automatically detect and use a `ServiceBindingRequest` resource with `-binding` naming format. The default value for this parameter is `true`. | `bindings.resourceRef` | The name of a `ServiceBindingRequest` custom resource created manually in the same namespace as the application. | `bindings.expose.enabled` | A boolean to toggle whether the operator expose the application as a bindable service. The default value for this parameter is `false`. | `service.port` | The port exposed by the container. | `service.targetPort` | The port that the operator assigns to containers inside pods. Defaults to the value of `service.port`. | `service.portName` | The name for the port exposed by the container. | `service.ports` | An array consisting of service ports. | `service.type` | The Kubernetes link:++https://kubernetes.io/docs/concepts/services-networking/service/#publishing-services-service-types++[Service Type]. | `service.nodePort` | Node proxies this port into your service. Please note once this port is set to a non-zero value it cannot be reset to zero. | `service.annotations` | Annotations to be added to the service. | `service.certificate` | A YAML object that represents a link:++https://cert-manager.io/docs/reference/api-docs/#cert-manager.io/v1alpha2.CertificateSpec++[Certificate]. | `service.certificateSecretRef` | A name of a secret that already contains TLS key, certificate and CA to be mounted in the pod. | `service.provides.category` | Service binding type to be provided by this CR. At this time, the only allowed value is `openapi`. | `service.provides.protocol` | Protocol of the provided service. Defauts to `http`. | `service.provides.context` | Specifies context root of the service. | `service.provides.auth.username` | Optional value to specify username as link:++https://v1-17.docs.kubernetes.io/docs/reference/generated/kubernetes-api/v1.17/#secretkeyselector-v1-core++[SecretKeySelector]. | `service.provides.auth.password` | Optional value to specify password as link:++https://v1-17.docs.kubernetes.io/docs/reference/generated/kubernetes-api/v1.17/#secretkeyselector-v1-core++[SecretKeySelector]. | `service.consumes` | An array consisting of services to be consumed by the `RuntimeComponent`. | `service.consumes[].category` | The type of service binding to be consumed. At this time, the only allowed value is `openapi`. | `service.consumes[].name` | The name of the service to be consumed. If binding to a `RuntimeComponent`, then this would be the provider's CR name. | `service.consumes[].namespace` | The namespace of the service to be consumed. If binding to a `RuntimeComponent`, then this would be the provider's CR namespace. | `service.consumes[].mountPath` | Optional field to specify which location in the pod, service binding secret should be mounted. If not specified, the secret keys would be injected as environment variables. | `createKnativeService` | A boolean to toggle the creation of Knative resources and usage of Knative serving. | `expose` | A boolean that toggles the external exposure of this deployment via a Route or a Knative Route resource. | `deployment.updateStrategy` | A field to specify the update strategy of the deployment. For more information, see link:++https://kubernetes.io/docs/concepts/workloads/controllers/deployment/#strategy++[updateStrategy] | `deployment.updateStrategy.type` | The type of update strategy of the deployment. The type can be set to `RollingUpdate` or `Recreate`, where `RollingUpdate` is the default update strategy. | `statefulSet.updateStrategy` | A field to specify the update strategy of the StatefulSet. For more information, see link:++https://kubernetes.io/docs/concepts/workloads/controllers/statefulset/#update-strategies++[updateStrategy] | `statefulSet.updateStrategy.type` | The type of update strategy of the StatefulSet. The type can be set to `RollingUpdate` or `OnDelete`, where `RollingUpdate` is the default update strategy. | `replicas` | The static number of desired replica pods that run simultaneously. | `autoscaling.maxReplicas` | Required field for autoscaling. Upper limit for the number of pods that can be set by the autoscaler. It cannot be lower than the minimum number of replicas. | `autoscaling.minReplicas` | Lower limit for the number of pods that can be set by the autoscaler. | `autoscaling.targetCPUUtilizationPercentage` | Target average CPU utilization (represented as a percentage of requested CPU) over all the pods. | `resourceConstraints.requests.cpu` | The minimum required CPU core. Specify integers, fractions (e.g. 0.5), or millicore values(e.g. 100m, where 100m is equivalent to .1 core). Required field for autoscaling. | `resourceConstraints.requests.memory` | The minimum memory in bytes. Specify integers with one of these suffixes: E, P, T, G, M, K, or power-of-two equivalents: Ei, Pi, Ti, Gi, Mi, Ki. | `resourceConstraints.limits.cpu` | The upper limit of CPU core. Specify integers, fractions (e.g. 0.5), or millicores values(e.g. 100m, where 100m is equivalent to .1 core). | `resourceConstraints.limits.memory` | The memory upper limit in bytes. Specify integers with suffixes: E, P, T, G, M, K, or power-of-two equivalents: Ei, Pi, Ti, Gi, Mi, Ki. | `env` | An array of environment variables following the format of `{name, value}`, where value is a simple string. It may also follow the format of `{name, valueFrom}`, where valueFrom refers to a value in a `ConfigMap` or `Secret` resource. See link:++#environment-variables++[Environment variables] for more info. | `envFrom` | An array of references to `ConfigMap` or `Secret` resources containing environment variables. Keys from `ConfigMap` or `Secret` resources become environment variable names in your container. See link:++#environment-variables++[Environment variables] for more info. | `readinessProbe` | A YAML object configuring the link:++https://kubernetes.io/docs/tasks/configure-pod-container/configure-liveness-readiness-startup-probes/#define-readiness-probes++[Kubernetes readiness probe] that controls when the pod is ready to receive traffic. | `livenessProbe` | A YAML object configuring the link:++https://kubernetes.io/docs/tasks/configure-pod-container/configure-liveness-readiness-startup-probes/#define-a-liveness-http-request++[Kubernetes liveness probe] that controls when Kubernetes needs to restart the pod. | `startupProbe` | A YAML object configuring the link:++https://kubernetes.io/docs/tasks/configure-pod-container/configure-liveness-readiness-startup-probes/#define-startup-probes++[Kubernetes startup probe] that controls when Kubernetes needs to startup the pod on its first initialization. | `volumes` | A YAML object that represents a link:++https://kubernetes.io/docs/concepts/storage/volumes++[pod volume]. | `volumeMounts` | A YAML object that represents a link:++https://kubernetes.io/docs/concepts/storage/volumes/++[pod volumeMount]. | `storage.size` | A convenient field to set the size of the persisted storage. Can be overridden by the `storage.volumeClaimTemplate` property. | `storage.mountPath` | The directory inside the container where this persisted storage will be bound to. | `storage.volumeClaimTemplate` | A YAML object that represents a link:++https://kubernetes.io/docs/concepts/workloads/controllers/statefulset/#components++[volumeClaimTemplate] component of a `StatefulSet`. | `monitoring.labels` | Labels to set on link:++https://github.com/coreos/prometheus-operator/blob/master/Documentation/api.md#servicemonitor++[ServiceMonitor]. | `monitoring.endpoints` | A YAML snippet representing an array of link:++https://github.com/coreos/prometheus-operator/blob/master/Documentation/api.md#endpoint++[Endpoint] component from ServiceMonitor. | `route.annotations` | Annotations to be added to the Route. | `route.host` | Hostname to be used for the Route. | `route.path` | Path to be used for Route. | `route.termination` | TLS termination policy. Can be one of `edge`, `reencrypt` and `passthrough`. | `route.insecureEdgeTerminationPolicy` | HTTP traffic policy with TLS enabled. Can be one of `Allow`, `Redirect` and `None`. | `route.certificate` | A YAML object that represents a link:++https://cert-manager.io/docs/reference/api-docs/#cert-manager.io/v1alpha2.CertificateSpec++[Certificate]. | `route.certificateSecretRef` | A name of a secret that already contains TLS key, certificate and CA to be used in the route. Also can contain destination CA certificate. | `affinity.nodeAffinity` | A YAML object that represents a link:++https://v1-17.docs.kubernetes.io/docs/reference/generated/kubernetes-api/v1.17/#nodeaffinity-v1-core++[NodeAffinity]. | `affinity.nodeAffinityLabels` | A YAML object that contains set of required labels and their values. | `affinity.podAffinity` | A YAML object that represents a link:++https://v1-17.docs.kubernetes.io/docs/reference/generated/kubernetes-api/v1.17/#podaffinity-v1-core++[PodAffinity]. | `affinity.podAntiAffinity` | A YAML object that represents a link:++https://v1-17.docs.kubernetes.io/docs/reference/generated/kubernetes-api/v1.17/#podantiaffinity-v1-core++[PodAntiAffinity]. |=== === Basic usage To deploy a Docker image that contains a runtime component to a Kubernetes environment, you can use the following CR: [source,yaml] ---- apiVersion: app.stacks/v1beta1 kind: RuntimeComponent metadata: name: my-app spec: applicationImage: quay.io/my-repo/my-app:1.0 ---- The `applicationImage` value must be defined in the `RuntimeComponent` CR. On OpenShift, the operator tries to find an image stream name with the `applicationImage` value. The operator falls back to the registry lookup if it is not able to find any image stream that matches the value. If you want to distinguish an image stream called `my-company/my-app` (project: `my-company`, image stream name: `my-app`) from the Docker Hub `my-company/my-app` image, you can use the full image reference as `docker.io/my-company/my-app`. To get information on the deployed CR, use either of the following: [source,sh] ---- oc get runtimecomponent my-app oc get comp my-app ---- The short name for `runtimecomponent` is `comp`. === Image Streams To deploy an image from an image stream, use the following CR: [source,yaml] ---- apiVersion: app.stacks/v1beta1 kind: RuntimeComponent metadata: name: my-app spec: applicationImage: my-namespace/my-image-stream:1.0 ---- The previous example looks up the `1.0` tag from the `my-image-stream` image stream in the `my-namespace` project and populates the CR `.status.imageReference` field with the exact referenced image similar to the following one: `image-registry.openshift-image-registry.svc:5000/my-namespace/my-image-stream@sha256:8a829d579b114a9115c0a7172d089413c5d5dd6120665406aae0600f338654d8`. The operator watches the specified image stream and deploys new images as new ones are available for the specified tag. To reference an image stream, the `applicationImage` parameter must follow the `/[:]` format. If `` or `` is not specified, the operator defaults the values to the namespace of the CR and the value of `latest`, respectively. For example, the `applicationImage: my-image-stream` configuration is the same as the `applicationImage: my-namespace/my-image-stream:latest` configuration. The Operator tries to find an image stream name first with the `/[:]` format and falls back to the registry lookup if it is not able to find any image stream that matches the value. _This feature is only available if you are running on OKD or OpenShift._ NOTE: The operator requires `ClusterRole` permissions if the image stream resource is in another namespace. === Service account The operator can create a `ServiceAccount` resource when deploying a `RuntimeComponent` custom resource (CR). If `serviceAccountName` is not specified in a CR, the operator creates a service account with the same name as the CR (e.g. `my-app`). Users can also specify `serviceAccountName` when they want to create a service account manually. If applications require specific permissions but still want the operator to create a `ServiceAccount`, users can still manually create a role binding to bind a role to the service account created by the operator. To learn more about Role-based access control (RBAC), see Kubernetes link:++https://kubernetes.io/docs/reference/access-authn-authz/rbac/++[documentation]. === Labels By default, the operator adds the following labels into all resources created for a `RuntimeComponent` CR: .Default Labels |=== | Label | Default | Description | `app.kubernetes.io/instance` | `metadata.name` | A unique name or identifier for this component. This cannot be modified. | `app.kubernetes.io/name` | `metadata.name` | A name that represents this component. | `app.kubernetes.io/managed-by` | `runtime-component-operator` | The tool being used to manage this component. | `app.kubernetes.io/component` | `backend` | The type of component being created. See OpenShift link:++https://github.com/gorkem/app-labels/blob/master/labels-annotation-for-openshift.adoc#labels++[documentation] for full list. | `app.kubernetes.io/part-of` | `applicationName` | The name of the higher-level application this component is a part of. Configure this if the component is not a standalone application. | `app.kubernetes.io/version` | `version` | The version of the component. |=== You can set new labels in addition to the pre-existing ones or overwrite them, excluding the `app.kubernetes.io/instance` label. To set labels, specify them in your CR as key/value pairs. [source,yaml] ---- apiVersion: app.stacks/v1beta1 kind: RuntimeComponent metadata: name: my-app labels: my-label-key: my-label-value spec: applicationImage: quay.io/my-repo/my-app:1.0 ---- _After the initial deployment of `RuntimeComponent`, any changes to its labels would be applied only when one of the parameters from `spec` is updated._ ==== OpenShift Recommended Labels When running in OpenShift, there are additional labels and annotations that are standard on the platform. It is recommended that you overwrite our defaults where applicable and add any labels from the list that are not set by default using the above instructions. See link:++https://github.com/gorkem/app-labels/blob/master/labels-annotation-for-openshift.adoc#labels++[documentation] for a full list. === Annotations To add new annotations into all resources created for a `RuntimeComponent`, specify them in your CR as key/value pairs. Annotations specified in CR would override any annotations specified on a resource, except for the annotations set on `Service` using `service.annotations`. [source,yaml] ---- apiVersion: app.stacks/v1beta1 kind: RuntimeComponent metadata: name: my-app annotations: my-annotation-key: my-annotation-value spec: applicationImage: quay.io/my-repo/my-app:1.0 ---- _After the initial deployment of `RuntimeComponent`, any changes to its annotations would be applied only when one of the parameters from `spec` is updated._ ==== OpenShift Recommended Annotations When running in OpenShift, there are additional annotations that are standard on the platform. It is recommended that you overwrite our defaults where applicable and add any annotations from the list that are not set by default using the above instructions. See link:++https://github.com/gorkem/app-labels/blob/master/labels-annotation-for-openshift.adoc#labels++[documentation] for a full list. === Environment variables You can set environment variables for your application container. To set environment variables, specify `env` and/or `envFrom` fields in your CR. The environment variables can come directly from key/value pairs, `ConfigMap`s or `Secret`s. The environment variables set using the `env` or `envFrom` fields will override any environment variables specified in the container image. [source,yaml] ---- apiVersion: app.stacks/v1beta1 kind: RuntimeComponent metadata: name: my-app spec: applicationImage: quay.io/my-repo/my-app:1.0 env: - name: DB_NAME value: ""database"" - name: DB_PORT valueFrom: configMapKeyRef: name: db-config key: db-port - name: DB_USERNAME valueFrom: secretKeyRef: name: db-credential key: adminUsername - name: DB_PASSWORD valueFrom: secretKeyRef: name: db-credential key: adminPassword envFrom: - configMapRef: name: env-configmap - secretRef: name: env-secrets ---- Use `envFrom` to define all data in a `ConfigMap` or a `Secret` as environment variables in a container. Keys from `ConfigMap` or `Secret` resources become environment variable name in your container. === High availability Run multiple instances of your application for high availability using one of the following mechanisms: - specify a static number of instances to run at all times using `replicas` parameter. __OR__ - configure auto-scaling to create (and delete) instances based on resource consumption using the `autoscaling` parameter. - Parameters `autoscaling.maxReplicas` and `resourceConstraints.requests.cpu` MUST be specified for auto-scaling. === Service ports Runtime Component Operator allows you to provide multiple service ports in addition to the primary service port. The primary port is exposed from the container running the application and it's values are used to configure the Route (or Ingress), Service binding and Knative service. The primary service port can be configured using `service.port`, `service.targetPort`, `service.portName`, and `service.nodePort` parameters. You can also specify an alternative port for Service Monitor using the `monitoring.endpoints` parameter and specifying either the `port` or `targetPort` field, otherwise it defaults to the primary port. The primary port is under the `service` field and the additional ports can be specified using the `ports` field as shown below. [source,yaml] ---- apiVersion: app.stacks/v1beta1 kind: RuntimeComponent metadata: name: my-app spec: applicationImage: quay.io/my-repo/my-app:1.0 service: type: NodePort port: 9080 portName: http targetPort: 9080 nodePort: 30008 ports: - port: 9443 name: https monitoring: endpoints: - basicAuth: password: key: password name: metrics-secret username: key: username name: metrics-secret interval: 5s port: https scheme: HTTPS tlsConfig: insecureSkipVerify: true labels: app-monitoring: 'true' ---- === Persistence Runtime Component Operator is capable of creating a `StatefulSet` and `PersistentVolumeClaim` for each pod if storage is specified in the `RuntimeComponent` CR. Users also can provide mount points for their application. There are 2 ways to enable storage. ==== Basic storage With the `RuntimeComponent` CR definition below the operator will create `PersistentVolumeClaim` called `pvc` with the size of `1Gi` and `ReadWriteOnce` access mode. The operator will also create a volume mount for the `StatefulSet` mounting to `/data` folder. You can use `volumeMounts` field instead of `storage.mountPath` if you require to persist more then one folder. [source,yaml] ---- apiVersion: app.stacks/v1beta1 kind: RuntimeComponent metadata: name: my-app spec: applicationImage: quay.io/my-repo/my-app:1.0 storage: size: 1Gi mountPath: ""/data"" ---- ==== Advanced storage Runtime Component Operator allows users to provide entire `volumeClaimTemplate` for full control over automatically created `PersistentVolumeClaim`. It is also possible to create multiple volume mount points for persistent volume using `volumeMounts` field as shown below. You can still use `storage.mountPath` if you require only a single mount point. [source,yaml] ---- apiVersion: app.stacks/v1beta1 kind: RuntimeComponent metadata: name: my-app spec: applicationImage: quay.io/my-repo/my-app:1.0 volumeMounts: - name: pvc mountPath: /data_1 subPath: data_1 - name: pvc mountPath: /data_2 subPath: data_2 storage: volumeClaimTemplate: metadata: name: pvc spec: accessModes: - ""ReadWriteMany"" storageClassName: 'glusterfs' resources: requests: storage: 1Gi ---- === Service binding ==== Service Binding Operator The link:++https://github.com/redhat-developer/service-binding-operator++[Service Binding Operator] enables application developers to bind applications together with operator-managed backing services. This can be achieved by creating a `ServiceBindingRequest` custom resource. For the Runtime Component Operator to pass the binding information to the application, define your `ServiceBindingRequest` custom resource in one of the following two ways: . Define the `ServiceBindingRequest` custom resource YAML within the `bindings.embedded` parameter in your `RuntimeComponent` custom resource. . Create the `ServiceBindingRequest` custom resource manually and either refer to it explicitly in your `RuntimeComponent` custom resource or let the operator detect it automatically. The auto-detection mechanism works only if the `ServiceBindingRequest` custom resource follows the `-binding` naming convention. ===== Embedding the Service Binding resource Define your `ServiceBindingRequest` custom resource within your `RuntimeComponent` custom resource: [source,yaml] ---- apiVersion: app.stacks/v1beta1 kind: RuntimeComponent metadata: name: my-app spec: applicationImage: quay.io/my-repo/my-app:1.0 bindings: embedded: apiVersion: apps.openshift.io/v1alpha1 kind: ServiceBindingRequest spec: backingServiceSelectors: - group: kafka.strimzi.io kind: Kafka resourceRef: my-cluster version: v1beta1 ---- After the Runtime Component Operator processes the `RuntimeComponent` custom resource, it creates a `ServiceBindingRequest` custom resource named `my-app-binding`. After the Service Binding Operator processes the `my-app` custom resource of the `ServiceBindingRequest` type, it creates a `Secret` object. The `Secret` resource contains binding information that the backing service provides. The Runtime Component Operator injects the `Secret` resource as an environment variable into application pods. The YAML definition specified in the `bindings.embedded` parameter must not include a `metadata` section because the Runtime Component operator adds a `metadata` section. If the YAML definition does not include an `apiVersion` field or a `kind` field, the Runtime Component operator uses the default `GroupVersionKind` value specified in the Operator Config Map. ===== Creating the Service Binding resource externally Create your `ServiceBindingRequest` custom resource in a separate YAML definition and then refer to the resource within your `RuntimeComponent` custom resource: [source,yaml] ---- apiVersion: app.stacks/v1beta1 kind: RuntimeComponent metadata: name: my-app spec: applicationImage: quay.io/my-repo/my-app:1.0 bindings: resourceRef: my-binding ---- After the Service Binding Operator, as defined previously, processes the `my-binding` custom resource of the `ServiceBindingRequest` type, it creates a `Secret` object. The `Secret` resource contains binding information that the backing service provides. The Runtime Component Operator injects the `Secret` resource as an environment variable into application pods. The Runtime Component Operator can also _automatically detect_ if a `ServiceBindingRequest` custom resource exists in the application namespace and is named `-binding` (e.g. `my-app-binding`). If the operator detects the custom resource, it injects the binding secret into the application container. Users can turn off the auto-detection mechanism by setting the `bindings.autoDetect` parameter to a value of `false`. The `bindings.resourceRef` parameter takes precedence over the `bindings.autoDetect` parameter. In other words, the Runtime Component Operator, injects secrets from the `my-binding` resource, even if a `ServiceBindingRequest` resource named `my-app-binding` exists: [source,yaml] ---- bindings: autoDetect: true resourceRef: my-binding ---- _This feature is only available if you have Service Binding Operator installed on your cluster._ ==== Exposing `RuntimeComponent` applications as Provisioned Services A `RuntimeComponent` application can be configured to behave as a link:++https://github.com/k8s-service-bindings/spec#provisioned-service++[Provisioned Service] defined by the link:++https://github.com/k8s-service-bindings/spec++[Service Binding Specification]. According to the specification, a Provisioned Service resource must define a `.status.binding.name` which is a reference to a Secret. To expose your application as a Provisioned Service, set the `.spec.bindings.expose.enabled` parameter to a value of `true`. The Runtime Component Operator creates a *binding secret* named `-expose-binding` and adds the following entries to the secret: `host`, `port`, `protocol`, `basePath` and `uri`. To override the default values for the entries in the binding secret or to add new entries to the secret, create an *override secret* named `-expose-binding-override` and add any entries to the secret. The operator reads the content of the override secret and overrides the default values in the binding secret. Once a `RuntimeComponent` application is exposed as a Provisioned Service, a service binding request can refer to the application as a backing service. ==== Binding to `RuntimeComponent` applications Runtime Component Operator can be used to help with service binding in a cluster. The operator creates a secret on behalf of the **provider** `RuntimeComponent` and injects the secret into pods of the **consumer** `RuntimeComponent` as either environment variable or mounted files. See link:++https://docs.google.com/document/d/1riOX0iTnBBJpTKAHcQShYVMlgkaTNKb4m8fY7W1GqMA/edit++[Runtime Component Operator Design for Service Binding] for more information on the architecture. At this time, the only supported service binding type is `openapi`. The provider lists information about the REST API it provides: [source,yaml] ---- apiVersion: app.stacks/v1beta1 kind: RuntimeComponent metadata: name: my-provider namespace: pro-namespace spec: applicationImage: quay.io/my-repo/my-provider:1.0 service: port: 3000 provides: category: openapi context: /my-context auth: password: name: my-secret key: password username: name: my-secret key: username --- kind: Secret apiVersion: v1 metadata: name: my-secret namespace: pro-namespace data: password: bW9vb29vb28= username: dGhlbGF1Z2hpbmdjb3c= type: Opaque ---- And the consumer lists the services it is intending to consume: [source,yaml] ---- apiVersion: app.stacks/v1beta1 kind: RuntimeComponent metadata: name: my-consumer namespace: con-namespace spec: applicationImage: quay.io/my-repo/my-consumer:1.0 expose: true service: port: 9080 consumes: - category: openapi name: my-provider namespace: pro-namespace mountPath: /sample ---- In the above example, the operator creates a secret named `pro-namespace-my-provider` and adds the following key-value pairs: `username`, `password`, `url`, `context`, `protocol` and `hostname`. The `url` value format is `://..svc.cluster.local:/`. Since the provider and the consumer are in two different namespaces, the operator copies the provider secret into consumer's namespace. The operator then mounts the provider secret into a directory with the pattern `//` on application container within pods. In the above example, the secret will be serialized into `/sample/pro-namespace/my-provider`, which means we will have a file for each key, where the filename is the key and the content is the key's value. If the `namespace` is not provided in the above example under `consumes`, then the operator mounts the provider secret into a directory with pattern `/`. If consumer's CR does not include `mountPath`, the secret will be bound to environment variables with the pattern `__`, and the value of that env var is the key’s value. Due to syntax restrictions for Kubernetes environment variables, the string representing the namespace and the string representing the service name will have to be normalized by turning any non-`[azAZ09]` characters to become an underscore `(_)` character. NOTE: The operator requires `ClusterRole` permissions if the provider application is in another namespace. === Monitoring Runtime Component Operator can create a `ServiceMonitor` resource to integrate with `Prometheus Operator`. _This feature does not support integration with Knative Service. Prometheus Operator is required to use ServiceMonitor._ ==== Basic monitoring specification At minimum, a label needs to be provided that Prometheus expects to be set on `ServiceMonitor` objects. In this case, it is `apps-prometheus`. [source,yaml] ---- apiVersion: app.stacks/v1beta1 kind: RuntimeComponent metadata: name: my-app spec: applicationImage: quay.io/my-repo/my-app:1.0 monitoring: labels: apps-prometheus: '' ---- ==== Advanced monitoring specification For advanced scenarios, it is possible to set many `ServicerMonitor` settings such as authentication secret using link:++https://github.com/coreos/prometheus-operator/blob/master/Documentation/api.md#endpoint++[Prometheus Endpoint] [source,yaml] ---- apiVersion: app.stacks/v1beta1 kind: RuntimeComponent metadata: name: my-app spec: applicationImage: quay.io/my-repo/my-app:1.0 monitoring: labels: app-prometheus: '' endpoints: - interval: '30s' basicAuth: username: key: username name: metrics-secret password: key: password name: metrics-secret tlsConfig: insecureSkipVerify: true ---- === Knative support Runtime Component Operator can deploy serverless applications with link:++https://knative.dev/docs/++[Knative] on a Kubernetes cluster. To achieve this, the operator creates a link:++https://github.com/knative/serving/blob/master/docs/spec/spec.md#service++[Knative `Service`] resource which manages the whole life cycle of a workload. To create Knative service, set `createKnativeService` to `true`: [source,yaml] ---- apiVersion: app.stacks/v1beta1 kind: RuntimeComponent metadata: name: my-app spec: applicationImage: quay.io/my-repo/my-app:1.0 createKnativeService: true ---- By setting this parameter, the operator creates a Knative service in the cluster and populates the resource with applicable `RuntimeComponent` fields. Also, it ensures non-Knative resources including Kubernetes `Service`, `Route`, `Deployment` and etc. are deleted. The CRD fields which are used to populate the Knative service resource include `applicationImage`, `serviceAccountName`, `livenessProbe`, `readinessProbe`, `service.Port`, `volumes`, `volumeMounts`, `env`, `envFrom`, `pullSecret` and `pullPolicy`. `startupProbe` is not fully supported by Knative and it will not apply when Knative service is enabled. For more details on how to configure Knative for tasks such as enabling HTTPS connections and setting up a custom domain, checkout link:++https://knative.dev/docs/serving/++[Knative Documentation]. _Autoscaling related fields in `RuntimeComponent` are not used to configure Knative Pod Autoscaler (KPA). To learn more about how to configure KPA, see link:++https://knative.dev/docs/serving/configuring-the-autoscaler/++[Configuring the Autoscaler]._ _This feature is only available if you have Knative installed on your cluster._ === Exposing service externally ==== Non-Knative deployment (Route) To expose your application externally, set `expose` to `true`: [source,yaml] ---- apiVersion: app.stacks/v1beta1 kind: RuntimeComponent metadata: name: my-app spec: applicationImage: quay.io/my-repo/my-app:1.0 expose: true ---- By setting this parameter, the operator creates an unsecured route based on your application service. Setting this parameter is the same as running `oc expose service `. To create a secured HTTPS route, see the link:++#certificate-manager-integration++[Certificate Manager Integration] section for more information. _This feature is only available if you are running on OKD or OpenShift._ ==== Non-Knative deployment (Ingress) Before you can use the Ingress resource to expose your cluster, you must install an ingress controller, such a Nginx or Traefik. _The Ingress resource is created only if the `Route` resource is not available._ To use the Ingress resource, set the `defaultHostName` variable in the _runtime-component-operator_ ConfigMap object to a host name such as _mycompany.com_ ===== Simple Ingress that uses `defaultHostName` and no `TLS`: [source,yaml] ---- apiVersion: app.stacks/v1beta1 kind: RuntimeComponent metadata: name: my-app namespace: backend spec: applicationImage: quay.io/my-repo/my-app:1.0 expose: true ---- With default hostname of _mycompany.com_, the application is available at the http://my-app-backend.mycompany.com URL. ===== Enable TLS and generate a certificate by using the cert-manager controller: _Note: You must install the cert-manager controller to automatically generate a custom certificate for the ingress controller._ [source,yaml] ---- apiVersion: app.stacks/v1beta1 kind: RuntimeComponent metadata: name: my-app namespace: backend spec: applicationImage: quay.io/my-repo/my-app:1.0 expose: true route: certificate: {} ---- ===== Advanced Ingress configuration: Most of the Ingress configuraiton is achieved through annotations. Annotations such as Nginx, HAProxy, Traefik, and others are specific to the ingress controller implementation. You can provide an existing TLS secret and set a custom hostname. [source,yaml] ---- apiVersion: app.stacks/v1beta1 kind: RuntimeComponent metadata: name: my-app namespace: backend spec: applicationImage: quay.io/my-repo/my-app:1.0 expose: true route: annotations: # You can use this annotation to specify the name of the ingress controller to use. # You can install multiple ingress controllers to address different types of incoming traffic such as an external or internal DNS. kubernetes.io/ingress.class: ""nginx"" # The following nginx annotation enables a secure pod connection: nginx.ingress.kubernetes.io/ssl-redirect: true nginx.ingress.kubernetes.io/backend-protocol: ""HTTPS"" # The following traefik annotation enables a secure pod connection: traefik.ingress.kubernetes.io/service.serversscheme: https # Use a custom hostname for the Ingress host: app-v1.mycompany.com # Reference a pre-existing TLS secret: certificateSecretRef: mycompany-tls ---- ==== Knative deployment To expose your application as a Knative service externally, set `expose` to `true`: [source,yaml] ---- apiVersion: app.stacks/v1beta1 kind: RuntimeComponent metadata: name: my-app spec: applicationImage: quay.io/my-repo/my-app:1.0 createKnativeService: true expose: true ---- When `expose` is **not** set to `true`, the Knative service is labeled with `serving.knative.dev/visibility=cluster-local` which makes the Knative route to only be available on the cluster-local network (and not on the public Internet). However, if `expose` is set `true`, the Knative route would be accessible externally. To configure secure HTTPS connections for your Knative deployment, see link:++https://knative.dev/docs/serving/using-a-tls-cert/++[Configuring HTTPS with TLS certificates] for more information. === Kubernetes Application Navigator (kAppNav) support By default, Runtime Component Operator configures the Kubernetes resources it generates to allow automatic creation of an link:++https://github.com/kubernetes-sigs/application++[Application definition] with the `applicationName` parameter as the `Application` CR name. The automatic creation is done by the link:++https://kappnav.io/++[Kubernetes Application Navigator (kAppNav)]. You can easily view and manage the deployed resources that comprise your application by using kAppNav. You can disable auto-creation by setting the `createAppDefinition` parameter to a value of `false`. To join an existing application definition in the `RuntimeComponent` CR namespace, ensure that the `applicationName` parameter is set to the name of the `Application` CR that you want to join. To join an existing application definition in another namespace, ensure that the `createAppDefinition` parameter is set to `false` and that the `applicationName` parameter is set to the name of the existing `Application` CR that you want to join. First, the operator searches in the `RuntimeComponent` CR namespace to find an `Application` CR named as the `applicationName` parameter. If it fails to find any, it searches the whole cluster to find `Application` CRs that meet the following criteria: - The `Application` CRs have the same name as the value of the `applicationName` parameter. - The `RuntimeComponent` CR namespace is listed in the value of the `kappnav.component.namespaces` annotation. After the operator finds any `Application` CRs in the previous steps, it adds labels to the `RuntimeComponent` CR. These labels are listed in the `spec.selector.matchLabels` parameter. However, if the operator fails to find any `Application` CRs, and if the `createAppDefinition` parameter is not set to `false`, the operator configures the Kubernetes resources it generates. These Kubernetes resources are configured to allow automatic creation of an `Application` definition. _This feature is only available if you have kAppNav installed on your cluster. Auto creation of an application definition is not supported when Knative service is created_ NOTE: The operator requires `ClusterRole` permissions when joining an existing `Application` custom resource in another namespace. === Certificate Manager Integration Runtime Component Operator is enabled to take advantage of link:++https://cert-manager.io/++[cert-manager] tool, if it is installed on the cluster. This allows to automatically provision TLS certificates for pods as well as routes. Cert-manager installation instruction can be found link:++https://cert-manager.io/docs/installation/++[here]. When creating certificates via the RuntimeComponent CR the user can specify a particular issuer name and toggle the scopes between `ClusterIssuer` (cluster scoped) and `Issuer` (namespace scoped). If not specified, these values are retrieved from a ConfigMap called `runtime-component-operator`, with keys `defaultIssuer` (default value of `self-signed`) and `useClusterIssuer` (default value of `""true""`). _This feature does not support integration with Knative Service._ ==== Create an ClusterIssuer or Issuer Self signed: [source,yaml] ---- apiVersion: cert-manager.io/v1alpha2 kind: ClusterIssuer metadata: name: self-signed spec: selfSigned: {} ---- Using custom CA key: [source,yaml] ---- apiVersion: cert-manager.io/v1alpha2 kind: ClusterIssuer metadata: name: mycompany-ca spec: ca: secretName: mycompany-ca-tls ---- ==== Simple scenario (Pods certificate) [source,yaml] ---- apiVersion: app.stacks/v1beta1 kind: RuntimeComponent metadata: name: my-app namespace: test spec: applicationImage: quay.io/my-repo/my-app:1.0 .... service: port: 9080 certificate: {} ---- In this scenario the operator generates a `Certificate` resource with a common name of `my-app.test.svc` that can be used for service to service communication. After this certificate request is resolved by the certificate manager, the resulting `my-app-svc-tls` secret is mounted onto each pod inside the `/etc/x509/certs` folder. Mounted files are always up to date with a secret. It will contain private key, certificate and CA certificate. It is up to the application container to consume these artifacts, applying any needed transformation or modification. ==== Simple scenario (Route certificate) [source,yaml] ---- apiVersion: app.stacks/v1beta1 kind: RuntimeComponent metadata: name: my-app namespace: test spec: applicationImage: quay.io/my-repo/my-app:1.0 expose: true route: host: myapp.mycompany.com termination: reencrypt certificate: {} ---- In this scenario the operator generates a `Certificate` resource with the common name of `myapp.mycompany.com` that will be injected into the `Route` resource. ==== Advanced scenario In this example we are overriding Issuer to be used for application. Certificate will be generated for specific organization and duration. Extra properties can be added as well. [source,yaml] ---- apiVersion: app.stacks/v1beta1 kind: RuntimeComponent metadata: name: my-app namespace: test spec: applicationImage: quay.io/my-repo/my-app:1.0 expose: true route: host: myapp.mycompany.com termination: reencrypt certificate: duration: 8760h0m0s organization: - My Company issuerRef: name: myComanyIssuer kind: ClusterIssuer ---- ==== Use existing certificates It is possible to bring your own certificates to be used in a pod and the route. In this case the cert-manager is not required. [source,yaml] ---- apiVersion: app.stacks/v1beta1 kind: RuntimeComponent metadata: name: my-app namespace: test spec: applicationImage: quay.io/my-repo/my-app:1.0 expose: true route: host: myapp.mycompany.com termination: reencrypt certificateSecretRef: my-app-rt-tls service: port: 9443 ---- Example of the manually provided route secret [source, yaml] ---- kind: Secret apiVersion: v1 metadata: name: my-app-rt-tls data: ca.crt: >- Certificate Authority public certificate...(base64) tls.crt: >- Route public certificate...(base64) tls.key: >- Route private key...(base64) destCA.crt: >- Pod/Service certificate Certificate Authority (base64). Might be required when using reencrypt termination policy. type: kubernetes.io/tls ---- === Affinity Using affinity you can constrain a Pod to only be able to run on particular Node(s), or to prefer to run on particular nodes. ==== Node Affinity ===== Basic node affinity Use `nodeAffinityLabels` field to set required labels for pod scheduling on specific nodes: [source,yaml] ---- apiVersion: app.stacks/v1beta1 kind: RuntimeComponent metadata: name: my-app namespace: test spec: applicationImage: quay.io/my-repo/my-app:1.0 affinity: nodeAffinityLabels: customNodeLabel: label1, label2 customNodeLabel2: label3 ---- ===== Advanced node affinity example: The following example requires a node type of _Large_ and preferences for two zones, which are named _zoneA_ and _zoneB_ [source,yaml] ---- apiVersion: app.stacks/v1beta1 kind: RuntimeComponent metadata: name: my-app namespace: test spec: applicationImage: quay.io/my-repo/my-app:1.0 affinity: nodeAffinity: requiredDuringSchedulingIgnoredDuringExecution: nodeSelectorTerms: - matchExpressions: - key: node.kubernetes.io/instance-type operator: In values: - large preferredDuringSchedulingIgnoredDuringExecution: - weight: 60 preference: matchExpressions: - key: failure-domain.beta.kubernetes.io/zone operator: In values: - zoneA - weight: 20 preference: matchExpressions: - key: failure-domain.beta.kubernetes.io/zone operator: In values: - zoneB ---- ==== Pod Affinity and Anti-Affinity Pod affinity and anti-affinity allow you to constrain which nodes your pod is eligible to be scheduled based on labels on pods that are already running on the node rather than based on labels on node. The following example shows that pod affinity is required and that the pods for _Service-A_ and _Service-B_ must be in the same zone. Through pod anti-affinity, it is preferred not to schedule _Service_B_ and _Service_C_ on the same host. [source,yaml] ---- apiVersion: app.stacks/v1beta1 kind: RuntimeComponent metadata: name: Service-B namespace: test spec: applicationImage: quay.io/my-repo/my-app:1.0 affinity: podAffinity: requiredDuringSchedulingIgnoredDuringExecution: - labelSelector: matchExpressions: - key: service operator: In values: - Service-A topologyKey: failure-domain.beta.kubernetes.io/zone podAntiAffinity: preferredDuringSchedulingIgnoredDuringExecution: - weight: 100 podAffinityTerm: labelSelector: matchExpressions: - key: service operator: In values: - Service-C topologyKey: kubernetes.io/hostname ---- See link:++https://github.com/application-stacks/runtime-component-operator/blob/master/examples/affinity/README.adocd++[Affinity Example] for more details === Day-2 Operations You can easily perform day-2 operations using the `RuntimeOperation` custom resource (CR), which allows you to specify the commands to run on a container within a Pod. .Configurable Parameters |=== | Parameter | Description | `podName` | The name of the Pod, which must be in the same namespace as the `RuntimeOperation` CR. | `containerName` | The name of the container within the Pod. The default value is the name of the main container, which is `app`. | `command` | Command to run. The command doesn't run in a shell. |=== Example: [source,yaml] ---- apiVersion: app.stacks/v1beta1 kind: RuntimeOperation metadata: name: example-runtime-operation spec: # Specify the name of the pod. The pod must be in the same namespace as this RuntimeOperation CR. podName: Specify_Pod_Name_Here # Specify the name of the container. The default value is the name of the main container, which is `app`. containerName: app # Run the following command. The command does not run in a shell. command: - /bin/sh - '-c' - echo ""Hello"" > /tmp/runtime-operation.log ---- You can check the status of a runtime operation by using the `status` field inside the CR YAML file. You can also run the `oc get runtimeop -o wide` command to see the status of all operations in the current namespace. The operator will retry to run the `RuntimeOperation` when it fails to start due to specified pod or container not being found or when the pod is not in running state. The retry interval will be doubled with each failed attempt. NOTE: The `RuntimeOperation` CR must be created in the same namespace as the Pod to operate on. After the `RuntimeOperation` CR starts, the CR cannot be reused for more operations. A new CR needs to be created for each day-2 operation. The operator can process only one `RuntimeOperation` instance at a time. Long running commands can cause other runtime operations to wait before they start. === Troubleshooting See the link:++troubleshooting.adoc++[troubleshooting guide] for information on how to investigate and resolve deployment problems. ",12070,False,2217.6787899393466,median ":toc: macro toc::[] :idprefix: :idseparator: - ifdef::env-github[] :tip-caption: :bulb: :note-caption: :information_source: :important-caption: :heavy_exclamation_mark: :caution-caption: :fire: :warning-caption: :warning: endif::[] = devon4j adding Custom Functionality Now we have a fully functional blank project. All we have to do now is to create the components and services which will compose our application. First, we are going to develop the views of the app through its components, then we will create the services with the logic, security and back-end connection. == Creating Components [NOTE] ==== You have already learned about creating Components in devon4ng https://github.com/devonfw/jump-the-queue/wiki/devon4ng-components#create-a-new-component[here]. + You can go back and read that section again to refresh your memory. ==== Our app is going to consist of 3 main views: * Login * Register * ViewQueue To navigate between these views/components, we are going to implement routes using the Angular Router. To see our progress, move to the root folder of the `angular` project and run `ng serve -o` again. This will recompile and publish our client app to http://localhost:4200. Angular will keep watching for changes, so whenever we modify the code, the app will automatically reload. === Root Component `app.component.ts` inside `angular/src/app` will be our root component, so we don't have to create a new file yet. We are going to add elements to the root component that will be common no matter what view will be displayed. [NOTE] ==== You have already learned about the Root Component in devon4ng https://github.com/devonfw/jump-the-queue/wiki/devon4ng-components#root-component[here]. + You can go back and read that section again to refresh your memory. ==== This applies to the header element which will be on top of the window and on top of all other components. If you want, you can read more about https://teradata.github.io/covalent/#/layouts[Covalent layouts], which we are going to use a lot from now on, for every view component. [NOTE] ==== You have already learned about Covalent Layouts in devon4ng https://github.com/devonfw/jump-the-queue/wiki/devon4ng-components#teradata-covalent-layouts[here]. + You can go back and read that section again to refresh your memory. ==== We don't really need anything more than a header, so we are going to use the simplest layout for this purpose; the *nav view*. In order to be able to use Covalent and Angular Material we are going to create a core module, which we will import into every other module where we want to use Covalent and Angular Material. First, we create a folder called `shared` in the `angular/src/app` directory. Inside there we are going to create a file called `core.module.ts` and will fill it with the following content: [source, typescript] ---- import { NgModule } from '@angular/core'; import { RouterModule } from '@angular/router'; import { CommonModule } from '@angular/common'; import { HttpClientModule, HTTP_INTERCEPTORS } from '@angular/common/http'; import { BrowserAnimationsModule } from '@angular/platform-browser/animations'; import { MatAutocompleteModule, MatButtonModule, MatButtonToggleModule, MatCardModule, MatCheckboxModule, MatChipsModule, MatDatepickerModule, MatDialogModule, MatExpansionModule, MatGridListModule, MatIconModule, MatInputModule, MatListModule, MatMenuModule, MatNativeDateModule, MatPaginatorModule, MatProgressBarModule, MatProgressSpinnerModule, MatRadioModule, MatRippleModule, MatSelectModule, MatSidenavModule, MatSliderModule, MatSlideToggleModule, MatSnackBarModule, MatSortModule, MatTableModule, MatTabsModule, MatToolbarModule, MatTooltipModule, } from '@angular/material'; import { CdkTableModule } from '@angular/cdk/table'; import { CovalentChipsModule, CovalentLayoutModule, CovalentExpansionPanelModule, CovalentDataTableModule, CovalentPagingModule, CovalentDialogsModule, CovalentLoadingModule, CovalentMediaModule, CovalentNotificationsModule, CovalentCommonModule, } from '@covalent/core'; @NgModule({ imports: [ RouterModule, BrowserAnimationsModule, MatCardModule, MatButtonModule, MatIconModule, CovalentMediaModule, CovalentLayoutModule, CdkTableModule, ], exports: [ CommonModule, CovalentChipsModule, CovalentLayoutModule, CovalentExpansionPanelModule, CovalentDataTableModule, CovalentPagingModule, CovalentDialogsModule, CovalentLoadingModule, CovalentMediaModule, CovalentNotificationsModule, CovalentCommonModule, CdkTableModule, MatAutocompleteModule, MatButtonModule, MatButtonToggleModule, MatCardModule, MatCheckboxModule, MatChipsModule, MatDatepickerModule, MatDialogModule, MatExpansionModule, MatGridListModule, MatIconModule, MatInputModule, MatListModule, MatMenuModule, MatNativeDateModule, MatPaginatorModule, MatProgressBarModule, MatProgressSpinnerModule, MatRadioModule, MatRippleModule, MatSelectModule, MatSidenavModule, MatSliderModule, MatSlideToggleModule, MatSnackBarModule, MatSortModule, MatTableModule, MatTabsModule, MatToolbarModule, MatTooltipModule, HttpClientModule, ], declarations: [], providers: [ HttpClientModule ], }) export class CoreModule {} ---- [NOTE] ==== This `CoreModule` has almost every module of the different components for *Angular Material* and *Covalent Teradata*. If you decide to use a component that is not included yet, you need to add the corresponding module here. ==== Remember that we need to import this `CoreModule` module into the `AppModule` and inside every module of the different components that use *Angular Material* and *Covalent Teradata*. If a component does not have a module, it will be imported in the `AppModule` and hence automatically have the `CoreModule`. Our `app.module.ts` should have the following content: [source, typescript] ---- import { BrowserModule } from '@angular/platform-browser'; import { NgModule, CUSTOM_ELEMENTS_SCHEMA } from '@angular/core'; // Application components and services import { AppRoutingModule } from './app-routing.module'; import { AppComponent } from './app.component'; import { CoreModule } from './shared/core.module'; @NgModule({ declarations: [ AppComponent ], imports: [ BrowserModule, AppRoutingModule, CoreModule, ], providers: [ ], bootstrap: [AppComponent], schemas: [ CUSTOM_ELEMENTS_SCHEMA ] }) export class AppModule { } ---- [NOTE] ==== Even if we setup module correctly the html file can give us this red flag: ""If 'td-layout' is a Web Component then add 'CUSTOM_ELEMENTS_SCHEMA' to the '@NgModule.schemas' of this component to suppress this message."" To solve this we add ""schemas: [ CUSTOM_ELEMENTS_SCHEMA ]"" inside the @NgModule of all the affected modules. ==== [NOTE] ==== Remember this step because you will have to repeat it for every other component from Teradata you use in your app. ==== Now we can use this layout, so let's implement it in `app.component.html`. Use the following code: [source, html] ----

Jump The Queue

app works!

---- [NOTE] ==== You have already learned about Toolbars in devon4ng https://github.com/devonfw/jump-the-queue/wiki/devon4ng-components#toolbars[here]. + You can go back and read that section again to refresh your memory. ==== [NOTE] ==== You have already learned about Toolbars in devon4ng https://github.com/devonfw/jump-the-queue/wiki/devon4ng-components#toolbars[here]. + You can go back and read that section again to refresh your memory. ==== Once this is done, our app should have a header and ""app works!"" should appear in the body of the page: image::images/devon4ng/3.BuildYourOwn/root_header.jpg[Root Header, 250] To go a step further, we have to modify the body of the root component because it should be the *output of the router*. Now it's time to prepare the routing system. First, we need to create a component to show as default which will be our access view. We will modify it later. Stop `ng serve` and run: ---- ng generate component form-login ---- It will add a folder to our project with all the files needed for a component. Now we can move on to the router task again. Run `ng serve` again to continue the development. Let's create a module that navigates between components when the Router checks for routes. The file `app-routing.module.ts` was created automatically when we chose to include Angular Routing during project creation and we only need to modify it now: [source, typescript] ---- import { NgModule } from '@angular/core'; import { RouterModule, Routes } from '@angular/router'; import { FormLoginComponent } from './form-login/form-login.component'; const appRoutes: Routes = [ { path: 'FormLogin', component: FormLoginComponent}, // Redirect if url path is /FormLogin. { path: '**', redirectTo: '/FormLogin', pathMatch: 'full' } // Redirect if url path do not match any other route. ]; @NgModule({ imports: [ RouterModule.forRoot( appRoutes, { enableTracing: true }, // <-- debugging purposes only ), ], exports: [RouterModule], }) export class AppRoutingModule {} ---- [NOTE] ==== You have already learned about Routing in devon4ng https://github.com/devonfw/jump-the-queue/wiki/devon4ng-components#routing[here]. + You can go back and read that section again to refresh your memory. ==== Finally, we remove the `

app works!

` from `app.component.html` and replace it with a `` tag. The final result of our root component will look like this: image::images/devon4ng/3.BuildYourOwn/root_router.jpg[Root Router, 250] As you can see, now the body content is the HTML of `FormLoginComponent`. This is because we told the Router to redirect to formlogin when the path is `/FormLogin`, but also, redirect to it by default if any of the other routes match the given path. For now we are going to leave the header like this. In the future we will separate it into another component inside a layout folder. === LoginForm Component As we have already created this component from the section before, let's move on to building the template of the login view. First, we need to add the Covalent Layout and the card to the file `form-login.component.html`: [source, html] ---- Login ---- This will add a grey background to the view and a card on top of it with the title ""Login"" now that we have the basic structure of the view. Now we are going to add this image: image::images/devon4ng/3.BuildYourOwn/jumptheq.png[JumpTheQueue Logo Image, 250] In order to have it available, save it in the following path of the project: `angular/src/assets/images/` and name it `jumptheq.png`. The final code with the form added will look like this: [source, html] ---- ---- This code will give us as a result similar to this: image::images/devon4ng/3.BuildYourOwn/formlogin.png[Form Login, 250] This is going to be the container for the login. + Now we will continue with the second component: Login. === Login Component Our first step will be to create the component in the exact same way we created the `FormLogin` component but this time we are going to generate it in a new folder called components inside formlogin. Putting every child component inside that folder will allow us to keep a good and clear structure. In order to do this, we use the command: ---- ng generate component form-login/components/login ---- After _Angular/CLI_ has finished generating the component, we have to create two modules, one for the form-login and one for the login: 1.- We create a new file called `login-module.ts` in the login root: [source, typescript] ---- import { NgModule, CUSTOM_ELEMENTS_SCHEMA } from '@angular/core'; import { CommonModule } from '@angular/common'; import { CoreModule } from 'src/app/shared/core.module'; import { LoginComponent } from './login.component'; @NgModule({ imports: [CommonModule, CoreModule], providers: [], declarations: [LoginComponent], exports: [LoginComponent], schemas: [ CUSTOM_ELEMENTS_SCHEMA ] }) export class LoginModule {} ---- 2.- We create a new file called `form-login-module.ts` in the form-login root: [source, typescript] ---- import { NgModule, CUSTOM_ELEMENTS_SCHEMA } from '@angular/core'; import { CommonModule } from '@angular/common'; import { FormLoginComponent } from './form-login.component'; import { CoreModule } from '../shared/core.module'; import { LoginModule } from './components/login/login-module'; @NgModule({ imports: [CommonModule, CoreModule, LoginModule], providers: [], declarations: [FormLoginComponent], exports: [FormLoginComponent], schemas: [ CUSTOM_ELEMENTS_SCHEMA ] }) export class FormLoginModule {} ---- As you can see, the `LoginModule` is already added to the `FormLoginModule`. Once this is done, we need to remove the `FormLoginComponent` and the `LoginComponent` from the `declarations` since they are already declared in their own modules. Then add the `FormLoginModule`. This will be done inside `AppModule`: [source, typescript] ---- ... import { FormLoginModule } from './form-login/form-login-module'; ... declarations: [ AppComponent, ] imports: [ BrowserModule, FormLoginModule, CoreModule, AppRoutingModule ] ... ---- [NOTE] ==== This is done so the `form-login` (container/wrapper) and the `login` stay separated allowing us to reuse the login without having the card around in other views. ==== After this, we modify the `login.component.html` and add the form: [source, typescript] ----
---- [NOTE] ==== You have already learned about Forms in devon4ng https://github.com/devonfw/jump-the-queue/wiki/devon4ng-components#forms[here]. + You can go back and read that section again to refresh your memory. ==== This form contains two input containers from Material. The containers enclose the input with the properties listed above. We also need to add a button to send the information and redirect to the `QueueViewer` or show an error if something went wrong in the process. But for the moment, as we neither have another component nor the auth service yet, we will implement the button visually, as well as the validator to disable it if the form is not correct. We will tackle the on-click-event later. As a last step we will add this component to the `form-login-component.html`: [source, html] ---- ---- Now you should see something like this: image::images/devon4ng/3.BuildYourOwn/login.png[JumpTheQueue Login Screen, 250] With two components already created, we need to use the router to navigate between them. Following the application flow of events, we are going to add a _navigate_ function to the register button. When we press it, we will be redirected to our future register component. === Register Component First, we are going to generate the register component via: ---- ng generate component register` ---- This will create our component so we can start working on it. Turning back to `login.component.html` we have to modify these lines of code: [source, html] ----
... ... ---- Two events were added. First, when we submit the form, the method `submitLogin()` is going to be called. Second, when the user clicks the button `(click)` will send an event to the function `onRegisterClick()`. This function should be inside `login.component.ts` which is going to be created now: [source, typescript] ---- ... import { Router } from '@angular/router'; ... constructor(private router: Router) { } ... onRegisterClick(): void { this.router.navigate(['Register']); } submitLogin(): void { } ---- We need to inject an instance of the Router object and declare it with the name _router_ in order to use it in the code, as we did with `onRegisterClick()`. Doing this will use the navigate function and redirect to the next view. In our case, it will redirect using the route we are going to define in `app.routing.module.ts`: [source, typescript] ---- ... import { RegisterComponent } from './register/register.component'; ... const appRoutes: Routes = [ { path: 'FormLogin', component: FormLoginComponent}, // Redirect if url path is /FormLogin. { path: 'Register', component: RegisterComponent}, // Redirect if url path is /Register. { path: '**', redirectTo: '/FormLogin', pathMatch: 'full' } // Redirect if url path do not match any other route. ]; ... ---- [NOTE] ==== You have already learned about Dependency Injection in devon4ng https://github.com/devonfw/jump-the-queue/wiki/devon4ng-services#dependency-injection[here]. + You can go back and read that section again to refresh your memory. ==== Now we are going to imitate the `login` to shape our `register.component.html`: [source, html] ----
Accept Terms And conditions
I want to receive notifications
---- Now that we have a minimum of navigation flow inside our application, we are going to generate our first service using the command: ---- ng generate service register/services/register ---- This will create a folder ""services"" inside ""register"" and create the service itself. Services are where we keep the logic that connects to our database and fetches data which is going to be used by our `component.ts`. In order to use the service, we are going to create some interface models. Let's create a folder called `backendModels` inside ""shared"" and inside this folder a file called `interfaces.ts` in which we are going to add the model interfaces that will match our backend: [source, typescript] ---- export class Visitor { id?: number; username: string; name: string; password: string; phoneNumber: string; acceptedCommercial: boolean; acceptedTerms: boolean; userType: boolean; } export class VisitorArray { content: Visitor[]; } ---- [NOTE] ==== You have already learned about creating new services in devon4ng https://github.com/devonfw/jump-the-queue/wiki/devon4ng-services#create-a-new-service[here]. + You can go back and read that section again to refresh your memory. ==== If we take a closer look, we can see that id has a `?` behind it. This indicates that the id is optional. [NOTE] ==== At this point we are going to assume that you have finished the https://github.com/devonfw/jump-the-queue/wiki/build-devon4j-application[devon4j] part of this tutorial, or have at least downloaded the project and have the back end running locally on http://localhost:8081. ==== After doing this, we are going to add an environment variable with our base-URL for the REST services. This way we won't have to change every URL when we switch to production. Inside `environments/environment.ts` we add: [source, typescript] ---- export const environment: {production: boolean, baseUrlRestServices: string} = { production: false, baseUrlRestServices: 'http://localhost:8081/jumpthequeue/services/rest' }; ---- Now in the service, we are going to add a `registerVisitor` method. To call the server in this method we are going to inject the Angular `HttpClient` class from `@angular/common/http`. This class is the standard used by Angular to perform HTTP calls. The register call demands a `Visitor` model which we created in the `interfaces` file. We are going to build a POST call and send the information to the proper URL of the server service. The call will return an observable: [source, typescript] ---- import { Injectable } from '@angular/core'; import { HttpClient } from '@angular/common/http'; import { Visitor} from 'src/app/shared/backendModels/interfaces'; import { Observable } from 'rxjs'; import { environment } from 'src/environments/environment'; @Injectable({ providedIn: 'root' }) export class RegisterService { private baseUrl = environment.baseUrlRestServices; constructor(private http: HttpClient) { } registerVisitor(visitor: Visitor): Observable { return this.http.post(`${this.baseUrl}` + '/visitormanagement/v1/visitor', visitor); } } ---- This method will send our model to the backend and return an Observable that we will use on the `component.ts`. [NOTE] ==== You have already learned about Observables and RxJs in devon4ng https://github.com/devonfw/jump-the-queue/wiki/devon4ng-services#server-communication[here]. + You can go back and read that section again to refresh your memory. ==== Now we are going to modify `register.component.ts` to call this service: [source, typescript] ---- import { Component, OnInit } from '@angular/core'; import { RegisterService } from './services/register.service'; import { Visitor } from '../shared/backendModels/interfaces'; import { Router } from '@angular/router'; import { MatSnackBar } from '@angular/material/snack-bar'; @Component({ selector: 'app-register', templateUrl: './register.component.html', styleUrls: ['./register.component.scss'] }) export class RegisterComponent implements OnInit { constructor(private registerService: RegisterService, private router: Router, public snackBar: MatSnackBar) { } submitRegister(formValue): void { const visitor: Visitor = new Visitor(); visitor.username = formValue.username; visitor.name = formValue.name; visitor.phoneNumber = formValue.phoneNumber; visitor.password = formValue.password; visitor.acceptedCommercial = formValue.acceptedCommercial; visitor.acceptedTerms = formValue.acceptedTerms; visitor.userType = false; this.registerService.registerVisitor(visitor).subscribe( (visitorResult: Visitor) => console.log(JSON.stringify(visitorResult)), // When call is received (err) => this.snackBar.open(err.error.message, 'OK', { duration: 5000, }), // When theres an error ); } ngOnInit() { } } ---- In this file we injected `RegisterService` and `Router` to use them. Then, inside the method `submitRegister`, we created a visitor that we are going to pass to the service. We called the service method `registerVisitor`, we passed the visitor and we subscribed to the `Observable`, which we returned from the service. This subscription allows us to control three things: . What to do when the data is received. . What to do when there's an error. . What to do when the call is complete. Finally, we modify the `register.component.html` to send the form values to the method: [source, html] ---- ...
... ---- image::images/devon4ng/3.BuildYourOwn/register.png[Register Page, 250] Using the method and taking a look at the browser console, we should see the visitor model being returned. == Creating Services Now that we registered a `Visitor`, it's time to create 3 important services: - AuthService - AuthGuardService - LoginService The `AuthService` will be the one that contains the login info, the `AuthGuardService` will check if a user is authorized to use a component (via the `canActivate` method), and the `LoginService` will be used to fill the `AuthService`. [NOTE] ==== To keep this tutorial simple, we are going to perform the password check client side. *THIS IS NOT CORRECT!* Usually, you would send the username and password to the backend, check that the values are correct, and create a corresponding token which you would pass in the header and use it inside the `AuthService` -- checking with some interceptors that the token is both in the `AuthService` and in the request. ==== === Login, Auth and AuthGuard Services We are going to create the 3 services via `ng generate service `: . `LoginService` via: + `ng generate service form-login/components/login/services/login` . `Auth` service via: + `ng generate service core/authentication/auth` . `AuthGuard` service via: + `ng generate service core/authentication/auth-guard` After generating the services, we are going to start modifying the interfaces. Inside `angular/src/app/shared/backendModels/interfaces` we are going to add `Role`, `FilterVisitor`, `Pageable` and a `Sort` interface: [source, typescript] ---- ... export class FilterVisitor { pageable: Pageable; username?: string; password?: string; } export class Pageable { pageSize: number; pageNumber: number; sort: Sort[]; } export class Sort { property: string; direction: string; } export class Role { name: string; permission: number; } ---- [NOTE] ==== As you can see, we added a `Pageable`, since a lot of the search methods in the backend are using `SearchCriterias`. These need pageables which specify a `paseSize` and `pageNumber`. Also, we can see that in this case `FilterVisitor` uses a pageable and adds parameters as a filter (`username` and `password`), which are optional. ==== Then we are going to create a `config.ts` file inside the root (`angular/app`). We are going to use that file to set up default config variables, for example: role names with their permission number, default pagination settings etc. For now we are just adding the roles: [source, typescript] ---- export const config: any = { roles: [ { name: 'VISITOR', permission: 0 }, { name: 'BOSS', permission: 1 }, ], }; ---- After that, we are going to modify the `auth.service.ts`: [source, typescript] ---- import { Injectable } from '@angular/core'; import { find } from 'lodash'; import { Role } from 'src/app/shared/backendModels/interfaces'; import { config } from 'src/app/config'; @Injectable({ providedIn: 'root' }) export class AuthService { private logged = false; private user = ''; private userId = 0; private currentRole = 'NONE'; private token: string; public isLogged(): boolean { return this.logged; } public setLogged(login: boolean): void { this.logged = login; } public getUser(): string { return this.user; } public setUser(username: string): void { this.user = username; } public getUserId(): number { return this.userId; } public setUserId(userId: number): void { this.userId = userId; } public getToken(): string { return this.token; } public setToken(token: string): void { this.token = token; } public setRole(role: string): void { this.currentRole = role; } public getPermission(roleName: string): number { const role: Role = find(config.roles, { name: roleName }); return role.permission; } public isPermited(userRole: string): boolean { return ( this.getPermission(this.currentRole) === this.getPermission(userRole) ); } } ---- We will use this service to fill it with information from the logged-in user once the user logs in. This will allow us to check the information of the logged-in user in any way necessary. [NOTE] ==== You have already learned about Authentication in devon4ng https://github.com/devonfw/jump-the-queue/wiki/devon4ng-services#authentication[here]. + You can go back and read that section again to refresh your memory. ==== Now we are going to use this class to fill the `auth-guard.service.ts`: [source, typescript] ---- import { Injectable } from '@angular/core'; import { CanActivate, Router, ActivatedRouteSnapshot, RouterStateSnapshot, } from '@angular/router'; import { AuthService } from './auth.service'; @Injectable({ providedIn: 'root' }) export class AuthGuardService implements CanActivate { constructor( private authService: AuthService, private router: Router, ) {} canActivate( route: ActivatedRouteSnapshot, state: RouterStateSnapshot, ): boolean { if (this.authService.isLogged() && this.authService.isPermited('VISITOR')) { // If its logged in and its role is visitor return true; } if (!this.authService.isLogged()) { // if its not logged in console.log('Error login'); } if (this.router.url === '/') { // if the router is the app route this.router.navigate(['/login']); } return false; } } ---- This service will be slightly different because we have to implement an interface called `CanActivate`. It has a method called `canActivate()` returning a boolean. This method will be called when navigating to a specified route, and -- depending on the return value of this implemented method -- the navigation will proceed or be rejected. [NOTE] ==== You have already learned about Guards in devon4ng https://github.com/devonfw/jump-the-queue/wiki/devon4ng-services#guards[here]. + You can go back and read that section again to refresh your memory. ==== Once this is done, the last step is to fill the `login.service.ts`. In this case, there's going to be three methods: . `getVisitorByUsername(username: string)`: + A method that recovers a single user corresponding to the email. . `login(username: string, password: string)`: + A method, which is going to use the previous method, to check that the username and password match the form input and then fill the `AuthService`. . `logout()`: + This is going to be used to reset the `AuthService` and log out the user. Also, we see the first use of `pipe` and `map`: + `pipe` allows us to execute a chain of functions, then `map` allows us to return the single visitor instead of all the parameters that the server will send us. [source, typescript] ---- import { map, tap } from 'rxjs/operators'; import { Injectable } from '@angular/core'; import { Observable } from 'rxjs'; import { Visitor, FilterVisitor, Pageable } from 'src/app/shared/backendModels/interfaces'; import { HttpClient } from '@angular/common/http'; import { environment } from 'src/environments/environment'; import { AuthService } from 'src/app/core/authentication/auth.service'; import { Router } from '@angular/router'; import { MatSnackBar } from '@angular/material/snack-bar'; @Injectable({ providedIn: 'root' }) export class LoginService { private baseUrl = environment.baseUrlRestServices; constructor(private router: Router, private http: HttpClient, private authService: AuthService, public snackBar: MatSnackBar) { } getVisitorByUsername(username: string): Observable { const filters: FilterVisitor = new FilterVisitor(); const pageable: Pageable = new Pageable(); pageable.pageNumber = 0; pageable.pageSize = 1; pageable.sort= []; filters.username = username; filters.pageable = pageable; return this.http.post(`${this.baseUrl}` + '/visitormanagement/v1/visitor/search', filters) .pipe( map(visitors => visitors.content[0]), ); } login(username: string, password: string): void { // Checks if given username and password are the ones aved in the database this.getVisitorByUsername(username).subscribe( (visitorFound) => { if (visitorFound.username === username && visitorFound.password === password) { this.authService.setUserId(visitorFound.id); this.authService.setLogged(true); this.authService.setUser(visitorFound.username); if (visitorFound.userType === false) { this.authService.setRole('VISITOR'); this.router.navigate(['ViewQueue']); } else { this.authService.setLogged(false); this.snackBar.open('access error', 'OK', { duration: 2000, }); } } else { this.snackBar.open('access error', 'OK', { duration: 2000, }); } }, (err: any) => { this.snackBar.open('access error', 'OK', { duration: 2000, }); }, ); } logout(): void { this.authService.setLogged(false); this.authService.setUser(''); this.authService.setUserId(0); this.router.navigate(['FormLogin']); } } ---- If you remember the devon4j tutorial, we used `Criteria` in order to filter and to search the DB. The `Criteria` require a pageable and you can add extra parameters to get specific results. In `getVisitorByUsername()` you can see the creation of a `FilterVisitor` corresponding to the `Criteria` in the backend. This `FilterVisitor` gets a `Pageable` and a `username` and will return a single result as soon as the POST call is performed. That's why we return the first page and only a single result. [NOTE] ==== For the tutorial we are only considering the visitor side of the application. That's why we `setLogged(false)` if it's `userType === true` (BOSS side). ==== Then we add to the `login-module.ts` and `LoginService`: [source, typescript] ---- ... import { LoginService } from './services/login.service'; @NgModule({ ... providers: [LoginService], ... }) ... ---- After that, we are going to add the `AuthGuard` and the `Auth` into the `shared/core-module.ts`. This will allow us to employ these two services when importing the core module avoiding having to provide these services in every component: [source, typescript] ---- ... providers: [ HttpClientModule, AuthService, AuthGuardService, ], ... ---- You need to import these modules as well, as shown earlier. Finally, we modify the `login.component.html` to send the form values to the `login.component.ts` like we did with the register form. Afterwards, we are going to modify the `register.components.ts`: When the visitor registers, we can log him in automatically to avoid any nuisances. Let's start with the `login.component.html`: [source, html] ---- ... ... ---- As you can see, in the form we just added, the values to the `ngSubmit` allow us to call the method `submitLogin()` within the logic, sending the `loginForm.form.values` which are the form's input values. In the next step we are going to modify the `login.components.ts`, adding the `submitLogin()` method. This method calls the `LoginService`, providing the service with the necessary values received from the form (i.e. the `loginFormValues`). [source, typescript] ---- ... import { LoginService } from './services/login.service'; ... export class LoginComponent implements OnInit { ... constructor(private router: Router, private loginService: LoginService) { } ... submitLogin(loginFormValues): void { this.loginService.login(loginFormValues.username, loginFormValues.password); } } ---- Finally, in the `register.components.ts` we are going to inject the `LoginService` and use it to login the visitor after registering him. This will also send the user to the `ViewQueue`, which we will create and secure later in the tutorial. [source, typescript] ---- import { LoginService } from '../form-login/components/login/services/login.service'; ... constructor(private registerService: RegisterService, private router: Router, public snackBar: MatSnackBar, private loginService: LoginService) { } ... submitRegister(formValue): void { ... this.registerService.registerVisitor(visitor).subscribe( (visitorResult: Visitor) => { this.loginService.login(visitorResult.username, visitorResult.password); }, ... ); } ... ---- == Finishing Touches Now we only need to generate two more components (`header` and `view-queue`) and services (`AccessCodeService` and `QueueService`) in order to finish the implementation of our _JumpTheQueue_ app. === Separating Header from Layout By separating the header on top of the page from the layout, we enable the reuse of this component and reach a better separation of concerns across our application. To do this, we are going to generate a new component inside `angular/src/app/layout/header` via: ---- ng generate component layout/header ---- Now we are going to add it to the main view `app.component.html`: [source, html] ---- ...
... ---- After adding the component to the header view (`app-header`), we are going to modify the HTML of the component (`header.component.html`) and the logic of the component (`header.component.ts`). As a first step, we are going to modify the HTML, adding an icon as a button, which checks whether or not the user is logged in via `*ngIf` by calling the auth service's `isLogged()` method. This will make the icon appear only if the user is logged in: [source, html] ---- Jump The Queue ---- In the header logic (`header.component.ts`) we are simply going to inject the `AuthService` and `LoginService`, then we are going call `logout()` from `LoginService` in the `OnClickLogout()`. Finally, the `AuthService` is needed because it's being used by the HTML template to control if the user is logged in with `isLogged()`: [source, typescript] ---- ... constructor(private authService: AuthService, private loginService: LoginService) { } ... onClickLogout(): void { this.loginService.logout(); } ... ---- Separating components will allow us to keep the code clean and easy to work with. === ViewQueue Component For the last view, we are going to learn how to use our Observables on the HTML template directly without having to `subscribe()` to them. First, we are going to generate the component via: ---- ng generate component view-queue ---- After that, we are going to include the component in the `app-routing.module.ts`, also adding the guard, to only allow users that are `VISITOR` to see the component. It is important to insert the following code before `{ path: '**', redirectTo: '/FormLogin', pathMatch: 'full' }`: [source, typescript] ---- ... const appRoutes: Routes = [ ... { path: 'ViewQueue', component: ViewQueueComponent, canActivate: [AuthGuardService]}, // Redirect if url path is /ViewQueue, check if canActivate() with the AuthGuardService. ... ]; ... ---- Now in order to make this view work, we are going to do these things: . Add the `Queue` and `AccessCode` interface in our `angular/src/app/shared/backendModels/interfaces` and their corresponding filters. . Generate the `QueueService` and `AccessCodeService` and add the necessary methods. . Modify the `view-queue.component.html`. . Modify the logic of the component `view-queue.component.ts`. First, we are going to add the necessary interfaces. We modify `angular/src/app/shared/backendModels/interfaces.ts` and add the `FilterQueue`, `Queue`, `FilterAccessCode`, `AccessCode`, `QueueArray` and `AccessCodeArray`. These are going to be necessary in order to communicate with the backend. [source, typescript] ---- ... export class FilterAccessCode { pageable: Pageable; visitorId?: Number; endTime?: string; } export class FilterQueue { pageable: Pageable; active: boolean; } export class AccessCode { id?: number; ticketNumber: string; creationTime: string; startTime?: string; endTime?: string; visitorId: number; queueId: number; content: any; } export class Queue { id?: number; name: string; logo: string; currentNumber: string; attentionTime: string; minAttentionTime: string; active: boolean; customers: number; content: any; } export class QueueArray { content: Queue[]; } export class AccessCodeArray { content: [{ accessCode: AccessCode }]; } ... ---- === AccessCode and Queue Services After this is done, we are going to generate the `AccessCodeService` and the `QueueService`: ---- ng generate service view-queue/services/Queue ng generate service view-queue/services/AccessCode ---- Once this is done, we are going to modify them and add the necessary methods: - For the `AccessCodeService` we are going to need a full CRUD: [source, typescript] ---- import { Injectable } from '@angular/core'; import { AuthService } from 'src/app/core/authentication/auth.service'; import { Router } from '@angular/router'; import { HttpClient } from '@angular/common/http'; import { AccessCode, Pageable, FilterAccessCode } from 'src/app/shared/backendModels/interfaces'; import { Observable } from 'rxjs'; import { environment } from 'src/environments/environment'; import { map } from 'rxjs/operators'; @Injectable({ providedIn: 'root' }) export class AccessCodeService { private baseUrl = environment.baseUrlRestServices; constructor(private router: Router, private http: HttpClient, private authService: AuthService) { } getCurrentlyAttendedAccessCode(): Observable { const filters: FilterAccessCode = new FilterAccessCode(); const pageable: Pageable = new Pageable(); filters.endTime = null; pageable.pageNumber = 0; pageable.pageSize = 1; filters.pageable = pageable; return this.http.post(`${this.baseUrl}` + '/accesscodemanagement/v1/accesscode/cto/search', filters) .pipe( map(accesscodes => { if (!accesscodes.content[0]) { // if theres no response it means theres noone in the queue return null; } else { if (accesscodes.content[0].accessCode.startTime != null) { // if start time is not null it means that hes being attended return accesscodes.content[0].accessCode; } else { // noone being attended return null; } } }), ); } getVisitorAccessCode(visitorId: number): Observable { const filters: FilterAccessCode = new FilterAccessCode(); const pageable: Pageable = new Pageable(); pageable.pageNumber = 0; pageable.pageSize = 1; filters.visitorId = visitorId; filters.pageable = pageable; return this.http.post(`${this.baseUrl}` + '/accesscodemanagement/v1/accesscode/cto/search', filters) .pipe( map(accesscodes => { if (accesscodes.content[0]) { return accesscodes.content[0].accessCode; } else { return null; } }), ); } deleteAccessCode(codeAccessId: number) { this.http.delete(`${this.baseUrl}` + '/accesscodemanagement/v1/accesscode/' + codeAccessId + '/').subscribe(); } saveAccessCode(visitorId: number, queueId: number) { const accessCode: AccessCode = new AccessCode(); accessCode.visitorId = visitorId; accessCode.queueId = queueId; return this.http.post(`${this.baseUrl}` + '/accesscodemanagement/v1/accesscode/', accessCode); } } ---- In the methods `getCurrentlyAttendedAccessCode` and `getVisitorAccessCode` we can see the use of `Pageable` and `FilterAccessCode` to match the `Criteria` in the backend like we explained in previous steps. In this case, the `getVisitorAccessCode` method will be used to see if the visitor has an `AccessCode` and the `getCurrentlyAttendedAccessCode` is going to recover the first `AccessCode` of the queue. - For the `QueueService` we are only going to need to find the active queue: [source, typescript] ---- import { Injectable } from '@angular/core'; import { HttpClient } from '@angular/common/http'; import { Router } from '@angular/router'; import { Observable } from 'rxjs'; import { Queue, FilterQueue, Pageable } from 'src/app/shared/backendModels/interfaces'; import { environment } from 'src/environments/environment'; import { map } from 'rxjs/operators'; @Injectable({ providedIn: 'root' }) export class QueueService { private baseUrl = environment.baseUrlRestServices; constructor(private router: Router, private http: HttpClient) { } getActiveQueue(): Observable { const filters: FilterQueue = new FilterQueue(); filters.active = true; const pageable: Pageable = new Pageable(); pageable.pageNumber = 0; pageable.pageSize = 1; pageable.sort = []; filters.pageable = pageable; return this.http.post(`${this.baseUrl}` + '/queuemanagement/v1/queue/search', filters) .pipe( map(queues => queues.content[0]), ); } } ---- Now we are going to create the template `view-queue.component.html` (which will use this data) and we will also introduce a new concept: ""_async pipes in templates_"". [source, html] ----

Your Number:

{{data.accessCodeVisitor.ticketNumber}}

Currently estimate time: 10:00:00

Currently Being Attended:

{{data.accessCodeAttended?.ticketNumber}}

The queue is not active try again later

---- If you watch closely, the starting `td-layout` has an `*ngIf` inside it. This `*ngIf` allows us to asynchronously pipe the observables that we will asign in the next steps. This solution avoids having to use `subscribe()` (as it subscribes automatically) and -- as a result -- we dont have to worry about where to `unsubscribe()` from the observables. In this HTML, we give `*ngif` another use: We use it to hide certain panels. Using `accessCodeVisitor`, we hide the ticket number panel and the ""leave the queue""-button and show the button to join the queue. On the contrary we can hide the ticket number and the ""leave the queue""-button and only show the ""join the queue""-button. [NOTE] ==== In this case, since we are using HTTP and the calls are finite, there wouldn't be any problems if you dont `unsubscribe()` from their corresponding observables. However, if -- for example -- we use an observable to keep track of an input and `subscribe()` to it but not controlling the `unsubscribe()` method, the app could end up containing a memory leak. This is because -- everytime we visit the component with the input -- it is going to create another subscription without unsubscribing from the last one. ==== Finally, to adapt the async pipe, the `ngOnInit()` method inside `view-queue.component.ts` now does not subscribe to the observable. In its place, we equal the queuers variable directly to the observable, so we can load it using `*ngIf`. [source, typescript] ---- import { Component, OnInit } from '@angular/core'; import { AccessCode, Queue } from '../shared/backendModels/interfaces'; import { Observable, timer } from 'rxjs'; import { AccessCodeService } from './services/access-code.service'; import { switchMap } from 'rxjs/operators'; import { AuthService } from '../core/authentication/auth.service'; import { QueueService } from './services/queue.service'; @Component({ selector: 'app-view-queue', templateUrl: './view-queue.component.html', styleUrls: ['./view-queue.component.scss'] }) export class ViewQueueComponent implements OnInit { accessCodeAttended$: Observable; accessCodeVisitor$: Observable; queue$: Observable; constructor(private accessCodeService: AccessCodeService, private queueService: QueueService, private authService: AuthService) { } ngOnInit() { // Every minute we are going to update accessCodeAttended$ starting instantly this.accessCodeAttended$ = timer(0, 60000).pipe( // we switchMap and give it the value necesary from the accessCodeService switchMap(() => { return this.accessCodeService.getCurrentlyAttendedAccessCode(); }) ); this.accessCodeVisitor$ = this.accessCodeService.getVisitorAccessCode(this.authService.getUserId()); this.queue$ = this.queueService.getActiveQueue(); } onJoinQueue(queueId: number): void { this.accessCodeVisitor$ = this.accessCodeService.saveAccessCode(this.authService.getUserId(), queueId); } onLeaveQueue(accessCodeId: number): void { this.accessCodeService.deleteAccessCode(accessCodeId); this.accessCodeVisitor$ = null; } } ---- In this last component we assign the `Observables` when the component is initiated. After that, when clicking the ""join the queue""-button, we assign a new `Observable` called `AccessCode` to the `accessCodeVisitor$`. Finally, when we leave the queue, we delete the `AccessCode` and set the `accessCodeVisitor` to null. Since we are using an async pipe, everytime we modify the status of the `Observables`, they are going to update the template. image::images/devon4ng/3.BuildYourOwn/withCodeAccess.png[Queue Page with Access Code, 250] image::images/devon4ng/3.BuildYourOwn/withoutCodeAccess.png[Queue Page without Access Code, 250] This is all on how to build your own devon4ng application. Now it's up to you to add features, change styles and do everything you can imagine doing with this app. As a final step to complete the tutorial, however, we are going to run the app outside of our local machine by deploying it. ''' *Next Chapter*: link:devon4ng-deployment.asciidoc[Deploy your devon4ng App] ",12301,False,2120.0167851259807,median " //// This file is generated! See _meta/fields.yml and scripts/generate_field_docs.py //// [[exported-fields]] = Exported fields [partintro] -- This document describes the fields that are exported by Heartbeat. They are grouped in the following categories: * <> * <> * <> * <> * <> * <> * <> * <> * <> * <> * <> * <> * <> -- [[exported-fields-beat]] == Beat fields Contains common beat fields available in all event types. *`beat.timezone`*:: + -- type: alias alias to: event.timezone -- *`fields`*:: + -- type: object Contains user configurable fields. -- [float] == error fields Error fields containing additional info in case of errors. *`error.type`*:: + -- type: keyword Error type. -- [[exported-fields-cloud]] == Cloud provider metadata fields Metadata from cloud providers added by the add_cloud_metadata processor. *`cloud.project.id`*:: + -- example: project-x Name of the project in Google Cloud. -- *`meta.cloud.provider`*:: + -- type: alias alias to: cloud.provider -- *`meta.cloud.instance_id`*:: + -- type: alias alias to: cloud.instance.id -- *`meta.cloud.instance_name`*:: + -- type: alias alias to: cloud.instance.name -- *`meta.cloud.machine_type`*:: + -- type: alias alias to: cloud.machine.type -- *`meta.cloud.availability_zone`*:: + -- type: alias alias to: cloud.availability_zone -- *`meta.cloud.project_id`*:: + -- type: alias alias to: cloud.project.id -- *`meta.cloud.region`*:: + -- type: alias alias to: cloud.region -- [[exported-fields-common]] == Common heartbeat monitor fields None [float] == monitor fields Common monitor fields. *`monitor.type`*:: + -- type: keyword The monitor type. -- *`monitor.name`*:: + -- type: keyword The monitors configured name -- *`monitor.id`*:: + -- type: keyword The monitors full job ID as used by heartbeat. -- [float] == duration fields Total monitoring test duration *`monitor.duration.us`*:: + -- type: long Duration in microseconds -- *`monitor.scheme`*:: + -- type: keyword Address url scheme. For example `tcp`, `tls`, `http`, and `https`. -- *`monitor.host`*:: + -- type: keyword Hostname of service being monitored. Can be missing, if service is monitored by IP. -- *`monitor.ip`*:: + -- type: ip IP of service being monitored. If service is monitored by hostname, the `ip` field contains the resolved ip address for the current host. -- *`monitor.status`*:: + -- type: keyword required: True Indicator if monitor could validate the service to be available. -- [[exported-fields-docker-processor]] == Docker fields Docker stats collected from Docker. *`docker.container.id`*:: + -- type: keyword Unique container id. -- *`docker.container.image`*:: + -- type: keyword Name of the image the container was built on. -- *`docker.container.name`*:: + -- type: keyword Container name. -- *`docker.container.labels`*:: + -- type: object Image labels. -- [[exported-fields-ecs]] == ECS fields ECS fields. *`@timestamp`*:: + -- type: date example: 2016-05-23T08:05:34.853Z required: True Date/time when the event originated. For log events this is the date/time when the event was generated, and not when it was read. Required field for all events. -- *`tags`*:: + -- type: keyword example: [""production"", ""env2""] List of keywords used to tag each event. -- *`labels`*:: + -- type: object example: {'application': 'foo-bar', 'env': 'production'} Key/value pairs. Can be used to add meta information to events. Should not contain nested objects. All values are stored as keyword. Example: `docker` and `k8s` labels. -- *`message`*:: + -- type: text example: Hello World For log events the message field contains the log message. In other use cases the message field can be used to concatenate different values which are then freely searchable. If multiple messages exist, they can be combined into one message. -- [float] == agent fields The agent fields contain the data about the software entity, if any, that collects, detects, or observes events on a host, or takes measurements on a host. Examples include Beats. Agents may also run on observers. ECS agent.* fields shall be populated with details of the agent running on the host or observer where the event happened or the measurement was taken. *`agent.version`*:: + -- type: keyword example: 6.0.0-rc2 Version of the agent. -- *`agent.name`*:: + -- type: keyword example: foo Name of the agent. This is a name that can be given to an agent. This can be helpful if for example two Filebeat instances are running on the same host but a human readable separation is needed on which Filebeat instance data is coming from. If no name is given, the name is often left empty. -- *`agent.type`*:: + -- type: keyword example: filebeat Type of the agent. The agent type stays always the same and should be given by the agent used. In case of Filebeat the agent would always be Filebeat also if two Filebeat instances are run on the same machine. -- *`agent.id`*:: + -- type: keyword example: 8a4f500d Unique identifier of this agent (if one exists). Example: For Beats this would be beat.id. -- *`agent.ephemeral_id`*:: + -- type: keyword example: 8a4f500f Ephemeral identifier of this agent (if one exists). This id normally changes across restarts, but `agent.id` does not. -- [float] == client fields A client is defined as the initiator of a network connection for events regarding sessions, connections, or bidirectional flow records. For TCP events, the client is the initiator of the TCP connection that sends the SYN packet(s). For other protocols, the client is generally the initiator or requestor in the network transaction. Some systems use the term ""originator"" to refer the client in TCP connections. The client fields describe details about the system acting as the client in the network event. Client fields are usually populated in conjuction with server fields. Client fields are generally not populated for packet-level events. *`client.ip`*:: + -- type: ip IP address of the client. Can be one or multiple IPv4 or IPv6 addresses. -- *`client.port`*:: + -- type: long Port of the client. -- *`client.mac`*:: + -- type: keyword MAC address of the client. -- *`client.domain`*:: + -- type: keyword Client domain. -- *`client.bytes`*:: + -- type: long example: 184 Bytes sent from the client to the server. -- *`client.packets`*:: + -- type: long example: 12 Packets sent from the client to the server. -- [float] == geo fields Geo fields can carry data about a specific location related to an event or geo information derived from an IP field. *`client.geo.location`*:: + -- type: geo_point example: { ""lon"": -73.614830, ""lat"": 45.505918 } Longitude and latitude. -- *`client.geo.continent_name`*:: + -- type: keyword example: North America Name of the continent. -- *`client.geo.country_name`*:: + -- type: keyword example: Canada Country name. -- *`client.geo.region_name`*:: + -- type: keyword example: Quebec Region name. -- *`client.geo.city_name`*:: + -- type: keyword example: Montreal City name. -- *`client.geo.country_iso_code`*:: + -- type: keyword example: CA Country ISO code. -- *`client.geo.region_iso_code`*:: + -- type: keyword example: CA-QC Region ISO code. -- *`client.geo.name`*:: + -- type: keyword example: boston-dc User-defined description of a location, at the level of granularity they care about. Could be the name of their data centers, the floor number, if this describes a local physical entity, city names. Not typically used in automated geolocation. -- [float] == cloud fields Fields related to the cloud or infrastructure the events are coming from. *`cloud.provider`*:: + -- type: keyword example: ec2 Name of the cloud provider. Example values are ec2, gce, or digitalocean. -- *`cloud.availability_zone`*:: + -- type: keyword example: us-east-1c Availability zone in which this host is running. -- *`cloud.region`*:: + -- type: keyword example: us-east-1 Region in which this host is running. -- *`cloud.instance.id`*:: + -- type: keyword example: i-1234567890abcdef0 Instance ID of the host machine. -- *`cloud.instance.name`*:: + -- type: keyword Instance name of the host machine. -- *`cloud.machine.type`*:: + -- type: keyword example: t2.medium Machine type of the host machine. -- *`cloud.account.id`*:: + -- type: keyword example: 666777888999 The cloud account or organization id used to identify different entities in a multi-tenant environment. Examples: AWS account id, Google Cloud ORG Id, or other unique identifier. -- [float] == container fields Container fields are used for meta information about the specific container that is the source of information. These fields help correlate data based containers from any runtime. *`container.runtime`*:: + -- type: keyword example: docker Runtime managing this container. -- *`container.id`*:: + -- type: keyword Unique container id. -- *`container.image.name`*:: + -- type: keyword Name of the image the container was built on. -- *`container.image.tag`*:: + -- type: keyword Container image tag. -- *`container.name`*:: + -- type: keyword Container name. -- *`container.labels`*:: + -- type: object Image labels. -- [float] == destination fields Destination fields describe details about the destination of a packet/event. Destination fields are usually populated in conjunction with source fields. *`destination.ip`*:: + -- type: ip IP address of the destination. Can be one or multiple IPv4 or IPv6 addresses. -- *`destination.port`*:: + -- type: long Port of the destination. -- *`destination.mac`*:: + -- type: keyword MAC address of the destination. -- *`destination.domain`*:: + -- type: keyword Destination domain. -- *`destination.bytes`*:: + -- type: long example: 184 Bytes sent from the destination to the source. -- *`destination.packets`*:: + -- type: long example: 12 Packets sent from the destination to the source. -- [float] == geo fields Geo fields can carry data about a specific location related to an event or geo information derived from an IP field. *`destination.geo.location`*:: + -- type: geo_point example: { ""lon"": -73.614830, ""lat"": 45.505918 } Longitude and latitude. -- *`destination.geo.continent_name`*:: + -- type: keyword example: North America Name of the continent. -- *`destination.geo.country_name`*:: + -- type: keyword example: Canada Country name. -- *`destination.geo.region_name`*:: + -- type: keyword example: Quebec Region name. -- *`destination.geo.city_name`*:: + -- type: keyword example: Montreal City name. -- *`destination.geo.country_iso_code`*:: + -- type: keyword example: CA Country ISO code. -- *`destination.geo.region_iso_code`*:: + -- type: keyword example: CA-QC Region ISO code. -- *`destination.geo.name`*:: + -- type: keyword example: boston-dc User-defined description of a location, at the level of granularity they care about. Could be the name of their data centers, the floor number, if this describes a local physical entity, city names. Not typically used in automated geolocation. -- [float] == ecs fields Meta-information specific to ECS. *`ecs.version`*:: + -- type: keyword example: 1.0.0-beta1 required: True ECS version this event conforms to. `ecs.version` is a required field and must exist in all events. When querying across multiple indices -- which may conform to slightly different ECS versions -- this field lets integrations adjust to the schema version of the events. The current version is 1.0.0-beta1 . -- [float] == error fields These fields can represent errors of any kind. Use them for errors that happen while fetching events or in cases where the event itself contains an error. *`error.id`*:: + -- type: keyword Unique identifier for the error. -- *`error.message`*:: + -- type: text Error message. -- *`error.code`*:: + -- type: keyword Error code describing the error. -- [float] == event fields The event fields are used for context information about the log or metric event itself. A log is defined as an event containing details of something that happened. Log events must include the time at which the thing happened. Examples of log events include a process starting on a host, a network packet being sent from a source to a destination, or a network connection between a client and a server being initiated or closed. A metric is defined as an event containing one or more numerical or categorical measurements and the time at which the measurement was taken. Examples of metric events include memory pressure measured on a host, or vulnerabilities measured on a scanned host. *`event.id`*:: + -- type: keyword example: 8a4f500d Unique ID to describe the event. -- *`event.kind`*:: + -- type: keyword example: state The kind of the event. This gives information about what type of information the event contains, without being specific to the contents of the event. Examples are `event`, `state`, `alarm`. Warning: In future versions of ECS, we plan to provide a list of acceptable values for this field, please use with caution. -- *`event.category`*:: + -- type: keyword example: user-management Event category. This contains high-level information about the contents of the event. It is more generic than `event.action`, in the sense that typically a category contains multiple actions. Warning: In future versions of ECS, we plan to provide a list of acceptable values for this field, please use with caution. -- *`event.action`*:: + -- type: keyword example: user-password-change The action captured by the event. This describes the information in the event. It is more specific than `event.category`. Examples are `group-add`, `process-started`, `file-created`. The value is normally defined by the implementer. -- *`event.outcome`*:: + -- type: keyword example: success The outcome of the event. If the event describes an action, this fields contains the outcome of that action. Examples outcomes are `success` and `failure`. Warning: In future versions of ECS, we plan to provide a list of acceptable values for this field, please use with caution. -- *`event.type`*:: + -- type: keyword Reserved for future usage. Please avoid using this field for user data. -- *`event.module`*:: + -- type: keyword example: mysql Name of the module this data is coming from. This information is coming from the modules used in Beats or Logstash. -- *`event.dataset`*:: + -- type: keyword example: stats Name of the dataset. The concept of a `dataset` (fileset / metricset) is used in Beats as a subset of modules. It contains the information which is currently stored in metricset.name and metricset.module or fileset.name. -- *`event.severity`*:: + -- type: long example: 7 Severity describes the severity of the event. What the different severity values mean can very different between use cases. It's up to the implementer to make sure severities are consistent across events. -- *`event.original`*:: + -- type: keyword example: Sep 19 08:26:10 host CEF:0|Security| threatmanager|1.0|100| worm successfully stopped|10|src=10.0.0.1 dst=2.1.2.2spt=1232 Raw text message of entire event. Used to demonstrate log integrity. This field is not indexed and doc_values are disabled. It cannot be searched, but it can be retrieved from `_source`. Field is not indexed. -- *`event.hash`*:: + -- type: keyword example: 123456789012345678901234567890ABCD Hash (perhaps logstash fingerprint) of raw field to be able to demonstrate log integrity. -- *`event.duration`*:: + -- type: long Duration of the event in nanoseconds. If event.start and event.end are known this value should be the difference between the end and start time. -- *`event.timezone`*:: + -- type: keyword This field should be populated when the event's timestamp does not include timezone information already (e.g. default Syslog timestamps). It's optional otherwise. Acceptable timezone formats are: a canonical ID (e.g. ""Europe/Amsterdam""), abbreviated (e.g. ""EST"") or an HH:mm differential (e.g. ""-05:00""). -- *`event.created`*:: + -- type: date event.created contains the date when the event was created. This timestamp is distinct from @timestamp in that @timestamp contains the processed timestamp. For logs these two timestamps can be different as the timestamp in the log line and when the event is read for example by Filebeat are not identical. `@timestamp` must contain the timestamp extracted from the log line, event.created when the log line is read. The same could apply to package capturing where @timestamp contains the timestamp extracted from the network package and event.created when the event was created. In case the two timestamps are identical, @timestamp should be used. -- *`event.start`*:: + -- type: date event.start contains the date when the event started or when the activity was first observed. -- *`event.end`*:: + -- type: date event.end contains the date when the event ended or when the activity was last observed. -- *`event.risk_score`*:: + -- type: float Risk score or priority of the event (e.g. security solutions). Use your system's original value here. -- *`event.risk_score_norm`*:: + -- type: float Normalized risk score or priority of the event, on a scale of 0 to 100. This is mainly useful if you use more than one system that assigns risk scores, and you want to see a normalized value across all systems. -- [float] == file fields A file is defined as a set of information that has been created on, or has existed on a filesystem. File objects can be associated with host events, network events, and/or file events (e.g., those produced by File Integrity Monitoring [FIM] products or services). File fields provide details about the affected file associated with the event or metric. *`file.path`*:: + -- type: keyword Path to the file. -- *`file.target_path`*:: + -- type: keyword Target path for symlinks. -- *`file.extension`*:: + -- type: keyword example: png File extension. This should allow easy filtering by file extensions. -- *`file.type`*:: + -- type: keyword File type (file, dir, or symlink). -- *`file.device`*:: + -- type: keyword Device that is the source of the file. -- *`file.inode`*:: + -- type: keyword Inode representing the file in the filesystem. -- *`file.uid`*:: + -- type: keyword The user ID (UID) or security identifier (SID) of the file owner. -- *`file.owner`*:: + -- type: keyword File owner's username. -- *`file.gid`*:: + -- type: keyword Primary group ID (GID) of the file. -- *`file.group`*:: + -- type: keyword Primary group name of the file. -- *`file.mode`*:: + -- type: keyword example: 416 Mode of the file in octal representation. -- *`file.size`*:: + -- type: long File size in bytes (field is only added when `type` is `file`). -- *`file.mtime`*:: + -- type: date Last time file content was modified. -- *`file.ctime`*:: + -- type: date Last time file metadata changed. -- [float] == group fields The group fields are meant to represent groups that are relevant to the event. *`group.id`*:: + -- type: keyword Unique identifier for the group on the system/platform. -- *`group.name`*:: + -- type: keyword Name of the group. -- [float] == host fields A host is defined as a general computing instance. ECS host.* fields should be populated with details about the host on which the event happened, or on which the measurement was taken. Host types include hardware, virtual machines, Docker containers, and Kubernetes nodes. *`host.hostname`*:: + -- type: keyword Hostname of the host. It normally contains what the `hostname` command returns on the host machine. -- *`host.name`*:: + -- type: keyword Name of the host. It can contain what `hostname` returns on Unix systems, the fully qualified domain name, or a name specified by the user. The sender decides which value to use. -- *`host.id`*:: + -- type: keyword Unique host id. As hostname is not always unique, use values that are meaningful in your environment. Example: The current usage of `beat.name`. -- *`host.ip`*:: + -- type: ip Host ip address. -- *`host.mac`*:: + -- type: keyword Host mac address. -- *`host.type`*:: + -- type: keyword Type of host. For Cloud providers this can be the machine type like `t2.medium`. If vm, this could be the container, for example, or other information meaningful in your environment. -- *`host.architecture`*:: + -- type: keyword example: x86_64 Operating system architecture. -- [float] == os fields The OS fields contain information about the operating system. *`host.os.platform`*:: + -- type: keyword example: darwin Operating system platform (such centos, ubuntu, windows). -- *`host.os.name`*:: + -- type: keyword example: Mac OS X Operating system name. -- *`host.os.family`*:: + -- type: keyword example: debian OS family (such as redhat, debian, freebsd, windows). -- *`host.os.version`*:: + -- type: keyword example: 10.12.6-rc2 Operating system version as a raw string. -- *`host.os.kernel`*:: + -- type: keyword example: 4.4.0-112-generic Operating system kernel version as a raw string. -- [float] == geo fields Geo fields can carry data about a specific location related to an event or geo information derived from an IP field. *`host.geo.location`*:: + -- type: geo_point example: { ""lon"": -73.614830, ""lat"": 45.505918 } Longitude and latitude. -- *`host.geo.continent_name`*:: + -- type: keyword example: North America Name of the continent. -- *`host.geo.country_name`*:: + -- type: keyword example: Canada Country name. -- *`host.geo.region_name`*:: + -- type: keyword example: Quebec Region name. -- *`host.geo.city_name`*:: + -- type: keyword example: Montreal City name. -- *`host.geo.country_iso_code`*:: + -- type: keyword example: CA Country ISO code. -- *`host.geo.region_iso_code`*:: + -- type: keyword example: CA-QC Region ISO code. -- *`host.geo.name`*:: + -- type: keyword example: boston-dc User-defined description of a location, at the level of granularity they care about. Could be the name of their data centers, the floor number, if this describes a local physical entity, city names. Not typically used in automated geolocation. -- [float] == http fields Fields related to HTTP activity. *`http.request.method`*:: + -- type: keyword example: GET, POST, PUT Http request method. -- *`http.request.referrer`*:: + -- type: keyword example: https://blog.example.com/ Referrer for this HTTP request. -- *`http.response.status_code`*:: + -- type: long example: 404 Http response status code. -- *`http.response.body`*:: + -- type: keyword example: Hello world The full http response body. -- *`http.version`*:: + -- type: keyword example: 1.1 Http version. -- [float] == log fields Fields which are specific to log events. *`log.level`*:: + -- type: keyword example: ERR Log level of the log event. Some examples are `WARN`, `ERR`, `INFO`. -- *`log.original`*:: + -- type: keyword example: Sep 19 08:26:10 localhost My log This is the original log message and contains the full log message before splitting it up in multiple parts. In contrast to the `message` field which can contain an extracted part of the log message, this field contains the original, full log message. It can have already some modifications applied like encoding or new lines removed to clean up the log message. This field is not indexed and doc_values are disabled so it can't be queried but the value can be retrieved from `_source`. Field is not indexed. -- [float] == network fields The network is defined as the communication path over which a host or network event happens. The network.* fields should be populated with details about the network activity associated with an event. *`network.name`*:: + -- type: keyword example: Guest Wifi Name given by operators to sections of their network. -- *`network.type`*:: + -- type: keyword example: IPv4 In the OSI Model this would be the Network Layer. IPv4, IPv6, IPSec, PIM, etc -- *`network.iana_number`*:: + -- type: keyword example: 6 IANA Protocol Number (https://www.iana.org/assignments/protocol-numbers/protocol-numbers.xhtml). Standardized list of protocols. This aligns well with NetFlow and sFlow related logs which use the IANA Protocol Number. -- *`network.transport`*:: + -- type: keyword example: TCP Same as network.iana_number, but instead using the Keyword name of the transport layer (UDP, TCP, IPv6-ICMP, etc.) -- *`network.application`*:: + -- type: keyword example: AIM A name given to an application. This can be arbitrarily assigned for things like microservices, but also apply to things like skype, icq, facebook, twitter. This would be used in situations where the vendor or service can be decoded such as from the source/dest IP owners, ports, or wire format. -- *`network.protocol`*:: + -- type: keyword example: http L7 Network protocol name. ex. http, lumberjack, transport protocol -- *`network.direction`*:: + -- type: keyword example: inbound Direction of the network traffic. Recommended values are: * inbound * outbound * internal * external * unknown When mapping events from a host-based monitoring context, populate this field from the host's point of view. When mapping events from a network or perimeter-based monitoring context, populate this field from the point of view of your network perimeter. -- *`network.forwarded_ip`*:: + -- type: ip example: 192.1.1.2 Host IP address when the source IP address is the proxy. -- *`network.community_id`*:: + -- type: keyword example: 1:hO+sN4H+MG5MY/8hIrXPqc4ZQz0= A hash of source and destination IPs and ports, as well as the protocol used in a communication. This is a tool-agnostic standard to identify flows. Learn more at https://github.com/corelight/community-id-spec. -- *`network.bytes`*:: + -- type: long example: 368 Total bytes transferred in both directions. If `source.bytes` and `destination.bytes` are known, `network.bytes` is their sum. -- *`network.packets`*:: + -- type: long example: 24 Total packets transferred in both directions. If `source.packets` and `destination.packets` are known, `network.packets` is their sum. -- [float] == observer fields An observer is defined as a special network, security, or application device used to detect, observe, or create network, security, or application-related events and metrics. This could be a custom hardware appliance or a server that has been configured to run special network, security, or application software. Examples include firewalls, intrusion detection/prevention systems, network monitoring sensors, web application firewalls, data loss prevention systems, and APM servers. The observer.* fields shall be populated with details of the system, if any, that detects, observes and/or creates a network, security, or application event or metric. Message queues and ETL components used in processing events or metrics are not considered observers in ECS. *`observer.mac`*:: + -- type: keyword MAC address of the observer -- *`observer.ip`*:: + -- type: ip IP address of the observer. -- *`observer.hostname`*:: + -- type: keyword Hostname of the observer. -- *`observer.vendor`*:: + -- type: keyword observer vendor information. -- *`observer.version`*:: + -- type: keyword Observer version. -- *`observer.serial_number`*:: + -- type: keyword Observer serial number. -- *`observer.type`*:: + -- type: keyword example: firewall The type of the observer the data is coming from. There is no predefined list of observer types. Some examples are `forwarder`, `firewall`, `ids`, `ips`, `proxy`, `poller`, `sensor`, `APM server`. -- [float] == os fields The OS fields contain information about the operating system. *`observer.os.platform`*:: + -- type: keyword example: darwin Operating system platform (such centos, ubuntu, windows). -- *`observer.os.name`*:: + -- type: keyword example: Mac OS X Operating system name. -- *`observer.os.family`*:: + -- type: keyword example: debian OS family (such as redhat, debian, freebsd, windows). -- *`observer.os.version`*:: + -- type: keyword example: 10.12.6-rc2 Operating system version as a raw string. -- *`observer.os.kernel`*:: + -- type: keyword example: 4.4.0-112-generic Operating system kernel version as a raw string. -- [float] == geo fields Geo fields can carry data about a specific location related to an event or geo information derived from an IP field. *`observer.geo.location`*:: + -- type: geo_point example: { ""lon"": -73.614830, ""lat"": 45.505918 } Longitude and latitude. -- *`observer.geo.continent_name`*:: + -- type: keyword example: North America Name of the continent. -- *`observer.geo.country_name`*:: + -- type: keyword example: Canada Country name. -- *`observer.geo.region_name`*:: + -- type: keyword example: Quebec Region name. -- *`observer.geo.city_name`*:: + -- type: keyword example: Montreal City name. -- *`observer.geo.country_iso_code`*:: + -- type: keyword example: CA Country ISO code. -- *`observer.geo.region_iso_code`*:: + -- type: keyword example: CA-QC Region ISO code. -- *`observer.geo.name`*:: + -- type: keyword example: boston-dc User-defined description of a location, at the level of granularity they care about. Could be the name of their data centers, the floor number, if this describes a local physical entity, city names. Not typically used in automated geolocation. -- [float] == organization fields The organization fields enrich data with information about the company or entity the data is associated with. These fields help you arrange or filter data stored in an index by one or multiple organizations. *`organization.name`*:: + -- type: keyword Organization name. -- *`organization.id`*:: + -- type: keyword Unique identifier for the organization. -- [float] == os fields The OS fields contain information about the operating system. *`os.platform`*:: + -- type: keyword example: darwin Operating system platform (such centos, ubuntu, windows). -- *`os.name`*:: + -- type: keyword example: Mac OS X Operating system name. -- *`os.family`*:: + -- type: keyword example: debian OS family (such as redhat, debian, freebsd, windows). -- *`os.version`*:: + -- type: keyword example: 10.12.6-rc2 Operating system version as a raw string. -- *`os.kernel`*:: + -- type: keyword example: 4.4.0-112-generic Operating system kernel version as a raw string. -- [float] == process fields These fields contain information about a process. These fields can help you correlate metrics information with a process id/name from a log message. The `process.pid` often stays in the metric itself and is copied to the global field for correlation. *`process.pid`*:: + -- type: long Process id. -- *`process.name`*:: + -- type: keyword example: ssh Process name. Sometimes called program name or similar. -- *`process.ppid`*:: + -- type: long Process parent id. -- *`process.args`*:: + -- type: keyword example: ['ssh', '-l', 'user', '10.0.0.16'] Process arguments. May be filtered to protect sensitive information. -- *`process.executable`*:: + -- type: keyword example: /usr/bin/ssh Absolute path to the process executable. -- *`process.title`*:: + -- type: keyword Process title. The proctitle, some times the same as process name. Can also be different: for example a browser setting its title to the web page currently opened. -- *`process.thread.id`*:: + -- type: long example: 4242 Thread ID. -- *`process.start`*:: + -- type: date example: 2016-05-23T08:05:34.853Z The time the process started. -- *`process.working_directory`*:: + -- type: keyword example: /home/alice The working directory of the process. -- [float] == related fields This field set is meant to facilitate pivoting around a piece of data. Some pieces of information can be seen in many places in ECS. To facilitate searching for them, append values to their corresponding field in `related.`. A concrete example is IP addresses, which can be under host, observer, source, destination, client, server, and network.forwarded_ip. If you append all IPs to `related.ip`, you can then search for a given IP trivially, no matter where it appeared, by querying `related.ip:a.b.c.d`. *`related.ip`*:: + -- type: ip All of the IPs seen on your event. -- [float] == server fields A Server is defined as the responder in a network connection for events regarding sessions, connections, or bidirectional flow records. For TCP events, the server is the receiver of the initial SYN packet(s) of the TCP connection. For other protocols, the server is generally the responder in the network transaction. Some systems actually use the term ""responder"" to refer the server in TCP connections. The server fields describe details about the system acting as the server in the network event. Server fields are usually populated in conjunction with client fields. Server fields are generally not populated for packet-level events. *`server.ip`*:: + -- type: ip IP address of the server. Can be one or multiple IPv4 or IPv6 addresses. -- *`server.port`*:: + -- type: long Port of the server. -- *`server.mac`*:: + -- type: keyword MAC address of the server. -- *`server.domain`*:: + -- type: keyword Server domain. -- *`server.bytes`*:: + -- type: long example: 184 Bytes sent from the server to the client. -- *`server.packets`*:: + -- type: long example: 12 Packets sent from the server to the client. -- [float] == geo fields Geo fields can carry data about a specific location related to an event or geo information derived from an IP field. *`server.geo.location`*:: + -- type: geo_point example: { ""lon"": -73.614830, ""lat"": 45.505918 } Longitude and latitude. -- *`server.geo.continent_name`*:: + -- type: keyword example: North America Name of the continent. -- *`server.geo.country_name`*:: + -- type: keyword example: Canada Country name. -- *`server.geo.region_name`*:: + -- type: keyword example: Quebec Region name. -- *`server.geo.city_name`*:: + -- type: keyword example: Montreal City name. -- *`server.geo.country_iso_code`*:: + -- type: keyword example: CA Country ISO code. -- *`server.geo.region_iso_code`*:: + -- type: keyword example: CA-QC Region ISO code. -- *`server.geo.name`*:: + -- type: keyword example: boston-dc User-defined description of a location, at the level of granularity they care about. Could be the name of their data centers, the floor number, if this describes a local physical entity, city names. Not typically used in automated geolocation. -- [float] == service fields The service fields describe the service for or from which the data was collected. These fields help you find and correlate logs for a specific service and version. *`service.id`*:: + -- type: keyword example: d37e5ebfe0ae6c4972dbe9f0174a1637bb8247f6 Unique identifier of the running service. This id should uniquely identify this service. This makes it possible to correlate logs and metrics for one specific service. Example: If you are experiencing issues with one redis instance, you can filter on that id to see metrics and logs for that single instance. -- *`service.name`*:: + -- type: keyword example: elasticsearch-metrics Name of the service data is collected from. The name of the service is normally user given. This allows if two instances of the same service are running on the same machine they can be differentiated by the `service.name`. Also it allows for distributed services that run on multiple hosts to correlate the related instances based on the name. In the case of Elasticsearch the service.name could contain the cluster name. For Beats the service.name is by default a copy of the `service.type` field if no name is specified. -- *`service.type`*:: + -- type: keyword example: elasticsearch The type of the service data is collected from. The type can be used to group and correlate logs and metrics from one service type. Example: If logs or metrics are collected from Elasticsearch, `service.type` would be `elasticsearch`. -- *`service.state`*:: + -- type: keyword Current state of the service. -- *`service.version`*:: + -- type: keyword example: 3.2.4 Version of the service the data was collected from. This allows to look at a data set only for a specific version of a service. -- *`service.ephemeral_id`*:: + -- type: keyword example: 8a4f500f Ephemeral identifier of this service (if one exists). This id normally changes across restarts, but `service.id` does not. -- [float] == source fields Source fields describe details about the source of a packet/event. Source fields are usually populated in conjunction with destination fields. *`source.address`*:: + -- type: keyword Some event source addresses are defined ambiguously. The event will sometimes list an IP, a domain or a unix socket. You should always store the raw address in the `.address` field. Then it should be duplicated to `.ip` or `.domain`, depending on which one it is. -- *`source.ip`*:: + -- type: ip IP address of the source. Can be one or multiple IPv4 or IPv6 addresses. -- *`source.port`*:: + -- type: long Port of the source. -- *`source.mac`*:: + -- type: keyword MAC address of the source. -- *`source.domain`*:: + -- type: keyword Source domain. -- *`source.bytes`*:: + -- type: long example: 184 Bytes sent from the source to the destination. -- *`source.packets`*:: + -- type: long example: 12 Packets sent from the source to the destination. -- [float] == geo fields Geo fields can carry data about a specific location related to an event or geo information derived from an IP field. *`source.geo.location`*:: + -- type: geo_point example: { ""lon"": -73.614830, ""lat"": 45.505918 } Longitude and latitude. -- *`source.geo.continent_name`*:: + -- type: keyword example: North America Name of the continent. -- *`source.geo.country_name`*:: + -- type: keyword example: Canada Country name. -- *`source.geo.region_name`*:: + -- type: keyword example: Quebec Region name. -- *`source.geo.city_name`*:: + -- type: keyword example: Montreal City name. -- *`source.geo.country_iso_code`*:: + -- type: keyword example: CA Country ISO code. -- *`source.geo.region_iso_code`*:: + -- type: keyword example: CA-QC Region ISO code. -- *`source.geo.name`*:: + -- type: keyword example: boston-dc User-defined description of a location, at the level of granularity they care about. Could be the name of their data centers, the floor number, if this describes a local physical entity, city names. Not typically used in automated geolocation. -- [float] == url fields URL fields provide a complete URL, with scheme, host, and path. *`url.original`*:: + -- type: keyword example: https://www.elastic.co:443/search?q=elasticsearch#top or /search?q=elasticsearch Unmodified original url as seen in the event source. Note that in network monitoring, the observed URL may be a full URL, whereas in access logs, the URL is often just represented as a path. This field is meant to represent the URL as it was observed, complete or not. -- *`url.full`*:: + -- type: keyword example: https://www.elastic.co:443/search?q=elasticsearch#top If full URLs are important to your use case, they should be stored in `url.full`, whether this field is reconstructed or present in the event source. -- *`url.scheme`*:: + -- type: keyword example: https Scheme of the request, such as ""https"". Note: The `:` is not part of the scheme. -- *`url.domain`*:: + -- type: keyword example: www.elastic.co Domain of the request, such as ""www.elastic.co"". In some cases a URL may refer to an IP and/or port directly, without a domain name. In this case, the IP address would go to the `domain` field. -- *`url.port`*:: + -- type: integer example: 443 Port of the request, such as 443. -- *`url.path`*:: + -- type: keyword Path of the request, such as ""/search"". -- *`url.query`*:: + -- type: keyword The query field describes the query string of the request, such as ""q=elasticsearch"". The `?` is excluded from the query string. If a URL contains no `?`, there is no query field. If there is a `?` but no query, the query field exists with an empty string. The `exists` query can be used to differentiate between the two cases. -- *`url.fragment`*:: + -- type: keyword Portion of the url after the `#`, such as ""top"". The `#` is not part of the fragment. -- *`url.username`*:: + -- type: keyword Username of the request. -- *`url.password`*:: + -- type: keyword Password of the request. -- [float] == user fields The user fields describe information about the user that is relevant to the event. Fields can have one entry or multiple entries. If a user has more than one id, provide an array that includes all of them. *`user.id`*:: + -- type: keyword One or multiple unique identifiers of the user. -- *`user.name`*:: + -- type: keyword example: albert Short name or login of the user. -- *`user.full_name`*:: + -- type: keyword example: Albert Einstein User's full name, if available. -- *`user.email`*:: + -- type: keyword User email address. -- *`user.hash`*:: + -- type: keyword Unique user hash to correlate information for a user in anonymized form. Useful if `user.id` or `user.name` contain confidential information and cannot be used. -- *`user.group`*:: + -- type: keyword Group the user is a part of. This field can contain a list of groups, if necessary. -- [float] == user_agent fields The user_agent fields normally come from a browser request. They often show up in web service logs coming from the parsed user agent string. *`user_agent.original`*:: + -- type: keyword example: Mozilla/5.0 (iPhone; CPU iPhone OS 12_1 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/12.0 Mobile/15E148 Safari/604.1 Unparsed version of the user_agent. Field is not indexed. -- *`user_agent.name`*:: + -- type: keyword example: Safari Name of the user agent. -- *`user_agent.version`*:: + -- type: keyword example: 12.0 Version of the user agent. -- *`user_agent.device.name`*:: + -- type: keyword example: iPhone Name of the device. -- [float] == os fields The OS fields contain information about the operating system. *`user_agent.os.platform`*:: + -- type: keyword example: darwin Operating system platform (such centos, ubuntu, windows). -- *`user_agent.os.name`*:: + -- type: keyword example: Mac OS X Operating system name. -- *`user_agent.os.family`*:: + -- type: keyword example: debian OS family (such as redhat, debian, freebsd, windows). -- *`user_agent.os.version`*:: + -- type: keyword example: 10.12.6-rc2 Operating system version as a raw string. -- *`user_agent.os.kernel`*:: + -- type: keyword example: 4.4.0-112-generic Operating system kernel version as a raw string. -- *`beat.name`*:: + -- type: alias alias to: agent.type -- *`beat.hostname`*:: + -- type: alias alias to: agent.hostname -- *`agent.hostname`*:: + -- type: keyword Hostname of the agent. -- *`user_agent.patch`*:: + -- type: keyword Patch version of the user agent. -- *`user_agent.minor`*:: + -- type: keyword Minor version of the user agent. -- *`user_agent.major`*:: + -- type: keyword Major version of the user agent. -- *`user_agent.device`*:: + -- type: keyword Name of the physical device. -- *`user_agent.os.major`*:: + -- type: long Major version of the operating system. -- *`user_agent.os.minor`*:: + -- type: long Minor version of the operating system. -- *`url.hostname`*:: + -- type: keyword Hostname of the request, such as ""elastic.co"". -- [[exported-fields-host-processor]] == Host fields Info collected for the host machine. [[exported-fields-http]] == HTTP monitor fields None [float] == http fields HTTP related fields. *`http.url`*:: + -- type: text Service url used by monitor. *`http.url.raw`*:: + -- type: keyword The service url used by monitor. This is a non-analyzed field that is useful for aggregations. -- -- [float] == rtt fields HTTP layer round trip times. [float] == validate fields Duration between first byte of HTTP request being written and response being processed by validator. Duration based on already available network connection. Note: if validator is not reading body or only a prefix, this number does not fully represent the total time needed to read the body. *`http.rtt.validate.us`*:: + -- type: long Duration in microseconds -- [float] == validate_body fields Duration of validator required to read and validate the response body. Note: if validator is not reading body or only a prefix, this number does not fully represent the total time needed to read the body. *`http.rtt.validate_body.us`*:: + -- type: long Duration in microseconds -- [float] == write_request fields Duration of sending the complete HTTP request. Duration based on already available network connection. *`http.rtt.write_request.us`*:: + -- type: long Duration in microseconds -- [float] == response_header fields Time required between sending the start of sending the HTTP request and first byte from HTTP response being read. Duration based on already available network connection. *`http.rtt.response_header.us`*:: + -- type: long Duration in microseconds -- *`http.rtt.content.us`*:: + -- type: long Time required to retrieved the content in micro seconds. -- [float] == total fields Duration required to process the HTTP transaction. Starts with the initial TCP connection attempt. Ends with after validator did check the response. Note: if validator is not reading body or only a prefix, this number does not fully represent the total time needed. *`http.rtt.total.us`*:: + -- type: long Duration in microseconds -- [[exported-fields-icmp]] == ICMP fields None [float] == icmp fields IP ping fields. *`icmp.requests`*:: + -- type: integer Number if ICMP EchoRequests send. -- [float] == rtt fields ICMP Echo Request and Reply round trip time *`icmp.rtt.us`*:: + -- type: long Duration in microseconds -- [[exported-fields-kubernetes-processor]] == Kubernetes fields Kubernetes metadata added by the kubernetes processor *`kubernetes.pod.name`*:: + -- type: keyword Kubernetes pod name -- *`kubernetes.pod.uid`*:: + -- type: keyword Kubernetes Pod UID -- *`kubernetes.namespace`*:: + -- type: keyword Kubernetes namespace -- *`kubernetes.node.name`*:: + -- type: keyword Kubernetes node name -- *`kubernetes.labels`*:: + -- type: object Kubernetes labels map -- *`kubernetes.annotations`*:: + -- type: object Kubernetes annotations map -- *`kubernetes.container.name`*:: + -- type: keyword Kubernetes container name -- *`kubernetes.container.image`*:: + -- type: keyword Kubernetes container image -- [[exported-fields-resolve]] == Host lookup fields None [float] == resolve fields Host lookup fields. *`resolve.host`*:: + -- type: keyword Hostname of service being monitored. -- *`resolve.ip`*:: + -- type: ip IP address found for the given host. -- [float] == rtt fields Duration required to resolve an IP from hostname. *`resolve.rtt.us`*:: + -- type: long Duration in microseconds -- [[exported-fields-socks5]] == SOCKS5 proxy fields None [float] == socks5 fields SOCKS5 proxy related fields: [float] == rtt fields TLS layer round trip times. [float] == connect fields Time required to establish a connection via SOCKS5 to endpoint based on available connection to SOCKS5 proxy. *`socks5.rtt.connect.us`*:: + -- type: long Duration in microseconds -- [[exported-fields-tcp]] == TCP layer fields None [float] == tcp fields TCP network layer related fields. *`tcp.port`*:: + -- type: integer Service port number. -- [float] == rtt fields TCP layer round trip times. [float] == connect fields Duration required to establish a TCP connection based on already available IP address. *`tcp.rtt.connect.us`*:: + -- type: long Duration in microseconds -- [float] == validate fields Duration of validation step based on existing TCP connection. *`tcp.rtt.validate.us`*:: + -- type: long Duration in microseconds -- [[exported-fields-tls]] == TLS encryption layer fields None [float] == tls fields TLS layer related fields. *`tls.certificate_not_valid_before`*:: + -- type: date Earliest time at which the connection's certificates are valid. -- *`tls.certificate_not_valid_after`*:: + -- type: date Latest time at which the connection's certificates are valid. -- [float] == rtt fields TLS layer round trip times. [float] == handshake fields Time required to finish TLS handshake based on already available network connection. *`tls.rtt.handshake.us`*:: + -- type: long Duration in microseconds -- ",12428,True,2932.4659418117017,median "********************************************************************** * UTILS ********************************************************************** CLASS lcl_utils DEFINITION FINAL. PUBLIC SECTION. CLASS-METHODS normalize_path IMPORTING iv_path TYPE string RETURNING VALUE(rv_path) TYPE string. CLASS-METHODS split_path IMPORTING iv_path TYPE string RETURNING VALUE(rv_path_name) TYPE zif_abapgit_ajson=>ty_path_name. CLASS-METHODS validate_array_index IMPORTING iv_path TYPE string iv_index TYPE string RETURNING VALUE(rv_index) TYPE i RAISING zcx_abapgit_ajson_error. ENDCLASS. CLASS lcl_utils IMPLEMENTATION. METHOD validate_array_index. IF NOT iv_index CO '0123456789'. zcx_abapgit_ajson_error=>raise( |Cannot add non-numeric key [{ iv_index }] to array [{ iv_path }]| ). ENDIF. rv_index = iv_index. IF rv_index = 0. zcx_abapgit_ajson_error=>raise( |Cannot add zero key to array [{ iv_path }]| ). ENDIF. ENDMETHOD. METHOD normalize_path. rv_path = iv_path. IF strlen( rv_path ) = 0. rv_path = '/'. ENDIF. IF rv_path+0(1) <> '/'. rv_path = '/' && rv_path. ENDIF. IF substring( val = rv_path off = strlen( rv_path ) - 1 ) <> '/'. rv_path = rv_path && '/'. ENDIF. ENDMETHOD. METHOD split_path. DATA lv_offs TYPE i. DATA lv_len TYPE i. DATA lv_trim_slash TYPE i. lv_len = strlen( iv_path ). IF lv_len = 0 OR iv_path = '/'. RETURN. "" empty path is the alias for root item = '' + '' ENDIF. IF substring( val = iv_path off = lv_len - 1 ) = '/'. lv_trim_slash = 1. "" ignore last '/' ENDIF. lv_offs = find( val = reverse( iv_path ) sub = '/' off = lv_trim_slash ). IF lv_offs = -1. lv_offs = lv_len. "" treat whole string as the 'name' part ENDIF. lv_offs = lv_len - lv_offs. rv_path_name-path = normalize_path( substring( val = iv_path len = lv_offs ) ). rv_path_name-name = substring( val = iv_path off = lv_offs len = lv_len - lv_offs - lv_trim_slash ). ENDMETHOD. ENDCLASS. ********************************************************************** * PARSER ********************************************************************** CLASS lcl_json_parser DEFINITION FINAL. PUBLIC SECTION. METHODS parse IMPORTING iv_json TYPE string RETURNING VALUE(rt_json_tree) TYPE zif_abapgit_ajson=>ty_nodes_tt RAISING zcx_abapgit_ajson_error. PRIVATE SECTION. TYPES: ty_stack_tt TYPE STANDARD TABLE OF REF TO zif_abapgit_ajson=>ty_node. DATA mt_stack TYPE ty_stack_tt. CLASS-METHODS join_path IMPORTING it_stack TYPE ty_stack_tt RETURNING VALUE(rv_path) TYPE string. METHODS raise IMPORTING iv_error TYPE string RAISING zcx_abapgit_ajson_error. METHODS _parse IMPORTING iv_json TYPE string RETURNING VALUE(rt_json_tree) TYPE zif_abapgit_ajson=>ty_nodes_tt RAISING zcx_abapgit_ajson_error cx_sxml_error. METHODS _get_location IMPORTING iv_json TYPE string iv_offset TYPE i RETURNING VALUE(rv_location) TYPE string. ENDCLASS. CLASS lcl_json_parser IMPLEMENTATION. METHOD parse. DATA lx_sxml_parse TYPE REF TO cx_sxml_parse_error. DATA lx_sxml TYPE REF TO cx_sxml_error. DATA lv_location TYPE string. TRY. "" TODO sane JSON check: "" JSON can be true,false,null,(-)digits "" or start from "" or from { rt_json_tree = _parse( iv_json ). CATCH cx_sxml_parse_error INTO lx_sxml_parse. lv_location = _get_location( iv_json = iv_json iv_offset = lx_sxml_parse->xml_offset ). zcx_abapgit_ajson_error=>raise( iv_msg = |Json parsing error (SXML): { lx_sxml_parse->get_text( ) }| iv_location = lv_location ). CATCH cx_sxml_error INTO lx_sxml. zcx_abapgit_ajson_error=>raise( iv_msg = |Json parsing error (SXML): { lx_sxml->get_text( ) }| iv_location = '@PARSER' ). ENDTRY. ENDMETHOD. METHOD _get_location. DATA lv_json TYPE string. DATA lv_offset TYPE i. DATA lt_text TYPE TABLE OF string. DATA lv_text TYPE string. DATA lv_line TYPE i. DATA lv_pos TYPE i. lv_offset = iv_offset. IF lv_offset < 0. lv_offset = 0. ENDIF. IF lv_offset > strlen( iv_json ). lv_offset = strlen( iv_json ). ENDIF. lv_json = iv_json(lv_offset). REPLACE ALL OCCURRENCES OF cl_abap_char_utilities=>cr_lf IN lv_json WITH cl_abap_char_utilities=>newline. SPLIT lv_json AT cl_abap_char_utilities=>newline INTO TABLE lt_text. lv_line = lines( lt_text ). IF lv_line = 0. lv_line = 1. lv_pos = 1. ELSE. READ TABLE lt_text INDEX lv_line INTO lv_text. lv_pos = strlen( lv_text ) + 1. ENDIF. rv_location = |Line { lv_line }, Offset { lv_pos }|. ENDMETHOD. METHOD _parse. DATA lo_reader TYPE REF TO if_sxml_reader. DATA lr_stack_top LIKE LINE OF mt_stack. DATA lo_node TYPE REF TO if_sxml_node. FIELD-SYMBOLS LIKE LINE OF rt_json_tree. CLEAR mt_stack. IF iv_json IS INITIAL. RETURN. ENDIF. lo_reader = cl_sxml_string_reader=>create( cl_abap_codepage=>convert_to( iv_json ) ). "" TODO: self protection, check non-empty, check starting from object ... DO. lo_node = lo_reader->read_next_node( ). IF lo_node IS NOT BOUND. EXIT. ENDIF. CASE lo_node->type. WHEN if_sxml_node=>co_nt_element_open. DATA lt_attributes TYPE if_sxml_attribute=>attributes. DATA lo_attr LIKE LINE OF lt_attributes. DATA lo_open TYPE REF TO if_sxml_open_element. lo_open ?= lo_node. APPEND INITIAL LINE TO rt_json_tree ASSIGNING . -type = to_lower( lo_open->qname-name ). READ TABLE mt_stack INDEX 1 INTO lr_stack_top. IF sy-subrc = 0. -path = join_path( mt_stack ). lr_stack_top->children = lr_stack_top->children + 1. IF lr_stack_top->type = 'array'. -name = |{ lr_stack_top->children }|. -index = lr_stack_top->children. ELSE. lt_attributes = lo_open->get_attributes( ). LOOP AT lt_attributes INTO lo_attr. IF lo_attr->qname-name = 'name' AND lo_attr->value_type = if_sxml_value=>co_vt_text. -name = lo_attr->get_value( ). ENDIF. ENDLOOP. ENDIF. IF -name IS INITIAL. raise( 'Node without name (maybe not JSON)' ). ENDIF. ENDIF. GET REFERENCE OF INTO lr_stack_top. INSERT lr_stack_top INTO mt_stack INDEX 1. WHEN if_sxml_node=>co_nt_element_close. DATA lo_close TYPE REF TO if_sxml_close_element. lo_close ?= lo_node. READ TABLE mt_stack INDEX 1 INTO lr_stack_top. DELETE mt_stack INDEX 1. IF lo_close->qname-name <> lr_stack_top->type. raise( 'Unexpected closing node type' ). ENDIF. WHEN if_sxml_node=>co_nt_value. DATA lo_value TYPE REF TO if_sxml_value_node. lo_value ?= lo_node. -value = lo_value->get_value( ). WHEN OTHERS. raise( 'Unexpected node type' ). ENDCASE. ENDDO. IF lines( mt_stack ) > 0. raise( 'Unexpected end of data' ). ENDIF. ENDMETHOD. METHOD join_path. FIELD-SYMBOLS LIKE LINE OF it_stack. LOOP AT it_stack ASSIGNING . rv_path = ->name && '/' && rv_path. ENDLOOP. ENDMETHOD. METHOD raise. zcx_abapgit_ajson_error=>raise( iv_location = join_path( mt_stack ) iv_msg = |JSON PARSER: { iv_error } @ { join_path( mt_stack ) }| ). ENDMETHOD. ENDCLASS. ********************************************************************** * SERIALIZER ********************************************************************** CLASS lcl_json_serializer DEFINITION FINAL CREATE PRIVATE. PUBLIC SECTION. CLASS-METHODS stringify IMPORTING it_json_tree TYPE zif_abapgit_ajson=>ty_nodes_ts iv_indent TYPE i DEFAULT 0 iv_keep_item_order TYPE abap_bool DEFAULT abap_false RETURNING VALUE(rv_json_string) TYPE string RAISING zcx_abapgit_ajson_error. CLASS-METHODS class_constructor. PRIVATE SECTION. CLASS-DATA gv_comma_with_lf TYPE string. DATA mt_json_tree TYPE zif_abapgit_ajson=>ty_nodes_ts. DATA mv_keep_item_order TYPE abap_bool. DATA mt_buffer TYPE string_table. DATA mv_indent_step TYPE i. DATA mv_level TYPE i. CLASS-METHODS escape IMPORTING iv_unescaped TYPE string RETURNING VALUE(rv_escaped) TYPE string. METHODS _stringify RETURNING VALUE(rv_json_string) TYPE string RAISING zcx_abapgit_ajson_error. METHODS stringify_node IMPORTING is_node TYPE zif_abapgit_ajson=>ty_node RAISING zcx_abapgit_ajson_error. METHODS stringify_set IMPORTING iv_parent_path TYPE string iv_array TYPE abap_bool RAISING zcx_abapgit_ajson_error. ENDCLASS. CLASS lcl_json_serializer IMPLEMENTATION. METHOD class_constructor. gv_comma_with_lf = ',' && cl_abap_char_utilities=>newline. ENDMETHOD. METHOD stringify. DATA lo TYPE REF TO lcl_json_serializer. CREATE OBJECT lo. lo->mt_json_tree = it_json_tree. lo->mv_indent_step = iv_indent. lo->mv_keep_item_order = iv_keep_item_order. rv_json_string = lo->_stringify( ). ENDMETHOD. METHOD _stringify. FIELD-SYMBOLS LIKE LINE OF mt_json_tree. READ TABLE mt_json_tree ASSIGNING WITH KEY path = '' name = ''. "" Root IF sy-subrc <> 0. RETURN. ENDIF. stringify_node( ). rv_json_string = concat_lines_of( table = mt_buffer ). ENDMETHOD. METHOD stringify_node. DATA lv_item TYPE string. DATA lv_indent_prefix TYPE string. IF mv_indent_step > 0. lv_indent_prefix = repeat( val = ` ` occ = mv_indent_step * mv_level ). lv_item = lv_indent_prefix. ENDIF. IF is_node-name IS NOT INITIAL AND is_node-index IS INITIAL. "" Not root, not array item IF mv_indent_step > 0. lv_item = lv_item && |""{ is_node-name }"": |. ELSE. lv_item = |""{ is_node-name }"":|. ENDIF. ENDIF. CASE is_node-type. WHEN zif_abapgit_ajson=>node_type-array. lv_item = lv_item && '['. WHEN zif_abapgit_ajson=>node_type-object. lv_item = lv_item && '{'. WHEN zif_abapgit_ajson=>node_type-string. lv_item = lv_item && |""{ escape( is_node-value ) }""|. WHEN zif_abapgit_ajson=>node_type-boolean OR zif_abapgit_ajson=>node_type-number. lv_item = lv_item && is_node-value. WHEN zif_abapgit_ajson=>node_type-null. lv_item = lv_item && 'null'. WHEN OTHERS. zcx_abapgit_ajson_error=>raise( iv_msg = |Unexpected type [{ is_node-type }]| iv_location = is_node-path && is_node-name ). ENDCASE. IF mv_indent_step > 0 AND ( is_node-type = zif_abapgit_ajson=>node_type-array OR is_node-type = zif_abapgit_ajson=>node_type-object ) AND is_node-children > 0. mv_level = mv_level + 1. lv_item = lv_item && cl_abap_char_utilities=>newline. ENDIF. APPEND lv_item TO mt_buffer. "" finish complex item IF is_node-type = zif_abapgit_ajson=>node_type-array OR is_node-type = zif_abapgit_ajson=>node_type-object. DATA lv_children_path TYPE string. DATA lv_tail TYPE string. lv_children_path = is_node-path && is_node-name && '/'. "" for root: path = '' and name = '', so result is '/' CASE is_node-type. WHEN zif_abapgit_ajson=>node_type-array. IF is_node-children > 0. stringify_set( iv_parent_path = lv_children_path iv_array = abap_true ). ENDIF. lv_tail = ']'. WHEN zif_abapgit_ajson=>node_type-object. IF is_node-children > 0. stringify_set( iv_parent_path = lv_children_path iv_array = abap_false ). ENDIF. lv_tail = '}'. ENDCASE. IF mv_indent_step > 0 AND is_node-children > 0. lv_tail = lv_indent_prefix && lv_tail. mv_level = mv_level - 1. ENDIF. APPEND lv_tail TO mt_buffer. ENDIF. ENDMETHOD. METHOD stringify_set. DATA lv_tab_key TYPE string. DATA lv_first_done TYPE abap_bool. FIELD-SYMBOLS LIKE LINE OF mt_json_tree. IF iv_array = abap_true. lv_tab_key = 'array_index'. "" path + index ELSEIF mv_keep_item_order = abap_true. lv_tab_key = 'item_order'. "" path + order ELSE. lv_tab_key = 'primary_key'. "" path + name ENDIF. LOOP AT mt_json_tree ASSIGNING USING KEY (lv_tab_key) WHERE path = iv_parent_path. IF lv_first_done = abap_false. lv_first_done = abap_true. ELSEIF mv_indent_step > 0. APPEND gv_comma_with_lf TO mt_buffer. ELSE. APPEND ',' TO mt_buffer. ENDIF. stringify_node( ). ENDLOOP. IF mv_indent_step > 0 AND lv_first_done = abap_true. "" only of items were in the list APPEND cl_abap_char_utilities=>newline TO mt_buffer. ENDIF. ENDMETHOD. METHOD escape. rv_escaped = iv_unescaped. IF rv_escaped CA |""\\\\\\t\\n\\r|. "" TODO consider performance ... "" see also https://www.json.org/json-en.html rv_escaped = replace( val = rv_escaped sub = '\\' with = '\\\\' occ = 0 ). rv_escaped = replace( val = rv_escaped sub = |\\n| with = '\\n' occ = 0 ). rv_escaped = replace( val = rv_escaped sub = |\\r| with = '\\r' occ = 0 ). rv_escaped = replace( val = rv_escaped sub = |\\t| with = '\\t' occ = 0 ). rv_escaped = replace( val = rv_escaped sub = '""' with = '\\""' occ = 0 ). ENDIF. ENDMETHOD. ENDCLASS. ********************************************************************** * JSON_TO_ABAP ********************************************************************** CLASS lcl_json_to_abap DEFINITION FINAL. PUBLIC SECTION. METHODS constructor IMPORTING !ii_custom_mapping TYPE REF TO zif_abapgit_ajson_mapping OPTIONAL. METHODS to_abap IMPORTING it_nodes TYPE zif_abapgit_ajson=>ty_nodes_ts CHANGING c_container TYPE any RAISING zcx_abapgit_ajson_error. METHODS to_timestamp IMPORTING iv_value TYPE zif_abapgit_ajson=>ty_node-value RETURNING VALUE(rv_result) TYPE timestamp RAISING zcx_abapgit_ajson_error. METHODS to_date IMPORTING iv_value TYPE zif_abapgit_ajson=>ty_node-value RETURNING VALUE(rv_result) TYPE d RAISING zcx_abapgit_ajson_error. PRIVATE SECTION. TYPES: BEGIN OF ty_type_cache, type_path TYPE string, target_field_name TYPE string, dd TYPE REF TO cl_abap_datadescr, type_kind LIKE cl_abap_typedescr=>typekind_any, tab_item_buf TYPE REF TO data, END OF ty_type_cache. DATA mt_node_type_cache TYPE HASHED TABLE OF ty_type_cache WITH UNIQUE KEY type_path. DATA mr_nodes TYPE REF TO zif_abapgit_ajson=>ty_nodes_ts. DATA mi_custom_mapping TYPE REF TO zif_abapgit_ajson_mapping. METHODS any_to_abap IMPORTING iv_path TYPE string is_parent_type TYPE ty_type_cache OPTIONAL i_container_ref TYPE REF TO data RAISING zcx_abapgit_ajson_error. METHODS value_to_abap IMPORTING is_node TYPE zif_abapgit_ajson=>ty_node is_node_type TYPE ty_type_cache i_container_ref TYPE REF TO data RAISING zcx_abapgit_ajson_error cx_sy_conversion_no_number. METHODS get_node_type IMPORTING is_node TYPE zif_abapgit_ajson=>ty_node OPTIONAL "" Empty for root is_parent_type TYPE ty_type_cache OPTIONAL i_container_ref TYPE REF TO data OPTIONAL RETURNING VALUE(rs_node_type) TYPE ty_type_cache RAISING zcx_abapgit_ajson_error. ENDCLASS. CLASS lcl_json_to_abap IMPLEMENTATION. METHOD constructor. mi_custom_mapping = ii_custom_mapping. ENDMETHOD. METHOD to_abap. DATA lr_ref TYPE REF TO data. CLEAR c_container. "" what about data/obj refs ? CLEAR mt_node_type_cache. GET REFERENCE OF c_container INTO lr_ref. GET REFERENCE OF it_nodes INTO mr_nodes. get_node_type( i_container_ref = lr_ref ). "" Pre-cache root node type any_to_abap( iv_path = '' i_container_ref = lr_ref ). ENDMETHOD. METHOD get_node_type. DATA lv_node_type_path TYPE string. DATA lo_sdescr TYPE REF TO cl_abap_structdescr. DATA lo_tdescr TYPE REF TO cl_abap_tabledescr. DATA lo_ddescr TYPE REF TO cl_abap_datadescr. "" Calculate type path IF is_parent_type-type_kind = cl_abap_typedescr=>typekind_table. lv_node_type_path = is_parent_type-type_path && '/-'. "" table item type ELSEIF is_parent_type-type_kind IS NOT INITIAL. lv_node_type_path = is_parent_type-type_path && '/' && is_node-name. ENDIF. "" For root node lv_node_type_path remains '' "" Get or create cached READ TABLE mt_node_type_cache INTO rs_node_type WITH KEY type_path = lv_node_type_path. IF sy-subrc <> 0. rs_node_type-type_path = lv_node_type_path. IF mi_custom_mapping IS BOUND. rs_node_type-target_field_name = to_upper( mi_custom_mapping->to_abap( iv_path = is_node-path iv_name = is_node-name ) ). IF rs_node_type-target_field_name IS INITIAL. rs_node_type-target_field_name = to_upper( is_node-name ). ENDIF. ELSE. rs_node_type-target_field_name = to_upper( is_node-name ). ENDIF. CASE is_parent_type-type_kind. WHEN 'h'. "" Table lo_tdescr ?= is_parent_type-dd. rs_node_type-dd = lo_tdescr->get_table_line_type( ). WHEN 'u' OR 'v'. "" Structure lo_sdescr ?= is_parent_type-dd. lo_sdescr->get_component_type( EXPORTING p_name = rs_node_type-target_field_name RECEIVING p_descr_ref = rs_node_type-dd EXCEPTIONS component_not_found = 4 ). IF sy-subrc <> 0. zcx_abapgit_ajson_error=>raise( |Path not found| ). ENDIF. WHEN ''. "" Root node rs_node_type-dd ?= cl_abap_typedescr=>describe_by_data_ref( i_container_ref ). WHEN OTHERS. zcx_abapgit_ajson_error=>raise( |Unexpected parent type| ). ENDCASE. rs_node_type-type_kind = rs_node_type-dd->type_kind. "" for caching and cleaner unintialized access IF rs_node_type-type_kind = 'h'. "" Table lo_tdescr ?= rs_node_type-dd. IF lo_tdescr->table_kind <> 'S'. "" standard lo_ddescr = lo_tdescr->get_table_line_type( ). CREATE DATA rs_node_type-tab_item_buf TYPE HANDLE lo_ddescr. ENDIF. ENDIF. INSERT rs_node_type INTO TABLE mt_node_type_cache. ENDIF. ENDMETHOD. METHOD any_to_abap. DATA ls_node_type LIKE LINE OF mt_node_type_cache. DATA lx_ajson TYPE REF TO zcx_abapgit_ajson_error. DATA lx_root TYPE REF TO cx_root. DATA lr_target_field TYPE REF TO data. FIELD-SYMBOLS TYPE zif_abapgit_ajson=>ty_node. FIELD-SYMBOLS TYPE STANDARD TABLE. FIELD-SYMBOLS TYPE ANY TABLE. FIELD-SYMBOLS TYPE any. FIELD-SYMBOLS TYPE any. "" Assign container CASE is_parent_type-type_kind. WHEN 'h'. "" Table IF is_parent_type-tab_item_buf IS BOUND. "" Indirect hint that table was sorted/hashed, see get_node_type. ASSIGN i_container_ref->* TO . ASSERT sy-subrc = 0. lr_target_field = is_parent_type-tab_item_buf. "" For hashed/sorted table - same buffer for all children ASSIGN is_parent_type-tab_item_buf->* TO . ASSERT sy-subrc = 0. ELSE. ASSIGN i_container_ref->* TO . ASSERT sy-subrc = 0. ENDIF. WHEN 'u' OR 'v'. "" Structure ASSIGN i_container_ref->* TO . ASSERT sy-subrc = 0. ENDCASE. TRY. "" array_index because stringified index goes in wrong order [1, 10, 2 ...] LOOP AT mr_nodes->* ASSIGNING USING KEY array_index WHERE path = iv_path. "" Get or create type cache record IF is_parent_type-type_kind <> 'h' OR ls_node_type-type_kind IS INITIAL. "" table records are the same, no need to refetch twice ls_node_type = get_node_type( is_node = is_parent_type = is_parent_type ). ENDIF. "" Validate node type IF ls_node_type-type_kind CA 'lr'. "" data/obj ref "" TODO maybe in future zcx_abapgit_ajson_error=>raise( 'Cannot assign to ref' ). ENDIF. "" Find target field reference CASE is_parent_type-type_kind. WHEN 'h'. "" Table IF NOT ls_node_type-target_field_name CO '0123456789'. "" Does not affect anything actually but for integrity zcx_abapgit_ajson_error=>raise( 'Need index to access tables' ). ENDIF. IF is_parent_type-tab_item_buf IS NOT BOUND. "" Indirect hint that table was srt/hsh, see get_node_type APPEND INITIAL LINE TO REFERENCE INTO lr_target_field. ASSERT sy-subrc = 0. ENDIF. WHEN 'u' OR 'v'. FIELD-SYMBOLS TYPE any. ASSIGN COMPONENT ls_node_type-target_field_name OF STRUCTURE TO . ASSERT sy-subrc = 0. GET REFERENCE OF INTO lr_target_field. WHEN ''. "" Root node lr_target_field = i_container_ref. WHEN OTHERS. zcx_abapgit_ajson_error=>raise( 'Unexpected parent type' ). ENDCASE. "" Process value assignment CASE -type. WHEN zif_abapgit_ajson=>node_type-object. IF NOT ls_node_type-type_kind CO 'uv'. zcx_abapgit_ajson_error=>raise( 'Expected structure' ). ENDIF. any_to_abap( iv_path = -path && -name && '/' is_parent_type = ls_node_type i_container_ref = lr_target_field ). WHEN zif_abapgit_ajson=>node_type-array. IF NOT ls_node_type-type_kind = 'h'. zcx_abapgit_ajson_error=>raise( 'Expected table' ). ENDIF. any_to_abap( iv_path = -path && -name && '/' is_parent_type = ls_node_type i_container_ref = lr_target_field ). WHEN OTHERS. value_to_abap( is_node = is_node_type = ls_node_type i_container_ref = lr_target_field ). ENDCASE. IF is_parent_type-tab_item_buf IS BOUND. "" Indirect hint that table was sorted/hashed, see get_node_type. TRY. INSERT INTO TABLE . CATCH cx_sy_itab_duplicate_key. sy-subrc = 4. ENDTRY. IF sy-subrc <> 0. zcx_abapgit_ajson_error=>raise( 'Duplicate insertion' ). ENDIF. ENDIF. ENDLOOP. CATCH zcx_abapgit_ajson_error INTO lx_ajson. IF lx_ajson->location IS INITIAL. lx_ajson->set_location( -path && -name ). ENDIF. RAISE EXCEPTION lx_ajson. CATCH cx_sy_conversion_no_number. zcx_abapgit_ajson_error=>raise( iv_msg = 'Source is not a number' iv_location = -path && -name ). CATCH cx_root INTO lx_root. zcx_abapgit_ajson_error=>raise( iv_msg = lx_root->get_text( ) iv_location = -path && -name ). ENDTRY. ENDMETHOD. METHOD value_to_abap. FIELD-SYMBOLS TYPE any. IF is_node_type-type_kind CA 'lruvh'. "" refs, table, strucs zcx_abapgit_ajson_error=>raise( |Unsupported target for value [{ is_node_type-type_kind }]| ). ENDIF. ASSIGN i_container_ref->* TO . ASSERT sy-subrc = 0. CASE is_node-type. WHEN zif_abapgit_ajson=>node_type-null. "" Do nothing WHEN zif_abapgit_ajson=>node_type-boolean. "" TODO: check type ? = boolc( is_node-value = 'true' ). WHEN zif_abapgit_ajson=>node_type-number. "" TODO: check type ? = is_node-value. WHEN zif_abapgit_ajson=>node_type-string. "" TODO: check type ? IF is_node_type-type_kind = 'D' AND is_node-value IS NOT INITIAL. = to_date( is_node-value ). ELSEIF is_node_type-type_kind = 'P' AND is_node-value IS NOT INITIAL. = to_timestamp( is_node-value ). ELSE. = is_node-value. ENDIF. WHEN OTHERS. zcx_abapgit_ajson_error=>raise( |Unexpected JSON type [{ is_node-type }]| ). ENDCASE. ENDMETHOD. METHOD to_date. DATA lv_y TYPE c LENGTH 4. DATA lv_m TYPE c LENGTH 2. DATA lv_d TYPE c LENGTH 2. FIND FIRST OCCURRENCE OF REGEX '^(\\d{4})-(\\d{2})-(\\d{2})(T|$)' IN iv_value SUBMATCHES lv_y lv_m lv_d. IF sy-subrc <> 0. zcx_abapgit_ajson_error=>raise( 'Unexpected date format' ). ENDIF. CONCATENATE lv_y lv_m lv_d INTO rv_result. ENDMETHOD. METHOD to_timestamp. CONSTANTS lc_utc TYPE c LENGTH 6 VALUE 'UTC'. CONSTANTS lc_regex_ts_with_hour TYPE string VALUE `^(\\d{4})-(\\d{2})-(\\d{2})(T)(\\d{2}):(\\d{2}):(\\d{2})(\\+)(\\d{2}):(\\d{2})`. CONSTANTS lc_regex_ts_utc TYPE string VALUE `^(\\d{4})-(\\d{2})-(\\d{2})(T)(\\d{2}):(\\d{2}):(\\d{2})(Z|$)`. DATA: BEGIN OF ls_timestamp, year TYPE c LENGTH 4, month TYPE c LENGTH 2, day TYPE c LENGTH 2, t TYPE c LENGTH 1, hour TYPE c LENGTH 2, minute TYPE c LENGTH 2, second TYPE c LENGTH 2, local_sign TYPE c LENGTH 1, local_hour TYPE c LENGTH 2, local_minute TYPE c LENGTH 2, END OF ls_timestamp. DATA lv_date TYPE d. DATA lv_time TYPE t. DATA lv_seconds_conv TYPE i. DATA lv_timestamp TYPE timestampl. FIND FIRST OCCURRENCE OF REGEX lc_regex_ts_with_hour IN iv_value SUBMATCHES ls_timestamp-year ls_timestamp-month ls_timestamp-day ls_timestamp-t ls_timestamp-hour ls_timestamp-minute ls_timestamp-second ls_timestamp-local_sign ls_timestamp-local_hour ls_timestamp-local_minute. IF sy-subrc = 0. lv_seconds_conv = ( ls_timestamp-local_hour * 3600 ) + ( ls_timestamp-local_minute * 60 ). ELSE. FIND FIRST OCCURRENCE OF REGEX lc_regex_ts_utc IN iv_value SUBMATCHES ls_timestamp-year ls_timestamp-month ls_timestamp-day ls_timestamp-t ls_timestamp-hour ls_timestamp-minute ls_timestamp-second. IF sy-subrc <> 0. zcx_abapgit_ajson_error=>raise( 'Unexpected timestamp format' ). ENDIF. ENDIF. CONCATENATE ls_timestamp-year ls_timestamp-month ls_timestamp-day INTO lv_date. CONCATENATE ls_timestamp-hour ls_timestamp-minute ls_timestamp-second INTO lv_time. CONVERT DATE lv_date TIME lv_time INTO TIME STAMP lv_timestamp TIME ZONE lc_utc. TRY. CASE ls_timestamp-local_sign. WHEN '-'. lv_timestamp = cl_abap_tstmp=>add( tstmp = lv_timestamp secs = lv_seconds_conv ). WHEN '+'. lv_timestamp = cl_abap_tstmp=>subtractsecs( tstmp = lv_timestamp secs = lv_seconds_conv ). ENDCASE. CATCH cx_parameter_invalid_range cx_parameter_invalid_type. zcx_abapgit_ajson_error=>raise( 'Unexpected error calculating timestamp' ). ENDTRY. cl_abap_tstmp=>move( EXPORTING tstmp_src = lv_timestamp IMPORTING tstmp_tgt = rv_result ). ENDMETHOD. ENDCLASS. ********************************************************************** * ABAP_TO_JSON ********************************************************************** CLASS lcl_abap_to_json DEFINITION FINAL. PUBLIC SECTION. CLASS-METHODS convert IMPORTING iv_data TYPE any is_prefix TYPE zif_abapgit_ajson=>ty_path_name OPTIONAL iv_array_index TYPE i DEFAULT 0 ii_custom_mapping TYPE REF TO zif_abapgit_ajson_mapping OPTIONAL iv_keep_item_order TYPE abap_bool DEFAULT abap_false iv_format_datetime TYPE abap_bool DEFAULT abap_false RETURNING VALUE(rt_nodes) TYPE zif_abapgit_ajson=>ty_nodes_tt RAISING zcx_abapgit_ajson_error. CLASS-METHODS insert_with_type IMPORTING iv_data TYPE any iv_type TYPE string is_prefix TYPE zif_abapgit_ajson=>ty_path_name OPTIONAL iv_array_index TYPE i DEFAULT 0 ii_custom_mapping TYPE REF TO zif_abapgit_ajson_mapping OPTIONAL iv_keep_item_order TYPE abap_bool DEFAULT abap_false iv_format_datetime TYPE abap_bool DEFAULT abap_false RETURNING VALUE(rt_nodes) TYPE zif_abapgit_ajson=>ty_nodes_tt RAISING zcx_abapgit_ajson_error. CLASS-METHODS format_date IMPORTING iv_date TYPE d RETURNING VALUE(rv_str) TYPE string. CLASS-METHODS format_time IMPORTING iv_time TYPE t RETURNING VALUE(rv_str) TYPE string. CLASS-METHODS format_timestamp IMPORTING iv_ts TYPE timestamp RETURNING VALUE(rv_str) TYPE string. CLASS-METHODS class_constructor. PRIVATE SECTION. CLASS-DATA gv_ajson_absolute_type_name TYPE string. DATA mi_custom_mapping TYPE REF TO zif_abapgit_ajson_mapping. DATA mv_keep_item_order TYPE abap_bool. DATA mv_format_datetime TYPE abap_bool. METHODS convert_any IMPORTING iv_data TYPE any io_type TYPE REF TO cl_abap_typedescr is_prefix TYPE zif_abapgit_ajson=>ty_path_name iv_index TYPE i DEFAULT 0 iv_item_order TYPE i DEFAULT 0 CHANGING ct_nodes TYPE zif_abapgit_ajson=>ty_nodes_tt RAISING zcx_abapgit_ajson_error. METHODS convert_ajson IMPORTING io_json TYPE REF TO zcl_abapgit_ajson is_prefix TYPE zif_abapgit_ajson=>ty_path_name iv_index TYPE i DEFAULT 0 CHANGING ct_nodes TYPE zif_abapgit_ajson=>ty_nodes_tt RAISING zcx_abapgit_ajson_error. METHODS convert_value IMPORTING iv_data TYPE any io_type TYPE REF TO cl_abap_typedescr is_prefix TYPE zif_abapgit_ajson=>ty_path_name iv_index TYPE i DEFAULT 0 iv_item_order TYPE i DEFAULT 0 CHANGING ct_nodes TYPE zif_abapgit_ajson=>ty_nodes_tt RAISING zcx_abapgit_ajson_error. METHODS convert_ref IMPORTING iv_data TYPE any is_prefix TYPE zif_abapgit_ajson=>ty_path_name iv_index TYPE i DEFAULT 0 iv_item_order TYPE i DEFAULT 0 CHANGING ct_nodes TYPE zif_abapgit_ajson=>ty_nodes_tt RAISING zcx_abapgit_ajson_error. METHODS convert_struc IMPORTING iv_data TYPE any io_type TYPE REF TO cl_abap_typedescr is_prefix TYPE zif_abapgit_ajson=>ty_path_name iv_index TYPE i DEFAULT 0 iv_item_order TYPE i DEFAULT 0 CHANGING ct_nodes TYPE zif_abapgit_ajson=>ty_nodes_tt cs_root TYPE zif_abapgit_ajson=>ty_node OPTIONAL RAISING zcx_abapgit_ajson_error. METHODS convert_table IMPORTING iv_data TYPE any io_type TYPE REF TO cl_abap_typedescr is_prefix TYPE zif_abapgit_ajson=>ty_path_name iv_index TYPE i DEFAULT 0 iv_item_order TYPE i DEFAULT 0 CHANGING ct_nodes TYPE zif_abapgit_ajson=>ty_nodes_tt RAISING zcx_abapgit_ajson_error. METHODS insert_value_with_type IMPORTING iv_data TYPE any iv_type TYPE string io_type TYPE REF TO cl_abap_typedescr is_prefix TYPE zif_abapgit_ajson=>ty_path_name iv_index TYPE i DEFAULT 0 iv_item_order TYPE i DEFAULT 0 CHANGING ct_nodes TYPE zif_abapgit_ajson=>ty_nodes_tt RAISING zcx_abapgit_ajson_error. ENDCLASS. CLASS lcl_abap_to_json IMPLEMENTATION. METHOD class_constructor. DATA lo_dummy TYPE REF TO zcl_abapgit_ajson. DATA lo_type TYPE REF TO cl_abap_refdescr. lo_type ?= cl_abap_typedescr=>describe_by_data( lo_dummy ). gv_ajson_absolute_type_name = lo_type->get_referenced_type( )->absolute_name. ENDMETHOD. METHOD convert. DATA lo_type TYPE REF TO cl_abap_typedescr. DATA lo_converter TYPE REF TO lcl_abap_to_json. lo_type = cl_abap_typedescr=>describe_by_data( iv_data ). CREATE OBJECT lo_converter. lo_converter->mi_custom_mapping = ii_custom_mapping. lo_converter->mv_keep_item_order = iv_keep_item_order. lo_converter->mv_format_datetime = iv_format_datetime. lo_converter->convert_any( EXPORTING iv_data = iv_data io_type = lo_type is_prefix = is_prefix iv_index = iv_array_index CHANGING ct_nodes = rt_nodes ). ENDMETHOD. METHOD convert_any. CASE io_type->kind. WHEN cl_abap_typedescr=>kind_elem. convert_value( EXPORTING iv_data = iv_data io_type = io_type is_prefix = is_prefix iv_index = iv_index iv_item_order = iv_item_order CHANGING ct_nodes = ct_nodes ). WHEN cl_abap_typedescr=>kind_struct. convert_struc( EXPORTING iv_data = iv_data io_type = io_type is_prefix = is_prefix iv_index = iv_index iv_item_order = iv_item_order CHANGING ct_nodes = ct_nodes ). WHEN cl_abap_typedescr=>kind_table. convert_table( EXPORTING iv_data = iv_data io_type = io_type is_prefix = is_prefix iv_index = iv_index iv_item_order = iv_item_order CHANGING ct_nodes = ct_nodes ). WHEN OTHERS. IF io_type->type_kind = cl_abap_typedescr=>typekind_dref. convert_ref( EXPORTING iv_data = iv_data is_prefix = is_prefix iv_index = iv_index iv_item_order = iv_item_order CHANGING ct_nodes = ct_nodes ). ELSEIF io_type->type_kind = cl_abap_typedescr=>typekind_oref AND cl_abap_typedescr=>describe_by_object_ref( iv_data )->absolute_name = gv_ajson_absolute_type_name. convert_ajson( EXPORTING io_json = iv_data is_prefix = is_prefix iv_index = iv_index CHANGING ct_nodes = ct_nodes ). ELSE. zcx_abapgit_ajson_error=>raise( |Unsupported type [{ io_type->type_kind }] @{ is_prefix-path && is_prefix-name }| ). ENDIF. ENDCASE. ENDMETHOD. METHOD convert_ajson. FIELD-SYMBOLS LIKE LINE OF ct_nodes. FIELD-SYMBOLS LIKE LINE OF ct_nodes. IF io_json IS NOT BOUND. RETURN. ENDIF. LOOP AT io_json->mt_json_tree ASSIGNING . APPEND TO ct_nodes ASSIGNING . IF -path IS INITIAL AND -name IS INITIAL. "" root node -path = is_prefix-path. -name = is_prefix-name. -index = iv_index. ELSE. -path = is_prefix-path && is_prefix-name && -path. ENDIF. ENDLOOP. ENDMETHOD. METHOD format_date. IF iv_date IS NOT INITIAL. rv_str = iv_date+0(4) && '-' && iv_date+4(2) && '-' && iv_date+6(2). ENDIF. ENDMETHOD. METHOD format_time. IF iv_time IS NOT INITIAL. rv_str = iv_time+0(2) && ':' && iv_time+2(2) && ':' && iv_time+4(2). ENDIF. ENDMETHOD. METHOD format_timestamp. CONSTANTS lc_utc TYPE c LENGTH 6 VALUE 'UTC'. DATA lv_date TYPE d. DATA lv_time TYPE t. IF iv_ts IS INITIAL. "" The zero value is January 1, year 1, 00:00:00.000000000 UTC. lv_date = '00010101'. ELSE. CONVERT TIME STAMP iv_ts TIME ZONE lc_utc INTO DATE lv_date TIME lv_time. ENDIF. rv_str = lv_date+0(4) && '-' && lv_date+4(2) && '-' && lv_date+6(2) && 'T' && lv_time+0(2) && '-' && lv_time+2(2) && '-' && lv_time+4(2) && 'Z'. ENDMETHOD. METHOD convert_value. DATA ls_node LIKE LINE OF ct_nodes. ls_node-path = is_prefix-path. ls_node-name = is_prefix-name. ls_node-index = iv_index. ls_node-order = iv_item_order. IF mi_custom_mapping IS BOUND. ls_node-name = mi_custom_mapping->to_json( iv_path = is_prefix-path iv_name = is_prefix-name ). ENDIF. IF ls_node-name IS INITIAL. ls_node-name = is_prefix-name. ENDIF. IF io_type->absolute_name = '\\TYPE-POOL=ABAP\\TYPE=ABAP_BOOL' OR io_type->absolute_name = '\\TYPE=ABAP_BOOLEAN' OR io_type->absolute_name = '\\TYPE=XSDBOOLEAN' OR io_type->absolute_name = '\\TYPE=FLAG' OR io_type->absolute_name = '\\TYPE=XFELD'. ls_node-type = zif_abapgit_ajson=>node_type-boolean. IF iv_data IS NOT INITIAL. ls_node-value = 'true'. ELSE. ls_node-value = 'false'. ENDIF. ELSEIF io_type->absolute_name = '\\TYPE=TIMESTAMP'. IF mv_format_datetime = abap_true. ls_node-type = zif_abapgit_ajson=>node_type-string. ls_node-value = format_timestamp( iv_data ). ELSE. ls_node-type = zif_abapgit_ajson=>node_type-number. ls_node-value = |{ iv_data }|. ENDIF. ELSEIF io_type->type_kind CO 'CNgXy'. "" Char like, xstring ls_node-type = zif_abapgit_ajson=>node_type-string. ls_node-value = |{ iv_data }|. ELSEIF io_type->type_kind = 'D'. "" Date ls_node-type = zif_abapgit_ajson=>node_type-string. IF mv_format_datetime = abap_true. ls_node-value = format_date( iv_data ). ELSE. ls_node-value = |{ iv_data }|. ENDIF. ELSEIF io_type->type_kind = 'T'. "" Time ls_node-type = zif_abapgit_ajson=>node_type-string. IF mv_format_datetime = abap_true. ls_node-value = format_time( iv_data ). ELSE. ls_node-value = |{ iv_data }|. ENDIF. ELSEIF io_type->type_kind CO 'bsI8aeFP'. "" Numeric ls_node-type = zif_abapgit_ajson=>node_type-number. ls_node-value = |{ iv_data }|. ELSE. zcx_abapgit_ajson_error=>raise( |Unexpected elementary type [{ io_type->type_kind }] @{ is_prefix-path && is_prefix-name }| ). ENDIF. APPEND ls_node TO ct_nodes. ENDMETHOD. METHOD convert_ref. DATA ls_node LIKE LINE OF ct_nodes. ls_node-path = is_prefix-path. ls_node-name = is_prefix-name. ls_node-index = iv_index. ls_node-order = iv_item_order. IF mi_custom_mapping IS BOUND. ls_node-name = mi_custom_mapping->to_json( iv_path = is_prefix-path iv_name = is_prefix-name ). ENDIF. IF ls_node-name IS INITIAL. ls_node-name = is_prefix-name. ENDIF. IF iv_data IS INITIAL. ls_node-type = zif_abapgit_ajson=>node_type-null. ls_node-value = 'null'. ELSE. "" TODO support data references zcx_abapgit_ajson_error=>raise( |Unexpected reference @{ is_prefix-path && is_prefix-name }| ). ENDIF. APPEND ls_node TO ct_nodes. ENDMETHOD. METHOD convert_struc. DATA lo_struc TYPE REF TO cl_abap_structdescr. DATA lt_comps TYPE cl_abap_structdescr=>component_table. DATA ls_next_prefix LIKE is_prefix. DATA lv_item_order TYPE i. DATA ls_root LIKE LINE OF ct_nodes. FIELD-SYMBOLS LIKE ls_root. FIELD-SYMBOLS LIKE LINE OF lt_comps. FIELD-SYMBOLS TYPE any. "" Object root IF cs_root IS SUPPLIED. "" call for include structure ASSIGN cs_root TO . ELSE. "" First call ls_root-path = is_prefix-path. ls_root-name = is_prefix-name. ls_root-type = zif_abapgit_ajson=>node_type-object. ls_root-index = iv_index. IF mi_custom_mapping IS BOUND. ls_root-name = mi_custom_mapping->to_json( iv_path = is_prefix-path iv_name = is_prefix-name ). ENDIF. IF ls_root-name IS INITIAL. ls_root-name = is_prefix-name. ENDIF. ls_root-order = iv_item_order. APPEND ls_root TO ct_nodes ASSIGNING . ENDIF. "" Object attributes lo_struc ?= io_type. lt_comps = lo_struc->get_components( ). "" get_components is potentially much slower than lo_struc->components "" but ! we still need it to identify booleans "" and rtti seems to cache type descriptions really well (https://github.com/sbcgua/benchmarks.git) "" the structures will be repeated in real life ls_next_prefix-path = is_prefix-path && ls_root-name && '/'. LOOP AT lt_comps ASSIGNING . IF -as_include = abap_true. convert_struc( EXPORTING iv_data = iv_data io_type = -type is_prefix = is_prefix CHANGING cs_root = ct_nodes = ct_nodes ). ELSE. -children = -children + 1. ls_next_prefix-name = to_lower( -name ). ASSIGN COMPONENT -name OF STRUCTURE iv_data TO . ASSERT sy-subrc = 0. IF mv_keep_item_order = abap_true. lv_item_order = -children. ENDIF. convert_any( EXPORTING iv_data = io_type = -type is_prefix = ls_next_prefix iv_item_order = lv_item_order CHANGING ct_nodes = ct_nodes ). ENDIF. ENDLOOP. ENDMETHOD. METHOD convert_table. DATA lo_table TYPE REF TO cl_abap_tabledescr. DATA lo_ltype TYPE REF TO cl_abap_typedescr. DATA ls_next_prefix LIKE is_prefix. DATA lv_tabix TYPE sy-tabix. DATA ls_root LIKE LINE OF ct_nodes. FIELD-SYMBOLS LIKE ls_root. FIELD-SYMBOLS TYPE ANY TABLE. FIELD-SYMBOLS TYPE any. "" Array root ls_root-path = is_prefix-path. ls_root-name = is_prefix-name. ls_root-type = zif_abapgit_ajson=>node_type-array. ls_root-index = iv_index. ls_root-order = iv_item_order. IF mi_custom_mapping IS BOUND. ls_root-name = mi_custom_mapping->to_json( iv_path = is_prefix-path iv_name = is_prefix-name ). ENDIF. IF ls_root-name IS INITIAL. ls_root-name = is_prefix-name. ENDIF. APPEND ls_root TO ct_nodes ASSIGNING . "" Array items lo_table ?= io_type. lo_ltype = lo_table->get_table_line_type( ). ls_next_prefix-path = is_prefix-path && is_prefix-name && '/'. ASSIGN iv_data TO . lv_tabix = 1. LOOP AT ASSIGNING . ls_next_prefix-name = to_lower( |{ lv_tabix }| ). convert_any( EXPORTING iv_data = io_type = lo_ltype is_prefix = ls_next_prefix iv_index = -children + 1 CHANGING ct_nodes = ct_nodes ). -children = -children + 1. lv_tabix = lv_tabix + 1. ENDLOOP. ENDMETHOD. METHOD insert_with_type. DATA lo_type TYPE REF TO cl_abap_typedescr. DATA lo_converter TYPE REF TO lcl_abap_to_json. lo_type = cl_abap_typedescr=>describe_by_data( iv_data ). CREATE OBJECT lo_converter. lo_converter->mi_custom_mapping = ii_custom_mapping. lo_converter->mv_keep_item_order = iv_keep_item_order. lo_converter->mv_format_datetime = iv_format_datetime. lo_converter->insert_value_with_type( EXPORTING iv_data = iv_data iv_type = iv_type io_type = lo_type is_prefix = is_prefix iv_index = iv_array_index CHANGING ct_nodes = rt_nodes ). ENDMETHOD. METHOD insert_value_with_type. DATA lv_prefix TYPE string. DATA ls_node LIKE LINE OF ct_nodes. lv_prefix = is_prefix-path && is_prefix-name. IF io_type->type_kind CO 'CNgXyDT'. "" Char like, date/time, xstring IF iv_type = zif_abapgit_ajson=>node_type-boolean AND iv_data <> 'true' AND iv_data <> 'false'. zcx_abapgit_ajson_error=>raise( |Unexpected boolean value [{ iv_data }] @{ lv_prefix }| ). ELSEIF iv_type = zif_abapgit_ajson=>node_type-null AND iv_data IS NOT INITIAL. zcx_abapgit_ajson_error=>raise( |Unexpected null value [{ iv_data }] @{ lv_prefix }| ). ELSEIF iv_type = zif_abapgit_ajson=>node_type-number AND iv_data CN '0123456789. E+-'. zcx_abapgit_ajson_error=>raise( |Unexpected numeric value [{ iv_data }] @{ lv_prefix }| ). ELSEIF iv_type <> zif_abapgit_ajson=>node_type-string AND iv_type <> zif_abapgit_ajson=>node_type-boolean AND iv_type <> zif_abapgit_ajson=>node_type-null AND iv_type <> zif_abapgit_ajson=>node_type-number. zcx_abapgit_ajson_error=>raise( |Unexpected type for value [{ iv_type },{ iv_data }] @{ lv_prefix }| ). ENDIF. ELSEIF io_type->type_kind CO 'bsI8PaeF'. "" Numeric IF iv_type <> zif_abapgit_ajson=>node_type-number. zcx_abapgit_ajson_error=>raise( |Unexpected value for numeric [{ iv_data }] @{ lv_prefix }| ). ENDIF. ELSE. zcx_abapgit_ajson_error=>raise( |Unexpected type [{ io_type->type_kind }] @{ lv_prefix }| ). ENDIF. ls_node-path = is_prefix-path. ls_node-name = is_prefix-name. ls_node-index = iv_index. ls_node-value = iv_data. ls_node-type = iv_type. ls_node-order = iv_item_order. IF mi_custom_mapping IS BOUND. ls_node-name = mi_custom_mapping->to_json( iv_path = is_prefix-path iv_name = is_prefix-name ). ENDIF. IF ls_node-name IS INITIAL. ls_node-name = is_prefix-name. ENDIF. APPEND ls_node TO ct_nodes. ENDMETHOD. ENDCLASS. ********************************************************************** * FILTER RUNNER ********************************************************************** CLASS lcl_filter_runner DEFINITION FINAL. PUBLIC SECTION. METHODS run IMPORTING ii_filter TYPE REF TO zif_abapgit_ajson_filter it_source_tree TYPE zif_abapgit_ajson=>ty_nodes_ts CHANGING ct_dest_tree TYPE zif_abapgit_ajson=>ty_nodes_ts RAISING zcx_abapgit_ajson_error. PRIVATE SECTION. DATA mi_filter TYPE REF TO zif_abapgit_ajson_filter. DATA mr_source_tree TYPE REF TO zif_abapgit_ajson=>ty_nodes_ts. DATA mr_dest_tree TYPE REF TO zif_abapgit_ajson=>ty_nodes_ts. METHODS walk IMPORTING iv_path TYPE string CHANGING cs_parent TYPE zif_abapgit_ajson=>ty_node OPTIONAL RAISING zcx_abapgit_ajson_error. ENDCLASS. CLASS lcl_filter_runner IMPLEMENTATION. METHOD run. ASSERT ii_filter IS BOUND. mi_filter = ii_filter. CLEAR ct_dest_tree. GET REFERENCE OF it_source_tree INTO mr_source_tree. GET REFERENCE OF ct_dest_tree INTO mr_dest_tree. walk( iv_path = '' ). ENDMETHOD. METHOD walk. DATA ls_node TYPE zif_abapgit_ajson=>ty_node. LOOP AT mr_source_tree->* INTO ls_node WHERE path = iv_path. CASE ls_node-type. WHEN zif_abapgit_ajson=>node_type-boolean OR zif_abapgit_ajson=>node_type-null OR zif_abapgit_ajson=>node_type-number OR zif_abapgit_ajson=>node_type-string. IF mi_filter->keep_node( ls_node ) = abap_false. CONTINUE. ENDIF. WHEN zif_abapgit_ajson=>node_type-array OR zif_abapgit_ajson=>node_type-object. IF mi_filter->keep_node( is_node = ls_node iv_visit = zif_abapgit_ajson_filter=>visit_type-open ) = abap_false. CONTINUE. ENDIF. "" Intentionally clear AFTER ""open"" CLEAR ls_node-children. walk( EXPORTING iv_path = iv_path && ls_node-name && `/` CHANGING cs_parent = ls_node ). IF mi_filter->keep_node( is_node = ls_node iv_visit = zif_abapgit_ajson_filter=>visit_type-close ) = abap_false. CONTINUE. ENDIF. WHEN OTHERS. zcx_abapgit_ajson_error=>raise( |Unexpected node type { ls_node-type }| ). ENDCASE. IF cs_parent IS SUPPLIED. cs_parent-children = cs_parent-children + 1. IF cs_parent-type = zif_abapgit_ajson=>node_type-array. ls_node-name = |{ cs_parent-children }|. ls_node-index = cs_parent-children. ENDIF. ENDIF. INSERT ls_node INTO TABLE mr_dest_tree->*. ENDLOOP. ENDMETHOD. ENDCLASS. ",13166,True,2820.0106839240243,median "= Personal Finance Tracker :site-section: DeveloperGuide :toc: :toc-title: :toc-placement: preamble :sectnums: :imagesDir: images :stylesDir: stylesheets :xrefstyle: full ifdef::env-github[] :tip-caption: :bulb: :note-caption: :information_source: :warning-caption: :warning: :experimental: endif::[] :repoURL: https://github.com/cs2103-ay1819s2-w15-2/main/tree/master By: `CS2103-AY1819S2-W15-2`      Since: `Feb 2019` == Setting up === Prerequisites . *JDK `9`* or later + [WARNING] JDK `10` on Windows will fail to run tests in <> due to a https://github.com/javafxports/openjdk-jfx/issues/66[JavaFX bug]. Windows developers are highly recommended to use JDK `9`. . *IntelliJ* IDE + [NOTE] IntelliJ by default has Gradle and JavaFx plugins installed. + Do not disable them. If you have disabled them, go to `File` > `Settings` > `Plugins` to re-enable them. === Setting up the project in your computer . Fork this repo, and clone the fork to your computer . Open IntelliJ (if you are not in the welcome screen, click `File` > `Close Project` to close the existing project dialog first) . Set up the correct JDK version for Gradle .. Click `Configure` > `Project Defaults` > `Project Structure` .. Click `New...` and find the directory of the JDK . Click `Import Project` . Locate the `build.gradle` file and select it. Click `OK` . Click `Open as Project` . Click `OK` to accept the default settings . Open a console and run the command `gradlew processResources` (Mac/Linux: `./gradlew processResources`). It should finish with the `BUILD SUCCESSFUL` message. + This will generate all resources required by the application and tests. . Open link:{repoURL}/src/main/java/seedu/address/ui/MainWindow.java[`MainWindow.java`] and check for any code errors .. Due to an ongoing https://youtrack.jetbrains.com/issue/IDEA-189060[issue] with some of the newer versions of IntelliJ, code errors may be detected even if the project can be built and run successfully .. To resolve this, place your cursor over any of the code section highlighted in red. Press kbd:[ALT + ENTER], and select `Add '--add-modules=...' to module compiler options` for each error . Repeat this for the test folder as well (e.g. check link:{repoURL}/src/test/java/seedu/address/ui/HelpWindowTest.java[`HelpWindowTest.java`] for code errors, and if so, resolve it the same way) === Verifying the setup . Run the `seedu.address.MainApp` and try a few commands . <> to ensure they all pass. === Configurations to do before writing code ==== Configuring the coding style This project follows https://github.com/oss-generic/process/blob/master/docs/CodingStandards.adoc[oss-generic coding standards]. IntelliJ's default style is mostly compliant with ours but it uses a different import order from ours. To rectify, . Go to `File` > `Settings...` (Windows/Linux), or `IntelliJ IDEA` > `Preferences...` (macOS) . Select `Editor` > `Code Style` > `Java` . Click on the `Imports` tab to set the order * For `Class count to use import with '\\*'` and `Names count to use static import with '*'`: Set to `999` to prevent IntelliJ from contracting the import statements * For `Import Layout`: The order is `import static all other imports`, `import java.\\*`, `import javax.*`, `import org.\\*`, `import com.*`, `import all other imports`. Add a `` between each `import` Optionally, you can follow the <> document to configure Intellij to check style-compliance as you write code. ==== Updating documentation to match your fork After forking the repo, the documentation will still have the SE-EDU branding and refer to the `se-edu/addressbook-level4` repo. If you plan to develop this fork as a separate product (i.e. instead of contributing to `se-edu/addressbook-level4`), you should do the following: . Configure the <> in link:{repoURL}/build.gradle[`build.gradle`], such as the `site-name`, to suit your own project. . Replace the URL in the attribute `repoURL` in link:{repoURL}/docs/DeveloperGuide.adoc[`DeveloperGuide.adoc`] and link:{repoURL}/docs/UserGuide.adoc[`UserGuide.adoc`] with the URL of your fork. ==== Setting up CI Set up Travis to perform Continuous Integration (CI) for your fork. See <> to learn how to set it up. After setting up Travis, you can optionally set up coverage reporting for your team fork (see <>). [NOTE] Coverage reporting could be useful for a team repository that hosts the final version but it is not that useful for your personal fork. Optionally, you can set up AppVeyor as a second CI (see <>). [NOTE] Having both Travis and AppVeyor ensures your App works on both Unix-based platforms and Windows-based platforms (Travis is Unix-based and AppVeyor is Windows-based) ==== Getting started with coding When you are ready to start coding, 1. Get some sense of the overall design by reading <>. 2. Take a look at <>. == Design [[Design-Architecture]] === Architecture .Architecture Diagram image::Architecture.png[width=""600""] The *_Architecture Diagram_* given above explains the high-level design of the App. Given below is a quick overview of each component. [TIP] The `.pptx` files used to create diagrams in this document can be found in the link:{repoURL}/docs/diagrams/[diagrams] folder. To update a diagram, modify the diagram in the pptx file, select the objects of the diagram, and choose `Save as picture`. `Main` has only one class called link:{repoURL}/src/main/java/seedu/address/MainApp.java[`MainApp`]. It is responsible for, * At app launch: Initializes the components in the correct sequence, and connects them up with each other. * At shut down: Shuts down the components and invokes cleanup method where necessary. <> represents a collection of classes used by multiple other components. The following class plays an important role at the architecture level: * `LogsCenter` : Used by many classes to write log messages to the App's log file. The rest of the App consists of four components. * <>: The UI of the App. * <>: The command executor. * <>: Holds the data of the App in-memory. * <>: Reads data from, and writes data to, the hard disk. Each of the four components * Defines its _API_ in an `interface` with the same name as the Component. * Exposes its functionality using a `{Component Name}Manager` class. For example, the `Logic` component (see the class diagram given below) defines it's API in the `Logic.java` interface and exposes its functionality using the `LogicManager.java` class. .Class Diagram of the Logic Component image::LogicClassDiagram.png[width=""800""] [discrete] ==== How the architecture components interact with each other The _Sequence Diagram_ below shows how the components interact with each other for the scenario where the user issues the command `delete 1`. .Component interactions for `delete 1` command image::SDforDeletePerson.png[width=""800""] The sections below give more details of each component. [[Design-Ui]] === UI component .Structure of the UI Component image::UiClassDiagram.png[width=""800""] *API* : link:{repoURL}/src/main/java/seedu/address/ui/Ui.java[`Ui.java`] The UI consists of a `MainWindow` that is made up of parts e.g.`CommandBox`, `ResultDisplay`, `PersonListPanel`, `StatusBarFooter`, `BrowserPanel` etc. All these, including the `MainWindow`, inherit from the abstract `UiPart` class. The `UI` component uses JavaFx UI framework. The layout of these UI parts are defined in matching `.fxml` files that are in the `src/main/resources/view` folder. For example, the layout of the link:{repoURL}/src/main/java/seedu/address/ui/MainWindow.java[`MainWindow`] is specified in link:{repoURL}/src/main/resources/view/MainWindow.fxml[`MainWindow.fxml`] The `UI` component, * Executes user commands using the `Logic` component. * Listens for changes to `Model` data so that the UI can be updated with the modified data. [[Design-Logic]] === Logic component [[fig-LogicClassDiagram]] .Structure of the Logic Component image::LogicClassDiagram.png[width=""800""] *API* : link:{repoURL}/src/main/java/seedu/address/logic/Logic.java[`Logic.java`] . `Logic` uses the `AddressBookParser` class to parse the user command. . This results in a `Command` object which is executed by the `LogicManager`. . The command execution can affect the `Model` (e.g. adding a person). . The result of the command execution is encapsulated as a `CommandResult` object which is passed back to the `Ui`. . In addition, the `CommandResult` object can also instruct the `Ui` to perform certain actions, such as displaying help to the user. Given below is the Sequence Diagram for interactions within the `Logic` component for the `execute(""delete 1"")` API call. .Interactions Inside the Logic Component for the `delete 1` Command image::DeletePersonSdForLogic.png[width=""800""] [[Design-Model]] === Model component .Structure of the Model Component image::ModelClassDiagram.png[width=""800""] *API* : link:{repoURL}/src/main/java/seedu/address/model/Model.java[`Model.java`] The `Model`, * stores a `UserPref` object that represents the user's preferences. * stores the Address Book data. * exposes an unmodifiable `ObservableList` that can be 'observed' e.g. the UI can be bound to this list so that the UI automatically updates when the data in the list change. * does not depend on any of the other three components. [NOTE] As a more OOP model, we can store a `Tag` list in `Address Book`, which `Person` can reference. This would allow `Address Book` to only require one `Tag` object per unique `Tag`, instead of each `Person` needing their own `Tag` object. An example of how such a model may look like is given below. + + image:ModelClassBetterOopDiagram.png[width=""800""] [[Design-Storage]] === Storage component .Structure of the Storage Component image::StorageClassDiagram.png[width=""800""] *API* : link:{repoURL}/src/main/java/seedu/address/storage/Storage.java[`Storage.java`] The `Storage` component, * can save `UserPref` objects in json format and read it back. * can save the Address Book data in json format and read it back. [[Design-Commons]] === Common classes Classes used by multiple components are in the `seedu.addressbook.commons` package. == Implementation This section describes some noteworthy details on how certain features are implemented. // tag::undoredo[] === Undo/Redo feature ==== Current Implementation The undo/redo mechanism is facilitated by `VersionedAddressBook`. It extends `AddressBook` with an undo/redo history, stored internally as an `addressBookStateList` and `currentStatePointer`. Additionally, it implements the following operations: * `VersionedAddressBook#commit()` -- Saves the current address book state in its history. * `VersionedAddressBook#undo()` -- Restores the previous address book state from its history. * `VersionedAddressBook#redo()` -- Restores a previously undone address book state from its history. These operations are exposed in the `Model` interface as `Model#commitAddressBook()`, `Model#undoAddressBook()` and `Model#redoAddressBook()` respectively. Given below is an example usage scenario and how the undo/redo mechanism behaves at each step. Step 1. The user launches the application for the first time. The `VersionedAddressBook` will be initialized with the initial address book state, and the `currentStatePointer` pointing to that single address book state. image::UndoRedoStartingStateListDiagram.png[width=""800""] Step 2. The user executes `delete 5` command to delete the 5th person in the address book. The `delete` command calls `Model#commitAddressBook()`, causing the modified state of the address book after the `delete 5` command executes to be saved in the `addressBookStateList`, and the `currentStatePointer` is shifted to the newly inserted address book state. image::UndoRedoNewCommand1StateListDiagram.png[width=""800""] Step 3. The user executes `add n/David ...` to add a new person. The `add` command also calls `Model#commitAddressBook()`, causing another modified address book state to be saved into the `addressBookStateList`. image::UndoRedoNewCommand2StateListDiagram.png[width=""800""] [NOTE] If a command fails its execution, it will not call `Model#commitAddressBook()`, so the address book state will not be saved into the `addressBookStateList`. Step 4. The user now decides that adding the person was a mistake, and decides to undo that action by executing the `undo` command. The `undo` command will call `Model#undoAddressBook()`, which will shift the `currentStatePointer` once to the left, pointing it to the previous address book state, and restores the address book to that state. image::UndoRedoExecuteUndoStateListDiagram.png[width=""800""] [NOTE] If the `currentStatePointer` is at index 0, pointing to the initial address book state, then there are no previous address book states to restore. The `undo` command uses `Model#canUndoAddressBook()` to check if this is the case. If so, it will return an error to the user rather than attempting to perform the undo. The following sequence diagram shows how the undo operation works: image::UndoRedoSequenceDiagram.png[width=""800""] The `redo` command does the opposite -- it calls `Model#redoAddressBook()`, which shifts the `currentStatePointer` once to the right, pointing to the previously undone state, and restores the address book to that state. [NOTE] If the `currentStatePointer` is at index `addressBookStateList.size() - 1`, pointing to the latest address book state, then there are no undone address book states to restore. The `redo` command uses `Model#canRedoAddressBook()` to check if this is the case. If so, it will return an error to the user rather than attempting to perform the redo. Step 5. The user then decides to execute the command `list`. Commands that do not modify the address book, such as `list`, will usually not call `Model#commitAddressBook()`, `Model#undoAddressBook()` or `Model#redoAddressBook()`. Thus, the `addressBookStateList` remains unchanged. image::UndoRedoNewCommand3StateListDiagram.png[width=""800""] Step 6. The user executes `clear`, which calls `Model#commitAddressBook()`. Since the `currentStatePointer` is not pointing at the end of the `addressBookStateList`, all address book states after the `currentStatePointer` will be purged. We designed it this way because it no longer makes sense to redo the `add n/David ...` command. This is the behavior that most modern desktop applications follow. image::UndoRedoNewCommand4StateListDiagram.png[width=""800""] The following activity diagram summarizes what happens when a user executes a new command: image::UndoRedoActivityDiagram.png[width=""650""] ==== Design Considerations ===== Aspect: How undo & redo executes * **Alternative 1 (current choice):** Saves the entire address book. ** Pros: Easy to implement. ** Cons: May have performance issues in terms of memory usage. * **Alternative 2:** Individual command knows how to undo/redo by itself. ** Pros: Will use less memory (e.g. for `delete`, just save the person being deleted). ** Cons: We must ensure that the implementation of each individual command are correct. ===== Aspect: Data structure to support the undo/redo commands * **Alternative 1 (current choice):** Use a list to store the history of address book states. ** Pros: Easy for new Computer Science student undergraduates to understand, who are likely to be the new incoming developers of our project. ** Cons: Logic is duplicated twice. For example, when a new command is executed, we must remember to update both `HistoryManager` and `VersionedAddressBook`. * **Alternative 2:** Use `HistoryManager` for undo/redo ** Pros: We do not need to maintain a separate list, and just reuse what is already in the codebase. ** Cons: Requires dealing with commands that have already been undone: We must remember to skip these commands. Violates Single Responsibility Principle and Separation of Concerns as `HistoryManager` now needs to do two different things. // end::undoredo[] // tag::dataencryption[] === [Proposed] Data Encryption _{Explain here how the data encryption feature will be implemented}_ // end::dataencryption[] === Logging We are using `java.util.logging` package for logging. The `LogsCenter` class is used to manage the logging levels and logging destinations. * The logging level can be controlled using the `logLevel` setting in the configuration file (See <>) * The `Logger` for a class can be obtained using `LogsCenter.getLogger(Class)` which will log messages according to the specified logging level * Currently log messages are output through: `Console` and to a `.log` file. *Logging Levels* * `SEVERE` : Critical problem detected which may possibly cause the termination of the application * `WARNING` : Can continue, but with caution * `INFO` : Information showing the noteworthy actions by the App * `FINE` : Details that is not usually noteworthy but may be useful in debugging e.g. print the actual list instead of just its size [[Implementation-Configuration]] === Configuration Certain properties of the application can be controlled (e.g user prefs file location, logging level) through the configuration file (default: `config.json`). == Documentation We use asciidoc for writing documentation. [NOTE] We chose asciidoc over Markdown because asciidoc, although a bit more complex than Markdown, provides more flexibility in formatting. === Editing Documentation See <> to learn how to render `.adoc` files locally to preview the end result of your edits. Alternatively, you can download the AsciiDoc plugin for IntelliJ, which allows you to preview the changes you have made to your `.adoc` files in real-time. === Publishing Documentation See <> to learn how to deploy GitHub Pages using Travis. === Converting Documentation to PDF format We use https://www.google.com/chrome/browser/desktop/[Google Chrome] for converting documentation to PDF format, as Chrome's PDF engine preserves hyperlinks used in webpages. Here are the steps to convert the project documentation files to PDF format. . Follow the instructions in <> to convert the AsciiDoc files in the `docs/` directory to HTML format. . Go to your generated HTML files in the `build/docs` folder, right click on them and select `Open with` -> `Google Chrome`. . Within Chrome, click on the `Print` option in Chrome's menu. . Set the destination to `Save as PDF`, then click `Save` to save a copy of the file in PDF format. For best results, use the settings indicated in the screenshot below. .Saving documentation as PDF files in Chrome image::chrome_save_as_pdf.png[width=""300""] [[Docs-SiteWideDocSettings]] === Site-wide Documentation Settings The link:{repoURL}/build.gradle[`build.gradle`] file specifies some project-specific https://asciidoctor.org/docs/user-manual/#attributes[asciidoc attributes] which affects how all documentation files within this project are rendered. [TIP] Attributes left unset in the `build.gradle` file will use their *default value*, if any. [cols=""1,2a,1"", options=""header""] .List of site-wide attributes |=== |Attribute name |Description |Default value |`site-name` |The name of the website. If set, the name will be displayed near the top of the page. |_not set_ |`site-githuburl` |URL to the site's repository on https://github.com[GitHub]. Setting this will add a ""View on GitHub"" link in the navigation bar. |_not set_ |`site-seedu` |Define this attribute if the project is an official SE-EDU project. This will render the SE-EDU navigation bar at the top of the page, and add some SE-EDU-specific navigation items. |_not set_ |=== [[Docs-PerFileDocSettings]] === Per-file Documentation Settings Each `.adoc` file may also specify some file-specific https://asciidoctor.org/docs/user-manual/#attributes[asciidoc attributes] which affects how the file is rendered. Asciidoctor's https://asciidoctor.org/docs/user-manual/#builtin-attributes[built-in attributes] may be specified and used as well. [TIP] Attributes left unset in `.adoc` files will use their *default value*, if any. [cols=""1,2a,1"", options=""header""] .List of per-file attributes, excluding Asciidoctor's built-in attributes |=== |Attribute name |Description |Default value |`site-section` |Site section that the document belongs to. This will cause the associated item in the navigation bar to be highlighted. One of: `UserGuide`, `DeveloperGuide`, ``LearningOutcomes``{asterisk}, `AboutUs`, `ContactUs` _{asterisk} Official SE-EDU projects only_ |_not set_ |`no-site-header` |Set this attribute to remove the site navigation bar. |_not set_ |=== === Site Template The files in link:{repoURL}/docs/stylesheets[`docs/stylesheets`] are the https://developer.mozilla.org/en-US/docs/Web/CSS[CSS stylesheets] of the site. You can modify them to change some properties of the site's design. The files in link:{repoURL}/docs/templates[`docs/templates`] controls the rendering of `.adoc` files into HTML5. These template files are written in a mixture of https://www.ruby-lang.org[Ruby] and http://slim-lang.com[Slim]. [WARNING] ==== Modifying the template files in link:{repoURL}/docs/templates[`docs/templates`] requires some knowledge and experience with Ruby and Asciidoctor's API. You should only modify them if you need greater control over the site's layout than what stylesheets can provide. The SE-EDU team does not provide support for modified template files. ==== [[Testing]] == Testing === Running Tests There are three ways to run tests. [TIP] The most reliable way to run tests is the 3rd one. The first two methods might fail some GUI tests due to platform/resolution-specific idiosyncrasies. *Method 1: Using IntelliJ JUnit test runner* * To run all tests, right-click on the `src/test/java` folder and choose `Run 'All Tests'` * To run a subset of tests, you can right-click on a test package, test class, or a test and choose `Run 'ABC'` *Method 2: Using Gradle* * Open a console and run the command `gradlew clean allTests` (Mac/Linux: `./gradlew clean allTests`) [NOTE] See <> for more info on how to run tests using Gradle. *Method 3: Using Gradle (headless)* Thanks to the https://github.com/TestFX/TestFX[TestFX] library we use, our GUI tests can be run in the _headless_ mode. In the headless mode, GUI tests do not show up on the screen. That means the developer can do other things on the Computer while the tests are running. To run tests in headless mode, open a console and run the command `gradlew clean headless allTests` (Mac/Linux: `./gradlew clean headless allTests`) === Types of tests We have two types of tests: . *GUI Tests* - These are tests involving the GUI. They include, .. _System Tests_ that test the entire App by simulating user actions on the GUI. These are in the `systemtests` package. .. _Unit tests_ that test the individual components. These are in `seedu.address.ui` package. . *Non-GUI Tests* - These are tests not involving the GUI. They include, .. _Unit tests_ targeting the lowest level methods/classes. + e.g. `seedu.address.commons.StringUtilTest` .. _Integration tests_ that are checking the integration of multiple code units (those code units are assumed to be working). + e.g. `seedu.address.storage.StorageManagerTest` .. Hybrids of unit and integration tests. These test are checking multiple code units as well as how the are connected together. + e.g. `seedu.address.logic.LogicManagerTest` === Troubleshooting Testing **Problem: `HelpWindowTest` fails with a `NullPointerException`.** * Reason: One of its dependencies, `HelpWindow.html` in `src/main/resources/docs` is missing. * Solution: Execute Gradle task `processResources`. == Dev Ops === Build Automation See <> to learn how to use Gradle for build automation. === Continuous Integration We use https://travis-ci.org/[Travis CI] and https://www.appveyor.com/[AppVeyor] to perform _Continuous Integration_ on our projects. See <> and <> for more details. === Coverage Reporting We use https://coveralls.io/[Coveralls] to track the code coverage of our projects. See <> for more details. === Documentation Previews When a pull request has changes to asciidoc files, you can use https://www.netlify.com/[Netlify] to see a preview of how the HTML version of those asciidoc files will look like when the pull request is merged. See <> for more details. === Making a Release Here are the steps to create a new release. . Update the version number in link:{repoURL}/src/main/java/seedu/address/MainApp.java[`MainApp.java`]. . Generate a JAR file <>. . Tag the repo with the version number. e.g. `v0.1` . https://help.github.com/articles/creating-releases/[Create a new release using GitHub] and upload the JAR file you created. === Managing Dependencies A project often depends on third-party libraries. For example, Address Book depends on the https://github.com/FasterXML/jackson[Jackson library] for JSON parsing. Managing these _dependencies_ can be automated using Gradle. For example, Gradle can download the dependencies automatically, which is better than these alternatives: [loweralpha] . Include those libraries in the repo (this bloats the repo size) . Require developers to download those libraries manually (this creates extra work for developers) [[GetStartedProgramming]] [appendix] == Suggested Programming Tasks to Get Started Suggested path for new programmers: 1. First, add small local-impact (i.e. the impact of the change does not go beyond the component) enhancements to one component at a time. Some suggestions are given in <>. 2. Next, add a feature that touches multiple components to learn how to implement an end-to-end feature across all components. <> explains how to go about adding such a feature. [[GetStartedProgramming-EachComponent]] === Improving each component Each individual exercise in this section is component-based (i.e. you would not need to modify the other components to get it to work). [discrete] ==== `Logic` component *Scenario:* You are in charge of `logic`. During dog-fooding, your team realize that it is troublesome for the user to type the whole command in order to execute a command. Your team devise some strategies to help cut down the amount of typing necessary, and one of the suggestions was to implement aliases for the command words. Your job is to implement such aliases. [TIP] Do take a look at <> before attempting to modify the `Logic` component. . Add a shorthand equivalent alias for each of the individual commands. For example, besides typing `clear`, the user can also type `c` to remove all persons in the list. + **** * Hints ** Just like we store each individual command word constant `COMMAND_WORD` inside `*Command.java` (e.g. link:{repoURL}/src/main/java/seedu/address/logic/commands/FindCommand.java[`FindCommand#COMMAND_WORD`], link:{repoURL}/src/main/java/seedu/address/logic/commands/DeleteCommand.java[`DeleteCommand#COMMAND_WORD`]), you need a new constant for aliases as well (e.g. `FindCommand#COMMAND_ALIAS`). ** link:{repoURL}/src/main/java/seedu/address/logic/parser/AddressBookParser.java[`AddressBookParser`] is responsible for analyzing command words. * Solution ** Modify the switch statement in link:{repoURL}/src/main/java/seedu/address/logic/parser/AddressBookParser.java[`AddressBookParser#parseCommand(String)`] such that both the proper command word and alias can be used to execute the same intended command. ** Add new tests for each of the aliases that you have added. ** Update the user guide to document the new aliases. ** See this https://github.com/se-edu/addressbook-level4/pull/785[PR] for the full solution. **** [discrete] ==== `Model` component *Scenario:* You are in charge of `model`. One day, the `logic`-in-charge approaches you for help. He wants to implement a command such that the user is able to remove a particular tag from everyone in the address book, but the model API does not support such a functionality at the moment. Your job is to implement an API method, so that your teammate can use your API to implement his command. [TIP] Do take a look at <> before attempting to modify the `Model` component. . Add a `removeTag(Tag)` method. The specified tag will be removed from everyone in the address book. + **** * Hints ** The link:{repoURL}/src/main/java/seedu/address/model/Model.java[`Model`] and the link:{repoURL}/src/main/java/seedu/address/model/AddressBook.java[`AddressBook`] API need to be updated. ** Think about how you can use SLAP to design the method. Where should we place the main logic of deleting tags? ** Find out which of the existing API methods in link:{repoURL}/src/main/java/seedu/address/model/AddressBook.java[`AddressBook`] and link:{repoURL}/src/main/java/seedu/address/model/person/Person.java[`Person`] classes can be used to implement the tag removal logic. link:{repoURL}/src/main/java/seedu/address/model/AddressBook.java[`AddressBook`] allows you to update a person, and link:{repoURL}/src/main/java/seedu/address/model/person/Person.java[`Person`] allows you to update the tags. * Solution ** Implement a `removeTag(Tag)` method in link:{repoURL}/src/main/java/seedu/address/model/AddressBook.java[`AddressBook`]. Loop through each person, and remove the `tag` from each person. ** Add a new API method `deleteTag(Tag)` in link:{repoURL}/src/main/java/seedu/address/model/ModelManager.java[`ModelManager`]. Your link:{repoURL}/src/main/java/seedu/address/model/ModelManager.java[`ModelManager`] should call `AddressBook#removeTag(Tag)`. ** Add new tests for each of the new public methods that you have added. ** See this https://github.com/se-edu/addressbook-level4/pull/790[PR] for the full solution. **** [discrete] ==== `Ui` component *Scenario:* You are in charge of `ui`. During a beta testing session, your team is observing how the users use your address book application. You realize that one of the users occasionally tries to delete non-existent tags from a contact, because the tags all look the same visually, and the user got confused. Another user made a typing mistake in his command, but did not realize he had done so because the error message wasn't prominent enough. A third user keeps scrolling down the list, because he keeps forgetting the index of the last person in the list. Your job is to implement improvements to the UI to solve all these problems. [TIP] Do take a look at <> before attempting to modify the `UI` component. . Use different colors for different tags inside person cards. For example, `friends` tags can be all in brown, and `colleagues` tags can be all in yellow. + **Before** + image::getting-started-ui-tag-before.png[width=""300""] + **After** + image::getting-started-ui-tag-after.png[width=""300""] + **** * Hints ** The tag labels are created inside link:{repoURL}/src/main/java/seedu/address/ui/PersonCard.java[the `PersonCard` constructor] (`new Label(tag.tagName)`). https://docs.oracle.com/javase/8/javafx/api/javafx/scene/control/Label.html[JavaFX's `Label` class] allows you to modify the style of each Label, such as changing its color. ** Use the .css attribute `-fx-background-color` to add a color. ** You may wish to modify link:{repoURL}/src/main/resources/view/DarkTheme.css[`DarkTheme.css`] to include some pre-defined colors using css, especially if you have experience with web-based css. * Solution ** You can modify the existing test methods for `PersonCard` 's to include testing the tag's color as well. ** See this https://github.com/se-edu/addressbook-level4/pull/798[PR] for the full solution. *** The PR uses the hash code of the tag names to generate a color. This is deliberately designed to ensure consistent colors each time the application runs. You may wish to expand on this design to include additional features, such as allowing users to set their own tag colors, and directly saving the colors to storage, so that tags retain their colors even if the hash code algorithm changes. **** . Modify link:{repoURL}/src/main/java/seedu/address/commons/events/ui/NewResultAvailableEvent.java[`NewResultAvailableEvent`] such that link:{repoURL}/src/main/java/seedu/address/ui/ResultDisplay.java[`ResultDisplay`] can show a different style on error (currently it shows the same regardless of errors). + **Before** + image::getting-started-ui-result-before.png[width=""200""] + **After** + image::getting-started-ui-result-after.png[width=""200""] + **** * Hints ** link:{repoURL}/src/main/java/seedu/address/commons/events/ui/NewResultAvailableEvent.java[`NewResultAvailableEvent`] is raised by link:{repoURL}/src/main/java/seedu/address/ui/CommandBox.java[`CommandBox`] which also knows whether the result is a success or failure, and is caught by link:{repoURL}/src/main/java/seedu/address/ui/ResultDisplay.java[`ResultDisplay`] which is where we want to change the style to. ** Refer to link:{repoURL}/src/main/java/seedu/address/ui/CommandBox.java[`CommandBox`] for an example on how to display an error. * Solution ** Modify link:{repoURL}/src/main/java/seedu/address/commons/events/ui/NewResultAvailableEvent.java[`NewResultAvailableEvent`] 's constructor so that users of the event can indicate whether an error has occurred. ** Modify link:{repoURL}/src/main/java/seedu/address/ui/ResultDisplay.java[`ResultDisplay#handleNewResultAvailableEvent(NewResultAvailableEvent)`] to react to this event appropriately. ** You can write two different kinds of tests to ensure that the functionality works: *** The unit tests for `ResultDisplay` can be modified to include verification of the color. *** The system tests link:{repoURL}/src/test/java/systemtests/AddressBookSystemTest.java[`AddressBookSystemTest#assertCommandBoxShowsDefaultStyle() and AddressBookSystemTest#assertCommandBoxShowsErrorStyle()`] to include verification for `ResultDisplay` as well. ** See this https://github.com/se-edu/addressbook-level4/pull/799[PR] for the full solution. *** Do read the commits one at a time if you feel overwhelmed. **** . Modify the link:{repoURL}/src/main/java/seedu/address/ui/StatusBarFooter.java[`StatusBarFooter`] to show the total number of people in the address book. + **Before** + image::getting-started-ui-status-before.png[width=""500""] + **After** + image::getting-started-ui-status-after.png[width=""500""] + **** * Hints ** link:{repoURL}/src/main/resources/view/StatusBarFooter.fxml[`StatusBarFooter.fxml`] will need a new `StatusBar`. Be sure to set the `GridPane.columnIndex` properly for each `StatusBar` to avoid misalignment! ** link:{repoURL}/src/main/java/seedu/address/ui/StatusBarFooter.java[`StatusBarFooter`] needs to initialize the status bar on application start, and to update it accordingly whenever the address book is updated. * Solution ** Modify the constructor of link:{repoURL}/src/main/java/seedu/address/ui/StatusBarFooter.java[`StatusBarFooter`] to take in the number of persons when the application just started. ** Use link:{repoURL}/src/main/java/seedu/address/ui/StatusBarFooter.java[`StatusBarFooter#handleAddressBookChangedEvent(AddressBookChangedEvent)`] to update the number of persons whenever there are new changes to the addressbook. ** For tests, modify link:{repoURL}/src/test/java/guitests/guihandles/StatusBarFooterHandle.java[`StatusBarFooterHandle`] by adding a state-saving functionality for the total number of people status, just like what we did for save location and sync status. ** For system tests, modify link:{repoURL}/src/test/java/systemtests/AddressBookSystemTest.java[`AddressBookSystemTest`] to also verify the new total number of persons status bar. ** See this https://github.com/se-edu/addressbook-level4/pull/803[PR] for the full solution. **** [discrete] ==== `Storage` component *Scenario:* You are in charge of `storage`. For your next project milestone, your team plans to implement a new feature of saving the address book to the cloud. However, the current implementation of the application constantly saves the address book after the execution of each command, which is not ideal if the user is working on limited internet connection. Your team decided that the application should instead save the changes to a temporary local backup file first, and only upload to the cloud after the user closes the application. Your job is to implement a backup API for the address book storage. [TIP] Do take a look at <> before attempting to modify the `Storage` component. . Add a new method `backupAddressBook(ReadOnlyAddressBook)`, so that the address book can be saved in a fixed temporary location. + **** * Hint ** Add the API method in link:{repoURL}/src/main/java/seedu/address/storage/AddressBookStorage.java[`AddressBookStorage`] interface. ** Implement the logic in link:{repoURL}/src/main/java/seedu/address/storage/StorageManager.java[`StorageManager`] and link:{repoURL}/src/main/java/seedu/address/storage/JsonAddressBookStorage.java[`JsonAddressBookStorage`] class. * Solution ** See this https://github.com/se-edu/addressbook-level4/pull/594[PR] for the full solution. **** [[GetStartedProgramming-RemarkCommand]] === Creating a new command: `remark` By creating this command, you will get a chance to learn how to implement a feature end-to-end, touching all major components of the app. *Scenario:* You are a software maintainer for `addressbook`, as the former developer team has moved on to new projects. The current users of your application have a list of new feature requests that they hope the software will eventually have. The most popular request is to allow adding additional comments/notes about a particular contact, by providing a flexible `remark` field for each contact, rather than relying on tags alone. After designing the specification for the `remark` command, you are convinced that this feature is worth implementing. Your job is to implement the `remark` command. ==== Description Edits the remark for a person specified in the `INDEX`. + Format: `remark INDEX r/[REMARK]` Examples: * `remark 1 r/Likes to drink coffee.` + Edits the remark for the first person to `Likes to drink coffee.` * `remark 1 r/` + Removes the remark for the first person. ==== Step-by-step Instructions ===== [Step 1] Logic: Teach the app to accept 'remark' which does nothing Let's start by teaching the application how to parse a `remark` command. We will add the logic of `remark` later. **Main:** . Add a `RemarkCommand` that extends link:{repoURL}/src/main/java/seedu/address/logic/commands/Command.java[`Command`]. Upon execution, it should just throw an `Exception`. . Modify link:{repoURL}/src/main/java/seedu/address/logic/parser/AddressBookParser.java[`AddressBookParser`] to accept a `RemarkCommand`. **Tests:** . Add `RemarkCommandTest` that tests that `execute()` throws an Exception. . Add new test method to link:{repoURL}/src/test/java/seedu/address/logic/parser/AddressBookParserTest.java[`AddressBookParserTest`], which tests that typing ""remark"" returns an instance of `RemarkCommand`. ===== [Step 2] Logic: Teach the app to accept 'remark' arguments Let's teach the application to parse arguments that our `remark` command will accept. E.g. `1 r/Likes to drink coffee.` **Main:** . Modify `RemarkCommand` to take in an `Index` and `String` and print those two parameters as the error message. . Add `RemarkCommandParser` that knows how to parse two arguments, one index and one with prefix 'r/'. . Modify link:{repoURL}/src/main/java/seedu/address/logic/parser/AddressBookParser.java[`AddressBookParser`] to use the newly implemented `RemarkCommandParser`. **Tests:** . Modify `RemarkCommandTest` to test the `RemarkCommand#equals()` method. . Add `RemarkCommandParserTest` that tests different boundary values for `RemarkCommandParser`. . Modify link:{repoURL}/src/test/java/seedu/address/logic/parser/AddressBookParserTest.java[`AddressBookParserTest`] to test that the correct command is generated according to the user input. ===== [Step 3] Ui: Add a placeholder for remark in `PersonCard` Let's add a placeholder on all our link:{repoURL}/src/main/java/seedu/address/ui/PersonCard.java[`PersonCard`] s to display a remark for each person later. **Main:** . Add a `Label` with any random text inside link:{repoURL}/src/main/resources/view/PersonListCard.fxml[`PersonListCard.fxml`]. . Add FXML annotation in link:{repoURL}/src/main/java/seedu/address/ui/PersonCard.java[`PersonCard`] to tie the variable to the actual label. **Tests:** . Modify link:{repoURL}/src/test/java/guitests/guihandles/PersonCardHandle.java[`PersonCardHandle`] so that future tests can read the contents of the remark label. ===== [Step 4] Model: Add `Remark` class We have to properly encapsulate the remark in our link:{repoURL}/src/main/java/seedu/address/model/person/Person.java[`Person`] class. Instead of just using a `String`, let's follow the conventional class structure that the codebase already uses by adding a `Remark` class. **Main:** . Add `Remark` to model component (you can copy from link:{repoURL}/src/main/java/seedu/address/model/person/Address.java[`Address`], remove the regex and change the names accordingly). . Modify `RemarkCommand` to now take in a `Remark` instead of a `String`. **Tests:** . Add test for `Remark`, to test the `Remark#equals()` method. ===== [Step 5] Model: Modify `Person` to support a `Remark` field Now we have the `Remark` class, we need to actually use it inside link:{repoURL}/src/main/java/seedu/address/model/person/Person.java[`Person`]. **Main:** . Add `getRemark()` in link:{repoURL}/src/main/java/seedu/address/model/person/Person.java[`Person`]. . You may assume that the user will not be able to use the `add` and `edit` commands to modify the remarks field (i.e. the person will be created without a remark). . Modify link:{repoURL}/src/main/java/seedu/address/model/util/SampleDataUtil.java/[`SampleDataUtil`] to add remarks for the sample data (delete your `data/addressbook.json` so that the application will load the sample data when you launch it.) ===== [Step 6] Storage: Add `Remark` field to `JsonAdaptedPerson` class We now have `Remark` s for `Person` s, but they will be gone when we exit the application. Let's modify link:{repoURL}/src/main/java/seedu/address/storage/JsonAdaptedPerson.java[`JsonAdaptedPerson`] to include a `Remark` field so that it will be saved. **Main:** . Add a new JSON field for `Remark`. **Tests:** . Fix `invalidAndValidPersonAddressBook.json`, `typicalPersonsAddressBook.json`, `validAddressBook.json` etc., such that the JSON tests will not fail due to a missing `remark` field. ===== [Step 6b] Test: Add withRemark() for `PersonBuilder` Since `Person` can now have a `Remark`, we should add a helper method to link:{repoURL}/src/test/java/seedu/address/testutil/PersonBuilder.java[`PersonBuilder`], so that users are able to create remarks when building a link:{repoURL}/src/main/java/seedu/address/model/person/Person.java[`Person`]. **Tests:** . Add a new method `withRemark()` for link:{repoURL}/src/test/java/seedu/address/testutil/PersonBuilder.java[`PersonBuilder`]. This method will create a new `Remark` for the person that it is currently building. . Try and use the method on any sample `Person` in link:{repoURL}/src/test/java/seedu/address/testutil/TypicalPersons.java[`TypicalPersons`]. ===== [Step 7] Ui: Connect `Remark` field to `PersonCard` Our remark label in link:{repoURL}/src/main/java/seedu/address/ui/PersonCard.java[`PersonCard`] is still a placeholder. Let's bring it to life by binding it with the actual `remark` field. **Main:** . Modify link:{repoURL}/src/main/java/seedu/address/ui/PersonCard.java[`PersonCard`]'s constructor to bind the `Remark` field to the `Person` 's remark. **Tests:** . Modify link:{repoURL}/src/test/java/seedu/address/ui/testutil/GuiTestAssert.java[`GuiTestAssert#assertCardDisplaysPerson(...)`] so that it will compare the now-functioning remark label. ===== [Step 8] Logic: Implement `RemarkCommand#execute()` logic We now have everything set up... but we still can't modify the remarks. Let's finish it up by adding in actual logic for our `remark` command. **Main:** . Replace the logic in `RemarkCommand#execute()` (that currently just throws an `Exception`), with the actual logic to modify the remarks of a person. **Tests:** . Update `RemarkCommandTest` to test that the `execute()` logic works. ==== Full Solution See this https://github.com/se-edu/addressbook-level4/pull/599[PR] for the step-by-step solution. [appendix] == Product Scope *Target user profile*: * has a need to manage a significant number of contacts * prefer desktop apps over other types * can type fast * prefers typing over mouse input * is reasonably comfortable using CLI apps *Value proposition*: manage contacts faster than a typical mouse/GUI driven app [appendix] == User Stories Priorities: High (must have) - `* * \\*`, Medium (nice to have) - `* \\*`, Low (unlikely to have) - `*` [width=""59%"",cols=""22%,<23%,<25%,<30%"",options=""header"",] |======================================================================= |Priority |As a/an ... |I want to ... |So that I can... |`* * *` |new user |see usage instructions |refer to instructions when I forget how to use the App |`* * *` |user |add expenses into the finance tracker |record all my expenses |`* *` |user |view a list of my expenses in certain time periods |have a better overview of my expenses |`* * *` |user |see the total amount of money I have |see how much money I have left overall and better plan my finances |`* * *` |user |make changes to expenses I previously added |correct any mistakes |`* * *` |organised user |categorise my expenses |know my spending for each category |`* * *` |user |delete an expense |remove entries that I no longer need to keep track of |`* * *` |thrifty user |set a budget |manage my expenses and see how much more I can spend for the remaining part of the day/week/month/year |`* *` |user | split my budget into different categories |enhance my finance planning further and not spend excessively on a single category, e.g. food |`* * *` |user |edit my budget |change the amount of budget available or the duration |`* * *` |user |cancel my budget | |`* * *` |forgetful user |add my debts |can see who I owe money to |`* * *` |user |edit my debts |change the amount I owe if any changes occur |`* *` |user |view a list of my debts and see when they are due |remind myself to pay the people I owe by their due dates |`* * *` |user |delete my debts | |`* * *` |user |clear my paid debts |know I have settled them |`* *` |analytical user |see a breakdown of my expenses |know what I spend the most on |`* *` |visual user |have charts and graphs to represent my expenditure |have a better picture on the different categories of my expenses |`* *` |efficient user |be able to view my command history |easily input a repeated command when needed |`* * *` |user |undo and redo my actions | |`* * *` |user |clear all entries |start with an empty finance tracker again when needed |`* *` |non-tech-savvy user |type simple commands step by step |use the programme more easily without having to keep referring to the help menu |`*` |user |receive reminders regarding my expenditure |know if my spending is about to exceed my budget or when my debts are about to be due |======================================================================= [appendix] == Use Cases (For all use cases below, the *System* is the `AddressBook` and the *Actor* is the `user`, unless specified otherwise) [discrete] === Use case: Delete person *MSS* 1. User requests to list persons 2. AddressBook shows a list of persons 3. User requests to delete a specific person in the list 4. AddressBook deletes the person + Use case ends. *Extensions* [none] * 2a. The list is empty. + Use case ends. * 3a. The given index is invalid. + [none] ** 3a1. AddressBook shows an error message. + Use case resumes at step 2. _{More to be added}_ [appendix] == Non Functional Requirements . Should work on any <> as long as it has Java `9` or higher installed. . Should be able to hold up to 1000 persons without a noticeable sluggishness in performance for typical usage. . A user with above average typing speed for regular English text (i.e. not code, not system admin commands) should be able to accomplish most of the tasks faster using commands than using the mouse. _{More to be added}_ [appendix] == Glossary [[mainstream-os]] Mainstream OS:: Windows, Linux, Unix, OS-X [[private-contact-detail]] Private contact detail:: A contact detail that is not meant to be shared with others [appendix] == Product Survey *Product Name* Author: ... Pros: * ... * ... Cons: * ... * ... [appendix] == Instructions for Manual Testing Given below are instructions to test the app manually. [NOTE] These instructions only provide a starting point for testers to work on; testers are expected to do more _exploratory_ testing. === Launch and Shutdown . Initial launch .. Download the jar file and copy into an empty folder .. Double-click the jar file + Expected: Shows the GUI with a set of sample contacts. The window size may not be optimum. . Saving window preferences .. Resize the window to an optimum size. Move the window to a different location. Close the window. .. Re-launch the app by double-clicking the jar file. + Expected: The most recent window size and location is retained. _{ more test cases ... }_ === Deleting a person . Deleting a person while all persons are listed .. Prerequisites: List all persons using the `list` command. Multiple persons in the list. .. Test case: `delete 1` + Expected: First contact is deleted from the list. Details of the deleted contact shown in the status message. Timestamp in the status bar is updated. .. Test case: `delete 0` + Expected: No person is deleted. Error details shown in the status message. Status bar remains the same. .. Other incorrect delete commands to try: `delete`, `delete x` (where x is larger than the list size) _{give more}_ + Expected: Similar to previous. _{ more test cases ... }_ === Saving data . Dealing with missing/corrupted data files .. _{explain how to simulate a missing/corrupted file and the expected behavior}_ _{ more test cases ... }_ ",12311,False,2055.39340256591,median "[[main-component]] = Main Component //THIS FILE IS COPIED: EDIT THE SOURCE FILE: :page-source: core/camel-main/src/main/docs/main.adoc :docTitle: Main :artifactId: camel-main :description: Camel Main support :since: 3.0 :supportLevel: Stable //Manually maintained attributes :group: Core *Since Camel {since}* This module is used for running Camel standalone via a main class extended from `camel-main`. == Configuration options When running Camel via `camel-main` you can configure Camel in the `application.properties` file. The following table lists all the options: // main options: START [width=""100%"",cols=""2,5,^1,2"",options=""header""] |=== | Name | Description | Default | Type | *camel.main.allowUseOriginal{zwsp}Message* | Sets whether to allow access to the original message from Camel's error handler, or from org.apache.camel.spi.UnitOfWork.getOriginalInMessage(). Turning this off can optimize performance, as defensive copy of the original message is not needed. Default is false. | | boolean | *camel.main.autoConfiguration{zwsp}Enabled* | Whether auto configuration of components, dataformats, languages is enabled or not. When enabled the configuration parameters are loaded from the properties component and optionally from the classpath file META-INF/services/org/apache/camel/autowire.properties. You can prefix the parameters in the properties file with: - camel.component.name.option1=value1 - camel.component.name.option2=value2 - camel.dataformat.name.option1=value1 - camel.dataformat.name.option2=value2 - camel.language.name.option1=value1 - camel.language.name.option2=value2 Where name is the name of the component, dataformat or language such as seda,direct,jaxb. The auto configuration also works for any options on components that is a complex type (not standard Java type) and there has been an explicit single bean instance registered to the Camel registry via the org.apache.camel.spi.Registry#bind(String,Object) method or by using the org.apache.camel.BindToRegistry annotation style. This option is default enabled. | true | boolean | *camel.main.autoConfiguration{zwsp}EnvironmentVariablesEnabled* | Whether auto configuration should include OS environment variables as well. When enabled this allows to overrule any configuration using an OS environment variable. For example to set a shutdown timeout of 5 seconds: CAMEL_MAIN_SHUTDOWNTIMEOUT=5. This option is default enabled. | true | boolean | *camel.main.autoConfiguration{zwsp}FailFast* | Whether auto configuration should fail fast when configuring one ore more properties fails for whatever reason such as a invalid property name, etc. This option is default enabled. | true | boolean | *camel.main.autoConfiguration{zwsp}LogSummary* | Whether auto configuration should log a summary with the configured properties. This option is default enabled. | true | boolean | *camel.main.autoConfiguration{zwsp}SystemPropertiesEnabled* | Whether auto configuration should include JVM system properties as well. When enabled this allows to overrule any configuration using a JVM system property. For example to set a shutdown timeout of 5 seconds: -D camel.main.shutdown-timeout=5. Note that JVM system properties take precedence over OS environment variables. This option is default enabled. | true | boolean | *camel.main.autoStartup* | Sets whether the object should automatically start when Camel starts. Important: Currently only routes can be disabled, as CamelContext's are always started. Note: When setting auto startup false on CamelContext then that takes precedence and no routes are started. You would need to start CamelContext explicit using the org.apache.camel.CamelContext.start() method, to start the context, and then you would need to start the routes manually using CamelContext.getRouteController().startRoute(String). Default is true to always start up. | true | boolean | *camel.main.autowiredEnabled* | Whether autowiring is enabled. This is used for automatic autowiring options (the option must be marked as autowired) by looking up in the registry to find if there is a single instance of matching type, which then gets configured on the component. This can be used for automatic configuring JDBC data sources, JMS connection factories, AWS Clients, etc. Default is true. | true | boolean | *camel.main.backlogTracing* | Sets whether backlog tracing is enabled or not. Default is false. | | boolean | *camel.main.beanIntrospection{zwsp}ExtendedStatistics* | Sets whether bean introspection uses extended statistics. The default is false. | | boolean | *camel.main.beanIntrospection{zwsp}LoggingLevel* | Sets the logging level used by bean introspection, logging activity of its usage. The default is TRACE. | | LoggingLevel | *camel.main.beanPostProcessor{zwsp}Enabled* | Can be used to turn off bean post processing. Be careful to turn this off, as this means that beans that use Camel annotations such as org.apache.camel.EndpointInject , org.apache.camel.ProducerTemplate , org.apache.camel.Produce , org.apache.camel.Consume etc will not be injected and in use. Turning this off should only be done if you are sure you do not use any of these Camel features. Not all runtimes allow turning this off (such as camel-blueprint or camel-cdi with XML). The default value is true (enabled). | true | boolean | *camel.main.caseInsensitive{zwsp}Headers* | Whether to use case sensitive or insensitive headers. Important: When using case sensitive (this is set to false). Then the map is case sensitive which means headers such as content-type and Content-Type are two different keys which can be a problem for some protocols such as HTTP based, which rely on case insensitive headers. However case sensitive implementations can yield faster performance. Therefore use case sensitive implementation with care. Default is true. | true | boolean | *camel.main.configuration{zwsp}Classes* | Sets classes names that will be used to configure the camel context as example by providing custom beans through org.apache.camel.BindToRegistry annotation. | | String | *camel.main.configurations* | Sets the configuration objects used to configure the camel context. | | List | *camel.main.consumerTemplate{zwsp}CacheSize* | Consumer template endpoints cache size. | 1000 | int | *camel.main.durationHitExitCode* | Sets the exit code for the application if duration was hit | | int | *camel.main.durationMaxIdle{zwsp}Seconds* | To specify for how long time in seconds Camel can be idle before automatic terminating the JVM. You can use this to run Camel for a short while. | | int | *camel.main.durationMaxMessages* | To specify how many messages to process by Camel before automatic terminating the JVM. You can use this to run Camel for a short while. | | int | *camel.main.durationMaxSeconds* | To specify for how long time in seconds to keep running the JVM before automatic terminating the JVM. You can use this to run Camel for a short while. | | int | *camel.main.endpointBridgeError{zwsp}Handler* | Allows for bridging the consumer to the Camel routing Error Handler, which mean any exceptions occurred while the consumer is trying to pickup incoming messages, or the likes, will now be processed as a message and handled by the routing Error Handler. By default the consumer will use the org.apache.camel.spi.ExceptionHandler to deal with exceptions, that will be logged at WARN/ERROR level and ignored. The default value is false. | | boolean | *camel.main.endpointLazyStart{zwsp}Producer* | Whether the producer should be started lazy (on the first message). By starting lazy you can use this to allow CamelContext and routes to startup in situations where a producer may otherwise fail during starting and cause the route to fail being started. By deferring this startup to be lazy then the startup failure can be handled during routing messages via Camel's routing error handlers. Beware that when the first message is processed then creating and starting the producer may take a little time and prolong the total processing time of the processing. The default value is false. | | boolean | *camel.main.endpointRuntime{zwsp}StatisticsEnabled* | Sets whether endpoint runtime statistics is enabled (gathers runtime usage of each incoming and outgoing endpoints). The default value is false. | | boolean | *camel.main.fileConfigurations* | Directory to load additional configuration files that contains configuration values that takes precedence over any other configuration. This can be used to refer to files that may have secret configuration that has been mounted on the file system for containers. You can specify a pattern to load from sub directories and a name pattern such as /var/app/secret/.properties, multiple directories can be separated by comma. | | String | *camel.main.inflightRepository{zwsp}BrowseEnabled* | Sets whether the inflight repository should allow browsing each inflight exchange. This is by default disabled as there is a very slight performance overhead when enabled. | | boolean | *camel.main.javaRoutesExclude{zwsp}Pattern* | Used for exclusive filtering RouteBuilder classes which are collected from the registry or via classpath scanning. The exclusive filtering takes precedence over inclusive filtering. The pattern is using Ant-path style pattern. Multiple patterns can be specified separated by comma. For example to exclude all classes starting with Bar use: **/Bar* To exclude all routes form a specific package use: com/mycompany/bar/* To exclude all routes form a specific package and its sub-packages use double wildcards: com/mycompany/bar/** And to exclude all routes from two specific packages use: com/mycompany/bar/*,com/mycompany/stuff/* | | String | *camel.main.javaRoutesInclude{zwsp}Pattern* | Used for inclusive filtering RouteBuilder classes which are collected from the registry or via classpath scanning. The exclusive filtering takes precedence over inclusive filtering. The pattern is using Ant-path style pattern. Multiple patterns can be specified separated by comma. Multiple patterns can be specified separated by comma. For example to include all classes starting with Foo use: **/Foo To include all routes form a specific package use: com/mycompany/foo/* To include all routes form a specific package and its sub-packages use double wildcards: com/mycompany/foo/** And to include all routes from two specific packages use: com/mycompany/foo/*,com/mycompany/stuff/* | | String | *camel.main.jmxEnabled* | Enable JMX in your Camel application. | true | boolean | *camel.main.jmxManagementName{zwsp}Pattern* | The naming pattern for creating the CamelContext JMX management name. The default pattern is #name# | #name# | String | *camel.main.jmxManagement{zwsp}StatisticsLevel* | Sets the JMX statistics level, the level can be set to Extended to gather additional information The default value is Default. | Default | ManagementStatisticsLevel | *camel.main.lightweight* | Experimental: Configure the context to be lightweight. This will trigger some optimizations and memory reduction options. Lightweight context have some limitations. At this moment, dynamic endpoint destinations are not supported. | | boolean | *camel.main.loadTypeConverters* | Whether to load custom type converters by scanning classpath. This is used for backwards compatibility with Camel 2.x. Its recommended to migrate to use fast type converter loading by setting Converter(loader = true) on your custom type converter classes. | | boolean | *camel.main.logDebugMaxChars* | Is used to limit the maximum length of the logging Camel message bodies. If the message body is longer than the limit, the log message is clipped. Use -1 to have unlimited length. Use for example 1000 to log at most 1000 characters. | | int | *camel.main.logExhaustedMessage{zwsp}Body* | Sets whether to log exhausted message body with message history. Default is false. | | boolean | *camel.main.logMask* | Sets whether log mask is enabled or not. Default is false. | | boolean | *camel.main.mdcLoggingKeys{zwsp}Pattern* | Sets the pattern used for determine which custom MDC keys to propagate during message routing when the routing engine continues routing asynchronously for the given message. Setting this pattern to will propagate all custom keys. Or setting the pattern to foo,bar will propagate any keys starting with either foo or bar. Notice that a set of standard Camel MDC keys are always propagated which starts with camel. as key name. The match rules are applied in this order (case insensitive): 1. exact match, returns true 2. wildcard match (pattern ends with a and the name starts with the pattern), returns true 3. regular expression match, returns true 4. otherwise returns false | | String | *camel.main.messageHistory* | Sets whether message history is enabled or not. Default is false. | | boolean | *camel.main.name* | Sets the name of the CamelContext. | | String | *camel.main.packageScanRoute{zwsp}Builders* | Sets package names for scanning for org.apache.camel.builder.RouteBuilder classes as candidates to be included. If you are using Spring Boot then its instead recommended to use Spring Boots component scanning and annotate your route builder classes with Component. In other words only use this for Camel Main in standalone mode. | | String | *camel.main.producerTemplate{zwsp}CacheSize* | Producer template endpoints cache size. | 1000 | int | *camel.main.routeControllerBack{zwsp}OffDelay* | Backoff delay in millis when restarting a route that failed to startup. | | long | *camel.main.routeControllerBack{zwsp}OffMaxAttempts* | Backoff maximum number of attempts to restart a route that failed to startup. When this threshold has been exceeded then the controller will give up attempting to restart the route, and the route will remain as stopped. | | long | *camel.main.routeControllerBack{zwsp}OffMaxDelay* | Backoff maximum delay in millis when restarting a route that failed to startup. | | long | *camel.main.routeControllerBack{zwsp}OffMaxElapsedTime* | Backoff maximum elapsed time in millis, after which the backoff should be considered exhausted and no more attempts should be made. | | long | *camel.main.routeControllerBack{zwsp}OffMultiplier* | Backoff multiplier to use for exponential backoff. This is used to extend the delay between restart attempts. | | double | *camel.main.routeController{zwsp}ExcludeRoutes* | Pattern for filtering routes to be excluded as supervised. The pattern is matching on route id, and endpoint uri for the route. Multiple patterns can be separated by comma. For example to exclude all JMS routes, you can say jms:. And to exclude routes with specific route ids mySpecialRoute,myOtherSpecialRoute. The pattern supports wildcards and uses the matcher from org.apache.camel.support.PatternHelper#matchPattern. | | String | *camel.main.routeController{zwsp}IncludeRoutes* | Pattern for filtering routes to be included as supervised. The pattern is matching on route id, and endpoint uri for the route. Multiple patterns can be separated by comma. For example to include all kafka routes, you can say kafka:. And to include routes with specific route ids myRoute,myOtherRoute. The pattern supports wildcards and uses the matcher from org.apache.camel.support.PatternHelper#matchPattern. | | String | *camel.main.routeController{zwsp}InitialDelay* | Initial delay in milli seconds before the route controller starts, after CamelContext has been started. | | long | *camel.main.routeController{zwsp}LoggingLevel* | Sets the logging level used for logging route activity (such as starting and stopping routes). The default logging level is DEBUG. | DEBUG | LoggingLevel | *camel.main.routeController{zwsp}SuperviseEnabled* | To enable using supervising route controller which allows Camel to startup and then the controller takes care of starting the routes in a safe manner. This can be used when you want to startup Camel despite a route may otherwise fail fast during startup and cause Camel to fail to startup as well. By delegating the route startup to the supervising route controller then its manages the startup using a background thread. The controller allows to be configured with various settings to attempt to restart failing routes. | | boolean | *camel.main.routeController{zwsp}ThreadPoolSize* | The number of threads used by the route controller scheduled thread pool that are used for restarting routes. The pool uses 1 thread by default, but you can increase this to allow the controller to concurrently attempt to restart multiple routes in case more than one route has problems starting. | | int | *camel.main.routeController{zwsp}UnhealthyOnExhausted* | Whether to mark the route as unhealthy (down) when all restarting attempts (backoff) have failed and the route is not successfully started and the route manager is giving up. Setting this to true allows health checks to know about this and can report the Camel application as DOWN. The default is false. | | boolean | *camel.main.routeFilterExclude{zwsp}Pattern* | Used for filtering routes routes matching the given pattern, which follows the following rules: - Match by route id - Match by route input endpoint uri The matching is using exact match, by wildcard and regular expression as documented by PatternHelper#matchPattern(String,String) . For example to only include routes which starts with foo in their route id's, use: include=foo* And to exclude routes which starts from JMS endpoints, use: exclude=jms:* Multiple patterns can be separated by comma, for example to exclude both foo and bar routes, use: exclude=foo*,bar* Exclude takes precedence over include. | | String | *camel.main.routeFilterInclude{zwsp}Pattern* | Used for filtering routes matching the given pattern, which follows the following rules: - Match by route id - Match by route input endpoint uri The matching is using exact match, by wildcard and regular expression as documented by PatternHelper#matchPattern(String,String) . For example to only include routes which starts with foo in their route id's, use: include=foo* And to exclude routes which starts from JMS endpoints, use: exclude=jms:* Multiple patterns can be separated by comma, for example to exclude both foo and bar routes, use: exclude=foo*,bar* Exclude takes precedence over include. | | String | *camel.main.routesBuilder{zwsp}Classes* | Sets classes names that implement RoutesBuilder . | | String | *camel.main.routesBuilders* | Sets the RoutesBuilder instances. | | List | *camel.main.routesCollector{zwsp}Enabled* | Whether the routes collector is enabled or not. When enabled Camel will auto-discover routes (RouteBuilder instances from the registry and also load additional routes from the file system). The routes collector is default enabled. | true | boolean | *camel.main.routesExclude{zwsp}Pattern* | Used for exclusive filtering of routes from directories. The exclusive filtering takes precedence over inclusive filtering. The pattern is using Ant-path style pattern. Multiple patterns can be specified separated by comma, as example, to exclude all the routes from a directory whose name contains foo use: **/foo. | | String | *camel.main.routesInclude{zwsp}Pattern* | Used for inclusive filtering of routes from directories. The exclusive filtering takes precedence over inclusive filtering. The pattern is using Ant-path style pattern. Multiple patterns can be specified separated by comma, as example, to include all the routes from a directory whose name contains foo use: **/foo. | classpath:camel/*.xml,classpath:camel-template/*.xml,classpath:camel-rest/*.xml | String | *camel.main.shutdownLogInflight{zwsp}ExchangesOnTimeout* | Sets whether to log information about the inflight Exchanges which are still running during a shutdown which didn't complete without the given timeout. This requires to enable the option inflightRepositoryBrowseEnabled. | true | boolean | *camel.main.shutdownNowOn{zwsp}Timeout* | Sets whether to force shutdown of all consumers when a timeout occurred and thus not all consumers was shutdown within that period. You should have good reasons to set this option to false as it means that the routes keep running and is halted abruptly when CamelContext has been shutdown. | true | boolean | *camel.main.shutdownRoutesIn{zwsp}ReverseOrder* | Sets whether routes should be shutdown in reverse or the same order as they were started. | true | boolean | *camel.main.shutdownSuppress{zwsp}LoggingOnTimeout* | Whether Camel should try to suppress logging during shutdown and timeout was triggered, meaning forced shutdown is happening. And during forced shutdown we want to avoid logging errors/warnings et all in the logs as a side-effect of the forced timeout. Notice the suppress is a best effort as there may still be some logs coming from 3rd party libraries and whatnot, which Camel cannot control. This option is default false. | | boolean | *camel.main.shutdownTimeout* | Timeout in seconds to graceful shutdown Camel. | 45 | int | *camel.main.startupRecorder* | To use startup recorder for capturing execution time during starting Camel. The recorder can be one of: false, logging, java-flight-recorder The default is false. | | String | *camel.main.startupRecorderDir* | Directory to store the recording. By default the user home directory will be used. Use false to turn off saving recording to disk. | | String | *camel.main.startupRecorder{zwsp}Duration* | How long time to run the startup recorder. Use 0 (default) to keep the recorder running until the JVM is exited. Use -1 to stop the recorder right after Camel has been started (to only focus on potential Camel startup performance bottlenecks) Use a positive value to keep recording for N seconds. When the recorder is stopped then the recording is auto saved to disk (note: save to disk can be disabled by setting startupRecorderDir to false) | | long | *camel.main.startupRecorderMax{zwsp}Depth* | To filter our sub steps at a maximum depth. Use -1 for no maximum. Use 0 for no sub steps. Use 1 for max 1 sub step, and so forth. The default is -1. | -1 | int | *camel.main.startupRecorder{zwsp}Profile* | To use a specific Java Flight Recorder profile configuration, such as default or profile. The default is default. | default | String | *camel.main.startupRecorder{zwsp}Recording* | To enable Java Flight Recorder to start a recording and automatic dump the recording to disk after startup is complete. This requires that camel-jfr is on the classpath. The default is true. | true | boolean | *camel.main.startupSummaryLevel* | Controls the level of information logged during startup (and shutdown) of CamelContext. | Default | StartupSummaryLevel | *camel.main.streamCachingAny{zwsp}SpoolRules* | Sets whether if just any of the org.apache.camel.spi.StreamCachingStrategy.SpoolRule rules returns true then shouldSpoolCache(long) returns true, to allow spooling to disk. If this option is false, then all the org.apache.camel.spi.StreamCachingStrategy.SpoolRule must return true. The default value is false which means that all the rules must return true. | | boolean | *camel.main.streamCachingBuffer{zwsp}Size* | Sets the stream caching buffer size to use when allocating in-memory buffers used for in-memory stream caches. The default size is 4096. | | int | *camel.main.streamCaching{zwsp}Enabled* | Sets whether stream caching is enabled or not. Default is false. | | boolean | *camel.main.streamCachingRemove{zwsp}SpoolDirectoryWhenStopping* | Whether to remove stream caching temporary directory when stopping. This option is default true. | true | boolean | *camel.main.streamCachingSpool{zwsp}Cipher* | Sets a stream caching cipher name to use when spooling to disk to write with encryption. By default the data is not encrypted. | | String | *camel.main.streamCachingSpool{zwsp}Directory* | Sets the stream caching spool (temporary) directory to use for overflow and spooling to disk. If no spool directory has been explicit configured, then a temporary directory is created in the java.io.tmpdir directory. | | String | *camel.main.streamCachingSpool{zwsp}Threshold* | Stream caching threshold in bytes when overflow to disk is activated. The default threshold is 128kb. Use -1 to disable overflow to disk. | | long | *camel.main.streamCachingSpool{zwsp}UsedHeapMemoryLimit* | Sets what the upper bounds should be when streamCachingSpoolUsedHeapMemoryThreshold is in use. | | String | *camel.main.streamCachingSpool{zwsp}UsedHeapMemoryThreshold* | Sets a percentage (1-99) of used heap memory threshold to activate stream caching spooling to disk. | | int | *camel.main.streamCaching{zwsp}StatisticsEnabled* | Sets whether stream caching statistics is enabled. | | boolean | *camel.main.threadNamePattern* | Sets the thread name pattern used for creating the full thread name. The default pattern is: Camel (#camelId#) thread ##counter# - #name# Where #camelId# is the name of the CamelContext. and #counter# is a unique incrementing counter. and #name# is the regular thread name. You can also use #longName# which is the long thread name which can includes endpoint parameters etc. | | String | *camel.main.tracing* | Sets whether tracing is enabled or not. Default is false. | | boolean | *camel.main.tracingPattern* | Tracing pattern to match which node EIPs to trace. For example to match all To EIP nodes, use to. The pattern matches by node and route id's Multiple patterns can be separated by comma. | | String | *camel.main.useBreadcrumb* | Set whether breadcrumb is enabled. The default value is false. | | boolean | *camel.main.useDataType* | Whether to enable using data type on Camel messages. Data type are automatic turned on if one ore more routes has been explicit configured with input and output types. Otherwise data type is default off. | | boolean | *camel.main.useMdcLogging* | To turn on MDC logging | | boolean | *camel.faulttolerance.bulkhead{zwsp}Enabled* | Whether bulkhead is enabled or not on the circuit breaker. Default is false. | false | Boolean | *camel.faulttolerance.bulkhead{zwsp}ExecutorServiceRef* | References to a custom thread pool to use when bulkhead is enabled. | | String | *camel.faulttolerance.bulkhead{zwsp}MaxConcurrentCalls* | Configures the max amount of concurrent calls the bulkhead will support. Default value is 10. | 10 | Integer | *camel.faulttolerance.bulkhead{zwsp}WaitingTaskQueue* | Configures the task queue size for holding waiting tasks to be processed by the bulkhead. Default value is 10. | 10 | Integer | *camel.faulttolerance.circuit{zwsp}BreakerRef* | Refers to an existing io.smallrye.faulttolerance.core.circuit.breaker.CircuitBreaker instance to lookup and use from the registry. When using this, then any other circuit breaker options are not in use. | | String | *camel.faulttolerance.delay* | Control how long the circuit breaker stays open. The value are in seconds and the default is 5 seconds. | 5 | Long | *camel.faulttolerance.failure{zwsp}Ratio* | Configures the failure rate threshold in percentage. If the failure rate is equal or greater than the threshold the CircuitBreaker transitions to open and starts short-circuiting calls. The threshold must be greater than 0 and not greater than 100. Default value is 50 percentage. | 50 | Integer | *camel.faulttolerance.request{zwsp}VolumeThreshold* | Controls the size of the rolling window used when the circuit breaker is closed Default value is 20. | 20 | Integer | *camel.faulttolerance.success{zwsp}Threshold* | Controls the number of trial calls which are allowed when the circuit breaker is half-open Default value is 1. | 1 | Integer | *camel.faulttolerance.timeout{zwsp}Duration* | Configures the thread execution timeout. Default value is 1000 milliseconds. | 1000 | Long | *camel.faulttolerance.timeout{zwsp}Enabled* | Whether timeout is enabled or not on the circuit breaker. Default is false. | false | Boolean | *camel.faulttolerance.timeout{zwsp}PoolSize* | Configures the pool size of the thread pool when timeout is enabled. Default value is 10. | 10 | Integer | *camel.faulttolerance.timeout{zwsp}ScheduledExecutorServiceRef* | References to a custom thread pool to use when timeout is enabled | | String | *camel.health.config* | Set additional HealthConfigurationProperties for fine grained configuration of health checks. | | Map | *camel.health.contextEnabled* | Whether context health check is enabled | true | Boolean | *camel.health.enabled* | Whether health check is enabled globally | true | Boolean | *camel.health.registryEnabled* | Whether registry health check is enabled | true | Boolean | *camel.health.routesEnabled* | Whether routes health check is enabled | true | Boolean | *camel.hystrix.allowMaximumSize{zwsp}ToDivergeFromCoreSize* | Allows the configuration for maximumSize to take effect. That value can then be equal to, or higher, than coreSize | | Boolean | *camel.hystrix.circuitBreaker{zwsp}Enabled* | Whether to use a HystrixCircuitBreaker or not. If false no circuit-breaker logic will be used and all requests permitted. This is similar in effect to circuitBreakerForceClosed() except that continues tracking metrics and knowing whether it should be open/closed, this property results in not even instantiating a circuit-breaker. | | Boolean | *camel.hystrix.circuitBreaker{zwsp}ErrorThresholdPercentage* | Error percentage threshold (as whole number such as 50) at which point the circuit breaker will trip open and reject requests. It will stay tripped for the duration defined in circuitBreakerSleepWindowInMilliseconds; The error percentage this is compared against comes from HystrixCommandMetrics.getHealthCounts(). | | Integer | *camel.hystrix.circuitBreaker{zwsp}ForceClosed* | If true the HystrixCircuitBreaker#allowRequest() will always return true to allow requests regardless of the error percentage from HystrixCommandMetrics.getHealthCounts(). The circuitBreakerForceOpen() property takes precedence so if it set to true this property does nothing. | | Boolean | *camel.hystrix.circuitBreaker{zwsp}ForceOpen* | If true the HystrixCircuitBreaker.allowRequest() will always return false, causing the circuit to be open (tripped) and reject all requests. This property takes precedence over circuitBreakerForceClosed(); | | Boolean | *camel.hystrix.circuitBreaker{zwsp}RequestVolumeThreshold* | Minimum number of requests in the metricsRollingStatisticalWindowInMilliseconds() that must exist before the HystrixCircuitBreaker will trip. If below this number the circuit will not trip regardless of error percentage. | | Integer | *camel.hystrix.circuitBreaker{zwsp}SleepWindowInMilliseconds* | The time in milliseconds after a HystrixCircuitBreaker trips open that it should wait before trying requests again. | | Integer | *camel.hystrix.corePoolSize* | Core thread-pool size that gets passed to java.util.concurrent.ThreadPoolExecutor#setCorePoolSize(int) | | Integer | *camel.hystrix.execution{zwsp}IsolationSemaphoreMax{zwsp}ConcurrentRequests* | Number of concurrent requests permitted to HystrixCommand.run(). Requests beyond the concurrent limit will be rejected. Applicable only when executionIsolationStrategy == SEMAPHORE. | | Integer | *camel.hystrix.execution{zwsp}IsolationStrategy* | What isolation strategy HystrixCommand.run() will be executed with. If THREAD then it will be executed on a separate thread and concurrent requests limited by the number of threads in the thread-pool. If SEMAPHORE then it will be executed on the calling thread and concurrent requests limited by the semaphore count. | | String | *camel.hystrix.execution{zwsp}IsolationThreadInterruptOn{zwsp}Timeout* | Whether the execution thread should attempt an interrupt (using Future#cancel ) when a thread times out. Applicable only when executionIsolationStrategy() == THREAD. | | Boolean | *camel.hystrix.executionTimeout{zwsp}Enabled* | Whether the timeout mechanism is enabled for this command | | Boolean | *camel.hystrix.executionTimeout{zwsp}InMilliseconds* | Time in milliseconds at which point the command will timeout and halt execution. If executionIsolationThreadInterruptOnTimeout == true and the command is thread-isolated, the executing thread will be interrupted. If the command is semaphore-isolated and a HystrixObservableCommand, that command will get unsubscribed. | | Integer | *camel.hystrix.fallbackEnabled* | Whether HystrixCommand.getFallback() should be attempted when failure occurs. | | Boolean | *camel.hystrix.fallback{zwsp}IsolationSemaphoreMax{zwsp}ConcurrentRequests* | Number of concurrent requests permitted to HystrixCommand.getFallback(). Requests beyond the concurrent limit will fail-fast and not attempt retrieving a fallback. | | Integer | *camel.hystrix.groupKey* | Sets the group key to use. The default value is CamelHystrix. | | String | *camel.hystrix.keepAliveTime* | Keep-alive time in minutes that gets passed to ThreadPoolExecutor#setKeepAliveTime(long,TimeUnit) | | Integer | *camel.hystrix.maximumSize* | Maximum thread-pool size that gets passed to ThreadPoolExecutor#setMaximumPoolSize(int) . This is the maximum amount of concurrency that can be supported without starting to reject HystrixCommands. Please note that this setting only takes effect if you also set allowMaximumSizeToDivergeFromCoreSize | | Integer | *camel.hystrix.maxQueueSize* | Max queue size that gets passed to BlockingQueue in HystrixConcurrencyStrategy.getBlockingQueue(int) This should only affect the instantiation of a threadpool - it is not eliglible to change a queue size on the fly. For that, use queueSizeRejectionThreshold(). | | Integer | *camel.hystrix.metricsHealth{zwsp}SnapshotIntervalInMilliseconds* | Time in milliseconds to wait between allowing health snapshots to be taken that calculate success and error percentages and affect HystrixCircuitBreaker.isOpen() status. On high-volume circuits the continual calculation of error percentage can become CPU intensive thus this controls how often it is calculated. | | Integer | *camel.hystrix.metricsRolling{zwsp}PercentileBucketSize* | Maximum number of values stored in each bucket of the rolling percentile. This is passed into HystrixRollingPercentile inside HystrixCommandMetrics. | | Integer | *camel.hystrix.metricsRolling{zwsp}PercentileEnabled* | Whether percentile metrics should be captured using HystrixRollingPercentile inside HystrixCommandMetrics. | | Boolean | *camel.hystrix.metricsRolling{zwsp}PercentileWindowBuckets* | Number of buckets the rolling percentile window is broken into. This is passed into HystrixRollingPercentile inside HystrixCommandMetrics. | | Integer | *camel.hystrix.metricsRolling{zwsp}PercentileWindowInMilliseconds* | Duration of percentile rolling window in milliseconds. This is passed into HystrixRollingPercentile inside HystrixCommandMetrics. | | Integer | *camel.hystrix.metricsRolling{zwsp}StatisticalWindowBuckets* | Number of buckets the rolling statistical window is broken into. This is passed into HystrixRollingNumber inside HystrixCommandMetrics. | | Integer | *camel.hystrix.metricsRolling{zwsp}StatisticalWindowIn{zwsp}Milliseconds* | This property sets the duration of the statistical rolling window, in milliseconds. This is how long metrics are kept for the thread pool. The window is divided into buckets and rolls by those increments. | | Integer | *camel.hystrix.queueSize{zwsp}RejectionThreshold* | Queue size rejection threshold is an artificial max size at which rejections will occur even if maxQueueSize has not been reached. This is done because the maxQueueSize of a BlockingQueue can not be dynamically changed and we want to support dynamically changing the queue size that affects rejections. This is used by HystrixCommand when queuing a thread for execution. | | Integer | *camel.hystrix.requestLog{zwsp}Enabled* | Whether HystrixCommand execution and events should be logged to HystrixRequestLog. | | Boolean | *camel.hystrix.threadPoolKey* | Sets the thread pool key to use. Will by default use the same value as groupKey has been configured to use. | | String | *camel.hystrix.threadPool{zwsp}RollingNumberStatisticalWindow{zwsp}Buckets* | Number of buckets the rolling statistical window is broken into. This is passed into HystrixRollingNumber inside each HystrixThreadPoolMetrics instance. | | Integer | *camel.hystrix.threadPool{zwsp}RollingNumberStatisticalWindow{zwsp}InMilliseconds* | Duration of statistical rolling window in milliseconds. This is passed into HystrixRollingNumber inside each HystrixThreadPoolMetrics instance. | | Integer | *camel.lra.coordinatorContext{zwsp}Path* | The context-path for the LRA coordinator. Is default /lra-coordinator | /lra-coordinator | String | *camel.lra.coordinatorUrl* | The URL for the LRA coordinator service that orchestrates the transactions | | String | *camel.lra.localParticipant{zwsp}ContextPath* | The context-path for the local participant. Is default /lra-participant | /lra-participant | String | *camel.lra.localParticipantUrl* | The URL for the local participant | | String | *camel.resilience4j.automatic{zwsp}TransitionFromOpenToHalfOpen{zwsp}Enabled* | Enables automatic transition from OPEN to HALF_OPEN state once the waitDurationInOpenState has passed. | | Boolean | *camel.resilience4j.bulkhead{zwsp}Enabled* | Whether bulkhead is enabled or not on the circuit breaker. | false | Boolean | *camel.resilience4j.bulkheadMax{zwsp}ConcurrentCalls* | Configures the max amount of concurrent calls the bulkhead will support. | | Integer | *camel.resilience4j.bulkheadMax{zwsp}WaitDuration* | Configures a maximum amount of time which the calling thread will wait to enter the bulkhead. If bulkhead has space available, entry is guaranteed and immediate. If bulkhead is full, calling threads will contest for space, if it becomes available. maxWaitDuration can be set to 0. Note: for threads running on an event-loop or equivalent (rx computation pool, etc), setting maxWaitDuration to 0 is highly recommended. Blocking an event-loop thread will most likely have a negative effect on application throughput. | | Integer | *camel.resilience4j.circuit{zwsp}BreakerRef* | Refers to an existing io.github.resilience4j.circuitbreaker.CircuitBreaker instance to lookup and use from the registry. When using this, then any other circuit breaker options are not in use. | | String | *camel.resilience4j.configRef* | Refers to an existing io.github.resilience4j.circuitbreaker.CircuitBreakerConfig instance to lookup and use from the registry. | | String | *camel.resilience4j.failureRate{zwsp}Threshold* | Configures the failure rate threshold in percentage. If the failure rate is equal or greater than the threshold the CircuitBreaker transitions to open and starts short-circuiting calls. The threshold must be greater than 0 and not greater than 100. Default value is 50 percentage. | 50 | Float | *camel.resilience4j.minimum{zwsp}NumberOfCalls* | Configures configures the minimum number of calls which are required (per sliding window period) before the CircuitBreaker can calculate the error rate. For example, if minimumNumberOfCalls is 10, then at least 10 calls must be recorded, before the failure rate can be calculated. If only 9 calls have been recorded the CircuitBreaker will not transition to open even if all 9 calls have failed. Default minimumNumberOfCalls is 100 | 100 | Integer | *camel.resilience4j.permitted{zwsp}NumberOfCallsInHalfOpenState* | Configures the number of permitted calls when the CircuitBreaker is half open. The size must be greater than 0. Default size is 10. | 10 | Integer | *camel.resilience4j.sliding{zwsp}WindowSize* | Configures the size of the sliding window which is used to record the outcome of calls when the CircuitBreaker is closed. slidingWindowSize configures the size of the sliding window. Sliding window can either be count-based or time-based. If slidingWindowType is COUNT_BASED, the last slidingWindowSize calls are recorded and aggregated. If slidingWindowType is TIME_BASED, the calls of the last slidingWindowSize seconds are recorded and aggregated. The slidingWindowSize must be greater than 0. The minimumNumberOfCalls must be greater than 0. If the slidingWindowType is COUNT_BASED, the minimumNumberOfCalls cannot be greater than slidingWindowSize . If the slidingWindowType is TIME_BASED, you can pick whatever you want. Default slidingWindowSize is 100. | 100 | Integer | *camel.resilience4j.sliding{zwsp}WindowType* | Configures the type of the sliding window which is used to record the outcome of calls when the CircuitBreaker is closed. Sliding window can either be count-based or time-based. If slidingWindowType is COUNT_BASED, the last slidingWindowSize calls are recorded and aggregated. If slidingWindowType is TIME_BASED, the calls of the last slidingWindowSize seconds are recorded and aggregated. Default slidingWindowType is COUNT_BASED. | COUNT_BASED | String | *camel.resilience4j.slowCall{zwsp}DurationThreshold* | Configures the duration threshold (seconds) above which calls are considered as slow and increase the slow calls percentage. Default value is 60 seconds. | 60 | Integer | *camel.resilience4j.slowCall{zwsp}RateThreshold* | Configures a threshold in percentage. The CircuitBreaker considers a call as slow when the call duration is greater than slowCallDurationThreshold(Duration. When the percentage of slow calls is equal or greater the threshold, the CircuitBreaker transitions to open and starts short-circuiting calls. The threshold must be greater than 0 and not greater than 100. Default value is 100 percentage which means that all recorded calls must be slower than slowCallDurationThreshold. | 100 | Float | *camel.resilience4j.timeout{zwsp}CancelRunningFuture* | Configures whether cancel is called on the running future. Defaults to true. | true | Boolean | *camel.resilience4j.timeout{zwsp}Duration* | Configures the thread execution timeout (millis). Default value is 1000 millis (1 second). | 1000 | Integer | *camel.resilience4j.timeout{zwsp}Enabled* | Whether timeout is enabled or not on the circuit breaker. Default is false. | false | Boolean | *camel.resilience4j.timeout{zwsp}ExecutorServiceRef* | References to a custom thread pool to use when timeout is enabled (uses ForkJoinPool#commonPool() by default) | | String | *camel.resilience4j.wait{zwsp}DurationInOpenState* | Configures the wait duration (in seconds) which specifies how long the CircuitBreaker should stay open, before it switches to half open. Default value is 60 seconds. | 60 | Integer | *camel.resilience4j.writable{zwsp}StackTraceEnabled* | Enables writable stack traces. When set to false, Exception.getStackTrace returns a zero length array. This may be used to reduce log spam when the circuit breaker is open as the cause of the exceptions is already known (the circuit breaker is short-circuiting calls). | | Boolean | *camel.rest.apiComponent* | Sets the name of the Camel component to use as the REST API (such as swagger or openapi) | | String | *camel.rest.apiContextIdPattern* | Optional CamelContext id pattern to only allow Rest APIs from rest services within CamelContext's which name matches the pattern. The pattern #name# refers to the CamelContext name, to match on the current CamelContext only. For any other value, the pattern uses the rules from org.apache.camel.support.EndpointHelper#matchPattern(String,String) | | String | *camel.rest.apiContextListing* | Sets whether listing of all available CamelContext's with REST services in the JVM is enabled. If enabled it allows to discover these contexts, if false then only the current CamelContext is in use. | | boolean | *camel.rest.apiContextPath* | Sets a leading API context-path the REST API services will be using. This can be used when using components such as camel-servlet where the deployed web application is deployed using a context-path. | | String | *camel.rest.apiContextRouteId* | Sets the route id to use for the route that services the REST API. The route will by default use an auto assigned route id. | | String | *camel.rest.apiHost* | To use an specific hostname for the API documentation (eg swagger) This can be used to override the generated host with this configured hostname | | String | *camel.rest.apiProperties* | Sets additional options on api level | | Map | *camel.rest.apiVendorExtension* | Whether vendor extension is enabled in the Rest APIs. If enabled then Camel will include additional information as vendor extension (eg keys starting with x-) such as route ids, class names etc. Not all 3rd party API gateways and tools supports vendor-extensions when importing your API docs. | | boolean | *camel.rest.bindingMode* | Sets the binding mode to be used by the REST consumer | RestBindingMode.off | RestBindingMode | *camel.rest.clientRequest{zwsp}Validation* | Whether to enable validation of the client request to check whether the Content-Type and Accept headers from the client is supported by the Rest-DSL configuration of its consumes/produces settings. This can be turned on, to enable this check. In case of validation error, then HTTP Status codes 415 or 406 is returned. The default value is false. | | boolean | *camel.rest.component* | Sets the name of the Camel component to use as the REST consumer | | String | *camel.rest.componentProperties* | Sets additional options on component level | | Map | *camel.rest.consumerProperties* | Sets additional options on consumer level | | Map | *camel.rest.contextPath* | Sets a leading context-path the REST services will be using. This can be used when using components such as camel-servlet where the deployed web application is deployed using a context-path. Or for components such as camel-jetty or camel-netty-http that includes a HTTP server. | | String | *camel.rest.corsHeaders* | Sets the CORS headers to use if CORS has been enabled. | | Map | *camel.rest.dataFormat{zwsp}Properties* | Sets additional options on data format level | | Map | *camel.rest.enableCORS* | To specify whether to enable CORS which means Camel will automatic include CORS in the HTTP headers in the response. This option is default false | | boolean | *camel.rest.endpointProperties* | Sets additional options on endpoint level | | Map | *camel.rest.host* | Sets the hostname to use by the REST consumer | | String | *camel.rest.hostNameResolver* | Sets the resolver to use for resolving hostname | RestHostNameResolver.allLocalIp | RestHostNameResolver | *camel.rest.jsonDataFormat* | Sets a custom json data format to be used Important: This option is only for setting a custom name of the data format, not to refer to an existing data format instance. | | String | *camel.rest.port* | Sets the port to use by the REST consumer | | int | *camel.rest.producerApiDoc* | Sets the location of the api document (swagger api) the REST producer will use to validate the REST uri and query parameters are valid accordingly to the api document. This requires adding camel-swagger-java to the classpath, and any miss configuration will let Camel fail on startup and report the error(s). The location of the api document is loaded from classpath by default, but you can use file: or http: to refer to resources to load from file or http url. | | String | *camel.rest.producerComponent* | Sets the name of the Camel component to use as the REST producer | | String | *camel.rest.scheme* | Sets the scheme to use by the REST consumer | | String | *camel.rest.skipBindingOnError{zwsp}Code* | Whether to skip binding output if there is a custom HTTP error code, and instead use the response body as-is. This option is default true. | true | boolean | *camel.rest.useXForwardHeaders* | WWhether to use X-Forward headers to set host etc. for Swagger. This option is default true. | true | boolean | *camel.rest.xmlDataFormat* | Sets a custom xml data format to be used. Important: This option is only for setting a custom name of the data format, not to refer to an existing data format instance. | | String | *camel.threadpool.allowCore{zwsp}ThreadTimeOut* | Sets default whether to allow core threads to timeout | | Boolean | *camel.threadpool.config* | Adds a configuration for a specific thread pool profile (inherits default values) | | Map | *camel.threadpool.keepAliveTime* | Sets the default keep alive time for inactive threads | | Long | *camel.threadpool.maxPoolSize* | Sets the default maximum pool size | | Integer | *camel.threadpool.maxQueueSize* | Sets the default maximum number of tasks in the work queue. Use -1 or an unbounded queue | | Integer | *camel.threadpool.poolSize* | Sets the default core pool size (threads to keep minimum in pool) | | Integer | *camel.threadpool.rejected{zwsp}Policy* | Sets the default handler for tasks which cannot be executed by the thread pool. | | ThreadPoolRejectedPolicy | *camel.threadpool.timeUnit* | Sets the default time unit used for keep alive time | | TimeUnit |=== // main options: END == Specifying custom beans Custom beans can be configured in `camel-main` via properties (such as in the `application.properties` file). For example to create a `DataSource` for a Postgress database, you can create a new bean instance via `#class:` with the class name (fully qualified). Properties on the data source can then additional configured such as the server and database name, etc. [source,properties] ---- camel.beans.myDS = #class:org.postgresql.jdbc3.Jdbc3PoolingDataSource camel.beans.myDS.dataSourceName = myDS camel.beans.myDS.serverName = mypostrgress camel.beans.myDS.databaseName = test camel.beans.myDS.user = testuser camel.beans.myDS.password = testpassword camel.beans.myDS.maxConnections = 10 ---- The bean is registered in the Camel Registry with the name `myDS`. If you use the SQL component then the datasource can be configured on the SQL component: [source,properties] ---- camel.component.sql.dataSource = #myDS ---- To refer to a custom bean you may want to favour using `#bean:` style, as this states the intention more clearly that its referring to a bean, and not just a text value that happens to start with a `#` sign: [source,properties] ---- camel.component.sql.dataSource = #bean:myDS ---- === Creating a custom bean with constructor parameters When creating a bean then parameters to the constructor can be provided. Suppose we have a class `MyFoo` with a constructor: [source,java] ---- public class MyFoo { private String name; private boolean important; private int id; public MyFoo(String name, boolean important, int id) { this.name = name; this.important = important; this.id = id; } } ---- Then we can create a bean instance with name `foo` and provide parameters to the constructor as shown: [source,properties] ---- camel.beans.foo = #class:com.foo.MyBean(""Hello World"", true, 123) ---- === Optional parameters on beans If a parameter on a bean is not mandatory then the parameter can be marked as optional using `?` syntax, as shown: [source,properties] ---- camel.beans.foo = #class:com.foo.MyBean(""Hello World"", true, 123) camel.beans.foo.?company = Acme ---- Then the company parameter is only set if `MyBean` has this option (silent ignore if no option present). Otherwise if a parameter is set and the bean does not have such a parameter, then an exception is thrown by Camel. === Nested parameters on beans You can configure nested parameters separating them via `.` (dot). For example given this `Country` class: [source,java] ---- public class Country { private String iso; private String name; public void setIso(String iso) { this.iso = iso; } public void setName(String name) { this.name = name; } } ---- Which is an option on the `MyBean` class. Then we can then configure its iso and name parameter as shown below: [source,properties] ---- camel.beans.foo = #class:com.foo.MyBean(""Hello World"", true, 123) camel.beans.foo.country.iso = USA camel.beans.foo.country.name = United States of America ---- Camel will automatic create an instance of `Country` if `MyBean` has a getter/setter for this option, and that the `Country` bean has a default no-arg constructor. === Configuring singleton beans by their type In the example above the SQL component was configured with the name of the `DataSource`. There can be situations where you know there is only a single instance of a data source in the Camel registry. In such a situation you can instead refer to the class or interface type via the `#type:` prefix as shown below: [source,properties] ---- camel.component.sql.dataSource = #type:javax.sql.DataSource ---- If there is no bean in the registry with the type `javax.sql.DataSource` then the option isn't configured. === Autowiring beans The example above can be taken one step further by letting `camel-main` try to autowire the beans. [source,properties] ---- camel.component.sql.dataSource = #autowired ---- In this situation then `#autowrired` will make Camel detect the type of the `dataSource` option on the `SQL` component. As the type is a `javax.sql.DataSource` instance, then Camel will lookup in the registry if there is a single instance of the same type. If there is no such bean then the option isn't configured. == Defining a Map bean You can specify `java.util.Map` beans in `camel-main` via properties (such as in the `application.properties` file). Maps have a special syntax with brackets as shown below: [source,properties] ---- camel.beans.mymap[table] = 12 camel.beans.mymap[food] = Big Burger camel.beans.mymap[cheese] = yes camel.beans.mymap[quantity] = 1 ---- The Map is registered in the Camel Registry with the name `mymap`. == Defining a List bean This is similar to Map bean where the key is the index, eg 0, 1, 2, etc: [source,properties] ---- camel.beans.myprojects[0] = Camel camel.beans.myprojects[1] = Kafka camel.beans.myprojects[2] = Quarkus ---- The List is registered in the Camel Registry with the name `myprojects`. == Examples You can find a set of examples using `camel-main` in https://github.com/apache/camel-examples[Camel Examples] which demonstrate running Camel in standalone with `camel-main`. ",12490,False,2179.18881985775,median "class ZCL_MOCKUP_LOADER_STUB_FACTORY definition public create public . public section. methods constructor importing !i_interface_name type seoclsname !ii_ml_instance type ref to zif_mockup_loader !io_proxy_target type ref to object optional !i_allow_overrides type abap_bool default abap_false raising zcx_mockup_loader_error . methods connect_method importing !i_method_name type abap_methname !i_mock_name type string optional !i_load_strict type abap_bool default abap_false !i_corresponding type abap_bool default abap_false !i_sift_param type string optional !i_sift_const type string optional !i_mock_tab_key type abap_compname optional !i_field_only type abap_parmname optional !i_output_param type abap_parmname optional !i_const_value type string optional !i_deep type abap_bool default abap_false !i_filter type zif_mockup_loader=>tty_stub_filter_params optional returning value(r_instance) type ref to zcl_mockup_loader_stub_factory raising zcx_mockup_loader_error . methods forward_method importing !i_method_name type abap_methname returning value(r_instance) type ref to zcl_mockup_loader_stub_factory raising zcx_mockup_loader_error . methods connect importing i_connect_string type string returning value(r_instance) type ref to zcl_mockup_loader_stub_factory raising zcx_mockup_loader_error . methods generate_stub returning value(r_stub) type ref to object . protected section. data mv_interface_name type seoclsname . data mt_config type zif_mockup_loader=>tt_mock_config . data mi_ml type ref to zif_mockup_loader . data md_if_desc type ref to cl_abap_objectdescr . data mo_proxy_target type ref to object . data mv_allow_overrides type abap_bool. class-methods build_config importing !id_if_desc type ref to cl_abap_objectdescr !i_config type zif_mockup_loader=>ty_mock_config returning value(r_config) type zif_mockup_loader=>ty_mock_config raising zcx_mockup_loader_error . private section. types: begin of ty_filter_type, mock_tab_key type abap_compname, type type ref to cl_abap_typedescr, end of ty_filter_type, tty_filter_types type standard table of ty_filter_type with key mock_tab_key. data mt_src type string_table. methods _src importing iv_src_line type string. methods handle_duplicates importing is_config like line of mt_config raising zcx_mockup_loader_error . class-methods validate_sift_and_get_type importing id_if_desc type ref to cl_abap_objectdescr iv_method_name type abap_methname iv_param_name type string returning value(rd_sift_type) type ref to cl_abap_typedescr raising zcx_mockup_loader_error . class-methods validate_connect_and_get_types importing id_if_desc type ref to cl_abap_objectdescr i_config type zif_mockup_loader=>ty_mock_config exporting et_sift_types type tty_filter_types ed_output_type type ref to cl_abap_typedescr es_output_param type abap_parmdescr raising zcx_mockup_loader_error . class-methods validate_method_and_get_otype importing id_if_desc type ref to cl_abap_objectdescr i_config type zif_mockup_loader=>ty_mock_config i_method type abap_methdescr exporting ed_output_type type ref to cl_abap_typedescr es_output_param type abap_parmdescr raising zcx_mockup_loader_error . class-methods validate_filter_and_get_ftype importing id_if_desc type ref to cl_abap_objectdescr i_config type zif_mockup_loader=>ty_mock_config returning value(rt_sift_types) type tty_filter_types raising zcx_mockup_loader_error . class-methods build_field_only_struc_type importing i_config type zif_mockup_loader=>ty_mock_config id_output_type type ref to cl_abap_typedescr it_sift_types type tty_filter_types returning value(rd_type) type ref to cl_abap_structdescr. class-methods parse_connect_string importing i_connect_string type string returning value(rs_parsed) type zif_mockup_loader=>ty_mock_config raising zcx_mockup_loader_error . class-methods parse_filter_item importing i_filter type string returning value(rs_filter_param) type zif_mockup_loader=>ty_stub_filter_param raising zcx_mockup_loader_error . ENDCLASS. CLASS ZCL_MOCKUP_LOADER_STUB_FACTORY IMPLEMENTATION. method build_config. data ld_output_type type ref to cl_abap_typedescr. data ls_output_param type abap_parmdescr. data lt_sift_types type tty_filter_types. "" TODO: unify filters: merge single filter params into filter tab validate_connect_and_get_types( exporting i_config = i_config id_if_desc = id_if_desc importing et_sift_types = lt_sift_types es_output_param = ls_output_param ed_output_type = ld_output_type ). r_config = i_config. r_config-output_param = ls_output_param-name. r_config-output_pkind = ls_output_param-parm_kind. if i_config-field_only is not initial. r_config-output_type ?= build_field_only_struc_type( id_output_type = ld_output_type it_sift_types = lt_sift_types i_config = r_config ). else. r_config-output_type ?= ld_output_type. endif. endmethod. method build_field_only_struc_type. data lt_components type cl_abap_structdescr=>component_table. field-symbols like line of lt_components. append initial line to lt_components assigning . -name = i_config-field_only. -type ?= id_output_type. field-symbols like line of it_sift_types. loop at it_sift_types assigning . append initial line to lt_components assigning . -name = -mock_tab_key. -type ?= -type. endloop. rd_type = cl_abap_structdescr=>get( lt_components ). endmethod. method connect. data ls_params type zif_mockup_loader=>ty_mock_config. ls_params = parse_connect_string( i_connect_string ). if ls_params-mock_name = '*'. "" Proxy forward_method( i_method_name = ls_params-method_name ). else. connect_method( i_sift_param = ls_params-sift_param i_mock_tab_key = ls_params-mock_tab_key i_field_only = ls_params-field_only i_method_name = ls_params-method_name i_corresponding = ls_params-corresponding i_const_value = ls_params-const_value i_mock_name = ls_params-mock_name i_filter = ls_params-filter ). endif. endmethod. method connect_method. data ls_config like line of mt_config. ls_config-method_name = to_upper( i_method_name ). ls_config-mock_name = i_mock_name. ls_config-load_strict = i_load_strict. ls_config-corresponding = i_corresponding. ls_config-sift_param = to_upper( i_sift_param ). ls_config-sift_const = i_sift_const. ls_config-mock_tab_key = to_upper( i_mock_tab_key ). ls_config-output_param = to_upper( i_output_param ). ls_config-field_only = to_upper( i_field_only ). ls_config-const_value = i_const_value. ls_config-deep = i_deep. ls_config-filter = i_filter. field-symbols like line of ls_config-filter. loop at ls_config-filter assigning . -mock_tab_key = to_upper( -mock_tab_key ). -sift_param = to_upper( -sift_param ). endloop. handle_duplicates( ls_config ). "" Validate and save config ls_config = build_config( id_if_desc = md_if_desc i_config = ls_config ). append ls_config to mt_config. r_instance = me. endmethod. method constructor. data ld_desc type ref to cl_abap_typedescr. ld_desc = cl_abap_typedescr=>describe_by_name( i_interface_name ). if ld_desc->kind <> cl_abap_typedescr=>kind_intf. zcx_mockup_loader_error=>raise( msg = |{ i_interface_name } is not interface| code = 'IF' ). ""#EC NOTEXT endif. me->md_if_desc ?= ld_desc. me->mi_ml = ii_ml_instance. me->mv_interface_name = i_interface_name. me->mo_proxy_target = io_proxy_target. me->mv_allow_overrides = i_allow_overrides. if io_proxy_target is bound. data ld_obj type ref to cl_abap_objectdescr. ld_obj ?= cl_abap_typedescr=>describe_by_object_ref( io_proxy_target ). read table ld_obj->interfaces transporting no fields with key name = i_interface_name. if sy-subrc is not initial. zcx_mockup_loader_error=>raise( msg = |io_proxy_target does not implement { i_interface_name } interface| code = 'II' ). ""#EC NOTEXT endif. endif. endmethod. method forward_method. if mo_proxy_target is initial. zcx_mockup_loader_error=>raise( msg = |Proxy target was not specified during instantiation| code = 'PA' ). ""#EC NOTEXT endif. data ls_config like line of mt_config. ls_config-method_name = to_upper( i_method_name ). ls_config-as_proxy = abap_true. read table md_if_desc->methods transporting no fields with key name = ls_config-method_name. if sy-subrc is not initial. zcx_mockup_loader_error=>raise( msg = |Method { ls_config-method_name } not found| code = 'MF' ). ""#EC NOTEXT endif. handle_duplicates( ls_config ). append ls_config to mt_config. r_instance = me. endmethod. method generate_stub. data: lv_message type string, l_prog_name type string, l_class_name type string. field-symbols like line of md_if_desc->methods. field-symbols like line of mt_config. clear mt_src. _src( 'program.' ). ""#EC NOTEXT _src( 'class lcl_mockup_loader_stub definition final' ). ""#EC NOTEXT _src( ' inheriting from zcl_mockup_loader_stub_base.' ). ""#EC NOTEXT _src( ' public section.' ). ""#EC NOTEXT _src( | interfaces { mv_interface_name }.| ). ""#EC NOTEXT _src( 'endclass.' ). ""#EC NOTEXT _src( 'class lcl_mockup_loader_stub implementation.' ). ""#EC NOTEXT loop at md_if_desc->methods assigning . unassign . read table mt_config assigning with key method_name = -name. _src( | method { mv_interface_name }~{ -name }.| ). _src( | if is_disabled( '{ -name }' ) = abap_true.| ). ""#EC NOTEXT if is assigned and -output_param is not initial. _src( | clear { -output_param }.| ). ""#EC NOTEXT endif. _src( ' return.' ). ""#EC NOTEXT _src( ' endif.' ). ""#EC NOTEXT _src( | increment_call_count( '{ -name }' ).| ). ""#EC NOTEXT if is assigned. if -as_proxy = abap_true. field-symbols like line of -parameters. data l_param_kind like -parm_kind. _src( ' data lt_params type abap_parmbind_tab.' ). ""#EC NOTEXT _src( ' data ls_param like line of lt_params.' ). ""#EC NOTEXT loop at -parameters assigning . l_param_kind = -parm_kind. translate l_param_kind using 'IEEICCRR'. "" Importing -> exporting, etc _src( | ls_param-name = '{ -name }'.| ) ##NO_TEXT. _src( | ls_param-kind = '{ l_param_kind }'.| ) ##NO_TEXT. _src( | get reference of { -name } into ls_param-value.| ) ##NO_TEXT. _src( ' insert ls_param into table lt_params.' ). ""#EC NOTEXT endloop. _src( | call method mo_proxy_target->('{ mv_interface_name }~{ -name }')| ). ""#EC NOTEXT _src( | parameter-table lt_params.| ). ""#EC NOTEXT elseif -const_value is not initial. _src( | { -output_param } = '{ -const_value }'.| ) ##NO_TEXT. else. if -filter is not initial. _src( ' data lt_sift_values type zif_mockup_loader=>tty_stub_sift_values.' ) ##NO_TEXT. _src( ' data lr_sift_val type ref to data.' ) ##NO_TEXT. field-symbols like line of -filter. loop at -filter assigning where sift_param is not initial. _src( | get reference of { -sift_param } into lr_sift_val.| ) ##NO_TEXT. _src( | append lr_sift_val to lt_sift_values.| ) ##NO_TEXT. endloop. endif. _src( ' data lr_data type ref to data.' ). ""#EC NOTEXT _src( ' lr_data = get_mock_data(' ). ""#EC NOTEXT if -sift_param is not initial. _src( | i_sift_value = { -sift_param }| ) ##NO_TEXT. elseif -filter is not initial. _src( ' i_sift_value = lt_sift_values' ) ##NO_TEXT. endif. _src( | i_method_name = '{ -name }' ).| ) ##NO_TEXT. _src( ' field-symbols type any.' ). ""#EC NOTEXT _src( ' assign lr_data->* to .' ). ""#EC NOTEXT _src( | { -output_param } = .| ) ##NO_TEXT. endif. endif. _src( ' endmethod.' ). ""#EC NOTEXT endloop. _src( 'endclass.' ). ""#EC NOTEXT generate subroutine pool mt_src name l_prog_name message lv_message. ""#EC CI_GENERATE l_class_name = |\\\\PROGRAM={ l_prog_name }\\\\CLASS=LCL_MOCKUP_LOADER_STUB|. create object r_stub type (l_class_name) exporting it_config = mt_config io_proxy_target = mo_proxy_target ii_ml = mi_ml. endmethod. method handle_duplicates. read table mt_config with key method_name = is_config-method_name transporting no fields. if sy-subrc = 0. "" already connected if mv_allow_overrides = abap_true. delete mt_config index sy-tabix. else. zcx_mockup_loader_error=>raise( msg = |Method { is_config-method_name } is already connected| code = 'MC' ). ""#EC NOTEXT endif. endif. endmethod. method parse_connect_string. "" for mock `METHOD -> file` "" for mock w/params `METHOD -> file [param = key]` "" for mock w/params `METHOD -> file [param = key, param2 = key2]` "" for mock w/params `METHOD -> file [param = ""const""]` "" for proxy `METHOD -> *` "" for corresponding `METHOD -> ~file` "" for single field `METHOD -> file(field_name)` "" for fixed value `METHOD -> =value` "" for deep `METHOD -> :deep:value` "" TODO 'directives' - :xxx: data l_pair type string. data l_filter type string. data lv_len type i. "" Pair and filter ====================================== split i_connect_string at '[' into l_pair l_filter. if l_filter is not initial. lv_len = strlen( l_filter ). if substring( val = l_filter off = lv_len - 1 ) <> ']'. zcx_mockup_loader_error=>raise( msg = 'incorrect connect string format' code = 'SF' ). endif. l_filter = substring( val = l_filter len = lv_len - 1 ). endif. "" Method and mock target =============================== split l_pair at '->' into rs_parsed-method_name rs_parsed-mock_name. "" Field only split rs_parsed-mock_name at '(' into rs_parsed-mock_name rs_parsed-field_only. if rs_parsed-field_only is not initial. lv_len = strlen( rs_parsed-field_only ). if substring( val = rs_parsed-field_only off = lv_len - 1 ) <> ')'. zcx_mockup_loader_error=>raise( msg = 'incorrect connect string format' code = 'SF' ). endif. rs_parsed-field_only = substring( val = rs_parsed-field_only len = lv_len - 1 ). endif. condense rs_parsed-method_name. condense rs_parsed-mock_name. "" Corresponding if rs_parsed-mock_name cp '*/~*'. rs_parsed-mock_name = replace( val = rs_parsed-mock_name sub = '/~' with = '/' ). rs_parsed-corresponding = abap_true. elseif rs_parsed-mock_name cp '~*'. rs_parsed-mock_name = replace( val = rs_parsed-mock_name sub = '~' with = '' ). rs_parsed-corresponding = abap_true. elseif rs_parsed-mock_name+0(1) = '='. rs_parsed-const_value = rs_parsed-mock_name. clear rs_parsed-mock_name. shift rs_parsed-const_value left by 1 places. condense rs_parsed-const_value. endif. "" Deep if rs_parsed-mock_name cp ':deep:*'. rs_parsed-mock_name = replace( val = rs_parsed-mock_name sub = ':deep:' with = '' ). rs_parsed-deep = abap_true. condense rs_parsed-mock_name. endif. "" Filter ======================================== data ls_filter_param type zif_mockup_loader=>ty_stub_filter_param. "" detect multi filter find first occurrence of ',' in l_filter. if sy-subrc = 0. data lt_filter_items type string_table. split l_filter at ',' into table lt_filter_items. loop at lt_filter_items into l_filter. ls_filter_param = parse_filter_item( l_filter ). append ls_filter_param to rs_parsed-filter. endloop. else. ls_filter_param = parse_filter_item( l_filter ). move-corresponding ls_filter_param to rs_parsed. endif. endmethod. method parse_filter_item. data lv_len type i. split i_filter at '=' into rs_filter_param-mock_tab_key rs_filter_param-sift_param. condense rs_filter_param-sift_param. if rs_filter_param-sift_param is not initial and rs_filter_param-sift_param+0(1) = '""'. lv_len = strlen( rs_filter_param-sift_param ). if substring( val = rs_filter_param-sift_param off = lv_len - 1 ) <> '""'. zcx_mockup_loader_error=>raise( msg = 'incorrect connect string format' code = 'SF' ). endif. rs_filter_param-sift_const = substring( val = rs_filter_param-sift_param len = lv_len - 2 off = 1 ). clear rs_filter_param-sift_param. endif. condense rs_filter_param-sift_const. condense rs_filter_param-mock_tab_key. endmethod. method validate_connect_and_get_types. "" Config basic checks if i_config-method_name is initial. zcx_mockup_loader_error=>raise( msg = 'Specify method_name' code = 'MM' ). ""#EC NOTEXT elseif i_config-mock_name is initial and i_config-const_value is initial. zcx_mockup_loader_error=>raise( msg = 'Specify mock_name' code = 'MK' ). ""#EC NOTEXT elseif i_config-mock_name is not initial and i_config-const_value is not initial. zcx_mockup_loader_error=>raise( msg = 'Either mock or const value is allowed' code = 'CV' ). ""#EC NOTEXT elseif i_config-corresponding = abap_true and i_config-field_only is not initial. zcx_mockup_loader_error=>raise( msg = 'Cannot combine field_only and corresponding' code = 'PC' ). ""#EC NOTEXT endif. "" find method, check if exists field-symbols like line of id_if_desc->methods. read table id_if_desc->methods assigning with key name = i_config-method_name. if is not assigned. zcx_mockup_loader_error=>raise( msg = |Method { i_config-method_name } not found| code = 'MF' ). ""#EC NOTEXT endif. validate_method_and_get_otype( exporting id_if_desc = id_if_desc i_config = i_config i_method = importing ed_output_type = ed_output_type es_output_param = es_output_param ). et_sift_types = validate_filter_and_get_ftype( id_if_desc = id_if_desc i_config = i_config ). endmethod. method validate_filter_and_get_ftype. "" Normalize filters data data lt_filter like i_config-filter. field-symbols like line of lt_filter. append initial line to lt_filter assigning . move-corresponding i_config to . "" key, param, const if is initial and i_config-filter is initial. return. endif. if is not initial and i_config-filter is not initial. zcx_mockup_loader_error=>raise( msg = 'Cannot specify single and multi filter at the same time' code = 'BF' ). ""#EC NOTEXT endif. if is initial. lt_filter = i_config-filter. endif. "" Get filter types loop at lt_filter assigning . "" check filters if boolc( -sift_param is initial and -sift_const is initial ) <> boolc( -mock_tab_key is initial ). "" XOR zcx_mockup_loader_error=>raise( msg = 'Specify both sift_param/const and mock_tab_key' code = 'MS' ). ""#EC NOTEXT elseif -sift_param is not initial and -sift_const is not initial. zcx_mockup_loader_error=>raise( msg = 'Cannot combine sift_param and sift_const' code = 'CS' ). ""#EC NOTEXT endif. "" duplication check read table rt_sift_types transporting no fields with key mock_tab_key = -mock_tab_key. if sy-subrc = 0. zcx_mockup_loader_error=>raise( msg = |Filter duplication for field { -mock_tab_key }| code = 'DF' ). ""#EC NOTEXT endif. "" get types data ls_filter_type like line of rt_sift_types. if -sift_param is not initial. ls_filter_type-type = validate_sift_and_get_type( id_if_desc = id_if_desc iv_method_name = i_config-method_name iv_param_name = -sift_param ). else. ls_filter_type-type = cl_abap_typedescr=>describe_by_name( 'STRING' ). endif. ls_filter_type-mock_tab_key = -mock_tab_key. append ls_filter_type to rt_sift_types. endloop. endmethod. method validate_method_and_get_otype. "" Check output param if i_config-output_param is initial. read table i_method-parameters with key parm_kind = 'R' into es_output_param. "" returning if sy-subrc is not initial. zcx_mockup_loader_error=>raise( msg = 'Method has no returning params and output_param was not specified' code = 'MR' ). ""#EC NOTEXT endif. else. read table i_method-parameters with key name = i_config-output_param into es_output_param. if sy-subrc is not initial. zcx_mockup_loader_error=>raise( msg = |Param { i_config-output_param } not found| code = 'PF' ). ""#EC NOTEXT endif. endif. if es_output_param-parm_kind = 'I'. zcx_mockup_loader_error=>raise( msg = |Param { i_config-output_param } is importing| code = 'PI' ). ""#EC NOTEXT endif. ed_output_type = id_if_desc->get_method_parameter_type( p_method_name = i_method-name p_parameter_name = es_output_param-name ). if i_config-field_only is not initial. if ed_output_type->kind <> cl_abap_typedescr=>kind_elem. "" Elementary zcx_mockup_loader_error=>raise( msg = |Field only param { es_output_param-name } must be elementary| code = 'PL' ). ""#EC NOTEXT endif. elseif i_config-const_value is not initial. if ed_output_type->kind <> cl_abap_typedescr=>kind_elem. "" Elementary zcx_mockup_loader_error=>raise( msg = |Const value result { es_output_param-name } must be elementary| code = 'CE' ). ""#EC NOTEXT endif. else. if not ed_output_type->kind co 'ST'. "" Table or structure zcx_mockup_loader_error=>raise( msg = |Param { es_output_param-name } must be table or structure| code = 'PT' ). ""#EC NOTEXT endif. endif. endmethod. method validate_sift_and_get_type. data ld_type type ref to cl_abap_typedescr. data ld_struc type ref to cl_abap_structdescr. data lv_part1 type abap_parmname. data lv_part2 type abap_parmname. data lv_final_param type abap_parmname. split iv_param_name at '-' into lv_part1 lv_part2. id_if_desc->get_method_parameter_type( exporting p_method_name = iv_method_name p_parameter_name = lv_part1 receiving p_descr_ref = ld_type exceptions parameter_not_found = 1 ). if sy-subrc = 1. zcx_mockup_loader_error=>raise( msg = |Param { lv_part1 } not found| code = 'PF' ). ""#EC NOTEXT endif. if lv_part2 is initial. "" elementary param lv_final_param = lv_part1. else. "" structured param if ld_type->kind <> cl_abap_typedescr=>kind_struct. "" TODO class ref ? zcx_mockup_loader_error=>raise( msg = |Param { lv_part1 } must be a structure| code = 'PE' ). ""#EC NOTEXT endif. ld_struc ?= ld_type. ld_struc->get_component_type( exporting p_name = lv_part2 receiving p_descr_ref = ld_type exceptions component_not_found = 1 ). if sy-subrc = 1. zcx_mockup_loader_error=>raise( msg = |Param { lv_part2 } not found| code = 'PF' ). ""#EC NOTEXT endif. lv_final_param = lv_part2. endif. if ld_type->kind <> cl_abap_typedescr=>kind_elem. if ld_type->kind = cl_abap_typedescr=>kind_table. if zcl_mockup_loader_utils=>is_range( ld_type ) = abap_false. zcx_mockup_loader_error=>raise( msg = |Param { lv_final_param } must be elementary or range| code = 'PE' ). ""#EC NOTEXT endif. data ld_table type ref to cl_abap_tabledescr. ld_table ?= ld_type. ld_struc ?= ld_table->get_table_line_type( ). ld_type = ld_struc->get_component_type( 'LOW' ). else. zcx_mockup_loader_error=>raise( msg = |Param { lv_final_param } must be elementary or range| code = 'PE' ). ""#EC NOTEXT endif. endif. rd_sift_type = ld_type. endmethod. method _src. append iv_src_line to mt_src. "" just to improve readability and linting endmethod. ENDCLASS. ",6794,False,1333.663085988611,median "[[FTPComponent]] FTP/SFTP/FTPS Component ~~~~~~~~~~~~~~~~~~~~~~~ This component provides access to remote file systems over the FTP and SFTP protocols. Maven users will need to add the following dependency to their `pom.xml` for this component: [source,xml] ----------------------------------------------------------------------- org.apache.camel camel-ftp x.x.xSee the documentation of the Apache Commons ----------------------------------------------------------------------- [Info] ==== More options See link:file2.html[File] for more options as all the options from link:file2.html[File] is inherited. ==== [Info] ==== Absolute paths Absolute path is *not* supported. *Camel 2.16* will translate absolute path to relative by trimming all leading slashes from `directoryname`. There'll be WARN message printed in the logs. ==== [Tip] ==== Consuming from remote FTP server Make sure you read the section titled _Default when consuming files_ further below for details related to consuming files. ==== [[FTP2-URIformat]] URI format ^^^^^^^^^^ [source,java] --------------------------------------------------------- ftp://[username@]hostname[:port]/directoryname[?options] sftp://[username@]hostname[:port]/directoryname[?options] ftps://[username@]hostname[:port]/directoryname[?options] --------------------------------------------------------- Where *directoryname* represents the underlying directory. The directory name is a relative path. Absolute path's is *not* supported. The relative path can contain nested folders, such as /inbox/us. For Camel versions before *Camel 2.16*, the directoryName *must* exist already as this component does not support the `autoCreate` option (which the file component does). The reason is that its the FTP administrator (FTP server) task to properly setup user accounts, and home directories with the right file permissions etc. For *Camel 2.16*, `autoCreate` option is supported. When consumer starts, before polling is scheduled, there's additional FTP operation performed to create the directory configured for endpoint. The default value for `autoCreate` is `true`. If no *username* is provided, then `anonymous` login is attempted using no password. + If no *port* number is provided, Camel will provide default values according to the protocol (ftp = 21, sftp = 22, ftps = 2222). You can append query options to the URI in the following format, `?option=value&option=value&...` This component uses two different libraries for the actual FTP work. FTP and FTPS uses http://commons.apache.org/net/[Apache Commons Net] while SFTP uses http://www.jcraft.com/jsch/[JCraft JSCH]. The FTPS component is only available in Camel 2.2 or newer. + FTPS (also known as FTP Secure) is an extension to FTP that adds support for the Transport Layer Security (TLS) and the Secure Sockets Layer (SSL) cryptographic protocols. [[FTP2-URIOptions]] URI Options ^^^^^^^^^^^ The options below are exclusive for the FTP component. [Info] ==== More options See link:file2.html[File] for more options as all the options from link:file2.html[File] is inherited. ==== // component options: START The FTP component has no options. // component options: END // endpoint options: START The FTP component supports 105 endpoint options which are listed below: {% raw %} [width=""100%"",cols=""2,1,1m,1m,5"",options=""header""] |======================================================================= | Name | Group | Default | Java Type | Description | host | common | | String | *Required* Hostname of the FTP server | port | common | | int | Port of the FTP server | directoryName | common | | String | The starting directory | binary | common | false | boolean | Specifies the file transfer mode BINARY or ASCII. Default is ASCII (false). | charset | common | | String | This option is used to specify the encoding of the file. You can use this on the consumer to specify the encodings of the files which allow Camel to know the charset it should load the file content in case the file content is being accessed. Likewise when writing a file you can use this option to specify which charset to write the file as well. | disconnect | common | false | boolean | Whether or not to disconnect from remote FTP server right after use. Disconnect will only disconnect the current connection to the FTP server. If you have a consumer which you want to stop then you need to stop the consumer/route instead. | doneFileName | common | | String | Producer: If provided then Camel will write a 2nd done file when the original file has been written. The done file will be empty. This option configures what file name to use. Either you can specify a fixed name. Or you can use dynamic placeholders. The done file will always be written in the same folder as the original file. Consumer: If provided Camel will only consume files if a done file exists. This option configures what file name to use. Either you can specify a fixed name. Or you can use dynamic placeholders.The done file is always expected in the same folder as the original file. Only $file.name and $file.name.noext is supported as dynamic placeholders. | fileName | common | | String | Use Expression such as File Language to dynamically set the filename. For consumers it's used as a filename filter. For producers it's used to evaluate the filename to write. If an expression is set it take precedence over the CamelFileName header. (Note: The header itself can also be an Expression). The expression options support both String and Expression types. If the expression is a String type it is always evaluated using the File Language. If the expression is an Expression type the specified Expression type is used - this allows you for instance to use OGNL expressions. For the consumer you can use it to filter filenames so you can for instance consume today's file using the File Language syntax: mydata-$date:now:yyyyMMdd.txt. The producers support the CamelOverruleFileName header which takes precedence over any existing CamelFileName header; the CamelOverruleFileName is a header that is used only once and makes it easier as this avoids to temporary store CamelFileName and have to restore it afterwards. | passiveMode | common | false | boolean | Sets passive mode connections. Default is active mode connections. | separator | common | UNIX | PathSeparator | Sets the path separator to be used. UNIX = Uses unix style path separator Windows = Uses windows style path separator Auto = (is default) Use existing path separator in file name | fastExistsCheck | common (advanced) | false | boolean | If set this option to be true camel-ftp will use the list file directly to check if the file exists. Since some FTP server may not support to list the file directly if the option is false camel-ftp will use the old way to list the directory and check if the file exists. This option also influences readLock=changed to control whether it performs a fast check to update file information or not. This can be used to speed up the process if the FTP server has a lot of files. | bridgeErrorHandler | consumer | false | boolean | Allows for bridging the consumer to the Camel routing Error Handler which mean any exceptions occurred while the consumer is trying to pickup incoming messages or the likes will now be processed as a message and handled by the routing Error Handler. By default the consumer will use the org.apache.camel.spi.ExceptionHandler to deal with exceptions that will be logged at WARN/ERROR level and ignored. | delete | consumer | false | boolean | If true the file will be deleted after it is processed successfully. | moveFailed | consumer | | String | Sets the move failure expression based on Simple language. For example to move files into a .error subdirectory use: .error. Note: When moving the files to the fail location Camel will handle the error and will not pick up the file again. | noop | consumer | false | boolean | If true the file is not moved or deleted in any way. This option is good for readonly data or for ETL type requirements. If noop=true Camel will set idempotent=true as well to avoid consuming the same files over and over again. | preMove | consumer | | String | Expression (such as File Language) used to dynamically set the filename when moving it before processing. For example to move in-progress files into the order directory set this value to order. | recursive | consumer | false | boolean | If a directory will look for files in all the sub-directories as well. | sendEmptyMessageWhenIdle | consumer | false | boolean | If the polling consumer did not poll any files you can enable this option to send an empty message (no body) instead. | streamDownload | consumer | false | boolean | Sets the download method to use when not using a local working directory. If set to true the remote files are streamed to the route as they are read. When set to false the remote files are loaded into memory before being sent into the route. | directoryMustExist | consumer (advanced) | false | boolean | Similar to startingDirectoryMustExist but this applies during polling recursive sub directories. | download | consumer (advanced) | false | boolean | Whether the FTP consumer should download the file. If this option is set to false then the message body will be null but the consumer will still trigger a Camel Exchange that has details about the file such as file name file size etc. It's just that the file will not be downloaded. | exceptionHandler | consumer (advanced) | | ExceptionHandler | To let the consumer use a custom ExceptionHandler. Notice if the option bridgeErrorHandler is enabled then this options is not in use. By default the consumer will deal with exceptions that will be logged at WARN/ERROR level and ignored. | exchangePattern | consumer (advanced) | | ExchangePattern | Sets the exchange pattern when the consumer creates an exchange. | ignoreFileNotFoundOrPermissionError | consumer (advanced) | false | boolean | Whether to ignore when trying to download a file which does not exist or due to permission error. By default when a file does not exists or insufficient permission then an exception is thrown. Setting this option to true allows to ignore that instead. | inProgressRepository | consumer (advanced) | | String> | A pluggable in-progress repository org.apache.camel.spi.IdempotentRepository. The in-progress repository is used to account the current in progress files being consumed. By default a memory based repository is used. | localWorkDirectory | consumer (advanced) | | String | When consuming a local work directory can be used to store the remote file content directly in local files to avoid loading the content into memory. This is beneficial if you consume a very big remote file and thus can conserve memory. | onCompletionExceptionHandler | consumer (advanced) | | ExceptionHandler | To use a custom org.apache.camel.spi.ExceptionHandler to handle any thrown exceptions that happens during the file on completion process where the consumer does either a commit or rollback. The default implementation will log any exception at WARN level and ignore. | pollStrategy | consumer (advanced) | | PollingConsumerPollStrategy | A pluggable org.apache.camel.PollingConsumerPollingStrategy allowing you to provide your custom implementation to control error handling usually occurred during the poll operation before an Exchange have been created and being routed in Camel. | processStrategy | consumer (advanced) | | GenericFileProcessStrategy | A pluggable org.apache.camel.component.file.GenericFileProcessStrategy allowing you to implement your own readLock option or similar. Can also be used when special conditions must be met before a file can be consumed such as a special ready file exists. If this option is set then the readLock option does not apply. | receiveBufferSize | consumer (advanced) | 32768 | int | The receive (download) buffer size Used only by FTPClient | startingDirectoryMustExist | consumer (advanced) | false | boolean | Whether the starting directory must exist. Mind that the autoCreate option is default enabled which means the starting directory is normally auto created if it doesn't exist. You can disable autoCreate and enable this to ensure the starting directory must exist. Will thrown an exception if the directory doesn't exist. | useList | consumer (advanced) | true | boolean | Whether to allow using LIST command when downloading a file. Default is true. In some use cases you may want to download a specific file and are not allowed to use the LIST command and therefore you can set this option to false. | fileExist | producer | Override | GenericFileExist | What to do if a file already exists with the same name. Override which is the default replaces the existing file. Append - adds content to the existing file. Fail - throws a GenericFileOperationException indicating that there is already an existing file. Ignore - silently ignores the problem and does not override the existing file but assumes everything is okay. Move - option requires to use the moveExisting option to be configured as well. The option eagerDeleteTargetFile can be used to control what to do if an moving the file and there exists already an existing file otherwise causing the move operation to fail. The Move option will move any existing files before writing the target file. TryRename Camel is only applicable if tempFileName option is in use. This allows to try renaming the file from the temporary name to the actual name without doing any exists check.This check may be faster on some file systems and especially FTP servers. | flatten | producer | false | boolean | Flatten is used to flatten the file name path to strip any leading paths so it's just the file name. This allows you to consume recursively into sub-directories but when you eg write the files to another directory they will be written in a single directory. Setting this to true on the producer enforces that any file name in CamelFileName header will be stripped for any leading paths. | moveExisting | producer | | String | Expression (such as File Language) used to compute file name to use when fileExist=Move is configured. To move files into a backup subdirectory just enter backup. This option only supports the following File Language tokens: file:name file:name.ext file:name.noext file:onlyname file:onlyname.noext file:ext and file:parent. Notice the file:parent is not supported by the FTP component as the FTP component can only move any existing files to a relative directory based on current dir as base. | tempFileName | producer | | String | The same as tempPrefix option but offering a more fine grained control on the naming of the temporary filename as it uses the File Language. | tempPrefix | producer | | String | This option is used to write the file using a temporary name and then after the write is complete rename it to the real name. Can be used to identify files being written and also avoid consumers (not using exclusive read locks) reading in progress files. Is often used by FTP when uploading big files. | allowNullBody | producer (advanced) | false | boolean | Used to specify if a null body is allowed during file writing. If set to true then an empty file will be created when set to false and attempting to send a null body to the file component a GenericFileWriteException of 'Cannot write null body to file.' will be thrown. If the fileExist option is set to 'Override' then the file will be truncated and if set to append the file will remain unchanged. | chmod | producer (advanced) | | String | Allows you to set chmod on the stored file. For example chmod=640. | disconnectOnBatchComplete | producer (advanced) | false | boolean | Whether or not to disconnect from remote FTP server right after a Batch upload is complete. disconnectOnBatchComplete will only disconnect the current connection to the FTP server. | eagerDeleteTargetFile | producer (advanced) | true | boolean | Whether or not to eagerly delete any existing target file. This option only applies when you use fileExists=Override and the tempFileName option as well. You can use this to disable (set it to false) deleting the target file before the temp file is written. For example you may write big files and want the target file to exists during the temp file is being written. This ensure the target file is only deleted until the very last moment just before the temp file is being renamed to the target filename. This option is also used to control whether to delete any existing files when fileExist=Move is enabled and an existing file exists. If this option copyAndDeleteOnRenameFails false then an exception will be thrown if an existing file existed if its true then the existing file is deleted before the move operation. | keepLastModified | producer (advanced) | false | boolean | Will keep the last modified timestamp from the source file (if any). Will use the Exchange.FILE_LAST_MODIFIED header to located the timestamp. This header can contain either a java.util.Date or long with the timestamp. If the timestamp exists and the option is enabled it will set this timestamp on the written file. Note: This option only applies to the file producer. You cannot use this option with any of the ftp producers. | sendNoop | producer (advanced) | true | boolean | Whether to send a noop command as a pre-write check before uploading files to the FTP server. This is enabled by default as a validation of the connection is still valid which allows to silently re-connect to be able to upload the file. However if this causes problems you can turn this option off. | activePortRange | advanced | | String | Set the client side port range in active mode. The syntax is: minPort-maxPort Both port numbers are inclusive eg 10000-19999 to include all 1xxxx ports. | autoCreate | advanced | true | boolean | Automatically create missing directories in the file's pathname. For the file consumer that means creating the starting directory. For the file producer it means the directory the files should be written to. | bufferSize | advanced | 131072 | int | Write buffer sized in bytes. | connectTimeout | advanced | 10000 | int | Sets the connect timeout for waiting for a connection to be established Used by both FTPClient and JSCH | ftpClient | advanced | | FTPClient | To use a custom instance of FTPClient | ftpClientConfig | advanced | | FTPClientConfig | To use a custom instance of FTPClientConfig to configure the FTP client the endpoint should use. | ftpClientConfigParameters | advanced | | Map | Used by FtpComponent to provide additional parameters for the FTPClientConfig | ftpClientParameters | advanced | | Map | Used by FtpComponent to provide additional parameters for the FTPClient | maximumReconnectAttempts | advanced | | int | Specifies the maximum reconnect attempts Camel performs when it tries to connect to the remote FTP server. Use 0 to disable this behavior. | reconnectDelay | advanced | | long | Delay in millis Camel will wait before performing a reconnect attempt. | siteCommand | advanced | | String | Sets optional site command(s) to be executed after successful login. Multiple site commands can be separated using a new line character (\\n). | soTimeout | advanced | 300000 | int | Sets the so timeout Used only by FTPClient | stepwise | advanced | true | boolean | Sets whether we should stepwise change directories while traversing file structures when downloading files or as well when uploading a file to a directory. You can disable this if you for example are in a situation where you cannot change directory on the FTP server due security reasons. | synchronous | advanced | false | boolean | Sets whether synchronous processing should be strictly used or Camel is allowed to use asynchronous processing (if supported). | throwExceptionOnConnectFailed | advanced | false | boolean | Should an exception be thrown if connection failed (exhausted) By default exception is not thrown and a WARN is logged. You can use this to enable exception being thrown and handle the thrown exception from the org.apache.camel.spi.PollingConsumerPollStrategy rollback method. | timeout | advanced | 30000 | int | Sets the data timeout for waiting for reply Used only by FTPClient | antExclude | filter | | String | Ant style filter exclusion. If both antInclude and antExclude are used antExclude takes precedence over antInclude. Multiple exclusions may be specified in comma-delimited format. | antFilterCaseSensitive | filter | true | boolean | Sets case sensitive flag on ant fiter | antInclude | filter | | String | Ant style filter inclusion. Multiple inclusions may be specified in comma-delimited format. | eagerMaxMessagesPerPoll | filter | true | boolean | Allows for controlling whether the limit from maxMessagesPerPoll is eager or not. If eager then the limit is during the scanning of files. Where as false would scan all files and then perform sorting. Setting this option to false allows for sorting all files first and then limit the poll. Mind that this requires a higher memory usage as all file details are in memory to perform the sorting. | exclude | filter | | String | Is used to exclude files if filename matches the regex pattern (matching is case in-senstive). Notice if you use symbols such as plus sign and others you would need to configure this using the RAW() syntax if configuring this as an endpoint uri. See more details at configuring endpoint uris | filter | filter | | GenericFileFilter | Pluggable filter as a org.apache.camel.component.file.GenericFileFilter class. Will skip files if filter returns false in its accept() method. | filterDirectory | filter | | String | Filters the directory based on Simple language. For example to filter on current date you can use a simple date pattern such as $date:now:yyyMMdd | filterFile | filter | | String | Filters the file based on Simple language. For example to filter on file size you can use $file:size 5000 | idempotent | filter | false | Boolean | Option to use the Idempotent Consumer EIP pattern to let Camel skip already processed files. Will by default use a memory based LRUCache that holds 1000 entries. If noop=true then idempotent will be enabled as well to avoid consuming the same files over and over again. | idempotentKey | filter | | String | To use a custom idempotent key. By default the absolute path of the file is used. You can use the File Language for example to use the file name and file size you can do: idempotentKey=$file:name-$file:size | idempotentRepository | filter | | String> | A pluggable repository org.apache.camel.spi.IdempotentRepository which by default use MemoryMessageIdRepository if none is specified and idempotent is true. | include | filter | | String | Is used to include files if filename matches the regex pattern (matching is case in-sensitive). Notice if you use symbols such as plus sign and others you would need to configure this using the RAW() syntax if configuring this as an endpoint uri. See more details at configuring endpoint uris | maxDepth | filter | 2147483647 | int | The maximum depth to traverse when recursively processing a directory. | maxMessagesPerPoll | filter | | int | To define a maximum messages to gather per poll. By default no maximum is set. Can be used to set a limit of e.g. 1000 to avoid when starting up the server that there are thousands of files. Set a value of 0 or negative to disabled it. Notice: If this option is in use then the File and FTP components will limit before any sorting. For example if you have 100000 files and use maxMessagesPerPoll=500 then only the first 500 files will be picked up and then sorted. You can use the eagerMaxMessagesPerPoll option and set this to false to allow to scan all files first and then sort afterwards. | minDepth | filter | | int | The minimum depth to start processing when recursively processing a directory. Using minDepth=1 means the base directory. Using minDepth=2 means the first sub directory. | move | filter | | String | Expression (such as Simple Language) used to dynamically set the filename when moving it after processing. To move files into a .done subdirectory just enter .done. | exclusiveReadLockStrategy | lock | | GenericFileExclusiveReadLockStrategy | Pluggable read-lock as a org.apache.camel.component.file.GenericFileExclusiveReadLockStrategy implementation. | readLock | lock | | String | Used by consumer to only poll the files if it has exclusive read-lock on the file (i.e. the file is not in-progress or being written). Camel will wait until the file lock is granted. This option provides the build in strategies: none - No read lock is in use markerFile - Camel creates a marker file (fileName.camelLock) and then holds a lock on it. This option is not available for the FTP component changed - Changed is using file length/modification timestamp to detect whether the file is currently being copied or not. Will at least use 1 sec to determine this so this option cannot consume files as fast as the others but can be more reliable as the JDK IO API cannot always determine whether a file is currently being used by another process. The option readLockCheckInterval can be used to set the check frequency. fileLock - is for using java.nio.channels.FileLock. This option is not avail for the FTP component. This approach should be avoided when accessing a remote file system via a mount/share unless that file system supports distributed file locks. rename - rename is for using a try to rename the file as a test if we can get exclusive read-lock. idempotent - (only for file component) idempotent is for using a idempotentRepository as the read-lock. This allows to use read locks that supports clustering if the idempotent repository implementation supports that. idempotent-changed - (only for file component) idempotent-changed is for using a idempotentRepository and changed as the combined read-lock. This allows to use read locks that supports clustering if the idempotent repository implementation supports that. idempotent-rename - (only for file component) idempotent-rename is for using a idempotentRepository and rename as the combined read-lock. This allows to use read locks that supports clustering if the idempotent repository implementation supports that. Notice: The various read locks is not all suited to work in clustered mode where concurrent consumers on different nodes is competing for the same files on a shared file system. The markerFile using a close to atomic operation to create the empty marker file but its not guaranteed to work in a cluster. The fileLock may work better but then the file system need to support distributed file locks and so on. Using the idempotent read lock can support clustering if the idempotent repository supports clustering such as Hazelcast Component or Infinispan. | readLockCheckInterval | lock | 1000 | long | Interval in millis for the read-lock if supported by the read lock. This interval is used for sleeping between attempts to acquire the read lock. For example when using the changed read lock you can set a higher interval period to cater for slow writes. The default of 1 sec. may be too fast if the producer is very slow writing the file. Notice: For FTP the default readLockCheckInterval is 5000. The readLockTimeout value must be higher than readLockCheckInterval but a rule of thumb is to have a timeout that is at least 2 or more times higher than the readLockCheckInterval. This is needed to ensure that amble time is allowed for the read lock process to try to grab the lock before the timeout was hit. | readLockDeleteOrphanLockFiles | lock | true | boolean | Whether or not read lock with marker files should upon startup delete any orphan read lock files which may have been left on the file system if Camel was not properly shutdown (such as a JVM crash). If turning this option to false then any orphaned lock file will cause Camel to not attempt to pickup that file this could also be due another node is concurrently reading files from the same shared directory. | readLockLoggingLevel | lock | WARN | LoggingLevel | Logging level used when a read lock could not be acquired. By default a WARN is logged. You can change this level for example to OFF to not have any logging. This option is only applicable for readLock of types: changed fileLock rename. | readLockMarkerFile | lock | true | boolean | Whether to use marker file with the changed rename or exclusive read lock types. By default a marker file is used as well to guard against other processes picking up the same files. This behavior can be turned off by setting this option to false. For example if you do not want to write marker files to the file systems by the Camel application. | readLockMinAge | lock | 0 | long | This option applied only for readLock=change. This option allows to specify a minimum age the file must be before attempting to acquire the read lock. For example use readLockMinAge=300s to require the file is at last 5 minutes old. This can speedup the changed read lock as it will only attempt to acquire files which are at least that given age. | readLockMinLength | lock | 1 | long | This option applied only for readLock=changed. This option allows you to configure a minimum file length. By default Camel expects the file to contain data and thus the default value is 1. You can set this option to zero to allow consuming zero-length files. | readLockRemoveOnCommit | lock | false | boolean | This option applied only for readLock=idempotent. This option allows to specify whether to remove the file name entry from the idempotent repository when processing the file is succeeded and a commit happens. By default the file is not removed which ensures that any race-condition do not occur so another active node may attempt to grab the file. Instead the idempotent repository may support eviction strategies that you can configure to evict the file name entry after X minutes - this ensures no problems with race conditions. | readLockRemoveOnRollback | lock | true | boolean | This option applied only for readLock=idempotent. This option allows to specify whether to remove the file name entry from the idempotent repository when processing the file failed and a rollback happens. If this option is false then the file name entry is confirmed (as if the file did a commit). | readLockTimeout | lock | 10000 | long | Optional timeout in millis for the read-lock if supported by the read-lock. If the read-lock could not be granted and the timeout triggered then Camel will skip the file. At next poll Camel will try the file again and this time maybe the read-lock could be granted. Use a value of 0 or lower to indicate forever. Currently fileLock changed and rename support the timeout. Notice: For FTP the default readLockTimeout value is 20000 instead of 10000. The readLockTimeout value must be higher than readLockCheckInterval but a rule of thumb is to have a timeout that is at least 2 or more times higher than the readLockCheckInterval. This is needed to ensure that amble time is allowed for the read lock process to try to grab the lock before the timeout was hit. | backoffErrorThreshold | scheduler | | int | The number of subsequent error polls (failed due some error) that should happen before the backoffMultipler should kick-in. | backoffIdleThreshold | scheduler | | int | The number of subsequent idle polls that should happen before the backoffMultipler should kick-in. | backoffMultiplier | scheduler | | int | To let the scheduled polling consumer backoff if there has been a number of subsequent idles/errors in a row. The multiplier is then the number of polls that will be skipped before the next actual attempt is happening again. When this option is in use then backoffIdleThreshold and/or backoffErrorThreshold must also be configured. | delay | scheduler | 500 | long | Milliseconds before the next poll. You can also specify time values using units such as 60s (60 seconds) 5m30s (5 minutes and 30 seconds) and 1h (1 hour). | greedy | scheduler | false | boolean | If greedy is enabled then the ScheduledPollConsumer will run immediately again if the previous run polled 1 or more messages. | initialDelay | scheduler | 1000 | long | Milliseconds before the first poll starts. You can also specify time values using units such as 60s (60 seconds) 5m30s (5 minutes and 30 seconds) and 1h (1 hour). | runLoggingLevel | scheduler | TRACE | LoggingLevel | The consumer logs a start/complete log line when it polls. This option allows you to configure the logging level for that. | scheduledExecutorService | scheduler | | ScheduledExecutorService | Allows for configuring a custom/shared thread pool to use for the consumer. By default each consumer has its own single threaded thread pool. | scheduler | scheduler | none | ScheduledPollConsumerScheduler | To use a cron scheduler from either camel-spring or camel-quartz2 component | schedulerProperties | scheduler | | Map | To configure additional properties when using a custom scheduler or any of the Quartz2 Spring based scheduler. | startScheduler | scheduler | true | boolean | Whether the scheduler should be auto started. | timeUnit | scheduler | MILLISECONDS | TimeUnit | Time unit for initialDelay and delay options. | useFixedDelay | scheduler | true | boolean | Controls if fixed delay or fixed rate is used. See ScheduledExecutorService in JDK for details. | shuffle | sort | false | boolean | To shuffle the list of files (sort in random order) | sortBy | sort | | String | Built-in sort by using the File Language. Supports nested sorts so you can have a sort by file name and as a 2nd group sort by modified date. | sorter | sort | | GenericFile> | Pluggable sorter as a java.util.Comparator class. | account | security | | String | Account to use for login | password | security | | String | Password to use for login | username | security | | String | Username to use for login |======================================================================= {% endraw %} // endpoint options: END [Info] ==== FTPS component default trust store When using the `ftpClient.` properties related to SSL with the FTPS component, the trust store accept all certificates. If you only want trust selective certificates, you have to configure the trust store with the `ftpClient.trustStore.xxx` options or by configuring a custom `ftpClient`. When using `sslContextParameters`, the trust store is managed by the configuration of the provided SSLContextParameters instance. ==== You can configure additional options on the `ftpClient` and `ftpClientConfig` from the URI directly by using the `ftpClient.` or `ftpClientConfig.` prefix. For example to set the `setDataTimeout` on the `FTPClient` to 30 seconds you can do: [source,java] -------------------------------------------------------------------------------------- from(""ftp://foo@myserver?password=secret&ftpClient.dataTimeout=30000"").to(""bean:foo""); -------------------------------------------------------------------------------------- You can mix and match and have use both prefixes, for example to configure date format or timezones. [source,java] ---------------------------------------------------------------------------------------------------------------------------- from(""ftp://foo@myserver?password=secret&ftpClient.dataTimeout=30000&ftpClientConfig.serverLanguageCode=fr"").to(""bean:foo""); ---------------------------------------------------------------------------------------------------------------------------- You can have as many of these options as you like. See the documentation of the Apache Commons FTP FTPClientConfig for possible options and more details. And as well for Apache Commons FTP FTPClient. If you do not like having many and long configuration in the url you can refer to the `ftpClient` or `ftpClientConfig` to use by letting Camel lookup in the link:registry.html[Registry] for it. For example: [source,java] -------------------------------------------------------------------------- -------------------------------------------------------------------------- And then let Camel lookup this bean when you use the # notation in the url. [source,java] ------------------------------------------------------------------------------------ from(""ftp://foo@myserver?password=secret&ftpClientConfig=#myConfig"").to(""bean:foo""); ------------------------------------------------------------------------------------ [[FTP2-MoreURIoptions]] More URI options ^^^^^^^^^^^^^^^^ [Info] ==== See link:file2.html[File2] as all the options there also applies for this component. ==== [[FTP2-Examples]] Examples ^^^^^^^^ `ftp://someone@someftpserver.com/public/upload/images/holiday2008?password=secret&binary=true` + `ftp://someoneelse@someotherftpserver.co.uk:12049/reports/2008/password=secret&binary=false` + `ftp://publicftpserver.com/download` [Warning] ==== FTP Consumer does not support concurrency The FTP consumer (with the same endpoint) does not support concurrency (the backing FTP client is not thread safe). + You can use multiple FTP consumers to poll from different endpoints. It is only a single endpoint that does not support concurrent consumers. The FTP producer does *not* have this issue, it supports concurrency. ==== [Tip] ==== More information This component is an extension of the link:file2.html[File] component. So there are more samples and details on the link:file2.html[File] component page. ==== [[FTP2-Defaultwhenconsumingfiles]] Default when consuming files ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ The link:ftp2.html[FTP] consumer will by default leave the consumed files untouched on the remote FTP server. You have to configure it explicitly if you want it to delete the files or move them to another location. For example you can use `delete=true` to delete the files, or use `move=.done` to move the files into a hidden done sub directory. The regular link:file2.html[File] consumer is different as it will by default move files to a `.camel` sub directory. The reason Camel does *not* do this by default for the FTP consumer is that it may lack permissions by default to be able to move or delete files. [[FTP2-limitations]] limitations +++++++++++ The option *readLock* can be used to force Camel *not* to consume files that is currently in the progress of being written. However, this option is turned off by default, as it requires that the user has write access. See the options table at link:file2.html[File2] for more details about read locks. + There are other solutions to avoid consuming files that are currently being written over FTP; for instance, you can write to a temporary destination and move the file after it has been written. When moving files using `move` or `preMove` option the files are restricted to the FTP_ROOT folder. That prevents you from moving files outside the FTP area. If you want to move files to another area you can use soft links and move files into a soft linked folder. [[FTP2-MessageHeaders]] Message Headers ^^^^^^^^^^^^^^^ The following message headers can be used to affect the behavior of the component [width=""100%"",cols=""50%,50%"",options=""header"",] |======================================================================= |Header |Description |`CamelFileName` |Specifies the output file name (relative to the endpoint directory) to be used for the output message when sending to the endpoint. If this is not present and no expression either, then a generated message ID is used as the filename instead. |`CamelFileNameProduced` |The actual filepath (path + name) for the output file that was written. This header is set by Camel and its purpose is providing end-users the name of the file that was written. |`CamelFileIndex` |Current index out of total number of files being consumed in this batch. |`CamelFileSize` |Total number of files being consumed in this batch. |`CamelFileHost` |The remote hostname. |`CamelFileLocalWorkPath` |Path to the local work file, if local work directory is used. |======================================================================= In addition the FTP/FTPS consumer and producer will enrich the Camel `Message` with the following headers [width=""100%"",cols=""50%,50%"",options=""header"",] |======================================================================= |Header |Description |`CamelFtpReplyCode` |*Camel 2.11.1:* The FTP client reply code (the type is a integer) |`CamelFtpReplyString` | *Camel 2.11.1:* The FTP client reply string |======================================================================= [[FTP2-Abouttimeouts]] About timeouts ^^^^^^^^^^^^^^ The two set of libraries (see top) has different API for setting timeout. You can use the `connectTimeout` option for both of them to set a timeout in millis to establish a network connection. An individual `soTimeout` can also be set on the FTP/FTPS, which corresponds to using `ftpClient.soTimeout`. Notice SFTP will automatically use `connectTimeout` as its `soTimeout`. The `timeout` option only applies for FTP/FTSP as the data timeout, which corresponds to the `ftpClient.dataTimeout` value. All timeout values are in millis. [[FTP2-UsingLocalWorkDirectory]] Using Local Work Directory ^^^^^^^^^^^^^^^^^^^^^^^^^^ Camel supports consuming from remote FTP servers and downloading the files directly into a local work directory. This avoids reading the entire remote file content into memory as it is streamed directly into the local file using `FileOutputStream`. Camel will store to a local file with the same name as the remote file, though with `.inprogress` as extension while the file is being downloaded. Afterwards, the file is renamed to remove the `.inprogress` suffix. And finally, when the link:exchange.html[Exchange] is complete the local file is deleted. So if you want to download files from a remote FTP server and store it as files then you need to route to a file endpoint such as: [source,java] ------------------------------------------------------------------------------------------------ from(""ftp://someone@someserver.com?password=secret&localWorkDirectory=/tmp"").to(""file://inbox""); ------------------------------------------------------------------------------------------------ [Tip] ==== *Optimization by renaming work file* The route above is ultra efficient as it avoids reading the entire file content into memory. It will download the remote file directly to a local file stream. The `java.io.File` handle is then used as the link:exchange.html[Exchange] body. The file producer leverages this fact and can work directly on the work file `java.io.File` handle and perform a `java.io.File.rename` to the target filename. As Camel knows it's a local work file, it can optimize and use a rename instead of a file copy, as the work file is meant to be deleted anyway. ==== [[FTP2-Stepwisechangingdirectories]] Stepwise changing directories ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Camel link:ftp2.html[FTP] can operate in two modes in terms of traversing directories when consuming files (eg downloading) or producing files (eg uploading) * stepwise * not stepwise You may want to pick either one depending on your situation and security issues. Some Camel end users can only download files if they use stepwise, while others can only download if they do not. At least you have the choice to pick (from Camel 2.6 onwards). In Camel 2.0 - 2.5 there is only one mode and it is: * before 2.5 not stepwise * 2.5 stepwise From Camel 2.6 onwards there is now an option `stepwise` you can use to control the behavior. Note that stepwise changing of directory will in most cases only work when the user is confined to it's home directory and when the home directory is reported as `""/""`. The difference between the two of them is best illustrated with an example. Suppose we have the following directory structure on the remote FTP server we need to traverse and download files: [source,java] -------------- / /one /one/two /one/two/sub-a /one/two/sub-b -------------- And that we have a file in each of sub-a (a.txt) and sub-b (b.txt) folder. [[FTP2-Usingstepwise]] Using stepwise=true (default mode) ++++++++++++++++++++++++++++++++++ [source,java] ---------------------------------------------------------- TYPE A 200 Type set to A PWD 257 ""/"" is current directory. CWD one 250 CWD successful. ""/one"" is current directory. CWD two 250 CWD successful. ""/one/two"" is current directory. SYST 215 UNIX emulated by FileZilla PORT 127,0,0,1,17,94 200 Port command successful LIST 150 Opening data channel for directory list. 226 Transfer OK CWD sub-a 250 CWD successful. ""/one/two/sub-a"" is current directory. PORT 127,0,0,1,17,95 200 Port command successful LIST 150 Opening data channel for directory list. 226 Transfer OK CDUP 200 CDUP successful. ""/one/two"" is current directory. CWD sub-b 250 CWD successful. ""/one/two/sub-b"" is current directory. PORT 127,0,0,1,17,96 200 Port command successful LIST 150 Opening data channel for directory list. 226 Transfer OK CDUP 200 CDUP successful. ""/one/two"" is current directory. CWD / 250 CWD successful. ""/"" is current directory. PWD 257 ""/"" is current directory. CWD one 250 CWD successful. ""/one"" is current directory. CWD two 250 CWD successful. ""/one/two"" is current directory. PORT 127,0,0,1,17,97 200 Port command successful RETR foo.txt 150 Opening data channel for file transfer. 226 Transfer OK CWD / 250 CWD successful. ""/"" is current directory. PWD 257 ""/"" is current directory. CWD one 250 CWD successful. ""/one"" is current directory. CWD two 250 CWD successful. ""/one/two"" is current directory. CWD sub-a 250 CWD successful. ""/one/two/sub-a"" is current directory. PORT 127,0,0,1,17,98 200 Port command successful RETR a.txt 150 Opening data channel for file transfer. 226 Transfer OK CWD / 250 CWD successful. ""/"" is current directory. PWD 257 ""/"" is current directory. CWD one 250 CWD successful. ""/one"" is current directory. CWD two 250 CWD successful. ""/one/two"" is current directory. CWD sub-b 250 CWD successful. ""/one/two/sub-b"" is current directory. PORT 127,0,0,1,17,99 200 Port command successful RETR b.txt 150 Opening data channel for file transfer. 226 Transfer OK CWD / 250 CWD successful. ""/"" is current directory. QUIT 221 Goodbye disconnected. ---------------------------------------------------------- As you can see when stepwise is enabled, it will traverse the directory structure using CD xxx. [[FTP2-Notusingstepwise]] Using stepwise=false ++++++++++++++++++++ [source,java] ------------------------------------------- 230 Logged on TYPE A 200 Type set to A SYST 215 UNIX emulated by FileZilla PORT 127,0,0,1,4,122 200 Port command successful LIST one/two 150 Opening data channel for directory list 226 Transfer OK PORT 127,0,0,1,4,123 200 Port command successful LIST one/two/sub-a 150 Opening data channel for directory list 226 Transfer OK PORT 127,0,0,1,4,124 200 Port command successful LIST one/two/sub-b 150 Opening data channel for directory list 226 Transfer OK PORT 127,0,0,1,4,125 200 Port command successful RETR one/two/foo.txt 150 Opening data channel for file transfer. 226 Transfer OK PORT 127,0,0,1,4,126 200 Port command successful RETR one/two/sub-a/a.txt 150 Opening data channel for file transfer. 226 Transfer OK PORT 127,0,0,1,4,127 200 Port command successful RETR one/two/sub-b/b.txt 150 Opening data channel for file transfer. 226 Transfer OK QUIT 221 Goodbye disconnected. ------------------------------------------- As you can see when not using stepwise, there are no CD operation invoked at all. [[FTP2-Samples]] Samples ^^^^^^^ In the sample below we set up Camel to download all the reports from the FTP server once every hour (60 min) as BINARY content and store it as files on the local file system. And the route using Spring DSL: [source,xml] ------------------------------------------------------------------------------------------------------ ------------------------------------------------------------------------------------------------------ [[FTP2-ConsumingaremoteFTPSserverimplicitSSLandclientauthentication]] Consuming a remote FTPS server (implicit SSL) and client authentication +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ [source,java] -------------------------------------------------------------------------------------------------- from(""ftps://admin@localhost:2222/public/camel?password=admin&securityProtocol=SSL&isImplicit=true &ftpClient.keyStore.file=./src/test/resources/server.jks &ftpClient.keyStore.password=password&ftpClient.keyStore.keyPassword=password"") .to(""bean:foo""); -------------------------------------------------------------------------------------------------- [[FTP2-ConsumingaremoteFTPSserverexplicitTLSandacustomtruststoreconfiguration]] Consuming a remote FTPS server (explicit TLS) and a custom trust store configuration ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ [source,java] ---------------------------------------------------------------------------------------------------------------------------------------------------------------- from(""ftps://admin@localhost:2222/public/camel?password=admin&ftpClient.trustStore.file=./src/test/resources/server.jks&ftpClient.trustStore.password=password"") .to(""bean:foo""); ---------------------------------------------------------------------------------------------------------------------------------------------------------------- [[FTP2-Filterusingorg.apache.camel.component.file.GenericFileFilter]] Filter using `org.apache.camel.component.file.GenericFileFilter` ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Camel supports pluggable filtering strategies. This strategy it to use the build in `org.apache.camel.component.file.GenericFileFilter` in Java. You can then configure the endpoint with such a filter to skip certain filters before being processed. In the sample we have built our own filter that only accepts files starting with report in the filename. And then we can configure our route using the *filter* attribute to reference our filter (using `#` notation) that we have defined in the spring XML file: [source,xml] --------------------------------------------------------------------------------------- --------------------------------------------------------------------------------------- [[FTP2-FilteringusingANTpathmatcher]] Filtering using ANT path matcher ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ The ANT path matcher is a filter that is shipped out-of-the-box in the *camel-spring* jar. So you need to depend on *camel-spring* if you are using Maven. + The reason is that we leverage Spring's http://static.springsource.org/spring/docs/3.0.x/api/org/springframework/util/AntPathMatcher.html[AntPathMatcher] to do the actual matching. The file paths are matched with the following rules: * `?` matches one character * `*` matches zero or more characters * `**` matches zero or more directories in a path The sample below demonstrates how to use it: [[FTP2-UsingaproxywithSFTP]] Using a proxy with SFTP ^^^^^^^^^^^^^^^^^^^^^^^ To use an HTTP proxy to connect to your remote host, you can configure your route in the following way: [source,xml] ------------------------------------------------------------------------------------- ------------------------------------------------------------------------------------- You can also assign a user name and password to the proxy, if necessary. Please consult the documentation for `com.jcraft.jsch.Proxy` to discover all options. [[FTP2-SettingpreferredSFTPauthenticationmethod]] Setting preferred SFTP authentication method ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ If you want to explicitly specify the list of authentication methods that should be used by `sftp` component, use `preferredAuthentications` option. If for example you would like Camel to attempt to authenticate with private/public SSH key and fallback to user/password authentication in the case when no public key is available, use the following route configuration: [source,java] ------------------------------------------------------------------------------------------------------------- from(""sftp://localhost:9999/root?username=admin&password=admin&preferredAuthentications=publickey,password""). to(""bean:processFile""); ------------------------------------------------------------------------------------------------------------- [[FTP2-Consumingasinglefileusingafixedname]] Consuming a single file using a fixed name ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ When you want to download a single file and knows the file name, you can use `fileName=myFileName.txt` to tell Camel the name of the file to download. By default the consumer will still do a FTP LIST command to do a directory listing and then filter these files based on the `fileName` option. Though in this use-case it may be desirable to turn off the directory listing by setting `useList=false`. For example the user account used to login to the FTP server may not have permission to do a FTP LIST command. So you can turn off this with `useList=false`, and then provide the fixed name of the file to download with `fileName=myFileName.txt`, then the FTP consumer can still download the file. If the file for some reason does not exist, then Camel will by default throw an exception, you can turn this off and ignore this by setting `ignoreFileNotFoundOrPermissionError=true`. For example to have a Camel route that pickup a single file, and delete it after use you can do [source,java] ------------------------------------------------------------------------------------------------------------------------------------------------------------- from(""ftp://admin@localhost:21/nolist/?password=admin&stepwise=false&useList=false&ignoreFileNotFoundOrPermissionError=true&fileName=report.txt&delete=true"") .to(""activemq:queue:report""); ------------------------------------------------------------------------------------------------------------------------------------------------------------- Notice that we have use all the options we talked above above. You can also use this with `ConsumerTemplate`. For example to download a single file (if it exists) and grab the file content as a String type: [source,java] ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- String data = template.retrieveBodyNoWait(""ftp://admin@localhost:21/nolist/?password=admin&stepwise=false&useList=false&ignoreFileNotFoundOrPermissionError=true&fileName=report.txt&delete=true"", String.class); ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- [[FTP2-Debuglogging]] Debug logging ^^^^^^^^^^^^^ This component has log level *TRACE* that can be helpful if you have problems. [[FTP2-SeeAlso]] See Also ^^^^^^^^ * link:configuring-camel.html[Configuring Camel] * link:component.html[Component] * link:endpoint.html[Endpoint] * link:getting-started.html[Getting Started] * link:file2.html[File2] ",12261,False,2066.8012114839935,median "CLASS zcl_abapgit_git_porcelain DEFINITION PUBLIC FINAL CREATE PUBLIC . PUBLIC SECTION. TYPES: BEGIN OF ty_pull_result, files TYPE zif_abapgit_definitions=>ty_files_tt, objects TYPE zif_abapgit_definitions=>ty_objects_tt, branch TYPE zif_abapgit_definitions=>ty_sha1, END OF ty_pull_result . TYPES: BEGIN OF ty_push_result, new_files TYPE zif_abapgit_definitions=>ty_files_tt, branch TYPE zif_abapgit_definitions=>ty_sha1, updated_files TYPE zif_abapgit_definitions=>ty_file_signatures_tt, new_objects TYPE zif_abapgit_definitions=>ty_objects_tt, END OF ty_push_result . CLASS-METHODS pull IMPORTING !iv_url TYPE string !iv_branch_name TYPE string RETURNING VALUE(rs_result) TYPE ty_pull_result RAISING zcx_abapgit_exception . CLASS-METHODS push IMPORTING !is_comment TYPE zif_abapgit_definitions=>ty_comment !io_stage TYPE REF TO zcl_abapgit_stage !it_old_objects TYPE zif_abapgit_definitions=>ty_objects_tt !iv_parent TYPE zif_abapgit_definitions=>ty_sha1 !iv_url TYPE string !iv_branch_name TYPE string RETURNING VALUE(rs_result) TYPE ty_push_result RAISING zcx_abapgit_exception . CLASS-METHODS create_branch IMPORTING !iv_url TYPE string !iv_name TYPE string !iv_from TYPE zif_abapgit_definitions=>ty_sha1 RAISING zcx_abapgit_exception . CLASS-METHODS create_tag IMPORTING !iv_url TYPE string !is_tag TYPE zif_abapgit_definitions=>ty_git_tag RAISING zcx_abapgit_exception . CLASS-METHODS delete_branch IMPORTING !iv_url TYPE string !is_branch TYPE zif_abapgit_definitions=>ty_git_branch RAISING zcx_abapgit_exception . CLASS-METHODS delete_tag IMPORTING !iv_url TYPE string !is_tag TYPE zif_abapgit_definitions=>ty_git_tag RAISING zcx_abapgit_exception . CLASS-METHODS full_tree IMPORTING !it_objects TYPE zif_abapgit_definitions=>ty_objects_tt !iv_branch TYPE zif_abapgit_definitions=>ty_sha1 RETURNING VALUE(rt_expanded) TYPE zif_abapgit_definitions=>ty_expanded_tt RAISING zcx_abapgit_exception . PROTECTED SECTION. PRIVATE SECTION. TYPES: BEGIN OF ty_tree, path TYPE string, data TYPE xstring, sha1 TYPE zif_abapgit_definitions=>ty_sha1, END OF ty_tree . TYPES: ty_trees_tt TYPE STANDARD TABLE OF ty_tree WITH DEFAULT KEY . TYPES: BEGIN OF ty_folder, path TYPE string, count TYPE i, sha1 TYPE zif_abapgit_definitions=>ty_sha1, END OF ty_folder . TYPES: ty_folders_tt TYPE STANDARD TABLE OF ty_folder WITH DEFAULT KEY . CONSTANTS c_zero TYPE zif_abapgit_definitions=>ty_sha1 VALUE '0000000000000000000000000000000000000000' ##NO_TEXT. CLASS-METHODS build_trees IMPORTING !it_expanded TYPE zif_abapgit_definitions=>ty_expanded_tt RETURNING VALUE(rt_trees) TYPE ty_trees_tt RAISING zcx_abapgit_exception . CLASS-METHODS find_folders IMPORTING !it_expanded TYPE zif_abapgit_definitions=>ty_expanded_tt RETURNING VALUE(rt_folders) TYPE ty_folders_tt . CLASS-METHODS walk IMPORTING !it_objects TYPE zif_abapgit_definitions=>ty_objects_tt !iv_sha1 TYPE zif_abapgit_definitions=>ty_sha1 !iv_path TYPE string CHANGING !ct_files TYPE zif_abapgit_definitions=>ty_files_tt RAISING zcx_abapgit_exception . CLASS-METHODS walk_tree IMPORTING !it_objects TYPE zif_abapgit_definitions=>ty_objects_tt !iv_tree TYPE zif_abapgit_definitions=>ty_sha1 !iv_base TYPE string RETURNING VALUE(rt_expanded) TYPE zif_abapgit_definitions=>ty_expanded_tt RAISING zcx_abapgit_exception . CLASS-METHODS receive_pack_push IMPORTING !is_comment TYPE zif_abapgit_definitions=>ty_comment !it_trees TYPE ty_trees_tt !it_blobs TYPE zif_abapgit_definitions=>ty_files_tt !iv_parent TYPE zif_abapgit_definitions=>ty_sha1 !iv_parent2 TYPE zif_abapgit_definitions=>ty_sha1 OPTIONAL !iv_url TYPE string !iv_branch_name TYPE string EXPORTING !ev_new_commit TYPE zif_abapgit_definitions=>ty_sha1 !et_new_objects TYPE zif_abapgit_definitions=>ty_objects_tt !ev_new_tree TYPE zif_abapgit_definitions=>ty_sha1 RAISING zcx_abapgit_exception . CLASS-METHODS receive_pack_create_tag IMPORTING !is_tag TYPE zif_abapgit_definitions=>ty_git_tag !iv_url TYPE string RAISING zcx_abapgit_exception . CLASS-METHODS create_annotated_tag IMPORTING !is_tag TYPE zif_abapgit_definitions=>ty_git_tag !iv_url TYPE string RAISING zcx_abapgit_exception . CLASS-METHODS create_lightweight_tag IMPORTING !is_tag TYPE zif_abapgit_definitions=>ty_git_tag !iv_url TYPE string RAISING zcx_abapgit_exception . ENDCLASS. CLASS ZCL_ABAPGIT_GIT_PORCELAIN IMPLEMENTATION. METHOD build_trees. DATA: lt_nodes TYPE zcl_abapgit_git_pack=>ty_nodes_tt, ls_tree LIKE LINE OF rt_trees, lv_len TYPE i, lt_folders TYPE ty_folders_tt. FIELD-SYMBOLS: LIKE LINE OF lt_folders, LIKE LINE OF lt_nodes, LIKE LINE OF lt_folders, LIKE LINE OF it_expanded. lt_folders = find_folders( it_expanded ). * start with the deepest folders SORT lt_folders BY count DESCENDING. LOOP AT lt_folders ASSIGNING . CLEAR lt_nodes. * files LOOP AT it_expanded ASSIGNING WHERE path = -path. APPEND INITIAL LINE TO lt_nodes ASSIGNING . -chmod = -chmod. -name = -name. -sha1 = -sha1. ENDLOOP. * folders LOOP AT lt_folders ASSIGNING WHERE count = -count + 1. lv_len = strlen( -path ). IF strlen( -path ) > lv_len AND -path(lv_len) = -path. APPEND INITIAL LINE TO lt_nodes ASSIGNING . -chmod = zif_abapgit_definitions=>c_chmod-dir. * extract folder name, this can probably be done easier using regular expressions -name = -path+lv_len. lv_len = strlen( -name ) - 1. -name = -name(lv_len). -sha1 = -sha1. ENDIF. ENDLOOP. CLEAR ls_tree. ls_tree-path = -path. ls_tree-data = zcl_abapgit_git_pack=>encode_tree( lt_nodes ). ls_tree-sha1 = zcl_abapgit_hash=>sha1( iv_type = zif_abapgit_definitions=>c_type-tree iv_data = ls_tree-data ). APPEND ls_tree TO rt_trees. -sha1 = ls_tree-sha1. ENDLOOP. ENDMETHOD. METHOD create_annotated_tag. receive_pack_create_tag( is_tag = is_tag iv_url = iv_url ). ENDMETHOD. METHOD create_branch. DATA: lt_objects TYPE zif_abapgit_definitions=>ty_objects_tt, lv_pack TYPE xstring. IF iv_name CS ` `. zcx_abapgit_exception=>raise( 'Branch name cannot contain blank spaces' ). ENDIF. * ""client MUST send an empty packfile"" * https://github.com/git/git/blob/master/Documentation/technical/pack-protocol.txt#L514 lv_pack = zcl_abapgit_git_pack=>encode( lt_objects ). zcl_abapgit_git_transport=>receive_pack( iv_url = iv_url iv_old = c_zero iv_new = iv_from iv_branch_name = iv_name iv_pack = lv_pack ). ENDMETHOD. METHOD create_lightweight_tag. DATA: lt_objects TYPE zif_abapgit_definitions=>ty_objects_tt, lv_pack TYPE xstring. * ""client MUST send an empty packfile"" * https://github.com/git/git/blob/master/Documentation/technical/pack-protocol.txt#L514 lv_pack = zcl_abapgit_git_pack=>encode( lt_objects ). zcl_abapgit_git_transport=>receive_pack( iv_url = iv_url iv_old = c_zero iv_new = is_tag-sha1 iv_branch_name = is_tag-name iv_pack = lv_pack ). ENDMETHOD. METHOD create_tag. IF is_tag-name CS ` `. zcx_abapgit_exception=>raise( 'Tag name cannot contain blank spaces' ). ENDIF. CASE is_tag-type. WHEN zif_abapgit_definitions=>c_git_branch_type-annotated_tag. create_annotated_tag( is_tag = is_tag iv_url = iv_url ). WHEN zif_abapgit_definitions=>c_git_branch_type-lightweight_tag. create_lightweight_tag( is_tag = is_tag iv_url = iv_url ). WHEN OTHERS. zcx_abapgit_exception=>raise( |Invalid tag type: { is_tag-type }| ). ENDCASE. ENDMETHOD. METHOD delete_branch. DATA: lt_objects TYPE zif_abapgit_definitions=>ty_objects_tt, lv_pack TYPE xstring. * ""client MUST send an empty packfile"" * https://github.com/git/git/blob/master/Documentation/technical/pack-protocol.txt#L514 lv_pack = zcl_abapgit_git_pack=>encode( lt_objects ). zcl_abapgit_git_transport=>receive_pack( iv_url = iv_url iv_old = is_branch-sha1 iv_new = c_zero iv_branch_name = is_branch-name iv_pack = lv_pack ). ENDMETHOD. METHOD delete_tag. DATA: lt_objects TYPE zif_abapgit_definitions=>ty_objects_tt, lv_pack TYPE xstring. * ""client MUST send an empty packfile"" * https://github.com/git/git/blob/master/Documentation/technical/pack-protocol.txt#L514 lv_pack = zcl_abapgit_git_pack=>encode( lt_objects ). zcl_abapgit_git_transport=>receive_pack( iv_url = iv_url iv_old = is_tag-sha1 iv_new = c_zero iv_branch_name = is_tag-name iv_pack = lv_pack ). ENDMETHOD. METHOD find_folders. DATA: lt_paths TYPE TABLE OF string, lv_split TYPE string, lv_path TYPE string. FIELD-SYMBOLS: LIKE LINE OF rt_folders, LIKE LINE OF rt_folders, LIKE LINE OF it_expanded. LOOP AT it_expanded ASSIGNING . READ TABLE rt_folders WITH KEY path = -path TRANSPORTING NO FIELDS. IF sy-subrc <> 0. APPEND INITIAL LINE TO rt_folders ASSIGNING . -path = -path. ENDIF. ENDLOOP. * add empty folders LOOP AT rt_folders ASSIGNING . SPLIT -path AT '/' INTO TABLE lt_paths. CLEAR lv_path. LOOP AT lt_paths INTO lv_split. CONCATENATE lv_path lv_split '/' INTO lv_path. READ TABLE rt_folders WITH KEY path = lv_path TRANSPORTING NO FIELDS. IF sy-subrc <> 0. APPEND INITIAL LINE TO rt_folders ASSIGNING . -path = lv_path. ENDIF. ENDLOOP. ENDLOOP. LOOP AT rt_folders ASSIGNING . FIND ALL OCCURRENCES OF '/' IN -path MATCH COUNT -count. ENDLOOP. ENDMETHOD. METHOD full_tree. DATA: ls_object LIKE LINE OF it_objects, ls_commit TYPE zcl_abapgit_git_pack=>ty_commit. READ TABLE it_objects INTO ls_object WITH KEY type COMPONENTS type = zif_abapgit_definitions=>c_type-commit sha1 = iv_branch. IF sy-subrc <> 0. zcx_abapgit_exception=>raise( 'commit not found' ). ENDIF. ls_commit = zcl_abapgit_git_pack=>decode_commit( ls_object-data ). rt_expanded = walk_tree( it_objects = it_objects iv_tree = ls_commit-tree iv_base = '/' ). ENDMETHOD. METHOD pull. DATA: ls_object LIKE LINE OF rs_result-objects, ls_commit TYPE zcl_abapgit_git_pack=>ty_commit. zcl_abapgit_git_transport=>upload_pack( EXPORTING iv_url = iv_url iv_branch_name = iv_branch_name IMPORTING et_objects = rs_result-objects ev_branch = rs_result-branch ). READ TABLE rs_result-objects INTO ls_object WITH KEY type COMPONENTS type = zif_abapgit_definitions=>c_type-commit sha1 = rs_result-branch. IF sy-subrc <> 0. zcx_abapgit_exception=>raise( 'Commit/branch not found' ). ENDIF. ls_commit = zcl_abapgit_git_pack=>decode_commit( ls_object-data ). walk( EXPORTING it_objects = rs_result-objects iv_sha1 = ls_commit-tree iv_path = '/' CHANGING ct_files = rs_result-files ). ENDMETHOD. METHOD push. DATA: lt_expanded TYPE zif_abapgit_definitions=>ty_expanded_tt, lt_blobs TYPE zif_abapgit_definitions=>ty_files_tt, lv_sha1 TYPE zif_abapgit_definitions=>ty_sha1, lv_new_tree TYPE zif_abapgit_definitions=>ty_sha1, lt_trees TYPE ty_trees_tt, lt_stage TYPE zcl_abapgit_stage=>ty_stage_tt. FIELD-SYMBOLS: LIKE LINE OF lt_stage, LIKE LINE OF rs_result-updated_files, LIKE LINE OF lt_expanded. lt_expanded = full_tree( it_objects = it_old_objects iv_branch = iv_parent ). lt_stage = io_stage->get_all( ). LOOP AT lt_stage ASSIGNING . "" Save file ref to updated files table APPEND INITIAL LINE TO rs_result-updated_files ASSIGNING . MOVE-CORRESPONDING -file TO . CASE -method. WHEN zcl_abapgit_stage=>c_method-add. APPEND -file TO lt_blobs. READ TABLE lt_expanded ASSIGNING WITH KEY name = -file-filename path = -file-path. IF sy-subrc <> 0. "" new files APPEND INITIAL LINE TO lt_expanded ASSIGNING . -name = -file-filename. -path = -file-path. -chmod = zif_abapgit_definitions=>c_chmod-file. ENDIF. lv_sha1 = zcl_abapgit_hash=>sha1( iv_type = zif_abapgit_definitions=>c_type-blob iv_data = -file-data ). IF -sha1 <> lv_sha1. -sha1 = lv_sha1. ENDIF. -sha1 = lv_sha1. ""New sha1 WHEN zcl_abapgit_stage=>c_method-rm. DELETE lt_expanded WHERE name = -file-filename AND path = -file-path. ASSERT sy-subrc = 0. CLEAR -sha1. "" Mark as deleted WHEN OTHERS. zcx_abapgit_exception=>raise( 'stage method not supported, todo' ). ENDCASE. ENDLOOP. lt_trees = build_trees( lt_expanded ). receive_pack_push( EXPORTING is_comment = is_comment it_trees = lt_trees iv_branch_name = iv_branch_name iv_url = iv_url iv_parent = iv_parent iv_parent2 = io_stage->get_merge_source( ) it_blobs = lt_blobs IMPORTING ev_new_commit = rs_result-branch et_new_objects = rs_result-new_objects ev_new_tree = lv_new_tree ). APPEND LINES OF it_old_objects TO rs_result-new_objects. walk( EXPORTING it_objects = rs_result-new_objects iv_sha1 = lv_new_tree iv_path = '/' CHANGING ct_files = rs_result-new_files ). ENDMETHOD. METHOD receive_pack_create_tag. DATA: lv_tag TYPE xstring, lt_objects TYPE zif_abapgit_definitions=>ty_objects_tt, lv_pack TYPE xstring, ls_object LIKE LINE OF lt_objects, ls_tag TYPE zcl_abapgit_git_pack=>ty_tag, lv_new_tag_sha1 TYPE zif_abapgit_definitions=>ty_sha1. * new tag ls_tag-object = is_tag-sha1. ls_tag-type = zif_abapgit_definitions=>c_type-commit. ls_tag-tag = is_tag-name. ls_tag-tagger_name = is_tag-tagger_name. ls_tag-tagger_email = is_tag-tagger_email. ls_tag-message = is_tag-message && |{ zif_abapgit_definitions=>c_newline }| && |{ zif_abapgit_definitions=>c_newline }| && is_tag-body. lv_tag = zcl_abapgit_git_pack=>encode_tag( ls_tag ). lv_new_tag_sha1 = zcl_abapgit_hash=>sha1( iv_type = zif_abapgit_definitions=>c_type-tag iv_data = lv_tag ). ls_object-sha1 = lv_new_tag_sha1. ls_object-type = zif_abapgit_definitions=>c_type-tag. ls_object-data = lv_tag. ls_object-index = 1. APPEND ls_object TO lt_objects. lv_pack = zcl_abapgit_git_pack=>encode( lt_objects ). zcl_abapgit_git_transport=>receive_pack( iv_url = iv_url iv_old = c_zero iv_new = lv_new_tag_sha1 iv_branch_name = is_tag-name iv_pack = lv_pack ). ENDMETHOD. METHOD receive_pack_push. DATA: lv_time TYPE zcl_abapgit_time=>ty_unixtime, lv_commit TYPE xstring, lv_pack TYPE xstring, ls_object LIKE LINE OF et_new_objects, ls_commit TYPE zcl_abapgit_git_pack=>ty_commit, lv_uindex TYPE sy-index. FIELD-SYMBOLS: LIKE LINE OF it_trees, LIKE LINE OF it_blobs. lv_time = zcl_abapgit_time=>get( ). READ TABLE it_trees ASSIGNING WITH KEY path = '/'. ASSERT sy-subrc = 0. * new commit ls_commit-committer = |{ is_comment-committer-name } <{ is_comment-committer-email }> { lv_time }|. IF is_comment-author-name IS NOT INITIAL. ls_commit-author = |{ is_comment-author-name } <{ is_comment-author-email }> { lv_time }|. ELSE. ls_commit-author = ls_commit-committer. ENDIF. ls_commit-tree = -sha1. ls_commit-parent = iv_parent. ls_commit-parent2 = iv_parent2. ls_commit-body = is_comment-comment. lv_commit = zcl_abapgit_git_pack=>encode_commit( ls_commit ). ls_object-sha1 = zcl_abapgit_hash=>sha1( iv_type = zif_abapgit_definitions=>c_type-commit iv_data = lv_commit ). ls_object-type = zif_abapgit_definitions=>c_type-commit. ls_object-data = lv_commit. APPEND ls_object TO et_new_objects. LOOP AT it_trees ASSIGNING . CLEAR ls_object. ls_object-sha1 = -sha1. READ TABLE et_new_objects WITH KEY type COMPONENTS type = zif_abapgit_definitions=>c_type-tree sha1 = ls_object-sha1 TRANSPORTING NO FIELDS. IF sy-subrc = 0. * two identical trees added at the same time, only add one to the pack CONTINUE. ENDIF. ls_object-type = zif_abapgit_definitions=>c_type-tree. ls_object-data = -data. lv_uindex = lv_uindex + 1. ls_object-index = lv_uindex. APPEND ls_object TO et_new_objects. ENDLOOP. LOOP AT it_blobs ASSIGNING . CLEAR ls_object. ls_object-sha1 = zcl_abapgit_hash=>sha1( iv_type = zif_abapgit_definitions=>c_type-blob iv_data = -data ). READ TABLE et_new_objects WITH KEY type COMPONENTS type = zif_abapgit_definitions=>c_type-blob sha1 = ls_object-sha1 TRANSPORTING NO FIELDS. IF sy-subrc = 0. * two identical files added at the same time, only add one blob to the pack CONTINUE. ENDIF. ls_object-type = zif_abapgit_definitions=>c_type-blob. * note -data can be empty, #1857 allow empty files - some more checks needed? ls_object-data = -data. lv_uindex = lv_uindex + 1. ls_object-index = lv_uindex. APPEND ls_object TO et_new_objects. ENDLOOP. lv_pack = zcl_abapgit_git_pack=>encode( et_new_objects ). ev_new_commit = zcl_abapgit_hash=>sha1( iv_type = zif_abapgit_definitions=>c_type-commit iv_data = lv_commit ). zcl_abapgit_git_transport=>receive_pack( iv_url = iv_url iv_old = iv_parent iv_new = ev_new_commit iv_branch_name = iv_branch_name iv_pack = lv_pack ). ev_new_tree = ls_commit-tree. ENDMETHOD. METHOD walk. DATA: lv_path TYPE string, ls_file LIKE LINE OF ct_files, lt_nodes TYPE zcl_abapgit_git_pack=>ty_nodes_tt. FIELD-SYMBOLS: LIKE LINE OF it_objects, LIKE LINE OF it_objects, LIKE LINE OF lt_nodes. READ TABLE it_objects ASSIGNING WITH KEY type COMPONENTS type = zif_abapgit_definitions=>c_type-tree sha1 = iv_sha1. IF sy-subrc <> 0. zcx_abapgit_exception=>raise( 'Walk, tree not found' ). ENDIF. lt_nodes = zcl_abapgit_git_pack=>decode_tree( -data ). LOOP AT lt_nodes ASSIGNING . IF -chmod = zif_abapgit_definitions=>c_chmod-file. READ TABLE it_objects ASSIGNING WITH KEY type COMPONENTS type = zif_abapgit_definitions=>c_type-blob sha1 = -sha1. IF sy-subrc <> 0. zcx_abapgit_exception=>raise( 'Walk, blob not found' ). ENDIF. CLEAR ls_file. ls_file-path = iv_path. ls_file-filename = -name. ls_file-data = -data. ls_file-sha1 = -sha1. APPEND ls_file TO ct_files. ENDIF. ENDLOOP. LOOP AT lt_nodes ASSIGNING WHERE chmod = zif_abapgit_definitions=>c_chmod-dir. CONCATENATE iv_path -name '/' INTO lv_path. walk( EXPORTING it_objects = it_objects iv_sha1 = -sha1 iv_path = lv_path CHANGING ct_files = ct_files ). ENDLOOP. ENDMETHOD. METHOD walk_tree. DATA: ls_object LIKE LINE OF it_objects, lt_expanded LIKE rt_expanded, lt_nodes TYPE zcl_abapgit_git_pack=>ty_nodes_tt. FIELD-SYMBOLS: LIKE LINE OF rt_expanded, LIKE LINE OF lt_nodes. READ TABLE it_objects INTO ls_object WITH KEY type COMPONENTS type = zif_abapgit_definitions=>c_type-tree sha1 = iv_tree. IF sy-subrc <> 0. zcx_abapgit_exception=>raise( 'tree not found' ). ENDIF. lt_nodes = zcl_abapgit_git_pack=>decode_tree( ls_object-data ). LOOP AT lt_nodes ASSIGNING . CASE -chmod. WHEN zif_abapgit_definitions=>c_chmod-file OR zif_abapgit_definitions=>c_chmod-executable. APPEND INITIAL LINE TO rt_expanded ASSIGNING . -path = iv_base. -name = -name. -sha1 = -sha1. -chmod = -chmod. WHEN zif_abapgit_definitions=>c_chmod-dir. lt_expanded = walk_tree( it_objects = it_objects iv_tree = -sha1 iv_base = iv_base && -name && '/' ). APPEND LINES OF lt_expanded TO rt_expanded. WHEN OTHERS. zcx_abapgit_exception=>raise( 'walk_tree: unknown chmod' ). ENDCASE. ENDLOOP. ENDMETHOD. ENDCLASS. ",6257,False,1310.7639754626452,median "[[_auth_spi]] == Authentication SPI {project_name} comes out of the box with a bunch of different authentication mechanisms: kerberos, password, and otp. These mechanisms may not meet all of your requirements and you may want to plug in your own custom ones. {project_name} provides an authentication SPI that you can use to write new plugins. The admin console supports applying, ordering, and configuring these new mechanisms. {project_name} also supports a simple registration form. Different aspects of this form can be enabled and disabled i.e. Recaptcha support can be turned off and on. The same authentication SPI can be used to add another page to the registration flow or reimplement it entirely. There's also an additional fine-grained SPI you can use to add specific validations and user extensions to the built in registration form. A required action in {project_name} is an action that a user has to perform after he authenticates. After the action is performed successfully, the user doesn't have to perform the action again. {project_name} comes with some built in required actions like ""reset password"". This action forces the user to change their password after they have logged in. You can write and plug in your own required actions. === Terms To first learn about the Authentication SPI, let's go over some of the terms used to describe it. Authentication Flow:: A flow is a container for all authentications that must happen during login or registration. If you go to the admin console authentication page, you can view all the defined flows in the system and what authenticators they are made up of. Flows can contain other flows. You can also bind a new different flow for browser login, direct grant access, and registration. Authenticator:: An authenticator is a pluggable component that hold the logic for performing the authentication or action within a flow. It is usually a singleton. Execution:: An execution is an object that binds the authenticator to the flow and the authenticator to the configuration of the authenticator. Flows contain execution entries. Execution Requirement:: Each execution defines how an authenticator behaves in a flow. The requirement defines whether the authenticator is enabled, disabled, conditional, required, or an alternative. An alternative requirement means that the authenticator is enough to validate the flow it's in, but isn't necessary. For example, in the built-in browser flow, cookie authentication, the Identity Provider Redirector, and the set of all authenticators in the forms subflow are all alternative. As they are executed in a sequential top-to-bottom order, if one of them is successful, the flow is successful, and any following execution in the flow (or sub-flow) is not evaluated. Authenticator Config:: This object defines the configuration for the Authenticator for a specific execution within an authentication flow. Each execution can have a different config. Required Action:: After authentication completes, the user might have one or more one-time actions he must complete before he is allowed to login. The user might be required to set up an OTP token generator or reset an expired password or even accept a Terms and Conditions document. === Algorithm Overview Let's talk about how this all works for browser login. Let's assume the following flows, executions and sub flows. [source] ---- Cookie - ALTERNATIVE Kerberos - ALTERNATIVE Forms subflow - ALTERNATIVE Username/Password Form - REQUIRED Conditional OTP subflow - CONDITIONAL Condition - User Configured - REQUIRED OTP Form - REQUIRED ---- In the top level of the form we have 3 executions of which all are alternatively required. This means that if any of these are successful, then the others do not have to execute. The Username/Password form is not executed if there is an SSO Cookie set or a successful Kerberos login. Let's walk through the steps from when a client first redirects to keycloak to authenticate the user. . The OpenID Connect or SAML protocol provider unpacks relevant data, verifies the client and any signatures. It creates an AuthenticationSessionModel. It looks up what the browser flow should be, then starts executing the flow. . The flow looks at the cookie execution and sees that it is an alternative. It loads the cookie provider. It checks to see if the cookie provider requires that a user already be associated with the authentication session. Cookie provider does not require a user. If it did, the flow would abort and the user would see an error screen. Cookie provider then executes. Its purpose is to see if there is an SSO cookie set. If there is one set, it is validated and the UserSessionModel is verified and associated with the AuthenticationSessionModel. The Cookie provider returns a success() status if the SSO cookie exists and is validated. Since the cookie provider returned success and each execution at this level of the flow is ALTERNATIVE, no other execution is executed and this results in a successful login. If there is no SSO cookie, the cookie provider returns with a status of attempted(). This means there was no error condition, but no success either. The provider tried, but the request just wasn't set up to handle this authenticator. . Next the flow looks at the Kerberos execution. This is also an alternative. The kerberos provider also does not require a user to be already set up and associated with the AuthenticationSessionModel so this provider is executed. Kerberos uses the SPNEGO browser protocol. This requires a series of challenge/responses between the server and client exchanging negotiation headers. The kerberos provider does not see any negotiate header, so it assumes that this is the first interaction between the server and client. It therefore creates an HTTP challenge response to the client and sets a forceChallenge() status. A forceChallenge() means that this HTTP response cannot be ignored by the flow and must be returned to the client. If instead the provider returned a challenge() status, the flow would hold the challenge response until all other alternatives are attempted. So, in this initial phase, the flow would stop and the challenge response would be sent back to the browser. If the browser then responds with a successful negotiate header, the provider associates the user with the AuthenticationSession and the flow ends because the rest of the executions on this level of the flow are all alternatives. Otherwise, again, the kerberos provider sets an attempted() status and the flow continues. . The next execution is a subflow called Forms. The executions for this subflow are loaded and the same processing logic occurs. . The first execution in the Forms subflow is the UsernamePassword provider. This provider also does not require for a user to already be associated with the flow. This provider creates a challenge HTTP response and sets its status to challenge(). This execution is required, so the flow honors this challenge and sends the HTTP response back to the browser. This response is a rendering of the Username/Password HTML page. The user enters in their username and password and clicks submit. This HTTP request is directed to the UsernamePassword provider. If the user entered an invalid username or password, a new challenge response is created and a status of failureChallenge() is set for this execution. A failureChallenge() means that there is a challenge, but that the flow should log this as an error in the error log. This error log can be used to lock accounts or IP Addresses that have had too many login failures. If the username and password is valid, the provider associated the UserModel with the AuthenticationSessionModel and returns a status of success(). . The next execution is a subflow called Conditional OTP. The executions for this subflow are loaded and the same processing logic occurs. Its Requirement is Conditional. This means that the flow will first evaluate all conditional executors that it contains. Conditional executors are authenticators that implement `ConditionalAuthenticator`, and must implement the method `boolean matchCondition(AuthenticationFlowContext context)`. A conditional subflow will call the `matchCondition` method of all conditional executions it contains, and if all of them evaluate to true, it will act as if it was a required subflow. If not, it will act as if it was a disabled subflow. Conditional authenticators are only used for this purpose, and are not used as authenticators. This means that even if the conditional authenticator evaluates to ""true"", then this will not mark a flow or subflow as successful. For example, a flow containing only a Conditional subflow with only a conditional authenticator will never allow a user to log in. . The first execution of the Conditional OTP subflow is the Condition - User Configured. This provider requires that a user has been associated with the flow. This requirement is satisfied because the UsernamePassword provider already associated the user with the flow. This provider's `matchCondition` method will evaluate the `configuredFor` method for all other Authenticators in its current subflow. If the subflow contains executors with their Requirement set to required, then the `matchCondition` method will only evaluate to true if all the required authenticators' `configuredFor` method evaluate to true. Otherwise, the `matchCondition` method will evaluate to true if any alternative authenticator evaluates to true. . The next execution is the OTP Form. This provider also requires that a user has been associated with the flow. This requirement is satisfied because the UsernamePassword provider already associated the user with the flow. Since a user is required for this provider, the provider is also asked if the user is configured to use this provider. If user is not configured, then the flow will then set up a required action that the user must perform after authentication is complete. For OTP, this means the OTP setup page. If the user is configured, he will be asked to enter his otp code. In our scenario, because of the conditional sub-flow, the user will never see the OTP login page, unless the Conditional OTP subflow is set to Required. . After the flow is complete, the authentication processor creates a UserSessionModel and associates it with the AuthenticationSessionModel. It then checks to see if the user is required to complete any required actions before logging in. . First, each required action's evaluateTriggers() method is called. This allows the required action provider to figure out if there is some state that might trigger the action to be fired. For example, if your realm has a password expiration policy, it might be triggered by this method. . Each required action associated with the user that has its requiredActionChallenge() method called. Here the provider sets up an HTTP response which renders the page for the required action. This is done by setting a challenge status. . If the required action is ultimately successful, then the required action is removed from the user's required actions list. . After all required actions have been resolved, the user is finally logged in. [[_auth_spi_walkthrough]] === Authenticator SPI Walk Through In this section, we'll take a look at the Authenticator interface. For this, we are going to implement an authenticator that requires that a user enter in the answer to a secret question like ""What is your mother's maiden name?"". This example is fully implemented and contained in the examples/providers/authenticator directory of the demo distribution of {project_name}. To create an authenticator, you must at minimum implement the org.keycloak.authentication.AuthenticatorFactory and Authenticator interfaces. The Authenticator interface defines the logic. The AuthenticatorFactory is responsible for creating instances of an Authenticator. They both extend a more generic Provider and ProviderFactory set of interfaces that other {project_name} components like User Federation do. Some authenticators, like the CookieAuthenticator don't rely on a Credential that the user has or knows to authenticate the user. However, some authenticators, such as the PasswordForm authenticator or the OTPFormAuthenticator rely on the user inputting some information and verifying that information against some information in the database. For the PasswordForm for example, the authenticator will verify the hash of the password against a hash stored in the database, while the OTPFormAuthenticator will verify the OTP received against the one generated from the shared secret stored in the database. These types of authenticators are called CredentialValidators, and will require you to implement a few more classes: * A class that extends org.keycloak.credential.CredentialModel, and that can generate the correct format of the credential in the database * A class implementing the org.keycloak.credential.CredentialProvider and interface, and a class implementing its CredentialProviderFactory factory interface. The SecretQuestionAuthenticator we'll see in this walk through is a CredentialValidator, so we'll see how to implement all these classes. ==== Packaging Classes and Deployment You will package your classes within a single jar. This jar must contain a file named `org.keycloak.authentication.AuthenticatorFactory` and must be contained in the `META-INF/services/` directory of your jar. This file must list the fully qualified class name of each AuthenticatorFactory implementation you have in the jar. For example: [source,java] ---- org.keycloak.examples.authenticator.SecretQuestionAuthenticatorFactory org.keycloak.examples.authenticator.AnotherProviderFactory ---- This services/ file is used by {project_name} to scan the providers it has to load into the system. To deploy this jar, just copy it to the providers directory. ==== Extending the CredentialModel class In {project_name}, credentials are stored in the database in the Credentials table. It has the following structure: ---- ----------------------------- | ID | ----------------------------- | user_ID | ----------------------------- | credential_type | ----------------------------- | created_date | ----------------------------- | user_label | ----------------------------- | secret_data | ----------------------------- | credential_data | ----------------------------- | priority | ----------------------------- ---- Where: * `ID` is the primary key of the credential. * `user_ID` is the foreign key linking the credential to a user. * `credential_type` is a string set during the creation that must reference an existing credential type. * `created_date` is the creation timestamp (in long format) of the credential. * `user_label` is the editable name of the credential by the user * `secret_data` contains a static json with the information that cannot be transmitted outside of {project_name} * `credential_data` contains a json with the static information of the credential that can be shared in the admin console or via the REST API. * `priority` defines how ""preferred"" a credential is for a user, to determine which credential to present when a user has multiple choices. As the secret_data and credential_data fields are designed to contain json, it is up to you to determine how to structure, read and write into these fields, allowing you a lot of flexibility. For this example, we are going to use a very simple credential data, containing only the question asked to the user: [source] ---- { ""question"":""aQuestion"" } ---- with an equally simple secret data, containing only the secret answer: [source] ---- { ""answer"":""anAnswer"" } ---- Here the answer will be kept in plain text in the database for the sake of simplicity, but it would also be possible to have a salted hash for the answer, as is the case for passwords in {project_name}. In this case, the secret data would also have to contain a field for the salt, and the credential data information about the algorithm such as the type of algorithm used and the number of iterations used. For more details you can consult the implementation of the `org.keycloak.models.credential.PasswordCredentialModel` class. In our case we create the class `SecretQuestionCredentialModel`: [source,java] ---- public class SecretQuestionCredentialModel extends CredentialModel { public static final String TYPE = ""SECRET_QUESTION""; private final SecretQuestionCredentialData credentialData; private final SecretQuestionSecretData secretData; ---- Where `TYPE` is the credential_type we write in the database. For consistency, we make sure that this String is always the one referenced when getting the type for this credential. The classes `SecretQuestionCredentialData` and `SecretQuestionSecretData` are used to marshal and unmarshal the json: [source,java] ---- public class SecretQuestionCredentialData { private final String question; @JsonCreator public SecretQuestionCredentialData(@JsonProperty(""question"") String question) { this.question = question; } public String getQuestion() { return question; } } ---- [source,java] ---- public class SecretQuestionSecretData { private final String answer; @JsonCreator public SecretQuestionSecretData(@JsonProperty(""answer"") String answer) { this.answer = answer; } public String getAnswer() { return answer; } } ---- To be fully usable, the `SecretQuestionCredentialModel` objects must both contain the raw json data from its parent class, and the unmarshalled objects in its own attributes. This leads us to create a method which reads from a simple CredentialModel, such as is created when reading from the database, to make a `SecretQuestionCredentialModel`: [source,java] ---- private SecretQuestionCredentialModel(SecretQuestionCredentialData credentialData, SecretQuestionSecretData secretData) { this.credentialData = credentialData; this.secretData = secretData; } public static SecretQuestionCredentialModel createFromCredentialModel(CredentialModel credentialModel){ try { SecretQuestionCredentialData credentialData = JsonSerialization.readValue(credentialModel.getCredentialData(), SecretQuestionCredentialData.class); SecretQuestionSecretData secretData = JsonSerialization.readValue(credentialModel.getSecretData(), SecretQuestionSecretData.class); SecretQuestionCredentialModel secretQuestionCredentialModel = new SecretQuestionCredentialModel(credentialData, secretData); secretQuestionCredentialModel.setUserLabel(credentialModel.getUserLabel()); secretQuestionCredentialModel.setCreatedDate(credentialModel.getCreatedDate()); secretQuestionCredentialModel.setType(TYPE); secretQuestionCredentialModel.setId(credentialModel.getId()); secretQuestionCredentialModel.setSecretData(credentialModel.getSecretData()); secretQuestionCredentialModel.setCredentialData(credentialModel.getCredentialData()); return secretQuestionCredentialModel; } catch (IOException e){ throw new RuntimeException(e); } } ---- And a method to create a `SecretQuestionCredentialModel` from the question and answer: [source,java] ---- private SecretQuestionCredentialModel(String question, String answer) { credentialData = new SecretQuestionCredentialData(question); secretData = new SecretQuestionSecretData(answer); } public static SecretQuestionCredentialModel createSecretQuestion(String question, String answer) { SecretQuestionCredentialModel credentialModel = new SecretQuestionCredentialModel(question, answer); credentialModel.fillCredentialModelFields(); return credentialModel; } private void fillCredentialModelFields(){ try { setCredentialData(JsonSerialization.writeValueAsString(credentialData)); setSecretData(JsonSerialization.writeValueAsString(secretData)); setType(TYPE); setCreatedDate(Time.currentTimeMillis()); } catch (IOException e) { throw new RuntimeException(e); } } ---- ==== Implementing a CredentialProvider As with all Providers, to allow {project_name} to generate the CredentialProvider, we require a CredentialProviderFactory. For this requirement we create the SecretQuestionCredentialProviderFactory, whose `create` method will be called when a SecretQuestionCredentialProvider is asked for: [source,java] ---- public class SecretQuestionCredentialProviderFactory implements CredentialProviderFactory { public static final String PROVIDER_ID = ""secret-question""; @Override public String getId() { return PROVIDER_ID; } @Override public CredentialProvider create(KeycloakSession session) { return new SecretQuestionCredentialProvider(session); } } ---- The CredentialProvider interface takes a generic parameter that extends a CredentialModel. In our case we to use the SecretQuestionCredentialModel we created: [source,java] ---- public class SecretQuestionCredentialProvider implements CredentialProvider, CredentialInputValidator { private static final Logger logger = Logger.getLogger(SecretQuestionCredentialProvider.class); protected KeycloakSession session; public SecretQuestionCredentialProvider(KeycloakSession session) { this.session = session; } private UserCredentialStore getCredentialStore() { return session.userCredentialManager(); } ---- We also want to implement the CredentialInputValidator interface, as this allows {project_name} to know that this provider can also be used to validate a credential for an Authenticator. For the CredentialProvider interface, the first method that needs to be implemented is the `getType()` method. This will simply return the `SecretQuestionCredentialModel`'s TYPE String: [source,java] ---- @Override public String getType() { return SecretQuestionCredentialModel.TYPE; } ---- The second method is to create a `SecretQuestionCredentialModel` from a `CredentialModel`. For this method we simply call the existing static method from `SecretQuestionCredentialModel`: [source,java] ---- @Override public SecretQuestionCredentialModel getCredentialFromModel(CredentialModel model) { return SecretQuestionCredentialModel.createFromCredentialModel(model); } ---- Finally, we have the methods to create a credential and delete a credential. These methods call the KeycloakSession's `userCredentialManager`, which is responsible for knowing where to read or write the credential, for example local storage or federated storage. [source,java] ---- @Override public CredentialModel createCredential(RealmModel realm, UserModel user, SecretQuestionCredentialModel credentialModel) { if (credentialModel.getCreatedDate() == null) { credentialModel.setCreatedDate(Time.currentTimeMillis()); } return getCredentialStore().createCredential(realm, user, credentialModel); } @Override public void deleteCredential(RealmModel realm, UserModel user, String credentialId) { getCredentialStore().removeStoredCredential(realm, user, credentialId); } ---- For the CredentialInputValidator, the main method to implement is the `isValid`, which tests whether a credential is valid for a given user in a given realm. This is the method that is called by the Authenticator when it seeks to validate the user's input. Here we simply need to check that the input String is the one recorded in the Credential: [source,java] ---- @Override public boolean isValid(RealmModel realm, UserModel user, CredentialInput input) { if (!(input instanceof UserCredentialModel)) { logger.debug(""Expected instance of UserCredentialModel for CredentialInput""); return false; } if (!input.getType().equals(getType())) { return false; } String challengeResponse = input.getChallengeResponse(); if (challengeResponse == null) { return false; } CredentialModel credentialModel = getCredentialStore().getStoredCredentialById(realm, user, input.getCredentialId()); SecretQuestionCredentialModel sqcm = getCredentialFromModel(credentialModel); return sqcm.getSecretQuestionSecretData().getAnswer().equals(challengeResponse); } ---- The other two methods to implement are a test if the CredentialProvider supports the given credential type and a test to check if the credential type is configured for a given user. For our case, the latter test simply means checking if the user has a credential of the SECRET_QUESTION type: [source,java] ---- @Override public boolean supportsCredentialType(String credentialType) { return getType().equals(credentialType); } @Override public boolean isConfiguredFor(RealmModel realm, UserModel user, String credentialType) { if (!supportsCredentialType(credentialType)) return false; return !getCredentialStore().getStoredCredentialsByType(realm, user, credentialType).isEmpty(); } ---- ==== Implementing an Authenticator When implementing an authenticator that uses Credentials to authenticate a user, you should have the authenticator implement the CredentialValidator interface. This interfaces takes a class extending a CredentialProvider as a parameter, and will allow {project_name} to directly call the methods from the CredentialProvider. The only method that needs to be implemented is `getCredentialProvider` method, which in our example allows the SecretQuestionAuthenticator to retrieve the SecretQuestionCredentialProvider: [source,java] ---- public SecretQuestionCredentialProvider getCredentialProvider(KeycloakSession session) { return (SecretQuestionCredentialProvider)session.getProvider(CredentialProvider.class, SecretQuestionCredentialProviderFactory.PROVIDER_ID); } ---- When implementing the Authenticator interface, the first method that needs to be implemented is the requiresUser() method. For our example, this method must return true as we need to validate the secret question associated with the user. A provider like kerberos would return false from this method as it can resolve a user from the negotiate header. This example, however, is validating a specific credential of a specific user. The next method to implement is the configuredFor() method. This method is responsible for determining if the user is configured for this particular authenticator. In our case, we can just call the method implemented in the SecretQuestionCredentialProvider [source,java] ---- @Override public boolean configuredFor(KeycloakSession session, RealmModel realm, UserModel user) { return getCredentialProvider(session).isConfiguredFor(realm, user, getType(session)); } ---- The next method to implement on the Authenticator is setRequiredActions(). If configuredFor() returns false and our example authenticator is required within the flow, this method will be called, but only if the associated AuthenticatorFactory's `isUserSetupAllowed` method returns true. The setRequiredActions() method is responsible for registering any required actions that must be performed by the user. In our example, we need to register a required action that will force the user to set up the answer to the secret question. We will implement this required action provider later in this chapter. Here is the implementation of the setRequiredActions() method. [source,java] ---- @Override public void setRequiredActions(KeycloakSession session, RealmModel realm, UserModel user) { user.addRequiredAction(""SECRET_QUESTION_CONFIG""); } ---- Now we are getting into the meat of the Authenticator implementation. The next method to implement is authenticate(). This is the initial method the flow invokes when the execution is first visited. What we want is that if a user has answered the secret question already on their browser's machine, then the user doesn't have to answer the question again, making that machine ""trusted"". The authenticate() method isn't responsible for processing the secret question form. Its sole purpose is to render the page or to continue the flow. [source,java] ---- @Override public void authenticate(AuthenticationFlowContext context) { if (hasCookie(context)) { context.success(); return; } Response challenge = context.form() .createForm(""secret-question.ftl""); context.challenge(challenge); } protected boolean hasCookie(AuthenticationFlowContext context) { Cookie cookie = context.getHttpRequest().getHttpHeaders().getCookies().get(""SECRET_QUESTION_ANSWERED""); boolean result = cookie != null; if (result) { System.out.println(""Bypassing secret question because cookie is set""); } return result; } ---- The hasCookie() method checks to see if there is already a cookie set on the browser which indicates that the secret question has already been answered. If that returns true, we just mark this execution's status as SUCCESS using the AuthenticationFlowContext.success() method and returning from the authentication() method. If the hasCookie() method returns false, we must return a response that renders the secret question HTML form. AuthenticationFlowContext has a form() method that initializes a Freemarker page builder with appropriate base information needed to build the form. This page builder is called `org.keycloak.login.LoginFormsProvider`. The LoginFormsProvider.createForm() method loads a Freemarker template file from your login theme. Additionally you can call the LoginFormsProvider.setAttribute() method if you want to pass additional information to the Freemarker template. We'll go over this later. Calling LoginFormsProvider.createForm() returns a JAX-RS Response object. We then call AuthenticationFlowContext.challenge() passing in this response. This sets the status of the execution as CHALLENGE and if the execution is Required, this JAX-RS Response object will be sent to the browser. So, the HTML page asking for the answer to a secret question is displayed to the user and the user enters in the answer and clicks submit. The action URL of the HTML form will send an HTTP request to the flow. The flow will end up invoking the action() method of our Authenticator implementation. [source,java] ---- @Override public void action(AuthenticationFlowContext context) { boolean validated = validateAnswer(context); if (!validated) { Response challenge = context.form() .setError(""badSecret"") .createForm(""secret-question.ftl""); context.failureChallenge(AuthenticationFlowError.INVALID_CREDENTIALS, challenge); return; } setCookie(context); context.success(); } ---- If the answer is not valid, we rebuild the HTML Form with an additional error message. We then call AuthenticationFlowContext.failureChallenge() passing in the reason for the value and the JAX-RS response. failureChallenge() works the same as challenge(), but it also records the failure so it can be analyzed by any attack detection service. If validation is successful, then we set a cookie to remember that the secret question has been answered and we call AuthenticationFlowContext.success(). The validation itself gets the data that was received from the form, and calls the isValid method from the SecretQuestionCredentialProvider. You'll notice that there's a section of the code concerning getting the credential Id. This is because if {project_name} is configured to allow multiple types of alternative authenticators, or if the user could record multiple credentials of the SECRET_QUESTION type (for example if we allowed to choose from several questions, and we allowed the user to have answers for more than one of those questions), then {project_name} needs to know which credential is being used to log the user. In case there is more than one credential, {project_name} allows the user to choose during the login which credential is being used, and the information is transmitted by the form to the Authenticator. In case the form doesn't present this information, credential id used is given by the CredentialProvider's `default getDefaultCredential` method, which will return the ""most preferred"" credential of the correct type of the user, [source,java] ---- protected boolean validateAnswer(AuthenticationFlowContext context) { MultivaluedMap formData = context.getHttpRequest().getDecodedFormParameters(); String secret = formData.getFirst(""secret_answer""); String credentialId = context.getSelectedCredentialId(); if (credentialId == null || credentialId.isEmpty()) { credentialId = getCredentialProvider(context.getSession()) .getDefaultCredential(context.getSession(), context.getRealm(), context.getUser()).getId(); context.setSelectedCredentialId(credentialId); } UserCredentialModel input = new UserCredentialModel(credentialId, getType(context.getSession()), secret); return getCredentialProvider(context.getSession()).isValid(context.getRealm(), context.getUser(), input); } ---- The last thing to go over is the setCookie() method. This is an example of providing configuration for the Authenticator. In this case we want the max age of the cookie to be configurable. [source,java] ---- protected void setCookie(AuthenticationFlowContext context) { AuthenticatorConfigModel config = context.getAuthenticatorConfig(); int maxCookieAge = 60 * 60 * 24 * 30; // 30 days if (config != null) { maxCookieAge = Integer.valueOf(config.getConfig().get(""cookie.max.age"")); } URI uri = context.getUriInfo().getBaseUriBuilder().path(""realms"").path(context.getRealm().getName()).build(); addCookie(context, ""SECRET_QUESTION_ANSWERED"", ""true"", uri.getRawPath(), null, null, maxCookieAge, false, true); } ---- We obtain an AuthenticatorConfigModel from the AuthenticationFlowContext.getAuthenticatorConfig() method. If configuration exists we pull the max age config out of it. We will see how we can define what should be configured when we talk about the AuthenticatorFactory implementation. The config values can be defined within the admin console if you set up config definitions in your AuthenticatorFactory implementation. ==== Implementing an AuthenticatorFactory The next step in this process is to implement an AuthenticatorFactory. This factory is responsible for instantiating an Authenticator. It also provides deployment and configuration metadata about the Authenticator. The getId() method is just the unique name of the component. The create() method is called by the runtime to allocate and process the Authenticator. [source,java] ---- public class SecretQuestionAuthenticatorFactory implements AuthenticatorFactory, ConfigurableAuthenticatorFactory { public static final String PROVIDER_ID = ""secret-question-authenticator""; private static final SecretQuestionAuthenticator SINGLETON = new SecretQuestionAuthenticator(); @Override public String getId() { return PROVIDER_ID; } @Override public Authenticator create(KeycloakSession session) { return SINGLETON; } ---- The next thing the factory is responsible for is to specify the allowed requirement switches. While there are four different requirement types: ALTERNATIVE, REQUIRED, CONDITIONAL, DISABLED, AuthenticatorFactory implementations can limit which requirement options are shown in the admin console when defining a flow. CONDITIONAL should only always be used for subflows, and unless there's a good reason for doing otherwise, the requirement on a authenticator should be REQUIRED, ALTERNATIVE and DISABLED: [source,java] ---- private static AuthenticationExecutionModel.Requirement[] REQUIREMENT_CHOICES = { AuthenticationExecutionModel.Requirement.REQUIRED, AuthenticationExecutionModel.Requirement.ALTERNATIVE, AuthenticationExecutionModel.Requirement.DISABLED }; @Override public AuthenticationExecutionModel.Requirement[] getRequirementChoices() { return REQUIREMENT_CHOICES; } ---- The AuthenticatorFactory.isUserSetupAllowed() is a flag that tells the flow manager whether or not Authenticator.setRequiredActions() method will be called. If an Authenticator is not configured for a user, the flow manager checks isUserSetupAllowed(). If it is false, then the flow aborts with an error. If it returns true, then the flow manager will invoke Authenticator.setRequiredActions(). [source,java] ---- @Override public boolean isUserSetupAllowed() { return true; } ---- The next few methods define how the Authenticator can be configured. The isConfigurable() method is a flag which specifies to the admin console on whether the Authenticator can be configured within a flow. The getConfigProperties() method returns a list of ProviderConfigProperty objects. These objects define a specific configuration attribute. [source,java] ---- @Override public List getConfigProperties() { return configProperties; } private static final List configProperties = new ArrayList(); static { ProviderConfigProperty property; property = new ProviderConfigProperty(); property.setName(""cookie.max.age""); property.setLabel(""Cookie Max Age""); property.setType(ProviderConfigProperty.STRING_TYPE); property.setHelpText(""Max age in seconds of the SECRET_QUESTION_COOKIE.""); configProperties.add(property); } ---- Each ProviderConfigProperty defines the name of the config property. This is the key used in the config map stored in AuthenticatorConfigModel. The label defines how the config option will be displayed in the admin console. The type defines if it is a String, Boolean, or other type. The admin console will display different UI inputs depending on the type. The help text is what will be shown in the tooltip for the config attribute in the admin console. Read the javadoc of ProviderConfigProperty for more detail. The rest of the methods are for the admin console. getHelpText() is the tooltip text that will be shown when you are picking the Authenticator you want to bind to an execution. getDisplayType() is the text that will be shown in the admin console when listing the Authenticator. getReferenceCategory() is just a category the Authenticator belongs to. ==== Adding Authenticator Form {project_name} comes with a Freemarker <<_themes,theme and template engine>>. The createForm() method you called within authenticate() of your Authenticator class, builds an HTML page from a file within your login theme: `secret-question.ftl`. This file should be added to the `theme-resources/templates` in your JAR, see <<_theme_resource,Theme Resource Provider>> for more details. Let's take a bigger look at secret-question.ftl Here's a small code snippet: [source,java] ----
---- Any piece of text enclosed in `${}` corresponds to an attribute or template funtion. If you see the form's action, you see it points to `${url.loginAction}`. This value is automatically generated when you invoke the AuthenticationFlowContext.form() method. You can also obtain this value by calling the AuthenticationFlowContext.getActionURL() method in Java code. You'll also see `${properties.someValue}`. These correspond to properties defined in your theme.properties file of our theme. `${msg(""someValue"")}` corresponds to the internationalized message bundles (.properties files) included with the login theme messages/ directory. If you're just using english, you can just add the value of the `loginSecretQuestion`. This should be the question you want to ask the user. When you call AuthenticationFlowContext.form() this gives you a LoginFormsProvider instance. If you called, `LoginFormsProvider.setAttribute(""foo"", ""bar"")`, the value of ""foo"" would be available for reference in your form as `${foo}`. The value of an attribute can be any Java bean as well. If you look at the top of the file, you'll see that we are importing a template: [source,java] ---- <#import ""select.ftl"" as layout> ---- Importing this template, instead of the standard `template.ftl` allows {project_name} to display a dropdown box that allows the user to select a different credential or execution. [[_adding_authenticator]] ==== Adding Authenticator to a Flow Adding an Authenticator to a flow must be done in the admin console. If you go to the Authentication menu item and go to the Flow tab, you will be able to view the currently defined flows. You cannot modify built in flows, so, to add the Authenticator we've created you have to copy an existing flow or create your own. I'm hoping the UI is intuitive enough so that you can figure out for yourself how to create a flow and add the Authenticator. After you've created your flow, you have to bind it to the login action you want to bind it to. If you go to the Authentication menu and go to the Bindings tab you will see options to bind a flow to the browser, registration, or direct grant flow. === Required Action Walkthrough In this section we will discuss how to define a required action. In the Authenticator section you may have wondered, ""How will we get the user's answer to the secret question entered into the system?"". As we showed in the example, if the answer is not set up, a required action will be triggered. This section discusses how to implement the required action for the Secret Question Authenticator. ==== Packaging Classes and Deployment You will package your classes within a single jar. This jar does not have to be separate from other provider classes but it must contain a file named `org.keycloak.authentication.RequiredActionFactory` and must be contained in the `META-INF/services/` directory of your jar. This file must list the fully qualified classname of each RequiredActionFactory implementation you have in the jar. For example: [source,java] ---- org.keycloak.examples.authenticator.SecretQuestionRequiredActionFactory ---- This services/ file is used by {project_name} to scan the providers it has to load into the system. To deploy this jar, just copy it to the `standalone/deployments` directory. ==== Implement the RequiredActionProvider Required actions must first implement the RequiredActionProvider interface. The RequiredActionProvider.requiredActionChallenge() is the initial call by the flow manager into the required action. This method is responsible for rendering the HTML form that will drive the required action. [source,java] ---- @Override public void requiredActionChallenge(RequiredActionContext context) { Response challenge = context.form().createForm(""secret_question_config.ftl""); context.challenge(challenge); } ---- You see that RequiredActionContext has similar methods to AuthenticationFlowContext. The form() method allows you to render the page from a Freemarker template. The action URL is preset by the call to this form() method. You just need to reference it within your HTML form. I'll show you this later. The challenge() method notifies the flow manager that a required action must be executed. The next method is responsible for processing input from the HTML form of the required action. The action URL of the form will be routed to the RequiredActionProvider.processAction() method [source,java] ---- @Override public void processAction(RequiredActionContext context) { String answer = (context.getHttpRequest().getDecodedFormParameters().getFirst(""answer"")); UserCredentialValueModel model = new UserCredentialValueModel(); model.setValue(answer); model.setType(SecretQuestionAuthenticator.CREDENTIAL_TYPE); context.getUser().updateCredentialDirectly(model); context.success(); } ---- The answer is pulled out of the form post. A UserCredentialValueModel is created and the type and value of the credential are set. Then UserModel.updateCredentialDirectly() is invoked. Finally, RequiredActionContext.success() notifies the container that the required action was successful. ==== Implement the RequiredActionFactory This class is really simple. It is just responsible for creating the required action provider instance. [source,java] ---- public class SecretQuestionRequiredActionFactory implements RequiredActionFactory { private static final SecretQuestionRequiredAction SINGLETON = new SecretQuestionRequiredAction(); @Override public RequiredActionProvider create(KeycloakSession session) { return SINGLETON; } @Override public String getId() { return SecretQuestionRequiredAction.PROVIDER_ID; } @Override public String getDisplayText() { return ""Secret Question""; } ---- The getDisplayText() method is just for the admin console when it wants to display a friendly name for the required action. ==== Enable Required Action The final thing you have to do is go into the admin console. Click on the Authentication left menu. Click on the Required Actions tab. Click on the Register button and choose your new Required Action. Your new required action should now be displayed and enabled in the required actions list. === Modifying/Extending the Registration Form It is entirely possible for you to implement your own flow with a set of Authenticators to totally change how registration is done in {project_name}. But what you'll usually want to do is just add a little bit of validation to the out of the box registration page. An additional SPI was created to be able to do this. It basically allows you to add validation of form elements on the page as well as to initialize UserModel attributes and data after the user has been registered. We'll look at both the implementation of the user profile registration processing as well as the registration Google Recaptcha plugin. ==== Implementation FormAction Interface The core interface you have to implement is the FormAction interface. A FormAction is responsible for rendering and processing a portion of the page. Rendering is done in the buildPage() method, validation is done in the validate() method, post validation operations are done in success(). Let's first take a look at buildPage() method of the Recaptcha plugin. [source,java] ---- @Override public void buildPage(FormContext context, LoginFormsProvider form) { AuthenticatorConfigModel captchaConfig = context.getAuthenticatorConfig(); if (captchaConfig == null || captchaConfig.getConfig() == null || captchaConfig.getConfig().get(SITE_KEY) == null || captchaConfig.getConfig().get(SITE_SECRET) == null ) { form.addError(new FormMessage(null, Messages.RECAPTCHA_NOT_CONFIGURED)); return; } String siteKey = captchaConfig.getConfig().get(SITE_KEY); form.setAttribute(""recaptchaRequired"", true); form.setAttribute(""recaptchaSiteKey"", siteKey); form.addScript(""https://www.google.com/recaptcha/api.js""); } ---- The Recaptcha buildPage() method is a callback by the form flow to help render the page. It receives a form parameter which is a LoginFormsProvider. You can add additional attributes to the form provider so that they can be displayed in the HTML page generated by the registration Freemarker template. The code above is from the registration recaptcha plugin. Recaptcha requires some specific settings that must be obtained from configuration. FormActions are configured in the exact same as Authenticators are. In this example, we pull the Google Recaptcha site key from configuration and add it as an attribute to the form provider. Our registration template file can read this attribute now. Recaptcha also has the requirement of loading a JavaScript script. You can do this by calling LoginFormsProvider.addScript() passing in the URL. For user profile processing, there is no additional information that it needs to add to the form, so its buildPage() method is empty. The next meaty part of this interface is the validate() method. This is called immediately upon receiving a form post. Let's look at the Recaptcha's plugin first. [source,java] ---- @Override public void validate(ValidationContext context) { MultivaluedMap formData = context.getHttpRequest().getDecodedFormParameters(); List errors = new ArrayList<>(); boolean success = false; String captcha = formData.getFirst(G_RECAPTCHA_RESPONSE); if (!Validation.isBlank(captcha)) { AuthenticatorConfigModel captchaConfig = context.getAuthenticatorConfig(); String secret = captchaConfig.getConfig().get(SITE_SECRET); success = validateRecaptcha(context, success, captcha, secret); } if (success) { context.success(); } else { errors.add(new FormMessage(null, Messages.RECAPTCHA_FAILED)); formData.remove(G_RECAPTCHA_RESPONSE); context.validationError(formData, errors); return; } } ---- Here we obtain the form data that the Recaptcha widget adds to the form. We obtain the Recaptcha secret key from configuration. We then validate the recaptcha. If successful, ValidationContext.success() is called. If not, we invoke ValidationContext.validationError() passing in the formData (so the user doesn't have to re-enter data), we also specify an error message we want displayed. The error message must point to a message bundle property in the internationalized message bundles. For other registration extensions validate() might be validating the format of a form element, i.e. an alternative email attribute. Let's also look at the user profile plugin that is used to validate email address and other user information when registering. [source,java] ---- @Override public void validate(ValidationContext context) { MultivaluedMap formData = context.getHttpRequest().getDecodedFormParameters(); List errors = new ArrayList<>(); String eventError = Errors.INVALID_REGISTRATION; if (Validation.isBlank(formData.getFirst((RegistrationPage.FIELD_FIRST_NAME)))) { errors.add(new FormMessage(RegistrationPage.FIELD_FIRST_NAME, Messages.MISSING_FIRST_NAME)); } if (Validation.isBlank(formData.getFirst((RegistrationPage.FIELD_LAST_NAME)))) { errors.add(new FormMessage(RegistrationPage.FIELD_LAST_NAME, Messages.MISSING_LAST_NAME)); } String email = formData.getFirst(Validation.FIELD_EMAIL); if (Validation.isBlank(email)) { errors.add(new FormMessage(RegistrationPage.FIELD_EMAIL, Messages.MISSING_EMAIL)); } else if (!Validation.isEmailValid(email)) { formData.remove(Validation.FIELD_EMAIL); errors.add(new FormMessage(RegistrationPage.FIELD_EMAIL, Messages.INVALID_EMAIL)); } if (context.getSession().users().getUserByEmail(email, context.getRealm()) != null) { formData.remove(Validation.FIELD_EMAIL); errors.add(new FormMessage(RegistrationPage.FIELD_EMAIL, Messages.EMAIL_EXISTS)); } if (errors.size() > 0) { context.validationError(formData, errors); return; } else { context.success(); } } ---- As you can see, this validate() method of user profile processing makes sure that the email, first, and last name are filled in the form. It also makes sure that email is in the right format. If any of these validations fail, an error message is queued up for rendering. Any fields in error are removed from the form data. Error messages are represented by the FormMessage class. The first parameter of the constructor of this class takes the HTML element id. The input in error will be highlighted when the form is re-rendered. The second parameter is a message reference id. This id must correspond to a property in one of the localized message bundle files. in the theme. After all validations have been processed then, the form flow then invokes the FormAction.success() method. For recaptcha this is a no-op, so we won't go over it. For user profile processing, this method fills in values in the registered user. [source,java] ---- @Override public void success(FormContext context) { UserModel user = context.getUser(); MultivaluedMap formData = context.getHttpRequest().getDecodedFormParameters(); user.setFirstName(formData.getFirst(RegistrationPage.FIELD_FIRST_NAME)); user.setLastName(formData.getFirst(RegistrationPage.FIELD_LAST_NAME)); user.setEmail(formData.getFirst(RegistrationPage.FIELD_EMAIL)); } ---- Pretty simple implementation. The UserModel of the newly registered user is obtained from the FormContext. The appropriate methods are called to initialize UserModel data. Finally, you are also required to define a FormActionFactory class. This class is implemented similarly to AuthenticatorFactory, so we won't go over it. ==== Packaging the Action You will package your classes within a single jar. This jar must contain a file named `org.keycloak.authentication.FormActionFactory` and must be contained in the `META-INF/services/` directory of your jar. This file must list the fully qualified class name of each FormActionFactory implementation you have in the jar. For example: [source] ---- org.keycloak.authentication.forms.RegistrationProfile org.keycloak.authentication.forms.RegistrationRecaptcha ---- This services/ file is used by {project_name} to scan the providers it has to load into the system. To deploy this jar, just copy it to the `standalone/deployments` directory. ==== Adding FormAction to the Registration Flow Adding a FormAction to a registration page flow must be done in the admin console. If you go to the Authentication menu item and go to the Flow tab, you will be able to view the currently defined flows. You cannot modify built in flows, so, to add the Authenticator we've created you have to copy an existing flow or create your own. I'm hoping the UI is intuitive enough so that you can figure out for yourself how to create a flow and add the FormAction. Basically you'll have to copy the registration flow. Then click Actions menu to the right of the Registration Form, and pick ""Add execution"" to add a new execution. You'll pick the FormAction from the selection list. Make sure your FormAction comes after ""Registration User Creation"" by using the down buttons to move it if your FormAction isn't already listed after ""Registration User Creation"". You want your FormAction to come after user creation because the success() method of Registration User Creation is responsible for creating the new UserModel. After you've created your flow, you have to bind it to registration. If you go to the Authentication menu and go to the Bindings tab you will see options to bind a flow to the browser, registration, or direct grant flow. === Modifying Forgot Password/Credential Flow {project_name} also has a specific authentication flow for forgot password, or rather credential reset initiated by a user. If you go to the admin console flows page, there is a ""reset credentials"" flow. By default, {project_name} asks for the email or username of the user and sends an email to them. If the user clicks on the link, then they are able to reset both their password and OTP (if an OTP has been set up). You can disable automatic OTP reset by disabling the ""Reset OTP"" authenticator in the flow. You can add additional functionality to this flow as well. For example, many deployments would like for the user to answer one or more secret questions in additional to sending an email with a link. You could expand on the secret question example that comes with the distro and incorporate it into the reset credential flow. One thing to note if you are extending the reset credentials flow. The first ""authenticator"" is just a page to obtain the username or email. If the username or email exists, then the AuthenticationFlowContext.getUser() will return the located user. Otherwise this will be null. This form *WILL NOT* re-ask the user to enter in an email or username if the previous email or username did not exist. You need to prevent attackers from being able to guess valid users. So, if AuthenticationFlowContext.getUser() returns null, you should proceed with the flow to make it look like a valid user was selected. I suggest that if you want to add secret questions to this flow, you should ask these questions after the email is sent. In other words, add your custom authenticator after the ""Send Reset Email"" authenticator. === Modifying First Broker Login Flow First Broker Login flow is used during first login with some identity provider. Term `First Login` means that there is not yet existing {project_name} account linked with the particular authenticated identity provider account. For more details about this flow see the `Identity Brokering` chapter in link:{adminguide_link}[{adminguide_name}] . [[_client_authentication]] === Authentication of clients {project_name} actually supports pluggable authentication for https://openid.net/specs/openid-connect-core-1_0.html[OpenID Connect] client applications. Authentication of client (application) is used under the hood by the {project_name} adapter during sending any backchannel requests to the {project_name} server (like the request for exchange code to access token after successful authentication or request to refresh token). But the client authentication can be also used directly by you during `Direct Access grants` (represented by OAuth2 `Resource Owner Password Credentials Flow`) or during `Service account` authentication (represented by OAuth2 `Client Credentials Flow`). For more details about {project_name} adapter and OAuth2 flows see link:{adapterguide_link}[{adapterguide_name}]. ==== Default implementations Actually {project_name} has 2 default implementations of client authentication: Traditional authentication with client_id and client_secret:: This is default mechanism mentioned in the https://openid.net/specs/openid-connect-core-1_0.html[OpenID Connect] or https://tools.ietf.org/html/rfc6749[OAuth2] specification and {project_name} supports it since it's early days. The public client needs to include `client_id` parameter with its ID in the POST request (so it's defacto not authenticated) and the confidential client needs to include `Authorization: Basic` header with the clientId and clientSecret used as username and password. Authentication with signed JWT:: This is based on the https://tools.ietf.org/html/rfc7523[JWT Bearer Token Profiles for OAuth 2.0] specification. The client/adapter generates the https://tools.ietf.org/html/rfc7519[JWT] and signs it with his private key. The {project_name} then verifies the signed JWT with the client's public key and authenticates client based on it. See the demo example and especially the `examples/preconfigured-demo/product-app` for the example application showing the application using client authentication with signed JWT. ==== Implement your own client authenticator For plug your own client authenticator, you need to implement few interfaces on both client (adapter) and server side. Client side:: Here you need to implement `org.keycloak.adapters.authentication.ClientCredentialsProvider` and put the implementation either to: * your WAR file into WEB-INF/classes . But in this case, the implementation can be used just for this single WAR application * Some JAR file, which will be added into WEB-INF/lib of your WAR * Some JAR file, which will be used as jboss module and configured in jboss-deployment-structure.xml of your WAR. In all cases, you also need to create the file `META-INF/services/org.keycloak.adapters.authentication.ClientCredentialsProvider` either in the WAR or in your JAR. Server side:: Here you need to implement `org.keycloak.authentication.ClientAuthenticatorFactory` and `org.keycloak.authentication.ClientAuthenticator` . You also need to add the file `META-INF/services/org.keycloak.authentication.ClientAuthenticatorFactory` with the name of the implementation classes. See <<_auth_spi_walkthrough,authenticators>> for more details. ",12122,False,1947.9094054933498,median "/* * Copyright (C) 2017-2020 Intel Corporation * * SPDX-License-Identifier: MIT * */ #include ""shared/source/command_stream/command_stream_receiver.h"" #include ""shared/source/command_stream/device_command_stream.h"" #include ""shared/source/command_stream/linear_stream.h"" #include ""shared/source/command_stream/preemption.h"" #include ""shared/source/direct_submission/dispatchers/render_dispatcher.h"" #include ""shared/source/direct_submission/windows/wddm_direct_submission.h"" #include ""shared/source/helpers/flush_stamp.h"" #include ""shared/source/helpers/windows/gmm_callbacks.h"" #include ""shared/source/memory_manager/internal_allocation_storage.h"" #include ""shared/source/memory_manager/memory_manager.h"" #include ""shared/source/os_interface/windows/os_context_win.h"" #include ""shared/source/os_interface/windows/os_interface.h"" #include ""shared/source/os_interface/windows/wddm_memory_manager.h"" #include ""shared/source/os_interface/windows/wddm_memory_operations_handler.h"" #include ""shared/source/os_interface/windows/wddm_residency_controller.h"" #include ""shared/test/unit_test/helpers/debug_manager_state_restore.h"" #include ""shared/test/unit_test/helpers/dispatch_flags_helper.h"" #include ""shared/test/unit_test/mocks/mock_device.h"" #include ""shared/test/unit_test/mocks/windows/mock_wddm_direct_submission.h"" #include ""shared/test/unit_test/os_interface/windows/mock_gdi_interface.h"" #include ""opencl/source/command_stream/aub_command_stream_receiver.h"" #include ""opencl/source/command_stream/command_stream_receiver_with_aub_dump.h"" #include ""opencl/source/helpers/built_ins_helper.h"" #include ""opencl/source/mem_obj/buffer.h"" #include ""opencl/source/os_interface/windows/wddm_device_command_stream.h"" #include ""opencl/source/platform/platform.h"" #include ""opencl/test/unit_test/fixtures/cl_device_fixture.h"" #include ""opencl/test/unit_test/fixtures/memory_management_fixture.h"" #include ""opencl/test/unit_test/fixtures/mock_aub_center_fixture.h"" #include ""opencl/test/unit_test/helpers/execution_environment_helper.h"" #include ""opencl/test/unit_test/mocks/mock_buffer.h"" #include ""opencl/test/unit_test/mocks/mock_builtins.h"" #include ""opencl/test/unit_test/mocks/mock_gmm_page_table_mngr.h"" #include ""opencl/test/unit_test/mocks/mock_graphics_allocation.h"" #include ""opencl/test/unit_test/mocks/mock_io_functions.h"" #include ""opencl/test/unit_test/mocks/mock_platform.h"" #include ""opencl/test/unit_test/mocks/mock_program.h"" #include ""opencl/test/unit_test/mocks/mock_submissions_aggregator.h"" #include ""opencl/test/unit_test/mocks/mock_wddm_interface23.h"" #include ""opencl/test/unit_test/os_interface/windows/mock_wddm_memory_manager.h"" #include ""opencl/test/unit_test/os_interface/windows/wddm_fixture.h"" #include ""test.h"" #include ""hw_cmds.h"" using namespace NEO; using namespace ::testing; class WddmCommandStreamFixture { public: std::unique_ptr device; std::unique_ptr osContext; DeviceCommandStreamReceiver *csr; MockWddmMemoryManager *memoryManager = nullptr; WddmMock *wddm = nullptr; DebugManagerStateRestore stateRestore; virtual void SetUp() { HardwareInfo *hwInfo = nullptr; DebugManager.flags.CsrDispatchMode.set(static_cast(DispatchMode::ImmediateDispatch)); auto executionEnvironment = getExecutionEnvironmentImpl(hwInfo, 1); memoryManager = new MockWddmMemoryManager(*executionEnvironment); executionEnvironment->memoryManager.reset(memoryManager); wddm = static_cast(executionEnvironment->rootDeviceEnvironments[0]->osInterface->get()->getWddm()); device.reset(MockDevice::create(executionEnvironment, 0u)); osContext.reset(OsContext::create(executionEnvironment->rootDeviceEnvironments[0]->osInterface.get(), 0, device->getDeviceBitfield(), aub_stream::ENGINE_RCS, PreemptionMode::ThreadGroup, false, false, false)); osContext->setDefaultContext(true); csr = new WddmCommandStreamReceiver(*executionEnvironment, 0); device->resetCommandStreamReceiver(csr); ASSERT_NE(nullptr, device); } virtual void TearDown() { } }; template struct MockWddmCsr : public WddmCommandStreamReceiver { using CommandStreamReceiver::commandStream; using CommandStreamReceiver::dispatchMode; using CommandStreamReceiver::getCS; using CommandStreamReceiver::globalFenceAllocation; using CommandStreamReceiverHw::blitterDirectSubmission; using CommandStreamReceiverHw::directSubmission; using WddmCommandStreamReceiver::commandBufferHeader; using WddmCommandStreamReceiver::initDirectSubmission; using WddmCommandStreamReceiver::WddmCommandStreamReceiver; void overrideDispatchPolicy(DispatchMode overrideValue) { this->dispatchMode = overrideValue; } SubmissionAggregator *peekSubmissionAggregator() { return this->submissionAggregator.get(); } void overrideSubmissionAggregator(SubmissionAggregator *newSubmissionsAggregator) { this->submissionAggregator.reset(newSubmissionsAggregator); } void overrideRecorededCommandBuffer(Device &device) { recordedCommandBuffer = std::unique_ptr(new CommandBuffer(device)); } bool initDirectSubmission(Device &device, OsContext &osContext) override { if (callParentInitDirectSubmission) { return WddmCommandStreamReceiver::initDirectSubmission(device, osContext); } bool ret = true; if (DebugManager.flags.EnableDirectSubmission.get() == 1) { directSubmission = std::make_unique< MockWddmDirectSubmission>>(device, osContext); ret = directSubmission->initialize(true); this->dispatchMode = DispatchMode::ImmediateDispatch; } return ret; } int flushCalledCount = 0; std::unique_ptr recordedCommandBuffer = nullptr; bool callParentInitDirectSubmission = true; }; class WddmCommandStreamWithMockGdiFixture { public: MockWddmCsr *csr = nullptr; MemoryManager *memoryManager = nullptr; std::unique_ptr device = nullptr; WddmMock *wddm = nullptr; MockGdi *gdi = nullptr; DebugManagerStateRestore stateRestore; GraphicsAllocation *preemptionAllocation = nullptr; virtual void SetUp() { HardwareInfo *hwInfo = nullptr; ExecutionEnvironment *executionEnvironment = getExecutionEnvironmentImpl(hwInfo, 1); wddm = static_cast(executionEnvironment->rootDeviceEnvironments[0]->osInterface->get()->getWddm()); gdi = new MockGdi(); wddm->resetGdi(gdi); ASSERT_NE(wddm, nullptr); DebugManager.flags.CsrDispatchMode.set(static_cast(DispatchMode::ImmediateDispatch)); this->csr = new MockWddmCsr(*executionEnvironment, 0); memoryManager = new WddmMemoryManager(*executionEnvironment); ASSERT_NE(nullptr, memoryManager); executionEnvironment->memoryManager.reset(memoryManager); device = std::unique_ptr(Device::create(executionEnvironment, 0u)); device->resetCommandStreamReceiver(this->csr); ASSERT_NE(nullptr, device); this->csr->overrideRecorededCommandBuffer(*device); } virtual void TearDown() { wddm = nullptr; } }; using WddmCommandStreamTest = ::Test; using WddmCommandStreamMockGdiTest = ::Test; using WddmDefaultTest = ::Test; using DeviceCommandStreamTest = ::Test; TEST_F(DeviceCommandStreamTest, WhenCreatingWddmCsrThenWddmPointerIsSetCorrectly) { ExecutionEnvironment *executionEnvironment = platform()->peekExecutionEnvironment(); auto wddm = Wddm::createWddm(nullptr, *executionEnvironment->rootDeviceEnvironments[0].get()); executionEnvironment->rootDeviceEnvironments[0]->osInterface = std::make_unique(); executionEnvironment->rootDeviceEnvironments[0]->osInterface->get()->setWddm(static_cast(wddm)); executionEnvironment->initializeMemoryManager(); std::unique_ptr> csr(static_cast *>(WddmCommandStreamReceiver::create(false, *executionEnvironment, 0))); EXPECT_NE(nullptr, csr); auto wddmFromCsr = csr->peekWddm(); EXPECT_NE(nullptr, wddmFromCsr); } TEST_F(DeviceCommandStreamTest, WhenCreatingWddmCsrWithAubDumpThenAubCsrIsCreated) { ExecutionEnvironment *executionEnvironment = platform()->peekExecutionEnvironment(); auto wddm = Wddm::createWddm(nullptr, *executionEnvironment->rootDeviceEnvironments[0].get()); executionEnvironment->rootDeviceEnvironments[0]->osInterface = std::make_unique(); executionEnvironment->rootDeviceEnvironments[0]->osInterface->get()->setWddm(static_cast(wddm)); executionEnvironment->initializeMemoryManager(); std::unique_ptr> csr(static_cast *>(WddmCommandStreamReceiver::create(true, *executionEnvironment, 0))); EXPECT_NE(nullptr, csr); auto wddmFromCsr = csr->peekWddm(); EXPECT_NE(nullptr, wddmFromCsr); auto aubCSR = static_cast> *>(csr.get())->aubCSR.get(); EXPECT_NE(nullptr, aubCSR); } TEST_F(WddmCommandStreamTest, givenFlushStampWhenWaitCalledThenWaitForSpecifiedMonitoredFence) { uint64_t stampToWait = 123; wddm->waitFromCpuResult.called = 0u; csr->waitForFlushStamp(stampToWait); EXPECT_EQ(1u, wddm->waitFromCpuResult.called); EXPECT_TRUE(wddm->waitFromCpuResult.success); EXPECT_EQ(stampToWait, wddm->waitFromCpuResult.uint64ParamPassed); } TEST_F(WddmCommandStreamTest, WhenFlushingThenFlushIsSubmitted) { GraphicsAllocation *commandBuffer = memoryManager->allocateGraphicsMemoryWithProperties(MockAllocationProperties{csr->getRootDeviceIndex(), MemoryConstants::pageSize}); ASSERT_NE(nullptr, commandBuffer); LinearStream cs(commandBuffer); BatchBuffer batchBuffer{cs.getGraphicsAllocation(), 0, 0, nullptr, false, false, QueueThrottle::MEDIUM, QueueSliceCount::defaultSliceCount, cs.getUsed(), &cs, nullptr}; csr->flush(batchBuffer, csr->getResidencyAllocations()); EXPECT_EQ(1u, wddm->submitResult.called); EXPECT_TRUE(wddm->submitResult.success); EXPECT_EQ(csr->obtainCurrentFlushStamp(), static_cast(csr->getOsContext()).getResidencyController().getMonitoredFence().lastSubmittedFence); memoryManager->freeGraphicsMemory(commandBuffer); } TEST_F(WddmCommandStreamTest, givenPrintIndicesEnabledWhenFlushThenPrintIndices) { DebugManagerStateRestore restorer; DebugManager.flags.PrintDeviceAndEngineIdOnSubmission.set(true); GraphicsAllocation *commandBuffer = memoryManager->allocateGraphicsMemoryWithProperties(MockAllocationProperties{csr->getRootDeviceIndex(), MemoryConstants::pageSize}); ASSERT_NE(nullptr, commandBuffer); LinearStream cs(commandBuffer); BatchBuffer batchBuffer{cs.getGraphicsAllocation(), 0, 0, nullptr, false, false, QueueThrottle::MEDIUM, QueueSliceCount::defaultSliceCount, cs.getUsed(), &cs, nullptr}; ::testing::internal::CaptureStdout(); csr->flush(batchBuffer, csr->getResidencyAllocations()); std::ostringstream expectedValue; expectedValue << ""Submission to RootDevice Index: "" << csr->getRootDeviceIndex() << "", Sub-Devices Mask: "" << csr->getOsContext().getDeviceBitfield().to_ulong() << "", EngineId: "" << csr->getOsContext().getEngineType() << ""\\n""; EXPECT_STREQ(::testing::internal::GetCapturedStdout().c_str(), expectedValue.str().c_str()); memoryManager->freeGraphicsMemory(commandBuffer); } TEST_F(WddmCommandStreamTest, givenGraphicsAllocationWithDifferentGpuAddressThenCpuAddressWhenSubmitIsCalledThenGpuAddressIsUsed) { GraphicsAllocation *commandBuffer = memoryManager->allocateGraphicsMemoryWithProperties(MockAllocationProperties{csr->getRootDeviceIndex(), MemoryConstants::pageSize}); auto cpuAddress = commandBuffer->getUnderlyingBuffer(); uint64_t mockGpuAddres = 1337; commandBuffer->setCpuPtrAndGpuAddress(cpuAddress, mockGpuAddres); LinearStream cs(commandBuffer); BatchBuffer batchBuffer{cs.getGraphicsAllocation(), 0, 0, nullptr, false, false, QueueThrottle::MEDIUM, QueueSliceCount::defaultSliceCount, cs.getUsed(), &cs, nullptr}; csr->flush(batchBuffer, csr->getResidencyAllocations()); EXPECT_EQ(mockGpuAddres, wddm->submitResult.commandBufferSubmitted); memoryManager->freeGraphicsMemory(commandBuffer); } TEST_F(WddmCommandStreamTest, GivenOffsetWhenFlushingThenFlushIsSubmittedCorrectly) { auto offset = 128u; GraphicsAllocation *commandBuffer = memoryManager->allocateGraphicsMemoryWithProperties(MockAllocationProperties{csr->getRootDeviceIndex(), MemoryConstants::pageSize, mockDeviceBitfield}); ASSERT_NE(nullptr, commandBuffer); LinearStream cs(commandBuffer); BatchBuffer batchBuffer{cs.getGraphicsAllocation(), offset, 0, nullptr, false, false, QueueThrottle::MEDIUM, QueueSliceCount::defaultSliceCount, cs.getUsed(), &cs, nullptr}; csr->flush(batchBuffer, csr->getResidencyAllocations()); EXPECT_EQ(1u, wddm->submitResult.called); EXPECT_TRUE(wddm->submitResult.success); EXPECT_EQ(wddm->submitResult.commandBufferSubmitted, commandBuffer->getGpuAddress() + offset); memoryManager->freeGraphicsMemory(commandBuffer); } TEST_F(WddmCommandStreamTest, givenWdmmWhenSubmitIsCalledThenCoherencyRequiredFlagIsSetToFalse) { GraphicsAllocation *commandBuffer = memoryManager->allocateGraphicsMemoryWithProperties(MockAllocationProperties{csr->getRootDeviceIndex(), MemoryConstants::pageSize}); ASSERT_NE(nullptr, commandBuffer); LinearStream cs(commandBuffer); BatchBuffer batchBuffer{cs.getGraphicsAllocation(), 0, 0, nullptr, false, false, QueueThrottle::MEDIUM, QueueSliceCount::defaultSliceCount, cs.getUsed(), &cs, nullptr}; csr->flush(batchBuffer, csr->getResidencyAllocations()); auto commandHeader = wddm->submitResult.commandHeaderSubmitted; COMMAND_BUFFER_HEADER *pHeader = reinterpret_cast(commandHeader); EXPECT_FALSE(pHeader->RequiresCoherency); memoryManager->freeGraphicsMemory(commandBuffer); } TEST(WddmPreemptionHeaderTests, givenWddmCommandStreamReceiverWhenPreemptionIsOffWhenWorkloadIsSubmittedThenHeaderDoesntHavePreemptionFieldSet) { HardwareInfo *hwInfo = nullptr; ExecutionEnvironment *executionEnvironment = getExecutionEnvironmentImpl(hwInfo, 1); hwInfo->capabilityTable.defaultPreemptionMode = PreemptionMode::Disabled; executionEnvironment->rootDeviceEnvironments[0]->setHwInfo(hwInfo); auto wddm = static_cast(executionEnvironment->rootDeviceEnvironments[0]->osInterface->get()->getWddm()); auto csr = std::make_unique>(*executionEnvironment, 0); executionEnvironment->memoryManager.reset(new MemoryManagerCreate(false, false, *executionEnvironment)); csr->overrideDispatchPolicy(DispatchMode::ImmediateDispatch); OsContextWin osContext(*wddm, 0u, 1, HwHelper::get(hwInfo->platform.eRenderCoreFamily).getGpgpuEngineInstances(*hwInfo)[0], PreemptionHelper::getDefaultPreemptionMode(*hwInfo), false, false, false); csr->setupContext(osContext); auto commandBuffer = executionEnvironment->memoryManager->allocateGraphicsMemoryWithProperties(MockAllocationProperties{csr->getRootDeviceIndex(), MemoryConstants::pageSize}); LinearStream cs(commandBuffer); BatchBuffer batchBuffer{cs.getGraphicsAllocation(), 0, 0, nullptr, false, false, QueueThrottle::MEDIUM, QueueSliceCount::defaultSliceCount, cs.getUsed(), &cs, nullptr}; csr->flush(batchBuffer, csr->getResidencyAllocations()); auto commandHeader = wddm->submitResult.commandHeaderSubmitted; COMMAND_BUFFER_HEADER *pHeader = reinterpret_cast(commandHeader); EXPECT_FALSE(pHeader->NeedsMidBatchPreEmptionSupport); executionEnvironment->memoryManager->freeGraphicsMemory(commandBuffer); } TEST(WddmPreemptionHeaderTests, givenWddmCommandStreamReceiverWhenPreemptionIsOnWhenWorkloadIsSubmittedThenHeaderDoesHavePreemptionFieldSet) { HardwareInfo *hwInfo = nullptr; ExecutionEnvironment *executionEnvironment = getExecutionEnvironmentImpl(hwInfo, 1); hwInfo->capabilityTable.defaultPreemptionMode = PreemptionMode::MidThread; executionEnvironment->rootDeviceEnvironments[0]->setHwInfo(hwInfo); auto wddm = static_cast(executionEnvironment->rootDeviceEnvironments[0]->osInterface->get()->getWddm()); auto csr = std::make_unique>(*executionEnvironment, 0); executionEnvironment->memoryManager.reset(new MemoryManagerCreate(false, false, *executionEnvironment)); csr->overrideDispatchPolicy(DispatchMode::ImmediateDispatch); OsContextWin osContext(*wddm, 0u, 1, HwHelper::get(hwInfo->platform.eRenderCoreFamily).getGpgpuEngineInstances(*hwInfo)[0], PreemptionHelper::getDefaultPreemptionMode(*hwInfo), false, false, false); csr->setupContext(osContext); auto commandBuffer = executionEnvironment->memoryManager->allocateGraphicsMemoryWithProperties(MockAllocationProperties{csr->getRootDeviceIndex(), MemoryConstants::pageSize}); LinearStream cs(commandBuffer); BatchBuffer batchBuffer{cs.getGraphicsAllocation(), 0, 0, nullptr, false, false, QueueThrottle::MEDIUM, QueueSliceCount::defaultSliceCount, cs.getUsed(), &cs, nullptr}; csr->flush(batchBuffer, csr->getResidencyAllocations()); auto commandHeader = wddm->submitResult.commandHeaderSubmitted; COMMAND_BUFFER_HEADER *pHeader = reinterpret_cast(commandHeader); EXPECT_TRUE(pHeader->NeedsMidBatchPreEmptionSupport); executionEnvironment->memoryManager->freeGraphicsMemory(commandBuffer); } TEST(WddmPreemptionHeaderTests, givenDeviceSupportingPreemptionWhenCommandStreamReceiverIsCreatedThenHeaderContainsPreemptionFieldSet) { HardwareInfo *hwInfo = nullptr; ExecutionEnvironment *executionEnvironment = getExecutionEnvironmentImpl(hwInfo, 1); hwInfo->capabilityTable.defaultPreemptionMode = PreemptionMode::MidThread; executionEnvironment->rootDeviceEnvironments[0]->setHwInfo(hwInfo); auto commandStreamReceiver = std::make_unique>(*executionEnvironment, 0); auto commandHeader = commandStreamReceiver->commandBufferHeader; auto header = reinterpret_cast(commandHeader); EXPECT_TRUE(header->NeedsMidBatchPreEmptionSupport); } TEST(WddmPreemptionHeaderTests, givenDevicenotSupportingPreemptionWhenCommandStreamReceiverIsCreatedThenHeaderPreemptionFieldIsNotSet) { HardwareInfo *hwInfo = nullptr; ExecutionEnvironment *executionEnvironment = getExecutionEnvironmentImpl(hwInfo, 1); hwInfo->capabilityTable.defaultPreemptionMode = PreemptionMode::Disabled; executionEnvironment->rootDeviceEnvironments[0]->setHwInfo(hwInfo); auto commandStreamReceiver = std::make_unique>(*executionEnvironment, 0); auto commandHeader = commandStreamReceiver->commandBufferHeader; auto header = reinterpret_cast(commandHeader); EXPECT_FALSE(header->NeedsMidBatchPreEmptionSupport); } TEST_F(WddmCommandStreamTest, givenWdmmWhenSubmitIsCalledWhenEUCountWouldBeOddThenRequestEvenEuCount) { GraphicsAllocation *commandBuffer = memoryManager->allocateGraphicsMemoryWithProperties(MockAllocationProperties{csr->getRootDeviceIndex(), MemoryConstants::pageSize}); ASSERT_NE(nullptr, commandBuffer); LinearStream cs(commandBuffer); wddm->getGtSysInfo()->EUCount = 9; wddm->getGtSysInfo()->SubSliceCount = 3; BatchBuffer batchBuffer{cs.getGraphicsAllocation(), 0, 0, nullptr, false, false, QueueThrottle::LOW, QueueSliceCount::defaultSliceCount, cs.getUsed(), &cs, nullptr}; csr->flush(batchBuffer, csr->getResidencyAllocations()); auto commandHeader = wddm->submitResult.commandHeaderSubmitted; COMMAND_BUFFER_HEADER *pHeader = reinterpret_cast(commandHeader); EXPECT_EQ(0, pHeader->UmdRequestedSliceState); EXPECT_EQ(0, pHeader->UmdRequestedSubsliceCount); EXPECT_EQ((wddm->getGtSysInfo()->EUCount / wddm->getGtSysInfo()->SubSliceCount) & (~1u), pHeader->UmdRequestedEUCount); memoryManager->freeGraphicsMemory(commandBuffer); } TEST_F(WddmCommandStreamTest, givenWdmmWhenSubmitIsCalledAndThrottleIsToLowThenSetHeaderFieldsProperly) { GraphicsAllocation *commandBuffer = memoryManager->allocateGraphicsMemoryWithProperties(MockAllocationProperties{csr->getRootDeviceIndex(), MemoryConstants::pageSize}); ASSERT_NE(nullptr, commandBuffer); LinearStream cs(commandBuffer); BatchBuffer batchBuffer{cs.getGraphicsAllocation(), 0, 0, nullptr, false, false, QueueThrottle::LOW, QueueSliceCount::defaultSliceCount, cs.getUsed(), &cs, nullptr}; csr->flush(batchBuffer, csr->getResidencyAllocations()); auto commandHeader = wddm->submitResult.commandHeaderSubmitted; COMMAND_BUFFER_HEADER *pHeader = reinterpret_cast(commandHeader); EXPECT_EQ(0, pHeader->UmdRequestedSliceState); EXPECT_EQ(0, pHeader->UmdRequestedSubsliceCount); EXPECT_EQ((wddm->getGtSysInfo()->EUCount / wddm->getGtSysInfo()->SubSliceCount) & (~1u), pHeader->UmdRequestedEUCount); memoryManager->freeGraphicsMemory(commandBuffer); } TEST_F(WddmCommandStreamTest, givenWdmmWhenSubmitIsCalledAndThrottleIsToMediumThenSetHeaderFieldsProperly) { GraphicsAllocation *commandBuffer = memoryManager->allocateGraphicsMemoryWithProperties(MockAllocationProperties{csr->getRootDeviceIndex(), MemoryConstants::pageSize}); ASSERT_NE(nullptr, commandBuffer); LinearStream cs(commandBuffer); BatchBuffer batchBuffer{cs.getGraphicsAllocation(), 0, 0, nullptr, false, false, QueueThrottle::MEDIUM, QueueSliceCount::defaultSliceCount, cs.getUsed(), &cs, nullptr}; csr->flush(batchBuffer, csr->getResidencyAllocations()); auto commandHeader = wddm->submitResult.commandHeaderSubmitted; COMMAND_BUFFER_HEADER *pHeader = reinterpret_cast(commandHeader); EXPECT_EQ(0, pHeader->UmdRequestedSliceState); EXPECT_EQ(0, pHeader->UmdRequestedSubsliceCount); EXPECT_EQ((wddm->getGtSysInfo()->EUCount / wddm->getGtSysInfo()->SubSliceCount) & (~1u), pHeader->UmdRequestedEUCount); memoryManager->freeGraphicsMemory(commandBuffer); } TEST_F(WddmCommandStreamTest, givenWdmmWhenSubmitIsCalledAndThrottleIsToHighThenSetHeaderFieldsProperly) { GraphicsAllocation *commandBuffer = memoryManager->allocateGraphicsMemoryWithProperties(MockAllocationProperties{csr->getRootDeviceIndex(), MemoryConstants::pageSize}); ASSERT_NE(nullptr, commandBuffer); LinearStream cs(commandBuffer); BatchBuffer batchBuffer{cs.getGraphicsAllocation(), 0, 0, nullptr, false, false, QueueThrottle::HIGH, QueueSliceCount::defaultSliceCount, cs.getUsed(), &cs, nullptr}; csr->flush(batchBuffer, csr->getResidencyAllocations()); auto commandHeader = wddm->submitResult.commandHeaderSubmitted; COMMAND_BUFFER_HEADER *pHeader = reinterpret_cast(commandHeader); const uint32_t maxRequestedSubsliceCount = 7; EXPECT_EQ(0, pHeader->UmdRequestedSliceState); EXPECT_EQ((wddm->getGtSysInfo()->SubSliceCount <= maxRequestedSubsliceCount) ? wddm->getGtSysInfo()->SubSliceCount : 0, pHeader->UmdRequestedSubsliceCount); EXPECT_EQ((wddm->getGtSysInfo()->EUCount / wddm->getGtSysInfo()->SubSliceCount) & (~1u), pHeader->UmdRequestedEUCount); memoryManager->freeGraphicsMemory(commandBuffer); } TEST_F(WddmCommandStreamTest, givenWddmWithKmDafDisabledWhenFlushIsCalledWithAllocationsForResidencyThenNoneAllocationShouldBeKmDafLocked) { GraphicsAllocation *commandBuffer = memoryManager->allocateGraphicsMemoryWithProperties(MockAllocationProperties{csr->getRootDeviceIndex(), MemoryConstants::pageSize}); ASSERT_NE(nullptr, commandBuffer); LinearStream cs(commandBuffer); BatchBuffer batchBuffer{cs.getGraphicsAllocation(), 0, 0, nullptr, false, false, QueueThrottle::MEDIUM, QueueSliceCount::defaultSliceCount, cs.getUsed(), &cs, nullptr}; auto linearStreamAllocation = memoryManager->allocateGraphicsMemoryWithProperties({csr->getRootDeviceIndex(), MemoryConstants::pageSize, GraphicsAllocation::AllocationType::LINEAR_STREAM, device->getDeviceBitfield()}); ASSERT_NE(nullptr, linearStreamAllocation); ResidencyContainer allocationsForResidency = {linearStreamAllocation}; EXPECT_FALSE(wddm->isKmDafEnabled()); csr->flush(batchBuffer, allocationsForResidency); EXPECT_EQ(0u, wddm->kmDafLockResult.called); EXPECT_EQ(0u, wddm->kmDafLockResult.lockedAllocations.size()); memoryManager->freeGraphicsMemory(commandBuffer); memoryManager->freeGraphicsMemory(linearStreamAllocation); } TEST_F(WddmCommandStreamTest, givenWddmWithKmDafEnabledWhenFlushIsCalledWithoutAllocationsForResidencyThenNoneAllocationShouldBeKmDafLocked) { GraphicsAllocation *commandBuffer = memoryManager->allocateGraphicsMemoryWithProperties(MockAllocationProperties{csr->getRootDeviceIndex(), MemoryConstants::pageSize}); ASSERT_NE(nullptr, commandBuffer); LinearStream cs(commandBuffer); BatchBuffer batchBuffer{cs.getGraphicsAllocation(), 0, 0, nullptr, false, false, QueueThrottle::MEDIUM, QueueSliceCount::defaultSliceCount, cs.getUsed(), &cs, nullptr}; wddm->setKmDafEnabled(true); csr->flush(batchBuffer, csr->getResidencyAllocations()); EXPECT_EQ(0u, wddm->kmDafLockResult.called); EXPECT_EQ(0u, wddm->kmDafLockResult.lockedAllocations.size()); memoryManager->freeGraphicsMemory(commandBuffer); } TEST_F(WddmCommandStreamTest, givenWddmWithKmDafEnabledWhenFlushIsCalledWithResidencyAllocationsInMemoryManagerThenLinearStreamAllocationsShouldBeKmDafLocked) { GraphicsAllocation *commandBuffer = memoryManager->allocateGraphicsMemoryWithProperties(MockAllocationProperties{csr->getRootDeviceIndex(), MemoryConstants::pageSize}); ASSERT_NE(nullptr, commandBuffer); LinearStream cs(commandBuffer); BatchBuffer batchBuffer{cs.getGraphicsAllocation(), 0, 0, nullptr, false, false, QueueThrottle::MEDIUM, QueueSliceCount::defaultSliceCount, cs.getUsed(), &cs, nullptr}; auto linearStreamAllocation = static_cast(memoryManager->allocateGraphicsMemoryWithProperties({csr->getRootDeviceIndex(), MemoryConstants::pageSize, GraphicsAllocation::AllocationType::LINEAR_STREAM, device->getDeviceBitfield()})); ASSERT_NE(nullptr, linearStreamAllocation); csr->makeResident(*linearStreamAllocation); EXPECT_EQ(1u, csr->getResidencyAllocations().size()); EXPECT_EQ(linearStreamAllocation, csr->getResidencyAllocations()[0]); wddm->setKmDafEnabled(true); csr->flush(batchBuffer, csr->getResidencyAllocations()); EXPECT_EQ(1u, wddm->kmDafLockResult.called); EXPECT_EQ(1u, wddm->kmDafLockResult.lockedAllocations.size()); EXPECT_EQ(linearStreamAllocation->getDefaultHandle(), wddm->kmDafLockResult.lockedAllocations[0]); memoryManager->freeGraphicsMemory(commandBuffer); memoryManager->freeGraphicsMemory(linearStreamAllocation); } TEST_F(WddmCommandStreamTest, givenWddmWithKmDafEnabledWhenFlushIsCalledWithAllocationsForResidencyThenLinearStreamAllocationsShouldBeKmDafLocked) { GraphicsAllocation *commandBuffer = memoryManager->allocateGraphicsMemoryWithProperties(MockAllocationProperties{csr->getRootDeviceIndex(), MemoryConstants::pageSize}); ASSERT_NE(nullptr, commandBuffer); LinearStream cs(commandBuffer); BatchBuffer batchBuffer{cs.getGraphicsAllocation(), 0, 0, nullptr, false, false, QueueThrottle::MEDIUM, QueueSliceCount::defaultSliceCount, cs.getUsed(), &cs, nullptr}; auto linearStreamAllocation = static_cast(memoryManager->allocateGraphicsMemoryWithProperties({csr->getRootDeviceIndex(), MemoryConstants::pageSize, GraphicsAllocation::AllocationType::LINEAR_STREAM, device->getDeviceBitfield()})); ASSERT_NE(nullptr, linearStreamAllocation); ResidencyContainer allocationsForResidency = {linearStreamAllocation}; wddm->setKmDafEnabled(true); csr->flush(batchBuffer, allocationsForResidency); EXPECT_EQ(1u, wddm->kmDafLockResult.called); EXPECT_EQ(1u, wddm->kmDafLockResult.lockedAllocations.size()); EXPECT_EQ(linearStreamAllocation->getDefaultHandle(), wddm->kmDafLockResult.lockedAllocations[0]); memoryManager->freeGraphicsMemory(commandBuffer); memoryManager->freeGraphicsMemory(linearStreamAllocation); } TEST_F(WddmCommandStreamTest, givenWddmWithKmDafEnabledWhenFlushIsCalledWithAllocationsForResidencyThenFillPatternAllocationsShouldBeKmDafLocked) { GraphicsAllocation *commandBuffer = memoryManager->allocateGraphicsMemoryWithProperties(MockAllocationProperties{csr->getRootDeviceIndex(), MemoryConstants::pageSize}); ASSERT_NE(nullptr, commandBuffer); LinearStream cs(commandBuffer); BatchBuffer batchBuffer{cs.getGraphicsAllocation(), 0, 0, nullptr, false, false, QueueThrottle::MEDIUM, QueueSliceCount::defaultSliceCount, cs.getUsed(), &cs, nullptr}; auto fillPatternAllocation = static_cast(memoryManager->allocateGraphicsMemoryWithProperties({csr->getRootDeviceIndex(), MemoryConstants::pageSize, GraphicsAllocation::AllocationType::FILL_PATTERN, device->getDeviceBitfield()})); ASSERT_NE(nullptr, fillPatternAllocation); ResidencyContainer allocationsForResidency = {fillPatternAllocation}; wddm->setKmDafEnabled(true); csr->flush(batchBuffer, allocationsForResidency); EXPECT_EQ(1u, wddm->kmDafLockResult.called); EXPECT_EQ(1u, wddm->kmDafLockResult.lockedAllocations.size()); EXPECT_EQ(fillPatternAllocation->getDefaultHandle(), wddm->kmDafLockResult.lockedAllocations[0]); memoryManager->freeGraphicsMemory(commandBuffer); memoryManager->freeGraphicsMemory(fillPatternAllocation); } TEST_F(WddmCommandStreamTest, givenWddmWithKmDafEnabledWhenFlushIsCalledWithAllocationsForResidencyThenCommandBufferAllocationsShouldBeKmDafLocked) { GraphicsAllocation *commandBuffer = memoryManager->allocateGraphicsMemoryWithProperties(MockAllocationProperties{csr->getRootDeviceIndex(), MemoryConstants::pageSize}); ASSERT_NE(nullptr, commandBuffer); LinearStream cs(commandBuffer); BatchBuffer batchBuffer{cs.getGraphicsAllocation(), 0, 0, nullptr, false, false, QueueThrottle::MEDIUM, QueueSliceCount::defaultSliceCount, cs.getUsed(), &cs, nullptr}; auto commandBufferAllocation = static_cast(memoryManager->allocateGraphicsMemoryWithProperties({csr->getRootDeviceIndex(), MemoryConstants::pageSize, GraphicsAllocation::AllocationType::COMMAND_BUFFER, device->getDeviceBitfield()})); ASSERT_NE(nullptr, commandBufferAllocation); ResidencyContainer allocationsForResidency = {commandBufferAllocation}; wddm->setKmDafEnabled(true); csr->flush(batchBuffer, allocationsForResidency); EXPECT_EQ(1u, wddm->kmDafLockResult.called); EXPECT_EQ(1u, wddm->kmDafLockResult.lockedAllocations.size()); EXPECT_EQ(commandBufferAllocation->getDefaultHandle(), wddm->kmDafLockResult.lockedAllocations[0]); memoryManager->freeGraphicsMemory(commandBuffer); memoryManager->freeGraphicsMemory(commandBufferAllocation); } TEST_F(WddmCommandStreamTest, givenWddmWithKmDafEnabledWhenFlushIsCalledWithAllocationsForResidencyThenNonLinearStreamAllocationShouldNotBeKmDafLocked) { GraphicsAllocation *commandBuffer = memoryManager->allocateGraphicsMemoryWithProperties(MockAllocationProperties{csr->getRootDeviceIndex(), MemoryConstants::pageSize}); ASSERT_NE(nullptr, commandBuffer); LinearStream cs(commandBuffer); BatchBuffer batchBuffer{cs.getGraphicsAllocation(), 0, 0, nullptr, false, false, QueueThrottle::MEDIUM, QueueSliceCount::defaultSliceCount, cs.getUsed(), &cs, nullptr}; auto nonLinearStreamAllocation = memoryManager->allocateGraphicsMemoryWithProperties(MockAllocationProperties{csr->getRootDeviceIndex(), MemoryConstants::pageSize}); ASSERT_NE(nullptr, nonLinearStreamAllocation); ResidencyContainer allocationsForResidency = {nonLinearStreamAllocation}; wddm->setKmDafEnabled(true); csr->flush(batchBuffer, allocationsForResidency); EXPECT_EQ(0u, wddm->kmDafLockResult.called); EXPECT_EQ(0u, wddm->kmDafLockResult.lockedAllocations.size()); memoryManager->freeGraphicsMemory(commandBuffer); memoryManager->freeGraphicsMemory(nonLinearStreamAllocation); } TEST_F(WddmCommandStreamTest, WhenMakingResidentThenAllocationIsCorrectlySet) { GraphicsAllocation *commandBuffer = memoryManager->allocateGraphicsMemoryWithProperties(MockAllocationProperties{csr->getRootDeviceIndex(), MemoryConstants::pageSize}); ASSERT_NE(nullptr, commandBuffer); LinearStream cs(commandBuffer); csr->makeResident(*commandBuffer); EXPECT_EQ(0u, wddm->makeResidentResult.called); EXPECT_EQ(1u, csr->getResidencyAllocations().size()); EXPECT_EQ(commandBuffer, csr->getResidencyAllocations()[0]); memoryManager->freeGraphicsMemory(commandBuffer); } TEST_F(WddmCommandStreamTest, WhenMakingNonResidentThenAllocationIsPlacedInEvictionAllocations) { GraphicsAllocation *commandBuffer = memoryManager->allocateGraphicsMemoryWithProperties(MockAllocationProperties{csr->getRootDeviceIndex(), MemoryConstants::pageSize}); ASSERT_NE(nullptr, commandBuffer); LinearStream cs(commandBuffer); csr->makeResident(*cs.getGraphicsAllocation()); csr->makeNonResident(*commandBuffer); EXPECT_EQ(1u, csr->getEvictionAllocations().size()); memoryManager->freeGraphicsMemory(commandBuffer); } TEST_F(WddmCommandStreamTest, WhenProcessingEvictionThenAllAllocationsArePlacedOnTrimCandidateList) { GraphicsAllocation *allocation = memoryManager->allocateGraphicsMemoryWithProperties(MockAllocationProperties{csr->getRootDeviceIndex(), MemoryConstants::pageSize}); GraphicsAllocation *allocation2 = memoryManager->allocateGraphicsMemoryWithProperties(MockAllocationProperties{csr->getRootDeviceIndex(), MemoryConstants::pageSize}); ASSERT_NE(nullptr, allocation); ASSERT_NE(nullptr, allocation2); csr->getEvictionAllocations().push_back(allocation); csr->getEvictionAllocations().push_back(allocation2); EXPECT_EQ(2u, csr->getEvictionAllocations().size()); csr->processEviction(); EXPECT_EQ(2u, static_cast(csr->getOsContext()).getResidencyController().peekTrimCandidateList().size()); memoryManager->freeGraphicsMemory(allocation); memoryManager->freeGraphicsMemory(allocation2); } TEST_F(WddmCommandStreamTest, WhenProcesssingEvictionThenEvictionAllocationsListIsCleared) { GraphicsAllocation *allocation = memoryManager->allocateGraphicsMemoryWithProperties(MockAllocationProperties{csr->getRootDeviceIndex(), MemoryConstants::pageSize}); ASSERT_NE(nullptr, allocation); csr->getEvictionAllocations().push_back(allocation); EXPECT_EQ(1u, csr->getEvictionAllocations().size()); csr->processEviction(); EXPECT_EQ(0u, csr->getEvictionAllocations().size()); memoryManager->freeGraphicsMemory(allocation); } TEST_F(WddmCommandStreamTest, WhenMakingResidentAndNonResidentThenAllocationIsMovedCorrectly) { GraphicsAllocation *gfxAllocation = memoryManager->allocateGraphicsMemoryWithProperties(MockAllocationProperties{csr->getRootDeviceIndex(), MemoryConstants::pageSize}); Buffer *buffer = new AlignedBuffer(gfxAllocation); csr->makeResident(*buffer->getGraphicsAllocation(csr->getRootDeviceIndex())); EXPECT_EQ(0u, wddm->makeResidentResult.called); EXPECT_EQ(1u, csr->getResidencyAllocations().size()); EXPECT_EQ(gfxAllocation, csr->getResidencyAllocations()[0]); csr->makeNonResident(*buffer->getGraphicsAllocation(csr->getRootDeviceIndex())); EXPECT_EQ(gfxAllocation, csr->getEvictionAllocations()[0]); delete buffer; memoryManager->freeGraphicsMemory(gfxAllocation); } TEST_F(WddmCommandStreamTest, givenGraphicsAllocationWhenMakeResidentThenAllocationIsInResidencyContainer) { void *hostPtr = reinterpret_cast(wddm->virtualAllocAddress + 0x1234); auto size = 1234u; auto gfxAllocation = memoryManager->allocateGraphicsMemoryWithProperties(MockAllocationProperties{csr->getRootDeviceIndex(), false, size}, hostPtr); ASSERT_NE(nullptr, gfxAllocation); csr->makeResidentHostPtrAllocation(gfxAllocation); EXPECT_EQ(1u, csr->getResidencyAllocations().size()); EXPECT_EQ(hostPtr, gfxAllocation->getUnderlyingBuffer()); memoryManager->freeGraphicsMemory(gfxAllocation); } TEST_F(WddmCommandStreamTest, givenHostPtrAllocationWhenMapFailsThenFragmentsAreClearedAndNullptrIsReturned) { this->wddm->callBaseMapGpuVa = false; this->wddm->mapGpuVaStatus = false; void *hostPtr = reinterpret_cast(wddm->virtualAllocAddress + 0x1234); auto size = 1234u; wddm->mapGpuVirtualAddressResult.called = 0u; wddm->destroyAllocationResult.called = 0u; auto gfxAllocation = memoryManager->allocateGraphicsMemoryWithProperties(MockAllocationProperties{csr->getRootDeviceIndex(), false, size}, hostPtr); EXPECT_EQ(1u, wddm->mapGpuVirtualAddressResult.called); EXPECT_EQ(1u, wddm->destroyAllocationResult.called); EXPECT_EQ(nullptr, gfxAllocation); } TEST_F(WddmCommandStreamTest, givenAddressWithHighestBitSetWhenItIsMappedThenProperAddressIsPassed) { uintptr_t address = 0xffff0000; void *faultyAddress = reinterpret_cast(address); wddm->mapGpuVirtualAddressResult.called = 0u; auto gfxAllocation = memoryManager->allocateGraphicsMemoryWithProperties(MockAllocationProperties{csr->getRootDeviceIndex(), false, MemoryConstants::pageSize}, faultyAddress); EXPECT_EQ(1u, wddm->mapGpuVirtualAddressResult.called); ASSERT_NE(nullptr, gfxAllocation); auto expectedAddress = castToUint64(faultyAddress); EXPECT_EQ(gfxAllocation->getGpuAddress(), expectedAddress); ASSERT_EQ(gfxAllocation->fragmentsStorage.fragmentCount, 1u); EXPECT_EQ(expectedAddress, gfxAllocation->fragmentsStorage.fragmentStorageData[0].osHandleStorage->gpuPtr); memoryManager->freeGraphicsMemory(gfxAllocation); } TEST_F(WddmCommandStreamTest, givenHostPtrWhenPtrBelowRestrictionThenCreateAllocationAndMakeResident) { void *hostPtr = reinterpret_cast(memoryManager->getAlignedMallocRestrictions()->minAddress - 0x1000); auto size = 0x2000u; auto gfxAllocation = static_cast(memoryManager->allocateGraphicsMemoryWithProperties(MockAllocationProperties{csr->getRootDeviceIndex(), false, size}, hostPtr)); void *expectedReserve = reinterpret_cast(wddm->virtualAllocAddress); ASSERT_NE(nullptr, gfxAllocation); csr->makeResidentHostPtrAllocation(gfxAllocation); EXPECT_EQ(1u, csr->getResidencyAllocations().size()); EXPECT_EQ(hostPtr, gfxAllocation->getUnderlyingBuffer()); EXPECT_EQ(expectedReserve, gfxAllocation->getReservedAddressPtr()); memoryManager->freeGraphicsMemory(gfxAllocation); } TEST_F(WddmCommandStreamTest, givenTwoTemporaryAllocationsWhenCleanTemporaryAllocationListThenDestoryOnlyCompletedAllocations) { void *host_ptr = (void *)0x1212341; void *host_ptr2 = (void *)0x2212341; auto size = 17262u; GraphicsAllocation *graphicsAllocation = memoryManager->allocateGraphicsMemoryWithProperties(MockAllocationProperties{csr->getRootDeviceIndex(), false, size}, host_ptr); GraphicsAllocation *graphicsAllocation2 = memoryManager->allocateGraphicsMemoryWithProperties(MockAllocationProperties{csr->getRootDeviceIndex(), false, size}, host_ptr2); csr->getInternalAllocationStorage()->storeAllocation(std::unique_ptr(graphicsAllocation), TEMPORARY_ALLOCATION); csr->getInternalAllocationStorage()->storeAllocation(std::unique_ptr(graphicsAllocation2), TEMPORARY_ALLOCATION); graphicsAllocation->updateTaskCount(1, csr->getOsContext().getContextId()); graphicsAllocation2->updateTaskCount(100, csr->getOsContext().getContextId()); csr->waitForTaskCountAndCleanAllocationList(1, TEMPORARY_ALLOCATION); // graphicsAllocation2 still lives EXPECT_EQ(host_ptr2, graphicsAllocation2->getUnderlyingBuffer()); auto hostPtrManager = memoryManager->getHostPtrManager(); auto alignedPtr = alignDown(host_ptr, MemoryConstants::pageSize); auto alignedPtr2 = alignDown(host_ptr2, MemoryConstants::pageSize); auto fragment = hostPtrManager->getFragment({alignedPtr2, csr->getRootDeviceIndex()}); ASSERT_NE(nullptr, fragment); EXPECT_EQ(alignedPtr2, fragment->fragmentCpuPointer); auto fragment2 = hostPtrManager->getFragment({alignedPtr, csr->getRootDeviceIndex()}); EXPECT_EQ(nullptr, fragment2); // destroy remaining allocation csr->waitForTaskCountAndCleanAllocationList(100, TEMPORARY_ALLOCATION); } TEST_F(WddmCommandStreamMockGdiTest, WhenFlushingThenWddmMakeResidentIsCalledForResidencyAllocations) { GraphicsAllocation *commandBuffer = memoryManager->allocateGraphicsMemoryWithProperties(MockAllocationProperties{csr->getRootDeviceIndex(), MemoryConstants::pageSize}); ASSERT_NE(nullptr, commandBuffer); LinearStream cs(commandBuffer); csr->makeResident(*commandBuffer); EXPECT_EQ(1u, csr->getResidencyAllocations().size()); gdi->getMakeResidentArg().NumAllocations = 0; BatchBuffer batchBuffer{cs.getGraphicsAllocation(), 0, 0, nullptr, false, false, QueueThrottle::MEDIUM, QueueSliceCount::defaultSliceCount, cs.getUsed(), &cs, nullptr}; csr->flush(batchBuffer, csr->getResidencyAllocations()); EXPECT_NE(0u, gdi->getMakeResidentArg().NumAllocations); memoryManager->freeGraphicsMemory(commandBuffer); } TEST_F(WddmCommandStreamMockGdiTest, WhenMakingResidentThenResidencyAllocationsListIsCleared) { GraphicsAllocation *commandBuffer = memoryManager->allocateGraphicsMemoryWithProperties(MockAllocationProperties{csr->getRootDeviceIndex(), MemoryConstants::pageSize}); ASSERT_NE(nullptr, commandBuffer); LinearStream cs(commandBuffer); csr->makeResident(*commandBuffer); EXPECT_EQ(1u, csr->getResidencyAllocations().size()); EXPECT_EQ(0u, csr->getEvictionAllocations().size()); EXPECT_EQ(trimListUnusedPosition, static_cast(commandBuffer)->getTrimCandidateListPosition(csr->getOsContext().getContextId())); csr->processResidency(csr->getResidencyAllocations(), 0u); csr->makeSurfacePackNonResident(csr->getResidencyAllocations()); EXPECT_EQ(0u, csr->getResidencyAllocations().size()); EXPECT_EQ(0u, csr->getEvictionAllocations().size()); EXPECT_EQ(0u, static_cast(commandBuffer)->getTrimCandidateListPosition(csr->getOsContext().getContextId())); memoryManager->freeGraphicsMemory(commandBuffer); } HWTEST_F(WddmCommandStreamMockGdiTest, givenRecordedCommandBufferWhenItIsSubmittedThenFlushTaskIsProperlyCalled) { //preemption allocation + sip allocation size_t csrSurfaceCount = 0; GraphicsAllocation *tmpAllocation = nullptr; if (device->getPreemptionMode() == PreemptionMode::MidThread) { csrSurfaceCount = 2; tmpAllocation = GlobalMockSipProgram::sipProgram->getAllocation(); GlobalMockSipProgram::sipProgram->resetAllocation(memoryManager->allocateGraphicsMemoryWithProperties(MockAllocationProperties{csr->getRootDeviceIndex(), MemoryConstants::pageSize})); } csrSurfaceCount += csr->globalFenceAllocation ? 1 : 0; csr->overrideDispatchPolicy(DispatchMode::BatchedDispatch); auto mockedSubmissionsAggregator = new mockSubmissionsAggregator(); csr->overrideSubmissionAggregator(mockedSubmissionsAggregator); auto commandBuffer = memoryManager->allocateGraphicsMemoryWithProperties(MockAllocationProperties{csr->getRootDeviceIndex(), MemoryConstants::pageSize}); auto dshAlloc = memoryManager->allocateGraphicsMemoryWithProperties(MockAllocationProperties{csr->getRootDeviceIndex(), MemoryConstants::pageSize}); auto iohAlloc = memoryManager->allocateGraphicsMemoryWithProperties(MockAllocationProperties{csr->getRootDeviceIndex(), MemoryConstants::pageSize}); auto sshAlloc = memoryManager->allocateGraphicsMemoryWithProperties(MockAllocationProperties{csr->getRootDeviceIndex(), MemoryConstants::pageSize}); auto tagAllocation = csr->getTagAllocation(); LinearStream cs(commandBuffer); IndirectHeap dsh(dshAlloc); IndirectHeap ioh(iohAlloc); IndirectHeap ssh(sshAlloc); DispatchFlags dispatchFlags = DispatchFlagsHelper::createDefaultDispatchFlags(); dispatchFlags.preemptionMode = PreemptionHelper::getDefaultPreemptionMode(device->getHardwareInfo()); dispatchFlags.guardCommandBufferWithPipeControl = true; dispatchFlags.requiresCoherency = true; csr->flushTask(cs, 0u, dsh, ioh, ssh, 0u, dispatchFlags, *device); auto &cmdBuffers = mockedSubmissionsAggregator->peekCommandBuffers(); auto storedCommandBuffer = cmdBuffers.peekHead(); ResidencyContainer copyOfResidency = storedCommandBuffer->surfaces; copyOfResidency.push_back(storedCommandBuffer->batchBuffer.commandBufferAllocation); csr->flushBatchedSubmissions(); EXPECT_TRUE(cmdBuffers.peekIsEmpty()); EXPECT_EQ(1u, wddm->submitResult.called); auto csrCommandStream = csr->commandStream.getGraphicsAllocation(); EXPECT_EQ(csrCommandStream->getGpuAddress(), wddm->submitResult.commandBufferSubmitted); EXPECT_TRUE(((COMMAND_BUFFER_HEADER *)wddm->submitResult.commandHeaderSubmitted)->RequiresCoherency); EXPECT_EQ(6u + csrSurfaceCount, wddm->makeResidentResult.handleCount); std::vector expectedHandles; expectedHandles.push_back(static_cast(tagAllocation)->getDefaultHandle()); expectedHandles.push_back(static_cast(commandBuffer)->getDefaultHandle()); expectedHandles.push_back(static_cast(dshAlloc)->getDefaultHandle()); expectedHandles.push_back(static_cast(iohAlloc)->getDefaultHandle()); expectedHandles.push_back(static_cast(sshAlloc)->getDefaultHandle()); expectedHandles.push_back(static_cast(csrCommandStream)->getDefaultHandle()); for (auto i = 0u; i < wddm->makeResidentResult.handleCount; i++) { auto handle = wddm->makeResidentResult.handlePack[i]; auto found = false; for (auto &expectedHandle : expectedHandles) { if (expectedHandle == handle) { found = true; } } EXPECT_TRUE(found); } EXPECT_NE(trimListUnusedPosition, static_cast(tagAllocation)->getTrimCandidateListPosition(csr->getOsContext().getContextId())); EXPECT_NE(trimListUnusedPosition, static_cast(commandBuffer)->getTrimCandidateListPosition(csr->getOsContext().getContextId())); EXPECT_EQ(trimListUnusedPosition, static_cast(dshAlloc)->getTrimCandidateListPosition(csr->getOsContext().getContextId())); EXPECT_EQ(trimListUnusedPosition, static_cast(iohAlloc)->getTrimCandidateListPosition(csr->getOsContext().getContextId())); EXPECT_NE(trimListUnusedPosition, static_cast(sshAlloc)->getTrimCandidateListPosition(csr->getOsContext().getContextId())); EXPECT_NE(trimListUnusedPosition, static_cast(csrCommandStream)->getTrimCandidateListPosition(csr->getOsContext().getContextId())); memoryManager->freeGraphicsMemory(dshAlloc); memoryManager->freeGraphicsMemory(iohAlloc); memoryManager->freeGraphicsMemory(sshAlloc); memoryManager->freeGraphicsMemory(commandBuffer); if (device->getPreemptionMode() == PreemptionMode::MidThread) { memoryManager->freeGraphicsMemory(GlobalMockSipProgram::sipProgram->getAllocation()); GlobalMockSipProgram::sipProgram->resetAllocation(tmpAllocation); } } using WddmSimpleTest = ::testing::Test; HWTEST_F(WddmSimpleTest, givenDefaultWddmCsrWhenItIsCreatedThenBatchingIsTurnedOn) { DebugManager.flags.CsrDispatchMode.set(0); ExecutionEnvironment *executionEnvironment = platform()->peekExecutionEnvironment(); std::unique_ptr device(Device::create(executionEnvironment, 0u)); auto wddm = Wddm::createWddm(nullptr, *executionEnvironment->rootDeviceEnvironments[0].get()); executionEnvironment->rootDeviceEnvironments[0]->osInterface = std::make_unique(); executionEnvironment->rootDeviceEnvironments[0]->osInterface->get()->setWddm(wddm); executionEnvironment->rootDeviceEnvironments[0]->memoryOperationsInterface = std::make_unique(wddm); std::unique_ptr> mockCsr(new MockWddmCsr(*executionEnvironment, 0)); EXPECT_EQ(DispatchMode::BatchedDispatch, mockCsr->dispatchMode); } HWTEST_F(WddmDefaultTest, givenFtrWddmHwQueuesFlagWhenCreatingCsrThenPickWddmVersionBasingOnFtrFlag) { auto wddm = Wddm::createWddm(nullptr, *pDevice->executionEnvironment->rootDeviceEnvironments[0].get()); pDevice->executionEnvironment->rootDeviceEnvironments[0]->osInterface = std::make_unique(); pDevice->executionEnvironment->rootDeviceEnvironments[0]->osInterface->get()->setWddm(wddm); pDevice->executionEnvironment->rootDeviceEnvironments[0]->memoryOperationsInterface = std::make_unique(wddm); WddmCommandStreamReceiver wddmCsr(*pDevice->executionEnvironment, 0); auto wddmFromCsr = wddmCsr.peekWddm(); EXPECT_EQ(typeid(*wddmFromCsr), typeid(WddmMock)); } struct WddmCsrCompressionTests : ::testing::Test { void setCompressionEnabled(bool enableForBuffer, bool enableForImages) { RuntimeCapabilityTable capabilityTable = defaultHwInfo->capabilityTable; capabilityTable.ftrRenderCompressedBuffers = enableForBuffer; capabilityTable.ftrRenderCompressedImages = enableForImages; hwInfo->capabilityTable = capabilityTable; } HardwareInfo *hwInfo = nullptr; WddmMock *myMockWddm; }; struct WddmCsrCompressionParameterizedTest : WddmCsrCompressionTests, ::testing::WithParamInterface { void SetUp() override { compressionEnabled = GetParam(); } bool compressionEnabled; }; HWTEST_P(WddmCsrCompressionParameterizedTest, givenEnabledCompressionWhenInitializedThenCreatePagetableMngr) { uint32_t index = 1u; ExecutionEnvironment *executionEnvironment = getExecutionEnvironmentImpl(hwInfo, 2); std::unique_ptr device(Device::create(executionEnvironment, 1u)); setCompressionEnabled(compressionEnabled, !compressionEnabled); myMockWddm = static_cast(executionEnvironment->rootDeviceEnvironments[0]->osInterface->get()->getWddm()); EXPECT_EQ(nullptr, executionEnvironment->rootDeviceEnvironments[index]->pageTableManager.get()); MockWddmCsr mockWddmCsr(*executionEnvironment, index); mockWddmCsr.createPageTableManager(); ASSERT_NE(nullptr, executionEnvironment->rootDeviceEnvironments[index]->pageTableManager.get()); auto mockMngr = reinterpret_cast(executionEnvironment->rootDeviceEnvironments[index]->pageTableManager.get()); EXPECT_EQ(1u, mockMngr->setCsrHanleCalled); EXPECT_EQ(&mockWddmCsr, mockMngr->passedCsrHandle); GMM_TRANSLATIONTABLE_CALLBACKS expectedTTCallbacks = {}; unsigned int expectedFlags = TT_TYPE::AUXTT; expectedTTCallbacks.pfWriteL3Adr = TTCallbacks::writeL3Address; EXPECT_TRUE(memcmp(&expectedTTCallbacks, &mockMngr->translationTableCb, sizeof(GMM_TRANSLATIONTABLE_CALLBACKS)) == 0); EXPECT_TRUE(memcmp(&expectedFlags, &mockMngr->translationTableFlags, sizeof(unsigned int)) == 0); } HWTEST_F(WddmCsrCompressionTests, givenDisabledCompressionWhenInitializedThenDontCreatePagetableMngr) { ExecutionEnvironment *executionEnvironment = getExecutionEnvironmentImpl(hwInfo, 2); std::unique_ptr device(Device::create(executionEnvironment, 1u)); setCompressionEnabled(false, false); myMockWddm = static_cast(executionEnvironment->rootDeviceEnvironments[0]->osInterface->get()->getWddm()); MockWddmCsr mockWddmCsr(*executionEnvironment, 1); EXPECT_EQ(nullptr, executionEnvironment->rootDeviceEnvironments[1]->pageTableManager.get()); } INSTANTIATE_TEST_CASE_P( WddmCsrCompressionParameterizedTestCreate, WddmCsrCompressionParameterizedTest, ::testing::Bool()); HWTEST_F(WddmCsrCompressionTests, givenDisabledCompressionWhenFlushingThenDontInitTranslationTable) { ExecutionEnvironment *executionEnvironment = getExecutionEnvironmentImpl(hwInfo, 2); setCompressionEnabled(false, false); myMockWddm = static_cast(executionEnvironment->rootDeviceEnvironments[0]->osInterface->get()->getWddm()); auto mockWddmCsr = new MockWddmCsr(*executionEnvironment, 1); mockWddmCsr->overrideDispatchPolicy(DispatchMode::BatchedDispatch); executionEnvironment->memoryManager.reset(new WddmMemoryManager(*executionEnvironment)); std::unique_ptr device(Device::create(executionEnvironment, 1u)); device->resetCommandStreamReceiver(mockWddmCsr); auto memoryManager = executionEnvironment->memoryManager.get(); EXPECT_EQ(nullptr, executionEnvironment->rootDeviceEnvironments[1]->pageTableManager.get()); auto graphicsAllocation = memoryManager->allocateGraphicsMemoryWithProperties(MockAllocationProperties{mockWddmCsr->getRootDeviceIndex(), MemoryConstants::pageSize}); IndirectHeap cs(graphicsAllocation); EXPECT_EQ(nullptr, executionEnvironment->rootDeviceEnvironments[1]->pageTableManager.get()); DispatchFlags dispatchFlags = DispatchFlagsHelper::createDefaultDispatchFlags(); mockWddmCsr->flushTask(cs, 0u, cs, cs, cs, 0u, dispatchFlags, *device); EXPECT_EQ(nullptr, executionEnvironment->rootDeviceEnvironments[1]->pageTableManager.get()); mockWddmCsr->flushBatchedSubmissions(); memoryManager->freeGraphicsMemory(graphicsAllocation); } TEST_F(WddmCommandStreamTest, whenDirectSubmissionDisabledThenExpectNoFeatureAvailable) { bool ret = csr->initDirectSubmission(*device.get(), *osContext.get()); EXPECT_TRUE(ret); EXPECT_FALSE(csr->isDirectSubmissionEnabled()); EXPECT_FALSE(csr->isBlitterDirectSubmissionEnabled()); } TEST_F(WddmCommandStreamTest, whenDirectSubmissionEnabledOnRcsThenExpectFeatureAvailable) { DebugManager.flags.EnableDirectSubmission.set(1); auto hwInfo = device->getRootDeviceEnvironment().getMutableHardwareInfo(); hwInfo->capabilityTable.directSubmissionEngines.data[aub_stream::ENGINE_RCS].engineSupported = true; bool ret = csr->initDirectSubmission(*device.get(), *osContext.get()); EXPECT_TRUE(ret); EXPECT_TRUE(csr->isDirectSubmissionEnabled()); EXPECT_FALSE(csr->isBlitterDirectSubmissionEnabled()); } TEST_F(WddmCommandStreamTest, givenDirectSubmissionEnabledWhenPlatformNotSupportsRcsThenExpectFeatureNotAvailable) { DebugManager.flags.EnableDirectSubmission.set(1); auto hwInfo = device->getRootDeviceEnvironment().getMutableHardwareInfo(); hwInfo->capabilityTable.directSubmissionEngines.data[aub_stream::ENGINE_RCS].engineSupported = false; bool ret = csr->initDirectSubmission(*device.get(), *osContext.get()); EXPECT_TRUE(ret); EXPECT_FALSE(csr->isDirectSubmissionEnabled()); } TEST_F(WddmCommandStreamTest, whenDirectSubmissionEnabledOnBcsThenExpectFeatureAvailable) { DebugManager.flags.EnableDirectSubmission.set(1); osContext.reset(OsContext::create(device->getExecutionEnvironment()->rootDeviceEnvironments[0]->osInterface.get(), 0, device->getDeviceBitfield(), aub_stream::ENGINE_BCS, PreemptionMode::ThreadGroup, false, false, false)); osContext->setDefaultContext(true); auto hwInfo = device->getRootDeviceEnvironment().getMutableHardwareInfo(); hwInfo->capabilityTable.directSubmissionEngines.data[aub_stream::ENGINE_BCS].engineSupported = true; bool ret = csr->initDirectSubmission(*device.get(), *osContext.get()); EXPECT_TRUE(ret); EXPECT_FALSE(csr->isDirectSubmissionEnabled()); EXPECT_TRUE(csr->isBlitterDirectSubmissionEnabled()); } TEST_F(WddmCommandStreamTest, givenDirectSubmissionEnabledWhenPlatformNotSupportsBcsThenExpectFeatureNotAvailable) { DebugManager.flags.EnableDirectSubmission.set(1); osContext.reset(OsContext::create(device->getExecutionEnvironment()->rootDeviceEnvironments[0]->osInterface.get(), 0, device->getDeviceBitfield(), aub_stream::ENGINE_BCS, PreemptionMode::ThreadGroup, false, false, false)); osContext->setDefaultContext(true); auto hwInfo = device->getRootDeviceEnvironment().getMutableHardwareInfo(); hwInfo->capabilityTable.directSubmissionEngines.data[aub_stream::ENGINE_BCS].engineSupported = false; bool ret = csr->initDirectSubmission(*device.get(), *osContext.get()); EXPECT_TRUE(ret); EXPECT_FALSE(csr->isDirectSubmissionEnabled()); EXPECT_FALSE(csr->isBlitterDirectSubmissionEnabled()); } TEST_F(WddmCommandStreamTest, givenLowPriorityContextWhenDirectSubmissionDisabledOnLowPriorityThenExpectFeatureNotAvailable) { DebugManager.flags.EnableDirectSubmission.set(1); osContext.reset(OsContext::create(device->getExecutionEnvironment()->rootDeviceEnvironments[0]->osInterface.get(), 0, device->getDeviceBitfield(), aub_stream::ENGINE_RCS, PreemptionMode::ThreadGroup, true, false, false)); osContext->setDefaultContext(true); auto hwInfo = device->getRootDeviceEnvironment().getMutableHardwareInfo(); hwInfo->capabilityTable.directSubmissionEngines.data[aub_stream::ENGINE_RCS].engineSupported = true; hwInfo->capabilityTable.directSubmissionEngines.data[aub_stream::ENGINE_RCS].useLowPriority = false; bool ret = csr->initDirectSubmission(*device.get(), *osContext.get()); EXPECT_TRUE(ret); EXPECT_FALSE(csr->isDirectSubmissionEnabled()); } TEST_F(WddmCommandStreamTest, givenLowPriorityContextWhenDirectSubmissionEnabledOnLowPriorityThenExpectFeatureAvailable) { DebugManager.flags.EnableDirectSubmission.set(1); osContext.reset(OsContext::create(device->getExecutionEnvironment()->rootDeviceEnvironments[0]->osInterface.get(), 0, device->getDeviceBitfield(), aub_stream::ENGINE_RCS, PreemptionMode::ThreadGroup, true, false, false)); auto hwInfo = device->getRootDeviceEnvironment().getMutableHardwareInfo(); hwInfo->capabilityTable.directSubmissionEngines.data[aub_stream::ENGINE_RCS].engineSupported = true; hwInfo->capabilityTable.directSubmissionEngines.data[aub_stream::ENGINE_RCS].useLowPriority = true; bool ret = csr->initDirectSubmission(*device.get(), *osContext.get()); EXPECT_TRUE(ret); EXPECT_TRUE(csr->isDirectSubmissionEnabled()); } TEST_F(WddmCommandStreamTest, givenInternalContextWhenDirectSubmissionDisabledOnInternalThenExpectFeatureNotAvailable) { DebugManager.flags.EnableDirectSubmission.set(1); osContext.reset(OsContext::create(device->getExecutionEnvironment()->rootDeviceEnvironments[0]->osInterface.get(), 0, device->getDeviceBitfield(), aub_stream::ENGINE_RCS, PreemptionMode::ThreadGroup, false, true, false)); osContext->setDefaultContext(true); auto hwInfo = device->getRootDeviceEnvironment().getMutableHardwareInfo(); hwInfo->capabilityTable.directSubmissionEngines.data[aub_stream::ENGINE_RCS].engineSupported = true; hwInfo->capabilityTable.directSubmissionEngines.data[aub_stream::ENGINE_RCS].useInternal = false; bool ret = csr->initDirectSubmission(*device.get(), *osContext.get()); EXPECT_TRUE(ret); EXPECT_FALSE(csr->isDirectSubmissionEnabled()); } TEST_F(WddmCommandStreamTest, givenInternalContextWhenDirectSubmissionEnabledOnInternalThenExpectFeatureAvailable) { DebugManager.flags.EnableDirectSubmission.set(1); osContext.reset(OsContext::create(device->getExecutionEnvironment()->rootDeviceEnvironments[0]->osInterface.get(), 0, device->getDeviceBitfield(), aub_stream::ENGINE_RCS, PreemptionMode::ThreadGroup, false, true, false)); auto hwInfo = device->getRootDeviceEnvironment().getMutableHardwareInfo(); hwInfo->capabilityTable.directSubmissionEngines.data[aub_stream::ENGINE_RCS].engineSupported = true; hwInfo->capabilityTable.directSubmissionEngines.data[aub_stream::ENGINE_RCS].useInternal = true; bool ret = csr->initDirectSubmission(*device.get(), *osContext.get()); EXPECT_TRUE(ret); EXPECT_TRUE(csr->isDirectSubmissionEnabled()); } TEST_F(WddmCommandStreamTest, givenRootDeviceContextWhenDirectSubmissionDisabledOnRootDeviceThenExpectFeatureNotAvailable) { DebugManager.flags.EnableDirectSubmission.set(1); osContext.reset(OsContext::create(device->getExecutionEnvironment()->rootDeviceEnvironments[0]->osInterface.get(), 0, device->getDeviceBitfield(), aub_stream::ENGINE_RCS, PreemptionMode::ThreadGroup, false, false, true)); osContext->setDefaultContext(true); auto hwInfo = device->getRootDeviceEnvironment().getMutableHardwareInfo(); hwInfo->capabilityTable.directSubmissionEngines.data[aub_stream::ENGINE_RCS].engineSupported = true; hwInfo->capabilityTable.directSubmissionEngines.data[aub_stream::ENGINE_RCS].useRootDevice = false; bool ret = csr->initDirectSubmission(*device.get(), *osContext.get()); EXPECT_TRUE(ret); EXPECT_FALSE(csr->isDirectSubmissionEnabled()); } TEST_F(WddmCommandStreamTest, givenRootDeviceContextWhenDirectSubmissionEnabledOnRootDeviceThenExpectFeatureAvailable) { DebugManager.flags.EnableDirectSubmission.set(1); osContext.reset(OsContext::create(device->getExecutionEnvironment()->rootDeviceEnvironments[0]->osInterface.get(), 0, device->getDeviceBitfield(), aub_stream::ENGINE_RCS, PreemptionMode::ThreadGroup, false, false, true)); auto hwInfo = device->getRootDeviceEnvironment().getMutableHardwareInfo(); hwInfo->capabilityTable.directSubmissionEngines.data[aub_stream::ENGINE_RCS].engineSupported = true; hwInfo->capabilityTable.directSubmissionEngines.data[aub_stream::ENGINE_RCS].useRootDevice = true; bool ret = csr->initDirectSubmission(*device.get(), *osContext.get()); EXPECT_TRUE(ret); EXPECT_TRUE(csr->isDirectSubmissionEnabled()); } TEST_F(WddmCommandStreamTest, givenNonDefaultContextWhenDirectSubmissionDisabledOnNonDefaultThenExpectFeatureNotAvailable) { DebugManager.flags.EnableDirectSubmission.set(1); osContext.reset(OsContext::create(device->getExecutionEnvironment()->rootDeviceEnvironments[0]->osInterface.get(), 0, device->getDeviceBitfield(), aub_stream::ENGINE_RCS, PreemptionMode::ThreadGroup, false, false, false)); osContext->setDefaultContext(false); auto hwInfo = device->getRootDeviceEnvironment().getMutableHardwareInfo(); hwInfo->capabilityTable.directSubmissionEngines.data[aub_stream::ENGINE_RCS].engineSupported = true; hwInfo->capabilityTable.directSubmissionEngines.data[aub_stream::ENGINE_RCS].useNonDefault = false; bool ret = csr->initDirectSubmission(*device.get(), *osContext.get()); EXPECT_TRUE(ret); EXPECT_FALSE(csr->isDirectSubmissionEnabled()); } TEST_F(WddmCommandStreamTest, givenNonDefaultContextContextWhenDirectSubmissionEnabledOnNonDefaultContextThenExpectFeatureAvailable) { DebugManager.flags.EnableDirectSubmission.set(1); osContext.reset(OsContext::create(device->getExecutionEnvironment()->rootDeviceEnvironments[0]->osInterface.get(), 0, device->getDeviceBitfield(), aub_stream::ENGINE_RCS, PreemptionMode::ThreadGroup, false, false, false)); osContext->setDefaultContext(false); auto hwInfo = device->getRootDeviceEnvironment().getMutableHardwareInfo(); hwInfo->capabilityTable.directSubmissionEngines.data[aub_stream::ENGINE_RCS].engineSupported = true; hwInfo->capabilityTable.directSubmissionEngines.data[aub_stream::ENGINE_RCS].useNonDefault = true; bool ret = csr->initDirectSubmission(*device.get(), *osContext.get()); EXPECT_TRUE(ret); EXPECT_TRUE(csr->isDirectSubmissionEnabled()); } TEST_F(WddmCommandStreamMockGdiTest, givenDirectSubmissionEnabledOnRcsWhenFlushingCommandBufferThenExpectDirectSubmissionUsed) { using Dispatcher = RenderDispatcher; using MockSubmission = MockWddmDirectSubmission; DebugManager.flags.EnableDirectSubmission.set(1); auto hwInfo = device->getRootDeviceEnvironment().getMutableHardwareInfo(); hwInfo->capabilityTable.directSubmissionEngines.data[aub_stream::ENGINE_RCS].engineSupported = true; std::unique_ptr osContext; osContext.reset(OsContext::create(device->getExecutionEnvironment()->rootDeviceEnvironments[0]->osInterface.get(), 0, device->getDeviceBitfield(), aub_stream::ENGINE_RCS, PreemptionMode::ThreadGroup, false, false, false)); osContext->setDefaultContext(true); csr->callParentInitDirectSubmission = false; bool ret = csr->initDirectSubmission(*device.get(), *osContext.get()); EXPECT_TRUE(ret); EXPECT_TRUE(csr->isDirectSubmissionEnabled()); EXPECT_FALSE(csr->isBlitterDirectSubmissionEnabled()); GraphicsAllocation *commandBuffer = memoryManager->allocateGraphicsMemoryWithProperties(MockAllocationProperties{csr->getRootDeviceIndex(), MemoryConstants::pageSize}); ASSERT_NE(nullptr, commandBuffer); LinearStream cs(commandBuffer); BatchBuffer batchBuffer{cs.getGraphicsAllocation(), 0, 0, nullptr, false, false, QueueThrottle::MEDIUM, QueueSliceCount::defaultSliceCount, cs.getUsed(), &cs, commandBuffer->getUnderlyingBuffer()}; csr->flush(batchBuffer, csr->getResidencyAllocations()); auto directSubmission = reinterpret_cast(csr->directSubmission.get()); EXPECT_TRUE(directSubmission->ringStart); size_t actualDispatchSize = directSubmission->ringCommandStream.getUsed(); size_t expectedSize = directSubmission->getSizeSemaphoreSection() + Dispatcher::getSizePreemption() + directSubmission->getSizeDispatch(); EXPECT_EQ(expectedSize, actualDispatchSize); memoryManager->freeGraphicsMemory(commandBuffer); } TEST_F(WddmCommandStreamTest, givenResidencyLoggingAvailableWhenFlushingCommandBufferThenNotifiesResidencyLogger) { if (!NEO::wddmResidencyLoggingAvailable) { GTEST_SKIP(); } GraphicsAllocation *commandBuffer = memoryManager->allocateGraphicsMemoryWithProperties(MockAllocationProperties{csr->getRootDeviceIndex(), MemoryConstants::pageSize}); ASSERT_NE(nullptr, commandBuffer); LinearStream cs(commandBuffer); BatchBuffer batchBuffer{cs.getGraphicsAllocation(), 0, 0, nullptr, false, false, QueueThrottle::MEDIUM, QueueSliceCount::defaultSliceCount, cs.getUsed(), &cs, nullptr}; DebugManagerStateRestore restorer; DebugManager.flags.WddmResidencyLogger.set(1); NEO::IoFunctions::mockFopenCalled = 0u; NEO::IoFunctions::mockVfptrinfCalled = 0u; NEO::IoFunctions::mockFcloseCalled = 0u; wddm->createPagingFenceLogger(); EXPECT_EQ(1u, NEO::IoFunctions::mockFopenCalled); EXPECT_EQ(1u, NEO::IoFunctions::mockVfptrinfCalled); EXPECT_EQ(0u, NEO::IoFunctions::mockFcloseCalled); csr->flush(batchBuffer, csr->getResidencyAllocations()); EXPECT_EQ(1u, NEO::IoFunctions::mockFopenCalled); EXPECT_EQ(3u, NEO::IoFunctions::mockVfptrinfCalled); EXPECT_EQ(0u, NEO::IoFunctions::mockFcloseCalled); memoryManager->freeGraphicsMemory(commandBuffer); } ",16131,True,3434.018520060832,median "= DiaManT Custom Module Development Guide :revnumber: 1.0 :revdate: June 03, 2020 :source-highlighter: highlightjs :toc: macro :toclevels: 5 :sectanchors: true :sectnums: :sectnumlevels: 5 :includedir: ../../styles :title-page: :productname: DiaManT :productversion: 9.13 - 9.14 :experimental: :classification: CONFIDENTIAL :icons: font :data-uri: :imagesdir: toc::[] <<< ifdef::backend-pdf[] :numbered!: == Document revision [options=""header""] |=== | Version | Date | Notes | 1.0 | June 2020 | Initial version |=== <<< include::{includedir}/preface.adoc[] <<< endif::[] <<< :numbered: == Introduction === About this guide The purpose of this document is to introduce the reader to the DiaManT API. Eventually, the reader should be able to create their own implementation for a DiaManT application’s back-end. This implementation is also known as the *Custom Module* and is required in most applications that do more than simple call routing. In chapter <> the CustomModule Archetype is presented - a structured way to get you started with an Omilia back-end implementation. === Introduction to Custom Module The typical architecture of an Application is shown in the next figure: .Custom Module architecture image::images/diam_cust_mod_3.png[Custom Module architecture] A Custom Module is actually the back-end of the Application. The Custom Module (DiaManT API implementation) is responsible for implementing the necessary back-end logic and aims to serve the Front-end’s needs. Its tasks include but are not limited to the following: * Integrate with the back-end Systems. * Implement Complex Business Logic. * Create Dynamic Announcements (Realizers). * Prepare and supply other systems with session data (e.g. CTI Data Handling). * Perform N-Best Validation on user input. === Definitions, Abbreviations, and Acronyms Before we get into the coding details, let’s introduce a few concepts : [horizontal] DiaManT:: Dialog Management Technology. The dialog manager is responsible for delivering a human-like interaction. It handles the conversation with the user by evaluating the dialog context and deciding what the next appropriate action is. Application:: A DiaManT application. The reader should be familiar with a DiaManT application’s structure and configuration before continuing on with this document. Dialog:: An incoming call to the Application. Custom Module:: An implementation of the DiaManT API. Also used as a way to describe the final package (_.jar_) that will contain this implementation. App Config:: Every Application contains a configuration file that is called _DiaManT_App_Config.xml_. This file dictates rules about the dialog flow and communicates with the Custom Module via DiaManT in order to: * Perform back-end actions (for example, call web services). * Validate caller Input. * Create complex announcements Custom Config:: Optionally, an Application can include a configuration file that is to be paired with the Custom Module. The filename is DiaManT_Custom_Config.xml. Realizers:: An optional part of the Custom Module. A FieldRealizer or Realizer is a Java Class that performs Natural Language Generation, i.e. binding prompts dynamically in order to create an announcement that will be voiced to the caller. Methods:: In this document, Java methods are going to be referred to as methods. Each word that is followed by parentheses () in this document refers to a Java method. This same notation is going to be used for methods both with and without parameters. == Application and dialog lifecycle During the application’s lifetime there are callback invocations in a specific order. There are two types of callbacks: * Platform callbacks: `onApplicationStart()`, `onApplicationClose()`, `getCopy()`, `onDialogStart()`, `onDialogEnding()` `onDialogClose()`. * Application callbacks: `applyCustomAction()`, `applyInference()`, `nBestValidate()`. All these methods belong to `CustomModuleAdaptor` class which is the class that a Custom Module must extend in order to work within an Application. Below is a brief description of the most important class’s methods. === onApplicationStart() Called once when the application starts. [source,java] ---- public boolean onApplicationStart(Map properties) ---- This method is overloaded by having an instance of Application as an additional parameter. [source,java] ---- public boolean onApplicationStart(Map properties, Application app) ---- It is recommended that all resources shared among Dialogs are initialized here. The `properties` parameter is a map that stores automatically-parsed properties from the _DiaManT_Custom_Config.xml_. In order for these properties to be automatically parsed, the Custom Config should look like this: [source,xml] ---- ---- .Example **** [source,java] ---- @Override public boolean onApplicationStart(Map properties) { GenericLogger logger = DialogManager.getInstance().getLogger(); logger.log(""Application is starting. Parsing properties from file.""); prop1 = (String) properties.get(""property1""); prop2 = (String) properties.get(""property2""); return true; } ---- **** === onApplicationClose() A callback to when the Application is about to stop. Any cleanup functions should be performed here. .Example **** [source,java] ---- public boolean onApplicationClose() { // cleanupFunction(); return true; } ---- **** === getCopy() A callback for each new Dialog, in order to initialize the Custom Module. This method will create a new instance of custom module for each call. For instance, assuming that five people call the telephone center of a company that uses Omilia’s technology. The `getCopy()` method will be called 5 times, one per each call. One instance of custom module will be created per caller in order to handle each caller’s dialog needs. This method ensures that the API user can create their own constructor with their own arguments as needed. .Example **** [source,java] ---- @Override public DataPooler getCopy() { return new CustomerNameModule(); } ---- **** === onDialogStart() Called every time a new dialog is started. [source,java] ---- boolean onDialogStart(FieldsContainer fieldsContainer) ---- Any resource in the scope of a single dialog should be initialized here. From here on the consumer can log in individual Dialog Log Files, via the `logger` member. The `fieldsContainer` is a DiaManT’s inner class instance that holds all the Fields as declared in the `FieldList` in App Config. .Example **** [source,java] ---- @Override public boolean onDialogStart(FieldsContainer fieldList) { logger.log(""CustomModule instance initialized.""); //get some fields field1 = fieldList.getField(""field1""); field2 = fieldList.getField(""field2""); return true; } ---- **** === onDialogEnding() Called just **before** a dialog ends. NOTE: Replaces **getTransferData()**. The method was kept to preserve backwards compatibility. [source,java] ---- OutgoingSessionData onDialogEnding(EndType endType, FieldsContainer fieldsContainer) ---- Its purpose is to create outgoing session data. The method can also perform actions based on the dialog's end type. With the `fieldsContainer` parameter, the consumer here can read the values and statuses from all Fields. With the `endType` parameter, the consumer can identify how the dialog ended (transfer, user hangup, system hangup etc.) .Example **** [source,java] ---- @Override public OutgoingSessionData onDialogEnding(EndType endType, FieldsContainer fieldsContainer) { switch (endType) { case TRANSFER: logger.log(""The dialog is ending with a transfer.""); break; case FAR_HUP: logger.log(""The dialog is ending with a user hangup.""); break; case NEAR_HUP: logger.log(""The dialog is ending with a system hangup.""); break; default: logger.log(""The dialog is ending with a "" + endType); } Map outgoingData = new HashMap<>(); outgoingData.put(""key1"",""value1""); outgoingData.put(""key2"",""value2""); return OutgoingSessionData.builder().outgoingData(outgoingData).build(); } ---- **** === onDialogClose() Called when a dialog ends. [source,java] ---- boolean onDialogClose() ---- All resources for the specific dialog should be closed now. .Example **** [source,java] ---- @Override public boolean onDialogClose() { // clearDialogResources(); logger.log("" CustomModule instance closed.""); return true; } ---- **** NOTE: The class that extends the `CustomModuleAdaptor` class should always have a default constructor. === The order of callbacks All the callbacks described above are invoked in a specific order which is presented in the following table. [options=""header""] |=== |Timestamp| Method called a|The application starts . A new dialog starts . Application Callbacks . The call is ready to be transferred . The dialog is closing The application is closing a|onApplicationStart() . getCopy() {empty}+ onDialogStart() . Back-end actions, inferences, nBestValidation... . onDialogEnding() . onDialogClose() onApplicationStop() |=== == Custom module features - functionality === Back-end calls Back-end calls are methods that have been declared in the _DiaManT_App_Config.xml_, and now, it’s the Custom Module’s job to implement these methods. A Back-end Call can: . Call a back-end system (Web Service, Database, API) in order to get information like: * Caller identification data (date of birth, VAT, telephone numbers, list of cards, list of accounts, and so on) * A banking product’s monetary balance (card/account) * Airline miles, reward points, and so on . Perform an offline action - for example, compute a sum before a payment or lookup a file in the file system or any other business logic. In order to perform a BackEndCall, DiaManT calls the `applyCustomAction()` method of Custom Module. This can be considered as a method that “generates” all the `BackEndCall` functions needed from the front-end, and thus it’s this method that decides what actions should be performed according to the name of the `BackEndCall` function. .Example implementation **** A typical example of a BackendCall, from the Front-end’s perspective, follows below. [source,xml] ---- ---- **** This `BackEndCall` points to a function named `GetAuthorisationToken`, with two input parameters (CardNumber and PIN), and one output (`AuthenticateOut`). On the back-end’s side, the above-mentioned block of code is going to call the method applyCustomAction() with 2 parameters. The first parameter is the function’s name and the second one is a Map with the input parameters of the function (the CardNumber and the PIN number). [source,java] ---- //applyCustomAction Method @Override public Map applyCustomAction(String function, Map input) ---- On completion of the method’s process, it will return a Map to DiaManT with all the output values that the front-end requested. In the next example, the `applyCustomAction()` serves three different BackEndCalls. [source,java] ---- @Override public Map applyCustomAction(String function, Map inputParams) { Map outputParams = null; switch (function) { case ""GetAuthorisationToken"": //all the processes of authentication, and fill the //outputParams break; case ""GetCardBalance"": //all the processes to get the card balance, and fill the //outputParams break; case ""MakePayment"": //all the processes to make a payment and fill the //outputParams break; default: logger.logWarning(CUSTOMER_NAME_MODULE + ""Action name "" + actionName +"" not found. Please check for typos.""); } return outputParams; } ---- === Inferences Inferences are used for inferring the value of fields based on: . the value of one or more fields. . external knowledge implemented and/or accessed in the custom code. For example, the system can infer a city based on a zip code. So whenever the ZipCode Field gets a value the inference rule is automatically triggered inferring the City Field’s value. In order to perform an inference, DiaManT calls the `applyInference()` method of Custom Module. Similar to applyCustomAction(), the `applyInference()` method decides which inference should be executed according to the name of the inference. Inferences are very similar to BackEndCalls, but two notable differences are: . The inference Output Map is pre-filled, and the Custom Module just updates its values. . DiaManT triggers an inference when at least one of its input fields is updated during the dialog. .Example implementation **** In the next example, an inference called ZipToState is declared in the _DiaManT_App_Config.xml_. [source,xml] ---- ---- The ZipCode inference has one input parameter (ZipCode) and expects one output (the State to which this ZipCode belongs). This inference will be triggered by DiaManT when the ZipCode’s status becomes DEFINED, and the `applyInference()` method is called. [source,java] ---- //applyInference Method @Override public void applyInference(String name, Map inputFields, Map inferredFields) ---- Similarly to BackEndCalls the `applyInference()` method works as a “generator” of inference functions that serves the front-end needs. In the next example, the `applyInference()` serves two2 different Inferences. [source,java] ---- @Override public void applyInference(String name, Map inputFields, Map inferredFields) { switch (name) { //First Inference case ""getBankAcountNumber"": //code to implement the logic of getBankAccountNumber //inference and update the inference inferredFields Map break; //Second Inference case ""ZipToState"": //code to implement the logic of ZipToState //inference and update the inference inferredFields Map break; default: logger.logWarning(CUSTOMER_NAME_MODULE + ""Inference name "" + name + "" not found. Please check for typos.""); } } ---- **** === N – Best Validation There are cases where the caller’s voice input is ambiguous. DiaManT offers a way for the Application to define which Fields might be ambiguous, and instruct the ASR to return N (N = integer) possible recognition results each time one of these Fields is updated. These results are sorted by recognition confidence. The CustomModule receives a callback and performs validation in order to select the first best result out of what was recognized. For example, during a dialog, the last five numbers of a credit card are asked. Then, the client replied: _“thirty four fifty one”_. The client might have meant _“34 51”_, _“30 4 51”_, _“30 4 50 1”_ or _“34 50 1”_. In order to overcome this ambiguity, DiaManT generates all possible combinations and provides the CustomModule with a List of all possible answers. The only thing that is necessary now, is a “rule” that can determine which one is correct. Here's the rule in our example: For every credit card in this Bank, the second to last digit must always be 0. Now we can assume that the client said _34501_ because it is a five-digit number and also has the digit zero in the second to last place. The field that needs N-Best Validations is declared in the _DiaManT_App_Config.xml_. [source,xml] ---- ---- When the _CreditCardLast5_ is triggered, DiaManT calls the `nBestValidate()` method. [source,java] ---- @Override public DiamantEntity nBestValidate(String method, List diamantEntities) ---- The `nBestValidate()` method needs two parameters. The first one is the name of the method, which will determine the operations that `nBestValidate()` will perform, and the second parameter is the List with all recognized values. `nBestValidate()` will return the first value that is valid. .Example implementation **** In the next example, the `nBestValidate()` serves 2 different `ValidateNBest` methods. [source,java] ---- @Override public DiamantEntity nBestValidate(String method, List diamantEntities) { switch (method) { case ""BankAccountNumberValidation"": logger.logInfo(CUSTOMER_NAME_MODULE +""Calling "" + methodName); for (DiamantEntity entity : diamantEntities) { String nbestResult = entity.getFirstInstanceValue(); if (isEmpty(nbestResult)) { logger.logWarning(CUSTOMER_NAME_MODULE+""Empty result""); } else { //all the necessary processes for the BankAccountNumberValidation // NOTE: Read the Notes below the block of code bankAccountNumberStatus.updateInstanceValue(""valid""); return entity; } } logger.logWarning(CUSTOMER_NAME_MODULE + nbestResult + ""is not a valid Bank Account number.""); //NOTE: Read the Notes below the block of code bankAccountNumberStatus.updateInstanceValue(""invalid""); return diamantEntities.get(0); case ""CreditCardLast5"": logger.logInfo(CUSTOMER_NAME_MODULE + ""Calling "" + methodName ); for (DiamantEntity entity : diamantEntities) { String nbestResult = entity.getFirstInstanceValue(); if (isEmpty(nbestResult)) { logger.logWarning(CUSTOMER_NAME_MODULE+""Empty result""); } else { //all the processes for the CreditCardLast5 //NOTE: Read the Notes below the block of code cardStatus.updateInstanceValue(""valid""); return entity; } } logger.logWarning(CUSTOMER_NAME_MODULE + nbestResult + ""is not a valid Credit Card number.""); //NOTE: Read the Notes below the block of code cardStatus.updateInstanceValue(""invalid""); return diamantEntities.get(0); default: logger.logWarning(CUSTOMER_NAME_MODULE + ""Validation name "" + methodName +"" not found. Please check for typos.""); } //NOTE: Read the Notes below the block of code return diamantEntities.get(0); } ---- NOTE: The `bankAccountNumberStatus` and the `cardStatus` are fields in the `FieldList` that are loaded on the `onDialogStart`. This practice has to be applied in agreement with the front-end developer, and thus the front-end will be supplied with valuable information if the nBestValidation succeeded or failed. This approach is used by Omilia, but it’s not mandatory. **** === Natural Language Generation (NLG) / Dynamic Announcements Natural Language Generation (NLG) is a process of generating natural language from any representation. For example, the natural language generation of money representation 25.40$ would be _“twenty-five dollars and forty cents”_. Audio files are combined to produce the generated utterance. ==== Audio files configuration All audio files that will be used in the application must be declared in a separate file named _DiaManT_Audio_Config.xml_. In this file, each audio file is associated with an utterance. These utterances, when combined by the realizers, are building a whole announcement. An example of a _DiaManT_Audio_Config_ file is shown below: .Example implementation **** [source,xml] ---- ---- **** ==== FieldRealizer A Class that implements this interface is called Custom FieldRealizer or Custom Realizer. Realizer’s job is to generate natural language from a Field’s value. Below is a brief description of the interface’s methods: - `registerPrompts()` is called when the Application starts. The implementer must register the individual text Prompts that will be used from the Realizer. For example, a `MonetaryRealizer` should declare the text for each number _0-99_ like this: _“one”_, _“two”_, _“three”_ and so on, and some various prompts like _“dollars”_, _“cents”_. The `promptLibrary` provides a method to register text to DiaManT. After this method is called, DiaManT will match the registered text from the Realizer with the registered audio file from the _DiaManT_Audio_Config.xml_ configuration file. [source,java] ---- void registerPrompts(PromptLibrary promptLibrary, String realizerName) ---- .Example implementation **** An example of registering some prompts is shown below : [source,java] ---- @Override public void registerPrompts(PromptLibrary promptLibrary, String realizerName){ String[] numbers = {""zero"", ""one"", ""two"", ""three"", ""four"", ""five"", ""six"", ""seven"", ""eight"", ""nine"",""ten""}; for (int i = 0; i <=10 ; i++) { numberPromptsID.put( String.valueOf(i), promptLibrary.registerFlaggedPrompt(Locale.EN_US, numbers[i], ""Digit Prompt"", false)); } variousPromptsID.put( ""dollars"", promptLibrary.registerFlaggedPrompt(Locale.EN_US, ""dollars"", ""Various Prompt"", false)); variousPromptsID.put( ""cents"", promptLibrary.registerFlaggedPrompt(Locale.EN_US, ""cents"", ""Various Prompt"", false)); variousPromptsID.put( ""and"", promptLibrary.registerFlaggedPrompt(Locale.EN_US, ""and"", ""Various Prompt"", false)); } ---- **** - `realizeValue()` is called when a Field is part of a dynamic announcement. The first parameter, `type`, is an optional instruction for the method call on how to synthesize the result `Prompt`. The `value` parameter is the value of the `Field` in question. The `fieldsContainer` parameter is the Application’s `FieldList` as provided in the Custom Module’s `onDialogStart()`. The logger parameter is the Dialog’s logger instance. [source,java] ---- PromptID realizeValue(String type, String value, FieldsContainer fieldsContainer, DialogLogger logger) ---- This method is the one responsible to compose and return a dynamic announcement. The return type is `PromptID`. This class represents one, or many prompts tied together. An example of the `realizeValue()` implementation for a simple monetary realizer is shown below. This realizer will turn the money representation 5.10$ to `“five dollars and ten cents”`. .Example implementation **** [source,java] ---- @Override public PromptID realizeValue(String type, String value, FieldsContainer fieldList, DialogLogger logger) { this.logHelper = new LogHelper(logger, MoneyRealizer.class.getSimpleName()); this.logHelper.log(""Realizing value: {0} with realizeType: {1}"", new LogParameter(value, true), new LogParameter(type, false)); try { PromptID pid = new PromptID(); String[] splitValue = value.split(""\\\\.""); String dollarsAmount = splitValue[0]; String centsAmount = splitValue[1]; pid.postAdd(numberPromptsID.get(dollarsAmount), true); pid.postAdd(variousPromptsID.get(""dollars""), true); pid.postAdd(variousPromptsID.get(""and""), true); pid.postAdd(numberPromptsID.get(centsAmount), true); pid.postAdd(variousPromptsID.get(""cents""), true); return pid; } catch (Exception e) { e.printStackTrace(); logHelper.logError(""Exception: {0}"", new LogParameter(e, false)); return new PromptID(); } } ---- **** - `getCopy()` method is treated as a constructor and is called at the start of each Dialog in order to initialize the implementer. [source,java] ---- FieldRealizer getCopy() ---- NOTE: A class that implements FieldRealizer should always have a default constructor. ==== Declare your custom realizers The implemented realizers have to be declared in the _DiaManT_App_Config.xml_ as shown below: [source,xml] ---- ---- [source,xml] ---- ---- And the announcement looks like this: [source,xml] ---- Your current balance is #TY01_currentBalance# ---- == Logging There are two logger instances that can be used: a. the `GenericLogger`. b. the `DialogLogger`. The `GenericLogger` is to be used only outside the scope of a Dialog, which is `onApplicationStart()` and `onApplicationClose()`. Here’s how to access it: [source,java] ---- DialogManager.getInstance().getLogger(); ---- .Example of `GenericLogger` record on server logs image::images/diam_cust_mod_8.png[Example of `GenericLogger` record on server logs] The `DialogLogger` is used everywhere else, and the way to access it is via the logger member in the main Custom Module class (the one that extends the `CustomModuleAdaptor`). An important difference in usage between the two loggers is that the first one writes in the Server Logs and the second writes in the Dialog Log. The Server Logs are accessible through the Dashboard’s DiaManT administration page. The Dialog Log is accessible through the DRT (select a call and then select DiaManT log file). Each Dialog has its own log file, so every call’s events are traceable in a single place, without other calls’ events interference. Below is the table of supported Log Levels, the corresponding method in the Loggers, and the message color: .Supported log levels [options=""header""] |=== |Log Level |Method Signature |Message Color |TRACE |log(String message) |WHITE/GRAY |INFO |logInfo(String message) |YELLOW |WARNING |logWarning(String message) |ORANGE |ERROR |logError(String message) |RED |=== Each one of these levels of logging appears in different colors in the dialog log file. Plain log messages are white/gray, information messages are yellow, warning messages are orange and error messages are red. Log messages have a hierarchy of systems. Each system is separated from a subsystem by using the :> delimiter at the end of the system name, for example : [source,java] ---- logInfo(""CustomModule :> Custom Module instance created.""); ---- According to the next dialog, the corresponding Dialog Logs are presented. .Dialog Logs example image::images/diam_cust_mod_1.png[Dialog Logs example] Firstly, the method `onDialogStart()` is called as shown below. .`onDialogStart()` method called image::images/diam_cust_mod_4.png[`onDialogStart()` method called] Next, the `applyCustomAction()` is called that triggers the associated action and Handler Classes. .`applyCustomAction()` method called image::images/diam_cust_mod_9.png[`applyCustomAction()` method called] The values that returned from the Web Service need to be realized in order to be announced to the client. Thus, the `FXRealizer` is called. .`FXRealizer` called image::images/diam_cust_mod_2.png[`FXRealizer` called] In the end, the Application says Goodbye to the client, and the `onDialogClose()` method is called, as shown below. .`onDialogClose()` method called image::images/diam_cust_mod_5.png[`onDialogClose()` method called] == Omilia archetype === Introduction In order to standardize the Custom Module and make code modular and more readable, Omilia has created its own archetype. In this chapter, Omilia’s patterns are presented. As a prerequisite, you should install JDK 1.8, and IntelliJ IDEA CE. Both can be downloaded from the official Web Sites (for IntelliJ select the Community edition). Lastly, Omilia’s archetype encourages the use of Maven as the project building tool. === Adding DiaManT dependency on local maven repository In order to add the DiaManT _.jar_ file, you need to create a folder path under the _.m2/ repository/_ folder. The _.m2_ folder can be found under the user’s home folder. Navigate to the _m2/ repository/_ folder. In this folder, you will need to create the following folder structure: _com/omilia/diamant/diamant-core/_. After the creation of the folders, you should place the DiaManT _.jar_ file in the _diamant-core_ folder you created. The DiaManT _.jar_ file has to be renamed to _diamant-core-.jar_. Maven looks for a dependency in the _.m2/repository_ folder according to the dependency declaration in the following way: `` and `` describe the folder structure (like the one you created before). Then Maven will look for a _jar_ name the content of the artifactId, followed by a dash, followed by the version. For example, for the following dependency, maven will look for a _jar_ named _diamant-core-9.13.0.jar_ under _.m2/ repository/com/omilia/diamant/diamant-core/_. Now, you can use DiaManT with maven by adding the following to your _pom.xml_: [source,xml] ---- com.omilia.diamant diamant-core 9.13.0 provided ---- === Project structure This is a typical Maven project structure. Here is a short description of each package. .Maven project structure image::images/diam_cust_mod_10.png[float=""left"", Maven project structure] actions:: contains every action. Actions are built by extending `AbstractAction` which partially implements Action interface. constants:: package for all the constants. inferences:: contains all the inferences. Inferences are built by extending the `AbstractInference`. nbestvalidation:: contains all the `nBestValidations`. `nBestValidations` are built by extending the `AbstractNBestValidation` class. properties:: Miscellaneous project properties. realizers:: contain all the realizers and realizer related sub-packages like prompts which contain a `PromptCollection` class for each realizer. utils:: Miscellaneous helper classes for the project. webservices.handlers:: All handlers for accessing web services. Handlers are built by extending the `AbstractHandler` class. webservices.requests:: contains all requests needed for calling the web services. webservice.responses:: all the expected responses from web services. resources.prompts.en_US:: the package of all JSON files which contains English prompts and will be used by realizers. === Data source access When the Custom Module needs data from any data source, the common architecture that is followed is to create three classes for each data call. These classes are : * A Request class. * A Handlers class * A Response class. ==== Requests Request classes model the back-ends system’s request into an Object and follow the next pattern: * Each class exists in the package requests. * Each class’s name ends in “_....Request”_. * Each class extends the Request class. * Each class has setters for all the class members. .Example implementation **** Assuming that our Application requires to call a RESTFUL web service in order to obtain a token, named `GetToken`. Here’s an example request: [source,java] ---- { ""cardNumber"": ""4735339478512110"", ""pin"": ""1234"" } ---- In order to call the mentioned web service, firstly we have to create the `GetTokenRequest` class that extends the Request, and have setters for all the class members. [source,java] ---- public class GetTokenRequest extends Request { private String cardNumber; private String pin; public GetTokenRequest() { } public void setCardNumber(String cardNumber) { this.cardNumber = cardNumber; } public void setPin(String pin) { this.pin = pin; } } ---- **** ==== Handlers Handlers are classes that have the responsibility to call the Web Service and to create the Response object. Every handler follows the next pattern. * Each class exists in the package handlers. * Each class’s name ends in “_....Handler_”. * Each class extends the AbstractHandler class and has to implement all the inherited abstract methods. * Each class has a request as input. * Each class creates a response object. .Example implementation **** Now we have to create the `GetTokenHandler` that extends the `AbstractHandler`, sets the request, executes the post Request and creates the Response Object. [source,java] ---- public class GetTokenHandler extends AbstractHandler { private GetTokenRequest request = new GetTokenRequest(); public GetTokenHandler(DialogLogger logger, String endpoint) { super(logger, endpoint, GetTokenHandler.class.getSimpleName()); } public void setRequest(GetTokenRequest request) { this.request = request; } @Override public boolean initialize() { log(""GetTokenHandler initialized."", LogParameter.noParams()); return true; } @Override public Response getResponse() { log(""Preparing to call the WebService for GetAuthorisationToken with request {0}"", new LogParameter(request, true)); //call the Web Service String output = WebUtilities.sendPostRequest(request, getEndpoint()); if (isNull(output)) { log(""The web service did not respond"", LogParameter.noParams()); return getErrorResponse(); } //Web Service Responded log(""WebService call was successful "", LogParameter.noParams()); log(""Parsing String {0} to POJO "", new LogParameter(output, true)); //Handling the web service's output, and create the necessary Response //object. This can be different according to your needs. Response response = WebUtilities.gson.fromJson(output, GetTokenResponse.class); //Web Service Status is everything but Successful if (!ResponseObjects.SUCCESS.equals(response.getStatusCode())) { log(""Response status code is {0}."", new LogParameter(response.getStatusCode(),false)); return new Response(response.getStatusCode(), response.getStatusMsg()); } //Web Service call returned Success log(""Response status code is SUCCESS"", LogParameter.noParams()); return response; } @Override public Response getErrorResponse() { return new Response(ResponseObjects.ERROR, ResponseObjects.ERROR_MSG); } } ---- **** ==== Responses Response classes model the back-end system response into an Object and follow the pattern below: * Each class exists in the package responses. * Each class’s name ends in “_....Response_”. * Each class extends the Response class. * Each class has getters for all the class members. .Example implementation **** In the previous example, the response of the web service is the following : [source,java] ---- { ""statusCode"": ""SUCCESS"", ""statusMsg"": ""Request Processed successfully"", ""token"": ""50CF18DC2B30E4CDA6B40C2C4E0F8337"" } ---- In order to model the mentioned response, we have to create the `GetTokenResponse` class that extends the Response, with all arguments constructor and getter for the class variable. [source,java] ---- public class GetTokenResponse extends Response { private String token; public GetTokenResponse(String returnCode, String statusMsg, String token) { super(returnCode, statusMsg); this.token = token; } public String getToken() { return token; } } ---- **** === Actions In the process of keeping the code clean and modular, each `BackEndCall` is associated with one action class. Action classes implement all the business logic that App Config requires, and thus, the `applyCustomAction()` method creates the necessary actions objects according to the input function name. The goal is to avoid having any business logic inside this method. Every action follows the next pattern: * Each class’s name ends in “_...Action_” or “_...Call_”. * Each class extends the AbstractAction. * An action can have many Handler class members. * Each class has a constructor,that sets the input from DiaManT (as defined in the App Config). * Each class has a method named process(), that : ** Reads the input fields. ** Applies pre-processing business logic. ** Calls the Web Services / DB / back-end Systems through Handlers. ** Applies post-processing business logic. ** Stores output fields. .Example implementation **** Following the previous example, a `BackEndCall` follows: [source,xml] ---- ---- Below you will find the implementation of the `AuthenticateAction`. [source,java] ---- public class AuthenticateAction extends AbstractAction { private String token; public String getToken() { return token; } public AuthenticateAction(Map input, DialogLogger logger) { super(input, logger, AuthenticateAction.class.getSimpleName()); } @Override public void process() { if (isNull(input.get(Inputs.CARD_NUMBER))||isNull(input.get(Inputs.PIN))) { addToMap(output, OutputNames.AUTHENTICATE_OUT, OutputValues.ERROR); logError(""Missing request element. Action output field \\"""" + OutputNames.AUTHENTICATE_OUT + ""\\"" is {0}"",new LogParameter(output.get(OutputNames.AUTHENTICATE_OUT).getValue(), false)); return; } //create and initialize the getTokenHandler GetTokenHandler handler = new GetTokenHandler(logger, Endpoints.BASE_URL + Endpoints.GET_TOKEN); handler.initialize(); //create request - read input fields GetTokenRequest request = new GetTokenRequest(input.get(Inputs.CARD_NUMBER) .getValue(), input.get(Inputs.PIN).getValue()); //set the request to handler handler.setRequest(request); //Call Web Service Response response = handler.getResponse(); String result; //check response status code switch (response.getStatusCode()) { case ResponseObjects.SUCCESS: result = OutputValues.SUCCESS; //Add token to input map in order to be available to other actions GetTokenResponse tokenResponse = (GetTokenResponse) response; this.token = tokenResponse.getToken(); break; case ResponseObjects.NOT_FOUND: result = OutputValues.FAIL; break; default: result = OutputValues.ERROR; } //Store output fields addToMap(output, OutputNames.AUTHENTICATE_OUT, result); log(""Action output field \\"""" + OutputNames.AUTHENTICATE_OUT + ""\\"" is {0}"", new LogParameter(result, false)); } } ---- Now the `applyCustomAction()` method looks like the following. [source,java] ---- @Override public Map applyCustomAction(String actionName, Map inputParams) { Map outputParams = null; switch (actionName) { case ""authenticateOut"": //create the action object AuthenticateAction authenticateAction = new AuthenticateAction(inputParams, logger); //call the process authenticateAction.process(); //store the output fields outputParams = authenticateAction.getOutput(); //set the class variable token this.token = authenticateAction.getToken(); break; //example of another action case ""anotherAction"": AnotherAction anotherAction = new AnotherAction(inputParams, logger); anotherAction.process(); outputParams = anotherAction.getOutput(); break; default: logger.logWarning(CUSTOMER_NAME_MODULE + ""Action name "" + actionName + "" not found. Please check for typos.""); } return outputParams; } ---- **** === Inferences Similar to actions, inferences go to their own package. Create one class per inference, so that the `applyInference()` method has to create the appropriate inference object, and call the `inferFields()` method. Every inference follows the next pattern: * One class per inference (as defined in the App Config). * Each class’s name ends in “_...Inference_”. * Each class extends the AbstractInference class. * Each inference class has a constructor that sets the input from DiaManT (as Defined in the App Config). * Each class has a method named inferFields, that: ** Reads the input fields. ** Applies pre-processing business logic. ** Calls the Web Services / DB / back-end Systems through Handlers. ** Applies post-processing business logic. ** Stores results in the PRE-FILLED inferredFields map. .Example implementation **** In the next example, an implementation of an inference class is presented. In this example, the input is a List with all the Bank Accounts that a client has, and a 3 digit string. The inference must find the Bank Account with the number that ends in the provided 3 digit string. The next block of code presents the declaration of this inference in the _DiaManT_App_Config.xml_. [source,xml] ---- ---- Bellow, you can see the implementation of the `FullBankAccountInference`: [source,java] ---- public class GetFullBankAccountNumberInference extends AbstractInference { private List openAccountList; //constructor public GetFullBankAccountNumberInference(Map inputFields, Map inferredFields, List openAccountList, DialogLogger logger) { super(inputFields, inferredFields, logger, GetFullBankAccountNumberInference.class.getSimpleName()); this.openAccountList = openAccountList; } @Override public void inferFields() { log(""GetFullBankAccountNumberInference"",LogParameter.noParams()) //Read input fields String bankAccountLast3 = inputFields.get(“AccountLastThree”).getValue() //check all the list for the correct bank account and the first one that //matches is returned for (BankAccount current : openAccountList) { String last3 = StringUtils.substring(current.getBankAccountNumber(), -3); if (bankAccountLast3.equals(last3)) { log(""Bank account inferred: {0}"", new LogParameter(current.getBankAccountNumber(), false)); //store results in the PRE-FILLED inferredFields map defineApiField(inferredFields.get(“FullBankAccountNumber”), current.getBankAccountNumber()); return; } } //Didn't find the bank account log(""Could not find the bank account. "", LogParameter.noParams()); //Apply post-processing business logic and store results in the // inferredFields map inferredFields.get(“AccountLastThree”).setStatus(FieldStatus.UNDEFINED); log(""The status of the field AccountLastThree is {0} "", new LogParameter(inferredFields.get(“AccountLastThree”).getStatus(),false)); inferredFields.get(“FullBankAccountNumber”).setValue(""error""); log(""The value of the field FullBankAccountNumber is {0} "", new LogParameter(inferredFields.get(“FullBankAccountNumber”).getValue(), false)); } } ---- Now, the `applyInference` method looks like this: [source,java] ---- @Override public void applyInference(String name, Map inputFields,Map inferredFields) { switch (name) { case ""getFullBankAccountNumber"": //create the inference object GetFullBankAccountNumberInference getFullBankAccountNumberInference = new GetFullBankAccountNumberInference(inputFields, inferredFields, openAccountList, logger); //call the inferfields method getFullBankAccountNumberInference.inferFields(); break; //example of another inference case ""anotherInference"": AnotherInference anotherInference = new AnotherInference(inputFields, inferredFields, anotherCollection, logger); anotherInference.inferFields(); break; default: logger.logWarning(CUSTOMER_NAME_MODULE + ""Inference name "" + name + "" not found. Please check for typos.""); } } ---- **** === NBestValidation For each `nBestValidation`, one Validation class has to be created. Then, the `nBestValidate()` method has to create the appropriate validate object, that calls its `validate()` method. Every nBestValidation follow the next pattern: * One class per nBestValidation. * Each class’s name ends in “_...Validation_”. * Each class extends the AbstractNBestValidation. * Each class has a constructor, that sets the input from DiaManT. The input is a list of `DiamantEntities ( List diamantEntities)`. * Each class has a method called `validate()`, that: ** Iterates through the List of DiaManT Entities. ** Applies business logic. ** Returns a `DiamantEntity`. .Example implementation **** In the next example, an implementation of an `nBestValidation` is presented. The purpose of this `nBestValidation` is to validate whether the given number is a valid bank number or not. The declaration of this `nBestValidation` in the _DiaManT_App_Config.xml_ is the following: [source,xml] ---- ---- It is assumed that a static method named `isValid()` is implemented in the `BankAccountUtils` class. [source,java] ---- public class BankAccountNumberValidation extends AbstractNBestValidation { private Field bankAccountNumberStatus; public BankAccountNumberValidation (DialogLogger logger, List diamantEntities, Field bankAccountNumberStatus) { super(logger, ExampleNBestValidation.class.getSimpleName(), diamantEntities); this.bankAccountNumberStatus = bankAccountNumberStatus; } @Override public DiamantEntity validate() { for (DiamantEntity entity : diamantEntities) { String nbestResult = entity.getFirstInstanceValue(); if (isEmpty(nbestResult)) { logWarning(CUSTOMMODULE + ""N-best result is empty Ignoring..."", LogParameter.noParams()); //A specific method is implemented in the CreditCardUtils // class to validate if a card number is valid } else if (!BankAccountUtils.isValid(nbestResult)) { logWarning(CUSTOMMODULE + nbestResult + ""is not a valid value"", LogParameter.noParams()); } else { //inform that a valid field is returned bankAccountNumberStatus.updateInstanceValue(""valid""); //sanitize nbestResult = deleteWhitespace(nbestResult); //return DiamantEntity with sanitized value return createDiamantEntity(entity.getEntityName(), nbestResult); } } //There is not a valid DiamantEntity in the given diamantEntities logWarning(CUSTOMMODULE + ""No valid value in the diamantEntities"", LogParameter.noParams()); //inform the front end that the returned entity is not valid, by updating a // field bankAccountNumberStatus.updateInstanceValue(""invalid""); //return the first return diamantEntities.get(0); } } ---- NOTE: The `bankAccountNumberStatus` is a field in the `FiledList` that is loaded in the `onDialogStart()` method. This practice has to be applied in agreement with the front-end developer, and thus the front-end will be supplied with valuable information if the `nBestValidation` succeeded or failed. This approach is used by Omilia, but it’s not mandatory. The `nBestValidate()` method looks like the next one. [source,java] ---- @Override public DiamantEntity nBestValidate(String methodName, List diamantEntities) { switch (methodName) { case ""bankAccountNumberValidation"": logger.logInfo(CUSTOMER_NAME_MODULE + ""Calling "" + methodName ); BankAccountNumberValidation validation = new BankAccountNumberValidation(logger, diamantEntities, bankAccountNumberStatus); return validation.validate(); default: logger.logWarning(CUSTOMER_NAME_MODULE + ""Validation name "" + methodName +"" not found. Please check for typos.""); } return diamantEntities.get(0); } ---- **** === Registering Prompts Omilia’s strategy about registering prompts is to store all prompts related to a specific realizer in a separated JSON file. This file is stored under the resources folder and in a package named as _pass:c[prompts.{local}]_ where local is a specific language code. The naming convention for this file is _pass:c[{RealizerName}Prompts.json]_. For example, all the English prompts that will be used in a DigitRealizer, will be found in the file _resources/prompts.en_us/DigitPrompts.json_ The JSON file must have the form shown below. [source,java] ---- { ""Digit Prompts"": { ""Single Digit Prompts"": { ""0"": ""zero"", ""1"": ""one"", ""2"": ""two"", ""3"": ""three"", ""4"": ""four"", ""5"": ""five"", ""6"": ""six"", ""7"": ""seven"", ""8"": ""eight"", ""9"": ""nine"" }, ""Other Category Prompts"": { ... } } } ---- Then the prompts JSON file has to be parsed and each prompt has to be registered. This is a standard procedure so Omilia’s archetype provides the `AbstractPromptsCollection` class which implements some of the methods of `PromptCollection` interface. The unimplemented methods have to be implemented by all subclasses of `AbstractPromptCollection` class. Every realizer must have its own `PromptCollection` object. A `JsonUtilities` class is also provided in order to parse the json file. Below is the `DigitPrompts` class which implements the register method and is used to create the `PromptCollection` object of `DigitRealizer`. .Example implementation **** [source,java] ---- @Getter public class DigitPrompts extends AbstractPromptCollection { private Map digitPromptsID; private Map digitPrompts; public DigitPrompts(Locale locale) { super(locale); String jsonPath = MessageFormat.format(""/prompts/{0}_US/DigitPrompts.json"", getLanguageCode(locale)); //parse json file Map parsedJson = JsonUtilities.loadJson(jsonPath, ""Digit Prompts""); digitPrompts = JsonUtilities.loadPromptMap(parsedJson, ""Single Digit Prompts""); } @Override public void register(PromptLibrary promptLibrary) { digitPromptsID = register(digitPrompts, ""Single Digit Prompts"", promptLibrary, """"); } @Override public void registerForTest() { digitPromptsID = registerForTest(digitPrompts, """"); } } ---- From this point, it is easy registering all the prompts as calling the register method of `DigitPrompts` class from registerPrompts method of `DigitRealizer` class. [source,java] ---- public class DigitsRealizer implements FieldRealizer { //create the PromptCollection object private static final DigitPrompts english = new DigitPrompts(Locale.EN_US); @Override public void registerPrompts(PromptLibrary promptLibrary, String realizerName){ english.register(promptLibrary); } ... } ---- **** === Environment One major advantage of Custom Module is the ability to perform differently according to the environment that is set up, without any modifications in the source code. The environment should be set up in the method `onApplicationStart()`, according to the developer’s or project’s needs. The developer is free to create their own configuration file, or to use the _Custom_Config.xml_, in order to declare the value of the environment. The environment types are declared in the Environment class, inside the package properties. In the Omillia’s Archetype three environments exist. The LAB environment which is used as the local development environment, the UAT which is the testing environment of the client, and lastly you will find the PROD environment, which stands for the production environment. The developer is encouraged to extend this enum according to their needs, and add more environments, for example, UAT-A, UAT-B, and so on. === Logging API The Omilia’s archetype offers a built-in `LogHelper` class, which can be extended. Any class that extends the `LogHelper` is able to log with the `DialogLogger`. The logging is similar to `printf()` and can log data dynamically. Example 1:: [source,java] ---- log(""This logging example does not have parameters "", LogParameter.noParams()); ---- Example 2:: [source,java] ---- log(""Example value is {0}"", new LogParameter(exampleValue, isSensitive)); ---- The second parameter (`isSensitive`) can mask in the production environment (PROD) any data that is sensitive (for example, a card number, a pin number, and so on). If the value of this parameter is true, the data will be masked and logged with asterisks (pass:c[*]). However in a testing environment (LAB, UAT) the data will not be masked. You can modify the logic that masks the sensitive data from the LogHelper class. == Getting Finished After the development of a Custom Module, a _.jar_ file should be created and included in the folder that contains all the Application’s files. In order to build a _.jar_ file, Intellij's Maven tool window can be used. In the up-right corner of the window, a Maven button can be found. Then, the user has to select the Lifecycle folder and execute the package option. .Intellij's Maven tool window image::images/diam_cust_mod_7.png[Intellij's Maven tool window] When the build finishes, the _.jar_ file will have been created, and the user can find it in the target folder. It is also necessary to declare the Custom Module in the App Config, as follows. [source,xml] ---- ---- The attribute `name` in the tag ``, refers to the class that extends the `CustomModuleAdaptor`. ",12195,False,2080.793305273571,median "/** * MaNGOS is a full featured server for World of Warcraft, supporting * the following clients: 1.12.x, 2.4.3, 3.3.5a, 4.3.4a and 5.4.8 * * Copyright (C) 2005-2017 MaNGOS project * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * World of Warcraft, and all World of Warcraft or Warcraft art, images, * and lore are copyrighted by Blizzard Entertainment, Inc. */ #include ""Common.h"" #include ""CreatureEventAI.h"" #include ""CreatureEventAIMgr.h"" #include ""ObjectMgr.h"" #include ""Spell.h"" #include ""World.h"" #include ""Cell.h"" #include ""CellImpl.h"" #include ""GameEventMgr.h"" #include ""GridNotifiers.h"" #include ""GridNotifiersImpl.h"" #include ""InstanceData.h"" #include ""Chat.h"" #include ""Language.h"" bool CreatureEventAIHolder::UpdateRepeatTimer(Creature* creature, uint32 repeatMin, uint32 repeatMax) { if (repeatMin == repeatMax) { Time = repeatMin; } else if (repeatMax > repeatMin) { Time = urand(repeatMin, repeatMax); } else { sLog.outErrorEventAI(""Creature %u using Event %u (Type = %u) has RandomMax < RandomMin. Event repeating disabled."", creature->GetEntry(), Event.event_id, Event.event_type); Enabled = false; return false; } return true; } int CreatureEventAI::Permissible(const Creature* creature) { if (creature->GetAIName() == ""EventAI"") { return PERMIT_BASE_SPECIAL; } return PERMIT_BASE_NO; } void CreatureEventAI::GetAIInformation(ChatHandler& reader) { reader.PSendSysMessage(LANG_NPC_EVENTAI_PHASE, (uint32)m_Phase); reader.PSendSysMessage(LANG_NPC_EVENTAI_MOVE, reader.GetOnOffStr(m_isCombatMovement)); reader.PSendSysMessage(LANG_NPC_EVENTAI_COMBAT, reader.GetOnOffStr(m_MeleeEnabled)); if (sLog.HasLogFilter(LOG_FILTER_EVENT_AI_DEV)) // Give some more details if in EventAI Dev Mode { return; } reader.PSendSysMessage(""Current events of this creature:""); for (CreatureEventAIList::const_iterator itr = m_CreatureEventAIList.begin(); itr != m_CreatureEventAIList.end(); ++itr) { if (itr->Event.action[2].type != ACTION_T_NONE) { reader.PSendSysMessage(""%u Type%3u (%s) Timer(%3us) actions[type(param1)]: %2u(%5u) -- %2u(%u) -- %2u(%5u)"", itr->Event.event_id, itr->Event.event_type, itr->Enabled ? ""On"" : ""Off"", itr->Time / 1000, itr->Event.action[0].type, itr->Event.action[0].raw.param1, itr->Event.action[1].type, itr->Event.action[1].raw.param1, itr->Event.action[2].type, itr->Event.action[2].raw.param1); } else if (itr->Event.action[1].type != ACTION_T_NONE) { reader.PSendSysMessage(""%u Type%3u (%s) Timer(%3us) actions[type(param1)]: %2u(%5u) -- %2u(%5u)"", itr->Event.event_id, itr->Event.event_type, itr->Enabled ? ""On"" : ""Off"", itr->Time / 1000, itr->Event.action[0].type, itr->Event.action[0].raw.param1, itr->Event.action[1].type, itr->Event.action[1].raw.param1); } else { reader.PSendSysMessage(""%u Type%3u (%s) Timer(%3us) action[type(param1)]: %2u(%5u)"", itr->Event.event_id, itr->Event.event_type, itr->Enabled ? ""On"" : ""Off"", itr->Time / 1000, itr->Event.action[0].type, itr->Event.action[0].raw.param1); } } } // For Non Dungeon map only allow non-difficulty flags or EFLAG_DIFFICULTY_0 mode inline bool IsEventFlagsFitForNormalMap(uint8 eFlags) { return !(eFlags & (EFLAG_DIFFICULTY_0 | EFLAG_DIFFICULTY_1 | EFLAG_DIFFICULTY_2 | EFLAG_DIFFICULTY_3)) || (eFlags & EFLAG_DIFFICULTY_0); } CreatureEventAI::CreatureEventAI(Creature* c) : CreatureAI(c), m_Phase(0), m_MeleeEnabled(true), m_InvinceabilityHpLevel(0), m_throwAIEventMask(0), m_throwAIEventStep(0) { // Need make copy for filter unneeded steps and safe in case table reload CreatureEventAI_Event_Map::const_iterator creatureEventsItr = sEventAIMgr.GetCreatureEventAIMap().find(m_creature->GetEntry()); if (creatureEventsItr != sEventAIMgr.GetCreatureEventAIMap().end()) { uint32 events_count = 0; for (CreatureEventAI_Event_Vec::const_iterator i = creatureEventsItr->second.begin(); i != creatureEventsItr->second.end(); ++i) { // Debug check #ifndef MANGOS_DEBUG if (i->event_flags & EFLAG_DEBUG_ONLY) { continue; } #endif if (m_creature->GetMap()->IsDungeon()) { if ((1 << (m_creature->GetMap()->GetSpawnMode() + 1)) & i->event_flags) { ++events_count; } } else if (IsEventFlagsFitForNormalMap(i->event_flags)) ++events_count; } // EventMap had events but they were not added because they must be for instance if (events_count == 0) sLog.outErrorEventAI(""Creature %u has events but no events added to list because of instance flags (spawned in map %u, difficulty %u)."", m_creature->GetEntry(), m_creature->GetMapId(), m_creature->GetMap()->GetDifficulty()); else { m_CreatureEventAIList.reserve(events_count); for (CreatureEventAI_Event_Vec::const_iterator i = creatureEventsItr->second.begin(); i != creatureEventsItr->second.end(); ++i) { // Debug check #ifndef MANGOS_DEBUG if (i->event_flags & EFLAG_DEBUG_ONLY) { continue; } #endif if (m_creature->GetMap()->IsDungeon()) { if ((1 << (m_creature->GetMap()->GetSpawnMode() + 1)) & i->event_flags) { // event flagged for instance mode m_CreatureEventAIList.push_back(CreatureEventAIHolder(*i)); } } else if (IsEventFlagsFitForNormalMap(i->event_flags)) m_CreatureEventAIList.push_back(CreatureEventAIHolder(*i)); } } } else { sLog.outErrorEventAI(""EventMap for Creature %u is empty but creature is using CreatureEventAI."", m_creature->GetEntry()); } // Handle Spawned Events, also calls Reset() JustRespawned(); } #define LOG_PROCESS_EVENT \\ DEBUG_FILTER_LOG(LOG_FILTER_EVENT_AI_DEV, ""CreatureEventAI: Event type %u (script %u) triggered for %s (invoked by %s)"", \\ pHolder.Event.event_type, pHolder.Event.event_id, m_creature->GetGuidStr().c_str(), pActionInvoker ? pActionInvoker->GetGuidStr().c_str() : """") inline bool IsTimerBasedEvent(EventAI_Type type) { switch (type) { case EVENT_T_TIMER_IN_COMBAT: case EVENT_T_TIMER_OOC: case EVENT_T_TIMER_GENERIC: case EVENT_T_MANA: case EVENT_T_HP: case EVENT_T_TARGET_HP: case EVENT_T_TARGET_CASTING: case EVENT_T_FRIENDLY_HP: case EVENT_T_AURA: case EVENT_T_TARGET_AURA: case EVENT_T_MISSING_AURA: case EVENT_T_TARGET_MISSING_AURA: case EVENT_T_RANGE: case EVENT_T_ENERGY: return true; default: return false; } } bool CreatureEventAI::ProcessEvent(CreatureEventAIHolder& pHolder, Unit* pActionInvoker, Creature* pAIEventSender /*=NULL*/) { if (!pHolder.Enabled || pHolder.Time) { return false; } // Check the inverse phase mask (event doesn't trigger if current phase bit is set in mask) if (pHolder.Event.event_inverse_phase_mask & (1 << m_Phase)) { if (!IsTimerBasedEvent(pHolder.Event.event_type)) { DEBUG_FILTER_LOG(LOG_FILTER_EVENT_AI_DEV, ""CreatureEventAI: Event %u skipped because of phasemask %u. Current phase %u"", pHolder.Event.event_id, pHolder.Event.event_inverse_phase_mask, m_Phase); } return false; } if (!IsTimerBasedEvent(pHolder.Event.event_type)) { LOG_PROCESS_EVENT; } CreatureEventAI_Event const& event = pHolder.Event; // Check event conditions based on the event type, also reset events switch (event.event_type) { case EVENT_T_TIMER_IN_COMBAT: if (!m_creature->IsInCombat()) { return false; } LOG_PROCESS_EVENT; // Repeat Timers pHolder.UpdateRepeatTimer(m_creature, event.timer.repeatMin, event.timer.repeatMax); break; case EVENT_T_TIMER_OOC: if (m_creature->IsInCombat() || m_creature->IsInEvadeMode()) { return false; } LOG_PROCESS_EVENT; // Repeat Timers pHolder.UpdateRepeatTimer(m_creature, event.timer.repeatMin, event.timer.repeatMax); break; case EVENT_T_TIMER_GENERIC: LOG_PROCESS_EVENT; // Repeat Timers pHolder.UpdateRepeatTimer(m_creature, event.timer.repeatMin, event.timer.repeatMax); break; case EVENT_T_HP: { if (!m_creature->IsInCombat() || !m_creature->GetMaxHealth()) { return false; } uint32 perc = (m_creature->GetHealth() * 100) / m_creature->GetMaxHealth(); if (perc > event.percent_range.percentMax || perc < event.percent_range.percentMin) { return false; } LOG_PROCESS_EVENT; // Repeat Timers pHolder.UpdateRepeatTimer(m_creature, event.percent_range.repeatMin, event.percent_range.repeatMax); break; } case EVENT_T_MANA: { if (!m_creature->IsInCombat() || !m_creature->GetMaxPower(POWER_MANA)) { return false; } uint32 perc = (m_creature->GetPower(POWER_MANA) * 100) / m_creature->GetMaxPower(POWER_MANA); if (perc > event.percent_range.percentMax || perc < event.percent_range.percentMin) { return false; } LOG_PROCESS_EVENT; // Repeat Timers pHolder.UpdateRepeatTimer(m_creature, event.percent_range.repeatMin, event.percent_range.repeatMax); break; } case EVENT_T_AGGRO: break; case EVENT_T_KILL: // Repeat Timers pHolder.UpdateRepeatTimer(m_creature, event.kill.repeatMin, event.kill.repeatMax); break; case EVENT_T_DEATH: case EVENT_T_EVADE: break; case EVENT_T_SPELLHIT: // Spell hit is special case, param1 and param2 handled within CreatureEventAI::SpellHit // Repeat Timers pHolder.UpdateRepeatTimer(m_creature, event.spell_hit.repeatMin, event.spell_hit.repeatMax); break; case EVENT_T_RANGE: // Repeat Timers pHolder.UpdateRepeatTimer(m_creature, event.range.repeatMin, event.range.repeatMax); break; case EVENT_T_OOC_LOS: // Repeat Timers pHolder.UpdateRepeatTimer(m_creature, event.ooc_los.repeatMin, event.ooc_los.repeatMax); break; case EVENT_T_SPAWNED: break; case EVENT_T_TARGET_HP: { if (!m_creature->IsInCombat() || !m_creature->getVictim() || !m_creature->getVictim()->GetMaxHealth()) { return false; } uint32 perc = (m_creature->getVictim()->GetHealth() * 100) / m_creature->getVictim()->GetMaxHealth(); if (perc > event.percent_range.percentMax || perc < event.percent_range.percentMin) { return false; } LOG_PROCESS_EVENT; // Repeat Timers pHolder.UpdateRepeatTimer(m_creature, event.percent_range.repeatMin, event.percent_range.repeatMax); break; } case EVENT_T_TARGET_CASTING: if (!m_creature->IsInCombat() || !m_creature->getVictim() || !m_creature->getVictim()->IsNonMeleeSpellCasted(false, false, true)) { return false; } LOG_PROCESS_EVENT; // Repeat Timers pHolder.UpdateRepeatTimer(m_creature, event.target_casting.repeatMin, event.target_casting.repeatMax); break; case EVENT_T_FRIENDLY_HP: { if (!m_creature->IsInCombat()) { return false; } Unit* pUnit = DoSelectLowestHpFriendly((float)event.friendly_hp.radius, event.friendly_hp.hpDeficit); if (!pUnit) { return false; } pActionInvoker = pUnit; LOG_PROCESS_EVENT; // Repeat Timers pHolder.UpdateRepeatTimer(m_creature, event.friendly_hp.repeatMin, event.friendly_hp.repeatMax); break; } case EVENT_T_FRIENDLY_IS_CC: { if (!m_creature->IsInCombat()) { return false; } std::list pList; DoFindFriendlyCC(pList, (float)event.friendly_is_cc.radius); // List is empty if (pList.empty()) { return false; } // We don't really care about the whole list, just return first available pActionInvoker = *(pList.begin()); // Repeat Timers pHolder.UpdateRepeatTimer(m_creature, event.friendly_is_cc.repeatMin, event.friendly_is_cc.repeatMax); break; } case EVENT_T_FRIENDLY_MISSING_BUFF: { std::list pList; DoFindFriendlyMissingBuff(pList, (float)event.friendly_buff.radius, event.friendly_buff.spellId); // List is empty if (pList.empty()) { return false; } // We don't really care about the whole list, just return first available pActionInvoker = *(pList.begin()); // Repeat Timers pHolder.UpdateRepeatTimer(m_creature, event.friendly_buff.repeatMin, event.friendly_buff.repeatMax); break; } case EVENT_T_SUMMONED_UNIT: case EVENT_T_SUMMONED_JUST_DIED: case EVENT_T_SUMMONED_JUST_DESPAWN: { // Prevent event from occuring on no unit or non creatures if (!pActionInvoker || pActionInvoker->GetTypeId() != TYPEID_UNIT) { return false; } // Creature id doesn't match up if (((Creature*)pActionInvoker)->GetEntry() != event.summoned.creatureId) { return false; } // Repeat Timers pHolder.UpdateRepeatTimer(m_creature, event.summoned.repeatMin, event.summoned.repeatMax); break; } case EVENT_T_TARGET_MANA: { if (!m_creature->IsInCombat() || !m_creature->getVictim() || !m_creature->getVictim()->GetMaxPower(POWER_MANA)) { return false; } uint32 perc = (m_creature->getVictim()->GetPower(POWER_MANA) * 100) / m_creature->getVictim()->GetMaxPower(POWER_MANA); if (perc > event.percent_range.percentMax || perc < event.percent_range.percentMin) { return false; } // Repeat Timers pHolder.UpdateRepeatTimer(m_creature, event.percent_range.repeatMin, event.percent_range.repeatMax); break; } case EVENT_T_REACHED_HOME: case EVENT_T_RECEIVE_EMOTE: break; case EVENT_T_AURA: { SpellAuraHolder* holder = m_creature->GetSpellAuraHolder(event.buffed.spellId); if (!holder || holder->GetStackAmount() < event.buffed.amount) { return false; } LOG_PROCESS_EVENT; // Repeat Timers pHolder.UpdateRepeatTimer(m_creature, event.buffed.repeatMin, event.buffed.repeatMax); break; } case EVENT_T_TARGET_AURA: { if (!m_creature->IsInCombat() || !m_creature->getVictim()) { return false; } SpellAuraHolder* holder = m_creature->getVictim()->GetSpellAuraHolder(event.buffed.spellId); if (!holder || holder->GetStackAmount() < event.buffed.amount) { return false; } LOG_PROCESS_EVENT; // Repeat Timers pHolder.UpdateRepeatTimer(m_creature, event.buffed.repeatMin, event.buffed.repeatMax); break; } case EVENT_T_MISSING_AURA: { SpellAuraHolder* holder = m_creature->GetSpellAuraHolder(event.buffed.spellId); if (holder && holder->GetStackAmount() >= event.buffed.amount) { return false; } LOG_PROCESS_EVENT; // Repeat Timers pHolder.UpdateRepeatTimer(m_creature, event.buffed.repeatMin, event.buffed.repeatMax); break; } case EVENT_T_TARGET_MISSING_AURA: { if (!m_creature->IsInCombat() || !m_creature->getVictim()) { return false; } SpellAuraHolder* holder = m_creature->getVictim()->GetSpellAuraHolder(event.buffed.spellId); if (holder && holder->GetStackAmount() >= event.buffed.amount) { return false; } LOG_PROCESS_EVENT; // Repeat Timers pHolder.UpdateRepeatTimer(m_creature, event.buffed.repeatMin, event.buffed.repeatMax); break; } case EVENT_T_RECEIVE_AI_EVENT: break; case EVENT_T_ENERGY: { if (!m_creature->IsInCombat() || !m_creature->GetMaxPower(POWER_ENERGY)) { return false; } uint32 perc = (m_creature->GetPower(POWER_ENERGY) * 100) / m_creature->GetMaxPower(POWER_ENERGY); if (perc > event.percent_range.percentMax || perc < event.percent_range.percentMin) { return false; } LOG_PROCESS_EVENT; // Repeat Timers pHolder.UpdateRepeatTimer(m_creature, event.percent_range.repeatMin, event.percent_range.repeatMax); break; } default: sLog.outErrorEventAI(""Creature %u using Event %u has invalid Event Type(%u), missing from ProcessEvent() Switch."", m_creature->GetEntry(), pHolder.Event.event_id, pHolder.Event.event_type); break; } // Disable non-repeatable events if (!(pHolder.Event.event_flags & EFLAG_REPEATABLE)) { pHolder.Enabled = false; } // Store random here so that all random actions match up uint32 rnd = rand(); // Return if chance for event is not met if (pHolder.Event.event_chance <= rnd % 100) { return false; } // Process actions, normal case if (!(pHolder.Event.event_flags & EFLAG_RANDOM_ACTION)) { for (uint32 j = 0; j < MAX_ACTIONS; ++j) { ProcessAction(pHolder.Event.action[j], rnd, pHolder.Event.event_id, pActionInvoker, pAIEventSender); } } // Process actions, random case else { // amount of real actions uint32 count = 0; for (uint32 j = 0; j < MAX_ACTIONS; ++j) if (pHolder.Event.action[j].type != ACTION_T_NONE) { ++count; } if (count) { // select action number from found amount uint32 idx = urand(0, count - 1); // find selected action, skipping not used uint32 j = 0; for (; ; ++j) { if (pHolder.Event.action[j].type != ACTION_T_NONE) { if (!idx) { break; } --idx; } } ProcessAction(pHolder.Event.action[j], rnd, pHolder.Event.event_id, pActionInvoker, pAIEventSender); } } return true; } void CreatureEventAI::ProcessAction(CreatureEventAI_Action const& action, uint32 rnd, uint32 EventId, Unit* pActionInvoker, Creature* pAIEventSender) { if (action.type == ACTION_T_NONE) { return; } DEBUG_FILTER_LOG(LOG_FILTER_EVENT_AI_DEV, ""CreatureEventAI: Process action %u (script %u) triggered for %s (invoked by %s)"", action.type, EventId, m_creature->GetGuidStr().c_str(), pActionInvoker ? pActionInvoker->GetGuidStr().c_str() : """"); bool reportTargetError = false; switch (action.type) { case ACTION_T_TEXT: case ACTION_T_CHANCED_TEXT: { if (!action.text.TextId[0]) { return; } int32 textId = 0; if (action.type == ACTION_T_TEXT) { if (action.text.TextId[1] && action.text.TextId[2]) { textId = action.text.TextId[urand(0, 2)]; } else if (action.text.TextId[1] && urand(0, 1)) { textId = action.text.TextId[1]; } else { textId = action.text.TextId[0]; } } // ACTION_T_CHANCED_TEXT, chance hits else if (urand(0, 99) < action.chanced_text.chance) { if (action.chanced_text.TextId[0] && action.chanced_text.TextId[1]) { textId = action.chanced_text.TextId[urand(0, 1)]; } else { textId = action.chanced_text.TextId[0]; } } if (textId) { Unit* target = NULL; if (pActionInvoker) { if (pActionInvoker->GetTypeId() == TYPEID_PLAYER) { target = pActionInvoker; } else if (Unit* owner = pActionInvoker->GetOwner()) { if (owner->GetTypeId() == TYPEID_PLAYER) { target = owner; } } } else if ((target = m_creature->getVictim())) { if (target->GetTypeId() != TYPEID_PLAYER) if (Unit* owner = target->GetOwner()) if (owner->GetTypeId() == TYPEID_PLAYER) { target = owner; } } if (!DoDisplayText(m_creature, textId, target)) { sLog.outErrorEventAI(""Error attempting to display text %i, used by script %u"", textId, EventId); } } break; } case ACTION_T_SET_FACTION: { if (action.set_faction.factionId) { m_creature->SetFactionTemporary(action.set_faction.factionId, action.set_faction.factionFlags); } else // no id provided, assume reset and then use default { m_creature->ClearTemporaryFaction(); } break; } case ACTION_T_MORPH_TO_ENTRY_OR_MODEL: { if (action.morph.creatureId || action.morph.modelId) { // set model based on entry from creature_template if (action.morph.creatureId) { if (CreatureInfo const* ci = ObjectMgr::GetCreatureTemplate(action.morph.creatureId)) { uint32 display_id = Creature::ChooseDisplayId(ci); m_creature->SetDisplayId(display_id); } } // if no param1, then use value from param2 (modelId) else { m_creature->SetDisplayId(action.morph.modelId); } } else { m_creature->DeMorph(); } break; } case ACTION_T_SOUND: m_creature->PlayDirectSound(action.sound.soundId); break; case ACTION_T_EMOTE: m_creature->HandleEmote(action.emote.emoteId); break; case ACTION_T_RANDOM_SOUND: { int32 temp = GetRandActionParam(rnd, action.random_sound.soundId1, action.random_sound.soundId2, action.random_sound.soundId3); if (temp >= 0) { m_creature->PlayDirectSound(temp); } break; } case ACTION_T_RANDOM_EMOTE: { int32 temp = GetRandActionParam(rnd, action.random_emote.emoteId1, action.random_emote.emoteId2, action.random_emote.emoteId3); if (temp >= 0) { m_creature->HandleEmote(temp); } break; } case ACTION_T_CAST: { uint32 selectFlags = 0; uint32 spellId = 0; if (!(action.cast.castFlags & (CAST_TRIGGERED | CAST_FORCE_CAST | CAST_FORCE_TARGET_SELF))) { spellId = action.cast.spellId; selectFlags = SELECT_FLAG_IN_LOS; } Unit* target = GetTargetByType(action.cast.target, pActionInvoker, pAIEventSender, reportTargetError, spellId, selectFlags); if (!target) { if (reportTargetError) { sLog.outErrorEventAI(""NULL target for ACTION_T_CAST creature entry %u casting spell id %u"", m_creature->GetEntry(), action.cast.spellId); } return; } CanCastResult castResult = DoCastSpellIfCan(target, action.cast.spellId, action.cast.castFlags); switch (castResult) { case CAST_FAIL_POWER: case CAST_FAIL_TOO_FAR: { // Melee current victim if flag not set if (!(action.cast.castFlags & CAST_NO_MELEE_IF_OOM)) { switch (m_creature->GetMotionMaster()->GetCurrentMovementGeneratorType()) { case CHASE_MOTION_TYPE: case FOLLOW_MOTION_TYPE: m_attackDistance = 0.0f; m_attackAngle = 0.0f; m_creature->GetMotionMaster()->Clear(false); m_creature->GetMotionMaster()->MoveChase(m_creature->getVictim(), m_attackDistance, m_attackAngle); break; default: break; } } break; } default: break; } break; } case ACTION_T_SUMMON: { Unit* target = GetTargetByType(action.summon.target, pActionInvoker, pAIEventSender, reportTargetError); if (!target && reportTargetError) { sLog.outErrorEventAI(""Event %u - NULL target for ACTION_T_SUMMON(%u), target-type %u"", EventId, action.type, action.summon.target); } Creature* pCreature = NULL; if (action.summon.duration) { pCreature = m_creature->SummonCreature(action.summon.creatureId, 0.0f, 0.0f, 0.0f, 0.0f, TEMPSUMMON_TIMED_OOC_OR_DEAD_DESPAWN, action.summon.duration); } else { pCreature = m_creature->SummonCreature(action.summon.creatureId, 0.0f, 0.0f, 0.0f, 0.0f, TEMPSUMMON_TIMED_OOC_DESPAWN, 0); } if (!pCreature) { sLog.outErrorEventAI(""failed to spawn creature %u. Spawn event %d is on creature %d"", action.summon.creatureId, EventId, m_creature->GetEntry()); } else if (action.summon.target != TARGET_T_SELF && target) { pCreature->AI()->AttackStart(target); } break; } case ACTION_T_THREAT_SINGLE_PCT: if (Unit* target = GetTargetByType(action.threat_single_pct.target, pActionInvoker, pAIEventSender, reportTargetError)) { m_creature->GetThreatManager().modifyThreatPercent(target, action.threat_single_pct.percent); } else if (reportTargetError) { sLog.outErrorEventAI(""Event %u - NULL target for ACTION_T_THREAT_SINGLE_PCT(%u), target-type %u"", EventId, action.type, action.threat_single_pct.target); } break; case ACTION_T_THREAT_ALL_PCT: { ThreatList const& threatList = m_creature->GetThreatManager().getThreatList(); for (ThreatList::const_iterator i = threatList.begin(); i != threatList.end(); ++i) if (Unit* Temp = m_creature->GetMap()->GetUnit((*i)->getUnitGuid())) { m_creature->GetThreatManager().modifyThreatPercent(Temp, action.threat_all_pct.percent); } break; } case ACTION_T_QUEST_EVENT: if (Unit* target = GetTargetByType(action.quest_event.target, pActionInvoker, pAIEventSender, reportTargetError)) { if (target->GetTypeId() == TYPEID_PLAYER) { ((Player*)target)->AreaExploredOrEventHappens(action.quest_event.questId); } } else if (reportTargetError) { sLog.outErrorEventAI(""Event %u - NULL target for ACTION_T_QUEST_EVENT(%u), target-type %u"", EventId, action.type, action.quest_event.target); } break; case ACTION_T_CAST_EVENT: if (Unit* target = GetTargetByType(action.cast_event.target, pActionInvoker, pAIEventSender, reportTargetError, 0, SELECT_FLAG_PLAYER)) { if (target->GetTypeId() == TYPEID_PLAYER) { ((Player*)target)->CastedCreatureOrGO(action.cast_event.creatureId, m_creature->GetObjectGuid(), action.cast_event.spellId); } } else if (reportTargetError) { sLog.outErrorEventAI(""Event %u - NULL target for ACTION_T_CST_EVENT(%u), target-type %u"", EventId, action.type, action.cast_event.target); } break; case ACTION_T_SET_UNIT_FIELD: { Unit* target = GetTargetByType(action.set_unit_field.target, pActionInvoker, pAIEventSender, reportTargetError); // not allow modify important for integrity object fields if (action.set_unit_field.field < OBJECT_END || action.set_unit_field.field >= UNIT_END) { return; } if (target) { target->SetUInt32Value(action.set_unit_field.field, action.set_unit_field.value); } else if (reportTargetError) { sLog.outErrorEventAI(""Event %u - NULL target for ACTION_T_SET_UNIT_FIELD(%u), target-type %u"", EventId, action.type, action.set_unit_field.target); } break; } case ACTION_T_SET_UNIT_FLAG: if (Unit* target = GetTargetByType(action.unit_flag.target, pActionInvoker, pAIEventSender, reportTargetError)) { target->SetFlag(UNIT_FIELD_FLAGS, action.unit_flag.value); } else if (reportTargetError) { sLog.outErrorEventAI(""Event %u - NULL target for ACTION_T_SET_UNIT_FLAG(%u), target-type %u"", EventId, action.type, action.unit_flag.target); } break; case ACTION_T_REMOVE_UNIT_FLAG: if (Unit* target = GetTargetByType(action.unit_flag.target, pActionInvoker, pAIEventSender, reportTargetError)) { target->RemoveFlag(UNIT_FIELD_FLAGS, action.unit_flag.value); } else if (reportTargetError) { sLog.outErrorEventAI(""Event %u - NULL target for ACTION_T_REMOVE_UNIT_FLAG(%u), target-type %u"", EventId, action.type, action.unit_flag.target); } break; case ACTION_T_AUTO_ATTACK: m_MeleeEnabled = action.auto_attack.state != 0; break; case ACTION_T_COMBAT_MOVEMENT: // ignore no affect case if (m_isCombatMovement == (action.combat_movement.state != 0) || m_creature->IsNonMeleeSpellCasted(false)) { return; } SetCombatMovement(action.combat_movement.state != 0, true); if (m_isCombatMovement && action.combat_movement.melee && m_creature->IsInCombat() && m_creature->getVictim()) { m_creature->SendMeleeAttackStart(m_creature->getVictim()); } else if (action.combat_movement.melee && m_creature->IsInCombat() && m_creature->getVictim()) { m_creature->SendMeleeAttackStop(m_creature->getVictim()); } break; case ACTION_T_SET_PHASE: m_Phase = action.set_phase.phase; DEBUG_FILTER_LOG(LOG_FILTER_EVENT_AI_DEV, ""CreatureEventAI: ACTION_T_SET_PHASE - script %u for %s, phase is now %u"", EventId, m_creature->GetGuidStr().c_str(), m_Phase); break; case ACTION_T_INC_PHASE: { int32 new_phase = int32(m_Phase) + action.set_inc_phase.step; if (new_phase < 0) { sLog.outErrorEventAI(""Event %d decrease Phase under 0. CreatureEntry = %d"", EventId, m_creature->GetEntry()); m_Phase = 0; } else if (new_phase >= MAX_PHASE) { sLog.outErrorEventAI(""Event %d incremented Phase above %u. Phase mask can not be used with phases past %u. CreatureEntry = %d"", EventId, MAX_PHASE - 1, MAX_PHASE - 1, m_creature->GetEntry()); m_Phase = MAX_PHASE - 1; } else { m_Phase = new_phase; } DEBUG_FILTER_LOG(LOG_FILTER_EVENT_AI_DEV, ""CreatureEventAI: ACTION_T_INC_PHASE - script %u for %s, phase is now %u"", EventId, m_creature->GetGuidStr().c_str(), m_Phase); break; } case ACTION_T_EVADE: EnterEvadeMode(); break; case ACTION_T_FLEE_FOR_ASSIST: m_creature->DoFleeToGetAssistance(); break; case ACTION_T_QUEST_EVENT_ALL: if (pActionInvoker && pActionInvoker->GetTypeId() == TYPEID_PLAYER) { ((Player*)pActionInvoker)->GroupEventHappens(action.quest_event_all.questId, m_creature); } break; case ACTION_T_CAST_EVENT_ALL: { ThreatList const& threatList = m_creature->GetThreatManager().getThreatList(); for (ThreatList::const_iterator i = threatList.begin(); i != threatList.end(); ++i) if (Player* temp = m_creature->GetMap()->GetPlayer((*i)->getUnitGuid())) { temp->CastedCreatureOrGO(action.cast_event_all.creatureId, m_creature->GetObjectGuid(), action.cast_event_all.spellId); } break; } case ACTION_T_REMOVEAURASFROMSPELL: if (Unit* target = GetTargetByType(action.remove_aura.target, pActionInvoker, pAIEventSender, reportTargetError)) { target->RemoveAurasDueToSpell(action.remove_aura.spellId); } else if (reportTargetError) { sLog.outErrorEventAI(""Event %u - NULL target for ACTION_T_REMOVEAURASFROMSPELL(%u), target-type %u"", EventId, action.type, action.remove_aura.target); } break; case ACTION_T_RANGED_MOVEMENT: m_attackDistance = (float)action.ranged_movement.distance; m_attackAngle = action.ranged_movement.angle / 180.0f * M_PI_F; if (m_isCombatMovement) { if (m_creature->GetMotionMaster()->GetCurrentMovementGeneratorType() == CHASE_MOTION_TYPE) { // Drop current movement gen m_creature->GetMotionMaster()->Clear(false); m_creature->GetMotionMaster()->MoveChase(m_creature->getVictim(), m_attackDistance, m_attackAngle); } } break; case ACTION_T_RANDOM_PHASE: m_Phase = GetRandActionParam(rnd, action.random_phase.phase1, action.random_phase.phase2, action.random_phase.phase3); DEBUG_FILTER_LOG(LOG_FILTER_EVENT_AI_DEV, ""CreatureEventAI: ACTION_T_RANDOM_PHASE - script %u for %s, phase is now %u"", EventId, m_creature->GetGuidStr().c_str(), m_Phase); break; case ACTION_T_RANDOM_PHASE_RANGE: if (action.random_phase_range.phaseMax > action.random_phase_range.phaseMin) { m_Phase = action.random_phase_range.phaseMin + (rnd % (action.random_phase_range.phaseMax - action.random_phase_range.phaseMin)); } else { sLog.outErrorEventAI(""ACTION_T_RANDOM_PHASE_RANGE can not have Param2 <= Param1. Divide by Zero. Event = %d. CreatureEntry = %d"", EventId, m_creature->GetEntry()); } break; case ACTION_T_SUMMON_ID: { Unit* target = GetTargetByType(action.summon_id.target, pActionInvoker, pAIEventSender, reportTargetError); if (!target && reportTargetError) { sLog.outErrorEventAI(""Event %u - NULL target for ACTION_T_SUMMON_ID(%u), target-type %u"", EventId, action.type, action.summon_id.target); } CreatureEventAI_Summon_Map::const_iterator i = sEventAIMgr.GetCreatureEventAISummonMap().find(action.summon_id.spawnId); if (i == sEventAIMgr.GetCreatureEventAISummonMap().end()) { sLog.outErrorEventAI(""failed to spawn creature %u. Summon map index %u does not exist. EventID %d. CreatureID %d"", action.summon_id.creatureId, action.summon_id.spawnId, EventId, m_creature->GetEntry()); return; } Creature* pCreature = NULL; if ((*i).second.SpawnTimeSecs) { pCreature = m_creature->SummonCreature(action.summon_id.creatureId, (*i).second.position_x, (*i).second.position_y, (*i).second.position_z, (*i).second.orientation, TEMPSUMMON_TIMED_OOC_OR_DEAD_DESPAWN, (*i).second.SpawnTimeSecs); } else { pCreature = m_creature->SummonCreature(action.summon_id.creatureId, (*i).second.position_x, (*i).second.position_y, (*i).second.position_z, (*i).second.orientation, TEMPSUMMON_TIMED_OOC_DESPAWN, 0); } if (!pCreature) { sLog.outErrorEventAI(""failed to spawn creature %u. EventId %d.Creature %d"", action.summon_id.creatureId, EventId, m_creature->GetEntry()); } else if (action.summon_id.target != TARGET_T_SELF && target) { pCreature->AI()->AttackStart(target); } break; } case ACTION_T_KILLED_MONSTER: // first attempt player/group who tapped creature if (Player* pPlayer = m_creature->GetLootRecipient()) { pPlayer->RewardPlayerAndGroupAtEvent(action.killed_monster.creatureId, m_creature); } else { // if not available, use pActionInvoker if (Unit* pTarget = GetTargetByType(action.killed_monster.target, pActionInvoker, pAIEventSender, reportTargetError, 0, SELECT_FLAG_PLAYER)) { if (Player* pPlayer2 = pTarget->GetCharmerOrOwnerPlayerOrPlayerItself()) { pPlayer2->RewardPlayerAndGroupAtEvent(action.killed_monster.creatureId, m_creature); } } else if (reportTargetError) { sLog.outErrorEventAI(""Event %u - NULL target for ACTION_T_KILLED_MONSTER(%u), target-type %u"", EventId, action.type, action.killed_monster.target); } } break; case ACTION_T_SET_INST_DATA: { InstanceData* pInst = m_creature->GetInstanceData(); if (!pInst) { sLog.outErrorEventAI(""Event %d attempt to set instance data without instance script. Creature %d"", EventId, m_creature->GetEntry()); return; } pInst->SetData(action.set_inst_data.field, action.set_inst_data.value); break; } case ACTION_T_SET_INST_DATA64: { Unit* target = GetTargetByType(action.set_inst_data64.target, pActionInvoker, pAIEventSender, reportTargetError); if (!target) { if (reportTargetError) { sLog.outErrorEventAI(""Event %d attempt to set instance data64 but Target == NULL. Creature %d"", EventId, m_creature->GetEntry()); } return; } InstanceData* pInst = m_creature->GetInstanceData(); if (!pInst) { sLog.outErrorEventAI(""Event %d attempt to set instance data64 without instance script. Creature %d"", EventId, m_creature->GetEntry()); return; } pInst->SetData64(action.set_inst_data64.field, target->GetObjectGuid().GetRawValue()); break; } case ACTION_T_UPDATE_TEMPLATE: if (m_creature->GetEntry() == action.update_template.creatureId) { sLog.outErrorEventAI(""Event %d ACTION_T_UPDATE_TEMPLATE call with param1 == current entry. Creature %d"", EventId, m_creature->GetEntry()); return; } m_creature->UpdateEntry(action.update_template.creatureId, action.update_template.team ? HORDE : ALLIANCE); break; case ACTION_T_DIE: if (m_creature->IsDead()) { sLog.outErrorEventAI(""Event %d ACTION_T_DIE on dead creature. Creature %d"", EventId, m_creature->GetEntry()); return; } m_creature->DealDamage(m_creature, m_creature->GetMaxHealth(), NULL, DIRECT_DAMAGE, SPELL_SCHOOL_MASK_NORMAL, NULL, false); break; case ACTION_T_ZONE_COMBAT_PULSE: { m_creature->SetInCombatWithZone(); break; } case ACTION_T_CALL_FOR_HELP: { m_creature->CallForHelp((float)action.call_for_help.radius); break; } case ACTION_T_SET_SHEATH: { m_creature->SetSheath(SheathState(action.set_sheath.sheath)); break; } case ACTION_T_FORCE_DESPAWN: { m_creature->ForcedDespawn(action.forced_despawn.msDelay); break; } case ACTION_T_SET_INVINCIBILITY_HP_LEVEL: { if (action.invincibility_hp_level.is_percent) { m_InvinceabilityHpLevel = m_creature->GetMaxHealth() * action.invincibility_hp_level.hp_level / 100; } else { m_InvinceabilityHpLevel = action.invincibility_hp_level.hp_level; } break; } case ACTION_T_MOUNT_TO_ENTRY_OR_MODEL: { if (action.mount.creatureId || action.mount.modelId) { // set model based on entry from creature_template if (action.mount.creatureId) { if (CreatureInfo const* cInfo = ObjectMgr::GetCreatureTemplate(action.mount.creatureId)) { uint32 display_id = Creature::ChooseDisplayId(cInfo); m_creature->Mount(display_id); } } // if no param1, then use value from param2 (modelId) else { m_creature->Mount(action.mount.modelId); } } else { m_creature->Unmount(); } break; } case ACTION_T_THROW_AI_EVENT: { SendAIEventAround(AIEventType(action.throwEvent.eventType), pActionInvoker, 0, action.throwEvent.radius); break; } case ACTION_T_SET_THROW_MASK: { m_throwAIEventMask = action.setThrowMask.eventTypeMask; break; } case ACTION_T_SET_STAND_STATE: { m_creature->SetStandState(action.setStandState.standState); break; } case ACTION_T_SUMMON_UNIQUE: //47 { Creature* pCreature = NULL; MaNGOS::NearestCreatureEntryWithLiveStateInObjectRangeCheck u_check(*m_creature, action.summon_unique.creatureId, true, false, 100, true); MaNGOS::CreatureLastSearcher searcher(pCreature, u_check); Cell::VisitGridObjects(m_creature, searcher, 100); WorldObject* pSpawn = NULL; pSpawn = pCreature; if (!pSpawn) { Unit* target = GetTargetByType(action.summon_unique.target, pActionInvoker, pAIEventSender, reportTargetError); if (!target && reportTargetError) { sLog.outErrorEventAI(""Event %u - NULL target for ACTION_T_SUMMON_UNIQUE(%u), target-type %u"", EventId, action.type, action.summon_unique.target); } CreatureEventAI_Summon_Map::const_iterator i = sEventAIMgr.GetCreatureEventAISummonMap().find(action.summon_unique.spawnId); if (i == sEventAIMgr.GetCreatureEventAISummonMap().end()) { sLog.outErrorEventAI(""failed to spawn creature %u. Summon map index %u does not exist. EventID %d. CreatureID %d"", action.summon_unique.creatureId, action.summon_unique.spawnId, EventId, m_creature->GetEntry()); return; } Creature* pCreature = NULL; if ((*i).second.SpawnTimeSecs) { pCreature = m_creature->SummonCreature(action.summon_unique.creatureId, (*i).second.position_x, (*i).second.position_y, (*i).second.position_z, (*i).second.orientation, TEMPSUMMON_TIMED_OOC_OR_DEAD_DESPAWN, (*i).second.SpawnTimeSecs); } else { pCreature = m_creature->SummonCreature(action.summon_unique.creatureId, (*i).second.position_x, (*i).second.position_y, (*i).second.position_z, (*i).second.orientation, TEMPSUMMON_TIMED_OOC_DESPAWN, 0); } if (!pCreature) { sLog.outErrorEventAI(""failed to spawn creature %u. EventId %d.Creature %d"", action.summon_unique.creatureId, EventId, m_creature->GetEntry()); } else if (action.summon_unique.target != TARGET_T_SELF && target) { pCreature->AI()->AttackStart(target); } } break; } case ACTION_T_EMOTE_TARGET: { Unit* pCreature = m_creature->GetMap()->GetCreature(ObjectGuid(HIGHGUID_UNIT, action.emoteTarget.targetGuid)); if (!pCreature) { sLog.outErrorEventAI(""Event %d. Cannot find creature by guid %d"", EventId, action.emoteTarget.targetGuid); return; } m_creature->SetFacingToObject(pCreature); m_creature->HandleEmote(action.emoteTarget.emoteId); break; } case ACTION_T_CHANGE_MOVEMENT: { switch (action.changeMovement.movementType) { case IDLE_MOTION_TYPE: m_creature->GetMotionMaster()->MoveIdle(); break; case RANDOM_MOTION_TYPE: m_creature->GetMotionMaster()->MoveRandomAroundPoint(m_creature->GetPositionX(), m_creature->GetPositionY(), m_creature->GetPositionZ(), float(action.changeMovement.wanderDistance)); break; case WAYPOINT_MOTION_TYPE: m_creature->GetMotionMaster()->MoveWaypoint(); break; } break; } } } void CreatureEventAI::JustRespawned() // NOTE that this is called from the AI's constructor as well { Reset(); for (CreatureEventAIList::iterator i = m_CreatureEventAIList.begin(); i != m_CreatureEventAIList.end(); ++i) { // Reset generic timer if (i->Event.event_type == EVENT_T_TIMER_GENERIC) { if (i->UpdateRepeatTimer(m_creature, i->Event.timer.initialMin, i->Event.timer.initialMax)) { i->Enabled = true; } } // Handle Spawned Events else if (SpawnedEventConditionsCheck((*i).Event)) { ProcessEvent(*i); } } } void CreatureEventAI::Reset() { m_EventUpdateTime = EVENT_UPDATE_TIME; m_EventDiff = 0; m_throwAIEventStep = 0; // Reset all events to enabled for (CreatureEventAIList::iterator i = m_CreatureEventAIList.begin(); i != m_CreatureEventAIList.end(); ++i) { CreatureEventAI_Event const& event = (*i).Event; switch (event.event_type) { // Reset all out of combat timers case EVENT_T_TIMER_OOC: { if ((*i).UpdateRepeatTimer(m_creature, event.timer.initialMin, event.timer.initialMax)) { (*i).Enabled = true; } break; } // default: // TODO: enable below code line / verify this is correct to enable events previously disabled (ex. aggro yell), instead of enable this in void Aggro() //(*i).Enabled = true; //(*i).Time = 0; // break; } } } void CreatureEventAI::JustReachedHome() { for (CreatureEventAIList::iterator i = m_CreatureEventAIList.begin(); i != m_CreatureEventAIList.end(); ++i) { if ((*i).Event.event_type == EVENT_T_REACHED_HOME) { ProcessEvent(*i); } } Reset(); } void CreatureEventAI::EnterEvadeMode() { m_creature->RemoveAllAurasOnEvade(); m_creature->DeleteThreatList(); m_creature->CombatStop(true); if (m_creature->IsAlive()) { m_creature->GetMotionMaster()->MoveTargetedHome(); } m_creature->SetLootRecipient(NULL); // Handle Evade events for (CreatureEventAIList::iterator i = m_CreatureEventAIList.begin(); i != m_CreatureEventAIList.end(); ++i) { if ((*i).Event.event_type == EVENT_T_EVADE) { ProcessEvent(*i); } } } void CreatureEventAI::JustDied(Unit* killer) { Reset(); if (m_creature->IsGuard()) { // Send Zone Under Attack message to the LocalDefense and WorldDefense Channels if (Player* pKiller = killer->GetCharmerOrOwnerPlayerOrPlayerItself()) { m_creature->SendZoneUnderAttackMessage(pKiller); } } if (m_throwAIEventMask & (1 << AI_EVENT_JUST_DIED)) { SendAIEventAround(AI_EVENT_JUST_DIED, killer, 0, AIEVENT_DEFAULT_THROW_RADIUS); } // Handle On Death events for (CreatureEventAIList::iterator i = m_CreatureEventAIList.begin(); i != m_CreatureEventAIList.end(); ++i) { if ((*i).Event.event_type == EVENT_T_DEATH) { ProcessEvent(*i, killer); } } // reset phase after any death state events m_Phase = 0; } void CreatureEventAI::KilledUnit(Unit* victim) { if (victim->GetTypeId() != TYPEID_PLAYER) { return; } for (CreatureEventAIList::iterator i = m_CreatureEventAIList.begin(); i != m_CreatureEventAIList.end(); ++i) { if ((*i).Event.event_type == EVENT_T_KILL) { ProcessEvent(*i, victim); } } } void CreatureEventAI::JustSummoned(Creature* pUnit) { for (CreatureEventAIList::iterator i = m_CreatureEventAIList.begin(); i != m_CreatureEventAIList.end(); ++i) { if ((*i).Event.event_type == EVENT_T_SUMMONED_UNIT) { ProcessEvent(*i, pUnit); } } } void CreatureEventAI::SummonedCreatureJustDied(Creature* pUnit) { for (CreatureEventAIList::iterator i = m_CreatureEventAIList.begin(); i != m_CreatureEventAIList.end(); ++i) { if ((*i).Event.event_type == EVENT_T_SUMMONED_JUST_DIED) { ProcessEvent(*i, pUnit); } } } void CreatureEventAI::SummonedCreatureDespawn(Creature* pUnit) { for (CreatureEventAIList::iterator i = m_CreatureEventAIList.begin(); i != m_CreatureEventAIList.end(); ++i) { if ((*i).Event.event_type == EVENT_T_SUMMONED_JUST_DESPAWN) { ProcessEvent(*i, pUnit); } } } void CreatureEventAI::ReceiveAIEvent(AIEventType eventType, Creature* pSender, Unit* pInvoker, uint32 /*miscValue*/) { MANGOS_ASSERT(pSender); for (CreatureEventAIList::iterator itr = m_CreatureEventAIList.begin(); itr != m_CreatureEventAIList.end(); ++itr) { if (itr->Event.event_type == EVENT_T_RECEIVE_AI_EVENT && itr->Event.receiveAIEvent.eventType == eventType && (!itr->Event.receiveAIEvent.senderEntry || itr->Event.receiveAIEvent.senderEntry == pSender->GetEntry())) { ProcessEvent(*itr, pInvoker, pSender); } } } void CreatureEventAI::EnterCombat(Unit* enemy) { // Check for on combat start events for (CreatureEventAIList::iterator i = m_CreatureEventAIList.begin(); i != m_CreatureEventAIList.end(); ++i) { CreatureEventAI_Event const& event = (*i).Event; switch (event.event_type) { case EVENT_T_AGGRO: (*i).Enabled = true; ProcessEvent(*i, enemy); break; // Reset all in combat timers case EVENT_T_TIMER_IN_COMBAT: if ((*i).UpdateRepeatTimer(m_creature, event.timer.initialMin, event.timer.initialMax)) { (*i).Enabled = true; } break; // All normal events need to be re-enabled and their time set to 0 default: (*i).Enabled = true; (*i).Time = 0; break; } } m_EventUpdateTime = EVENT_UPDATE_TIME; m_EventDiff = 0; } void CreatureEventAI::AttackStart(Unit* who) { if (!who) { return; } if (m_creature->Attack(who, m_MeleeEnabled)) { m_creature->AddThreat(who); m_creature->SetInCombatWith(who); who->SetInCombatWith(m_creature); HandleMovementOnAttackStart(who); } } void CreatureEventAI::MoveInLineOfSight(Unit* who) { if (!who) { return; } // Check for OOC LOS Event if (!m_creature->getVictim()) { for (CreatureEventAIList::iterator itr = m_CreatureEventAIList.begin(); itr != m_CreatureEventAIList.end(); ++itr) { if ((*itr).Event.event_type == EVENT_T_OOC_LOS) { // can trigger if closer than fMaxAllowedRange float fMaxAllowedRange = (float)(*itr).Event.ooc_los.maxRange; // if range is ok and we are actually in LOS if (m_creature->IsWithinDistInMap(who, fMaxAllowedRange) && m_creature->IsWithinLOSInMap(who)) { // if friendly event&&who is not hostile OR hostile event&&who is hostile if (((*itr).Event.ooc_los.noHostile && !m_creature->IsHostileTo(who)) || ((!(*itr).Event.ooc_los.noHostile) && m_creature->IsHostileTo(who))) { ProcessEvent(*itr, who); } } } } } if (m_creature->IsCivilian() || m_creature->IsNeutralToAll()) { return; } if (m_creature->CanInitiateAttack() && who->IsTargetableForAttack() && m_creature->IsHostileTo(who) && who->isInAccessablePlaceFor(m_creature)) { if (!m_creature->CanFly() && m_creature->GetDistanceZ(who) > CREATURE_Z_ATTACK_RANGE) { return; } float attackRadius = m_creature->GetAttackDistance(who); if (m_creature->IsWithinDistInMap(who, attackRadius) && m_creature->IsWithinLOSInMap(who)) { if (!m_creature->getVictim()) { AttackStart(who); who->RemoveSpellsCausingAura(SPELL_AURA_MOD_STEALTH); } else if (m_creature->GetMap()->IsDungeon()) { m_creature->AddThreat(who); who->SetInCombatWith(m_creature); } } } } void CreatureEventAI::SpellHit(Unit* pUnit, const SpellEntry* pSpell) { for (CreatureEventAIList::iterator i = m_CreatureEventAIList.begin(); i != m_CreatureEventAIList.end(); ++i) if ((*i).Event.event_type == EVENT_T_SPELLHIT) // If spell id matches (or no spell id) & if spell school matches (or no spell school) if (!(*i).Event.spell_hit.spellId || pSpell->Id == (*i).Event.spell_hit.spellId) if (pSpell->SchoolMask & (*i).Event.spell_hit.schoolMask) { ProcessEvent(*i, pUnit); } } void CreatureEventAI::UpdateAI(const uint32 diff) { // Check if we are in combat (also updates calls threat update code) bool Combat = m_creature->SelectHostileTarget() && m_creature->getVictim(); // Events are only updated once every EVENT_UPDATE_TIME ms to prevent lag with large amount of events if (m_EventUpdateTime < diff) { m_EventDiff += diff; // Check for time based events for (CreatureEventAIList::iterator i = m_CreatureEventAIList.begin(); i != m_CreatureEventAIList.end(); ++i) { // Decrement Timers if ((*i).Time) { if ((*i).Time > m_EventDiff) { // Do not decrement timers if event can not trigger in this phase if (!((*i).Event.event_inverse_phase_mask & (1 << m_Phase))) { (*i).Time -= m_EventDiff; } // Skip processing of events that have time remaining continue; } else { (*i).Time = 0; } } // Events that are updated every EVENT_UPDATE_TIME switch ((*i).Event.event_type) { case EVENT_T_TIMER_OOC: case EVENT_T_TIMER_GENERIC: ProcessEvent(*i); break; case EVENT_T_TIMER_IN_COMBAT: case EVENT_T_MANA: case EVENT_T_HP: case EVENT_T_TARGET_HP: case EVENT_T_TARGET_CASTING: case EVENT_T_FRIENDLY_HP: case EVENT_T_AURA: case EVENT_T_TARGET_AURA: case EVENT_T_MISSING_AURA: case EVENT_T_TARGET_MISSING_AURA: if (Combat) { ProcessEvent(*i); } break; case EVENT_T_RANGE: if (Combat) { if (m_creature->getVictim() && m_creature->IsInMap(m_creature->getVictim())) if (m_creature->IsInRange(m_creature->getVictim(), (float)(*i).Event.range.minDist, (float)(*i).Event.range.maxDist)) { ProcessEvent(*i); } } break; } } m_EventDiff = 0; m_EventUpdateTime = EVENT_UPDATE_TIME; } else { m_EventDiff += diff; m_EventUpdateTime -= diff; } // Melee Auto-Attack (recheck m_creature->getVictim in case of combat state was changed while processing events) if (Combat && m_MeleeEnabled && m_creature->getVictim()) { DoMeleeAttackIfReady(); } } bool CreatureEventAI::IsVisible(Unit* pl) const { return m_creature->IsWithinDist(pl, sWorld.getConfig(CONFIG_FLOAT_SIGHT_MONSTER)) && pl->IsVisibleForOrDetect(m_creature, m_creature, true); } inline uint32 CreatureEventAI::GetRandActionParam(uint32 rnd, uint32 param1, uint32 param2, uint32 param3) { switch (rnd % 3) { case 0: return param1; case 1: return param2; case 2: return param3; } return 0; } inline int32 CreatureEventAI::GetRandActionParam(uint32 rnd, int32 param1, int32 param2, int32 param3) { switch (rnd % 3) { case 0: return param1; case 1: return param2; case 2: return param3; } return 0; } inline Unit* CreatureEventAI::GetTargetByType(uint32 Target, Unit* pActionInvoker, Creature* pAIEventSender, bool& isError, uint32 forSpellId, uint32 selectFlags) { Unit* resTarget; switch (Target) { case TARGET_T_SELF: return m_creature; case TARGET_T_HOSTILE: resTarget = m_creature->getVictim(); if (!resTarget) { isError = true; } return resTarget; case TARGET_T_HOSTILE_SECOND_AGGRO: resTarget = m_creature->SelectAttackingTarget(ATTACKING_TARGET_TOPAGGRO, 1, forSpellId, selectFlags); if (!resTarget && ((forSpellId == 0 && selectFlags == 0 && m_creature->GetThreatManager().getThreatList().size() > 1) || m_creature->GetThreatManager().getThreatList().empty())) { isError = true; } return resTarget; case TARGET_T_HOSTILE_LAST_AGGRO: resTarget = m_creature->SelectAttackingTarget(ATTACKING_TARGET_BOTTOMAGGRO, 0, forSpellId, selectFlags); if (!resTarget && m_creature->GetThreatManager().getThreatList().empty()) { isError = true; } return resTarget; case TARGET_T_HOSTILE_RANDOM: resTarget = m_creature->SelectAttackingTarget(ATTACKING_TARGET_RANDOM, 0, forSpellId, selectFlags); if (!resTarget && m_creature->GetThreatManager().getThreatList().empty()) { isError = true; } return resTarget; case TARGET_T_HOSTILE_RANDOM_NOT_TOP: resTarget = m_creature->SelectAttackingTarget(ATTACKING_TARGET_RANDOM, 1, forSpellId, selectFlags); if (!resTarget && ((forSpellId == 0 && selectFlags == 0 && m_creature->GetThreatManager().getThreatList().size() > 1) || m_creature->GetThreatManager().getThreatList().empty())) { isError = true; } return resTarget; case TARGET_T_HOSTILE_RANDOM_PLAYER: resTarget = m_creature->SelectAttackingTarget(ATTACKING_TARGET_RANDOM, 0, forSpellId, SELECT_FLAG_PLAYER | selectFlags); if (!resTarget) { isError = true; } return resTarget; case TARGET_T_HOSTILE_RANDOM_NOT_TOP_PLAYER: resTarget = m_creature->SelectAttackingTarget(ATTACKING_TARGET_RANDOM, 1, forSpellId, SELECT_FLAG_PLAYER | selectFlags); if (!resTarget && ((forSpellId == 0 && selectFlags == 0 && m_creature->GetThreatManager().getThreatList().size() > 1) || m_creature->GetThreatManager().getThreatList().empty())) { isError = true; } return resTarget; case TARGET_T_ACTION_INVOKER: if (!pActionInvoker) { isError = true; } return pActionInvoker; case TARGET_T_ACTION_INVOKER_OWNER: resTarget = pActionInvoker ? pActionInvoker->GetCharmerOrOwnerOrSelf() : NULL; if (!resTarget) { isError = true; } return resTarget; case TARGET_T_EVENT_SENDER: if (!pAIEventSender) { isError = true; } return pAIEventSender; default: isError = true; return NULL; }; } Unit* CreatureEventAI::DoSelectLowestHpFriendly(float range, uint32 MinHPDiff) { Unit* pUnit = NULL; MaNGOS::MostHPMissingInRangeCheck u_check(m_creature, range, MinHPDiff); MaNGOS::UnitLastSearcher searcher(pUnit, u_check); /* typedef TYPELIST_4(GameObject, Creature*except pets*, DynamicObject, Corpse*Bones*) AllGridObjectTypes; This means that if we only search grid then we can not possibly return pets or players so this is safe */ Cell::VisitGridObjects(m_creature, searcher, range); return pUnit; } void CreatureEventAI::DoFindFriendlyCC(std::list& _list, float range) { MaNGOS::FriendlyCCedInRangeCheck u_check(m_creature, range); MaNGOS::CreatureListSearcher searcher(_list, u_check); Cell::VisitGridObjects(m_creature, searcher, range); } void CreatureEventAI::DoFindFriendlyMissingBuff(std::list& _list, float range, uint32 spellid) { MaNGOS::FriendlyMissingBuffInRangeCheck u_check(m_creature, range, spellid); MaNGOS::CreatureListSearcher searcher(_list, u_check); Cell::VisitGridObjects(m_creature, searcher, range); } //********************************* //*** Functions used globally *** void CreatureEventAI::ReceiveEmote(Player* pPlayer, uint32 text_emote) { for (CreatureEventAIList::iterator itr = m_CreatureEventAIList.begin(); itr != m_CreatureEventAIList.end(); ++itr) { if ((*itr).Event.event_type == EVENT_T_RECEIVE_EMOTE) { if ((*itr).Event.receive_emote.emoteId != text_emote) { return; } PlayerCondition pcon(0, (*itr).Event.receive_emote.condition, (*itr).Event.receive_emote.conditionValue1, (*itr).Event.receive_emote.conditionValue2); if (pcon.Meets(pPlayer, m_creature->GetMap(), m_creature, CONDITION_FROM_EVENTAI)) { DEBUG_FILTER_LOG(LOG_FILTER_AI_AND_MOVEGENSS, ""CreatureEventAI: ReceiveEmote CreatureEventAI: Condition ok, processing""); ProcessEvent(*itr, pPlayer); } } } } #define HEALTH_STEPS 3 void CreatureEventAI::DamageTaken(Unit* dealer, uint32& damage) { if (m_InvinceabilityHpLevel > 0 && m_creature->GetHealth() < m_InvinceabilityHpLevel + damage) { if (m_creature->GetHealth() <= m_InvinceabilityHpLevel) { damage = 0; } else { damage = m_creature->GetHealth() - m_InvinceabilityHpLevel; } } uint32 step = m_throwAIEventStep != 100 ? m_throwAIEventStep : 0; if (step < HEALTH_STEPS) { // Throw at 90%, 50% and 10% health float healthSteps[HEALTH_STEPS] = { 90.0f, 50.0f, 10.0f }; float newHealthPercent = (m_creature->GetHealth() - damage) * 100.0f / m_creature->GetMaxHealth(); AIEventType sendEvent[HEALTH_STEPS] = { AI_EVENT_LOST_SOME_HEALTH, AI_EVENT_LOST_HEALTH, AI_EVENT_CRITICAL_HEALTH }; if (newHealthPercent > healthSteps[step]) { return; } // Not reached the next mark // search for highest reached mark (with actual event attached) for (uint32 i = HEALTH_STEPS - 1; i > step; --i) { if (newHealthPercent < healthSteps[i] && (m_throwAIEventMask & (1 << sendEvent[i]))) { step = i; break; } } if (m_throwAIEventMask & (1 << sendEvent[step])) { SendAIEventAround(sendEvent[step], dealer, 0, AIEVENT_DEFAULT_THROW_RADIUS); } m_throwAIEventStep = step + 1; } } void CreatureEventAI::HealedBy(Unit* healer, uint32& healedAmount) { if (m_throwAIEventStep == 100) { return; } if (m_creature->GetHealth() + healedAmount >= m_creature->GetMaxHealth()) { if (m_throwAIEventMask & (1 << AI_EVENT_GOT_FULL_HEALTH)) { SendAIEventAround(AI_EVENT_GOT_FULL_HEALTH, healer, 0, AIEVENT_DEFAULT_THROW_RADIUS); } m_throwAIEventStep = 100; } } bool CreatureEventAI::SpawnedEventConditionsCheck(CreatureEventAI_Event const& event) { if (event.event_type != EVENT_T_SPAWNED) { return false; } switch (event.spawned.condition) { case SPAWNED_EVENT_ALWAY: // always return true; case SPAWNED_EVENT_MAP: // map ID check return m_creature->GetMapId() == event.spawned.conditionValue1; case SPAWNED_EVENT_ZONE: { // zone ID check uint32 zone, area; m_creature->GetZoneAndAreaId(zone, area); return zone == event.spawned.conditionValue1 || area == event.spawned.conditionValue1; } default: break; } return false; } ",16169,True,3167.3425795550766,median "//========= Copyright Valve Corporation, All rights reserved. ============// // // Purpose: // // $NoKeywords: $ //=============================================================================// #include ""client_pch.h"" #include ""networkstringtabledefs.h"" #include #include #include ""pure_server.h"" #include ""netmessages.h"" #include ""cl_demo.h"" #include ""host_state.h"" #include ""host.h"" #include ""gl_matsysiface.h"" #include ""vgui_baseui_interface.h"" #include ""tier0/icommandline.h"" #include #include ""checksum_engine.h"" #include ""filesystem_engine.h"" #include ""logofile_shared.h"" #include ""sound.h"" #include ""decal.h"" #include ""networkstringtableclient.h"" #include ""dt_send_eng.h"" #include ""ents_shared.h"" #include ""cl_ents_parse.h"" #include ""cl_entityreport.h"" #include ""MapReslistGenerator.h"" #include ""DownloadListGenerator.h"" #include ""GameEventManager.h"" #include ""host_phonehome.h"" #include ""vgui_baseui_interface.h"" #include ""clockdriftmgr.h"" #include ""snd_audio_source.h"" #include ""vgui_controls/Controls.h"" #include ""vgui/ILocalize.h"" #include ""download.h"" #include ""checksum_engine.h"" #include ""ModelInfo.h"" #include ""materialsystem/imaterial.h"" #include ""materialsystem/materialsystem_config.h"" #include ""tier1/fmtstr.h"" #include ""cl_steamauth.h"" #include ""matchmaking.h"" #include ""server.h"" #include ""eiface.h"" #include ""tier0/platform.h"" #include ""tier0/systeminformation.h"" // memdbgon must be the last include file in a .cpp file!!! #include ""tier0/memdbgon.h"" static ConVar cl_timeout( ""cl_timeout"", ""30"", FCVAR_ARCHIVE, ""After this many seconds without receiving a packet from the server, the client will disconnect itself"" ); ConVar cl_logofile( ""cl_logofile"", ""materials/decals/spraylogo.vtf"", FCVAR_ARCHIVE, ""Spraypoint logo decal."" ); // TODO must be more generic static ConVar cl_soundfile( ""cl_soundfile"", ""sound/player/jingle.wav"", FCVAR_ARCHIVE, ""Jingle sound file."" ); static ConVar cl_allowdownload ( ""cl_allowdownload"", ""1"", FCVAR_ARCHIVE, ""Client downloads customization files"" ); static ConVar cl_downloadfilter( ""cl_downloadfilter"", ""all"", FCVAR_ARCHIVE, ""Determines which files can be downloaded from the server (all, none, nosounds, mapsonly)"" ); #ifdef OSX // OS X is barely making it due to virtual memory pressure on 32bit, our behavior of load new models -> unload // unused is far too abusive for its estimated margin of maybe two or three bytes before crashing. #define CONVAR_DEFAULT_ALWAYS_FLUSH_MODELS ""1"" #else #define CONVAR_DEFAULT_ALWAYS_FLUSH_MODELS ""0"" #endif static ConVar cl_always_flush_models( ""cl_always_flush_models"", CONVAR_DEFAULT_ALWAYS_FLUSH_MODELS, 0, ""If set, always flush models between map loads. Useful on systems under memory pressure."" ); extern ConVar sv_downloadurl; #if defined( _DEBUG ) || defined( STAGING_ONLY ) static ConVar debug_clientstate_fake_hltv( ""debug_clientstate_fake_hltv"", ""0"", 0, ""If set, spoof as HLTV for testing purposes."" ); #if defined( REPLAY_ENABLED ) static ConVar debug_clientstate_fake_replay( ""debug_clientstate_fake_replay"", ""0"", 0, ""If set, spoof as REPLAY for testing purposes."" ); #endif // defined( REPLAY_ENABLED ) #endif // defined( _DEBUG ) || defined( STAGING_ONLY ) ////////////////////////////////////////////////////////////////////// // Construction/Destruction ////////////////////////////////////////////////////////////////////// CClientState::CClientState() { m_bMarkedCRCsUnverified = false; demonum = -1; m_tickRemainder = 0; m_frameTime = 0; m_pAreaBits = NULL; m_hWaitForResourcesHandle = NULL; m_bUpdateSteamResources = false; m_bPrepareClientDLL = false; m_bShownSteamResourceUpdateProgress = false; m_pPureServerWhitelist = NULL; m_pPendingPureFileReloads = NULL; m_bCheckCRCsWithServer = false; m_flLastCRCBatchTime = 0; m_nFriendsID = 0; m_FriendsName[0] = 0; #if defined( REPLAY_ENABLED ) isreplay = false; #endif } CClientState::~CClientState() { if ( m_pPureServerWhitelist ) m_pPureServerWhitelist->Release(); } // HL1 CD Key #define GUID_LEN 13 /* ======================= CL_GetCDKeyHash() Connections will now use a hashed cd key value A LAN server will know not to allows more then xxx users with the same CD Key ======================= */ const char *CClientState::GetCDKeyHash( void ) { if ( IsPC() ) { char szKeyBuffer[256]; // Keys are about 13 chars long. static char szHashedKeyBuffer[64]; int nKeyLength; bool bDedicated = false; MD5Context_t ctx; unsigned char digest[16]; // The MD5 Hash nKeyLength = Q_snprintf( szKeyBuffer, sizeof( szKeyBuffer ), ""%s"", registry->ReadString( ""key"", """" ) ); if (bDedicated) { ConMsg(""Key has no meaning on dedicated server...\\n""); return """"; } if ( nKeyLength == 0 ) { nKeyLength = 13; Q_strncpy( szKeyBuffer, ""1234567890123"", sizeof( szKeyBuffer ) ); Assert( Q_strlen( szKeyBuffer ) == nKeyLength ); DevMsg( ""Missing CD Key from registry, inserting blank key\\n"" ); registry->WriteString( ""key"", szKeyBuffer ); } if (nKeyLength <= 0 || nKeyLength >= 256 ) { ConMsg(""Bogus key length on CD Key...\\n""); return """"; } // Now get the md5 hash of the key memset( &ctx, 0, sizeof( ctx ) ); memset( digest, 0, sizeof( digest ) ); MD5Init(&ctx); MD5Update(&ctx, (unsigned char*)szKeyBuffer, nKeyLength); MD5Final(digest, &ctx); Q_strncpy ( szHashedKeyBuffer, MD5_Print ( digest, sizeof( digest ) ), sizeof( szHashedKeyBuffer ) ); return szHashedKeyBuffer; } return ""12345678901234567890123456789012""; } void CClientState::SendClientInfo( void ) { CLC_ClientInfo info; info.m_nSendTableCRC = SendTable_GetCRC(); info.m_nServerCount = m_nServerCount; info.m_bIsHLTV = false; #if defined( REPLAY_ENABLED ) info.m_bIsReplay = false; #endif #if !defined( NO_STEAM ) info.m_nFriendsID = Steam3Client().SteamUser() ? Steam3Client().SteamUser()->GetSteamID().GetAccountID() : 0; #else info.m_nFriendsID = 0; #endif Q_strncpy( info.m_FriendsName, m_FriendsName, sizeof(info.m_FriendsName) ); CheckOwnCustomFiles(); // load & verfiy custom player files for ( int i=0; i< MAX_CUSTOM_FILES; i++ ) info.m_nCustomFiles[i] = m_nCustomFiles[i].crc; // Testing to ensure we don't blow up servers by faking our client info #if defined( _DEBUG ) || defined( STAGING_ONLY ) if ( debug_clientstate_fake_hltv.GetBool() ) { Msg( ""!! Spoofing connect as HLTV in SendClientInfo\\n"" ); info.m_bIsHLTV = true; } #if defined( REPLAY_ENABLED ) if ( debug_clientstate_fake_replay.GetBool() ) { Msg( ""!! Spoofing connect as REPLAY in SendClientInfo\\n"" ); info.m_bIsReplay = true; } #endif // defined( REPLAY_ENABLED ) #endif // defined( _DEBUG ) || defined( STAGING_ONLY ) m_NetChannel->SendNetMsg( info ); } void CClientState::SendServerCmdKeyValues( KeyValues *pKeyValues ) { if ( !pKeyValues ) return; CLC_CmdKeyValues clcCommand( pKeyValues ); if ( !m_NetChannel ) return; m_NetChannel->SendNetMsg( clcCommand ); } extern IVEngineClient *engineClient; //----------------------------------------------------------------------------- // Purpose: A svc_signonnum has been received, perform a client side setup // Output : void CL_SignonReply //----------------------------------------------------------------------------- bool CClientState::SetSignonState ( int state, int count ) { if ( !CBaseClientState::SetSignonState( state, count ) ) { CL_Retry(); return false; } // ConDMsg (""Signon state: %i\\n"", state ); COM_TimestampedLog( ""CClientState::SetSignonState: start %i"", state ); switch ( m_nSignonState ) { case SIGNONSTATE_CHALLENGE : m_bMarkedCRCsUnverified = false; // Remember that we just connected to a new server so it'll // reverify any necessary file CRCs on this server. EngineVGui()->UpdateProgressBar(PROGRESS_SIGNONCHALLENGE); break; case SIGNONSTATE_CONNECTED : { EngineVGui()->UpdateProgressBar(PROGRESS_SIGNONCONNECTED); // make sure it's turned off when connecting EngineVGui()->HideDebugSystem(); SCR_BeginLoadingPlaque (); // Clear channel and stuff m_NetChannel->Clear(); // allow longer timeout m_NetChannel->SetTimeout( SIGNON_TIME_OUT ); m_NetChannel->SetMaxBufferSize( true, NET_MAX_PAYLOAD ); // set user settings (rate etc) NET_SetConVar convars; Host_BuildConVarUpdateMessage( &convars, FCVAR_USERINFO, false ); m_NetChannel->SendNetMsg( convars ); } break; case SIGNONSTATE_NEW : { EngineVGui()->UpdateProgressBar(PROGRESS_SIGNONNEW); if ( IsPC() && !demoplayer->IsPlayingBack() ) { // start making sure we have all the specified resources StartUpdatingSteamResources(); } else { // during demo playback dont try to download resource FinishSignonState_New(); } // don't tell the server yet that we've entered this state return true; } break; case SIGNONSTATE_PRESPAWN : m_nSoundSequence = 1; // reset sound sequence number after receiving signon sounds break; case SIGNONSTATE_SPAWN : { Assert( g_ClientDLL ); EngineVGui()->UpdateProgressBar(PROGRESS_SIGNONSPAWN); // Tell client .dll about the transition char mapname[256]; CL_SetupMapName( modelloader->GetName( host_state.worldmodel ), mapname, sizeof( mapname ) ); COM_TimestampedLog( ""LevelInitPreEntity: start %d"", state ); g_ClientDLL->LevelInitPreEntity(mapname); COM_TimestampedLog( ""LevelInitPreEntity: end %d"", state ); phonehome->Message( IPhoneHome::PHONE_MSG_MAPSTART, mapname ); audiosourcecache->LevelInit( mapname ); // stop recording demo header demorecorder->SetSignonState( SIGNONSTATE_SPAWN ); } break; case SIGNONSTATE_FULL: { CL_FullyConnected(); if ( m_NetChannel ) { m_NetChannel->SetTimeout( cl_timeout.GetFloat() ); m_NetChannel->SetMaxBufferSize( true, NET_MAX_DATAGRAM_PAYLOAD ); } HostState_OnClientConnected(); if ( m_nMaxClients > 1 ) { g_pMatchmaking->AddLocalPlayersToTeams(); } } break; case SIGNONSTATE_CHANGELEVEL: m_NetChannel->SetTimeout( SIGNON_TIME_OUT ); // allow 5 minutes timeout if ( m_nMaxClients > 1 ) { // start progress bar immediately for multiplayer level transitions EngineVGui()->EnabledProgressBarForNextLoad(); } SCR_BeginLoadingPlaque(); if ( m_nMaxClients > 1 ) { EngineVGui()->UpdateProgressBar(PROGRESS_CHANGELEVEL); } break; } COM_TimestampedLog( ""CClientState::SetSignonState: end %i"", state ); if ( state >= SIGNONSTATE_CONNECTED && m_NetChannel ) { // tell server that we entered now that state m_NetChannel->SendNetMsg( NET_SignonState( state, count) ); } return true; } bool CClientState::HookClientStringTable( char const *tableName ) { INetworkStringTable *table = GetStringTable( tableName ); if ( !table ) { // If engine takes a pass, allow client dll to hook in its callbacks if ( g_ClientDLL ) { g_ClientDLL->InstallStringTableCallback( tableName ); } return false; } #if 0 // This was added into staging at some point and is not enabled in main or rel. char szDownloadableFileTablename[255] = DOWNLOADABLE_FILE_TABLENAME; char szModelPrecacheTablename[255] = MODEL_PRECACHE_TABLENAME; char szGenericPrecacheTablename[255] = GENERIC_PRECACHE_TABLENAME; char szSoundPrecacheTablename[255] = SOUND_PRECACHE_TABLENAME; char szDecalPrecacheTablename[255] = DECAL_PRECACHE_TABLENAME; Q_snprintf( szDownloadableFileTablename, 255, "":%s"", DOWNLOADABLE_FILE_TABLENAME ); Q_snprintf( szModelPrecacheTablename, 255, "":%s"", MODEL_PRECACHE_TABLENAME ); Q_snprintf( szGenericPrecacheTablename, 255, "":%s"", GENERIC_PRECACHE_TABLENAME ); Q_snprintf( szSoundPrecacheTablename, 255, "":%s"", SOUND_PRECACHE_TABLENAME ); Q_snprintf( szDecalPrecacheTablename, 255, "":%s"", DECAL_PRECACHE_TABLENAME ); #else const char *szDownloadableFileTablename = DOWNLOADABLE_FILE_TABLENAME; const char *szModelPrecacheTablename = MODEL_PRECACHE_TABLENAME; const char *szGenericPrecacheTablename = GENERIC_PRECACHE_TABLENAME; const char *szSoundPrecacheTablename = SOUND_PRECACHE_TABLENAME; const char *szDecalPrecacheTablename = DECAL_PRECACHE_TABLENAME; #endif // Hook Model Precache table if ( !Q_strcasecmp( tableName, szModelPrecacheTablename ) ) { m_pModelPrecacheTable = table; return true; } if ( !Q_strcasecmp( tableName, szGenericPrecacheTablename ) ) { m_pGenericPrecacheTable = table; return true; } if ( !Q_strcasecmp( tableName, szSoundPrecacheTablename ) ) { m_pSoundPrecacheTable = table; return true; } if ( !Q_strcasecmp( tableName, szDecalPrecacheTablename ) ) { // Cache the id m_pDecalPrecacheTable = table; return true; } if ( !Q_strcasecmp( tableName, INSTANCE_BASELINE_TABLENAME ) ) { // Cache the id m_pInstanceBaselineTable = table; return true; } if ( !Q_strcasecmp( tableName, LIGHT_STYLES_TABLENAME ) ) { // Cache the id m_pLightStyleTable = table; return true; } if ( !Q_strcasecmp( tableName, USER_INFO_TABLENAME ) ) { // Cache the id m_pUserInfoTable = table; return true; } if ( !Q_strcasecmp( tableName, SERVER_STARTUP_DATA_TABLENAME ) ) { // Cache the id m_pServerStartupTable = table; return true; } if ( !Q_strcasecmp( tableName, szDownloadableFileTablename ) ) { // Cache the id m_pDownloadableFileTable = table; return true; } if ( !Q_strcasecmp( tableName, ""DynamicModels"" ) ) { m_pDynamicModelsTable = table; return true; } // If engine takes a pass, allow client dll to hook in its callbacks g_ClientDLL->InstallStringTableCallback( tableName ); return false; } bool CClientState::InstallEngineStringTableCallback( char const *tableName ) { INetworkStringTable *table = GetStringTable( tableName ); if ( !table ) return false; #if 0 // This was added into staging at some point and is not enabled in main or rel. char szDownloadableFileTablename[255] = DOWNLOADABLE_FILE_TABLENAME; char szModelPrecacheTablename[255] = MODEL_PRECACHE_TABLENAME; char szGenericPrecacheTablename[255] = GENERIC_PRECACHE_TABLENAME; char szSoundPrecacheTablename[255] = SOUND_PRECACHE_TABLENAME; char szDecalPrecacheTablename[255] = DECAL_PRECACHE_TABLENAME; Q_snprintf( szDownloadableFileTablename, 255, "":%s"", DOWNLOADABLE_FILE_TABLENAME ); Q_snprintf( szModelPrecacheTablename, 255, "":%s"", MODEL_PRECACHE_TABLENAME ); Q_snprintf( szGenericPrecacheTablename, 255, "":%s"", GENERIC_PRECACHE_TABLENAME ); Q_snprintf( szSoundPrecacheTablename, 255, "":%s"", SOUND_PRECACHE_TABLENAME ); Q_snprintf( szDecalPrecacheTablename, 255, "":%s"", DECAL_PRECACHE_TABLENAME ); #else const char *szDownloadableFileTablename = DOWNLOADABLE_FILE_TABLENAME; const char *szModelPrecacheTablename = MODEL_PRECACHE_TABLENAME; const char *szGenericPrecacheTablename = GENERIC_PRECACHE_TABLENAME; const char *szSoundPrecacheTablename = SOUND_PRECACHE_TABLENAME; const char *szDecalPrecacheTablename = DECAL_PRECACHE_TABLENAME; #endif // Hook Model Precache table if ( !Q_strcasecmp( tableName, szModelPrecacheTablename ) ) { table->SetStringChangedCallback( NULL, Callback_ModelChanged ); return true; } if ( !Q_strcasecmp( tableName, szGenericPrecacheTablename ) ) { // Install the callback table->SetStringChangedCallback( NULL, Callback_GenericChanged ); return true; } if ( !Q_strcasecmp( tableName, szSoundPrecacheTablename ) ) { // Install the callback table->SetStringChangedCallback( NULL, Callback_SoundChanged ); return true; } if ( !Q_strcasecmp( tableName, szDecalPrecacheTablename ) ) { // Install the callback table->SetStringChangedCallback( NULL, Callback_DecalChanged ); return true; } if ( !Q_strcasecmp( tableName, INSTANCE_BASELINE_TABLENAME ) ) { // Install the callback (already done above) table->SetStringChangedCallback( NULL, Callback_InstanceBaselineChanged ); return true; } if ( !Q_strcasecmp( tableName, LIGHT_STYLES_TABLENAME ) ) { return true; } if ( !Q_strcasecmp( tableName, USER_INFO_TABLENAME ) ) { // Install the callback table->SetStringChangedCallback( NULL, Callback_UserInfoChanged ); return true; } if ( !Q_strcasecmp( tableName, SERVER_STARTUP_DATA_TABLENAME ) ) { return true; } if ( !Q_strcasecmp( tableName, szDownloadableFileTablename ) ) { return true; } if ( !Q_strcasecmp( tableName, ""DynamicModels"" ) ) { table->SetStringChangedCallback( NULL, Callback_DynamicModelsChanged ); m_pDynamicModelsTable = table; return true; } // The the client.dll have a shot at it return false; } void CClientState::InstallStringTableCallback( char const *tableName ) { // Let engine hook callbacks before we read in any data values at all if ( !InstallEngineStringTableCallback( tableName ) ) { // If engine takes a pass, allow client dll to hook in its callbacks g_ClientDLL->InstallStringTableCallback( tableName ); } } bool CClientState::IsPaused() const { return m_bPaused || ( g_LostVideoMemory && Host_IsSinglePlayerGame() ) || !host_initialized || demoplayer->IsPlaybackPaused() || EngineVGui()->ShouldPause(); } float CClientState::GetTime() const { int nTickCount = GetClientTickCount(); float flTickTime = nTickCount * host_state.interval_per_tick; // Timestamps are rounded to exact tick during simulation if ( insimulation ) { return flTickTime; } return flTickTime + m_tickRemainder; } float CClientState::GetFrameTime() const { if ( CClockDriftMgr::IsClockCorrectionEnabled() ) { return IsPaused() ? 0 : m_frameTime; } else { if ( insimulation ) { int nElapsedTicks = ( GetClientTickCount() - oldtickcount ); return nElapsedTicks * host_state.interval_per_tick; } else { return IsPaused() ? 0 : m_frameTime; } } } float CClientState::GetClientInterpAmount() { // we need client cvar cl_interp_ratio static const ConVar *s_cl_interp_ratio = NULL; if ( !s_cl_interp_ratio ) { s_cl_interp_ratio = g_pCVar->FindVar( ""cl_interp_ratio"" ); if ( !s_cl_interp_ratio ) return 0.1f; } static const ConVar *s_cl_interp = NULL; if ( !s_cl_interp ) { s_cl_interp = g_pCVar->FindVar( ""cl_interp"" ); if ( !s_cl_interp ) return 0.1f; } float flInterpRatio = s_cl_interp_ratio->GetFloat(); float flInterp = s_cl_interp->GetFloat(); const ConVar_ServerBounded *pBounded = static_cast( s_cl_interp_ratio ); if ( pBounded ) flInterpRatio = pBounded->GetFloat(); //#define FIXME_INTERP_RATIO return max( flInterpRatio / cl_updaterate->GetFloat(), flInterp ); } //----------------------------------------------------------------------------- // Purpose: // Clear all the variables in the CClientState. //----------------------------------------------------------------------------- void CClientState::Clear( void ) { CBaseClientState::Clear(); m_pModelPrecacheTable = NULL; m_pGenericPrecacheTable = NULL; m_pSoundPrecacheTable = NULL; m_pDecalPrecacheTable = NULL; m_pInstanceBaselineTable = NULL; m_pLightStyleTable = NULL; m_pUserInfoTable = NULL; m_pServerStartupTable = NULL; m_pDynamicModelsTable = NULL; m_pAreaBits = NULL; // Clear all download vars. m_pDownloadableFileTable = NULL; m_hWaitForResourcesHandle = NULL; m_bUpdateSteamResources = false; m_bShownSteamResourceUpdateProgress = false; m_bDownloadResources = false; m_bPrepareClientDLL = false; DeleteClientFrames( -1 ); // clear all viewangles.Init(); m_flLastServerTickTime = 0.0f; oldtickcount = 0; insimulation = false; addangle.RemoveAll(); addangletotal = 0.0f; prevaddangletotal = 0.0f; memset(model_precache, 0, sizeof(model_precache)); memset(sound_precache, 0, sizeof(sound_precache)); ishltv = false; #if defined( REPLAY_ENABLED ) isreplay = false; #endif cdtrack = 0; V_memset( serverMD5.bits, 0, MD5_DIGEST_LENGTH ); last_command_ack = 0; command_ack = 0; m_nSoundSequence = 0; // make sure the client isn't active anymore, but stay // connected if we are. if ( m_nSignonState > SIGNONSTATE_CONNECTED ) { m_nSignonState = SIGNONSTATE_CONNECTED; } } void CClientState::ClearSounds() { int c = ARRAYSIZE( sound_precache ); for ( int i = 0; i < c; ++i ) { sound_precache[ i ].SetSound( NULL ); } } bool CClientState::ProcessConnectionlessPacket( netpacket_t *packet ) { Assert( packet ); return CBaseClientState::ProcessConnectionlessPacket( packet ); } void CClientState::FullConnect( netadr_t &adr ) { CBaseClientState::FullConnect( adr ); m_NetChannel->SetDemoRecorder( g_pClientDemoRecorder ); m_NetChannel->SetDataRate( cl_rate->GetFloat() ); // Not in the demo loop now demonum = -1; // We don't have a backed up cmd history yet lastoutgoingcommand = -1; // we didn't send commands yet chokedcommands = 0; // Report connection success. if ( Q_stricmp(""loopback"", adr.ToString() ) ) { ConMsg( ""Connected to %s\\n"", adr.ToString() ); } } //----------------------------------------------------------------------------- // Purpose: // Input : index - // Output : model_t //----------------------------------------------------------------------------- model_t *CClientState::GetModel( int index ) { if ( !m_pModelPrecacheTable ) { return NULL; } if ( index <= 0 ) { return NULL; } if ( index >= m_pModelPrecacheTable->GetNumStrings() ) { Assert( 0 ); // model index for unkown model requested return NULL; } CPrecacheItem *p = &model_precache[ index ]; model_t *m = p->GetModel(); if ( m ) { return m; } // The world model has special handling and should not be lazy loaded here if ( index == 1 ) { Assert( false ); Warning( ""Attempting to get world model before it was loaded\\n"" ); return NULL; } char const *name = m_pModelPrecacheTable->GetString( index ); if ( host_showcachemiss.GetBool() ) { ConDMsg( ""client model cache miss on %s\\n"", name ); } m = modelloader->GetModelForName( name, IModelLoader::FMODELLOADER_CLIENT ); if ( !m ) { const CPrecacheUserData *data = CL_GetPrecacheUserData( m_pModelPrecacheTable, index ); if ( data && ( data->flags & RES_FATALIFMISSING ) ) { COM_ExplainDisconnection( true, ""Cannot continue without model %s, disconnecting\\n"", name ); Host_Disconnect( true, ""Missing model"" ); } } p->SetModel( m ); return m; } //----------------------------------------------------------------------------- // Purpose: // Input : *name - // Output : int -- note -1 if missing //----------------------------------------------------------------------------- int CClientState::LookupModelIndex( char const *name ) { if ( !m_pModelPrecacheTable ) { return -1; } int idx = m_pModelPrecacheTable->FindStringIndex( name ); return ( idx == INVALID_STRING_INDEX ) ? -1 : idx; } //----------------------------------------------------------------------------- // Purpose: // Input : index - // *name - //----------------------------------------------------------------------------- void CClientState::SetModel( int tableIndex ) { if ( !m_pModelPrecacheTable ) { return; } // Bogus index if ( tableIndex < 0 || tableIndex >= m_pModelPrecacheTable->GetNumStrings() ) { return; } char const *name = m_pModelPrecacheTable->GetString( tableIndex ); if ( tableIndex == 1 ) { // The world model must match the LevelFileName -- it is the path we just checked the CRC for, and paths may differ // from what the server is using based on what the gameDLL override does name = m_szLevelFileName; } CPrecacheItem *p = &model_precache[ tableIndex ]; const CPrecacheUserData *data = CL_GetPrecacheUserData( m_pModelPrecacheTable, tableIndex ); bool bLoadNow = ( data && ( data->flags & RES_PRELOAD ) ) || IsX360(); if ( CommandLine()->FindParm( ""-nopreload"" ) || CommandLine()->FindParm( ""-nopreloadmodels"" )) { bLoadNow = false; } else if ( CommandLine()->FindParm( ""-preload"" ) ) { bLoadNow = true; } if ( bLoadNow ) { p->SetModel( modelloader->GetModelForName( name, IModelLoader::FMODELLOADER_CLIENT ) ); } else { p->SetModel( NULL ); } // log the file reference, if necssary if (MapReslistGenerator().IsEnabled()) { name = m_pModelPrecacheTable->GetString( tableIndex ); MapReslistGenerator().OnModelPrecached( name ); } } //----------------------------------------------------------------------------- // Purpose: // Input : index - // Output : model_t //----------------------------------------------------------------------------- char const *CClientState::GetGeneric( int index ) { if ( !m_pGenericPrecacheTable ) { Warning( ""Can't GetGeneric( %d ), no precache table [no level loaded?]\\n"", index ); return """"; } if ( index <= 0 ) return """"; if ( index >= m_pGenericPrecacheTable->GetNumStrings() ) { return """"; } CPrecacheItem *p = &generic_precache[ index ]; char const *g = p->GetGeneric(); return g; } //----------------------------------------------------------------------------- // Purpose: // Input : *name - // Output : int -- note -1 if missing //----------------------------------------------------------------------------- int CClientState::LookupGenericIndex( char const *name ) { if ( !m_pGenericPrecacheTable ) { Warning( ""Can't LookupGenericIndex( %s ), no precache table [no level loaded?]\\n"", name ); return -1; } int idx = m_pGenericPrecacheTable->FindStringIndex( name ); return ( idx == INVALID_STRING_INDEX ) ? -1 : idx; } //----------------------------------------------------------------------------- // Purpose: // Input : index - // *name - //----------------------------------------------------------------------------- void CClientState::SetGeneric( int tableIndex ) { if ( !m_pGenericPrecacheTable ) { Warning( ""Can't SetGeneric( %d ), no precache table [no level loaded?]\\n"", tableIndex ); return; } // Bogus index if ( tableIndex < 0 || tableIndex >= m_pGenericPrecacheTable->GetNumStrings() ) { return; } char const *name = m_pGenericPrecacheTable->GetString( tableIndex ); CPrecacheItem *p = &generic_precache[ tableIndex ]; p->SetGeneric( name ); } //----------------------------------------------------------------------------- // Purpose: // Input : index - // Output : char const //----------------------------------------------------------------------------- char const *CClientState::GetSoundName( int index ) { if ( index <= 0 || !m_pSoundPrecacheTable ) return """"; if ( index >= m_pSoundPrecacheTable->GetNumStrings() ) { return """"; } char const *name = m_pSoundPrecacheTable->GetString( index ); return name; } //----------------------------------------------------------------------------- // Purpose: // Input : index - // Output : model_t //----------------------------------------------------------------------------- CSfxTable *CClientState::GetSound( int index ) { if ( index <= 0 || !m_pSoundPrecacheTable ) return NULL; if ( index >= m_pSoundPrecacheTable->GetNumStrings() ) { return NULL; } CPrecacheItem *p = &sound_precache[ index ]; CSfxTable *s = p->GetSound(); if ( s ) return s; char const *name = m_pSoundPrecacheTable->GetString( index ); if ( host_showcachemiss.GetBool() ) { ConDMsg( ""client sound cache miss on %s\\n"", name ); } s = S_PrecacheSound( name ); p->SetSound( s ); return s; } //----------------------------------------------------------------------------- // Purpose: // Input : *name - // Output : int -- note -1 if missing //----------------------------------------------------------------------------- int CClientState::LookupSoundIndex( char const *name ) { if ( !m_pSoundPrecacheTable ) return -1; int idx = m_pSoundPrecacheTable->FindStringIndex( name ); return ( idx == INVALID_STRING_INDEX ) ? -1 : idx; } //----------------------------------------------------------------------------- // Purpose: // Input : index - // *name - //----------------------------------------------------------------------------- void CClientState::SetSound( int tableIndex ) { // Bogus index if ( !m_pSoundPrecacheTable ) return; if ( tableIndex < 0 || tableIndex >= m_pSoundPrecacheTable->GetNumStrings() ) { return; } CPrecacheItem *p = &sound_precache[ tableIndex ]; const CPrecacheUserData *data = CL_GetPrecacheUserData( m_pSoundPrecacheTable, tableIndex ); bool bLoadNow = ( data && ( data->flags & RES_PRELOAD ) ) || IsX360(); if ( CommandLine()->FindParm( ""-nopreload"" ) || CommandLine()->FindParm( ""-nopreloadsounds"" )) { bLoadNow = false; } else if ( CommandLine()->FindParm( ""-preload"" ) ) { bLoadNow = true; } if ( bLoadNow ) { char const *name = m_pSoundPrecacheTable->GetString( tableIndex ); p->SetSound( S_PrecacheSound( name ) ); } else { p->SetSound( NULL ); } // log the file reference, if necssary if (MapReslistGenerator().IsEnabled()) { char const *name = m_pSoundPrecacheTable->GetString( tableIndex ); MapReslistGenerator().OnSoundPrecached( name ); } } //----------------------------------------------------------------------------- // Purpose: // Input : index - // Output : model_t //----------------------------------------------------------------------------- char const *CClientState::GetDecalName( int index ) { if ( index <= 0 || !m_pDecalPrecacheTable ) { return NULL; } if ( index >= m_pDecalPrecacheTable->GetNumStrings() ) { return NULL; } CPrecacheItem *p = &decal_precache[ index ]; char const *d = p->GetDecal(); return d; } //----------------------------------------------------------------------------- // Purpose: // Input : index - // *name - //----------------------------------------------------------------------------- void CClientState::SetDecal( int tableIndex ) { if ( !m_pDecalPrecacheTable ) return; if ( tableIndex < 0 || tableIndex >= m_pDecalPrecacheTable->GetNumStrings() ) { return; } char const *name = m_pDecalPrecacheTable->GetString( tableIndex ); CPrecacheItem *p = &decal_precache[ tableIndex ]; p->SetDecal( name ); Draw_DecalSetName( tableIndex, (char *)name ); } //----------------------------------------------------------------------------- // Purpose: sets friends info locally to be sent to other users //----------------------------------------------------------------------------- void CClientState::SetFriendsID( uint friendsID, const char *friendsName ) { m_nFriendsID = friendsID; Q_strncpy( m_FriendsName, friendsName, sizeof(m_FriendsName) ); } void CClientState::CheckOthersCustomFile( CRC32_t crcValue ) { if ( crcValue == 0 ) return; // not a valid custom file if ( !cl_allowdownload.GetBool() ) return; // client doesn't want to download anything CCustomFilename filehex( crcValue ); if ( g_pFileSystem->FileExists( filehex.m_Filename, ""game"" ) ) return; // we already have this file (assuming the CRC is correct) // we don't have it, request download from server m_NetChannel->RequestFile( filehex.m_Filename ); } void CClientState::AddCustomFile( int slot, const char *resourceFile) { if ( Q_strlen(resourceFile) <= 0 ) return; // no resource file given if ( !COM_IsValidPath( resourceFile ) ) { Msg(""Customization file '%s' has invalid path.\\n"", resourceFile ); return; } if ( slot < 0 || slot >= MAX_CUSTOM_FILES ) return; // wrong slot if ( !g_pFileSystem->FileExists( resourceFile ) ) { DevMsg(""Couldn't find customization file '%s'.\\n"", resourceFile ); return; // resource file doesn't exits } if ( g_pFileSystem->Size( resourceFile ) > MAX_CUSTOM_FILE_SIZE ) { Msg(""Customization file '%s' is too big ( >%i bytes).\\n"", resourceFile, MAX_CUSTOM_FILE_SIZE ); return; // resource file doesn't exits } CRC32_t crcValue; // Compute checksum of resource file CRC_File( &crcValue, resourceFile ); // Copy it into materials/downloads if it's not there yet, so the server doesn't have to // transmit the file back to us. bool bCopy = true; CCustomFilename filehex( crcValue ); char szAbsFilename[ MAX_PATH ]; if ( g_pFileSystem->RelativePathToFullPath( filehex.m_Filename, ""game"", szAbsFilename, sizeof(szAbsFilename), FILTER_CULLPACK ) ) { // check if existing file already has same CRC, // then we don't need to copy it anymore CRC32_t test; CRC_File( &test, szAbsFilename ); if ( test == crcValue ) bCopy = false; } if ( bCopy ) { // Copy it over under the new name // Load up the file CUtlBuffer buf; if ( !g_pFileSystem->ReadFile( resourceFile, ""game"", buf ) ) { Warning( ""CacheCustomFiles: can't read '%s'.\\n"", resourceFile ); return; } // Make sure dest directory exists char szParentDir[ MAX_PATH ]; V_ExtractFilePath( filehex.m_Filename, szParentDir, sizeof(szParentDir) ); g_pFileSystem->CreateDirHierarchy( szParentDir, ""download"" ); // Save it if ( !g_pFileSystem->WriteFile( filehex.m_Filename, ""download"", buf ) ) { Warning( ""CacheCustomFiles: can't write '%s'.\\n"", filehex.m_Filename ); return; } } /* Finally, validate the VTF file. TODO CUtlVector fileData; if ( LogoFile_ReadFile( crcValue, fileData ) ) { bValid = true; } else { Warning( ""CL_LogoFile_OnConnect: logo file '%s' invalid.\\n"", logotexture ); } */ m_nCustomFiles[slot].crc = crcValue; // first slot is logo m_nCustomFiles[slot].reqID = 0; } void CClientState::CheckOwnCustomFiles() { // clear file CRCs Q_memset( m_nCustomFiles, 0, sizeof(m_nCustomFiles) ); if ( m_nMaxClients == 1 ) return; // not in singleplayer if ( IsPC() ) { AddCustomFile( 0, cl_logofile.GetString() ); AddCustomFile( 1, cl_soundfile.GetString() ); } } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CClientState::DumpPrecacheStats( const char * name ) { if ( !name || !name[0] ) { ConMsg( ""Can only dump stats when active in a level\\n"" ); return; } CPrecacheItem *items = NULL; if ( !Q_strcmp(MODEL_PRECACHE_TABLENAME, name ) ) { items = model_precache; } else if ( !Q_strcmp(GENERIC_PRECACHE_TABLENAME, name ) ) { items = generic_precache; } else if ( !Q_strcmp(SOUND_PRECACHE_TABLENAME, name ) ) { items = sound_precache; } else if ( !Q_strcmp(DECAL_PRECACHE_TABLENAME, name ) ) { items = decal_precache; } INetworkStringTable *table = GetStringTable( name ); if ( !items || !table) { ConMsg( ""Precache table '%s' not found.\\n"", name ); return; } int count = table->GetNumStrings(); int maxcount = table->GetMaxStrings(); ConMsg( ""\\n"" ); ConMsg( ""Precache table %s: %i of %i slots used\\n"", table->GetTableName(), count, maxcount ); for ( int i = 0; i < count; i++ ) { char const *pchName = table->GetString( i ); CPrecacheItem *slot = &items[ i ]; const CPrecacheUserData *p = CL_GetPrecacheUserData( table, i ); if ( !pchName || !slot || !p ) continue; ConMsg( ""%03i: %s (%s): "", i, pchName, GetFlagString( p->flags ) ); if ( slot->GetReferenceCount() == 0 ) { ConMsg( "" never used\\n"" ); } else { ConMsg( "" %i refs, first %.2f mru %.2f\\n"", slot->GetReferenceCount(), slot->GetFirstReference(), slot->GetMostRecentReference() ); } } ConMsg( ""\\n"" ); } void CClientState::ReadDeletions( CEntityReadInfo &u ) { VPROF( ""ReadDeletions"" ); while ( u.m_pBuf->ReadOneBit()!=0 ) { int idx = u.m_pBuf->ReadUBitLong( MAX_EDICT_BITS ); Assert( !u.m_pTo->transmit_entity.Get( idx ) ); CL_DeleteDLLEntity( idx, ""ReadDeletions"" ); } } void CClientState::ReadEnterPVS( CEntityReadInfo &u ) { VPROF( ""ReadEnterPVS"" ); TRACE_PACKET(( "" CL Enter PVS (%d)\\n"", u.m_nNewEntity )); int iClass = u.m_pBuf->ReadUBitLong( m_nServerClassBits ); int iSerialNum = u.m_pBuf->ReadUBitLong( NUM_NETWORKED_EHANDLE_SERIAL_NUMBER_BITS ); CL_CopyNewEntity( u, iClass, iSerialNum ); if ( u.m_nNewEntity == u.m_nOldEntity ) // that was a recreate u.NextOldEntity(); } void CClientState::ReadLeavePVS( CEntityReadInfo &u ) { VPROF( ""ReadLeavePVS"" ); // Sanity check. if ( !u.m_bAsDelta ) { Assert(0); // cl.validsequence = 0; ConMsg( ""WARNING: LeavePVS on full update"" ); u.m_UpdateType = Failed; // break out return; } Assert( !u.m_pTo->transmit_entity.Get( u.m_nOldEntity ) ); if ( u.m_UpdateFlags & FHDR_DELETE ) { CL_DeleteDLLEntity( u.m_nOldEntity, ""ReadLeavePVS"" ); } u.NextOldEntity(); } void CClientState::ReadDeltaEnt( CEntityReadInfo &u ) { VPROF( ""ReadDeltaEnt"" ); CL_CopyExistingEntity( u ); u.NextOldEntity(); } void CClientState::ReadPreserveEnt( CEntityReadInfo &u ) { VPROF( ""ReadPreserveEnt"" ); if ( !u.m_bAsDelta ) // Should never happen on a full update. { Assert(0); // cl.validsequence = 0; ConMsg( ""WARNING: PreserveEnt on full update"" ); u.m_UpdateType = Failed; // break out return; } Assert( u.m_pFrom->transmit_entity.Get(u.m_nOldEntity) ); // copy one of the old entities over to the new packet unchanged // XXX(JohnS): This was historically checking for NewEntity overflow, though this path does not care (and new entity // may be -1). The old entity bounds check here seems like what was intended, but since nNewEntity // should not be overflowed either, I've left that check in case it was guarding against a case I am // overlooking. if ( u.m_nOldEntity >= MAX_EDICTS || u.m_nOldEntity < 0 || u.m_nNewEntity >= MAX_EDICTS ) { Host_Error( ""CL_ReadPreserveEnt: Entity out of bounds. Old: %i, New: %i"", u.m_nOldEntity, u.m_nNewEntity ); } u.m_pTo->last_entity = u.m_nOldEntity; u.m_pTo->transmit_entity.Set( u.m_nOldEntity ); // Zero overhead if ( cl_entityreport.GetBool() ) CL_RecordEntityBits( u.m_nOldEntity, 0 ); CL_PreserveExistingEntity( u.m_nOldEntity ); u.NextOldEntity(); } //----------------------------------------------------------------------------- // Purpose: Starts checking that all the necessary files are local //----------------------------------------------------------------------------- void CClientState::StartUpdatingSteamResources() { if ( IsX360() ) { return; } // we can only do this when in SIGNONSTATE_NEW, // since the completion of this triggers the continuation of SIGNONSTATE_NEW Assert(m_nSignonState == SIGNONSTATE_NEW); // make sure we have all the necessary resources locally before continuing m_hWaitForResourcesHandle = g_pFileSystem->WaitForResources(m_szLevelBaseName); m_bUpdateSteamResources = false; m_bShownSteamResourceUpdateProgress = false; m_bDownloadResources = false; m_bPrepareClientDLL = true; } //----------------------------------------------------------------------------- // Purpose: checks to see if we're done updating files //----------------------------------------------------------------------------- void CClientState::CheckUpdatingSteamResources() { if ( IsX360() ) { return; } VPROF_BUDGET( ""CheckUpdatingSteamResources"", VPROF_BUDGETGROUP_STEAM ); if ( m_bPrepareClientDLL ) { float flPrepareProgress = 0.f; char szMutableLevelName[ sizeof( m_szLevelBaseName ) ] = { 0 }; V_strncpy( szMutableLevelName, m_szLevelBaseName, sizeof( szMutableLevelName ) ); // if the game .dll doesn't support this call assume everything is prepared IServerGameDLL::ePrepareLevelResourcesResult eResult = IServerGameDLL::ePrepareLevelResources_Prepared; if ( g_iServerGameDLLVersion >= 10 ) { eResult = serverGameDLL->AsyncPrepareLevelResources( szMutableLevelName, sizeof( szMutableLevelName ), m_szLevelFileName, sizeof( m_szLevelFileName ), &flPrepareProgress ); } switch ( eResult ) { case IServerGameDLL::ePrepareLevelResources_InProgress: if (!m_bShownSteamResourceUpdateProgress) { // make sure the loading dialog is up EngineVGui()->StartCustomProgress(); EngineVGui()->ActivateGameUI(); m_bShownSteamResourceUpdateProgress = true; } EngineVGui()->UpdateCustomProgressBar( flPrepareProgress, g_pVGuiLocalize->Find(""#Valve_UpdatingSteamResources"") ); break; default: case IServerGameDLL::ePrepareLevelResources_Prepared: flPrepareProgress = 100.f; m_bPrepareClientDLL = false; m_bUpdateSteamResources = true; break; } } if (m_bUpdateSteamResources) { bool bComplete = false; float flProgress = 0.0f; g_pFileSystem->GetWaitForResourcesProgress(m_hWaitForResourcesHandle, &flProgress, &bComplete); if (bComplete) { m_hWaitForResourcesHandle = NULL; m_bUpdateSteamResources = false; m_bDownloadResources = false; if ( m_pDownloadableFileTable ) { bool allowDownloads = true; bool allowSoundDownloads = true; bool allowNonMaps = true; if ( !Q_strcasecmp( cl_downloadfilter.GetString(), ""none"" ) ) { allowDownloads = allowSoundDownloads = allowNonMaps = false; } else if ( !Q_strcasecmp( cl_downloadfilter.GetString(), ""nosounds"" ) ) { allowSoundDownloads = false; } else if ( !Q_strcasecmp( cl_downloadfilter.GetString(), ""mapsonly"" ) ) { allowNonMaps = false; } if ( allowDownloads ) { char extension[4]; for ( int i=0; iGetNumStrings(); ++i ) { const char *fname = m_pDownloadableFileTable->GetString( i ); if ( !allowSoundDownloads ) { Q_ExtractFileExtension( fname, extension, sizeof( extension ) ); if ( !Q_strcasecmp( extension, ""wav"" ) || !Q_strcasecmp( extension, ""mp3"" ) ) { continue; } } if ( !allowNonMaps ) { // The user wants maps only. Q_ExtractFileExtension( fname, extension, sizeof( extension ) ); // If the extension is not bsp, skip it. if ( Q_strcasecmp( extension, ""bsp"" ) ) { continue; } } CL_QueueDownload( fname ); } } if ( CL_GetDownloadQueueSize() ) { // make sure the loading dialog is up EngineVGui()->StartCustomProgress(); EngineVGui()->ActivateGameUI(); m_bDownloadResources = true; } else { m_bDownloadResources = false; FinishSignonState_New(); } } else { Host_Error( ""Invalid download file table."" ); } } else if (flProgress > 0.0f) { if (!m_bShownSteamResourceUpdateProgress) { // make sure the loading dialog is up EngineVGui()->StartCustomProgress(); EngineVGui()->ActivateGameUI(); m_bShownSteamResourceUpdateProgress = true; } // change it to be updating steam resources EngineVGui()->UpdateCustomProgressBar( flProgress, g_pVGuiLocalize->Find(""#Valve_UpdatingSteamResources"") ); } } if ( m_bDownloadResources ) { // Check on any HTTP downloads in progress bool stillDownloading = CL_DownloadUpdate(); if ( !stillDownloading ) { m_bDownloadResources = false; FinishSignonState_New(); } } } //----------------------------------------------------------------------------- // Purpose: At a certain rate, this function will verify any unverified // file CRCs with the server. //----------------------------------------------------------------------------- void CClientState::CheckFileCRCsWithServer() { //! !FIXME! Stubbed this. Several reasons: //! //! 1.) Removed the CRC functionality (because it was broken when we switched to use MD5's for hashes of //! loose files, but the server only has CRC's of some files in the VPK headers.). Currently the only //! supported pure server mode is ""trusted source."" //! 2.) Sending MD5's of VPK's is a bit too restrictive for most use cases. For example, if a client //! has an extra VPK for custom content, the server doesn't know what to do with it. Or if we //! release an optional update, the VPK's might legitimately differ. //! //! Rich has pointed out that we really need pure server client work to be something that the client //! cannot easily bypass. Currently that is the case. But I need to ship the SteamPipe conversion now. //! We can revisit pure server security after that has shipped. // // VPROF_( ""CheckFileCRCsWithServer"", 1, VPROF_BUDGETGROUP_OTHER_NETWORKING, false, BUDGETFLAG_CLIENT ); // const float flBatchInterval = 1.0f / 5.0f; // const int nBatchSize = 5; // // // Don't do this yet.. // if ( !m_bCheckCRCsWithServer ) // return; // // if ( m_nSignonState != SIGNONSTATE_FULL ) // return; // // // Only send a batch every so often. // float flCurTime = Plat_FloatTime(); // if ( (flCurTime - m_flLastCRCBatchTime) < flBatchInterval ) // return; // // m_flLastCRCBatchTime = flCurTime; // // CUnverifiedFileHash rgUnverifiedFiles[nBatchSize]; // int count = g_pFileSystem->GetUnverifiedFileHashes( rgUnverifiedFiles, ARRAYSIZE( rgUnverifiedFiles ) ); // if ( count == 0 ) // return; // // // Send the messages to the server. // for ( int i=0; i < count; i++ ) // { // CLC_FileCRCCheck crcCheck; // V_strncpy( crcCheck.m_szPathID, rgUnverifiedFiles[i].m_PathID, sizeof( crcCheck.m_szPathID ) ); // V_strncpy( crcCheck.m_szFilename, rgUnverifiedFiles[i].m_Filename, sizeof( crcCheck.m_szFilename ) ); // crcCheck.m_nFileFraction = rgUnverifiedFiles[i].m_nFileFraction; // crcCheck.m_MD5 = rgUnverifiedFiles[i].m_FileHash.m_md5contents; // crcCheck.m_CRCIOs = rgUnverifiedFiles[i].m_FileHash.m_crcIOSequence; // crcCheck.m_eFileHashType = rgUnverifiedFiles[i].m_FileHash.m_eFileHashType; // crcCheck.m_cbFileLen = rgUnverifiedFiles[i].m_FileHash.m_cbFileLen; // crcCheck.m_nPackFileNumber = rgUnverifiedFiles[i].m_FileHash.m_nPackFileNumber; // crcCheck.m_PackFileID = rgUnverifiedFiles[i].m_FileHash.m_PackFileID; // // m_NetChannel->SendNetMsg( crcCheck ); // } } //----------------------------------------------------------------------------- // Purpose: sanity-checks the variables in a VMT file to prevent the client from // making player etc. textures that glow or show through walls etc. Anything // other than $baseTexture and $bumpmap is hereby verboten. //----------------------------------------------------------------------------- bool CheckSimpleMaterial( IMaterial *pMaterial ) { if ( !pMaterial ) return false; const char *name = pMaterial->GetShaderName(); if ( Q_strncasecmp( name, ""VertexLitGeneric"", 16 ) && Q_strncasecmp( name, ""UnlitGeneric"", 12 ) && Q_strncasecmp( name, ""Character"", 9 ) ) return false; if ( pMaterial->GetMaterialVarFlag( MATERIAL_VAR_IGNOREZ ) ) return false; if ( pMaterial->GetMaterialVarFlag( MATERIAL_VAR_WIREFRAME ) ) return false; if ( pMaterial->GetMaterialVarFlag( MATERIAL_VAR_SELFILLUM ) ) return false; if ( pMaterial->GetMaterialVarFlag( MATERIAL_VAR_ADDITIVE ) ) return false; if ( pMaterial->GetMaterialVarFlag( MATERIAL_VAR_NOFOG ) ) return false; if ( pMaterial->GetMaterialVarFlag( MATERIAL_VAR_HALFLAMBERT ) ) return false; return true; } //----------------------------------------------------------------------------- // Purpose: find a filename in the string table, ignoring case and slash mismatches. Returns the index, or INVALID_STRING_INDEX if not found. //----------------------------------------------------------------------------- int FindFilenameInStringTable( INetworkStringTable *table, const char *searchFname ) { char searchFilename[MAX_PATH]; char tableFilename[MAX_PATH]; Q_strncpy( searchFilename, searchFname, MAX_PATH ); Q_FixSlashes( searchFilename ); for ( int i=0; iGetNumStrings(); ++i ) { const char *tableFname = table->GetString( i ); Q_strncpy( tableFilename, tableFname, MAX_PATH ); Q_FixSlashes( tableFilename ); if ( !Q_strcasecmp( searchFilename, tableFilename ) ) { return i; } } return INVALID_STRING_INDEX; } //----------------------------------------------------------------------------- // Purpose: find a filename in the string table, ignoring case and slash mismatches. // Returns the consistency type, with CONSISTENCY_NONE being a Not Found result. //----------------------------------------------------------------------------- ConsistencyType GetFileConsistencyType( INetworkStringTable *table, const char *searchFname ) { int index = FindFilenameInStringTable( table, searchFname ); if ( index == INVALID_STRING_INDEX ) { return CONSISTENCY_NONE; } int length = 0; unsigned char *userData = NULL; userData = (unsigned char *)table->GetStringUserData( index, &length ); if ( userData && length == sizeof( ExactFileUserData ) ) { switch ( userData[0] ) { case CONSISTENCY_EXACT: case CONSISTENCY_SIMPLE_MATERIAL: return (ConsistencyType)userData[0]; default: return CONSISTENCY_NONE; } } else { return CONSISTENCY_NONE; } } //----------------------------------------------------------------------------- // Purpose: Does a CRC check compared to the CRC stored in the user data. //----------------------------------------------------------------------------- bool CheckCRCs( unsigned char *userData, int length, const char *filename ) { if ( userData && length == sizeof( ExactFileUserData ) ) { if ( userData[0] != CONSISTENCY_EXACT && userData[0] != CONSISTENCY_SIMPLE_MATERIAL ) { return false; } ExactFileUserData *exactFileData = (ExactFileUserData *)userData; CRC32_t crc; if ( !CRC_File( &crc, filename ) ) { return false; } return ( crc == exactFileData->crc ); } return false; } //----------------------------------------------------------------------------- // Purpose: completes the SIGNONSTATE_NEW state //----------------------------------------------------------------------------- void CClientState::FinishSignonState_New() { // make sure we're still in the right signon state if (m_nSignonState != SIGNONSTATE_NEW) return; if ( !m_bMarkedCRCsUnverified ) { // Mark all file CRCs unverified once per server. We may have verified CRCs for certain files on // the previous server, but we need to reverify them on the new server. m_bMarkedCRCsUnverified = true; g_pFileSystem->MarkAllCRCsUnverified(); } // Verify the map and player .mdl crc's now that we've finished downloading missing resources (maps etc) if ( !CL_CheckCRCs( m_szLevelFileName ) ) { Host_Error( ""Unable to verify map %s"", ( m_szLevelFileName && m_szLevelFileName[0] ) ? m_szLevelFileName : ""unknown"" ); return; } // We're going to force-touch a lot of textures and resources below, we don't want the streaming system to try and // pull these in as if they were being used for normal rendering. materials->SuspendTextureStreaming(); // Only do this if our server is shut down and we're acting as a client. Otherwise the server handles this when it // starts the load. if ( sv.m_State < ss_loading ) { // Reset the last used count on all models before beginning the new load -- The nServerCount value on models should // always resolve as different from values from previous servers. modelloader->ResetModelServerCounts(); } if ( cl_always_flush_models.GetBool() ) { modelloader->PurgeUnusedModels(); } // Our load process is causing some very bad allocation & performance impact in drivers, due to the enormous amount // of resources being used (and, in the case of EnableHDR(), released and re-uploaded) in a single frame. Ensuring // that we push a few frames through before and after the main model loading spree results in dramatically better // results. Without these calls, for instance, OS X on high texture quality cannot survive map load. // // This is pretty janky, but doesn't really have any cost (and even makes our one-frozen-frame load screen slightly // less likely to trigger OS ""not responding"" warnings) extern void V_RenderVGuiOnly(); V_RenderVGuiOnly(); // Before we do anything with the whitelist, make sure we have the proper map pack mounted // this will load the .bsp by setting the world model the string list at the hardcoded index 1. cl.SetModel( 1 ); V_RenderVGuiOnly(); // Check for a new whitelist. It's good to do it early in the connection process here because if we wait until later, // the client may have loaded some files w/o the proper whitelist restrictions and we'd have to reload them. m_bCheckCRCsWithServer = false; // Don't check CRCs yet.. wait until we got a whitelist and cleaned out our files based on it to send CRCs. // We check the new whitelist now so loads that happen between here and FullyConnected are checked against it, but // don't trigger a reload of dirty files until after we flush unused resources from the last map in // CL_FullyConnected. This fixes reloading materials that are unused, and trying to reload materials that are no // longer pure, but would be unloaded in fully connected anyway. CL_CheckForPureServerWhitelist( m_pPendingPureFileReloads ); CL_InstallAndInvokeClientStringTableCallbacks(); materials->CacheUsedMaterials(); // force a consistency check ConsistencyCheck( true ); CL_RegisterResources(); // Done with all resources, issue prespawn command. // Include server count in case server disconnects and changes level during d/l // Tell rendering system we have a new set of models. R_LevelInit(); // Balanced against SuspendTextureStreaming above materials->ResumeTextureStreaming(); EngineVGui()->UpdateProgressBar(PROGRESS_SENDCLIENTINFO); if ( !m_NetChannel ) return; SendClientInfo(); CL_SetSteamCrashComment(); // tell server that we entered now that state m_NetChannel->SendNetMsg( NET_SignonState( m_nSignonState, m_nServerCount ) ); } //----------------------------------------------------------------------------- // Purpose: run a file consistency check if enforced by server //----------------------------------------------------------------------------- void CClientState::ConsistencyCheck(bool bChanged ) { // get the default config for the current card as a starting point. // server must have sent us this table if ( !m_pDownloadableFileTable ) return; // no checks during single player or demo playback if( (m_nMaxClients == 1) || demoplayer->IsPlayingBack() ) return; // only if we are connected if ( !IsConnected() ) return; // check if material configuration changed static MaterialSystem_Config_t s_LastConfig; MaterialSystem_Config_t newConfig = materials->GetCurrentConfigForVideoCard(); if ( Q_memcmp( &s_LastConfig, &newConfig, sizeof(MaterialSystem_Config_t) ) ) { // remember last config we tested s_LastConfig = newConfig; bChanged = true; } if ( !bChanged ) return; #if 0 // This check was removed as GetSteamUniverse() is very expensive and was getting // called every frame on Linux. I don't believe it should have been merged over from // l4d2 in the first place either... // If we're not signed into the steam universe, then bail. // This should only happen when we're developing internally without Steam I hope? if ( k_EUniverseInvalid == GetSteamUniverse() ) { return; } #endif const char *errorMsg = NULL; const char *errorFilename = NULL; // check CRCs and model sizes Color red( 200, 20, 20, 255 ); Color blue( 100, 100, 200, 255 ); for ( int i=0; iGetNumStrings(); ++i ) { int length = 0; unsigned char *userData = NULL; userData = (unsigned char *)m_pDownloadableFileTable->GetStringUserData( i, &length ); const char *filename = m_pDownloadableFileTable->GetString( i ); // // CRC Check // if ( userData && userData[0] == CONSISTENCY_EXACT && length == sizeof( ExactFileUserData ) ) { // Hm, this isn't supported anymore. (Use sv_pure instead.) Under ordinary // circumstances, servers shouldn't be asking for it. Assert( false ); continue; } // // Bounds Check // // This is simply asking for the model's mins and maxs. Also, it checks each material referenced // by the model, to make sure it doesn't ignore Z, isn't overbright, etc. // // TODO: Animations and facial expressions can still pull verts out past this. // else if ( userData && userData[0] == CONSISTENCY_BOUNDS && length == sizeof( ModelBoundsUserData ) ) { ModelBoundsUserData *boundsData = (ModelBoundsUserData *)userData; model_t *pModel = modelloader->GetModelForName( filename, IModelLoader::FMODELLOADER_CLIENT ); if ( !pModel ) { errorMsg = ""Cannot find required model""; errorFilename = filename; } else { if ( pModel->mins.x < boundsData->mins.x || pModel->mins.y < boundsData->mins.y || pModel->mins.z < boundsData->mins.z ) { ConColorMsg( red, ""Model %s exceeds mins (%.1f %.1f %.1f vs. %.1f %.1f %.1f)\\n"", filename, pModel->mins.x, pModel->mins.y, pModel->mins.z, boundsData->mins.x, boundsData->mins.y, boundsData->mins.z); errorMsg = ""Server is enforcing model bounds""; errorFilename = filename; } if ( pModel->maxs.x > boundsData->maxs.x || pModel->maxs.y > boundsData->maxs.y || pModel->maxs.z > boundsData->maxs.z ) { ConColorMsg( red, ""Model %s exceeds maxs (%.1f %.1f %.1f vs. %.1f %.1f %.1f)\\n"", filename, pModel->maxs.x, pModel->maxs.y, pModel->maxs.z, boundsData->maxs.x, boundsData->maxs.y, boundsData->maxs.z); errorMsg = ""Server is enforcing model bounds""; errorFilename = filename; } // Check each texture IMaterial *pMaterials[ 128 ]; int materialCount = Mod_GetModelMaterials( pModel, ARRAYSIZE( pMaterials ), pMaterials ); for ( int j = 0; jGetName() ); errorMsg = ""Server is enforcing simple material""; errorFilename = pMaterial->GetName(); break; } } } } } if ( errorFilename && *errorFilename ) { COM_ExplainDisconnection( true, ""%s:\\n%s\\n"", errorMsg, errorFilename ); Host_Error( ""%s: %s\\n"", errorMsg, errorFilename ); } } void CClientState::UpdateAreaBits_BackwardsCompatible() { if ( m_pAreaBits ) { tmZone( TELEMETRY_LEVEL0, TMZF_NONE, ""%s"", __FUNCTION__ ); memcpy( m_chAreaBits, m_pAreaBits, sizeof( m_chAreaBits ) ); // The whole point of adding this array was that the client could react to closed portals. // If they're using the old interface to set area portal bits, then we use the old // behavior of assuming all portals are open on the clent. memset( m_chAreaPortalBits, 0xFF, sizeof( m_chAreaPortalBits ) ); m_bAreaBitsValid = true; } } unsigned char** CClientState::GetAreaBits_BackwardCompatibility() { return &m_pAreaBits; } void CClientState::RunFrame() { CBaseClientState::RunFrame(); tmZone( TELEMETRY_LEVEL0, TMZF_NONE, ""%s"", __FUNCTION__ ); // Since cl_rate is a virtualized cvar, make sure to pickup changes in it. if ( m_NetChannel ) m_NetChannel->SetDataRate( cl_rate->GetFloat() ); ConsistencyCheck( false ); // Check if paged pool is low ( < 8% free ) static bool s_bLowPagedPoolMemoryWarning = false; PAGED_POOL_INFO_t ppi; if ( ( SYSCALL_SUCCESS == Plat_GetPagedPoolInfo( &ppi ) ) && ( ( ppi.numPagesFree * 12 ) < ( ppi.numPagesUsed + ppi.numPagesFree ) ) ) { con_nprint_t np; np.time_to_live = 1.0; np.index = 1; np.fixed_width_font = false; np.color[ 0 ] = 1.0; np.color[ 1 ] = 0.2; np.color[ 2 ] = 0.0; Con_NXPrintf( &np, ""WARNING: OS Paged Pool Memory Low"" ); // Also print a warning to console static float s_flLastWarningTime = 0.0f; if ( !s_bLowPagedPoolMemoryWarning || ( Plat_FloatTime() - s_flLastWarningTime > 3.0f ) ) // print a warning no faster than once every 3 sec { s_bLowPagedPoolMemoryWarning = true; s_flLastWarningTime = Plat_FloatTime(); Warning( ""OS Paged Pool Memory Low!\\n"" ); Warning( "" Currently using %lu pages (%lu Kb) of total %lu pages (%lu Kb total)\\n"", ppi.numPagesUsed, ppi.numPagesUsed * Plat_GetMemPageSize(), ( ppi.numPagesFree + ppi.numPagesUsed ), ( ppi.numPagesFree + ppi.numPagesUsed ) * Plat_GetMemPageSize() ); Warning( "" Please see http://www.steampowered.com for more information.\\n"" ); } } else if ( s_bLowPagedPoolMemoryWarning ) { s_bLowPagedPoolMemoryWarning = false; Msg( ""Info: OS Paged Pool Memory restored - currently %lu pages free (%lu Kb) of total %lu pages (%lu Kb total).\\n"", ppi.numPagesFree, ppi.numPagesFree * Plat_GetMemPageSize(), ( ppi.numPagesFree + ppi.numPagesUsed ), ( ppi.numPagesFree + ppi.numPagesUsed ) * Plat_GetMemPageSize() ); } } ",16160,True,2738.7070725078665,median "/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * ""License""); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * ""AS IS"" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ /*! * Copyright (c) 2018 by Contributors * \\file test_lib.cpp * \\brief Test library for the VTA design simulation and driver tests. */ #include ""test_lib.h"" #ifdef NO_SIM #ifdef VTA_TARGET_PYNQ uint64_t vta( uint32_t insn_count, VTAGenericInsn *insns, VTAUop *uops, inp_T *inputs, wgt_T *weights, acc_T *biases, inp_T *outputs) { // Performance counter variables uint64_t t_fpga; struct timespec start, stop; // Derive bitstream file char bitstream[128]; char str_batch_size[4]; char str_block_out_size[4]; char str_block_in_size[4]; char str_block_bit_width[4]; snprintf(str_batch_size, sizeof(str_batch_size), ""%d"", VTA_BATCH); snprintf(str_block_out_size, sizeof(str_block_out_size), ""%d"", VTA_BLOCK_OUT); snprintf(str_block_in_size, sizeof(str_block_in_size), ""%d"", VTA_BLOCK_IN); snprintf(str_block_bit_width, sizeof(str_block_bit_width), ""%d"", VTA_WGT_WIDTH); snprintf(bitstream, sizeof(bitstream), ""%s"", ""vta.bit""); // Get VTA handles void* vta_fetch_handle = VTAMapRegister(VTA_FETCH_ADDR, VTA_RANGE); void* vta_load_handle = VTAMapRegister(VTA_LOAD_ADDR, VTA_RANGE); void* vta_compute_handle = VTAMapRegister(VTA_COMPUTE_ADDR, VTA_RANGE); void* vta_store_handle = VTAMapRegister(VTA_STORE_ADDR, VTA_RANGE); // Physical address pointers uint32_t insn_phy = insns ? VTAMemGetPhyAddr(insns) : 0; uint32_t uop_phy = uops ? VTAMemGetPhyAddr(uops) : 0; uint32_t input_phy = inputs ? VTAMemGetPhyAddr(inputs) : 0; uint32_t weight_phy = weights ? VTAMemGetPhyAddr(weights) : 0; uint32_t bias_phy = biases ? VTAMemGetPhyAddr(biases) : 0; uint32_t output_phy = outputs ? VTAMemGetPhyAddr(outputs) : 0; #if VTA_DEBUG == 1 printf(""INFO - Starting FPGA!\\n""); #endif clock_gettime(CLOCK_REALTIME, &start); // FETCH @ 0x10 : Data signal of insn_count_V VTAWriteMappedReg(vta_fetch_handle, 0x10, insn_count); // FETCH @ 0x18 : Data signal of insns_V if (insns) VTAWriteMappedReg(vta_fetch_handle, 0x18, insn_phy); // LOAD @ 0x10 : Data signal of inputs_V if (inputs) VTAWriteMappedReg(vta_load_handle, 0x10, input_phy); // LOAD @ 0x18 : Data signal of weight_V if (weights) VTAWriteMappedReg(vta_load_handle, 0x18, weight_phy); // COMPUTE @ 0x20 : Data signal of uops_V if (uops) VTAWriteMappedReg(vta_compute_handle, 0x20, uop_phy); // COMPUTE @ 0x28 : Data signal of biases_V if (biases) VTAWriteMappedReg(vta_compute_handle, 0x28, bias_phy); // STORE @ 0x10 : Data signal of outputs_V if (outputs) VTAWriteMappedReg(vta_store_handle, 0x10, output_phy); // VTA start VTAWriteMappedReg(vta_fetch_handle, 0x0, 0x1); VTAWriteMappedReg(vta_load_handle, 0x0, 0x81); VTAWriteMappedReg(vta_compute_handle, 0x0, 0x81); VTAWriteMappedReg(vta_store_handle, 0x0, 0x81); int flag = 0, t = 0; for (t = 0; t < 10000000; ++t) { flag = VTAReadMappedReg(vta_compute_handle, 0x18); if (flag & VTA_DONE) break; } if (t == 10000000) { printf(""\\tWARNING: VTA TIMEOUT!!!!\\n""); #if VTA_DEBUG == 1 } else { printf(""INFO - FPGA Finished!\\n""); #endif } clock_gettime(CLOCK_REALTIME, &stop); t_fpga = 1000000000ULL * (stop.tv_sec - start.tv_sec) + (stop.tv_nsec - start.tv_nsec); // Unmap VTA register VTAUnmapRegister(vta_fetch_handle, VTA_RANGE); VTAUnmapRegister(vta_load_handle, VTA_RANGE); VTAUnmapRegister(vta_compute_handle, VTA_RANGE); VTAUnmapRegister(vta_store_handle, VTA_RANGE); return t_fpga; } #endif // VTA_TARGET_PYNQ #endif // NO_SIM uint32_t globalSeed; const char* getOpcodeString(int opcode, bool use_imm) { // Returns string name if (opcode == VTA_ALU_OPCODE_MIN) { if (use_imm) { return ""min imm""; } else { return ""min""; } } else if (opcode == VTA_ALU_OPCODE_MAX) { if (use_imm) { return ""max imm""; } else { return ""max""; } } else if (opcode == VTA_ALU_OPCODE_ADD) { if (use_imm) { return ""add imm""; } else { return ""add""; } } else if (opcode == VTA_ALU_OPCODE_SHR) { return ""shr""; } return ""unknown op""; } template void packBuffer(T *dst, T **src, int y_size, int x_size, int y_block, int x_block) { int buffer_idx = 0; for (int i = 0; i < y_size / y_block; i++) { for (int j = 0; j < x_size / x_block; j++) { for (int k = 0; k < y_block; k++) { if (T_WIDTH < 8) { for (int l = 0; l < x_block; l += 8 / T_WIDTH) { dst[buffer_idx] = 0; for (int m = 0; m < 8 / T_WIDTH; m++) { dst[buffer_idx] |= (src[i * y_block + k][j * x_block + l + m] & ((1ULL << T_WIDTH) - 1)) << (m * T_WIDTH); } buffer_idx++; } } else { for (int l = 0; l < x_block; l++) { dst[buffer_idx++] = src[i * y_block + k][j * x_block + l]; } } } } } } template void unpackBuffer(T **dst, T *src, int y_size, int x_size, int y_block, int x_block) { int buffer_idx = 0; for (int i = 0; i < y_size / y_block; i++) { for (int j = 0; j < x_size / x_block; j++) { for (int k = 0; k < y_block; k++) { if (T_WIDTH < 8) { for (int l = 0; l < x_block; l += 8 / T_WIDTH) { for (int m = 0; m < 8 / T_WIDTH; m++) { dst[i * y_block + k][j * x_block + l + m] = (src[buffer_idx] >> (m * T_WIDTH)) & ((1 << T_WIDTH) - 1); } buffer_idx++; } } else { for (int l = 0; l < x_block; l++) { dst[i * y_block + k][j * x_block + l] = src[buffer_idx++]; } } } } } } template T ** allocInit2dArray(int rows, int cols) { // Allocate T **array = static_cast(malloc(sizeof(T *) * rows)); for (int i = 0; i < rows; i++) { array[i] = static_cast(malloc(sizeof(T) * cols)); } // Init for (int i = 0; i < rows; i++) { for (int j = 0; j < cols; j++) { array[i][j] = static_cast(rand_r(&globalSeed) % (1LL << (T_WIDTH - 1)) - (1LL << (T_WIDTH - 2))); } } return array; } template T ** alloc2dArray(int rows, int cols) { T **array = static_cast(malloc(sizeof(T *) * rows)); for (int i = 0; i < rows; i++) { array[i] = static_cast(malloc(sizeof(T) * cols)); } return array; } template void free2dArray(T **array, int rows, int cols) { for (int i = 0; i < rows; i++) { free(array[i]); } free(array); } template T *** alloc3dArray(int rows, int cols, int depth) { T ***array = static_cast(malloc(sizeof(T **) * rows)); for (int i = 0; i < rows; i++) { array[i] = static_cast(malloc(sizeof(T *) * cols)); for (int j = 0; j < cols; j++) { array[i][j] = static_cast(malloc(sizeof(T) * depth)); } } return array; } template void free3dArray(T *** array, int rows, int cols, int depth) { for (int i = 0; i < rows; i++) { for (int j = 0; j < cols; j++) { free(array[i][j]); } free(array[i]); } free(array); } void * allocBuffer(size_t num_bytes) { #ifdef NO_SIM return VTAMemAlloc(num_bytes, VTA_CACHED); #else return malloc(num_bytes); #endif } void freeBuffer(void * buffer) { #ifdef NO_SIM return VTAMemFree(buffer); #else return free(buffer); #endif } VTAGenericInsn get2DLoadStoreInsn(int opcode, int type, int sram_offset, int dram_offset, int y_size, int x_size, int x_stride, int y_pad, int x_pad, int pop_prev_dep, int pop_next_dep, int push_prev_dep, int push_next_dep) { // Converter union VTAInsn converter; // Memory instruction initialization VTAMemInsn insn = {}; insn.opcode = opcode; insn.pop_prev_dep = pop_prev_dep; insn.pop_next_dep = pop_next_dep; insn.push_prev_dep = push_prev_dep; insn.push_next_dep = push_next_dep; insn.memory_type = type; insn.sram_base = sram_offset; insn.dram_base = dram_offset; insn.y_size = y_size; insn.x_size = x_size; insn.x_stride = x_stride; insn.y_pad_0 = y_pad; insn.y_pad_1 = y_pad; insn.x_pad_0 = x_pad; insn.x_pad_1 = x_pad; converter.mem = insn; return converter.generic; } VTAGenericInsn get1DLoadStoreInsn(int opcode, int type, int sram_offset, int dram_offset, int size, int pop_prev_dep, int pop_next_dep, int push_prev_dep, int push_next_dep) { // Converter union VTAInsn converter; // Memory instruction initialization VTAMemInsn insn = {}; insn.opcode = opcode; insn.pop_prev_dep = pop_prev_dep; insn.pop_next_dep = pop_next_dep; insn.push_prev_dep = push_prev_dep; insn.push_next_dep = push_next_dep; insn.memory_type = type; insn.sram_base = sram_offset; insn.dram_base = dram_offset; insn.y_size = 1; insn.x_size = size; insn.x_stride = size; insn.y_pad_0 = 0; insn.y_pad_1 = 0; insn.x_pad_0 = 0; insn.x_pad_1 = 0; converter.mem = insn; return converter.generic; } VTAGenericInsn getGEMMInsn(int uop_offset, int batch, int in_feat, int out_feat, bool uop_compression, int pop_prev_dep, int pop_next_dep, int push_prev_dep, int push_next_dep) { // Converter union VTAInsn converter; // GEMM instruction initialization VTAGemInsn insn; insn.opcode = VTA_OPCODE_GEMM; insn.pop_prev_dep = pop_prev_dep; insn.pop_next_dep = pop_next_dep; insn.push_prev_dep = push_prev_dep; insn.push_next_dep = push_next_dep; insn.reset_reg = false; if (!uop_compression) { insn.uop_bgn = uop_offset; insn.uop_end = uop_offset + batch * in_feat * out_feat; insn.iter_out = 1; insn.iter_in = 1; insn.dst_factor_out = 0; insn.src_factor_out = 0; insn.wgt_factor_out = 0; insn.dst_factor_in = 0; insn.src_factor_in = 0; insn.wgt_factor_in = 0; } else { insn.uop_bgn = uop_offset; insn.uop_end = uop_offset + batch; insn.iter_out = in_feat; insn.iter_in = out_feat; insn.dst_factor_out = 0; insn.src_factor_out = 1; insn.wgt_factor_out = 1; insn.dst_factor_in = 1; insn.src_factor_in = 0; insn.wgt_factor_in = in_feat; } converter.gemm = insn; return converter.generic; } VTAGenericInsn getALUInsn(int opcode, int vector_size, bool use_imm, int imm, bool uop_compression, int pop_prev_dep, int pop_next_dep, int push_prev_dep, int push_next_dep) { // Converter union VTAInsn converter; // Memory instruction initialization VTAAluInsn insn = {}; insn.opcode = VTA_OPCODE_ALU; insn.pop_prev_dep = pop_prev_dep; insn.pop_next_dep = pop_next_dep; insn.push_prev_dep = push_prev_dep; insn.push_next_dep = push_next_dep; insn.reset_reg = false; if (!uop_compression) { insn.uop_bgn = 0; insn.uop_end = vector_size; insn.iter_out = 1; insn.iter_in = 1; insn.dst_factor_out = 0; insn.src_factor_out = 0; insn.dst_factor_in = 0; insn.src_factor_in = 0; insn.alu_opcode = opcode; insn.use_imm = use_imm; insn.imm = imm; } else { insn.uop_bgn = 0; insn.uop_end = 1; insn.iter_out = 1; insn.iter_in = vector_size; insn.dst_factor_out = 0; insn.src_factor_out = 0; insn.dst_factor_in = 1; insn.src_factor_in = 1; insn.alu_opcode = opcode; insn.use_imm = use_imm; insn.imm = imm; } converter.alu = insn; return converter.generic; } VTAGenericInsn getFinishInsn(bool pop_prev, bool pop_next) { // Converter union VTAInsn converter; // GEMM instruction initialization VTAGemInsn insn; insn.opcode = VTA_OPCODE_FINISH; insn.pop_prev_dep = pop_prev; insn.pop_next_dep = pop_next; insn.push_prev_dep = 0; insn.push_next_dep = 0; insn.reset_reg = false; insn.uop_bgn = 0; insn.uop_end = 0; insn.iter_out = 0; insn.iter_in = 0; insn.dst_factor_out = 0; insn.src_factor_out = 0; insn.wgt_factor_out = 0; insn.dst_factor_in = 0; insn.src_factor_in = 0; insn.wgt_factor_in = 0; converter.gemm = insn; return converter.generic; } VTAUop * getCopyUops(int y_size, int x_size, int uop_compression) { // Derive the total uop size int uop_size = (uop_compression) ? 1 : y_size * x_size; // Allocate buffer #ifdef NO_SIM VTAUop *uop_buf = static_cast(VTAMemAlloc(sizeof(VTAUop) * uop_size, VTA_CACHED)); #else VTAUop *uop_buf = static_cast(malloc(sizeof(VTAUop) * uop_size)); #endif if (!uop_compression) { int uop_idx = 0; for (int i = 0; i < y_size; i++) { for (int j = 0; j < x_size; j++) { uop_buf[uop_idx].dst_idx = i * x_size + j; uop_buf[uop_idx].src_idx = 0; uop_buf[uop_idx].wgt_idx = 0; uop_idx++; } } } else { uop_buf[0].dst_idx = 1; uop_buf[0].src_idx = 0; uop_buf[0].wgt_idx = 0; } return uop_buf; } VTAUop * getGEMMUops(int batch, int in_feat, int out_feat, bool uop_compression, bool multi_threaded) { // Derive the total uop size int uop_size = (uop_compression) ? batch : batch * in_feat * out_feat; if (multi_threaded) uop_size *= 2; // Allocate buffer #ifdef NO_SIM VTAUop *uop_buf = static_cast(VTAMemAlloc(sizeof(VTAUop) * uop_size, VTA_CACHED)); #else VTAUop *uop_buf = static_cast(malloc(sizeof(VTAUop) * uop_size)); #endif if (!uop_compression) { int uop_idx = 0; for (int i = 0; i < batch; i++) { for (int j = 0; j < in_feat; j++) { for (int k = 0; k < out_feat; k++) { uop_buf[uop_idx].dst_idx = i * out_feat + k; uop_buf[uop_idx].src_idx = i * in_feat + j; uop_buf[uop_idx].wgt_idx = k * in_feat + j; uop_idx++; } } } } else { for (int i = 0; i < batch; i++) { uop_buf[i].dst_idx = i * out_feat; uop_buf[i].src_idx = i * in_feat; uop_buf[i].wgt_idx = 0; } } if (multi_threaded) { if (!uop_compression) { int uop_idx = uop_size / 2; for (int i = 0; i < batch; i++) { for (int j = 0; j < in_feat; j++) { for (int k = 0; k < out_feat; k++) { uop_buf[uop_idx].dst_idx = i * out_feat + k; uop_buf[uop_idx].src_idx = batch * in_feat + i * in_feat + j; uop_buf[uop_idx].wgt_idx = out_feat * in_feat + k * in_feat + j; uop_idx++; } } } } else { for (int i = 0; i < batch; i++) { uop_buf[batch+i].dst_idx = i * out_feat; uop_buf[batch+i].src_idx = batch * in_feat + i * in_feat; uop_buf[batch+i].wgt_idx = out_feat * in_feat; } } } return uop_buf; } VTAUop * getMapALUUops(int vector_size, bool uop_compression) { // Derive the total uop size int uop_size = (uop_compression) ? 1 : vector_size; // Allocate buffer #ifdef NO_SIM VTAUop *uop_buf = static_cast(VTAMemAlloc(sizeof(VTAUop) * uop_size, VTA_CACHED)); #else VTAUop *uop_buf = static_cast(malloc(sizeof(VTAUop) * uop_size)); #endif if (!uop_compression) { for (int i = 0; i < vector_size; i++) { uop_buf[i].dst_idx = i; uop_buf[i].src_idx = vector_size + i; } } else { uop_buf[0].dst_idx = 0; uop_buf[0].src_idx = vector_size; } return uop_buf; } void printParameters() { // Some debugging code printf(""Size of VTAInsn: %d\\n"", sizeof(VTAGenericInsn)); printf(""Size of VTAUop: %d\\n"", sizeof(VTAUop)); printf(""VTA_UOP_BUFF_DEPTH: %d\\n"", VTA_UOP_BUFF_DEPTH); printf(""VTA_LOG_UOP_BUFF_DEPTH: %d\\n"", VTA_LOG_UOP_BUFF_DEPTH); printf(""VTA_WGT_BUFF_DEPTH: %d\\n"", VTA_WGT_BUFF_DEPTH); printf(""VTA_LOG_WGT_BUFF_DEPTH: %d\\n"", VTA_LOG_WGT_BUFF_DEPTH); printf(""VTA_INP_BUFF_DEPTH: %d\\n"", VTA_INP_BUFF_DEPTH); printf(""VTA_LOG_INP_BUFF_DEPTH: %d\\n"", VTA_LOG_INP_BUFF_DEPTH); printf(""VTA_ACC_BUFF_DEPTH: %d\\n"", VTA_ACC_BUFF_DEPTH); printf(""VTA_LOG_ACC_BUFF_DEPTH: %d\\n"", VTA_LOG_ACC_BUFF_DEPTH); printf(""VTA_WGT_WORDS: %d\\n"", VTA_WGT_BUFF_DEPTH*VTA_BLOCK_IN*VTA_BLOCK_OUT); printf(""VTA_INP_WORDS: %d\\n"", VTA_INP_BUFF_DEPTH*VTA_BLOCK_IN); printf(""VTA_ACC_WORDS: %d\\n"", VTA_ACC_BUFF_DEPTH*VTA_BLOCK_OUT); printf(""VTA_INS_ELEM_BYTES: %d\\n"", VTA_INS_ELEM_BYTES); printf(""VTA_UOP_ELEM_BYTES: %d\\n"", VTA_UOP_ELEM_BYTES); printf(""VTA_INP_ELEM_BYTES: %d\\n"", VTA_INP_ELEM_BYTES); printf(""VTA_WGT_ELEM_BYTES: %d\\n"", VTA_WGT_ELEM_BYTES); printf(""VTA_ACC_ELEM_BYTES: %d\\n"", VTA_ACC_ELEM_BYTES); printf(""VTA_BLOCK_IN: %d\\n"", VTA_BLOCK_IN); printf(""VTA_BLOCK_OUT: %d\\n"", VTA_BLOCK_OUT); printf(""VTA_INSN_MEM_0 [%d-%d]\\n"", VTA_INSN_MEM_0_0, VTA_INSN_MEM_0_1); printf(""VTA_INSN_MEM_1 [%d]\\n"", VTA_INSN_MEM_1); printf(""VTA_INSN_MEM_2 [%d]\\n"", VTA_INSN_MEM_2); printf(""VTA_INSN_MEM_3 [%d]\\n"", VTA_INSN_MEM_3); printf(""VTA_INSN_MEM_4 [%d]\\n"", VTA_INSN_MEM_4); printf(""VTA_INSN_MEM_5 [%d-%d]\\n"", VTA_INSN_MEM_5_0, VTA_INSN_MEM_5_1); printf(""VTA_INSN_MEM_6 [%d-%d]\\n"", VTA_INSN_MEM_6_0, VTA_INSN_MEM_6_1); printf(""VTA_INSN_MEM_7 [%d-%d]\\n"", VTA_INSN_MEM_7_0, VTA_INSN_MEM_7_1); printf(""VTA_INSN_MEM_8 [%d-%d]\\n"", VTA_INSN_MEM_8_0, VTA_INSN_MEM_8_1); printf(""VTA_INSN_MEM_9 [%d-%d]\\n"", VTA_INSN_MEM_9_0, VTA_INSN_MEM_9_1); printf(""VTA_INSN_MEM_A [%d-%d]\\n"", VTA_INSN_MEM_A_0, VTA_INSN_MEM_A_1); printf(""VTA_INSN_MEM_B [%d-%d]\\n"", VTA_INSN_MEM_B_0, VTA_INSN_MEM_B_1); printf(""VTA_INSN_MEM_C [%d-%d]\\n"", VTA_INSN_MEM_C_0, VTA_INSN_MEM_C_1); printf(""VTA_INSN_MEM_D [%d-%d]\\n"", VTA_INSN_MEM_D_0, VTA_INSN_MEM_D_1); printf(""VTA_INSN_MEM_E [%d-%d]\\n"", VTA_INSN_MEM_E_0, VTA_INSN_MEM_E_1); printf(""VTA_INSN_GEM_0 [%d-%d]\\n"", VTA_INSN_GEM_0_0, VTA_INSN_GEM_0_1); printf(""VTA_INSN_GEM_1 [%d]\\n"", VTA_INSN_GEM_1); printf(""VTA_INSN_GEM_2 [%d]\\n"", VTA_INSN_GEM_2); printf(""VTA_INSN_GEM_3 [%d]\\n"", VTA_INSN_GEM_3); printf(""VTA_INSN_GEM_4 [%d]\\n"", VTA_INSN_GEM_4); printf(""VTA_INSN_GEM_5 [%d]\\n"", VTA_INSN_GEM_5); printf(""VTA_INSN_GEM_6 [%d-%d]\\n"", VTA_INSN_GEM_6_0, VTA_INSN_GEM_6_1); printf(""VTA_INSN_GEM_7 [%d-%d]\\n"", VTA_INSN_GEM_7_0, VTA_INSN_GEM_7_1); printf(""VTA_INSN_GEM_8 [%d-%d]\\n"", VTA_INSN_GEM_8_0, VTA_INSN_GEM_8_1); printf(""VTA_INSN_GEM_9 [%d-%d]\\n"", VTA_INSN_GEM_9_0, VTA_INSN_GEM_9_1); printf(""VTA_INSN_GEM_A [%d-%d]\\n"", VTA_INSN_GEM_A_0, VTA_INSN_GEM_A_1); printf(""VTA_INSN_GEM_B [%d-%d]\\n"", VTA_INSN_GEM_B_0, VTA_INSN_GEM_B_1); printf(""VTA_INSN_GEM_C [%d-%d]\\n"", VTA_INSN_GEM_C_0, VTA_INSN_GEM_C_1); printf(""VTA_INSN_GEM_D [%d-%d]\\n"", VTA_INSN_GEM_D_0, VTA_INSN_GEM_D_1); printf(""VTA_INSN_GEM_E [%d-%d]\\n"", VTA_INSN_GEM_E_0, VTA_INSN_GEM_E_1); printf(""VTA_INSN_GEM_F [%d-%d]\\n"", VTA_INSN_GEM_F_0, VTA_INSN_GEM_F_1); printf(""VTA_INSN_ALU_E [%d-%d]\\n"", VTA_INSN_ALU_E_0, VTA_INSN_ALU_E_1); printf(""VTA_INSN_ALU_F [%d]\\n"", VTA_INSN_ALU_F); printf(""VTA_INSN_ALU_G [%d-%d]\\n"", VTA_INSN_ALU_G_0, VTA_INSN_ALU_G_1); printf(""VTA_UOP_GEM_0 [%d-%d]\\n"", VTA_UOP_GEM_0_0, VTA_UOP_GEM_0_1); printf(""VTA_UOP_GEM_1 [%d-%d]\\n"", VTA_UOP_GEM_1_0, VTA_UOP_GEM_1_1); printf(""VTA_UOP_GEM_2 [%d-%d]\\n"", VTA_UOP_GEM_2_0, VTA_UOP_GEM_2_1); printf(""VTA_UOP_ALU_0 [%d-%d]\\n"", VTA_UOP_ALU_0_0, VTA_UOP_ALU_0_1); printf(""VTA_UOP_ALU_1 [%d-%d]\\n"", VTA_UOP_ALU_1_0, VTA_UOP_ALU_1_1); } void printInstruction(int num_insn, VTAGenericInsn *insns) { // Keep tabs on dependence queues int l2g_queue = 0; int g2l_queue = 0; int s2g_queue = 0; int g2s_queue = 0; // Converter union VTAInsn c; // Iterate over all instructions printf(""DEBUG - There are %u instructions\\n"", num_insn); for (int i = 0; i < num_insn; i++) { // Fetch instruction and decode opcode c.generic = insns[i]; printf(""DEBUG - INSTRUCTION %u: "", i); if (c.mem.opcode == VTA_OPCODE_LOAD || c.mem.opcode == VTA_OPCODE_STORE) { // Print instruction field information if (c.mem.opcode == VTA_OPCODE_LOAD) { printf(""LOAD ""); if (c.mem.memory_type == VTA_MEM_ID_UOP) printf(""UOP\\n""); if (c.mem.memory_type == VTA_MEM_ID_WGT) printf(""WGT\\n""); if (c.mem.memory_type == VTA_MEM_ID_INP) printf(""INP\\n""); if (c.mem.memory_type == VTA_MEM_ID_ACC) printf(""ACC\\n""); } if (c.mem.opcode == VTA_OPCODE_STORE) { printf(""STORE ACC\\n""); } printf(""\\tdep - pop prev: %d, pop next: %d, push prev: %d, push next: %d\\n"", static_cast(c.mem.pop_prev_dep), static_cast(c.mem.pop_next_dep), static_cast(c.mem.push_prev_dep), static_cast(c.mem.push_next_dep)); printf(""\\tDRAM: 0x%08x, SRAM:0x%04x\\n"", static_cast(c.mem.dram_base), static_cast(c.mem.sram_base)); printf(""\\ty: size=%d, pad=[%d, %d]\\n"", static_cast(c.mem.y_size), static_cast(c.mem.y_pad_0), static_cast(c.mem.y_pad_1)); printf(""\\tx: size=%d, stride=%d, pad=[%d, %d]\\n"", static_cast(c.mem.x_size), static_cast(c.mem.x_stride), static_cast(c.mem.x_pad_0), static_cast(c.mem.x_pad_1)); if (c.mem.opcode == VTA_OPCODE_STORE) { if (c.mem.pop_prev_dep) g2s_queue--; if (c.mem.push_prev_dep) s2g_queue++; } else if (c.mem.opcode == VTA_OPCODE_LOAD && (c.mem.memory_type == VTA_MEM_ID_INP || c.mem.memory_type == VTA_MEM_ID_WGT)) { if (c.mem.pop_next_dep) g2l_queue--; if (c.mem.push_next_dep) l2g_queue++; } else { if (c.mem.pop_prev_dep) l2g_queue--; if (c.mem.push_prev_dep) g2l_queue++; if (c.mem.pop_next_dep) s2g_queue--; if (c.mem.push_next_dep) g2s_queue++; } } else if (c.mem.opcode == VTA_OPCODE_GEMM) { // Print instruction field information printf(""GEMM\\n""); printf(""\\tdep - pop prev: %d, pop next: %d, push prev: %d, push next: %d\\n"", static_cast(c.mem.pop_prev_dep), static_cast(c.mem.pop_next_dep), static_cast(c.mem.push_prev_dep), static_cast(c.mem.push_next_dep)); printf(""\\trange (%d, %d)\\n"", static_cast(c.gemm.uop_bgn), static_cast(c.gemm.uop_end)); printf(""\\treset_out: %d\\n"", static_cast(c.gemm.reset_reg)); printf(""\\touter loop - iter: %d, acc: %d, inp: %d, wgt: %d\\n"", static_cast(c.gemm.iter_out), static_cast(c.gemm.dst_factor_out), static_cast(c.gemm.src_factor_out), static_cast(c.gemm.wgt_factor_out)); printf(""\\tinner loop - iter: %d, acc: %d, inp: %d, wgt: %d\\n"", static_cast(c.gemm.iter_in), static_cast(c.gemm.dst_factor_in), static_cast(c.gemm.src_factor_in), static_cast(c.gemm.wgt_factor_in)); if (c.gemm.pop_prev_dep) l2g_queue--; if (c.gemm.push_prev_dep) g2l_queue++; if (c.gemm.pop_next_dep) s2g_queue--; if (c.gemm.push_next_dep) g2s_queue++; } else if (c.mem.opcode == VTA_OPCODE_FINISH) { printf(""FINISH\\n""); printf(""\\tdep - pop prev: %d, pop next: %d, push prev: %d, push next: %d\\n"", static_cast(c.mem.pop_prev_dep), static_cast(c.mem.pop_next_dep), static_cast(c.mem.push_prev_dep), static_cast(c.mem.push_next_dep)); if (c.gemm.pop_prev_dep) l2g_queue--; if (c.gemm.push_prev_dep) g2l_queue++; if (c.gemm.pop_next_dep) s2g_queue--; if (c.gemm.push_next_dep) g2s_queue++; } else if (c.mem.opcode == VTA_OPCODE_ALU) { // Print instruction field information printf(""ALU - %s\\n"", getOpcodeString(c.alu.alu_opcode, c.alu.use_imm)); printf(""\\tdep - pop prev: %d, pop next: %d, push prev: %d, push next: %d\\n"", static_cast(c.mem.pop_prev_dep), static_cast(c.mem.pop_next_dep), static_cast(c.mem.push_prev_dep), static_cast(c.mem.push_next_dep)); printf(""\\treset_out: %d\\n"", static_cast(c.alu.reset_reg)); printf(""\\trange (%d, %d)\\n"", static_cast(c.alu.uop_bgn), static_cast(c.alu.uop_end)); printf(""\\touter loop - iter: %d, dst: %d, src: %d\\n"", static_cast(c.alu.iter_out), static_cast(c.alu.dst_factor_out), static_cast(c.alu.src_factor_out)); printf(""\\tinner loop - iter: %d, dst: %d, src: %d\\n"", static_cast(c.alu.iter_in), static_cast(c.alu.dst_factor_in), static_cast(c.alu.src_factor_in)); if (c.alu.pop_prev_dep) l2g_queue--; if (c.alu.push_prev_dep) g2l_queue++; if (c.alu.pop_next_dep) s2g_queue--; if (c.alu.push_next_dep) g2s_queue++; } } printf(""DEBUG - l2g_queue = %d, g2l_queue = %d\\n"", l2g_queue, g2l_queue); printf(""DEBUG - s2g_queue = %d, g2s_queue = %d\\n"", s2g_queue, g2s_queue); } // Helper function: Print micro-ops status void printMicroOp(int num_uop, VTAUop *uops) { // Iterate over all micro ops printf(""DEBUG - There are %u micro-ops\\n"", num_uop); for (int i = 0; i < num_uop; i++) { // Read micro-op printf(""DEBUG - UOP %u: "", i); printf(""acc=%u, inp= %u, wgt=%u\\n"", uops[i].dst_idx, uops[i].src_idx, uops[i].wgt_idx); } } int alu_test(int opcode, bool use_imm, int batch, int vector_size, bool uop_compression) { // Some assertions assert(batch % VTA_BATCH == 0); assert(vector_size % VTA_BLOCK_OUT == 0); assert(!(opcode == VTA_ALU_OPCODE_SHR && !use_imm)); printf(""=====================================================================================\\n""); printf(""INFO - ALU test of %s: batch=%d, vector_size=%d, uop_compression=%d\\n"", getOpcodeString(opcode, use_imm), batch, vector_size, uop_compression); // Instruction count int ins_size = 3 * batch / VTA_BATCH + 2; // Micro op count int uop_size = uop_compression ? 1 : vector_size / VTA_BLOCK_OUT; // Input/output elements in each transfer int tx_size = vector_size / VTA_BLOCK_OUT; // Number of input sets to be generated int input_sets = (use_imm) ? 1 : 2; // Make sure we don't exceed buffer bounds assert(uop_size <= VTA_UOP_BUFF_DEPTH); assert(tx_size * input_sets <= VTA_ACC_BUFF_DEPTH); // Immediate values acc_T *immediate = static_cast(malloc(sizeof(acc_T) * batch / VTA_BATCH)); for (int b = 0; b < batch / VTA_BATCH; b++) { if (opcode == VTA_ALU_OPCODE_MIN) { immediate[b] = static_cast( rand_r(&globalSeed) % (1LL << (VTA_INP_WIDTH / 2)) - (1LL << (VTA_INP_WIDTH / 2 - 1))); } else if (opcode == VTA_ALU_OPCODE_MAX) { immediate[b] = static_cast( rand_r(&globalSeed) % (1LL << (VTA_INP_WIDTH / 2)) - (1LL << (VTA_INP_WIDTH / 2 - 1))); } else if (opcode == VTA_ALU_OPCODE_ADD) { immediate[b] = static_cast( rand_r(&globalSeed) % (1LL << (VTA_INP_WIDTH / 2)) - (1LL << (VTA_INP_WIDTH / 2 - 1))); } else if (opcode == VTA_ALU_OPCODE_SHR) { immediate[b] = static_cast( rand_r(&globalSeed) % VTA_ACC_WIDTH - VTA_ACC_WIDTH/2); } } // Initialize instructions VTAGenericInsn *insn_buf = static_cast(allocBuffer(sizeof(VTAGenericInsn) * ins_size)); int insn_idx = 0; insn_buf[insn_idx++] = get1DLoadStoreInsn(VTA_OPCODE_LOAD, VTA_MEM_ID_UOP, 0, 0, uop_size, 0, 0, 0, 0); for (int b = 0; b < batch; b += VTA_BATCH) { insn_buf[insn_idx++] = get2DLoadStoreInsn( VTA_OPCODE_LOAD, // opcode VTA_MEM_ID_ACC, // vector size 0, // sram offset b / VTA_BATCH * tx_size * input_sets, // dram offset 1, // y size tx_size * input_sets, // x size tx_size * input_sets, // x stride 0, // y pad 0, // x pad 0, // pop prev dep b > 0, // pop next dep 0, // push prev dep 0); // push next dep insn_buf[insn_idx++] = getALUInsn( opcode, // opcode tx_size, // vector size use_imm, // use imm immediate[b / VTA_BATCH], // imm uop_compression, // uop compression 0, // pop prev dep 0, // pop next dep 0, // push prev dep 1); // push next dep insn_buf[insn_idx++] = get2DLoadStoreInsn( VTA_OPCODE_STORE, // opcode VTA_MEM_ID_OUT, // vector size 0, // sram offset b / VTA_BATCH * tx_size, // dram offset 1, // y size tx_size, // x size tx_size, // x stride 0, // y pad 0, // x pad 1, // pop prev dep 0, // pop next dep 1, // push prev dep 0); // push next dep } // Finish insn_buf[insn_idx++] = getFinishInsn(0, 1); // Prepare the uop buffer VTAUop * uop_buf = getMapALUUops(tx_size, uop_compression); #if VTA_DEBUG == 1 printInstruction(ins_size, insn_buf); printMicroOp(uop_size, uop_buf); #endif // Initialize the input/output data acc_T **inputs = alloc2dArray(batch, vector_size * input_sets); for (int i = 0; i < batch; i++) { for (int j = 0; j < vector_size * input_sets; j++) { if (opcode == VTA_ALU_OPCODE_MIN) { inputs[i][j] = static_cast( rand_r(&globalSeed) % (1LL << (VTA_INP_WIDTH - 1)) - (1LL << (VTA_INP_WIDTH - 2))); } else if (opcode == VTA_ALU_OPCODE_MAX) { inputs[i][j] = static_cast( rand_r(&globalSeed) % (1LL << (VTA_INP_WIDTH - 1)) - (1LL << (VTA_INP_WIDTH - 2))); } else if (opcode == VTA_ALU_OPCODE_ADD) { inputs[i][j] = static_cast( rand_r(&globalSeed) % (1LL << (VTA_INP_WIDTH - 1)) - (1LL << (VTA_INP_WIDTH - 2))); } } } // Compute reference output out_T **outputs_ref = alloc2dArray(batch, vector_size); for (int i = 0; i < batch; i++) { for (int j = 0; j < vector_size; j++) { acc_T tmp = 0; if (opcode == VTA_ALU_OPCODE_MIN) { if (!use_imm) { tmp = inputs[i][j] < inputs[i][j + vector_size] ? inputs[i][j] : inputs[i][j + vector_size]; } else { tmp = inputs[i][j] < immediate[i / VTA_BATCH] ? inputs[i][j] : immediate[i / VTA_BATCH]; } } else if (opcode == VTA_ALU_OPCODE_MAX) { if (!use_imm) { tmp = inputs[i][j] > inputs[i][j + vector_size] ? inputs[i][j] : inputs[i][j + vector_size]; } else { tmp = inputs[i][j] > immediate[i / VTA_BATCH] ? inputs[i][j] : immediate[i / VTA_BATCH]; } } else if (opcode == VTA_ALU_OPCODE_ADD) { if (!use_imm) { tmp = inputs[i][j] + inputs[i][j + vector_size]; } else { tmp = inputs[i][j] + immediate[i / VTA_BATCH]; } } else if (opcode == VTA_ALU_OPCODE_SHR) { if (immediate[i / VTA_BATCH] >= 0) { tmp = inputs[i][j] >> immediate[i / VTA_BATCH]; } else { tmp = inputs[i][j] << (0 - immediate[i / VTA_BATCH]); } } // Set outputs_ref[i][j] = (out_T) tmp; } } // Pack input buffer acc_T *bias_buf = static_cast(allocBuffer(VTA_ACC_ELEM_BYTES * batch * tx_size * input_sets)); packBuffer( bias_buf, inputs, batch, vector_size * input_sets, VTA_BATCH, VTA_BLOCK_OUT); // Prepare output buffer out_T *output_buf = static_cast(allocBuffer(VTA_INP_ELEM_BYTES * batch * tx_size * input_sets)); #ifdef NO_SIM // Invoke the VTA uint64_t t_fpga = vta(ins_size, insn_buf, uop_buf, NULL, NULL, bias_buf, output_buf); // Report on timining printf(""INFO - Synchronization time: %.3fms\\n"", static_cast(t_fpga) / 1E6); printf(""INFO - Throughput: %.3fGOps/s\\n"", static_cast(vector_size * batch) / t_fpga); #else // Invoke the VTA vta(ins_size, (volatile insn_T *) insn_buf, (volatile uop_T *) uop_buf, (volatile inp_vec_T *) NULL, (volatile wgt_vec_T *) NULL, (volatile acc_vec_T *) bias_buf, (volatile out_vec_T *) output_buf); #endif // Unpack output buffer out_T **outputs = alloc2dArray(batch, vector_size); unpackBuffer(outputs, output_buf, batch, vector_size, VTA_BATCH, VTA_BLOCK_OUT); // Correctness checks int err = 0; for (int i = 0; i < batch; i++) { for (int j = 0; j < vector_size; j++) { if (outputs_ref[i][j] != outputs[i][j]) { err++; #if VTA_DEBUG == 1 printf(""DEBUG - %d, %d: expected 0x%x but got 0x%x\\n"", i, j, static_cast(outputs_ref[i][j]), static_cast(outputs[i][j])); #endif } } } // Free all allocated arrays free(immediate); free2dArray(inputs, batch, vector_size * input_sets); free2dArray(outputs_ref, batch, vector_size); free2dArray(outputs, batch, vector_size); freeBuffer(insn_buf); freeBuffer(uop_buf); freeBuffer(bias_buf); freeBuffer(output_buf); if (err == 0) { printf(""INFO - ALU test successful!\\n""); return 0; } else { printf(""INFO - ALU test failed, got %d errors!\\n"", err); return -1; } } int blocked_gemm_test(int batch, int channels, int block, bool uop_compression, int virtual_threads) { // Some assertions assert(block % VTA_BLOCK_IN == 0); assert(block % VTA_BLOCK_OUT == 0); assert(block % VTA_BATCH == 0); assert(channels % block == 0); assert(batch % block == 0); printf(""=====================================================================================\\n""); printf(""INFO - Blocked GEMM test: batch=%d, channels=%d, block=%d, uop_comp=%d, vt=%d\\n"", batch, channels, block, uop_compression, virtual_threads); // Input/output channels int in_feat = channels; int out_feat = channels; // Derive number of elements that need to be loaded/stored int ins_size = batch / block * out_feat / block * (2 + in_feat / block * 3) + 2; int uop_size = uop_compression ? block / VTA_BATCH * virtual_threads : block / VTA_BATCH * block / VTA_BLOCK_IN * block / VTA_BLOCK_OUT * virtual_threads; int inp_size = batch / VTA_BATCH * in_feat / VTA_BLOCK_IN; int wgt_size = in_feat / VTA_BLOCK_IN * out_feat / VTA_BLOCK_OUT; int out_size = batch / VTA_BATCH * out_feat / VTA_BLOCK_OUT; // Blocked buffer sizes (in terms of elements) int inp_block_size = block / VTA_BATCH * block / VTA_BLOCK_IN; int wgt_block_size = block / VTA_BLOCK_IN * block / VTA_BLOCK_OUT; int out_block_size = block / VTA_BATCH * block / VTA_BLOCK_OUT; // Make sure we don't exceed buffer bounds assert(uop_size <= VTA_UOP_BUFF_DEPTH); assert(inp_block_size <= VTA_INP_BUFF_DEPTH); assert(wgt_block_size <= VTA_WGT_BUFF_DEPTH); assert(out_block_size <= VTA_ACC_BUFF_DEPTH); // Initialize instruction buffer VTAGenericInsn *insn_buf = static_cast(allocBuffer(sizeof(VTAGenericInsn) * ins_size)); int insn_idx = 0; // Load uops insn_buf[insn_idx++] = get1DLoadStoreInsn(VTA_OPCODE_LOAD, VTA_MEM_ID_UOP, 0, 0, uop_size, 0, 0, 0, 0); // Iterate over batch blocks for (int i = 0; i < batch; i += block) { // Iterate over output channel blocks for (int j = 0; j < out_feat; j += block) { // Load bias block (pop next if not first, push prev) insn_buf[insn_idx++] = get2DLoadStoreInsn( VTA_OPCODE_LOAD, // opcode VTA_MEM_ID_ACC, // type 0, // sram offset (i / VTA_BATCH * out_feat + j) / VTA_BLOCK_OUT, // dram offset block / VTA_BATCH, // y size block / VTA_BLOCK_OUT, // x size out_feat / VTA_BLOCK_OUT, // x stride 0, // y pad 0, // x pad 0, // pop prev dep (i > 0 || j > 0), // pop next dep (virtual_threads == 1), // push prev dep 0); // push next dep // Iterate over input channel blocks for (int k = 0; k < in_feat; k += block * virtual_threads) { for (int l = 0; l < block * virtual_threads; l += block) { // Derive dependence flags bool pop = (virtual_threads == 1) ? 1 : (i > 0 || j > 0 || k > 0 || l > 0) && (k + l != block * virtual_threads - block); bool push_prev = (virtual_threads == 1) ? ((k + l) != in_feat - block) : ((k + l) != in_feat - virtual_threads * block) && ( (k + l != in_feat - block) || (j != out_feat - block) || (i != batch - block)); bool push_next = (k + l == in_feat - block); // Load weight block (pop next) insn_buf[insn_idx++] = get2DLoadStoreInsn( VTA_OPCODE_LOAD, // opcode VTA_MEM_ID_WGT, // type l / VTA_BLOCK_IN * block / VTA_BLOCK_OUT, // sram offset (j / VTA_BLOCK_OUT * in_feat + k + l) / VTA_BLOCK_IN, // dram offset block / VTA_BLOCK_OUT, // y size block / VTA_BLOCK_IN, // x size in_feat / VTA_BLOCK_IN, // x stride 0, // y pad 0, // x pad 0, // pop prev dep pop, // pop next dep 0, // push prev dep 0); // push next dep // Load input block (push next) insn_buf[insn_idx++] = get2DLoadStoreInsn( VTA_OPCODE_LOAD, // opcode VTA_MEM_ID_INP, // type l / VTA_BLOCK_IN * block / VTA_BATCH, // sram offset (i / VTA_BATCH * in_feat + k + l) / VTA_BLOCK_IN, // dram offset block / VTA_BATCH, // y size block / VTA_BLOCK_IN, // x size in_feat / VTA_BLOCK_IN, // x stride 0, // y pad 0, // x pad 0, // pop prev dep 0, // pop next dep 0, // push prev dep 1); // push next dep // Perform GEMM (pop prev, push prev if not last, push next if last) insn_buf[insn_idx++] = getGEMMInsn( l / block * uop_size / virtual_threads, // uop offset block / VTA_BATCH, // batch block / VTA_BLOCK_IN, // in_feat block / VTA_BLOCK_OUT, // out_feat uop_compression, // uop_compression 1, // pop_prev_dep 0, // pop_next_dep push_prev, // push prev dep push_next); // push_next_dep } } // Store output block (pop prev, push prev if not last) insn_buf[insn_idx++] = get2DLoadStoreInsn( VTA_OPCODE_STORE, // opcode VTA_MEM_ID_OUT, // type 0, // sram offset (i / VTA_BATCH * out_feat + j) / VTA_BLOCK_OUT, // dram offset block / VTA_BATCH, // y size block / VTA_BLOCK_OUT, // x size out_feat / VTA_BLOCK_OUT, // x stride 0, // y pad 0, // x pad 1, // pop prev dep 0, // pop next dep 1, // pop prev dep 0); // push next dep } } // Finish insn_buf[insn_idx++] = getFinishInsn(0, 1); // Prepare the uop buffer VTAUop * uop_buf = getGEMMUops( block / VTA_BATCH, block / VTA_BLOCK_IN, block / VTA_BLOCK_OUT, uop_compression, virtual_threads > 1); #if VTA_DEBUG == 1 printInstruction(ins_size, insn_buf); printMicroOp(uop_size, uop_buf); #endif // Initialize inputs inp_T **inputs = allocInit2dArray(batch, in_feat); // Initialize weights wgt_T **weights = allocInit2dArray(out_feat, in_feat); // Initialize biases acc_T **biases = allocInit2dArray(batch, out_feat); // Reference GEMM implementation out_T **outputs_ref = alloc2dArray(batch, out_feat); for (int i = 0; i < batch; i++) { for (int j = 0; j < out_feat; j++) { acc_T sum = biases[i][j]; for (int k = 0; k < in_feat; k++) { sum += (acc_T) (inputs[i][k] * weights[j][k]); } // Set outputs_ref[i][j] = (out_T) sum; } } // Prepare the input buffer inp_T *input_buf = static_cast(allocBuffer(VTA_INP_ELEM_BYTES * inp_size)); packBuffer(input_buf, inputs, batch, in_feat, VTA_BATCH, VTA_BLOCK_IN); // Prepare the weight buffer wgt_T *weight_buf = static_cast(allocBuffer(VTA_WGT_ELEM_BYTES * wgt_size)); packBuffer(weight_buf, weights, out_feat, in_feat, VTA_BLOCK_OUT, VTA_BLOCK_IN); // Prepare the bias buffer acc_T *bias_buf = static_cast(allocBuffer(VTA_ACC_ELEM_BYTES * out_size)); packBuffer(bias_buf, biases, batch, out_feat, VTA_BATCH, VTA_BLOCK_OUT); // Prepare the output buffer out_T *output_buf = static_cast(allocBuffer(VTA_INP_ELEM_BYTES * out_size)); #ifdef NO_SIM // Invoke the VTA uint64_t t_fpga = vta(ins_size, insn_buf, uop_buf, input_buf, weight_buf, bias_buf, output_buf); // Report on timining printf(""INFO - Synchronization time: %.3lfms\\n"", static_cast(t_fpga) / 1E6); printf(""INFO - Throughput: %.3lfGOPs/s\\n"", static_cast(batch) * in_feat * out_feat * 2 / t_fpga); #else // Invoke the VTA vta(ins_size, (volatile insn_T *) insn_buf, (volatile uop_T *) uop_buf, (volatile inp_vec_T *) input_buf, (volatile wgt_vec_T *) weight_buf, (volatile acc_vec_T *) bias_buf, (volatile out_vec_T *) output_buf); #endif // Unpack output data out_T **outputs = alloc2dArray(batch, out_feat); unpackBuffer(outputs, output_buf, batch, out_feat, VTA_BATCH, VTA_BLOCK_OUT); // Correctness checks int err = 0; for (int i = 0; i < batch; i++) { for (int j = 0; j < out_feat; j++) { if (outputs_ref[i][j] != outputs[i][j]) { err++; #if VTA_DEBUG == 1 printf(""DEBUG - %d, %d: expected 0x%x but got 0x%x\\n"", i, j, static_cast(outputs_ref[i][j]), static_cast(outputs[i][j])); #endif } } } // Free all allocated arrays free2dArray(inputs, batch, in_feat); free2dArray(weights, out_feat, in_feat); free2dArray(biases, batch, out_feat); free2dArray(outputs_ref, batch, out_feat); free2dArray(outputs, batch, out_feat); freeBuffer(insn_buf); freeBuffer(uop_buf); freeBuffer(input_buf); freeBuffer(weight_buf); freeBuffer(bias_buf); freeBuffer(output_buf); if (err == 0) { printf(""INFO - Blocked GEMM test successful!\\n""); return 0; } else { printf(""INFO - Blocked GEMM test failed, got %d errors!\\n"", err); return -1; } } int gemm_test(int batch, int in_channels, int out_channels, bool uop_compression) { // Some assertions assert(batch % VTA_BATCH == 0); assert(in_channels % VTA_BLOCK_IN == 0); assert(out_channels % VTA_BLOCK_OUT == 0); printf(""=====================================================================================\\n""); printf(""INFO - Blocked GEMM test: batch=%d, in_channels=%d, out_channels=%d, uop_comp=%d\\n"", batch, in_channels, out_channels, uop_compression); // Derive number of elements that need to be loaded/stored int ins_size = 7; int uop_size = uop_compression ? batch / VTA_BATCH : batch / VTA_BATCH * in_channels / VTA_BLOCK_IN * out_channels / VTA_BLOCK_OUT; int inp_size = batch / VTA_BATCH * in_channels / VTA_BLOCK_IN; int wgt_size = in_channels / VTA_BLOCK_IN * out_channels / VTA_BLOCK_OUT; int out_size = batch / VTA_BATCH * out_channels / VTA_BLOCK_OUT; // Make sure we don't exceed buffer bounds assert(uop_size <= VTA_UOP_BUFF_DEPTH); assert(inp_size <= VTA_INP_BUFF_DEPTH); assert(wgt_size <= VTA_WGT_BUFF_DEPTH); assert(out_size <= VTA_ACC_BUFF_DEPTH); // Initialize instruction buffer VTAGenericInsn *insn_buf = static_cast(allocBuffer(sizeof(VTAGenericInsn) * ins_size)); int insn_idx = 0; // Load uops insn_buf[insn_idx++] = get1DLoadStoreInsn( VTA_OPCODE_LOAD, VTA_MEM_ID_UOP, 0, 0, uop_size, 0, 0, 0, 0); // Load bias insn_buf[insn_idx++] = get1DLoadStoreInsn( VTA_OPCODE_LOAD, // opcode VTA_MEM_ID_ACC, // type 0, // sram offset 0, // dram offset out_size, // size 0, // pop prev dep 0, // pop next dep 1, // push prev dep 0); // push next dep // Load weight block (pop next) insn_buf[insn_idx++] = get1DLoadStoreInsn( VTA_OPCODE_LOAD, // opcode VTA_MEM_ID_WGT, // type 0, // sram offset 0, // dram offset wgt_size, // size 0, // pop prev dep 1, // pop next dep 0, // push prev dep 0); // push next dep // Load input block (push next) insn_buf[insn_idx++] = get1DLoadStoreInsn( VTA_OPCODE_LOAD, // opcode VTA_MEM_ID_INP, // type 0, // sram offset 0, // dram offset inp_size, // size 0, // pop prev dep 0, // pop next dep 0, // push prev dep 1); // push next dep // Perform GEMM (pop prev, push prev if not last, push next if last) insn_buf[insn_idx++] = getGEMMInsn( 0, // uop offset batch / VTA_BATCH, // batch in_channels / VTA_BLOCK_IN, // in_channels out_channels / VTA_BLOCK_OUT, // out_channels uop_compression, // uop_compression 1, // pop_prev_dep 0, // pop_next_dep 0, // push prev dep 1); // push_next_dep // Store output block (pop prev, push prev if not last) insn_buf[insn_idx++] = get1DLoadStoreInsn( VTA_OPCODE_STORE, // opcode VTA_MEM_ID_OUT, // type 0, // sram offset 0, // dram offset out_size, // size 1, // pop prev dep 0, // pop next dep 1, // push prev dep 0); // push next dep // Finish insn_buf[insn_idx++] = getFinishInsn(0, 1); // Prepare the uop buffer VTAUop * uop_buf = getGEMMUops( batch / VTA_BATCH, in_channels / VTA_BLOCK_IN, out_channels / VTA_BLOCK_OUT, uop_compression, 0); #if VTA_DEBUG == 1 printInstruction(ins_size, insn_buf); printMicroOp(uop_size, uop_buf); #endif // Initialize inputs inp_T **inputs = allocInit2dArray(batch, in_channels); // Initialize weights wgt_T **weights = allocInit2dArray(out_channels, in_channels); // Initialize biases acc_T **biases = allocInit2dArray(batch, out_channels); // Reference GEMM implementation out_T **outputs_ref = alloc2dArray(batch, out_channels); for (int i = 0; i < batch; i++) { for (int j = 0; j < out_channels; j++) { acc_T sum = biases[i][j]; for (int k = 0; k < in_channels; k++) { sum += (acc_T) (inputs[i][k] * weights[j][k]); } // Set outputs_ref[i][j] = (out_T) sum; } } // Prepare the input buffer inp_T *input_buf = static_cast(allocBuffer(VTA_INP_ELEM_BYTES * inp_size)); packBuffer(input_buf, inputs, batch, in_channels, VTA_BATCH, VTA_BLOCK_IN); // Prepare the weight buffer wgt_T *weight_buf = static_cast(allocBuffer(VTA_WGT_ELEM_BYTES * wgt_size)); packBuffer(weight_buf, weights, out_channels, in_channels, VTA_BLOCK_OUT, VTA_BLOCK_IN); // Prepare the bias buffer acc_T *bias_buf = static_cast(allocBuffer(VTA_ACC_ELEM_BYTES * out_size)); packBuffer(bias_buf, biases, batch, out_channels, VTA_BATCH, VTA_BLOCK_OUT); // Prepare the output buffer out_T *output_buf = static_cast(allocBuffer(VTA_INP_ELEM_BYTES * out_size)); #ifdef NO_SIM // Invoke the VTA uint64_t t_fpga = vta(ins_size, insn_buf, uop_buf, input_buf, weight_buf, bias_buf, output_buf); // Report on timining printf(""INFO - Synchronization time: %.3lfms\\n"", static_cast(t_fpga) / 1E6); printf(""INFO - Throughput: %.3lfGOPs/s\\n"", static_cast(batch) * in_channels * out_channels * 2 / t_fpga); #else // Invoke the VTA vta(ins_size, (volatile insn_T *) insn_buf, (volatile uop_T *) uop_buf, (volatile inp_vec_T *) input_buf, (volatile wgt_vec_T *) weight_buf, (volatile acc_vec_T *) bias_buf, (volatile out_vec_T *) output_buf); #endif // Unpack output data out_T **outputs = alloc2dArray(batch, out_channels); unpackBuffer(outputs, output_buf, batch, out_channels, VTA_BATCH, VTA_BLOCK_OUT); // Correctness checks int err = 0; for (int i = 0; i < batch; i++) { for (int j = 0; j < out_channels; j++) { if (outputs_ref[i][j] != outputs[i][j]) { err++; #if VTA_DEBUG == 1 printf(""DEBUG - %d, %d: expected 0x%x but got 0x%x\\n"", i, j, static_cast(outputs_ref[i][j]), static_cast(outputs[i][j])); #endif } } } // Free all allocated arrays free2dArray(inputs, batch, in_channels); free2dArray(weights, out_channels, in_channels); free2dArray(biases, batch, out_channels); free2dArray(outputs_ref, batch, out_channels); free2dArray(outputs, batch, out_channels); freeBuffer(insn_buf); freeBuffer(uop_buf); freeBuffer(input_buf); freeBuffer(weight_buf); freeBuffer(bias_buf); freeBuffer(output_buf); if (err == 0) { printf(""INFO - Blocked GEMM test successful!\\n""); return 0; } else { printf(""INFO - Blocked GEMM test failed, got %d errors!\\n"", err); return -1; } } ",16215,True,2997.6377493672258,median "// -*- C++ -*- Copyright (c) Microsoft Corporation; see license.txt #include ""Video.h"" // I actually get better read/write performance by directly calling Media Foundation, at least in Windows 7. // Generally, I prefer ffmpeg for its portability and quality. #define HH_VIDEO_HAVE_MF // unless disabled below #define HH_VIDEO_HAVE_FFMPEG // always as fallback #if !defined(_MSC_VER) || defined(__clang__) #undef HH_VIDEO_HAVE_MF #endif //---------------------------------------------------------------------------- #if defined(HH_VIDEO_HAVE_MF) #include // std::once_flag, std::call_once() // #undef _WIN32_WINNT // #define _WIN32_WINNT _WIN32_WINNT_WIN7 #define WIN32_LEAN_AND_MEAN #include // required by Media Foundation #include // IsWindows8OrGreater() #include #include #include #include // CODECAPI_AVEncMPVGOPSize, etc. // #include // ComPtr<> // template using ComPtr = Microsoft::WRL::ComPtr; HH_REFERENCE_LIB(""mfplat.lib""); HH_REFERENCE_LIB(""mfreadwrite.lib""); // MFCreateSourceReaderFromByteStream() HH_REFERENCE_LIB(""ole32.lib""); // PropVariantClear() HH_REFERENCE_LIB(""mfuuid.lib""); // MF_MT_DEFAULT_STRIDE #include ""windows_com.h"" // com_ptr<> #if defined(TRY_WIC) #include // WIC #endif #endif // defined(HH_VIDEO_HAVE_MF) //---------------------------------------------------------------------------- #if defined(HH_VIDEO_HAVE_FFMPEG) #include ""BinaryIO.h"" #endif // defined(HH_VIDEO_HAVE_FFMPEG) //---------------------------------------------------------------------------- #include ""GridPixelOp.h"" // spatially_scale_Grid3_Pixel() #include ""FileIO.h"" #include ""Vector4.h"" #include ""Timer.h"" #include ""ConsoleProgress.h"" #include ""StringOp.h"" // get_path_extension() #include // std::memcpy() //---------------------------------------------------------------------------- // Notes on uncompressed/lossless video formats: // http://superuser.com/questions/347433/how-to-create-an-uncompressed-avi-from-a-series-of-1000s-of-png-images-using-ff // Consider 1280x720p 24fps Big Buck Bunny movie: // - uncompressed (V308 is the 8 bpc variant of V410; not supported in many viewers) 518 Mbps // ffmpeg ... -c:v v308 output.mov // - compressed but lossless (Apple QuickTime Animation which is trivial RLE scheme) 165 Mbps // ffmpeg ... -c:v qtrle -pix_fmt rgb24 output.mov // - effectively lossless (NV12 is 4:2:0) 133 Mbps // ffmpeg ... -c:v ffvhuff -pix_fmt yuv420p output.avi // - lossless H.264 (libx264-only) (default pix_fmt is yuv444p or rgb24?) (""-preset ultrafast"" for faster encoding) // 29 Mbps for yuv422p, 43 Mbps with ultrafast // ffmpeg ... -c:v libx264 -qp 0 -pix_fmt yuv420p -f mp4 output.mp4 // I choose ""-c:v ffvhuff"" because it allows a unique container suffix (""avi"") that is distinct from the others. // I could use ""-c:v ffvhuff -pix_fmt yuv420p"" because it is compact and translates trivially to/from Nv12Video. // However, it is lossy like NV12. // Instead, I prefer ""-c:v ffvhuff -pix_fmt yuv444p"" which is lossless. // An alternative would be to use lossless x264, still in an avi container? namespace hh { static void verify_attrib(Video::Attrib& attrib) { if (!attrib.framerate) { Warning(""Video write: setting framerate to 30fps""); attrib.framerate = 30.; } } void Video::init(const Vec3& dims) { base::init(dims); if (0) { // required for Nv12/YUV support, but VideoViewer uses Video as a container for arbitrary images assertx(xsize()%2==0 && ysize()%2==0); } } string Video::diagnostic_string(const Vec3& dims, const Attrib& attrib) { string s = sform(""nframes~%d %dx%d (%gfps)"", dims[0], dims[2], dims[1], attrib.framerate); if (attrib.suffix!="""") s += "" ("" + attrib.suffix + "")""; int brate = attrib.bitrate; if (brate) s += (brate>1000000 ? sform("" (%.2fMi bps)"", brate/1000000.f) : brate>1000 ? sform("" (%.2fKi bps)"", brate/1000.f) : sform("" (%d bps)"", brate)); return s; } void Video::scale(const Vec2& syx, const Vec2& filterbs) { *this = hh::scale(*this, syx, filterbs, std::move(*this)); } void Video::read_file(const string& filename) { // Similar code in: Video::read_file(), VideoNv12::read_file(), and FilterVideo.cpp::read_video(). HH_TIMER(_read_video); clear(); RVideo rvideo(filename); attrib() = rvideo.attrib(); const int nfexpect = rvideo.nframes(); assertw(nfexpect>0); const int padframes = 2; // because may read a different number of frames init(nfexpect+padframes, rvideo.spatial_dims()); { ConsoleProgress cprogress(""Vread""); int f = 0; for (;;) { if (nfexpect) cprogress.update(float(f)/(nfexpect)); if (f>=nframes()) break; if (!rvideo.read((*this)[f])) break; f++; } base::special_reduce_dim0(f); } const int nf = nframes(); if (abs(nf-nfexpect)>1) { SHOW(nf, nfexpect); Warning(""Video: read unexpected num frames""); } } void Video::write_file(const string& filename) const { HH_TIMER(_write_video); assertx(size()); verify_attrib(const_cast(*this).attrib()); // mutable string suffix = to_lower(get_path_extension(filename)); if (suffix!="""") const_cast(*this).attrib().suffix = suffix; // mutable const bool use_nv12 = false; WVideo wvideo(filename, spatial_dims(), attrib(), use_nv12); ConsoleProgress cprogress(""Vwrite""); for_int(f, nframes()) { cprogress.update(float(f)/nframes()); wvideo.write((*this)[f]); } } //---------------------------------------------------------------------------- bool filename_is_video(const string& filename) { static const Array k_extensions = { ""mpg"", ""mpeg"", ""mpe"", ""mpv"", ""mp2"", ""mpeg2"", ""mp4"", ""mpeg4"", ""mov"", ""avi"", ""wmv"", ""flv"", ""m2v"", ""m4v"", ""webm"", ""ogv"", ""3gp"", ""mts"" }; return k_extensions.index(to_lower(get_path_extension(filename)))>=0; } string video_suffix_for_magic_byte(uchar c) { // see also image_suffix_for_magic_byte() and audio_suffix_for_magic_byte() // Documentation on prefixes for various video containers: // *.mp4: ""\\000\\000\\000\\030ftypmp42"", ""\\000\\000\\000 ftypisom"", ""\\000\\000\\000\\034ftypisom"" // *.wmv: ""0&\\262u"" // *.avi: ""RIFF"" // *.mov: ""\\000\\000\\000\\030ftypqt \\a\\t\\000"" switch (c) { bcase 0: return ""mp4""; // u'\\x00'; or ""mov"" bcase '0': return ""wmv""; bcase 'R': return ""avi""; bdefault: return """"; } } //---------------------------------------------------------------------------- void VideoNv12::read_file(const string& filename, Video::Attrib* pattrib) { // Similar code in: Video::read_file(), VideoNv12::read_file(), and FilterVideo.cpp::read_video(). HH_TIMER(_read_video); clear(); const bool use_nv12 = true; RVideo rvideo(filename, use_nv12); if (pattrib) *pattrib = rvideo.attrib(); const int nfexpect = rvideo.nframes(); assertw(nfexpect>0); const int padframes = 2; // because may read a different number of frames init(concat(V(nfexpect+padframes), rvideo.spatial_dims())); { ConsoleProgress cprogress(""Vread""); int f = 0; for (;;) { if (nfexpect) cprogress.update(float(f)/(nfexpect)); if (f>=_grid_Y.dim(0)) break; if (!rvideo.read((*this)[f])) break; f++; } special_reduce_dim0(f); } const int nf = _grid_Y.dim(0); if (abs(nf-nfexpect)>1) { SHOW(nf, nfexpect); Warning(""VideoNv12: read unexpected num frames""); } } void VideoNv12::write_file(const string& filename, const Video::Attrib& pattrib) const { HH_TIMER(_write_video); assertx(size()); Video::Attrib attrib = pattrib; verify_attrib(attrib); string suffix = to_lower(get_path_extension(filename)); if (suffix!="""") attrib.suffix = suffix; const bool use_nv12 = true; WVideo wvideo(filename, _grid_Y.dims().tail<2>(), attrib, use_nv12); ConsoleProgress cprogress(""Vwrite""); const int nf = _grid_Y.dim(0); for_int(f, nf) { cprogress.update(float(f)/nf); wvideo.write((*this)[f]); } } //---------------------------------------------------------------------------- void convert_VideoNv12_to_Video(CVideoNv12View vnv12, GridView<3,Pixel> video) { assertx(vnv12.nframes()==video.dim(0)); parallel_for_int(f, video.dim(0)) { convert_Nv12_to_Image(vnv12[f], video[f]); } } void convert_Video_to_VideoNv12(CGridView<3,Pixel> video, VideoNv12View vnv12) { assertx(vnv12.nframes()==video.dim(0)); parallel_for_int(f, video.dim(0)) { convert_Image_to_Nv12(video[f], vnv12[f]); } } //---------------------------------------------------------------------------- Video scale(const Video& video, const Vec2& syx, const Vec2& filterbs, Video&& pnewvideo) { // With Grid<3,Pixel> rather than Array>, we cannot directly overwrite video in-place. Video newvideo = &pnewvideo==&video ? Video() : std::move(pnewvideo); assertx(min(syx)>=0.f); Vec2 newdims = convert(convert(video.spatial_dims())*syx+.5f); if (video.attrib().suffix!=""avi"") newdims = (newdims+1)/2*2; // make sizes be even integers if (!product(newdims)) { Warning(""scaling to zero-sized frame""); if (0) fill(newdims, 0); } newvideo.init(video.nframes(), newdims); newvideo.attrib() = video.attrib(); if (!product(newdims)) return newvideo; spatially_scale_Grid3_Pixel(video, filterbs, newvideo); return newvideo; } VideoNv12 scale(const VideoNv12& video_nv12, const Vec2& syx, const Vec2& filterbs, VideoNv12&& pnewvideo_nv12) { VideoNv12 newvideo_nv12 = &pnewvideo_nv12==&video_nv12 ? VideoNv12() : std::move(pnewvideo_nv12); assertx(min(syx)>=0.f); const Vec2 sdims = video_nv12.get_Y().dims().tail<2>(); Vec2 newdims = convert(convert(sdims)*syx+.5f); if (1) newdims = (newdims+1)/2*2; // make sizes be even integers if (!product(newdims)) { Warning(""scaling to zero-sized frame""); if (0) fill(newdims, 0); } newvideo_nv12.init(concat(V(video_nv12.nframes()), newdims)); if (!product(newdims)) return newvideo_nv12; parallel_for_int(f, newvideo_nv12.nframes()) { Matrix mat(sdims); convert(video_nv12.get_Y()[f], mat); Matrix mat2 = scale(mat, newdims, filterbs); convert(mat2, newvideo_nv12.get_Y()[f]); } parallel_for_int(f, newvideo_nv12.nframes()) { Matrix mat(sdims/2); convert(video_nv12.get_UV()[f], mat); Matrix mat2 = scale(mat, newdims/2, filterbs); convert(mat2, newvideo_nv12.get_UV()[f]); } return newvideo_nv12; } //---------------------------------------------------------------------------- class RVideo::Implementation { public: Implementation(RVideo& rvideo) : _rvideo(rvideo) { } virtual ~Implementation() { } virtual string name() const = 0; virtual bool read(MatrixView frame) = 0; virtual bool read_nv12(Nv12View frame) { // default slow path const Vec2 sdims = _rvideo.spatial_dims(); assertx(frame.get_Y().dims()==sdims); Matrix tframe(frame.get_Y().dims()); if (!read(tframe)) return false; convert_Image_to_Nv12(tframe, frame); return true; } virtual bool discard_frame() { // default slow path const Vec2 sdims = _rvideo.spatial_dims(); if (_rvideo._use_nv12) { Nv12 nv12(sdims); return read_nv12(nv12); } else { Matrix tframe(sdims); return read(tframe); } } static unique_ptr make(RVideo& rvideo); protected: RVideo& _rvideo; }; class WVideo::Implementation { public: Implementation(WVideo& wvideo) : _wvideo(wvideo) { } virtual ~Implementation() { } virtual string name() const = 0; virtual void write(CMatrixView frame) = 0; virtual void write_nv12(CNv12View frame) { // default slow path assertx(product(_wvideo.spatial_dims())); assertx(frame.get_Y().dims()==_wvideo.spatial_dims()); Matrix tframe(frame.get_Y().dims()); convert_Nv12_to_Image(frame, tframe); write(tframe); } static unique_ptr make(WVideo& wvideo); protected: WVideo& _wvideo; }; class Unsupported_RVideo_Implementation : public RVideo::Implementation { public: Unsupported_RVideo_Implementation(RVideo& rvideo) : RVideo::Implementation(rvideo) { assertnever_ret(""?""); } ~Unsupported_RVideo_Implementation() { } virtual string name() const override { return ""unsupported""; } bool read(MatrixView frame) override { dummy_use(frame); assertnever(""?""); } }; class Unsupported_WVideo_Implementation : public WVideo::Implementation { public: Unsupported_WVideo_Implementation(WVideo& wvideo) : WVideo::Implementation(wvideo) { assertnever_ret(""?""); } ~Unsupported_WVideo_Implementation() { } virtual string name() const override { return ""unsupported""; } void write(CMatrixView frame) override { dummy_use(frame); assertnever(""?""); } }; //---------------------------------------------------------------------------- RVideo::RVideo(const string& filename, bool use_nv12) : _filename(filename), _use_nv12(use_nv12) { if (file_requires_pipe(_filename)) { RFile fi(_filename); int c = fi().peek(); if (c<0) throw std::runtime_error(""Error reading video from empty pipe '"" + _filename + ""'""); _attrib.suffix = video_suffix_for_magic_byte(uchar(c)); if (_attrib.suffix=="""") throw std::runtime_error(sform(""Peeked video format (c=%d) in pipe '%s' is not recognized"", c, _filename.c_str())); // if (_attrib.suffix==""avi"") _use_nv12 = false; // must be done in caller _tmpfile = make_unique(_attrib.suffix); _filename = _tmpfile->filename(); WFile fi2(_filename); fi2() << fi().rdbuf(); // copy the entire input stream to the temporary file } if (!file_exists(_filename)) throw std::runtime_error(""Video file '"" + _filename + ""' does not exist""); _attrib.suffix = to_lower(get_path_extension(_filename)); _impl = Implementation::make(*this); if (getenv_bool(""VIDEO_DEBUG"")) SHOW(_impl->name()); } RVideo::~RVideo() { _impl.reset(); } bool RVideo::read(MatrixView frame) { assertw(!_use_nv12); return _impl->read(frame); } bool RVideo::read(Nv12View frame) { assertw(_use_nv12); return _impl->read_nv12(frame); } bool RVideo::discard_frame() { return _impl->discard_frame(); } WVideo::WVideo(const string& filename, const Vec2& spatial_dims, const Video::Attrib& attrib, bool use_nv12) : _filename(filename), _sdims(spatial_dims), _attrib(attrib), _use_nv12(use_nv12), _pfilename(filename) { if (_attrib.suffix=="""") _attrib.suffix = to_lower(get_path_extension(_filename)); if (_attrib.suffix=="""") throw std::runtime_error(""Video '"" + filename + ""': no filename suffix specified for writing""); if (file_requires_pipe(_filename)) { if (_filename==""-"") my_setenv(""NO_DIAGNOSTICS_IN_STDOUT"", ""1""); _tmpfile = make_unique(_attrib.suffix); _filename = _tmpfile->filename(); } if (!_attrib.bitrate) { Warning(""Setting a high video bitrate""); _attrib.bitrate = 40*1000000; } _impl = Implementation::make(*this); if (getenv_bool(""VIDEO_DEBUG"")) SHOW(_impl->name()); } WVideo::~WVideo() { _impl.reset(); if (_tmpfile) { WFile fi(_pfilename); RFile fi2(_filename); fi() << fi2().rdbuf(); // copy the entire stream } } void WVideo::write(CMatrixView frame) { assertw(!_use_nv12); _impl->write(frame); } void WVideo::write(CNv12View frame) { assertw(_use_nv12); _impl->write_nv12(frame); } //---------------------------------------------------------------------------- // *** Video I/O #define AS(expr) assertx(SUCCEEDED(expr)) //---------------------------------------------------------------------------- // **** using Media Foundation #if defined(HH_VIDEO_HAVE_MF) // Supported Media Formats in Media Foundation // http://msdn.microsoft.com/en-us/library/dd757927%28VS.85%29.aspx // Containers: 3gp, asf, wma, wmv, aac, adts, avi, mp3, m4a, v4v, mov, mp4, sami, smi, wav class Initialize_COM_MF { public: Initialize_COM_MF() { if (s_num_video_uses++ && 0) return; // default may be COINIT_MULTITHREADED, but VT code assumes COINIT_APARTMENTTHREADED if (0) { // The following could work if we could guarantee that VT initialization occurred before this call. HRESULT hr = CoInitializeEx(nullptr, COINIT_MULTITHREADED); assertx(SUCCEEDED(hr) || hr==RPC_E_CHANGED_MODE); } else { HRESULT hr = CoInitializeEx(nullptr, COINIT_APARTMENTTHREADED); assertx(SUCCEEDED(hr) || hr==S_FALSE); // may equal S_FALSE if COM was previously initialized } AS(MFStartup(MF_VERSION, MFSTARTUP_FULL)); // initialize Media Foundation } ~Initialize_COM_MF() { if (--s_num_video_uses) return; if (1) return; // there may still be other users, such as Vision Tools. AS(MFShutdown()); CoUninitialize(); } private: static std::atomic s_num_video_uses; // only release MediaFoundation and COM when this reaches zero }; std::atomic Initialize_COM_MF::s_num_video_uses; class LockIMFMediaBuffer { public: LockIMFMediaBuffer(IMFMediaBuffer* buffer) : _buffer(buffer) { AS(_buffer->Lock(&_pData, nullptr, nullptr)); } ~LockIMFMediaBuffer() { assertx(_pData); AS(_buffer->Unlock()); } uchar* operator()() const { return _pData; } private: IMFMediaBuffer* _buffer; uchar* _pData {nullptr}; }; static void retrieve_strided_BGRA(const uchar* pData, int stride, MatrixView frame) { const int ny = frame.ysize(), nx = frame.xsize(); uchar* pd = frame.data()->data(); for_int(y, ny) { const uchar* ps = pData+y*stride; for_int(x, nx) { pd[0] = ps[2]; pd[1] = ps[1]; pd[2] = ps[0]; pd[3] = 255; // BGRA to RGBA pd += 4; ps += 4; } } } static void retrieve_strided_Nv12(const uchar* pData, int stride, int offsetUV, Nv12View nv12v) { const int ny = nv12v.get_Y().ysize(), nx = nv12v.get_Y().xsize(); // This is a bottleneck, so worth optimizing. if (stride==nv12v.get_Y().xsize()) { std::memcpy(nv12v.get_Y().data(), pData, nv12v.get_Y().size()); std::memcpy(nv12v.get_UV().data(), pData+offsetUV, nv12v.get_UV().size()*2); } else if (1) { for_int(y, ny) { std::memcpy(nv12v.get_Y()[y].data(), pData+y*stride, nx); } for_int(y, ny/2) { std::memcpy(nv12v.get_UV()[y].data(), pData+offsetUV+y*stride, nx); } } else { uchar* pd = nv12v.get_Y().data(); for_int(y, ny) { const uchar *ps = pData+y*stride; for_int(x, nx) { *pd++ = *ps++; } } pd = nv12v.get_UV().data()->data(); for_int(y, ny/2) { const uchar *ps = pData+offsetUV+y*stride; for_int(x, nx) { *pd++ = *ps++; } } } } class MF_RVideo_Implementation : public RVideo::Implementation { public: MF_RVideo_Implementation(RVideo& rvideo) : RVideo::Implementation(rvideo) { { com_ptr pSourceResolver; AS(MFCreateSourceResolver(&pSourceResolver)); DWORD createObjFlags = MF_RESOLUTION_BYTESTREAM | MF_RESOLUTION_CONTENT_DOES_NOT_HAVE_TO_MATCH_EXTENSION_OR_MIME_TYPE; MF_OBJECT_TYPE objectType = MF_OBJECT_INVALID; com_ptr pSource; if (FAILED(pSourceResolver->CreateObjectFromURL(widen(_rvideo._filename).c_str(), createObjFlags, nullptr, &objectType, &pSource))) throw std::runtime_error(""Could not open video in file '"" + _rvideo._filename + ""'""); assertx(objectType==MF_OBJECT_BYTESTREAM); AS(pSource->QueryInterface(IID_PPV_ARGS(&_pByteStream))); } { com_ptr pAttributes; AS(MFCreateAttributes(&pAttributes, 2)); AS(pAttributes->SetUINT32(MF_SOURCE_READER_ENABLE_VIDEO_PROCESSING, TRUE)); AS(pAttributes->SetUINT32(MF_READWRITE_ENABLE_HARDWARE_TRANSFORMS, TRUE)); if (FAILED(MFCreateSourceReaderFromByteStream(_pByteStream, pAttributes, &_pReader))) throw std::runtime_error(""Could not open video in file '"" + _rvideo._filename + ""'""); } double duration; { PROPVARIANT var; PropVariantInit(&var); AS(_pReader->GetPresentationAttribute(DWORD(MF_SOURCE_READER_MEDIASOURCE), MF_PD_DURATION, &var)); assertx(var.vt==VT_UI8); ULONGLONG durationInHundredsOfNanoseconds = var.uhVal.QuadPart; double TIME_HNS_TO_S_FACTOR = 10000000.; duration = double(durationInHundredsOfNanoseconds)/TIME_HNS_TO_S_FACTOR; PropVariantClear(&var); } { _impl_nv12 = _rvideo._use_nv12; if (1 || !IsWindows8OrGreater()) _impl_nv12 = true; // It may be ~3.5x faster on Windows 7 // Actually it is still 5x faster on Windows 10 } { com_ptr pType; AS(MFCreateMediaType(&pType)); AS(pType->SetGUID(MF_MT_MAJOR_TYPE, MFMediaType_Video)); AS(pType->SetGUID(MF_MT_SUBTYPE, _impl_nv12 ? MFVideoFormat_NV12 : MFVideoFormat_RGB32)); if (FAILED(_pReader->SetCurrentMediaType(DWORD(MF_SOURCE_READER_FIRST_VIDEO_STREAM), nullptr, pType))) { assertx(_impl_nv12); Warning(""Read video using MFVideoFormat_NV12 failed; reverting to MFVideoFormat_RGB32""); _impl_nv12 = false; AS(pType->SetGUID(MF_MT_SUBTYPE, _impl_nv12 ? MFVideoFormat_NV12 : MFVideoFormat_RGB32)); if (FAILED(_pReader->SetCurrentMediaType(DWORD(MF_SOURCE_READER_FIRST_VIDEO_STREAM), nullptr, pType))) throw std::runtime_error(""Could not open video media type in file '"" + _rvideo._filename + ""'""); } AS(_pReader->SetStreamSelection(DWORD(MF_SOURCE_READER_FIRST_VIDEO_STREAM), TRUE)); } { com_ptr pType; AS(_pReader->GetCurrentMediaType(DWORD(MF_SOURCE_READER_FIRST_VIDEO_STREAM), &pType)); GUID subtype; AS(pType->GetGUID(MF_MT_SUBTYPE, &subtype)); assertx(subtype==(_impl_nv12 ? MFVideoFormat_NV12 : MFVideoFormat_RGB32)); UINT32 vnum = 0; UINT32 vdenom = 1; AS(MFGetAttributeRatio(pType, MF_MT_FRAME_RATE, &vnum, &vdenom)); _rvideo._attrib.framerate = double(vnum)/double(vdenom); if (0) SHOW(_rvideo._attrib.framerate, duration); Vec3& dims = _rvideo._dims; dims[0] = int(_rvideo._attrib.framerate*duration+.5); // set nframes UINT32 tx = 0; UINT32 ty = 0; AS(MFGetAttributeSize(pType, MF_MT_FRAME_SIZE, &tx, &ty)); dims[1] = int(ty); dims[2] = int(tx); // set ysize, xsize _mf_ny = dims[1]; _mf_nx = dims[2]; // initial settings UINT32 bitrate = 0; if (!SUCCEEDED(pType->GetUINT32(MF_MT_AVG_BITRATE, &bitrate))) bitrate = 0; _rvideo._attrib.bitrate = int(bitrate); UINT32 tstride = 0; AS(pType->GetUINT32(MF_MT_DEFAULT_STRIDE, &tstride)); _stride = tstride; assertx(_stride>0); if (0) SHOW(dims, _stride); } } ~MF_RVideo_Implementation() { // Note that _init_com_mf.~Initialize_COM_MF() is called after this destructor } virtual string name() const { return ""MF""; } bool read(MatrixView frame) override { const Vec2 sdims = _rvideo.spatial_dims(); assertx(frame.dims()==sdims); com_ptr pSample = get_sample(); if (!pSample) return false; const int stride = _stride; com_ptr pBuffer; AS(pSample->ConvertToContiguousBuffer(&pBuffer)); { LockIMFMediaBuffer lock(pBuffer); const uchar* pData = lock(); // The following fails on the mp4 I tried! // com_ptr p2Dbuf; AS(pBuffer->QueryInterface(IID_PPV_ARGS(&p2Dbuf))); // BYTE* pData; LONG lstride; AS(p2Dbuf->Lock2D(&pData, &lstride)); { if (!_impl_nv12) { retrieve_strided_BGRA(pData, stride, frame); } else { int offset = _mf_ny*stride; if (stride==sdims[1]*1) { CMatrixView matY(pData, sdims); CMatrixView> matUV(reinterpret_cast*>(pData+offset), sdims/2); convert_Nv12_to_Image(CNv12View(matY, matUV), frame); } else { Nv12 nv12(sdims); retrieve_strided_Nv12(pData, stride, offset, nv12); // slow path convert_Nv12_to_Image(nv12, frame); } } // } AS(p2Dbuf->Unlock2D()); } return true; } bool read_nv12(Nv12View nv12v) override { const Vec2 sdims = _rvideo.spatial_dims(); assertx(nv12v.get_Y().dims()==sdims); com_ptr pSample = get_sample(); if (!pSample) return false; const int stride = _stride; com_ptr pBuffer; AS(pSample->ConvertToContiguousBuffer(&pBuffer)); { LockIMFMediaBuffer lock(pBuffer); const uchar* pData = lock(); if (_impl_nv12) { retrieve_strided_Nv12(pData, stride, _mf_ny*stride, nv12v); } else { if (stride==sdims[1]*4) { MatrixView mat(reinterpret_cast(const_cast(pData)), sdims); for (Pixel& pix : mat) std::swap(pix[0], pix[2]); // BGRA to RGBA convert_Image_to_Nv12(mat, nv12v); } else { Matrix mat(sdims); retrieve_strided_BGRA(pData, stride, mat); // slower path convert_Image_to_Nv12(mat, nv12v); } } } return true; } bool discard_frame() override { com_ptr pSample = get_sample(); return !!pSample; } com_ptr get_sample() { com_ptr pSample; for (;;) { DWORD dwFlags = 0; assertx(!pSample); AS(_pReader->ReadSample(DWORD(MF_SOURCE_READER_FIRST_VIDEO_STREAM), 0, nullptr, &dwFlags, nullptr, &pSample)); if (dwFlags & MF_SOURCE_READERF_ENDOFSTREAM) { assertx(!pSample); return {}; } // It is possible for real media to be 960x540 and then get ""changed"" to 960x544. // Both tx and ty may change: Filtervideo ~/proj/videoloops/data/ReallyFreakinAll/SDBaiModelS.mp4 -noo // xsize=300 ysize=540 --> _mf_ny=544 _mf_nx=304 _stride=304 if ((dwFlags & MF_SOURCE_READERF_CURRENTMEDIATYPECHANGED)) { com_ptr pType; AS(_pReader->GetCurrentMediaType(DWORD(MF_SOURCE_READER_FIRST_VIDEO_STREAM), &pType)); UINT32 tx = 0; UINT32 ty = 0; AS(MFGetAttributeSize(pType, MF_MT_FRAME_SIZE, &tx, &ty)); _mf_ny = ty; _mf_nx = tx; assertx(_mf_ny>=_rvideo.ysize() && _mf_nx>=_rvideo.xsize()); UINT32 tstride = 0; AS(pType->GetUINT32(MF_MT_DEFAULT_STRIDE, &tstride)); _stride = tstride; assertx(_stride>0); // SHOW(_mf_ny, _mf_nx, _stride); } assertw(pSample); if (pSample) break; } return pSample; } static bool supported() { return true; } private: Initialize_COM_MF _init_com_mf; // must be declared first, to be destroyed after remaining members com_ptr _pByteStream; com_ptr _pReader; bool _impl_nv12; int _mf_ny; int _mf_nx; int _stride; }; class MF_WVideo_Implementation : public WVideo::Implementation { public: MF_WVideo_Implementation(WVideo& wvideo) : WVideo::Implementation(wvideo) { const auto& attrib = _wvideo._attrib; if (attrib.audio.size()) Warning(""MF_WVideo does not currently support audio""); _impl_nv12 = attrib.suffix==""mp4""; if (0 && _impl_nv12) { Warning(""Disabling _impl_nv12""); _impl_nv12 = false; } int iFramesPerSecond = int(attrib.framerate+.5); AS(MFFrameRateToAverageTimePerFrame(iFramesPerSecond, 1, &_rtDuration)); GUID videoOutputFormat; if (0) void(); else if (attrib.suffix==""mp4"") videoOutputFormat = MFVideoFormat_H264; else if (attrib.suffix==""mov"") videoOutputFormat = MFVideoFormat_H264; else if (attrib.suffix==""wmv"") videoOutputFormat = MFVideoFormat_WVC1; // Note that Media Foundation does not support *.avi as an output format; // see: https://msdn.microsoft.com/en-us/library/dd757927(VS.85).aspx else if (0 && attrib.suffix==""avi"") videoOutputFormat = MFVideoFormat_420O; // 8bpc planar YUV 4:2:0 else throw std::runtime_error(""Video: encoder suffix '"" + attrib.suffix + ""' not recognized""); // See Tutorial: Using the Sink Writer to Encode Video (Windows) // http://msdn.microsoft.com/en-us/library/windows/desktop/ff819477%28v=vs.85%29.aspx // Color conversion bug: // http://social.msdn.microsoft.com/Forums/en-US/mediafoundationdevelopment/thread/8a03ac4d-34a3-493d-b27e-5147de575fb7 // Use Color Converter DSP (http://msdn.microsoft.com/en-us/library/ff819079%28VS.85%29.aspx) // See ""Work around for XVP color conversion problem"" in // ~/git/CompPhoto/ClassLibs/VisionTools/src/fileio/MFVideoSrc.h { com_ptr pAttributes; AS(MFCreateAttributes(&pAttributes, 10)); AS(pAttributes->SetUINT32(MF_READWRITE_ENABLE_HARDWARE_TRANSFORMS, TRUE)); // AS(pAttributes->SetUINT32(MF_READWRITE_ENABLE_HARDWARE_TRANSFORMS, FALSE)); // no effect // AS(pAttributes->SetUINT32(MF_READWRITE_DISABLE_CONVERTERS, TRUE)); // causes it to fail AS(pAttributes->SetUINT32(MF_SOURCE_READER_ENABLE_VIDEO_PROCESSING, TRUE)); // no effect // AS(pAttributes->SetUINT32(MF_SOURCE_READER_ENABLE_VIDEO_PROCESSING, FALSE)); // no effect IMFByteStream* const k_ByteStream = nullptr; if (FAILED(MFCreateSinkWriterFromURL(widen(_wvideo._filename).c_str(), k_ByteStream, nullptr/*pAttributes*/, &_pSinkWriter))) throw std::runtime_error(""Could not write video to file '"" + _wvideo._filename + ""'""); } { com_ptr pMediaTypeOut; AS(MFCreateMediaType(&pMediaTypeOut)); AS(pMediaTypeOut->SetGUID(MF_MT_MAJOR_TYPE, MFMediaType_Video)); AS(pMediaTypeOut->SetGUID(MF_MT_SUBTYPE, videoOutputFormat)); AS(pMediaTypeOut->SetUINT32(MF_MT_AVG_BITRATE, UINT32(attrib.bitrate))); AS(pMediaTypeOut->SetUINT32(MF_MT_INTERLACE_MODE, MFVideoInterlace_Progressive)); AS(MFSetAttributeSize(pMediaTypeOut, MF_MT_FRAME_SIZE, _wvideo.xsize(), _wvideo.ysize())); AS(MFSetAttributeRatio(pMediaTypeOut, MF_MT_FRAME_RATE, iFramesPerSecond, 1)); AS(MFSetAttributeRatio(pMediaTypeOut, MF_MT_PIXEL_ASPECT_RATIO, 1, 1)); AS(_pSinkWriter->AddStream(pMediaTypeOut, &_streamIndex)); } { com_ptr pMediaTypeIn; AS(MFCreateMediaType(&pMediaTypeIn)); AS(pMediaTypeIn->SetGUID(MF_MT_MAJOR_TYPE, MFMediaType_Video)); GUID video_format = MFVideoFormat_RGB32; if (_impl_nv12) video_format = MFVideoFormat_NV12; AS(pMediaTypeIn->SetGUID(MF_MT_SUBTYPE, video_format)); AS(pMediaTypeIn->SetUINT32(MF_MT_DEFAULT_STRIDE, _wvideo.xsize()*(_impl_nv12 ? 1 : 4))); AS(pMediaTypeIn->SetUINT32(MF_MT_INTERLACE_MODE, MFVideoInterlace_Progressive)); AS(MFSetAttributeSize(pMediaTypeIn, MF_MT_FRAME_SIZE, _wvideo.xsize(), _wvideo.ysize())); AS(MFSetAttributeRatio(pMediaTypeIn, MF_MT_FRAME_RATE, iFramesPerSecond, 1)); AS(MFSetAttributeRatio(pMediaTypeIn, MF_MT_PIXEL_ASPECT_RATIO, 1, 1)); com_ptr pAttributes; // pEncodingParameters // IMFAttributes* const pEncodingParameters = nullptr; if (0) { // untested AS(MFCreateAttributes(&pAttributes, 10)); if (0) { unsigned force_keyframe_every_nframes = 20; AS(pAttributes->SetUINT32(CODECAPI_AVEncMPVGOPSize, force_keyframe_every_nframes)); } if (0) { unsigned quality = 78; AS(pAttributes->SetUINT32(CODECAPI_AVEncCommonRateControlMode, eAVEncCommonRateControlMode_Quality)); AS(pAttributes->SetUINT32(CODECAPI_AVEncCommonQuality, quality)); } } AS(_pSinkWriter->SetInputMediaType(_streamIndex, pMediaTypeIn, pAttributes)); } AS(_pSinkWriter->BeginWriting()); } ~MF_WVideo_Implementation() { if (_pSinkWriter) AS(_pSinkWriter->Finalize()); // Note that _init_com_mf.~Initialize_COM_MF() is called after this destructor } virtual string name() const { return ""MF""; } void write(CMatrixView frame) override { const Vec2 sdims = _wvideo.spatial_dims(); assertx(product(_wvideo.spatial_dims())); assertx(frame.dims()==_wvideo.spatial_dims()); #if defined(TRY_WIC) // untested (not sure if this can work) assertnever(""untested""); static IWICImagingFactory* wic_factory; static std::once_flag flag; std::call_once(flag, []() { AS(CoCreateInstance(CLSID_WICImagingFactory, nullptr, CLSCTX_INPROC_SERVER, IID_PPV_ARGS(&wic_factory))); }); assertx(wic_factory); com_ptr bitmap; { WICPixelFormatGUID bitmap_pixel_format = GUID_WICPixelFormat32bppRGBA; // ignore undefined alpha unsigned stride = sdims[1]*sizeof(Pixel); // Note: problem for huge images; no workaround using WIC. unsigned buffer_size = assert_narrow_cast(sdims[0]*sdims[1]*sizeof(Pixel)); uchar* buf = const_cast(frame.data()->data()); AS(wic_factory->CreateBitmapFromMemory(sdims[1], sdims[0], bitmap_pixel_format, stride, buffer_size, buf, &bitmap)); } // requires Windows 8 com_ptr pBuffer; AS(MFCreateWICBitmapBuffer(__uuidof(IWICBitmap), bitmap, &pBuffer)); #else DWORD cbBuffer = DWORD(product(_wvideo.spatial_dims())*(_impl_nv12 ? 1.5f : 4.f)); com_ptr pBuffer; AS(MFCreateAlignedMemoryBuffer(cbBuffer, MF_16_BYTE_ALIGNMENT, &pBuffer)); { LockIMFMediaBuffer lock(pBuffer); uchar* pData = lock(); if (!_impl_nv12) { uchar* pd = pData; const uchar* ps = frame.data()->data(); for_int(y, sdims[0]) { for_int(x, sdims[1]) { pd[0] = ps[2]; pd[1] = ps[1]; pd[2] = ps[0]; pd[3] = 0; // RGBA to BGRA pd += 4; ps += 4; } } } else { // Media Foundation MP4 encoding under Win7 may have poor quality -- independent of this workaround. MatrixView matY(pData, _wvideo.spatial_dims()); MatrixView> matUV(reinterpret_cast*>(pData+sdims[0]*sdims[1]), _wvideo.spatial_dims()/2); convert_Image_to_Nv12(frame, Nv12View(matY, matUV)); } } AS(pBuffer->SetCurrentLength(cbBuffer)); #endif com_ptr pSample; AS(MFCreateSample(&pSample)); AS(pSample->AddBuffer(pBuffer)); AS(pSample->SetSampleTime(_rtStart)); AS(pSample->SetSampleDuration(_rtDuration)); AS(_pSinkWriter->WriteSample(_streamIndex, pSample)); _rtStart += _rtDuration; } void write_nv12(CNv12View nv12v) override { const Vec2 sdims = _wvideo.spatial_dims(); assertx(product(_wvideo.spatial_dims())); assertx(nv12v.get_Y().dims()==_wvideo.spatial_dims()); DWORD cbBuffer = DWORD(product(_wvideo.spatial_dims())*(_impl_nv12 ? 1.5f : 4.f)); com_ptr pBuffer; AS(MFCreateAlignedMemoryBuffer(cbBuffer, MF_16_BYTE_ALIGNMENT, &pBuffer)); { LockIMFMediaBuffer lock(pBuffer); uchar* pData = lock(); if (_impl_nv12) { // Media Foundation MP4 encoding under Win7 may have poor quality; it is independent of this workaround MatrixView matY(pData, _wvideo.spatial_dims()); MatrixView> matUV(reinterpret_cast*>(pData+sdims[0]*sdims[1]), _wvideo.spatial_dims()/2); matY.assign(nv12v.get_Y()); matUV.assign(nv12v.get_UV()); } else { MatrixView mat(reinterpret_cast(pData), _wvideo.spatial_dims()); convert_Nv12_to_Image(nv12v, mat); for (Pixel& pix : mat) std::swap(pix[0], pix[2]); // RGBA to BGRA } } AS(pBuffer->SetCurrentLength(cbBuffer)); com_ptr pSample; AS(MFCreateSample(&pSample)); AS(pSample->AddBuffer(pBuffer)); AS(pSample->SetSampleTime(_rtStart)); AS(pSample->SetSampleDuration(_rtDuration)); AS(_pSinkWriter->WriteSample(_streamIndex, pSample)); _rtStart += _rtDuration; } static bool supported() { return true; } private: Initialize_COM_MF _init_com_mf; // must be declared first, to be destroyed after remaining members com_ptr _pSinkWriter; DWORD _streamIndex; UINT64 _rtDuration; LONGLONG _rtStart {0}; bool _impl_nv12; // otherwise, Windows 7 Media Foundation shifts colors during MP4 compression! // for *.wmv files, _impl_nv12 does not speed up compression -- it is always about 3x slower than MP4 in Win7. }; #else class MF_RVideo_Implementation : public Unsupported_RVideo_Implementation { public: MF_RVideo_Implementation(RVideo& rvideo) : Unsupported_RVideo_Implementation(rvideo) { } static bool supported() { return false; } }; class MF_WVideo_Implementation : public Unsupported_WVideo_Implementation { public: MF_WVideo_Implementation(WVideo& wvideo) : Unsupported_WVideo_Implementation(wvideo) { } static bool supported() { return false; } }; #endif // defined(HH_VIDEO_HAVE_MF) //---------------------------------------------------------------------------- // **** using ffmpeg #if defined(HH_VIDEO_HAVE_FFMPEG) class FF_RVideo_Implementation : public RVideo::Implementation { public: FF_RVideo_Implementation(RVideo& rvideo) : RVideo::Implementation(rvideo) { assertx(supported()); // See: ~/src/_other/Repository.cpp // See: ffmpeg -hide_banner -pix_fmts const bool ldebug = getenv_bool(""FF_DEBUG""); const string& filename = _rvideo._filename; bool expect_audio = false; { // read header for dimensions and attributes (ignore video and audio data) // 2>&1 works on both Unix bash shell and Windows cmd shell: http://stackoverflow.com/questions/1420965/ // Ideally, &1 |""); Vec3 dims{0, 0, 0}; double duration = -1., total_bitrate = -1.; double video_bitrate = -1., framerate = -1.; bool yuv444p = false; int nlines = 0; string sline; while (my_getline(fi(), sline, false)) { nlines++; if (ldebug) SHOW(sline); char vch; if (contains(sline, ""Could not find option 'nostdin'"")) { Warning(""Version of external program 'ffmpeg' may be too old""); continue; } if (contains(sline, ""Duration:"")) { // Duration: 00:00:05.00, start: 0.000000, bitrate: 32842 kb/s (some mp4 files) // Duration: 00:00:05.03, bitrate: 100505 kb/s // Duration: N/A, bitrate: N/A (invalid.mp4) if (contains(sline, ""Duration: N/A"")) throw std::runtime_error(""Invalid video in file '"" + filename + ""'""); { int vh, vm, vs, vcs; assertx(sscanf(sline.c_str(), "" Duration: %d:%d:%d.%d%c"", &vh, &vm, &vs, &vcs, &vch)==5 && vch==','); duration = vh*3600. + vm*60. + vs + vcs*.01; if (ldebug) SHOW(vh, vm, vs, vcs, duration); } { auto i = sline.find("", bitrate:""); assertx(i!=string::npos); assertx(sscanf(sline.c_str()+i, "", bitrate: %lg kb/%c"", &total_bitrate, &vch)==2 && vch=='s'); total_bitrate *= 1000.; if (ldebug) SHOW(total_bitrate); } } if (contains(sline, ""Stream #0:"") && contains(sline, "": Video:"")) { // Stream #0:0(eng): Video: mpeg4 (Simple Profile) (mp4v / 0x7634706D), yuv420p, 960x540 [SAR 1:1 DAR 16:9], 32840 kb/s, 30 fps, 30 tbr, 30 tbn, 30 tbc (default) // Stream #0:0: Video: msmpeg4v3 (MP43 / 0x3334504D), yuv420p, 960x540, 30 fps, 30 tbr, 1k tbn, 1k tbc // Stream #0:0: Video: h264 (High) (H264 / 0x34363248), yuv420p, 960x540, 68071 kb/s, 30 fps, 30 tbr, 30 tbn, 60 tbc // Stream #0:0(eng): Video: vc1 (Advanced) (WVC1 / 0x31435657), yuv420p, 3840x2160, 100000 kb/s, SAR 1:1 DAR 16:9, 30 fps, 30 tbr, 1k tbn, 1k tbc // Stream #0:0(und): Video: h264 (Baseline) (avc1 / 0x31637661), yuv420p(tv, bt709), 1280x720, 10734 kb/s, 29.97 fps, 29.97 tbr, 600 tbn, 1200 tbc (default) // Stream #0:0(eng): Video: h264 (High) (avc1 / 0x31637661), yuv420p(tv, bt709), 3840x2160 [SAR 1:1 DAR 16:9], 59969 kb/s, 29.97 fps, 29.97 tbr, 30k tbn, 59.94 tbc (default) // Stream #0:0(eng): Video: vc1 (Advanced) (WVC1 / 0x31435657), yuv420p, 3840x2160 [SAR 1:1 DAR 16:9], 100000 kb/s, 30 tbr, 1k tbn, 60 tbc // Stream #0:1(eng): Video: wmv3 (Main) (WMV3 / 0x33564D57), yuv420p, 640x480, 768 kb/s, SAR 1:1 DAR 4:3, 30 fps, 30 tbr, 1k tbn, 1k tbc // Stream #0:0: Video: rawvideo, bgr24, 768x1024, 2 fps, 2 tbr, 2 tbn, 2 tbc // Stream #0:0: Video: ffvhuff (FFVH / 0x48564646), yuv444p, 960x540, 155182 kb/s, 30 fps, 30 tbr, 30 tbn, 30 tbc [*.avi] for (string::size_type i = 0; ; ) { i = sline.find(',', i+1); assertx(i!=string::npos); if (sscanf(sline.c_str()+i, "", %dx%d"", &dims[2], &dims[1])==2) break; } string::size_type i = sline.find("" kb/s""); if (i!=string::npos) { if (video_bitrate>=0.) assertnever(""Multiple video streams inside media container""); i = sline.rfind("", "", i); if (i!=string::npos) { assertx(sscanf(sline.c_str()+i, "", %lg kb/%c"", &video_bitrate, &vch)==2 && vch=='s'); video_bitrate *= 1000.; } } i = sline.find("" fps""); if (i!=string::npos) { i = sline.rfind("", "", i); assertx(i!=string::npos); assertx(sscanf(sline.c_str()+i, "", %lg fp%c"", &framerate, &vch)==2 && vch=='s'); } else { i = sline.find("" tbr""); assertx(i!=string::npos); i = sline.rfind("", "", i); assertx(i!=string::npos); assertx(sscanf(sline.c_str()+i, "", %lg tb%c"", &framerate, &vch)==2 && vch=='r'); } if (sline.find(""yuv444p"")!=string::npos) yuv444p = true; if (ldebug) SHOW(dims[2], dims[1], video_bitrate, framerate, yuv444p); } if (contains(sline, ""Stream #0:"") && contains(sline, "": Audio:"") && contains(sline, ""kb/s"")) expect_audio = true; } if (!nlines) throw std::runtime_error(""ffmpeg is unable to read video file '"" + filename + ""'""); if (video_bitrate<0.) video_bitrate = total_bitrate; if (ldebug) SHOW(duration, total_bitrate, video_bitrate, framerate); if (!(duration>0. && total_bitrate>0. && video_bitrate>0. && framerate>0.)) throw std::runtime_error(""ffmpeg is unable to parse video in file '"" + filename + ""'""); dims[0] = int(duration*framerate+.5); assertx(product(dims)>0); _rvideo._dims = dims; _rvideo._attrib.bitrate = int(video_bitrate); _rvideo._attrib.framerate = framerate; if (yuv444p && _rvideo._use_nv12) { // must be fixed in caller if (0) Warning(""Switching video read away from NV12 because video encoding is yuv444p""); if (0) _rvideo._use_nv12 = false; Warning(""Reading NV12 from a Video encoded with yuv444p""); } } if (expect_audio) { try { Audio& audio = _rvideo._attrib.audio; audio.read_file(filename); if (ldebug) SHOW(audio.diagnostic_string()); } catch (std::runtime_error& ex) { SHOW(""Failed to read audio within video"", filename, ex.what()); } } string pixfmt = _rvideo._use_nv12 ? ""nv12"" : ""rgba""; // was rgb24 // Note: -hide_banner unnecessary with ""-loglevel panic"" if using ""-i some_input"". string scmd = (""ffmpeg -loglevel panic -nostdin -i "" + quote_arg_for_shell(filename) + "" -f image2pipe -pix_fmt "" + pixfmt + "" -vcodec rawvideo - |""); if (ldebug) SHOW(scmd); _pfi = make_unique(scmd); } ~FF_RVideo_Implementation() { } virtual string name() const override { return ""FF""; } bool read(MatrixView frame) override { const Vec2 sdims = _rvideo.spatial_dims(); assertx(frame.dims()==sdims); if (!_rvideo._use_nv12) { if (!read_binary_raw((*_pfi)(), frame.array_view())) return false; if (0) { for_int(i, int(product(sdims))) { frame.raster(i)[3] = 255; } } } else { _ar_tmp.init(assert_narrow_cast(product(sdims)+product(sdims)/2)); // NV12 if (!read_binary_raw((*_pfi)(), _ar_tmp)) return false; CMatrixView matY(_ar_tmp.data(), sdims); CMatrixView> matUV(reinterpret_cast*>(_ar_tmp.data()+product(sdims)), sdims/2); convert_Nv12_to_Image(CNv12View(matY, matUV), frame); } return true; } bool read_nv12(Nv12View nv12v) override { const Vec2 sdims = _rvideo.spatial_dims(); assertx(nv12v.get_Y().dims()==sdims); if (_rvideo._use_nv12) { if (!read_binary_raw((*_pfi)(), nv12v.get_Y().array_view())) return false; assertx(read_binary_raw((*_pfi)(), nv12v.get_UV().array_view())); } else { _frame_rgb_tmp.init(sdims); if (!read(_frame_rgb_tmp)) return false; convert_Image_to_Nv12(_frame_rgb_tmp, nv12v); } return true; } bool discard_frame() override { const Vec2 sdims = _rvideo.spatial_dims(); if (_rvideo._use_nv12) { (*_pfi)().ignore(product(sdims)+product(sdims)/2); } else { (*_pfi)().ignore(product(sdims)*4); } return !!(*_pfi)(); } static bool supported() { return ffmpeg_command_exists(); } private: unique_ptr _pfi; Array _ar_tmp; Matrix _frame_rgb_tmp; }; class FF_WVideo_Implementation : public WVideo::Implementation { public: FF_WVideo_Implementation(WVideo& wvideo) : WVideo::Implementation(wvideo) { const bool ldebug = getenv_bool(""FF_DEBUG""); assertx(supported()); const string& filename = _wvideo._filename; Video::Attrib& attrib = _wvideo._attrib; const Vec2 sdims = _wvideo.spatial_dims(); string sfilecontainer = """"; // default is to infer container format based on filename extension // ffmpeg -hide_banner -formats { assertx(filename!=""-""); // WVideo::WVideo() should have created TmpFile if writing to stdout. // (Note that ffmpeg -f mp4 is not supported over pipe because it requires a seekable output; // without -f, it actually uses avi as a default container, which doesn't match the mp4 file suffix.) // At some point I managed to get Win7 Windows Media Player to play some type of file by creating an avi // container with a file suffix of mp4. Not good for the long term. // if (attrib.suffix==""mp4"") sfilecontainer = "" -f avi""; // Setting container should be unnecessary because it is derived automatically based on file suffix. } string ipixfmt = _wvideo._use_nv12 ? ""nv12"" : ""rgba""; // was rgb24 string str_audio = "" -an""; // default no audio string ocodec = """"; string opixfmt = ""yuv420p""; // ffmpeg -hide_banner -codecs | grep '^..E' // ffmpeg -hide_banner -encoders // hevc : H.265 (libx265) // webp : WebP (libwebp) // (e=mp4; ffmpeg -hide_banner -i ~/data/video/fewpalms.mp4 -y v.$e && ffmpeg -hide_banner -i v.$e -an -vn) // Default encoders chosen by ffmpeg based on file suffix: // mp4: h264 (High) (avc1 / 0x31637661), yuv420p // mov: h264 (High) (avc1 / 0x31637661), yuv420p // avi: mpeg4 (Simple Profile) (FMP4 / 0x34504D46), yuv420p // wmv: msmpeg4v3 (MP43 / 0x3334504D), yuv420p // (wmv2 inferior; wmv3 & vc1 encoders missing) // Note: Windows Media Player in Win7 cannot play back msmpeg4v3 4K video in real time! if (attrib.suffix==""wmv"") Warning(""FF_WVideo_Implementation uses msmpeg4v3 (not vc1) for *.wmv""); if (0 && attrib.suffix==""mp4"") ocodec = "" -vcodec h264""; if (0 && attrib.suffix==""mov"") ocodec = "" -vcodec h264""; if (attrib.suffix==""avi"") { ocodec = "" -c:v ffvhuff""; // ""effectively lossless"" opixfmt = ""yuv444p""; // lossless (not NV12 like ""yuv420p"") if (_wvideo._use_nv12) Warning(""Using NV12 to write to a *.avi Video with yuv444p encoding""); } Audio& audio = attrib.audio; if (audio.size()) { if (ldebug) SHOW(""previously"", audio.attrib().suffix); audio.attrib().suffix = ""aac""; // or ""mp3"" // Create a temporary file containing the audio encoded as aac. _tmpfile_audio = make_unique(audio.attrib().suffix); try { audio.write_file(_tmpfile_audio->filename()); str_audio = "" -i "" + _tmpfile_audio->filename() + sform("" -ab %d"", audio.attrib().bitrate); } catch (std::runtime_error& ex) { SHOW(""Failed to write audio within video"", ex.what()); } } // Note: ""-hide_banner"" unnecessary with ""-loglevel panic"" and ""-i some_input"". string scmd = (""| ffmpeg -loglevel panic -f rawvideo -vcodec rawvideo -pix_fmt "" + ipixfmt + sform("" -s %dx%d -r %g"", sdims[1], sdims[0], attrib.framerate) + "" -i -"" + str_audio + sfilecontainer + ocodec + "" -pix_fmt "" + opixfmt + sform("" -vb %d"", attrib.bitrate) + "" -y "" + quote_arg_for_shell(filename)); if (ldebug) SHOW(scmd); _pfi = make_unique(scmd); } ~FF_WVideo_Implementation() { } virtual string name() const override { return ""FF""; } void write(CMatrixView frame) override { const Vec2 sdims = _wvideo.spatial_dims(); assertx(product(sdims)); assertx(frame.dims()==sdims); if (!_wvideo._use_nv12) { if (!write_binary_raw((*_pfi)(), frame.array_view())) throw std::runtime_error(""FF_WVideo write frame failed""); } else { _frame_nv12_tmp.init(sdims); convert_Image_to_Nv12(frame, _frame_nv12_tmp); return write_nv12(_frame_nv12_tmp); } } void write_nv12(CNv12View nv12v) override { const Vec2 sdims = _wvideo.spatial_dims(); assertx(product(sdims)); assertx(nv12v.get_Y().dims()==sdims); if (_wvideo._use_nv12) { assertx(write_binary_raw((*_pfi)(), nv12v.get_Y().array_view())); assertx(write_binary_raw((*_pfi)(), nv12v.get_UV().array_view())); } else { _frame_rgb_tmp.init(sdims); convert_Nv12_to_Image(nv12v, _frame_rgb_tmp); write(_frame_rgb_tmp); } } static bool supported() { return ffmpeg_command_exists(); } private: unique_ptr _tmpfile_audio; // lifespan should be longer than _pfi unique_ptr _pfi; Nv12 _frame_nv12_tmp; Matrix _frame_rgb_tmp; }; #endif // defined(HH_VIDEO_HAVE_FFMPEG) //---------------------------------------------------------------------------- unique_ptr RVideo::Implementation::make(RVideo& rvideo) { // Notes: // - Win7 Media Foundation: For some mp4 files, e.g. ~/data/video/fewpalms.mp4, bitrate is read as 0. // e.g.: RVIDEO_IMPLEMENTATION=MF Filtervideo ~/data/video/fewpalms.mp4 -stat string implementation = getenv_string(""RVIDEO_IMPLEMENTATION""); if (implementation=="""") implementation = getenv_string(""VIDEO_IMPLEMENTATION""); if (implementation==""MF"") return make_unique(rvideo); if (implementation==""FF"") return make_unique(rvideo); if (implementation!="""") throw std::runtime_error(""RVideo implementation '"" + implementation + ""' not recognized""); if (FF_RVideo_Implementation::supported()) return make_unique(rvideo); if (MF_RVideo_Implementation::supported()) return make_unique(rvideo); throw std::runtime_error(""Video I/O not implemented""); } unique_ptr WVideo::Implementation::make(WVideo& wvideo) { // Notes: // - Win7 Media Foundation: I can set large bitrate on mp4, but do not see increase in file size. // e.g.: VIDEO_IMPLEMENTATION=MF Filtervideo ~/data/video/fewpalms.mp4 -info -bitrate 32.84m -info -to mp4 | Filtervideo -stat // - ffmpeg: cannot write *.wmv using VC1 codec (instead resorts to msmpeg4v3). string implementation = getenv_string(""WVIDEO_IMPLEMENTATION""); if (implementation=="""") implementation = getenv_string(""VIDEO_IMPLEMENTATION""); if (implementation==""MF"") return make_unique(wvideo); if (implementation==""FF"") return make_unique(wvideo); if (implementation!="""") throw std::runtime_error(""WVideo implementation '"" + implementation + ""' not recognized""); // Prefer ffmpeg, but revert to Windows Media Foundation (if available) for *.wmv output (using VC1 encoder). if (wvideo._attrib.suffix==""wmv"" && MF_WVideo_Implementation::supported()) return make_unique(wvideo); if (FF_WVideo_Implementation::supported()) return make_unique(wvideo); if (MF_WVideo_Implementation::supported()) return make_unique(wvideo); throw std::runtime_error(""Video I/O not implemented""); } } // namespace hh ",16299,True,3074.5607627329045,median "= jbang - Unleash the power of Java :idprefix: :idseparator: - ifndef::env-github[] :toc: left :icons: font endif::[] ifdef::env-github[] :toc: macro :caution-caption: :fire: :important-caption: :exclamation: :note-caption: :paperclip: :tip-caption: :bulb: :warning-caption: :warning: endif::[] image:https://img.shields.io/github/release/jbangdev/jbang.svg[Release,link=https://github.com/jbangdev/jbang/releases] image:https://github.com/jbangdev/jbang/workflows/ci-build/badge.svg[Build Status,link=https://github.com/jbangdev/jbang/actions] image:https://www.eclipse.org/che/contribute.svg[Che, link=https://che.openshift.io/f?url=https://github.com/jbangdev/jbang] image:https://img.shields.io/badge/Gitpod-Workspace-blue?logo=gitpodp[Gitpod, link=https://gitpod.io/#https://github.com/jbangdev/jbang] image:https://badges.gitter.im/jbangdev/community.svg[Gitter, link=https://gitter.im/jbangdev/community] image:images/jbang_logo.svg[JBang Logo, title=""JBang Logo""] == Intro Want to learn, explore or use Java instantly without setup ? Do you like Java but use python, groovy, kotlin or similar languages for scripts, experimentation and exploration ? Ever wanted to just be able to run java from anywhere without any or very minimal setup ? Ever tried out Java 11+ support for running `.java` files directly in your shell but felt it was a bit too cumbersome ? Then try `jbang` which lets you do this: image:https://asciinema.org/a/4AiobRxUwPUPztCtrDYcmoKjs.svg[link=https://asciinema.org/a/4AiobRxUwPUPztCtrDYcmoKjs?autoplay=true&theme=solarized-dark] [source, bash] ---- $ jbang init --template=cli hello.java $ jbang hello.java Max! [jbang] Resolving dependencies... [jbang] Resolving info.picocli:picocli:4.5.0...Done [jbang] Dependencies resolved [jbang] Building jar... Hello Max! $ jbang hello.java -h Usage: hello [-hV] hello made with jbang The greeting to print -h, --help Show this help message and exit. -V, --version Print version information and exit. ---- Instant cli app generated built using java and picocli as a dependency that was fetched as needed for the compilation and execution. JBang goes beyond more than just easy scripting; you can use `jbang` to launch any kind of java application or library packaged as a jar available locally, via http/https download or in a Maven repository. toc::[] == Features * `.java` Scripting for Java 8 and upwards * `.jsh` via JShell from Java 9 and upwards * Works on icon:windows[] Windows, icon:apple[] OSX and icon:linux[] Linux * Install using curl, power shell, SDKMan (icon:apple[]/icon:linux[]), Homebrew (icon:apple[]), Chocolatey (icon:windows[]) or Scoop (icon:windows[]) * Installation of scripts to user `PATH` Include multiple files and sources * Dependency declarations using `//DEPS ` for automatic dependency resolution * Control compile and runtime options with `//JAVAC_OPTIONS ` and `//JAVA_OPTIONS ` * Compiled jar and Dependency resolution caching * native-image generation (`--native`) * Launch with debug enabled for instant debugging from your favorite IDE * Transparent launch of JavaFX Applications on Java 8 and higher * Can be used for writing plugins to other cli's like `kubectl` * Init templates to get started easily (`jbang init -t cli hello.java`) * Generate gradle and IDE config with dependencies for easy editing in your favorite IDE (`jbang edit myfile.java`) To use it install `jbang` and run `jbang yourscript.java` == Requirements Tested and verified to use on OSX, Linux and Windows (incl. command.exe, cygwin and mingw shells). == Installation To use `jbang` Java 8 is the minimum required version, however Java 11 or higher is recommended. Note: `jbang` will download and install `java` from Adopt OpenJDK if no `java` is available. Once you have installed from one of the below approaches it is recommended you run `jbang app setup` to have it setup your `PATH` to include jbang app scripts + it will on operating systems that supports it setup a `j!` alias you can use instead of `jbang`. === SDKMan icon:linux[] / icon:apple[] To install both java and `jbang` we recommend https://sdkman.io[sdkman] on Linux and OSX. [source, bash] ---- curl -s ""https://get.sdkman.io"" | bash # <.> source ~/.bash_profile # <.> sdk install java # <.> ---- Once Java is installed and ready, you install `jbang` with [source, bash] ---- sdk install jbang ---- To test your installation run: [source, bash] ---- jbang --help ---- This should print out usage information. To update run: [source] ---- sdk update jbang ---- === Chocolatey icon:windows[] On Windows you can install both `java` and jbang` with https://chocolatey.org[Chocolatey]. From a command prompt with enough rights to install with choco: choco install jdk11 Once Java in installed run: choco install jbang To upgrade to latest version: choco upgrade jbang The latest package will be published to https://chocolatey.org/packages/jbang[jbang choco package page], it might be a bit delayed as the review is still manual. In case the default version is not the latest you can see the https://chocolatey.org/packages/jbang/#versionhistory[version list] and install specific version using: choco install jbang --version= === Scoop icon:windows[] On Windows you can also install `jbang` with https://scoop.sh[Scoop]. [source, bash] ---- scoop bucket add jbangdev https://github.com/jbangdev/scoop-bucket scoop install jbang ---- To upgrade to latest version: scoop update jbang === Homebrew icon:apple[] On OSX you can install 'java' and `jbang` with https://brew.sh[Homebrew] using custom taps. To install Java 11: [source, bash] ---- brew tap AdoptOpenJDK/openjdk brew cask install adoptopenjdk11 ---- Once Java is installed you can use brew with https://github.com/jbangdev/homebrew-tap/[jbangdev/tap] to get `jbang`: brew install jbangdev/tap/jbang To upgrade to latest version: brew upgrade jbangdev/tap/jbang === (Experimental) Linux packages icon:linux[] WARNING: These builds are not fully automated yet thus might be slightly behind. You can install rpm packages from https://copr.fedorainfracloud.org/coprs/maxandersen/jbang/[Fedora Copr] by doing the following: [source] ---- dnf copr enable maxandersen/jbang dnf install jbang ---- The COPR currently includes builds from various versions of CentOS, Fedora, Mageia and OpenSuse. === Docker / GitHub Action icon:docker[] You can run `jbang` via Docker: [source, bash] ---- docker run -v `pwd`:/ws --workdir=/ws jbangdev/jbang-action helloworld.java ---- or if you prefer using Quay.io: [source, bash] ---- docker run -v `pwd`:/ws --workdir=/ws quay.io/jbangdev/jbang-action helloworld.java ---- The same container images can be used with GitHub Actions, see https://github.com/jbangdev/jbang-action[jbang-action] for details. === Manual install Unzip the https://github.com/jbangdev/jbang/releases/latest[latest binary release], add the `jbang-/bin` folder to your `$PATH` and you are set. === Wrapper install If you would like to have `jbang` available in a local directory and committed into a source code repository (akin to Maven and Gradle wrappers) you can use the `jbang wrapper` command. If you have `jbang` already installed you call `jbang wrapper install` in a folder to install a local `jbang` that will run out of that directory using `./jbang`. The `./.jbang` directory which `jbang wrapper install` creates is just a cache which you typically would not commit to a source code repository, so you can e.g. `echo .jbang/ >>.gitignore`. === ""Zero"" Install If you want to try out jbang without a package manager or similar you can run the following to download jbang in `~/.jbang` and if necessary `java`. Linux/OSX/Windows Bash: [source, bash] ---- curl -Ls https://sh.jbang.dev | bash -s - ---- For example `curl -Ls https://sh.jbang.dev | bash -s - properties@jbangdev` Windows Powershell: [source, powershell] ---- iex ""& { $(iwr -useb https://ps.jbang.dev) } "" ---- For example `iex ""& { $(iwr -useb https://ps.jbang.dev) } properties@jbangdev""` == Usage A script is just a single `.java` file with a classic static main method or a `.jsh` file which will be passed to `jshell`. Below is an (almost) minimal example you can save in `helloworld.java` or simply run `jbang init helloworld.java`: [source,java] ---- ///usr/bin/env jbang ""$0"" ""$@"" ; exit $? # <.> class helloworld { // <.> public static void main(String[] args) { if(args.length==0) { System.out.println(""Hello World!""); } else { System.out.println(""Hello "" + args[0]); } } } ---- <.> By using this `//` style instead of shebang `#!` you trick `bash`, `zsh` etc. to run this as a script while still being valid java code. <.> A classname, can be anything when using `jbang` but to be valid java for most IDEs you'll want to name it the same as the source file. Now to run this you can call it via `jbang`: [source] ---- jbang helloworld.java ---- or if on Linux/OSX run it directly. If you created it manually you need to mark it as executable before running it. [source] ---- chmod +x helloworld.java ./helloworld.java jbang! ---- [WARNING] ==== When no <> is available in the PATH, JDK 11 will be downloaded by default to bootstrap jbang. If your script requires a higher version and you don' want to download two JDK's, you can define an alternative default with `JBANG_DEFAULT_JAVA_VERSION` env variable. $ JBANG_DEFAULT_JAVA_VERSION=14 jbang my-script.java Note that if JDK is found in the PATH, `JBANG_DEFAULT_JAVA_VERSION` will be ignored. ==== === Default application If you pass a directory or a url ending in `/` jbang will look for `main.java` to run as default application for that directory / location. === URLs from Trusted Sources You can use `http(s):/` and `file:/` url's for input:. [source] ---- jbang https://gist.github.com/maxandersen/f43b4c52dfcfc42dcd59a04e49acf6ec ---- For safety reasons jbang will not run arbitrary urls before you indicated you trust their source. Thus when running the above for the first time you will see the following warning about the url not being a trusted source: [source,bash] ---- jbang https://gist.github.com/maxandersen/f43b4c52dfcfc42dcd59a04e49acf6ec [jbang] https://gist.github.com/maxandersen/f43b4c52dfcfc42dcd59a04e49acf6ec is not from a trusted source thus not running it automatically. If you trust the url to be safe to run you can do one of the following: 0) Trust once: Add no trust, just run this time 1) Trust this url in future: jbang trust add https://gist.github.com/maxandersen/ Any other response will result in exit. [jbang] Type in your choice (0 or 1) and hit enter. Times out after 10 seconds. ---- You can then choose 0 to run once or 1 to trust the suggested url. If you don't answer within 10 seconds jbang will exit. To enable running it without such question you need to mark that url or a sub part of it as a trusted source. i.e. `jbang trust add https://github.com/maxandersen/` will tell `jbang` to trust anything with that base url. You can see more in the comments of the `~/.jbang/trusted-sources.json`. [TIP] ==== Sites such as GitHub, gitlab, bitbucket, gist, carbon.now.sh jbang will try and extract the proper source rather than the raw html. i.e. doing `jbang https://carbon.now.sh/ae51bf967c98f31a13cba976903030d5 carbon!` is possible. ==== [TIP] ==== URL's will follow redirects. In case you need to use it with sites with self-signed/non-trusted certificates you can if you trust the site use `--insecure`. ==== === Build and run native image (Experimental) There is support for using `native-image` from GraalVM project to produce a binary executable. Since not all java libraries can automatically be built with `native-image` - especially if using reflection feature are considered highly experimental. Just run `jbang --native helloworld.java` and `jbang` will use `native-image` from either `$JAVA_HOME/bin` or `$GRAALVM_HOME/bin` or `$PATH` to produce a native image binary. You can install the `native-image` utility binary e.g. by installing GraalVM from https://www.graalvm.org/downloads, and then once running `gu install native-image` as per https://www.graalvm.org/reference-manual/native-image. [TIP] ==== If you use `--native` with picocli remember to add `info.picocli:picocli-codegen` as that will ensure it will actually work with `native-image`. ==== === Using `.jsh` for `jshell` There is support to run `.jsh` via `jshell`. The advantage of `jshell` is that you do not need to have a class or static main method. Classic `jshell` does not support passing in arguments nor system properties, `jbang` does. In the case of `.jsh` files `jbang` injects a startup script that declares a `String[] args` which will contain any passed in arguments, and it sets any properties passed in as `-Dkey=value` as parameters to `jbang`. That means you can run a script as `jbang -Dkey=value World helloworld.jsh` and retrieve arguments and properties as: [source,java] ---- System.out.println(""Hello "" + (args.length>0?args[0]:""World"")); // <.> System.out.println(System.getProperty(""key"")); // <.> ---- <.> Line where `args` are accessible without previous declaration. <.> System properties set when passed as `-D` arguments to `jbang` The script will have the output: Hello World value Please note that `.jsh` files are source only, they are not compiled thus they are https://github.com/jbangdev/jbang/issues/506[not cached] nor can they be https://github.com/jbangdev/jbang/issues/510[built as native images]. ==== Running script from standard input jbang can run scripts directly from standard input using `-` or `/dev/stdin` as input. i.e. `echo 'System.out.println(""Hello World!"");' | jbang -` [TIP] ==== If you use `--interactive` `jbang` will let `jshell` enter into interactive/REPL mode. You can write `/exit` to leave this mode. ==== [TIP] ==== If your own code needs to handle chained pipes well it is recommended to add the following code: [source,java] ---- import sun.misc.Signal; if (!""Windows"".equals(System.getProperty(""os.name""))) { Signal.handle(new Signal(""PIPE""), (final Signal sig) -> System.exit(1)); } ---- It will give a compiler warning as it is internal API; but for now it works. ==== === Running ``.jar``'s `jbang` will also run `.jar` files directly. i.e. `jbang helloworld.jar` will run `helloworld.jar` if found on your local file system. The `.jar` can be a local file or a http/https url. You can also run a `.jar` file referenced by a Maven coordinate, i.e.: jbang info.picocli:picocli-codegen:4.5.0 This will fetch the dependency stated and put the transitive dependencies on the class-path. If you need to specify a main class you can do so by using `--main` i.e. jbang --main picocli.codegen.aot.graalvm.ReflectionConfigGenerator info.picocli:picocli-codegen:4.5.0 [TIP] ==== A side effect of running GAV as a jar, the GAV could also be a `.java` or `.jsh` file and it would be launched as a script instead of a jar. No one would want to do that (right?) but now you know. ==== == Init templates To get started you can run `jbang init helloworld.java` and a simple java class with a static main is generated. Using `jbang init --template=cli helloworld.java` you get a more complete Hello World CLI using https://picocli.info/[picocli] as dependency. == Declare dependencies If you want to write real scripts you will want to use some java libraries. To specify dependencies you use gradle-style locators or links to Git sources. Below are examples for `log4j`. === Using `//DEPS` [source,java] ---- ///usr/bin/env jbang ""$0"" ""$@"" ; exit $? // <.> //DEPS log4j:log4j:1.2.17 import static java.lang.System.out; import org.apache.log4j.Logger; import org.apache.log4j.BasicConfigurator; import java.util.Arrays; class classpath_example { static final Logger logger = Logger.getLogger(classpath_example.class); public static void main(String[] args) { BasicConfigurator.configure(); // <.> logger.info(""Welcome to jbang""); Arrays.asList(args).forEach(arg -> logger.warn(""arg: "" + arg)); logger.info(""Hello from Java!""); } } ---- <.> `//DEPS` must be placed at the start of line and can be one or more space separated dependencies. <.> Minimal logging setup - required by log4j. Now when you run this, the first time with no existing dependencies installed you should get an output like this: [source] ---- $ ./classpath_example.java [jbang] Resolving dependencies... [jbang] Resolving log4j:log4j:1.2.17...Done [jbang] Dependencies resolved 0 [main] INFO classpath_example - Welcome to jbang 1 [main] INFO classpath_example - Hello from Java! ---- === Using links to Git sources Instead of gradle-style locators you can also use URLs to projects on GitHub, GitLab or BitBucket. Links to those projects will then be converted to artifacts references on https://jitpack.io/[jitpack]. You can use links to the root of the project, to the root of a tag/release and to specific commits. If the project you link to has multiple modules and you want only a specific module you can specify the name of the module by appending `#name-of-module` to the URL. And finally if the link you provide is to a specific branch of the project then you need to append `#:SNAPSHOT` to the URL. (If you have both a branch and a module name then use `#name-of-module:SNAPSHOT`) .Examples of links and their resulting locator: |=== |Link | Locator |https://github.com/jbangdev/jbang |com.github.jbangdev:jbang:HEAD-SNAPSHOT |https://github.com/jbangdev/jbang/tree/v1.2.3 |com.github.jbangdev:jbang:v1.2.3 |https://github.com/jbangdev/jbang/tree/f1f34b031d2163e0cdc6f9a3725b59f47129c923[https://github.com/jbangdev/jbang/tree/f1f34b031...] |com.github.jbangdev:jbang:f1f34b031d |https://github.com/jbangdev/jbang#mymodule |com.github.jbangdev.jbang:mymodule:HEAD-SNAPSHOT |https://github.com/jbangdev/jbang/tree/mybranch#:SNAPSHOT |com.github.jbangdev:jbang:mybranch-SNAPSHOT |https://github.com/jbangdev/jbang/tree/mybranch#mymodule:SNAPSHOT |com.github.jbangdev.jbang.mymodule:mybranch-SNAPSHOT |=== === Offline mode In case you prefer `jbang` to just fail-fast when dependencies cannot be found locally you can run `jbang` in offline mode using `jbang -o` or `jbang --offline`. In this mode `jbang` will simply fail if dependencies have not been cached already. === Repositories By default `jbang` uses https://jcenter.bintray.com/[jcenter] as its repository as it is a superset of Maven Central and supposedly should be faster. And if you are using the above mentioned URL dependencies https://jitpack.io[jitpack] will be added automatically as well. If that is not sufficient for you or need some custom repo you can use `//REPOS id=repourl` to state which repository URL to use. For ease of use there are also a few shorthands to use popular commonly available repositories. |=== |Short name | Description |`mavencentral` |Maven Central |`jcenter` |`https://jcenter.bintray.com/` |`google` |`https://maven.google.com/` |`jitpack` |`https://jitpack.io/` |=== Following example enables use of Maven Central and add a custom `acme` repository. [source,java] ---- //REPOS mavenCentral,acme=https://maven.acme.local/maven ---- [WARNING] ==== If you add any `//REPOS` lines `jbang` will no longer consult `jcenter` thus you need to explicitly add it if needed. ==== [TIP] ==== For secure authentication `jbang` will honor `~/.m2/settings-security.xml` for configuring username/passwords. ==== === Using `@Grab` There is also support for using Groovy lang style `@Grab` syntax. [source,java] ---- ///usr/bin/env jbang ""$0"" ""$@"" ; exit $? import static java.lang.System.out; import org.apache.log4j.Logger; import org.apache.log4j.BasicConfigurator; import java.util.Arrays; import groovy.lang.Grab; // <.> import groovy.lang.Grapes; import groovy.lang.GrabResolver; @GrabResolver(""mavenCentral"") // <.> @GrabResolver(name='acme', root='https://maven.acme.local/maven') @Grapes({ // <.> @Grab(group=""org.codehaus.groovy"", module=""groovy"", version=""2.5.8""), // <.> @Grab(module = ""log4j"", group = ""log4j"", version = ""1.2.17"") }) class classpath_example { static final Logger logger = Logger.getLogger(classpath_example.class); public static void main(String[] args) { BasicConfigurator.configure(); Arrays.asList(args).forEach(arg -> out.println(arg)); } } ---- <.> Import needed to make the compiler be okey with `@Grab` annotation. <.> Using `GrabResolver` to enable `mavenCentral` and custom `acme` repository <.> In Groovy you normally put `@Grab` on import statements. That is not allowed in Java thus when having multiple imports you need to put them in a `@Grapes` annotation first. <.> `jbang` will grab any `@Grab` annotation and assume it is declaring dependencies. === System properties and Environment variables In dependencies you can refer to environment and system properties to parameterize the dependencies. It uses the format `${[env.]propertyname:}`. Furthermore to align with properties commonly used to make dependency resolution portable `jbang` exposes properties similar to what the `https://github.com/trustin/os-maven-plugin[os-maven-plugin]` does. Plus for ease of use for javafx dependencies it also setups a property named `${os.detected.jfxname}`. Examples: [source,bash] ---- ${env.USER} = 'max' ${os.name} = 'Mac OS X' ${non.existing.key:empty} = 'empty' ${os.detected.jfxname} = 'mac' ---- This can be put to use in `//DEPS` like so: //DEPS org.openjfx:javafx-graphics:11.0.2:${os.detected.jfxname} Here we use the properties to avoid hardcoding your script to a specific operating system. === JavaFX If `jbang` detects you have a `javafx-` dependency in your list of dependencies it will if you `java` command supports Java modules automatically set the necessary `--module-path` and `--add-modules`. See `link:examples/jfx.java[]` and `link:examples/jfxtiles.java[]` for examples of this. == Multiple source files It is possible to use multiple source files just by having the files in the same source directory, it will even work for a limited extent with packages. For example the example below works by just calling `jbang Main.java`: .Main.java [source,java] ---- import model.Person; public class Main { public static void main(String... args) { Person p = new Person(args[0]); System.out.println(""Hello "" + p.getName()); } } ---- .model/Person.java [source,java] ---- package model; public class Person { String name; public String getName() { return name; } public Person(String n) { this.name = n; } } ---- There are some cases where the above does not work; i.e. if two packages refer to each other - i.e. `model.Person` referring to `util.Generator` will fail. Also `jbang edit` does not know about multiple sources as it runs and must run before compilation occurs. Thus version 0.46 there is now support for having that all work with multiple source files. The main script file defines all the dependencies and you add more source files into the application using `//SOURCES `. If included source has `//SOURCES` that will also get included recursively. The listed file name(s) gets added to source list when compiling. Currently there are not `*.java` style matching or support for these `.java` files to declare `//DEPS` or other jbang configuration. That will currently only be honored by the main script/app. These will be loosened up in future based on feedback. == Adding more resources If you want to add a `META-INF/application.properties` or `META-INF/resource.index.html` or other files to the generated jar you can use `//FILES` to add them. The format is `//FILES [=]`. Example: //FILES resource.properties //FILES META-INF/resources/index.html=index.html Here `resource.properties` will be copied as is and `META-INF/resources/index.html` gets its content from `index.html`. All locations are relative to the script location. WARNING: Currently `jbang edit` and http(s) based script do not work with `//FILES`. Will be added later. == Extension-less/non-java files for cli-plugins You can use `jbang` to write plugins for cli's like `kubectl`, `git`, etc. They expect their plugins to be named like `-`, i.e. `kubectl-myplugin`. Furthermore some of them, particularly `kubectl` currently require the file to start with `#!` otherwise you get a `exec format error`. There are two ways to have that work. The first recommended way is to use `jbang app install` which setups an intermediate script to avoid the issue, i.e. `jbang app install --name kubectl-my-plugin myplugin.java`. The second is to use a bit of auto-magic `jbang` has to help in case you only want a single file, no intermediate script. That is described below. === Kebab casing of filename `jbang` lets you name your file without a `.java` or `.jsh` extension, such as `kubectl-my-plugin` or `myjavascript.sh`. `jbang` will in this case copy the file to a temporary directory using kebab-case to map the name to a proper java class name. For example, if you make a file called `kubectl-my-plugin` then `jbang` will assume the actual class name to launch to be `KubectlMyPlugin`. Note, similar is done when using `jbang edit`, here the symbolic link will be made so the IDE will treat it as regular camel cased java class. NOTE: If you do not follow this naming pattern you will get a compile error as `javac` expects both the public class and file names to be equal. === she-bang auto-stripped For extension less scripts, you can put `#!' header at the beginning to let apps recognize it is to be treated as a script. To avoid issues when compiling, `jbang` will remove that line before compilation. For now this is required for `kubectl` plugin but not `git`. https://github.com/kubernetes/kubectl/issues/822[Issue opened] on this limitation. == Java version `jbang` will by default use `JAVA_HOME` and if not available, check the `PATH` to locate the `java` executable to run the script with. If your script requires a specific or minimal version of Java you can use `//JAVA (+)`. If Jbang finds a java executable using `JAVA_HOME` or `PATH` which satisfies the stated java version jbang will use it. If no such version is found it will automatically download and install it. Examples: `//JAVA 11` will force use of Java 11. + `//JAVA 13+` will require at least java 13. Java 13 or higher will be used. In case no matching `java` is found `jbang` will fail. You can always force running with specific version of `java` using `--java` command line option, i.e. `jbang --java 8 hello.java` == Managing JDKs In the previous section it was mentioned that Jbang will automatically download and install JDKs when necessary. You can use the `jdk` command to manage JDKs, for example you can run the following: jbang jdk list which will list all the JDKs that are currently installed by Jbang. It's easy to `install` additional JDKs by running: jbang jdk install 14 which will download and install JDK version 14 into Jbang's cache (`~/.jbang/cache/jdks` by default). The list of versions that are available for installation can be found here: https://adoptopenjdk.net/releases.html The first JDK that gets installed by Jbang will be set as the ""default"" JDK. This is from then on the JDK that will be used by Jbang if no Java could be found on the system (meaning `javac` wasn't found on the `PATH` and no `JAVA_HOME` is set). You can change the default JDK by running: jbang jdk default 12 Running it without an argument will return the version of the JDK that is currently set as the default. NOTE: On Windows you might need elevated privileges to create symbolic links. If you don't have permissions then running the above command will result in an error. To use it https://stackoverflow.com/a/24353758[enable symbolic links] for your user or run your shell/terminal as administrator to have this feature working. When you `uninstall` a JDK by running: jbang jdk uninstall 12 and that JDK was set as the default, Jbang will set the next higher version JDK as the default. If no higher version is available it will select the next lower version. === Using managed JDKs yourself Given the fact that Jbang is able to easily download and install JDKs we thought that it might be a good option for our users to be able to access those JDKs for their own use instead of having to install yet another version themselves. To make that easy we added a couple of useful commands. The first can be used to set retrieve to location where the JDK is installed: jbang jdk home This will return the path to the ""default"" JDK (by default `~/.jbang/currentjdk)`, if you want to know the location of a specific JDK you can pass the version as an argument: `jbang jdk home 14`. This command could be used by scripts to find a JDK to use to run a Java program for example (eg: `JAVA_HOME=$(jbang jdk home)`. For setting up your current command line environment there's something simpler. You can run: jbang jdk java-env On Linux and Mac this will output something like: [source] ---- export PATH=""/home/user/.jbang/currentjdk/bin:$PATH"" export JAVA_HOME=""/home/user/.jbang/currentjdk"" # Run this command to configure your shell: # eval $(jbang jdk java-env) ---- And the output itself shows how to properly use it to configure your command line to use the JDK. In this case it's by running: eval $(jbang jdk java-env) To do this by default for all shells you start simply add the above line to your `~/.bashrc` file. Unfortunately on Windows using CMD things are not as easy as is show by the output of `jbang jdk java-env` on that platform: [source] ---- set PATH=C:\\Users\\user\\.jbang\\currentjdk\\bin;%PATH% set JAVA_HOME=C:\\Users\\user\\.jbang\\currentjdk rem Copy & paste the above commands in your CMD window or add rem them to your Environment Variables in the System Settings. ---- Instead of copying and pasting lines you could also redirect the output to a .bat file and execute that instead: > jbang jdk java-env > setenv.bat > setenv == Editing You can edit your script in your IDE by using `jbang edit helloworld.java`. This will generate a project in a temporary location with symbolic links to your script and output the generated folder name. The easiest way to use that is to use it in a call to your IDE: [source, bash] ---- code `jbang edit helloworld.java` ---- If you add further dependencies to your file just re-run the edit command and the relevant files will be regenerated with the updated dependencies. Above does require using a shell that allows for variable evaluation, if you are on i.e. Windows then you might prefer using: [source, bash] ---- jbang edit --open=[editor] helloworld.java ---- The editor used will be what is specified as the argument to `--open` or default to `$JBANG_EDITOR`, `$VISUAL` or `$EDITOR` in that order. NOTE: On Windows you might need elevated privileges to create symbolic links. If you don't have permissions then the `edit` option will result in an error. To use it https://stackoverflow.com/a/24353758[enable symbolic links] for your user or run your shell/terminal as administrator to have this feature working. === Live Editing You can also use `jbang edit --live` and `jbang` will launch your editor while watching for file changes and regenerate the temporary project to pick up changes in dependencies. === IDE and Editor support The `edit` feature been tested with the following IDE's: :sicons: https://simpleicons.org/icons .IDE's and Editors tested with `jbang` [width=75%,frame=none,grid=none] |=== |image:{sicons}/visualstudiocode.svg[50,50] https://code.visualstudio.com[Visual Studio Code] |image:{sicons}/eclipseide.svg[50,50] https://www.eclipse.org/downloads/download.php[Eclipse] |image:{sicons}/intellijidea.svg[50,50] https://www.jetbrains.com/idea/download[IntelliJ Idea] |image:{sicons}/apachenetbeanside.svg[50,50] https://netbeans.apache.org/download/[Apache NetBeans] |image:{sicons}/neovim.svg[50,50] https://github.com/neovim/neovim/wiki/Installing-Neovim[Neovim] w/ https://spacevim.org/use-vim-as-a-java-ide/[spacevim Java] |image:{sicons}/gnuemacs.svg[50,50] https://www.gnu.org/software/emacs/[Emacs] w/ https://www.spacemacs.org[Spacemacs Java] |=== The `edit` feature works with various IDE's - it generates a `build.gradle` to use with IDE's that understands Gradle directly. For speed and consistency `jbang` also generates IDE specific settings. Currently launchers and project files are generated for Eclipse and vscode. Intellij just reads `build.gradle` for now thus to run/debug you will need to manually set it up. == Debugging When running `.java` scripts with `jbang` you can pass the `--debug`-flag and the script will enable debug, suspend the execution and wait until you connect a debugger to port 4004. [source, bash] ---- jbang --debug helloworld.java Listening for transport dt_socket at address: 4004 ---- You can change the debug port and host by passing in a interface pattern and number to the debug argument, e.g., `--debug=*:4321`. This will make it use port 4321 and make it listen on all ('*') network interfaces. NOTE: Be sure to put a breakpoint in your IDE/debugger before you connect to make the debugger actually stop when you need it. === Debug jbang itself Java itself will add `JAVA_TOOL_OPTIONS` which will apply to `jbang` too. For finer and more explicit control the scripts, `jbang` will add `JBANG_JAVA_OPTIONS` to the call to `jbang` itself. Thus if you want to enable debug or other details for `jbang` set that environment variable. == Flight Recorder Flight recorder is a feature of the Java VM that lets you gather diagnostic and profiling data about your script. You can use `//JAVA_OPTIONS` to have full control over it; but for the easiest setup `jbang` lets you just run with `--jfr`, e.g., jbang --jfr myapp.java By default `--jfr` will start flight recorder and tell it to dump event recordings to `myapp.jfr` (i.e. using base name of the script as its filename). Then you can use tools like `jvisualvm` or `jmc` to explore the data. If you want to tweak the configuration you can pass flight recorder options, like `jbang --jfr=filename={baseName}.jfr,maxage=24h` where `{baseName}` will be replaced by the filename and then added `maxage=24h` to flight recording options. If you want further control use `//JAVAC_OPTS -XX:StartFlightRecording=` instead. == `java` and `javac` Options If you want to tweak memory settings or enable preview features you can setup the necessary options using `//JAVA_OPTS` and `//COMPILER_OPTS` as in the following example using Java 14 experimental `record` feature: [source, java] ---- ///usr/bin/env jbang ""$0"" ""$@"" ; exit $? //JAVAC_OPTIONS --enable-preview -source 14 <.> //JAVA_OPTIONS --enable-preview // <.> import static java.lang.System.*; public class records { record Point(int x, int y) {} public static void main(String[] args) { var p = new Point(2,4); out.println(p); } } ---- Since Java 9 https://docs.oracle.com/javase/9/tools/java.htm#GUID-3B1CE181-CD30-4178-9602-230B800D4FAE__USINGTHEJDK_JAVA_OPTIONSLAUNCHERENV-F3C0E3BA[JDK_JAVA_OPTIONS] and https://docs.oracle.com/javase/9/tools/javac.htm#GUID-AEEC9F07-CB49-4E96-8BC7-BCC2C7F725C9\\_\\_USINGJDK_JAVAC_OPTIONSENVIRONMENTVA-F3C76845[JDK_JAVAC_OPTIONS] are also picked up by the Java runtime and compiler automatically. For Java 8 and if you want to set explicitly only for `jbang` you can also add flags by setting `JBANG_JAVA_OPTIONS` and `JBANG_JAVAC_OPTIONS` respectively. === (Experimental) Application Class Data Sharing If your scripts uses a lot of classes Class Data Sharing might help on your startup. The following requires Java 13+. Using `--cds` jbang will build the jar with Application Class Data Sharing enabled and when run have it load shared class data. You can put `//CDS` in the java file to enable it by default, or simply use `--cds` to force it or `--no-cds` to turn it off no matter what the jbang script file contains. == Aliases To avoid remembering long paths and to enable easy launch of jbang scripts there is an `alias` command to setup and manage aliases to actual scripts. jbang alias add hello https://github.com/jbangdev/jbang-examples/blob/master/examples/helloworld.java will add an alias named `hello` pointing to that github url which then can be run using `jbang hello`. jbang alias list will show you all the aliases that are defined locally. === Implicit Alias Catalogs The aliases you create are stored locally (see <>), but Jbang can also use remote catalogs. You can access those catalogs explicitly (see <>) but it is much easier to use what we call ""implicit catalogs"", which are aliases that have a special format and Jbang is smart enough to know where to find their definition. Examples: `jbang hello@jbangdev` will run the alias `hello` as defined in `jbang-catalog.json` found in https://github.com/jbangdev/jbang-catalog. This allows anyone to provide a set of jbang scripts defined in their github, gitlab or bitbucket repositories. The full format is `@(/repository)(/branch)(~path)` allowing you to do things like: .Implicit Catalog Examples: |==== |Command | Description |`jbang hello@acme` |`hello` alias found in `acme/jbang-catalog/jbang-catalog.json` of the default branch searched on github, gitlab and bitbucket in that order. |`jbang hello@acme/mycatalog` |`hello` found in `acme/mycatalog/jbang-catalog.json` searched on github, gitlab and bitbucket in that order. |`jbang hello@acme/mycatalog/dev` |`hello` found in `acme/mycatalog/jbang-catalog.json` in the `dev` branch searched on github, gitlab and bitbucket in that order. |`jbang hello@acme~experimental` |`hello` found in `acme/jbang-catalog/experimental/jbang-catalog.json` |==== === Local Alias Catalogs Jbang will also look in the current directory for a `jbang-catalog.json` file and if it exists it will look up any aliases in there too. In fact it will look in several places in the following order: 1. Current directory, `./jbang-catalog.json` 2. In `.jbang/jbang-catalog.json` 3. In the parent directory, `../jbang-catalog.json` 4. In the parent's `.jbang` directory, ../.jbang/jbang-catalog.json` 5. And repeating steps 3 and 4 recursively upwards to the root of the file system 6. As the last step it will look in `$HOME/.jbang/jbang-catalog.json` Jbang will use any aliases defined in those files, but on top of that it will also look at the aliases defined in any catalogs mentioned in those files as well. Aliases defined in the file have preference over aliases found in any catalogs defined in the same file. When you create aliases using `jbang alias add`, or add catalogs using `jbang catalog add` the _same_ ordering will be used to determine where to store the alias or catalog. Btw, this will only take into account _existing_ files! So if no `jbang-catalog.json` file exists in the local directory it will _not_ be created for you, but Jbang will keep looking until it finds a file to use (as a last option it will always be written to `$HOME/.jbang/jbang-catalog.json`). This means that if you want to write the alias to `jbang-catalog.json` in your local folder you will either have to create the file first (eg by running `touch jbang-catalog.json`) or by explicitly specifying the file location: jbang alias add -f jbang-catalog.json hello https://github.com/jbangdev/jbang-examples/blob/master/examples/helloworld.java Btw, the flag `--show-origin` is very useful when listing aliases to find out where exactly an alias is defined: jbang alias list --show-origin == Catalogs Catalogs are lists of Aliases as defined in the previous section, but while the `alias` command is used to manage aliases within a catalog, the `catalog` command is for managing references to catalogs. This is mostly useful when dealing with remote catalogs. You can for example add a catalog like this: jbang catalog add demo https://github.com/jbangdev/jbang-catalog/blob/master/jbang-catalog.json or simply by using the same ""implicit"" catalog system described in <>: jbang catalog add demo jbangdev The aliases in that catalog are now available by adding `@demo` to their names. For example: $ jbang alias list demo env@demo = Dump table of Environment Variables gavsearch@demo = Search search.maven.org for maven artifacts. hello@demo = Script that says hello back for each argument properties@demo = Dump table of System properties $ jbang run hello@demo World! [jbang] Building jar... Hello World! In fact it's possible to run the alias just by using `jbang run hello`, the `@demo` part is only necessary when trying to disambiguate between aliases with the same name from different catalogs. You can list the available catalogs by running: jbang catalog list NB: The output will not only show the catalogs you defined yourself but also the ones that get added implicitly when running aliases as described in the section <>. == Java Agents You can activate a javaagent using `--javaagent=[=]` where agent can be a already packaged agent jar from file, http url or Maven Coordinate. It can also be a jbang script itself where you have put `//JAVAAGENT` to activate agent packaging. You can create a basic agent using `jbang init -t agent myagent.java` to get started. == Bash/Zsh auto-completion If you are using bash or zsh in your terminal you can get auto-completion by running the following: [source, bash] ---- source <(jbang completion) ---- == Caching In previous versions of `jbang`, Java 10+ direct launch of `.java` was used, but since v0.6 `jbang` works with Java 8 and thus it needs to do a separate compile step. Besides now working with Java 8 this also allows to cache the compiled script and thus launch faster on consecutive runs. The caching goes to `~/.jbang/cache` by default, you can run `jbang cache clear` to remove all cache data from this folder. == Install apps [EXPERIMENTAL] Since version 0.56 jbang comes with ability to setup jbang to put scripts/apps into your `PATH` using `jbang app`. This is useful to easily make scripts available from anywhere on any Operating System; To get started run `jbang app setup` this will on Windows modify your system wide `PATH` to include a folder managed by jbang. On bash/zsh based shells it will setup `PATH` in your `bashrc` or `zshrc` file(s.) Once setup, you can use `jbang app install ` to install that script into the jbang managed path. i.e. `jbang app install myscript.java` will add `myscript` as a command you can run. You can also use aliases, like `jbang app install gavsearch@jbangdev`. If you have two script/apps with same name or just want to use a specific name you can use `--name` to control the generated command: `jbang app install --name mvnsearch gavsearch@jbangdev` If you want to see which are already installed use `jbang list` and you can use `jbang uinstall ` to uninstall the script/app. == Build Integration [EXPERIMENTAL] While `jbang` prepares and builds the underlying jar used for launch there is since v0.40 (for now) experimental API allowing user included dependencies to influence the generated jar and possible native image. An example use case enabled by this is to have full Quarkus integration, `jbang quarkuscode.java` will have Quarkus participate to perform its build time optimizations rather than doing it at runtime every time. It works as following: Before the jar is created `jbang` will scan the classpath for `META-INF/jbang-integration.list`. Any classes listed in this file will be loaded and jbang will expect and call the following method on these classes: [source,java] ---- /** * * @param param build dir directory which will be made into a jar when build is done * @param pomFile location of pom.xml representing the projects dependencies * @param dependencies list of GAV to Path of artifact/classpath dependencies * @param nativeImage true if --native been requested * @return Map map of returns; special keys are ""native-image"" which is a and ""files"" to * return native-image to be run and list of files to get written to the output directory. * */ Map postBuild(Path builddir, Path pomFile, List> dependencies, boolean nativeImage) ---- Still very experimental and bound to change. Example of its use can be found in https://github.com/quarkusio/quarkus/pull/11542[Quarkus]. == Cheatsheet You can get examples on running/using `jbang` using https://github.com/cheat/cheat[cheat] command with `cheat jbang`. == FAQ [qanda] Why the name j'bang?:: I was reading up on how to use the new shebang (#!) feature support in Java 10 and came up with the idea of port `kscript` to Java and needed a name. From there came j'bang which is a ""bad"" spelling of how shebang is pronounced in French. Why use gradle resource locators rather than ?:: kscript used it and it's nice as it is a one-liner and easily parsable. How does this compare to ?:: After doing `jbang` I've learned about similar projects and thought it would be nice with some comparison; + https://github.com/scijava/jgo[jgo]: an alternative way to launch jars using maven coordinates. Implemented in python, depends on Java and Maven to be available. Not really for scripting but a novel way to launch java apps already packaged as a maven dependency. + Why would I use Java to write scripts ? Java sucks for that... Use groovy, kotlin, scala, etc. instead!:: Well, does it really suck ? With Java 8 streams, static imports and greatly improved standard java libraries it is very close to what kscript and grape look like. With the following advantages: + * works with plain Java without installing additional compiler/build tools * all IDE's support editing .java files very well, content assist, etc. * great debugging + And to be honest I built `jbang` just to see if I could and get my Java skills refreshed for the newer features in the language. Use it at your own risk :) Why not use normal shebang(`#!`) in the header ?:: You can use normal shebang (`#!/usr/bin/env jbang`) and Java 10+ will actually work with it from the command line. Not recommended though as many tools and especially IDE's will start complaining about syntax errors as they don't ignore the first line in this case. + By using the `//` form it is treated as both a bash/shell file AND a valid java file and thus works everywhere a java file will work. + It's worth noting that Go https://golangcookbook.com/chapters/running/shebang/[uses a similar approach] which is also where I learned it from. HELP! My code formatter keeps breaking my `//` directives!:: When using automated code formatting tools, some care and configuration must be made to prevent the tooling from rewriting and preventing `jbang` from working as expected. + Use the following configuration blocks to correctly configure your tool: + .Configuration Tool Settings: |==== | Formatting Tool | Configuration | Clang Format a| [source] ---- CommentPragmas: '^[^ ]' ---- |==== == Thanks `jbang` was heavily inspired by how `https://github.com/holgerbrandl/kscript[kscript]` by Holger Brand works. ",12110,False,2215.7815470180544,median "grammar SwiftMtParser_MT503; @lexer::header { #include ""repository/ISwiftMtParser.h"" #include ""SwiftMtMessage.pb.h"" #include #include #include ""BaseErrorListener.h"" } @parser::header { #include ""repository/ISwiftMtParser.h"" #include ""SwiftMtMessage.pb.h"" #include #include #include ""BaseErrorListener.h"" #include ""SwiftMtParser_MT503Lexer.h"" } @parser::members { public: typedef SwiftMtParser_MT503Lexer tLexer; typedef SwiftMtParser_MT503Parser tParser; private: std::vector _errors; public: [[nodiscard]] const std::vector& errors() const { return _errors; } private: class DefaultErrorListener : public antlr4::BaseErrorListener { private: std::vector& _errors; public: explicit DefaultErrorListener(std::vector& errors) : _errors(errors) { } void syntaxError(Recognizer *recognizer, antlr4::Token * offendingSymbol, size_t line, size_t charPositionInLine, const std::string &msg, std::exception_ptr e) override { _errors.push_back(msg); } }; DefaultErrorListener _error_listener { _errors }; public: class Helper : public ISwiftMtParser { public: bool parse_message(const std::string& message, std::vector& errors, SwiftMtMessage& out_message) override { antlr4::ANTLRInputStream stream{message}; tLexer lexer{&stream}; antlr4::CommonTokenStream token_stream{&lexer}; tParser parser{&token_stream}; return parser.process(errors, out_message); } }; private: SwiftMtMessage _message_builder{}; bool process(std::vector& errors, SwiftMtMessage& out_message) { _errors.clear(); removeErrorListeners(); addErrorListener(&_error_listener); _message_builder = SwiftMtMessage{}; message(); if(!_errors.empty()) { errors.insert(errors.end(), _errors.begin(), _errors.end()); return false; } out_message = _message_builder; return true; } public: [[nodiscard]] SwiftMtMessage parsed_message() const { return _message_builder; } } message : bh ah uh? mt tr? EOF; bh : TAG_BH bh_content RBRACE ; bh_content : ~(RBRACE)+ ; ah : TAG_AH ah_content RBRACE ; ah_content : ~( RBRACE )+ ; uh : TAG_UH sys_block RBRACE ; tr : TAG_TR sys_block RBRACE ; sys_block : sys_element+ ; sys_element : LBRACE sys_element_key COLON sys_element_content RBRACE ; sys_element_key : ~( COLON | RBRACE )+ ; sys_element_content : ~( RBRACE )+ ; mt returns [message::definition::swift::mt::MessageText elem] @after { _message_builder.mutable_msg_text()->MergeFrom($elem); } : TAG_MT seq_A seq_B seq_C* seq_D? MT_END; seq_A returns [message::definition::swift::mt::Sequence elem] @init { $elem.set_tag(""A""); } : fld_16R_A { $elem.mutable_objects()->Add()->mutable_field()->MergeFrom($fld_16R_A.fld); } fld_20C_A+ { $elem.mutable_objects()->Add()->mutable_field()->MergeFrom($fld_20C_A.fld); } fld_23G_A { $elem.mutable_objects()->Add()->mutable_field()->MergeFrom($fld_23G_A.fld); } seq_A1+ { $elem.mutable_objects()->Add()->mutable_sequence()->MergeFrom($seq_A1.elem); } fld_98a_A? { $elem.mutable_objects()->Add()->mutable_field()->MergeFrom($fld_98a_A.fld); } fld_22a_A+ { $elem.mutable_objects()->Add()->mutable_field()->MergeFrom($fld_22a_A.fld); } fld_95a_A+ { $elem.mutable_objects()->Add()->mutable_field()->MergeFrom($fld_95a_A.fld); } fld_70C_A? { $elem.mutable_objects()->Add()->mutable_field()->MergeFrom($fld_70C_A.fld); } seq_A2* { $elem.mutable_objects()->Add()->mutable_sequence()->MergeFrom($seq_A2.elem); } fld_16S_A { $elem.mutable_objects()->Add()->mutable_field()->MergeFrom($fld_16S_A.fld); } ; seq_A1 returns [message::definition::swift::mt::Sequence elem] @init { $elem.set_tag(""A1""); } : fld_16R_A1 { $elem.mutable_objects()->Add()->mutable_field()->MergeFrom($fld_16R_A1.fld); } fld_22F_A1? { $elem.mutable_objects()->Add()->mutable_field()->MergeFrom($fld_22F_A1.fld); } fld_98A_A1? { $elem.mutable_objects()->Add()->mutable_field()->MergeFrom($fld_98A_A1.fld); } fld_13B_A1? { $elem.mutable_objects()->Add()->mutable_field()->MergeFrom($fld_13B_A1.fld); } fld_70C_A1? { $elem.mutable_objects()->Add()->mutable_field()->MergeFrom($fld_70C_A1.fld); } fld_16S_A1 { $elem.mutable_objects()->Add()->mutable_field()->MergeFrom($fld_16S_A1.fld); } ; seq_A2 returns [message::definition::swift::mt::Sequence elem] @init { $elem.set_tag(""A2""); } : fld_16R_A2 { $elem.mutable_objects()->Add()->mutable_field()->MergeFrom($fld_16R_A2.fld); } fld_13a_A2? { $elem.mutable_objects()->Add()->mutable_field()->MergeFrom($fld_13a_A2.fld); } fld_20C_A2 { $elem.mutable_objects()->Add()->mutable_field()->MergeFrom($fld_20C_A2.fld); } fld_16S_A2 { $elem.mutable_objects()->Add()->mutable_field()->MergeFrom($fld_16S_A2.fld); } ; seq_B returns [message::definition::swift::mt::Sequence elem] @init { $elem.set_tag(""B""); } : fld_16R_B { $elem.mutable_objects()->Add()->mutable_field()->MergeFrom($fld_16R_B.fld); } fld_95a_B? { $elem.mutable_objects()->Add()->mutable_field()->MergeFrom($fld_95a_B.fld); } fld_19B_B+ { $elem.mutable_objects()->Add()->mutable_field()->MergeFrom($fld_19B_B.fld); } seq_B1? { $elem.mutable_objects()->Add()->mutable_sequence()->MergeFrom($seq_B1.elem); } fld_16S_B { $elem.mutable_objects()->Add()->mutable_field()->MergeFrom($fld_16S_B.fld); } ; seq_B1 returns [message::definition::swift::mt::Sequence elem] @init { $elem.set_tag(""B1""); } : fld_16R_B1 { $elem.mutable_objects()->Add()->mutable_field()->MergeFrom($fld_16R_B1.fld); } fld_19B_B1* { $elem.mutable_objects()->Add()->mutable_field()->MergeFrom($fld_19B_B1.fld); } fld_98a_B1* { $elem.mutable_objects()->Add()->mutable_field()->MergeFrom($fld_98a_B1.fld); } fld_16S_B1 { $elem.mutable_objects()->Add()->mutable_field()->MergeFrom($fld_16S_B1.fld); } ; seq_C returns [message::definition::swift::mt::Sequence elem] @init { $elem.set_tag(""C""); } : fld_16R_C { $elem.mutable_objects()->Add()->mutable_field()->MergeFrom($fld_16R_C.fld); } fld_20C_C { $elem.mutable_objects()->Add()->mutable_field()->MergeFrom($fld_20C_C.fld); } fld_22a_C+ { $elem.mutable_objects()->Add()->mutable_field()->MergeFrom($fld_22a_C.fld); } fld_98A_C? { $elem.mutable_objects()->Add()->mutable_field()->MergeFrom($fld_98A_C.fld); } seq_C1? { $elem.mutable_objects()->Add()->mutable_sequence()->MergeFrom($seq_C1.elem); } seq_C2? { $elem.mutable_objects()->Add()->mutable_sequence()->MergeFrom($seq_C2.elem); } seq_C3? { $elem.mutable_objects()->Add()->mutable_sequence()->MergeFrom($seq_C3.elem); } fld_16S_C { $elem.mutable_objects()->Add()->mutable_field()->MergeFrom($fld_16S_C.fld); } ; seq_C1 returns [message::definition::swift::mt::Sequence elem] @init { $elem.set_tag(""C1""); } : fld_16R_C1 { $elem.mutable_objects()->Add()->mutable_field()->MergeFrom($fld_16R_C1.fld); } fld_35B_C1 { $elem.mutable_objects()->Add()->mutable_field()->MergeFrom($fld_35B_C1.fld); } fld_36B_C1 { $elem.mutable_objects()->Add()->mutable_field()->MergeFrom($fld_36B_C1.fld); } fld_17B_C1? { $elem.mutable_objects()->Add()->mutable_field()->MergeFrom($fld_17B_C1.fld); } fld_16S_C1 { $elem.mutable_objects()->Add()->mutable_field()->MergeFrom($fld_16S_C1.fld); } ; seq_C2 returns [message::definition::swift::mt::Sequence elem] @init { $elem.set_tag(""C2""); } : fld_16R_C2 { $elem.mutable_objects()->Add()->mutable_field()->MergeFrom($fld_16R_C2.fld); } fld_19B_C2 { $elem.mutable_objects()->Add()->mutable_field()->MergeFrom($fld_19B_C2.fld); } fld_22H_C2 { $elem.mutable_objects()->Add()->mutable_field()->MergeFrom($fld_22H_C2.fld); } fld_98A_C2? { $elem.mutable_objects()->Add()->mutable_field()->MergeFrom($fld_98A_C2.fld); } fld_16S_C2 { $elem.mutable_objects()->Add()->mutable_field()->MergeFrom($fld_16S_C2.fld); } ; seq_C3 returns [message::definition::swift::mt::Sequence elem] @init { $elem.set_tag(""C3""); } : fld_16R_C3 { $elem.mutable_objects()->Add()->mutable_field()->MergeFrom($fld_16R_C3.fld); } fld_22H_C3 { $elem.mutable_objects()->Add()->mutable_field()->MergeFrom($fld_22H_C3.fld); } fld_98a_C3+ { $elem.mutable_objects()->Add()->mutable_field()->MergeFrom($fld_98a_C3.fld); } fld_95a_C3 { $elem.mutable_objects()->Add()->mutable_field()->MergeFrom($fld_95a_C3.fld); } fld_19B_C3 { $elem.mutable_objects()->Add()->mutable_field()->MergeFrom($fld_19B_C3.fld); } fld_16S_C3 { $elem.mutable_objects()->Add()->mutable_field()->MergeFrom($fld_16S_C3.fld); } ; seq_D returns [message::definition::swift::mt::Sequence elem] @init { $elem.set_tag(""D""); } : fld_16R_D { $elem.mutable_objects()->Add()->mutable_field()->MergeFrom($fld_16R_D.fld); } fld_95a_D* { $elem.mutable_objects()->Add()->mutable_field()->MergeFrom($fld_95a_D.fld); } fld_16S_D { $elem.mutable_objects()->Add()->mutable_field()->MergeFrom($fld_16S_D.fld); } ; fld_16R_A returns [message::definition::swift::mt::Field fld] @init { $fld.set_tag(""16R""); } : START_OF_FIELD '16R:' ~(START_OF_FIELD)+; fld_20C_A returns [message::definition::swift::mt::Field fld] : fld_20C_A_C { $fld.MergeFrom($fld_20C_A_C.fld); } ; fld_23G_A returns [message::definition::swift::mt::Field fld] : fld_23G_A_G { $fld.MergeFrom($fld_23G_A_G.fld); } ; fld_16R_A1 returns [message::definition::swift::mt::Field fld] @init { $fld.set_tag(""16R""); } : START_OF_FIELD '16R:' ~(START_OF_FIELD)+; fld_22F_A1 returns [message::definition::swift::mt::Field fld] : fld_22F_A1_F { $fld.MergeFrom($fld_22F_A1_F.fld); } ; fld_98A_A1 returns [message::definition::swift::mt::Field fld] : fld_98A_A1_A { $fld.MergeFrom($fld_98A_A1_A.fld); } ; fld_13B_A1 returns [message::definition::swift::mt::Field fld] : fld_13B_A1_B { $fld.MergeFrom($fld_13B_A1_B.fld); } ; fld_70C_A1 returns [message::definition::swift::mt::Field fld] : fld_70C_A1_C { $fld.MergeFrom($fld_70C_A1_C.fld); } ; fld_16S_A1 returns [message::definition::swift::mt::Field fld] @init { $fld.set_tag(""16S""); } : START_OF_FIELD '16S:' ~(START_OF_FIELD)+; fld_98a_A returns [message::definition::swift::mt::Field fld] : fld_98a_A_A { $fld.MergeFrom($fld_98a_A_A.fld); } | fld_98a_A_C { $fld.MergeFrom($fld_98a_A_C.fld); } | fld_98a_A_E { $fld.MergeFrom($fld_98a_A_E.fld); } ; fld_22a_A returns [message::definition::swift::mt::Field fld] : fld_22a_A_F { $fld.MergeFrom($fld_22a_A_F.fld); } | fld_22a_A_H { $fld.MergeFrom($fld_22a_A_H.fld); } ; fld_95a_A returns [message::definition::swift::mt::Field fld] : fld_95a_A_P { $fld.MergeFrom($fld_95a_A_P.fld); } | fld_95a_A_Q { $fld.MergeFrom($fld_95a_A_Q.fld); } | fld_95a_A_R { $fld.MergeFrom($fld_95a_A_R.fld); } ; fld_70C_A returns [message::definition::swift::mt::Field fld] : fld_70C_A_C { $fld.MergeFrom($fld_70C_A_C.fld); } ; fld_16R_A2 returns [message::definition::swift::mt::Field fld] @init { $fld.set_tag(""16R""); } : START_OF_FIELD '16R:' ~(START_OF_FIELD)+; fld_13a_A2 returns [message::definition::swift::mt::Field fld] : fld_13a_A2_A { $fld.MergeFrom($fld_13a_A2_A.fld); } | fld_13a_A2_B { $fld.MergeFrom($fld_13a_A2_B.fld); } ; fld_20C_A2 returns [message::definition::swift::mt::Field fld] : fld_20C_A2_C { $fld.MergeFrom($fld_20C_A2_C.fld); } ; fld_16S_A2 returns [message::definition::swift::mt::Field fld] @init { $fld.set_tag(""16S""); } : START_OF_FIELD '16S:' ~(START_OF_FIELD)+; fld_16S_A returns [message::definition::swift::mt::Field fld] @init { $fld.set_tag(""16S""); } : START_OF_FIELD '16S:' ~(START_OF_FIELD)+; fld_16R_B returns [message::definition::swift::mt::Field fld] @init { $fld.set_tag(""16R""); } : START_OF_FIELD '16R:' ~(START_OF_FIELD)+; fld_95a_B returns [message::definition::swift::mt::Field fld] : fld_95a_B_P { $fld.MergeFrom($fld_95a_B_P.fld); } | fld_95a_B_Q { $fld.MergeFrom($fld_95a_B_Q.fld); } | fld_95a_B_R { $fld.MergeFrom($fld_95a_B_R.fld); } ; fld_19B_B returns [message::definition::swift::mt::Field fld] : fld_19B_B_B { $fld.MergeFrom($fld_19B_B_B.fld); } ; fld_16R_B1 returns [message::definition::swift::mt::Field fld] @init { $fld.set_tag(""16R""); } : START_OF_FIELD '16R:' ~(START_OF_FIELD)+; fld_19B_B1 returns [message::definition::swift::mt::Field fld] : fld_19B_B1_B { $fld.MergeFrom($fld_19B_B1_B.fld); } ; fld_98a_B1 returns [message::definition::swift::mt::Field fld] : fld_98a_B1_A { $fld.MergeFrom($fld_98a_B1_A.fld); } | fld_98a_B1_C { $fld.MergeFrom($fld_98a_B1_C.fld); } ; fld_16S_B1 returns [message::definition::swift::mt::Field fld] @init { $fld.set_tag(""16S""); } : START_OF_FIELD '16S:' ~(START_OF_FIELD)+; fld_16S_B returns [message::definition::swift::mt::Field fld] @init { $fld.set_tag(""16S""); } : START_OF_FIELD '16S:' ~(START_OF_FIELD)+; fld_16R_C returns [message::definition::swift::mt::Field fld] @init { $fld.set_tag(""16R""); } : START_OF_FIELD '16R:' ~(START_OF_FIELD)+; fld_20C_C returns [message::definition::swift::mt::Field fld] : fld_20C_C_C { $fld.MergeFrom($fld_20C_C_C.fld); } ; fld_22a_C returns [message::definition::swift::mt::Field fld] : fld_22a_C_F { $fld.MergeFrom($fld_22a_C_F.fld); } | fld_22a_C_H { $fld.MergeFrom($fld_22a_C_H.fld); } ; fld_98A_C returns [message::definition::swift::mt::Field fld] : fld_98A_C_A { $fld.MergeFrom($fld_98A_C_A.fld); } ; fld_16R_C1 returns [message::definition::swift::mt::Field fld] @init { $fld.set_tag(""16R""); } : START_OF_FIELD '16R:' ~(START_OF_FIELD)+; fld_35B_C1 returns [message::definition::swift::mt::Field fld] : fld_35B_C1_B { $fld.MergeFrom($fld_35B_C1_B.fld); } ; fld_36B_C1 returns [message::definition::swift::mt::Field fld] : fld_36B_C1_B { $fld.MergeFrom($fld_36B_C1_B.fld); } ; fld_17B_C1 returns [message::definition::swift::mt::Field fld] : fld_17B_C1_B { $fld.MergeFrom($fld_17B_C1_B.fld); } ; fld_16S_C1 returns [message::definition::swift::mt::Field fld] @init { $fld.set_tag(""16S""); } : START_OF_FIELD '16S:' ~(START_OF_FIELD)+; fld_16R_C2 returns [message::definition::swift::mt::Field fld] @init { $fld.set_tag(""16R""); } : START_OF_FIELD '16R:' ~(START_OF_FIELD)+; fld_19B_C2 returns [message::definition::swift::mt::Field fld] : fld_19B_C2_B { $fld.MergeFrom($fld_19B_C2_B.fld); } ; fld_22H_C2 returns [message::definition::swift::mt::Field fld] : fld_22H_C2_H { $fld.MergeFrom($fld_22H_C2_H.fld); } ; fld_98A_C2 returns [message::definition::swift::mt::Field fld] : fld_98A_C2_A { $fld.MergeFrom($fld_98A_C2_A.fld); } ; fld_16S_C2 returns [message::definition::swift::mt::Field fld] @init { $fld.set_tag(""16S""); } : START_OF_FIELD '16S:' ~(START_OF_FIELD)+; fld_16R_C3 returns [message::definition::swift::mt::Field fld] @init { $fld.set_tag(""16R""); } : START_OF_FIELD '16R:' ~(START_OF_FIELD)+; fld_22H_C3 returns [message::definition::swift::mt::Field fld] : fld_22H_C3_H { $fld.MergeFrom($fld_22H_C3_H.fld); } ; fld_98a_C3 returns [message::definition::swift::mt::Field fld] : fld_98a_C3_A { $fld.MergeFrom($fld_98a_C3_A.fld); } | fld_98a_C3_B { $fld.MergeFrom($fld_98a_C3_B.fld); } ; fld_95a_C3 returns [message::definition::swift::mt::Field fld] : fld_95a_C3_P { $fld.MergeFrom($fld_95a_C3_P.fld); } | fld_95a_C3_Q { $fld.MergeFrom($fld_95a_C3_Q.fld); } | fld_95a_C3_R { $fld.MergeFrom($fld_95a_C3_R.fld); } ; fld_19B_C3 returns [message::definition::swift::mt::Field fld] : fld_19B_C3_B { $fld.MergeFrom($fld_19B_C3_B.fld); } ; fld_16S_C3 returns [message::definition::swift::mt::Field fld] @init { $fld.set_tag(""16S""); } : START_OF_FIELD '16S:' ~(START_OF_FIELD)+; fld_16S_C returns [message::definition::swift::mt::Field fld] @init { $fld.set_tag(""16S""); } : START_OF_FIELD '16S:' ~(START_OF_FIELD)+; fld_16R_D returns [message::definition::swift::mt::Field fld] @init { $fld.set_tag(""16R""); } : START_OF_FIELD '16R:' ~(START_OF_FIELD)+; fld_95a_D returns [message::definition::swift::mt::Field fld] : fld_95a_D_P { $fld.MergeFrom($fld_95a_D_P.fld); } | fld_95a_D_Q { $fld.MergeFrom($fld_95a_D_Q.fld); } | fld_95a_D_R { $fld.MergeFrom($fld_95a_D_R.fld); } ; fld_16S_D returns [message::definition::swift::mt::Field fld] @init { $fld.set_tag(""16S""); } : START_OF_FIELD '16S:' ~(START_OF_FIELD)+; fld_20C_A_C returns [message::definition::swift::mt::Field fld] @init { $fld.set_tag(""20C""); }: START_OF_FIELD '20C:' ~(START_OF_FIELD)+ ; fld_23G_A_G returns [message::definition::swift::mt::Field fld] @init { $fld.set_tag(""23G""); }: START_OF_FIELD '23G:' ~(START_OF_FIELD)+ ; fld_22F_A1_F returns [message::definition::swift::mt::Field fld] @init { $fld.set_tag(""22F""); }: START_OF_FIELD '22F:' ~(START_OF_FIELD)+ ; fld_98A_A1_A returns [message::definition::swift::mt::Field fld] @init { $fld.set_tag(""98A""); }: START_OF_FIELD '98A:' ~(START_OF_FIELD)+ ; fld_13B_A1_B returns [message::definition::swift::mt::Field fld] @init { $fld.set_tag(""13B""); }: START_OF_FIELD '13B:' ~(START_OF_FIELD)+ ; fld_70C_A1_C returns [message::definition::swift::mt::Field fld] @init { $fld.set_tag(""70C""); }: START_OF_FIELD '70C:' ~(START_OF_FIELD)+ ; fld_98a_A_A returns [message::definition::swift::mt::Field fld] @init { $fld.set_tag(""98A""); }: START_OF_FIELD '98A:' ~(START_OF_FIELD)+ ; fld_98a_A_C returns [message::definition::swift::mt::Field fld] @init { $fld.set_tag(""98C""); }: START_OF_FIELD '98C:' ~(START_OF_FIELD)+ ; fld_98a_A_E returns [message::definition::swift::mt::Field fld] @init { $fld.set_tag(""98E""); }: START_OF_FIELD '98E:' ~(START_OF_FIELD)+ ; fld_22a_A_F returns [message::definition::swift::mt::Field fld] @init { $fld.set_tag(""22F""); }: START_OF_FIELD '22F:' ~(START_OF_FIELD)+ ; fld_22a_A_H returns [message::definition::swift::mt::Field fld] @init { $fld.set_tag(""22H""); }: START_OF_FIELD '22H:' ~(START_OF_FIELD)+ ; fld_95a_A_P returns [message::definition::swift::mt::Field fld] @init { $fld.set_tag(""95P""); }: START_OF_FIELD '95P:' ~(START_OF_FIELD)+ ; fld_95a_A_Q returns [message::definition::swift::mt::Field fld] @init { $fld.set_tag(""95Q""); }: START_OF_FIELD '95Q:' ~(START_OF_FIELD)+ ; fld_95a_A_R returns [message::definition::swift::mt::Field fld] @init { $fld.set_tag(""95R""); }: START_OF_FIELD '95R:' ~(START_OF_FIELD)+ ; fld_70C_A_C returns [message::definition::swift::mt::Field fld] @init { $fld.set_tag(""70C""); }: START_OF_FIELD '70C:' ~(START_OF_FIELD)+ ; fld_13a_A2_A returns [message::definition::swift::mt::Field fld] @init { $fld.set_tag(""13A""); }: START_OF_FIELD '13A:' ~(START_OF_FIELD)+ ; fld_13a_A2_B returns [message::definition::swift::mt::Field fld] @init { $fld.set_tag(""13B""); }: START_OF_FIELD '13B:' ~(START_OF_FIELD)+ ; fld_20C_A2_C returns [message::definition::swift::mt::Field fld] @init { $fld.set_tag(""20C""); }: START_OF_FIELD '20C:' ~(START_OF_FIELD)+ ; fld_95a_B_P returns [message::definition::swift::mt::Field fld] @init { $fld.set_tag(""95P""); }: START_OF_FIELD '95P:' ~(START_OF_FIELD)+ ; fld_95a_B_Q returns [message::definition::swift::mt::Field fld] @init { $fld.set_tag(""95Q""); }: START_OF_FIELD '95Q:' ~(START_OF_FIELD)+ ; fld_95a_B_R returns [message::definition::swift::mt::Field fld] @init { $fld.set_tag(""95R""); }: START_OF_FIELD '95R:' ~(START_OF_FIELD)+ ; fld_19B_B_B returns [message::definition::swift::mt::Field fld] @init { $fld.set_tag(""19B""); }: START_OF_FIELD '19B:' ~(START_OF_FIELD)+ ; fld_19B_B1_B returns [message::definition::swift::mt::Field fld] @init { $fld.set_tag(""19B""); }: START_OF_FIELD '19B:' ~(START_OF_FIELD)+ ; fld_98a_B1_A returns [message::definition::swift::mt::Field fld] @init { $fld.set_tag(""98A""); }: START_OF_FIELD '98A:' ~(START_OF_FIELD)+ ; fld_98a_B1_C returns [message::definition::swift::mt::Field fld] @init { $fld.set_tag(""98C""); }: START_OF_FIELD '98C:' ~(START_OF_FIELD)+ ; fld_20C_C_C returns [message::definition::swift::mt::Field fld] @init { $fld.set_tag(""20C""); }: START_OF_FIELD '20C:' ~(START_OF_FIELD)+ ; fld_22a_C_F returns [message::definition::swift::mt::Field fld] @init { $fld.set_tag(""22F""); }: START_OF_FIELD '22F:' ~(START_OF_FIELD)+ ; fld_22a_C_H returns [message::definition::swift::mt::Field fld] @init { $fld.set_tag(""22H""); }: START_OF_FIELD '22H:' ~(START_OF_FIELD)+ ; fld_98A_C_A returns [message::definition::swift::mt::Field fld] @init { $fld.set_tag(""98A""); }: START_OF_FIELD '98A:' ~(START_OF_FIELD)+ ; fld_35B_C1_B returns [message::definition::swift::mt::Field fld] @init { $fld.set_tag(""35B""); }: START_OF_FIELD '35B:' ~(START_OF_FIELD)+ ; fld_36B_C1_B returns [message::definition::swift::mt::Field fld] @init { $fld.set_tag(""36B""); }: START_OF_FIELD '36B:' ~(START_OF_FIELD)+ ; fld_17B_C1_B returns [message::definition::swift::mt::Field fld] @init { $fld.set_tag(""17B""); }: START_OF_FIELD '17B:' ~(START_OF_FIELD)+ ; fld_19B_C2_B returns [message::definition::swift::mt::Field fld] @init { $fld.set_tag(""19B""); }: START_OF_FIELD '19B:' ~(START_OF_FIELD)+ ; fld_22H_C2_H returns [message::definition::swift::mt::Field fld] @init { $fld.set_tag(""22H""); }: START_OF_FIELD '22H:' ~(START_OF_FIELD)+ ; fld_98A_C2_A returns [message::definition::swift::mt::Field fld] @init { $fld.set_tag(""98A""); }: START_OF_FIELD '98A:' ~(START_OF_FIELD)+ ; fld_22H_C3_H returns [message::definition::swift::mt::Field fld] @init { $fld.set_tag(""22H""); }: START_OF_FIELD '22H:' ~(START_OF_FIELD)+ ; fld_98a_C3_A returns [message::definition::swift::mt::Field fld] @init { $fld.set_tag(""98A""); }: START_OF_FIELD '98A:' ~(START_OF_FIELD)+ ; fld_98a_C3_B returns [message::definition::swift::mt::Field fld] @init { $fld.set_tag(""98B""); }: START_OF_FIELD '98B:' ~(START_OF_FIELD)+ ; fld_95a_C3_P returns [message::definition::swift::mt::Field fld] @init { $fld.set_tag(""95P""); }: START_OF_FIELD '95P:' ~(START_OF_FIELD)+ ; fld_95a_C3_Q returns [message::definition::swift::mt::Field fld] @init { $fld.set_tag(""95Q""); }: START_OF_FIELD '95Q:' ~(START_OF_FIELD)+ ; fld_95a_C3_R returns [message::definition::swift::mt::Field fld] @init { $fld.set_tag(""95R""); }: START_OF_FIELD '95R:' ~(START_OF_FIELD)+ ; fld_19B_C3_B returns [message::definition::swift::mt::Field fld] @init { $fld.set_tag(""19B""); }: START_OF_FIELD '19B:' ~(START_OF_FIELD)+ ; fld_95a_D_P returns [message::definition::swift::mt::Field fld] @init { $fld.set_tag(""95P""); }: START_OF_FIELD '95P:' ~(START_OF_FIELD)+ ; fld_95a_D_Q returns [message::definition::swift::mt::Field fld] @init { $fld.set_tag(""95Q""); }: START_OF_FIELD '95Q:' ~(START_OF_FIELD)+ ; fld_95a_D_R returns [message::definition::swift::mt::Field fld] @init { $fld.set_tag(""95R""); }: START_OF_FIELD '95R:' ~(START_OF_FIELD)+ ; TAG_BH : '{1:' ; TAG_AH : '{2:' ; TAG_UH : '{3:' ; TAG_MT : '{4:' ; TAG_TR : '{5:' ; MT_END : '-}'; LBRACE : '{'; RBRACE : '}' ; COLON : ':'; START_OF_FIELD : '\\r'? '\\n:' ; ANY : . ;",8090,True,2501.954818388801,median "/* * Licensed under the Apache License, Version 2.0 (the ""License""); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an ""AS IS"" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * This file is an adaptation of Presto's presto-parser/src/main/antlr4/com/facebook/presto/sql/parser/SqlBase.g4 grammar. */ grammar SqlBase; @members { /** * Verify whether current token is a valid decimal token (which contains dot). * Returns true if the character that follows the token is not a digit or letter or underscore. * * For example: * For char stream ""2.3"", ""2."" is not a valid decimal token, because it is followed by digit '3'. * For char stream ""2.3_"", ""2.3"" is not a valid decimal token, because it is followed by '_'. * For char stream ""2.3W"", ""2.3"" is not a valid decimal token, because it is followed by 'W'. * For char stream ""12.0D 34.E2+0.12 "" 12.0D is a valid decimal token because it is followed * by a space. 34.E2 is a valid decimal token because it is followed by symbol '+' * which is not a digit or letter or underscore. */ public boolean isValidDecimal() { int nextChar = _input.LA(1); if (nextChar >= 'A' && nextChar <= 'Z' || nextChar >= '0' && nextChar <= '9' || nextChar == '_') { return false; } else { return true; } } } singleStatement : statement EOF ; singleExpression : namedExpression EOF ; singleTableIdentifier : tableIdentifier EOF ; singleFunctionIdentifier : functionIdentifier EOF ; singleDataType : dataType EOF ; singleTableSchema : colTypeList EOF ; statement : query #statementDefault | USE db=identifier #use | CREATE DATABASE (IF NOT EXISTS)? identifier (COMMENT comment=STRING)? locationSpec? (WITH DBPROPERTIES tablePropertyList)? #createDatabase | ALTER DATABASE identifier SET DBPROPERTIES tablePropertyList #setDatabaseProperties | DROP DATABASE (IF EXISTS)? identifier (RESTRICT | CASCADE)? #dropDatabase | createTableHeader ('(' colTypeList ')')? tableProvider (OPTIONS options=tablePropertyList)? (PARTITIONED BY partitionColumnNames=identifierList)? bucketSpec? locationSpec? (COMMENT comment=STRING)? (TBLPROPERTIES tableProps=tablePropertyList)? (AS? query)? #createTable | createTableHeader ('(' columns=colTypeList ')')? (COMMENT comment=STRING)? (PARTITIONED BY '(' partitionColumns=colTypeList ')')? bucketSpec? skewSpec? rowFormat? createFileFormat? locationSpec? (TBLPROPERTIES tablePropertyList)? (AS? query)? #createHiveTable | CREATE TABLE (IF NOT EXISTS)? target=tableIdentifier LIKE source=tableIdentifier locationSpec? #createTableLike | ANALYZE TABLE tableIdentifier partitionSpec? COMPUTE STATISTICS (identifier | FOR COLUMNS identifierSeq)? #analyze | ALTER TABLE tableIdentifier ADD COLUMNS '(' columns=colTypeList ')' #addTableColumns | ALTER (TABLE | VIEW) from=tableIdentifier RENAME TO to=tableIdentifier #renameTable | ALTER (TABLE | VIEW) tableIdentifier SET TBLPROPERTIES tablePropertyList #setTableProperties | ALTER (TABLE | VIEW) tableIdentifier UNSET TBLPROPERTIES (IF EXISTS)? tablePropertyList #unsetTableProperties | ALTER TABLE tableIdentifier partitionSpec? CHANGE COLUMN? identifier colType colPosition? #changeColumn | ALTER TABLE tableIdentifier (partitionSpec)? SET SERDE STRING (WITH SERDEPROPERTIES tablePropertyList)? #setTableSerDe | ALTER TABLE tableIdentifier (partitionSpec)? SET SERDEPROPERTIES tablePropertyList #setTableSerDe | ALTER TABLE tableIdentifier ADD (IF NOT EXISTS)? partitionSpecLocation+ #addTablePartition | ALTER VIEW tableIdentifier ADD (IF NOT EXISTS)? partitionSpec+ #addTablePartition | ALTER TABLE tableIdentifier from=partitionSpec RENAME TO to=partitionSpec #renameTablePartition | ALTER TABLE tableIdentifier DROP (IF EXISTS)? partitionSpec (',' partitionSpec)* PURGE? #dropTablePartitions | ALTER VIEW tableIdentifier DROP (IF EXISTS)? partitionSpec (',' partitionSpec)* #dropTablePartitions | ALTER TABLE tableIdentifier partitionSpec? SET locationSpec #setTableLocation | ALTER TABLE tableIdentifier RECOVER PARTITIONS #recoverPartitions | DROP TABLE (IF EXISTS)? tableIdentifier PURGE? #dropTable | DROP VIEW (IF EXISTS)? tableIdentifier #dropTable | CREATE (OR REPLACE)? (GLOBAL? TEMPORARY)? VIEW (IF NOT EXISTS)? tableIdentifier identifierCommentList? (COMMENT STRING)? (PARTITIONED ON identifierList)? (TBLPROPERTIES tablePropertyList)? AS query #createView | CREATE (OR REPLACE)? GLOBAL? TEMPORARY VIEW tableIdentifier ('(' colTypeList ')')? tableProvider (OPTIONS tablePropertyList)? #createTempViewUsing | ALTER VIEW tableIdentifier AS? query #alterViewQuery | CREATE (OR REPLACE)? TEMPORARY? FUNCTION (IF NOT EXISTS)? qualifiedName AS className=STRING (USING resource (',' resource)*)? #createFunction | DROP TEMPORARY? FUNCTION (IF EXISTS)? qualifiedName #dropFunction | EXPLAIN (LOGICAL | FORMATTED | EXTENDED | CODEGEN | COST)? statement #explain | SHOW TABLES ((FROM | IN) db=identifier)? (LIKE? pattern=STRING)? #showTables | SHOW TABLE EXTENDED ((FROM | IN) db=identifier)? LIKE pattern=STRING partitionSpec? #showTable | SHOW DATABASES (LIKE pattern=STRING)? #showDatabases | SHOW TBLPROPERTIES table=tableIdentifier ('(' key=tablePropertyKey ')')? #showTblProperties | SHOW COLUMNS (FROM | IN) tableIdentifier ((FROM | IN) db=identifier)? #showColumns | SHOW PARTITIONS tableIdentifier partitionSpec? #showPartitions | SHOW identifier? FUNCTIONS (LIKE? (qualifiedName | pattern=STRING))? #showFunctions | SHOW CREATE TABLE tableIdentifier #showCreateTable | (DESC | DESCRIBE) FUNCTION EXTENDED? describeFuncName #describeFunction | (DESC | DESCRIBE) DATABASE EXTENDED? identifier #describeDatabase | (DESC | DESCRIBE) TABLE? option=(EXTENDED | FORMATTED)? tableIdentifier partitionSpec? describeColName? #describeTable | REFRESH TABLE tableIdentifier #refreshTable | REFRESH (STRING | .*?) #refreshResource | CACHE LAZY? TABLE tableIdentifier (AS? query)? #cacheTable | UNCACHE TABLE (IF EXISTS)? tableIdentifier #uncacheTable | CLEAR CACHE #clearCache | LOAD DATA LOCAL? INPATH path=STRING OVERWRITE? INTO TABLE tableIdentifier partitionSpec? #loadData | TRUNCATE TABLE tableIdentifier partitionSpec? #truncateTable | MSCK REPAIR TABLE tableIdentifier #repairTable | op=(ADD | LIST) identifier .*? #manageResource | SET ROLE .*? #failNativeCommand | SET .*? #setConfiguration | RESET #resetConfiguration | unsupportedHiveNativeCommands .*? #failNativeCommand ; unsupportedHiveNativeCommands : kw1=CREATE kw2=ROLE | kw1=DROP kw2=ROLE | kw1=GRANT kw2=ROLE? | kw1=REVOKE kw2=ROLE? | kw1=SHOW kw2=GRANT | kw1=SHOW kw2=ROLE kw3=GRANT? | kw1=SHOW kw2=PRINCIPALS | kw1=SHOW kw2=ROLES | kw1=SHOW kw2=CURRENT kw3=ROLES | kw1=EXPORT kw2=TABLE | kw1=IMPORT kw2=TABLE | kw1=SHOW kw2=COMPACTIONS | kw1=SHOW kw2=CREATE kw3=TABLE | kw1=SHOW kw2=TRANSACTIONS | kw1=SHOW kw2=INDEXES | kw1=SHOW kw2=LOCKS | kw1=CREATE kw2=INDEX | kw1=DROP kw2=INDEX | kw1=ALTER kw2=INDEX | kw1=LOCK kw2=TABLE | kw1=LOCK kw2=DATABASE | kw1=UNLOCK kw2=TABLE | kw1=UNLOCK kw2=DATABASE | kw1=CREATE kw2=TEMPORARY kw3=MACRO | kw1=DROP kw2=TEMPORARY kw3=MACRO | kw1=ALTER kw2=TABLE tableIdentifier kw3=NOT kw4=CLUSTERED | kw1=ALTER kw2=TABLE tableIdentifier kw3=CLUSTERED kw4=BY | kw1=ALTER kw2=TABLE tableIdentifier kw3=NOT kw4=SORTED | kw1=ALTER kw2=TABLE tableIdentifier kw3=SKEWED kw4=BY | kw1=ALTER kw2=TABLE tableIdentifier kw3=NOT kw4=SKEWED | kw1=ALTER kw2=TABLE tableIdentifier kw3=NOT kw4=STORED kw5=AS kw6=DIRECTORIES | kw1=ALTER kw2=TABLE tableIdentifier kw3=SET kw4=SKEWED kw5=LOCATION | kw1=ALTER kw2=TABLE tableIdentifier kw3=EXCHANGE kw4=PARTITION | kw1=ALTER kw2=TABLE tableIdentifier kw3=ARCHIVE kw4=PARTITION | kw1=ALTER kw2=TABLE tableIdentifier kw3=UNARCHIVE kw4=PARTITION | kw1=ALTER kw2=TABLE tableIdentifier kw3=TOUCH | kw1=ALTER kw2=TABLE tableIdentifier partitionSpec? kw3=COMPACT | kw1=ALTER kw2=TABLE tableIdentifier partitionSpec? kw3=CONCATENATE | kw1=ALTER kw2=TABLE tableIdentifier partitionSpec? kw3=SET kw4=FILEFORMAT | kw1=ALTER kw2=TABLE tableIdentifier partitionSpec? kw3=REPLACE kw4=COLUMNS | kw1=START kw2=TRANSACTION | kw1=COMMIT | kw1=ROLLBACK | kw1=DFS | kw1=DELETE kw2=FROM ; createTableHeader : CREATE TEMPORARY? EXTERNAL? TABLE (IF NOT EXISTS)? tableIdentifier ; bucketSpec : CLUSTERED BY identifierList (SORTED BY orderedIdentifierList)? INTO INTEGER_VALUE BUCKETS ; skewSpec : SKEWED BY identifierList ON (constantList | nestedConstantList) (STORED AS DIRECTORIES)? ; locationSpec : LOCATION STRING ; query : ctes? queryNoWith ; insertInto : INSERT OVERWRITE TABLE tableIdentifier (partitionSpec (IF NOT EXISTS)?)? #insertOverwriteTable | INSERT INTO TABLE? tableIdentifier partitionSpec? #insertIntoTable | INSERT OVERWRITE LOCAL? DIRECTORY path=STRING rowFormat? createFileFormat? #insertOverwriteHiveDir | INSERT OVERWRITE LOCAL? DIRECTORY (path=STRING)? tableProvider (OPTIONS options=tablePropertyList)? #insertOverwriteDir ; partitionSpecLocation : partitionSpec locationSpec? ; partitionSpec : PARTITION '(' partitionVal (',' partitionVal)* ')' ; partitionVal : identifier (EQ constant)? ; describeFuncName : qualifiedName | STRING | comparisonOperator | arithmeticOperator | predicateOperator ; describeColName : nameParts+=identifier ('.' nameParts+=identifier)* ; ctes : WITH namedQuery (',' namedQuery)* ; namedQuery : name=identifier AS? '(' query ')' ; tableProvider : USING qualifiedName ; tablePropertyList : '(' tableProperty (',' tableProperty)* ')' ; tableProperty : key=tablePropertyKey (EQ? value=tablePropertyValue)? ; tablePropertyKey : identifier ('.' identifier)* | STRING ; tablePropertyValue : INTEGER_VALUE | DECIMAL_VALUE | booleanValue | STRING ; constantList : '(' constant (',' constant)* ')' ; nestedConstantList : '(' constantList (',' constantList)* ')' ; createFileFormat : STORED AS fileFormat | STORED BY storageHandler ; fileFormat : INPUTFORMAT inFmt=STRING OUTPUTFORMAT outFmt=STRING #tableFileFormat | identifier #genericFileFormat ; storageHandler : STRING (WITH SERDEPROPERTIES tablePropertyList)? ; resource : identifier STRING ; queryNoWith : insertInto? queryTerm queryOrganization #singleInsertQuery | fromClause multiInsertQueryBody+ #multiInsertQuery ; queryOrganization : (ORDER BY order+=sortItem (',' order+=sortItem)*)? (CLUSTER BY clusterBy+=expression (',' clusterBy+=expression)*)? (DISTRIBUTE BY distributeBy+=expression (',' distributeBy+=expression)*)? (SORT BY sort+=sortItem (',' sort+=sortItem)*)? windows? (LIMIT (ALL | limit=expression))? ; multiInsertQueryBody : insertInto? querySpecification queryOrganization ; queryTerm : queryPrimary #queryTermDefault | left=queryTerm operator=(INTERSECT | UNION | EXCEPT | SETMINUS) setQuantifier? right=queryTerm #setOperation ; queryPrimary : querySpecification #queryPrimaryDefault | TABLE tableIdentifier #table | inlineTable #inlineTableDefault1 | '(' queryNoWith ')' #subquery ; sortItem : expression ordering=(ASC | DESC)? (NULLS nullOrder=(LAST | FIRST))? ; querySpecification : (((SELECT kind=TRANSFORM '(' namedExpressionSeq ')' | kind=MAP namedExpressionSeq | kind=REDUCE namedExpressionSeq)) inRowFormat=rowFormat? (RECORDWRITER recordWriter=STRING)? USING script=STRING (AS (identifierSeq | colTypeList | ('(' (identifierSeq | colTypeList) ')')))? outRowFormat=rowFormat? (RECORDREADER recordReader=STRING)? fromClause? (WHERE where=booleanExpression)?) | ((kind=SELECT (hints+=hint)* setQuantifier? namedExpressionSeq fromClause? | fromClause (kind=SELECT setQuantifier? namedExpressionSeq)?) lateralView* (WHERE where=booleanExpression)? aggregation? (HAVING having=booleanExpression)? windows?) ; hint : '/*+' hintStatements+=hintStatement (','? hintStatements+=hintStatement)* '*/' ; hintStatement : hintName=identifier | hintName=identifier '(' parameters+=primaryExpression (',' parameters+=primaryExpression)* ')' ; fromClause : FROM relation (',' relation)* lateralView* ; aggregation : GROUP BY groupingExpressions+=expression (',' groupingExpressions+=expression)* ( WITH kind=ROLLUP | WITH kind=CUBE | kind=GROUPING SETS '(' groupingSet (',' groupingSet)* ')')? ; groupingSet : '(' (expression (',' expression)*)? ')' | expression ; lateralView : LATERAL VIEW (OUTER)? qualifiedName '(' (expression (',' expression)*)? ')' tblName=identifier (AS? colName+=identifier (',' colName+=identifier)*)? ; setQuantifier : DISTINCT | ALL ; relation : relationPrimary joinRelation* ; joinRelation : (joinType) JOIN right=relationPrimary joinCriteria? | NATURAL joinType JOIN right=relationPrimary ; joinType : INNER? | CROSS | LEFT OUTER? | LEFT SEMI | RIGHT OUTER? | FULL OUTER? | LEFT? ANTI ; joinCriteria : ON booleanExpression | USING '(' identifier (',' identifier)* ')' ; sample : TABLESAMPLE '(' sampleMethod? ')' ; sampleMethod : negativeSign=MINUS? percentage=(INTEGER_VALUE | DECIMAL_VALUE) PERCENTLIT #sampleByPercentile | expression ROWS #sampleByRows | sampleType=BUCKET numerator=INTEGER_VALUE OUT OF denominator=INTEGER_VALUE (ON (identifier | qualifiedName '(' ')'))? #sampleByBucket | bytes=expression #sampleByBytes ; identifierList : '(' identifierSeq ')' ; identifierSeq : identifier (',' identifier)* ; orderedIdentifierList : '(' orderedIdentifier (',' orderedIdentifier)* ')' ; orderedIdentifier : identifier ordering=(ASC | DESC)? ; identifierCommentList : '(' identifierComment (',' identifierComment)* ')' ; identifierComment : identifier (COMMENT STRING)? ; relationPrimary : tableIdentifier sample? tableAlias #tableName | '(' queryNoWith ')' sample? tableAlias #aliasedQuery | '(' relation ')' sample? tableAlias #aliasedRelation | inlineTable #inlineTableDefault2 | functionTable #tableValuedFunction ; inlineTable : VALUES expression (',' expression)* tableAlias ; functionTable : identifier '(' (expression (',' expression)*)? ')' tableAlias ; tableAlias : (AS? strictIdentifier identifierList?)? ; rowFormat : ROW FORMAT SERDE name=STRING (WITH SERDEPROPERTIES props=tablePropertyList)? #rowFormatSerde | ROW FORMAT DELIMITED (FIELDS TERMINATED BY fieldsTerminatedBy=STRING (ESCAPED BY escapedBy=STRING)?)? (COLLECTION ITEMS TERMINATED BY collectionItemsTerminatedBy=STRING)? (MAP KEYS TERMINATED BY keysTerminatedBy=STRING)? (LINES TERMINATED BY linesSeparatedBy=STRING)? (NULL DEFINED AS nullDefinedAs=STRING)? #rowFormatDelimited ; tableIdentifier : (db=identifier '.')? table=identifier ; functionIdentifier : (db=identifier '.')? function=identifier ; namedExpression : expression (AS? (identifier | identifierList))? ; namedExpressionSeq : namedExpression (',' namedExpression)* ; expression : booleanExpression ; booleanExpression : NOT booleanExpression #logicalNot | EXISTS '(' query ')' #exists | predicated #booleanDefault | left=booleanExpression operator=AND right=booleanExpression #logicalBinary | left=booleanExpression operator=OR right=booleanExpression #logicalBinary ; // workaround for: // https://github.com/antlr/antlr4/issues/780 // https://github.com/antlr/antlr4/issues/781 predicated : valueExpression predicate? ; predicate : NOT? kind=BETWEEN lower=valueExpression AND upper=valueExpression | NOT? kind=IN '(' expression (',' expression)* ')' | NOT? kind=IN '(' query ')' | NOT? kind=(RLIKE | LIKE) pattern=valueExpression | IS NOT? kind=NULL | IS NOT? kind=DISTINCT FROM right=valueExpression ; valueExpression : primaryExpression #valueExpressionDefault | operator=(MINUS | PLUS | TILDE) valueExpression #arithmeticUnary | left=valueExpression operator=(ASTERISK | SLASH | PERCENT | DIV) right=valueExpression #arithmeticBinary | left=valueExpression operator=(PLUS | MINUS | CONCAT_PIPE) right=valueExpression #arithmeticBinary | left=valueExpression operator=AMPERSAND right=valueExpression #arithmeticBinary | left=valueExpression operator=HAT right=valueExpression #arithmeticBinary | left=valueExpression operator=PIPE right=valueExpression #arithmeticBinary | left=valueExpression comparisonOperator right=valueExpression #comparison ; primaryExpression : name=(CURRENT_DATE | CURRENT_TIMESTAMP) #timeFunctionCall | CASE whenClause+ (ELSE elseExpression=expression)? END #searchedCase | CASE value=expression whenClause+ (ELSE elseExpression=expression)? END #simpleCase | CAST '(' expression AS dataType ')' #cast | STRUCT '(' (argument+=namedExpression (',' argument+=namedExpression)*)? ')' #struct | FIRST '(' expression (IGNORE NULLS)? ')' #first | LAST '(' expression (IGNORE NULLS)? ')' #last | POSITION '(' substr=valueExpression IN str=valueExpression ')' #position | constant #constantDefault | ASTERISK #star | qualifiedName '.' ASTERISK #star | '(' namedExpression (',' namedExpression)+ ')' #rowConstructor | '(' query ')' #subqueryExpression | qualifiedName '(' (setQuantifier? argument+=expression (',' argument+=expression)*)? ')' (OVER windowSpec)? #functionCall | qualifiedName '(' trimOption=(BOTH | LEADING | TRAILING) argument+=expression FROM argument+=expression ')' #functionCall | value=primaryExpression '[' index=valueExpression ']' #subscript | identifier #columnReference | base=primaryExpression '.' fieldName=identifier #dereference | '(' expression ')' #parenthesizedExpression ; constant : NULL #nullLiteral | interval #intervalLiteral | identifier STRING #typeConstructor | number #numericLiteral | booleanValue #booleanLiteral | STRING+ #stringLiteral ; comparisonOperator : EQ | NEQ | NEQJ | LT | LTE | GT | GTE | NSEQ ; arithmeticOperator : PLUS | MINUS | ASTERISK | SLASH | PERCENT | DIV | TILDE | AMPERSAND | PIPE | CONCAT_PIPE | HAT ; predicateOperator : OR | AND | IN | NOT ; booleanValue : TRUE | FALSE ; interval : INTERVAL intervalField* ; intervalField : value=intervalValue unit=identifier (TO to=identifier)? ; intervalValue : (PLUS | MINUS)? (INTEGER_VALUE | DECIMAL_VALUE) | STRING ; colPosition : FIRST | AFTER identifier ; dataType : complex=ARRAY '<' dataType '>' #complexDataType | complex=MAP '<' dataType ',' dataType '>' #complexDataType | complex=STRUCT ('<' complexColTypeList? '>' | NEQ) #complexDataType | identifier ('(' INTEGER_VALUE (',' INTEGER_VALUE)* ')')? #primitiveDataType ; colTypeList : colType (',' colType)* ; colType : identifier dataType (COMMENT STRING)? ; complexColTypeList : complexColType (',' complexColType)* ; complexColType : identifier ':' dataType (COMMENT STRING)? ; whenClause : WHEN condition=expression THEN result=expression ; windows : WINDOW namedWindow (',' namedWindow)* ; namedWindow : identifier AS windowSpec ; windowSpec : name=identifier #windowRef | '(' ( CLUSTER BY partition+=expression (',' partition+=expression)* | ((PARTITION | DISTRIBUTE) BY partition+=expression (',' partition+=expression)*)? ((ORDER | SORT) BY sortItem (',' sortItem)*)?) windowFrame? ')' #windowDef ; windowFrame : frameType=RANGE start=frameBound | frameType=ROWS start=frameBound | frameType=RANGE BETWEEN start=frameBound AND end=frameBound | frameType=ROWS BETWEEN start=frameBound AND end=frameBound ; frameBound : UNBOUNDED boundType=(PRECEDING | FOLLOWING) | boundType=CURRENT ROW | expression boundType=(PRECEDING | FOLLOWING) ; qualifiedName : identifier ('.' identifier)* ; identifier : strictIdentifier | ANTI | FULL | INNER | LEFT | SEMI | RIGHT | NATURAL | JOIN | CROSS | ON | UNION | INTERSECT | EXCEPT | SETMINUS ; strictIdentifier : IDENTIFIER #unquotedIdentifier | quotedIdentifier #quotedIdentifierAlternative | nonReserved #unquotedIdentifier ; quotedIdentifier : BACKQUOTED_IDENTIFIER ; number : MINUS? DECIMAL_VALUE #decimalLiteral | MINUS? INTEGER_VALUE #integerLiteral | MINUS? BIGINT_LITERAL #bigIntLiteral | MINUS? SMALLINT_LITERAL #smallIntLiteral | MINUS? TINYINT_LITERAL #tinyIntLiteral | MINUS? DOUBLE_LITERAL #doubleLiteral | MINUS? BIGDECIMAL_LITERAL #bigDecimalLiteral ; nonReserved : SHOW | TABLES | COLUMNS | COLUMN | PARTITIONS | FUNCTIONS | DATABASES | ADD | OVER | PARTITION | RANGE | ROWS | PRECEDING | FOLLOWING | CURRENT | ROW | LAST | FIRST | AFTER | MAP | ARRAY | STRUCT | LATERAL | WINDOW | REDUCE | TRANSFORM | SERDE | SERDEPROPERTIES | RECORDREADER | DELIMITED | FIELDS | TERMINATED | COLLECTION | ITEMS | KEYS | ESCAPED | LINES | SEPARATED | EXTENDED | REFRESH | CLEAR | CACHE | UNCACHE | LAZY | GLOBAL | TEMPORARY | OPTIONS | GROUPING | CUBE | ROLLUP | EXPLAIN | FORMAT | LOGICAL | FORMATTED | CODEGEN | COST | TABLESAMPLE | USE | TO | BUCKET | PERCENTLIT | OUT | OF | SET | RESET | VIEW | REPLACE | IF | POSITION | NO | DATA | START | TRANSACTION | COMMIT | ROLLBACK | IGNORE | SORT | CLUSTER | DISTRIBUTE | UNSET | TBLPROPERTIES | SKEWED | STORED | DIRECTORIES | LOCATION | EXCHANGE | ARCHIVE | UNARCHIVE | FILEFORMAT | TOUCH | COMPACT | CONCATENATE | CHANGE | CASCADE | RESTRICT | BUCKETS | CLUSTERED | SORTED | PURGE | INPUTFORMAT | OUTPUTFORMAT | DBPROPERTIES | DFS | TRUNCATE | COMPUTE | LIST | STATISTICS | ANALYZE | PARTITIONED | EXTERNAL | DEFINED | RECORDWRITER | REVOKE | GRANT | LOCK | UNLOCK | MSCK | REPAIR | RECOVER | EXPORT | IMPORT | LOAD | VALUES | COMMENT | ROLE | ROLES | COMPACTIONS | PRINCIPALS | TRANSACTIONS | INDEX | INDEXES | LOCKS | OPTION | LOCAL | INPATH | ASC | DESC | LIMIT | RENAME | SETS | AT | NULLS | OVERWRITE | ALL | ALTER | AS | BETWEEN | BY | CREATE | DELETE | DESCRIBE | DROP | EXISTS | FALSE | FOR | GROUP | IN | INSERT | INTO | IS |LIKE | NULL | ORDER | OUTER | TABLE | TRUE | WITH | RLIKE | AND | CASE | CAST | DISTINCT | DIV | ELSE | END | FUNCTION | INTERVAL | MACRO | OR | STRATIFY | THEN | UNBOUNDED | WHEN | DATABASE | SELECT | FROM | WHERE | HAVING | TO | TABLE | WITH | NOT | CURRENT_DATE | CURRENT_TIMESTAMP | DIRECTORY | BOTH | LEADING | TRAILING ; SELECT: 'SELECT'; FROM: 'FROM'; ADD: 'ADD'; AS: 'AS'; ALL: 'ALL'; DISTINCT: 'DISTINCT'; WHERE: 'WHERE'; GROUP: 'GROUP'; BY: 'BY'; GROUPING: 'GROUPING'; SETS: 'SETS'; CUBE: 'CUBE'; ROLLUP: 'ROLLUP'; ORDER: 'ORDER'; HAVING: 'HAVING'; LIMIT: 'LIMIT'; AT: 'AT'; OR: 'OR'; AND: 'AND'; IN: 'IN'; NOT: 'NOT' | '!'; NO: 'NO'; EXISTS: 'EXISTS'; BETWEEN: 'BETWEEN'; LIKE: 'LIKE'; RLIKE: 'RLIKE' | 'REGEXP'; IS: 'IS'; NULL: 'NULL'; TRUE: 'TRUE'; FALSE: 'FALSE'; NULLS: 'NULLS'; ASC: 'ASC'; DESC: 'DESC'; FOR: 'FOR'; INTERVAL: 'INTERVAL'; CASE: 'CASE'; WHEN: 'WHEN'; THEN: 'THEN'; ELSE: 'ELSE'; END: 'END'; JOIN: 'JOIN'; CROSS: 'CROSS'; OUTER: 'OUTER'; INNER: 'INNER'; LEFT: 'LEFT'; SEMI: 'SEMI'; RIGHT: 'RIGHT'; FULL: 'FULL'; NATURAL: 'NATURAL'; ON: 'ON'; LATERAL: 'LATERAL'; WINDOW: 'WINDOW'; OVER: 'OVER'; PARTITION: 'PARTITION'; RANGE: 'RANGE'; ROWS: 'ROWS'; UNBOUNDED: 'UNBOUNDED'; PRECEDING: 'PRECEDING'; FOLLOWING: 'FOLLOWING'; CURRENT: 'CURRENT'; FIRST: 'FIRST'; AFTER: 'AFTER'; LAST: 'LAST'; ROW: 'ROW'; WITH: 'WITH'; VALUES: 'VALUES'; CREATE: 'CREATE'; TABLE: 'TABLE'; DIRECTORY: 'DIRECTORY'; VIEW: 'VIEW'; REPLACE: 'REPLACE'; INSERT: 'INSERT'; DELETE: 'DELETE'; INTO: 'INTO'; DESCRIBE: 'DESCRIBE'; EXPLAIN: 'EXPLAIN'; FORMAT: 'FORMAT'; LOGICAL: 'LOGICAL'; CODEGEN: 'CODEGEN'; COST: 'COST'; CAST: 'CAST'; SHOW: 'SHOW'; TABLES: 'TABLES'; COLUMNS: 'COLUMNS'; COLUMN: 'COLUMN'; USE: 'USE'; PARTITIONS: 'PARTITIONS'; FUNCTIONS: 'FUNCTIONS'; DROP: 'DROP'; UNION: 'UNION'; EXCEPT: 'EXCEPT'; SETMINUS: 'MINUS'; INTERSECT: 'INTERSECT'; TO: 'TO'; TABLESAMPLE: 'TABLESAMPLE'; STRATIFY: 'STRATIFY'; ALTER: 'ALTER'; RENAME: 'RENAME'; ARRAY: 'ARRAY'; MAP: 'MAP'; STRUCT: 'STRUCT'; COMMENT: 'COMMENT'; SET: 'SET'; RESET: 'RESET'; DATA: 'DATA'; START: 'START'; TRANSACTION: 'TRANSACTION'; COMMIT: 'COMMIT'; ROLLBACK: 'ROLLBACK'; MACRO: 'MACRO'; IGNORE: 'IGNORE'; BOTH: 'BOTH'; LEADING: 'LEADING'; TRAILING: 'TRAILING'; IF: 'IF'; POSITION: 'POSITION'; EQ : '=' | '=='; NSEQ: '<=>'; NEQ : '<>'; NEQJ: '!='; LT : '<'; LTE : '<=' | '!>'; GT : '>'; GTE : '>=' | '!<'; PLUS: '+'; MINUS: '-'; ASTERISK: '*'; SLASH: '/'; PERCENT: '%'; DIV: 'DIV'; TILDE: '~'; AMPERSAND: '&'; PIPE: '|'; CONCAT_PIPE: '||'; HAT: '^'; PERCENTLIT: 'PERCENT'; BUCKET: 'BUCKET'; OUT: 'OUT'; OF: 'OF'; SORT: 'SORT'; CLUSTER: 'CLUSTER'; DISTRIBUTE: 'DISTRIBUTE'; OVERWRITE: 'OVERWRITE'; TRANSFORM: 'TRANSFORM'; REDUCE: 'REDUCE'; USING: 'USING'; SERDE: 'SERDE'; SERDEPROPERTIES: 'SERDEPROPERTIES'; RECORDREADER: 'RECORDREADER'; RECORDWRITER: 'RECORDWRITER'; DELIMITED: 'DELIMITED'; FIELDS: 'FIELDS'; TERMINATED: 'TERMINATED'; COLLECTION: 'COLLECTION'; ITEMS: 'ITEMS'; KEYS: 'KEYS'; ESCAPED: 'ESCAPED'; LINES: 'LINES'; SEPARATED: 'SEPARATED'; FUNCTION: 'FUNCTION'; EXTENDED: 'EXTENDED'; REFRESH: 'REFRESH'; CLEAR: 'CLEAR'; CACHE: 'CACHE'; UNCACHE: 'UNCACHE'; LAZY: 'LAZY'; FORMATTED: 'FORMATTED'; GLOBAL: 'GLOBAL'; TEMPORARY: 'TEMPORARY' | 'TEMP'; OPTIONS: 'OPTIONS'; UNSET: 'UNSET'; TBLPROPERTIES: 'TBLPROPERTIES'; DBPROPERTIES: 'DBPROPERTIES'; BUCKETS: 'BUCKETS'; SKEWED: 'SKEWED'; STORED: 'STORED'; DIRECTORIES: 'DIRECTORIES'; LOCATION: 'LOCATION'; EXCHANGE: 'EXCHANGE'; ARCHIVE: 'ARCHIVE'; UNARCHIVE: 'UNARCHIVE'; FILEFORMAT: 'FILEFORMAT'; TOUCH: 'TOUCH'; COMPACT: 'COMPACT'; CONCATENATE: 'CONCATENATE'; CHANGE: 'CHANGE'; CASCADE: 'CASCADE'; RESTRICT: 'RESTRICT'; CLUSTERED: 'CLUSTERED'; SORTED: 'SORTED'; PURGE: 'PURGE'; INPUTFORMAT: 'INPUTFORMAT'; OUTPUTFORMAT: 'OUTPUTFORMAT'; DATABASE: 'DATABASE' | 'SCHEMA'; DATABASES: 'DATABASES' | 'SCHEMAS'; DFS: 'DFS'; TRUNCATE: 'TRUNCATE'; ANALYZE: 'ANALYZE'; COMPUTE: 'COMPUTE'; LIST: 'LIST'; STATISTICS: 'STATISTICS'; PARTITIONED: 'PARTITIONED'; EXTERNAL: 'EXTERNAL'; DEFINED: 'DEFINED'; REVOKE: 'REVOKE'; GRANT: 'GRANT'; LOCK: 'LOCK'; UNLOCK: 'UNLOCK'; MSCK: 'MSCK'; REPAIR: 'REPAIR'; RECOVER: 'RECOVER'; EXPORT: 'EXPORT'; IMPORT: 'IMPORT'; LOAD: 'LOAD'; ROLE: 'ROLE'; ROLES: 'ROLES'; COMPACTIONS: 'COMPACTIONS'; PRINCIPALS: 'PRINCIPALS'; TRANSACTIONS: 'TRANSACTIONS'; INDEX: 'INDEX'; INDEXES: 'INDEXES'; LOCKS: 'LOCKS'; OPTION: 'OPTION'; ANTI: 'ANTI'; LOCAL: 'LOCAL'; INPATH: 'INPATH'; CURRENT_DATE: 'CURRENT_DATE'; CURRENT_TIMESTAMP: 'CURRENT_TIMESTAMP'; STRING : '\\'' ( ~('\\''|'\\\\') | ('\\\\' .) )* '\\'' | '""' ( ~('""'|'\\\\') | ('\\\\' .) )* '""' ; BIGINT_LITERAL : DIGIT+ 'L' ; SMALLINT_LITERAL : DIGIT+ 'S' ; TINYINT_LITERAL : DIGIT+ 'Y' ; INTEGER_VALUE : DIGIT+ ; DECIMAL_VALUE : DIGIT+ EXPONENT | DECIMAL_DIGITS EXPONENT? {isValidDecimal()}? ; DOUBLE_LITERAL : DIGIT+ EXPONENT? 'D' | DECIMAL_DIGITS EXPONENT? 'D' {isValidDecimal()}? ; BIGDECIMAL_LITERAL : DIGIT+ EXPONENT? 'BD' | DECIMAL_DIGITS EXPONENT? 'BD' {isValidDecimal()}? ; IDENTIFIER : (LETTER | DIGIT | '_')+ ; BACKQUOTED_IDENTIFIER : '`' ( ~'`' | '``' )* '`' ; fragment DECIMAL_DIGITS : DIGIT+ '.' DIGIT* | '.' DIGIT+ ; fragment EXPONENT : 'E' [+-]? DIGIT+ ; fragment DIGIT : [0-9] ; fragment LETTER : [A-Z] ; SIMPLE_COMMENT : '--' ~[\\r\\n]* '\\r'? '\\n'? -> channel(HIDDEN) ; BRACKETED_EMPTY_COMMENT : '/**/' -> channel(HIDDEN) ; BRACKETED_COMMENT : '/*' ~[+] .*? '*/' -> channel(HIDDEN) ; WS : [ \\r\\n\\t]+ -> channel(HIDDEN) ; // Catch-all for anything we can't recognize. // We use this to be able to ignore and recover all the text // when splitting statements with DelimiterLexer UNRECOGNIZED : . ; ",8395,False,1572.1149920950215,median "= Object Generator v{display-version}, {build-date} :toc: right :sectlinks: :sectanchors: :numbered: :source-highlighter: highlightjs :icons: font :sampledir: ../resources/conf/sample == Introduction Object Generator (OG) is an HTTP object storage load tool designed for system level stress, stability and performance testing. OG supports several common object storage APIs including S3 and OpenStack Swift. == Installation === Minimum Requirements |=== |Component|Configuration |CPU |Dual Core |Memory |4GB system; 2GB available |Free Disk Space |20GB for logging |Operating System |Modern Linux OS* |Java Version |Java 7 |=== NOTE: *OG has been tested on Ubuntu 14.04, but any modern linux OS should work. === Distribution OG is distributed as a _tar.gz_ archive. To install, simply unpack the archive in a directory of your choice. [source, bash, subs=""attributes""] ---- ~$ tar -zxf og-{display-version}.tar.gz ---- == Project Layout The OG project consists of the following files and directories: [source, bash] ---- ~$ tree ├── conf // <1> │   ├── object-file-log4j2.xml │   ├── og-log4j2.xml // <2> │   └── sample // <3> ├── docs │   └── userguide.html <4> ├── lib // <5> ├── log // <6> ├── object // <7> ├── object-file // <8> └── og // <9> ---- <1> Configuration directory. Includes logging configuration and sample test configurations <2> OG logging configuration <3> Sample test configurations <4> This user guide <5> Third party library dependencies <6> Default log location <7> Default object file location <8> Auxiliary object file management script <9> Primary OG load driver script === Invocation OG is a command line load tool which is controlled via the _og_ shell script. .OG Help [source, bash] ---- $ ./og --help Usage: og [] [-v|--version] [-h|--help] [] A relative or absolute path to an og json configuration file [-v|--version] Prints the og version and exits [-h|--help] Prints this help and exits ---- To run a test with OG, call the _og_ shell script with a relative or absolute path to a configuration file: .Basic Invocation [source, bash, subs=""attributes""] ---- $ ./og conf/sample/simple-s3.json ------------------------------------------------------------------------------- Object Generator ({display-version}) ------------------------------------------------------------------------------- Configuring... Configured. Test Running... Test Completed. ------------------------------------------------------------------------------- Summary ------------------------------------------------------------------------------- Start: 21/Jan/2016:23:20:31 -0600 End: 21/Jan/2016:23:20:32 -0600 Runtime: 0.29 Seconds Operations: 31 [WRITE] Operations: 31 Bytes: 310.00 Throughput: 1.07 KB/s OPS: 107.27 Status Codes: 201: 31 [READ] Operations: 0 Bytes: 0.00 Throughput: 0.00 B/s OPS: 0.00 Status Codes: N/A [DELETE] Operations: 0 Bytes: 0.00 Throughput: 0.00 B/s OPS: 0.00 Status Codes: N/A $ ---- == Configuration OG is configured via a json formatted test configuration file. This file controls which object storage API, request mix, file size mix and concurrency to use, and more. To jump straight to complete examples, see <>. Otherwise, the following sections describe OG configuration in detail. === Storage OG supports the following Storage APIs: |=== |Storage API |S3 |OpenStack Swift |Cleversafe SOH |WebDAV |=== Write, Read, Metadata, and Delete operations are supported for each of the supported Storage APIs. In addition, Overwrite is supported for S3 and OpenStack Swift. Storage API is configured via the _api_ key: .S3 API Example [source, json] ---- ""api"": ""s3"" ---- === Authentication OG supports the following authentication configurations: |=== |Authentication |Anonymous |Basic Auth |AWS Auth V2 |AWS Auth V4 |Keystone |=== Authentication is configured via an _authentication_ block of the test configuration: [source, json] ---- ""authentication"": {} ---- Authentication credentials can be provided directly in the OG json config file for a single user. The credentials can also be provided in a CSV formatted file. .CSV Format For Basic and AWS Authentication Example [source, bash] ---- username1,password1 username2,password2 username3,password3 ---- .CSV Format for Keystone Authentication Example [source, bash] ---- token1 token2 token3 ---- ==== Anonymous Anonymous authentication is the default authentication configuration. It is configured by omitting the _authentication_ block from the test configuration. It can also be explicitly configured. .None Auth Example [source, json] ---- ""authentication"": { ""type"": ""none"" } ---- ==== Basic Auth Basic authentication uses base64 encoding to encode username and password credentials into an authorization request header that is sent to the target server. When using basic auth for openstack swift implementation on a dsnet stass based release, storage account field is needed. The given account is used in openstack swift API url. .Basic Auth with Single User Example [source, json] ---- ""authentication"": { ""type"": ""basic"", ""username"": ""my_user"", ""password"": ""my_password"" } ---- .Basic Auth with Single User with OpenStack swift API [source, json] ---- ""authentication"": { ""type"": ""basic"", ""username"": ""my_user"", ""password"": ""my_password"", ""account"": ""swiftaccountX"" } ---- .Basic Auth with Multiple Users Example [source, json] ---- ""authentication"": { ""type"": ""basic"", ""credential_source"": ""file"", ""credential_file"""": ""/var/log/user.csv"" } ---- ==== AWS Auth V2 AWS Auth V2 authentication is an S3 authentication scheme which uses an access key and secret key for credentials. These keys are configured in OG via _username_ and _password_ keys, respectively. .AWS Auth V2 Example [source, json] ---- ""authentication"": { ""type"": ""awsv2"", ""username"": ""AKIAIOSFODNN74SFNMK"", ""password"": ""nJalrUUFklNEMI/K7MDENG/gPwRfiCYXY73DER"" } ---- .AWS Auth V2 with Multiple Users Example [source, json] ---- ""authentication"": { ""type"": ""awsv2"", ""credential_source"": ""file"", ""credential_file"""": ""/var/log/user.csv"" } ---- NOTE: The current AWS Auth V2 implementation does not support virtual host addressing. See <> for more details. ==== AWS Auth V4 AWS Auth V4 authentication is an S3 authentication scheme which uses an access key and secret key for credentials. These keys are configured in OG via _username_ and _password_ keys, respectively. With AWS Auth V4, the body of the request is included in the signing process. AWS Auth V4 requests can either sign the entire request body up front, which requires reading the entire contents first, or sign the body in chunks as the request is sent. Chunked signing is configured via the _aws_chunked_ key. NOTE: For more information about AWS V4 signing, see: http://docs.aws.amazon.com/AmazonS3/latest/dev/RESTAuthentication.html[Signing and Authenticating REST Requests] .AWS Auth V4 With Signing The Entire Request Example [source, json] ---- ""authentication"": { ""type"": ""awsv4"", ""username"": ""AKIAIOSFODNN74SFNMK"", ""password"": ""nJalrUUFklNEMI/K7MDENG/gPwRfiCYXY73DER"" } ---- .AWS Auth V4 With Signing The Entire Request with Multiple Users Example [source, json] ---- ""authentication"": { ""type"": ""awsv4"", ""credential_source"": ""file"", ""credential_file"""": ""/var/log/user.csv"" } ---- .AWS Auth V4 With Chunked Signing Example [source, json] ---- ""authentication"": { ""type"": ""awsv4"", ""username"": ""AKIAIOSFODNN74SFNMK"", ""password"": ""nJalrUUFklNEMI/K7MDENG/gPwRfiCYXY73DER"", ""aws_chunked"": true } ---- .AWS Auth V4 With Chunked Signing with Multiple Users Example [source, json] ---- ""authentication"": { ""type"": ""awsv4"", ""credential_source"": ""file"", ""credential_file"""": ""/var/log/user.csv"", ""aws_chunked"": true } ---- Because the signing process for V4 requests is CPU intensive, OG additionally provides an optional mechanism for caching a portion of the signature process, which reduces the CPU load on the load tool, which in turn reduces the risk of the load tool as a performance bottleneck when executing V4 performance tests. To enable caching, OG must be configured to write objects with all zeroes for data (See <>) so that the signatures are cacheable. Then, to enable the cache, configure the cache size via _aws_cache_size_. .AWS Auth V4 With Signature Caching [source, json] ---- ""authentication"": { ""type"": ""awsv4"", ""username"": ""AKIAIOSFODNN74SFNMK"", ""password"": ""nJalrUUFklNEMI/K7MDENG/gPwRfiCYXY73DER"", ""aws_cache_size"": 10000 } ---- .AWS Auth V4 With Signature Caching with Multiple Users Example [source, json] ---- ""authentication"": { ""type"": ""awsv4"", ""credential_source"": ""file"", ""credential_file"""": ""/var/log/user.csv"", ""aws_cache_size"": 10000 } ---- ==== Keystone Keystone authentication is an OpenStack Swift authentication scheme which typically relies on an external Keystone server to generate an authentication token for use by object storage requests. Keystone support in OG does not include token lookup via an external Keystone server. Rather, OG requires a keystone token be manually generated prior to test start. When using keystone auth for openstack swift implementation on a dsnet stass based release, storage account field is needed. The given account is used in openstack swift API url. .Keystone Example [source, json] ---- ""authentication"": { ""type"": ""keystone"", ""keystone_token"": ""7fe2cd9ee6384a1894a43878d3e52daf"" } ---- .Keystone Example for Openstack API, stass based release [source, json] ---- ""authentication"": { ""type"": ""keystone"", ""keystone_token"": ""7fe2cd9ee6384a1894a43878d3e52daf"", ""account"": ""swiftaccountX"" } ---- .Keystone with Multiple Users Example [source, json] ---- ""authentication"": { ""type"": ""basic"", ""credential_source"": ""file"", ""credential_file"""": ""/var/log/user.csv"" } ---- === Host Host is the target endpoint that the OG load tool communicates with to execute object storage requests. A host can be either a host name or an IPv4 IP address. OG supports single and multiple host configurations. For multiple hosts, OG supports selection of a host for a given request via round robin, random, or weighted random configurations. Host(s) are configured via the _host_ key. NOTE: When testing against a Cleversafe dsNet, the _host_ key refers to Accesser hostnames or IP addresses. .Single Host Example [source, json] ---- ""host"": ""s3.amazonaws.com"" ---- .Multiple Host Round Robin Example [source, json] ---- ""host"": { ""selection"": ""roundrobin"", ""choices"": [""10.129.100.100"", ""s3.amazonaws.com"", ""loadbalancer01.example.com""] } ---- .Multiple Host Random Example [source, json] ---- ""host"": { ""selection"": ""random"", ""choices"": [""10.129.100.100"", ""s3.amazonaws.com""] } ---- .Multiple Host Weighted Random Example [source, json] ---- ""host"": { ""selection"": ""random"", ""choices"": [ { ""choice"": ""10.129.100.100"", ""weight"": 80.0 }, { ""choice"": ""s3.amazonaws.com"", ""weight"": 20.0 } ] } ---- === Port OG supports configuring the port that object storage requests are executed against. Port configuration applies to all configured hosts. Port is configured via the _port_ key. .Port Example [source, json] ---- ""port"": ""8080"" ---- === Container Container is the logical bucket that the OG load tool will write objects into. OG supports single and multiple container configurations. For multiple containers, OG supports selection of a container for a given request via round robin or random configurations. With multiple containers, _prefix_, _min_suffix_ and _max_suffix_ keys are used to produce a range of container names. Container(s) are configured via the _container_ key. This key is available at both the top level and operation level. The most common usage at the operation level is for StaaS container creation. NOTE: If writes are done using container suffixes, then all other operations using these objects will need to use a prefix only or prefix+suffix with the object configuration block. NOTE: When testing against a Cleversafe dsNet, the _container_ key refers to dsNet Vaults or StaaS containers. .Single Container Example [source, json] ---- ""container"": ""my_container"" ---- .Multiple Container Round Robin Example [source, json] ---- ""container"": { ""selection"": ""roundrobin"", ""prefix"": ""my_container"", ""min_suffix"": 0, ""max_suffix"": 100 } ---- .Multiple Container Random Example [source, json] ---- ""container"": { ""selection"": ""random"", ""prefix"": ""my_container"", ""min_suffix"": 0, ""max_suffix"": 100 } ---- === Headers Custom HTTP request headers can be added to every request that is executed. Header values can be constant or dynamic. For dynamic header value configuration, values can be selected via round robin, random or weighted random. Headers are configured via the _headers_ key. NOTE: Custom headers will be added to every request. To add custom headers only for a specific operation type, see <> .Headers Static Values Example [source, json] ---- ""headers"": { ""custom_key_01"": ""custom_value_01"", ""custom_key_02"": ""custom_value_02"" } ---- .Headers Random Dynamic Values Example [source, json] ---- ""headers"": { ""custom_key_01"": { ""selection"": ""random"", ""choices"": [""custom_value_01"", ""custom_value_02"", ""custom_value_03""] }, ""custom_key_02"": ""custom_value_04"" } ---- .Headers Round Robin Dynamic Values Example [source, json] ---- ""headers"": { ""custom_key_01"": { ""selection"": ""roundrobin"", ""choices"": [""custom_value_01"", ""custom_value_02"", ""custom_value_03""] }, ""custom_key_02"": ""custom_value_04"" } ---- .Headers Weighted Random Dynamic Values Example [source, json] ---- ""headers"": { ""custom_key_01"": { ""selection"": ""random"", ""choices"": [ {""choice"": ""custom_value_01"", ""weight"": 20.0}, {""choice"": ""custom_value_02"", ""weight"": 75.0}, {""choice"": ""custom_value_03"", ""weight"": 5.0} ] }, ""custom_key_02"": ""custom_value_04"" } ---- === Write, Overwrite, Read, Metadata, Delete, List, Container Create, Container List, Multipart Write Operations Write, Read, Metadata, Delete, and List operations are supported for all Object Storage APIs. Overwrite is supported for S3 and OpenStack Swift Container Create and Container List are supported for S3 only and the current dsnet implementation requires the uri_root be set to ""/"". Multipart Write is also only supported for S3 Operation mix is configured via _write_, _overwrite_, _read_, _metadata_, _delete_, _list_, _container_create_, _container_list_, _multipart_write_ keys respectively. Each operation type is configured via a configuration block. E.g. for write: [source, json] ---- ""write"": {} ---- The configuration block supports _weight_, _host_, _object_ and _header_ keys. ==== Operation Weight The _weight_ configuration key determines what percentage of requests are of each operation type. .100% Write Example [source, json] ---- ""write"": {""weight"": 100.0}, ""read"": {""weight"": 0.0}, ""delete"": {""weight"": 0.0} ---- ==== Operation Host OG supports overriding the global host configuration for a particular operation type. See <> for more details. ==== Operation Object OG supports multiple object name configurations via the _object_ key: [source, json] ---- ""object"": {} ---- By default, OG will generate a unique, uuid-like object name for every write request. Overwrite, Read, Metadata, and Delete requests will select a random object name from objects which have already been written. List will use a random object name as its starting point and then provide the default number of entries for the associated API. See <>. To override this behavior, the _object_ configuration block can be configured to include _selection_, _prefix_, _min_suffix_ and _max_suffix_ keys. Random and round robin selection configuration is supported. The resulting object name will be of the form: [source, bash] ---- ---- WARNING: Using custom object name configuration bypasses object management. Object names written with a custom prefix and suffix will not be stored in the object manager, for example. CAUTION: The Cleversafe SOH Storage API does not support custom object names. Instead, an auto-generated name is returned to the client after the object has been written. Because of this, custom object name configuration should not be configured in OG for use with the SOH API. .Random Object Name Example [source, json] ---- ""object"": { ""selection"": ""random"", ""prefix"": ""my_object"", ""min_suffix"": 0, ""max_suffix"": 100 } ---- .Round Robin Object Name Example [source, json] ---- ""object"": { ""selection"": ""roundrobin"", ""prefix"": ""my_object"", ""min_suffix"": 0, ""max_suffix"": 100 } ---- ==== Operation Headers OG supports custom headers for a particular operation type. Headers configured for an operation type override any custom headers which were configured generally. See <> for more details. .Custom Headers For Write Requests Example [source, json] ---- ""write"": { ""headers"": { ""custom_key_01"": ""custom_value_01"", ""custom_key_02"": ""custom_value_02"" } } ---- ==== Operation Query Parameters OG supports custom query parameters for a particular operation. This is currently supported only for the List operation. .Custom Query For List Requests Example [source, json] ---- ""list"": { ""parameters"": { ""custom_key_01"": ""custom_value_01"", ""custom_key_02"": ""custom_value_02"" } } ---- ==== Operation Container OG supports the _container_ key at the operation level with some caveats as noted in the Container section. ==== Operation Multipart Write Multipart write supports an additional part size parameter so that the user can define one or more part sizes as part of the object block to use in conjunction with filesize. The default part size is 5MiB and part size is defined in bytes in the config document. .Example Multipart Write using Multiple Part Sizes [source, json] ""multipart_write"": { ""weight"": 100.0, ""object"": {""part_size"":{""selection"":""random"",""choices"":[5242880, 10485760]}} } .Example Multipart Write using a Single Part Size [source, json] ""multipart_write"": { ""weight"": 100.0, ""object"": {""part_size"":5242880, 10485760} } Regarding the OG implementation of Multipart Write, there are some caveats. In the current implementation, OG will send as many INITIATE requests as it can, up to the thread count, until it receives an upload id response from one of the requests. At that point, it will begin sending PART requests for in process multipart sequences in order of INITIATE request responses. Once all parts are uploaded, a COMPLETE will be sent before any other PART or INITIATE requests are sent. For example, in a 100 thread test, up to 100 INITIATE requests will be sent. Once one request returns, it will begin sending parts for that request, up to 100 parts at a time. Once all those parts are in process or finished, it will begin sending parts for the other requests. === Filesize OG supports one or more filesize distributions for describing object file sizes to be written for write requests. If multiple filesize distributions are configured, round robin, random and weighted random selection are supported. Each file size distribution supports _distribution_, _average_, _average_unit_, _spread_ and _spread_unit_ keys. *uniform* and *normal* distributions are supported. For *uniform* distribution, the shape of the distribution is _average_ +/- _spread_. For *normal* distribution the shape of the distribution is centered about _average_, with one standard deviation of _spread_. Both _average_unit_ and _spread_unit_ support a large number of size units. See <> for details. Units are case insensitive. .Single Fixed Filesize (10KB) Example [source, json] ---- ""filesize"": {""average"": 10, ""average_unit"": ""kb""} ---- .Single Filesize Distribution Example [source, json] ---- ""filesize"": { ""distribution"": ""uniform"", ""average"": 10, ""average_unit"": ""kb"", ""spread"": 2, ""spread_unit"": ""kb"" } ---- .Multiple Filesize Distributions Round Robin Example [source, json] ---- ""filesize"": { ""selection"": ""roundrobin"", ""choices"": [ { ""distribution"": ""uniform"", ""average"": 10, ""average_unit"": ""kb"", ""spread"": 2, ""spread_unit"": ""kb"" }, { ""distribution"": ""normal"", ""average"": 100, ""average_unit"": ""mb"" } ] } ---- .Multiple Filesize Distributions Weighted Random Example [source, json] ---- ""filesize"": { ""selection"": ""random"", ""choices"": [ { ""choice"": { ""distribution"": ""uniform"", ""average"": 10, ""average_unit"": ""kb"", ""spread"": 2, ""spread_unit"": ""kb"" }, ""weight"": 80.0 }, { ""choice"": { ""distribution"": ""normal"", ""average"": 100, ""average_unit"": ""mb"" }, ""weight"": 20.0 } ] } ---- === Data Data determines what type of source data is used for write requests. By default, OG will generate a small, fixed buffer of random data for every write request, which is returned repeatedly until the length of the object is satisfied. Optionally, data can be configured to use all zeroes for object content. Data is configured via the _data_ key; valid options are *random* and *zeroes*. .Zeroes Data Example [source, json] ---- ""data"": ""zeroes"" ---- === Concurrency Concurrency configuration allows the OG tool to execute requests in parallel. There are two types of supported concurrency in OG, *threads* and *ops*. Concurrency is configured via the _concurrency_ key. List operations are very resource intensive and excessive concurrency may result in 503 errors. [source, json] ---- ""concurrency"": {} ---- ==== Threads Concurrency Thread testing involves configuring a fixed number of concurrent TCP connections, each of which will execute requests as quickly as possible. Thread based testing is good for measuring system capacity. Thread testing supports _count_, _rampup_ and _rampup_unit_ keys. Rampup allows a thread based test to build up to a steady connection rate over a configurable period of time. .Single Thread Example [source, json] ---- ""concurrency"": { ""type"": ""threads"", ""count"": 1 } ---- .Multiple Threads Example [source, json] ---- ""concurrency"": { ""type"": ""threads"", ""count"": 10 } ---- .Multiple Threads With Rampup Example [source, json] ---- ""concurrency"": { ""type"": ""threads"", ""count"": 10, ""rampup"": 60, ""rampup_unit"": ""seconds"" } ---- See <