]> source.dussan.org Git - sonarqube.git/commitdiff
[NO-JIRA] Remove reported code smells about usage of instanceof
authorMatteo Mara <matteo.mara@sonarsource.com>
Mon, 9 Jan 2023 09:21:46 +0000 (10:21 +0100)
committersonartech <sonartech@sonarsource.com>
Tue, 10 Jan 2023 20:03:01 +0000 (20:03 +0000)
20 files changed:
server/sonar-auth-ldap/src/main/java/org/sonar/auth/ldap/CallbackHandlerImpl.java
server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/component/VisitorsCrawler.java
server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/duplication/Duplication.java
server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/step/PersistDuplicationDataStep.java
server/sonar-ce-task/src/main/java/org/sonar/ce/task/CeTaskInterruptedException.java
server/sonar-ce/src/main/java/org/sonar/ce/queue/InternalCeQueueImpl.java
server/sonar-main/src/main/java/org/sonar/application/ProcessLauncherImpl.java
server/sonar-process/src/main/java/org/sonar/process/PluginFileWriteRule.java
server/sonar-server-common/src/main/java/org/sonar/server/es/BaseDoc.java
server/sonar-server-common/src/main/java/org/sonar/server/es/IndexDefinitionHash.java
server/sonar-server-common/src/main/java/org/sonar/server/es/metadata/MetadataIndexImpl.java
server/sonar-server-common/src/main/java/org/sonar/server/issue/notification/FpOrWontFixEmailTemplate.java
server/sonar-server-common/src/main/java/org/sonar/server/issue/notification/IssuesChangesNotificationSerializer.java
server/sonar-webserver-auth/src/main/java/org/sonar/server/authentication/InitFilter.java
server/sonar-webserver-auth/src/main/java/org/sonar/server/authentication/OAuth2CallbackFilter.java
server/sonar-webserver-auth/src/main/java/org/sonar/server/authentication/UserSessionInitializer.java
server/sonar-webserver-core/src/main/java/org/sonar/server/platform/web/RootFilter.java
server/sonar-webserver-webapi/src/main/java/org/sonar/server/batch/ProjectAction.java
server/sonar-webserver-webapi/src/main/java/org/sonar/server/permission/PermissionUpdater.java
server/sonar-webserver-ws/src/main/java/org/sonar/server/ws/WebServiceEngine.java

