Merging if statements (#7851)

This commit is contained in:
André Oliveira 2022-10-01 19:51:39 +01:00 committed by GitHub
parent 03f1d4f2fb
commit 736637a598
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
9 changed files with 64 additions and 82 deletions

View File

@ -50,10 +50,8 @@ public abstract class AbstractEventPublisher implements EventPublisher {
throws Exception { throws Exception {
// Ignore events that don't match the webhook event filters // Ignore events that don't match the webhook event filters
ChangeEvent changeEvent = changeEventHolder.get(); ChangeEvent changeEvent = changeEventHolder.get();
if (!filter.isEmpty()) { if (!filter.isEmpty() && !FilterUtil.shouldProcessRequest(changeEvent, filter)) {
if (!FilterUtil.shouldProcessRequest(changeEvent, filter)) { return;
return;
}
} }
// Batch until either the batch has ended or batch size has reached the max size // Batch until either the batch has ended or batch size has reached the max size

View File

@ -967,10 +967,8 @@ public interface CollectionDAO {
return listAnnouncementsByEntityLinkBefore( return listAnnouncementsByEntityLinkBefore(
fqnPrefix, toType, limit, before, type, relation, mysqlCondition, postgresCondition); fqnPrefix, toType, limit, before, type, relation, mysqlCondition, postgresCondition);
} }
if (userName != null) { if (userName != null && filterType == FilterType.MENTIONS) {
if (filterType == FilterType.MENTIONS) { filterRelation = Relationship.MENTIONED_IN.ordinal();
filterRelation = Relationship.MENTIONED_IN.ordinal();
}
} }
return listThreadsByEntityLinkBefore( return listThreadsByEntityLinkBefore(
fqnPrefix, toType, limit, before, type, status, resolved, relation, userName, teamNames, filterRelation); fqnPrefix, toType, limit, before, type, status, resolved, relation, userName, teamNames, filterRelation);
@ -1058,10 +1056,8 @@ public interface CollectionDAO {
return listAnnouncementsByEntityLinkAfter( return listAnnouncementsByEntityLinkAfter(
fqnPrefix, toType, limit, after, type, relation, mysqlCondition, postgresCondition); fqnPrefix, toType, limit, after, type, relation, mysqlCondition, postgresCondition);
} }
if (userName != null) { if (userName != null && filterType == FilterType.MENTIONS) {
if (filterType == FilterType.MENTIONS) { filterRelation = Relationship.MENTIONED_IN.ordinal();
filterRelation = Relationship.MENTIONED_IN.ordinal();
}
} }
return listThreadsByEntityLinkAfter( return listThreadsByEntityLinkAfter(
fqnPrefix, toType, limit, after, type, status, resolved, relation, userName, teamNames, filterRelation); fqnPrefix, toType, limit, after, type, status, resolved, relation, userName, teamNames, filterRelation);
@ -1146,10 +1142,8 @@ public interface CollectionDAO {
} }
return listCountAnnouncementsByEntityLink(fqnPrefix, toType, type, relation, mysqlCondition, postgresCondition); return listCountAnnouncementsByEntityLink(fqnPrefix, toType, type, relation, mysqlCondition, postgresCondition);
} }
if (userName != null) { if (userName != null && filterType == FilterType.MENTIONS) {
if (filterType == FilterType.MENTIONS) { filterRelation = Relationship.MENTIONED_IN.ordinal();
filterRelation = Relationship.MENTIONED_IN.ordinal();
}
} }
return listCountThreadsByEntityLink( return listCountThreadsByEntityLink(
fqnPrefix, toType, type, status, resolved, relation, userName, teamNames, filterRelation); fqnPrefix, toType, type, status, resolved, relation, userName, teamNames, filterRelation);

View File

