index int64 0 0 | repo_id stringlengths 9 205 | file_path stringlengths 31 246 | content stringlengths 1 12.2M | __index_level_0__ int64 0 10k |
|---|---|---|---|---|
0 | Create_ds/fineract-cn-identity/api/src/main/java/org/apache/fineract/cn/identity/api/v1 | Create_ds/fineract-cn-identity/api/src/main/java/org/apache/fineract/cn/identity/api/v1/domain/Permission.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.fineract.cn.identity.api.v1.domain;
import java.util.Objects;
import java.util.Set;
import javax.validation.Valid;
import javax.validation.constraints.NotNull;
import org.apache.fineract.cn.anubis.api.v1.domain.AllowedOperation;
import org.hibernate.validator.constraints.NotBlank;
/**
* @author Myrle Krantz
*/
@SuppressWarnings({"WeakerAccess", "unused"})
public class Permission {
@NotBlank
private String permittableEndpointGroupIdentifier;
@NotNull
@Valid
private Set<AllowedOperation> allowedOperations;
public Permission() {
}
public Permission(String permittableEndpointGroupIdentifier, Set<AllowedOperation> allowedOperations) {
this.permittableEndpointGroupIdentifier = permittableEndpointGroupIdentifier;
this.allowedOperations = allowedOperations;
}
public String getPermittableEndpointGroupIdentifier() {
return permittableEndpointGroupIdentifier;
}
public void setPermittableEndpointGroupIdentifier(String permittableEndpointGroupIdentifier) {
this.permittableEndpointGroupIdentifier = permittableEndpointGroupIdentifier;
}
public Set<AllowedOperation> getAllowedOperations() {
return allowedOperations;
}
public void setAllowedOperations(Set<AllowedOperation> allowedOperations) {
this.allowedOperations = allowedOperations;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Permission that = (Permission) o;
return Objects.equals(permittableEndpointGroupIdentifier, that.permittableEndpointGroupIdentifier) &&
Objects.equals(allowedOperations, that.allowedOperations);
}
@Override
public int hashCode() {
return Objects.hash(permittableEndpointGroupIdentifier, allowedOperations);
}
@Override
public String toString() {
return "Permission{" +
"permittableEndpointGroupIdentifier='" + permittableEndpointGroupIdentifier + '\'' +
", allowedOperations=" + allowedOperations +
'}';
}
}
| 2,100 |
0 | Create_ds/fineract-cn-identity/api/src/main/java/org/apache/fineract/cn/identity/api/v1 | Create_ds/fineract-cn-identity/api/src/main/java/org/apache/fineract/cn/identity/api/v1/domain/Role.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.fineract.cn.identity.api.v1.domain;
import org.apache.fineract.cn.identity.api.v1.validation.ChangeableRole;
import org.apache.fineract.cn.lang.validation.constraints.ValidIdentifier;
import org.springframework.util.Assert;
import javax.annotation.Nonnull;
import javax.validation.Valid;
import javax.validation.constraints.NotNull;
import java.util.List;
import java.util.Objects;
/**
* @author Myrle Krantz
*/
@SuppressWarnings("unused")
public class Role {
@ValidIdentifier
@ChangeableRole
private String identifier;
@NotNull
@Valid
private List<Permission> permissions;
public Role() {}
public Role(
final @Nonnull String identifier,
final @Nonnull List<Permission> permissions) {
Assert.notNull(identifier);
Assert.notNull(permissions);
this.identifier = identifier;
this.permissions = permissions;
}
public void setIdentifier(String identifier) { this.identifier = identifier;}
public String getIdentifier() {
return identifier;
}
public void setPermissions(List<Permission> permissions) {this.permissions = permissions;}
public List<Permission> getPermissions() {
return permissions;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Role role = (Role) o;
return Objects.equals(identifier, role.identifier) &&
Objects.equals(permissions, role.permissions);
}
@Override
public int hashCode() {
return Objects.hash(identifier, permissions);
}
@Override
public String toString() {
return "Role{" +
"identifier='" + identifier + '\'' +
", permissions=" + permissions +
'}';
}
} | 2,101 |
0 | Create_ds/fineract-cn-identity/api/src/main/java/org/apache/fineract/cn/identity/api/v1 | Create_ds/fineract-cn-identity/api/src/main/java/org/apache/fineract/cn/identity/api/v1/domain/Password.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.fineract.cn.identity.api.v1.domain;
import org.hibernate.validator.constraints.Length;
import org.hibernate.validator.constraints.NotBlank;
import java.util.Objects;
/**
* @author Myrle Krantz
*/
@SuppressWarnings({"unused", "WeakerAccess"})
public class Password {
@NotBlank
@Length(min = 8)
private String password;
public Password() {
}
public Password(String password) {
this.password = password;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
@Override public boolean equals(Object o) {
if (this == o)
return true;
if (!(o instanceof Password))
return false;
Password password1 = (Password) o;
return Objects.equals(password, password1.password);
}
@Override public int hashCode() {
return Objects.hash(password);
}
@Override public String toString() {
return "Password{" +
"password='" + password + '\'' +
'}';
}
}
| 2,102 |
0 | Create_ds/fineract-cn-identity/api/src/main/java/org/apache/fineract/cn/identity/api/v1 | Create_ds/fineract-cn-identity/api/src/main/java/org/apache/fineract/cn/identity/api/v1/client/IdentityManager.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.fineract.cn.identity.api.v1.client;
import org.apache.fineract.cn.identity.api.v1.domain.Authentication;
import org.apache.fineract.cn.identity.api.v1.domain.CallEndpointSet;
import org.apache.fineract.cn.identity.api.v1.domain.Password;
import org.apache.fineract.cn.identity.api.v1.domain.Permission;
import org.apache.fineract.cn.identity.api.v1.domain.PermittableGroup;
import org.apache.fineract.cn.identity.api.v1.domain.Role;
import org.apache.fineract.cn.identity.api.v1.domain.RoleIdentifier;
import org.apache.fineract.cn.identity.api.v1.domain.User;
import org.apache.fineract.cn.identity.api.v1.domain.UserWithPassword;
import java.util.List;
import java.util.Set;
import org.apache.fineract.cn.anubis.api.v1.client.Anubis;
import org.apache.fineract.cn.anubis.api.v1.domain.ApplicationSignatureSet;
import org.apache.fineract.cn.anubis.api.v1.domain.Signature;
import org.apache.fineract.cn.anubis.api.v1.validation.ValidKeyTimestamp;
import org.apache.fineract.cn.api.annotation.ThrowsException;
import org.apache.fineract.cn.api.util.CustomFeignClientsConfiguration;
import org.springframework.cloud.netflix.feign.FeignClient;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
/**
* @author Myrle Krantz
*/
@SuppressWarnings("unused")
@FeignClient(path="/identity/v1", url = "http://${kubernetes.identity.service.name}:${kubernetes.identity.server.port}", configuration=CustomFeignClientsConfiguration.class)
public interface IdentityManager extends Anubis {
String REFRESH_TOKEN = "Identity-RefreshToken";
@RequestMapping(value = "/token?grant_type=password", method = RequestMethod.POST,
consumes = {MediaType.APPLICATION_JSON_VALUE},
produces = {MediaType.ALL_VALUE})
Authentication login(@RequestParam("username") String username, @RequestParam("password") String password);
@RequestMapping(value = "/token?grant_type=refresh_token", method = RequestMethod.POST,
consumes = {MediaType.APPLICATION_JSON_VALUE},
produces = {MediaType.ALL_VALUE})
Authentication refresh();
@RequestMapping(value = "/token?grant_type=refresh_token", method = RequestMethod.POST,
consumes = {MediaType.APPLICATION_JSON_VALUE},
produces = {MediaType.ALL_VALUE})
//Using a header different than the one used by anubis for authentication so that this function is called without
//access token-based authentication checking. The refresh token checking result is what's important here.
Authentication refresh(@RequestHeader(REFRESH_TOKEN) String refreshToken);
@RequestMapping(value = "/token/_current", method = RequestMethod.DELETE,
consumes = {MediaType.APPLICATION_JSON_VALUE},
produces = {MediaType.ALL_VALUE})
void logout();
@RequestMapping(value = "/permittablegroups", method = RequestMethod.POST,
consumes = {MediaType.APPLICATION_JSON_VALUE},
produces = {MediaType.APPLICATION_JSON_VALUE})
@ThrowsException(status = HttpStatus.CONFLICT, exception = PermittableGroupAlreadyExistsException.class)
void createPermittableGroup(@RequestBody final PermittableGroup x);
@RequestMapping(value = "/permittablegroups/{identifier}", method = RequestMethod.GET,
consumes = {MediaType.APPLICATION_JSON_VALUE},
produces = {MediaType.ALL_VALUE})
PermittableGroup getPermittableGroup(@PathVariable("identifier") String identifier);
@RequestMapping(value = "/permittablegroups", method = RequestMethod.GET,
consumes = {MediaType.APPLICATION_JSON_VALUE},
produces = {MediaType.ALL_VALUE})
List<PermittableGroup> getPermittableGroups();
@RequestMapping(value = "/roles", method = RequestMethod.POST,
consumes = {MediaType.APPLICATION_JSON_VALUE},
produces = {MediaType.APPLICATION_JSON_VALUE})
void createRole(@RequestBody final Role role);
@RequestMapping(value = "/roles/{identifier}", method = RequestMethod.PUT,
consumes = {MediaType.APPLICATION_JSON_VALUE},
produces = {MediaType.APPLICATION_JSON_VALUE})
void changeRole(@PathVariable("identifier") String identifier, @RequestBody final Role role);
@RequestMapping(value = "/roles/{identifier}", method = RequestMethod.GET,
consumes = {MediaType.APPLICATION_JSON_VALUE},
produces = {MediaType.ALL_VALUE})
Role getRole(@PathVariable("identifier") String identifier);
@RequestMapping(value = "/roles", method = RequestMethod.GET,
consumes = {MediaType.APPLICATION_JSON_VALUE},
produces = {MediaType.ALL_VALUE})
List<Role> getRoles();
@RequestMapping(value = "/roles/{identifier}", method = RequestMethod.DELETE,
consumes = {MediaType.APPLICATION_JSON_VALUE},
produces = {MediaType.ALL_VALUE})
void deleteRole(@PathVariable("identifier") String identifier);
@RequestMapping(value = "/users", method = RequestMethod.POST,
consumes = {MediaType.APPLICATION_JSON_VALUE},
produces = {MediaType.APPLICATION_JSON_VALUE})
@ThrowsException(status = HttpStatus.CONFLICT, exception = UserAlreadyExistsException.class)
void createUser(@RequestBody UserWithPassword user);
@RequestMapping(value = "/users/{useridentifier}/roleIdentifier", method = RequestMethod.PUT,
consumes = {MediaType.APPLICATION_JSON_VALUE},
produces = {MediaType.APPLICATION_JSON_VALUE})
void changeUserRole(@PathVariable("useridentifier") String userIdentifier, @RequestBody RoleIdentifier role);
@RequestMapping(value = "/users/{useridentifier}/permissions", method = RequestMethod.GET,
consumes = {MediaType.APPLICATION_JSON_VALUE},
produces = {MediaType.ALL_VALUE})
Set<Permission> getUserPermissions(@PathVariable("useridentifier") String userIdentifier);
@RequestMapping(value = "/users/{useridentifier}/password", method = RequestMethod.PUT,
consumes = {MediaType.APPLICATION_JSON_VALUE},
produces = {MediaType.APPLICATION_JSON_VALUE})
void changeUserPassword(@PathVariable("useridentifier") String userIdentifier, @RequestBody Password password);
@RequestMapping(value = "/users/{useridentifier}", method = RequestMethod.GET,
consumes = {MediaType.APPLICATION_JSON_VALUE},
produces = {MediaType.ALL_VALUE})
User getUser(@PathVariable("useridentifier") String userIdentifier);
@RequestMapping(value = "/users", method = RequestMethod.GET,
consumes = {MediaType.APPLICATION_JSON_VALUE},
produces = {MediaType.ALL_VALUE})
List<User> getUsers();
@RequestMapping(value = "/applications", method = RequestMethod.GET,
consumes = {MediaType.APPLICATION_JSON_VALUE},
produces = {MediaType.ALL_VALUE})
List<String> getApplications();
@RequestMapping(value = "/applications/{applicationidentifier}/signatures/{timestamp}", method = RequestMethod.PUT,
consumes = {MediaType.APPLICATION_JSON_VALUE},
produces = {MediaType.ALL_VALUE})
void setApplicationSignature(@PathVariable("applicationidentifier") String applicationIdentifier,
@PathVariable("timestamp") @ValidKeyTimestamp String timestamp,
Signature signature);
@RequestMapping(value = "/applications/{applicationidentifier}/signatures/{timestamp}", method = RequestMethod.GET,
consumes = {MediaType.APPLICATION_JSON_VALUE},
produces = {MediaType.ALL_VALUE})
Signature getApplicationSignature(@PathVariable("applicationidentifier") String applicationIdentifier,
@PathVariable("timestamp") @ValidKeyTimestamp String timestamp);
@RequestMapping(value = "/applications/{applicationidentifier}", method = RequestMethod.DELETE,
consumes = {MediaType.APPLICATION_JSON_VALUE},
produces = {MediaType.ALL_VALUE})
void deleteApplication(@PathVariable("applicationidentifier") String applicationIdentifier);
@RequestMapping(value = "/applications/{applicationidentifier}/permissions", method = RequestMethod.POST,
consumes = {MediaType.APPLICATION_JSON_VALUE},
produces = {MediaType.ALL_VALUE})
@ThrowsException(status = HttpStatus.CONFLICT, exception = ApplicationPermissionAlreadyExistsException.class)
void createApplicationPermission(@PathVariable("applicationidentifier") String applicationIdentifier, Permission permission);
@RequestMapping(value = "/applications/{applicationidentifier}/permissions", method = RequestMethod.GET,
consumes = {MediaType.APPLICATION_JSON_VALUE},
produces = {MediaType.ALL_VALUE})
List<Permission> getApplicationPermissions(@PathVariable("applicationidentifier") String applicationIdentifier);
@RequestMapping(value = "/applications/{applicationidentifier}/permissions/{permissionidentifier}", method = RequestMethod.GET,
consumes = {MediaType.APPLICATION_JSON_VALUE},
produces = {MediaType.ALL_VALUE})
Permission getApplicationPermission(@PathVariable("applicationidentifier") String applicationIdentifier,
@PathVariable("permissionidentifier") String permittableEndpointGroupIdentifier);
@RequestMapping(value = "/applications/{applicationidentifier}/permissions/{permissionidentifier}", method = RequestMethod.DELETE,
consumes = {MediaType.APPLICATION_JSON_VALUE},
produces = {MediaType.ALL_VALUE})
void deleteApplicationPermission(@PathVariable("applicationidentifier") String applicationIdentifier,
@PathVariable("permissionidentifier") String permittableEndpointGroupIdentifier);
@RequestMapping(value = "/applications/{applicationidentifier}/callendpointset", method = RequestMethod.POST,
consumes = {MediaType.APPLICATION_JSON_VALUE},
produces = {MediaType.ALL_VALUE})
@ThrowsException(status = HttpStatus.CONFLICT, exception = CallEndpointSetAlreadyExistsException.class)
void createApplicationCallEndpointSet(@PathVariable("applicationidentifier") String applicationIdentifier, CallEndpointSet callEndpointSet);
@RequestMapping(value = "/applications/{applicationidentifier}/callendpointset/{callendpointsetidentifier}", method = RequestMethod.PUT,
consumes = {MediaType.APPLICATION_JSON_VALUE},
produces = {MediaType.ALL_VALUE})
void changeApplicationCallEndpointSet(@PathVariable("applicationidentifier") String applicationIdentifier,
@PathVariable("callendpointsetidentifier") String callEndpointSetIdentifier,
CallEndpointSet callEndpointSet);
@RequestMapping(value = "/applications/{applicationidentifier}/callendpointset", method = RequestMethod.GET,
consumes = {MediaType.APPLICATION_JSON_VALUE},
produces = {MediaType.ALL_VALUE})
List<CallEndpointSet> getApplicationCallEndpointSets(@PathVariable("applicationidentifier") String applicationIdentifier);
@RequestMapping(value = "/applications/{applicationidentifier}/callendpointset/{callendpointsetidentifier}", method = RequestMethod.GET,
consumes = {MediaType.APPLICATION_JSON_VALUE},
produces = {MediaType.ALL_VALUE})
CallEndpointSet getApplicationCallEndpointSet(@PathVariable("applicationidentifier") String applicationIdentifier,
@PathVariable("callendpointsetidentifier") String callEndpointSetIdentifier);
@RequestMapping(value = "/applications/{applicationidentifier}/callendpointset/{callendpointsetidentifier}", method = RequestMethod.DELETE,
consumes = {MediaType.APPLICATION_JSON_VALUE},
produces = {MediaType.ALL_VALUE})
void deleteApplicationCallEndpointSet(@PathVariable("applicationidentifier") String applicationIdentifier,
@PathVariable("callendpointsetidentifier") String callEndpointSetIdentifier);
@RequestMapping(value = "/applications/{applicationidentifier}/permissions/{permissionidentifier}/users/{useridentifier}/enabled", method = RequestMethod.PUT,
consumes = {MediaType.APPLICATION_JSON_VALUE},
produces = {MediaType.ALL_VALUE})
void setApplicationPermissionEnabledForUser(@PathVariable("applicationidentifier") String applicationIdentifier,
@PathVariable("permissionidentifier") String permittableEndpointGroupIdentifier,
@PathVariable("useridentifier") String userIdentifier,
Boolean enabled);
@RequestMapping(value = "/applications/{applicationidentifier}/permissions/{permissionidentifier}/users/{useridentifier}/enabled", method = RequestMethod.GET,
consumes = {MediaType.APPLICATION_JSON_VALUE},
produces = {MediaType.APPLICATION_JSON_VALUE})
boolean getApplicationPermissionEnabledForUser(@PathVariable("applicationidentifier") String applicationIdentifier,
@PathVariable("permissionidentifier") String permittableEndpointGroupIdentifier,
@PathVariable("useridentifier") String userIdentifier);
@RequestMapping(value = "/initialize", method = RequestMethod.POST,
consumes = {MediaType.APPLICATION_JSON_VALUE},
produces = {MediaType.APPLICATION_JSON_VALUE})
ApplicationSignatureSet initialize(@RequestParam("password") String password);
@RequestMapping(value = "/signatures", method = RequestMethod.POST,
consumes = {MediaType.APPLICATION_JSON_VALUE},
produces = {MediaType.ALL_VALUE})
ApplicationSignatureSet createSignatureSet();
}
| 2,103 |
0 | Create_ds/fineract-cn-identity/api/src/main/java/org/apache/fineract/cn/identity/api/v1 | Create_ds/fineract-cn-identity/api/src/main/java/org/apache/fineract/cn/identity/api/v1/client/PermittableGroupAlreadyExistsException.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.fineract.cn.identity.api.v1.client;
/**
* @author Myrle Krantz
*/
@SuppressWarnings("WeakerAccess")
public class PermittableGroupAlreadyExistsException extends RuntimeException {
}
| 2,104 |
0 | Create_ds/fineract-cn-identity/api/src/main/java/org/apache/fineract/cn/identity/api/v1 | Create_ds/fineract-cn-identity/api/src/main/java/org/apache/fineract/cn/identity/api/v1/client/TenantNotSetException.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.fineract.cn.identity.api.v1.client;
/**
* @author Myrle Krantz
*/
@SuppressWarnings("unused")
public class TenantNotSetException extends RuntimeException {
}
| 2,105 |
0 | Create_ds/fineract-cn-identity/api/src/main/java/org/apache/fineract/cn/identity/api/v1 | Create_ds/fineract-cn-identity/api/src/main/java/org/apache/fineract/cn/identity/api/v1/client/ApplicationPermissionAlreadyExistsException.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.fineract.cn.identity.api.v1.client;
/**
* @author Myrle Krantz
*/
@SuppressWarnings("WeakerAccess")
public class ApplicationPermissionAlreadyExistsException extends RuntimeException {
}
| 2,106 |
0 | Create_ds/fineract-cn-identity/api/src/main/java/org/apache/fineract/cn/identity/api/v1 | Create_ds/fineract-cn-identity/api/src/main/java/org/apache/fineract/cn/identity/api/v1/client/UserAlreadyExistsException.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.fineract.cn.identity.api.v1.client;
/**
* @author Myrle Krantz
*/
@SuppressWarnings("WeakerAccess")
public class UserAlreadyExistsException extends RuntimeException {
}
| 2,107 |
0 | Create_ds/fineract-cn-identity/api/src/main/java/org/apache/fineract/cn/identity/api/v1 | Create_ds/fineract-cn-identity/api/src/main/java/org/apache/fineract/cn/identity/api/v1/client/CallEndpointSetAlreadyExistsException.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.fineract.cn.identity.api.v1.client;
/**
* @author Myrle Krantz
*/
@SuppressWarnings("WeakerAccess")
public class CallEndpointSetAlreadyExistsException extends RuntimeException {
}
| 2,108 |
0 | Create_ds/fineract-cn-identity/api/src/main/java/org/apache/fineract/cn/identity/api/v1 | Create_ds/fineract-cn-identity/api/src/main/java/org/apache/fineract/cn/identity/api/v1/validation/NotRootRole.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.fineract.cn.identity.api.v1.validation;
import javax.validation.Constraint;
import javax.validation.Payload;
import java.lang.annotation.*;
/**
* @author Myrle Krantz
*/
@SuppressWarnings({"unused", "WeakerAccess"})
@Target({ElementType.FIELD, ElementType.METHOD, ElementType.PARAMETER})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Constraint(
validatedBy = {CheckNotRootRole.class}
)
public @interface NotRootRole {
String message() default "The role 'pharaoh' cannot be assigned to a user.";
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
}
| 2,109 |
0 | Create_ds/fineract-cn-identity/api/src/main/java/org/apache/fineract/cn/identity/api/v1 | Create_ds/fineract-cn-identity/api/src/main/java/org/apache/fineract/cn/identity/api/v1/validation/CheckRoleChangeable.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.fineract.cn.identity.api.v1.validation;
import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
/**
* @author Myrle Krantz
*/
@SuppressWarnings("WeakerAccess")
public class CheckRoleChangeable implements ConstraintValidator<ChangeableRole, String> {
@Override
public void initialize(final ChangeableRole constraintAnnotation) {
}
@Override
public boolean isValid(final String value, final ConstraintValidatorContext context) {
return isChangeableRoleIdentifier(value);
}
public static boolean isChangeableRoleIdentifier(final String value) {
return !value.equals("pharaoh") && !value.equals("deactivated");
}
}
| 2,110 |
0 | Create_ds/fineract-cn-identity/api/src/main/java/org/apache/fineract/cn/identity/api/v1 | Create_ds/fineract-cn-identity/api/src/main/java/org/apache/fineract/cn/identity/api/v1/validation/CheckNotRootRole.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.fineract.cn.identity.api.v1.validation;
import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
/**
* @author Myrle Krantz
*/
public class CheckNotRootRole implements ConstraintValidator<NotRootRole, String> {
@Override
public void initialize(final NotRootRole constraintAnnotation) {
}
@Override
public boolean isValid(final String value, final ConstraintValidatorContext context) {
return !value.equals("pharaoh");
}
} | 2,111 |
0 | Create_ds/fineract-cn-identity/api/src/main/java/org/apache/fineract/cn/identity/api/v1 | Create_ds/fineract-cn-identity/api/src/main/java/org/apache/fineract/cn/identity/api/v1/validation/ChangeableRole.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.fineract.cn.identity.api.v1.validation;
import javax.validation.Constraint;
import javax.validation.Payload;
import java.lang.annotation.*;
/**
* @author Myrle Krantz
*/
@SuppressWarnings({"unused", "WeakerAccess"})
@Target({ElementType.FIELD, ElementType.METHOD, ElementType.PARAMETER})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Constraint(
validatedBy = {CheckRoleChangeable.class}
)
public @interface ChangeableRole {
String message() default "The role 'pharaoh' cannot be changed or deleted.";
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
}
| 2,112 |
0 | Create_ds/fineract-cn-identity/service/src/test/java/org/apache/fineract/cn/identity/internal/command | Create_ds/fineract-cn-identity/service/src/test/java/org/apache/fineract/cn/identity/internal/command/handler/AuthenticationCommandHandlerTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.fineract.cn.identity.internal.command.handler;
import com.google.gson.Gson;
import org.apache.fineract.cn.anubis.provider.TenantRsaKeyProvider;
import org.apache.fineract.cn.anubis.token.TenantAccessTokenSerializer;
import org.apache.fineract.cn.anubis.token.TenantRefreshTokenSerializer;
import org.apache.fineract.cn.anubis.token.TokenDeserializationResult;
import org.apache.fineract.cn.anubis.token.TokenSerializationResult;
import org.apache.fineract.cn.crypto.HashGenerator;
import org.apache.fineract.cn.crypto.SaltGenerator;
import org.apache.fineract.cn.identity.internal.command.AuthenticationCommandResponse;
import org.apache.fineract.cn.identity.internal.command.PasswordAuthenticationCommand;
import org.apache.fineract.cn.identity.internal.command.RefreshTokenAuthenticationCommand;
import org.apache.fineract.cn.identity.internal.repository.AllowedOperationType;
import org.apache.fineract.cn.identity.internal.repository.ApplicationCallEndpointSets;
import org.apache.fineract.cn.identity.internal.repository.ApplicationPermissionUsers;
import org.apache.fineract.cn.identity.internal.repository.ApplicationPermissions;
import org.apache.fineract.cn.identity.internal.repository.ApplicationSignatures;
import org.apache.fineract.cn.identity.internal.repository.PermissionType;
import org.apache.fineract.cn.identity.internal.repository.PermittableGroups;
import org.apache.fineract.cn.identity.internal.repository.PrivateSignatureEntity;
import org.apache.fineract.cn.identity.internal.repository.PrivateTenantInfoEntity;
import org.apache.fineract.cn.identity.internal.repository.RoleEntity;
import org.apache.fineract.cn.identity.internal.repository.Roles;
import org.apache.fineract.cn.identity.internal.repository.Signatures;
import org.apache.fineract.cn.identity.internal.repository.Tenants;
import org.apache.fineract.cn.identity.internal.repository.UserEntity;
import org.apache.fineract.cn.identity.internal.repository.Users;
import org.apache.fineract.cn.lang.ApplicationName;
import org.apache.fineract.cn.lang.DateConverter;
import org.apache.fineract.cn.lang.security.RsaKeyPairFactory;
import org.junit.Assert;
import org.junit.BeforeClass;
import org.junit.Test;
import org.mockito.Mockito;
import org.slf4j.Logger;
import org.springframework.jms.core.JmsTemplate;
import java.nio.ByteBuffer;
import java.time.Instant;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import static org.mockito.Matchers.*;
import static org.mockito.Mockito.when;
/**
* @author Myrle Krantz
*/
public class AuthenticationCommandHandlerTest {
private static final String USER_NAME = "me";
private static final String ROLE = "I";
private static final String PASSWORD = "mine";
private static final int ITERATION_COUNT = 20;
private static final String TEST_APPLICATION_NAME = "test-v1";
private static final long ACCESS_TOKEN_TIME_TO_LIVE = 20;
private static final long REFRESH_TOKEN_TIME_TO_LIVE = 40;
private static final int GRACE_PERIOD = 2;
private static AuthenticationCommandHandler commandHandler;
@BeforeClass()
static public void setup()
{
RsaKeyPairFactory.KeyPairHolder keyPair = RsaKeyPairFactory.createKeyPair();
final Users users = Mockito.mock(Users.class);
final Roles roles = Mockito.mock(Roles.class);
final PermittableGroups permittableGroups = Mockito.mock(PermittableGroups.class);
final Signatures signatures = Mockito.mock(Signatures.class);
final Tenants tenants = Mockito.mock(Tenants.class);
final HashGenerator hashGenerator = Mockito.mock(HashGenerator.class);
final TenantAccessTokenSerializer tenantAccessTokenSerializer
= Mockito.mock(TenantAccessTokenSerializer.class);
final TenantRefreshTokenSerializer tenantRefreshTokenSerializer
= Mockito.mock(TenantRefreshTokenSerializer.class);
final JmsTemplate jmsTemplate = Mockito.mock(JmsTemplate.class);
final ApplicationName applicationName = Mockito.mock(ApplicationName.class);
final Gson gson = new Gson();
final Logger logger = Mockito.mock(Logger.class);
final TenantRsaKeyProvider tenantRsaKeyProvider = Mockito.mock(TenantRsaKeyProvider.class);
final ApplicationSignatures applicationSignatures = Mockito.mock(ApplicationSignatures.class);
final ApplicationPermissions applicationPermissions = Mockito.mock(ApplicationPermissions.class);
final ApplicationPermissionUsers applicationPermissionUsers = Mockito.mock(ApplicationPermissionUsers.class);
final ApplicationCallEndpointSets applicationCallEndpointSets = Mockito.mock(ApplicationCallEndpointSets.class);
commandHandler = new AuthenticationCommandHandler(
users, roles, permittableGroups, signatures, tenants,
hashGenerator,
tenantAccessTokenSerializer, tenantRefreshTokenSerializer, tenantRsaKeyProvider,
applicationSignatures, applicationPermissions, applicationPermissionUsers, applicationCallEndpointSets,
jmsTemplate, applicationName,
gson, logger);
final PrivateTenantInfoEntity privateTenantInfoEntity = new PrivateTenantInfoEntity();
privateTenantInfoEntity.setFixedSalt(ByteBuffer.wrap(new SaltGenerator().createRandomSalt()));
privateTenantInfoEntity.setTimeToChangePasswordAfterExpirationInDays(GRACE_PERIOD);
when(tenants.getPrivateTenantInfo()).thenReturn(Optional.of(privateTenantInfoEntity));
final PrivateSignatureEntity privateSignatureEntity = new PrivateSignatureEntity();
privateSignatureEntity.setKeyTimestamp(keyPair.getTimestamp());
privateSignatureEntity.setPrivateKeyExp(keyPair.getPrivateKeyExp());
privateSignatureEntity.setPrivateKeyMod(keyPair.getPrivateKeyMod());
when(signatures.getPrivateSignature()).thenReturn(Optional.of(privateSignatureEntity));
final UserEntity userEntity = new UserEntity();
userEntity.setRole(ROLE);
userEntity.setIdentifier(USER_NAME);
userEntity.setIterationCount(ITERATION_COUNT);
userEntity.setPassword(ByteBuffer.wrap(PASSWORD.getBytes()));
userEntity.setSalt(ByteBuffer.wrap(new SaltGenerator().createRandomSalt()));
userEntity.setPasswordExpiresOn(dataStaxNow());
when(users.get(USER_NAME)).thenReturn(Optional.of(userEntity));
final List<PermissionType> permissionsList = new ArrayList<>();
final RoleEntity roleEntity = new RoleEntity(ROLE, permissionsList);
when(roles.get(ROLE)).thenReturn(Optional.of(roleEntity));
when(applicationName.toString()).thenReturn(TEST_APPLICATION_NAME);
final TokenSerializationResult accessTokenSerializationResult = new TokenSerializationResult("blah", LocalDateTime.now(ZoneId.of("UTC")).plusSeconds(ACCESS_TOKEN_TIME_TO_LIVE));
when(tenantAccessTokenSerializer.build(anyObject())).thenReturn(accessTokenSerializationResult);
final TokenSerializationResult refreshTokenSerializationResult = new TokenSerializationResult("blah", LocalDateTime.now(ZoneId.of("UTC")).plusSeconds(REFRESH_TOKEN_TIME_TO_LIVE));
when(tenantRefreshTokenSerializer.build(anyObject())).thenReturn(refreshTokenSerializationResult);
final TokenDeserializationResult deserialized = new TokenDeserializationResult(USER_NAME, Date.from(Instant.now().plusSeconds(REFRESH_TOKEN_TIME_TO_LIVE)), TEST_APPLICATION_NAME, null);
when(tenantRefreshTokenSerializer.deserialize(anyObject(), anyObject())).thenReturn(deserialized);
when(hashGenerator.isEqual(any(), any(), any(), any(), anyInt(), anyInt())).thenReturn(true);
}
private static com.datastax.driver.core.LocalDate dataStaxNow() {
return com.datastax.driver.core.LocalDate.fromDaysSinceEpoch((int) LocalDate.now(ZoneId.of("UTC")).toEpochDay());
}
@Test
public void correctPasswordAuthentication()
{
final PasswordAuthenticationCommand command = new PasswordAuthenticationCommand(USER_NAME, PASSWORD);
final AuthenticationCommandResponse commandResponse = commandHandler.process(command);
Assert.assertNotNull(commandResponse);
}
@Test
public void correctRefreshTokenAuthentication()
{
final String refreshTokenPlaceHolder = "refresh_token";
final RefreshTokenAuthenticationCommand command = new RefreshTokenAuthenticationCommand(refreshTokenPlaceHolder);
final LocalDateTime now = LocalDateTime.now(ZoneId.of("UTC"));
final AuthenticationCommandResponse commandResponse = commandHandler.process(command);
Assert.assertNotNull(commandResponse);
Assert.assertNotNull(commandResponse.getRefreshToken());
Assert.assertEquals(commandResponse.getRefreshToken(), refreshTokenPlaceHolder);
checkExpiration(commandResponse.getAccessTokenExpiration(), now, ACCESS_TOKEN_TIME_TO_LIVE);
checkExpiration(commandResponse.getRefreshTokenExpiration(), now, REFRESH_TOKEN_TIME_TO_LIVE);
}
private void checkExpiration(final String expirationString, final LocalDateTime now, final long timeToLive) {
final LocalDateTime expectedExpiration = now.plusSeconds(timeToLive);
final LocalDateTime parsedExpiration = LocalDateTime.parse(expirationString, DateTimeFormatter.ISO_DATE_TIME);
final long deltaFromExpected = Math.abs(parsedExpiration.until(expectedExpiration, ChronoUnit.SECONDS));
Assert.assertTrue("Delta from expected should have been less than 2 second, but was " + deltaFromExpected +
". Expiration string was " + expirationString + ". Now was " + now + ".",
deltaFromExpected <= 2);
}
@Test
public void correctDeterminationOfPasswordExpiration()
{
final LocalDateTime passwordExpirationFromToday = LocalDateTime.now(ZoneId.of("UTC"));
Assert.assertTrue(AuthenticationCommandHandler.pastExpiration(Optional.of(passwordExpirationFromToday)));
final LocalDateTime passwordExpirationFromYesterday = passwordExpirationFromToday.minusDays(1);
Assert.assertTrue(AuthenticationCommandHandler.pastExpiration(Optional.of(passwordExpirationFromYesterday)));
final LocalDateTime passwordExpirationFromTommorrow = passwordExpirationFromToday.plusDays(1);
Assert.assertFalse(AuthenticationCommandHandler.pastExpiration(Optional.of(passwordExpirationFromTommorrow)));
}
@Test
public void correctDeterminationOfPasswordGracePeriod()
{
final LocalDateTime passwordExpirationFromToday = LocalDateTime.now(ZoneId.of("UTC"));
Assert.assertFalse(AuthenticationCommandHandler.pastGracePeriod(Optional.of(passwordExpirationFromToday), GRACE_PERIOD));
final LocalDateTime nowJustWithinPasswordExpirationAndGracePeriod = passwordExpirationFromToday.minusDays(GRACE_PERIOD - 1);
Assert.assertFalse(AuthenticationCommandHandler.pastGracePeriod(Optional.of(nowJustWithinPasswordExpirationAndGracePeriod), GRACE_PERIOD));
final LocalDateTime nowJustOutsideOfPasswordExpirationAndGracePeriod = passwordExpirationFromToday.minusDays(GRACE_PERIOD);
Assert.assertTrue(AuthenticationCommandHandler.pastGracePeriod(Optional.of(nowJustOutsideOfPasswordExpirationAndGracePeriod), GRACE_PERIOD));
}
@Test
public void matchingFormatOfDates() {
final Instant now = Instant.now();
final Date nowDate = Date.from(now);
final LocalDateTime nowLocalDateTime = LocalDateTime.ofInstant(now, ZoneId.of("UTC"));
final LocalDate nowLocalDate = nowLocalDateTime.toLocalDate();
final String dateString = DateConverter.toIsoString(nowDate);
final String localDateTimeString = DateConverter.toIsoString(nowLocalDateTime);
final String localDateString = DateConverter.toIsoString(nowLocalDate);
Assert.assertEquals(dateString, localDateTimeString);
Assert.assertTrue(localDateTimeString.startsWith(localDateString.substring(0, localDateString.length()-1))); //(removing Z)
}
@Test
public void intersectSets() {
final Set<AllowedOperationType> intersectionWithNull
= AuthenticationCommandHandler.intersectSets(new HashSet<>(), null);
Assert.assertTrue(intersectionWithNull.isEmpty());
final Set<AllowedOperationType> intersectionWithEqualSet
= AuthenticationCommandHandler.intersectSets(Collections.singleton(AllowedOperationType.CHANGE),
Collections.singleton(AllowedOperationType.CHANGE));
Assert.assertEquals(Collections.singleton(AllowedOperationType.CHANGE), intersectionWithEqualSet);
final Set<AllowedOperationType> intersectionWithAll
= AuthenticationCommandHandler.intersectSets(AllowedOperationType.ALL,
AllowedOperationType.ALL);
Assert.assertEquals(AllowedOperationType.ALL, intersectionWithAll);
final Set<AllowedOperationType> intersectionWithNonOverlappingSet
= AuthenticationCommandHandler.intersectSets(Collections.singleton(AllowedOperationType.DELETE),
Collections.singleton(AllowedOperationType.CHANGE));
Assert.assertTrue(intersectionWithNonOverlappingSet.isEmpty());
final Set<AllowedOperationType> intersectionWithSubSet
= AuthenticationCommandHandler.intersectSets(AllowedOperationType.ALL,
Collections.singleton(AllowedOperationType.CHANGE));
Assert.assertEquals(Collections.singleton(AllowedOperationType.CHANGE), intersectionWithSubSet);
final Set<AllowedOperationType> intersectionWithPartiallyOverlapping = AuthenticationCommandHandler.intersectSets(
Stream.of(AllowedOperationType.CHANGE, AllowedOperationType.DELETE).collect(Collectors.toSet()),
Stream.of(AllowedOperationType.CHANGE, AllowedOperationType.READ).collect(Collectors.toSet()));
Assert.assertEquals(Collections.singleton(AllowedOperationType.CHANGE), intersectionWithPartiallyOverlapping);
}
@Test
public void transformToSearchablePermissions()
{
Map<String, Set<AllowedOperationType>> x = AuthenticationCommandHandler.transformToSearchablePermissions(Arrays.asList(
new PermissionType("x", new HashSet<>(AllowedOperationType.ALL)),
new PermissionType("y", new HashSet<>(Collections.singletonList(AllowedOperationType.CHANGE)))));
Assert.assertEquals(AllowedOperationType.ALL, x.get("x"));
}
}
| 2,113 |
0 | Create_ds/fineract-cn-identity/service/src/main/java/org/apache/fineract/cn/identity | Create_ds/fineract-cn-identity/service/src/main/java/org/apache/fineract/cn/identity/config/IdentityServiceConfig.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.fineract.cn.identity.config;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import org.apache.fineract.cn.anubis.config.EnableAnubis;
import org.apache.fineract.cn.async.config.EnableAsync;
import org.apache.fineract.cn.cassandra.config.EnableCassandra;
import org.apache.fineract.cn.command.config.EnableCommandProcessing;
import org.apache.fineract.cn.crypto.config.EnableCrypto;
import org.apache.fineract.cn.identity.internal.util.IdentityConstants;
import org.apache.fineract.cn.lang.config.EnableServiceException;
import org.apache.fineract.cn.lang.config.EnableTenantContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.PathMatchConfigurer;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
@Configuration
@EnableAutoConfiguration
@EnableWebMvc
@EnableAsync
@EnableTenantContext
@EnableCassandra
@EnableCommandProcessing
@EnableServiceException
@EnableCrypto
@EnableAnubis(provideSignatureStorage = false)
@ComponentScan({
"org.apache.fineract.cn.identity.rest",
"org.apache.fineract.cn.identity.internal.service",
"org.apache.fineract.cn.identity.internal.repository",
"org.apache.fineract.cn.identity.internal.command.handler"
})
public class IdentityServiceConfig extends WebMvcConfigurerAdapter {
public IdentityServiceConfig() {}
@Bean(name = IdentityConstants.JSON_SERIALIZER_NAME)
public Gson gson() {
return new GsonBuilder().create();
}
@Bean(name = IdentityConstants.LOGGER_NAME)
public Logger logger() {
return LoggerFactory.getLogger(IdentityConstants.LOGGER_NAME);
}
@Override
public void configurePathMatch(final PathMatchConfigurer configurer) {
configurer.setUseSuffixPatternMatch(Boolean.FALSE);
}
public static void main(String[] args) {
SpringApplication.run(IdentityServiceConfig.class, args);
}
}
| 2,114 |
0 | Create_ds/fineract-cn-identity/service/src/main/java/org/apache/fineract/cn/identity/internal | Create_ds/fineract-cn-identity/service/src/main/java/org/apache/fineract/cn/identity/internal/repository/ApplicationSignatureEntity.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.fineract.cn.identity.internal.repository;
import com.datastax.driver.mapping.annotations.ClusteringColumn;
import com.datastax.driver.mapping.annotations.Column;
import com.datastax.driver.mapping.annotations.PartitionKey;
import com.datastax.driver.mapping.annotations.Table;
import java.math.BigInteger;
/**
* @author Myrle Krantz
*/
@Table(name = ApplicationSignatures.TABLE_NAME)
public class ApplicationSignatureEntity {
@PartitionKey
@Column(name = ApplicationSignatures.APPLICATION_IDENTIFIER_COLUMN)
private String applicationIdentifier;
@ClusteringColumn
@Column(name = ApplicationSignatures.KEY_TIMESTAMP_COLUMN)
private String keyTimestamp;
@Column(name = ApplicationSignatures.PUBLIC_KEY_MOD_COLUMN)
private BigInteger publicKeyMod;
@Column(name = ApplicationSignatures.PUBLIC_KEY_EXP_COLUMN)
private BigInteger publicKeyExp;
public String getApplicationIdentifier() {
return applicationIdentifier;
}
public void setApplicationIdentifier(String applicationIdentifier) {
this.applicationIdentifier = applicationIdentifier;
}
public String getKeyTimestamp() {
return keyTimestamp;
}
public void setKeyTimestamp(String keyTimestamp) {
this.keyTimestamp = keyTimestamp;
}
public BigInteger getPublicKeyMod() {
return publicKeyMod;
}
public void setPublicKeyMod(BigInteger publicKeyMod) {
this.publicKeyMod = publicKeyMod;
}
public BigInteger getPublicKeyExp() {
return publicKeyExp;
}
public void setPublicKeyExp(BigInteger publicKeyExp) {
this.publicKeyExp = publicKeyExp;
}
}
| 2,115 |
0 | Create_ds/fineract-cn-identity/service/src/main/java/org/apache/fineract/cn/identity/internal | Create_ds/fineract-cn-identity/service/src/main/java/org/apache/fineract/cn/identity/internal/repository/PermissionType.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.fineract.cn.identity.internal.repository;
import com.datastax.driver.mapping.annotations.Field;
import com.datastax.driver.mapping.annotations.UDT;
import java.util.Objects;
import java.util.Set;
/**
* @author Myrle Krantz
*/
@SuppressWarnings({"unused", "WeakerAccess"})
@UDT(name = Permissions.TYPE_NAME)
public class PermissionType {
@Field(name = Permissions.PERMITTABLE_GROUP_IDENTIFIER_FIELD)
private String permittableGroupIdentifier;
@Field(name = Permissions.ALLOWED_OPERATIONS_FIELD)
private Set<AllowedOperationType> allowedOperations;
public PermissionType() {
}
public PermissionType(String permittableGroupIdentifier, Set<AllowedOperationType> allowedOperations) {
this.permittableGroupIdentifier = permittableGroupIdentifier;
this.allowedOperations = allowedOperations;
}
public String getPermittableGroupIdentifier() {
return permittableGroupIdentifier;
}
public void setPermittableGroupIdentifier(String permittableGroupIdentifier) {
this.permittableGroupIdentifier = permittableGroupIdentifier;
}
public Set<AllowedOperationType> getAllowedOperations() {
return allowedOperations;
}
public void setAllowedOperations(Set<AllowedOperationType> allowedOperations) {
this.allowedOperations = allowedOperations;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
PermissionType that = (PermissionType) o;
return Objects.equals(permittableGroupIdentifier, that.permittableGroupIdentifier) &&
Objects.equals(allowedOperations, that.allowedOperations);
}
@Override
public int hashCode() {
return Objects.hash(permittableGroupIdentifier, allowedOperations);
}
@Override
public String toString() {
return "PermissionType{" +
"permittableGroupIdentifier='" + permittableGroupIdentifier + '\'' +
", allowedOperations=" + allowedOperations +
'}';
}
}
| 2,116 |
0 | Create_ds/fineract-cn-identity/service/src/main/java/org/apache/fineract/cn/identity/internal | Create_ds/fineract-cn-identity/service/src/main/java/org/apache/fineract/cn/identity/internal/repository/AllowedOperationType.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.fineract.cn.identity.internal.repository;
import com.datastax.driver.core.TypeCodec;
import com.datastax.driver.extras.codecs.enums.EnumNameCodec;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
public enum AllowedOperationType {
READ, //GET, TRACE
CHANGE, //POST, PUT
DELETE; //DELETE
public static final Set<AllowedOperationType> ALL = Collections.unmodifiableSet(
new HashSet<AllowedOperationType>() {{add(READ); add(CHANGE); add(DELETE);}});
static TypeCodec<AllowedOperationType> getCodec()
{
return new EnumNameCodec<>(AllowedOperationType.class);
}
static public AllowedOperationType fromHttpMethod(final String httpMethod)
{
switch (httpMethod) {
case "GET":
case "TRACE":
return READ;
case "POST":
case "PUT":
return CHANGE;
case "DELETE":
return DELETE;
default:
return null;
}
}
}
| 2,117 |
0 | Create_ds/fineract-cn-identity/service/src/main/java/org/apache/fineract/cn/identity/internal | Create_ds/fineract-cn-identity/service/src/main/java/org/apache/fineract/cn/identity/internal/repository/RoleEntity.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.fineract.cn.identity.internal.repository;
import com.datastax.driver.mapping.annotations.Column;
import com.datastax.driver.mapping.annotations.Frozen;
import com.datastax.driver.mapping.annotations.PartitionKey;
import com.datastax.driver.mapping.annotations.Table;
import java.util.List;
import java.util.Objects;
/**
* @author Myrle Krantz
*/
@SuppressWarnings({"unused", "WeakerAccess"})
@Table(name = Roles.TABLE_NAME)
public class RoleEntity {
@PartitionKey
@Column(name = Roles.IDENTIFIER_COLUMN)
private String identifier;
@Frozen
@Column(name = Roles.PERMISSIONS_COLUMN)
private List<PermissionType> permissions;
public RoleEntity() {
}
public RoleEntity(String identifier, List<PermissionType> permissions) {
this.identifier = identifier;
this.permissions = permissions;
}
public String getIdentifier() {
return identifier;
}
public void setIdentifier(String identifier) {
this.identifier = identifier;
}
public List<PermissionType> getPermissions() {
return permissions;
}
public void setPermissions(List<PermissionType> permissions) {
this.permissions = permissions;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
RoleEntity that = (RoleEntity) o;
return Objects.equals(identifier, that.identifier) &&
Objects.equals(permissions, that.permissions);
}
@Override
public int hashCode() {
return Objects.hash(identifier, permissions);
}
@Override
public String toString() {
return "RoleEntity{" +
"identifier='" + identifier + '\'' +
", permissions=" + permissions +
'}';
}
}
| 2,118 |
0 | Create_ds/fineract-cn-identity/service/src/main/java/org/apache/fineract/cn/identity/internal | Create_ds/fineract-cn-identity/service/src/main/java/org/apache/fineract/cn/identity/internal/repository/PermittableGroupEntity.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.fineract.cn.identity.internal.repository;
import com.datastax.driver.mapping.annotations.Column;
import com.datastax.driver.mapping.annotations.Frozen;
import com.datastax.driver.mapping.annotations.PartitionKey;
import com.datastax.driver.mapping.annotations.Table;
import java.util.List;
import java.util.Objects;
/**
* @author Myrle Krantz
*/
@SuppressWarnings({"unused", "WeakerAccess"})
@Table(name = PermittableGroups.TABLE_NAME)
public class PermittableGroupEntity {
@PartitionKey
@Column(name = PermittableGroups.IDENTIFIER_COLUMN)
private String identifier;
@Frozen
@Column(name = PermittableGroups.PERMITTABLES_COLUMN)
private List<PermittableType> permittables;
public PermittableGroupEntity() {
}
public String getIdentifier() {
return identifier;
}
public void setIdentifier(String identifier) {
this.identifier = identifier;
}
public List<PermittableType> getPermittables() {
return permittables;
}
public void setPermittables(List<PermittableType> permittables) {
this.permittables = permittables;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
PermittableGroupEntity that = (PermittableGroupEntity) o;
return Objects.equals(identifier, that.identifier) &&
Objects.equals(permittables, that.permittables);
}
@Override
public int hashCode() {
return Objects.hash(identifier, permittables);
}
@Override
public String toString() {
return "PermittableGroupEntity{" +
"identifier='" + identifier + '\'' +
", permittables=" + permittables +
'}';
}
}
| 2,119 |
0 | Create_ds/fineract-cn-identity/service/src/main/java/org/apache/fineract/cn/identity/internal | Create_ds/fineract-cn-identity/service/src/main/java/org/apache/fineract/cn/identity/internal/repository/ApplicationSignatures.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.fineract.cn.identity.internal.repository;
import com.datastax.driver.core.DataType;
import com.datastax.driver.core.ResultSet;
import com.datastax.driver.core.Session;
import com.datastax.driver.core.Statement;
import com.datastax.driver.core.querybuilder.Delete;
import com.datastax.driver.core.querybuilder.QueryBuilder;
import com.datastax.driver.core.querybuilder.Select;
import com.datastax.driver.core.schemabuilder.Create;
import com.datastax.driver.core.schemabuilder.SchemaBuilder;
import com.datastax.driver.mapping.Mapper;
import org.apache.fineract.cn.cassandra.core.CassandraSessionProvider;
import org.apache.fineract.cn.cassandra.core.TenantAwareCassandraMapperProvider;
import org.apache.fineract.cn.cassandra.core.TenantAwareEntityTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.Assert;
import java.util.List;
import java.util.Optional;
/**
* @author Myrle Krantz
*/
@Component
public class ApplicationSignatures {
static final java.lang.String TABLE_NAME = "isis_application_signatures";
static final String APPLICATION_IDENTIFIER_COLUMN = "application_identifier";
static final String KEY_TIMESTAMP_COLUMN = "key_timestamp";
static final String PUBLIC_KEY_MOD_COLUMN = "public_key_mod";
static final String PUBLIC_KEY_EXP_COLUMN = "public_key_exp";
private final CassandraSessionProvider cassandraSessionProvider;
private final TenantAwareEntityTemplate tenantAwareEntityTemplate;
private final TenantAwareCassandraMapperProvider tenantAwareCassandraMapperProvider;
@Autowired
public ApplicationSignatures(final CassandraSessionProvider cassandraSessionProvider,
final TenantAwareEntityTemplate tenantAwareEntityTemplate,
final TenantAwareCassandraMapperProvider tenantAwareCassandraMapperProvider) {
this.cassandraSessionProvider = cassandraSessionProvider;
this.tenantAwareEntityTemplate = tenantAwareEntityTemplate;
this.tenantAwareCassandraMapperProvider = tenantAwareCassandraMapperProvider;
}
public void buildTable() {
final Create create = SchemaBuilder.createTable(TABLE_NAME)
.ifNotExists()
.addPartitionKey(APPLICATION_IDENTIFIER_COLUMN, DataType.text())
.addClusteringColumn(KEY_TIMESTAMP_COLUMN, DataType.text())
.addColumn(PUBLIC_KEY_MOD_COLUMN, DataType.varint())
.addColumn(PUBLIC_KEY_EXP_COLUMN, DataType.varint());
cassandraSessionProvider.getTenantSession().execute(create);
}
public void add(final ApplicationSignatureEntity entity) {
tenantAwareEntityTemplate.save(entity);
}
public Optional<ApplicationSignatureEntity> get(final String applicationIdentifier, final String keyTimestamp)
{
final ApplicationSignatureEntity entity =
tenantAwareCassandraMapperProvider.getMapper(ApplicationSignatureEntity.class).get(applicationIdentifier, keyTimestamp);
if (entity != null) {
Assert.notNull(entity.getApplicationIdentifier());
Assert.notNull(entity.getKeyTimestamp());
Assert.notNull(entity.getPublicKeyMod());
Assert.notNull(entity.getPublicKeyExp());
}
return Optional.ofNullable(entity);
}
public List<ApplicationSignatureEntity> getAll() {
final Mapper<ApplicationSignatureEntity> entityMapper = tenantAwareCassandraMapperProvider.getMapper(ApplicationSignatureEntity.class);
final Session tenantSession = cassandraSessionProvider.getTenantSession();
final Statement statement = QueryBuilder.select().all().from(TABLE_NAME);
return entityMapper.map(tenantSession.execute(statement)).all();
}
public void delete(final String applicationIdentifier) {
final Delete.Where deleteStatement = QueryBuilder.delete().from(TABLE_NAME)
.where(QueryBuilder.eq(APPLICATION_IDENTIFIER_COLUMN, applicationIdentifier));
cassandraSessionProvider.getTenantSession().execute(deleteStatement);
}
public boolean signaturesExistForApplication(final String applicationIdentifier) {
final Select.Where selectStatement = QueryBuilder.select().from(TABLE_NAME)
.where(QueryBuilder.eq(APPLICATION_IDENTIFIER_COLUMN, applicationIdentifier));
final ResultSet selected = cassandraSessionProvider.getTenantSession().execute(selectStatement);
final int count = selected.getAvailableWithoutFetching();
return count > 0;
}
} | 2,120 |
0 | Create_ds/fineract-cn-identity/service/src/main/java/org/apache/fineract/cn/identity/internal | Create_ds/fineract-cn-identity/service/src/main/java/org/apache/fineract/cn/identity/internal/repository/UserEntity.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.fineract.cn.identity.internal.repository;
import com.datastax.driver.core.LocalDate;
import com.datastax.driver.mapping.annotations.Column;
import com.datastax.driver.mapping.annotations.PartitionKey;
import com.datastax.driver.mapping.annotations.Table;
import java.nio.ByteBuffer;
/**
* @author Myrle Krantz
*/
@Table(name = Users.TABLE_NAME)
public class UserEntity {
@PartitionKey
@Column(name = Users.IDENTIFIER_COLUMN)
private String identifier;
@Column(name = Users.ROLE_COLUMN)
private String role;
@Column(name = Users.PASSWORD_COLUMN)
private ByteBuffer password;
@Column(name = Users.SALT_COLUMN)
private ByteBuffer salt;
@Column(name = Users.ITERATION_COUNT_COLUMN)
private int iterationCount;
@Column(name = Users.PASSWORD_EXPIRES_ON_COLUMN)
private LocalDate passwordExpiresOn;
public UserEntity() {}
public String getIdentifier() {
return identifier;
}
public void setIdentifier(String identifier) {
this.identifier = identifier;
}
public String getRole() {
return role;
}
public void setRole(String role) {
this.role = role;
}
public ByteBuffer getPassword() {
return password;
}
public void setPassword(ByteBuffer password) {
this.password = password;
}
public ByteBuffer getSalt() {
return salt;
}
public void setSalt(ByteBuffer salt) {
this.salt = salt;
}
public int getIterationCount() {
return iterationCount;
}
public void setIterationCount(int iterationCount) {
this.iterationCount = iterationCount;
}
public LocalDate getPasswordExpiresOn() {
return passwordExpiresOn;
}
public void setPasswordExpiresOn(LocalDate passwordExpiresOn) {
this.passwordExpiresOn = passwordExpiresOn;
}
}
| 2,121 |
0 | Create_ds/fineract-cn-identity/service/src/main/java/org/apache/fineract/cn/identity/internal | Create_ds/fineract-cn-identity/service/src/main/java/org/apache/fineract/cn/identity/internal/repository/ApplicationPermissionUsersEntity.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.fineract.cn.identity.internal.repository;
import com.datastax.driver.mapping.annotations.ClusteringColumn;
import com.datastax.driver.mapping.annotations.Column;
import com.datastax.driver.mapping.annotations.PartitionKey;
import com.datastax.driver.mapping.annotations.Table;
/**
* @author Myrle Krantz
*/
@SuppressWarnings({"unused", "WeakerAccess"})
@Table(name = ApplicationPermissionUsers.TABLE_NAME)
public class ApplicationPermissionUsersEntity {
@PartitionKey
@Column(name = ApplicationPermissionUsers.APPLICATION_IDENTIFIER_COLUMN)
private String applicationIdentifier;
@SuppressWarnings("DefaultAnnotationParam")
@ClusteringColumn(0)
@Column(name = ApplicationPermissionUsers.PERMITTABLE_GROUP_IDENTIFIER_COLUMN)
private String permittableGroupIdentifier;
@ClusteringColumn(1)
@Column(name = ApplicationPermissionUsers.USER_IDENTIFIER_COLUMN)
private String userIdentifier;
@Column(name = ApplicationPermissionUsers.ENABLED_COLUMN)
private Boolean enabled;
public ApplicationPermissionUsersEntity() {
}
public ApplicationPermissionUsersEntity(String applicationIdentifier, String permittableGroupIdentifier, String userIdentifier, Boolean enabled) {
this.applicationIdentifier = applicationIdentifier;
this.permittableGroupIdentifier = permittableGroupIdentifier;
this.userIdentifier = userIdentifier;
this.enabled = enabled;
}
public String getApplicationIdentifier() {
return applicationIdentifier;
}
public void setApplicationIdentifier(String applicationIdentifier) {
this.applicationIdentifier = applicationIdentifier;
}
public String getPermittableGroupIdentifier() {
return permittableGroupIdentifier;
}
public void setPermittableGroupIdentifier(String permittableGroupIdentifier) {
this.permittableGroupIdentifier = permittableGroupIdentifier;
}
public String getUserIdentifier() {
return userIdentifier;
}
public void setUserIdentifier(String userIdentifier) {
this.userIdentifier = userIdentifier;
}
public Boolean getEnabled() {
return enabled;
}
public void setEnabled(Boolean enabled) {
this.enabled = enabled;
}
} | 2,122 |
0 | Create_ds/fineract-cn-identity/service/src/main/java/org/apache/fineract/cn/identity/internal | Create_ds/fineract-cn-identity/service/src/main/java/org/apache/fineract/cn/identity/internal/repository/ApplicationPermissions.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.fineract.cn.identity.internal.repository;
import com.datastax.driver.core.DataType;
import com.datastax.driver.core.Session;
import com.datastax.driver.core.Statement;
import com.datastax.driver.core.querybuilder.QueryBuilder;
import com.datastax.driver.core.schemabuilder.Create;
import com.datastax.driver.core.schemabuilder.SchemaBuilder;
import com.datastax.driver.mapping.Mapper;
import org.apache.fineract.cn.cassandra.core.CassandraSessionProvider;
import org.apache.fineract.cn.cassandra.core.TenantAwareCassandraMapperProvider;
import org.apache.fineract.cn.cassandra.core.TenantAwareEntityTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;
/**
* @author Myrle Krantz
*/
@Component
public class ApplicationPermissions {
static final String TABLE_NAME = "isis_application_permissions";
static final String APPLICATION_IDENTIFIER_COLUMN = "application_identifier";
static final String PERMITTABLE_GROUP_IDENTIFIER_COLUMN = "permittable_group_identifier";
static final String PERMISSION_COLUMN = "permission";
private final CassandraSessionProvider cassandraSessionProvider;
private final TenantAwareEntityTemplate tenantAwareEntityTemplate;
private final TenantAwareCassandraMapperProvider tenantAwareCassandraMapperProvider;
@Autowired
public ApplicationPermissions(final CassandraSessionProvider cassandraSessionProvider,
final TenantAwareEntityTemplate tenantAwareEntityTemplate,
final TenantAwareCassandraMapperProvider tenantAwareCassandraMapperProvider) {
this.cassandraSessionProvider = cassandraSessionProvider;
this.tenantAwareEntityTemplate = tenantAwareEntityTemplate;
this.tenantAwareCassandraMapperProvider = tenantAwareCassandraMapperProvider;
}
public void buildTable() {
final Create create = SchemaBuilder.createTable(TABLE_NAME)
.ifNotExists()
.addPartitionKey(APPLICATION_IDENTIFIER_COLUMN, DataType.text())
.addClusteringColumn(PERMITTABLE_GROUP_IDENTIFIER_COLUMN, DataType.text())
.addUDTColumn(PERMISSION_COLUMN, SchemaBuilder.frozen(Permissions.TYPE_NAME));
cassandraSessionProvider.getTenantSession().execute(create);
}
public void add(final ApplicationPermissionEntity entity) {
tenantAwareEntityTemplate.save(entity);
}
public boolean exists(final String applicationIdentifier, final String permittableGroupIdentifier) {
return tenantAwareEntityTemplate.findById(ApplicationPermissionEntity.class, applicationIdentifier, permittableGroupIdentifier).isPresent();
}
public List<PermissionType> getAllPermissionsForApplication(final String applicationIdentifier) {
final List<ApplicationPermissionEntity> result = getAllApplicationPermissionEntitiesForApplication(applicationIdentifier);
return result.stream().map(ApplicationPermissionEntity::getPermission).collect(Collectors.toList());
}
private List<ApplicationPermissionEntity> getAllApplicationPermissionEntitiesForApplication(final String applicationIdentifier) {
final Mapper<ApplicationPermissionEntity> entityMapper = tenantAwareCassandraMapperProvider.getMapper(ApplicationPermissionEntity.class);
final Session tenantSession = cassandraSessionProvider.getTenantSession();
final Statement statement = QueryBuilder.select().from(TABLE_NAME).where(QueryBuilder.eq(APPLICATION_IDENTIFIER_COLUMN, applicationIdentifier));
return entityMapper.map(tenantSession.execute(statement)).all();
}
public void delete(final String applicationIdentifier, final String permittableGroupIdentifier) {
final Optional<ApplicationPermissionEntity> toDelete = tenantAwareEntityTemplate.findById(ApplicationPermissionEntity.class, applicationIdentifier, permittableGroupIdentifier);
toDelete.ifPresent(tenantAwareEntityTemplate::delete);
}
public Optional<PermissionType> getPermissionForApplication(
final String applicationIdentifier,
final String permittableEndpointGroupIdentifier) {
return tenantAwareEntityTemplate
.findById(ApplicationPermissionEntity.class, applicationIdentifier, permittableEndpointGroupIdentifier)
.map(ApplicationPermissionEntity::getPermission);
}
} | 2,123 |
0 | Create_ds/fineract-cn-identity/service/src/main/java/org/apache/fineract/cn/identity/internal | Create_ds/fineract-cn-identity/service/src/main/java/org/apache/fineract/cn/identity/internal/repository/Signatures.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.fineract.cn.identity.internal.repository;
import com.datastax.driver.core.BoundStatement;
import com.datastax.driver.core.DataType;
import com.datastax.driver.core.ResultSet;
import com.datastax.driver.core.exceptions.InvalidQueryException;
import com.datastax.driver.core.querybuilder.QueryBuilder;
import com.datastax.driver.core.querybuilder.Select;
import com.datastax.driver.core.querybuilder.Update;
import com.datastax.driver.core.schemabuilder.Create;
import com.datastax.driver.core.schemabuilder.SchemaBuilder;
import com.datastax.driver.core.schemabuilder.SchemaStatement;
import com.datastax.driver.mapping.Mapper;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import java.util.stream.StreamSupport;
import org.apache.fineract.cn.cassandra.core.CassandraSessionProvider;
import org.apache.fineract.cn.cassandra.core.TenantAwareCassandraMapperProvider;
import org.apache.fineract.cn.lang.security.RsaKeyPairFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
/**
* All write accesses are synchronized. These occur only during provisioning or key rotation, so they are not
* performance critical. These are only necessary because for some reason (that I have not yet been able to track
* down), provisioning is being called multiple times in rapid succession for a tenant.
*
* All calls to cassandra which could conceivably be performed before provisioning is complete are surrounded by
* a try-catch block for an InvalidQueryException. If provisioning is not completed, the table is treated as empty.
*
* @author Myrle Krantz
*/
@Component
public class Signatures {
static final String TABLE_NAME = "isis_signatures";
private static final String INDEX_NAME = "isis_signatures_valid_index";
static final String KEY_TIMESTAMP_COLUMN = "key_timestamp";
static final String VALID_COLUMN = "valid";
static final String PRIVATE_KEY_MOD_COLUMN = "private_key_mod";
static final String PRIVATE_KEY_EXP_COLUMN = "private_key_exp";
static final String PUBLIC_KEY_MOD_COLUMN = "public_key_mod";
static final String PUBLIC_KEY_EXP_COLUMN = "public_key_exp";
private final CassandraSessionProvider cassandraSessionProvider;
private final TenantAwareCassandraMapperProvider tenantAwareCassandraMapperProvider;
@Autowired
public Signatures(
final CassandraSessionProvider cassandraSessionProvider,
final TenantAwareCassandraMapperProvider tenantAwareCassandraMapperProvider) {
this.cassandraSessionProvider = cassandraSessionProvider;
this.tenantAwareCassandraMapperProvider = tenantAwareCassandraMapperProvider;
}
public synchronized void buildTable() {
final Create create = SchemaBuilder.createTable(TABLE_NAME)
.ifNotExists()
.addPartitionKey(KEY_TIMESTAMP_COLUMN, DataType.text())
.addColumn(VALID_COLUMN, DataType.cboolean())
.addColumn(PRIVATE_KEY_MOD_COLUMN, DataType.varint())
.addColumn(PRIVATE_KEY_EXP_COLUMN, DataType.varint())
.addColumn(PUBLIC_KEY_MOD_COLUMN, DataType.varint())
.addColumn(PUBLIC_KEY_EXP_COLUMN, DataType.varint());
cassandraSessionProvider.getTenantSession().execute(create);
final SchemaStatement createValidIndex = SchemaBuilder.createIndex(INDEX_NAME)
.ifNotExists()
.onTable(TABLE_NAME)
.andColumn(VALID_COLUMN);
cassandraSessionProvider.getTenantSession().execute(createValidIndex);
}
public synchronized SignatureEntity add(final RsaKeyPairFactory.KeyPairHolder keys)
{
//There will only be one entry in this table.
final BoundStatement tenantCreationStatement =
cassandraSessionProvider.getTenantSession().prepare("INSERT INTO " + TABLE_NAME + " ("
+ KEY_TIMESTAMP_COLUMN + ", "
+ VALID_COLUMN + ", "
+ PRIVATE_KEY_MOD_COLUMN + ", "
+ PRIVATE_KEY_EXP_COLUMN + ", "
+ PUBLIC_KEY_MOD_COLUMN + ", "
+ PUBLIC_KEY_EXP_COLUMN + ")"
+ "VALUES (?, ?, ?, ?, ?, ?)").bind();
tenantCreationStatement.setString(KEY_TIMESTAMP_COLUMN, keys.getTimestamp());
tenantCreationStatement.setBool(VALID_COLUMN, true);
tenantCreationStatement.setVarint(PRIVATE_KEY_MOD_COLUMN, keys.getPrivateKeyMod());
tenantCreationStatement.setVarint(PRIVATE_KEY_EXP_COLUMN, keys.getPrivateKeyExp());
tenantCreationStatement.setVarint(PUBLIC_KEY_MOD_COLUMN, keys.getPublicKeyMod());
tenantCreationStatement.setVarint(PUBLIC_KEY_EXP_COLUMN, keys.getPublicKeyExp());
cassandraSessionProvider.getTenantSession().execute(tenantCreationStatement);
final SignatureEntity ret = new SignatureEntity();
ret.setKeyTimestamp(keys.getTimestamp());
ret.setPublicKeyMod(keys.getPublicKeyMod());
ret.setPublicKeyExp(keys.getPublicKeyExp());
ret.setValid(true);
return ret;
}
public Optional<SignatureEntity> getSignature(final String keyTimestamp) {
try {
final Mapper<SignatureEntity> signatureEntityMapper
= tenantAwareCassandraMapperProvider.getMapper(SignatureEntity.class);
final Optional<SignatureEntity> ret = Optional.ofNullable(signatureEntityMapper.get(keyTimestamp));
return ret.filter(SignatureEntity::getValid);
}
catch (final InvalidQueryException e) {
return Optional.empty();
}
}
/**
* @return the most current valid private key pair with key timestamp. If there are no valid key pairs, returns Optional.empty.
*/
public Optional<PrivateSignatureEntity> getPrivateSignature()
{
final Optional<String> maximumKeyTimestamp = streamValidKeyTimestamps().max(String::compareTo);
return maximumKeyTimestamp.flatMap(this::getPrivateSignatureEntity);
}
private Optional<PrivateSignatureEntity> getPrivateSignatureEntity(final String keyTimestamp) {
try {
final Mapper<PrivateSignatureEntity> privateSignatureEntityMapper
= tenantAwareCassandraMapperProvider.getMapper(PrivateSignatureEntity.class);
final Optional<PrivateSignatureEntity> ret = Optional.ofNullable(privateSignatureEntityMapper.get(keyTimestamp));
return ret.filter(PrivateSignatureEntity::getValid);
}
catch (final InvalidQueryException e) {
return Optional.empty();
}
}
public List<String> getAllKeyTimestamps() {
return streamValidKeyTimestamps().collect(Collectors.toList());
}
private Stream<String> streamValidKeyTimestamps() {
try {
final Select.Where selectValid = QueryBuilder.select(KEY_TIMESTAMP_COLUMN)
.from(TABLE_NAME)
.where(QueryBuilder.eq(VALID_COLUMN, true));
final ResultSet result = cassandraSessionProvider.getTenantSession().execute(selectValid);
return StreamSupport.stream(result.spliterator(), false)
.map(x -> x.get(KEY_TIMESTAMP_COLUMN, String.class));
}
catch (final InvalidQueryException e) {
return Stream.empty();
}
}
public synchronized void invalidateEntry(final String keyTimestamp) {
final Update.Assignments updateQuery = QueryBuilder.update(TABLE_NAME).where(QueryBuilder.eq(KEY_TIMESTAMP_COLUMN, keyTimestamp)).with(QueryBuilder.set(VALID_COLUMN, false));
cassandraSessionProvider.getTenantSession().execute(updateQuery);
}
}
| 2,124 |
0 | Create_ds/fineract-cn-identity/service/src/main/java/org/apache/fineract/cn/identity/internal | Create_ds/fineract-cn-identity/service/src/main/java/org/apache/fineract/cn/identity/internal/repository/PrivateSignatureEntity.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.fineract.cn.identity.internal.repository;
import com.datastax.driver.mapping.annotations.Column;
import com.datastax.driver.mapping.annotations.PartitionKey;
import com.datastax.driver.mapping.annotations.Table;
import java.math.BigInteger;
/**
* @author Myrle Krantz
*/
@SuppressWarnings("WeakerAccess")
@Table(name = Signatures.TABLE_NAME)
public class PrivateSignatureEntity {
@PartitionKey
@Column(name = Signatures.KEY_TIMESTAMP_COLUMN)
private String keyTimestamp;
@Column(name = Signatures.VALID_COLUMN)
private Boolean valid;
@Column(name = Signatures.PRIVATE_KEY_MOD_COLUMN)
private BigInteger privateKeyMod;
@Column(name = Signatures.PRIVATE_KEY_EXP_COLUMN)
private BigInteger privateKeyExp;
public String getKeyTimestamp() {
return keyTimestamp;
}
public void setKeyTimestamp(String keyTimestamp) {
this.keyTimestamp = keyTimestamp;
}
public Boolean getValid() {
return valid;
}
public void setValid(Boolean valid) {
this.valid = valid;
}
public BigInteger getPrivateKeyMod() {
return privateKeyMod;
}
public void setPrivateKeyMod(BigInteger privateKeyMod) {
this.privateKeyMod = privateKeyMod;
}
public BigInteger getPrivateKeyExp() {
return privateKeyExp;
}
public void setPrivateKeyExp(BigInteger privateKeyExp) {
this.privateKeyExp = privateKeyExp;
}
}
| 2,125 |
0 | Create_ds/fineract-cn-identity/service/src/main/java/org/apache/fineract/cn/identity/internal | Create_ds/fineract-cn-identity/service/src/main/java/org/apache/fineract/cn/identity/internal/repository/Users.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.fineract.cn.identity.internal.repository;
import com.datastax.driver.core.DataType;
import com.datastax.driver.core.Session;
import com.datastax.driver.core.Statement;
import com.datastax.driver.core.querybuilder.QueryBuilder;
import com.datastax.driver.core.schemabuilder.Create;
import com.datastax.driver.core.schemabuilder.SchemaBuilder;
import com.datastax.driver.mapping.Mapper;
import org.apache.fineract.cn.cassandra.core.CassandraSessionProvider;
import org.apache.fineract.cn.cassandra.core.TenantAwareCassandraMapperProvider;
import org.apache.fineract.cn.cassandra.core.TenantAwareEntityTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.Assert;
import java.util.List;
import java.util.Optional;
/**
* @author Myrle Krantz
*/
@Component
public class Users {
static final String TABLE_NAME = "isis_users";
static final String IDENTIFIER_COLUMN = "identifier";
static final String ROLE_COLUMN = "roleIdentifier";
static final String PASSWORD_COLUMN = "passwordWord";
static final String PASSWORD_EXPIRES_ON_COLUMN = "password_expires_on";
static final String SALT_COLUMN = "salt";
static final String ITERATION_COUNT_COLUMN = "iteration_count";
private final CassandraSessionProvider cassandraSessionProvider;
private final TenantAwareEntityTemplate tenantAwareEntityTemplate;
private final TenantAwareCassandraMapperProvider tenantAwareCassandraMapperProvider;
@Autowired
Users(final CassandraSessionProvider cassandraSessionProvider,
final TenantAwareEntityTemplate tenantAwareEntityTemplate,
final TenantAwareCassandraMapperProvider tenantAwareCassandraMapperProvider)
{
this.cassandraSessionProvider = cassandraSessionProvider;
this.tenantAwareEntityTemplate = tenantAwareEntityTemplate;
this.tenantAwareCassandraMapperProvider = tenantAwareCassandraMapperProvider;
}
public void buildTable() {
final Create create = SchemaBuilder.createTable(TABLE_NAME)
.ifNotExists()
.addPartitionKey(IDENTIFIER_COLUMN, DataType.text())
.addColumn(ROLE_COLUMN, DataType.text())
.addColumn(PASSWORD_COLUMN, DataType.blob())
.addColumn(SALT_COLUMN, DataType.blob())
.addColumn(ITERATION_COUNT_COLUMN, DataType.cint())
.addColumn(PASSWORD_EXPIRES_ON_COLUMN, DataType.date());
cassandraSessionProvider.getTenantSession().execute(create);
}
public void add(final UserEntity instance) {
tenantAwareEntityTemplate.save(instance);
}
public Optional<UserEntity> get(final String identifier)
{
final UserEntity instance =
tenantAwareCassandraMapperProvider.getMapper(UserEntity.class).get(identifier);
if (instance != null) {
Assert.notNull(instance.getIdentifier());
Assert.notNull(instance.getRole());
Assert.notNull(instance.getPassword());
}
return Optional.ofNullable(instance);
}
public List<UserEntity> getAll()
{
final Mapper<UserEntity> entityMapper = tenantAwareCassandraMapperProvider.getMapper(UserEntity.class);
final Session tenantSession = cassandraSessionProvider.getTenantSession();
final Statement statement = QueryBuilder.select().all().from(TABLE_NAME);
return entityMapper.map(tenantSession.execute(statement)).all();
}
}
| 2,126 |
0 | Create_ds/fineract-cn-identity/service/src/main/java/org/apache/fineract/cn/identity/internal | Create_ds/fineract-cn-identity/service/src/main/java/org/apache/fineract/cn/identity/internal/repository/ApplicationCallEndpointSetEntity.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.fineract.cn.identity.internal.repository;
import com.datastax.driver.mapping.annotations.ClusteringColumn;
import com.datastax.driver.mapping.annotations.Column;
import com.datastax.driver.mapping.annotations.PartitionKey;
import com.datastax.driver.mapping.annotations.Table;
import java.util.List;
/**
* @author Myrle Krantz
*/
@Table(name = ApplicationCallEndpointSets.TABLE_NAME)
public class ApplicationCallEndpointSetEntity {
@PartitionKey
@Column(name = ApplicationCallEndpointSets.APPLICATION_IDENTIFIER_COLUMN)
private String applicationIdentifier;
@ClusteringColumn
@Column(name = ApplicationCallEndpointSets.CALLENDPOINTSET_IDENTIFIER_COLUMN)
private String callEndpointSetIdentifier;
@Column(name = ApplicationCallEndpointSets.CALLENDPOINT_GROUP_IDENTIFIERS_COLUMN)
private List<String> callEndpointGroupIdentifiers;
public ApplicationCallEndpointSetEntity() {
}
public String getApplicationIdentifier() {
return applicationIdentifier;
}
public void setApplicationIdentifier(String applicationIdentifier) {
this.applicationIdentifier = applicationIdentifier;
}
public String getCallEndpointSetIdentifier() {
return callEndpointSetIdentifier;
}
public void setCallEndpointSetIdentifier(String callEndpointSetIdentifier) {
this.callEndpointSetIdentifier = callEndpointSetIdentifier;
}
public List<String> getCallEndpointGroupIdentifiers() {
return callEndpointGroupIdentifiers;
}
public void setCallEndpointGroupIdentifiers(List<String> callEndpointGroupIdentifiers) {
this.callEndpointGroupIdentifiers = callEndpointGroupIdentifiers;
}
}
| 2,127 |
0 | Create_ds/fineract-cn-identity/service/src/main/java/org/apache/fineract/cn/identity/internal | Create_ds/fineract-cn-identity/service/src/main/java/org/apache/fineract/cn/identity/internal/repository/PrivateTenantInfoEntity.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.fineract.cn.identity.internal.repository;
import com.datastax.driver.mapping.annotations.Column;
import com.datastax.driver.mapping.annotations.PartitionKey;
import com.datastax.driver.mapping.annotations.Table;
import java.nio.ByteBuffer;
/**
* @author Myrle Krantz
*/
@SuppressWarnings("unused")
@Table(name = Tenants.TABLE_NAME)
public class PrivateTenantInfoEntity {
@PartitionKey
@Column(name = Tenants.VERSION_COLUMN)
private int version;
@Column(name = Tenants.FIXED_SALT_COLUMN)
private ByteBuffer fixedSalt;
@Column(name = Tenants.PASSWORD_EXPIRES_IN_DAYS_COLUMN)
private int passwordExpiresInDays;
@Column(name = Tenants.TIME_TO_CHANGE_PASSWORD_AFTER_EXPIRATION_IN_DAYS)
private int timeToChangePasswordAfterExpirationInDays;
public PrivateTenantInfoEntity() { }
public int getVersion() {
return version;
}
public void setVersion(int version) {
this.version = version;
}
public ByteBuffer getFixedSalt() {
return fixedSalt;
}
public void setFixedSalt(ByteBuffer fixedSalt) {
this.fixedSalt = fixedSalt;
}
public int getPasswordExpiresInDays() {
return passwordExpiresInDays;
}
public void setPasswordExpiresInDays(final int passwordExpiresInDays) {
this.passwordExpiresInDays = passwordExpiresInDays;
}
public int getTimeToChangePasswordAfterExpirationInDays() {
return timeToChangePasswordAfterExpirationInDays;
}
public void setTimeToChangePasswordAfterExpirationInDays(int timeToChangePasswordAfterExpirationInDays) {
this.timeToChangePasswordAfterExpirationInDays = timeToChangePasswordAfterExpirationInDays;
}
}
| 2,128 |
0 | Create_ds/fineract-cn-identity/service/src/main/java/org/apache/fineract/cn/identity/internal | Create_ds/fineract-cn-identity/service/src/main/java/org/apache/fineract/cn/identity/internal/repository/ApplicationCallEndpointSets.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.fineract.cn.identity.internal.repository;
import com.datastax.driver.core.DataType;
import com.datastax.driver.core.Session;
import com.datastax.driver.core.Statement;
import com.datastax.driver.core.querybuilder.QueryBuilder;
import com.datastax.driver.core.schemabuilder.Create;
import com.datastax.driver.core.schemabuilder.SchemaBuilder;
import com.datastax.driver.mapping.Mapper;
import org.apache.fineract.cn.cassandra.core.CassandraSessionProvider;
import org.apache.fineract.cn.cassandra.core.TenantAwareCassandraMapperProvider;
import org.apache.fineract.cn.cassandra.core.TenantAwareEntityTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.Assert;
import java.util.List;
import java.util.Optional;
/**
* @author Myrle Krantz
*/
@Component
public class ApplicationCallEndpointSets {
static final String TABLE_NAME = "isis_application_callendpointsets";
static final String APPLICATION_IDENTIFIER_COLUMN = "application_identifier";
static final String CALLENDPOINTSET_IDENTIFIER_COLUMN = "call_endpoint_set_identifier";
static final String CALLENDPOINT_GROUP_IDENTIFIERS_COLUMN = "call_endpoint_group_identifiers";
private final CassandraSessionProvider cassandraSessionProvider;
private final TenantAwareEntityTemplate tenantAwareEntityTemplate;
private final TenantAwareCassandraMapperProvider tenantAwareCassandraMapperProvider;
@Autowired
public ApplicationCallEndpointSets(
final CassandraSessionProvider cassandraSessionProvider,
final TenantAwareEntityTemplate tenantAwareEntityTemplate,
final TenantAwareCassandraMapperProvider tenantAwareCassandraMapperProvider) {
this.cassandraSessionProvider = cassandraSessionProvider;
this.tenantAwareEntityTemplate = tenantAwareEntityTemplate;
this.tenantAwareCassandraMapperProvider = tenantAwareCassandraMapperProvider;
}
public void buildTable() {
final Create create = SchemaBuilder.createTable(TABLE_NAME)
.ifNotExists()
.addPartitionKey(APPLICATION_IDENTIFIER_COLUMN, DataType.text())
.addClusteringColumn(CALLENDPOINTSET_IDENTIFIER_COLUMN, DataType.text())
.addColumn(CALLENDPOINT_GROUP_IDENTIFIERS_COLUMN, DataType.list(DataType.text()));
cassandraSessionProvider.getTenantSession().execute(create);
}
public void add(final ApplicationCallEndpointSetEntity entity) {
tenantAwareEntityTemplate.save(entity);
}
public void change(final ApplicationCallEndpointSetEntity instance) {
tenantAwareEntityTemplate.save(instance);
}
public Optional<ApplicationCallEndpointSetEntity> get(final String applicationIdentifier, final String callEndpointSetIdentifier)
{
final ApplicationCallEndpointSetEntity entity =
tenantAwareCassandraMapperProvider.getMapper(ApplicationCallEndpointSetEntity.class).get(applicationIdentifier, callEndpointSetIdentifier);
if (entity != null) {
Assert.notNull(entity.getApplicationIdentifier());
Assert.notNull(entity.getCallEndpointSetIdentifier());
}
return Optional.ofNullable(entity);
}
public List<ApplicationCallEndpointSetEntity> getAllForApplication(final String applicationIdentifier) {
final Mapper<ApplicationCallEndpointSetEntity> entityMapper = tenantAwareCassandraMapperProvider.getMapper(ApplicationCallEndpointSetEntity.class);
final Session tenantSession = cassandraSessionProvider.getTenantSession();
final Statement statement = QueryBuilder.select().from(TABLE_NAME).where(QueryBuilder.eq(APPLICATION_IDENTIFIER_COLUMN, applicationIdentifier));
return entityMapper.map(tenantSession.execute(statement)).all();
}
public void delete(final String applicationIdentifier, final String callEndpointSetIdentifier) {
final Optional<ApplicationCallEndpointSetEntity> toDelete = tenantAwareEntityTemplate.findById(ApplicationCallEndpointSetEntity.class, applicationIdentifier, callEndpointSetIdentifier);
toDelete.ifPresent(tenantAwareEntityTemplate::delete);
}
}
| 2,129 |
0 | Create_ds/fineract-cn-identity/service/src/main/java/org/apache/fineract/cn/identity/internal | Create_ds/fineract-cn-identity/service/src/main/java/org/apache/fineract/cn/identity/internal/repository/ApplicationPermissionEntity.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.fineract.cn.identity.internal.repository;
import com.datastax.driver.mapping.annotations.ClusteringColumn;
import com.datastax.driver.mapping.annotations.Column;
import com.datastax.driver.mapping.annotations.PartitionKey;
import com.datastax.driver.mapping.annotations.Table;
/**
* @author Myrle Krantz
*/
@Table(name = ApplicationPermissions.TABLE_NAME)
public class ApplicationPermissionEntity {
@PartitionKey
@Column(name = ApplicationPermissions.APPLICATION_IDENTIFIER_COLUMN)
private String applicationIdentifier;
@ClusteringColumn
@Column(name = ApplicationPermissions.PERMITTABLE_GROUP_IDENTIFIER_COLUMN)
private String permittableGroupIdentifier;
@Column(name = ApplicationPermissions.PERMISSION_COLUMN)
private PermissionType permission;
public ApplicationPermissionEntity() {
}
public ApplicationPermissionEntity(final String applicationIdentifier, final PermissionType permission) {
this.applicationIdentifier = applicationIdentifier;
this.permittableGroupIdentifier = permission.getPermittableGroupIdentifier();
this.permission = permission;
}
public String getApplicationIdentifier() {
return applicationIdentifier;
}
public void setApplicationIdentifier(String applicationIdentifier) {
this.applicationIdentifier = applicationIdentifier;
}
public String getPermittableGroupIdentifier() {
return permittableGroupIdentifier;
}
public void setPermittableGroupIdentifier(String permittableGroupIdentifier) {
this.permittableGroupIdentifier = permittableGroupIdentifier;
}
public PermissionType getPermission() {
return permission;
}
public void setPermission(PermissionType permission) {
this.permission = permission;
}
}
| 2,130 |
0 | Create_ds/fineract-cn-identity/service/src/main/java/org/apache/fineract/cn/identity/internal | Create_ds/fineract-cn-identity/service/src/main/java/org/apache/fineract/cn/identity/internal/repository/ApplicationPermissionUsers.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.fineract.cn.identity.internal.repository;
import com.datastax.driver.core.DataType;
import com.datastax.driver.core.schemabuilder.Create;
import com.datastax.driver.core.schemabuilder.SchemaBuilder;
import org.apache.fineract.cn.cassandra.core.CassandraSessionProvider;
import org.apache.fineract.cn.cassandra.core.TenantAwareEntityTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
/**
* @author Myrle Krantz
*/
@Component
public class ApplicationPermissionUsers {
static final String TABLE_NAME = "isis_application_permission_users";
static final String APPLICATION_IDENTIFIER_COLUMN = "application_identifier";
static final String PERMITTABLE_GROUP_IDENTIFIER_COLUMN = "permittable_group_identifier";
static final String USER_IDENTIFIER_COLUMN = "user_identifier";
static final String ENABLED_COLUMN = "enabled";
private final CassandraSessionProvider cassandraSessionProvider;
private final TenantAwareEntityTemplate tenantAwareEntityTemplate;
@Autowired
public ApplicationPermissionUsers(final CassandraSessionProvider cassandraSessionProvider,
final TenantAwareEntityTemplate tenantAwareEntityTemplate) {
this.cassandraSessionProvider = cassandraSessionProvider;
this.tenantAwareEntityTemplate = tenantAwareEntityTemplate;
}
public void buildTable() {
final Create create = SchemaBuilder.createTable(TABLE_NAME)
.ifNotExists()
.addPartitionKey(APPLICATION_IDENTIFIER_COLUMN, DataType.text())
.addClusteringColumn(PERMITTABLE_GROUP_IDENTIFIER_COLUMN, DataType.text())
.addClusteringColumn(USER_IDENTIFIER_COLUMN, DataType.text())
.addColumn(ENABLED_COLUMN, DataType.cboolean());
cassandraSessionProvider.getTenantSession().execute(create);
}
public boolean enabled(final String applicationIdentifier,
final String permittableEndpointGroupIdentifier,
final String userIdentifier) {
return tenantAwareEntityTemplate.findById(
ApplicationPermissionUsersEntity.class, applicationIdentifier, permittableEndpointGroupIdentifier, userIdentifier)
.map(ApplicationPermissionUsersEntity::getEnabled)
.orElse(false);
}
public void setEnabled(final String applicationIdentifier,
final String permittableGroupIdentifier,
final String userIdentifier,
final boolean enabled) {
tenantAwareEntityTemplate.save(new ApplicationPermissionUsersEntity(applicationIdentifier, permittableGroupIdentifier, userIdentifier, enabled));
}
}
| 2,131 |
0 | Create_ds/fineract-cn-identity/service/src/main/java/org/apache/fineract/cn/identity/internal | Create_ds/fineract-cn-identity/service/src/main/java/org/apache/fineract/cn/identity/internal/repository/PermittableType.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.fineract.cn.identity.internal.repository;
import com.datastax.driver.mapping.annotations.Field;
import com.datastax.driver.mapping.annotations.UDT;
import java.util.Objects;
/**
* @author Myrle Krantz
*/
@SuppressWarnings({"unused", "WeakerAccess"})
@UDT(name = PermittableGroups.TYPE_NAME)
public class PermittableType {
@Field(name = PermittableGroups.PATH_FIELD)
private String path;
@Field(name = PermittableGroups.METHOD_FIELD)
private String method;
@Field(name = PermittableGroups.SOURCE_GROUP_ID_FIELD)
private String sourceGroupId;
public String getPath() {
return path;
}
public void setPath(String path) {
this.path = path;
}
public String getMethod() {
return method;
}
public void setMethod(String method) {
this.method = method;
}
public String getSourceGroupId() {
return sourceGroupId;
}
public void setSourceGroupId(String sourceGroupId) {
this.sourceGroupId = sourceGroupId;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
PermittableType that = (PermittableType) o;
return Objects.equals(path, that.path) &&
Objects.equals(method, that.method) &&
Objects.equals(sourceGroupId, that.sourceGroupId);
}
@Override
public int hashCode() {
return Objects.hash(path, method, sourceGroupId);
}
@Override
public String toString() {
return "PermittableType{" +
"path='" + path + '\'' +
", method='" + method + '\'' +
", sourceGroupId='" + sourceGroupId + '\'' +
'}';
}
}
| 2,132 |
0 | Create_ds/fineract-cn-identity/service/src/main/java/org/apache/fineract/cn/identity/internal | Create_ds/fineract-cn-identity/service/src/main/java/org/apache/fineract/cn/identity/internal/repository/SignatureEntity.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.fineract.cn.identity.internal.repository;
import com.datastax.driver.mapping.annotations.Column;
import com.datastax.driver.mapping.annotations.PartitionKey;
import com.datastax.driver.mapping.annotations.Table;
import java.math.BigInteger;
/**
* @author Myrle Krantz
*/
@SuppressWarnings({"unused", "WeakerAccess"})
@Table(name = Signatures.TABLE_NAME)
public class SignatureEntity {
@PartitionKey
@Column(name = Signatures.KEY_TIMESTAMP_COLUMN)
private String keyTimestamp;
@Column(name = Signatures.VALID_COLUMN)
private Boolean valid;
@Column(name = Signatures.PUBLIC_KEY_MOD_COLUMN)
private BigInteger publicKeyMod;
@Column(name = Signatures.PUBLIC_KEY_EXP_COLUMN)
private BigInteger publicKeyExp;
public SignatureEntity() { }
public String getKeyTimestamp() {
return keyTimestamp;
}
public void setKeyTimestamp(String keyTimestamp) {
this.keyTimestamp = keyTimestamp;
}
public Boolean getValid() {
return valid;
}
public void setValid(Boolean valid) {
this.valid = valid;
}
public BigInteger getPublicKeyMod() {
return publicKeyMod;
}
public void setPublicKeyMod(BigInteger publicKeyMod) {
this.publicKeyMod = publicKeyMod;
}
public BigInteger getPublicKeyExp() {
return publicKeyExp;
}
public void setPublicKeyExp(BigInteger publicKeyExp) {
this.publicKeyExp = publicKeyExp;
}
}
| 2,133 |
0 | Create_ds/fineract-cn-identity/service/src/main/java/org/apache/fineract/cn/identity/internal | Create_ds/fineract-cn-identity/service/src/main/java/org/apache/fineract/cn/identity/internal/repository/Roles.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.fineract.cn.identity.internal.repository;
import com.datastax.driver.core.DataType;
import com.datastax.driver.core.Session;
import com.datastax.driver.core.Statement;
import com.datastax.driver.core.querybuilder.QueryBuilder;
import com.datastax.driver.core.schemabuilder.Create;
import com.datastax.driver.core.schemabuilder.SchemaBuilder;
import com.datastax.driver.mapping.Mapper;
import org.apache.fineract.cn.cassandra.core.CassandraSessionProvider;
import org.apache.fineract.cn.cassandra.core.TenantAwareCassandraMapperProvider;
import org.apache.fineract.cn.cassandra.core.TenantAwareEntityTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.Assert;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
/**
* @author Myrle Krantz
*/
@Component
public class Roles {
static final String TABLE_NAME = "isis_roles";
static final String IDENTIFIER_COLUMN = "identifier";
static final String PERMISSIONS_COLUMN = "permissions";
private final CassandraSessionProvider cassandraSessionProvider;
private final TenantAwareEntityTemplate tenantAwareEntityTemplate;
private final TenantAwareCassandraMapperProvider tenantAwareCassandraMapperProvider;
@Autowired
Roles(
final CassandraSessionProvider cassandraSessionProvider,
final TenantAwareEntityTemplate tenantAwareEntityTemplate,
final TenantAwareCassandraMapperProvider tenantAwareCassandraMapperProvider) {
this.cassandraSessionProvider = cassandraSessionProvider;
this.tenantAwareEntityTemplate = tenantAwareEntityTemplate;
this.tenantAwareCassandraMapperProvider = tenantAwareCassandraMapperProvider;
}
public void buildTable() {
final Create create = SchemaBuilder.createTable(TABLE_NAME)
.ifNotExists()
.addPartitionKey(IDENTIFIER_COLUMN, DataType.text())
.addUDTListColumn(PERMISSIONS_COLUMN, SchemaBuilder.frozen(Permissions.TYPE_NAME));
cassandraSessionProvider.getTenantSession().execute(create);
}
public void add(final RoleEntity instance) {
tenantAwareEntityTemplate.save(instance);
}
public void change(final RoleEntity instance) {
tenantAwareEntityTemplate.save(instance);
}
public Optional<RoleEntity> get(final String identifier)
{
final RoleEntity instance =
tenantAwareCassandraMapperProvider.getMapper(RoleEntity.class).get(identifier);
if (instance != null) {
Assert.notNull(instance.getIdentifier());
Assert.notNull(instance.getPermissions());
}
return Optional.ofNullable(instance);
}
public void delete(final RoleEntity instance) {
tenantAwareEntityTemplate.delete(instance);
}
public List<RoleEntity> getAll()
{
final Session tenantSession = cassandraSessionProvider.getTenantSession();
final Mapper<RoleEntity> entityMapper = tenantAwareCassandraMapperProvider.getMapper(RoleEntity.class);
final Statement statement = QueryBuilder.select().all().from(TABLE_NAME);
return new ArrayList<>(entityMapper.map(tenantSession.execute(statement)).all());
}
}
| 2,134 |
0 | Create_ds/fineract-cn-identity/service/src/main/java/org/apache/fineract/cn/identity/internal | Create_ds/fineract-cn-identity/service/src/main/java/org/apache/fineract/cn/identity/internal/repository/Tenants.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.fineract.cn.identity.internal.repository;
import com.datastax.driver.core.BoundStatement;
import com.datastax.driver.core.DataType;
import com.datastax.driver.core.schemabuilder.Create;
import com.datastax.driver.core.schemabuilder.SchemaBuilder;
import java.nio.ByteBuffer;
import java.util.Optional;
import org.apache.fineract.cn.cassandra.core.CassandraSessionProvider;
import org.apache.fineract.cn.cassandra.core.TenantAwareEntityTemplate;
import org.apache.fineract.cn.identity.internal.util.IdentityConstants;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
/**
* @author Myrle Krantz
*/
@Component
public class Tenants {
static final String TABLE_NAME = "isis_tenant";
static final String VERSION_COLUMN = "version";
static final String FIXED_SALT_COLUMN = "fixed_salt";
static final String PASSWORD_EXPIRES_IN_DAYS_COLUMN = "password_expires_in_days";
static final String TIME_TO_CHANGE_PASSWORD_AFTER_EXPIRATION_IN_DAYS = "time_to_change_password_after_expiration_in_days";
private final CassandraSessionProvider cassandraSessionProvider;
private final TenantAwareEntityTemplate tenantAwareEntityTemplate;
@Autowired
Tenants(final CassandraSessionProvider cassandraSessionProvider,
final TenantAwareEntityTemplate tenantAwareEntityTemplate)
{
this.cassandraSessionProvider = cassandraSessionProvider;
this.tenantAwareEntityTemplate = tenantAwareEntityTemplate;
}
public void buildTable() {
final Create create = SchemaBuilder.createTable(TABLE_NAME)
.ifNotExists()
.addPartitionKey(VERSION_COLUMN, DataType.cint())
.addColumn(FIXED_SALT_COLUMN, DataType.blob())
.addColumn(PASSWORD_EXPIRES_IN_DAYS_COLUMN, DataType.cint())
.addColumn(TIME_TO_CHANGE_PASSWORD_AFTER_EXPIRATION_IN_DAYS, DataType.cint());
cassandraSessionProvider.getTenantSession().execute(create);
}
public void add(
final byte[] fixedSalt,
final int passwordExpiresInDays,
final int timeToChangePasswordAfterExpirationInDays)
{
//There will only be one entry in this table.
final BoundStatement tenantCreationStatement =
cassandraSessionProvider.getTenantSession().prepare("INSERT INTO " + Tenants.TABLE_NAME + " ("
+ VERSION_COLUMN + ", "
+ FIXED_SALT_COLUMN + ", "
+ PASSWORD_EXPIRES_IN_DAYS_COLUMN + ", "
+ TIME_TO_CHANGE_PASSWORD_AFTER_EXPIRATION_IN_DAYS + ")"
+ "VALUES (?, ?, ?, ?)").bind();
tenantCreationStatement.setInt(VERSION_COLUMN, IdentityConstants.CURRENT_VERSION);
tenantCreationStatement.setBytes(FIXED_SALT_COLUMN, ByteBuffer.wrap(fixedSalt));
tenantCreationStatement.setInt(PASSWORD_EXPIRES_IN_DAYS_COLUMN, passwordExpiresInDays);
tenantCreationStatement.setInt(TIME_TO_CHANGE_PASSWORD_AFTER_EXPIRATION_IN_DAYS, timeToChangePasswordAfterExpirationInDays);
cassandraSessionProvider.getTenantSession().execute(tenantCreationStatement);
}
public Optional<PrivateTenantInfoEntity> getPrivateTenantInfo()
{
return tenantAwareEntityTemplate
.findById(PrivateTenantInfoEntity.class, IdentityConstants.CURRENT_VERSION);
}
}
| 2,135 |
0 | Create_ds/fineract-cn-identity/service/src/main/java/org/apache/fineract/cn/identity/internal | Create_ds/fineract-cn-identity/service/src/main/java/org/apache/fineract/cn/identity/internal/repository/Permissions.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.fineract.cn.identity.internal.repository;
import com.datastax.driver.core.DataType;
import com.datastax.driver.core.schemabuilder.SchemaBuilder;
import org.apache.fineract.cn.cassandra.core.CassandraSessionProvider;
import org.apache.fineract.cn.cassandra.util.CodecRegistry;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import javax.annotation.PostConstruct;
/**
* @author Myrle Krantz
*/
@Component
public class Permissions {
static final String TYPE_NAME = "isis_permission";
static final String PERMITTABLE_GROUP_IDENTIFIER_FIELD = "permittable_group_identifier";
static final String ALLOWED_OPERATIONS_FIELD = "allowed_operations";
private final CassandraSessionProvider cassandraSessionProvider;
@Autowired
public Permissions(final CassandraSessionProvider cassandraSessionProvider) {
this.cassandraSessionProvider = cassandraSessionProvider;
}
@SuppressWarnings("unchecked")
@PostConstruct
public void initialize()
{
CodecRegistry.register(AllowedOperationType.getCodec());
}
public void buildType() {
final String type_statement =
SchemaBuilder.createType(TYPE_NAME)
.ifNotExists()
.addColumn(PERMITTABLE_GROUP_IDENTIFIER_FIELD, DataType.text())
.addColumn(ALLOWED_OPERATIONS_FIELD, DataType.set(DataType.text()))
.buildInternal();
cassandraSessionProvider.getTenantSession().execute(type_statement);
}
}
| 2,136 |
0 | Create_ds/fineract-cn-identity/service/src/main/java/org/apache/fineract/cn/identity/internal | Create_ds/fineract-cn-identity/service/src/main/java/org/apache/fineract/cn/identity/internal/repository/PermittableGroups.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.fineract.cn.identity.internal.repository;
import com.datastax.driver.core.DataType;
import com.datastax.driver.core.Session;
import com.datastax.driver.core.Statement;
import com.datastax.driver.core.querybuilder.QueryBuilder;
import com.datastax.driver.core.schemabuilder.Create;
import com.datastax.driver.core.schemabuilder.CreateType;
import com.datastax.driver.core.schemabuilder.SchemaBuilder;
import com.datastax.driver.mapping.Mapper;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import org.apache.fineract.cn.cassandra.core.CassandraSessionProvider;
import org.apache.fineract.cn.cassandra.core.TenantAwareCassandraMapperProvider;
import org.apache.fineract.cn.cassandra.core.TenantAwareEntityTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.Assert;
/**
* @author Myrle Krantz
*/
@Component
public class PermittableGroups {
static final String TABLE_NAME = "isis_permittable_groups";
static final String IDENTIFIER_COLUMN = "identifier";
static final String PERMITTABLES_COLUMN = "permittables";
static final String TYPE_NAME = "isis_permittable_group";
static final String PATH_FIELD = "path";
static final String METHOD_FIELD = "method";
static final String SOURCE_GROUP_ID_FIELD = "source_group_id";
private final CassandraSessionProvider cassandraSessionProvider;
private final TenantAwareEntityTemplate tenantAwareEntityTemplate;
private final TenantAwareCassandraMapperProvider tenantAwareCassandraMapperProvider;
@Autowired
PermittableGroups(
final CassandraSessionProvider cassandraSessionProvider,
final TenantAwareEntityTemplate tenantAwareEntityTemplate,
final TenantAwareCassandraMapperProvider tenantAwareCassandraMapperProvider) {
this.cassandraSessionProvider = cassandraSessionProvider;
this.tenantAwareEntityTemplate = tenantAwareEntityTemplate;
this.tenantAwareCassandraMapperProvider = tenantAwareCassandraMapperProvider;
}
public void buildTable() {
final CreateType createType = SchemaBuilder.createType(TYPE_NAME)
.ifNotExists()
.addColumn(PATH_FIELD, DataType.text())
.addColumn(METHOD_FIELD, DataType.text())
.addColumn(SOURCE_GROUP_ID_FIELD, DataType.text());
cassandraSessionProvider.getTenantSession().execute(createType);
final Create create = SchemaBuilder.createTable(TABLE_NAME)
.ifNotExists()
.addPartitionKey(IDENTIFIER_COLUMN, DataType.text())
.addUDTListColumn(PERMITTABLES_COLUMN, SchemaBuilder.frozen(TYPE_NAME));
cassandraSessionProvider.getTenantSession().execute(create);
}
public void add(final PermittableGroupEntity instance) {
tenantAwareEntityTemplate.save(instance);
}
public Optional<PermittableGroupEntity> get(final String identifier)
{
final PermittableGroupEntity instance =
tenantAwareCassandraMapperProvider.getMapper(PermittableGroupEntity.class).get(identifier);
if (instance != null) {
Assert.notNull(instance.getIdentifier());
}
return Optional.ofNullable(instance);
}
public List<PermittableGroupEntity> getAll() {
final Session tenantSession = cassandraSessionProvider.getTenantSession();
final Mapper<PermittableGroupEntity> entityMapper = tenantAwareCassandraMapperProvider.getMapper(PermittableGroupEntity.class);
final Statement statement = QueryBuilder.select().all().from(TABLE_NAME);
return new ArrayList<>(entityMapper.map(tenantSession.execute(statement)).all());
}
}
| 2,137 |
0 | Create_ds/fineract-cn-identity/service/src/main/java/org/apache/fineract/cn/identity/internal | Create_ds/fineract-cn-identity/service/src/main/java/org/apache/fineract/cn/identity/internal/util/IdentityConstants.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.fineract.cn.identity.internal.util;
/**
* @author Myrle Krantz
*/
public interface IdentityConstants {
String SU_ROLE = "pharaoh";
String SU_NAME = "antony";
int ITERATION_COUNT = 4096;
int HASH_LENGTH = 256;
int CURRENT_VERSION = 0;
String LOGGER_NAME = "identity-logger";
String JSON_SERIALIZER_NAME = "identity-json-serializer";
}
| 2,138 |
0 | Create_ds/fineract-cn-identity/service/src/main/java/org/apache/fineract/cn/identity/internal | Create_ds/fineract-cn-identity/service/src/main/java/org/apache/fineract/cn/identity/internal/util/Time.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.fineract.cn.identity.internal.util;
import com.datastax.driver.core.LocalDate;
import java.time.Clock;
import java.time.temporal.ChronoField;
/**
* @author Myrle Krantz
*/
public class Time {
public static LocalDate utcNowAsStaxLocalDate()
{
return LocalDate.fromDaysSinceEpoch((int) utcNowInEpochDays());
}
private static long utcNowInEpochDays()
{
return java.time.LocalDate.now(Clock.systemUTC()).getLong(ChronoField.EPOCH_DAY);
}
}
| 2,139 |
0 | Create_ds/fineract-cn-identity/service/src/main/java/org/apache/fineract/cn/identity/internal | Create_ds/fineract-cn-identity/service/src/main/java/org/apache/fineract/cn/identity/internal/mapper/SignatureMapper.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.fineract.cn.identity.internal.mapper;
import org.apache.fineract.cn.anubis.api.v1.domain.ApplicationSignatureSet;
import org.apache.fineract.cn.anubis.api.v1.domain.Signature;
import org.apache.fineract.cn.identity.internal.repository.ApplicationSignatureEntity;
import org.apache.fineract.cn.identity.internal.repository.SignatureEntity;
/**
* @author Myrle Krantz
*/
public interface SignatureMapper {
static ApplicationSignatureSet mapToApplicationSignatureSet(final SignatureEntity signatureEntity) {
return new ApplicationSignatureSet(
signatureEntity.getKeyTimestamp(),
new Signature(signatureEntity.getPublicKeyMod(), signatureEntity.getPublicKeyExp()),
new Signature(signatureEntity.getPublicKeyMod(), signatureEntity.getPublicKeyExp()));
}
static Signature mapToSignature(final ApplicationSignatureEntity entity) {
final Signature ret = new Signature();
ret.setPublicKeyExp(entity.getPublicKeyExp());
ret.setPublicKeyMod(entity.getPublicKeyMod());
return ret;
}
}
| 2,140 |
0 | Create_ds/fineract-cn-identity/service/src/main/java/org/apache/fineract/cn/identity/internal | Create_ds/fineract-cn-identity/service/src/main/java/org/apache/fineract/cn/identity/internal/mapper/ApplicationCallEndpointSetMapper.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.fineract.cn.identity.internal.mapper;
import org.apache.fineract.cn.identity.api.v1.domain.CallEndpointSet;
import java.util.Collections;
import org.apache.fineract.cn.identity.internal.repository.ApplicationCallEndpointSetEntity;
/**
* @author Myrle Krantz
*/
public interface ApplicationCallEndpointSetMapper {
static ApplicationCallEndpointSetEntity mapToEntity(
final String applicationIdentifier,
final CallEndpointSet callEndpointSet)
{
final ApplicationCallEndpointSetEntity ret = new ApplicationCallEndpointSetEntity();
ret.setApplicationIdentifier(applicationIdentifier);
ret.setCallEndpointSetIdentifier(callEndpointSet.getIdentifier());
ret.setCallEndpointGroupIdentifiers(callEndpointSet.getPermittableEndpointGroupIdentifiers());
return ret;
}
static CallEndpointSet map(final ApplicationCallEndpointSetEntity entity) {
final CallEndpointSet ret = new CallEndpointSet();
ret.setIdentifier(entity.getCallEndpointSetIdentifier());
if (entity.getCallEndpointGroupIdentifiers() == null)
ret.setPermittableEndpointGroupIdentifiers(Collections.emptyList());
else
ret.setPermittableEndpointGroupIdentifiers(entity.getCallEndpointGroupIdentifiers());
return ret;
}
}
| 2,141 |
0 | Create_ds/fineract-cn-identity/service/src/main/java/org/apache/fineract/cn/identity/internal | Create_ds/fineract-cn-identity/service/src/main/java/org/apache/fineract/cn/identity/internal/mapper/PermissionMapper.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.fineract.cn.identity.internal.mapper;
import org.apache.fineract.cn.identity.api.v1.domain.Permission;
import java.util.Collections;
import java.util.Set;
import java.util.stream.Collectors;
import javax.annotation.Nullable;
import org.apache.fineract.cn.anubis.api.v1.domain.AllowedOperation;
import org.apache.fineract.cn.identity.internal.repository.AllowedOperationType;
import org.apache.fineract.cn.identity.internal.repository.PermissionType;
/**
* @author Myrle Krantz
*/
public interface PermissionMapper {
static Set<AllowedOperationType> mapToAllowedOperationsTypeSet(
@Nullable final Set<AllowedOperation> allowedOperations) {
if (allowedOperations == null)
return Collections.emptySet();
return allowedOperations.stream().map(op -> {
switch (op) {
case READ:
return AllowedOperationType.READ;
case CHANGE:
return AllowedOperationType.CHANGE;
case DELETE:
return AllowedOperationType.DELETE;
default:
return null;
}
}).filter(op -> (op != null)).collect(Collectors.toSet());
}
static Set<AllowedOperation> mapToAllowedOperations(final Set<AllowedOperationType> allowedOperations) {
return allowedOperations.stream().map(op -> {
switch (op) {
case READ:
return AllowedOperation.READ;
case CHANGE:
return AllowedOperation.CHANGE;
case DELETE:
return AllowedOperation.DELETE;
default:
return null;
}
}).filter(op -> (op != null)).collect(Collectors.toSet());
}
static PermissionType mapToPermissionType(final Permission instance) {
return new PermissionType(instance.getPermittableEndpointGroupIdentifier(), mapToAllowedOperationsTypeSet(instance.getAllowedOperations()));
}
static Permission mapToPermission(final PermissionType instance) {
return new Permission(instance.getPermittableGroupIdentifier(), mapToAllowedOperations(instance.getAllowedOperations()));
}
}
| 2,142 |
0 | Create_ds/fineract-cn-identity/service/src/main/java/org/apache/fineract/cn/identity/internal | Create_ds/fineract-cn-identity/service/src/main/java/org/apache/fineract/cn/identity/internal/command/CreatePermittableGroupCommand.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.fineract.cn.identity.internal.command;
import org.apache.fineract.cn.identity.api.v1.domain.PermittableGroup;
/**
* @author Myrle Krantz
*/
public class CreatePermittableGroupCommand {
private PermittableGroup instance;
@SuppressWarnings("unused")
public CreatePermittableGroupCommand() {
}
public CreatePermittableGroupCommand(final PermittableGroup instance) {
this.instance = instance;
}
public PermittableGroup getInstance() {
return instance;
}
public void setInstance(PermittableGroup instance) {
this.instance = instance;
}
@Override
public String toString() {
return "CreatePermittableGroupCommand{" +
"instance=" + instance.getIdentifier() +
'}';
}
}
| 2,143 |
0 | Create_ds/fineract-cn-identity/service/src/main/java/org/apache/fineract/cn/identity/internal | Create_ds/fineract-cn-identity/service/src/main/java/org/apache/fineract/cn/identity/internal/command/ChangeRoleCommand.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.fineract.cn.identity.internal.command;
import org.apache.fineract.cn.identity.api.v1.domain.Role;
/**
* @author Myrle Krantz
*/
@SuppressWarnings("unused")
public class ChangeRoleCommand {
private String identifier;
private Role instance;
public ChangeRoleCommand()
{
}
public ChangeRoleCommand(final String identifier, final Role instance) {
this.identifier = identifier;
this.instance = instance;
}
public String getIdentifier() {
return identifier;
}
public void setIdentifier(String identifier) {
this.identifier = identifier;
}
public Role getInstance() {
return instance;
}
public void setInstance(Role instance) {
this.instance = instance;
}
@Override
public String toString() {
return "ChangeRoleCommand{" +
"identifier='" + identifier + '\'' +
'}';
}
}
| 2,144 |
0 | Create_ds/fineract-cn-identity/service/src/main/java/org/apache/fineract/cn/identity/internal | Create_ds/fineract-cn-identity/service/src/main/java/org/apache/fineract/cn/identity/internal/command/ChangeUserRoleCommand.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.fineract.cn.identity.internal.command;
/**
* @author Myrle Krantz
*/
@SuppressWarnings("unused")
public class ChangeUserRoleCommand {
private String identifier;
private String role;
public ChangeUserRoleCommand() {
}
public ChangeUserRoleCommand(final String identifier, final String role) {
this.identifier = identifier;
this.role = role;
}
public String getIdentifier() {
return identifier;
}
public void setIdentifier(String identifier) {
this.identifier = identifier;
}
public String getRole() {
return role;
}
public void setRole(String role) {
this.role = role;
}
@Override
public String toString() {
return "ChangeUserRoleCommand{" +
"identifier='" + identifier + '\'' +
", role='" + role + '\'' +
'}';
}
}
| 2,145 |
0 | Create_ds/fineract-cn-identity/service/src/main/java/org/apache/fineract/cn/identity/internal | Create_ds/fineract-cn-identity/service/src/main/java/org/apache/fineract/cn/identity/internal/command/CreateApplicationCallEndpointSetCommand.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.fineract.cn.identity.internal.command;
import org.apache.fineract.cn.identity.api.v1.domain.CallEndpointSet;
/**
* @author Myrle Krantz
*/
@SuppressWarnings("unused")
public class CreateApplicationCallEndpointSetCommand {
private String applicationIdentifier;
private CallEndpointSet callEndpointSet;
public CreateApplicationCallEndpointSetCommand() {
}
public CreateApplicationCallEndpointSetCommand(String applicationIdentifier, CallEndpointSet callEndpointSet) {
this.applicationIdentifier = applicationIdentifier;
this.callEndpointSet = callEndpointSet;
}
public String getApplicationIdentifier() {
return applicationIdentifier;
}
public void setApplicationIdentifier(String applicationIdentifier) {
this.applicationIdentifier = applicationIdentifier;
}
public CallEndpointSet getCallEndpointSet() {
return callEndpointSet;
}
public void setEndpointSet(CallEndpointSet callEndpointSet) {
this.callEndpointSet = callEndpointSet;
}
@Override
public String toString() {
return "CreateApplicationCallEndpointSetCommand{" +
"applicationIdentifier='" + applicationIdentifier + '\'' +
", callEndpointSet=" + callEndpointSet.getIdentifier() +
'}';
}
} | 2,146 |
0 | Create_ds/fineract-cn-identity/service/src/main/java/org/apache/fineract/cn/identity/internal | Create_ds/fineract-cn-identity/service/src/main/java/org/apache/fineract/cn/identity/internal/command/SetApplicationSignatureCommand.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.fineract.cn.identity.internal.command;
import org.apache.fineract.cn.anubis.api.v1.domain.Signature;
/**
* @author Myrle Krantz
*/
@SuppressWarnings("unused")
public class SetApplicationSignatureCommand {
private String applicationIdentifier;
private String keyTimestamp;
private Signature signature;
public SetApplicationSignatureCommand() {
}
public SetApplicationSignatureCommand(String applicationIdentifier, String keyTimestamp, Signature signature) {
this.applicationIdentifier = applicationIdentifier;
this.keyTimestamp = keyTimestamp;
this.signature = signature;
}
public String getApplicationIdentifier() {
return applicationIdentifier;
}
public void setApplicationIdentifier(String applicationIdentifier) {
this.applicationIdentifier = applicationIdentifier;
}
public String getKeyTimestamp() {
return keyTimestamp;
}
public void setKeyTimestamp(String keyTimestamp) {
this.keyTimestamp = keyTimestamp;
}
public Signature getSignature() {
return signature;
}
public void setSignature(Signature signature) {
this.signature = signature;
}
@Override
public String toString() {
return "SetApplicationSignatureCommand{" +
"applicationIdentifier='" + applicationIdentifier + '\'' +
", keyTimestamp='" + keyTimestamp + '\'' +
'}';
}
}
| 2,147 |
0 | Create_ds/fineract-cn-identity/service/src/main/java/org/apache/fineract/cn/identity/internal | Create_ds/fineract-cn-identity/service/src/main/java/org/apache/fineract/cn/identity/internal/command/AuthenticationCommandResponse.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.fineract.cn.identity.internal.command;
import java.util.Objects;
/**
* @author Myrle Krantz
*/
public class AuthenticationCommandResponse {
private String accessToken;
private String accessTokenExpiration;
private String refreshToken;
private String refreshTokenExpiration;
private String passwordExpiration;
public AuthenticationCommandResponse() {
}
public AuthenticationCommandResponse(String accessToken, String accessTokenExpiration, String refreshToken, String refreshTokenExpiration, String passwordExpiration) {
this.accessToken = accessToken;
this.accessTokenExpiration = accessTokenExpiration;
this.refreshToken = refreshToken;
this.refreshTokenExpiration = refreshTokenExpiration;
this.passwordExpiration = passwordExpiration;
}
public String getAccessToken() {
return accessToken;
}
public void setAccessToken(String accessToken) {
this.accessToken = accessToken;
}
public String getAccessTokenExpiration() {
return accessTokenExpiration;
}
public void setAccessTokenExpiration(String accessTokenExpiration) {
this.accessTokenExpiration = accessTokenExpiration;
}
public String getRefreshToken() {
return refreshToken;
}
public void setRefreshToken(String refreshToken) {
this.refreshToken = refreshToken;
}
public String getRefreshTokenExpiration() {
return refreshTokenExpiration;
}
public void setRefreshTokenExpiration(String refreshTokenExpiration) {
this.refreshTokenExpiration = refreshTokenExpiration;
}
public String getPasswordExpiration() {
return passwordExpiration;
}
public void setPasswordExpiration(String passwordExpiration) {
this.passwordExpiration = passwordExpiration;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
AuthenticationCommandResponse that = (AuthenticationCommandResponse) o;
return Objects.equals(accessToken, that.accessToken) &&
Objects.equals(accessTokenExpiration, that.accessTokenExpiration) &&
Objects.equals(refreshToken, that.refreshToken) &&
Objects.equals(refreshTokenExpiration, that.refreshTokenExpiration) &&
Objects.equals(passwordExpiration, that.passwordExpiration);
}
@Override
public int hashCode() {
return Objects.hash(accessToken, accessTokenExpiration, refreshToken, refreshTokenExpiration, passwordExpiration);
}
@Override
public String toString() {
return "AuthenticationCommandResponse{" +
"accessToken='" + accessToken + '\'' +
", accessTokenExpiration='" + accessTokenExpiration + '\'' +
", refreshToken='" + refreshToken + '\'' +
", refreshTokenExpiration='" + refreshTokenExpiration + '\'' +
", passwordExpiration='" + passwordExpiration + '\'' +
'}';
}
}
| 2,148 |
0 | Create_ds/fineract-cn-identity/service/src/main/java/org/apache/fineract/cn/identity/internal | Create_ds/fineract-cn-identity/service/src/main/java/org/apache/fineract/cn/identity/internal/command/RefreshTokenAuthenticationCommand.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.fineract.cn.identity.internal.command;
/**
* @author Myrle Krantz
*/
@SuppressWarnings("unused")
public class RefreshTokenAuthenticationCommand {
private String refreshToken;
public RefreshTokenAuthenticationCommand() {
}
public RefreshTokenAuthenticationCommand(final String refreshToken) {
this.refreshToken = refreshToken;
}
public String getRefreshToken() {
return refreshToken;
}
public void setRefreshToken(String refreshToken) {
this.refreshToken = refreshToken;
}
@Override
public String toString() {
return "RefreshTokenAuthenticationCommand{" +
"refreshToken='" + refreshToken + '\'' +
'}';
}
}
| 2,149 |
0 | Create_ds/fineract-cn-identity/service/src/main/java/org/apache/fineract/cn/identity/internal | Create_ds/fineract-cn-identity/service/src/main/java/org/apache/fineract/cn/identity/internal/command/DeleteApplicationPermissionCommand.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.fineract.cn.identity.internal.command;
/**
* @author Myrle Krantz
*/
@SuppressWarnings("unused")
public class DeleteApplicationPermissionCommand {
private String applicationIdentifier;
private String permittableGroupIdentifier;
public DeleteApplicationPermissionCommand() {
}
public DeleteApplicationPermissionCommand(String applicationIdentifier, String permittableGroupIdentifier) {
this.applicationIdentifier = applicationIdentifier;
this.permittableGroupIdentifier = permittableGroupIdentifier;
}
public String getApplicationIdentifier() {
return applicationIdentifier;
}
public void setApplicationIdentifier(String applicationIdentifier) {
this.applicationIdentifier = applicationIdentifier;
}
public String getPermittableGroupIdentifier() {
return permittableGroupIdentifier;
}
public void setPermittableGroupIdentifier(String permittableGroupIdentifier) {
this.permittableGroupIdentifier = permittableGroupIdentifier;
}
@Override
public String toString() {
return "DeleteApplicationPermissionCommand{" +
"applicationIdentifier='" + applicationIdentifier + '\'' +
", permittableGroupIdentifier='" + permittableGroupIdentifier + '\'' +
'}';
}
}
| 2,150 |
0 | Create_ds/fineract-cn-identity/service/src/main/java/org/apache/fineract/cn/identity/internal | Create_ds/fineract-cn-identity/service/src/main/java/org/apache/fineract/cn/identity/internal/command/ChangeUserPasswordCommand.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.fineract.cn.identity.internal.command;
/**
* @author Myrle Krantz
*/
@SuppressWarnings("unused")
public class ChangeUserPasswordCommand {
private String identifier;
//transient to ensure this field doesn't land in the audit log.
private transient String password;
public ChangeUserPasswordCommand() {
}
public ChangeUserPasswordCommand(final String identifier, final String password) {
this.identifier = identifier;
this.password = password;
}
public String getIdentifier() {
return identifier;
}
public void setIdentifier(String identifier) {
this.identifier = identifier;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
@Override
public String toString() {
return "ChangeUserPasswordCommand{" +
"identifier='" + identifier + '\'' +
'}';
}
}
| 2,151 |
0 | Create_ds/fineract-cn-identity/service/src/main/java/org/apache/fineract/cn/identity/internal | Create_ds/fineract-cn-identity/service/src/main/java/org/apache/fineract/cn/identity/internal/command/CreateRoleCommand.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.fineract.cn.identity.internal.command;
import org.apache.fineract.cn.identity.api.v1.domain.Role;
/**
* @author Myrle Krantz
*/
@SuppressWarnings("unused")
public class CreateRoleCommand {
private Role instance;
public CreateRoleCommand() {
}
public CreateRoleCommand(final Role instance) {
this.instance = instance;
}
public Role getInstance() {
return instance;
}
public void setInstance(Role instance) {
this.instance = instance;
}
@Override
public String toString() {
return "CreateRoleCommand{" +
"instance=" + instance.getIdentifier() +
'}';
}
}
| 2,152 |
0 | Create_ds/fineract-cn-identity/service/src/main/java/org/apache/fineract/cn/identity/internal | Create_ds/fineract-cn-identity/service/src/main/java/org/apache/fineract/cn/identity/internal/command/DeleteApplicationCallEndpointSetCommand.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.fineract.cn.identity.internal.command;
/**
* @author Myrle Krantz
*/
@SuppressWarnings("unused")
public class DeleteApplicationCallEndpointSetCommand {
private String applicationIdentifier;
private String callEndpointSetIdentifier;
public DeleteApplicationCallEndpointSetCommand() {
}
public DeleteApplicationCallEndpointSetCommand(String applicationIdentifier, String callEndpointSetIdentifier) {
this.applicationIdentifier = applicationIdentifier;
this.callEndpointSetIdentifier = callEndpointSetIdentifier;
}
public String getApplicationIdentifier() {
return applicationIdentifier;
}
public void setApplicationIdentifier(String applicationIdentifier) {
this.applicationIdentifier = applicationIdentifier;
}
public String getCallEndpointSetIdentifier() {
return callEndpointSetIdentifier;
}
public void setCallEndpointSetIdentifier(String callEndpointSetIdentifier) {
this.callEndpointSetIdentifier = callEndpointSetIdentifier;
}
@Override
public String toString() {
return "DeleteApplicationCallEndpointSetCommand{" +
"applicationIdentifier='" + applicationIdentifier + '\'' +
", callEndpointSetIdentifier='" + callEndpointSetIdentifier + '\'' +
'}';
}
}
| 2,153 |
0 | Create_ds/fineract-cn-identity/service/src/main/java/org/apache/fineract/cn/identity/internal | Create_ds/fineract-cn-identity/service/src/main/java/org/apache/fineract/cn/identity/internal/command/DeleteRoleCommand.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.fineract.cn.identity.internal.command;
/**
* @author Myrle Krantz
*/
@SuppressWarnings("unused")
public class DeleteRoleCommand {
private String identifier;
public DeleteRoleCommand() {
}
public DeleteRoleCommand(final String identifier) {
this.identifier = identifier;
}
public String getIdentifier() {
return identifier;
}
public void setIdentifier(String identifier) {
this.identifier = identifier;
}
@Override
public String toString() {
return "DeleteRoleCommand{" +
"identifier='" + identifier + '\'' +
'}';
}
}
| 2,154 |
0 | Create_ds/fineract-cn-identity/service/src/main/java/org/apache/fineract/cn/identity/internal | Create_ds/fineract-cn-identity/service/src/main/java/org/apache/fineract/cn/identity/internal/command/PasswordAuthenticationCommand.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.fineract.cn.identity.internal.command;
/**
* @author Myrle Krantz
*/
@SuppressWarnings("unused")
public class PasswordAuthenticationCommand {
private String useridentifier;
private transient String password;
PasswordAuthenticationCommand() {}
public PasswordAuthenticationCommand(
final String useridentifier,
final String password) {
this.useridentifier = useridentifier;
this.password = password;
}
public String getUseridentifier() {
return useridentifier;
}
public void setUseridentifier(String useridentifier) {
this.useridentifier = useridentifier;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
@Override
public String toString() {
return "PasswordAuthenticationCommand{" +
"useridentifier='" + useridentifier + '\'' +
'}';
}
}
| 2,155 |
0 | Create_ds/fineract-cn-identity/service/src/main/java/org/apache/fineract/cn/identity/internal | Create_ds/fineract-cn-identity/service/src/main/java/org/apache/fineract/cn/identity/internal/command/CreateApplicationPermissionCommand.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.fineract.cn.identity.internal.command;
import org.apache.fineract.cn.identity.api.v1.domain.Permission;
/**
* @author Myrle Krantz
*/
@SuppressWarnings("unused")
public class CreateApplicationPermissionCommand {
private String applicationIdentifer;
private Permission permission;
public CreateApplicationPermissionCommand() {
}
public CreateApplicationPermissionCommand(final String applicationIdentifier, final Permission permission) {
this.applicationIdentifer = applicationIdentifier;
this.permission = permission;
}
public String getApplicationIdentifer() {
return applicationIdentifer;
}
public void setApplicationIdentifer(String applicationIdentifer) {
this.applicationIdentifer = applicationIdentifer;
}
public Permission getPermission() {
return permission;
}
public void setPermission(Permission permission) {
this.permission = permission;
}
@Override
public String toString() {
return "CreateApplicationPermissionCommand{" +
"applicationIdentifer='" + applicationIdentifer + '\'' +
", permission=" + permission.getPermittableEndpointGroupIdentifier() +
'}';
}
}
| 2,156 |
0 | Create_ds/fineract-cn-identity/service/src/main/java/org/apache/fineract/cn/identity/internal | Create_ds/fineract-cn-identity/service/src/main/java/org/apache/fineract/cn/identity/internal/command/DeleteApplicationCommand.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.fineract.cn.identity.internal.command;
/**
* @author Myrle Krantz
*/
@SuppressWarnings("unused")
public class DeleteApplicationCommand {
private String applicationIdentifier;
public DeleteApplicationCommand() {
}
public DeleteApplicationCommand(String applicationIdentifier) {
this.applicationIdentifier = applicationIdentifier;
}
public String getApplicationIdentifier() {
return applicationIdentifier;
}
public void setApplicationIdentifier(String applicationIdentifier) {
this.applicationIdentifier = applicationIdentifier;
}
@Override
public String toString() {
return "DeleteApplicationCommand{" +
"applicationIdentifier='" + applicationIdentifier + '\'' +
'}';
}
}
| 2,157 |
0 | Create_ds/fineract-cn-identity/service/src/main/java/org/apache/fineract/cn/identity/internal | Create_ds/fineract-cn-identity/service/src/main/java/org/apache/fineract/cn/identity/internal/command/CreateUserCommand.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.fineract.cn.identity.internal.command;
import org.apache.fineract.cn.identity.api.v1.domain.UserWithPassword;
/**
* @author Myrle Krantz
*/
@SuppressWarnings("unused")
public class CreateUserCommand {
private String identifier;
private String role;
//transient to ensure this field doesn't land in the audit log.
private transient String password;
public CreateUserCommand() {
}
public CreateUserCommand(final UserWithPassword instance) {
this.identifier = instance.getIdentifier();
this.role = instance.getRole();
this.password = instance.getPassword();
}
public String getIdentifier() {
return identifier;
}
public void setIdentifier(String identifier) {
this.identifier = identifier;
}
public String getRole() {
return role;
}
public void setRole(String role) {
this.role = role;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
@Override
public String toString() {
return "CreateUserCommand{" +
"identifier='" + identifier + '\'' +
", role='" + role + '\'' +
'}';
}
}
| 2,158 |
0 | Create_ds/fineract-cn-identity/service/src/main/java/org/apache/fineract/cn/identity/internal | Create_ds/fineract-cn-identity/service/src/main/java/org/apache/fineract/cn/identity/internal/command/ChangeApplicationCallEndpointSetCommand.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.fineract.cn.identity.internal.command;
import org.apache.fineract.cn.identity.api.v1.domain.CallEndpointSet;
/**
* @author Myrle Krantz
*/
@SuppressWarnings("unused")
public class ChangeApplicationCallEndpointSetCommand {
private String applicationIdentifier;
private String callEndpointSetIdentifier;
private CallEndpointSet callEndpointSet;
public ChangeApplicationCallEndpointSetCommand() {
}
public ChangeApplicationCallEndpointSetCommand(
String applicationIdentifier,
String callEndpointSetIdentifier,
CallEndpointSet callEndpointSet) {
this.applicationIdentifier = applicationIdentifier;
this.callEndpointSetIdentifier = callEndpointSetIdentifier;
this.callEndpointSet = callEndpointSet;
}
public String getApplicationIdentifier() {
return applicationIdentifier;
}
public void setApplicationIdentifier(String applicationIdentifier) {
this.applicationIdentifier = applicationIdentifier;
}
public String getCallEndpointSetIdentifier() {
return callEndpointSetIdentifier;
}
public void setCallEndpointSetIdentifier(String callEndpointSetIdentifier) {
this.callEndpointSetIdentifier = callEndpointSetIdentifier;
}
public CallEndpointSet getCallEndpointSet() {
return callEndpointSet;
}
public void setCallEndpointSet(CallEndpointSet callEndpointSet) {
this.callEndpointSet = callEndpointSet;
}
@Override
public String toString() {
return "ChangeApplicationCallEndpointSetCommand{" +
"applicationIdentifier='" + applicationIdentifier + '\'' +
", callEndpointSetIdentifier='" + callEndpointSetIdentifier + '\'' +
'}';
}
} | 2,159 |
0 | Create_ds/fineract-cn-identity/service/src/main/java/org/apache/fineract/cn/identity/internal | Create_ds/fineract-cn-identity/service/src/main/java/org/apache/fineract/cn/identity/internal/command/SetApplicationPermissionUserEnabledCommand.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.fineract.cn.identity.internal.command;
/**
* @author Myrle Krantz
*/
@SuppressWarnings("unused")
public class SetApplicationPermissionUserEnabledCommand {
private String applicationIdentifier;
private String permittableGroupIdentifier;
private String userIdentifier;
private boolean enabled;
public SetApplicationPermissionUserEnabledCommand() {
}
public SetApplicationPermissionUserEnabledCommand(String applicationIdentifier, String permittableGroupIdentifier, String userIdentifier, boolean enabled) {
this.applicationIdentifier = applicationIdentifier;
this.permittableGroupIdentifier = permittableGroupIdentifier;
this.userIdentifier = userIdentifier;
this.enabled = enabled;
}
public String getApplicationIdentifier() {
return applicationIdentifier;
}
public void setApplicationIdentifier(String applicationIdentifier) {
this.applicationIdentifier = applicationIdentifier;
}
public String getPermittableGroupIdentifier() {
return permittableGroupIdentifier;
}
public void setPermittableGroupIdentifier(String permittableGroupIdentifier) {
this.permittableGroupIdentifier = permittableGroupIdentifier;
}
public String getUserIdentifier() {
return userIdentifier;
}
public void setUserIdentifier(String userIdentifier) {
this.userIdentifier = userIdentifier;
}
public boolean isEnabled() {
return enabled;
}
public void setEnabled(boolean enabled) {
this.enabled = enabled;
}
@Override
public String toString() {
return "SetApplicationPermissionUserEnabledCommand{" +
"applicationIdentifier='" + applicationIdentifier + '\'' +
", permittableGroupIdentifier='" + permittableGroupIdentifier + '\'' +
", userIdentifier='" + userIdentifier + '\'' +
", enabled=" + enabled +
'}';
}
}
| 2,160 |
0 | Create_ds/fineract-cn-identity/service/src/main/java/org/apache/fineract/cn/identity/internal/command | Create_ds/fineract-cn-identity/service/src/main/java/org/apache/fineract/cn/identity/internal/command/handler/Provisioner.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.fineract.cn.identity.internal.command.handler;
import com.datastax.driver.core.exceptions.InvalidQueryException;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import org.apache.fineract.cn.anubis.api.v1.domain.ApplicationSignatureSet;
import org.apache.fineract.cn.crypto.SaltGenerator;
import org.apache.fineract.cn.identity.api.v1.PermittableGroupIds;
import org.apache.fineract.cn.identity.internal.mapper.SignatureMapper;
import org.apache.fineract.cn.identity.internal.repository.AllowedOperationType;
import org.apache.fineract.cn.identity.internal.repository.ApplicationCallEndpointSets;
import org.apache.fineract.cn.identity.internal.repository.ApplicationPermissionUsers;
import org.apache.fineract.cn.identity.internal.repository.ApplicationPermissions;
import org.apache.fineract.cn.identity.internal.repository.ApplicationSignatures;
import org.apache.fineract.cn.identity.internal.repository.PermissionType;
import org.apache.fineract.cn.identity.internal.repository.Permissions;
import org.apache.fineract.cn.identity.internal.repository.PermittableGroupEntity;
import org.apache.fineract.cn.identity.internal.repository.PermittableGroups;
import org.apache.fineract.cn.identity.internal.repository.PermittableType;
import org.apache.fineract.cn.identity.internal.repository.PrivateTenantInfoEntity;
import org.apache.fineract.cn.identity.internal.repository.RoleEntity;
import org.apache.fineract.cn.identity.internal.repository.Roles;
import org.apache.fineract.cn.identity.internal.repository.SignatureEntity;
import org.apache.fineract.cn.identity.internal.repository.Signatures;
import org.apache.fineract.cn.identity.internal.repository.Tenants;
import org.apache.fineract.cn.identity.internal.repository.UserEntity;
import org.apache.fineract.cn.identity.internal.repository.Users;
import org.apache.fineract.cn.identity.internal.util.IdentityConstants;
import org.apache.fineract.cn.lang.ServiceException;
import org.apache.fineract.cn.lang.TenantContextHolder;
import org.apache.fineract.cn.lang.security.RsaKeyPairFactory;
import org.slf4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
/**
* @author Myrle Krantz
*/
@Component
public class Provisioner {
private final Signatures signature;
private final Tenants tenant;
private final Users users;
private final PermittableGroups permittableGroups;
private final Permissions permissions;
private final Roles roles;
private final ApplicationSignatures applicationSignatures;
private final ApplicationPermissions applicationPermissions;
private final ApplicationPermissionUsers applicationPermissionUsers;
private final ApplicationCallEndpointSets applicationCallEndpointSets;
private final UserEntityCreator userEntityCreator;
private final Logger logger;
private final SaltGenerator saltGenerator;
@Value("${spring.application.name}")
private String applicationName;
@Value("${identity.passwordExpiresInDays:93}")
private int passwordExpiresInDays;
@Value("${identity.timeToChangePasswordAfterExpirationInDays:4}")
private int timeToChangePasswordAfterExpirationInDays;
@Autowired
Provisioner(
final Signatures signature,
final Tenants tenant,
final Users users,
final PermittableGroups permittableGroups,
final Permissions permissions,
final Roles roles,
final ApplicationSignatures applicationSignatures,
final ApplicationPermissions applicationPermissions,
final ApplicationPermissionUsers applicationPermissionUsers,
final ApplicationCallEndpointSets applicationCallEndpointSets,
final UserEntityCreator userEntityCreator,
@Qualifier(IdentityConstants.LOGGER_NAME) final Logger logger,
final SaltGenerator saltGenerator)
{
this.signature = signature;
this.tenant = tenant;
this.users = users;
this.permittableGroups = permittableGroups;
this.permissions = permissions;
this.roles = roles;
this.applicationSignatures = applicationSignatures;
this.applicationPermissions = applicationPermissions;
this.applicationPermissionUsers = applicationPermissionUsers;
this.applicationCallEndpointSets = applicationCallEndpointSets;
this.userEntityCreator = userEntityCreator;
this.logger = logger;
this.saltGenerator = saltGenerator;
}
public synchronized ApplicationSignatureSet provisionTenant(final String initialPasswordHash) {
{
final Optional<ApplicationSignatureSet> latestSignature = signature.getAllKeyTimestamps().stream()
.max(String::compareTo)
.flatMap(signature::getSignature)
.map(SignatureMapper::mapToApplicationSignatureSet);
if (latestSignature.isPresent()) {
final Optional<ByteBuffer> fixedSalt = tenant.getPrivateTenantInfo().map(PrivateTenantInfoEntity::getFixedSalt);
if (fixedSalt.isPresent()) {
logger.info("Changing password for tenant '{}' instead of provisioning...", TenantContextHolder
.checkedGetIdentifier());
final UserEntity suUser = userEntityCreator
.build(IdentityConstants.SU_NAME, IdentityConstants.SU_ROLE, initialPasswordHash, true,
fixedSalt.get().array(), timeToChangePasswordAfterExpirationInDays);
users.add(suUser);
logger.info("Successfully changed admin password '{}'...", TenantContextHolder.checkedGetIdentifier());
return latestSignature.get();
}
}
}
logger.info("Provisioning cassandra tables for tenant '{}'...", TenantContextHolder.checkedGetIdentifier());
final RsaKeyPairFactory.KeyPairHolder keys = RsaKeyPairFactory.createKeyPair();
byte[] fixedSalt = this.saltGenerator.createRandomSalt();
try {
signature.buildTable();
final SignatureEntity signatureEntity = signature.add(keys);
tenant.buildTable();
tenant.add(fixedSalt, passwordExpiresInDays, timeToChangePasswordAfterExpirationInDays);
users.buildTable();
permittableGroups.buildTable();
permissions.buildType();
roles.buildTable();
applicationSignatures.buildTable();
applicationPermissions.buildTable();
applicationPermissionUsers.buildTable();
applicationCallEndpointSets.buildTable();
createPermittablesGroup(PermittableGroupIds.ROLE_MANAGEMENT, "/roles/*", "/permittablegroups/*");
createPermittablesGroup(PermittableGroupIds.IDENTITY_MANAGEMENT, "/users/*");
createPermittablesGroup(PermittableGroupIds.SELF_MANAGEMENT, "/users/{useridentifier}/password", "/applications/*/permissions/*/users/{useridentifier}/enabled");
createPermittablesGroup(PermittableGroupIds.APPLICATION_SELF_MANAGEMENT, "/applications/{applicationidentifier}/permissions");
final List<PermissionType> permissions = new ArrayList<>();
permissions.add(fullAccess(PermittableGroupIds.ROLE_MANAGEMENT));
permissions.add(fullAccess(PermittableGroupIds.IDENTITY_MANAGEMENT));
permissions.add(fullAccess(PermittableGroupIds.SELF_MANAGEMENT));
permissions.add(fullAccess(PermittableGroupIds.APPLICATION_SELF_MANAGEMENT));
final RoleEntity suRole = new RoleEntity();
suRole.setIdentifier(IdentityConstants.SU_ROLE);
suRole.setPermissions(permissions);
roles.add(suRole);
final UserEntity suUser = userEntityCreator
.build(IdentityConstants.SU_NAME, IdentityConstants.SU_ROLE, initialPasswordHash, true,
fixedSalt, timeToChangePasswordAfterExpirationInDays);
users.add(suUser);
final ApplicationSignatureSet ret = SignatureMapper.mapToApplicationSignatureSet(signatureEntity);
logger.info("Successfully provisioned cassandra tables for tenant '{}'...", TenantContextHolder.checkedGetIdentifier());
return ret;
}
catch (final InvalidQueryException e)
{
logger.error("Failed to provision cassandra tables for tenant.", e);
throw ServiceException.internalError("Failed to provision tenant.");
}
}
private PermissionType fullAccess(final String permittableGroupIdentifier) {
final PermissionType ret = new PermissionType();
ret.setPermittableGroupIdentifier(permittableGroupIdentifier);
ret.setAllowedOperations(AllowedOperationType.ALL);
return ret;
}
private void createPermittablesGroup(final String identifier, final String... paths) {
final PermittableGroupEntity permittableGroup = new PermittableGroupEntity();
permittableGroup.setIdentifier(identifier);
permittableGroup.setPermittables(Arrays.stream(paths).flatMap(this::permittables).collect(Collectors.toList()));
permittableGroups.add(permittableGroup);
}
private Stream<PermittableType> permittables(final String path)
{
final PermittableType getret = new PermittableType();
getret.setPath(applicationName + path);
getret.setMethod("GET");
final PermittableType postret = new PermittableType();
postret.setPath(applicationName + path);
postret.setMethod("POST");
final PermittableType putret = new PermittableType();
putret.setPath(applicationName + path);
putret.setMethod("PUT");
final PermittableType delret = new PermittableType();
delret.setPath(applicationName + path);
delret.setMethod("DELETE");
final List<PermittableType> ret = new ArrayList<>();
ret.add(getret);
ret.add(postret);
ret.add(putret);
ret.add(delret);
return ret.stream();
}
}
| 2,161 |
0 | Create_ds/fineract-cn-identity/service/src/main/java/org/apache/fineract/cn/identity/internal/command | Create_ds/fineract-cn-identity/service/src/main/java/org/apache/fineract/cn/identity/internal/command/handler/UserEntityCreator.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.fineract.cn.identity.internal.command.handler;
import com.datastax.driver.core.LocalDate;
import java.nio.ByteBuffer;
import java.util.Optional;
import org.apache.fineract.cn.crypto.HashGenerator;
import org.apache.fineract.cn.crypto.SaltGenerator;
import org.apache.fineract.cn.identity.internal.repository.PrivateTenantInfoEntity;
import org.apache.fineract.cn.identity.internal.repository.Tenants;
import org.apache.fineract.cn.identity.internal.repository.UserEntity;
import org.apache.fineract.cn.identity.internal.util.IdentityConstants;
import org.apache.fineract.cn.identity.internal.util.Time;
import org.apache.fineract.cn.lang.ServiceException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.util.EncodingUtils;
import org.springframework.stereotype.Component;
/**
* @author Myrle Krantz
*/
@SuppressWarnings("WeakerAccess")
@Component
public class UserEntityCreator {
private final SaltGenerator saltGenerator;
private final HashGenerator hashGenerator;
private final Tenants tenants;
@Autowired UserEntityCreator(
final SaltGenerator saltGenerator,
final HashGenerator hashGenerator,
final Tenants tenants)
{
this.saltGenerator = saltGenerator;
this.hashGenerator = hashGenerator;
this.tenants = tenants;
}
UserEntity build(
final String identifier,
final String role,
final String password,
final boolean passwordMustChange) {
final Optional<PrivateTenantInfoEntity> tenantInfo = tenants.getPrivateTenantInfo();
return tenantInfo
.map(x -> build(identifier, role, password, passwordMustChange,
x.getFixedSalt().array(), x.getPasswordExpiresInDays()))
.orElseThrow(() -> ServiceException.internalError("The tenant is not initialized."));
}
public UserEntity build(
final String identifier,
final String role,
final String password,
final boolean passwordMustChange,
final byte[] fixedSalt,
final int passwordExpiresInDays)
{
final UserEntity userEntity = new UserEntity();
userEntity.setIdentifier(identifier);
userEntity.setRole(role);
final byte[] variableSalt = this.saltGenerator.createRandomSalt();
final byte[] fullSalt = EncodingUtils.concatenate(variableSalt, fixedSalt);
userEntity.setPassword(ByteBuffer.wrap(this.hashGenerator.hash(password, fullSalt,
IdentityConstants.ITERATION_COUNT, IdentityConstants.HASH_LENGTH)));
userEntity.setSalt(ByteBuffer.wrap(variableSalt));
userEntity.setIterationCount(IdentityConstants.ITERATION_COUNT);
userEntity.setPasswordExpiresOn(deriveExpiration(passwordMustChange, passwordExpiresInDays));
return userEntity;
}
private LocalDate deriveExpiration(final boolean passwordMustChange, final int passwordExpiresInDays) {
final LocalDate now = Time.utcNowAsStaxLocalDate();
if (passwordMustChange)
return now;
else {
final int offset = (passwordExpiresInDays <= 0) ? 93 : passwordExpiresInDays;
return LocalDate.fromDaysSinceEpoch(now.getDaysSinceEpoch() + offset);
}
}
}
| 2,162 |
0 | Create_ds/fineract-cn-identity/service/src/main/java/org/apache/fineract/cn/identity/internal/command | Create_ds/fineract-cn-identity/service/src/main/java/org/apache/fineract/cn/identity/internal/command/handler/UserCommandHandler.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.fineract.cn.identity.internal.command.handler;
import org.apache.fineract.cn.command.annotation.Aggregate;
import org.apache.fineract.cn.command.annotation.CommandHandler;
import org.apache.fineract.cn.command.annotation.CommandLogLevel;
import org.apache.fineract.cn.command.annotation.EventEmitter;
import org.apache.fineract.cn.identity.api.v1.events.EventConstants;
import org.apache.fineract.cn.identity.internal.command.ChangeUserPasswordCommand;
import org.apache.fineract.cn.identity.internal.command.ChangeUserRoleCommand;
import org.apache.fineract.cn.identity.internal.command.CreateUserCommand;
import org.apache.fineract.cn.identity.internal.repository.UserEntity;
import org.apache.fineract.cn.identity.internal.repository.Users;
import org.apache.fineract.cn.lang.ServiceException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.util.Assert;
/**
* @author Myrle Krantz
*/
@SuppressWarnings("unused")
@Aggregate
@Component
public class UserCommandHandler {
private final Users usersRepository;
private final UserEntityCreator userEntityCreator;
@Autowired
UserCommandHandler(
final Users usersRepository,
final UserEntityCreator userEntityCreator)
{
this.usersRepository = usersRepository;
this.userEntityCreator = userEntityCreator;
}
@CommandHandler(logStart = CommandLogLevel.INFO, logFinish = CommandLogLevel.INFO)
@EventEmitter(selectorName = EventConstants.OPERATION_HEADER, selectorValue = EventConstants.OPERATION_PUT_USER_ROLEIDENTIFIER)
public String process(final ChangeUserRoleCommand command) {
final UserEntity user = usersRepository.get(command.getIdentifier())
.orElseThrow(() -> ServiceException.notFound(
"User " + command.getIdentifier() + " doesn't exist."));
user.setRole(command.getRole());
usersRepository.add(user);
return user.getIdentifier();
}
@CommandHandler(logStart = CommandLogLevel.INFO, logFinish = CommandLogLevel.INFO)
@EventEmitter(selectorName = EventConstants.OPERATION_HEADER, selectorValue = EventConstants.OPERATION_PUT_USER_PASSWORD)
public String process(final ChangeUserPasswordCommand command) {
final UserEntity user = usersRepository.get(command.getIdentifier())
.orElseThrow(() -> ServiceException.notFound(
"User " + command.getIdentifier() + " doesn't exist."));
final UserEntity userWithNewPassword = userEntityCreator.build(
user.getIdentifier(), user.getRole(), command.getPassword(),
!SecurityContextHolder.getContext().getAuthentication().getName().equals(command.getIdentifier()));
usersRepository.add(userWithNewPassword);
return user.getIdentifier();
}
@CommandHandler(logStart = CommandLogLevel.INFO, logFinish = CommandLogLevel.INFO)
@EventEmitter(selectorName = EventConstants.OPERATION_HEADER, selectorValue = EventConstants.OPERATION_POST_USER)
public String process(final CreateUserCommand command) {
Assert.hasText(command.getPassword());
final UserEntity userEntity = userEntityCreator.build(
command.getIdentifier(), command.getRole(), command.getPassword(), true);
usersRepository.add(userEntity);
return command.getIdentifier();
}
}
| 2,163 |
0 | Create_ds/fineract-cn-identity/service/src/main/java/org/apache/fineract/cn/identity/internal/command | Create_ds/fineract-cn-identity/service/src/main/java/org/apache/fineract/cn/identity/internal/command/handler/RoleCommandHandler.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.fineract.cn.identity.internal.command.handler;
import java.util.Optional;
import java.util.stream.Collectors;
import javax.annotation.Nonnull;
import org.apache.fineract.cn.command.annotation.Aggregate;
import org.apache.fineract.cn.command.annotation.CommandHandler;
import org.apache.fineract.cn.command.annotation.CommandLogLevel;
import org.apache.fineract.cn.command.annotation.EventEmitter;
import org.apache.fineract.cn.identity.api.v1.domain.Role;
import org.apache.fineract.cn.identity.api.v1.events.EventConstants;
import org.apache.fineract.cn.identity.internal.command.ChangeRoleCommand;
import org.apache.fineract.cn.identity.internal.command.CreateRoleCommand;
import org.apache.fineract.cn.identity.internal.command.DeleteRoleCommand;
import org.apache.fineract.cn.identity.internal.mapper.PermissionMapper;
import org.apache.fineract.cn.identity.internal.repository.RoleEntity;
import org.apache.fineract.cn.identity.internal.repository.Roles;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.Assert;
/**
* @author Myrle Krantz
*/
@SuppressWarnings("unused")
@Aggregate
@Component
public class RoleCommandHandler {
private final Roles roles;
@Autowired
public RoleCommandHandler(final Roles roles)
{
this.roles = roles;
}
@CommandHandler(logStart = CommandLogLevel.INFO, logFinish = CommandLogLevel.INFO)
@EventEmitter(selectorName = EventConstants.OPERATION_HEADER, selectorValue = EventConstants.OPERATION_PUT_ROLE)
public String process(final ChangeRoleCommand command) {
final Optional<RoleEntity> instance = roles.get(command.getIdentifier());
Assert.isTrue(instance.isPresent());
instance.ifPresent(x -> roles.change(mapRole(command.getInstance())));
return command.getInstance().getIdentifier();
}
@CommandHandler(logStart = CommandLogLevel.INFO, logFinish = CommandLogLevel.INFO)
@EventEmitter(selectorName = EventConstants.OPERATION_HEADER, selectorValue = EventConstants.OPERATION_POST_ROLE)
public String process(final CreateRoleCommand command) {
Assert.isTrue(!roles.get(command.getInstance().getIdentifier()).isPresent());
roles.add(mapRole(command.getInstance()));
return command.getInstance().getIdentifier();
}
@CommandHandler(logStart = CommandLogLevel.INFO, logFinish = CommandLogLevel.INFO)
@EventEmitter(selectorName = EventConstants.OPERATION_HEADER, selectorValue = EventConstants.OPERATION_DELETE_ROLE)
public String process(final DeleteRoleCommand command) {
final Optional<RoleEntity> instance = roles.get(command.getIdentifier());
Assert.isTrue(instance.isPresent());
instance.ifPresent(roles::delete);
return command.getIdentifier();
}
private @Nonnull RoleEntity mapRole(
@Nonnull final Role role) {
final RoleEntity ret = new RoleEntity();
ret.setIdentifier(role.getIdentifier());
ret.setPermissions(role.getPermissions().stream()
.map(PermissionMapper::mapToPermissionType)
.collect(Collectors.toList()));
return ret;
}
} | 2,164 |
0 | Create_ds/fineract-cn-identity/service/src/main/java/org/apache/fineract/cn/identity/internal/command | Create_ds/fineract-cn-identity/service/src/main/java/org/apache/fineract/cn/identity/internal/command/handler/AuthenticationCommandHandler.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.fineract.cn.identity.internal.command.handler;
import com.google.common.collect.Sets;
import com.google.gson.Gson;
import org.apache.fineract.cn.identity.api.v1.events.EventConstants;
import org.apache.fineract.cn.anubis.api.v1.domain.AllowedOperation;
import org.apache.fineract.cn.anubis.api.v1.domain.TokenContent;
import org.apache.fineract.cn.anubis.api.v1.domain.TokenPermission;
import org.apache.fineract.cn.anubis.provider.InvalidKeyTimestampException;
import org.apache.fineract.cn.anubis.provider.TenantRsaKeyProvider;
import org.apache.fineract.cn.anubis.security.AmitAuthenticationException;
import org.apache.fineract.cn.anubis.token.TenantAccessTokenSerializer;
import org.apache.fineract.cn.anubis.token.TenantApplicationRsaKeyProvider;
import org.apache.fineract.cn.anubis.token.TenantRefreshTokenSerializer;
import org.apache.fineract.cn.anubis.token.TokenDeserializationResult;
import org.apache.fineract.cn.anubis.token.TokenSerializationResult;
import org.apache.fineract.cn.command.annotation.Aggregate;
import org.apache.fineract.cn.command.annotation.CommandHandler;
import org.apache.fineract.cn.command.annotation.CommandLogLevel;
import org.apache.fineract.cn.crypto.HashGenerator;
import org.apache.fineract.cn.identity.internal.command.AuthenticationCommandResponse;
import org.apache.fineract.cn.identity.internal.command.PasswordAuthenticationCommand;
import org.apache.fineract.cn.identity.internal.command.RefreshTokenAuthenticationCommand;
import org.apache.fineract.cn.identity.internal.repository.AllowedOperationType;
import org.apache.fineract.cn.identity.internal.repository.ApplicationCallEndpointSetEntity;
import org.apache.fineract.cn.identity.internal.repository.ApplicationCallEndpointSets;
import org.apache.fineract.cn.identity.internal.repository.ApplicationPermissionUsers;
import org.apache.fineract.cn.identity.internal.repository.ApplicationPermissions;
import org.apache.fineract.cn.identity.internal.repository.ApplicationSignatureEntity;
import org.apache.fineract.cn.identity.internal.repository.ApplicationSignatures;
import org.apache.fineract.cn.identity.internal.repository.PermissionType;
import org.apache.fineract.cn.identity.internal.repository.PermittableGroupEntity;
import org.apache.fineract.cn.identity.internal.repository.PermittableGroups;
import org.apache.fineract.cn.identity.internal.repository.PermittableType;
import org.apache.fineract.cn.identity.internal.repository.PrivateSignatureEntity;
import org.apache.fineract.cn.identity.internal.repository.PrivateTenantInfoEntity;
import org.apache.fineract.cn.identity.internal.repository.RoleEntity;
import org.apache.fineract.cn.identity.internal.repository.Roles;
import org.apache.fineract.cn.identity.internal.repository.Signatures;
import org.apache.fineract.cn.identity.internal.repository.Tenants;
import org.apache.fineract.cn.identity.internal.repository.UserEntity;
import org.apache.fineract.cn.identity.internal.repository.Users;
import org.apache.fineract.cn.identity.internal.service.RoleMapper;
import org.apache.fineract.cn.identity.internal.util.IdentityConstants;
import org.apache.fineract.cn.lang.ApplicationName;
import org.apache.fineract.cn.lang.DateConverter;
import org.apache.fineract.cn.lang.ServiceException;
import org.apache.fineract.cn.lang.TenantContextHolder;
import org.apache.fineract.cn.lang.config.TenantHeaderFilter;
import org.apache.fineract.cn.lang.security.RsaPrivateKeyBuilder;
import org.apache.fineract.cn.lang.security.RsaPublicKeyBuilder;
import org.slf4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.jms.core.JmsTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.Base64Utils;
import javax.annotation.Nullable;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.ZoneId;
import java.util.*;
import java.util.stream.Collector;
import java.util.stream.Collectors;
import java.util.stream.Stream;
/**
* @author Myrle Krantz
*/
@SuppressWarnings({"unused", "WeakerAccess"})
@Aggregate
@Component
public class AuthenticationCommandHandler {
private final Users users;
private final Roles roles;
private final PermittableGroups permittableGroups;
private final Signatures signatures;
private final Tenants tenants;
private final HashGenerator hashGenerator;
private final TenantAccessTokenSerializer tenantAccessTokenSerializer;
private final TenantRefreshTokenSerializer tenantRefreshTokenSerializer;
private final TenantRsaKeyProvider tenantRsaKeyProvider;
private final ApplicationSignatures applicationSignatures;
private final ApplicationPermissions applicationPermissions;
private final ApplicationPermissionUsers applicationPermissionUsers;
private final ApplicationCallEndpointSets applicationCallEndpointSets;
private final JmsTemplate jmsTemplate;
private final Gson gson;
private final Logger logger;
private final ApplicationName applicationName;
@Value("${identity.token.access.ttl:1200}") //Given in seconds. Default 20 minutes.
private int accessTtl;
@Value("${identity.token.refresh.ttl:54000}") //Given in seconds. Default 15 hours.
private int refreshTtl;
@Autowired
public AuthenticationCommandHandler(final Users users,
final Roles roles,
final PermittableGroups permittableGroups,
final Signatures signatures,
final Tenants tenants,
final HashGenerator hashGenerator,
@SuppressWarnings("SpringJavaAutowiringInspection")
final TenantAccessTokenSerializer tenantAccessTokenSerializer,
@SuppressWarnings("SpringJavaAutowiringInspection")
final TenantRefreshTokenSerializer tenantRefreshTokenSerializer,
@SuppressWarnings("SpringJavaAutowiringInspection")
final TenantRsaKeyProvider tenantRsaKeyProvider,
final ApplicationSignatures applicationSignatures,
final ApplicationPermissions applicationPermissions,
final ApplicationPermissionUsers applicationPermissionUsers,
final ApplicationCallEndpointSets applicationCallEndpointSets,
final JmsTemplate jmsTemplate,
final ApplicationName applicationName,
@Qualifier(IdentityConstants.JSON_SERIALIZER_NAME) final Gson gson,
@Qualifier(IdentityConstants.LOGGER_NAME) final Logger logger) {
this.users = users;
this.roles = roles;
this.permittableGroups = permittableGroups;
this.signatures = signatures;
this.tenants = tenants;
this.hashGenerator = hashGenerator;
this.tenantAccessTokenSerializer = tenantAccessTokenSerializer;
this.tenantRefreshTokenSerializer = tenantRefreshTokenSerializer;
this.tenantRsaKeyProvider = tenantRsaKeyProvider;
this.applicationSignatures = applicationSignatures;
this.applicationPermissions = applicationPermissions;
this.applicationPermissionUsers = applicationPermissionUsers;
this.applicationCallEndpointSets = applicationCallEndpointSets;
this.jmsTemplate = jmsTemplate;
this.gson = gson;
this.logger = logger;
this.applicationName = applicationName;
}
@CommandHandler(logStart = CommandLogLevel.DEBUG, logFinish = CommandLogLevel.DEBUG)
public AuthenticationCommandResponse process(final PasswordAuthenticationCommand command)
throws AmitAuthenticationException
{
final byte[] base64decodedPassword;
try {
base64decodedPassword = Base64Utils.decodeFromString(command.getPassword());
}
catch (final IllegalArgumentException e)
{
throw ServiceException.badRequest("Password was not base64 encoded.");
}
final PrivateTenantInfoEntity privateTenantInfo = checkedGetPrivateTenantInfo();
final PrivateSignatureEntity privateSignature = checkedGetPrivateSignature();
byte[] fixedSalt = privateTenantInfo.getFixedSalt().array();
final UserEntity user = getUser(command.getUseridentifier());
if (!this.hashGenerator.isEqual(
user.getPassword().array(),
base64decodedPassword,
fixedSalt,
user.getSalt().array(),
user.getIterationCount(),
256))
{
throw AmitAuthenticationException.userPasswordCombinationNotFound();
}
final TokenSerializationResult refreshToken = getRefreshToken(user, privateSignature);
final AuthenticationCommandResponse ret = getAuthenticationResponse(
applicationName.toString(),
Optional.empty(),
privateTenantInfo,
privateSignature,
user,
refreshToken.getToken(),
refreshToken.getExpiration());
fireAuthenticationEvent(user.getIdentifier());
return ret;
}
private PrivateSignatureEntity checkedGetPrivateSignature() {
final Optional<PrivateSignatureEntity> privateSignature = signatures.getPrivateSignature();
if (!privateSignature.isPresent()) {
logger.error("Authentication attempted on tenant with no valid signature{}.", TenantContextHolder
.identifier());
throw ServiceException.internalError("Tenant has no valid signature.");
}
return privateSignature.get();
}
private PrivateTenantInfoEntity checkedGetPrivateTenantInfo() {
final Optional<PrivateTenantInfoEntity> privateTenantInfo = tenants.getPrivateTenantInfo();
if (!privateTenantInfo.isPresent()) {
logger.error("Authentication attempted on uninitialized tenant {}.", TenantContextHolder.identifier());
throw ServiceException.internalError("Tenant is not initialized.");
}
return privateTenantInfo.get();
}
private class TenantIdentityRsaKeyProvider implements TenantApplicationRsaKeyProvider {
@Override
public PublicKey getApplicationPublicKey(final String tokenApplicationName, final String timestamp) throws InvalidKeyTimestampException {
if (applicationName.toString().equals(tokenApplicationName))
return tenantRsaKeyProvider.getPublicKey(timestamp);
final ApplicationSignatureEntity signature = applicationSignatures.get(tokenApplicationName, timestamp)
.orElseThrow(() -> new InvalidKeyTimestampException(timestamp));
return new RsaPublicKeyBuilder()
.setPublicKeyMod(signature.getPublicKeyMod())
.setPublicKeyExp(signature.getPublicKeyExp())
.build();
}
}
@CommandHandler(logStart = CommandLogLevel.DEBUG, logFinish = CommandLogLevel.DEBUG)
public AuthenticationCommandResponse process(final RefreshTokenAuthenticationCommand command)
throws AmitAuthenticationException
{
final TokenDeserializationResult deserializedRefreshToken =
tenantRefreshTokenSerializer.deserialize(new TenantIdentityRsaKeyProvider(), command.getRefreshToken());
final PrivateTenantInfoEntity privateTenantInfo = checkedGetPrivateTenantInfo();
final PrivateSignatureEntity privateSignature = checkedGetPrivateSignature();
final UserEntity user = getUser(deserializedRefreshToken.getUserIdentifier());
final String sourceApplicationName = deserializedRefreshToken.getSourceApplication();
return getAuthenticationResponse(
sourceApplicationName,
Optional.ofNullable(deserializedRefreshToken.getEndpointSet()),
privateTenantInfo,
privateSignature,
user,
command.getRefreshToken(),
LocalDateTime.ofInstant(deserializedRefreshToken.getExpiration().toInstant(), ZoneId.of("UTC")));
}
private AuthenticationCommandResponse getAuthenticationResponse(
final String sourceApplicationName,
@SuppressWarnings("OptionalUsedAsFieldOrParameterType")
final Optional<String> callEndpointSet,
final PrivateTenantInfoEntity privateTenantInfo,
final PrivateSignatureEntity privateSignature,
final UserEntity user,
final String refreshToken,
final LocalDateTime refreshTokenExpiration) {
final Optional<LocalDateTime> passwordExpiration = getExpiration(user);
final int gracePeriod = privateTenantInfo.getTimeToChangePasswordAfterExpirationInDays();
if (pastGracePeriod(passwordExpiration, gracePeriod))
throw AmitAuthenticationException.passwordExpired();
final Set<TokenPermission> tokenPermissions;
if (sourceApplicationName.equals(applicationName.toString())) { //ie, this is a token for the identity manager.
if (pastExpiration(passwordExpiration)) {
tokenPermissions = identityEndpointsAllowedEvenWithExpiredPassword();
logger.info("Password expired {}", passwordExpiration.map(LocalDateTime::toString).orElse("empty"));
}
else {
tokenPermissions = getUserTokenPermissions(user);
}
}
else {
tokenPermissions = getApplicationTokenPermissions(user, sourceApplicationName, callEndpointSet);
}
final HashSet<TokenPermission> minifiedTokenPermissions = new HashSet<>(
tokenPermissions
.stream()
.collect(Collectors.toMap(TokenPermission::getPath,
tokenPermission -> tokenPermission,
(currentTokenPermission, newTokenPermission) -> {
newTokenPermission.getAllowedOperations()
.forEach(allowedOperation -> currentTokenPermission.getAllowedOperations().add(allowedOperation));
return currentTokenPermission;
})
)
.values()
);
logger.info("Access token for tenant '{}', user '{}', application '{}', and callEndpointSet '{}' being returned containing the permissions '{}'.",
TenantContextHolder.identifier().orElse("null"),
user.getIdentifier(),
sourceApplicationName,
callEndpointSet.orElse("null"),
minifiedTokenPermissions.toString());
final TokenSerializationResult accessToken = getAuthenticationResponse(
user.getIdentifier(),
minifiedTokenPermissions,
privateSignature,
sourceApplicationName);
return new AuthenticationCommandResponse(
accessToken.getToken(), DateConverter.toIsoString(accessToken.getExpiration()),
refreshToken, DateConverter.toIsoString(refreshTokenExpiration),
passwordExpiration.map(DateConverter::toIsoString).orElse(null));
}
private Optional<LocalDateTime> getExpiration(final UserEntity user)
{
if (user.getIdentifier().equals(IdentityConstants.SU_NAME))
return Optional.empty();
else
return Optional.of(LocalDateTime.of(
LocalDate.ofEpochDay(user.getPasswordExpiresOn().getDaysSinceEpoch()), //Convert from cassandra LocalDate to java LocalDate.
LocalTime.MIDNIGHT));
}
private UserEntity getUser(final String identifier) throws AmitAuthenticationException {
final Optional<UserEntity> user = users.get(identifier);
if (!user.isPresent()) {
this.logger.info("Attempt to get a user who doesn't exist: " + identifier);
throw AmitAuthenticationException.userPasswordCombinationNotFound();
}
return user.get();
}
private void fireAuthenticationEvent(final String userIdentifier) {
this.jmsTemplate.convertAndSend(
this.gson.toJson(userIdentifier),
message -> {
if (TenantContextHolder.identifier().isPresent()) {
//noinspection OptionalGetWithoutIsPresent
message.setStringProperty(
TenantHeaderFilter.TENANT_HEADER,
TenantContextHolder.identifier().get());
}
message.setStringProperty(EventConstants.OPERATION_HEADER,
EventConstants.OPERATION_AUTHENTICATE
);
return message;
}
);
}
private TokenSerializationResult getAuthenticationResponse(
final String userIdentifier,
final Set<TokenPermission> tokenPermissions,
final PrivateSignatureEntity privateSignatureEntity,
final String sourceApplication) {
final PrivateKey privateKey = new RsaPrivateKeyBuilder()
.setPrivateKeyExp(privateSignatureEntity.getPrivateKeyExp())
.setPrivateKeyMod(privateSignatureEntity.getPrivateKeyMod())
.build();
final TenantAccessTokenSerializer.Specification x =
new TenantAccessTokenSerializer.Specification()
.setKeyTimestamp(privateSignatureEntity.getKeyTimestamp())
.setPrivateKey(privateKey)
.setTokenContent(new TokenContent(new ArrayList<>(tokenPermissions)))
.setSecondsToLive(accessTtl)
.setUser(userIdentifier)
.setSourceApplication(sourceApplication);
return tenantAccessTokenSerializer.build(x);
}
private Set<TokenPermission> getUserTokenPermissions(
final UserEntity user) {
final Optional<RoleEntity> userRole = roles.get(user.getRole());
final Set<TokenPermission> tokenPermissions = userRole
.map(r -> r.getPermissions().stream().flatMap(this::mapPermissions).collect(Collectors.toSet()))
.orElse(new HashSet<>());
tokenPermissions.addAll(identityEndpointsForEveryUser());
return tokenPermissions;
}
private Set<TokenPermission> getApplicationTokenPermissions(
final UserEntity user,
final String sourceApplicationName,
@SuppressWarnings("OptionalUsedAsFieldOrParameterType") final Optional<String> callEndpointSet) {
//If the call endpoint set was given, but does not correspond to a stored call endpoint set, throw an exception.
//If it wasn't given then return all of the permissions for the application.
final Optional<ApplicationCallEndpointSetEntity> applicationCallEndpointSet = callEndpointSet.map(x -> {
final Optional<ApplicationCallEndpointSetEntity> optionalEndpointSetEntity =
applicationCallEndpointSets.get(sourceApplicationName, x);
if (optionalEndpointSetEntity.isPresent()) {
return optionalEndpointSetEntity.get();
} else {
throw AmitAuthenticationException.invalidToken();
}
});
final RoleEntity userRole = roles.get(user.getRole())
.orElseThrow(AmitAuthenticationException::userPasswordCombinationNotFound);
return applicationCallEndpointSet.map(x -> this.getApplicationCallEndpointSetTokenPermissions(user.getIdentifier(), userRole, x, sourceApplicationName))
.orElseGet(() -> this.getApplicationUserTokenPermissions(user.getIdentifier(), userRole, sourceApplicationName));
}
private Set<TokenPermission> getApplicationCallEndpointSetTokenPermissions(
final String userIdentifier,
final RoleEntity userRole,
final ApplicationCallEndpointSetEntity applicationCallEndpointSet,
final String sourceApplicationName) {
final List<PermissionType> permissionsForUser = userRole.getPermissions();
final Set<PermissionType> permissionsRequestedByApplication = applicationCallEndpointSet.getCallEndpointGroupIdentifiers().stream()
.map(x -> applicationPermissions.getPermissionForApplication(sourceApplicationName, x))
.filter(Optional::isPresent)
.map(Optional::get)
.collect(Collectors.toSet());
final Stream<PermissionType> applicationRequestedPermissionsTheUserHas
= intersectPermissionList(permissionsForUser, permissionsRequestedByApplication.stream());
final Set<PermissionType> permissionsPossible = applicationRequestedPermissionsTheUserHas
.filter(x ->
applicationPermissionUsers.enabled(sourceApplicationName, x.getPermittableGroupIdentifier(), userIdentifier))
.collect(Collectors.toSet());
if (!permissionsPossible.containsAll(permissionsRequestedByApplication))
throw AmitAuthenticationException.applicationMissingPermissions(userIdentifier, sourceApplicationName);
return permissionsPossible.stream()
.flatMap(this::mapPermissions)
.collect(Collectors.toSet());
}
private Set<TokenPermission> getApplicationUserTokenPermissions(
final String userIdentifier,
final RoleEntity userRole,
final String sourceApplicationName) {
final List<PermissionType> permissionsForUser = userRole.getPermissions();
final List<PermissionType> permissionsRequestedByApplication = applicationPermissions.getAllPermissionsForApplication(sourceApplicationName);
final Stream<PermissionType> applicationRequestedPermissionsTheUserHas
= intersectPermissionList(permissionsForUser, permissionsRequestedByApplication.stream());
return applicationRequestedPermissionsTheUserHas
.filter(x ->
applicationPermissionUsers.enabled(sourceApplicationName, x.getPermittableGroupIdentifier(), userIdentifier))
.flatMap(this::mapPermissions)
.collect(Collectors.toSet());
}
private Stream<PermissionType> intersectPermissionList(
final List<PermissionType> permissionsForUser,
final Stream<PermissionType> permissionsRequestedByApplication) {
final Map<String, Set<AllowedOperationType>> keyedUserPermissions = transformToSearchablePermissions(permissionsForUser);
return permissionsRequestedByApplication
.map(x -> new PermissionType(
x.getPermittableGroupIdentifier(),
intersectSets(keyedUserPermissions.get(x.getPermittableGroupIdentifier()), x.getAllowedOperations())))
.filter(x -> !x.getAllowedOperations().isEmpty());
}
static <T> Set<T> intersectSets(
final @Nullable Set<T> allowedOperations1,
final @Nullable Set<T> allowedOperations2) {
if (allowedOperations1 == null || allowedOperations2 == null)
return Collections.emptySet();
final Set<T> ret = new HashSet<>(allowedOperations1);
ret.retainAll(allowedOperations2);
return ret;
}
static Map<String, Set<AllowedOperationType>> transformToSearchablePermissions(final List<PermissionType> permissionsForUser) {
final Collector<Set<AllowedOperationType>, Set<AllowedOperationType>, Set<AllowedOperationType>> setToSetCollector
= Collector.of(
HashSet::new,
Set::addAll,
(x, y) -> {
final Set<AllowedOperationType> ret = new HashSet<>();
ret.addAll(x);
ret.addAll(y);
return ret;
});
return permissionsForUser.stream().collect(
Collectors.groupingBy(PermissionType::getPermittableGroupIdentifier,
Collectors.mapping(PermissionType::getAllowedOperations, setToSetCollector)));
}
private Set<TokenPermission> identityEndpointsForEveryUser() {
final Set<TokenPermission> ret = identityEndpointsAllowedEvenWithExpiredPassword();
ret.add(new TokenPermission(
applicationName + "/applications/*/permissions/*/users/{useridentifier}/enabled",
Sets.newHashSet(AllowedOperation.READ, AllowedOperation.CHANGE, AllowedOperation.DELETE)));
ret.add(new TokenPermission(
applicationName + "/users/{useridentifier}/permissions",
Sets.newHashSet(AllowedOperation.READ)));
return ret;
}
private Set<TokenPermission> identityEndpointsAllowedEvenWithExpiredPassword() {
final Set<TokenPermission> ret = new HashSet<>();
ret.add(new TokenPermission(
applicationName + "/users/{useridentifier}/password",
Sets.newHashSet(AllowedOperation.READ, AllowedOperation.CHANGE, AllowedOperation.DELETE)));
ret.add(new TokenPermission(
applicationName + "/token/_current",
Sets.newHashSet(AllowedOperation.DELETE)));
return ret;
}
static boolean pastExpiration(
@SuppressWarnings("OptionalUsedAsFieldOrParameterType") final Optional<LocalDateTime> passwordExpiration) {
return passwordExpiration.map(x -> LocalDateTime.now().compareTo(x) >= 0).orElse(false);
}
static boolean pastGracePeriod(
@SuppressWarnings("OptionalUsedAsFieldOrParameterType") final Optional<LocalDateTime> passwordExpiration,
final long gracePeriod) {
return passwordExpiration.map(x -> (LocalDateTime.now().compareTo(x.plusDays(gracePeriod)) >= 0)).orElse(false);
}
private Stream<TokenPermission> mapPermissions(final PermissionType permission) {
return permittableGroups.get(permission.getPermittableGroupIdentifier())
.map(PermittableGroupEntity::getPermittables)
.map(Collection::stream)
.orElse(Stream.empty())
.filter(permittable -> isAllowed(permittable, permission))
.map(this::getTokenPermission);
}
private boolean isAllowed(final PermittableType permittable, final PermissionType permission) {
return permission.getAllowedOperations().contains(AllowedOperationType.fromHttpMethod(permittable.getMethod()));
}
private TokenPermission getTokenPermission(final PermittableType permittable) {
final HashSet<AllowedOperation> allowedOperations = new HashSet<>();
allowedOperations.add(RoleMapper.mapAllowedOperation(AllowedOperationType.fromHttpMethod(permittable.getMethod())));
return new TokenPermission(permittable.getPath(), allowedOperations);
}
private TokenSerializationResult getRefreshToken(final UserEntity user,
final PrivateSignatureEntity privateSignatureEntity) {
final PrivateKey privateKey = new RsaPrivateKeyBuilder()
.setPrivateKeyExp(privateSignatureEntity.getPrivateKeyExp())
.setPrivateKeyMod(privateSignatureEntity.getPrivateKeyMod())
.build();
final TenantRefreshTokenSerializer.Specification x =
new TenantRefreshTokenSerializer.Specification()
.setKeyTimestamp(privateSignatureEntity.getKeyTimestamp())
.setPrivateKey(privateKey)
.setSecondsToLive(refreshTtl)
.setUser(user.getIdentifier())
.setSourceApplication(applicationName.toString());
return tenantRefreshTokenSerializer.build(x);
}
}
| 2,165 |
0 | Create_ds/fineract-cn-identity/service/src/main/java/org/apache/fineract/cn/identity/internal/command | Create_ds/fineract-cn-identity/service/src/main/java/org/apache/fineract/cn/identity/internal/command/handler/PermittableGroupCommandHandler.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.fineract.cn.identity.internal.command.handler;
import java.util.stream.Collectors;
import org.apache.fineract.cn.anubis.api.v1.domain.PermittableEndpoint;
import org.apache.fineract.cn.command.annotation.Aggregate;
import org.apache.fineract.cn.command.annotation.CommandHandler;
import org.apache.fineract.cn.command.annotation.CommandLogLevel;
import org.apache.fineract.cn.command.annotation.EventEmitter;
import org.apache.fineract.cn.identity.api.v1.domain.PermittableGroup;
import org.apache.fineract.cn.identity.api.v1.events.EventConstants;
import org.apache.fineract.cn.identity.internal.command.CreatePermittableGroupCommand;
import org.apache.fineract.cn.identity.internal.repository.PermittableGroupEntity;
import org.apache.fineract.cn.identity.internal.repository.PermittableGroups;
import org.apache.fineract.cn.identity.internal.repository.PermittableType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.Assert;
/**
* @author Myrle Krantz
*/
@SuppressWarnings("unused")
@Aggregate
@Component
public class PermittableGroupCommandHandler {
private final PermittableGroups repository;
@Autowired
public PermittableGroupCommandHandler(final PermittableGroups repository)
{
this.repository = repository;
}
@CommandHandler(logStart = CommandLogLevel.INFO, logFinish = CommandLogLevel.INFO)
@EventEmitter(selectorName = EventConstants.OPERATION_HEADER, selectorValue = EventConstants.OPERATION_POST_PERMITTABLE_GROUP)
public String process(final CreatePermittableGroupCommand command) {
Assert.isTrue(!repository.get(command.getInstance().getIdentifier()).isPresent());
repository.add(map(command.getInstance()));
return command.getInstance().getIdentifier();
}
private PermittableGroupEntity map(final PermittableGroup instance) {
final PermittableGroupEntity ret = new PermittableGroupEntity();
ret.setIdentifier(instance.getIdentifier());
ret.setPermittables(instance.getPermittables().stream().map(this::map).collect(Collectors.toList()));
return ret;
}
private PermittableType map(final PermittableEndpoint instance) {
final PermittableType ret = new PermittableType();
ret.setMethod(instance.getMethod());
ret.setSourceGroupId(instance.getGroupId());
ret.setPath(instance.getPath());
return ret;
}
}
| 2,166 |
0 | Create_ds/fineract-cn-identity/service/src/main/java/org/apache/fineract/cn/identity/internal/command | Create_ds/fineract-cn-identity/service/src/main/java/org/apache/fineract/cn/identity/internal/command/handler/ApplicationCommandHandler.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.fineract.cn.identity.internal.command.handler;
import org.apache.fineract.cn.command.annotation.Aggregate;
import org.apache.fineract.cn.command.annotation.CommandHandler;
import org.apache.fineract.cn.command.annotation.CommandLogLevel;
import org.apache.fineract.cn.command.annotation.EventEmitter;
import org.apache.fineract.cn.identity.api.v1.events.ApplicationCallEndpointSetEvent;
import org.apache.fineract.cn.identity.api.v1.events.ApplicationPermissionEvent;
import org.apache.fineract.cn.identity.api.v1.events.ApplicationPermissionUserEvent;
import org.apache.fineract.cn.identity.api.v1.events.ApplicationSignatureEvent;
import org.apache.fineract.cn.identity.api.v1.events.EventConstants;
import org.apache.fineract.cn.identity.internal.command.ChangeApplicationCallEndpointSetCommand;
import org.apache.fineract.cn.identity.internal.command.CreateApplicationCallEndpointSetCommand;
import org.apache.fineract.cn.identity.internal.command.CreateApplicationPermissionCommand;
import org.apache.fineract.cn.identity.internal.command.DeleteApplicationCallEndpointSetCommand;
import org.apache.fineract.cn.identity.internal.command.DeleteApplicationCommand;
import org.apache.fineract.cn.identity.internal.command.DeleteApplicationPermissionCommand;
import org.apache.fineract.cn.identity.internal.command.SetApplicationPermissionUserEnabledCommand;
import org.apache.fineract.cn.identity.internal.command.SetApplicationSignatureCommand;
import org.apache.fineract.cn.identity.internal.mapper.ApplicationCallEndpointSetMapper;
import org.apache.fineract.cn.identity.internal.mapper.PermissionMapper;
import org.apache.fineract.cn.identity.internal.repository.ApplicationCallEndpointSetEntity;
import org.apache.fineract.cn.identity.internal.repository.ApplicationCallEndpointSets;
import org.apache.fineract.cn.identity.internal.repository.ApplicationPermissionEntity;
import org.apache.fineract.cn.identity.internal.repository.ApplicationPermissionUsers;
import org.apache.fineract.cn.identity.internal.repository.ApplicationPermissions;
import org.apache.fineract.cn.identity.internal.repository.ApplicationSignatureEntity;
import org.apache.fineract.cn.identity.internal.repository.ApplicationSignatures;
import org.apache.fineract.cn.lang.ServiceException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
/**
* @author Myrle Krantz
*/
@SuppressWarnings("unused")
@Aggregate
@Component
public class ApplicationCommandHandler {
private final ApplicationSignatures applicationSignatures;
private final ApplicationPermissions applicationPermissions;
private final ApplicationPermissionUsers applicationPermissionUsers;
private final ApplicationCallEndpointSets applicationCallEndpointSets;
@Autowired
public ApplicationCommandHandler(final ApplicationSignatures applicationSignatures,
final ApplicationPermissions applicationPermissions,
final ApplicationPermissionUsers applicationPermissionUsers,
final ApplicationCallEndpointSets applicationCallEndpointSets) {
this.applicationSignatures = applicationSignatures;
this.applicationPermissions = applicationPermissions;
this.applicationPermissionUsers = applicationPermissionUsers;
this.applicationCallEndpointSets = applicationCallEndpointSets;
}
@CommandHandler(logStart = CommandLogLevel.INFO, logFinish = CommandLogLevel.INFO)
@EventEmitter(selectorName = EventConstants.OPERATION_HEADER, selectorValue = EventConstants.OPERATION_PUT_APPLICATION_SIGNATURE)
public ApplicationSignatureEvent process(final SetApplicationSignatureCommand command) {
final ApplicationSignatureEntity applicationSignatureEntity = new ApplicationSignatureEntity();
applicationSignatureEntity.setApplicationIdentifier(command.getApplicationIdentifier());
applicationSignatureEntity.setKeyTimestamp(command.getKeyTimestamp());
applicationSignatureEntity.setPublicKeyMod(command.getSignature().getPublicKeyMod());
applicationSignatureEntity.setPublicKeyExp(command.getSignature().getPublicKeyExp());
applicationSignatures.add(applicationSignatureEntity);
return new ApplicationSignatureEvent(command.getApplicationIdentifier(), command.getKeyTimestamp());
}
@CommandHandler(logStart = CommandLogLevel.INFO, logFinish = CommandLogLevel.INFO)
@EventEmitter(selectorName = EventConstants.OPERATION_HEADER, selectorValue = EventConstants.OPERATION_DELETE_APPLICATION)
public String process(final DeleteApplicationCommand command) {
applicationSignatures.delete(command.getApplicationIdentifier());
return command.getApplicationIdentifier();
}
@CommandHandler(logStart = CommandLogLevel.INFO, logFinish = CommandLogLevel.INFO)
@EventEmitter(selectorName = EventConstants.OPERATION_HEADER, selectorValue = EventConstants.OPERATION_POST_APPLICATION_PERMISSION)
public ApplicationPermissionEvent process(final CreateApplicationPermissionCommand command) {
final ApplicationPermissionEntity applicationPermissionEntity = new ApplicationPermissionEntity(
command.getApplicationIdentifer(), PermissionMapper.mapToPermissionType(command.getPermission()));
applicationPermissions.add(applicationPermissionEntity);
return new ApplicationPermissionEvent(command.getApplicationIdentifer(), command.getPermission().getPermittableEndpointGroupIdentifier());
}
@CommandHandler(logStart = CommandLogLevel.INFO, logFinish = CommandLogLevel.INFO)
@EventEmitter(selectorName = EventConstants.OPERATION_HEADER, selectorValue = EventConstants.OPERATION_DELETE_APPLICATION_PERMISSION)
public ApplicationPermissionEvent process(final DeleteApplicationPermissionCommand command) {
applicationPermissions.delete(command.getApplicationIdentifier(), command.getPermittableGroupIdentifier());
return new ApplicationPermissionEvent(command.getApplicationIdentifier(), command.getPermittableGroupIdentifier());
}
@CommandHandler(logStart = CommandLogLevel.INFO, logFinish = CommandLogLevel.INFO)
@EventEmitter(selectorName = EventConstants.OPERATION_HEADER, selectorValue = EventConstants.OPERATION_PUT_APPLICATION_PERMISSION_USER_ENABLED)
public ApplicationPermissionUserEvent process(final SetApplicationPermissionUserEnabledCommand command) {
applicationPermissionUsers.setEnabled(command.getApplicationIdentifier(), command.getPermittableGroupIdentifier(), command.getUserIdentifier(), command.isEnabled());
return new ApplicationPermissionUserEvent(command.getApplicationIdentifier(), command.getPermittableGroupIdentifier(), command.getUserIdentifier());
}
@CommandHandler(logStart = CommandLogLevel.INFO, logFinish = CommandLogLevel.INFO)
@EventEmitter(selectorName = EventConstants.OPERATION_HEADER, selectorValue = EventConstants.OPERATION_PUT_APPLICATION_CALLENDPOINTSET)
public ApplicationCallEndpointSetEvent process(final ChangeApplicationCallEndpointSetCommand command) {
applicationCallEndpointSets.get(command.getApplicationIdentifier(), command.getCallEndpointSetIdentifier())
.orElseThrow(() -> ServiceException.notFound("No application call endpoint '"
+ command.getApplicationIdentifier() + "." + command.getCallEndpointSetIdentifier() + "'."));
final ApplicationCallEndpointSetEntity toSave = ApplicationCallEndpointSetMapper.mapToEntity(
command.getApplicationIdentifier(),
command.getCallEndpointSet());
applicationCallEndpointSets.change(toSave);
return new ApplicationCallEndpointSetEvent(command.getApplicationIdentifier(), command.getCallEndpointSetIdentifier());
}
@CommandHandler(logStart = CommandLogLevel.INFO, logFinish = CommandLogLevel.INFO)
@EventEmitter(selectorName = EventConstants.OPERATION_HEADER, selectorValue = EventConstants.OPERATION_POST_APPLICATION_CALLENDPOINTSET)
public ApplicationCallEndpointSetEvent process(final CreateApplicationCallEndpointSetCommand command) {
if (!applicationSignatures.signaturesExistForApplication(command.getApplicationIdentifier()))
throw ServiceException.notFound("No application '" + command.getApplicationIdentifier() + "'.");
final ApplicationCallEndpointSetEntity toSave = ApplicationCallEndpointSetMapper.mapToEntity(
command.getApplicationIdentifier(),
command.getCallEndpointSet());
applicationCallEndpointSets.add(toSave);
return new ApplicationCallEndpointSetEvent(command.getApplicationIdentifier(), command.getCallEndpointSet().getIdentifier());
}
@CommandHandler(logStart = CommandLogLevel.INFO, logFinish = CommandLogLevel.INFO)
@EventEmitter(selectorName = EventConstants.OPERATION_HEADER, selectorValue = EventConstants.OPERATION_DELETE_APPLICATION_CALLENDPOINTSET)
public ApplicationCallEndpointSetEvent process(final DeleteApplicationCallEndpointSetCommand command) {
applicationCallEndpointSets.get(command.getApplicationIdentifier(), command.getCallEndpointSetIdentifier())
.orElseThrow(() -> ServiceException.notFound("No application call endpoint '"
+ command.getApplicationIdentifier() + "." + command.getCallEndpointSetIdentifier() + "'."));
applicationCallEndpointSets.delete(command.getApplicationIdentifier(), command.getCallEndpointSetIdentifier());
return new ApplicationCallEndpointSetEvent(command.getApplicationIdentifier(), command.getCallEndpointSetIdentifier());
}
} | 2,167 |
0 | Create_ds/fineract-cn-identity/service/src/main/java/org/apache/fineract/cn/identity/internal | Create_ds/fineract-cn-identity/service/src/main/java/org/apache/fineract/cn/identity/internal/service/UserService.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.fineract.cn.identity.internal.service;
import org.apache.fineract.cn.identity.api.v1.PermittableGroupIds;
import org.apache.fineract.cn.identity.api.v1.domain.Permission;
import org.apache.fineract.cn.identity.api.v1.domain.User;
import org.apache.fineract.cn.anubis.api.v1.domain.AllowedOperation;
import org.apache.fineract.cn.identity.internal.repository.PermissionType;
import org.apache.fineract.cn.identity.internal.repository.RoleEntity;
import org.apache.fineract.cn.identity.internal.repository.Roles;
import org.apache.fineract.cn.identity.internal.repository.UserEntity;
import org.apache.fineract.cn.identity.internal.repository.Users;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.*;
import java.util.stream.Collectors;
/**
* @author Myrle Krantz
*/
@Service
public class UserService {
private final Users users;
private final Roles roles;
@Autowired
UserService(final Users users, final Roles roles)
{
this.users = users;
this.roles = roles;
}
public List<User> findAll() {
return users.getAll().stream().map(UserService::mapUser).collect(Collectors.toList());
}
public Optional<User> findByIdentifier(final String identifier)
{
return users.get(identifier).map(UserService::mapUser);
}
static private User mapUser(final UserEntity u) {
return new User(u.getIdentifier(), u.getRole());
}
public Set<Permission> getPermissions(final String userIdentifier) {
final Optional<UserEntity> userEntity = users.get(userIdentifier);
final Optional<RoleEntity> roleEntity = userEntity.map(UserEntity::getRole).map(roles::get).orElse(Optional.empty());
final List<PermissionType> permissionEntities = roleEntity.map(RoleEntity::getPermissions).orElse(Collections.emptyList());
final List<Permission> permissions = RoleMapper.mapPermissions(permissionEntities);
permissions.add(new Permission(PermittableGroupIds.SELF_MANAGEMENT, AllowedOperation.ALL));
return new HashSet<>(permissions);
}
} | 2,168 |
0 | Create_ds/fineract-cn-identity/service/src/main/java/org/apache/fineract/cn/identity/internal | Create_ds/fineract-cn-identity/service/src/main/java/org/apache/fineract/cn/identity/internal/service/PermittableGroupService.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.fineract.cn.identity.internal.service;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;
import org.apache.fineract.cn.anubis.api.v1.domain.PermittableEndpoint;
import org.apache.fineract.cn.identity.api.v1.domain.PermittableGroup;
import org.apache.fineract.cn.identity.internal.repository.PermittableGroupEntity;
import org.apache.fineract.cn.identity.internal.repository.PermittableGroups;
import org.apache.fineract.cn.identity.internal.repository.PermittableType;
import org.springframework.stereotype.Service;
/**
* @author Myrle Krantz
*/
@Service
public class PermittableGroupService {
private final PermittableGroups repository;
public PermittableGroupService(final PermittableGroups repository) {
this.repository = repository;
}
public Optional<PermittableGroup> findByIdentifier(final String identifier) {
final Optional<PermittableGroupEntity> ret = repository.get(identifier);
return ret.map(this::mapPermittableGroup);
}
public List<PermittableGroup> findAll() {
return repository.getAll().stream()
.map(this::mapPermittableGroup)
.collect(Collectors.toList());
}
private PermittableGroup mapPermittableGroup(final PermittableGroupEntity permittableGroupEntity) {
final PermittableGroup ret = new PermittableGroup();
ret.setIdentifier(permittableGroupEntity.getIdentifier());
ret.setPermittables(permittableGroupEntity.getPermittables().stream()
.map(this::mapPermittable)
.collect(Collectors.toList()));
return ret;
}
private PermittableEndpoint mapPermittable(final PermittableType entity) {
final PermittableEndpoint ret = new PermittableEndpoint();
ret.setMethod(entity.getMethod());
ret.setGroupId(entity.getSourceGroupId());
ret.setPath(entity.getPath());
return ret;
}
}
| 2,169 |
0 | Create_ds/fineract-cn-identity/service/src/main/java/org/apache/fineract/cn/identity/internal | Create_ds/fineract-cn-identity/service/src/main/java/org/apache/fineract/cn/identity/internal/service/RoleService.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.fineract.cn.identity.internal.service;
import org.apache.fineract.cn.identity.api.v1.domain.Role;
import org.apache.fineract.cn.identity.internal.repository.RoleEntity;
import org.apache.fineract.cn.identity.internal.repository.Roles;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;
/**
* @author Myrle Krantz
*/
@Service
public class RoleService {
private final Roles repository;
@Autowired
public RoleService(final Roles repository) {
this.repository = repository;
}
public List<Role> findAll() {
return repository.getAll().stream()
.map(this::mapEntity)
.sorted((x, y) -> (x.getIdentifier().compareTo(y.getIdentifier())))
.collect(Collectors.toList());
}
private Role mapEntity(final RoleEntity roleEntity) {
final Role ret = new Role();
ret.setIdentifier(roleEntity.getIdentifier());
ret.setPermissions(RoleMapper.mapPermissions(roleEntity.getPermissions()));
return ret;
}
public Optional<Role> findByIdentifier(final String identifier)
{
final Optional<RoleEntity> ret = repository.get(identifier);
return ret.map(this::mapEntity);
}
}
| 2,170 |
0 | Create_ds/fineract-cn-identity/service/src/main/java/org/apache/fineract/cn/identity/internal | Create_ds/fineract-cn-identity/service/src/main/java/org/apache/fineract/cn/identity/internal/service/TenantService.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.fineract.cn.identity.internal.service;
import java.security.PrivateKey;
import java.security.interfaces.RSAPrivateKey;
import java.util.List;
import java.util.Optional;
import org.apache.fineract.cn.anubis.api.v1.domain.ApplicationSignatureSet;
import org.apache.fineract.cn.anubis.api.v1.domain.Signature;
import org.apache.fineract.cn.anubis.config.TenantSignatureRepository;
import org.apache.fineract.cn.identity.internal.mapper.SignatureMapper;
import org.apache.fineract.cn.identity.internal.repository.PrivateSignatureEntity;
import org.apache.fineract.cn.identity.internal.repository.SignatureEntity;
import org.apache.fineract.cn.identity.internal.repository.Signatures;
import org.apache.fineract.cn.lang.security.RsaKeyPairFactory;
import org.apache.fineract.cn.lang.security.RsaPrivateKeyBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
/**
* @author Myrle Krantz
*/
@Service
public class TenantService implements TenantSignatureRepository {
private final Signatures signatures;
@Autowired
TenantService(final Signatures signatures)
{
this.signatures = signatures;
}
public Optional<Signature> getIdentityManagerSignature(final String keyTimestamp) {
final Optional<SignatureEntity> signature = signatures.getSignature(keyTimestamp);
return signature.map(x -> new Signature(x.getPublicKeyMod(), x.getPublicKeyExp()));
}
@Override
public List<String> getAllSignatureSetKeyTimestamps() {
return signatures.getAllKeyTimestamps();
}
@Override
public Optional<ApplicationSignatureSet> getSignatureSet(final String keyTimestamp) {
final Optional<SignatureEntity> signatureEntity = signatures.getSignature(keyTimestamp);
return signatureEntity.map(SignatureMapper::mapToApplicationSignatureSet);
}
@Override
public void deleteSignatureSet(final String keyTimestamp) {
signatures.invalidateEntry(keyTimestamp);
}
@Override
public Optional<Signature> getApplicationSignature(final String keyTimestamp) {
final Optional<SignatureEntity> signatureEntity = signatures.getSignature(keyTimestamp);
return signatureEntity.map(x -> new Signature(x.getPublicKeyMod(), x.getPublicKeyExp()));
}
public ApplicationSignatureSet createSignatureSet() {
final RsaKeyPairFactory.KeyPairHolder keys = RsaKeyPairFactory.createKeyPair();
final SignatureEntity signatureEntity = signatures.add(keys);
return SignatureMapper.mapToApplicationSignatureSet(signatureEntity);
}
@Override
public Optional<ApplicationSignatureSet> getLatestSignatureSet() {
Optional<String> timestamp = getMostRecentTimestamp();
return timestamp.flatMap(this::getSignatureSet);
}
@Override
public Optional<Signature> getLatestApplicationSignature() {
Optional<String> timestamp = getMostRecentTimestamp();
return timestamp.flatMap(this::getApplicationSignature);
}
@Override
public Optional<RsaKeyPairFactory.KeyPairHolder> getLatestApplicationSigningKeyPair() {
final Optional<PrivateSignatureEntity> privateSignatureEntity = signatures.getPrivateSignature();
return privateSignatureEntity.map(x -> {
final String timestamp = x.getKeyTimestamp();
final PrivateKey privateKey = new RsaPrivateKeyBuilder()
.setPrivateKeyExp(x.getPrivateKeyExp())
.setPrivateKeyMod(x.getPrivateKeyMod())
.build();
return new RsaKeyPairFactory.KeyPairHolder(timestamp, null, (RSAPrivateKey)privateKey);
});
}
private Optional<String> getMostRecentTimestamp() {
return getAllSignatureSetKeyTimestamps().stream()
.max(String::compareTo);
}
}
| 2,171 |
0 | Create_ds/fineract-cn-identity/service/src/main/java/org/apache/fineract/cn/identity/internal | Create_ds/fineract-cn-identity/service/src/main/java/org/apache/fineract/cn/identity/internal/service/ApplicationService.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.fineract.cn.identity.internal.service;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;
import javax.annotation.Nonnull;
import org.apache.fineract.cn.anubis.api.v1.domain.Signature;
import org.apache.fineract.cn.identity.api.v1.domain.CallEndpointSet;
import org.apache.fineract.cn.identity.api.v1.domain.Permission;
import org.apache.fineract.cn.identity.internal.mapper.ApplicationCallEndpointSetMapper;
import org.apache.fineract.cn.identity.internal.mapper.PermissionMapper;
import org.apache.fineract.cn.identity.internal.mapper.SignatureMapper;
import org.apache.fineract.cn.identity.internal.repository.ApplicationCallEndpointSets;
import org.apache.fineract.cn.identity.internal.repository.ApplicationPermissionUsers;
import org.apache.fineract.cn.identity.internal.repository.ApplicationPermissions;
import org.apache.fineract.cn.identity.internal.repository.ApplicationSignatureEntity;
import org.apache.fineract.cn.identity.internal.repository.ApplicationSignatures;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
/**
* @author Myrle Krantz
*/
@Service
public class ApplicationService {
private final ApplicationSignatures applicationSignaturesRepository;
private final ApplicationPermissions applicationPermissionsRepository;
private final ApplicationPermissionUsers applicationPermissionsUserRepository;
private final ApplicationCallEndpointSets applicationCallEndpointSets;
@Autowired
public ApplicationService(final ApplicationSignatures applicationSignaturesRepository,
final ApplicationPermissions applicationPermissionsRepository,
final ApplicationPermissionUsers applicationPermissionsUserRepository,
final ApplicationCallEndpointSets applicationCallEndpointSets) {
this.applicationSignaturesRepository = applicationSignaturesRepository;
this.applicationPermissionsRepository = applicationPermissionsRepository;
this.applicationPermissionsUserRepository = applicationPermissionsUserRepository;
this.applicationCallEndpointSets = applicationCallEndpointSets;
}
public List<String> getAllApplications() {
return applicationSignaturesRepository.getAll().stream()
.map(ApplicationSignatureEntity::getApplicationIdentifier)
.collect(Collectors.toList());
}
public List<Permission> getAllPermissionsForApplication(final String applicationIdentifier) {
return applicationPermissionsRepository.getAllPermissionsForApplication(applicationIdentifier).stream()
.map(PermissionMapper::mapToPermission)
.collect(Collectors.toList());
}
public Optional<Permission> getPermissionForApplication(
final String applicationIdentifier,
final String permittableEndpointGroupIdentifier) {
return applicationPermissionsRepository.getPermissionForApplication(applicationIdentifier, permittableEndpointGroupIdentifier)
.map(PermissionMapper::mapToPermission);
}
public Optional<Signature> getSignatureForApplication(final String applicationIdentifier, final String timestamp) {
return applicationSignaturesRepository.get(applicationIdentifier, timestamp)
.map(SignatureMapper::mapToSignature);
}
public boolean applicationExists(final String applicationIdentifier) {
return applicationSignaturesRepository.signaturesExistForApplication(applicationIdentifier);
}
public boolean applicationPermissionExists(final @Nonnull String applicationIdentifier,
final @Nonnull String permittableGroupIdentifier) {
return applicationPermissionsRepository.exists(applicationIdentifier, permittableGroupIdentifier);
}
public boolean applicationPermissionEnabledForUser(final String applicationIdentifier,
final String permittableEndpointGroupIdentifier,
final String userIdentifier) {
return applicationPermissionsUserRepository.enabled(applicationIdentifier, permittableEndpointGroupIdentifier, userIdentifier);
}
public List<CallEndpointSet> getAllCallEndpointSetsForApplication(final String applicationIdentifier) {
return applicationCallEndpointSets.getAllForApplication(applicationIdentifier).stream()
.map(ApplicationCallEndpointSetMapper::map)
.collect(Collectors.toList());
}
public Optional<CallEndpointSet> getCallEndpointSetForApplication(
final String applicationIdentifier,
final String callEndpointSetIdentifier) {
return applicationCallEndpointSets.get(applicationIdentifier, callEndpointSetIdentifier)
.map(ApplicationCallEndpointSetMapper::map);
}
public boolean applicationCallEndpointSetExists(String applicationIdentifier, String callEndpointSetIdentifier) {
return applicationCallEndpointSets.get(applicationIdentifier, callEndpointSetIdentifier).isPresent();
}
}
| 2,172 |
0 | Create_ds/fineract-cn-identity/service/src/main/java/org/apache/fineract/cn/identity/internal | Create_ds/fineract-cn-identity/service/src/main/java/org/apache/fineract/cn/identity/internal/service/RoleMapper.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.fineract.cn.identity.internal.service;
import org.apache.fineract.cn.identity.api.v1.domain.Permission;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
import org.apache.fineract.cn.anubis.api.v1.domain.AllowedOperation;
import org.apache.fineract.cn.identity.internal.repository.AllowedOperationType;
import org.apache.fineract.cn.identity.internal.repository.PermissionType;
/**
* @author Myrle Krantz
*/
public class RoleMapper {
@SuppressWarnings("WeakerAccess")
static Set<AllowedOperation> mapAllowedOperations(
final Set<AllowedOperationType> allowedOperations) {
return allowedOperations.stream()
.map(RoleMapper::mapAllowedOperation)
.collect(Collectors.toSet());
}
public static AllowedOperation mapAllowedOperation(final AllowedOperationType allowedOperationType) {
return AllowedOperation.valueOf(allowedOperationType.toString());
}
static List<Permission> mapPermissions(List<PermissionType> permissions) {
return permissions.stream()
.map(i -> new Permission(
i.getPermittableGroupIdentifier(),
RoleMapper.mapAllowedOperations(i.getAllowedOperations()))).collect(Collectors.toList());
}
}
| 2,173 |
0 | Create_ds/fineract-cn-identity/service/src/main/java/org/apache/fineract/cn/identity | Create_ds/fineract-cn-identity/service/src/main/java/org/apache/fineract/cn/identity/rest/ApplicationPermissionUserRestController.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.fineract.cn.identity.rest;
import org.apache.fineract.cn.identity.api.v1.PermittableGroupIds;
import javax.annotation.Nonnull;
import org.apache.fineract.cn.anubis.annotation.AcceptedTokenType;
import org.apache.fineract.cn.anubis.annotation.Permittable;
import org.apache.fineract.cn.command.gateway.CommandGateway;
import org.apache.fineract.cn.identity.internal.command.SetApplicationPermissionUserEnabledCommand;
import org.apache.fineract.cn.identity.internal.service.ApplicationService;
import org.apache.fineract.cn.identity.internal.service.UserService;
import org.apache.fineract.cn.lang.ServiceException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
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.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
/**
* @author Myrle Krantz
*/
@SuppressWarnings("unused")
@RestController
@RequestMapping("/applications/{applicationidentifier}/permissions/{permissionidentifier}/users/{useridentifier}")
public class ApplicationPermissionUserRestController {
private final ApplicationService service;
private final UserService userService;
private final CommandGateway commandGateway;
@Autowired
public ApplicationPermissionUserRestController(
final ApplicationService service,
final UserService userService,
final CommandGateway commandGateway) {
this.service = service;
this.userService = userService;
this.commandGateway = commandGateway;
}
@Permittable(value = AcceptedTokenType.TENANT, groupId = PermittableGroupIds.SELF_MANAGEMENT)
@RequestMapping(value = "/enabled", method = RequestMethod.PUT,
consumes = {MediaType.ALL_VALUE},
produces = {MediaType.APPLICATION_JSON_VALUE})
public @ResponseBody
ResponseEntity<Void>
setApplicationPermissionEnabledForUser(@PathVariable("applicationidentifier") String applicationIdentifier,
@PathVariable("permissionidentifier") String permittableEndpointGroupIdentifier,
@PathVariable("useridentifier") String userIdentifier,
@RequestBody Boolean enabled)
{
ApplicationRestController.checkApplicationPermissionIdentifier(service, applicationIdentifier, permittableEndpointGroupIdentifier);
checkUserIdentifier(userIdentifier);
commandGateway.process(new SetApplicationPermissionUserEnabledCommand(applicationIdentifier, permittableEndpointGroupIdentifier, userIdentifier, enabled));
return ResponseEntity.accepted().build();
}
@Permittable(value = AcceptedTokenType.TENANT, groupId = PermittableGroupIds.SELF_MANAGEMENT)
@RequestMapping(value = "/enabled", method = RequestMethod.GET,
consumes = {MediaType.APPLICATION_JSON_VALUE},
produces = {MediaType.APPLICATION_JSON_VALUE})
public @ResponseBody
ResponseEntity<Boolean>
getApplicationPermissionEnabledForUser(@PathVariable("applicationidentifier") String applicationIdentifier,
@PathVariable("permissionidentifier") String permittableEndpointGroupIdentifier,
@PathVariable("useridentifier") String userIdentifier) {
ApplicationRestController.checkApplicationPermissionIdentifier(service, applicationIdentifier, permittableEndpointGroupIdentifier);
checkUserIdentifier(userIdentifier);
return ResponseEntity.ok(service.applicationPermissionEnabledForUser(applicationIdentifier, permittableEndpointGroupIdentifier, userIdentifier));
}
private void checkUserIdentifier(final @Nonnull String identifier) {
userService.findByIdentifier(identifier).orElseThrow(
() -> ServiceException.notFound("User ''" + identifier + "'' doesn''t exist."));
}
}
| 2,174 |
0 | Create_ds/fineract-cn-identity/service/src/main/java/org/apache/fineract/cn/identity | Create_ds/fineract-cn-identity/service/src/main/java/org/apache/fineract/cn/identity/rest/InitializeRestController.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.fineract.cn.identity.rest;
import org.apache.fineract.cn.anubis.annotation.AcceptedTokenType;
import org.apache.fineract.cn.anubis.annotation.Permittable;
import org.apache.fineract.cn.anubis.api.v1.domain.ApplicationSignatureSet;
import org.apache.fineract.cn.identity.internal.command.handler.Provisioner;
import org.apache.fineract.cn.identity.internal.service.TenantService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
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.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
/**
* @author Myrle Krantz
*/
@SuppressWarnings("unused")
@RestController
@RequestMapping()
public class InitializeRestController {
private final TenantService tenantService;
private final Provisioner provisioner;
@Autowired
InitializeRestController(
final TenantService tenantService,
final Provisioner provisioner)
{
this.tenantService = tenantService;
this.provisioner = provisioner;
}
@RequestMapping(value = "/initialize",
method = RequestMethod.POST,
consumes = {MediaType.ALL_VALUE},
produces = {MediaType.APPLICATION_JSON_VALUE})
@Permittable(AcceptedTokenType.SYSTEM)
public @ResponseBody ResponseEntity<ApplicationSignatureSet> initializeTenant(
@RequestParam("password") final String adminPassword)
{
final ApplicationSignatureSet newSignatureSet = provisioner.provisionTenant(adminPassword);
return new ResponseEntity<>(newSignatureSet, HttpStatus.OK);
}
@RequestMapping(value = "/signatures",
method = RequestMethod.POST,
consumes = {MediaType.ALL_VALUE},
produces = {MediaType.APPLICATION_JSON_VALUE})
@Permittable(AcceptedTokenType.SYSTEM)
public @ResponseBody ResponseEntity<ApplicationSignatureSet> createSignatureSet() {
return ResponseEntity.ok(tenantService.createSignatureSet());
}
}
| 2,175 |
0 | Create_ds/fineract-cn-identity/service/src/main/java/org/apache/fineract/cn/identity | Create_ds/fineract-cn-identity/service/src/main/java/org/apache/fineract/cn/identity/rest/ApplicationCallEndpointSetRestController.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.fineract.cn.identity.rest;
import org.apache.fineract.cn.identity.api.v1.domain.CallEndpointSet;
import org.apache.fineract.cn.anubis.annotation.AcceptedTokenType;
import org.apache.fineract.cn.anubis.annotation.Permittable;
import org.apache.fineract.cn.command.gateway.CommandGateway;
import org.apache.fineract.cn.identity.internal.command.ChangeApplicationCallEndpointSetCommand;
import org.apache.fineract.cn.identity.internal.command.CreateApplicationCallEndpointSetCommand;
import org.apache.fineract.cn.identity.internal.command.DeleteApplicationCallEndpointSetCommand;
import org.apache.fineract.cn.identity.internal.service.ApplicationService;
import org.apache.fineract.cn.lang.ServiceException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import java.util.List;
/**
* @author Myrle Krantz
*/
@SuppressWarnings("unused")
@RestController
@RequestMapping("/applications/{applicationidentifier}/callendpointset")
public class ApplicationCallEndpointSetRestController {
private final CommandGateway commandGateway;
private final ApplicationService applicationService;
@Autowired
public ApplicationCallEndpointSetRestController(
final CommandGateway commandGateway,
final ApplicationService applicationService) {
this.commandGateway = commandGateway;
this.applicationService = applicationService;
}
@RequestMapping(method = RequestMethod.POST,
produces = {MediaType.APPLICATION_JSON_VALUE},
consumes = {MediaType.ALL_VALUE})
@Permittable(value = AcceptedTokenType.SYSTEM)
public @ResponseBody
ResponseEntity<Void> createApplicationCallEndpointSet(
@PathVariable("applicationidentifier") final String applicationIdentifier,
@RequestBody final CallEndpointSet instance)
{
if (!applicationService.applicationExists(applicationIdentifier))
throw ServiceException.notFound("Application ''"
+ applicationIdentifier + "'' doesn''t exist.");
commandGateway.process(new CreateApplicationCallEndpointSetCommand(applicationIdentifier, instance));
return ResponseEntity.accepted().build();
}
@RequestMapping(value = "/{callendpointsetidentifier}", method = RequestMethod.PUT,
produces = {MediaType.APPLICATION_JSON_VALUE},
consumes = {MediaType.ALL_VALUE})
@Permittable(value = AcceptedTokenType.SYSTEM)
public @ResponseBody
ResponseEntity<Void> changeApplicationCallEndpointSet(
@PathVariable("applicationidentifier") String applicationIdentifier,
@PathVariable("callendpointsetidentifier") String callEndpointSetIdentifier,
@RequestBody final CallEndpointSet instance)
{
if (!applicationService.applicationCallEndpointSetExists(applicationIdentifier, callEndpointSetIdentifier))
throw ServiceException.notFound("Application call endpointset ''"
+ applicationIdentifier + "." + callEndpointSetIdentifier + "'' doesn''t exist.");
if (!callEndpointSetIdentifier.equals(instance.getIdentifier()))
throw ServiceException.badRequest("Instance identifiers may not be changed.");
commandGateway.process(new ChangeApplicationCallEndpointSetCommand(applicationIdentifier, callEndpointSetIdentifier, instance));
return ResponseEntity.accepted().build();
}
@RequestMapping(value = "/{callendpointsetidentifier}", method = RequestMethod.GET,
produces = {MediaType.APPLICATION_JSON_VALUE},
consumes = {MediaType.ALL_VALUE})
@Permittable(value = AcceptedTokenType.SYSTEM)
public @ResponseBody
ResponseEntity<CallEndpointSet> getApplicationCallEndpointSet(
@PathVariable("applicationidentifier") String applicationIdentifier,
@PathVariable("callendpointsetidentifier") String callEndpointSetIdentifier)
{
if (!applicationService.applicationCallEndpointSetExists(applicationIdentifier, callEndpointSetIdentifier))
throw ServiceException.notFound("Application call endpointset ''"
+ applicationIdentifier + "." + callEndpointSetIdentifier + "'' doesn''t exist.");
return applicationService.getCallEndpointSetForApplication(applicationIdentifier, callEndpointSetIdentifier)
.map(ResponseEntity::ok)
.orElseThrow(() -> ServiceException.notFound("Call endpointset for application " + applicationIdentifier + " and call endpointset identifier " + callEndpointSetIdentifier + "doesn't exist."));
}
@RequestMapping(method = RequestMethod.GET,
produces = {MediaType.APPLICATION_JSON_VALUE},
consumes = {MediaType.ALL_VALUE})
@Permittable(value = AcceptedTokenType.SYSTEM)
public @ResponseBody
ResponseEntity<List<CallEndpointSet>>
getApplicationCallEndpointSets(
@PathVariable("applicationidentifier") final String applicationIdentifier)
{
return ResponseEntity.ok(applicationService.getAllCallEndpointSetsForApplication(applicationIdentifier));
}
@RequestMapping(value = "/{callendpointsetidentifier}", method = RequestMethod.DELETE,
produces = {MediaType.APPLICATION_JSON_VALUE},
consumes = {MediaType.ALL_VALUE})
@Permittable(value = AcceptedTokenType.SYSTEM)
public @ResponseBody
ResponseEntity<Void> deleteApplicationCallEndpointSet(
@PathVariable("applicationidentifier") final String applicationIdentifier,
@PathVariable("callendpointsetidentifier") final String callEndpointSetIdentifier)
{
if (!applicationService.applicationCallEndpointSetExists(applicationIdentifier, callEndpointSetIdentifier))
throw ServiceException.notFound("Application call endpointset ''"
+ applicationIdentifier + "." + callEndpointSetIdentifier + "'' doesn''t exist.");
commandGateway.process(new DeleteApplicationCallEndpointSetCommand(applicationIdentifier, callEndpointSetIdentifier));
return ResponseEntity.accepted().build();
}
} | 2,176 |
0 | Create_ds/fineract-cn-identity/service/src/main/java/org/apache/fineract/cn/identity | Create_ds/fineract-cn-identity/service/src/main/java/org/apache/fineract/cn/identity/rest/UserRestController.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.fineract.cn.identity.rest;
import org.apache.fineract.cn.identity.api.v1.PermittableGroupIds;
import org.apache.fineract.cn.anubis.annotation.AcceptedTokenType;
import org.apache.fineract.cn.anubis.annotation.Permittable;
import org.apache.fineract.cn.api.util.UserContextHolder;
import org.apache.fineract.cn.command.gateway.CommandGateway;
import org.apache.fineract.cn.identity.api.v1.domain.Password;
import org.apache.fineract.cn.identity.api.v1.domain.Permission;
import org.apache.fineract.cn.identity.api.v1.domain.RoleIdentifier;
import org.apache.fineract.cn.identity.api.v1.domain.User;
import org.apache.fineract.cn.identity.api.v1.domain.UserWithPassword;
import org.apache.fineract.cn.identity.internal.command.ChangeUserPasswordCommand;
import org.apache.fineract.cn.identity.internal.command.ChangeUserRoleCommand;
import org.apache.fineract.cn.identity.internal.command.CreateUserCommand;
import org.apache.fineract.cn.identity.internal.service.UserService;
import org.apache.fineract.cn.identity.internal.util.IdentityConstants;
import org.apache.fineract.cn.lang.ServiceException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import javax.validation.Valid;
import java.util.List;
import java.util.Set;
/**
* @author Myrle Krantz
*/
@SuppressWarnings("unused")
@RestController
@RequestMapping("/users")
public class UserRestController {
private final UserService service;
private final CommandGateway commandGateway;
@Autowired
public UserRestController(
final CommandGateway commandGateway,
final UserService service) {
this.commandGateway = commandGateway;
this.service = service;
}
@RequestMapping(method = RequestMethod.GET,
consumes = {MediaType.ALL_VALUE},
produces = {MediaType.APPLICATION_JSON_VALUE})
@Permittable(value = AcceptedTokenType.TENANT, groupId = PermittableGroupIds.IDENTITY_MANAGEMENT)
public @ResponseBody List<User> findAll() {
return this.service.findAll();
}
@RequestMapping(method = RequestMethod.POST,
consumes = {MediaType.APPLICATION_JSON_VALUE},
produces = {MediaType.APPLICATION_JSON_VALUE})
@Permittable(value = AcceptedTokenType.TENANT, groupId = PermittableGroupIds.IDENTITY_MANAGEMENT)
public @ResponseBody ResponseEntity<Void> create(@RequestBody @Valid final UserWithPassword instance)
{
if (instance == null)
throw ServiceException.badRequest("Instance may not be null.");
if (service.findByIdentifier(instance.getIdentifier()).isPresent())
throw ServiceException.conflict("Instance already exists with identifier:" + instance.getIdentifier());
final CreateUserCommand createCommand = new CreateUserCommand(instance);
this.commandGateway.process(createCommand);
return new ResponseEntity<>(HttpStatus.ACCEPTED);
}
@RequestMapping(value= PathConstants.IDENTIFIER_RESOURCE_STRING, method = RequestMethod.GET,
consumes = {MediaType.ALL_VALUE},
produces = {MediaType.APPLICATION_JSON_VALUE})
@Permittable(value = AcceptedTokenType.TENANT, groupId = PermittableGroupIds.IDENTITY_MANAGEMENT)
public @ResponseBody ResponseEntity<User> get(@PathVariable(PathConstants.IDENTIFIER_PATH_VARIABLE) final String userIdentifier)
{
return new ResponseEntity<>(checkIdentifier(userIdentifier), HttpStatus.OK);
}
@RequestMapping(value = PathConstants.IDENTIFIER_RESOURCE_STRING + "/roleIdentifier", method = RequestMethod.PUT,
consumes = {MediaType.APPLICATION_JSON_VALUE},
produces = {MediaType.APPLICATION_JSON_VALUE})
@Permittable(value = AcceptedTokenType.TENANT, groupId = PermittableGroupIds.IDENTITY_MANAGEMENT)
public @ResponseBody ResponseEntity<Void> changeUserRole(
@PathVariable(PathConstants.IDENTIFIER_PATH_VARIABLE) final String userIdentifier,
@RequestBody @Valid final RoleIdentifier roleIdentifier)
{
if (userIdentifier.equals(IdentityConstants.SU_NAME))
throw ServiceException.badRequest("Role of user with identifier: " + userIdentifier + " cannot be changed.");
checkIdentifier(userIdentifier);
final ChangeUserRoleCommand changeCommand = new ChangeUserRoleCommand(userIdentifier, roleIdentifier.getIdentifier());
this.commandGateway.process(changeCommand);
return new ResponseEntity<>(HttpStatus.ACCEPTED);
}
@RequestMapping(value = PathConstants.IDENTIFIER_RESOURCE_STRING + "/permissions", method = RequestMethod.GET,
consumes = {MediaType.ALL_VALUE},
produces = {MediaType.APPLICATION_JSON_VALUE})
@Permittable(value = AcceptedTokenType.TENANT, groupId = PermittableGroupIds.IDENTITY_MANAGEMENT)
@Permittable(value = AcceptedTokenType.TENANT, groupId = PermittableGroupIds.SELF_MANAGEMENT, permittedEndpoint = "/users/{useridentifier}/permissions")
@ResponseBody
Set<Permission> getUserPermissions(@PathVariable(PathConstants.IDENTIFIER_PATH_VARIABLE) String userIdentifier)
{
checkIdentifier(userIdentifier);
return service.getPermissions(userIdentifier);
}
@RequestMapping(value = PathConstants.IDENTIFIER_RESOURCE_STRING + "/password", method = RequestMethod.PUT,
consumes = {MediaType.APPLICATION_JSON_VALUE},
produces = {MediaType.APPLICATION_JSON_VALUE})
@Permittable(value = AcceptedTokenType.TENANT, groupId = PermittableGroupIds.IDENTITY_MANAGEMENT)
@Permittable(value = AcceptedTokenType.TENANT, groupId = PermittableGroupIds.SELF_MANAGEMENT, permittedEndpoint = "/users/{useridentifier}/password")
public @ResponseBody ResponseEntity<Void> changeUserPassword(
@PathVariable(PathConstants.IDENTIFIER_PATH_VARIABLE) final String userIdentifier,
@RequestBody @Valid final Password password)
{
if (userIdentifier.equals(IdentityConstants.SU_NAME) && !UserContextHolder.checkedGetUser().equals(
IdentityConstants.SU_NAME))
throw ServiceException.badRequest("Password of ''{0}'' can only be changed by themselves.", IdentityConstants.SU_NAME);
checkIdentifier(userIdentifier);
checkPassword(password);
final ChangeUserPasswordCommand changeCommand = new ChangeUserPasswordCommand(userIdentifier, password.getPassword());
this.commandGateway.process(changeCommand);
return new ResponseEntity<>(HttpStatus.ACCEPTED);
}
private void checkPassword(final Password password) {
if (password == null || password.getPassword() == null || password.getPassword().isEmpty())
throw ServiceException.badRequest("password may not be empty.");
}
private User checkIdentifier(final String identifier) {
if (identifier == null)
throw ServiceException.badRequest("identifier may not be null.");
return service.findByIdentifier(identifier)
.orElseThrow(() -> ServiceException.notFound("Instance with identifier " + identifier + " doesn't exist."));
}
} | 2,177 |
0 | Create_ds/fineract-cn-identity/service/src/main/java/org/apache/fineract/cn/identity | Create_ds/fineract-cn-identity/service/src/main/java/org/apache/fineract/cn/identity/rest/RoleRestController.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.fineract.cn.identity.rest;
import org.apache.fineract.cn.identity.api.v1.PermittableGroupIds;
import org.apache.fineract.cn.identity.api.v1.domain.Role;
import org.apache.fineract.cn.identity.api.v1.validation.CheckRoleChangeable;
import java.util.List;
import javax.validation.Valid;
import org.apache.fineract.cn.anubis.annotation.AcceptedTokenType;
import org.apache.fineract.cn.anubis.annotation.Permittable;
import org.apache.fineract.cn.command.gateway.CommandGateway;
import org.apache.fineract.cn.identity.internal.command.ChangeRoleCommand;
import org.apache.fineract.cn.identity.internal.command.CreateRoleCommand;
import org.apache.fineract.cn.identity.internal.command.DeleteRoleCommand;
import org.apache.fineract.cn.identity.internal.service.RoleService;
import org.apache.fineract.cn.lang.ServiceException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
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.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
/**
* @author Myrle Krantz
*/
@SuppressWarnings("unused")
@RestController
@RequestMapping("/roles")
public class RoleRestController
{
private final RoleService service;
private final CommandGateway commandGateway;
@Autowired public RoleRestController(
final CommandGateway commandGateway,
final RoleService service)
{
this.commandGateway = commandGateway;
this.service = service;
}
@RequestMapping(method = RequestMethod.POST,
consumes = {MediaType.APPLICATION_JSON_VALUE},
produces = {MediaType.APPLICATION_JSON_VALUE})
@Permittable(value = AcceptedTokenType.TENANT, groupId = PermittableGroupIds.ROLE_MANAGEMENT)
public @ResponseBody ResponseEntity<Void> create(@RequestBody @Valid final Role instance)
{
if (instance == null)
throw ServiceException.badRequest("Instance may not be null.");
if (service.findByIdentifier(instance.getIdentifier()).isPresent())
throw ServiceException.conflict("Instance already exists with identifier:" + instance.getIdentifier());
final CreateRoleCommand createCommand = new CreateRoleCommand(instance);
this.commandGateway.process(createCommand);
return new ResponseEntity<>(HttpStatus.ACCEPTED);
}
@RequestMapping(method = RequestMethod.GET,
consumes = {MediaType.ALL_VALUE},
produces = {MediaType.APPLICATION_JSON_VALUE})
@Permittable(value = AcceptedTokenType.TENANT, groupId = PermittableGroupIds.ROLE_MANAGEMENT)
public @ResponseBody List<Role> findAll() {
return service.findAll();
}
@RequestMapping(value= PathConstants.IDENTIFIER_RESOURCE_STRING, method = RequestMethod.GET,
consumes = {MediaType.ALL_VALUE},
produces = {MediaType.APPLICATION_JSON_VALUE})
@Permittable(value = AcceptedTokenType.TENANT, groupId = PermittableGroupIds.ROLE_MANAGEMENT)
public @ResponseBody ResponseEntity<Role> get(@PathVariable(PathConstants.IDENTIFIER_PATH_VARIABLE) final String identifier)
{
return new ResponseEntity<>(checkIdentifier(identifier), HttpStatus.OK);
}
@RequestMapping(value= PathConstants.IDENTIFIER_RESOURCE_STRING, method = RequestMethod.DELETE,
consumes = {MediaType.ALL_VALUE},
produces = {MediaType.APPLICATION_JSON_VALUE})
@Permittable(value = AcceptedTokenType.TENANT, groupId = PermittableGroupIds.ROLE_MANAGEMENT)
public @ResponseBody ResponseEntity<Void> delete(@PathVariable(PathConstants.IDENTIFIER_PATH_VARIABLE) final String identifier)
{
if (!CheckRoleChangeable.isChangeableRoleIdentifier(identifier))
throw ServiceException.badRequest("Role with identifier: " + identifier + " cannot be deleted.");
checkIdentifier(identifier);
final DeleteRoleCommand deleteCommand = new DeleteRoleCommand(identifier);
this.commandGateway.process(deleteCommand);
return new ResponseEntity<>(HttpStatus.ACCEPTED);
}
@RequestMapping(value= PathConstants.IDENTIFIER_RESOURCE_STRING,method = RequestMethod.PUT,
consumes = {MediaType.APPLICATION_JSON_VALUE},
produces = {MediaType.APPLICATION_JSON_VALUE})
@Permittable(value = AcceptedTokenType.TENANT, groupId = PermittableGroupIds.ROLE_MANAGEMENT)
public @ResponseBody ResponseEntity<Void> change(
@PathVariable(PathConstants.IDENTIFIER_PATH_VARIABLE) final String identifier, @RequestBody @Valid final Role instance)
{
if (!CheckRoleChangeable.isChangeableRoleIdentifier(identifier))
throw ServiceException.badRequest("Role with identifier: " + identifier + " cannot be changed.");
checkIdentifier(identifier);
if (!identifier.equals(instance.getIdentifier()))
throw ServiceException.badRequest("Instance identifiers may not be changed.");
final ChangeRoleCommand changeCommand = new ChangeRoleCommand(identifier, instance);
this.commandGateway.process(changeCommand);
return new ResponseEntity<>(HttpStatus.ACCEPTED);
}
private Role checkIdentifier(final String identifier) {
if (identifier == null)
throw ServiceException.badRequest("identifier may not be null.");
return service.findByIdentifier(identifier)
.orElseThrow(() -> ServiceException.notFound("Instance with identifier " + identifier + " doesn't exist."));
}
}
| 2,178 |
0 | Create_ds/fineract-cn-identity/service/src/main/java/org/apache/fineract/cn/identity | Create_ds/fineract-cn-identity/service/src/main/java/org/apache/fineract/cn/identity/rest/PathConstants.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.fineract.cn.identity.rest;
/**
* @author Myrle Krantz
*/
interface PathConstants
{
String IDENTIFIER_PATH_VARIABLE = "identifier";
String IDENTIFIER_RESOURCE_STRING = "/{identifier}";
}
| 2,179 |
0 | Create_ds/fineract-cn-identity/service/src/main/java/org/apache/fineract/cn/identity | Create_ds/fineract-cn-identity/service/src/main/java/org/apache/fineract/cn/identity/rest/PermittableGroupRestController.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.fineract.cn.identity.rest;
import org.apache.fineract.cn.identity.api.v1.PermittableGroupIds;
import org.apache.fineract.cn.identity.api.v1.domain.PermittableGroup;
import org.apache.fineract.cn.anubis.annotation.AcceptedTokenType;
import org.apache.fineract.cn.anubis.annotation.Permittable;
import org.apache.fineract.cn.command.gateway.CommandGateway;
import org.apache.fineract.cn.identity.internal.command.CreatePermittableGroupCommand;
import org.apache.fineract.cn.identity.internal.service.PermittableGroupService;
import org.apache.fineract.cn.lang.ServiceException;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import javax.validation.Valid;
import java.util.List;
/**
* @author Myrle Krantz
*/
@SuppressWarnings("unused")
@RestController
@RequestMapping("/permittablegroups")
public class PermittableGroupRestController {
private final PermittableGroupService service;
private final CommandGateway commandGateway;
public PermittableGroupRestController(final PermittableGroupService service,
final CommandGateway commandGateway) {
this.service = service;
this.commandGateway = commandGateway;
}
@RequestMapping(method = RequestMethod.POST,
consumes = {MediaType.APPLICATION_JSON_VALUE},
produces = {MediaType.APPLICATION_JSON_VALUE})
@Permittable(value = AcceptedTokenType.SYSTEM)
public @ResponseBody
ResponseEntity<Void> create(@RequestBody @Valid final PermittableGroup instance)
{
if (instance == null)
throw ServiceException.badRequest("Instance may not be null.");
if (service.findByIdentifier(instance.getIdentifier()).isPresent())
throw ServiceException.conflict("Instance already exists with identifier:" + instance.getIdentifier());
final CreatePermittableGroupCommand createCommand = new CreatePermittableGroupCommand(instance);
this.commandGateway.process(createCommand);
return new ResponseEntity<>(HttpStatus.ACCEPTED);
}
@RequestMapping(method = RequestMethod.GET,
consumes = {MediaType.ALL_VALUE},
produces = {MediaType.APPLICATION_JSON_VALUE})
@Permittable(value = AcceptedTokenType.TENANT, groupId = PermittableGroupIds.ROLE_MANAGEMENT)
public @ResponseBody
List<PermittableGroup> findAll() {
return service.findAll();
}
@RequestMapping(value= PathConstants.IDENTIFIER_RESOURCE_STRING, method = RequestMethod.GET,
consumes = {MediaType.ALL_VALUE},
produces = {MediaType.APPLICATION_JSON_VALUE})
@Permittable(value = AcceptedTokenType.SYSTEM)
@Permittable(value = AcceptedTokenType.TENANT, groupId = PermittableGroupIds.ROLE_MANAGEMENT)
public @ResponseBody ResponseEntity<PermittableGroup> get(@PathVariable(PathConstants.IDENTIFIER_PATH_VARIABLE) final String identifier)
{
return new ResponseEntity<>(checkIdentifier(identifier), HttpStatus.OK);
}
private PermittableGroup checkIdentifier(final String identifier) {
if (identifier == null)
throw ServiceException.badRequest("identifier may not be null.");
return service.findByIdentifier(identifier)
.orElseThrow(() -> ServiceException.notFound("Instance with identifier " + identifier + " doesn't exist."));
}
} | 2,180 |
0 | Create_ds/fineract-cn-identity/service/src/main/java/org/apache/fineract/cn/identity | Create_ds/fineract-cn-identity/service/src/main/java/org/apache/fineract/cn/identity/rest/AuthorizationRestController.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.fineract.cn.identity.rest;
import org.apache.fineract.cn.identity.api.v1.PermittableGroupIds;
import org.apache.fineract.cn.identity.api.v1.client.IdentityManager;
import org.apache.fineract.cn.identity.api.v1.domain.Authentication;
import org.apache.fineract.cn.anubis.annotation.AcceptedTokenType;
import org.apache.fineract.cn.anubis.annotation.Permittable;
import org.apache.fineract.cn.anubis.api.v1.TokenConstants;
import org.apache.fineract.cn.anubis.security.AmitAuthenticationException;
import org.apache.fineract.cn.command.domain.CommandCallback;
import org.apache.fineract.cn.command.domain.CommandProcessingException;
import org.apache.fineract.cn.command.gateway.CommandGateway;
import org.apache.fineract.cn.identity.internal.command.AuthenticationCommandResponse;
import org.apache.fineract.cn.identity.internal.command.PasswordAuthenticationCommand;
import org.apache.fineract.cn.identity.internal.command.RefreshTokenAuthenticationCommand;
import org.apache.fineract.cn.identity.internal.util.IdentityConstants;
import org.apache.fineract.cn.lang.ServiceException;
import org.slf4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.util.WebUtils;
import javax.annotation.Nullable;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.concurrent.ExecutionException;
/**
* @author Myrle Krantz
*/
@SuppressWarnings("unused")
@RestController //
public class AuthorizationRestController {
private final CommandGateway commandGateway;
private final Logger logger;
//Whether the cookie can only be transported via https. Should only be set to false for testing.
@Value("${identity.token.refresh.secureCookie:true}")
private boolean secureRefreshTokenCookie;
@Value("${server.contextPath}")
private String contextPath;
@Autowired public AuthorizationRestController(
final CommandGateway commandGateway,
@Qualifier(IdentityConstants.LOGGER_NAME) final Logger logger) {
super();
this.commandGateway = commandGateway;
this.logger = logger;
}
@RequestMapping(
value = "/token",
method = RequestMethod.POST,
consumes = {MediaType.ALL_VALUE},
produces = {MediaType.APPLICATION_JSON_VALUE}
)
@Permittable(AcceptedTokenType.GUEST)
public
@ResponseBody ResponseEntity<Authentication> authenticate(
final HttpServletResponse response,
final HttpServletRequest request,
@RequestParam("grant_type") final String grantType,
@RequestParam(value = "username", required = false) final String username,
@RequestParam(value = "password", required = false) final String password,
@RequestHeader(value = IdentityManager.REFRESH_TOKEN, required = false) final String refreshTokenParam) throws InterruptedException {
switch (grantType) {
case "refresh_token": {
final String refreshToken = getRefreshToken(refreshTokenParam, request);
try {
final AuthenticationCommandResponse authenticationCommandResponse
= getAuthenticationCommandResponse(new RefreshTokenAuthenticationCommand(refreshToken));
final Authentication ret = map(authenticationCommandResponse, response);
return new ResponseEntity<>(ret, HttpStatus.OK);
}
catch (final AmitAuthenticationException e)
{
return new ResponseEntity<>(HttpStatus.FORBIDDEN);
}
}
case "password": {
if (username == null)
throw ServiceException.badRequest("The query parameter username must be set if the grant_type is password.");
if (password == null)
throw ServiceException.badRequest("The query parameter password must be set if the grant_type is password.");
try {
final Authentication ret = map(getAuthenticationCommandResponse(
new PasswordAuthenticationCommand(username, password)), response);
return new ResponseEntity<>(ret, HttpStatus.OK);
}
catch (final AmitAuthenticationException e)
{
return new ResponseEntity<>(HttpStatus.NOT_FOUND);
}
}
default:
throw ServiceException.badRequest("invalid grant type: " + grantType);
}
}
@RequestMapping(value = "/token/_current", method = RequestMethod.DELETE,
consumes = {MediaType.ALL_VALUE},
produces = {MediaType.APPLICATION_JSON_VALUE})
@Permittable(value = AcceptedTokenType.TENANT, groupId = PermittableGroupIds.SELF_MANAGEMENT)
@ResponseBody ResponseEntity<Void> logout(
final HttpServletResponse response,
final HttpServletRequest request)
{
response.addCookie(bakeRefreshTokenCookie(""));
return ResponseEntity.ok().build();
}
private String getRefreshToken(final @Nullable String refreshTokenParam, final HttpServletRequest request) {
if (refreshTokenParam != null)
return refreshTokenParam;
final Cookie refreshTokenCookie = WebUtils.getCookie(request, TokenConstants.REFRESH_TOKEN_COOKIE_NAME);
if (refreshTokenCookie == null)
throw ServiceException.badRequest("One (and only one) refresh token cookie must be included in the request if the grant_type is refresh_token");
return refreshTokenCookie.getValue();
}
private AuthenticationCommandResponse getAuthenticationCommandResponse(
final Object authenticationCommand) throws AmitAuthenticationException, InterruptedException {
try
{
final CommandCallback<AuthenticationCommandResponse> ret =
commandGateway.process(authenticationCommand,
AuthenticationCommandResponse.class);
return ret.get();
}
catch (final ExecutionException e)
{
if (AmitAuthenticationException.class.isAssignableFrom(e.getCause().getClass()))
{
logger.debug("Authentication failed.", e);
throw AmitAuthenticationException.class.cast(e.getCause());
}
else if (CommandProcessingException.class.isAssignableFrom(e.getCause().getClass()))
{
final CommandProcessingException commandProcessingException = (CommandProcessingException) e.getCause();
if (ServiceException.class.isAssignableFrom(commandProcessingException.getCause().getClass()))
throw (ServiceException)commandProcessingException.getCause();
else {
logger.error("Authentication failed with an unexpected error.", e);
throw ServiceException.internalError("An error occurred while attempting to authenticate a user.");
}
}
else if (ServiceException.class.isAssignableFrom(e.getCause().getClass()))
{
throw (ServiceException)e.getCause();
}
else {
logger.error("Authentication failed with an unexpected error.", e);
throw ServiceException.internalError("An error occurred while attempting to authenticate a user.");
}
}
catch (final CommandProcessingException e)
{
logger.error("Authentication failed with an unexpected error.", e);
throw ServiceException.internalError("An error occurred while attempting to authenticate a user.");
}
}
private Authentication map(
final AuthenticationCommandResponse commandResponse,
final HttpServletResponse httpServletResponse)
{
httpServletResponse.addCookie(bakeRefreshTokenCookie(commandResponse.getRefreshToken()));
return new Authentication(
commandResponse.getAccessToken(),
commandResponse.getAccessTokenExpiration(),
commandResponse.getRefreshTokenExpiration(),
commandResponse.getPasswordExpiration());
}
private Cookie bakeRefreshTokenCookie(final String refreshToken) {
final Cookie refreshTokenCookie = new Cookie(TokenConstants.REFRESH_TOKEN_COOKIE_NAME, refreshToken);
refreshTokenCookie.setSecure(secureRefreshTokenCookie);
refreshTokenCookie.setHttpOnly(true);
refreshTokenCookie.setPath(contextPath + "/token");
return refreshTokenCookie;
}
}
| 2,181 |
0 | Create_ds/fineract-cn-identity/service/src/main/java/org/apache/fineract/cn/identity | Create_ds/fineract-cn-identity/service/src/main/java/org/apache/fineract/cn/identity/rest/ApplicationRestController.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.fineract.cn.identity.rest;
import org.apache.fineract.cn.identity.api.v1.PermittableGroupIds;
import org.apache.fineract.cn.identity.api.v1.domain.Permission;
import org.apache.fineract.cn.anubis.annotation.AcceptedTokenType;
import org.apache.fineract.cn.anubis.annotation.Permittable;
import org.apache.fineract.cn.anubis.api.v1.domain.Signature;
import org.apache.fineract.cn.anubis.api.v1.validation.ValidKeyTimestamp;
import org.apache.fineract.cn.command.gateway.CommandGateway;
import org.apache.fineract.cn.identity.internal.command.CreateApplicationPermissionCommand;
import org.apache.fineract.cn.identity.internal.command.DeleteApplicationCommand;
import org.apache.fineract.cn.identity.internal.command.DeleteApplicationPermissionCommand;
import org.apache.fineract.cn.identity.internal.command.SetApplicationSignatureCommand;
import org.apache.fineract.cn.identity.internal.service.ApplicationService;
import org.apache.fineract.cn.identity.internal.service.PermittableGroupService;
import org.apache.fineract.cn.lang.ServiceException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Nonnull;
import javax.validation.Valid;
import java.util.List;
/**
* @author Myrle Krantz
*/
@SuppressWarnings("WeakerAccess")
@RestController
@RequestMapping("/applications")
public class ApplicationRestController {
private final ApplicationService service;
private final PermittableGroupService permittableGroupService;
private final CommandGateway commandGateway;
@Autowired
public ApplicationRestController(
final ApplicationService service,
final PermittableGroupService permittableGroupService,
final CommandGateway commandGateway) {
this.service = service;
this.permittableGroupService = permittableGroupService;
this.commandGateway = commandGateway;
}
@RequestMapping(method = RequestMethod.GET,
consumes = {MediaType.ALL_VALUE},
produces = {MediaType.APPLICATION_JSON_VALUE})
@Permittable(value = AcceptedTokenType.SYSTEM)
public @ResponseBody
ResponseEntity<List<String>>
getApplications() {
return ResponseEntity.ok(service.getAllApplications());
}
@RequestMapping(value = "/{applicationidentifier}/signatures/{timestamp}", method = RequestMethod.PUT,
consumes = {MediaType.ALL_VALUE},
produces = {MediaType.APPLICATION_JSON_VALUE})
@Permittable(value = AcceptedTokenType.SYSTEM)
public @ResponseBody
ResponseEntity<Void>
setApplicationSignature(@PathVariable("applicationidentifier") @Nonnull String applicationIdentifier,
@PathVariable("timestamp") @ValidKeyTimestamp String timestamp,
@RequestBody @Valid Signature signature) {
commandGateway.process(new SetApplicationSignatureCommand(applicationIdentifier, timestamp, signature));
return ResponseEntity.accepted().build();
}
@RequestMapping(value = "/{applicationidentifier}/signatures/{timestamp}", method = RequestMethod.GET,
consumes = {MediaType.ALL_VALUE},
produces = {MediaType.APPLICATION_JSON_VALUE})
@Permittable(value = AcceptedTokenType.SYSTEM)
public @ResponseBody
ResponseEntity<Signature>
getApplicationSignature(@PathVariable("applicationidentifier") @Nonnull String applicationIdentifier,
@PathVariable("timestamp") @ValidKeyTimestamp String timestamp) {
return service.getSignatureForApplication(applicationIdentifier, timestamp)
.map(ResponseEntity::ok)
.orElseThrow(() -> ServiceException
.notFound("Signature for application ''" + applicationIdentifier + "'' and key timestamp ''" + timestamp + "'' doesn''t exist."));
}
@RequestMapping(value = "/{applicationidentifier}", method = RequestMethod.DELETE,
consumes = {MediaType.ALL_VALUE},
produces = {MediaType.APPLICATION_JSON_VALUE})
@Permittable(value = AcceptedTokenType.SYSTEM)
public @ResponseBody
ResponseEntity<Void>
deleteApplication(@PathVariable("applicationidentifier") @Nonnull String applicationIdentifier) {
checkApplicationIdentifier(applicationIdentifier);
commandGateway.process(new DeleteApplicationCommand(applicationIdentifier));
return ResponseEntity.accepted().build();
}
@RequestMapping(value = "/{applicationidentifier}/permissions", method = RequestMethod.POST,
consumes = {MediaType.ALL_VALUE},
produces = {MediaType.APPLICATION_JSON_VALUE})
@Permittable(value = AcceptedTokenType.SYSTEM)
@Permittable(value = AcceptedTokenType.TENANT, permittedEndpoint = "applications/{applicationidentifier}/permissions", groupId = PermittableGroupIds.APPLICATION_SELF_MANAGEMENT)
public @ResponseBody
ResponseEntity<Void>
createApplicationPermission(@PathVariable("applicationidentifier") @Nonnull String applicationIdentifier,
@RequestBody @Valid Permission permission) {
checkApplicationIdentifier(applicationIdentifier);
checkPermittableGroupIdentifier(permission.getPermittableEndpointGroupIdentifier());
commandGateway.process(new CreateApplicationPermissionCommand(applicationIdentifier, permission));
return ResponseEntity.accepted().build();
}
@RequestMapping(value = "/{applicationidentifier}/permissions", method = RequestMethod.GET,
consumes = {MediaType.ALL_VALUE},
produces = {MediaType.APPLICATION_JSON_VALUE})
@Permittable(value = AcceptedTokenType.SYSTEM)
@Permittable(value = AcceptedTokenType.TENANT, permittedEndpoint = "applications/{applicationidentifier}/permissions", groupId = PermittableGroupIds.APPLICATION_SELF_MANAGEMENT)
public @ResponseBody
ResponseEntity<List<Permission>>
getApplicationPermissions(@PathVariable("applicationidentifier") @Nonnull String applicationIdentifier) {
checkApplicationIdentifier(applicationIdentifier);
return ResponseEntity.ok(service.getAllPermissionsForApplication(applicationIdentifier));
}
@RequestMapping(value = "/{applicationidentifier}/permissions/{permissionidentifier}", method = RequestMethod.GET,
consumes = {MediaType.ALL_VALUE},
produces = {MediaType.APPLICATION_JSON_VALUE})
@Permittable(value = AcceptedTokenType.SYSTEM)
public @ResponseBody
ResponseEntity<Permission> getApplicationPermission(@PathVariable("applicationidentifier") String applicationIdentifier,
@PathVariable("permissionidentifier") String permittableEndpointGroupIdentifier) {
return service.getPermissionForApplication(applicationIdentifier, permittableEndpointGroupIdentifier)
.map(ResponseEntity::ok)
.orElseThrow(() -> ServiceException.notFound("Application permission ''{0}.{1}'' doesn''t exist.",
applicationIdentifier, permittableEndpointGroupIdentifier));
}
@RequestMapping(value = "/{applicationidentifier}/permissions/{permissionidentifier}", method = RequestMethod.DELETE,
consumes = {MediaType.ALL_VALUE},
produces = {MediaType.APPLICATION_JSON_VALUE})
@Permittable(value = AcceptedTokenType.SYSTEM)
public @ResponseBody
ResponseEntity<Void>
deleteApplicationPermission(@PathVariable("applicationidentifier") @Nonnull String applicationIdentifier,
@PathVariable("permissionidentifier") @Nonnull String permittableEndpointGroupIdentifier)
{
checkApplicationPermissionIdentifier(service, applicationIdentifier, permittableEndpointGroupIdentifier);
commandGateway.process(new DeleteApplicationPermissionCommand(applicationIdentifier, permittableEndpointGroupIdentifier));
return ResponseEntity.accepted().build();
}
private void checkApplicationIdentifier(final @Nonnull String identifier) {
if (!service.applicationExists(identifier))
throw ServiceException.notFound("Application with identifier ''" + identifier + "'' doesn''t exist.");
}
static void checkApplicationPermissionIdentifier(final @Nonnull ApplicationService service,
final @Nonnull String applicationIdentifier,
final @Nonnull String permittableEndpointGroupIdentifier) {
if (!service.applicationPermissionExists(applicationIdentifier, permittableEndpointGroupIdentifier))
throw ServiceException.notFound("Application permission ''{0}.{1}'' doesn''t exist.",
applicationIdentifier, permittableEndpointGroupIdentifier);
}
private void checkPermittableGroupIdentifier(final String permittableEndpointGroupIdentifier) {
permittableGroupService.findByIdentifier(permittableEndpointGroupIdentifier)
.orElseThrow(() -> ServiceException.notFound("Permittable group ''{0}'' doesn''t exist.", permittableEndpointGroupIdentifier));
}
} | 2,182 |
0 | Create_ds/ocelli/ocelli-examples/src/main/java/netflix/ocelli/examples/rxnetty | Create_ds/ocelli/ocelli-examples/src/main/java/netflix/ocelli/examples/rxnetty/http/RandomWeighted.java | package netflix.ocelli.examples.rxnetty.http;
import io.netty.buffer.ByteBuf;
import io.reactivex.netty.protocol.http.client.HttpClient;
import netflix.ocelli.Instance;
import netflix.ocelli.examples.rxnetty.http.HttpExampleUtils.*;
import netflix.ocelli.rxnetty.protocol.http.HttpLoadBalancer;
import netflix.ocelli.rxnetty.protocol.http.WeightedHttpClientListener;
import rx.Observable;
import java.net.ConnectException;
import java.net.SocketAddress;
import java.net.SocketException;
import java.nio.charset.Charset;
import java.util.concurrent.TimeUnit;
import static netflix.ocelli.examples.rxnetty.http.HttpExampleUtils.*;
public final class RandomWeighted {
private RandomWeighted() {
}
public static void main(String[] args) {
Observable<Instance<SocketAddress>> hosts = newHostStreamWithCannedLatencies(1L, 2L);
HttpLoadBalancer<ByteBuf, ByteBuf> lb =
HttpLoadBalancer.<ByteBuf, ByteBuf>weigthedRandom(hosts, failureListener -> {
return new WeightedHttpClientListener() {
private volatile int weight;
@Override
public int getWeight() {
return weight;
}
@Override
public void onResponseHeadersReceived(int responseCode, long duration, TimeUnit timeUnit) {
/* This is just a demo for how to wire the weight of an instance to the load balancer, it
* certainly is not the algorithm to be used in real production applications.
*/
weight = (int) (Long.MAX_VALUE - duration); // High latency => low weight
if (responseCode == 503) {
// When throttled, quarantine.
failureListener.quarantine(1, TimeUnit.MINUTES);
}
}
@Override
public void onConnectFailed(long duration, TimeUnit timeUnit, Throwable throwable) {
// Connect failed, remove
failureListener.remove();
}
};
});
HttpClient.newClient(lb.toConnectionProvider())
.createGet("/hello")
.doOnNext(System.out::println)
.flatMap(resp -> {
if (resp.getStatus().code() != 200) {
return Observable.error(new InvalidResponseException());
}
return resp.getContent();
})
.retry((integer, throwable) -> throwable instanceof SocketException
|| throwable instanceof ConnectException
|| throwable instanceof InvalidResponseException)
.repeat(10)
.toBlocking()
.forEach(bb -> bb.toString(Charset.defaultCharset()));
}
}
| 2,183 |
0 | Create_ds/ocelli/ocelli-examples/src/main/java/netflix/ocelli/examples/rxnetty | Create_ds/ocelli/ocelli-examples/src/main/java/netflix/ocelli/examples/rxnetty/http/ChoiceOfTwo.java | package netflix.ocelli.examples.rxnetty.http;
import io.netty.buffer.ByteBuf;
import io.reactivex.netty.protocol.http.client.HttpClient;
import netflix.ocelli.Instance;
import netflix.ocelli.rxnetty.protocol.http.HttpLoadBalancer;
import netflix.ocelli.rxnetty.protocol.http.WeightedHttpClientListener;
import rx.Observable;
import java.net.ConnectException;
import java.net.SocketAddress;
import java.net.SocketException;
import java.nio.charset.Charset;
import java.util.concurrent.TimeUnit;
import static netflix.ocelli.examples.rxnetty.http.HttpExampleUtils.*;
public final class ChoiceOfTwo {
private ChoiceOfTwo() {
}
public static void main(String[] args) {
Observable<Instance<SocketAddress>> hosts = newHostStreamWithCannedLatencies(5L, 1L, 2L, 1L, 0L);
HttpLoadBalancer<ByteBuf, ByteBuf> lb =
HttpLoadBalancer.<ByteBuf, ByteBuf>choiceOfTwo(hosts, failureListener -> {
return new WeightedHttpClientListener() {
private volatile int lastSeenLatencyInverse;
@Override
public int getWeight() {
return lastSeenLatencyInverse;
}
@Override
public void onResponseHeadersReceived(int responseCode, long duration, TimeUnit timeUnit) {
/* This is just a demo for how to wire the weight of an instance to the load balancer, it
* certainly is not the algorithm to be used in real production applications.
*/
lastSeenLatencyInverse = Integer.MAX_VALUE - (int)duration; // High latency => low weight
if (responseCode == 503) {
// When throttled, quarantine.
failureListener.quarantine(1, TimeUnit.MINUTES);
}
}
@Override
public void onConnectFailed(long duration, TimeUnit timeUnit, Throwable throwable) {
// Connect failed, remove
failureListener.remove();
}
};
});
HttpClient.newClient(lb.toConnectionProvider())
.createGet("/hello")
.doOnNext(System.out::println)
.flatMap(resp -> {
if (resp.getStatus().code() != 200) {
return Observable.error(new InvalidResponseException());
}
return resp.getContent();
})
.retry((integer, throwable) -> throwable instanceof SocketException
|| throwable instanceof ConnectException
|| throwable instanceof InvalidResponseException)
.repeat(10)
.toBlocking()
.forEach(bb -> bb.toString(Charset.defaultCharset()));
}
}
| 2,184 |
0 | Create_ds/ocelli/ocelli-examples/src/main/java/netflix/ocelli/examples/rxnetty | Create_ds/ocelli/ocelli-examples/src/main/java/netflix/ocelli/examples/rxnetty/http/HttpExampleUtils.java | package netflix.ocelli.examples.rxnetty.http;
import io.netty.handler.codec.http.HttpResponseStatus;
import io.reactivex.netty.protocol.http.server.HttpServer;
import netflix.ocelli.Instance;
import rx.Observable;
import rx.functions.Func1;
import java.net.InetSocketAddress;
import java.net.SocketAddress;
import java.util.concurrent.TimeUnit;
final class HttpExampleUtils {
private HttpExampleUtils() {
}
protected static Observable<Instance<SocketAddress>> newHostStreamWithCannedLatencies(Long... latencies) {
return Observable.from(latencies)
.map(latency -> {
return startServer(latency);
})
.map(new SockAddrToInstance());
}
protected static Observable<Instance<SocketAddress>> newHostStreamWithCannedStatus(
HttpResponseStatus... cannedStatuses) {
return Observable.from(cannedStatuses)
.map(cannedStatus -> {
if (null != cannedStatus) {
return startServer(cannedStatus);
}
return new InetSocketAddress(0);
})
.map(new SockAddrToInstance());
}
protected static SocketAddress startServer(long latencyMillis) {
return HttpServer.newServer()
.start((request, response) -> {
return Observable.timer(latencyMillis, TimeUnit.MILLISECONDS)
.flatMap(aTick -> response.addHeader("X-Instance",
response.unsafeNettyChannel()
.localAddress())
.setStatus(HttpResponseStatus.OK));
})
.getServerAddress();
}
protected static SocketAddress startServer(HttpResponseStatus cannedStatus) {
return HttpServer.newServer()
.start((request, response) -> {
return response.addHeader("X-Instance", response.unsafeNettyChannel().localAddress())
.setStatus(cannedStatus);
})
.getServerAddress();
}
protected static class InvalidResponseException extends RuntimeException {
private static final long serialVersionUID = -712946630951320233L;
public InvalidResponseException() {
}
}
private static class SockAddrToInstance implements Func1<SocketAddress, Instance<SocketAddress>> {
@Override
public Instance<SocketAddress> call(SocketAddress socketAddr) {
return new Instance<SocketAddress>() {
@Override
public Observable<Void> getLifecycle() {
return Observable.never();
}
@Override
public SocketAddress getValue() {
return socketAddr;
}
};
}
}
}
| 2,185 |
0 | Create_ds/ocelli/ocelli-examples/src/main/java/netflix/ocelli/examples/rxnetty | Create_ds/ocelli/ocelli-examples/src/main/java/netflix/ocelli/examples/rxnetty/http/RoundRobin.java | package netflix.ocelli.examples.rxnetty.http;
import io.netty.buffer.ByteBuf;
import io.reactivex.netty.protocol.http.client.HttpClient;
import io.reactivex.netty.protocol.http.client.events.HttpClientEventsListener;
import netflix.ocelli.Instance;
import netflix.ocelli.examples.rxnetty.http.HttpExampleUtils.*;
import netflix.ocelli.rxnetty.protocol.http.HttpLoadBalancer;
import rx.Observable;
import java.net.ConnectException;
import java.net.SocketAddress;
import java.net.SocketException;
import java.nio.charset.Charset;
import java.util.concurrent.TimeUnit;
import static io.netty.handler.codec.http.HttpResponseStatus.*;
import static netflix.ocelli.examples.rxnetty.http.HttpExampleUtils.*;
public final class RoundRobin {
private RoundRobin() {
}
public static void main(String[] args) {
Observable<Instance<SocketAddress>> hosts = newHostStreamWithCannedStatus(OK, SERVICE_UNAVAILABLE,
null/*Unavailable socket address*/);
HttpLoadBalancer<ByteBuf, ByteBuf> lb =
HttpLoadBalancer.<ByteBuf, ByteBuf>roundRobin(hosts, failureListener -> {
return new HttpClientEventsListener() {
@Override
public void onResponseHeadersReceived(int responseCode, long duration, TimeUnit timeUnit) {
if (responseCode == 503) {
// When throttled, quarantine.
failureListener.quarantine(1, TimeUnit.MINUTES);
}
}
@Override
public void onConnectFailed(long duration, TimeUnit timeUnit, Throwable throwable) {
// Connect failed, remove
failureListener.remove();
}
};
});
HttpClient.newClient(lb.toConnectionProvider())
.createGet("/hello")
.doOnNext(System.out::println)
.flatMap(resp -> {
if (resp.getStatus().code() != 200) {
return Observable.error(new InvalidResponseException());
}
return resp.getContent();
})
.retry((integer, throwable) -> throwable instanceof SocketException
|| throwable instanceof ConnectException
|| throwable instanceof InvalidResponseException)
.repeat(10)
.toBlocking()
.forEach(bb -> bb.toString(Charset.defaultCharset()));
}
}
| 2,186 |
0 | Create_ds/ocelli/ocelli-core/src/test/java/netflix | Create_ds/ocelli/ocelli-core/src/test/java/netflix/ocelli/InstanceQuarantinerTest.java | package netflix.ocelli;
import java.util.Comparator;
import java.util.List;
import java.util.NoSuchElementException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import netflix.ocelli.InstanceQuarantiner.IncarnationFactory;
import netflix.ocelli.functions.Delays;
import netflix.ocelli.loadbalancer.ChoiceOfTwoLoadBalancer;
import netflix.ocelli.loadbalancer.RoundRobinLoadBalancer;
import org.junit.Assert;
import org.junit.Ignore;
import org.junit.Test;
import rx.Observable;
import rx.functions.Func1;
import rx.schedulers.TestScheduler;
public class InstanceQuarantinerTest {
public static interface EventListener {
public void onBegin();
public void onSuccess();
public void onFailed();
}
final static TestScheduler scheduler = new TestScheduler();
public static class Client implements EventListener {
public static Func1<Instance<Integer>, Instance<Client>> connector() {
return new Func1<Instance<Integer>, Instance<Client>>() {
@Override
public Instance<Client> call(Instance<Integer> t1) {
return Instance.create(new Client(t1.getValue(), t1.getLifecycle()), t1.getLifecycle());
}
};
}
public static IncarnationFactory<Client> incarnationFactory() {
return new IncarnationFactory<Client>() {
@Override
public Client create(
Client value,
InstanceEventListener listener,
Observable<Void> lifecycle) {
return new Client(value, listener, lifecycle);
}
};
}
private Integer address;
private final Observable<Void> lifecycle;
private final AtomicInteger counter;
private AtomicInteger score = new AtomicInteger();
private final InstanceEventListener listener;
private final int id;
public Client(Integer address, Observable<Void> lifecycle) {
this.address = address;
this.counter = new AtomicInteger();
this.lifecycle = lifecycle;
this.listener = null;
id = 0;
}
Client(Client client, InstanceEventListener listener, Observable<Void> lifecycle) {
this.address = client.address;
this.counter = client.counter;
this.lifecycle = lifecycle;
this.listener = listener;
id = this.counter.incrementAndGet();
}
@Override
public void onBegin() {
}
@Override
public void onSuccess() {
listener.onEvent(InstanceEvent.EXECUTION_SUCCESS, 0, TimeUnit.SECONDS, null, null);
}
@Override
public void onFailed() {
listener.onEvent(InstanceEvent.EXECUTION_FAILED, 0, TimeUnit.SECONDS, new Exception("Failed"), null);
}
public Integer getValue() {
return address;
}
public int getId() {
return id;
}
public String toString() {
return address.toString() + "[" + id + "]";
}
public static Comparator<Client> compareByMetric() {
return new Comparator<Client>() {
@Override
public int compare(Client o1, Client o2) {
return o1.score.get() - o2.score.get();
}
};
}
public Observable<Void> getLifecycle() {
return lifecycle;
}
}
@Test
public void basicTest() {
final InstanceManager<Integer> instances = InstanceManager.create();
final LoadBalancer<Client> lb = LoadBalancer
.fromSource(instances.map(Client.connector()))
.withQuarantiner(Client.incarnationFactory(), Delays.fixed(1, TimeUnit.SECONDS), scheduler)
.build(RoundRobinLoadBalancer.<Client>create());
instances.add(1);
// Load balancer now has one instance
Client c = lb.next();
Assert.assertNotNull("Load balancer should have an active intance", c);
Assert.assertEquals(1, c.getId());
// Force the instance to fail
c.onFailed();
// Load balancer is now empty
try {
c = lb.next();
Assert.fail("Load balancer should be empty");
}
catch (NoSuchElementException e) {
}
// Advance past quarantine time
scheduler.advanceTimeBy(2, TimeUnit.SECONDS);
c = lb.next();
Assert.assertNotNull("Load balancer should have an active intance", c);
Assert.assertEquals(2, c.getId());
// Force the instance to fail
c.onFailed();
// Load balancer is now empty
try {
c = lb.next();
Assert.fail("Load balancer should be empty");
}
catch (NoSuchElementException e) {
}
// Advance past quarantine time
scheduler.advanceTimeBy(2, TimeUnit.SECONDS);
c = lb.next();
Assert.assertNotNull("Load balancer should have an active intance", c);
Assert.assertEquals(3, c.counter.get());
// Remove the instance entirely
instances.remove(1);
try {
c = lb.next();
Assert.fail();
}
catch (NoSuchElementException e) {
}
System.out.println(c);
}
@Test
@Ignore
public void test() {
final InstanceManager<Integer> instances = InstanceManager.create();
final LoadBalancer<Client> lb = LoadBalancer
.fromSource(instances.map(Client.connector()))
.withQuarantiner(Client.incarnationFactory(), Delays.fixed(1, TimeUnit.SECONDS), scheduler)
.build(RoundRobinLoadBalancer.<Client>create());
// Add to the load balancer
instances.add(1);
instances.add(2);
// Perform 10 operations
List<String> result = Observable
.interval(100, TimeUnit.MILLISECONDS)
.concatMap(new Func1<Long, Observable<String>>() {
@Override
public Observable<String> call(final Long counter) {
return Observable.just(lb.next())
.concatMap(new Func1<Client, Observable<String>>() {
@Override
public Observable<String> call(Client instance) {
instance.onBegin();
if (1 == instance.getValue()) {
instance.onFailed();
return Observable.error(new Exception("Failed"));
}
instance.onSuccess();
return Observable.just(instance + "-" + counter);
}
})
.retry(1);
}
})
.take(10)
.toList()
.toBlocking()
.first()
;
}
@Test
public void integrationTest() {
final InstanceManager<Integer> instances = InstanceManager.create();
final LoadBalancer<Client> lb = LoadBalancer
.fromSource(instances.map(Client.connector()))
.withQuarantiner(Client.incarnationFactory(), Delays.fixed(1, TimeUnit.SECONDS), scheduler)
.build(ChoiceOfTwoLoadBalancer.<Client>create(Client.compareByMetric()));
instances.add(1);
Client client = lb.next();
instances.add(2);
client = lb.next();
}
}
| 2,187 |
0 | Create_ds/ocelli/ocelli-core/src/test/java/netflix | Create_ds/ocelli/ocelli-core/src/test/java/netflix/ocelli/LoadBalancerTest.java | package netflix.ocelli;
import com.google.common.collect.Lists;
import netflix.ocelli.InstanceQuarantiner.IncarnationFactory;
import netflix.ocelli.functions.Delays;
import netflix.ocelli.loadbalancer.ChoiceOfTwoLoadBalancer;
import netflix.ocelli.loadbalancer.RoundRobinLoadBalancer;
import org.hamcrest.MatcherAssert;
import org.junit.Test;
import rx.Observable;
import rx.Subscription;
import rx.functions.Func0;
import rx.functions.Func1;
import rx.schedulers.TestScheduler;
import java.util.Comparator;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import static org.hamcrest.Matchers.*;
public class LoadBalancerTest {
private static final Comparator<ClientWithWeight> COMPARE_BY_WEIGHT = new Comparator<ClientWithWeight>() {
@Override
public int compare(ClientWithWeight o1, ClientWithWeight o2) {
return o1.weight.compareTo(o2.weight);
}
};
private static final Func1<Instance<String>, Instance<ClientWithWeight>> CLIENT_FROM_ADDRESS = new Func1<Instance<String>, Instance<ClientWithWeight>>() {
@Override
public Instance<ClientWithWeight> call(Instance<String> t1) {
return Instance.create(new ClientWithWeight(t1.getValue(), 1), t1.getLifecycle());
}
};
@Test
public void createFromFixedList() {
LoadBalancer<String> lb = LoadBalancer
.fromFixedSource(Lists.newArrayList("host1:8080", "host2:8080"))
.build(RoundRobinLoadBalancer.<String>create(0),
InstanceCollector.create(new Func0<Map<String, Subscription>>() {
@Override
public Map<String, Subscription> call() {
return new LinkedHashMap<String, Subscription>();
}
}))
;
MatcherAssert.assertThat("Unexpected first host chosen.", lb.next(), is("host2:8080"));
MatcherAssert.assertThat("Unexpected second host chosen.", lb.next(), is("host1:8080"));
}
@Test
public void createFromFixedListAndConvertToDifferentType() {
LoadBalancer<ClientWithWeight> lb = LoadBalancer
.fromFixedSource(Lists.newArrayList("host1:8080", "host2:8080"))
.convertTo(CLIENT_FROM_ADDRESS)
.build(RoundRobinLoadBalancer.<ClientWithWeight>create(0),
InstanceCollector.create(new Func0<Map<ClientWithWeight, Subscription>>() {
@Override
public Map<ClientWithWeight, Subscription> call() {
return new LinkedHashMap<ClientWithWeight, Subscription>();
}
}))
;
MatcherAssert.assertThat("Unexpected first host chosen.", lb.next().address, equalTo("host2:8080"));
MatcherAssert.assertThat("Unexpected second host chosen.", lb.next().address, equalTo("host1:8080"));
}
@Test
public void createFromFixedListWithAdvancedAlgorithm() {
LoadBalancer<ClientWithWeight> lb = LoadBalancer
.fromFixedSource(
Lists.newArrayList(new ClientWithWeight("host1:8080", 1), new ClientWithWeight("host2:8080", 2)))
.build(ChoiceOfTwoLoadBalancer.create(COMPARE_BY_WEIGHT),
InstanceCollector.create(new Func0<Map<ClientWithWeight, Subscription>>() {
@Override
public Map<ClientWithWeight, Subscription> call() {
return new LinkedHashMap<ClientWithWeight, Subscription>();
}
}))
;
MatcherAssert.assertThat("Unexpected first host chosen.", lb.next().address, equalTo("host2:8080"));
MatcherAssert.assertThat("Unexpected second host chosen.", lb.next().address, equalTo("host2:8080"));
}
@Test
public void createFromFixedAndUseQuaratiner() {
TestScheduler scheduler = new TestScheduler();
LoadBalancer<ClientWithLifecycle> lb = LoadBalancer
.fromFixedSource(Lists.newArrayList(new ClientWithLifecycle("host1:8080"),
new ClientWithLifecycle("host2:8080")))
.withQuarantiner(new IncarnationFactory<ClientWithLifecycle>() {
@Override
public ClientWithLifecycle create(ClientWithLifecycle client,
InstanceEventListener listener,
Observable<Void> lifecycle) {
return new ClientWithLifecycle(client, listener);
}
}, Delays.fixed(10, TimeUnit.SECONDS), scheduler)
.build(RoundRobinLoadBalancer.<ClientWithLifecycle>create(0),
InstanceCollector.create(new Func0<Map<ClientWithLifecycle, Subscription>>() {
@Override
public Map<ClientWithLifecycle, Subscription> call() {
return new LinkedHashMap<ClientWithLifecycle, Subscription>();
}
}));
ClientWithLifecycle clientToFail = lb.next();
MatcherAssert.assertThat("Unexpected host chosen before failure.", clientToFail.address, equalTo("host2:8080"));
clientToFail.forceFail();
MatcherAssert.assertThat("Unexpected first host chosen post failure.", lb.next().address, equalTo("host1:8080"));
MatcherAssert.assertThat("Unexpected second host chosen post failure.", lb.next().address, equalTo("host1:8080"));
}
static class ClientWithLifecycle {
private final String address;
private final InstanceEventListener listener;
public ClientWithLifecycle(String address) {
this.address = address;
listener = null;
}
public ClientWithLifecycle(ClientWithLifecycle parent, InstanceEventListener listener) {
address = parent.address;
this.listener = listener;
}
public void forceFail() {
listener.onEvent(InstanceEvent.EXECUTION_FAILED, 0, TimeUnit.MILLISECONDS, new Throwable("Failed"), null);
}
}
static class ClientWithWeight {
private final String address;
private final Integer weight;
public ClientWithWeight(String address, int weight) {
this.address = address;
this.weight = weight;
}
}
}
| 2,188 |
0 | Create_ds/ocelli/ocelli-core/src/test/java/netflix/ocelli | Create_ds/ocelli/ocelli-core/src/test/java/netflix/ocelli/retry/RetryFailedTestRule.java | package netflix.ocelli.retry;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import org.junit.rules.TestRule;
import org.junit.runner.Description;
import org.junit.runners.model.Statement;
public class RetryFailedTestRule implements TestRule {
private int attemptNumber;
@Target({ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
public @interface Retry {
int value();
}
public RetryFailedTestRule() {
this.attemptNumber = 0;
}
public Statement apply(final Statement base, final Description description) {
Retry retry = description.getAnnotation(Retry.class);
final int retryCount = retry == null ? 1 : retry.value();
return new Statement() {
@Override
public void evaluate() throws Throwable {
Throwable caughtThrowable = null;
for (attemptNumber = 0; attemptNumber <= retryCount; ++attemptNumber) {
try {
base.evaluate();
System.err.println(description.getDisplayName() + ": attempt number " + attemptNumber + " succeeded");
return;
} catch (Throwable t) {
caughtThrowable = t;
System.err.println(description.getDisplayName() + ": attempt number " + attemptNumber + " failed:");
System.err.println(t.toString());
}
}
System.err.println(description.getDisplayName() + ": giving up after " + retryCount + " failures.");
throw caughtThrowable;
}
};
}
public int getAttemptNumber() {
return attemptNumber;
}
}
| 2,189 |
0 | Create_ds/ocelli/ocelli-core/src/test/java/netflix/ocelli | Create_ds/ocelli/ocelli-core/src/test/java/netflix/ocelli/retry/BackupRequestStrategyTest.java | package netflix.ocelli.retry;
import netflix.ocelli.LoadBalancer;
import netflix.ocelli.functions.Metrics;
import netflix.ocelli.loadbalancer.RoundRobinLoadBalancer;
import netflix.ocelli.retrys.BackupRequestRetryStrategy;
import netflix.ocelli.util.RxUtil;
import org.junit.Assert;
import org.junit.Ignore;
import org.junit.Test;
import rx.Observable;
import rx.functions.Action1;
import rx.functions.Func1;
import rx.schedulers.TestScheduler;
import rx.subjects.BehaviorSubject;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReference;
@Ignore
// Test needs to be updated to tracks clients not as Observables since they cannot be
// effectively compared when cached internally
public class BackupRequestStrategyTest {
private final Func1<Observable<Integer>, Observable<String>> Operation = new Func1<Observable<Integer>, Observable<String>>() {
@Override
public Observable<String> call(Observable<Integer> t1) {
return t1.map(new Func1<Integer, String>() {
@Override
public String call(Integer t1) {
return t1.toString();
}
});
}
};
private final TestScheduler scheduler = new TestScheduler();
private final BackupRequestRetryStrategy<String> strategy = BackupRequestRetryStrategy.<String>builder()
.withScheduler(scheduler)
.withTimeoutMetric(Metrics.memoize(1000L))
.build();
@Test
public void firstSucceedsFast() {
BehaviorSubject<List<Observable<Integer>>> subject = BehaviorSubject.create(Arrays.asList(
Observable.just(1),
Observable.just(2),
Observable.just(3)));
LoadBalancer<Observable<Integer>> lb = LoadBalancer.fromSnapshotSource(subject).build(RoundRobinLoadBalancer.<Observable<Integer>>create(-1));
final AtomicInteger lbCounter = new AtomicInteger();
final AtomicReference<String> result = new AtomicReference<String>();
lb .toObservable()
.doOnNext(RxUtil.increment(lbCounter))
.flatMap(Operation)
.compose(strategy)
.doOnNext(RxUtil.set(result))
.subscribe();
scheduler.advanceTimeBy(2, TimeUnit.SECONDS);
scheduler.advanceTimeBy(1, TimeUnit.SECONDS);
Assert.assertEquals("1", result.get());
Assert.assertEquals(1, lbCounter.get());
}
@Test
public void firstNeverSecondSucceeds() {
BehaviorSubject<List<Observable<Integer>>> subject = BehaviorSubject.create(Arrays.asList(
Observable.<Integer>never(),
Observable.just(2),
Observable.just(3)));
LoadBalancer<Observable<Integer>> lb = LoadBalancer.fromSnapshotSource(subject).build(RoundRobinLoadBalancer.<Observable<Integer>>create(-1));
final AtomicInteger lbCounter = new AtomicInteger();
final AtomicReference<String> result = new AtomicReference<String>();
lb .toObservable()
.doOnNext(RxUtil.increment(lbCounter))
.flatMap(Operation)
.compose(strategy)
.doOnNext(RxUtil.set(result))
.subscribe();
scheduler.advanceTimeBy(2, TimeUnit.SECONDS);
scheduler.advanceTimeBy(1, TimeUnit.SECONDS);
Assert.assertEquals("2", result.get());
Assert.assertEquals(2, lbCounter.get());
}
@Test
public void firstFailsSecondSucceeds() {
BehaviorSubject<List<Observable<Integer>>> subject = BehaviorSubject.create(Arrays.asList(
Observable.<Integer>error(new Exception("1")),
Observable.just(2),
Observable.just(3)));
LoadBalancer<Observable<Integer>> lb = LoadBalancer.fromSnapshotSource(subject).build(RoundRobinLoadBalancer.<Observable<Integer>>create(-1));
final AtomicInteger lbCounter = new AtomicInteger();
final AtomicReference<String> result = new AtomicReference<String>();
lb .toObservable()
.doOnNext(RxUtil.increment(lbCounter))
.flatMap(Operation)
.compose(strategy)
.doOnNext(RxUtil.set(result))
.subscribe();
scheduler.advanceTimeBy(2, TimeUnit.SECONDS);
scheduler.advanceTimeBy(1, TimeUnit.SECONDS);
Assert.assertEquals("2", result.get());
Assert.assertEquals(2, lbCounter.get());
}
@Test
public void bothDelayed() {
BehaviorSubject<List<Observable<Integer>>> subject = BehaviorSubject.create(Arrays.asList(
Observable.just(1).delaySubscription(2, TimeUnit.SECONDS, scheduler),
Observable.just(2).delaySubscription(2, TimeUnit.SECONDS, scheduler),
Observable.just(3)));
LoadBalancer<Observable<Integer>> lb = LoadBalancer.fromSnapshotSource(subject).build(RoundRobinLoadBalancer.<Observable<Integer>>create(-1));
final AtomicInteger lbCounter = new AtomicInteger();
final AtomicReference<String> result = new AtomicReference<String>();
lb .toObservable()
.doOnNext(RxUtil.increment(lbCounter))
.flatMap(Operation)
.compose(strategy)
.doOnNext(RxUtil.set(result))
.subscribe();
scheduler.advanceTimeBy(1, TimeUnit.SECONDS);
scheduler.advanceTimeBy(1, TimeUnit.SECONDS);
scheduler.advanceTimeBy(3, TimeUnit.SECONDS);
Assert.assertEquals(2, lbCounter.get());
Assert.assertEquals("1", result.get());
}
@Test
public void bothFailed() {
BehaviorSubject<List<Observable<Integer>>> subject = BehaviorSubject.create(Arrays.asList(
Observable.<Integer>error(new Exception("1")),
Observable.<Integer>error(new Exception("2")),
Observable.just(3)));
LoadBalancer<Observable<Integer>> lb = LoadBalancer.fromSnapshotSource(subject).build(RoundRobinLoadBalancer.<Observable<Integer>>create(-1));
final AtomicInteger lbCounter = new AtomicInteger();
final AtomicReference<String> result = new AtomicReference<String>();
final AtomicBoolean failed = new AtomicBoolean(false);
lb .toObservable()
.doOnNext(RxUtil.increment(lbCounter))
.flatMap(Operation)
.compose(strategy)
.doOnNext(RxUtil.set(result))
.doOnError(new Action1<Throwable>() {
@Override
public void call(Throwable t1) {
failed.set(true);
}
})
.subscribe();
scheduler.advanceTimeBy(1, TimeUnit.SECONDS);
scheduler.advanceTimeBy(1, TimeUnit.SECONDS);
scheduler.advanceTimeBy(3, TimeUnit.SECONDS);
Assert.assertEquals(2, lbCounter.get());
Assert.assertTrue(failed.get());
}
@Test
public void firstSucceedsSecondFailsAfterBackupStarted() {
BehaviorSubject<List<Observable<Integer>>> subject = BehaviorSubject.create(Arrays.asList(
Observable.just(1).delaySubscription(2, TimeUnit.SECONDS, scheduler),
Observable.<Integer>error(new Exception("2")),
Observable.just(3)));
LoadBalancer<Observable<Integer>> lb = LoadBalancer.fromSnapshotSource(subject).build(RoundRobinLoadBalancer.<Observable<Integer>>create(-1));
final AtomicInteger lbCounter = new AtomicInteger();
final AtomicReference<String> result = new AtomicReference<String>();
lb .toObservable()
.doOnNext(RxUtil.increment(lbCounter))
.flatMap(Operation)
.compose(strategy)
.doOnNext(RxUtil.set(result))
.subscribe();
scheduler.advanceTimeBy(1, TimeUnit.SECONDS);
scheduler.advanceTimeBy(1, TimeUnit.SECONDS);
scheduler.advanceTimeBy(1, TimeUnit.SECONDS);
Assert.assertEquals("1", result.get());
Assert.assertEquals(2, lbCounter.get());
}
}
| 2,190 |
0 | Create_ds/ocelli/ocelli-core/src/test/java/netflix/ocelli | Create_ds/ocelli/ocelli-core/src/test/java/netflix/ocelli/util/CountDownAction.java | package netflix.ocelli.util;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import rx.functions.Action1;
public class CountDownAction<T> implements Action1<T> {
private CountDownLatch latch;
private CopyOnWriteArrayList<T> list = new CopyOnWriteArrayList<T>();
public CountDownAction(int count) {
latch = new CountDownLatch(count);
}
@Override
public void call(T t1) {
list.add(t1);
latch.countDown();
}
public void await(long timeout, TimeUnit units) throws Exception {
latch.await(timeout, units);
}
public List<T> get() {
return list;
}
public void reset(int count) {
latch = new CountDownLatch(count);
list = new CopyOnWriteArrayList<T>();
}
}
| 2,191 |
0 | Create_ds/ocelli/ocelli-core/src/test/java/netflix/ocelli | Create_ds/ocelli/ocelli-core/src/test/java/netflix/ocelli/util/RandomQueueTest.java | package netflix.ocelli.util;
import org.junit.Assert;
import org.junit.Ignore;
import org.junit.Test;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.NoSuchElementException;
import java.util.concurrent.TimeUnit;
public class RandomQueueTest {
@Test
public void shouldBeInitiallyEmpty() {
RandomBlockingQueue<Integer> queue = new RandomBlockingQueue<Integer>();
Assert.assertTrue(queue.isEmpty());
Assert.assertNull(queue.peek());
Assert.assertTrue(queue.isEmpty());
try {
queue.remove();
Assert.fail();
}
catch (NoSuchElementException e) {
}
}
@Test
public void shouldBlockEmptyQueue() throws InterruptedException {
RandomBlockingQueue<Integer> queue = new RandomBlockingQueue<Integer>();
Assert.assertNull(queue.poll(100, TimeUnit.MILLISECONDS));
}
@Test
@Ignore
public void addRemoveAndShouldBlock() throws InterruptedException {
RandomBlockingQueue<Integer> queue = new RandomBlockingQueue<Integer>();
queue.add(123);
Integer item = queue.take();
Assert.assertEquals((Integer)123, item);
Assert.assertNull(queue.poll(100, TimeUnit.MILLISECONDS));
}
@Test
public void addOne() {
RandomBlockingQueue<Integer> queue = new RandomBlockingQueue<Integer>();
queue.add(123);
Assert.assertTrue(!queue.isEmpty());
Assert.assertEquals(1, queue.size());
Assert.assertEquals((Integer)123, queue.peek());
Assert.assertEquals((Integer)123, queue.poll());
Assert.assertTrue(queue.isEmpty());
Assert.assertEquals(0, queue.size());
Assert.assertNull(queue.peek());
try {
queue.remove();
Assert.fail();
}
catch (NoSuchElementException e) {
}
}
@Test(timeout=1000)
public void removeIsRandom() {
RandomBlockingQueue<Integer> queue = new RandomBlockingQueue<Integer>();
List<Integer> items = new ArrayList<Integer>();
for (int i = 0; i < 100; i++) {
items.add(i);
queue.add(i);
}
List<Integer> actual = new ArrayList<Integer>();
Integer item;
while (null != (item = queue.poll())) {
actual.add(item);
}
Assert.assertTrue(queue.isEmpty());
Assert.assertEquals(100, actual.size());
Assert.assertNotSame(items, actual);
Collections.sort(actual);
Assert.assertEquals(items, actual);
}
}
| 2,192 |
0 | Create_ds/ocelli/ocelli-core/src/test/java/netflix/ocelli | Create_ds/ocelli/ocelli-core/src/test/java/netflix/ocelli/toplogies/TopologiesTest.java | package netflix.ocelli.toplogies;
import com.google.common.collect.Sets;
import netflix.ocelli.CloseableInstance;
import netflix.ocelli.Host;
import netflix.ocelli.Instance;
import netflix.ocelli.InstanceCollector;
import netflix.ocelli.functions.Functions;
import netflix.ocelli.topologies.RingTopology;
import netflix.ocelli.util.RxUtil;
import org.junit.Assert;
import org.junit.Test;
import rx.schedulers.TestScheduler;
import rx.subjects.PublishSubject;
import java.util.List;
import java.util.concurrent.atomic.AtomicReference;
public class TopologiesTest {
public static class HostWithId extends Host {
private final Integer id;
public HostWithId(String hostName, int port, Integer id) {
super(hostName, port);
this.id = id;
}
public Integer getId() {
return this.id;
}
public String toString() {
return id.toString();
}
}
@Test
public void test() {
CloseableInstance<Integer> m1 = CloseableInstance.from(1);
CloseableInstance<Integer> m2 = CloseableInstance.from(2);
CloseableInstance<Integer> m3 = CloseableInstance.from(3);
CloseableInstance<Integer> m4 = CloseableInstance.from(4);
CloseableInstance<Integer> m6 = CloseableInstance.from(6);
CloseableInstance<Integer> m7 = CloseableInstance.from(7);
CloseableInstance<Integer> m8 = CloseableInstance.from(8);
CloseableInstance<Integer> m9 = CloseableInstance.from(9);
CloseableInstance<Integer> m10 = CloseableInstance.from(10);
CloseableInstance<Integer> m11 = CloseableInstance.from(11);
PublishSubject<Instance<Integer>> members = PublishSubject.create();
TestScheduler scheduler = new TestScheduler();
RingTopology<Integer, Integer> mapper = RingTopology.create(5, Functions.identity(), Functions.memoize(3), scheduler);
AtomicReference<List<Integer>> current = new AtomicReference<List<Integer>>();
members
.doOnNext(RxUtil.info("add"))
.compose(mapper)
.compose(InstanceCollector.<Integer>create())
.doOnNext(RxUtil.info("current"))
.subscribe(RxUtil.set(current));
members.onNext(m11);
Assert.assertEquals(Sets.newHashSet(11) , Sets.newHashSet(current.get()));
members.onNext(m7);
Assert.assertEquals(Sets.newHashSet(7, 11) , Sets.newHashSet(current.get()));
members.onNext(m1);
Assert.assertEquals(Sets.newHashSet(1, 7, 11) , Sets.newHashSet(current.get()));
members.onNext(m2);
Assert.assertEquals(Sets.newHashSet(1, 7, 11) , Sets.newHashSet(current.get()));
members.onNext(m4);
Assert.assertEquals(Sets.newHashSet(1, 7, 11) , Sets.newHashSet(current.get()));
members.onNext(m3);
Assert.assertEquals(Sets.newHashSet(1, 7, 11) , Sets.newHashSet(current.get()));
members.onNext(m8);
Assert.assertEquals(Sets.newHashSet(7, 8, 11) , Sets.newHashSet(current.get()));
members.onNext(m10);
Assert.assertEquals(Sets.newHashSet(7, 8, 10), Sets.newHashSet(current.get()));
members.onNext(m9);
Assert.assertEquals(Sets.newHashSet(7, 8, 9), Sets.newHashSet(current.get()));
members.onNext(m6);
Assert.assertEquals(Sets.newHashSet(6, 7, 8), Sets.newHashSet(current.get()));
m6.close();
Assert.assertEquals(Sets.newHashSet(7, 8, 9), Sets.newHashSet(current.get()));
m9.close();
Assert.assertEquals(Sets.newHashSet(7, 8, 10), Sets.newHashSet(current.get()));
m8.close();
Assert.assertEquals(Sets.newHashSet(7, 10, 11), Sets.newHashSet(current.get()));
}
}
| 2,193 |
0 | Create_ds/ocelli/ocelli-core/src/test/java/netflix/ocelli | Create_ds/ocelli/ocelli-core/src/test/java/netflix/ocelli/loadbalancer/ChoiceOfTwoLoadBalancerTest.java | package netflix.ocelli.loadbalancer;
import com.google.common.collect.Lists;
import netflix.ocelli.LoadBalancer;
import org.junit.Assert;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TestName;
import rx.subjects.BehaviorSubject;
import java.util.Comparator;
import java.util.List;
import java.util.NoSuchElementException;
import java.util.concurrent.atomic.AtomicIntegerArray;
public class ChoiceOfTwoLoadBalancerTest {
@Rule
public TestName name = new TestName();
private static final Comparator<Integer> COMPARATOR = new Comparator<Integer>() {
@Override
public int compare(Integer o1, Integer o2) {
return o1 - o2;
}
};
@Test(expected=NoSuchElementException.class)
public void testEmpty() {
BehaviorSubject<List<Integer>> source = BehaviorSubject.create();
LoadBalancer<Integer> lb = LoadBalancer.fromSnapshotSource(source).build(ChoiceOfTwoLoadBalancer.create(COMPARATOR));
source.onNext(Lists.<Integer>newArrayList());
lb.next();
}
@Test
public void testOne() {
BehaviorSubject<List<Integer>> source = BehaviorSubject.create();
LoadBalancer<Integer> lb = LoadBalancer.fromSnapshotSource(source).build(ChoiceOfTwoLoadBalancer.create(COMPARATOR));
source.onNext(Lists.newArrayList(0));
for (int i = 0; i < 100; i++) {
Assert.assertEquals(0, (int)lb.next());
}
}
@Test
public void testTwo() {
BehaviorSubject<List<Integer>> source = BehaviorSubject.create();
LoadBalancer<Integer> lb = LoadBalancer.fromSnapshotSource(source).build(ChoiceOfTwoLoadBalancer.create(COMPARATOR));
source.onNext(Lists.newArrayList(0,1));
AtomicIntegerArray counts = new AtomicIntegerArray(2);
for (int i = 0; i < 100; i++) {
counts.incrementAndGet(lb.next());
}
Assert.assertEquals(counts.get(0), 0);
Assert.assertEquals(counts.get(1), 100);
}
@Test
public void testMany() {
BehaviorSubject<List<Integer>> source = BehaviorSubject.create();
LoadBalancer<Integer> lb = LoadBalancer.fromSnapshotSource(source).build(ChoiceOfTwoLoadBalancer.create(COMPARATOR));
source.onNext(Lists.newArrayList(0,1,2,3,4,5,6,7,8,9));
AtomicIntegerArray counts = new AtomicIntegerArray(10);
for (int i = 0; i < 100000; i++) {
counts.incrementAndGet(lb.next());
}
Double[] pct = new Double[counts.length()];
for (int i = 0; i < counts.length(); i++) {
pct[i] = counts.get(i)/100000.0;
}
for (int i = 1; i < counts.length(); i++) {
Assert.assertTrue(counts.get(i) > counts.get(i-1));
}
}
}
| 2,194 |
0 | Create_ds/ocelli/ocelli-core/src/test/java/netflix/ocelli/loadbalancer | Create_ds/ocelli/ocelli-core/src/test/java/netflix/ocelli/loadbalancer/weighting/InverseMaxWeightingStrategyTest.java | package netflix.ocelli.loadbalancer.weighting;
import com.google.common.collect.Lists;
import netflix.ocelli.LoadBalancer;
import netflix.ocelli.loadbalancer.RandomWeightedLoadBalancer;
import netflix.ocelli.retry.RetryFailedTestRule;
import netflix.ocelli.retry.RetryFailedTestRule.Retry;
import org.junit.Assert;
import org.junit.Rule;
import org.junit.Test;
import rx.subjects.BehaviorSubject;
import java.util.Arrays;
import java.util.List;
import java.util.NoSuchElementException;
public class InverseMaxWeightingStrategyTest extends BaseWeightingStrategyTest {
@Rule
public RetryFailedTestRule retryRule = new RetryFailedTestRule();
BehaviorSubject<List<IntClientAndMetrics>> subject = BehaviorSubject.create();
LoadBalancer<IntClientAndMetrics> lb = LoadBalancer.fromSnapshotSource(subject).build(RandomWeightedLoadBalancer.create(
new InverseMaxWeightingStrategy<IntClientAndMetrics>(IntClientAndMetrics.BY_METRIC)));
@Test(expected=NoSuchElementException.class)
public void testEmptyClients() throws Throwable {
List<IntClientAndMetrics> clients = create();
subject.onNext(clients);
List<Integer> counts = Arrays.<Integer>asList(roundToNearest(simulate(lb, clients.size(), 1000), 100));
Assert.assertEquals(Lists.newArrayList(), counts);
}
@Test
@Retry(5)
public void testOneClient() throws Throwable {
List<IntClientAndMetrics> clients = create(10);
subject.onNext(clients);
List<Integer> counts = Arrays.<Integer>asList(roundToNearest(simulate(lb, clients.size(), 1000), 100));
Assert.assertEquals(Lists.newArrayList(1000), counts);
}
@Test
@Retry(5)
public void testEqualsWeights() throws Throwable {
List<IntClientAndMetrics> clients = create(1,1,1,1);
subject.onNext(clients);
List<Integer> counts = Arrays.<Integer>asList(roundToNearest(simulate(lb, clients.size(), 4000), 100));
Assert.assertEquals(Lists.newArrayList(1000, 1000, 1000, 1000), counts);
}
@Test
@Retry(5)
public void testDifferentWeights() throws Throwable {
List<IntClientAndMetrics> clients = create(1,2,3,4);
subject.onNext(clients);
List<Integer> counts = Arrays.<Integer>asList(roundToNearest(simulate(lb, clients.size(), 4000), 100));
Assert.assertEquals(Lists.newArrayList(1600, 1200, 800, 400), counts);
}
}
| 2,195 |
0 | Create_ds/ocelli/ocelli-core/src/test/java/netflix/ocelli/loadbalancer | Create_ds/ocelli/ocelli-core/src/test/java/netflix/ocelli/loadbalancer/weighting/LinearWeightingStrategyTest.java | package netflix.ocelli.loadbalancer.weighting;
import com.google.common.collect.Lists;
import netflix.ocelli.LoadBalancer;
import netflix.ocelli.loadbalancer.RandomWeightedLoadBalancer;
import netflix.ocelli.retry.RetryFailedTestRule;
import netflix.ocelli.retry.RetryFailedTestRule.Retry;
import org.junit.Assert;
import org.junit.Rule;
import org.junit.Test;
import rx.subjects.BehaviorSubject;
import java.util.Arrays;
import java.util.List;
import java.util.NoSuchElementException;
public class LinearWeightingStrategyTest extends BaseWeightingStrategyTest {
@Rule
public RetryFailedTestRule retryRule = new RetryFailedTestRule();
BehaviorSubject<List<IntClientAndMetrics>> subject = BehaviorSubject.create();
LoadBalancer<IntClientAndMetrics> lb = LoadBalancer.fromSnapshotSource(subject).build(RandomWeightedLoadBalancer.create(
new LinearWeightingStrategy<IntClientAndMetrics>(IntClientAndMetrics.BY_METRIC)));
@Test(expected=NoSuchElementException.class)
public void testEmptyClients() throws Throwable {
List<IntClientAndMetrics> clients = create();
subject.onNext(clients);
List<Integer> counts = Arrays.<Integer>asList(roundToNearest(simulate(lb, clients.size(), 1000), 100));
Assert.assertEquals(Lists.newArrayList(), counts);
}
@Test
@Retry(5)
public void testOneClient() throws Throwable {
List<IntClientAndMetrics> clients = create(10);
subject.onNext(clients);
List<Integer> counts = Arrays.<Integer>asList(roundToNearest(simulate(lb, clients.size(), 1000), 100));
Assert.assertEquals(Lists.newArrayList(1000), counts);
}
@Test
@Retry(5)
public void testEqualsWeights() throws Throwable {
List<IntClientAndMetrics> clients = create(1,1,1,1);
subject.onNext(clients);
List<Integer> counts = Arrays.<Integer>asList(roundToNearest(simulate(lb, clients.size(), 4000), 100));
Assert.assertEquals(Lists.newArrayList(1000, 1000, 1000, 1000), counts);
}
@Test
@Retry(5)
public void testDifferentWeights() throws Throwable {
List<IntClientAndMetrics> clients = create(1,2,3,4);
subject.onNext(clients);
List<Integer> counts = Arrays.<Integer>asList(roundToNearest(simulate(lb, clients.size(), 4000), 100));
Assert.assertEquals(Lists.newArrayList(400, 800, 1200, 1600), counts);
}
}
| 2,196 |
0 | Create_ds/ocelli/ocelli-core/src/test/java/netflix/ocelli/loadbalancer | Create_ds/ocelli/ocelli-core/src/test/java/netflix/ocelli/loadbalancer/weighting/IntClientAndMetrics.java | package netflix.ocelli.loadbalancer.weighting;
import rx.functions.Func1;
public class IntClientAndMetrics {
private Integer client;
private Integer metrics;
public IntClientAndMetrics(int client, int metrics) {
this.client = client;
this.metrics = metrics;
}
public Integer getClient() {
return client;
}
public Integer getMetrics() {
return metrics;
}
public static Func1<IntClientAndMetrics, Integer> BY_METRIC = new Func1<IntClientAndMetrics, Integer>() {
@Override
public Integer call(IntClientAndMetrics t1) {
return t1.getMetrics();
}
};
@Override
public String toString() {
return "IntClientAndMetrics [client=" + client + ", metrics=" + metrics + "]";
}
}
| 2,197 |
0 | Create_ds/ocelli/ocelli-core/src/test/java/netflix/ocelli/loadbalancer | Create_ds/ocelli/ocelli-core/src/test/java/netflix/ocelli/loadbalancer/weighting/BaseWeightingStrategyTest.java | package netflix.ocelli.loadbalancer.weighting;
import java.util.ArrayList;
import java.util.List;
import netflix.ocelli.LoadBalancer;
import org.junit.Ignore;
import rx.exceptions.OnErrorNotImplementedException;
import rx.functions.Action1;
import com.google.common.base.Function;
import com.google.common.base.Joiner;
import com.google.common.collect.Collections2;
import com.google.common.collect.Lists;
@Ignore
public class BaseWeightingStrategyTest {
/**
* Creates a list of clients
*
* @param weights
* @return
*/
static List<IntClientAndMetrics> create(Integer... weights) {
List<IntClientAndMetrics> cam = new ArrayList<IntClientAndMetrics>(weights.length);
int counter = 0;
for (int i = 0; i < weights.length; i++) {
cam.add(new IntClientAndMetrics(counter++, weights[i]));
}
return cam;
}
/**
* Get an array of weights with indexes matching the list of clients.
* @param caw
* @return
*/
static int[] getWeights(ClientsAndWeights<IntClientAndMetrics> caw) {
int[] weights = new int[caw.size()];
for (int i = 0; i < caw.size(); i++) {
weights[i] = caw.getWeight(i);
}
return weights;
}
/**
* Run a simulation of 'count' selects and update the clients
* @param strategy
* @param N
* @param count
* @return
* @throws Throwable
*/
static Integer[] simulate(LoadBalancer<IntClientAndMetrics> lb, int N, int count) throws Throwable {
// Set up array of counts
final Integer[] counts = new Integer[N];
for (int i = 0; i < N; i++) {
counts[i] = 0;
}
// Run simulation
for (int i = 0; i < count; i++) {
try {
lb.toObservable().subscribe(new Action1<IntClientAndMetrics>() {
@Override
public void call(IntClientAndMetrics t1) {
counts[t1.getClient()] = counts[t1.getClient()] + 1;
}
});
}
catch (OnErrorNotImplementedException e) {
throw e.getCause();
}
}
return counts;
}
static Integer[] roundToNearest(Integer[] counts, int amount) {
int middle = amount / 2;
for (int i = 0; i < counts.length; i++) {
counts[i] = amount * ((counts[i] + middle) / amount);
}
return counts;
}
static String printClients(IntClientAndMetrics[] clients) {
return Joiner.on(", ").join(Collections2.transform(Lists.newArrayList(clients), new Function<IntClientAndMetrics, Integer>() {
@Override
public Integer apply(IntClientAndMetrics arg0) {
return arg0.getClient();
}
}));
}
static String printMetrics(IntClientAndMetrics[] clients) {
return Joiner.on(", ").join(Collections2.transform(Lists.newArrayList(clients), new Function<IntClientAndMetrics, Integer>() {
@Override
public Integer apply(IntClientAndMetrics arg0) {
return arg0.getMetrics();
}
}));
}
}
| 2,198 |
0 | Create_ds/ocelli/ocelli-core/src/test/java/netflix/ocelli | Create_ds/ocelli/ocelli-core/src/test/java/netflix/ocelli/functions/GuardsTest.java | package netflix.ocelli.functions;
import org.junit.Test;
import rx.functions.Func1;
public class GuardsTest {
@Test
public void shouldRejectAfter100Percent() {
Func1<Boolean, Boolean> guard = Limiters.exponential(0.90, 30);
int discarded = 0;
for (int i = 0; i < 100; i++) {
guard.call(true);
if (!guard.call(false)) {
discarded++;
}
}
System.out.println("Discarded : " + discarded);
}
@Test
public void shouldRejectAfter90Percent() {
Func1<Boolean, Boolean> guard = Limiters.exponential(0.90, 30);
int discarded = 0;
for (int i = 0; i < 100; i++) {
guard.call(true);
if (i % 5 == 0) {
if (!guard.call(false)) {
discarded++;
}
}
}
System.out.println("Discarded : " + discarded);
}
}
| 2,199 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.