index 472a1821cf8130e3c5626e623f37d1ce5afd347d..08b267d3478609990a0ae754724088270236d9d3 100644 (file)
@@ -41,13 +41,11 @@ public class CallbackHandlerImpl implements CallbackHandler {
   @Override
   public void handle(Callback[] callbacks) throws UnsupportedCallbackException, IOException {
     for (Callback callBack : callbacks) {
-      if (callBack instanceof NameCallback) {
+      if (callBack instanceof NameCallback nameCallback) {
         // Handles username callback
-        NameCallback nameCallback = (NameCallback) callBack;
         nameCallback.setName(name);
-      } else if (callBack instanceof PasswordCallback) {
+      } else if (callBack instanceof PasswordCallback passwordCallback) {
         // Handles password callback
-        PasswordCallback passwordCallback = (PasswordCallback) callBack;
         passwordCallback.setPassword(password.toCharArray());
       } else {
         throw new UnsupportedCallbackException(callBack, "Callback not supported");
index 0049d77c855f36a268c44836f24f233d0a192455..b3aeae90cef0197f82760141834c628bf923efe3 100644 (file)
@@ -149,10 +149,10 @@ public class VisitorsCrawler implements ComponentCrawler {
 
     @Override
     public VisitorWrapper apply(@Nonnull ComponentVisitor componentVisitor) {
-      if (componentVisitor instanceof TypeAwareVisitor) {
-        return new TypeAwareVisitorWrapper((TypeAwareVisitor) componentVisitor);
-      } else if (componentVisitor instanceof PathAwareVisitor) {
-        return new PathAwareVisitorWrapper((PathAwareVisitor) componentVisitor);
+      if (componentVisitor instanceof TypeAwareVisitor typeAwareVisitor) {
+        return new TypeAwareVisitorWrapper(typeAwareVisitor);
+      } else if (componentVisitor instanceof PathAwareVisitor pathAwareVisitor) {
+        return new PathAwareVisitorWrapper(pathAwareVisitor);
       } else {
         throw new IllegalArgumentException("Only TypeAwareVisitor and PathAwareVisitor can be used");
       }
index 1f106ca1bfc2adf6e9a598317a9c9246dd0476b9..18dda44d20e0c1ef14c8add2b2b7217ac1c9977b 100644 (file)
@@ -147,11 +147,11 @@ public final class Duplication {
       if (duplicate instanceof InnerDuplicate) {
         return "";
       }
-      if (duplicate instanceof InProjectDuplicate) {
-        return ((InProjectDuplicate) duplicate).getFile().getKey();
+      if (duplicate instanceof InProjectDuplicate inProjectDuplicate) {
+        return inProjectDuplicate.getFile().getKey();
       }
-      if (duplicate instanceof CrossProjectDuplicate) {
-        return ((CrossProjectDuplicate) duplicate).getFileKey();
+      if (duplicate instanceof CrossProjectDuplicate crossProjectDuplicate) {
+        return crossProjectDuplicate.getFileKey();
       }
       throw new IllegalArgumentException("Unsupported type of Duplicate " + duplicate.getClass().getName());
     }
index 90aa22d9ede0d514f17aece377528e9ae7f4b835..3561fd0d9b4b3ed7e91baad1cdf2574e514d3ef8 100644 (file)
@@ -159,15 +159,15 @@ public class PersistDuplicationDataStep implements ComputationStep {
       if (duplicate instanceof InnerDuplicate) {
         // Duplication is on the same file
         appendDuplication(xml, componentDbKey, duplicate);
-      } else if (duplicate instanceof InExtendedProjectDuplicate) {
+      } else if (duplicate instanceof InExtendedProjectDuplicate inExtendedProjectDuplicate) {
         // Duplication is on a different file that is not saved in the DB
-        appendDuplication(xml, ((InExtendedProjectDuplicate) duplicate).getFile().getKey(), duplicate.getTextBlock(), true);
-      } else if (duplicate instanceof InProjectDuplicate) {
+        appendDuplication(xml, inExtendedProjectDuplicate.getFile().getKey(), duplicate.getTextBlock(), true);
+      } else if (duplicate instanceof InProjectDuplicate inProjectDuplicate) {
         // Duplication is on a different file
-        appendDuplication(xml, ((InProjectDuplicate) duplicate).getFile().getKey(), duplicate);
-      } else if (duplicate instanceof CrossProjectDuplicate) {
+        appendDuplication(xml, inProjectDuplicate.getFile().getKey(), duplicate);
+      } else if (duplicate instanceof CrossProjectDuplicate crossProjectDuplicate) {
         // Only componentKey is set for cross project duplications
-        String crossProjectComponentKey = ((CrossProjectDuplicate) duplicate).getFileKey();
+        String crossProjectComponentKey = crossProjectDuplicate.getFileKey();
         appendDuplication(xml, crossProjectComponentKey, duplicate);
       } else {
         throw new IllegalArgumentException("Unsupported type of Duplicate " + duplicate.getClass().getName());
index 0c50abd1087d1ec2823ce579365ed428a09929d7..5ab9674b1e8b0550bda15539cc83dec06992edc2 100644 (file)
@@ -37,8 +37,8 @@ public abstract class CeTaskInterruptedException extends RuntimeException {
   }
 
   public static Optional<CeTaskInterruptedException> isTaskInterruptedException(Throwable e) {
-    if (e instanceof CeTaskInterruptedException) {
-      return Optional.of((CeTaskInterruptedException) e);
+    if (e instanceof CeTaskInterruptedException ceTaskInterruptedException) {
+      return Optional.of(ceTaskInterruptedException);
     }
     return isCauseInterruptedException(e);
   }
@@ -48,8 +48,8 @@ public abstract class CeTaskInterruptedException extends RuntimeException {
     if (cause == null || cause == e) {
       return Optional.empty();
     }
-    if (cause instanceof CeTaskInterruptedException) {
-      return Optional.of((CeTaskInterruptedException) cause);
+    if (cause instanceof CeTaskInterruptedException ceTaskInterruptedException) {
+      return Optional.of(ceTaskInterruptedException);
     }
     return isCauseInterruptedException(cause);
   }
index c235664cb2b9d40a4aeba938e26d0a2e9a92c4d2..69d319c7aa93b5ea6de5e3b5175b538450b102e0 100644 (file)
@@ -154,8 +154,8 @@ public class InternalCeQueueImpl extends CeQueueImpl implements InternalCeQueue
     if (stacktrace != null) {
       activityDto.setErrorStacktrace(stacktrace);
     }
-    if (error instanceof TypedException) {
-      activityDto.setErrorType(((TypedException) error).getType());
+    if (error instanceof TypedException typedException) {
+      activityDto.setErrorType(typedException.getType());
     }
   }
 
index 4b22911f5d7f13430ff6253a03c152c1d032bd4f..eb9d72d8ba98fe1e44522e0097496f4d9252c824 100644 (file)
@@ -93,8 +93,8 @@ public class ProcessLauncherImpl implements ProcessLauncher {
     }
 
     Process process;
-    if (command instanceof EsScriptCommand) {
-      process = launchExternal((EsScriptCommand) command);
+    if (command instanceof EsScriptCommand esScriptCommand) {
+      process = launchExternal(esScriptCommand);
     } else if (command instanceof JavaCommand) {
       process = launchJava((JavaCommand<?>) command);
     } else {
index 1008f196d3d0c794a3fecb0f9a8885bea1e7e70b..18b055bb1d7c7eca145b95dae61649dd0f31e476 100644 (file)
@@ -44,11 +44,8 @@ public class PluginFileWriteRule implements PluginPolicyRule {
 
   @Override
   public boolean implies(Permission permission) {
-    if (permission instanceof FilePermission) {
-      FilePermission requestPermission = (FilePermission) permission;
-      if (blockedFilePermission.implies(requestPermission) && !tmpFilePermission.implies(requestPermission)) {
-        return false;
-      }
+    if (permission instanceof FilePermission requestPermission) {
+      return !blockedFilePermission.implies(requestPermission) || tmpFilePermission.implies(requestPermission);
     }
     return true;
   }
index 847b9df15dbaa65e74ca66352c864984ad89e5e4..5130fd15655abd8d852ad6b8ec1e238bfe5c8312 100644 (file)
@@ -51,12 +51,9 @@ public abstract class BaseDoc {
   protected BaseDoc(IndexType indexType, Map<String, Object> fields) {
     this.indexType = indexType;
     this.fields = fields;
-    if (indexType instanceof IndexMainType) {
-      IndexMainType mainType = (IndexMainType) indexType;
-      if (mainType.getIndex().acceptsRelations()) {
-        setField(mainType.getIndex().getJoinField(), ImmutableMap.of("name", mainType.getType()));
-        setField(FIELD_INDEX_TYPE, mainType.getType());
-      }
+    if (indexType instanceof IndexMainType mainType && mainType.getIndex().acceptsRelations()) {
+      setField(mainType.getIndex().getJoinField(), ImmutableMap.of("name", mainType.getType()));
+      setField(FIELD_INDEX_TYPE, mainType.getType());
     }
   }
 
@@ -106,11 +103,11 @@ public abstract class BaseDoc {
   public Date getNullableFieldAsDate(String key) {
     Object val = getNullableField(key);
     if (val != null) {
-      if (val instanceof Date) {
-        return (Date) val;
+      if (val instanceof Date date) {
+        return date;
       }
-      if (val instanceof Number) {
-        return epochSecondsToDate((Number) val);
+      if (val instanceof Number number) {
+        return epochSecondsToDate(number);
       }
       return EsUtils.parseDateTime((String) val);
     }
@@ -136,11 +133,11 @@ public abstract class BaseDoc {
 
   public Date getFieldAsDate(String key) {
     Object value = getField(key);
-    if (value instanceof Date) {
-      return (Date) value;
+    if (value instanceof Date date) {
+      return date;
     }
-    if (value instanceof Number) {
-      return epochSecondsToDate((Number) value);
+    if (value instanceof Number number) {
+      return epochSecondsToDate(number);
     }
     return EsUtils.parseDateTime((String) value);
   }
index fa073389e6600f2d509b98c0bcf22276280cb858..b2d4f83f7618acbc5e7494f9596c22cb06cbbc6e 100644 (file)
@@ -67,12 +67,12 @@ class IndexDefinitionHash {
   }
 
   private static void appendObject(StringBuilder sb, Object value) {
-    if (value instanceof Object[]) {
-      sb.append(Arrays.toString((Object[]) value));
-    } else if (value instanceof Map) {
-      appendMap(sb, (Map) value);
-    } else if (value instanceof IndexType) {
-      sb.append(((IndexType) value).format());
+    if (value instanceof Object[] arrayValue) {
+      sb.append(Arrays.toString(arrayValue));
+    } else if (value instanceof Map map) {
+      appendMap(sb, map);
+    } else if (value instanceof IndexType indexType) {
+      sb.append(indexType.format());
     } else {
       sb.append(value);
     }
index 80e91f7e16e05822075838ec2f96cd5136cb9280..c4377b7ebbfd86d076ca2ee695b373358faa7d0d 100644 (file)
@@ -68,12 +68,10 @@ public class MetadataIndexImpl implements MetadataIndex {
   }
 
   private static String initializedId(IndexType indexType) {
-    if (indexType instanceof IndexMainType) {
-      IndexMainType mainType = (IndexMainType) indexType;
+    if (indexType instanceof IndexMainType mainType) {
       return mainType.getIndex().getName() + "." + mainType.getType() + ".initialized";
     }
-    if (indexType instanceof IndexRelationType) {
-      IndexRelationType relationType = (IndexRelationType) indexType;
+    if (indexType instanceof IndexRelationType relationType) {
       IndexMainType mainType = relationType.getMainType();
       return mainType.getIndex().getName() + "." + mainType.getType() + "." + relationType.getName() + ".initialized";
     }
index 488d7efdbce902f868023cefd14db2a3b2671eed..5afe9794b00582b4fe10d757c245c5371c542e80 100644 (file)
@@ -54,8 +54,8 @@ public class FpOrWontFixEmailTemplate extends IssueChangesEmailTemplate {
       .setMessageId(getMessageId(notification.getResolution()))
       .setSubject(buildSubject(notification))
       .setHtmlMessage(buildMessage(notification));
-    if (notification.getChange() instanceof UserChange) {
-      User user = ((UserChange) notification.getChange()).getUser();
+    if (notification.getChange() instanceof UserChange userChange) {
+      User user = userChange.getUser();
       emailMessage.setFrom(user.getName().orElse(user.getLogin()));
     }
     return emailMessage;
index 68fdc0bc6d747cc6bb0f0c80ba4b5e70d4676207..d7c9b93e06980cec47383456b42b25f5b6d4655d 100644 (file)
@@ -222,8 +222,7 @@ public class IssuesChangesNotificationSerializer {
 
   private static void serializeChange(IssuesChangesNotification notification, IssuesChangesNotificationBuilder.Change change) {
     notification.setFieldValue(FIELD_CHANGE_DATE, String.valueOf(change.date));
-    if (change instanceof IssuesChangesNotificationBuilder.UserChange) {
-      IssuesChangesNotificationBuilder.UserChange userChange = (IssuesChangesNotificationBuilder.UserChange) change;
+    if (change instanceof IssuesChangesNotificationBuilder.UserChange userChange) {
       User user = userChange.getUser();
       notification.setFieldValue(FIELD_CHANGE_AUTHOR_UUID, user.getUuid());
       notification.setFieldValue(FIELD_CHANGE_AUTHOR_LOGIN, user.getLogin());
index faa28b4783d24775eb6df66e6f00180856bf00f6..fe35388cc5bbf2171a67c2a57485b20343cac76f 100644 (file)
@@ -73,11 +73,11 @@ public class InitFilter extends AuthenticationFilter {
 
   private void handleProvider(HttpServletRequest request, HttpServletResponse response, IdentityProvider provider) {
     try {
-      if (provider instanceof BaseIdentityProvider) {
-        handleBaseIdentityProvider(request, response, (BaseIdentityProvider) provider);
-      } else if (provider instanceof OAuth2IdentityProvider) {
+      if (provider instanceof BaseIdentityProvider baseIdentityProvider) {
+        handleBaseIdentityProvider(request, response, baseIdentityProvider);
+      } else if (provider instanceof OAuth2IdentityProvider oAuth2IdentityProvider) {
         oAuthOAuth2AuthenticationParameters.init(request, response);
-        handleOAuth2IdentityProvider(request, response, (OAuth2IdentityProvider) provider);
+        handleOAuth2IdentityProvider(request, response, oAuth2IdentityProvider);
       } else {
         handleError(request, response, format("Unsupported IdentityProvider class: %s", provider.getClass()));
       }
index 389436e56368376fb03e81c166bf3d5e50bdb867..c3b5a664073bb29de83327beb5790938e73b157a 100644 (file)
@@ -71,8 +71,8 @@ public class OAuth2CallbackFilter extends AuthenticationFilter {
 
   private void handleProvider(HttpServletRequest request, HttpServletResponse response, IdentityProvider provider) {
     try {
-      if (provider instanceof OAuth2IdentityProvider) {
-        handleOAuth2Provider(response, request, (OAuth2IdentityProvider) provider);
+      if (provider instanceof OAuth2IdentityProvider oAuth2IdentityProvider) {
+        handleOAuth2Provider(response, request, oAuth2IdentityProvider);
       } else {
         handleError(request, response, format("Not an OAuth2IdentityProvider: %s", provider.getClass()));
       }
index 66376c7717048d343a895eaf734a577b471808b9..fa6be146e7e508c10a5df641d0cae38783296c37 100644 (file)
@@ -141,8 +141,8 @@ public class UserSessionInitializer {
   }
 
   private static void checkTokenUserSession(HttpServletResponse response, UserSession session) {
-    if (session instanceof TokenUserSession) {
-      UserTokenDto userTokenDto = ((TokenUserSession) session).getUserToken();
+    if (session instanceof TokenUserSession tokenUserSession) {
+      UserTokenDto userTokenDto = tokenUserSession.getUserToken();
       Optional.ofNullable(userTokenDto.getExpirationDate()).ifPresent(expirationDate -> response.addHeader(SQ_AUTHENTICATION_TOKEN_EXPIRATION, formatDateTime(expirationDate)));
     }
   }
index dfe496820458f0fdeb56cb6881aac7771fde4a6d..4803903e9f980c3850e87444eea423273363f1ab 100644 (file)
@@ -58,8 +58,7 @@ public class RootFilter implements Filter {
 
   @Override
   public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
-    if (request instanceof HttpServletRequest) {
-      HttpServletRequest httpRequest = (HttpServletRequest) request;
+    if (request instanceof HttpServletRequest httpRequest) {
       HttpServletResponse httpResponse = (HttpServletResponse) response;
       try {
         chain.doFilter(new ServletRequestWrapper(httpRequest), httpResponse);
index 28edcefa65616852dc6af902f4d5365c5c79044e..bb125f8b175f22c154491319204ec5f0976d2b14 100644 (file)
@@ -103,8 +103,8 @@ public class ProjectAction implements BatchWsAction {
 
   private static WsProjectResponse buildResponse(ProjectRepositories data) {
     WsProjectResponse.Builder response = WsProjectResponse.newBuilder();
-    if (data instanceof SingleProjectRepository) {
-      response.putAllFileDataByPath(buildFileDataByPath((SingleProjectRepository) data));
+    if (data instanceof SingleProjectRepository singleProjectRepository) {
+      response.putAllFileDataByPath(buildFileDataByPath(singleProjectRepository));
     } else {
       response.putAllFileDataByModuleAndPath(buildFileDataByModuleAndPath((MultiModuleProjectRepository) data));
     }
index d6ab624c000b2166fff7c05bfe0630e1abe0eb30..f3bdf455d6bbce5e8897a09ad23bcda52ee1fa44 100644 (file)
@@ -55,11 +55,11 @@ public class PermissionUpdater {
   }
 
   private boolean doApply(DbSession dbSession, PermissionChange change) {
-    if (change instanceof UserPermissionChange) {
-      return userPermissionChanger.apply(dbSession, (UserPermissionChange) change);
+    if (change instanceof UserPermissionChange userPermissionChange) {
+      return userPermissionChanger.apply(dbSession, userPermissionChange);
     }
-    if (change instanceof GroupPermissionChange) {
-      return groupPermissionChanger.apply(dbSession, (GroupPermissionChange) change);
+    if (change instanceof GroupPermissionChange groupPermissionChange) {
+      return groupPermissionChanger.apply(dbSession, groupPermissionChange);
     }
     throw new UnsupportedOperationException("Unsupported permission change: " + change.getClass());
 
index 4c9d380cd2f6984e84fc4b5d63cb95d8b0da4587..da04ef94fdd900c3308fdd5d0d9f01e7b41f0435 100644 (file)
@@ -102,9 +102,9 @@ public class WebServiceEngine implements LocalConnector, Startable {
       ActionExtractor actionExtractor = new ActionExtractor(request.getPath());
       WebService.Action action = getAction(actionExtractor);
       checkFound(action, "Unknown url : %s", request.getPath());
-      if (request instanceof ValidatingRequest) {
-        ((ValidatingRequest) request).setAction(action);
-        ((ValidatingRequest) request).setLocalConnector(this);
+      if (request instanceof ValidatingRequest validatingRequest) {
+        validatingRequest.setAction(action);
+        validatingRequest.setLocalConnector(this);
       }
       checkActionExtension(actionExtractor.getExtension());
       verifyRequest(action, request);
@@ -160,8 +160,8 @@ public class WebServiceEngine implements LocalConnector, Startable {
     }
 
     // response is not committed, status and content can be changed to return the error
-    if (stream instanceof ServletResponse.ServletStream) {
-      ((ServletResponse.ServletStream) stream).reset();
+    if (stream instanceof ServletResponse.ServletStream servletStream) {
+      servletStream.reset();
     }
     stream.setStatus(status);
     stream.setMediaType(MediaTypes.JSON);
@@ -189,7 +189,7 @@ public class WebServiceEngine implements LocalConnector, Startable {
   private static boolean isResponseCommitted(Response response) {
     Response.Stream stream = response.stream();
     // Request has been aborted by the client or the response was partially streamed, nothing can been done as Tomcat has committed the response
-    return stream instanceof ServletResponse.ServletStream && ((ServletResponse.ServletStream) stream).response().isCommitted();
+    return stream instanceof ServletResponse.ServletStream servletStream && servletStream.response().isCommitted();
   }
 
   public static void writeErrors(JsonWriter json, List<String> errorMessages) {