@ -1221,11 +1221,10 @@ public abstract class EntityRepository<T extends EntityInterface> {
private void updateOwner() throws JsonProcessingException { private void updateOwner() throws JsonProcessingException {
EntityReference origOwner = original.getOwner(); EntityReference origOwner = original.getOwner();
EntityReference updatedOwner = updated.getOwner(); EntityReference updatedOwner = updated.getOwner();
if (operation.isPatch() || updatedOwner != null) { if ((operation.isPatch() || updatedOwner != null)
&& recordChange(FIELD_OWNER, origOwner, updatedOwner, true, entityReferenceMatch)) {
// Update owner for all PATCH operations. For PUT operations, ownership can't be removed // Update owner for all PATCH operations. For PUT operations, ownership can't be removed
if (recordChange(FIELD_OWNER, origOwner, updatedOwner, true, entityReferenceMatch)) { EntityRepository.this.updateOwner(original, origOwner, updatedOwner);
EntityRepository.this.updateOwner(original, origOwner, updatedOwner);
}
} }
} }

View File

@ -1053,22 +1053,22 @@ public class TableRepository extends EntityRepository<Table> {
private void updateColumnPrecision(Column origColumn, Column updatedColumn) throws JsonProcessingException { private void updateColumnPrecision(Column origColumn, Column updatedColumn) throws JsonProcessingException {
String columnField = getColumnField(original, origColumn, "precision"); String columnField = getColumnField(original, origColumn, "precision");
boolean updated = recordChange(columnField, origColumn.getPrecision(), updatedColumn.getPrecision()); boolean updated = recordChange(columnField, origColumn.getPrecision(), updatedColumn.getPrecision());
if (origColumn.getPrecision() != null) { // Previously precision was set if (origColumn.getPrecision() != null
if (updated && updatedColumn.getPrecision() < origColumn.getPrecision()) { && updated
// The precision was reduced. Treat it as backward-incompatible change && updatedColumn.getPrecision() < origColumn.getPrecision()) { // Previously precision was set
majorVersionChange = true; // The precision was reduced. Treat it as backward-incompatible change
} majorVersionChange = true;
} }
} }
private void updateColumnScale(Column origColumn, Column updatedColumn) throws JsonProcessingException { private void updateColumnScale(Column origColumn, Column updatedColumn) throws JsonProcessingException {
String columnField = getColumnField(original, origColumn, "scale"); String columnField = getColumnField(original, origColumn, "scale");
boolean updated = recordChange(columnField, origColumn.getScale(), updatedColumn.getScale()); boolean updated = recordChange(columnField, origColumn.getScale(), updatedColumn.getScale());
if (origColumn.getScale() != null) { // Previously scale was set if (origColumn.getScale() != null
if (updated && updatedColumn.getScale() < origColumn.getScale()) { && updated
// The scale was reduced. Treat it as backward-incompatible change && updatedColumn.getScale() < origColumn.getScale()) { // Previously scale was set
majorVersionChange = true; // The scale was reduced. Treat it as backward-incompatible change
} majorVersionChange = true;
} }
} }
} }

View File

@ -349,10 +349,10 @@ public class UserRepository extends EntityRepository<User> {
AuthenticationMechanism updatedAuthMechanism = updated.getAuthenticationMechanism(); AuthenticationMechanism updatedAuthMechanism = updated.getAuthenticationMechanism();
if (origAuthMechanism == null && updatedAuthMechanism != null) { if (origAuthMechanism == null && updatedAuthMechanism != null) {
recordChange("authenticationMechanism", original.getAuthenticationMechanism(), "new-encrypted-value"); recordChange("authenticationMechanism", original.getAuthenticationMechanism(), "new-encrypted-value");
} else if (origAuthMechanism != null && updatedAuthMechanism != null) { } else if (origAuthMechanism != null
if (!JsonUtils.areEquals(origAuthMechanism, updatedAuthMechanism)) { && updatedAuthMechanism != null
recordChange("authenticationMechanism", "old-encrypted-value", "new-encrypted-value"); && !JsonUtils.areEquals(origAuthMechanism, updatedAuthMechanism)) {
} recordChange("authenticationMechanism", "old-encrypted-value", "new-encrypted-value");
} }
} }
} }

View File

@ -426,11 +426,9 @@ public class UserResource extends EntityResource<User, UserRepository> {
.withUsername(securityContext.getUserPrincipal().getName()) .withUsername(securityContext.getUserPrincipal().getName())
.withToken(request.getToken()) .withToken(request.getToken())
.withLogoutTime(logoutTime)); .withLogoutTime(logoutTime));
if (isBasicAuth()) { if (isBasicAuth() && request.getRefreshToken() != null) {
// need to clear the refresh token as well // need to clear the refresh token as well
if (request.getRefreshToken() != null) { tokenRepository.deleteToken(request.getRefreshToken());
tokenRepository.deleteToken(request.getRefreshToken());
}
} }
return Response.status(200).entity("Logout Successful").build(); return Response.status(200).entity("Logout Successful").build();
} }
@ -1441,16 +1439,16 @@ public class UserResource extends EntityResource<User, UserRepository> {
String botName = create.getBotName(); String botName = create.getBotName();
EntityInterface bot = retrieveBot(botName); EntityInterface bot = retrieveBot(botName);
// check if the bot user exists // check if the bot user exists
if (!botHasRelationshipWithUser(bot, original)) { if (!botHasRelationshipWithUser(bot, original)
&& original != null
&& userHasRelationshipWithAnyBot(original, bot)) {
// throw an exception if user already has a relationship with a bot // throw an exception if user already has a relationship with a bot
if (original != null && userHasRelationshipWithAnyBot(original, bot)) { List<CollectionDAO.EntityRelationshipRecord> userBotRelationship = retrieveBotRelationshipsFor(original);
List<CollectionDAO.EntityRelationshipRecord> userBotRelationship = retrieveBotRelationshipsFor(original); bot =
bot = Entity.getEntityRepository(Entity.BOT)
Entity.getEntityRepository(Entity.BOT) .get(null, userBotRelationship.stream().findFirst().orElseThrow().getId(), Fields.EMPTY_FIELDS);
.get(null, userBotRelationship.stream().findFirst().orElseThrow().getId(), Fields.EMPTY_FIELDS); throw new IllegalArgumentException(
throw new IllegalArgumentException( String.format("Bot user [%s] is already used by [%s] bot.", user.getName(), bot.getName()));
String.format("Bot user [%s] is already used by [%s] bot.", user.getName(), bot.getName()));
}
} }
addAuthMechanismToBot(user, create, uriInfo); addAuthMechanismToBot(user, create, uriInfo);
RestUtil.PutResponse<User> response = dao.createOrUpdate(uriInfo, user); RestUtil.PutResponse<User> response = dao.createOrUpdate(uriInfo, user);

View File

@ -201,11 +201,9 @@ public class JwtFilter implements ContainerRequestFilter {
} }
// validate principal domain // validate principal domain
if (enforcePrincipalDomain) { if (enforcePrincipalDomain && !domain.equals(principalDomain)) {
if (!domain.equals(principalDomain)) { throw new AuthenticationException(
throw new AuthenticationException( String.format("Not Authorized! Email does not match the principal domain %s", principalDomain));
String.format("Not Authorized! Email does not match the principal domain %s", principalDomain));
}
} }
return userName; return userName;
} }

