index
int64
repo_id
string
file_path
string
content
string
0
java-sources/africa/absa/inception-security/1.2.0/africa/absa/inception
java-sources/africa/absa/inception-security/1.2.0/africa/absa/inception/security/UserStatus.java
/* * Copyright 2021 original 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. */ package africa.absa.inception.security; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonValue; import io.swagger.v3.oas.annotations.media.Schema; /** * The <b>UserStatus</b> enumeration defines the possible statuses for a user. * * @author Marcus Portmann */ @Schema(description = "The user status") public enum UserStatus { /** Inactive. */ INACTIVE("inactive", "Inactive"), /** Active. */ ACTIVE("active", "Active"), /** Locked. */ LOCKED("locked", "Locked"), /** Expired. */ EXPIRED("expired", "Expired"); private final String code; private final String description; UserStatus(String code, String description) { this.code = code; this.description = description; } /** * Returns the numeric code for the user status. * * @param userStatus the user status * @return the numeric code for the user status */ public static int toNumericCode(UserStatus userStatus) { switch (userStatus) { case ACTIVE: return 1; case INACTIVE: return 2; case LOCKED: return 3; case EXPIRED: return 4; default: throw new RuntimeException( "Failed to determine the numeric code for the user status (" + userStatus.code() + ")"); } } /** * Returns the user status for the specified numeric code. * * @param numericCode the numeric code for the user status * @return the user status given by the specified numeric code value */ public static UserStatus fromNumericCode(int numericCode) { switch (numericCode) { case 1: return UserStatus.ACTIVE; case 2: return UserStatus.INACTIVE; case 3: return UserStatus.LOCKED; case 4: return UserStatus.EXPIRED; default: throw new RuntimeException( "Failed to determine the user status for the numeric database code (" + numericCode + ")"); } } /** * Returns the user status given by the specified code value. * * @param code the code for the user status * @return the user status given by the specified code value */ @JsonCreator public static UserStatus fromCode(String code) { switch (code) { case "inactive": return UserStatus.INACTIVE; case "active": return UserStatus.ACTIVE; case "locked": return UserStatus.LOCKED; case "expired": return UserStatus.EXPIRED; default: throw new RuntimeException( "Failed to determine the user status with the invalid code (" + code + ")"); } } /** * Returns the code value for the user status. * * @return the code value for the user status */ @JsonValue public String code() { return code; } /** * Returns the description for the user status. * * @return the description for the user status */ public String description() { return description; } }
0
java-sources/africa/absa/inception-security/1.2.0/africa/absa/inception
java-sources/africa/absa/inception-security/1.2.0/africa/absa/inception/security/UserStatusConverter.java
/* * Copyright 2021 original 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. */ package africa.absa.inception.security; import javax.persistence.AttributeConverter; import javax.persistence.Converter; /** * The <b>UserStatusConverter</b> class implements the custom JPA converter for the <b> * UserStatus</b> enumeration. * * @author Marcus Portmann */ @Converter(autoApply = true) public class UserStatusConverter implements AttributeConverter<UserStatus, Integer> { /** * Converts the value stored in the entity attribute into the data representation to be stored in * the database. * * @param attribute the entity attribute value to be converted * @return the converted data to be stored in the database column */ @Override public Integer convertToDatabaseColumn(UserStatus attribute) { if (attribute == null) return null; return UserStatus.toNumericCode(attribute); } /** * Converts the data stored in the database column into the value to be stored in the entity * attribute. Note that it is the responsibility of the converter writer to specify the correct * dbData type for the corresponding column for use by the JDBC driver: i.e., persistence * providers are not expected to do such type conversion. * * @param dbData the data from the database column to be converted * @return the converted value to be stored in the entity attribute */ @Override public UserStatus convertToEntityAttribute(Integer dbData) { if (dbData == null) return null; return UserStatus.fromNumericCode(dbData); } }
0
java-sources/africa/absa/inception-security/1.2.0/africa/absa/inception
java-sources/africa/absa/inception-security/1.2.0/africa/absa/inception/security/UserStatusToStringConverter.java
/* * Copyright 2021 original 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. */ package africa.absa.inception.security; import org.springframework.core.convert.converter.Converter; import org.springframework.data.convert.WritingConverter; import org.springframework.stereotype.Component; /** * The <b>UserStatusToStringConverter</b> class implements the Spring converter that converts a * <b>UserStatus</b> type into a <b>String</b> type. * * @author Marcus Portmann */ @Component @WritingConverter public class UserStatusToStringConverter implements Converter<UserStatus, String> { /** Constructs a new <b>UserStatusToStringConverter</b>. */ public UserStatusToStringConverter() {} @Override public String convert(UserStatus source) { return source.code(); } }
0
java-sources/africa/absa/inception-security/1.2.0/africa/absa/inception
java-sources/africa/absa/inception-security/1.2.0/africa/absa/inception/security/Users.java
/* * Copyright 2021 original 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. */ package africa.absa.inception.security; import africa.absa.inception.core.sorting.SortDirection; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonPropertyOrder; import io.swagger.v3.oas.annotations.media.Schema; import java.io.Serializable; import java.util.List; import java.util.UUID; /** * The <b>Users</b> class holds the results of a request to retrieve a list of users. * * @author Marcus Portmann */ @Schema(description = "The results of a request to retrieve a list of users") @JsonInclude(JsonInclude.Include.NON_NULL) @JsonPropertyOrder({ "userDirectoryId", "users", "total", "filter", "sortBy", "sortDirection", "pageIndex", "pageSize" }) @SuppressWarnings({"unused"}) public class Users implements Serializable { private static final long serialVersionUID = 1000000; /** The optional filter that was applied to the users. */ @Schema(description = "The optional filter that was applied to the users") @JsonProperty private String filter; /** The optional page index. */ @Schema(description = "The optional page index") @JsonProperty private Integer pageIndex; /** The optional page size. */ @Schema(description = "The optional page size") @JsonProperty private Integer pageSize; /** The optional method used to sort the users e.g. by name. */ @Schema(description = "The optional method used to sort the users e.g. by name") @JsonProperty private UserSortBy sortBy; /** The optional sort direction that was applied to the users. */ @Schema(description = "The optional sort direction that was applied to the users") @JsonProperty private SortDirection sortDirection; /** The total number of users. */ @Schema(description = "The total number of users", required = true) @JsonProperty(required = true) private long total; /** The ID for the user directory the users are associated with. */ @Schema( description = "The ID for the user directory the users are associated with", required = true) @JsonProperty(required = true) private UUID userDirectoryId; /** The users. */ @Schema(description = "The users", required = true) @JsonProperty(required = true) private List<User> users; /** Constructs a new <b>Users</b>. */ public Users() {} /** * Constructs a new <b>Users</b>. * * @param userDirectoryId the ID for the user directory the users are associated with * @param users the users * @param total the total number of users * @param filter the optional filter that was applied to the users * @param sortBy the optional method used to sort the users e.g. by name * @param sortDirection the optional sort direction that was applied to the users * @param pageIndex the optional page index * @param pageSize the optional page size */ public Users( UUID userDirectoryId, List<User> users, long total, String filter, UserSortBy sortBy, SortDirection sortDirection, Integer pageIndex, Integer pageSize) { this.userDirectoryId = userDirectoryId; this.users = users; this.total = total; this.filter = filter; this.sortBy = sortBy; this.sortDirection = sortDirection; this.pageIndex = pageIndex; this.pageSize = pageSize; } /** * Returns the optional filter that was applied to the users. * * @return the optional filter that was applied to the users */ public String getFilter() { return filter; } /** * Returns the optional page index. * * @return the optional page index */ public Integer getPageIndex() { return pageIndex; } /** * Returns the optional page size. * * @return the optional page size */ public Integer getPageSize() { return pageSize; } /** * Returns the optional method used to sort the users e.g. by name. * * @return the optional method used to sort the users */ public UserSortBy getSortBy() { return sortBy; } /** * Returns the optional sort direction that was applied to the users. * * @return the optional sort direction that was applied to the users */ public SortDirection getSortDirection() { return sortDirection; } /** * Returns the total number of users. * * @return the total number of users */ public Long getTotal() { return total; } /** * Returns the ID for the user directory the users are associated with. * * @return the ID for the user directory the users are associated with */ public UUID getUserDirectoryId() { return userDirectoryId; } /** * Returns the users. * * @return the users */ public List<User> getUsers() { return users; } }
0
java-sources/africa/absa/inception-security-api/1.2.0/africa/absa/inception
java-sources/africa/absa/inception-security-api/1.2.0/africa/absa/inception/security/SecurityApi.java
/* * Copyright 2021 original 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. */ package africa.absa.inception.security; import africa.absa.inception.api.ApiUtil; import africa.absa.inception.api.ProblemDetails; import africa.absa.inception.api.SecureApi; import africa.absa.inception.core.service.InvalidArgumentException; import africa.absa.inception.core.service.ServiceUnavailableException; import africa.absa.inception.core.service.ValidationError; import africa.absa.inception.core.sorting.SortDirection; import io.swagger.v3.oas.annotations.Operation; import io.swagger.v3.oas.annotations.Parameter; import io.swagger.v3.oas.annotations.media.Content; import io.swagger.v3.oas.annotations.media.Schema; import io.swagger.v3.oas.annotations.responses.ApiResponse; import io.swagger.v3.oas.annotations.responses.ApiResponses; import io.swagger.v3.oas.annotations.tags.Tag; import java.util.ArrayList; import java.util.List; import java.util.Optional; import java.util.Set; import java.util.UUID; import javax.validation.ConstraintViolation; import javax.validation.Validator; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.context.ApplicationContext; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.security.access.AccessDeniedException; import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.security.core.Authentication; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.util.StringUtils; import org.springframework.web.bind.annotation.CrossOrigin; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseStatus; import org.springframework.web.bind.annotation.RestController; /** * The <b>SecurityApi</b> class. * * @author Marcus Portmann */ @Tag(name = "Security") @RestController @RequestMapping(value = "/api/security") @CrossOrigin @SuppressWarnings({"unused", "WeakerAccess"}) // @el (isSecurityDisabled: africa.absa.inception.api.ApiSecurityExpressionRoot.isSecurityEnabled) public class SecurityApi extends SecureApi { /* Logger */ private static final Logger logger = LoggerFactory.getLogger(SecurityApi.class); /** The Security Service. */ private final ISecurityService securityService; /** The JSR-303 validator. */ private final Validator validator; /** * Constructs a new <b>SecurityRestController</b>. * * @param applicationContext the Spring application context * @param validator the JSR-303 validator * @param securityService the Security Service */ public SecurityApi( ApplicationContext applicationContext, Validator validator, ISecurityService securityService) { super(applicationContext); this.validator = validator; this.securityService = securityService; } /** * Add the group member to the group. * * @param userDirectoryId the ID for the user directory * @param groupName the name of the group * @param groupMember the group member * @throws InvalidArgumentException if an argument is invalid * @throws UserDirectoryNotFoundException if the user directory could not be found * @throws GroupNotFoundException if the group could not be found * @throws UserNotFoundException if the user could not be found * @throws ServiceUnavailableException if the group member could not be added to the group */ @Operation( summary = "Add the group member to the group", description = "Add the group member to the group") @ApiResponses( value = { @ApiResponse( responseCode = "204", description = "The group member was successfully added to the group"), @ApiResponse( responseCode = "400", description = "Invalid argument", content = @Content( mediaType = "application/problem+json", schema = @Schema(implementation = ProblemDetails.class))), @ApiResponse( responseCode = "403", description = "Access denied", content = @Content( mediaType = "application/problem+json", schema = @Schema(implementation = ProblemDetails.class))), @ApiResponse( responseCode = "404", description = "The user directory or group or user could not be found", content = @Content( mediaType = "application/problem+json", schema = @Schema(implementation = ProblemDetails.class))), @ApiResponse( responseCode = "409", description = "The group member already exists", content = @Content( mediaType = "application/problem+json", schema = @Schema(implementation = ProblemDetails.class))), @ApiResponse( responseCode = "500", description = "An error has occurred and the request could not be processed at this time", content = @Content( mediaType = "application/problem+json", schema = @Schema(implementation = ProblemDetails.class))) }) @RequestMapping( value = "/user-directories/{userDirectoryId}/groups/{groupName}/members", method = RequestMethod.POST, produces = "application/json") @ResponseStatus(HttpStatus.NO_CONTENT) @PreAuthorize( "isSecurityDisabled() or hasRole('Administrator') or hasAuthority('FUNCTION_Security.TenantAdministration') or hasAuthority('FUNCTION_Security.GroupAdministration')") public void addMemberToGroup( @Parameter( name = "userDirectoryId", description = "The ID for the user directory", required = true) @PathVariable UUID userDirectoryId, @Parameter(name = "groupName", description = "The name of the group", required = true) @PathVariable String groupName, @io.swagger.v3.oas.annotations.parameters.RequestBody( description = "The group member association to add", required = true) @RequestBody GroupMember groupMember) throws InvalidArgumentException, UserDirectoryNotFoundException, GroupNotFoundException, UserNotFoundException, ServiceUnavailableException { if (!hasAccessToUserDirectory(userDirectoryId)) { throw new AccessDeniedException( "Access denied to the user directory (" + userDirectoryId + ")"); } if (!StringUtils.hasText(groupName)) { throw new InvalidArgumentException("groupName"); } if (groupMember == null) { throw new InvalidArgumentException("groupMember"); } if (!userDirectoryId.equals(groupMember.getUserDirectoryId())) { throw new InvalidArgumentException("groupMember"); } if (!groupName.equals(groupMember.getGroupName())) { throw new InvalidArgumentException("groupMember"); } Set<ConstraintViolation<GroupMember>> constraintViolations = validator.validate(groupMember); if (!constraintViolations.isEmpty()) { throw new InvalidArgumentException( "groupMember", ValidationError.toValidationErrors(constraintViolations)); } securityService.addMemberToGroup( userDirectoryId, groupName, groupMember.getMemberType(), groupMember.getMemberName()); } /** * Add the role to the group. * * @param userDirectoryId the ID for the user directory * @param groupName the name of the group * @param groupRole the group role * @throws InvalidArgumentException if an argument is invalid * @throws UserDirectoryNotFoundException if the user directory could not be found * @throws GroupNotFoundException if the group could not be found * @throws RoleNotFoundException if the role could not be found * @throws ServiceUnavailableException if the role could not be added to the group */ @Operation(summary = "Add the role to the group", description = "Add the role to the group") @ApiResponses( value = { @ApiResponse( responseCode = "204", description = "The role was successfully added to the group"), @ApiResponse( responseCode = "400", description = "Invalid argument", content = @Content( mediaType = "application/problem+json", schema = @Schema(implementation = ProblemDetails.class))), @ApiResponse( responseCode = "403", description = "Access denied", content = @Content( mediaType = "application/problem+json", schema = @Schema(implementation = ProblemDetails.class))), @ApiResponse( responseCode = "404", description = "The user directory or group or role could not be found", content = @Content( mediaType = "application/problem+json", schema = @Schema(implementation = ProblemDetails.class))), @ApiResponse( responseCode = "409", description = "The group role already exists", content = @Content( mediaType = "application/problem+json", schema = @Schema(implementation = ProblemDetails.class))), @ApiResponse( responseCode = "500", description = "An error has occurred and the request could not be processed at this time", content = @Content( mediaType = "application/problem+json", schema = @Schema(implementation = ProblemDetails.class))) }) @RequestMapping( value = "/user-directories/{userDirectoryId}/groups/{groupName}/roles", method = RequestMethod.POST, produces = "application/json") @ResponseStatus(HttpStatus.NO_CONTENT) @PreAuthorize( "isSecurityDisabled() or hasRole('Administrator') or hasAuthority('FUNCTION_Security.TenantAdministration') or hasAuthority('FUNCTION_Security.GroupAdministration')") public void addRoleToGroup( @Parameter( name = "userDirectoryId", description = "The ID for the user directory", required = true) @PathVariable UUID userDirectoryId, @Parameter(name = "groupName", description = "The name of the group", required = true) @PathVariable String groupName, @io.swagger.v3.oas.annotations.parameters.RequestBody( description = "The group role association to add", required = true) @RequestBody GroupRole groupRole) throws InvalidArgumentException, UserDirectoryNotFoundException, GroupNotFoundException, RoleNotFoundException, ServiceUnavailableException { if (!hasAccessToUserDirectory(userDirectoryId)) { throw new AccessDeniedException( "Access denied to the user directory (" + userDirectoryId + ")"); } if (!StringUtils.hasText(groupName)) { throw new InvalidArgumentException("groupName"); } if (groupRole == null) { throw new InvalidArgumentException("groupRole"); } if (!userDirectoryId.equals(groupRole.getUserDirectoryId())) { throw new InvalidArgumentException("groupRole"); } if (!groupName.equals(groupRole.getGroupName())) { throw new InvalidArgumentException("groupRole"); } Set<ConstraintViolation<GroupRole>> constraintViolations = validator.validate(groupRole); if (!constraintViolations.isEmpty()) { throw new InvalidArgumentException( "groupRole", ValidationError.toValidationErrors(constraintViolations)); } if (groupRole.getRoleCode().equalsIgnoreCase(SecurityService.ADMINISTRATOR_ROLE_CODE) && (!hasRole(SecurityService.ADMINISTRATOR_ROLE_CODE))) { throw new AccessDeniedException( "Insufficient authority to add the " + SecurityService.ADMINISTRATOR_ROLE_CODE + " role to the group (" + groupName + ") for the user directory (" + userDirectoryId + ")"); } securityService.addRoleToGroup(userDirectoryId, groupName, groupRole.getRoleCode()); } /** * Add the user directory to the tenant. * * @param tenantId the ID for the tenant * @param tenantUserDirectory the tenant user directory * @throws InvalidArgumentException if an argument is invalid * @throws TenantNotFoundException if the tenant could not be found * @throws UserDirectoryNotFoundException if the user directory could not be found * @throws ServiceUnavailableException if the user directory could not be added to the tenant */ @Operation( summary = "Add the user directory to the tenant", description = "Add the user directory to the tenant") @ApiResponses( value = { @ApiResponse( responseCode = "204", description = "The user directory was successfully added to the tenant"), @ApiResponse( responseCode = "400", description = "Invalid argument", content = @Content( mediaType = "application/problem+json", schema = @Schema(implementation = ProblemDetails.class))), @ApiResponse( responseCode = "403", description = "Access denied", content = @Content( mediaType = "application/problem+json", schema = @Schema(implementation = ProblemDetails.class))), @ApiResponse( responseCode = "404", description = "The tenant or user directory could not be found", content = @Content( mediaType = "application/problem+json", schema = @Schema(implementation = ProblemDetails.class))), @ApiResponse( responseCode = "409", description = "The tenant user directory already exists", content = @Content( mediaType = "application/problem+json", schema = @Schema(implementation = ProblemDetails.class))), @ApiResponse( responseCode = "500", description = "An error has occurred and the request could not be processed at this time", content = @Content( mediaType = "application/problem+json", schema = @Schema(implementation = ProblemDetails.class))) }) @RequestMapping( value = "/tenants/{tenantId}/user-directories", method = RequestMethod.POST, produces = "application/json") @ResponseStatus(HttpStatus.NO_CONTENT) @PreAuthorize( "isSecurityDisabled() or hasRole('Administrator') or hasAuthority('FUNCTION_Security.TenantAdministration')") public void addUserDirectoryToTenant( @Parameter(name = "tenantId", description = "The ID for the tenant", required = true) @PathVariable UUID tenantId, @io.swagger.v3.oas.annotations.parameters.RequestBody( description = "The tenant user directory association to add", required = true) @RequestBody TenantUserDirectory tenantUserDirectory) throws InvalidArgumentException, TenantNotFoundException, UserDirectoryNotFoundException, ServiceUnavailableException { Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); if (tenantId == null) { throw new InvalidArgumentException("tenantId"); } if (tenantUserDirectory == null) { throw new InvalidArgumentException("tenantUserDirectory"); } if (!tenantId.equals(tenantUserDirectory.getTenantId())) { throw new InvalidArgumentException("tenantUserDirectory"); } Set<ConstraintViolation<TenantUserDirectory>> constraintViolations = validator.validate(tenantUserDirectory); if (!constraintViolations.isEmpty()) { throw new InvalidArgumentException( "tenantUserDirectory", ValidationError.toValidationErrors(constraintViolations)); } if (!tenantUserDirectory.getTenantId().equals(tenantId)) { throw new InvalidArgumentException("tenantId"); } securityService.addUserDirectoryToTenant(tenantId, tenantUserDirectory.getUserDirectoryId()); } /** * Administratively change the password for the user. * * @param userDirectoryId the ID for the user directory * @param username the username for the user * @param passwordChange the password change * @throws InvalidArgumentException if an argument is invalid * @throws UserDirectoryNotFoundException if the user directory could not be found * @throws UserNotFoundException if the user could not be found * @throws ServiceUnavailableException if the password could not be administratively changed */ @Operation( summary = "Administratively change the password for the user", description = "Administratively change the password for the user") @ApiResponses( value = { @ApiResponse( responseCode = "204", description = "The password for the user was changed successfully"), @ApiResponse( responseCode = "400", description = "Invalid argument", content = @Content( mediaType = "application/problem+json", schema = @Schema(implementation = ProblemDetails.class))), @ApiResponse( responseCode = "403", description = "Access denied", content = @Content( mediaType = "application/problem+json", schema = @Schema(implementation = ProblemDetails.class))), @ApiResponse( responseCode = "404", description = "The user directory or user could not be found", content = @Content( mediaType = "application/problem+json", schema = @Schema(implementation = ProblemDetails.class))), @ApiResponse( responseCode = "500", description = "An error has occurred and the request could not be processed at this time", content = @Content( mediaType = "application/problem+json", schema = @Schema(implementation = ProblemDetails.class))) }) @RequestMapping( value = "/user-directories/{userDirectoryId}/users/{username}/password", method = RequestMethod.PUT, produces = "application/json") @ResponseStatus(HttpStatus.NO_CONTENT) @PreAuthorize( "isSecurityDisabled() or hasRole('Administrator') or hasAuthority('FUNCTION_Security.TenantAdministration') or hasAuthority('FUNCTION_Security.UserAdministration') or hasAuthority('FUNCTION_Security.ResetUserPassword')") public void adminChangePassword( @Parameter( name = "userDirectoryId", description = "The ID for the user directory", required = true) @PathVariable UUID userDirectoryId, @Parameter(name = "username", description = "The username for the user", required = true) @PathVariable String username, @io.swagger.v3.oas.annotations.parameters.RequestBody( description = "The password change to apply", required = true) @RequestBody PasswordChange passwordChange) throws InvalidArgumentException, UserDirectoryNotFoundException, UserNotFoundException, ServiceUnavailableException { if (!hasAccessToUserDirectory(userDirectoryId)) { throw new AccessDeniedException( "Access denied to the user directory (" + userDirectoryId + ")"); } if (!StringUtils.hasText(username)) { throw new InvalidArgumentException("username"); } if (passwordChange == null) { throw new InvalidArgumentException("passwordChange"); } if (!StringUtils.hasText(passwordChange.getNewPassword())) { throw new InvalidArgumentException("passwordChange"); } Set<ConstraintViolation<PasswordChange>> constraintViolations = validator.validate(passwordChange); if (!constraintViolations.isEmpty()) { throw new InvalidArgumentException( "passwordChange", ValidationError.toValidationErrors(constraintViolations)); } securityService.adminChangePassword( userDirectoryId, username, passwordChange.getNewPassword(), passwordChange.getExpirePassword() != null && passwordChange.getExpirePassword(), passwordChange.getLockUser() != null && passwordChange.getLockUser(), passwordChange.getResetPasswordHistory() != null && passwordChange.getResetPasswordHistory(), passwordChange.getReason()); } /** * Change the password for the user. * * @param username the username for the user * @param passwordChange the password change * @throws InvalidArgumentException if an argument is invalid * @throws UserDirectoryNotFoundException if the user directory could not be found * @throws UserNotFoundException if the user could not be found * @throws AuthenticationFailedException if the authentication failed * @throws InvalidSecurityCodeException if the security code is invalid * @throws ExistingPasswordException if the user has previously used the new password * @throws UserLockedException if the user is locked * @throws ServiceUnavailableException if the password could not be changed */ @Operation( summary = "Change the password for the user", description = "Change the password for the user") @ApiResponses( value = { @ApiResponse( responseCode = "204", description = "The password for the user was changed successfully"), @ApiResponse( responseCode = "400", description = "Invalid argument", content = @Content( mediaType = "application/problem+json", schema = @Schema(implementation = ProblemDetails.class))), @ApiResponse( responseCode = "403", description = "Access denied", content = @Content( mediaType = "application/problem+json", schema = @Schema(implementation = ProblemDetails.class))), @ApiResponse( responseCode = "401", description = "Authentication failed or invalid security code", content = @Content( mediaType = "application/problem+json", schema = @Schema(implementation = ProblemDetails.class))), @ApiResponse( responseCode = "403", description = "The user has exceeded the maximum number of failed password attempts and has been locked", content = @Content( mediaType = "application/problem+json", schema = @Schema(implementation = ProblemDetails.class))), @ApiResponse( responseCode = "404", description = "The user directory or user could not be found", content = @Content( mediaType = "application/problem+json", schema = @Schema(implementation = ProblemDetails.class))), @ApiResponse( responseCode = "409", description = "The new password for the user has been used recently and is not valid", content = @Content( mediaType = "application/problem+json", schema = @Schema(implementation = ProblemDetails.class))), @ApiResponse( responseCode = "500", description = "An error has occurred and the request could not be processed at this time", content = @Content( mediaType = "application/problem+json", schema = @Schema(implementation = ProblemDetails.class))) }) @RequestMapping( value = "/users/{username}/password", method = RequestMethod.PUT, produces = "application/json") @ResponseStatus(HttpStatus.NO_CONTENT) public void changePassword( @Parameter(name = "username", description = "The username for the user", required = true) @PathVariable String username, @io.swagger.v3.oas.annotations.parameters.RequestBody( description = "The password change to apply", required = true) @RequestBody PasswordChange passwordChange) throws InvalidArgumentException, UserDirectoryNotFoundException, UserNotFoundException, AuthenticationFailedException, InvalidSecurityCodeException, ExistingPasswordException, UserLockedException, ServiceUnavailableException { if (!StringUtils.hasText(username)) { throw new InvalidArgumentException("username"); } if (passwordChange == null) { throw new InvalidArgumentException("passwordChange"); } if (!StringUtils.hasText(passwordChange.getNewPassword())) { throw new InvalidArgumentException("passwordChange"); } Set<ConstraintViolation<PasswordChange>> constraintViolations = validator.validate(passwordChange); if (!constraintViolations.isEmpty()) { throw new InvalidArgumentException( "passwordChange", ValidationError.toValidationErrors(constraintViolations)); } if (passwordChange.getReason() == PasswordChangeReason.ADMINISTRATIVE) { if (isSecurityDisabled() || hasRole(SecurityService.ADMINISTRATOR_ROLE_CODE) || hasAccessToFunction("Security.TenantAdministration") || hasAccessToFunction("Security.UserAdministration") || hasAccessToFunction("Security.ResetUserPassword")) { Optional<UUID> userDirectoryIdOptional = securityService.getUserDirectoryIdForUser(username); if (userDirectoryIdOptional.isEmpty()) { throw new UserNotFoundException(username); } UUID userDirectoryId = userDirectoryIdOptional.get(); if (isSecurityEnabled() && (!hasAccessToUserDirectory(userDirectoryId))) { throw new AccessDeniedException( "Access denied to the user directory (" + userDirectoryId + ")"); } securityService.adminChangePassword( userDirectoryId, username, passwordChange.getNewPassword(), passwordChange.getExpirePassword() != null && passwordChange.getExpirePassword(), passwordChange.getLockUser() != null && passwordChange.getLockUser(), passwordChange.getResetPasswordHistory() != null && passwordChange.getResetPasswordHistory(), passwordChange.getReason()); } else { throw new AccessDeniedException( "Insufficient access to change the password for the user (" + username + ")"); } } else if (passwordChange.getReason() == PasswordChangeReason.USER) { if (!StringUtils.hasText(passwordChange.getPassword())) { throw new InvalidArgumentException("passwordChange"); } securityService.changePassword( username, passwordChange.getPassword(), passwordChange.getNewPassword()); } else if (passwordChange.getReason() == PasswordChangeReason.RESET) { if (!StringUtils.hasText(passwordChange.getSecurityCode())) { throw new InvalidArgumentException("passwordChange"); } securityService.resetPassword( username, passwordChange.getNewPassword(), passwordChange.getSecurityCode()); } } /** * Create the new group. * * @param userDirectoryId the ID for the user directory * @param group the group * @throws InvalidArgumentException if an argument is invalid * @throws UserDirectoryNotFoundException if the user directory could not be found * @throws DuplicateGroupException if the group already exists * @throws ServiceUnavailableException if the group could not be created */ @Operation(summary = "Create the group", description = "Create the group") @ApiResponses( value = { @ApiResponse(responseCode = "204", description = "The group was created successfully"), @ApiResponse( responseCode = "400", description = "Invalid argument", content = @Content( mediaType = "application/problem+json", schema = @Schema(implementation = ProblemDetails.class))), @ApiResponse( responseCode = "403", description = "Access denied", content = @Content( mediaType = "application/problem+json", schema = @Schema(implementation = ProblemDetails.class))), @ApiResponse( responseCode = "404", description = "The user directory could not be found", content = @Content( mediaType = "application/problem+json", schema = @Schema(implementation = ProblemDetails.class))), @ApiResponse( responseCode = "409", description = "A group with the specified name already exists", content = @Content( mediaType = "application/problem+json", schema = @Schema(implementation = ProblemDetails.class))), @ApiResponse( responseCode = "500", description = "An error has occurred and the request could not be processed at this time", content = @Content( mediaType = "application/problem+json", schema = @Schema(implementation = ProblemDetails.class))) }) @RequestMapping( value = "/user-directories/{userDirectoryId}/groups", method = RequestMethod.POST, produces = "application/json") @ResponseStatus(HttpStatus.NO_CONTENT) @PreAuthorize( "isSecurityDisabled() or hasRole('Administrator') or hasAuthority('FUNCTION_Security.TenantAdministration') or hasAuthority('FUNCTION_Security.GroupAdministration')") public void createGroup( @Parameter( name = "userDirectoryId", description = "The ID for the user directory", required = true) @PathVariable UUID userDirectoryId, @io.swagger.v3.oas.annotations.parameters.RequestBody( description = "The group to create", required = true) @RequestBody Group group) throws InvalidArgumentException, UserDirectoryNotFoundException, DuplicateGroupException, ServiceUnavailableException { if (!hasAccessToUserDirectory(userDirectoryId)) { throw new AccessDeniedException( "Access denied to the user directory (" + userDirectoryId + ")"); } if (group == null) { throw new InvalidArgumentException("group"); } if (!userDirectoryId.equals(group.getUserDirectoryId())) { throw new InvalidArgumentException("group"); } securityService.createGroup(group); } /** * Create the new tenant. * * @param tenant the tenant * @param createUserDirectory should a new internal user directory be created for the tenant * @throws InvalidArgumentException if an argument is invalid * @throws DuplicateTenantException if the tenant already exists * @throws ServiceUnavailableException if the tenant could not be created */ @Operation(summary = "Create the tenant", description = "Create the tenant") @ApiResponses( value = { @ApiResponse(responseCode = "204", description = "The tenant was created successfully"), @ApiResponse( responseCode = "400", description = "Invalid argument", content = @Content( mediaType = "application/problem+json", schema = @Schema(implementation = ProblemDetails.class))), @ApiResponse( responseCode = "403", description = "Access denied", content = @Content( mediaType = "application/problem+json", schema = @Schema(implementation = ProblemDetails.class))), @ApiResponse( responseCode = "409", description = "An tenant with the specified ID or name already exists", content = @Content( mediaType = "application/problem+json", schema = @Schema(implementation = ProblemDetails.class))), @ApiResponse( responseCode = "500", description = "An error has occurred and the request could not be processed at this time", content = @Content( mediaType = "application/problem+json", schema = @Schema(implementation = ProblemDetails.class))) }) @RequestMapping(value = "/tenants", method = RequestMethod.POST, produces = "application/json") @ResponseStatus(HttpStatus.NO_CONTENT) @PreAuthorize( "isSecurityDisabled() or hasRole('Administrator') or hasAuthority('FUNCTION_Security.TenantAdministration')") public void createTenant( @io.swagger.v3.oas.annotations.parameters.RequestBody( description = "The tenant to create", required = true) @RequestBody Tenant tenant, @Parameter( name = "createUserDirectory", description = "Should a new internal user directory be created for the tenant") @RequestParam(value = "createUserDirectory", required = false) Boolean createUserDirectory) throws InvalidArgumentException, DuplicateTenantException, ServiceUnavailableException { securityService.createTenant(tenant, (createUserDirectory != null) && createUserDirectory); } /** * Create the new user. * * @param userDirectoryId the ID for the user directory * @param user the user * @param expiredPassword create the user with its password expired * @param userLocked create the user locked * @throws InvalidArgumentException if an argument is invalid * @throws UserDirectoryNotFoundException if the user directory could not be found * @throws DuplicateUserException if the user already exists * @throws ServiceUnavailableException if the user could not be created */ @Operation(summary = "Create the user", description = "Create the user") @ApiResponses( value = { @ApiResponse(responseCode = "204", description = "The user was created successfully"), @ApiResponse( responseCode = "400", description = "Invalid argument", content = @Content( mediaType = "application/problem+json", schema = @Schema(implementation = ProblemDetails.class))), @ApiResponse( responseCode = "403", description = "Access denied", content = @Content( mediaType = "application/problem+json", schema = @Schema(implementation = ProblemDetails.class))), @ApiResponse( responseCode = "404", description = "The user directory could not be found", content = @Content( mediaType = "application/problem+json", schema = @Schema(implementation = ProblemDetails.class))), @ApiResponse( responseCode = "409", description = "A user with the specified username already exists", content = @Content( mediaType = "application/problem+json", schema = @Schema(implementation = ProblemDetails.class))), @ApiResponse( responseCode = "500", description = "An error has occurred and the request could not be processed at this time", content = @Content( mediaType = "application/problem+json", schema = @Schema(implementation = ProblemDetails.class))) }) @RequestMapping( value = "/user-directories/{userDirectoryId}/users", method = RequestMethod.POST, produces = "application/json") @ResponseStatus(HttpStatus.NO_CONTENT) @PreAuthorize( "isSecurityDisabled() or hasRole('Administrator') or hasAuthority('FUNCTION_Security.TenantAdministration') or hasAuthority('FUNCTION_Security.UserAdministration')") public void createUser( @Parameter( name = "userDirectoryId", description = "The ID for the user directory", required = true) @PathVariable UUID userDirectoryId, @io.swagger.v3.oas.annotations.parameters.RequestBody( description = "The user to create", required = true) @RequestBody User user, @Parameter( name = "expiredPassword", description = "Create the user with its password expired") @RequestParam(value = "expiredPassword", required = false) Boolean expiredPassword, @Parameter(name = "userLocked", description = "Create the user locked") @RequestParam(value = "userLocked", required = false) Boolean userLocked) throws InvalidArgumentException, UserDirectoryNotFoundException, DuplicateUserException, ServiceUnavailableException { if (!hasAccessToUserDirectory(userDirectoryId)) { throw new AccessDeniedException( "Access denied to the user directory (" + userDirectoryId + ")"); } if (user == null) { throw new InvalidArgumentException("user"); } if (!userDirectoryId.equals(user.getUserDirectoryId())) { throw new InvalidArgumentException("user"); } securityService.createUser( user, (expiredPassword != null) && expiredPassword, (userLocked != null) && userLocked); } /** * Create the new user directory. * * @param userDirectory the user directory * @throws InvalidArgumentException if an argument is invalid * @throws DuplicateUserDirectoryException if the user directory already exists * @throws ServiceUnavailableException if the user directory could not be created */ @Operation(summary = "Create the user directory", description = "Create the user directory") @ApiResponses( value = { @ApiResponse( responseCode = "204", description = "The user directory was created successfully"), @ApiResponse( responseCode = "400", description = "Invalid argument", content = @Content( mediaType = "application/problem+json", schema = @Schema(implementation = ProblemDetails.class))), @ApiResponse( responseCode = "403", description = "Access denied", content = @Content( mediaType = "application/problem+json", schema = @Schema(implementation = ProblemDetails.class))), @ApiResponse( responseCode = "409", description = "A user directory with the specified ID or name already exists", content = @Content( mediaType = "application/problem+json", schema = @Schema(implementation = ProblemDetails.class))), @ApiResponse( responseCode = "500", description = "An error has occurred and the request could not be processed at this time", content = @Content( mediaType = "application/problem+json", schema = @Schema(implementation = ProblemDetails.class))) }) @RequestMapping( value = "/user-directories", method = RequestMethod.POST, produces = "application/json") @ResponseStatus(HttpStatus.NO_CONTENT) @PreAuthorize( "isSecurityDisabled() or hasRole('Administrator') or hasAuthority('FUNCTION_Security.UserDirectoryAdministration')") public void createUserDirectory( @io.swagger.v3.oas.annotations.parameters.RequestBody( description = "The user directory to create", required = true) @RequestBody UserDirectory userDirectory) throws InvalidArgumentException, DuplicateUserDirectoryException, ServiceUnavailableException { securityService.createUserDirectory(userDirectory); } /** * Delete the group. * * @param userDirectoryId the ID for the user directory * @param groupName the name of the group * @throws InvalidArgumentException if an argument is invalid * @throws UserDirectoryNotFoundException if the user directory could not be found * @throws GroupNotFoundException if the group could not be found * @throws ExistingGroupMembersException if the group has existing members * @throws ServiceUnavailableException if the group could not be deleted */ @Operation(summary = "Delete the group", description = "Delete the group") @ApiResponses( value = { @ApiResponse(responseCode = "204", description = "The group was deleted successfully"), @ApiResponse( responseCode = "400", description = "Invalid argument", content = @Content( mediaType = "application/problem+json", schema = @Schema(implementation = ProblemDetails.class))), @ApiResponse( responseCode = "403", description = "Access denied", content = @Content( mediaType = "application/problem+json", schema = @Schema(implementation = ProblemDetails.class))), @ApiResponse( responseCode = "404", description = "The user directory or group could not be found", content = @Content( mediaType = "application/problem+json", schema = @Schema(implementation = ProblemDetails.class))), @ApiResponse( responseCode = "409", description = "The group could not be deleted since it is still associated with 1 or more user(s)", content = @Content( mediaType = "application/problem+json", schema = @Schema(implementation = ProblemDetails.class))), @ApiResponse( responseCode = "500", description = "An error has occurred and the request could not be processed at this time", content = @Content( mediaType = "application/problem+json", schema = @Schema(implementation = ProblemDetails.class))) }) @RequestMapping( value = "/user-directories/{userDirectoryId}/groups/{groupName}", method = RequestMethod.DELETE, produces = "application/json") @ResponseStatus(HttpStatus.NO_CONTENT) @PreAuthorize( "isSecurityDisabled() or hasRole('Administrator') or hasAuthority('FUNCTION_Security.TenantAdministration') or hasAuthority('FUNCTION_Security.GroupAdministration')") public void deleteGroup( @Parameter( name = "userDirectoryId", description = "The ID for the user directory", required = true) @PathVariable UUID userDirectoryId, @Parameter(name = "groupName", description = "The name of the group", required = true) @PathVariable String groupName) throws InvalidArgumentException, UserDirectoryNotFoundException, GroupNotFoundException, ExistingGroupMembersException, ServiceUnavailableException { if (!hasAccessToUserDirectory(userDirectoryId)) { throw new AccessDeniedException( "Access denied to the user directory (" + userDirectoryId + ")"); } securityService.deleteGroup(userDirectoryId, groupName); } /** * Delete the tenant. * * @param tenantId the ID for the tenant * @throws InvalidArgumentException if an argument is invalid * @throws TenantNotFoundException if the tenant could not be found * @throws ServiceUnavailableException if the tenant could not be deleted */ @Operation(summary = "Delete the tenant", description = "Delete the tenant") @ApiResponses( value = { @ApiResponse(responseCode = "204", description = "The tenant was deleted successfully"), @ApiResponse( responseCode = "400", description = "Invalid argument", content = @Content( mediaType = "application/problem+json", schema = @Schema(implementation = ProblemDetails.class))), @ApiResponse( responseCode = "403", description = "Access denied", content = @Content( mediaType = "application/problem+json", schema = @Schema(implementation = ProblemDetails.class))), @ApiResponse( responseCode = "404", description = "The tenant could not be found", content = @Content( mediaType = "application/problem+json", schema = @Schema(implementation = ProblemDetails.class))), @ApiResponse( responseCode = "500", description = "An error has occurred and the request could not be processed at this time", content = @Content( mediaType = "application/problem+json", schema = @Schema(implementation = ProblemDetails.class))) }) @RequestMapping( value = "/tenants/{tenantId}", method = RequestMethod.DELETE, produces = "application/json") @ResponseStatus(HttpStatus.NO_CONTENT) @PreAuthorize( "isSecurityDisabled() or hasRole('Administrator') or hasAuthority('FUNCTION_Security.TenantAdministration')") public void deleteTenant( @Parameter(name = "tenantId", description = "The ID for the tenant", required = true) @PathVariable UUID tenantId) throws InvalidArgumentException, TenantNotFoundException, ServiceUnavailableException { securityService.deleteTenant(tenantId); } /** * Delete the user. * * @param userDirectoryId the ID for the user directory * @param username the username for the user * @throws InvalidArgumentException if an argument is invalid * @throws UserDirectoryNotFoundException if the user directory could not be found * @throws UserNotFoundException if the user could not be found * @throws ServiceUnavailableException if the user could not be deleted */ @Operation(summary = "Delete the user", description = "Delete the user") @ApiResponses( value = { @ApiResponse(responseCode = "204", description = "The user was deleted successfully"), @ApiResponse( responseCode = "400", description = "Invalid argument", content = @Content( mediaType = "application/problem+json", schema = @Schema(implementation = ProblemDetails.class))), @ApiResponse( responseCode = "403", description = "Access denied", content = @Content( mediaType = "application/problem+json", schema = @Schema(implementation = ProblemDetails.class))), @ApiResponse( responseCode = "404", description = "The user directory or user could not be found", content = @Content( mediaType = "application/problem+json", schema = @Schema(implementation = ProblemDetails.class))), @ApiResponse( responseCode = "500", description = "An error has occurred and the request could not be processed at this time", content = @Content( mediaType = "application/problem+json", schema = @Schema(implementation = ProblemDetails.class))) }) @RequestMapping( value = "/user-directories/{userDirectoryId}/users/{username}", method = RequestMethod.DELETE, produces = "application/json") @ResponseStatus(HttpStatus.NO_CONTENT) @PreAuthorize( "isSecurityDisabled() or hasRole('Administrator') or hasAuthority('FUNCTION_Security.TenantAdministration') or hasAuthority('FUNCTION_Security.UserAdministration')") public void deleteUser( @Parameter( name = "userDirectoryId", description = "The ID for the user directory", required = true) @PathVariable UUID userDirectoryId, @Parameter(name = "username", description = "The username for the user", required = true) @PathVariable String username) throws InvalidArgumentException, UserDirectoryNotFoundException, UserNotFoundException, ServiceUnavailableException { if (!hasAccessToUserDirectory(userDirectoryId)) { throw new AccessDeniedException( "Access denied to the user directory (" + userDirectoryId + ")"); } securityService.deleteUser(userDirectoryId, username); } /** * Delete the user directory. * * @param userDirectoryId the ID for the user directory * @throws InvalidArgumentException if an argument is invalid * @throws UserDirectoryNotFoundException if the user directory could not be found * @throws ServiceUnavailableException if the user directory could not be deleted */ @Operation(summary = "Delete the user directory", description = "Delete the user directory") @ApiResponses( value = { @ApiResponse( responseCode = "204", description = "The user directory was deleted successfully"), @ApiResponse( responseCode = "400", description = "Invalid argument", content = @Content( mediaType = "application/problem+json", schema = @Schema(implementation = ProblemDetails.class))), @ApiResponse( responseCode = "403", description = "Access denied", content = @Content( mediaType = "application/problem+json", schema = @Schema(implementation = ProblemDetails.class))), @ApiResponse( responseCode = "404", description = "The user directory could not be found", content = @Content( mediaType = "application/problem+json", schema = @Schema(implementation = ProblemDetails.class))), @ApiResponse( responseCode = "500", description = "An error has occurred and the request could not be processed at this time", content = @Content( mediaType = "application/problem+json", schema = @Schema(implementation = ProblemDetails.class))) }) @RequestMapping( value = "/user-directories/{userDirectoryId}", method = RequestMethod.DELETE, produces = "application/json") @ResponseStatus(HttpStatus.NO_CONTENT) @PreAuthorize( "isSecurityDisabled() or hasRole('Administrator') or hasAuthority('FUNCTION_Security.UserDirectoryAdministration')") public void deleteUserDirectory( @Parameter( name = "userDirectoryId", description = "The ID for the user directory", required = true) @PathVariable UUID userDirectoryId) throws InvalidArgumentException, UserDirectoryNotFoundException, ServiceUnavailableException { securityService.deleteUserDirectory(userDirectoryId); } /** * Retrieve the group. * * @param userDirectoryId the ID for the user directory * @param groupName the name of the group * @return the group * @throws InvalidArgumentException if an argument is invalid * @throws UserDirectoryNotFoundException if the user directory could not be found * @throws GroupNotFoundException if the group could not be found * @throws ServiceUnavailableException if the group could not be retrieved */ @Operation(summary = "Retrieve the group", description = "Retrieve the group") @ApiResponses( value = { @ApiResponse(responseCode = "200", description = "OK"), @ApiResponse( responseCode = "400", description = "Invalid argument", content = @Content( mediaType = "application/problem+json", schema = @Schema(implementation = ProblemDetails.class))), @ApiResponse( responseCode = "403", description = "Access denied", content = @Content( mediaType = "application/problem+json", schema = @Schema(implementation = ProblemDetails.class))), @ApiResponse( responseCode = "404", description = "The user directory or group could not be found", content = @Content( mediaType = "application/problem+json", schema = @Schema(implementation = ProblemDetails.class))), @ApiResponse( responseCode = "500", description = "An error has occurred and the request could not be processed at this time", content = @Content( mediaType = "application/problem+json", schema = @Schema(implementation = ProblemDetails.class))) }) @RequestMapping( value = "/user-directories/{userDirectoryId}/groups/{groupName}", method = RequestMethod.GET, produces = "application/json") @ResponseStatus(HttpStatus.OK) @PreAuthorize( "isSecurityDisabled() or hasRole('Administrator') or hasAuthority('FUNCTION_Security.TenantAdministration') or hasAuthority('FUNCTION_Security.GroupAdministration')") public Group getGroup( @Parameter( name = "userDirectoryId", description = "The ID for the user directory", required = true) @PathVariable UUID userDirectoryId, @Parameter(name = "groupName", description = "The name of the group", required = true) @PathVariable String groupName) throws InvalidArgumentException, UserDirectoryNotFoundException, GroupNotFoundException, ServiceUnavailableException { if (!hasAccessToUserDirectory(userDirectoryId)) { throw new AccessDeniedException( "Access denied to the user directory (" + userDirectoryId + ")"); } return securityService.getGroup(userDirectoryId, groupName); } /** * Retrieve all the group names. * * @param userDirectoryId the ID for the user directory * @return the group names * @throws InvalidArgumentException if an argument is invalid * @throws UserDirectoryNotFoundException if the user directory could not be found * @throws ServiceUnavailableException if the group names could not be retrieved */ @Operation(summary = "Retrieve the group names", description = "Retrieve the group names") @ApiResponses( value = { @ApiResponse(responseCode = "200", description = "OK"), @ApiResponse( responseCode = "400", description = "Invalid argument", content = @Content( mediaType = "application/problem+json", schema = @Schema(implementation = ProblemDetails.class))), @ApiResponse( responseCode = "403", description = "Access denied", content = @Content( mediaType = "application/problem+json", schema = @Schema(implementation = ProblemDetails.class))), @ApiResponse( responseCode = "404", description = "The user directory could not be found", content = @Content( mediaType = "application/problem+json", schema = @Schema(implementation = ProblemDetails.class))), @ApiResponse( responseCode = "500", description = "An error has occurred and the request could not be processed at this time", content = @Content( mediaType = "application/problem+json", schema = @Schema(implementation = ProblemDetails.class))) }) @RequestMapping( value = "/user-directories/{userDirectoryId}/group-names", method = RequestMethod.GET, produces = "application/json") @ResponseStatus(HttpStatus.OK) @PreAuthorize( "isSecurityDisabled() or hasRole('Administrator') or hasAuthority('FUNCTION_Security.TenantAdministration') or hasAuthority('FUNCTION_Security.GroupAdministration')") public List<String> getGroupNames( @Parameter( name = "userDirectoryId", description = "The ID for the user directory", required = true) @PathVariable UUID userDirectoryId) throws InvalidArgumentException, UserDirectoryNotFoundException, ServiceUnavailableException { if (!hasAccessToUserDirectory(userDirectoryId)) { throw new AccessDeniedException( "Access denied to the user directory (" + userDirectoryId + ")"); } return securityService.getGroupNames(userDirectoryId); } /** * Retrieve the names of the groups the user is a member of. * * @param userDirectoryId the ID for the user directory * @param username the username for the user * @return the names of the groups the user is a member of * @throws InvalidArgumentException if an argument is invalid * @throws UserDirectoryNotFoundException if the user directory could not be found * @throws UserNotFoundException if the user could not be found * @throws ServiceUnavailableException if the names of the groups the user is a member of could * not be retrieved */ @Operation( summary = "Retrieve the names of the groups the user is a member of", description = "Retrieve the names of the groups the user is a member of") @ApiResponses( value = { @ApiResponse(responseCode = "200", description = "OK"), @ApiResponse( responseCode = "400", description = "Invalid argument", content = @Content( mediaType = "application/problem+json", schema = @Schema(implementation = ProblemDetails.class))), @ApiResponse( responseCode = "403", description = "Access denied", content = @Content( mediaType = "application/problem+json", schema = @Schema(implementation = ProblemDetails.class))), @ApiResponse( responseCode = "404", description = "The user directory or user could not be found", content = @Content( mediaType = "application/problem+json", schema = @Schema(implementation = ProblemDetails.class))), @ApiResponse( responseCode = "500", description = "An error has occurred and the request could not be processed at this time", content = @Content( mediaType = "application/problem+json", schema = @Schema(implementation = ProblemDetails.class))) }) @RequestMapping( value = "/user-directories/{userDirectoryId}/users/{username}/group-names", method = RequestMethod.GET, produces = "application/json") @ResponseStatus(HttpStatus.OK) @PreAuthorize( "isSecurityDisabled() or hasRole('Administrator') or hasAuthority('FUNCTION_Security.TenantAdministration') or hasAuthority('FUNCTION_Security.UserAdministration')") public List<String> getGroupNamesForUser( @Parameter( name = "userDirectoryId", description = "The ID for the user directory", required = true) @PathVariable UUID userDirectoryId, @Parameter(name = "username", description = "The username for the user", required = true) @PathVariable String username) throws InvalidArgumentException, UserDirectoryNotFoundException, UserNotFoundException, ServiceUnavailableException { if (!hasAccessToUserDirectory(userDirectoryId)) { throw new AccessDeniedException( "Access denied to the user directory (" + userDirectoryId + ")"); } return securityService.getGroupNamesForUser(userDirectoryId, username); } /** * Retrieve the groups. * * @param userDirectoryId the ID for the user directory * @param filter the optional filter to apply to the groups * @param sortDirection the optional sort direction to apply to the groups * @param pageIndex the optional page index * @param pageSize the optional page size * @return the groups * @throws InvalidArgumentException if an argument is invalid * @throws UserDirectoryNotFoundException if the user directory could not be found * @throws ServiceUnavailableException if the groups could not be retrieved */ @Operation(summary = "Retrieve the groups", description = "Retrieve the groups") @ApiResponses( value = { @ApiResponse(responseCode = "200", description = "OK"), @ApiResponse( responseCode = "400", description = "Invalid argument", content = @Content( mediaType = "application/problem+json", schema = @Schema(implementation = ProblemDetails.class))), @ApiResponse( responseCode = "403", description = "Access denied", content = @Content( mediaType = "application/problem+json", schema = @Schema(implementation = ProblemDetails.class))), @ApiResponse( responseCode = "404", description = "The user directory could not be found", content = @Content( mediaType = "application/problem+json", schema = @Schema(implementation = ProblemDetails.class))), @ApiResponse( responseCode = "500", description = "An error has occurred and the request could not be processed at this time", content = @Content( mediaType = "application/problem+json", schema = @Schema(implementation = ProblemDetails.class))) }) @RequestMapping( value = "/user-directories/{userDirectoryId}/groups", method = RequestMethod.GET, produces = "application/json") @ResponseStatus(HttpStatus.OK) @PreAuthorize( "isSecurityDisabled() or hasRole('Administrator') or hasAuthority('FUNCTION_Security.TenantAdministration') or hasAuthority('FUNCTION_Security.GroupAdministration')") public Groups getGroups( @Parameter( name = "userDirectoryId", description = "The ID for the user directory", required = true) @PathVariable UUID userDirectoryId, @Parameter(name = "filter", description = "The optional filter to apply to the groups") @RequestParam(value = "filter", required = false) String filter, @Parameter( name = "sortDirection", description = "The optional sort direction to apply to the groups") @RequestParam(value = "sortDirection", required = false) SortDirection sortDirection, @Parameter(name = "pageIndex", description = "The optional page index", example = "0") @RequestParam(value = "pageIndex", required = false, defaultValue = "0") Integer pageIndex, @Parameter(name = "pageSize", description = "The optional page size", example = "10") @RequestParam(value = "pageSize", required = false, defaultValue = "10") Integer pageSize) throws InvalidArgumentException, UserDirectoryNotFoundException, ServiceUnavailableException { if (pageIndex == null) { pageIndex = 0; } if (pageSize == null) { pageSize = 10; } if (!hasAccessToUserDirectory(userDirectoryId)) { throw new AccessDeniedException( "Access denied to the user directory (" + userDirectoryId + ")"); } return securityService.getGroups(userDirectoryId, filter, sortDirection, pageIndex, pageSize); } /** * Retrieve the group members for the group. * * @param userDirectoryId the ID for the user directory * @param groupName the name of the group * @param filter the optional filter to apply to the group members * @param sortDirection the optional sort direction to apply to the group members * @param pageIndex the optional page index * @param pageSize the optional page size * @return the group members for the group * @throws InvalidArgumentException if an argument is invalid * @throws UserDirectoryNotFoundException if the user directory could not be found * @throws GroupNotFoundException if the group could not be found * @throws ServiceUnavailableException if the group members could not be retrieved for the group */ @Operation(summary = "Retrieve the group members", description = "Retrieve the group members") @ApiResponses( value = { @ApiResponse(responseCode = "200", description = "OK"), @ApiResponse( responseCode = "400", description = "Invalid argument", content = @Content( mediaType = "application/problem+json", schema = @Schema(implementation = ProblemDetails.class))), @ApiResponse( responseCode = "403", description = "Access denied", content = @Content( mediaType = "application/problem+json", schema = @Schema(implementation = ProblemDetails.class))), @ApiResponse( responseCode = "404", description = "The user directory or group could not be found", content = @Content( mediaType = "application/problem+json", schema = @Schema(implementation = ProblemDetails.class))), @ApiResponse( responseCode = "500", description = "An error has occurred and the request could not be processed at this time", content = @Content( mediaType = "application/problem+json", schema = @Schema(implementation = ProblemDetails.class))) }) @RequestMapping( value = "/user-directories/{userDirectoryId}/groups/{groupName}/members", method = RequestMethod.GET, produces = "application/json") @ResponseStatus(HttpStatus.OK) @PreAuthorize( "isSecurityDisabled() or hasRole('Administrator') or hasAuthority('FUNCTION_Security.TenantAdministration') or hasAuthority('FUNCTION_Security.GroupAdministration')") public GroupMembers getMembersForGroup( @Parameter( name = "userDirectoryId", description = "The ID for the user directory", required = true) @PathVariable UUID userDirectoryId, @Parameter(name = "groupName", description = "The name of the group", required = true) @PathVariable String groupName, @Parameter(name = "filter", description = "The optional filter to apply to the group members") @RequestParam(value = "filter", required = false) String filter, @Parameter( name = "sortDirection", description = "The optional sort direction to apply to the group members") @RequestParam(value = "sortDirection", required = false) SortDirection sortDirection, @Parameter(name = "pageIndex", description = "The optional page index", example = "0") @RequestParam(value = "pageIndex", required = false, defaultValue = "0") Integer pageIndex, @Parameter(name = "pageSize", description = "The optional page size", example = "10") @RequestParam(value = "pageSize", required = false, defaultValue = "10") Integer pageSize) throws InvalidArgumentException, UserDirectoryNotFoundException, GroupNotFoundException, ServiceUnavailableException { if (pageIndex == null) { pageIndex = 0; } if (pageSize == null) { pageSize = 10; } if (!hasAccessToUserDirectory(userDirectoryId)) { throw new AccessDeniedException( "Access denied to the user directory (" + userDirectoryId + ")"); } return securityService.getMembersForGroup( userDirectoryId, groupName, filter, sortDirection, pageIndex, pageSize); } /** * Retrieve the codes for the roles that have been assigned to the group. * * @param userDirectoryId the ID for the user directory * @param groupName the name of the group * @return the codes for the roles that have been assigned to the group * @throws InvalidArgumentException if an argument is invalid * @throws UserDirectoryNotFoundException if the user directory could not be found * @throws GroupNotFoundException if the group could not be found * @throws ServiceUnavailableException if the codes for the roles assigned to the group could not * be retrieved */ @Operation( summary = "Retrieve the codes for the roles that have been assigned to the group", description = "Retrieve the codes for the roles that have been assigned to the group") @ApiResponses( value = { @ApiResponse(responseCode = "200", description = "OK"), @ApiResponse( responseCode = "400", description = "Invalid argument", content = @Content( mediaType = "application/problem+json", schema = @Schema(implementation = ProblemDetails.class))), @ApiResponse( responseCode = "403", description = "Access denied", content = @Content( mediaType = "application/problem+json", schema = @Schema(implementation = ProblemDetails.class))), @ApiResponse( responseCode = "404", description = "The user directory or group could not be found", content = @Content( mediaType = "application/problem+json", schema = @Schema(implementation = ProblemDetails.class))), @ApiResponse( responseCode = "500", description = "An error has occurred and the request could not be processed at this time", content = @Content( mediaType = "application/problem+json", schema = @Schema(implementation = ProblemDetails.class))) }) @RequestMapping( value = "/user-directories/{userDirectoryId}/groups/{groupName}/role-codes", method = RequestMethod.GET, produces = "application/json") @ResponseStatus(HttpStatus.OK) @PreAuthorize( "isSecurityDisabled() or hasRole('Administrator') or hasAuthority('FUNCTION_Security.TenantAdministration') or hasAuthority('FUNCTION_Security.GroupAdministration')") public List<String> getRoleCodesForGroup( @Parameter( name = "userDirectoryId", description = "The ID for the user directory", required = true) @PathVariable UUID userDirectoryId, @Parameter(name = "groupName", description = "The name of the group", required = true) @PathVariable String groupName) throws InvalidArgumentException, UserDirectoryNotFoundException, GroupNotFoundException, ServiceUnavailableException { if (!hasAccessToUserDirectory(userDirectoryId)) { throw new AccessDeniedException( "Access denied to the user directory (" + userDirectoryId + ")"); } return securityService.getRoleCodesForGroup(userDirectoryId, groupName); } /** * Retrieve all the roles. * * @return the roles * @throws ServiceUnavailableException if the roles could not be retrieved */ @Operation(summary = "Retrieve all the roles", description = "Retrieve all the roles") @ApiResponses( value = { @ApiResponse(responseCode = "200", description = "OK"), @ApiResponse( responseCode = "500", description = "An error has occurred and the request could not be processed at this time", content = @Content( mediaType = "application/problem+json", schema = @Schema(implementation = ProblemDetails.class))) }) @RequestMapping(value = "/roles", method = RequestMethod.GET, produces = "application/json") @ResponseStatus(HttpStatus.OK) @PreAuthorize( "isSecurityDisabled() or hasRole('Administrator') or hasAuthority('FUNCTION_Security.TenantAdministration') or hasAuthority('FUNCTION_Security.GroupAdministration')") public List<Role> getRoles() throws ServiceUnavailableException { return securityService.getRoles(); } /** * Retrieve the roles that have been assigned to the group. * * @param userDirectoryId the ID for the user directory * @param groupName the name of the group * @return the roles that have been assigned to the group * @throws InvalidArgumentException if an argument is invalid * @throws UserDirectoryNotFoundException if the user directory could not be found * @throws GroupNotFoundException if the group could not be found * @throws ServiceUnavailableException if the codes for the roles assigned to the group could not * be retrieved */ @Operation( summary = "Retrieve the roles that have been assigned to the group", description = "Retrieve the roles that have been assigned to the group") @ApiResponses( value = { @ApiResponse(responseCode = "200", description = "OK"), @ApiResponse( responseCode = "400", description = "Invalid argument", content = @Content( mediaType = "application/problem+json", schema = @Schema(implementation = ProblemDetails.class))), @ApiResponse( responseCode = "403", description = "Access denied", content = @Content( mediaType = "application/problem+json", schema = @Schema(implementation = ProblemDetails.class))), @ApiResponse( responseCode = "404", description = "The user directory or group could not be found", content = @Content( mediaType = "application/problem+json", schema = @Schema(implementation = ProblemDetails.class))), @ApiResponse( responseCode = "500", description = "An error has occurred and the request could not be processed at this time", content = @Content( mediaType = "application/problem+json", schema = @Schema(implementation = ProblemDetails.class))) }) @RequestMapping( value = "/user-directories/{userDirectoryId}/groups/{groupName}/roles", method = RequestMethod.GET, produces = "application/json") @ResponseStatus(HttpStatus.OK) @PreAuthorize( "isSecurityDisabled() or hasRole('Administrator') or hasAuthority('FUNCTION_Security.TenantAdministration') or hasAuthority('FUNCTION_Security.GroupAdministration')") public List<GroupRole> getRolesForGroup( @Parameter( name = "userDirectoryId", description = "The ID for the user directory", required = true) @PathVariable UUID userDirectoryId, @Parameter(name = "groupName", description = "The name of the group", required = true) @PathVariable String groupName) throws InvalidArgumentException, UserDirectoryNotFoundException, GroupNotFoundException, ServiceUnavailableException { if (!hasAccessToUserDirectory(userDirectoryId)) { throw new AccessDeniedException( "Access denied to the user directory (" + userDirectoryId + ")"); } return securityService.getRolesForGroup(userDirectoryId, groupName); } /** * Retrieve the tenant. * * @param tenantId the ID for the tenant * @return the tenant * @throws InvalidArgumentException if an argument is invalid * @throws TenantNotFoundException if the tenant could not be found * @throws ServiceUnavailableException if the tenant could not be retrieved */ @Operation(summary = "Retrieve the tenant", description = "Retrieve the tenant") @ApiResponses( value = { @ApiResponse(responseCode = "200", description = "OK"), @ApiResponse( responseCode = "400", description = "Invalid argument", content = @Content( mediaType = "application/problem+json", schema = @Schema(implementation = ProblemDetails.class))), @ApiResponse( responseCode = "403", description = "Access denied", content = @Content( mediaType = "application/problem+json", schema = @Schema(implementation = ProblemDetails.class))), @ApiResponse( responseCode = "404", description = "The tenant could not be found", content = @Content( mediaType = "application/problem+json", schema = @Schema(implementation = ProblemDetails.class))), @ApiResponse( responseCode = "500", description = "An error has occurred and the request could not be processed at this time", content = @Content( mediaType = "application/problem+json", schema = @Schema(implementation = ProblemDetails.class))) }) @RequestMapping( value = "/tenants/{tenantId}", method = RequestMethod.GET, produces = "application/json") @ResponseStatus(HttpStatus.OK) @PreAuthorize( "isSecurityDisabled() or hasRole('Administrator') or hasAuthority('FUNCTION_Security.TenantAdministration')") public Tenant getTenant( @Parameter(name = "tenantId", description = "The ID for the tenant", required = true) @PathVariable UUID tenantId) throws InvalidArgumentException, TenantNotFoundException, ServiceUnavailableException { return securityService.getTenant(tenantId); } /** * Retrieve the name of the tenant. * * @param tenantId the ID for the tenant * @return the name of the tenant * @throws InvalidArgumentException if an argument is invalid * @throws TenantNotFoundException if the tenant could not be found * @throws ServiceUnavailableException if the name of the tenant could not be retrieved */ @Operation( summary = "Retrieve the name of tenant", description = "Retrieve the name of the tenant") @ApiResponses( value = { @ApiResponse(responseCode = "200", description = "OK"), @ApiResponse( responseCode = "400", description = "Invalid argument", content = @Content( mediaType = "application/problem+json", schema = @Schema(implementation = ProblemDetails.class))), @ApiResponse( responseCode = "403", description = "Access denied", content = @Content( mediaType = "application/problem+json", schema = @Schema(implementation = ProblemDetails.class))), @ApiResponse( responseCode = "404", description = "The tenant could not be found", content = @Content( mediaType = "application/problem+json", schema = @Schema(implementation = ProblemDetails.class))), @ApiResponse( responseCode = "500", description = "An error has occurred and the request could not be processed at this time", content = @Content( mediaType = "application/problem+json", schema = @Schema(implementation = ProblemDetails.class))) }) @RequestMapping( value = "/tenants/{tenantId}/name", method = RequestMethod.GET, produces = "application/json") @ResponseStatus(HttpStatus.OK) @PreAuthorize( "isSecurityDisabled() or hasRole('Administrator') or hasAuthority('FUNCTION_Security.TenantAdministration')") public String getTenantName( @Parameter(name = "tenantId", description = "The ID for the tenant", required = true) @PathVariable UUID tenantId) throws InvalidArgumentException, TenantNotFoundException, ServiceUnavailableException { return ApiUtil.quote(securityService.getTenantName(tenantId)); } /** * Retrieve the tenants. * * @param filter the optional filter to apply to the tenants * @param sortDirection the optional sort direction to apply to the tenants * @param pageIndex the optional page index * @param pageSize the optional page size * @return the tenants * @throws InvalidArgumentException if an argument is invalid * @throws ServiceUnavailableException if the tenants could not be retrieved */ @Operation(summary = "Retrieve the tenants", description = "Retrieve the tenants") @ApiResponses( value = { @ApiResponse(responseCode = "200", description = "OK"), @ApiResponse( responseCode = "400", description = "Invalid argument", content = @Content( mediaType = "application/problem+json", schema = @Schema(implementation = ProblemDetails.class))), @ApiResponse( responseCode = "403", description = "Access denied", content = @Content( mediaType = "application/problem+json", schema = @Schema(implementation = ProblemDetails.class))), @ApiResponse( responseCode = "500", description = "An error has occurred and the request could not be processed at this time", content = @Content( mediaType = "application/problem+json", schema = @Schema(implementation = ProblemDetails.class))) }) @RequestMapping(value = "/tenants", method = RequestMethod.GET, produces = "application/json") @ResponseStatus(HttpStatus.OK) @PreAuthorize( "isSecurityDisabled() or hasRole('Administrator') or hasAuthority('FUNCTION_Security.TenantAdministration')") public Tenants getTenants( @Parameter(name = "filter", description = "The optional filter to apply to the tenants") @RequestParam(value = "filter", required = false) String filter, @Parameter( name = "sortDirection", description = "The optional sort direction to apply to the tenants") @RequestParam(value = "sortDirection", required = false) SortDirection sortDirection, @Parameter(name = "pageIndex", description = "The optional page index", example = "0") @RequestParam(value = "pageIndex", required = false, defaultValue = "0") Integer pageIndex, @Parameter(name = "pageSize", description = "The optional page size", example = "10") @RequestParam(value = "pageSize", required = false, defaultValue = "10") Integer pageSize) throws InvalidArgumentException, ServiceUnavailableException { if (pageIndex == null) { pageIndex = 0; } if (pageSize == null) { pageSize = 10; } return securityService.getTenants(filter, sortDirection, pageIndex, pageSize); } /** * Retrieve the tenants the user directory is associated with. * * @param userDirectoryId the ID for the user directory * @return the tenants the user directory is associated with * @throws InvalidArgumentException if an argument is invalid * @throws UserDirectoryNotFoundException if the user directory could not be found * @throws ServiceUnavailableException if the tenants could not be retrieved for the user * directory */ @Operation( summary = "Retrieve the tenants the user directory is associated with", description = "Retrieve the tenants the user directory is associated with") @ApiResponses( value = { @ApiResponse(responseCode = "200", description = "OK"), @ApiResponse( responseCode = "400", description = "Invalid argument", content = @Content( mediaType = "application/problem+json", schema = @Schema(implementation = ProblemDetails.class))), @ApiResponse( responseCode = "403", description = "Access denied", content = @Content( mediaType = "application/problem+json", schema = @Schema(implementation = ProblemDetails.class))), @ApiResponse( responseCode = "404", description = "The user directory could not be found", content = @Content( mediaType = "application/problem+json", schema = @Schema(implementation = ProblemDetails.class))), @ApiResponse( responseCode = "500", description = "An error has occurred and the request could not be processed at this time", content = @Content( mediaType = "application/problem+json", schema = @Schema(implementation = ProblemDetails.class))) }) @RequestMapping( value = "/user-directories/{userDirectoryId}/tenants", method = RequestMethod.GET, produces = "application/json") @ResponseStatus(HttpStatus.OK) public ResponseEntity<List<Tenant>> getTenantsForUserDirectory( @Parameter( name = "userDirectoryId", description = "The ID for the user directory", required = true) @PathVariable UUID userDirectoryId) throws InvalidArgumentException, UserDirectoryNotFoundException, ServiceUnavailableException { if (isSecurityEnabled() && (!hasAccessToUserDirectory(userDirectoryId))) { throw new AccessDeniedException( "Access denied to the user directory (" + userDirectoryId + ")"); } List<Tenant> tenants = securityService.getTenantsForUserDirectory(userDirectoryId); return new ResponseEntity<>(tenants, HttpStatus.OK); } /** * Retrieve the user. * * @param userDirectoryId the ID for the user directory * @param username the username for the user * @return the user * @throws InvalidArgumentException if an argument is invalid * @throws UserDirectoryNotFoundException if the user directory could not be found * @throws UserNotFoundException if the user could not be found * @throws ServiceUnavailableException if the user could not be retrieved */ @Operation(summary = "Retrieve the user", description = "Retrieve the user") @ApiResponses( value = { @ApiResponse(responseCode = "200", description = "OK"), @ApiResponse( responseCode = "400", description = "Invalid argument", content = @Content( mediaType = "application/problem+json", schema = @Schema(implementation = ProblemDetails.class))), @ApiResponse( responseCode = "403", description = "Access denied", content = @Content( mediaType = "application/problem+json", schema = @Schema(implementation = ProblemDetails.class))), @ApiResponse( responseCode = "404", description = "The user directory or user could not be found", content = @Content( mediaType = "application/problem+json", schema = @Schema(implementation = ProblemDetails.class))), @ApiResponse( responseCode = "500", description = "An error has occurred and the request could not be processed at this time", content = @Content( mediaType = "application/problem+json", schema = @Schema(implementation = ProblemDetails.class))) }) @RequestMapping( value = "/user-directories/{userDirectoryId}/users/{username}", method = RequestMethod.GET, produces = "application/json") @ResponseStatus(HttpStatus.OK) public User getUser( @Parameter( name = "userDirectoryId", description = "The ID for the user directory", required = true) @PathVariable UUID userDirectoryId, @Parameter(name = "username", description = "The username for the user", required = true) @PathVariable String username) throws InvalidArgumentException, UserDirectoryNotFoundException, UserNotFoundException, ServiceUnavailableException { if (!StringUtils.hasText(username)) { throw new InvalidArgumentException("username"); } Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); if (hasRole("Administrator")) { // Administrators always have access to retrieve a user's details } else if (isSecurityDisabled() || hasAccessToFunction("Security.TenantAdministration") || hasAccessToFunction("Security.UserAdministration") || hasAccessToFunction("Security.ResetUserPassword")) { if (isSecurityEnabled() && (!hasAccessToUserDirectory(userDirectoryId))) { throw new AccessDeniedException( "Access denied to the user directory (" + userDirectoryId + ")"); } } else if ((authentication != null) && (authentication.getName().equalsIgnoreCase(username))) { // Users can retrieve their own details } else { throw new AccessDeniedException("Access denied to the user (" + username + ")"); } User user = securityService.getUser(userDirectoryId, username); // Remove the password information user.setPassword(null); user.setPasswordAttempts(0); user.setPasswordExpiry(null); return user; } /** * Retrieve the user directories. * * @param filter the optional filter to apply to the user directories * @param sortDirection the optional sort direction to apply to the user directories * @param pageIndex the optional page index * @param pageSize the optional page size * @return the user directories * @throws InvalidArgumentException if an argument is invalid * @throws ServiceUnavailableException if the user directories could not be retrieved */ @Operation( summary = "Retrieve the user directories", description = "Retrieve the user directories") @ApiResponses( value = { @ApiResponse(responseCode = "200", description = "OK"), @ApiResponse( responseCode = "400", description = "Invalid argument", content = @Content( mediaType = "application/problem+json", schema = @Schema(implementation = ProblemDetails.class))), @ApiResponse( responseCode = "403", description = "Access denied", content = @Content( mediaType = "application/problem+json", schema = @Schema(implementation = ProblemDetails.class))), @ApiResponse( responseCode = "500", description = "An error has occurred and the request could not be processed at this time", content = @Content( mediaType = "application/problem+json", schema = @Schema(implementation = ProblemDetails.class))) }) @RequestMapping( value = "/user-directories", method = RequestMethod.GET, produces = "application/json") @ResponseStatus(HttpStatus.OK) @PreAuthorize( "isSecurityDisabled() or hasRole('Administrator') or hasAuthority('FUNCTION_Security.UserDirectoryAdministration')") public UserDirectories getUserDirectories( @Parameter( name = "filter", description = "The optional filter to apply to the user directories") @RequestParam(value = "filter", required = false) String filter, @Parameter( name = "sortDirection", description = "The optional sort direction to apply to the user directories") @RequestParam(value = "sortDirection", required = false) SortDirection sortDirection, @Parameter(name = "pageIndex", description = "The optional page index", example = "0") @RequestParam(value = "pageIndex", required = false, defaultValue = "0") Integer pageIndex, @Parameter(name = "pageSize", description = "The optional page size", example = "10") @RequestParam(value = "pageSize", required = false, defaultValue = "10") Integer pageSize) throws InvalidArgumentException, ServiceUnavailableException { if (pageIndex == null) { pageIndex = 0; } if (pageSize == null) { pageSize = 10; } return securityService.getUserDirectories(filter, sortDirection, pageIndex, pageSize); } /** * Retrieve the user directories the tenant is associated with. * * @param tenantId the ID for the tenant * @return the user directories the tenant is associated with * @throws InvalidArgumentException if an argument is invalid * @throws TenantNotFoundException if the tenant could not be found * @throws ServiceUnavailableException if the user directories could not be retrieved for the * tenant */ @Operation( summary = "Retrieve the user directories the tenant is associated with", description = "Retrieve the user directories the tenant is associated with") @ApiResponses( value = { @ApiResponse(responseCode = "200", description = "OK"), @ApiResponse( responseCode = "400", description = "Invalid argument", content = @Content( mediaType = "application/problem+json", schema = @Schema(implementation = ProblemDetails.class))), @ApiResponse( responseCode = "403", description = "Access denied", content = @Content( mediaType = "application/problem+json", schema = @Schema(implementation = ProblemDetails.class))), @ApiResponse( responseCode = "404", description = "The tenant could not be found", content = @Content( mediaType = "application/problem+json", schema = @Schema(implementation = ProblemDetails.class))), @ApiResponse( responseCode = "500", description = "An error has occurred and the request could not be processed at this time", content = @Content( mediaType = "application/problem+json", schema = @Schema(implementation = ProblemDetails.class))) }) @RequestMapping( value = "/tenants/{tenantId}/user-directories", method = RequestMethod.GET, produces = "application/json") @ResponseStatus(HttpStatus.OK) @PreAuthorize( "isSecurityDisabled() or hasRole('Administrator') or hasAuthority('FUNCTION_Security.TenantAdministration') or hasAuthority('FUNCTION_Security.UserAdministration') or hasAuthority('FUNCTION_Security.GroupAdministration')") public ResponseEntity<List<UserDirectory>> getUserDirectoriesForTenant( @Parameter(name = "tenantId", description = "The ID for the tenant", required = true) @PathVariable UUID tenantId) throws InvalidArgumentException, TenantNotFoundException, ServiceUnavailableException { List<UserDirectory> userDirectories = securityService.getUserDirectoriesForTenant(tenantId); if (hasRole(SecurityService.ADMINISTRATOR_ROLE_CODE) || hasAccessToFunction("Security.TenantAdministration")) { return new ResponseEntity<>(userDirectories, HttpStatus.OK); } else { List<UserDirectory> filteredUserDirectories = new ArrayList<>(); for (UserDirectory userDirectory : userDirectories) { if (hasAccessToUserDirectory(userDirectory.getId())) { filteredUserDirectories.add(userDirectory); } } return new ResponseEntity<>(filteredUserDirectories, HttpStatus.OK); } } /** * Retrieve the user directory. * * @param userDirectoryId the ID for the user directory * @return the user directory * @throws InvalidArgumentException if an argument is invalid * @throws UserDirectoryNotFoundException if the user directory could not be found * @throws ServiceUnavailableException if the user directory could not be retrieved */ @Operation(summary = "Retrieve the user directory", description = "Retrieve the user directory") @ApiResponses( value = { @ApiResponse(responseCode = "200", description = "OK"), @ApiResponse( responseCode = "400", description = "Invalid argument", content = @Content( mediaType = "application/problem+json", schema = @Schema(implementation = ProblemDetails.class))), @ApiResponse( responseCode = "403", description = "Access denied", content = @Content( mediaType = "application/problem+json", schema = @Schema(implementation = ProblemDetails.class))), @ApiResponse( responseCode = "404", description = "The user directory could not be found", content = @Content( mediaType = "application/problem+json", schema = @Schema(implementation = ProblemDetails.class))), @ApiResponse( responseCode = "500", description = "An error has occurred and the request could not be processed at this time", content = @Content( mediaType = "application/problem+json", schema = @Schema(implementation = ProblemDetails.class))) }) @RequestMapping( value = "/user-directories/{userDirectoryId}", method = RequestMethod.GET, produces = "application/json") @ResponseStatus(HttpStatus.OK) @PreAuthorize( "isSecurityDisabled() or hasRole('Administrator') or hasAuthority('FUNCTION_Security.UserDirectoryAdministration')") public UserDirectory getUserDirectory( @Parameter( name = "userDirectoryId", description = "The ID for the user directory", required = true) @PathVariable UUID userDirectoryId) throws InvalidArgumentException, UserDirectoryNotFoundException, ServiceUnavailableException { return securityService.getUserDirectory(userDirectoryId); } /** * Retrieve the capabilities the user directory supports. * * @param userDirectoryId the ID for the user directory * @return the capabilities the user directory supports * @throws InvalidArgumentException if an argument is invalid * @throws UserDirectoryNotFoundException if the user directory could not be found * @throws ServiceUnavailableException if the user directory capabilities could not be retrieved */ @Operation( summary = "Retrieve the capabilities the user directory supports", description = "Retrieve the capabilities the user directory supports") @ApiResponses( value = { @ApiResponse(responseCode = "200", description = "OK"), @ApiResponse( responseCode = "400", description = "Invalid argument", content = @Content( mediaType = "application/problem+json", schema = @Schema(implementation = ProblemDetails.class))), @ApiResponse( responseCode = "403", description = "Access denied", content = @Content( mediaType = "application/problem+json", schema = @Schema(implementation = ProblemDetails.class))), @ApiResponse( responseCode = "404", description = "The user directory could not be found", content = @Content( mediaType = "application/problem+json", schema = @Schema(implementation = ProblemDetails.class))), @ApiResponse( responseCode = "500", description = "An error has occurred and the request could not be processed at this time", content = @Content( mediaType = "application/problem+json", schema = @Schema(implementation = ProblemDetails.class))) }) @RequestMapping( value = "/user-directories/{userDirectoryId}/capabilities", method = RequestMethod.GET, produces = "application/json") @ResponseStatus(HttpStatus.OK) @PreAuthorize( "isSecurityDisabled() or hasRole('Administrator') or hasAuthority('FUNCTION_Security.UserDirectoryAdministration') or hasAuthority('FUNCTION_Security.UserAdministration') or hasAuthority('FUNCTION_Security.GroupAdministration') or hasAuthority('FUNCTION_Security.ResetUserPassword')") public UserDirectoryCapabilities getUserDirectoryCapabilities( @Parameter( name = "userDirectoryId", description = "The ID for the user directory", required = true) @PathVariable UUID userDirectoryId) throws InvalidArgumentException, UserDirectoryNotFoundException, ServiceUnavailableException { if (!hasAccessToUserDirectory(userDirectoryId)) { throw new AccessDeniedException( "Access denied to the user directory (" + userDirectoryId + ")"); } return securityService.getUserDirectoryCapabilities(userDirectoryId); } /** * Retrieve the name of the user directory. * * @param userDirectoryId the ID for the user directory * @return the name of user directory * @throws InvalidArgumentException if an argument is invalid * @throws UserDirectoryNotFoundException if the user directory could not be found * @throws ServiceUnavailableException if the name of the user directory could not be retrieved */ @Operation( summary = "Retrieve the name of the user directory", description = "Retrieve the name of the user directory") @ApiResponses( value = { @ApiResponse(responseCode = "200", description = "OK"), @ApiResponse( responseCode = "400", description = "Invalid argument", content = @Content( mediaType = "application/problem+json", schema = @Schema(implementation = ProblemDetails.class))), @ApiResponse( responseCode = "403", description = "Access denied", content = @Content( mediaType = "application/problem+json", schema = @Schema(implementation = ProblemDetails.class))), @ApiResponse( responseCode = "404", description = "The user directory could not be found", content = @Content( mediaType = "application/problem+json", schema = @Schema(implementation = ProblemDetails.class))), @ApiResponse( responseCode = "500", description = "An error has occurred and the request could not be processed at this time", content = @Content( mediaType = "application/problem+json", schema = @Schema(implementation = ProblemDetails.class))) }) @RequestMapping( value = "/user-directories/{userDirectoryId}/name", method = RequestMethod.GET, produces = "application/json") @ResponseStatus(HttpStatus.OK) @PreAuthorize( "isSecurityDisabled() or hasRole('Administrator') or hasAuthority('FUNCTION_Security.UserDirectoryAdministration')") public String getUserDirectoryName( @Parameter( name = "userDirectoryId", description = "The ID for the user directory", required = true) @PathVariable UUID userDirectoryId) throws InvalidArgumentException, UserDirectoryNotFoundException, ServiceUnavailableException { return ApiUtil.quote(securityService.getUserDirectoryName(userDirectoryId)); } /** * Retrieve the summaries for the user directories. * * @param filter the optional filter to apply to the user directories * @param sortDirection the optional sort direction to apply to the user directories * @param pageIndex the optional page index * @param pageSize the optional page size * @return the summaries for the user directories * @throws InvalidArgumentException if an argument is invalid * @throws ServiceUnavailableException if the user directory summaries could not be retrieved */ @Operation( summary = "Retrieve the summaries for the user directories", description = "Retrieve the summaries for the user directories") @ApiResponses( value = { @ApiResponse(responseCode = "200", description = "OK"), @ApiResponse( responseCode = "400", description = "Invalid argument", content = @Content( mediaType = "application/problem+json", schema = @Schema(implementation = ProblemDetails.class))), @ApiResponse( responseCode = "403", description = "Access denied", content = @Content( mediaType = "application/problem+json", schema = @Schema(implementation = ProblemDetails.class))), @ApiResponse( responseCode = "500", description = "An error has occurred and the request could not be processed at this time", content = @Content( mediaType = "application/problem+json", schema = @Schema(implementation = ProblemDetails.class))) }) @RequestMapping( value = "/user-directory-summaries", method = RequestMethod.GET, produces = "application/json") @ResponseStatus(HttpStatus.OK) @PreAuthorize( "isSecurityDisabled() or hasRole('Administrator') or hasAuthority('FUNCTION_Security.UserDirectoryAdministration')") public UserDirectorySummaries getUserDirectorySummaries( @Parameter( name = "filter", description = "The optional filter to apply to the user directories") @RequestParam(value = "filter", required = false) String filter, @Parameter( name = "sortDirection", description = "The optional sort direction to apply to the user directories") @RequestParam(value = "sortDirection", required = false) SortDirection sortDirection, @Parameter(name = "pageIndex", description = "The optional page index", example = "0") @RequestParam(value = "pageIndex", required = false, defaultValue = "0") Integer pageIndex, @Parameter(name = "pageSize", description = "The optional page size", example = "10") @RequestParam(value = "pageSize", required = false, defaultValue = "10") Integer pageSize) throws InvalidArgumentException, ServiceUnavailableException { if (pageIndex == null) { pageIndex = 0; } if (pageSize == null) { pageSize = 10; } return securityService.getUserDirectorySummaries(filter, sortDirection, pageIndex, pageSize); } /** * Retrieve the summaries for the user directories the tenant is associated with. * * @param tenantId the ID for the tenant * @return the summaries for the user directories the tenant is associated with * @throws InvalidArgumentException if an argument is invalid * @throws TenantNotFoundException if the tenant could not be found * @throws ServiceUnavailableException if the user directory summaries could not be retrieved for * the tenant */ @Operation( summary = "Retrieve the summaries for the user directories the tenant is associated with", description = "Retrieve the summaries for the user directories the tenant is associated with") @ApiResponses( value = { @ApiResponse(responseCode = "200", description = "OK"), @ApiResponse( responseCode = "400", description = "Invalid argument", content = @Content( mediaType = "application/problem+json", schema = @Schema(implementation = ProblemDetails.class))), @ApiResponse( responseCode = "403", description = "Access denied", content = @Content( mediaType = "application/problem+json", schema = @Schema(implementation = ProblemDetails.class))), @ApiResponse( responseCode = "404", description = "The tenant could not be found", content = @Content( mediaType = "application/problem+json", schema = @Schema(implementation = ProblemDetails.class))), @ApiResponse( responseCode = "500", description = "An error has occurred and the request could not be processed at this time", content = @Content( mediaType = "application/problem+json", schema = @Schema(implementation = ProblemDetails.class))) }) @RequestMapping( value = "/tenants/{tenantId}/user-directory-summaries", method = RequestMethod.GET, produces = "application/json") @ResponseStatus(HttpStatus.OK) @PreAuthorize( "isSecurityDisabled() or hasRole('Administrator') or hasAuthority('FUNCTION_Security.TenantAdministration') or hasAuthority('FUNCTION_Security.ResetUserPassword') or hasAuthority('FUNCTION_Security.UserAdministration') or hasAuthority('FUNCTION_Security.UserGroups')") public ResponseEntity<List<UserDirectorySummary>> getUserDirectorySummariesForTenant( @Parameter(name = "tenantId", description = "The ID for the tenant", required = true) @PathVariable UUID tenantId) throws InvalidArgumentException, TenantNotFoundException, ServiceUnavailableException { List<UserDirectorySummary> userDirectorySummaries = securityService.getUserDirectorySummariesForTenant(tenantId); if (hasRole("Administrator") || hasAccessToFunction("Security.TenantAdministration")) { return new ResponseEntity<>(userDirectorySummaries, HttpStatus.OK); } else { List<UserDirectorySummary> filteredUserDirectorySummaries = new ArrayList<>(); for (UserDirectorySummary userDirectorySummary : userDirectorySummaries) { if (hasAccessToUserDirectory(userDirectorySummary.getId())) { filteredUserDirectorySummaries.add(userDirectorySummary); } } return new ResponseEntity<>(filteredUserDirectorySummaries, HttpStatus.OK); } } /** * Retrieve the user directory type for the user directory. * * @param userDirectoryId the ID for the user directory * @return the user directory type for the user directory * @throws InvalidArgumentException if an argument is invalid * @throws UserDirectoryNotFoundException if the user directory could not be found * @throws UserDirectoryTypeNotFoundException if the user directory type could not be found * @throws ServiceUnavailableException if the user directory type could not be retrieved for the * user directory */ @Operation( summary = "Retrieve the user directory type for the user directory", description = "Retrieve the user directory type for the user directory") @ApiResponses( value = { @ApiResponse(responseCode = "200", description = "OK"), @ApiResponse( responseCode = "400", description = "Invalid argument", content = @Content( mediaType = "application/problem+json", schema = @Schema(implementation = ProblemDetails.class))), @ApiResponse( responseCode = "403", description = "Access denied", content = @Content( mediaType = "application/problem+json", schema = @Schema(implementation = ProblemDetails.class))), @ApiResponse( responseCode = "404", description = "The user directory or user directory type could not be found", content = @Content( mediaType = "application/problem+json", schema = @Schema(implementation = ProblemDetails.class))), @ApiResponse( responseCode = "500", description = "An error has occurred and the request could not be processed at this time", content = @Content( mediaType = "application/problem+json", schema = @Schema(implementation = ProblemDetails.class))) }) @RequestMapping( value = "/user-directories/{userDirectoryId}/user-directory-type", method = RequestMethod.GET, produces = "application/json") @ResponseStatus(HttpStatus.OK) @PreAuthorize( "isSecurityDisabled() or hasRole('Administrator') or hasAuthority('FUNCTION_Security.UserDirectoryAdministration') or hasAuthority('FUNCTION_Security.UserAdministration')") public UserDirectoryType getUserDirectoryTypeForUserDirectory( @Parameter( name = "userDirectoryId", description = "The ID for the user directory", required = true) @PathVariable UUID userDirectoryId) throws InvalidArgumentException, UserDirectoryNotFoundException, UserDirectoryTypeNotFoundException, ServiceUnavailableException { if (!hasAccessToUserDirectory(userDirectoryId)) { throw new AccessDeniedException( "Access denied to the user directory (" + userDirectoryId + ")"); } return securityService.getUserDirectoryTypeForUserDirectory(userDirectoryId); } /** * Retrieve the user directory types. * * @return the user directory types * @throws ServiceUnavailableException if the user directory types could not be retrieved */ @Operation( summary = "Retrieve the user directory types", description = "Retrieve the user directory types") @ApiResponses( value = { @ApiResponse(responseCode = "200", description = "OK"), @ApiResponse( responseCode = "500", description = "An error has occurred and the request could not be processed at this time", content = @Content( mediaType = "application/problem+json", schema = @Schema(implementation = ProblemDetails.class))) }) @RequestMapping( value = "/user-directory-types", method = RequestMethod.GET, produces = "application/json") @ResponseStatus(HttpStatus.OK) @PreAuthorize( "isSecurityDisabled() or hasRole('Administrator') or hasAuthority('FUNCTION_Security.UserDirectoryAdministration')") public List<UserDirectoryType> getUserDirectoryTypes() throws ServiceUnavailableException { return securityService.getUserDirectoryTypes(); } /** * Retrieve the name of the user. * * @param userDirectoryId the ID for the user directory * @param username the username for the user * @return the name of the user * @throws InvalidArgumentException if an argument is invalid * @throws UserDirectoryNotFoundException if the user directory could not be found * @throws UserNotFoundException if the user could not be found * @throws ServiceUnavailableException if the name of the user could not be retrieved */ @Operation( summary = "Retrieve the name of the user", description = "Retrieve the name of the user") @ApiResponses( value = { @ApiResponse(responseCode = "200", description = "OK"), @ApiResponse( responseCode = "400", description = "Invalid argument", content = @Content( mediaType = "application/problem+json", schema = @Schema(implementation = ProblemDetails.class))), @ApiResponse( responseCode = "403", description = "Access denied", content = @Content( mediaType = "application/problem+json", schema = @Schema(implementation = ProblemDetails.class))), @ApiResponse( responseCode = "404", description = "The user directory or user could not be found", content = @Content( mediaType = "application/problem+json", schema = @Schema(implementation = ProblemDetails.class))), @ApiResponse( responseCode = "500", description = "An error has occurred and the request could not be processed at this time", content = @Content( mediaType = "application/problem+json", schema = @Schema(implementation = ProblemDetails.class))) }) @RequestMapping( value = "/user-directories/{userDirectoryId}/users/{username}/name", method = RequestMethod.GET, produces = "application/json") @ResponseStatus(HttpStatus.OK) @PreAuthorize( "isSecurityDisabled() or hasRole('Administrator') or hasAuthority('FUNCTION_Security.TenantAdministration') or hasAuthority('FUNCTION_Security.UserAdministration') or hasAuthority('FUNCTION_Security.ResetUserPassword')") public String getUserName( @Parameter( name = "userDirectoryId", description = "The ID for the user directory", required = true) @PathVariable UUID userDirectoryId, @Parameter(name = "username", description = "The username for the user", required = true) @PathVariable String username) throws InvalidArgumentException, UserDirectoryNotFoundException, UserNotFoundException, ServiceUnavailableException { if (!hasAccessToUserDirectory(userDirectoryId)) { throw new AccessDeniedException( "Access denied to the user directory (" + userDirectoryId + ")"); } return ApiUtil.quote(securityService.getUserName(userDirectoryId, username)); } /** * Retrieve the users. * * @param userDirectoryId the ID for the user directory * @param filter the optional filter to apply to the users * @param sortBy the optional method used to sort the users e.g. by name. * @param sortDirection the optional sort direction to apply to the users * @param pageIndex the optional page index * @param pageSize the optional page size * @return the users * @throws InvalidArgumentException if an argument is invalid * @throws UserDirectoryNotFoundException if the user directory could not be found * @throws ServiceUnavailableException if the users could not be retrieved */ @Operation(summary = "Retrieve the users", description = "Retrieve the users") @ApiResponses( value = { @ApiResponse(responseCode = "200", description = "OK"), @ApiResponse( responseCode = "400", description = "Invalid argument", content = @Content( mediaType = "application/problem+json", schema = @Schema(implementation = ProblemDetails.class))), @ApiResponse( responseCode = "403", description = "Access denied", content = @Content( mediaType = "application/problem+json", schema = @Schema(implementation = ProblemDetails.class))), @ApiResponse( responseCode = "404", description = "The user directory could not be found", content = @Content( mediaType = "application/problem+json", schema = @Schema(implementation = ProblemDetails.class))), @ApiResponse( responseCode = "500", description = "An error has occurred and the request could not be processed at this time", content = @Content( mediaType = "application/problem+json", schema = @Schema(implementation = ProblemDetails.class))) }) @RequestMapping( value = "/user-directories/{userDirectoryId}/users", method = RequestMethod.GET, produces = "application/json") @ResponseStatus(HttpStatus.OK) @PreAuthorize( "isSecurityDisabled() or hasRole('Administrator') or hasAuthority('FUNCTION_Security.TenantAdministration') or hasAuthority('FUNCTION_Security.UserAdministration') or hasAuthority('FUNCTION_Security.ResetUserPassword')") public Users getUsers( @Parameter( name = "userDirectoryId", description = "The ID for the user directory", required = true) @PathVariable UUID userDirectoryId, @Parameter(name = "filter", description = "The optional filter to apply to the users") @RequestParam(value = "filter", required = false) String filter, @Parameter( name = "sortBy", description = "The optional method used to sort the users e.g. by name") @RequestParam(value = "sortBy", required = false) UserSortBy sortBy, @Parameter( name = "sortDirection", description = "The optional sort direction to apply to the users") @RequestParam(value = "sortDirection", required = false) SortDirection sortDirection, @Parameter(name = "pageIndex", description = "The optional page index", example = "0") @RequestParam(value = "pageIndex", required = false, defaultValue = "0") Integer pageIndex, @Parameter(name = "pageSize", description = "The optional page size", example = "10") @RequestParam(value = "pageSize", required = false, defaultValue = "10") Integer pageSize) throws InvalidArgumentException, UserDirectoryNotFoundException, ServiceUnavailableException { if (pageIndex == null) { pageIndex = 0; } if (pageSize == null) { pageSize = 10; } if (!hasAccessToUserDirectory(userDirectoryId)) { throw new AccessDeniedException( "Access denied to the user directory (" + userDirectoryId + ")"); } return securityService.getUsers( userDirectoryId, filter, sortBy, sortDirection, pageIndex, pageSize); } /** * Remove the group member from the group. * * @param userDirectoryId the ID for the user directory * @param groupName the name of the group * @param memberType the group member type * @param memberName the name of the group member * @throws InvalidArgumentException if an argument is invalid * @throws UserDirectoryNotFoundException if the user directory could not be found * @throws GroupNotFoundException if the group could not be found * @throws GroupMemberNotFoundException if the group member could not be found * @throws ServiceUnavailableException if the group member could not be removed from the group */ @Operation( summary = "Remove the group member from the group", description = "Remove the group member from the group") @ApiResponses( value = { @ApiResponse( responseCode = "204", description = "The group member was successfully removed from the group"), @ApiResponse( responseCode = "400", description = "Invalid argument", content = @Content( mediaType = "application/problem+json", schema = @Schema(implementation = ProblemDetails.class))), @ApiResponse( responseCode = "403", description = "Access denied", content = @Content( mediaType = "application/problem+json", schema = @Schema(implementation = ProblemDetails.class))), @ApiResponse( responseCode = "404", description = "The user directory or group or group member could not be found", content = @Content( mediaType = "application/problem+json", schema = @Schema(implementation = ProblemDetails.class))), @ApiResponse( responseCode = "500", description = "An error has occurred and the request could not be processed at this time", content = @Content( mediaType = "application/problem+json", schema = @Schema(implementation = ProblemDetails.class))) }) @RequestMapping( value = "/user-directories/{userDirectoryId}/groups/{groupName}/members/{memberType}/{memberName}", method = RequestMethod.DELETE, produces = "application/json") @ResponseStatus(HttpStatus.NO_CONTENT) @PreAuthorize( "isSecurityDisabled() or hasRole('Administrator') or hasAuthority('FUNCTION_Security.TenantAdministration') or hasAuthority('FUNCTION_Security.GroupAdministration')") public void removeMemberFromGroup( @Parameter( name = "userDirectoryId", description = "The ID for the user directory", required = true) @PathVariable UUID userDirectoryId, @Parameter(name = "groupName", description = "The name of the group", required = true) @PathVariable String groupName, @Parameter(name = "memberType", description = "The group member type", required = true) @PathVariable GroupMemberType memberType, @Parameter(name = "memberName", description = "The name of the group member", required = true) @PathVariable String memberName) throws InvalidArgumentException, UserDirectoryNotFoundException, GroupNotFoundException, GroupMemberNotFoundException, ServiceUnavailableException { if (!hasAccessToUserDirectory(userDirectoryId)) { throw new AccessDeniedException( "Access denied to the user directory (" + userDirectoryId + ")"); } securityService.removeMemberFromGroup(userDirectoryId, groupName, memberType, memberName); } /** * Remove the role from the group. * * @param userDirectoryId the ID for the user directory * @param groupName the name of the group * @param roleCode the code for the role * @throws InvalidArgumentException if an argument is invalid * @throws UserDirectoryNotFoundException if the user directory could not be found * @throws GroupNotFoundException if the group could not be found * @throws GroupRoleNotFoundException if the group role could not be found * @throws ServiceUnavailableException if the role could not be removed from the group */ @Operation( summary = "Remove the role from the group", description = "Remove the role from the group") @ApiResponses( value = { @ApiResponse( responseCode = "204", description = "The role was successfully removed from the group"), @ApiResponse( responseCode = "400", description = "Invalid argument", content = @Content( mediaType = "application/problem+json", schema = @Schema(implementation = ProblemDetails.class))), @ApiResponse( responseCode = "403", description = "Access denied", content = @Content( mediaType = "application/problem+json", schema = @Schema(implementation = ProblemDetails.class))), @ApiResponse( responseCode = "404", description = "The user directory or group or group role could not be found", content = @Content( mediaType = "application/problem+json", schema = @Schema(implementation = ProblemDetails.class))), @ApiResponse( responseCode = "500", description = "An error has occurred and the request could not be processed at this time", content = @Content( mediaType = "application/problem+json", schema = @Schema(implementation = ProblemDetails.class))) }) @RequestMapping( value = "/user-directories/{userDirectoryId}/groups/{groupName}/roles/{roleCode}", method = RequestMethod.DELETE, produces = "application/json") @ResponseStatus(HttpStatus.NO_CONTENT) @PreAuthorize( "isSecurityDisabled() or hasRole('Administrator') or hasAuthority('FUNCTION_Security.TenantAdministration') or hasAuthority('FUNCTION_Security.GroupAdministration')") public void removeRoleFromGroup( @Parameter( name = "userDirectoryId", description = "The ID for the user directory", required = true) @PathVariable UUID userDirectoryId, @Parameter(name = "groupName", description = "The name of the group", required = true) @PathVariable String groupName, @Parameter(name = "roleCode", description = "The code for the role", required = true) @PathVariable String roleCode) throws InvalidArgumentException, UserDirectoryNotFoundException, GroupNotFoundException, GroupRoleNotFoundException, ServiceUnavailableException { if (!hasAccessToUserDirectory(userDirectoryId)) { throw new AccessDeniedException( "Access denied to the user directory (" + userDirectoryId + ")"); } if (roleCode.equalsIgnoreCase(SecurityService.ADMINISTRATOR_ROLE_CODE) && (!hasRole(SecurityService.ADMINISTRATOR_ROLE_CODE))) { throw new AccessDeniedException( "Insufficient authority to remove the " + SecurityService.ADMINISTRATOR_ROLE_CODE + " role from the group (" + groupName + ") for the user directory (" + userDirectoryId + ")"); } securityService.removeRoleFromGroup(userDirectoryId, groupName, roleCode); } /** * Remove the user directory from the tenant. * * @param tenantId the ID for the tenant * @param userDirectoryId the ID for the user directory * @throws InvalidArgumentException if an argument is invalid * @throws TenantNotFoundException if the tenant could not be found * @throws TenantUserDirectoryNotFoundException if the tenant user directory could not be found * @throws ServiceUnavailableException if the user directory could not be removed from the tenant */ @Operation( summary = "Remove the user directory from the tenant", description = "Remove the user directory from the tenant") @ApiResponses( value = { @ApiResponse( responseCode = "204", description = "The user directory was successfully removed from the tenant"), @ApiResponse( responseCode = "400", description = "Invalid argument", content = @Content( mediaType = "application/problem+json", schema = @Schema(implementation = ProblemDetails.class))), @ApiResponse( responseCode = "403", description = "Access denied", content = @Content( mediaType = "application/problem+json", schema = @Schema(implementation = ProblemDetails.class))), @ApiResponse( responseCode = "404", description = "The tenant or tenant user directory could not be found", content = @Content( mediaType = "application/problem+json", schema = @Schema(implementation = ProblemDetails.class))), @ApiResponse( responseCode = "500", description = "An error has occurred and the request could not be processed at this time", content = @Content( mediaType = "application/problem+json", schema = @Schema(implementation = ProblemDetails.class))) }) @RequestMapping( value = "/tenants/{tenantId}/user-directories/{userDirectoryId}", method = RequestMethod.DELETE, produces = "application/json") @ResponseStatus(HttpStatus.NO_CONTENT) @PreAuthorize( "isSecurityDisabled() or hasRole('Administrator') or hasAuthority('FUNCTION_Security.TenantAdministration')") public void removeUserDirectoryFromTenant( @Parameter(name = "tenantId", description = "The ID for the tenant", required = true) @PathVariable UUID tenantId, @Parameter( name = "userDirectoryId", description = "The ID for the user directory", required = true) @PathVariable UUID userDirectoryId) throws InvalidArgumentException, TenantNotFoundException, TenantUserDirectoryNotFoundException, ServiceUnavailableException { securityService.removeUserDirectoryFromTenant(tenantId, userDirectoryId); } /** * Initiate the password reset process for the user. * * @param username the username for the user * @param resetPasswordUrl the reset password URL * @throws InvalidArgumentException if an argument is invalid * @throws ServiceUnavailableException if the password reset could not be initiated */ @Operation( summary = "Initiate the password reset process for the user", description = "Initiate the password reset process for the user") @ApiResponses( value = { @ApiResponse( responseCode = "204", description = "The password reset process was initiated successfully"), @ApiResponse( responseCode = "400", description = "Invalid argument", content = @Content( mediaType = "application/problem+json", schema = @Schema(implementation = ProblemDetails.class))), @ApiResponse( responseCode = "403", description = "Access denied", content = @Content( mediaType = "application/problem+json", schema = @Schema(implementation = ProblemDetails.class))), @ApiResponse( responseCode = "404", description = "The user could not be found", content = @Content( mediaType = "application/problem+json", schema = @Schema(implementation = ProblemDetails.class))), @ApiResponse( responseCode = "500", description = "An error has occurred and the request could not be processed at this time", content = @Content( mediaType = "application/problem+json", schema = @Schema(implementation = ProblemDetails.class))) }) @RequestMapping( value = "/users/{username}/reset-password", method = RequestMethod.POST, produces = "application/json") @ResponseStatus(HttpStatus.NO_CONTENT) public void resetPassword( @Parameter(name = "username", description = "The username for the user", required = true) @PathVariable String username, @Parameter(name = "resetPasswordUrl", description = "The reset password URL") @RequestParam(value = "resetPasswordUrl") String resetPasswordUrl) throws InvalidArgumentException, ServiceUnavailableException { try { securityService.initiatePasswordReset(username, resetPasswordUrl, true); } catch (UserNotFoundException ignored) { // Swallow exception to prevent disclosing whether a user exists } } /** * Update the group. * * @param userDirectoryId the ID for the user directory * @param groupName the name of the group * @param group the group * @throws InvalidArgumentException if an argument is invalid * @throws UserDirectoryNotFoundException if the user directory could not be found * @throws GroupNotFoundException if the group could not be found * @throws ServiceUnavailableException if the group could not be updated */ @Operation(summary = "Update the group", description = "Update the group") @ApiResponses( value = { @ApiResponse(responseCode = "204", description = "The group was updated successfully"), @ApiResponse( responseCode = "400", description = "Invalid argument", content = @Content( mediaType = "application/problem+json", schema = @Schema(implementation = ProblemDetails.class))), @ApiResponse( responseCode = "403", description = "Access denied", content = @Content( mediaType = "application/problem+json", schema = @Schema(implementation = ProblemDetails.class))), @ApiResponse( responseCode = "404", description = "The user directory or group could not be found", content = @Content( mediaType = "application/problem+json", schema = @Schema(implementation = ProblemDetails.class))), @ApiResponse( responseCode = "500", description = "An error has occurred and the request could not be processed at this time", content = @Content( mediaType = "application/problem+json", schema = @Schema(implementation = ProblemDetails.class))) }) @RequestMapping( value = "/user-directories/{userDirectoryId}/groups/{groupName}", method = RequestMethod.PUT, produces = "application/json") @ResponseStatus(HttpStatus.NO_CONTENT) @PreAuthorize( "isSecurityDisabled() or hasRole('Administrator') or hasAuthority('FUNCTION_Security.TenantAdministration') or hasAuthority('FUNCTION_Security.GroupAdministration')") public void updateGroup( @Parameter( name = "userDirectoryId", description = "The ID for the user directory", required = true) @PathVariable UUID userDirectoryId, @Parameter(name = "groupName", description = "The name of the group", required = true) @PathVariable String groupName, @io.swagger.v3.oas.annotations.parameters.RequestBody( description = "The group to update", required = true) @RequestBody Group group) throws InvalidArgumentException, UserDirectoryNotFoundException, GroupNotFoundException, ServiceUnavailableException { if (!hasAccessToUserDirectory(userDirectoryId)) { throw new AccessDeniedException( "Access denied to the user directory (" + userDirectoryId + ")"); } if (!StringUtils.hasText(groupName)) { throw new InvalidArgumentException("groupName"); } if (group == null) { throw new InvalidArgumentException("group"); } if (!groupName.equals(group.getName())) { throw new InvalidArgumentException("group"); } securityService.updateGroup(group); } /** * Update the tenant. * * @param tenantId the ID for the tenant * @param tenant the tenant * @throws InvalidArgumentException if an argument is invalid * @throws TenantNotFoundException if the tenant could not be found * @throws ServiceUnavailableException if the tenant could not be updated */ @Operation(summary = "Update the tenant", description = "Update the tenant") @ApiResponses( value = { @ApiResponse(responseCode = "204", description = "The tenant was updated successfully"), @ApiResponse( responseCode = "400", description = "Invalid argument", content = @Content( mediaType = "application/problem+json", schema = @Schema(implementation = ProblemDetails.class))), @ApiResponse( responseCode = "403", description = "Access denied", content = @Content( mediaType = "application/problem+json", schema = @Schema(implementation = ProblemDetails.class))), @ApiResponse( responseCode = "404", description = "The tenant could not be found", content = @Content( mediaType = "application/problem+json", schema = @Schema(implementation = ProblemDetails.class))), @ApiResponse( responseCode = "500", description = "An error has occurred and the request could not be processed at this time", content = @Content( mediaType = "application/problem+json", schema = @Schema(implementation = ProblemDetails.class))) }) @RequestMapping( value = "/tenants/{tenantId}", method = RequestMethod.PUT, produces = "application/json") @ResponseStatus(HttpStatus.NO_CONTENT) @PreAuthorize( "isSecurityDisabled() or hasRole('Administrator') or hasAuthority('FUNCTION_Security.TenantAdministration')") public void updateTenant( @Parameter(name = "tenantId", description = "The ID for the tenant", required = true) @PathVariable UUID tenantId, @io.swagger.v3.oas.annotations.parameters.RequestBody( description = "The tenant to update", required = true) @RequestBody Tenant tenant) throws InvalidArgumentException, TenantNotFoundException, ServiceUnavailableException { if (tenantId == null) { throw new InvalidArgumentException("tenantId"); } if (tenant == null) { throw new InvalidArgumentException("tenant"); } if (!tenantId.equals(tenant.getId())) { throw new InvalidArgumentException("tenant"); } securityService.updateTenant(tenant); } /** * Update the user. * * @param userDirectoryId the ID for the user directory * @param username the username for the user * @param user the user * @param expirePassword expire the user's password * @param lockUser lock the user * @throws InvalidArgumentException if an argument is invalid * @throws UserDirectoryNotFoundException if the user directory could not be found * @throws UserNotFoundException if the user could not be found * @throws ServiceUnavailableException if the user could not be updated */ @Operation(summary = "Update the user", description = "Update the user") @ApiResponses( value = { @ApiResponse(responseCode = "204", description = "The user was updated successfully"), @ApiResponse( responseCode = "400", description = "Invalid argument", content = @Content( mediaType = "application/problem+json", schema = @Schema(implementation = ProblemDetails.class))), @ApiResponse( responseCode = "403", description = "Access denied", content = @Content( mediaType = "application/problem+json", schema = @Schema(implementation = ProblemDetails.class))), @ApiResponse( responseCode = "404", description = "The user directory or user could not be found", content = @Content( mediaType = "application/problem+json", schema = @Schema(implementation = ProblemDetails.class))), @ApiResponse( responseCode = "500", description = "An error has occurred and the request could not be processed at this time", content = @Content( mediaType = "application/problem+json", schema = @Schema(implementation = ProblemDetails.class))) }) @RequestMapping( value = "/user-directories/{userDirectoryId}/users/{username}", method = RequestMethod.PUT, produces = "application/json") @ResponseStatus(HttpStatus.NO_CONTENT) public void updateUser( @Parameter( name = "userDirectoryId", description = "The ID for the user directory", required = true) @PathVariable UUID userDirectoryId, @Parameter(name = "username", description = "The username for the user", required = true) @PathVariable String username, @io.swagger.v3.oas.annotations.parameters.RequestBody( description = "The user to update", required = true) @RequestBody User user, @Parameter(name = "expirePassword", description = "Expire the user's password") @RequestParam(value = "expirePassword", required = false) Boolean expirePassword, @Parameter(name = "lockUser", description = "Lock the user") @RequestParam(value = "lockUser", required = false) Boolean lockUser) throws InvalidArgumentException, UserDirectoryNotFoundException, UserNotFoundException, ServiceUnavailableException { if (!StringUtils.hasText(username)) { throw new InvalidArgumentException("username"); } // Apply access control Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); if (isSecurityEnabled()) { if (hasRole("Administrator")) { // Administrators always have access to retrieve a user's details } else if (hasAccessToFunction("Security.TenantAdministration") || hasAccessToFunction("Security.UserAdministration")) { if (!hasAccessToUserDirectory(userDirectoryId)) { throw new AccessDeniedException( "Access denied to the user directory (" + userDirectoryId + ")"); } } else if ((authentication != null) && (authentication.getName().equalsIgnoreCase(username))) { // Users can retrieve their own details } else { throw new AccessDeniedException("Access denied to the user (" + username + ")"); } } if (user == null) { throw new InvalidArgumentException("user"); } if (!username.equals(user.getUsername())) { throw new InvalidArgumentException("user"); } securityService.updateUser( user, (expirePassword != null) && expirePassword, (lockUser != null) && lockUser); } /** * Update the user directory. * * @param userDirectoryId the ID for the user directory * @param userDirectory the user directory * @throws InvalidArgumentException if an argument is invalid * @throws UserDirectoryNotFoundException if the user directory could not be found * @throws ServiceUnavailableException if the user directory could not be updated */ @Operation(summary = "Update the user directory", description = "Update the user directory") @ApiResponses( value = { @ApiResponse( responseCode = "204", description = "The user directory was updated successfully"), @ApiResponse( responseCode = "400", description = "Invalid argument", content = @Content( mediaType = "application/problem+json", schema = @Schema(implementation = ProblemDetails.class))), @ApiResponse( responseCode = "403", description = "Access denied", content = @Content( mediaType = "application/problem+json", schema = @Schema(implementation = ProblemDetails.class))), @ApiResponse( responseCode = "404", description = "The user directory could not be found", content = @Content( mediaType = "application/problem+json", schema = @Schema(implementation = ProblemDetails.class))), @ApiResponse( responseCode = "500", description = "An error has occurred and the request could not be processed at this time", content = @Content( mediaType = "application/problem+json", schema = @Schema(implementation = ProblemDetails.class))) }) @RequestMapping( value = "/user-directories/{userDirectoryId}", method = RequestMethod.PUT, produces = "application/json") @ResponseStatus(HttpStatus.NO_CONTENT) @PreAuthorize( "hasRole('Administrator') or hasAuthority('FUNCTION_Security.UserDirectoryAdministration')") public void updateUserDirectory( @Parameter( name = "userDirectoryId", description = "The ID for the user directory", required = true) @PathVariable UUID userDirectoryId, @io.swagger.v3.oas.annotations.parameters.RequestBody( description = "The user directory to update", required = true) @RequestBody UserDirectory userDirectory) throws InvalidArgumentException, UserDirectoryNotFoundException, ServiceUnavailableException { if (userDirectoryId == null) { throw new InvalidArgumentException("userDirectoryId"); } if (userDirectory == null) { throw new InvalidArgumentException("userDirectory"); } if (!userDirectoryId.equals(userDirectory.getId())) { throw new InvalidArgumentException("userDirectory"); } securityService.updateUserDirectory(userDirectory); } /** * Confirm that the user associated with the authenticated request has access to the user * directory. * * @param userDirectoryId the ID for the user directory * @return <b>true</b> if the user associated with the authenticated request has access to the * user directory or <b>false</b> otherwise * @throws InvalidArgumentException if an argument is invalid */ protected boolean hasAccessToUserDirectory(UUID userDirectoryId) throws InvalidArgumentException { if (isSecurityEnabled()) { if (userDirectoryId == null) { throw new InvalidArgumentException("userDirectoryId"); } Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); // Could not retrieve the currently authenticated principal if (authentication == null) { return false; } try { // If the user is not authenticated then they cannot have access if (!authentication.isAuthenticated()) { return false; } // If the user has the "Administrator" role they always have access if (hasRole(SecurityService.ADMINISTRATOR_ROLE_CODE)) { return true; } List<UUID> userDirectoryIdsForUser = new ArrayList<>(); List<UUID> tenantIds = getUUIDValuesForAuthoritiesWithPrefix(authentication, "TENANT_"); for (UUID tenantId : tenantIds) { var userDirectoryIdsForTenant = securityService.getUserDirectoryIdsForTenant(tenantId); userDirectoryIdsForUser.addAll(userDirectoryIdsForTenant); } return userDirectoryIdsForUser.stream().anyMatch(userDirectoryId::equals); } catch (Throwable e) { logger.error( "Failed to check if the user (" + authentication.getName() + ") has access to the user directory (" + userDirectoryId + ")", e); return false; } } else { return true; } } }
0
java-sources/africa/absa/inception-security-api/1.2.0/africa/absa/inception
java-sources/africa/absa/inception-security-api/1.2.0/africa/absa/inception/security/SecurityApiConfiguration.java
/* * Copyright 2021 original 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. */ package africa.absa.inception.security; import io.swagger.v3.oas.models.info.Info; import org.springdoc.core.GroupedOpenApi; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; /** * The <b>SecurityApiConfiguration</b> class provides the Spring configuration for the Security API * module. * * @author Marcus Portmann */ @Configuration public class SecurityApiConfiguration { /** * Returns the grouped Open API for the Security API. * * @return the grouped Open API for the Security API */ @Bean public GroupedOpenApi securityOpenApi() { return GroupedOpenApi.builder() .group("security") .packagesToScan("africa.absa.inception.security") .addOpenApiCustomiser( openApi -> openApi.info(new Info().title("Security API").version(Version.PROJECT_VERSION))) .build(); } }
0
java-sources/africa/absa/inception-security-api/1.2.0/africa/absa/inception
java-sources/africa/absa/inception-security-api/1.2.0/africa/absa/inception/security/Version.java
/* * Copyright 2021 original 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. */ package africa.absa.inception.security; /** * The <b>Version</b> class. * * @author Marcus Portmann */ public final class Version { public static final String PROJECT_VERSION = "1.2.0"; }
0
java-sources/africa/absa/inception-test/1.2.0/africa/absa/inception
java-sources/africa/absa/inception-test/1.2.0/africa/absa/inception/test/Assert.java
/* * Copyright 2021 original 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. */ package africa.absa.inception.test; import static org.junit.jupiter.api.Assertions.assertEquals; import java.time.LocalDateTime; import java.time.temporal.ChronoUnit; /** * The <b>Assert</b> class provides additional assertions for JUnit tests. * * @author Marcus Portmann */ public class Assert { /** * Asserts that two LocalDateTime values are equal. * * @param expected the expected value * @param actual the value to check * @param message the for message for the AssertionError */ public static void assertEqualsToMillisecond( LocalDateTime expected, LocalDateTime actual, String message) { if ((expected != null) && (actual != null)) { assertEquals( expected.truncatedTo(ChronoUnit.MILLIS), actual.truncatedTo(ChronoUnit.MILLIS), message); } else { assertEquals(expected, actual, message); } } }
0
java-sources/africa/absa/inception-test/1.2.0/africa/absa/inception
java-sources/africa/absa/inception-test/1.2.0/africa/absa/inception/test/ConnectionProxy.java
/* * Copyright 2021 original 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. */ package africa.absa.inception.test; import java.sql.Array; import java.sql.Blob; import java.sql.CallableStatement; import java.sql.Clob; import java.sql.Connection; import java.sql.DatabaseMetaData; import java.sql.NClob; import java.sql.PreparedStatement; import java.sql.SQLClientInfoException; import java.sql.SQLException; import java.sql.SQLWarning; import java.sql.SQLXML; import java.sql.Savepoint; import java.sql.Statement; import java.sql.Struct; import java.util.Map; import java.util.Properties; import java.util.concurrent.Executor; /** * The <b>ConnectionProxy</b> class implements a proxy for JDBC connections. * * @author Marcus Portmann */ public class ConnectionProxy implements Connection { private final Connection connection; ConnectionProxy(Connection connection) { this.connection = connection; } @Override public void abort(Executor executor) throws SQLException { connection.abort(executor); } @Override public void clearWarnings() throws SQLException { connection.clearWarnings(); } @Override public void close() throws SQLException { DataSourceProxy.getActiveDatabaseConnections().remove(this); connection.close(); } @Override public void commit() throws SQLException { connection.commit(); } @Override public Array createArrayOf(String typeName, Object[] elements) throws SQLException { return connection.createArrayOf(typeName, elements); } @Override public Blob createBlob() throws SQLException { return connection.createBlob(); } @Override public Clob createClob() throws SQLException { return connection.createClob(); } @Override public NClob createNClob() throws SQLException { return connection.createNClob(); } @Override public SQLXML createSQLXML() throws SQLException { return connection.createSQLXML(); } @Override public Statement createStatement() throws SQLException { return connection.createStatement(); } @Override public Statement createStatement(int resultSetType, int resultSetConcurrency) throws SQLException { return connection.createStatement(resultSetType, resultSetConcurrency); } @Override public Statement createStatement( int resultSetType, int resultSetConcurrency, int resultSetHoldability) throws SQLException { return connection.createStatement(resultSetType, resultSetConcurrency, resultSetHoldability); } @Override public Struct createStruct(String typeName, Object[] attributes) throws SQLException { return connection.createStruct(typeName, attributes); } @Override public boolean getAutoCommit() throws SQLException { return connection.getAutoCommit(); } @Override public String getCatalog() throws SQLException { return connection.getCatalog(); } @Override public Properties getClientInfo() throws SQLException { return connection.getClientInfo(); } @Override public String getClientInfo(String name) throws SQLException { return connection.getClientInfo(name); } @Override public int getHoldability() throws SQLException { return connection.getHoldability(); } @Override public DatabaseMetaData getMetaData() throws SQLException { return connection.getMetaData(); } @Override public int getNetworkTimeout() throws SQLException { return connection.getNetworkTimeout(); } @Override public String getSchema() throws SQLException { return connection.getSchema(); } @Override public int getTransactionIsolation() throws SQLException { return connection.getTransactionIsolation(); } @Override public Map<String, Class<?>> getTypeMap() throws SQLException { return connection.getTypeMap(); } @Override public SQLWarning getWarnings() throws SQLException { return connection.getWarnings(); } @Override public boolean isClosed() throws SQLException { return connection.isClosed(); } @Override public boolean isReadOnly() throws SQLException { return connection.isReadOnly(); } @Override public boolean isValid(int timeout) throws SQLException { return connection.isValid(timeout); } @Override public boolean isWrapperFor(Class<?> iface) throws SQLException { return iface.isAssignableFrom(getClass()); } @Override public String nativeSQL(String sql) throws SQLException { return connection.nativeSQL(sql); } @Override public CallableStatement prepareCall(String sql) throws SQLException { return connection.prepareCall(sql); } @Override public CallableStatement prepareCall(String sql, int resultSetType, int resultSetConcurrency) throws SQLException { return connection.prepareCall(sql, resultSetType, resultSetConcurrency); } @Override public CallableStatement prepareCall( String sql, int resultSetType, int resultSetConcurrency, int resultSetHoldability) throws SQLException { return connection.prepareCall(sql, resultSetType, resultSetConcurrency, resultSetHoldability); } @Override public PreparedStatement prepareStatement(String sql) throws SQLException { return connection.prepareStatement(sql); } @Override public PreparedStatement prepareStatement(String sql, int autoGeneratedKeys) throws SQLException { return connection.prepareStatement(sql, autoGeneratedKeys); } @Override public PreparedStatement prepareStatement(String sql, int[] columnIndexes) throws SQLException { return connection.prepareStatement(sql, columnIndexes); } @Override public PreparedStatement prepareStatement(String sql, String[] columnNames) throws SQLException { return connection.prepareStatement(sql, columnNames); } @Override public PreparedStatement prepareStatement(String sql, int resultSetType, int resultSetConcurrency) throws SQLException { return connection.prepareStatement(sql, resultSetType, resultSetConcurrency); } @Override public PreparedStatement prepareStatement( String sql, int resultSetType, int resultSetConcurrency, int resultSetHoldability) throws SQLException { return connection.prepareStatement( sql, resultSetType, resultSetConcurrency, resultSetHoldability); } @Override public void releaseSavepoint(Savepoint savepoint) throws SQLException { connection.releaseSavepoint(savepoint); } @Override public void rollback() throws SQLException { connection.rollback(); } @Override public void rollback(Savepoint savepoint) throws SQLException { connection.rollback(savepoint); } @Override public void setAutoCommit(boolean autoCommit) throws SQLException { connection.setAutoCommit(autoCommit); } @Override public void setCatalog(String catalog) throws SQLException { connection.setCatalog(catalog); } @Override public void setClientInfo(Properties properties) throws SQLClientInfoException { connection.setClientInfo(properties); } @Override public void setClientInfo(String name, String value) throws SQLClientInfoException { connection.setClientInfo(name, value); } @Override public void setHoldability(int holdability) throws SQLException { connection.setHoldability(holdability); } @Override public void setNetworkTimeout(Executor executor, int milliseconds) throws SQLException { connection.setNetworkTimeout(executor, milliseconds); } @Override public void setReadOnly(boolean readOnly) throws SQLException { connection.setReadOnly(readOnly); } @Override public Savepoint setSavepoint() throws SQLException { return connection.setSavepoint(); } @Override public Savepoint setSavepoint(String name) throws SQLException { return connection.setSavepoint(name); } @Override public void setSchema(String schema) throws SQLException { connection.setSchema(schema); } @Override public void setTransactionIsolation(int level) throws SQLException { connection.setTransactionIsolation(level); } @Override public void setTypeMap(Map<String, Class<?>> map) throws SQLException { connection.setTypeMap(map); } @Override public String toString() { return connection.toString(); } @SuppressWarnings("unchecked") @Override public <T> T unwrap(Class<T> iface) throws SQLException { if (isWrapperFor(iface)) { return (T) this; } if (iface.isAssignableFrom(this.connection.getClass())) { return (T) this.connection; } throw new SQLException(getClass() + " is not a wrapper for " + iface); } }
0
java-sources/africa/absa/inception-test/1.2.0/africa/absa/inception
java-sources/africa/absa/inception-test/1.2.0/africa/absa/inception/test/DataSourceProxy.java
/* * Copyright 2021 original 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. */ package africa.absa.inception.test; import java.io.PrintWriter; import java.sql.Connection; import java.sql.ConnectionBuilder; import java.sql.SQLException; import java.sql.SQLFeatureNotSupportedException; import java.sql.ShardingKeyBuilder; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.logging.Logger; import javax.sql.DataSource; /** * The <b>DataSourceProxy</b> class provides a proxy that tracks the JDBC connections associated * with the current thread and managed by a <b>javax.sql.DataSource</b> implementation. * * @author Marcus Portmann */ public class DataSourceProxy implements DataSource { /** The active database connections associated with the current thread. */ private static final ThreadLocal<Map<Connection, StackTraceElement[]>> activeDatabaseConnections = ThreadLocal.withInitial(ConcurrentHashMap::new); /** The data source. */ private final DataSource dataSource; /** * Constructs a new <b>DataSourceProxy</b>. * * @param dataSource the data source */ public DataSourceProxy(DataSource dataSource) { this.dataSource = dataSource; } /** * Add the database connection to the tracked active database connections associated with the * current thread. * * @param connection the connection */ public static void addActiveDatabaseConnection(Connection connection) { getActiveDatabaseConnections().put(connection, Thread.currentThread().getStackTrace()); } /** * Returns the active database connections for all Data Sources associated with the tracker. * * @return the active database connections for all Data Sources associated with the tracker */ public static Map<Connection, StackTraceElement[]> getActiveDatabaseConnections() { return activeDatabaseConnections.get(); } @Override public ConnectionBuilder createConnectionBuilder() throws SQLException { return dataSource.createConnectionBuilder(); } @Override public ShardingKeyBuilder createShardingKeyBuilder() throws SQLException { return dataSource.createShardingKeyBuilder(); } @Override public Connection getConnection() throws SQLException { Connection connection = new ConnectionProxy(dataSource.getConnection()); addActiveDatabaseConnection(connection); return connection; } @Override public Connection getConnection(String username, String password) throws SQLException { Connection connection = new ConnectionProxy(dataSource.getConnection(username, password)); addActiveDatabaseConnection(connection); return connection; } @Override public PrintWriter getLogWriter() throws SQLException { return dataSource.getLogWriter(); } @Override public int getLoginTimeout() throws SQLException { return dataSource.getLoginTimeout(); } @Override public Logger getParentLogger() throws SQLFeatureNotSupportedException { return dataSource.getParentLogger(); } @Override public boolean isWrapperFor(Class<?> iface) throws SQLException { return iface.isAssignableFrom(getClass()); } @Override public void setLogWriter(PrintWriter out) throws SQLException { dataSource.setLogWriter(out); } @Override public void setLoginTimeout(int seconds) throws SQLException { dataSource.setLoginTimeout(seconds); } @SuppressWarnings("unchecked") @Override public <T> T unwrap(Class<T> iface) throws SQLException { if (isWrapperFor(iface)) { return (T) this; } if (iface.isAssignableFrom(this.dataSource.getClass())) { return (T) this.dataSource; } throw new SQLException(getClass() + " is not a wrapper for " + iface); } }
0
java-sources/africa/absa/inception-test/1.2.0/africa/absa/inception
java-sources/africa/absa/inception-test/1.2.0/africa/absa/inception/test/InceptionExtension.java
/* * Copyright 2021 original 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. */ package africa.absa.inception.test; import java.lang.reflect.Method; import java.sql.Connection; import java.util.Map; import java.util.Optional; import javax.sql.XAConnection; import javax.transaction.Transaction; import org.junit.jupiter.api.extension.AfterEachCallback; import org.junit.jupiter.api.extension.ExtensionContext; import org.slf4j.LoggerFactory; /** * The <b>InceptionExtension</b> class. * * @author Marcus Portmann */ public class InceptionExtension implements AfterEachCallback { /** Constructs a new <b>InceptionExtension</b>. */ public InceptionExtension() {} @Override public void afterEach(ExtensionContext context) throws Exception { Optional<Method> testMethodOptional = context.getTestMethod(); if (testMethodOptional.isPresent()) { checkForActiveTransactions( testMethodOptional.get(), TransactionManagerProxy.getActiveTransactionStackTraces()); checkForActiveTransactions( testMethodOptional.get(), UserTransactionProxy.getActiveTransactionStackTraces()); checkForOpenDatabaseConnections( testMethodOptional.get(), DataSourceProxy.getActiveDatabaseConnections()); checkForOpenXADatabaseConnections( testMethodOptional.get(), XADataSourceProxy.getActiveXADatabaseConnections()); } } private void checkForActiveTransactions( Method method, Map<Transaction, StackTraceElement[]> activeTransactionStackTraces) { for (Transaction transaction : activeTransactionStackTraces.keySet()) { StackTraceElement[] stackTrace = activeTransactionStackTraces.get(transaction); for (int i = 0; i < stackTrace.length; i++) { if (stackTrace[i].getMethodName().equals("begin") && (stackTrace[i].getLineNumber() != -1)) { LoggerFactory.getLogger(InceptionExtension.class) .warn( "Failed to successfully execute the test (" + method.getName() + "): Found an " + "unexpected active transaction (" + transaction.toString() + ") that was " + "started by the method (" + stackTrace[i + 1].getMethodName() + ") on the class (" + stackTrace[i + 1].getClassName() + ") on line (" + stackTrace[i + 1].getLineNumber() + ")"); throw new RuntimeException( "Failed to successfully execute the test (" + method.getName() + "): Found an unexpected active transaction (" + transaction.toString() + ") that was started by the method (" + stackTrace[i + 1].getMethodName() + ") on the class (" + stackTrace[i + 1].getClassName() + ") on line (" + stackTrace[i + 1].getLineNumber() + ")"); } } } } private void checkForOpenDatabaseConnections( Method method, Map<Connection, StackTraceElement[]> activeDatabaseConnections) { for (Connection connection : activeDatabaseConnections.keySet()) { StackTraceElement[] stackTrace = activeDatabaseConnections.get(connection); for (int i = 0; i < stackTrace.length; i++) { if (stackTrace[i].getMethodName().equals("getConnection")) { LoggerFactory.getLogger(InceptionExtension.class) .warn( "Failed to successfully execute the test (" + method.getName() + "): Found an " + "unexpected open database connection (" + connection.toString() + ") that was " + "retrieved by the method (" + stackTrace[i + 1].getMethodName() + ") on the class (" + stackTrace[i + 1].getClassName() + ") on line (" + stackTrace[i + 1].getLineNumber() + ")"); throw new RuntimeException( "Failed to successfully execute the test (" + method.getName() + "): Found an unexpected open database connection (" + connection.toString() + ") that was retrieved by the method (" + stackTrace[i + 1].getMethodName() + ") on the class (" + stackTrace[i + 1].getClassName() + ") on line (" + stackTrace[i + 1].getLineNumber() + ")"); } } } } private void checkForOpenXADatabaseConnections( Method method, Map<XAConnection, StackTraceElement[]> activeXADatabaseConnections) { for (XAConnection connection : activeXADatabaseConnections.keySet()) { StackTraceElement[] stackTrace = activeXADatabaseConnections.get(connection); for (int i = 0; i < stackTrace.length; i++) { if (stackTrace[i].getMethodName().equals("getXAConnection")) { LoggerFactory.getLogger(InceptionExtension.class) .warn( "Failed to successfully execute the test (" + method.getName() + "): Found an " + "unexpected open XA database connection (" + connection.toString() + ") that was " + "retrieved by the method (" + stackTrace[i + 1].getMethodName() + ") on the class (" + stackTrace[i + 1].getClassName() + ") on line (" + stackTrace[i + 1].getLineNumber() + ")"); throw new RuntimeException( "Failed to successfully execute the test (" + method.getName() + "): Found an unexpected open XA database connection (" + connection.toString() + ") that was retrieved by the method (" + stackTrace[i + 1].getMethodName() + ") on the class (" + stackTrace[i + 1].getClassName() + ") on line (" + stackTrace[i + 1].getLineNumber() + ")"); } } } } }
0
java-sources/africa/absa/inception-test/1.2.0/africa/absa/inception
java-sources/africa/absa/inception-test/1.2.0/africa/absa/inception/test/TestConfiguration.java
/* * Copyright 2021 original 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. */ package africa.absa.inception.test; import africa.absa.inception.jpa.JpaUtil; import africa.absa.inception.json.DateTimeModule; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.SerializationFeature; import io.agroal.api.AgroalDataSource; import io.agroal.api.configuration.supplier.AgroalDataSourceConfigurationSupplier; import io.agroal.api.configuration.supplier.AgroalPropertiesReader; import io.agroal.api.transaction.TransactionIntegration; import java.sql.Connection; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.Properties; import java.util.concurrent.Executor; import javax.sql.DataSource; import liquibase.Contexts; import liquibase.LabelExpression; import liquibase.Liquibase; import liquibase.configuration.HubConfiguration; import liquibase.configuration.LiquibaseConfiguration; import liquibase.database.DatabaseFactory; import liquibase.database.jvm.JdbcConnection; import liquibase.resource.ClassLoaderResourceAccessor; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.context.properties.EnableConfigurationProperties; import org.springframework.cache.CacheManager; import org.springframework.cache.annotation.EnableCaching; import org.springframework.cache.concurrent.ConcurrentMapCacheManager; import org.springframework.context.ApplicationContext; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.FilterType; import org.springframework.context.annotation.Primary; import org.springframework.core.io.Resource; import org.springframework.core.task.SimpleAsyncTaskExecutor; import org.springframework.data.jpa.repository.config.EnableJpaRepositories; import org.springframework.http.converter.json.Jackson2ObjectMapperBuilder; import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean; import org.springframework.scheduling.TaskScheduler; import org.springframework.scheduling.annotation.EnableAsync; import org.springframework.scheduling.annotation.EnableScheduling; import org.springframework.scheduling.concurrent.ConcurrentTaskScheduler; import org.springframework.transaction.PlatformTransactionManager; import org.springframework.transaction.annotation.EnableTransactionManagement; import org.springframework.util.StringUtils; import org.springframework.web.reactive.function.client.WebClient; /** * The <b>TestConfiguration</b> class provides the base Spring configuration for the JUnit test * classes that test the capabilities provided by the <b>Inception</b> framework. * * <p>This configuration class disables the default application data source and Camunda Process * Engine bootstrapping using the component scan filters. * * @author Marcus Portmann */ @Configuration @EnableAsync @EnableCaching @EnableConfigurationProperties @EnableScheduling @EnableTransactionManagement @ComponentScan( basePackages = {"africa.absa.inception"}, lazyInit = true, excludeFilters = { @ComponentScan.Filter(value = SpringBootApplication.class, type = FilterType.ANNOTATION), @ComponentScan.Filter( pattern = "digital\\.inception\\.bmi\\.BMIConfiguration", type = FilterType.REGEX) }) @SuppressWarnings("WeakerAccess") public class TestConfiguration { private static final Object dataSourceLock = new Object(); /* Logger */ private static final Logger logger = LoggerFactory.getLogger(TestConfiguration.class); private static DataSource dataSource; private final ApplicationContext applicationContext; /** Execute the Liquibase changelogs using the data context. */ @Value("${inception.application.data-source.liquibase.apply-data-context:#{true}}") private boolean liquibaseApplyDataContext; /** * The Liquibase changelog resources on the classpath used to initialize the application database. */ @Value("classpath*:**/db/*.changelog.xml") private Resource[] liquibaseChangelogResources; /** * Constructs a new <b>TestConfiguration</b>. * * @param applicationContext the Spring application context */ public TestConfiguration(ApplicationContext applicationContext) { this.applicationContext = applicationContext; } /** * Initialize the in-memory application database and return a data source that can be used to * interact with the database. * * <p>This data source returned by this method must be closed after use with the <b>close()</b> * method. * * @return the data source that can be used to interact with the in-memory database */ @Bean @Primary public DataSource applicationDataSource() { synchronized (dataSourceLock) { if (dataSource == null) { try { Properties agroalProperties = new Properties(); agroalProperties.setProperty( AgroalPropertiesReader.JDBC_URL, "jdbc:h2:mem:" + Thread.currentThread().getName() + ";AUTOCOMMIT=OFF;MODE=PostgreSQL;DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=FALSE;DATABASE_TO_LOWER=TRUE;CASE_INSENSITIVE_IDENTIFIERS=TRUE"); agroalProperties.setProperty( AgroalPropertiesReader.PROVIDER_CLASS_NAME, "org.h2.jdbcx.JdbcDataSource"); agroalProperties.setProperty(AgroalPropertiesReader.MAX_SIZE, "5"); AgroalPropertiesReader agroalReaderProperties2 = new AgroalPropertiesReader().readProperties(agroalProperties); AgroalDataSourceConfigurationSupplier agroalDataSourceConfigurationSupplier = agroalReaderProperties2.modify(); TransactionIntegration transactionIntegration = applicationContext.getBean(TransactionIntegration.class); if (transactionIntegration != null) { agroalDataSourceConfigurationSupplier .connectionPoolConfiguration() .transactionIntegration(transactionIntegration); } dataSource = new DataSourceProxy(AgroalDataSource.from(agroalDataSourceConfigurationSupplier)); // Initialize the in-memory database using Liquibase changeSets LiquibaseConfiguration.getInstance() .getConfiguration(HubConfiguration.class) .setLiquibaseHubMode("OFF"); try (Connection connection = dataSource.getConnection()) { liquibase.database.Database database = DatabaseFactory.getInstance() .findCorrectDatabaseImplementation(new JdbcConnection(connection)); for (Resource changelogResource : liquibaseChangelogResources) { if (!changelogResource.getFilename().toLowerCase().endsWith("-data.changelog.xml")) { String changelogFile = "db/" + changelogResource.getFilename(); logger.info("Applying Liquibase changelog: " + changelogResource.getFilename()); Liquibase liquibase = new Liquibase(changelogFile, new ClassLoaderResourceAccessor(), database); liquibase.update(new Contexts(), new LabelExpression()); } } for (Resource changelogResource : liquibaseChangelogResources) { if (changelogResource.getFilename().toLowerCase().endsWith("-data.changelog.xml")) { String changelogFile = "db/" + changelogResource.getFilename(); logger.info( "Applying Liquibase data changelog: " + changelogResource.getFilename()); Liquibase liquibase = new Liquibase(changelogFile, new ClassLoaderResourceAccessor(), database); liquibase.update(new Contexts(), new LabelExpression()); } } } } catch (Throwable e) { throw new RuntimeException("Failed to initialize the in-memory application database", e); } } return dataSource; } } /** * Returns the application entity manager factory bean associated with the application data * source. * * @param dataSource the application data source * @param platformTransactionManager the platform transaction manager * @return the application entity manager factory bean associated with the application data source */ @Bean @Primary public LocalContainerEntityManagerFactoryBean applicationEntityManagerFactory( @Qualifier("applicationDataSource") DataSource dataSource, PlatformTransactionManager platformTransactionManager) { return JpaUtil.createEntityManager( "application", dataSource, platformTransactionManager, StringUtils.toStringArray(packagesToScanForEntities())); } /** * Returns the cache manager. * * @return the cache manager */ @Bean public CacheManager cacheManager() { return new ConcurrentMapCacheManager(); } /** * Returns the Jackson2 object mapper. * * @return the Jackson2 object mapper */ @Bean public ObjectMapper objectMapper() { return jackson2ObjectMapperBuilder().build().disable(SerializationFeature.INDENT_OUTPUT); } /** * Returns the Spring task executor to use for @Async method invocations. * * @return the Spring task executor to use for @Async method invocations */ @Bean public Executor taskExecutor() { return new SimpleAsyncTaskExecutor(); } /** * Returns the Spring task scheduler. * * @return the Spring task scheduler */ @Bean public TaskScheduler taskScheduler() { return new ConcurrentTaskScheduler(); } /** * Returns the WebClient.Builder. * * @return the default WebClient.Builder */ @Bean public WebClient.Builder webClientBuilder() { // TODO: Configure with security if available -- MARCUS return WebClient.builder(); } /** * Returns the <b>Jackson2ObjectMapperBuilder</b> bean, which configures the Jackson JSON * processor package. * * @return the <b>Jackson2ObjectMapperBuilder</b> bean, which configures the Jackson JSON * processor package */ protected Jackson2ObjectMapperBuilder jackson2ObjectMapperBuilder() { Jackson2ObjectMapperBuilder jackson2ObjectMapperBuilder = new Jackson2ObjectMapperBuilder(); jackson2ObjectMapperBuilder.indentOutput(true); /* * Install the custom Jackson module that supports serializing and de-serializing ISO 8601 date * and date/time values. The jackson-datatype-jsr310 module provided by Jackson was not used as * it does not handle timezones correctly for LocalDateTime objects. */ jackson2ObjectMapperBuilder.modulesToInstall(new DateTimeModule()); return jackson2ObjectMapperBuilder; } /** * Returns the names of the packages to scan for JPA entity classes. * * @return the names of the packages to scan for JPA entity classes */ protected List<String> packagesToScanForEntities() { List<String> packagesToScan = new ArrayList<>(); // Add the base packages specified using the EnableJpaRepositories annotation Map<String, Object> annotatedBeans = applicationContext.getBeansWithAnnotation(EnableJpaRepositories.class); for (String beanName : annotatedBeans.keySet()) { Class<?> beanClass = annotatedBeans.get(beanName).getClass(); EnableJpaRepositories enableJpaRepositories = beanClass.getAnnotation(EnableJpaRepositories.class); if (enableJpaRepositories != null) { for (String basePackage : enableJpaRepositories.basePackages()) { if (!basePackage.startsWith("africa.absa.inception")) { // Replace any existing packages to scan with the higher level package packagesToScan.removeIf(packageToScan -> packageToScan.startsWith(basePackage)); // Check if there is a higher level package already being scanned if (packagesToScan.stream().noneMatch(basePackage::startsWith)) { packagesToScan.add(basePackage); } } } } } logger.info( "Scanning the following packages for JPA entities: " + StringUtils.collectionToDelimitedString(packagesToScan, ",")); return packagesToScan; } }
0
java-sources/africa/absa/inception-test/1.2.0/africa/absa/inception
java-sources/africa/absa/inception-test/1.2.0/africa/absa/inception/test/TransactionManagerProxy.java
/* * Copyright 2021 original 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. */ package africa.absa.inception.test; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import javax.transaction.HeuristicMixedException; import javax.transaction.HeuristicRollbackException; import javax.transaction.InvalidTransactionException; import javax.transaction.NotSupportedException; import javax.transaction.RollbackException; import javax.transaction.SystemException; import javax.transaction.Transaction; import javax.transaction.TransactionManager; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * The <b>TransactionManagerProxy</b> class provides a proxy that tracks the Java Transaction (JTA) * API transactions associated with the current thread and managed by a <b> * javax.transaction.TransactionManager</b> implementation. * * @author Marcus Portmann */ @SuppressWarnings({"unused"}) public class TransactionManagerProxy implements TransactionManager { /** The stack traces for the active transactions associated with the current thread. */ private static final ThreadLocal<Map<Transaction, StackTraceElement[]>> activeTransactionStackTraces = ThreadLocal.withInitial(ConcurrentHashMap::new); /* Logger */ private static final Logger logger = LoggerFactory.getLogger(TransactionManagerProxy.class); /** The JTA transaction manager. */ private final TransactionManager transactionManager; /** * Constructs a new <b>TransactionManagerProxy</b>. * * @param transactionManager the JTA transaction manager */ public TransactionManagerProxy(TransactionManager transactionManager) { this.transactionManager = transactionManager; } /** * Returns the active transaction stack traces for the current thread. * * @return the active transaction stack traces for the current thread */ static Map<Transaction, StackTraceElement[]> getActiveTransactionStackTraces() { return activeTransactionStackTraces.get(); } @Override public void begin() throws NotSupportedException, SystemException { try { transactionManager.begin(); } finally { Transaction afterTransaction = getTransaction(); if (afterTransaction != null) { getActiveTransactionStackTraces() .put(afterTransaction, Thread.currentThread().getStackTrace()); } } } @Override public void commit() throws RollbackException, HeuristicMixedException, HeuristicRollbackException, SecurityException, IllegalStateException, SystemException { Transaction beforeTransaction = getTransaction(); try { transactionManager.commit(); } finally { Transaction afterTransaction = getTransaction(); if ((beforeTransaction != null) && (afterTransaction == null)) { getActiveTransactionStackTraces().remove(beforeTransaction); } } } @Override public int getStatus() throws SystemException { return transactionManager.getStatus(); } @Override public Transaction getTransaction() throws SystemException { return transactionManager.getTransaction(); } @Override public void resume(Transaction transaction) throws InvalidTransactionException, IllegalStateException, SystemException { transactionManager.resume(transaction); } @Override public void rollback() throws IllegalStateException, SecurityException, SystemException { Transaction beforeTransaction = getTransaction(); try { transactionManager.rollback(); } finally { Transaction afterTransaction = getTransaction(); if ((beforeTransaction != null) && (afterTransaction == null)) { getActiveTransactionStackTraces().remove(beforeTransaction); } } } @Override public void setRollbackOnly() throws IllegalStateException, SystemException { /* * This check to confirm that we have a valid transaction was added to handle the issue * where the Hibernate JPA implementation would try to rollback a transaction even if one * didn't exist when a non-hibernate exception was thrown. */ if (getTransaction() != null) { transactionManager.setRollbackOnly(); } } @Override public void setTransactionTimeout(int i) throws SystemException { transactionManager.setTransactionTimeout(i); } @Override public Transaction suspend() throws SystemException { return transactionManager.suspend(); } }
0
java-sources/africa/absa/inception-test/1.2.0/africa/absa/inception
java-sources/africa/absa/inception-test/1.2.0/africa/absa/inception/test/UserTransactionProxy.java
/* * Copyright 2021 original 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. */ package africa.absa.inception.test; import java.util.Map; import java.util.Optional; import java.util.concurrent.ConcurrentHashMap; import javax.transaction.HeuristicMixedException; import javax.transaction.HeuristicRollbackException; import javax.transaction.NotSupportedException; import javax.transaction.RollbackException; import javax.transaction.SystemException; import javax.transaction.Transaction; import javax.transaction.TransactionManager; import javax.transaction.UserTransaction; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * The <b>UserTransactionProxy</b> class provides a proxy that tracks the Java Transaction (JTA) API * transactions associated with the current thread and managed by a <b> * javax.transaction.UserTransaction</b> implementation. * * @author Marcus Portmann */ @SuppressWarnings({"unused"}) public class UserTransactionProxy implements UserTransaction { /** The stack traces for the active transactions associated with the current thread. */ private static final ThreadLocal<Map<Transaction, StackTraceElement[]>> activeTransactionStackTraces = ThreadLocal.withInitial(ConcurrentHashMap::new); /* Logger */ private static final Logger logger = LoggerFactory.getLogger(UserTransactionProxy.class); /** The JTA transaction manager. */ private final TransactionManager transactionManager; /** The JTA user transaction. */ private final UserTransaction userTransaction; /** * Constructs a new <b>UserTransactionProxy</b>. * * @param userTransaction the JTA user transaction * @param transactionManager the JTA transaction manager */ public UserTransactionProxy( UserTransaction userTransaction, TransactionManager transactionManager) { this.transactionManager = transactionManager; this.userTransaction = userTransaction; } /** * Returns the active transaction stack traces for the current thread. * * @return the active transaction stack traces for the current thread */ static Map<Transaction, StackTraceElement[]> getActiveTransactionStackTraces() { return activeTransactionStackTraces.get(); } @Override public void begin() throws NotSupportedException, SystemException { try { userTransaction.begin(); } finally { Optional<Transaction> afterTransactionOptional = getCurrentTransaction(); if (afterTransactionOptional.isPresent()) { getActiveTransactionStackTraces() .put(afterTransactionOptional.get(), Thread.currentThread().getStackTrace()); } } } @Override public void commit() throws RollbackException, HeuristicMixedException, HeuristicRollbackException, SecurityException, IllegalStateException, SystemException { Optional<Transaction> beforeTransactionOptional = getCurrentTransaction(); try { userTransaction.commit(); } finally { Optional<Transaction> afterTransactionOptional = getCurrentTransaction(); if (beforeTransactionOptional.isPresent() && (afterTransactionOptional.isEmpty())) { getActiveTransactionStackTraces().remove(beforeTransactionOptional.get()); } } } @Override public int getStatus() throws SystemException { return userTransaction.getStatus(); } @Override public void rollback() throws IllegalStateException, SecurityException, SystemException { Optional<Transaction> beforeTransactionOptional = getCurrentTransaction(); try { userTransaction.rollback(); } finally { Optional<Transaction> afterTransactionOptional = getCurrentTransaction(); if (beforeTransactionOptional.isPresent() && (afterTransactionOptional.isEmpty())) { getActiveTransactionStackTraces().remove(beforeTransactionOptional.get()); } } } @Override public void setRollbackOnly() throws IllegalStateException, SystemException { userTransaction.setRollbackOnly(); } @Override public void setTransactionTimeout(int i) throws SystemException { userTransaction.setTransactionTimeout(i); } /** * Returns the current transaction. * * @return an Optional containing the current transaction or an empty Optional if there is no * current transaction */ private Optional<Transaction> getCurrentTransaction() { try { return Optional.ofNullable(transactionManager.getTransaction()); } catch (Throwable e) { logger.error("Failed to retrieve the current transaction", e); return Optional.empty(); } } }
0
java-sources/africa/absa/inception-test/1.2.0/africa/absa/inception
java-sources/africa/absa/inception-test/1.2.0/africa/absa/inception/test/XAConnectionProxy.java
/* * Copyright 2021 original 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. */ package africa.absa.inception.test; import java.sql.Connection; import java.sql.SQLException; import javax.sql.ConnectionEventListener; import javax.sql.StatementEventListener; import javax.sql.XAConnection; import javax.transaction.xa.XAResource; /** * The <b>XAConnectionProxy</b> class implements a proxy for JDBC XA connections. * * @author Marcus Portmann */ public class XAConnectionProxy implements XAConnection { private final XAConnection xaConnection; XAConnectionProxy(XAConnection xaConnection) { this.xaConnection = xaConnection; } @Override public void addConnectionEventListener(ConnectionEventListener listener) { xaConnection.addConnectionEventListener(listener); } @Override public void addStatementEventListener(StatementEventListener listener) { xaConnection.addStatementEventListener(listener); } @Override public void close() throws SQLException { XADataSourceProxy.getActiveXADatabaseConnections().remove(this); xaConnection.close(); } @Override public Connection getConnection() throws SQLException { Connection connection = new ConnectionProxy(xaConnection.getConnection()); DataSourceProxy.addActiveDatabaseConnection(connection); return connection; } @Override public XAResource getXAResource() throws SQLException { return xaConnection.getXAResource(); } @Override public void removeConnectionEventListener(ConnectionEventListener listener) { xaConnection.removeConnectionEventListener(listener); } @Override public void removeStatementEventListener(StatementEventListener listener) { xaConnection.removeStatementEventListener(listener); } }
0
java-sources/africa/absa/inception-test/1.2.0/africa/absa/inception
java-sources/africa/absa/inception-test/1.2.0/africa/absa/inception/test/XADataSourceProxy.java
/* * Copyright 2021 original 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. */ package africa.absa.inception.test; import java.io.PrintWriter; import java.sql.SQLException; import java.sql.SQLFeatureNotSupportedException; import java.sql.ShardingKeyBuilder; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.logging.Logger; import javax.sql.XAConnection; import javax.sql.XAConnectionBuilder; import javax.sql.XADataSource; /** * The <b>DataSourceProxy</b> class provides a proxy that tracks the JDBC connections associated * with the current thread and managed by a <b>javax.sql.XADataSource</b> implementation. * * @author Marcus Portmann */ public class XADataSourceProxy implements XADataSource { /** The active XA database connections associated with the current thread. */ private static final ThreadLocal<Map<XAConnection, StackTraceElement[]>> activeXADatabaseConnections = ThreadLocal.withInitial(ConcurrentHashMap::new); /** The XA data source. */ private final XADataSource xaDataSource; /** * Constructs a new <b>XADataSourceProxy</b>. * * @param xaDataSource the XA data source */ public XADataSourceProxy(XADataSource xaDataSource) { this.xaDataSource = xaDataSource; } /** * Add the XA database connection to the tracked active XA database connections associated with * the current thread. * * @param connection the connection */ public static void addActiveXADatabaseConnection(XAConnection connection) { getActiveXADatabaseConnections().put(connection, Thread.currentThread().getStackTrace()); } /** * Returns the active XA database connections for all Data Sources associated with the tracker. * * @return the active XA database connections for all Data Sources associated with the tracker */ public static Map<XAConnection, StackTraceElement[]> getActiveXADatabaseConnections() { return activeXADatabaseConnections.get(); } @Override public ShardingKeyBuilder createShardingKeyBuilder() throws SQLException { return xaDataSource.createShardingKeyBuilder(); } @Override public XAConnectionBuilder createXAConnectionBuilder() throws SQLException { return xaDataSource.createXAConnectionBuilder(); } @Override public PrintWriter getLogWriter() throws SQLException { return xaDataSource.getLogWriter(); } @Override public int getLoginTimeout() throws SQLException { return xaDataSource.getLoginTimeout(); } @Override public Logger getParentLogger() throws SQLFeatureNotSupportedException { return xaDataSource.getParentLogger(); } @Override public XAConnection getXAConnection() throws SQLException { XAConnection xaConnection = new XAConnectionProxy(xaDataSource.getXAConnection()); addActiveXADatabaseConnection(xaConnection); return xaConnection; } @Override public XAConnection getXAConnection(String user, String password) throws SQLException { XAConnection xaConnection = new XAConnectionProxy(xaDataSource.getXAConnection(user, password)); addActiveXADatabaseConnection(xaConnection); return xaConnection; } @Override public void setLogWriter(PrintWriter out) throws SQLException { xaDataSource.setLogWriter(out); } @Override public void setLoginTimeout(int seconds) throws SQLException { xaDataSource.setLoginTimeout(seconds); } }
0
java-sources/ai/active/webhook-sdk/1.0.7/ai/active/fulfillment
java-sources/ai/active/webhook-sdk/1.0.7/ai/active/fulfillment/webhook/WebhookUtil.java
/* * (C) Copyright 2019 Active Intelligence Pte Ltd (http://active.ai/). * * 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. */ package ai.active.fulfillment.webhook; import java.nio.charset.StandardCharsets; import java.security.InvalidKeyException; import java.security.NoSuchAlgorithmException; import javax.crypto.Mac; import javax.crypto.spec.SecretKeySpec; import org.springframework.security.crypto.codec.Hex; /** * @author Shashank Sh. * */ public class WebhookUtil { private static final String SHA1 = "sha1="; private static final String HMAC_SHA1_ALGORITHM = "HmacSHA1"; public static String generateSignature(String request, String secret) throws NoSuchAlgorithmException, InvalidKeyException { Mac mac = Mac.getInstance(HMAC_SHA1_ALGORITHM); SecretKeySpec signingKey = new SecretKeySpec(secret.getBytes(StandardCharsets.UTF_8), HMAC_SHA1_ALGORITHM); mac.init(signingKey); byte[] rawHmac = mac.doFinal(request.getBytes(StandardCharsets.UTF_8)); StringBuilder stringBuilder = new StringBuilder(); stringBuilder.append(SHA1); stringBuilder.append(Hex.encode(rawHmac)); return stringBuilder.toString(); } }
0
java-sources/ai/active/webhook-sdk/1.0.7/ai/active/fulfillment/webhook/data
java-sources/ai/active/webhook-sdk/1.0.7/ai/active/fulfillment/webhook/data/request/Body.java
/* * (C) Copyright 2019 Active Intelligence Pte Ltd (http://active.ai/). * * 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. */ package ai.active.fulfillment.webhook.data.request; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonPropertyOrder; import org.apache.commons.lang3.builder.ToStringBuilder; import java.io.Serializable; @JsonInclude(JsonInclude.Include.NON_NULL) @JsonPropertyOrder({}) public class Body implements Serializable { private static final long serialVersionUID = -8690564525515815493L; @Override public String toString() { return new ToStringBuilder(this).toString(); } }
0
java-sources/ai/active/webhook-sdk/1.0.7/ai/active/fulfillment/webhook/data
java-sources/ai/active/webhook-sdk/1.0.7/ai/active/fulfillment/webhook/data/request/Bot.java
/* * (C) Copyright 2019 Active Intelligence Pte Ltd (http://active.ai/). * * 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. */ package ai.active.fulfillment.webhook.data.request; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonPropertyOrder; import org.apache.commons.lang3.builder.ToStringBuilder; import java.io.Serializable; @JsonInclude(JsonInclude.Include.NON_NULL) @JsonPropertyOrder({"id", "channel_type", "channel_id", "developer_mode", "language_code", "sync"}) public class Bot implements Serializable { private static final long serialVersionUID = -4564770086015273798L; @JsonProperty("id") private String id; @JsonProperty("channel_type") private String channelType; @JsonProperty("channel_id") private String channelId; @JsonProperty("developer_mode") private Boolean developerMode; @JsonProperty("language_code") private String languageCode; @JsonProperty("sync") private Boolean sync; @JsonProperty("id") public String getId() { return id; } @JsonProperty("id") public void setId(String id) { this.id = id; } @JsonProperty("channel_type") public String getChannelType() { return channelType; } @JsonProperty("channel_type") public void setChannelType(String channelType) { this.channelType = channelType; } @JsonProperty("channel_id") public String getChannelId() { return channelId; } @JsonProperty("channel_id") public void setChannelId(String channelId) { this.channelId = channelId; } @JsonProperty("developer_mode") public Boolean getDeveloperMode() { return developerMode; } @JsonProperty("developer_mode") public void setDeveloperMode(Boolean developerMode) { this.developerMode = developerMode; } @JsonProperty("language_code") public String getLanguageCode() { return languageCode; } @JsonProperty("language_code") public void setLanguageCode(String languageCode) { this.languageCode = languageCode; } @JsonProperty("sync") public Boolean getSync() { return sync; } @JsonProperty("sync") public void setSync(Boolean sync) { this.sync = sync; } @Override public String toString() { return new ToStringBuilder(this).append("id", id).append("channelType", channelType).append("channelId", channelId) .append("developerMode", developerMode).append("languageCode", languageCode).append("sync", sync).toString(); } }
0
java-sources/ai/active/webhook-sdk/1.0.7/ai/active/fulfillment/webhook/data
java-sources/ai/active/webhook-sdk/1.0.7/ai/active/fulfillment/webhook/data/request/MorfeusWebhookRequest.java
/* * (C) Copyright 2019 Active Intelligence Pte Ltd (http://active.ai/). * * 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. */ package ai.active.fulfillment.webhook.data.request; import java.io.Serializable; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonPropertyOrder; import ai.active.fulfillment.webhook.data.request.enums.EventType; @JsonInclude(JsonInclude.Include.NON_NULL) @JsonPropertyOrder({"id", "session_id", "time", "event", "user", "bot", "request", "nlp", "workflow"}) public class MorfeusWebhookRequest implements Serializable { private static final long serialVersionUID = -1091926364497494093L; @JsonProperty("id") private String id; @JsonProperty("session_id") private String sessionId; @JsonProperty("time") private String time; @JsonProperty("event") private EventType event; @JsonProperty("user") private User user; @JsonProperty("bot") private Bot bot; @JsonProperty("request") private Request request; @JsonProperty("nlp") private Nlp nlp; @JsonProperty("workflow") private WorkflowParams workflowParams; @JsonProperty("id") public String getId() { return id; } @JsonProperty("id") public void setId(String id) { this.id = id; } @JsonProperty("time") public String getTime() { return time; } @JsonProperty("time") public void setTime(String time) { this.time = time; } @JsonProperty("event") public EventType getEvent() { return event; } @JsonProperty("event") public void setEvent(EventType event) { this.event = event; } @JsonProperty("user") public User getUser() { return user; } @JsonProperty("user") public void setUser(User user) { this.user = user; } @JsonProperty("bot") public Bot getBot() { return bot; } @JsonProperty("bot") public void setBot(Bot bot) { this.bot = bot; } @JsonProperty("request") public Request getRequest() { return request; } @JsonProperty("request") public void setRequest(Request request) { this.request = request; } @JsonProperty("nlp") public Nlp getNlp() { return nlp; } @JsonProperty("nlp") public void setNlp(Nlp nlp) { this.nlp = nlp; } public String getSessionId() { return sessionId; } public void setSessionId(String sessionId) { this.sessionId = sessionId; } @JsonProperty("workflow") public WorkflowParams getWorkflowParams() { return workflowParams; } @JsonProperty("workflow") public void setWorkflowParams(WorkflowParams workflowParams) { this.workflowParams = workflowParams; } @Override public String toString() { return "MorfeusWebhookRequest [id=" + id + ", sessionId=" + sessionId + ", time=" + time + ", event=" + event + ", user=" + user + ", bot=" + bot + ", request=" + request + ", nlp=" + nlp + ", workflow=" + workflowParams + "]"; } }
0
java-sources/ai/active/webhook-sdk/1.0.7/ai/active/fulfillment/webhook/data
java-sources/ai/active/webhook-sdk/1.0.7/ai/active/fulfillment/webhook/data/request/Nlp.java
/* * (C) Copyright 2019 Active Intelligence Pte Ltd (http://active.ai/). * * 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. */ package ai.active.fulfillment.webhook.data.request; import java.io.Serializable; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonSubTypes; import com.fasterxml.jackson.annotation.JsonSubTypes.Type; import com.fasterxml.jackson.annotation.JsonTypeInfo; @JsonInclude(JsonInclude.Include.NON_NULL) @JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "version") @JsonSubTypes({@Type(value = NlpV1.class, name = "v1"), @Type(value = NlpV2.class, name = "v2")}) public abstract class Nlp implements Serializable { private static final long serialVersionUID = 6073475112576317287L; }
0
java-sources/ai/active/webhook-sdk/1.0.7/ai/active/fulfillment/webhook/data
java-sources/ai/active/webhook-sdk/1.0.7/ai/active/fulfillment/webhook/data/request/NlpV1.java
/* * (C) Copyright 2019 Active Intelligence Pte Ltd (http://active.ai/). * * 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. */ package ai.active.fulfillment.webhook.data.request; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.databind.JsonNode; /** * @author Shashank Sh. * */ public class NlpV1 extends Nlp { private static final long serialVersionUID = -7682657105367673954L; @JsonProperty("data") private JsonNode data; public JsonNode getData() { return data; } public void setData(JsonNode data) { this.data = data; } }
0
java-sources/ai/active/webhook-sdk/1.0.7/ai/active/fulfillment/webhook/data
java-sources/ai/active/webhook-sdk/1.0.7/ai/active/fulfillment/webhook/data/request/NlpV2.java
/* * (C) Copyright 2019 Active Intelligence Pte Ltd (http://active.ai/). * * 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. */ package ai.active.fulfillment.webhook.data.request; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.databind.JsonNode; /** * @author Shashank Sh. * */ public class NlpV2 extends Nlp { private static final long serialVersionUID = 1828334277206938335L; @JsonProperty("data") private JsonNode data; public JsonNode getData() { return data; } public void setData(JsonNode data) { this.data = data; } }
0
java-sources/ai/active/webhook-sdk/1.0.7/ai/active/fulfillment/webhook/data
java-sources/ai/active/webhook-sdk/1.0.7/ai/active/fulfillment/webhook/data/request/Profile.java
/* * (C) Copyright 2019 Active Intelligence Pte Ltd (http://active.ai/). * * 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. */ package ai.active.fulfillment.webhook.data.request; import java.io.Serializable; import org.apache.commons.lang3.builder.ToStringBuilder; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonPropertyOrder; @JsonInclude(JsonInclude.Include.NON_NULL) @JsonPropertyOrder({ }) public class Profile implements Serializable { private static final long serialVersionUID = -4832129033249388404L; @JsonProperty("firstName") private String firstName; @JsonProperty("lastName") private String lastName; @JsonProperty("middleName") private String middleName; @JsonProperty("email") private String email; @JsonProperty("phoneNumber") private String phoneNumber; @JsonProperty("gender") private String gender; @JsonProperty("dob") private String dob; @JsonProperty("locale") private String locale; @JsonProperty("relationshipStatus") private String relationshipStatus; @JsonProperty("religion") private String religion; @JsonProperty("city") private String city; @JsonProperty("state") private String state; @JsonProperty("country") private String country; @JsonProperty("age") private String age; @JsonProperty("spouseId") private String spouseId; @JsonProperty("workExpMatch") private String workExpMatch; @JsonProperty("coverPhotoUrl") private String coverPhotoUrl; @JsonProperty("profileLastupdateDate") private String profileLastupdateDate; @JsonProperty("timeZone") private String timeZone; @JsonProperty("title") private String title; @JsonProperty("address") private String address; @JsonProperty("firstName") public String getFirstName() { return firstName; } @JsonProperty("firstName") public void setFirstName(String firstName) { this.firstName = firstName; } @JsonProperty("lastName") public String getLastName() { return lastName; } @JsonProperty("lastName") public void setLastName(String lastName) { this.lastName = lastName; } @JsonProperty("middleName") public String getMiddleName() { return middleName; } @JsonProperty("middleName") public void setMiddleName(String middleName) { this.middleName = middleName; } @JsonProperty("email") public String getEmail() { return email; } @JsonProperty("email") public void setEmail(String email) { this.email = email; } @JsonProperty("phoneNumber") public String getPhoneNumber() { return phoneNumber; } @JsonProperty("phoneNumber") public void setPhoneNumber(String phoneNumber) { this.phoneNumber = phoneNumber; } @JsonProperty("gender") public String getGender() { return gender; } @JsonProperty("gender") public void setGender(String gender) { this.gender = gender; } @JsonProperty("dob") public String getDob() { return dob; } public void setDob(String dob) { this.dob = dob; } @JsonProperty("locale") public String getLocale() { return locale; } @JsonProperty("locale") public void setLocale(String locale) { this.locale = locale; } @JsonProperty("relationshipStatus") public String getRelationshipStatus() { return relationshipStatus; } @JsonProperty("relationshipStatus") public void setRelationshipStatus(String relationshipStatus) { this.relationshipStatus = relationshipStatus; } @JsonProperty("religion") public String getReligion() { return religion; } @JsonProperty("religion") public void setReligion(String religion) { this.religion = religion; } @JsonProperty("city") public String getCity() { return city; } @JsonProperty("city") public void setCity(String city) { this.city = city; } @JsonProperty("state") public String getState() { return state; } @JsonProperty("state") public void setState(String state) { this.state = state; } @JsonProperty("country") public String getCountry() { return country; } @JsonProperty("country") public void setCountry(String country) { this.country = country; } @JsonProperty("age") public String getAge() { return age; } @JsonProperty("age") public void setAge(String age) { this.age = age; } @JsonProperty("spouseId") public String getSpouseId() { return spouseId; } @JsonProperty("spouseId") public void setSpouseId(String spouseId) { this.spouseId = spouseId; } @JsonProperty("workExpMatch") public String getWorkExpMatch() { return workExpMatch; } @JsonProperty("workExpMatch") public void setWorkExpMatch(String workExpMatch) { this.workExpMatch = workExpMatch; } @JsonProperty("coverPhotoUrl") public String getCoverPhotoUrl() { return coverPhotoUrl; } @JsonProperty("coverPhotoUrl") public void setCoverPhotoUrl(String coverPhotoUrl) { this.coverPhotoUrl = coverPhotoUrl; } @JsonProperty("profileLastupdateDate") public String getProfileLastupdateDate() { return profileLastupdateDate; } @JsonProperty("profileLastupdateDate") public void setProfileLastupdateDate(String profileLastupdateDate) { this.profileLastupdateDate = profileLastupdateDate; } @JsonProperty("timeZone") public String getTimeZone() { return timeZone; } @JsonProperty("timeZone") public void setTimeZone(String timeZone) { this.timeZone = timeZone; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } @Override public String toString() { return new ToStringBuilder(this).toString(); } }
0
java-sources/ai/active/webhook-sdk/1.0.7/ai/active/fulfillment/webhook/data
java-sources/ai/active/webhook-sdk/1.0.7/ai/active/fulfillment/webhook/data/request/Request.java
/* * (C) Copyright 2019 Active Intelligence Pte Ltd (http://active.ai/). * * 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. */ package ai.active.fulfillment.webhook.data.request; import java.io.Serializable; import java.util.HashMap; import java.util.Map; import org.apache.commons.lang3.builder.ToStringBuilder; import com.fasterxml.jackson.annotation.JsonAnyGetter; import com.fasterxml.jackson.annotation.JsonAnySetter; import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonInclude; @JsonInclude(JsonInclude.Include.NON_NULL) public class Request implements Serializable { private static final long serialVersionUID = 718818345247810591L; private String type; private String text; private String payload; @JsonIgnore private Map<String, Object> additionalProperties = new HashMap<>(); public String getType() { return type; } public void setType(String type) { this.type = type; } public String getText() { return text; } public void setText(String text) { this.text = text; } public String getPayload() { return payload; } public void setPayload(String payload) { this.payload = payload; } @JsonAnyGetter public Map<String, Object> getAdditionalProperties() { return this.additionalProperties; } @JsonAnySetter public void setAdditionalProperty(String name, Object value) { this.additionalProperties.put(name, value); } @Override public String toString() { return new ToStringBuilder(this).toString(); } }
0
java-sources/ai/active/webhook-sdk/1.0.7/ai/active/fulfillment/webhook/data
java-sources/ai/active/webhook-sdk/1.0.7/ai/active/fulfillment/webhook/data/request/User.java
/* * (C) Copyright 2019 Active Intelligence Pte Ltd (http://active.ai/). * * 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. */ package ai.active.fulfillment.webhook.data.request; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonPropertyOrder; import org.apache.commons.lang3.builder.ToStringBuilder; import java.io.Serializable; @JsonInclude(JsonInclude.Include.NON_NULL) @JsonPropertyOrder({"id", "profile"}) public class User implements Serializable { private static final long serialVersionUID = 6613268779717286316L; @JsonProperty("id") private String id; @JsonProperty("channel_id") private String channelId; @JsonProperty("logged_id") private boolean loggedIn; @JsonProperty("customer_id") private String customerId; @JsonProperty("access_token") private String accessToken; @JsonProperty("profile") private Profile profile; @JsonProperty("custSeg") private String custSeg; @JsonProperty("id") public String getId() { return id; } @JsonProperty("id") public void setId(String id) { this.id = id; } @JsonProperty("profile") public Profile getProfile() { return profile; } @JsonProperty("profile") public void setProfile(Profile profile) { this.profile = profile; } public String getChannelId() { return channelId; } public void setChannelId(String channelId) { this.channelId = channelId; } public String getAccessToken() { return accessToken; } public void setAccessToken(String accessToken) { this.accessToken = accessToken; } public boolean isLoggedIn() { return loggedIn; } public void setLoggedIn(boolean loggedIn) { this.loggedIn = loggedIn; } public String getCustomerId() { return customerId; } public void setCustomerId(String customerId) { this.customerId = customerId; } @Override public String toString() { return new ToStringBuilder(this).append("id", id).append("profile", profile).toString(); } public String getCustSeg() { return custSeg; } public void setCustSeg(String custSeg) { this.custSeg = custSeg; } }
0
java-sources/ai/active/webhook-sdk/1.0.7/ai/active/fulfillment/webhook/data
java-sources/ai/active/webhook-sdk/1.0.7/ai/active/fulfillment/webhook/data/request/WorkflowParams.java
/* * (C) Copyright 2019 Active Intelligence Pte Ltd (http://active.ai/). * * 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. */ package ai.active.fulfillment.webhook.data.request; import java.io.Serializable; import java.util.Map; import ai.active.fulfillment.webhook.data.request.enums.WorkflowProperty; /** * @author Pranay Kh. * * This class will contain all properties that are specific to workflow and * are needed to access workflow state data from api implementation. * */ public class WorkflowParams implements Serializable { private static final long serialVersionUID = 2499593678372277829L; /* * this will contain key value pair for pojos defined in workflow module * that need inclusion in webhook request from workflow * e.g. Node, Workflow * * */ private Map<WorkflowProperty, Object> additionalParams; private Map<String, String> workflowVariables; private Map<String, String> globalVariables; private Map<String, String> requestVariables; private String nodeId; private String workflowId; private String status; private Integer dataVersion; private Boolean enableJumpNode; public Map<WorkflowProperty, Object> getAdditionalParams() { return additionalParams; } public void setAdditionalParams(Map<WorkflowProperty, Object> additionalParams) { this.additionalParams = additionalParams; } public Map<String, String> getWorkflowVariables() { return workflowVariables; } public void setWorkflowVariables(Map<String, String> workflowVariables) { this.workflowVariables = workflowVariables; } public Map<String, String> getGlobalVariables() { return globalVariables; } public void setGlobalVariables(Map<String, String> globalVariables) { this.globalVariables = globalVariables; } public Map<String, String> getRequestVariables() { return requestVariables; } public void setRequestVariables(Map<String, String> requestVariables) { this.requestVariables = requestVariables; } public String getNodeId() { return nodeId; } public void setNodeId(String nodeId) { this.nodeId = nodeId; } public String getWorkflowId() { return workflowId; } public void setWorkflowId(String workflowId) { this.workflowId = workflowId; } public String getStatus() { return status; } public void setStatus(String status) { this.status = status; } public Integer getDataVersion() { return dataVersion; } public void setDataVersion(Integer dataVersion) { this.dataVersion = dataVersion; } public Boolean getEnableJumpNode() { return enableJumpNode; } public void setEnableJumpNode(Boolean enableJumpNode) { this.enableJumpNode = enableJumpNode; } }
0
java-sources/ai/active/webhook-sdk/1.0.7/ai/active/fulfillment/webhook/data/request
java-sources/ai/active/webhook-sdk/1.0.7/ai/active/fulfillment/webhook/data/request/enums/EventType.java
/* * (C) Copyright 2019 Active Intelligence Pte Ltd (http://active.ai/). * * 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. */ package ai.active.fulfillment.webhook.data.request.enums; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonValue; import java.util.HashMap; import java.util.Map; /** * @author Pranay Kh. */ public enum EventType { // @formatter:off FULFILMENT("fulfilment"), WORKFLOW_VALIDATION("wf_validation"), WORKFLOW_CONNECTION("wf_connection"), WORKFLOW_PROMPT("wf_prompt"), WORKFLOW_UPDATE_VALIDATION("wf_u_validation"), WORKFLOW_UPDATE_CONNECTION("wf_u_connection"); // @formatter:on private static final Map<String, EventType> CONSTANTS = new HashMap<>(); private String value; static { for (EventType c : values()) { CONSTANTS.put(c.value, c); } } EventType(String value) { this.value = value; } @JsonCreator public static EventType fromValue(String value) { EventType constant = CONSTANTS.get(value); if (constant == null) { throw new IllegalArgumentException(value); } else { return constant; } } @Override public String toString() { return this.value; } @JsonValue public String value() { return this.value; } }
0
java-sources/ai/active/webhook-sdk/1.0.7/ai/active/fulfillment/webhook/data/request
java-sources/ai/active/webhook-sdk/1.0.7/ai/active/fulfillment/webhook/data/request/enums/WorkflowProperty.java
/* * (C) Copyright 2019 Active Intelligence Pte Ltd (http://active.ai/). * * 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. */ package ai.active.fulfillment.webhook.data.request.enums; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonValue; import java.util.HashMap; import java.util.Map; /** * @author Pranay Kh. */ public enum WorkflowProperty { NODE("node"), WORKFLOW("workflow"); private static final Map<String, WorkflowProperty> CONSTANTS = new HashMap<>(); private String value; static { for (WorkflowProperty c : values()) { CONSTANTS.put(c.value, c); } } WorkflowProperty(String value) { this.value = value; } @JsonCreator public static WorkflowProperty fromValue(String value) { WorkflowProperty constant = CONSTANTS.get(value); if (constant == null) { throw new IllegalArgumentException(value); } else { return constant; } } @Override public String toString() { return this.value; } @JsonValue public String value() { return this.value; } }
0
java-sources/ai/active/webhook-sdk/1.0.7/ai/active/fulfillment/webhook/data
java-sources/ai/active/webhook-sdk/1.0.7/ai/active/fulfillment/webhook/data/response/AbstractMessage.java
/* * (C) Copyright 2019 Active Intelligence Pte Ltd (http://active.ai/). * * 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. */ package ai.active.fulfillment.webhook.data.response; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonSubTypes; import com.fasterxml.jackson.annotation.JsonTypeInfo; import java.io.Serializable; import java.util.List; // @formatter:off @JsonTypeInfo( use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.EXISTING_PROPERTY, property = "type", visible = true, defaultImpl = HookMessage.class ) @JsonSubTypes({ @JsonSubTypes.Type(value = TextMessage.class, name = TextMessage.TYPE), @JsonSubTypes.Type(value = ListMessage.class, name = ListMessage.TYPE), @JsonSubTypes.Type(value = ButtonMessage.class, name = ButtonMessage.TYPE), @JsonSubTypes.Type(value = CarouselMessage.class, name = CarouselMessage.TYPE), @JsonSubTypes.Type(value = ImageMessage.class, name = ImageMessage.TYPE), @JsonSubTypes.Type(value = VideoMessage.class, name = VideoMessage.TYPE), @JsonSubTypes.Type(value = CustomMessage.class, name = CustomMessage.TYPE), @JsonSubTypes.Type(value = MarkupMessage.class, name = MarkupMessage.TYPE), @JsonSubTypes.Type(value = DynamicMessage.class, name = DynamicMessage.TYPE) }) // @formatter:on public abstract class AbstractMessage implements Serializable { private static final long serialVersionUID = 3371211295620897143L; @JsonProperty("type") private String type; @JsonProperty("quick_replies") private List<QuickReply> quickReplies = null; @JsonProperty("speechResponse") private String speechResponse; @JsonProperty("customTemplateName") private String customTemplateName; @JsonProperty("max_digits") private Integer maxDigits; @JsonProperty("type") public String getType() { return type; } @JsonProperty("type") public void setType(String type) { this.type = type; } @JsonProperty("quick_replies") public List<QuickReply> getQuickReplies() { return quickReplies; } @JsonProperty("quick_replies") public void setQuickReplies(List<QuickReply> quickReplies) { this.quickReplies = quickReplies; } @JsonProperty("speechResponse") public String getSpeechResponse() { return speechResponse; } @JsonProperty("speechResponse") public void setSpeechResponse(String speechResponse) { this.speechResponse = speechResponse; } @JsonProperty("customTemplateName") public String getCustomTemplateName() { return customTemplateName; } @JsonProperty("customTemplateName") public void setCustomTemplateName(String customTemplateName) { this.customTemplateName = customTemplateName; } @JsonProperty("max_digits") public Integer getMaxDigits() { return maxDigits; } @JsonProperty("max_digits") public void setMaxDigits(Integer maxDigits) { this.maxDigits = maxDigits; } public abstract Object getContent(); }
0
java-sources/ai/active/webhook-sdk/1.0.7/ai/active/fulfillment/webhook/data
java-sources/ai/active/webhook-sdk/1.0.7/ai/active/fulfillment/webhook/data/response/Audit.java
/* * (C) Copyright 2019 Active Intelligence Pte Ltd (http://active.ai/). * * 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. */ package ai.active.fulfillment.webhook.data.response; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonPropertyOrder; import org.apache.commons.lang3.builder.ToStringBuilder; import java.io.Serializable; @JsonInclude(JsonInclude.Include.NON_NULL) @JsonPropertyOrder({"sub_intent", "step", "transaction_id", "transaction_type"}) public class Audit implements Serializable { private static final long serialVersionUID = -7397974993814211024L; @JsonProperty("sub_intent") private String subIntent; @JsonProperty("step") private String step; @JsonProperty("transaction_id") private String transactionId; @JsonProperty("transaction_type") private String transactionType; @JsonProperty("sub_intent") public String getSubIntent() { return subIntent; } @JsonProperty("sub_intent") public void setSubIntent(String subIntent) { this.subIntent = subIntent; } @JsonProperty("step") public String getStep() { return step; } @JsonProperty("step") public void setStep(String step) { this.step = step; } @JsonProperty("transaction_id") public String getTransactionId() { return transactionId; } @JsonProperty("transaction_id") public void setTransactionId(String transactionId) { this.transactionId = transactionId; } @JsonProperty("transaction_type") public String getTransactionType() { return transactionType; } @JsonProperty("transaction_type") public void setTransactionType(String transactionType) { this.transactionType = transactionType; } @Override public String toString() { return new ToStringBuilder(this).append("subIntent", subIntent).append("step", step).append("transactionId", transactionId) .append("transactionType", transactionType).toString(); } }
0
java-sources/ai/active/webhook-sdk/1.0.7/ai/active/fulfillment/webhook/data
java-sources/ai/active/webhook-sdk/1.0.7/ai/active/fulfillment/webhook/data/response/Button.java
/* * (C) Copyright 2019 Active Intelligence Pte Ltd (http://active.ai/). * * 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. */ package ai.active.fulfillment.webhook.data.response; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonPropertyOrder; import org.apache.commons.lang3.builder.ToStringBuilder; import java.io.Serializable; @JsonInclude(JsonInclude.Include.NON_NULL) @JsonPropertyOrder({"title", "type", "webview_type", "auth_required", "life", "payload", "postback", "intent", "extra_payload", "message"}) public class Button implements Serializable { private static final long serialVersionUID = 2639997584698897729L; @JsonProperty("title") private String title; @JsonProperty("type") private String type; @JsonProperty("webview_type") private String webviewType; @JsonProperty("auth_required") private String authRequired; @JsonProperty("life") private String life; @JsonProperty("payload") private String payload; @JsonProperty("postback") private String postback; @JsonProperty("intent") private String intent; @JsonProperty("extra_payload") private String extraPayload; @JsonProperty("message") private String message; @JsonProperty("title") public String getTitle() { return title; } @JsonProperty("title") public void setTitle(String title) { this.title = title; } @JsonProperty("type") public String getType() { return type; } @JsonProperty("type") public void setType(String type) { this.type = type; } @JsonProperty("webview_type") public String getWebviewType() { return webviewType; } @JsonProperty("webview_type") public void setWebviewType(String webviewType) { this.webviewType = webviewType; } @JsonProperty("auth_required") public String getAuthRequired() { return authRequired; } @JsonProperty("auth_required") public void setAuthRequired(String authRequired) { this.authRequired = authRequired; } @JsonProperty("life") public String getLife() { return life; } @JsonProperty("life") public void setLife(String life) { this.life = life; } @JsonProperty("payload") public String getPayload() { return payload; } @JsonProperty("payload") public void setPayload(String payload) { this.payload = payload; } @JsonProperty("postback") public String getPostback() { return postback; } @JsonProperty("postback") public void setPostback(String postback) { this.postback = postback; } @JsonProperty("intent") public String getIntent() { return intent; } @JsonProperty("intent") public void setIntent(String intent) { this.intent = intent; } @JsonProperty("extra_payload") public String getExtraPayload() { return extraPayload; } @JsonProperty("extra_payload") public void setExtraPayload(String extraPayload) { this.extraPayload = extraPayload; } @JsonProperty("message") public String getMessage() { return message; } @JsonProperty("message") public void setMessage(String message) { this.message = message; } @Override public String toString() { return new ToStringBuilder(this).append("title", title).append("type", type).append("webviewType", webviewType) .append("authRequired", authRequired).append("life", life).append("payload", payload).append("postback", postback) .append("intent", intent).append("extraPayload", extraPayload).append("message", message).toString(); } }
0
java-sources/ai/active/webhook-sdk/1.0.7/ai/active/fulfillment/webhook/data
java-sources/ai/active/webhook-sdk/1.0.7/ai/active/fulfillment/webhook/data/response/ButtonMessage.java
/* * (C) Copyright 2019 Active Intelligence Pte Ltd (http://active.ai/). * * 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. */ package ai.active.fulfillment.webhook.data.response; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; import java.io.Serializable; @JsonInclude(JsonInclude.Include.NON_NULL) public class ButtonMessage extends AbstractMessage implements Serializable { private static final long serialVersionUID = 5610150626917294732L; protected static final String TYPE = "button"; @JsonProperty("content") private Content content; @JsonProperty("content") public Content getContent() { return content; } @JsonProperty("content") public void setContent(Content content) { this.content = content; } }
0
java-sources/ai/active/webhook-sdk/1.0.7/ai/active/fulfillment/webhook/data
java-sources/ai/active/webhook-sdk/1.0.7/ai/active/fulfillment/webhook/data/response/ButtonType.java
/* * (C) Copyright 2019 Active Intelligence Pte Ltd (http://active.ai/). * * 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. */ package ai.active.fulfillment.webhook.data.response; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonValue; import java.util.HashMap; import java.util.Map; public enum ButtonType { POSTBACK("postback"), WEBURL("weburl"); private static final Map<String, ButtonType> CONSTANTS = new HashMap<>(); static { for (ButtonType c : values()) { CONSTANTS.put(c.value, c); } } private String value; ButtonType(String value) { this.value = value; } @JsonCreator public static ButtonType fromValue(String value) { ButtonType constant = CONSTANTS.get(value); if (constant == null) { throw new IllegalArgumentException(value); } else { return constant; } } @Override public String toString() { return this.value; } @JsonValue public String value() { return this.value; } }
0
java-sources/ai/active/webhook-sdk/1.0.7/ai/active/fulfillment/webhook/data
java-sources/ai/active/webhook-sdk/1.0.7/ai/active/fulfillment/webhook/data/response/CarouselMessage.java
/* * (C) Copyright 2019 Active Intelligence Pte Ltd (http://active.ai/). * * 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. */ package ai.active.fulfillment.webhook.data.response; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; import java.io.Serializable; import java.util.List; @JsonInclude(JsonInclude.Include.NON_NULL) public class CarouselMessage extends AbstractMessage implements Serializable { private static final long serialVersionUID = 8125746124348212739L; protected static final String TYPE = "carousel"; @JsonProperty("content") private List<Content> content = null; @JsonProperty("content") public List<Content> getContent() { return content; } @JsonProperty("content") public void setContent(List<Content> content) { this.content = content; } }
0
java-sources/ai/active/webhook-sdk/1.0.7/ai/active/fulfillment/webhook/data
java-sources/ai/active/webhook-sdk/1.0.7/ai/active/fulfillment/webhook/data/response/Content.java
/* * (C) Copyright 2019 Active Intelligence Pte Ltd (http://active.ai/). * * 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. */ package ai.active.fulfillment.webhook.data.response; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonPropertyOrder; import java.io.Serializable; @JsonInclude(JsonInclude.Include.NON_NULL) @JsonPropertyOrder({"list", "buttons"}) public class Content implements Serializable { private static final long serialVersionUID = 1237183270312594134L; @JsonProperty("list") private java.util.List<Content> list = null; @JsonProperty("buttons") private java.util.List<Object> buttons = null; @JsonProperty("image") private String image = null; @JsonProperty("title") private String title = null; @JsonProperty("subtitle") private String subtitle = null; @JsonProperty("video") private String video = null; @JsonProperty("markup") private String markup = null; @JsonProperty("image") public String getImage() { return this.image; } @JsonProperty("image") public void setImage(String image) { this.image = image; } @JsonProperty("list") public java.util.List<Content> getList() { return list; } @JsonProperty("list") public void setList(java.util.List<Content> list) { this.list = list; } @JsonProperty("buttons") public java.util.List<Object> getButtons() { return buttons; } @JsonProperty("buttons") public void setButtons(java.util.List<Object> buttons) { this.buttons = buttons; } @JsonProperty("title") public String getTitle() { return title; } @JsonProperty("title") public void setTitle(String title) { this.title = title; } @JsonProperty("subtitle") public String getSubtitle() { return subtitle; } @JsonProperty("subtitle") public void setSubtitle(String subtitle) { this.subtitle = subtitle; } @JsonProperty("video") public String getVideo() { return video; } @JsonProperty("video") public void setVideo(String video) { this.video = video; } @JsonProperty("markup") public String getMarkup() { return markup; } @JsonProperty("markup") public void setMarkup(String markup) { this.markup = markup; } }
0
java-sources/ai/active/webhook-sdk/1.0.7/ai/active/fulfillment/webhook/data
java-sources/ai/active/webhook-sdk/1.0.7/ai/active/fulfillment/webhook/data/response/CustomMessage.java
/* * (C) Copyright 2019 Active Intelligence Pte Ltd (http://active.ai/). * * 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. */ package ai.active.fulfillment.webhook.data.response; import java.io.Serializable; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonPropertyOrder; @JsonInclude(JsonInclude.Include.NON_NULL) @JsonPropertyOrder({ "content" }) public class CustomMessage extends AbstractMessage implements Serializable { private static final long serialVersionUID = -4906337297706130771L; protected static final String TYPE = "custom"; @JsonProperty("content") private Content content; @JsonProperty("content") public Content getContent() { return content; } @JsonProperty("content") public void setContent(Content content) { this.content = content; } }
0
java-sources/ai/active/webhook-sdk/1.0.7/ai/active/fulfillment/webhook/data
java-sources/ai/active/webhook-sdk/1.0.7/ai/active/fulfillment/webhook/data/response/DynamicMessage.java
/* * (C) Copyright 2016 Active Intelligence Pte Ltd (http://active.ai/). * * This software is the confidential and proprietary information of Active Intelligence. * ("Confidential Information"). You shall not disclose such Confidential Information and shall use * it only in accordance with the terms of the license agreement you entered into with Active * Intelligence * */ package ai.active.fulfillment.webhook.data.response; /** * @author Shashank Sh. * */ public class DynamicMessage extends AbstractMessage { private static final long serialVersionUID = -5184670312445561846L; protected static final String TYPE = "dynamic"; private String id; private String base; private AbstractMessage content; /* * (non-Javadoc) * * @see ai.active.fulfillment.webhook.data.response.AbstractMessage#getContent() */ @Override public AbstractMessage getContent() { return content; } public String getId() { return id; } public void setId(String id) { this.id = id; } public void setContent(AbstractMessage content) { this.content = content; } public String getBase() { return base; } public void setBase(String base) { this.base = base; } }
0
java-sources/ai/active/webhook-sdk/1.0.7/ai/active/fulfillment/webhook/data
java-sources/ai/active/webhook-sdk/1.0.7/ai/active/fulfillment/webhook/data/response/GotoLinkedType.java
/* * (C) Copyright 2019 Active Intelligence Pte Ltd (http://active.ai/). * * 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. */ package ai.active.fulfillment.webhook.data.response; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonValue; import java.util.HashMap; import java.util.Map; /** * @author Pranay Kh. */ public enum GotoLinkedType { BACKLINK("backlink"); private static final Map<String, GotoLinkedType> CONSTANTS = new HashMap<>(); static { for (GotoLinkedType c : values()) { CONSTANTS.put(c.value, c); } } private final String value; private GotoLinkedType(String value) { this.value = value; } @JsonCreator public static GotoLinkedType fromValue(String value) { GotoLinkedType constant = CONSTANTS.get(value); if (constant == null) { return null; } else { return constant; } } @Override public String toString() { return this.value; } @JsonValue public String value() { return this.value; } }
0
java-sources/ai/active/webhook-sdk/1.0.7/ai/active/fulfillment/webhook/data
java-sources/ai/active/webhook-sdk/1.0.7/ai/active/fulfillment/webhook/data/response/GotoType.java
/* * (C) Copyright 2019 Active Intelligence Pte Ltd (http://active.ai/). * * 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. */ package ai.active.fulfillment.webhook.data.response; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonValue; import java.util.HashMap; import java.util.Map; /** * @author Pranay Kh. */ public enum GotoType { PROCESS("process"), OUTPUT("output"), NODE("node"), END_FLOW("endFlow"),CUSTOM("custom"), JAVA("java"), WEBHOOK("webhook"); private static final Map<String, GotoType> CONSTANTS = new HashMap<>(); static { for (GotoType c : values()) { CONSTANTS.put(c.value, c); } } private final String value; private GotoType(String value) { this.value = value; } @JsonCreator public static GotoType fromValue(String value) { GotoType constant = CONSTANTS.get(value); if (constant == null) { return null; } else { return constant; } } @Override public String toString() { return this.value; } @JsonValue public String value() { return this.value; } }
0
java-sources/ai/active/webhook-sdk/1.0.7/ai/active/fulfillment/webhook/data
java-sources/ai/active/webhook-sdk/1.0.7/ai/active/fulfillment/webhook/data/response/HookMessage.java
/* * (C) Copyright 2019 Active Intelligence Pte Ltd (http://active.ai/). * * 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. */ package ai.active.fulfillment.webhook.data.response; /** * @author Shashank Sh. * */ public class HookMessage extends AbstractMessage { private static final long serialVersionUID = -6883454168752075023L; private String content; public void setContent(String content) { this.content = content; } /* * (non-Javadoc) * * @see com.morfeus.fulfillment.webhook.data.response.AbstractMessage#getContent() */ @Override public String getContent() { return content; } }
0
java-sources/ai/active/webhook-sdk/1.0.7/ai/active/fulfillment/webhook/data
java-sources/ai/active/webhook-sdk/1.0.7/ai/active/fulfillment/webhook/data/response/ImageMessage.java
/* * (C) Copyright 2019 Active Intelligence Pte Ltd (http://active.ai/). * * 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. */ package ai.active.fulfillment.webhook.data.response; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; import java.io.Serializable; @JsonInclude(JsonInclude.Include.NON_NULL) public class ImageMessage extends AbstractMessage implements Serializable { private static final long serialVersionUID = 6224513910639829674L; protected static final String TYPE = "image"; @JsonProperty("content") private Content content; @JsonProperty("content") public Content getContent() { return content; } @JsonProperty("content") public void setContent(Content content) { this.content = content; } }
0
java-sources/ai/active/webhook-sdk/1.0.7/ai/active/fulfillment/webhook/data
java-sources/ai/active/webhook-sdk/1.0.7/ai/active/fulfillment/webhook/data/response/KeyboardState.java
/* * (C) Copyright 2019 Active Intelligence Pte Ltd (http://active.ai/). * * 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. */ package ai.active.fulfillment.webhook.data.response; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonValue; import java.util.HashMap; import java.util.Map; public enum KeyboardState { ALPHA("ALPHA"), NUM("NUM"), NONE("NONE"), HIDE("HIDE"), PWD("PWD"), TEXT("TEXT"), DISABLE("DISABLE"); private static final Map<String, KeyboardState> CONSTANTS = new HashMap<>(); static { for (KeyboardState c : values()) { CONSTANTS.put(c.value, c); } } private String value; KeyboardState(String value) { this.value = value; } @JsonCreator public static KeyboardState fromValue(String value) { KeyboardState constant = CONSTANTS.get(value); if (constant == null) { throw new IllegalArgumentException(value); } else { return constant; } } @Override public String toString() { return this.value; } @JsonValue public String value() { return this.value; } }
0
java-sources/ai/active/webhook-sdk/1.0.7/ai/active/fulfillment/webhook/data
java-sources/ai/active/webhook-sdk/1.0.7/ai/active/fulfillment/webhook/data/response/ListContent.java
/* * (C) Copyright 2019 Active Intelligence Pte Ltd (http://active.ai/). * * 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. */ package ai.active.fulfillment.webhook.data.response; import java.io.Serializable; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonPropertyOrder; @JsonInclude(JsonInclude.Include.NON_NULL) @JsonPropertyOrder({"list", "buttons"}) public class ListContent implements Serializable { private static final long serialVersionUID = -1759045313387280359L; @JsonProperty("style") private ListStyle style; @JsonProperty("list") private java.util.List<Content> list = null; @JsonProperty("buttons") private java.util.List<Object> buttons = null; @JsonProperty("list") public java.util.List<Content> getList() { return list; } @JsonProperty("list") public void setList(java.util.List<Content> list) { this.list = list; } @JsonProperty("buttons") public java.util.List<Object> getButtons() { return buttons; } @JsonProperty("buttons") public void setButtons(java.util.List<Object> buttons) { this.buttons = buttons; } @JsonProperty("style") public ListStyle getStyle() { return style; } @JsonProperty("style") public void setStyle(ListStyle style) { this.style = style; } }
0
java-sources/ai/active/webhook-sdk/1.0.7/ai/active/fulfillment/webhook/data
java-sources/ai/active/webhook-sdk/1.0.7/ai/active/fulfillment/webhook/data/response/ListMessage.java
/* * (C) Copyright 2019 Active Intelligence Pte Ltd (http://active.ai/). * * 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. */ package ai.active.fulfillment.webhook.data.response; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; @JsonInclude(JsonInclude.Include.NON_NULL) public class ListMessage extends AbstractMessage { private static final long serialVersionUID = 216963375915855841L; protected static final String TYPE = "list"; @JsonProperty("content") private ListContent content; @JsonProperty("content") public ListContent getContent() { return content; } @JsonProperty("content") public void setContent(ListContent content) { this.content = content; } }
0
java-sources/ai/active/webhook-sdk/1.0.7/ai/active/fulfillment/webhook/data
java-sources/ai/active/webhook-sdk/1.0.7/ai/active/fulfillment/webhook/data/response/ListStyle.java
/* * (C) Copyright 2016 Active Intelligence Pte Ltd (http://active.ai/). * * This software is the confidential and proprietary information of Active Intelligence. * ("Confidential Information"). You shall not disclose such Confidential Information and shall use * it only in accordance with the terms of the license agreement you entered into with Active * Intelligence * */ package ai.active.fulfillment.webhook.data.response; import com.fasterxml.jackson.annotation.JsonProperty; /** * @author Shashank Sh. * */ public enum ListStyle { @JsonProperty("compact") COMPACT("compact"), @JsonProperty("large") LARGE("large"); private String style; ListStyle(String style) { this.style = style; } public String getStyle() { return this.style; } }
0
java-sources/ai/active/webhook-sdk/1.0.7/ai/active/fulfillment/webhook/data
java-sources/ai/active/webhook-sdk/1.0.7/ai/active/fulfillment/webhook/data/response/MarkupMessage.java
/* * (C) Copyright 2019 Active Intelligence Pte Ltd (http://active.ai/). * * 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. */ package ai.active.fulfillment.webhook.data.response; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonPropertyOrder; import java.io.Serializable; /** * @author Pranay Kh. */ @JsonInclude(JsonInclude.Include.NON_NULL) @JsonPropertyOrder({ "content" }) public class MarkupMessage extends AbstractMessage implements Serializable { private static final long serialVersionUID = 2809781085766744287L; protected static final String TYPE = "markup"; @JsonProperty("content") private Content content; @JsonProperty("content") public Content getContent() { return content; } @JsonProperty("content") public void setContent(Content content) { this.content = content; } }
0
java-sources/ai/active/webhook-sdk/1.0.7/ai/active/fulfillment/webhook/data
java-sources/ai/active/webhook-sdk/1.0.7/ai/active/fulfillment/webhook/data/response/MessageType.java
/* * (C) Copyright 2019 Active Intelligence Pte Ltd (http://active.ai/). * * 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. */ package ai.active.fulfillment.webhook.data.response; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonValue; import java.util.HashMap; import java.util.Map; public enum MessageType { TEXT(TextMessage.TYPE), LIST(ListMessage.TYPE), BUTTON(ButtonMessage.TYPE), CAROUSEL(CarouselMessage.TYPE), IMAGE( ImageMessage.TYPE), VIDEO(VideoMessage.TYPE), CUSTOM(CustomMessage.TYPE), MARKUP(MarkupMessage.TYPE), DYNAMIC(DynamicMessage.TYPE); private static final Map<String, MessageType> CONSTANTS = new HashMap<>(); static { for (MessageType c : values()) { CONSTANTS.put(c.value, c); } } private String value; MessageType(String value) { this.value = value; } @JsonCreator public static MessageType fromValue(String value) { MessageType constant = CONSTANTS.get(value); if (constant == null) { throw new IllegalArgumentException(value); } else { return constant; } } @Override public String toString() { return this.value; } @JsonValue public final String value() { return this.value; } }
0
java-sources/ai/active/webhook-sdk/1.0.7/ai/active/fulfillment/webhook/data
java-sources/ai/active/webhook-sdk/1.0.7/ai/active/fulfillment/webhook/data/response/MorfeusWebhookResponse.java
/* * (C) Copyright 2019 Active Intelligence Pte Ltd (http://active.ai/). * * 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. */ package ai.active.fulfillment.webhook.data.response; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonPropertyOrder; import org.apache.commons.lang3.builder.ToStringBuilder; import java.io.Serializable; import java.util.List; import java.util.Map; @JsonInclude(JsonInclude.Include.NON_NULL) @JsonPropertyOrder({"messages", "render", "keyboard_state", "status", "expected_entities", "extra_data", "audit", "headers", "customerId"}) public class MorfeusWebhookResponse implements Serializable { private static final long serialVersionUID = -5495533712195902428L; @JsonProperty("messages") private List<AbstractMessage> messages = null; @JsonProperty("render") private String render; @JsonProperty("keyboard_state") private String keyboardState; @JsonProperty("max_digits") private Integer maxDigits; @JsonProperty("status") private Status status; @JsonProperty("expected_entities") private List<String> expectedEntities = null; @JsonProperty("extra_data") private Map<String, Object> extraData = null; @JsonProperty("audit") private Audit audit; @JsonProperty("headers") private Map<String, String> headers; @JsonProperty("customerId") private String customerId; @JsonProperty("messages") public List<AbstractMessage> getMessages() { return messages; } @JsonProperty("messages") public void setMessages(List<AbstractMessage> messages) { this.messages = messages; } @JsonProperty("render") public String getRender() { return render; } @JsonProperty("render") public void setRender(String render) { this.render = render; } @JsonProperty("keyboard_state") public String getKeyboardState() { return keyboardState; } @JsonProperty("keyboard_state") public void setKeyboardState(String keyboardState) { this.keyboardState = keyboardState; } @JsonProperty("max_digits") public Integer getMaxDigits() { return maxDigits; } @JsonProperty("max_digits") public void setMaxDigits(Integer maxDigits) { this.maxDigits = maxDigits; } @JsonProperty("status") public Status getStatus() { return status; } @JsonProperty("status") public void setStatus(Status status) { this.status = status; } @JsonProperty("expected_entities") public List<String> getExpectedEntities() { return expectedEntities; } @JsonProperty("expected_entities") public void setExpectedEntities(List<String> expectedEntities) { this.expectedEntities = expectedEntities; } @JsonProperty("extra_data") public Map<String, Object> getExtraData() { return extraData; } @JsonProperty("extra_data") public void setExtraData(Map<String, Object> extraData) { this.extraData = extraData; } @JsonProperty("audit") public Audit getAudit() { return audit; } @JsonProperty("audit") public void setAudit(Audit audit) { this.audit = audit; } @JsonProperty("headers") public Map<String, String> getHeaders() { return headers; } @JsonProperty("headers") public void setHeaders(Map<String, String> headers) { this.headers = headers; } @JsonProperty("customerId") public String getCustomerId() { return customerId; } @JsonProperty("customerId") public void setCustomerId(String customerId) { this.customerId = customerId; } public MorfeusWebhookResponse(List<AbstractMessage> messages, String render, String keyboardState, Status status, List<String> expectedEntities, Map<String, Object> extraData, Audit audit, Map<String, String> headers, String customerId) { this.messages = messages; this.render = render; this.keyboardState = keyboardState; this.status = status; this.expectedEntities = expectedEntities; this.extraData = extraData; this.audit = audit; this.headers = headers; this.customerId = customerId; } public MorfeusWebhookResponse() { } @Override public String toString() { return new ToStringBuilder(this).append("messages", messages).append("render", render).append("keyboardState", keyboardState) .append("status", status).append("expectedEntities", expectedEntities).append("extraData", extraData).append("audit", audit) .append("customerId", customerId).toString(); } }
0
java-sources/ai/active/webhook-sdk/1.0.7/ai/active/fulfillment/webhook/data
java-sources/ai/active/webhook-sdk/1.0.7/ai/active/fulfillment/webhook/data/response/QuickReply.java
/* * (C) Copyright 2019 Active Intelligence Pte Ltd (http://active.ai/). * * 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. */ package ai.active.fulfillment.webhook.data.response; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonPropertyOrder; import org.apache.commons.lang3.builder.ToStringBuilder; import java.io.Serializable; @JsonInclude(JsonInclude.Include.NON_NULL) @JsonPropertyOrder({"type", "title", "payload", "image_url"}) public class QuickReply implements Serializable { private static final long serialVersionUID = 5270925252792966501L; @JsonProperty("type") private String type; @JsonProperty("title") private String title; @JsonProperty("payload") private String payload; @JsonProperty("image_url") private String imageUrl; @JsonProperty("type") public String getType() { return type; } @JsonProperty("type") public void setType(String type) { this.type = type; } @JsonProperty("title") public String getTitle() { return title; } @JsonProperty("title") public void setTitle(String title) { this.title = title; } @JsonProperty("payload") public String getPayload() { return payload; } @JsonProperty("payload") public void setPayload(String payload) { this.payload = payload; } @JsonProperty("image_url") public String getImageUrl() { return imageUrl; } @JsonProperty("image_url") public void setImageUrl(String imageUrl) { this.imageUrl = imageUrl; } @Override public String toString() { return new ToStringBuilder(this).append("type", type).append("title", title).append("payload", payload).append("imageUrl", imageUrl) .toString(); } }
0
java-sources/ai/active/webhook-sdk/1.0.7/ai/active/fulfillment/webhook/data
java-sources/ai/active/webhook-sdk/1.0.7/ai/active/fulfillment/webhook/data/response/QuickReplyType.java
/* * (C) Copyright 2019 Active Intelligence Pte Ltd (http://active.ai/). * * 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. */ package ai.active.fulfillment.webhook.data.response; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonValue; import java.util.HashMap; import java.util.Map; public enum QuickReplyType { TEXT("text"), LOCATION("location"); private static final Map<String, QuickReplyType> CONSTANTS = new HashMap<>(); static { for (QuickReplyType c : values()) { CONSTANTS.put(c.value, c); } } private String value; QuickReplyType(String value) { this.value = value; } @JsonCreator public static QuickReplyType fromValue(String value) { QuickReplyType constant = CONSTANTS.get(value); if (constant == null) { throw new IllegalArgumentException(value); } else { return constant; } } @Override public String toString() { return this.value; } @JsonValue public String value() { return this.value; } }
0
java-sources/ai/active/webhook-sdk/1.0.7/ai/active/fulfillment/webhook/data
java-sources/ai/active/webhook-sdk/1.0.7/ai/active/fulfillment/webhook/data/response/RenderMethod.java
/* * (C) Copyright 2019 Active Intelligence Pte Ltd (http://active.ai/). * * 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. */ package ai.active.fulfillment.webhook.data.response; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonValue; import java.util.HashMap; import java.util.Map; public enum RenderMethod { WEBVIEW("WEBVIEW"), BOT("BOT"); private static final Map<String, RenderMethod> CONSTANTS = new HashMap<>(); static { for (RenderMethod c : values()) { CONSTANTS.put(c.value, c); } } private String value; RenderMethod(String value) { this.value = value; } @JsonCreator public static RenderMethod fromValue(String value) { RenderMethod constant = CONSTANTS.get(value); if (constant == null) { throw new IllegalArgumentException(value); } else { return constant; } } @Override public String toString() { return this.value; } @JsonValue public String value() { return this.value; } }
0
java-sources/ai/active/webhook-sdk/1.0.7/ai/active/fulfillment/webhook/data
java-sources/ai/active/webhook-sdk/1.0.7/ai/active/fulfillment/webhook/data/response/Status.java
/* * (C) Copyright 2019 Active Intelligence Pte Ltd (http://active.ai/). * * 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. */ package ai.active.fulfillment.webhook.data.response; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonValue; import java.util.HashMap; import java.util.Map; public enum Status { SUCCESS("success"), FAILED("error"), TFA_PENDING("2faPending"), TFA_SUCCESS("2faSuccess"), TFA_FAILURE("2faFailure"), PENDING( "pending"), LOGIN_PENDING("loginPending"); private static final Map<String, Status> CONSTANTS = new HashMap<>(); static { for (Status c : values()) { CONSTANTS.put(c.value, c); } } private String value; Status(String value) { this.value = value; } @JsonCreator public static Status fromValue(String value) { Status constant = CONSTANTS.get(value); if (constant == null) { throw new IllegalArgumentException(value); } else { return constant; } } @Override public String toString() { return this.value; } @JsonValue public String value() { return this.value; } }
0
java-sources/ai/active/webhook-sdk/1.0.7/ai/active/fulfillment/webhook/data
java-sources/ai/active/webhook-sdk/1.0.7/ai/active/fulfillment/webhook/data/response/TextMessage.java
package ai.active.fulfillment.webhook.data.response; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; @JsonInclude(JsonInclude.Include.NON_NULL) public class TextMessage extends AbstractMessage { private static final long serialVersionUID = -319802185150685079L; protected static final String TYPE = "text"; @JsonProperty("content") private String content; @JsonProperty("content") public String getContent() { return content; } @JsonProperty("content") public void setContent(String content) { this.content = content; } }
0
java-sources/ai/active/webhook-sdk/1.0.7/ai/active/fulfillment/webhook/data
java-sources/ai/active/webhook-sdk/1.0.7/ai/active/fulfillment/webhook/data/response/VideoMessage.java
/* * (C) Copyright 2019 Active Intelligence Pte Ltd (http://active.ai/). * * 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. */ package ai.active.fulfillment.webhook.data.response; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; import java.io.Serializable; @JsonInclude(JsonInclude.Include.NON_NULL) public class VideoMessage extends AbstractMessage implements Serializable { private static final long serialVersionUID = 8606241681808842990L; protected static final String TYPE = "video"; @JsonProperty("content") private Content content; @JsonProperty("content") public Content getContent() { return content; } @JsonProperty("content") public void setContent(Content content) { this.content = content; } }
0
java-sources/ai/active/webhook-sdk/1.0.7/ai/active/fulfillment/webhook/data
java-sources/ai/active/webhook-sdk/1.0.7/ai/active/fulfillment/webhook/data/response/WebviewType.java
/* * (C) Copyright 2019 Active Intelligence Pte Ltd (http://active.ai/). * * 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. */ package ai.active.fulfillment.webhook.data.response; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonValue; import java.util.HashMap; import java.util.Map; public enum WebviewType { COMPACT("COMPACT"), TALL("TALL"), FULL("FULL"); private static final Map<String, WebviewType> CONSTANTS = new HashMap<>(); static { for (WebviewType c : values()) { CONSTANTS.put(c.value, c); } } private String value; WebviewType(String value) { this.value = value; } @JsonCreator public static WebviewType fromValue(String value) { WebviewType constant = CONSTANTS.get(value); if (constant == null) { throw new IllegalArgumentException(value); } else { return constant; } } @Override public String toString() { return this.value; } @JsonValue public String value() { return this.value; } }
0
java-sources/ai/active/webhook-sdk/1.0.7/ai/active/fulfillment/webhook/data
java-sources/ai/active/webhook-sdk/1.0.7/ai/active/fulfillment/webhook/data/response/WorkflowPipelineResponse.java
/* * (C) Copyright 2019 Active Intelligence Pte Ltd (http://active.ai/). * * 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. */ package ai.active.fulfillment.webhook.data.response; import com.fasterxml.jackson.annotation.JsonProperty; import org.apache.commons.lang3.builder.ToStringBuilder; import java.util.List; import java.util.Map; /** * @author Pranay Kh. */ public class WorkflowPipelineResponse extends MorfeusWebhookResponse { private static final long serialVersionUID = -195167304507467429L; @JsonProperty("workflow_variables") private Map<String, String> workflowVariables; @JsonProperty("global_variables") private Map<String, String> globalVariables; @JsonProperty("workflow_variables") public Map<String, String> getWorkflowVariables() { return workflowVariables; } @JsonProperty("workflow_variables") public void setWorkflowVariables(Map<String, String> workflowVariables) { this.workflowVariables = workflowVariables; } @JsonProperty("global_variables") public Map<String, String> getGlobalVariables() { return globalVariables; } @JsonProperty("global_variables") public void setGlobalVariables(Map<String, String> globalVariables) { this.globalVariables = globalVariables; } @Override public String toString() { return new ToStringBuilder(this).append("messages", getMessages()).append("render", getRender()).append("keyboardState", getKeyboardState()) .append("status", getStatus()).append("expectedEntities", getExpectedEntities()).append("workflow_variables", workflowVariables) .append("global_variables", globalVariables).toString(); } public static class Builder { private List<AbstractMessage> messages; private String render; private String keyboardState; private Status status; private List<String> expectedEntities; private Map<String, String> workflowVariables; private Map<String, String> globalVariables; public Builder setMessages(List<AbstractMessage> messages) { this.messages = messages; return this; } public Builder setRender(String render) { this.render = render; return this; } public Builder setKeyboardState(String keyboardState) { this.keyboardState = keyboardState; return this; } public Builder setStatus(Status status) { this.status = status; return this; } public Builder setExpectedEntities(List<String> expectedEntities) { this.expectedEntities = expectedEntities; return this; } public Builder setWorkflowVariables(Map<String, String> workflowVariables) { this.workflowVariables = workflowVariables; return this; } public Builder setGlobalVariables(Map<String, String> globalVariables) { this.globalVariables = globalVariables; return this; } public WorkflowPipelineResponse build() { WorkflowPipelineResponse workflowPipelineResponse = new WorkflowPipelineResponse(); workflowPipelineResponse.setMessages(messages); workflowPipelineResponse.setRender(render); workflowPipelineResponse.setKeyboardState(keyboardState); workflowPipelineResponse.setStatus(status); workflowPipelineResponse.setExpectedEntities(expectedEntities); workflowPipelineResponse.setWorkflowVariables(workflowVariables); workflowPipelineResponse.setGlobalVariables(globalVariables); return workflowPipelineResponse; } public Builder(List<AbstractMessage> messages, String render, String keyboardState, Status status, List<String> expectedEntities , Map<String, String> workflowVariables, Map<String, String> globalVariables) { this(messages, status, expectedEntities, workflowVariables, globalVariables); this.render = render; this.keyboardState = keyboardState; } public Builder(List<AbstractMessage> messages, Status status, List<String> expectedEntities, Map<String, String> workflowVariables, Map<String, String> globalVariables) { this(messages, status); this.expectedEntities =expectedEntities; this.workflowVariables = workflowVariables; this.globalVariables = globalVariables; } public Builder(List<AbstractMessage> messages, Status status, List<String> expectedEntities) { this(messages,status); this.expectedEntities = expectedEntities; } public Builder(List<AbstractMessage> messages, Status status) { this(status); this.messages = messages; } public Builder(Status status) { this.status = status; } } private WorkflowPipelineResponse() { } }
0
java-sources/ai/active/webhook-sdk/1.0.7/ai/active/fulfillment/webhook/data
java-sources/ai/active/webhook-sdk/1.0.7/ai/active/fulfillment/webhook/data/response/WorkflowScriptResponse.java
/* * (C) Copyright 2019 Active Intelligence Pte Ltd (http://active.ai/). * * 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. */ package ai.active.fulfillment.webhook.data.response; import com.fasterxml.jackson.annotation.JsonProperty; import org.apache.commons.lang3.builder.ToStringBuilder; import java.util.List; import java.util.Map; /** * @author Pranay Kh. */ public class WorkflowScriptResponse extends MorfeusWebhookResponse { private static final long serialVersionUID = -2349927267160877254L; @JsonProperty("goto") private String goTo; @JsonProperty("gotoType") private GotoType gotoType; @JsonProperty("gotoLinkedType") private GotoLinkedType gotoLinkedType; @JsonProperty("workflow_variables") private Map<String, String> workflowVariables; @JsonProperty("global_variables") private Map<String, String> globalVariables; @JsonProperty("goto") public String getGoTo() { return goTo; } @JsonProperty("goto") public void setGoTo(String goTo) { this.goTo = goTo; } @JsonProperty("gotoType") public GotoType getGotoType() { return gotoType; } @JsonProperty("gotoType") public void setGotoType(GotoType gotoType) { this.gotoType = gotoType; } @JsonProperty("gotoLinkedType") public GotoLinkedType getGotoLinkedType() { return gotoLinkedType; } @JsonProperty("gotoLinkedType") public void setGotoLinkedType(GotoLinkedType gotoLinkedType) { this.gotoLinkedType = gotoLinkedType; } @JsonProperty("workflow_variables") public Map<String, String> getWorkflowVariables() { return workflowVariables; } @JsonProperty("workflow_variables") public void setWorkflowVariables(Map<String, String> workflowVariables) { this.workflowVariables = workflowVariables; } @JsonProperty("global_variables") public Map<String, String> getGlobalVariables() { return globalVariables; } @JsonProperty("global_variables") public void setGlobalVariables(Map<String, String> globalVariables) { this.globalVariables = globalVariables; } @Override public String toString() { return new ToStringBuilder(this).append("messages", getMessages()).append("render", getRender()).append("keyboardState", getKeyboardState()) .append("status", getStatus()).append("expectedEntities", getExpectedEntities()).append("goto", goTo).append("gotoType", gotoType) .append("gotoLinkedType", gotoLinkedType).append("workflow_variables", workflowVariables) .append("global_variables", globalVariables).toString(); } public static class Builder { private List<AbstractMessage> messages; private String render; private String keyboardState; private Status status; private List<String> expectedEntities; private GotoType gotoType; private GotoLinkedType gotoLinkedType; private String goTo; private Map<String, String> workflowVariables; private Map<String, String> globalVariables; public Builder setMessages(List<AbstractMessage> messages) { this.messages = messages; return this; } public Builder setRender(String render) { this.render = render; return this; } public Builder setKeyboardState(String keyboardState) { this.keyboardState = keyboardState; return this; } public Builder setStatus(Status status) { this.status = status; return this; } public Builder setExpectedEntities(List<String> expectedEntities) { this.expectedEntities = expectedEntities; return this; } public Builder setGotoType(GotoType gotoType) { this.gotoType = gotoType; return this; } public Builder setGotoLinkedType(GotoLinkedType gotoLinkedType) { this.gotoLinkedType = gotoLinkedType; return this; } public Builder setGoTo(String goTo) { this.goTo = goTo; return this; } public Builder setWorkflowVariables(Map<String, String> workflowVariables) { this.workflowVariables = workflowVariables; return this; } public Builder setGlobalVariables(Map<String, String> globalVariables) { this.globalVariables = globalVariables; return this; } public WorkflowScriptResponse build() { WorkflowScriptResponse workflowScriptResponse = new WorkflowScriptResponse(); workflowScriptResponse.setMessages(messages); workflowScriptResponse.setRender(render); workflowScriptResponse.setKeyboardState(keyboardState); workflowScriptResponse.setStatus(status); workflowScriptResponse.setExpectedEntities(expectedEntities); workflowScriptResponse.setGotoType(gotoType); workflowScriptResponse.setGoTo(goTo); workflowScriptResponse.setGotoLinkedType(gotoLinkedType); return workflowScriptResponse; } public Builder(List<AbstractMessage> messages, String render, String keyboardState, Status status, List<String> expectedEntities , String goTo, GotoType gotoType, GotoLinkedType gotoLinkedType, Map<String, String> workflowVariables, Map<String, String> globalVariables) { this(messages, status); this.render = render; this.keyboardState = keyboardState; this.expectedEntities = expectedEntities; this.goTo = goTo; this.gotoType = gotoType; this.gotoLinkedType = gotoLinkedType; this.workflowVariables = workflowVariables; this.globalVariables = globalVariables; } public Builder(Status status, String goTo, GotoType gotoType, GotoLinkedType gotoLinkedType, Map<String, String> workflowVariables, Map<String, String> globalVariables) { this(status, goTo, gotoType, gotoLinkedType); this.workflowVariables = workflowVariables; this.globalVariables = globalVariables; } public Builder(Status status, String goTo, GotoType gotoType, GotoLinkedType gotoLinkedType) { this(status, goTo, gotoType); this.gotoLinkedType = gotoLinkedType; } public Builder(Status status, String goTo, GotoType gotoType) { this(status); this.goTo = goTo; this.gotoType = gotoType; } public Builder(List<AbstractMessage> messages, Status status, List<String> expectedEntities) { this(messages,status); this.expectedEntities = expectedEntities; } public Builder(List<AbstractMessage> messages, Status status) { this(status); this.messages = messages; } public Builder(Status status) { this.status = status; } } private WorkflowScriptResponse() { } }
0
java-sources/ai/active/webhook-sdk/1.0.7/ai/active/fulfillment/webhook/data
java-sources/ai/active/webhook-sdk/1.0.7/ai/active/fulfillment/webhook/data/response/WorkflowValidationResponse.java
/* * (C) Copyright 2019 Active Intelligence Pte Ltd (http://active.ai/). * * 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. */ package ai.active.fulfillment.webhook.data.response; import com.fasterxml.jackson.annotation.JsonProperty; import org.apache.commons.lang3.builder.ToStringBuilder; import java.util.List; import java.util.Map; /** * @author Pranay Kh. */ public class WorkflowValidationResponse extends MorfeusWebhookResponse { private static final long serialVersionUID = -6636756897538918825L; @JsonProperty("workflow_variables") private Map<String, String> workflowVariables; @JsonProperty("global_variables") private Map<String, String> globalVariables; @JsonProperty("workflow_variables") public Map<String, String> getWorkflowVariables() { return workflowVariables; } @JsonProperty("workflow_variables") public void setWorkflowVariables(Map<String, String> workflowVariables) { this.workflowVariables = workflowVariables; } @JsonProperty("global_variables") public Map<String, String> getGlobalVariables() { return globalVariables; } @JsonProperty("global_variables") public void setGlobalVariables(Map<String, String> globalVariables) { this.globalVariables = globalVariables; } @Override public String toString() { return new ToStringBuilder(this).append("messages", getMessages()).append("render", getRender()).append("keyboardState", getKeyboardState()) .append("status", getStatus()).append("expectedEntities", getExpectedEntities()).append("workflow_variables", workflowVariables) .append("global_variables", globalVariables).toString(); } public static class Builder { private List<AbstractMessage> messages; private String render; private String keyboardState; private Status status; private List<String> expectedEntities; private Map<String, String> workflowVariables; private Map<String, String> globalVariables; public Builder setMessages(List<AbstractMessage> messages) { this.messages = messages; return this; } public Builder setRender(String render) { this.render = render; return this; } public Builder setKeyboardState(String keyboardState) { this.keyboardState = keyboardState; return this; } public Builder setStatus(Status status) { this.status = status; return this; } public Builder setExpectedEntities(List<String> expectedEntities) { this.expectedEntities = expectedEntities; return this; } public Builder setWorkflowVariables(Map<String, String> workflowVariables) { this.workflowVariables = workflowVariables; return this; } public Builder setGlobalVariables(Map<String, String> globalVariables) { this.globalVariables = globalVariables; return this; } public WorkflowValidationResponse build() { WorkflowValidationResponse workflowValidationResponse = new WorkflowValidationResponse(); workflowValidationResponse.setMessages(messages); workflowValidationResponse.setRender(render); workflowValidationResponse.setKeyboardState(keyboardState); workflowValidationResponse.setStatus(status); workflowValidationResponse.setExpectedEntities(expectedEntities); workflowValidationResponse.setWorkflowVariables(workflowVariables); workflowValidationResponse.setGlobalVariables(globalVariables); return workflowValidationResponse; } public Builder(List<AbstractMessage> messages, String render, String keyboardState, Status status, List<String> expectedEntities , Map<String, String> workflowVariables, Map<String, String> globalVariables) { this(messages, status, expectedEntities, workflowVariables, globalVariables); this.render = render; this.keyboardState = keyboardState; } public Builder(List<AbstractMessage> messages, Status status, List<String> expectedEntities, Map<String, String> workflowVariables, Map<String, String> globalVariables) { this(messages, status); this.expectedEntities = expectedEntities; this.workflowVariables = workflowVariables; this.globalVariables = globalVariables; } public Builder(List<AbstractMessage> messages, Status status, List<String> expectedEntities) { this(messages,status); this.expectedEntities = expectedEntities; } public Builder(List<AbstractMessage> messages, Status status) { this(status); this.messages = messages; } public Builder(Status status) { this.status = status; } } private WorkflowValidationResponse() { } }
0
java-sources/ai/agentscentral/agentj-anthropic/0.0.5/ai/agentscentral/anthropic
java-sources/ai/agentscentral/agentj-anthropic/0.0.5/ai/agentscentral/anthropic/client/AnthropicClient.java
package ai.agentscentral.anthropic.client; import ai.agentscentral.anthropic.client.request.MessagesRequest; import ai.agentscentral.anthropic.client.response.MessagesResponse; import ai.agentscentral.anthropic.config.AnthropicConfig; import ai.agentscentral.core.model.ProviderClient; import org.apache.hc.client5.http.HttpResponseException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import static ai.agentscentral.anthropic.client.Jsonify.asJson; import static org.apache.hc.client5.http.fluent.Request.post; import static org.apache.hc.core5.http.ContentType.APPLICATION_JSON; import static org.apache.hc.core5.http.HttpHeaders.CONTENT_TYPE; /** * AnthropicClient * * @author Rizwan Idrees */ public class AnthropicClient implements ProviderClient { private static final Logger logger = LoggerFactory.getLogger(AnthropicClient.class); public static final String HEADER_ANTHROPIC_VERSION = "anthropic-version"; public static final String HEADER_X_API_KEY = "x-api-key"; private final String url; private final String apiKey; private final String anthropicVersion; public AnthropicClient(AnthropicConfig config) { this(config.getUrl(), config.getApiKey(), config.getAnthropicVersion()); } public AnthropicClient(String url, String apiKey, String anthropicVersion) { this.url = url; this.apiKey = apiKey; this.anthropicVersion = anthropicVersion; } public MessagesResponse sendMessages(MessagesRequest request) { try { final String responseAsString = post(url) .addHeader(HEADER_X_API_KEY, apiKey) .addHeader(HEADER_ANTHROPIC_VERSION, anthropicVersion) .addHeader(CONTENT_TYPE, APPLICATION_JSON.getMimeType()) .bodyString(asJson(request), APPLICATION_JSON) .execute().returnContent().asString(); return Jsonify.asObject(responseAsString, MessagesResponse.class); } catch (HttpResponseException e) { logger.error("Http error while processing. error {} content {}", e.getMessage(), new String(e.getContentBytes()), e); throw new RuntimeException(e); } catch (IOException ioe) { throw new RuntimeException(ioe); } } }
0
java-sources/ai/agentscentral/agentj-anthropic/0.0.5/ai/agentscentral/anthropic
java-sources/ai/agentscentral/agentj-anthropic/0.0.5/ai/agentscentral/anthropic/client/Jsonify.java
package ai.agentscentral.anthropic.client; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; /** * Jsonify * * @author Rizwan Idrees */ class Jsonify { private static final ObjectMapper mapper = new ObjectMapper() {{ setSerializationInclusion(JsonInclude.Include.NON_NULL); }}; private Jsonify() { } static String asJson(Object o) throws JsonProcessingException { return mapper.writeValueAsString(o); } static <T> T asObject(String stringValue, Class<T> clazz) throws JsonProcessingException { return mapper.readValue(stringValue, clazz); } }
0
java-sources/ai/agentscentral/agentj-anthropic/0.0.5/ai/agentscentral/anthropic/client
java-sources/ai/agentscentral/agentj-anthropic/0.0.5/ai/agentscentral/anthropic/client/common/Role.java
package ai.agentscentral.anthropic.client.common; /** * Role * * @author Rizwan Idrees */ public enum Role { assistant }
0
java-sources/ai/agentscentral/agentj-anthropic/0.0.5/ai/agentscentral/anthropic/client
java-sources/ai/agentscentral/agentj-anthropic/0.0.5/ai/agentscentral/anthropic/client/request/MessagesRequest.java
package ai.agentscentral.anthropic.client.request; import ai.agentscentral.anthropic.client.request.attributes.AnthropicMessage; import ai.agentscentral.anthropic.client.request.attributes.AnthropicTool; import ai.agentscentral.anthropic.client.request.attributes.ServiceTier; import ai.agentscentral.anthropic.client.request.attributes.SystemPrompt; import ai.agentscentral.anthropic.client.response.attributes.MetaData; import ai.agentscentral.anthropic.config.AnthropicConfig; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonUnwrapped; import java.util.List; import java.util.Set; import static java.util.Optional.ofNullable; /** * MessagesRequest * * @param model * @param messages * @param maxTokens * @param metaData * @param serviceTier * @param stopSequences * @param stream * @param system * @param temperature * @param tools * @param topK * @param topP * @author Rizwan Idrees */ public record MessagesRequest(String model, List<AnthropicMessage> messages, @JsonProperty("max_tokens") Integer maxTokens, @JsonProperty("metadata") MetaData metaData, @JsonProperty("service_tier") ServiceTier serviceTier, @JsonProperty("stop_sequences") Set<String> stopSequences, boolean stream, @JsonUnwrapped SystemPrompt system, Double temperature, List<AnthropicTool> tools, @JsonProperty("top_k") Integer topK, @JsonProperty("top_p") Double topP) { public static MessagesRequest from(String model, AnthropicConfig config, SystemPrompt system, String userId, List<AnthropicTool> tools, List<AnthropicMessage> messages) { return new MessagesRequest(model, messages, config.getMaxTokens(), ofNullable(userId).map(MetaData::new).orElse(null), config.getServiceTier(), config.getStopSequences(), config.isStream(), system, config.getTemperature(), tools, config.getTopK(), config.getTopP() ); } }
0
java-sources/ai/agentscentral/agentj-anthropic/0.0.5/ai/agentscentral/anthropic/client/request
java-sources/ai/agentscentral/agentj-anthropic/0.0.5/ai/agentscentral/anthropic/client/request/attributes/AnthropicAssistantMessage.java
package ai.agentscentral.anthropic.client.request.attributes; import com.fasterxml.jackson.annotation.JsonUnwrapped; public record AnthropicAssistantMessage(String role, @JsonUnwrapped MessageContent content) implements AnthropicMessage { public static final String ASSISTANT = "assistant"; public String role() { return ASSISTANT; } }
0
java-sources/ai/agentscentral/agentj-anthropic/0.0.5/ai/agentscentral/anthropic/client/request
java-sources/ai/agentscentral/agentj-anthropic/0.0.5/ai/agentscentral/anthropic/client/request/attributes/AnthropicMessage.java
package ai.agentscentral.anthropic.client.request.attributes; /** * AnthropicMessage * * @author Rizwan Idrees */ public interface AnthropicMessage { String role(); }
0
java-sources/ai/agentscentral/agentj-anthropic/0.0.5/ai/agentscentral/anthropic/client/request
java-sources/ai/agentscentral/agentj-anthropic/0.0.5/ai/agentscentral/anthropic/client/request/attributes/AnthropicTool.java
package ai.agentscentral.anthropic.client.request.attributes; import com.fasterxml.jackson.annotation.JsonProperty; /** * AnthropicTool * * @param name * @param description * @author Rizwan Idrees */ public record AnthropicTool(String name, String description, String type, @JsonProperty("input_schema") InputSchema inputSchema) { }
0
java-sources/ai/agentscentral/agentj-anthropic/0.0.5/ai/agentscentral/anthropic/client/request
java-sources/ai/agentscentral/agentj-anthropic/0.0.5/ai/agentscentral/anthropic/client/request/attributes/AnthropicUserMessage.java
package ai.agentscentral.anthropic.client.request.attributes; import com.fasterxml.jackson.annotation.JsonUnwrapped; /** * AnthropicUserMessage * * @param role * @param content * @author Rizwan Idrees */ public record AnthropicUserMessage(String role, @JsonUnwrapped MessageContent content) implements AnthropicMessage { public static final String USER = "user"; public String role() { return USER; } }
0
java-sources/ai/agentscentral/agentj-anthropic/0.0.5/ai/agentscentral/anthropic/client/request
java-sources/ai/agentscentral/agentj-anthropic/0.0.5/ai/agentscentral/anthropic/client/request/attributes/ContentPart.java
package ai.agentscentral.anthropic.client.request.attributes; /** * ContentPart * * @author Rizwan Idrees */ public interface ContentPart { String type(); }
0
java-sources/ai/agentscentral/agentj-anthropic/0.0.5/ai/agentscentral/anthropic/client/request
java-sources/ai/agentscentral/agentj-anthropic/0.0.5/ai/agentscentral/anthropic/client/request/attributes/EnumSchemaProperty.java
package ai.agentscentral.anthropic.client.request.attributes; /** * EnumFunctionProperty * * @param type * @param enums * @author Rizwan Idrees */ public record EnumSchemaProperty(String type, String[] enums) implements SchemaProperty { }
0
java-sources/ai/agentscentral/agentj-anthropic/0.0.5/ai/agentscentral/anthropic/client/request
java-sources/ai/agentscentral/agentj-anthropic/0.0.5/ai/agentscentral/anthropic/client/request/attributes/InputSchema.java
package ai.agentscentral.anthropic.client.request.attributes; import java.util.Map; import java.util.Set; /** * InputSchema * * @param type * @param properties * @param required * @author Rizwan Idrees */ public record InputSchema(String type, Map<String, ? extends SchemaProperty> properties, Set<String> required) { }
0
java-sources/ai/agentscentral/agentj-anthropic/0.0.5/ai/agentscentral/anthropic/client/request
java-sources/ai/agentscentral/agentj-anthropic/0.0.5/ai/agentscentral/anthropic/client/request/attributes/MessageContent.java
package ai.agentscentral.anthropic.client.request.attributes; /** * MessageContent * * @author Rizwan Idrees */ public interface MessageContent { }
0
java-sources/ai/agentscentral/agentj-anthropic/0.0.5/ai/agentscentral/anthropic/client/request
java-sources/ai/agentscentral/agentj-anthropic/0.0.5/ai/agentscentral/anthropic/client/request/attributes/MessageContentParts.java
package ai.agentscentral.anthropic.client.request.attributes; import java.util.List; /** * TextContents * * @param content * @author Rizwan Idrees */ public record MessageContentParts(List<? extends ContentPart> content) implements MessageContent { }
0
java-sources/ai/agentscentral/agentj-anthropic/0.0.5/ai/agentscentral/anthropic/client/request
java-sources/ai/agentscentral/agentj-anthropic/0.0.5/ai/agentscentral/anthropic/client/request/attributes/SchemaProperty.java
package ai.agentscentral.anthropic.client.request.attributes; /** * SchemaProperty * * @author Rizwan Idrees */ public interface SchemaProperty { }
0
java-sources/ai/agentscentral/agentj-anthropic/0.0.5/ai/agentscentral/anthropic/client/request
java-sources/ai/agentscentral/agentj-anthropic/0.0.5/ai/agentscentral/anthropic/client/request/attributes/ServiceTier.java
package ai.agentscentral.anthropic.client.request.attributes; /** * ServiceTier * * @author Rizwan Idrees */ public enum ServiceTier { auto, standard_only }
0
java-sources/ai/agentscentral/agentj-anthropic/0.0.5/ai/agentscentral/anthropic/client/request
java-sources/ai/agentscentral/agentj-anthropic/0.0.5/ai/agentscentral/anthropic/client/request/attributes/SystemPrompt.java
package ai.agentscentral.anthropic.client.request.attributes; /** * SystemPrompt * * @author Rizwan Idrees */ public interface SystemPrompt { }
0
java-sources/ai/agentscentral/agentj-anthropic/0.0.5/ai/agentscentral/anthropic/client/request
java-sources/ai/agentscentral/agentj-anthropic/0.0.5/ai/agentscentral/anthropic/client/request/attributes/SystemPrompts.java
package ai.agentscentral.anthropic.client.request.attributes; import java.util.List; /** * TextPrompt * * @author Rizwan Idrees */ public record SystemPrompts(List<TextPrompt> system) implements SystemPrompt { }
0
java-sources/ai/agentscentral/agentj-anthropic/0.0.5/ai/agentscentral/anthropic/client/request
java-sources/ai/agentscentral/agentj-anthropic/0.0.5/ai/agentscentral/anthropic/client/request/attributes/TextContent.java
package ai.agentscentral.anthropic.client.request.attributes; /** * TextContent * * @param content * @author Rizwan Idrees */ public record TextContent(String content) implements MessageContent { }
0
java-sources/ai/agentscentral/agentj-anthropic/0.0.5/ai/agentscentral/anthropic/client/request
java-sources/ai/agentscentral/agentj-anthropic/0.0.5/ai/agentscentral/anthropic/client/request/attributes/TextContentPart.java
package ai.agentscentral.anthropic.client.request.attributes; /** * TextContentPart * * @param type * @param text * @author Rizwan Idrees */ public record TextContentPart(String type, String text) implements ContentPart { public static final String TEXT = "text"; public String type() { return TEXT; } }
0
java-sources/ai/agentscentral/agentj-anthropic/0.0.5/ai/agentscentral/anthropic/client/request
java-sources/ai/agentscentral/agentj-anthropic/0.0.5/ai/agentscentral/anthropic/client/request/attributes/TextPrompt.java
package ai.agentscentral.anthropic.client.request.attributes; /** * TextPrompt * * @param type * @param text * @author Rizwan Idrees */ public record TextPrompt(String type, String text) { public static final String TYPE = "text"; public String type() { return TYPE; } }
0
java-sources/ai/agentscentral/agentj-anthropic/0.0.5/ai/agentscentral/anthropic/client/request
java-sources/ai/agentscentral/agentj-anthropic/0.0.5/ai/agentscentral/anthropic/client/request/attributes/TextSystemPrompt.java
package ai.agentscentral.anthropic.client.request.attributes; /** * TextPrompt * * @author Rizwan Idrees */ public record TextSystemPrompt(String system) implements SystemPrompt { }
0
java-sources/ai/agentscentral/agentj-anthropic/0.0.5/ai/agentscentral/anthropic/client/request
java-sources/ai/agentscentral/agentj-anthropic/0.0.5/ai/agentscentral/anthropic/client/request/attributes/ToolResultContentPart.java
package ai.agentscentral.anthropic.client.request.attributes; import com.fasterxml.jackson.annotation.JsonProperty; public record ToolResultContentPart(String type, @JsonProperty("tool_use_id") String toolUseId, String content) implements ContentPart { public static String TOOL_RESULT = "tool_result"; public String type() { return TOOL_RESULT; } }
0
java-sources/ai/agentscentral/agentj-anthropic/0.0.5/ai/agentscentral/anthropic/client/request
java-sources/ai/agentscentral/agentj-anthropic/0.0.5/ai/agentscentral/anthropic/client/request/attributes/TypedSchemaProperty.java
package ai.agentscentral.anthropic.client.request.attributes; /** * TypedFunctionProperty * * @param type * @param description * @author Rizwan Idrees */ public record TypedSchemaProperty(String type, String description) implements SchemaProperty { }
0
java-sources/ai/agentscentral/agentj-anthropic/0.0.5/ai/agentscentral/anthropic/client
java-sources/ai/agentscentral/agentj-anthropic/0.0.5/ai/agentscentral/anthropic/client/response/MessagesResponse.java
package ai.agentscentral.anthropic.client.response; import ai.agentscentral.anthropic.client.common.Role; import ai.agentscentral.anthropic.client.response.attributes.*; import com.fasterxml.jackson.annotation.JsonProperty; import java.util.List; /** * MessagesResponse * * @param id * @param type * @param role * @param content * @param model * @param stopReason * @param stopSequence * @param container * @param usage * @author Rizwan Idrees */ public record MessagesResponse(String id, MessageResponseType type, Role role, List<ResponseContent> content, String model, @JsonProperty("stop_reason") StopReason stopReason, @JsonProperty("stop_sequence") String stopSequence, Container container, Usage usage) { public boolean hasToolCalls() { return content.stream().anyMatch(c -> c instanceof ToolUseResponseContent); } }
0
java-sources/ai/agentscentral/agentj-anthropic/0.0.5/ai/agentscentral/anthropic/client/response
java-sources/ai/agentscentral/agentj-anthropic/0.0.5/ai/agentscentral/anthropic/client/response/attributes/Container.java
package ai.agentscentral.anthropic.client.response.attributes; import com.fasterxml.jackson.annotation.JsonProperty; /** * Container * * @param id * @param expiresAt * @author Rizwan Idrees */ public record Container(String id, @JsonProperty("expires_at") String expiresAt) { }
0
java-sources/ai/agentscentral/agentj-anthropic/0.0.5/ai/agentscentral/anthropic/client/response
java-sources/ai/agentscentral/agentj-anthropic/0.0.5/ai/agentscentral/anthropic/client/response/attributes/MessageResponseType.java
package ai.agentscentral.anthropic.client.response.attributes; /** * MessageResponseType * * @author Rizwan Idrees */ public enum MessageResponseType { message }
0
java-sources/ai/agentscentral/agentj-anthropic/0.0.5/ai/agentscentral/anthropic/client/response
java-sources/ai/agentscentral/agentj-anthropic/0.0.5/ai/agentscentral/anthropic/client/response/attributes/MetaData.java
package ai.agentscentral.anthropic.client.response.attributes; import com.fasterxml.jackson.annotation.JsonProperty; public record MetaData(@JsonProperty("user_id") String userId) { }
0
java-sources/ai/agentscentral/agentj-anthropic/0.0.5/ai/agentscentral/anthropic/client/response
java-sources/ai/agentscentral/agentj-anthropic/0.0.5/ai/agentscentral/anthropic/client/response/attributes/RedactedThinkingResponseContent.java
package ai.agentscentral.anthropic.client.response.attributes; /** * RedactedThinkingResponseContent * * @param type * @param data * @author Rizwan Idrees */ public record RedactedThinkingResponseContent(ResponseContentType type, String data) implements ResponseContent { }
0
java-sources/ai/agentscentral/agentj-anthropic/0.0.5/ai/agentscentral/anthropic/client/response
java-sources/ai/agentscentral/agentj-anthropic/0.0.5/ai/agentscentral/anthropic/client/response/attributes/ResponseContent.java
package ai.agentscentral.anthropic.client.response.attributes; import com.fasterxml.jackson.annotation.JsonSubTypes; import com.fasterxml.jackson.annotation.JsonTypeInfo; /** * ResponseContent * @author Rizwan Idrees */ @JsonTypeInfo(use = JsonTypeInfo.Id.NAME, property = "type", visible = true) @JsonSubTypes({ @JsonSubTypes.Type(value = TextResponseContent.class, name = "text"), @JsonSubTypes.Type(value = ThinkingResponseContent.class, name = "thinking"), @JsonSubTypes.Type(value = RedactedThinkingResponseContent.class, name = "redacted_thinking"), @JsonSubTypes.Type(value = ToolUseResponseContent.class, name = "tool_use"), @JsonSubTypes.Type(value = ServerToolUseResponseContent.class, name = "server_tool_use"), @JsonSubTypes.Type(value = ServerToolUseResponseContent.class, name = "web_search_tool_result") }) public interface ResponseContent { ResponseContentType type(); }
0
java-sources/ai/agentscentral/agentj-anthropic/0.0.5/ai/agentscentral/anthropic/client/response
java-sources/ai/agentscentral/agentj-anthropic/0.0.5/ai/agentscentral/anthropic/client/response/attributes/ResponseContentType.java
package ai.agentscentral.anthropic.client.response.attributes; /** * ResponseContentType * * @author Rizwan Idrees */ public enum ResponseContentType { text, thinking, redacted_thinking, tool_use, server_tool_use, web_search_tool_result }
0
java-sources/ai/agentscentral/agentj-anthropic/0.0.5/ai/agentscentral/anthropic/client/response
java-sources/ai/agentscentral/agentj-anthropic/0.0.5/ai/agentscentral/anthropic/client/response/attributes/ServerToolUseName.java
package ai.agentscentral.anthropic.client.response.attributes; /** * ServerToolUseName * * @author Rizwan Idrees */ public enum ServerToolUseName { web_search, code_execution }
0
java-sources/ai/agentscentral/agentj-anthropic/0.0.5/ai/agentscentral/anthropic/client/response
java-sources/ai/agentscentral/agentj-anthropic/0.0.5/ai/agentscentral/anthropic/client/response/attributes/ServerToolUseResponseContent.java
package ai.agentscentral.anthropic.client.response.attributes; import java.util.Map; /** * ServerToolUseResponseContent * * @param id * @param type * @param name * @param input * @author Rizwan Idrees */ public record ServerToolUseResponseContent(String id, ResponseContentType type, ServerToolUseName name, Map<String, Object> input) implements ResponseContent { }
0
java-sources/ai/agentscentral/agentj-anthropic/0.0.5/ai/agentscentral/anthropic/client/response
java-sources/ai/agentscentral/agentj-anthropic/0.0.5/ai/agentscentral/anthropic/client/response/attributes/StopReason.java
package ai.agentscentral.anthropic.client.response.attributes; /** * StopReason * * @author Rizwan Idrees */ public enum StopReason { end_turn, max_tokens, stop_sequence, tool_use, pause_turn, refusal }
0
java-sources/ai/agentscentral/agentj-anthropic/0.0.5/ai/agentscentral/anthropic/client/response
java-sources/ai/agentscentral/agentj-anthropic/0.0.5/ai/agentscentral/anthropic/client/response/attributes/TextResponseContent.java
package ai.agentscentral.anthropic.client.response.attributes; /** * TextResponseContent * * @param type * @param text * @author Rizwan Idrees */ public record TextResponseContent(ResponseContentType type, String text) implements ResponseContent { }
0
java-sources/ai/agentscentral/agentj-anthropic/0.0.5/ai/agentscentral/anthropic/client/response
java-sources/ai/agentscentral/agentj-anthropic/0.0.5/ai/agentscentral/anthropic/client/response/attributes/ThinkingResponseContent.java
package ai.agentscentral.anthropic.client.response.attributes; /** * ThinkingResponseContent * * @param type * @param signature * @param thinking * @author Rizwan Idrees */ public record ThinkingResponseContent(ResponseContentType type, String signature, String thinking) implements ResponseContent { }
0
java-sources/ai/agentscentral/agentj-anthropic/0.0.5/ai/agentscentral/anthropic/client/response
java-sources/ai/agentscentral/agentj-anthropic/0.0.5/ai/agentscentral/anthropic/client/response/attributes/ToolUseResponseContent.java
package ai.agentscentral.anthropic.client.response.attributes; import java.util.Map; /** * ToolUseResponseContent * * @param id * @param type * @param name * @param input * @author Rizwan Idrees */ public record ToolUseResponseContent(String id, ResponseContentType type, String name, Map<String, Object> input) implements ResponseContent { }
0
java-sources/ai/agentscentral/agentj-anthropic/0.0.5/ai/agentscentral/anthropic/client/response
java-sources/ai/agentscentral/agentj-anthropic/0.0.5/ai/agentscentral/anthropic/client/response/attributes/Usage.java
package ai.agentscentral.anthropic.client.response.attributes; import com.fasterxml.jackson.annotation.JsonProperty; /** * Usage * * @param inputTokens * @param outputTokens * @param cacheCreationInputTokens * @param cacheReadInputTokens * @param cacheCreation * @param serviceTier * @author Rizwan Idrees */ public record Usage(@JsonProperty("input_tokens") Integer inputTokens, @JsonProperty("output_tokens") Integer outputTokens, @JsonProperty("cache_creation_input_tokens") Integer cacheCreationInputTokens, @JsonProperty("cache_read_input_tokens") Integer cacheReadInputTokens, @JsonProperty("cache_creation") UsageCacheCreation cacheCreation, @JsonProperty("service_tier") UsageServiceTier serviceTier) { }
0
java-sources/ai/agentscentral/agentj-anthropic/0.0.5/ai/agentscentral/anthropic/client/response
java-sources/ai/agentscentral/agentj-anthropic/0.0.5/ai/agentscentral/anthropic/client/response/attributes/UsageCacheCreation.java
package ai.agentscentral.anthropic.client.response.attributes; import com.fasterxml.jackson.annotation.JsonProperty; /** * UsageCacheCreation * * @param ephemeral1hInputTokens * @param ephemeral5mInputTokens * @author Rizwan Idrees */ public record UsageCacheCreation(@JsonProperty("ephemeral_1h_input_tokens") Integer ephemeral1hInputTokens, @JsonProperty("ephemeral_5m_input_tokens") Integer ephemeral5mInputTokens) { }
0
java-sources/ai/agentscentral/agentj-anthropic/0.0.5/ai/agentscentral/anthropic/client/response
java-sources/ai/agentscentral/agentj-anthropic/0.0.5/ai/agentscentral/anthropic/client/response/attributes/UsageServiceTier.java
package ai.agentscentral.anthropic.client.response.attributes; /** * UsageServiceTier * * @author Rizwan Idrees */ public enum UsageServiceTier { standard, priority, batch }
0
java-sources/ai/agentscentral/agentj-anthropic/0.0.5/ai/agentscentral/anthropic
java-sources/ai/agentscentral/agentj-anthropic/0.0.5/ai/agentscentral/anthropic/config/AnthropicConfig.java
package ai.agentscentral.anthropic.config; import ai.agentscentral.anthropic.client.AnthropicClient; import ai.agentscentral.anthropic.client.request.attributes.ServiceTier; import ai.agentscentral.anthropic.factory.AnthropicFactory; import ai.agentscentral.core.model.ModelConfig; import ai.agentscentral.core.model.ProviderFactory; import ai.agentscentral.core.provider.ProviderAgentExecutor; import jakarta.annotation.Nonnull; import java.util.Set; import static java.util.Optional.ofNullable; /** * AnthropicConfig * * @author Rizwan Idrees */ public class AnthropicConfig implements ModelConfig { public static final String DEFAULT_URL = "https://api.anthropic.com/v1/messages"; private AnthropicFactory factory; private String url; private String apiKey; private String anthropicVersion; private Integer maxTokens; private ServiceTier serviceTier; private Set<String> stopSequences; private boolean stream; private Double temperature = 1.0D; private Integer topK; private Double topP; public AnthropicConfig(@Nonnull String apiKey, @Nonnull String anthropicVersion, @Nonnull Integer maxTokens) { this(DEFAULT_URL, apiKey, anthropicVersion, maxTokens); } public AnthropicConfig(@Nonnull String url, @Nonnull String apiKey, @Nonnull String anthropicVersion, @Nonnull Integer maxTokens) { this.url = url; this.apiKey = apiKey; this.anthropicVersion = anthropicVersion; this.maxTokens = maxTokens; } public String getUrl() { return url; } public void setUrl(String url) { this.url = url; } public String getApiKey() { return apiKey; } public void setApiKey(String apiKey) { this.apiKey = apiKey; } public String getAnthropicVersion() { return anthropicVersion; } public void setAnthropicVersion(String anthropicVersion) { this.anthropicVersion = anthropicVersion; } public Integer getMaxTokens() { return maxTokens; } public void setMaxTokens(Integer maxTokens) { this.maxTokens = maxTokens; } public ServiceTier getServiceTier() { return serviceTier; } public void setServiceTier(ServiceTier serviceTier) { this.serviceTier = serviceTier; } public Set<String> getStopSequences() { return stopSequences; } public void setStopSequences(Set<String> stopSequences) { this.stopSequences = stopSequences; } public boolean isStream() { return stream; } public void setStream(boolean stream) { this.stream = stream; } public Double getTemperature() { return temperature; } public void setTemperature(Double temperature) { this.temperature = temperature; } public Integer getTopK() { return topK; } public void setTopK(Integer topK) { this.topK = topK; } public Double getTopP() { return topP; } public void setTopP(Double topP) { this.topP = topP; } @Override public ProviderFactory<? extends ProviderAgentExecutor> getFactory() { factory = ofNullable(factory) .orElseGet(() -> new AnthropicFactory(new AnthropicClient(url, apiKey, anthropicVersion))); return factory; } }
0
java-sources/ai/agentscentral/agentj-anthropic/0.0.5/ai/agentscentral/anthropic
java-sources/ai/agentscentral/agentj-anthropic/0.0.5/ai/agentscentral/anthropic/factory/AnthropicFactory.java
package ai.agentscentral.anthropic.factory; import ai.agentscentral.anthropic.client.AnthropicClient; import ai.agentscentral.anthropic.processor.AnthropicAgentExecutor; import ai.agentscentral.core.agent.Agent; import ai.agentscentral.core.factory.AgentJFactory; import ai.agentscentral.core.model.ProviderFactory; import jakarta.annotation.Nonnull; import java.util.Optional; /** * AnthropicFactory * * @author Rizwan Idrees */ public class AnthropicFactory implements ProviderFactory<AnthropicAgentExecutor> { private final AnthropicClient client; public AnthropicFactory(AnthropicClient client) { this.client = client; } // @Override public AnthropicAgentExecutor createAgentExecutor(@Nonnull Agent agent, @Nonnull AgentJFactory agentJFactory) { return Optional.of(agent) .map(a -> new AnthropicAgentExecutor(a, agentJFactory, client)) .orElseThrow(() -> new RuntimeException("Cannot process agent of type " + agent.getClass())); } }