View File

@ -132,11 +132,9 @@ public class CompiledRule extends Rule {
Iterator<MetadataOperation> iterator = operationContext.getOperations().listIterator(); Iterator<MetadataOperation> iterator = operationContext.getOperations().listIterator();
while (iterator.hasNext()) { while (iterator.hasNext()) {
MetadataOperation operation = iterator.next(); MetadataOperation operation = iterator.next();
if (matchOperation(operation)) { if (matchOperation(operation) && matchExpression(policyContext, subjectContext, resourceContext)) {
if (matchExpression(policyContext, subjectContext, resourceContext)) { LOG.info("operation {} allowed", operation);
LOG.info("operation {} allowed", operation); iterator.remove();
iterator.remove();
}
} }
} }
} }
@ -154,15 +152,13 @@ public class CompiledRule extends Rule {
Access access = getAccess(); Access access = getAccess();
// Walk through all the operations in the rule and set permissions // Walk through all the operations in the rule and set permissions
for (Permission permission : resourcePermission.getPermissions()) { for (Permission permission : resourcePermission.getPermissions()) {
if (matchOperation(permission.getOperation())) { if (matchOperation(permission.getOperation()) && overrideAccess(access, permission.getAccess())) {
if (overrideAccess(access, permission.getAccess())) { permission
permission .withAccess(access)
.withAccess(access) .withRole(policyContext.getRoleName())
.withRole(policyContext.getRoleName()) .withPolicy(policyContext.getPolicyName())
.withPolicy(policyContext.getPolicyName()) .withRule(this);
.withRule(this); LOG.debug("Updated permission {}", permission);
LOG.debug("Updated permission {}", permission);
}
} }
} }
} }

View File

@ -62,22 +62,21 @@ public final class ElasticSearchClientUtils {
private static SSLContext createSSLContext(ElasticSearchConfiguration elasticSearchConfiguration) private static SSLContext createSSLContext(ElasticSearchConfiguration elasticSearchConfiguration)
throws KeyStoreException { throws KeyStoreException {
if (elasticSearchConfiguration.getScheme().equals("https")) { if (elasticSearchConfiguration.getScheme().equals("https")
if (elasticSearchConfiguration.getTruststorePath() != null && elasticSearchConfiguration.getTruststorePath() != null
&& !elasticSearchConfiguration.getTruststorePath().isEmpty()) { && !elasticSearchConfiguration.getTruststorePath().isEmpty()) {
Path trustStorePath = Paths.get(elasticSearchConfiguration.getTruststorePath()); Path trustStorePath = Paths.get(elasticSearchConfiguration.getTruststorePath());
KeyStore truststore = KeyStore.getInstance("jks"); KeyStore truststore = KeyStore.getInstance("jks");
try (InputStream is = Files.newInputStream(trustStorePath)) { try (InputStream is = Files.newInputStream(trustStorePath)) {
truststore.load(is, elasticSearchConfiguration.getTruststorePassword().toCharArray()); truststore.load(is, elasticSearchConfiguration.getTruststorePassword().toCharArray());
SSLContextBuilder sslBuilder = SSLContexts.custom().loadTrustMaterial(truststore, null); SSLContextBuilder sslBuilder = SSLContexts.custom().loadTrustMaterial(truststore, null);
return sslBuilder.build(); return sslBuilder.build();
} catch (IOException } catch (IOException
| NoSuchAlgorithmException | NoSuchAlgorithmException
| CertificateException | CertificateException
| KeyStoreException | KeyStoreException
| KeyManagementException e) { | KeyManagementException e) {
throw new RuntimeException("Failed to crete SSLContext to for ElasticSearch Client", e); throw new RuntimeException("Failed to crete SSLContext to for ElasticSearch Client", e);
}
} }
} }
return null; return null;