diff --git a/announcements/src/org/labkey/announcements/NotificationSettingsImporterFactory.java b/announcements/src/org/labkey/announcements/NotificationSettingsImporterFactory.java index e3992d80d17..9c2e23f6998 100644 --- a/announcements/src/org/labkey/announcements/NotificationSettingsImporterFactory.java +++ b/announcements/src/org/labkey/announcements/NotificationSettingsImporterFactory.java @@ -61,7 +61,7 @@ public void process(PipelineJob job, FolderImportContext ctx, VirtualFile root) { if (null != job) job.setStatus("IMPORT " + getDescription()); - ctx.getLogger().info("Loading " + getDescription()); + ctx.getLogger().info("Loading {}", getDescription()); NotificationsType notifications = ctx.getXml().getNotifications(); if (notifications.isSetMessagesDefault()) { @@ -70,7 +70,7 @@ public void process(PipelineJob job, FolderImportContext ctx, VirtualFile root) if (messagesOption != null) AnnouncementManager.saveDefaultEmailOption(ctx.getContainer(), messagesDefault); else - ctx.getLogger().error("Unable to find default messages email option for id " + messagesDefault); + ctx.getLogger().error("Unable to find default messages email option for id {}", messagesDefault); } if (notifications.isSetFilesDefault()) { @@ -79,10 +79,10 @@ public void process(PipelineJob job, FolderImportContext ctx, VirtualFile root) if (filesOption != null) EmailService.get().setDefaultEmailPref(ctx.getContainer(), new FileContentDefaultEmailPref(), String.valueOf(filesDefault)); else - ctx.getLogger().error("Unable to find default files email option for id " + filesDefault); + ctx.getLogger().error("Unable to find default files email option for id {}", filesDefault); } - ctx.getLogger().info("Done importing " + getDescription()); + ctx.getLogger().info("Done importing {}", getDescription()); } } diff --git a/announcements/src/org/labkey/announcements/RSSServiceImpl.java b/announcements/src/org/labkey/announcements/RSSServiceImpl.java index df2cdc3f09d..7d68a4a4e99 100644 --- a/announcements/src/org/labkey/announcements/RSSServiceImpl.java +++ b/announcements/src/org/labkey/announcements/RSSServiceImpl.java @@ -88,7 +88,7 @@ public void aggregateFeeds(List feeds, User user, Writer writer) } catch (IOException e) { - LogManager.getLogger(RSSService.class).error("Invalid RSS Feed: " + e.getMessage()); + LogManager.getLogger(RSSService.class).error("Invalid RSS Feed: {}", e.getMessage()); } if (null != reader) @@ -102,7 +102,7 @@ public void aggregateFeeds(List feeds, User user, Writer writer) } catch (FeedException fe) { - LogManager.getLogger(RSSService.class).error("Invalid Feed (FeedException): " + _feed.getFeedURL()); + LogManager.getLogger(RSSService.class).error("Invalid Feed (FeedException): {}", _feed.getFeedURL()); } } } diff --git a/announcements/src/org/labkey/announcements/SendMessageAction.java b/announcements/src/org/labkey/announcements/SendMessageAction.java index ca535ae08a7..14f8b6f1fe6 100644 --- a/announcements/src/org/labkey/announcements/SendMessageAction.java +++ b/announcements/src/org/labkey/announcements/SendMessageAction.java @@ -16,7 +16,6 @@ package org.labkey.announcements; -import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.Strings; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; @@ -141,7 +140,7 @@ private Address getEmailTo(String email) throws IllegalArgumentException // filter out disabled users or users who have never logged in : Issue #33255 if (!user.isActive() || user.isFirstLogin()) { - _log.warn("The user: " + user.getName() + " is either disabled or has never logged in and has been omitted."); + _log.warn("The user: {} is either disabled or has never logged in and has been omitted.", user.getName()); return null; } diff --git a/announcements/src/org/labkey/announcements/model/AnnouncementManager.java b/announcements/src/org/labkey/announcements/model/AnnouncementManager.java index 1d5e146c090..06136316a62 100644 --- a/announcements/src/org/labkey/announcements/model/AnnouncementManager.java +++ b/announcements/src/org/labkey/announcements/model/AnnouncementManager.java @@ -383,7 +383,7 @@ private static void notifyModerators(Container c, User user, AnnouncementModel a if (toList.isEmpty()) { - LOG.warn("New " + name.toLowerCase() + " requires moderator review, but no moderators are subscribed to receive 'Individual' notifications in this folder: " + c.getPath()); + LOG.warn("New {} requires moderator review, but no moderators are subscribed to receive 'Individual' notifications in this folder: {}", name.toLowerCase(), c.getPath()); } else { diff --git a/announcements/src/org/labkey/announcements/query/ForumSubscriptionTable.java b/announcements/src/org/labkey/announcements/query/ForumSubscriptionTable.java index 7fbe6ea5088..1db7cfb3887 100644 --- a/announcements/src/org/labkey/announcements/query/ForumSubscriptionTable.java +++ b/announcements/src/org/labkey/announcements/query/ForumSubscriptionTable.java @@ -40,7 +40,6 @@ import org.labkey.api.security.UserManager; import org.labkey.api.security.UserPrincipal; import org.labkey.api.security.permissions.Permission; -import org.labkey.api.security.permissions.ReadPermission; import java.util.HashMap; import java.util.Map; @@ -92,22 +91,6 @@ public boolean hasPermission(@NotNull UserPrincipal user, @NotNull Class perm, Container container) - { - // Guests can't subscribe to anything, or edit anyone else's subscriptions, but they can read the table - // It'll have no rows for them - if (user.isGuest() && !ReadPermission.class.equals(perm)) - { - return false; - } - - // For authenticated users, if they have read access, that's enough to edit their own subscription level - // The QueryUpdateService implementation will make sure they have permission to insert/update/delete at the row - // level. - return container.hasPermission(user, ReadPermission.class); - } - @Override public QueryUpdateService getUpdateService() { diff --git a/api/src/jakarta/servlet/jsp/JspWriter.java b/api/src/jakarta/servlet/jsp/JspWriter.java index 857ec34db3c..d7336b5dcbc 100644 --- a/api/src/jakarta/servlet/jsp/JspWriter.java +++ b/api/src/jakarta/servlet/jsp/JspWriter.java @@ -187,7 +187,7 @@ protected JspWriter(int bufferSize, boolean autoFlush) { * @throws NullPointerException If s is null * @throws IOException If an error occurred while writing */ - public abstract void print(char s[]) throws IOException; + public abstract void print(char[] s) throws IOException; /** * Print a string. If the argument is null then the string "null" is printed. Otherwise, @@ -293,7 +293,7 @@ protected JspWriter(int bufferSize, boolean autoFlush) { * * @throws IOException If an error occurred while writing */ - public abstract void println(char x[]) throws IOException; + public abstract void println(char[] x) throws IOException; /** * Print a String and then terminate the line. This method behaves as though it invokes diff --git a/api/src/org/labkey/api/action/ApiQueryResponse.java b/api/src/org/labkey/api/action/ApiQueryResponse.java index b8d927756c2..42828afe0cc 100644 --- a/api/src/org/labkey/api/action/ApiQueryResponse.java +++ b/api/src/org/labkey/api/action/ApiQueryResponse.java @@ -409,7 +409,7 @@ protected Map getMetaData() //include an id property set to the pk column name if there is one (and only one) List pkCols = _tinfo.getPkColumns(); if (1 == pkCols.size()) - metaData.put("id", pkCols.get(0).getName()); + metaData.put("id", pkCols.getFirst().getName()); metaData.put("fields", fields); diff --git a/api/src/org/labkey/api/action/BaseApiAction.java b/api/src/org/labkey/api/action/BaseApiAction.java index 4f9c9364e18..e7253c3eacf 100644 --- a/api/src/org/labkey/api/action/BaseApiAction.java +++ b/api/src/org/labkey/api/action/BaseApiAction.java @@ -19,12 +19,12 @@ import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.ObjectReader; -import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import org.json.JSONTokener; +import org.jetbrains.annotations.NotNull; import org.labkey.api.miniprofiler.MiniProfiler; import org.labkey.api.miniprofiler.Timing; import org.labkey.api.query.BatchValidationException; @@ -583,7 +583,7 @@ else if (value instanceof JSONObject) } @Override - public final void validate(Object form, Errors errors) + public final void validate(@NotNull Object form, @NotNull Errors errors) { try (Timing ignored = MiniProfiler.step("validate")) { diff --git a/api/src/org/labkey/api/action/BaseViewAction.java b/api/src/org/labkey/api/action/BaseViewAction.java index 2a7f515b772..d2fbf165b45 100644 --- a/api/src/org/labkey/api/action/BaseViewAction.java +++ b/api/src/org/labkey/api/action/BaseViewAction.java @@ -509,7 +509,7 @@ else if (!value.getClass().isArray()) } @Override - public boolean supports(Class clazz) + public boolean supports(@NotNull Class clazz) { return getCommandClass().isAssignableFrom(clazz); } @@ -559,7 +559,7 @@ public BeanUtilsPropertyBindingResult(Object target, String objectName) } @Override - protected BeanWrapper createBeanWrapper() + protected @NotNull BeanWrapper createBeanWrapper() { return new BeanUtilsWrapperImpl((DynaBean)getTarget()); } @@ -583,7 +583,7 @@ public BeanUtilsWrapperImpl(DynaBean target) } @Override - public Object getPropertyValue(String propertyName) throws BeansException + public Object getPropertyValue(@NotNull String propertyName) throws BeansException { try { @@ -596,7 +596,7 @@ public Object getPropertyValue(String propertyName) throws BeansException } @Override - public void setPropertyValue(String propertyName, Object value) throws BeansException + public void setPropertyValue(@NotNull String propertyName, Object value) throws BeansException { try { @@ -609,19 +609,19 @@ public void setPropertyValue(String propertyName, Object value) throws BeansExce } @Override - public boolean isReadableProperty(String propertyName) + public boolean isReadableProperty(@NotNull String propertyName) { return true; } @Override - public boolean isWritableProperty(String propertyName) + public boolean isWritableProperty(@NotNull String propertyName) { return true; } @Override - public TypeDescriptor getPropertyTypeDescriptor(String s) throws BeansException + public TypeDescriptor getPropertyTypeDescriptor(@NotNull String s) throws BeansException { return null; } @@ -632,25 +632,25 @@ public void setWrappedInstance(Object obj) } @Override - public Object getWrappedInstance() + public @NotNull Object getWrappedInstance() { return object; } @Override - public Class getWrappedClass() + public @NotNull Class getWrappedClass() { return object.getClass(); } @Override - public PropertyDescriptor[] getPropertyDescriptors() + public PropertyDescriptor @NotNull [] getPropertyDescriptors() { throw new UnsupportedOperationException(); } @Override - public PropertyDescriptor getPropertyDescriptor(String propertyName) throws BeansException + public @NotNull PropertyDescriptor getPropertyDescriptor(@NotNull String propertyName) throws BeansException { throw new UnsupportedOperationException(); } diff --git a/api/src/org/labkey/api/action/ConfirmAction.java b/api/src/org/labkey/api/action/ConfirmAction.java index afc2c83d738..46c34162248 100644 --- a/api/src/org/labkey/api/action/ConfirmAction.java +++ b/api/src/org/labkey/api/action/ConfirmAction.java @@ -129,7 +129,7 @@ public BindException bindParameters(PropertyValues m) throws Exception public abstract boolean handlePost(FORM form, BindException errors) throws Exception; @Override - public void validate(Object form, Errors errors) + public void validate(@NotNull Object form, @NotNull Errors errors) { validateCommand((FORM)form, errors); } diff --git a/api/src/org/labkey/api/action/NullSafeBindException.java b/api/src/org/labkey/api/action/NullSafeBindException.java index e1451882234..bcc164f2939 100644 --- a/api/src/org/labkey/api/action/NullSafeBindException.java +++ b/api/src/org/labkey/api/action/NullSafeBindException.java @@ -18,6 +18,7 @@ import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; +import org.jetbrains.annotations.NotNull; import org.labkey.api.util.ExceptionUtil; import org.springframework.validation.BindingResult; import org.springframework.validation.Errors; @@ -49,7 +50,7 @@ public NullSafeBindException(@JsonProperty("target") Object target, @JsonPropert } @Override - public void reject(String errorCode) + public void reject(@NotNull String errorCode) { if (errorCode == null) { @@ -60,7 +61,7 @@ public void reject(String errorCode) } @Override - public void reject(String errorCode, String defaultMessage) + public void reject(@NotNull String errorCode, @NotNull String defaultMessage) { if (errorCode == null && defaultMessage == null) { @@ -71,7 +72,7 @@ public void reject(String errorCode, String defaultMessage) } @Override - public void reject(String errorCode, Object[] errorArgs, String defaultMessage) + public void reject(@NotNull String errorCode, Object[] errorArgs, String defaultMessage) { if (errorCode == null && defaultMessage == null) { @@ -82,7 +83,7 @@ public void reject(String errorCode, Object[] errorArgs, String defaultMessage) } @Override - public void rejectValue(String field, String errorCode) + public void rejectValue(String field, @NotNull String errorCode) { if (field == null || errorCode == null) { @@ -93,7 +94,7 @@ public void rejectValue(String field, String errorCode) } @Override - public void rejectValue(String field, String errorCode, String defaultMessage) + public void rejectValue(String field, @NotNull String errorCode, @NotNull String defaultMessage) { if (field == null || (errorCode == null && defaultMessage == null)) { @@ -105,7 +106,7 @@ public void rejectValue(String field, String errorCode, String defaultMessage) } @Override - public void rejectValue(String field, String errorCode, Object[] errorArgs, String defaultMessage) + public void rejectValue(String field, @NotNull String errorCode, Object[] errorArgs, String defaultMessage) { if (field == null || (errorCode == null && defaultMessage == null)) { @@ -117,14 +118,14 @@ public void rejectValue(String field, String errorCode, Object[] errorArgs, Stri } @Override - public void addError(ObjectError error) + public void addError(@NotNull ObjectError error) { checkError(error); super.addError(error); } @Override - public void addAllErrors(Errors errors) + public void addAllErrors(@NotNull Errors errors) { checkErrors(errors); super.addAllErrors(errors); diff --git a/api/src/org/labkey/api/action/PermissionCheckableAction.java b/api/src/org/labkey/api/action/PermissionCheckableAction.java index 984aa69a8a4..ad538934317 100644 --- a/api/src/org/labkey/api/action/PermissionCheckableAction.java +++ b/api/src/org/labkey/api/action/PermissionCheckableAction.java @@ -152,7 +152,7 @@ private void _checkActionPermissions(Set contextualRoles) throws Unauthori User user = context.getUser(); Class actionClass = getClass(); if (LOG.isDebugEnabled()) - LOG.debug(actionClass.getName() + ": checking permissions for user " + (user == null ? "" : user.getName() + " (impersonated=" + user.isImpersonated() + ")")); + LOG.debug("{}: checking permissions for user {}", actionClass.getName(), user == null ? "" : user.getName() + " (impersonated=" + user.isImpersonated() + ")"); if (!actionClass.isAnnotationPresent(IgnoresForbiddenProjectCheck.class)) c.throwIfForbiddenProject(user); @@ -172,14 +172,14 @@ private void _checkActionPermissions(Set contextualRoles) throws Unauthori boolean requiresSiteAdmin = actionClass.isAnnotationPresent(RequiresSiteAdmin.class); if (requiresSiteAdmin && !user.hasSiteAdminPermission()) { - LOG.debug(actionClass.getName() + ": action requires site admin permissions"); + LOG.debug("{}: action requires site admin permissions", actionClass.getName()); throw new UnauthorizedException(); } boolean requiresLogin = actionClass.isAnnotationPresent(RequiresLogin.class); if (requiresLogin && user.isGuest()) { - LOG.debug(actionClass.getName() + ": action requires login (non-guest)"); + LOG.debug("{}: action requires login (non-guest)", actionClass.getName()); throw new UnauthorizedException(); } @@ -224,7 +224,7 @@ private void _checkActionPermissions(Set contextualRoles) throws Unauthori if (!SecurityManager.hasAllPermissions(this.getClass().getName()+"_checkActionPermissions", c, user, permissionsRequired, contextualRoles)) { - LOG.debug(actionClass.getName() + ": action requires all permissions: " + permissionsRequired); + LOG.debug("{}: action requires all permissions: {}", actionClass.getName(), permissionsRequired); throw new UnauthorizedException(); } @@ -241,7 +241,7 @@ private void _checkActionPermissions(Set contextualRoles) throws Unauthori if (!SecurityManager.hasAnyPermissions(this.getClass().getName() + "_checkActionPermissions", c, user, permissionsAnyOf, contextualRoles)) { - LOG.debug(actionClass.getName() + ": action requires any permissions: " + permissionsAnyOf); + LOG.debug("{}: action requires any permissions: {}", actionClass.getName(), permissionsAnyOf); throw new UnauthorizedException(); } } diff --git a/api/src/org/labkey/api/action/SpringActionController.java b/api/src/org/labkey/api/action/SpringActionController.java index 5886b50cae3..ccf94d11cd7 100644 --- a/api/src/org/labkey/api/action/SpringActionController.java +++ b/api/src/org/labkey/api/action/SpringActionController.java @@ -23,9 +23,9 @@ import org.apache.commons.lang3.StringUtils; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; -import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.json.JSONObject; +import org.jetbrains.annotations.NotNull; import org.labkey.api.action.ApiResponseWriter.Format; import org.labkey.api.admin.AdminUrls; import org.labkey.api.collections.CaseInsensitiveHashMap; @@ -95,7 +95,6 @@ import java.util.List; import java.util.Locale; import java.util.Map; -import java.util.Objects; import java.util.Set; import java.util.concurrent.CopyOnWriteArraySet; @@ -225,7 +224,7 @@ public SpringActionController() } @Override - public void setApplicationContext(ApplicationContext applicationContext) throws BeansException + public void setApplicationContext(@NotNull ApplicationContext applicationContext) throws BeansException { _applicationContext = applicationContext; } @@ -629,7 +628,7 @@ public static ActionURL getUpgradeMaintenanceRedirect(HttpServletRequest request boolean actionIsAllowed = (null != action && action.getClass().isAnnotationPresent(AllowedDuringUpgrade.class)); if (null != action) - _log.debug("Action " + action.getClass() + " allowed: " + actionIsAllowed); + _log.debug("Action {} allowed: {}", action.getClass(), actionIsAllowed); if (!actionIsAllowed) { @@ -720,7 +719,7 @@ protected void sendPlainText(String message) throws IOException List children = root.getChildren(); page.setNavTrail(children); if (null == page.getTitle()) - page.setTitle(children.get(children.size() - 1).getText()); + page.setTitle(children.getLast().getText()); } return page.getTemplate().getTemplate(context, mv, page); @@ -1084,7 +1083,7 @@ private DefaultActionDescriptor(Class actionClass) throws ActionNames actionNames = actionClass.getAnnotation(ActionNames.class); _allNames = (null != actionNames ? initializeNames(actionNames.value().split(",")) : initializeNames(getDefaultActionName())); - _primaryName = _allNames.get(0); + _primaryName = _allNames.getFirst(); Constructor con = null; @@ -1136,7 +1135,7 @@ public Controller createController(Controller actionController) } catch (IllegalAccessException | InstantiationException | InvocationTargetException e) { - _log.error("Unexpected error attempting to instantiate " + getActionClass(), e); + _log.error("Unexpected error attempting to instantiate {}", getActionClass(), e); throw new RuntimeException(e); } } @@ -1241,8 +1240,8 @@ public static void clearActionForThread(Class c) { ArrayList> list = currentAction.get(); assert !list.isEmpty(); - assert list.get(list.size()-1) == c; - list.remove(list.size() - 1); + assert list.getLast() == c; + list.removeLast(); } } @@ -1261,7 +1260,7 @@ public static Class getActionForThread() { ArrayList> list = currentAction.get(); if (!list.isEmpty()) - return list.get(list.size()-1); + return list.getLast(); } return null; } @@ -1290,7 +1289,7 @@ else if (SimpleRedirectAction.class.isAssignableFrom(c) || SimpleViewAction.clas else if (null != vc && "GET".equals(vc.getRequest().getMethod())) { readonly = true; - _log.warn("Action " + c.getName() + " accepted GET unexpectedly... might need to update executingMutatingSql()"); + _log.warn("Action {} accepted GET unexpectedly... might need to update executingMutatingSql()", c.getName()); } if (readonly) diff --git a/api/src/org/labkey/api/admin/AbstractImportExportContext.java b/api/src/org/labkey/api/admin/AbstractImportExportContext.java index 8a0c31cbaa3..5d9a386c129 100644 --- a/api/src/org/labkey/api/admin/AbstractImportExportContext.java +++ b/api/src/org/labkey/api/admin/AbstractImportExportContext.java @@ -60,7 +60,7 @@ public abstract class AbstractImportExportContext dataTypes, @JsonProperty("_user") User user, - @JsonProperty("_c") Container c, @JsonProperty("_root") VirtualFile root, + @JsonProperty("_c") Container c, @JsonProperty("_root") @Nullable VirtualFile root, @JsonProperty("_contextMap") Map>, ImportExportContext> contextMap) { _dataTypes = dataTypes; diff --git a/api/src/org/labkey/api/admin/FolderWriterImpl.java b/api/src/org/labkey/api/admin/FolderWriterImpl.java index 0cc061e1c4b..5f56db75a29 100644 --- a/api/src/org/labkey/api/admin/FolderWriterImpl.java +++ b/api/src/org/labkey/api/admin/FolderWriterImpl.java @@ -49,12 +49,6 @@ public FolderWriterImpl() _writers = registry.getRegisteredFolderWriters(); } - @Override - public String getDataType() - { - return null; - } - protected BaseFolderWriter createSubfolderWriter() { return new SubfolderWriter(); @@ -63,7 +57,7 @@ protected BaseFolderWriter createSubfolderWriter() @Override public void write(Container c, FolderExportContext ctx, VirtualFile vf) throws Exception { - LOG.info("Exporting folder to " + vf.getLocation()); + LOG.info("Exporting folder to {}", vf.getLocation()); Set dataTypes = ctx.getDataTypes(); @@ -92,7 +86,7 @@ public void write(Container c, FolderExportContext ctx, VirtualFile vf) throws E if (ctx.isIncludeFolderXml()) writeFolderXml(c, ctx, vf); - LOG.info("Done exporting folder to " + vf.getLocation()); + LOG.info("Done exporting folder to {}", vf.getLocation()); } // This writer is responsible for folder.xml. It writes the top-level folder attributes and saves out the bean when it's complete. diff --git a/api/src/org/labkey/api/admin/ImportOptions.java b/api/src/org/labkey/api/admin/ImportOptions.java index 61e7b23c2ae..bc82a45b074 100644 --- a/api/src/org/labkey/api/admin/ImportOptions.java +++ b/api/src/org/labkey/api/admin/ImportOptions.java @@ -21,7 +21,6 @@ import org.labkey.api.security.UserManager; import org.labkey.vfs.FileLike; -import java.nio.file.Path; import java.util.Collection; import java.util.LinkedList; import java.util.Set; diff --git a/api/src/org/labkey/api/admin/SubfolderWriter.java b/api/src/org/labkey/api/admin/SubfolderWriter.java index 35eed53c3cc..d4ad839e06d 100644 --- a/api/src/org/labkey/api/admin/SubfolderWriter.java +++ b/api/src/org/labkey/api/admin/SubfolderWriter.java @@ -118,7 +118,7 @@ public void testGetChildrenToExport() List noSubfolders = new ArrayList<>(); writer.getChildrenToExport(fec, childList, noSubfolders); assertEquals("Expected one container tab subfolder", 1, noSubfolders.size()); - assertEquals("containertab", noSubfolders.get(0).getName()); + assertEquals("containertab", noSubfolders.getFirst().getName()); } } } diff --git a/api/src/org/labkey/api/assay/AbstractAssayTsvDataHandler.java b/api/src/org/labkey/api/assay/AbstractAssayTsvDataHandler.java index 20b4050fe83..8b0c0cfcbf7 100644 --- a/api/src/org/labkey/api/assay/AbstractAssayTsvDataHandler.java +++ b/api/src/org/labkey/api/assay/AbstractAssayTsvDataHandler.java @@ -429,7 +429,7 @@ public void beforeDeleteData(List data, User user) throws ExperimentExc ProvenanceService.get().deleteProvenanceByLsids(run.getContainer(), user, new SQLFragment(" IN (").append(assayResultLsidSql).append(")"), true, Set.of(StudyPublishService.STUDY_PUBLISH_PROTOCOL_LSID)); int count = OntologyManager.deleteOntologyObjects(ExperimentService.get().getSchema(), assayResultLsidSql, run.getContainer()); - LOG.debug("AbstractAssayTsvDataHandler.beforeDeleteData: deleted " + count + " ontology objects for assay result lsids"); + LOG.debug("AbstractAssayTsvDataHandler.beforeDeleteData: deleted {} ontology objects for assay result lsids", count); } if (domain != null && domain.getStorageTableName() != null) @@ -441,7 +441,7 @@ public void beforeDeleteData(List data, User user) throws ExperimentExc try { int count = new SqlExecutor(DbSchema.get(domain.getDomainKind().getStorageSchemaName(), DbSchemaType.Provisioned)).execute(deleteSQL); - LOG.debug("AbstractAssayTsvDataHandler.beforeDeleteData: deleted " + count + " assay result rows"); + LOG.debug("AbstractAssayTsvDataHandler.beforeDeleteData: deleted {} assay result rows", count); } catch (BadSqlGrammarException x) { @@ -521,7 +521,7 @@ public boolean next() throws BatchValidationException { if (provider.getResultRowLSIDPrefix() == null) { - LOG.info("Import failed for run '" + run.getName() + "; Assay provider '" + provider.getName() + "' for assay '" + protocol.getName() + "' has no result row lsid prefix"); + LOG.info("Import failed for run '{}; Assay provider '{}' for assay '{}' has no result row lsid prefix", run.getName(), provider.getName(), protocol.getName()); transaction.commit(); return; } diff --git a/api/src/org/labkey/api/assay/AssayDataCollector.java b/api/src/org/labkey/api/assay/AssayDataCollector.java index 90027eb4baa..0d3cf8b83df 100644 --- a/api/src/org/labkey/api/assay/AssayDataCollector.java +++ b/api/src/org/labkey/api/assay/AssayDataCollector.java @@ -56,7 +56,7 @@ public String getButtonText() } /** @return the UI to plug into the import wizard for the user to somehow select/upload the file */ - HttpView getView(ContextType context) throws ExperimentException; + HttpView getView(ContextType context); /** @return the name for this AssayDataCollector. Needs to be unique within the set of data collectors for any given import attempt */ String getShortName(); diff --git a/api/src/org/labkey/api/assay/AssayFileWriter.java b/api/src/org/labkey/api/assay/AssayFileWriter.java index 78dc87c283e..e35eb648e81 100644 --- a/api/src/org/labkey/api/assay/AssayFileWriter.java +++ b/api/src/org/labkey/api/assay/AssayFileWriter.java @@ -204,14 +204,14 @@ public Map savePipelineFiles(ContextType context, Map> allAggResults = renderContext.getAggregates(dataRegion.getDisplayColumns(), dataRegion.getTable(), dataRegion.getSettings(), dataRegion.getName(), Collections.singletonList(countAgg), dataRegion.getQueryParameters(), dataRegion.isAllowAsync()); List aggResults = allAggResults.get(countAgg.getFieldKey().toString()); assert aggResults.size() == 1 : "Expected a single aggregate result but got " + aggResults.size(); - int totalRows = ((Number)aggResults.get(0).getValue()).intValue(); + int totalRows = ((Number)aggResults.getFirst().getValue()).intValue(); if (totalRows < rowCount) { diff --git a/api/src/org/labkey/api/assay/AssayProvider.java b/api/src/org/labkey/api/assay/AssayProvider.java index e9d72679fec..5d67c310c9f 100644 --- a/api/src/org/labkey/api/assay/AssayProvider.java +++ b/api/src/org/labkey/api/assay/AssayProvider.java @@ -241,7 +241,7 @@ enum Scope @NotNull List getValidationAndAnalysisScripts(ExpProtocol protocol, Scope scope); - void setSaveScriptFiles(ExpProtocol protocol, boolean save) throws ExperimentException; + void setSaveScriptFiles(ExpProtocol protocol, boolean save); boolean isSaveScriptFiles(ExpProtocol protocol); /** Whether the provider is capable of letting users edit existing result rows */ diff --git a/api/src/org/labkey/api/assay/AssayRunUploadContext.java b/api/src/org/labkey/api/assay/AssayRunUploadContext.java index dcfb757336b..706aa817516 100644 --- a/api/src/org/labkey/api/assay/AssayRunUploadContext.java +++ b/api/src/org/labkey/api/assay/AssayRunUploadContext.java @@ -36,7 +36,6 @@ import org.labkey.api.writer.ContainerUser; import org.labkey.vfs.FileLike; -import java.io.File; import java.util.Map; import java.util.Set; diff --git a/api/src/org/labkey/api/assay/AssayRunUploadContextImpl.java b/api/src/org/labkey/api/assay/AssayRunUploadContextImpl.java index 8722c3231b1..2e755067282 100644 --- a/api/src/org/labkey/api/assay/AssayRunUploadContextImpl.java +++ b/api/src/org/labkey/api/assay/AssayRunUploadContextImpl.java @@ -253,7 +253,7 @@ private void addVocabularyAndUnresolvedRunProperties(Map throw new NotFoundException("No Vocabularies found for this property - " + property.getKey()); } - DomainProperty dp = vocabularyDomains.get(0).getPropertyByURI(property.getKey()); + DomainProperty dp = vocabularyDomains.getFirst().getPropertyByURI(property.getKey()); if (!properties.containsKey(dp)) { properties.put(dp, property.getValue().toString()); diff --git a/api/src/org/labkey/api/assay/AssayTableMetadata.java b/api/src/org/labkey/api/assay/AssayTableMetadata.java index a4f0d5eb263..65efa9fa3b8 100644 --- a/api/src/org/labkey/api/assay/AssayTableMetadata.java +++ b/api/src/org/labkey/api/assay/AssayTableMetadata.java @@ -152,18 +152,12 @@ public FieldKey getTargetStudyFieldKey() if (pair == null) return null; - switch (pair.first) + return switch (pair.first) { - case Result: - return getTargetStudyFieldKeyOnResults(); - - case Run: - return getTargetStudyFieldKeyOnRun(); - - case Batch: - default: - return getTargetStudyFieldKeyOnBatch(); - } + case Result -> getTargetStudyFieldKeyOnResults(); + case Run -> getTargetStudyFieldKeyOnRun(); + default -> getTargetStudyFieldKeyOnBatch(); + }; } protected FieldKey getTargetStudyFieldKeyOnResults() diff --git a/api/src/org/labkey/api/assay/DefaultAssayRunCreator.java b/api/src/org/labkey/api/assay/DefaultAssayRunCreator.java index c3b9579d844..357253da842 100644 --- a/api/src/org/labkey/api/assay/DefaultAssayRunCreator.java +++ b/api/src/org/labkey/api/assay/DefaultAssayRunCreator.java @@ -582,7 +582,7 @@ protected void importStandardResultData( } } if (primaryData == null && !insertedDatas.isEmpty()) - primaryData = insertedDatas.get(0); + primaryData = insertedDatas.getFirst(); if (primaryData != null) { @@ -811,7 +811,7 @@ public static ExpData generateResultData(User user, Container container, AssayPr } // pick the most recently created one - return existing.get(0); + return existing.getFirst(); } return null; diff --git a/api/src/org/labkey/api/assay/PipelineDataCollector.java b/api/src/org/labkey/api/assay/PipelineDataCollector.java index 2f2eb520491..e15e84c9b1b 100644 --- a/api/src/org/labkey/api/assay/PipelineDataCollector.java +++ b/api/src/org/labkey/api/assay/PipelineDataCollector.java @@ -56,7 +56,7 @@ public PipelineDataCollector() private FileLike _originalFileLocation = null; @Override - public HttpView getView(ContextType context) throws ExperimentException + public HttpView getView(ContextType context) { return new HtmlView(getHTML(context)); } @@ -107,7 +107,7 @@ protected Map getCurrentFilesForDisplay(ContextType context) { return Collections.emptyMap(); } - return files.get(0); + return files.getFirst(); } @Override @@ -124,7 +124,7 @@ public String getDescription(ContextType context) { return ""; } - Map files = allFiles.get(0); + Map files = allFiles.getFirst(); return (files.size() > 1 ? files.size() + " files" : "One file ") + " from the Data Pipeline in " + files.values().iterator().next().getParent(); } @@ -174,7 +174,7 @@ public Map createData(ContextType context) throws IOException, throw new FileNotFoundException("No files from the pipeline directory have been selected"); } - Map currentFiles = files.get(0); + Map currentFiles = files.getFirst(); if (!currentFiles.isEmpty()) { _originalFileLocation = currentFiles.values().iterator().next().getParent(); @@ -194,7 +194,7 @@ public FileLike getOriginalFileLocation() @Override protected FileLike getFilePath(ContextType context, @Nullable ExpRun run, FileLike tempDirFile) { - Map files = getFileQueue(context).get(0); + Map files = getFileQueue(context).getFirst(); for (FileLike file : files.values()) { if (file.getName().equals(tempDirFile.getName())) @@ -219,7 +219,7 @@ public Map uploadComplete(ContextType context, @Nullable ExpRu List> files = getFileQueue(context); if (!files.isEmpty()) { - files.remove(0); + files.removeFirst(); } return result; } diff --git a/api/src/org/labkey/api/assay/ReplacedRunFilter.java b/api/src/org/labkey/api/assay/ReplacedRunFilter.java index ea4840f8802..9ce26adf220 100644 --- a/api/src/org/labkey/api/assay/ReplacedRunFilter.java +++ b/api/src/org/labkey/api/assay/ReplacedRunFilter.java @@ -99,7 +99,7 @@ public void addToURL(ActionURL url, String dataRegionName, FieldKey fieldKey) assert helper.getParameters().size() == 1; // Remove any existing URL filters on the Replaced column - String paramName = helper.getParameters().get(0).getKey(); + String paramName = helper.getParameters().getFirst().getKey(); String prefix = paramName.split(SimpleFilter.SEPARATOR_CHAR)[0]; for (Pair entry : url.getParameters()) { @@ -153,8 +153,8 @@ public static ReplacedRunFilter getFromURL(QueryView view, FieldKey fieldKey) typeFilter.applyToURL(helper, view.getDataRegionName()); List> parameters = helper.getParameters(); assert parameters.size() == 1; - String paramName = parameters.get(0).getKey(); - String paramValue = parameters.get(0).getValue(); + String paramName = parameters.getFirst().getKey(); + String paramValue = parameters.getFirst().getValue(); if (sortFilterParams.containsKey(paramName)) { diff --git a/api/src/org/labkey/api/assay/TsvDataHandler.java b/api/src/org/labkey/api/assay/TsvDataHandler.java index d8d88c447d2..cb03e3e88c2 100644 --- a/api/src/org/labkey/api/assay/TsvDataHandler.java +++ b/api/src/org/labkey/api/assay/TsvDataHandler.java @@ -32,7 +32,6 @@ import org.labkey.api.data.TableSelector; import org.labkey.api.exp.ExperimentException; import org.labkey.api.exp.Lsid; -import org.labkey.api.exp.PropertyType; import org.labkey.api.exp.api.DataType; import org.labkey.api.exp.api.ExpData; import org.labkey.api.exp.api.ExpProtocol; @@ -47,7 +46,6 @@ import java.io.File; import java.io.IOException; import java.io.OutputStream; -import java.nio.file.Path; import java.util.ArrayList; import java.util.Arrays; import java.util.List; @@ -173,7 +171,7 @@ public void exportFile(ExpData data, org.labkey.vfs.FileLike dataFile, User user FileUtils.copyFile(tempFile, out); if (!tempFile.delete()) - LOG.warn("Unable to delete temp file: " + tempFile.getPath()); + LOG.warn("Unable to delete temp file: {}", tempFile.getPath()); } catch (IOException e) { diff --git a/api/src/org/labkey/api/assay/actions/AssayRunUploadForm.java b/api/src/org/labkey/api/assay/actions/AssayRunUploadForm.java index ad9e02587c1..3ab5372518d 100644 --- a/api/src/org/labkey/api/assay/actions/AssayRunUploadForm.java +++ b/api/src/org/labkey/api/assay/actions/AssayRunUploadForm.java @@ -17,13 +17,11 @@ package org.labkey.api.assay.actions; import org.apache.commons.beanutils.ConversionException; -import org.apache.commons.beanutils.ConvertUtils; import org.apache.commons.io.FileUtils; import org.apache.commons.lang3.StringUtils; import org.apache.logging.log4j.Logger; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; -import org.labkey.api.action.BaseViewAction; import org.labkey.api.assay.AbstractAssayProvider; import org.labkey.api.assay.AssayDataCollector; import org.labkey.api.assay.AssayFileWriter; @@ -275,7 +273,7 @@ public AssayDataCollector getSelectedDataCollector() } if (collectors.size() == 1) { - return collectors.get(0); + return collectors.getFirst(); } return null; } @@ -509,14 +507,14 @@ else if (AbstractAssayProvider.PARTICIPANT_VISIT_RESOLVER_PROPERTY_NAME.equals(k List pks = lookupTable.getPkColumns(); if (pks.size() == 1) { - ColumnInfo pk = pks.get(0); + ColumnInfo pk = pks.getFirst(); try { Object filterValue = pk.convert(value); SimpleFilter filter = new SimpleFilter(pk.getFieldKey(), filterValue); Set cols = new HashSet<>(); cols.add(lookupTable.getTitleColumn()); - cols.add(pks.get(0).getName()); + cols.add(pks.getFirst().getName()); Map[] maps = new TableSelector(lookupTable, cols, filter, null).setForDisplay(true).getMapArray(); if (maps.length > 0) { diff --git a/api/src/org/labkey/api/assay/actions/UploadWizardAction.java b/api/src/org/labkey/api/assay/actions/UploadWizardAction.java index ead3f9259c8..00aad8f1334 100644 --- a/api/src/org/labkey/api/assay/actions/UploadWizardAction.java +++ b/api/src/org/labkey/api/assay/actions/UploadWizardAction.java @@ -459,7 +459,7 @@ private void decodePropertyValues(Map inputNameToValue, String p inputNameToValue.put(propName, propValue); } - private ModelAndView getBatchPropertiesView(FormType runForm, boolean errorReshow, BindException errors) throws ServletException, ExperimentException + private ModelAndView getBatchPropertiesView(FormType runForm, boolean errorReshow, BindException errors) throws ExperimentException { // Check if the user is trying to replace a run that's already been replaced if (runForm.getReRun() != null) @@ -511,7 +511,7 @@ private ModelAndView getBatchPropertiesView(FormType runForm, boolean errorResho * @param form the form with posted values * @param batchDomain domain for the batch fields */ - protected boolean showBatchStep(FormType form, Domain batchDomain) throws ServletException + protected boolean showBatchStep(FormType form, Domain batchDomain) { return batchDomain != null && !batchDomain.getProperties().isEmpty(); } @@ -532,27 +532,6 @@ protected void addNextButton(ButtonBar bbar) bbar.add(newRunButton); } - protected void addCancelButton(ButtonBar bbar) - { - ActionButton cancelButton = new ActionButton("Cancel", PageFlowUtil.urlProvider(AssayUrls.class).getAssayRunsURL(getContainer(), _protocol)); - bbar.add(cancelButton); - } - - protected void addCancelButton(ButtonBar bbar, String returnUrl) - { - ActionURL link; - if (returnUrl != null && !returnUrl.isEmpty()) - { - link = new ActionURL(returnUrl); - } - else - { - link = PageFlowUtil.urlProvider(AssayUrls.class).getAssayRunsURL(getContainer(), _protocol); - } - ActionButton cancelButton = new ActionButton("Cancel", link); - bbar.add(cancelButton); - } - protected void addCancelButton(ButtonBar bbar, ActionURL returnUrl) { ActionURL link; @@ -687,7 +666,7 @@ protected ModelAndView getRunPropertiesView(FormType newRunForm, boolean errorRe AssayWellExclusionService svc = AssayWellExclusionService.getProvider(_protocol); if (svc != null) { - HttpView exclusionWarning = svc.getAssayReImportWarningView(getContainer(), newRunForm.getReRun()); + HttpView exclusionWarning = svc.getAssayReImportWarningView(getContainer(), newRunForm.getReRun()); if (exclusionWarning != null) { vbox.addView(exclusionWarning); @@ -695,7 +674,7 @@ protected ModelAndView getRunPropertiesView(FormType newRunForm, boolean errorRe } AssayQCService qcService = AssayQCService.getProvider(); - HttpView qcWarning = qcService.getAssayReImportWarningView(getContainer(), newRunForm.getReRun()); + HttpView qcWarning = qcService.getAssayReImportWarningView(getContainer(), newRunForm.getReRun()); if (qcWarning != null) { vbox.addView(qcWarning); @@ -835,7 +814,6 @@ protected void addSampleInputColumns(FormType form, InsertView insertView) } @Override - @Nullable public void addNavTrail(NavTree root) { if (null != _protocol) @@ -951,14 +929,14 @@ public void validateStep(FormType form, Errors errors) } @Override - public boolean executeStep(FormType form, BindException errors) throws ServletException, SQLException, ExperimentException + public boolean executeStep(FormType form, BindException errors) { // nothing to handle but need to show the run step handler return false; } @Override - public ModelAndView getNextStep(FormType form, BindException errors) throws ServletException, SQLException, ExperimentException + public ModelAndView getNextStep(FormType form, BindException errors) throws ServletException, ExperimentException { if ((form.isResetDefaultValues() || errors.hasErrors()) && showBatchStep(form, form.getProvider().getBatchDomain(form.getProtocol()))) return getBatchPropertiesView(form, !form.isResetDefaultValues(), errors); @@ -1000,7 +978,7 @@ public static abstract class StepHandler"); int cnt = 0; - for (Object m : list) + for (MessageSourceResolvable m : list) { - HtmlString errStr = HtmlString.of(getViewContext().getMessage((MessageSourceResolvable)m)); + HtmlString errStr = HtmlString.of(getViewContext().getMessage(m)); if (!uniqueErrorStrs.contains(errStr)) { if (cnt++ < MAX_ERRORS) diff --git a/api/src/org/labkey/api/assay/pipeline/AssayRunAsyncContext.java b/api/src/org/labkey/api/assay/pipeline/AssayRunAsyncContext.java index ff013ed6325..a1c2d64e8ac 100644 --- a/api/src/org/labkey/api/assay/pipeline/AssayRunAsyncContext.java +++ b/api/src/org/labkey/api/assay/pipeline/AssayRunAsyncContext.java @@ -215,9 +215,9 @@ else if(entry.getKey().getName().equals(AbstractAssayProvider.TARGET_STUDY_PROPE valueText = entry.getValue(); if(entry.getKey().getLabel() != null) - logger.info("\t"+entry.getKey().getLabel()+": " + valueText); + logger.info("\t{}: {}", entry.getKey().getLabel(), valueText); else - logger.info("\t"+entry.getKey().getName()+": " + valueText); + logger.info("\t{}: {}", entry.getKey().getName(), valueText); } logger.info("----- End Batch Properties -----"); @@ -226,18 +226,18 @@ else if(entry.getKey().getName().equals(AbstractAssayProvider.TARGET_STUDY_PROPE for(Map.Entry entry : getUploadedData().entrySet()) { - logger.info("\t\t* " + entry.getValue().getName()); + logger.info("\t\t* {}", entry.getValue().getName()); } if(_runName == null) logger.info("\tAssay ID: [Blank]"); else - logger.info("\tAssay ID: " + _runName); + logger.info("\tAssay ID: {}", _runName); if(_runComments == null) logger.info("\tRun Comments: [Blank]"); else - logger.info("\tRun Comments: " + _runComments); + logger.info("\tRun Comments: {}", _runComments); for (Map.Entry entry : _runProperties.entrySet()) { @@ -247,9 +247,9 @@ else if(entry.getKey().getName().equals(AbstractAssayProvider.TARGET_STUDY_PROPE valueText = entry.getValue(); if(entry.getKey().getLabel() != null) - logger.info("\t"+entry.getKey().getLabel()+": " + valueText); + logger.info("\t{}: {}", entry.getKey().getLabel(), valueText); else - logger.info("\t"+entry.getKey().getName()+": " + valueText); + logger.info("\t{}: {}", entry.getKey().getName(), valueText); } logger.info("----- End Run Properties -----"); } diff --git a/api/src/org/labkey/api/assay/pipeline/AssayUploadPipelineJob.java b/api/src/org/labkey/api/assay/pipeline/AssayUploadPipelineJob.java index afb323ea18a..904cd3d51cf 100644 --- a/api/src/org/labkey/api/assay/pipeline/AssayUploadPipelineJob.java +++ b/api/src/org/labkey/api/assay/pipeline/AssayUploadPipelineJob.java @@ -202,7 +202,7 @@ public void doWork() } else { - getLogger().error(e.getMessage() + "\n"); + getLogger().error("{}\n", e.getMessage()); setStatus(TaskStatus.error, e.getMessage()); } } diff --git a/api/src/org/labkey/api/assay/pipeline/AssayUploadPipelineTask.java b/api/src/org/labkey/api/assay/pipeline/AssayUploadPipelineTask.java index 168ba614911..7008232479e 100644 --- a/api/src/org/labkey/api/assay/pipeline/AssayUploadPipelineTask.java +++ b/api/src/org/labkey/api/assay/pipeline/AssayUploadPipelineTask.java @@ -4,7 +4,6 @@ import org.labkey.api.pipeline.AbstractTaskFactory; import org.labkey.api.pipeline.AbstractTaskFactorySettings; import org.labkey.api.pipeline.PipelineJob; -import org.labkey.api.pipeline.PipelineJobException; import org.labkey.api.pipeline.RecordedActionSet; import org.labkey.api.util.FileType; @@ -23,7 +22,7 @@ public AssayUploadPipelineTask(Factory factory, PipelineJob job) } @Override - public @NotNull RecordedActionSet run() throws PipelineJobException + public @NotNull RecordedActionSet run() { ((AssayUploadPipelineJob)getJob()).doWork(); return new RecordedActionSet(); diff --git a/api/src/org/labkey/api/assay/plate/AssayPlateMetadataService.java b/api/src/org/labkey/api/assay/plate/AssayPlateMetadataService.java index f4b60adb492..d07f45e7764 100644 --- a/api/src/org/labkey/api/assay/plate/AssayPlateMetadataService.java +++ b/api/src/org/labkey/api/assay/plate/AssayPlateMetadataService.java @@ -129,7 +129,7 @@ OntologyManager.UpdateableTableImportHelper getImportHelper( ExpProtocol protocol, AssayProvider provider, @Nullable AssayRunUploadContext context - ) throws ExperimentException; + ); /** * Return the domain representing the plate replicate statistical columns that are created for plate based diff --git a/api/src/org/labkey/api/assay/plate/PlateMetadataDataHandler.java b/api/src/org/labkey/api/assay/plate/PlateMetadataDataHandler.java index b9c26edc22f..f4dd58e9ad5 100644 --- a/api/src/org/labkey/api/assay/plate/PlateMetadataDataHandler.java +++ b/api/src/org/labkey/api/assay/plate/PlateMetadataDataHandler.java @@ -4,7 +4,6 @@ import org.jetbrains.annotations.NotNull; import org.labkey.api.assay.AbstractAssayTsvDataHandler; import org.labkey.api.assay.AssayDataType; -import org.labkey.api.exp.ExperimentException; import org.labkey.api.exp.Lsid; import org.labkey.api.exp.XarContext; import org.labkey.api.exp.api.DataType; @@ -56,7 +55,7 @@ public Priority getPriority(ExpData data) } @Override - public void importFile(@NotNull ExpData data, @NotNull FileLike dataFile, @NotNull ViewBackgroundInfo info, @NotNull Logger log, @NotNull XarContext context) throws ExperimentException + public void importFile(@NotNull ExpData data, @NotNull FileLike dataFile, @NotNull ViewBackgroundInfo info, @NotNull Logger log, @NotNull XarContext context) { // this is just a noop data handler, the actual parsing and importing of the plate metadata needs to happen in // AbstractAssayTsvDataHandler.addAssayPlateMetadata because we need to access the inserted result data to get at the diff --git a/api/src/org/labkey/api/assay/query/ResultsQueryView.java b/api/src/org/labkey/api/assay/query/ResultsQueryView.java index b46448a9b09..82ecdba4947 100644 --- a/api/src/org/labkey/api/assay/query/ResultsQueryView.java +++ b/api/src/org/labkey/api/assay/query/ResultsQueryView.java @@ -25,7 +25,6 @@ import org.labkey.api.assay.ReplacedRunFilter; import org.labkey.api.data.ActionButton; import org.labkey.api.data.ButtonBar; -import org.labkey.api.data.ColumnHeaderType; import org.labkey.api.data.ColumnInfo; import org.labkey.api.data.Container; import org.labkey.api.data.ContainerFilter; @@ -223,12 +222,6 @@ protected void populateButtonBar(DataView view, ButtonBar bar) } } - @Override - protected ColumnHeaderType getColumnHeaderType() - { - return ColumnHeaderType.Caption; - } - public static class ResultsDataRegion extends DataRegion { private ColumnInfo _matchColumn; diff --git a/api/src/org/labkey/api/assay/transform/AnalysisScript.java b/api/src/org/labkey/api/assay/transform/AnalysisScript.java index 350a2ec936a..a3a16e09987 100644 --- a/api/src/org/labkey/api/assay/transform/AnalysisScript.java +++ b/api/src/org/labkey/api/assay/transform/AnalysisScript.java @@ -4,12 +4,10 @@ import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; -import org.labkey.api.util.UnexpectedException; import org.labkey.vfs.FileLike; import org.labkey.vfs.FileSystemLike; import java.io.File; -import java.io.IOException; import java.util.ArrayList; import java.util.Collection; import java.util.HashSet; diff --git a/api/src/org/labkey/api/attachments/AttachmentDirectory.java b/api/src/org/labkey/api/attachments/AttachmentDirectory.java index a4361197372..a336b039d25 100644 --- a/api/src/org/labkey/api/attachments/AttachmentDirectory.java +++ b/api/src/org/labkey/api/attachments/AttachmentDirectory.java @@ -18,7 +18,6 @@ import org.jetbrains.annotations.Nullable; import org.labkey.api.data.Container; -import org.labkey.api.files.MissingRootDirectoryException; import org.labkey.api.security.User; import java.io.File; @@ -36,9 +35,9 @@ public interface AttachmentDirectory extends AttachmentParent String getName(); @Deprecated - File getFileSystemDirectory() throws MissingRootDirectoryException; - Path getFileSystemDirectoryPath() throws MissingRootDirectoryException; - Path getFileSystemDirectoryPath(Container container, boolean create) throws MissingRootDirectoryException; + File getFileSystemDirectory(); + Path getFileSystemDirectoryPath(); + Path getFileSystemDirectoryPath(Container container, boolean create); void addAttachment(User user, AttachmentFile attachment) throws IOException; void deleteAttachment(User user, @Nullable String name); diff --git a/api/src/org/labkey/api/audit/AbstractAuditHandler.java b/api/src/org/labkey/api/audit/AbstractAuditHandler.java index 3f4c3f1c098..a5e9945f26d 100644 --- a/api/src/org/labkey/api/audit/AbstractAuditHandler.java +++ b/api/src/org/labkey/api/audit/AbstractAuditHandler.java @@ -103,7 +103,7 @@ public void addAuditEvent(User user, Container c, TableInfo table, @Nullable Aud { assert null != rows; - AuditTypeEvent event = createSummaryAuditRecord(user, c, auditConfigurable, action, userComment, rows.size(), rows.get(0)); + AuditTypeEvent event = createSummaryAuditRecord(user, c, auditConfigurable, action, userComment, rows.size(), rows.getFirst()); AuditLogService.get().addEvent(user, event); diff --git a/api/src/org/labkey/api/audit/AuditLogService.java b/api/src/org/labkey/api/audit/AuditLogService.java index 59facccef87..b4d005a1d86 100644 --- a/api/src/org/labkey/api/audit/AuditLogService.java +++ b/api/src/org/labkey/api/audit/AuditLogService.java @@ -156,7 +156,7 @@ static void handleAuditFailure(User user, Throwable e) } catch (Exception ex) { - LOG.warn("Exception while committing: " + ex.getMessage()); + LOG.warn("Exception while committing", ex); } } } diff --git a/api/src/org/labkey/api/cache/ehcache/EhCacheProvider.java b/api/src/org/labkey/api/cache/ehcache/EhCacheProvider.java index d734dc0666c..c68f60c6d4d 100644 --- a/api/src/org/labkey/api/cache/ehcache/EhCacheProvider.java +++ b/api/src/org/labkey/api/cache/ehcache/EhCacheProvider.java @@ -131,8 +131,8 @@ void closeCache(Cache cache) // We've upgraded EhCache to 2.6.8, so we no longer need to modify ehCacheReferenceList. Just log its size to keep us (and EhCache) honest. See #19480. if (null != ehCacheReferenceList) - LOG.debug("Caches in EhCache reference list: " + ehCacheReferenceList.size()); + LOG.debug("Caches in EhCache reference list: {}", ehCacheReferenceList.size()); - LOG.debug("Closing \"" + cache.getName() + "\". Ehcaches: " + MANAGER.getCacheNames().length); + LOG.debug("Closing \"{}\". Ehcaches: {}", cache.getName(), MANAGER.getCacheNames().length); } } diff --git a/api/src/org/labkey/api/collections/ArrayListMap.java b/api/src/org/labkey/api/collections/ArrayListMap.java index 64df314459e..2e597ce21eb 100644 --- a/api/src/org/labkey/api/collections/ArrayListMap.java +++ b/api/src/org/labkey/api/collections/ArrayListMap.java @@ -113,7 +113,7 @@ public Integer remove(Object o) } @Override - public void putAll(Map map) + public void putAll(@NotNull Map map) { _map.putAll(map); } @@ -125,19 +125,19 @@ public void clear() } @Override - public Set keySet() + public @NotNull Set keySet() { return _map.keySet(); } @Override - public Collection values() + public @NotNull Collection values() { return _map.values(); } @Override - public Set> entrySet() + public @NotNull Set> entrySet() { return _map.entrySet(); } @@ -245,7 +245,7 @@ public boolean containsValue(Object value) /* ArrayList order please */ @Override - public Set> entrySet() + public @NotNull Set> entrySet() { // This is not particularly fast, but that's probably OK // CONSIDER: use a LinkedHashMap to implement FindMap and skip this alignment step @@ -292,7 +292,7 @@ public int size() @Override - public Collection values() + public @NotNull Collection values() { ArrayList a = new ArrayList<>(size()); for (Object o : _row) diff --git a/api/src/org/labkey/api/collections/BoundMap.java b/api/src/org/labkey/api/collections/BoundMap.java index 3fcec8a87b3..be9e88be705 100644 --- a/api/src/org/labkey/api/collections/BoundMap.java +++ b/api/src/org/labkey/api/collections/BoundMap.java @@ -19,6 +19,7 @@ import org.apache.commons.beanutils.ConvertUtils; import org.apache.commons.lang3.StringUtils; import org.apache.logging.log4j.LogManager; +import org.jetbrains.annotations.NotNull; import org.junit.Assert; import org.junit.Test; @@ -168,7 +169,7 @@ public Object put(String key, Object value) @Override - public Set> entrySet() + public @NotNull Set> entrySet() { Set keys = keySet(); Set> entries = new HashSet<>(); @@ -233,7 +234,7 @@ private BoundProperty getBoundProperty(String key) } @Override - public Set keySet() + public @NotNull Set keySet() { Set keys = new HashSet<>(); Set mapKeys = _map.keySet(); diff --git a/api/src/org/labkey/api/collections/CaseInsensitiveMapWrapper.java b/api/src/org/labkey/api/collections/CaseInsensitiveMapWrapper.java index 28bdd578d85..31fb53d7dd0 100644 --- a/api/src/org/labkey/api/collections/CaseInsensitiveMapWrapper.java +++ b/api/src/org/labkey/api/collections/CaseInsensitiveMapWrapper.java @@ -16,8 +16,8 @@ package org.labkey.api.collections; -import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; +import org.jetbrains.annotations.NotNull; import org.junit.Assert; import org.junit.Test; @@ -127,14 +127,14 @@ public Iterator iterator() @NotNull @Override - public Object[] toArray() + public Object @NotNull [] toArray() { return _nativeKeySet.toArray(); } @NotNull @Override - public T[] toArray(@NotNull T[] a) + public T @NotNull [] toArray(@NotNull T @NotNull [] a) { return _nativeKeySet.toArray(a); } diff --git a/api/src/org/labkey/api/collections/IndexMappingList.java b/api/src/org/labkey/api/collections/IndexMappingList.java index eff237cfe01..685e4d90da7 100644 --- a/api/src/org/labkey/api/collections/IndexMappingList.java +++ b/api/src/org/labkey/api/collections/IndexMappingList.java @@ -15,6 +15,8 @@ */ package org.labkey.api.collections; +import org.jetbrains.annotations.NotNull; + import java.util.List; import java.util.ListIterator; @@ -77,7 +79,7 @@ public int lastIndexOf(Object o) } @Override - public L subList(int fromIndex, int toIndex) + public @NotNull L subList(int fromIndex, int toIndex) { return wrapList(super.subList(mapIndexIn(fromIndex), mapIndexIn(toIndex))); } @@ -86,13 +88,13 @@ public L subList(int fromIndex, int toIndex) // to nextIndex() and previousIndex() @Override - public ListIterator listIterator() + public @NotNull ListIterator listIterator() { throw new UnsupportedOperationException(); } @Override - public ListIterator listIterator(int index) + public @NotNull ListIterator listIterator(int index) { throw new UnsupportedOperationException(); } diff --git a/api/src/org/labkey/api/collections/ListWrapper.java b/api/src/org/labkey/api/collections/ListWrapper.java index 94007f66e0b..7e7dc851354 100644 --- a/api/src/org/labkey/api/collections/ListWrapper.java +++ b/api/src/org/labkey/api/collections/ListWrapper.java @@ -15,6 +15,8 @@ */ package org.labkey.api.collections; +import org.jetbrains.annotations.NotNull; + import java.util.Collection; import java.util.Iterator; import java.util.List; @@ -58,19 +60,19 @@ public boolean contains(Object o) } @Override - public Iterator iterator() + public @NotNull Iterator iterator() { return _list.iterator(); } @Override - public Object[] toArray() + public Object @NotNull [] toArray() { return _list.toArray(); } @Override - public T[] toArray(T[] a) + public T @NotNull [] toArray(T @NotNull [] a) { return _list.toArray(a); } @@ -88,31 +90,31 @@ public boolean remove(Object o) } @Override - public boolean containsAll(Collection c) + public boolean containsAll(@NotNull Collection c) { return _list.containsAll(c); } @Override - public boolean addAll(Collection c) + public boolean addAll(@NotNull Collection c) { return _list.addAll(c); } @Override - public boolean addAll(int index, Collection c) + public boolean addAll(int index, @NotNull Collection c) { return _list.addAll(index, c); } @Override - public boolean removeAll(Collection c) + public boolean removeAll(@NotNull Collection c) { return _list.removeAll(c); } @Override - public boolean retainAll(Collection c) + public boolean retainAll(@NotNull Collection c) { return _list.retainAll(c); } @@ -172,19 +174,19 @@ public int lastIndexOf(Object o) } @Override - public ListIterator listIterator() + public @NotNull ListIterator listIterator() { return _list.listIterator(); } @Override - public ListIterator listIterator(int index) + public @NotNull ListIterator listIterator(int index) { return _list.listIterator(index); } @Override - public List subList(int fromIndex, int toIndex) + public @NotNull List subList(int fromIndex, int toIndex) { return _list.subList(fromIndex, toIndex); } diff --git a/api/src/org/labkey/api/collections/MapWrapper.java b/api/src/org/labkey/api/collections/MapWrapper.java index 2031a087620..731f25860ff 100644 --- a/api/src/org/labkey/api/collections/MapWrapper.java +++ b/api/src/org/labkey/api/collections/MapWrapper.java @@ -15,6 +15,8 @@ */ package org.labkey.api.collections; +import org.jetbrains.annotations.NotNull; + import java.io.Serializable; import java.util.Collection; import java.util.Map; @@ -77,7 +79,7 @@ public V remove(Object key) } @Override - public void putAll(Map m) + public void putAll(@NotNull Map m) { _map.putAll(m); } @@ -89,19 +91,19 @@ public void clear() } @Override - public Set keySet() + public @NotNull Set keySet() { return _map.keySet(); } @Override - public Collection values() + public @NotNull Collection values() { return _map.values(); } @Override - public Set> entrySet() + public @NotNull Set> entrySet() { return _map.entrySet(); } diff --git a/api/src/org/labkey/api/collections/NamedObjectList.java b/api/src/org/labkey/api/collections/NamedObjectList.java index a2833b13e8d..23a3c4df024 100644 --- a/api/src/org/labkey/api/collections/NamedObjectList.java +++ b/api/src/org/labkey/api/collections/NamedObjectList.java @@ -15,6 +15,8 @@ */ package org.labkey.api.collections; +import org.jetbrains.annotations.NotNull; + import java.util.Collection; import java.util.Iterator; @@ -64,13 +66,13 @@ public Object get(String s) } @Override - public NamedObject[] toArray(NamedObject[] array) + public NamedObject @NotNull [] toArray(NamedObject @NotNull [] array) { return _map.values().toArray(array); } @Override - public NamedObject[] toArray() + public NamedObject @NotNull [] toArray() { return _map.values().toArray(new NamedObject[size()]); } @@ -82,7 +84,7 @@ public boolean add(NamedObject arg0) } @Override - public boolean addAll(Collection arg0) + public boolean addAll(@NotNull Collection arg0) { throw new UnsupportedOperationException(); } @@ -100,7 +102,7 @@ public boolean contains(Object arg0) } @Override - public boolean containsAll(Collection arg0) + public boolean containsAll(@NotNull Collection arg0) { throw new UnsupportedOperationException(); } @@ -112,7 +114,7 @@ public boolean isEmpty() } @Override - public Iterator iterator() + public @NotNull Iterator iterator() { return _map.values().iterator(); } @@ -124,13 +126,13 @@ public boolean remove(Object arg0) } @Override - public boolean removeAll(Collection arg0) + public boolean removeAll(@NotNull Collection arg0) { throw new UnsupportedOperationException(); } @Override - public boolean retainAll(Collection arg0) + public boolean retainAll(@NotNull Collection arg0) { throw new UnsupportedOperationException(); } diff --git a/api/src/org/labkey/api/collections/OneBasedList.java b/api/src/org/labkey/api/collections/OneBasedList.java index 4776e33f8b0..ba39b8670a3 100644 --- a/api/src/org/labkey/api/collections/OneBasedList.java +++ b/api/src/org/labkey/api/collections/OneBasedList.java @@ -107,7 +107,7 @@ public void testGetOutOfBounds() { List list = getTestList(); exception.expect(IndexOutOfBoundsException.class); - list.get(0); + list.getFirst(); } @Test @@ -115,7 +115,7 @@ public void testAddOutOfBounds() { List list = getTestList(); exception.expect(IndexOutOfBoundsException.class); - list.add(0, "Foo"); + list.addFirst("Foo"); } private List getTestList() diff --git a/api/src/org/labkey/api/collections/SetFromMap.java b/api/src/org/labkey/api/collections/SetFromMap.java index db518c89170..b62c160af6d 100644 --- a/api/src/org/labkey/api/collections/SetFromMap.java +++ b/api/src/org/labkey/api/collections/SetFromMap.java @@ -16,6 +16,8 @@ package org.labkey.api.collections; +import org.jetbrains.annotations.NotNull; + import java.io.IOException; import java.io.Serializable; import java.util.AbstractSet; @@ -60,20 +62,20 @@ class SetFromMap extends AbstractSet implements Set, Serializable @Override public boolean add(E e) { return m.put(e, Boolean.TRUE) == null; } @Override - public Iterator iterator() { return s.iterator(); } + public @NotNull Iterator iterator() { return s.iterator(); } @Override - public Object[] toArray() { return s.toArray(); } + public Object @NotNull [] toArray() { return s.toArray(); } @Override - public T[] toArray(T[] a) { return s.toArray(a); } + public T @NotNull [] toArray(T @NotNull [] a) { return s.toArray(a); } public String toString() { return s.toString(); } public int hashCode() { return s.hashCode(); } public boolean equals(Object o) { return o == this || s.equals(o); } @Override - public boolean containsAll(Collection c) {return s.containsAll(c);} + public boolean containsAll(@NotNull Collection c) {return s.containsAll(c);} @Override - public boolean removeAll(Collection c) {return s.removeAll(c);} + public boolean removeAll(@NotNull Collection c) {return s.removeAll(c);} @Override - public boolean retainAll(Collection c) {return s.retainAll(c);} + public boolean retainAll(@NotNull Collection c) {return s.retainAll(c);} // addAll is the only inherited implementation private static final long serialVersionUID = 2454657854757543876L; diff --git a/api/src/org/labkey/api/compliance/ComplianceService.java b/api/src/org/labkey/api/compliance/ComplianceService.java index ad1ca07611e..0f18b691ecc 100644 --- a/api/src/org/labkey/api/compliance/ComplianceService.java +++ b/api/src/org/labkey/api/compliance/ComplianceService.java @@ -125,16 +125,6 @@ public boolean hasViewSignedSnapshotsPermission(@NotNull Container container, @N { return false; } - @Override - @NotNull public PHI getMaxAllowedPhi(@NotNull Container container, @NotNull User user) - { - return PHI.Restricted; - } - @Override - public Activity getCurrentActivity(ViewContext viewContext) - { - return null; - } @Override public ComplianceFolderSettings getFolderSettings(@NotNull Container container, @NotNull User user) throws UnauthorizedException diff --git a/api/src/org/labkey/api/compliance/TableRulesManager.java b/api/src/org/labkey/api/compliance/TableRulesManager.java index c3bcef83bb0..113b8e22a14 100644 --- a/api/src/org/labkey/api/compliance/TableRulesManager.java +++ b/api/src/org/labkey/api/compliance/TableRulesManager.java @@ -40,7 +40,7 @@ private TableRulesManager() public void addTableRulesProvider(TableRulesProvider provider) { // Always add to the beginning... we want to iterate in reverse dependency order - TABLE_RULES_PROVIDERS.add(0, provider); + TABLE_RULES_PROVIDERS.addFirst(provider); } public @NotNull TableRules getTableRules(@NotNull Container c, @NotNull User user, SecurableResource permissionsResource) diff --git a/api/src/org/labkey/api/data/AbstractForeignKey.java b/api/src/org/labkey/api/data/AbstractForeignKey.java index e738d8eaaf8..be37b32cf4b 100644 --- a/api/src/org/labkey/api/data/AbstractForeignKey.java +++ b/api/src/org/labkey/api/data/AbstractForeignKey.java @@ -244,7 +244,7 @@ protected void initTableAndColumnNames() if (pkColumns != null && !pkColumns.isEmpty()) { int first = 0; - if (pkColumns.size() > 1 && isContainerColumn(pkColumns.get(0))) + if (pkColumns.size() > 1 && isContainerColumn(pkColumns.getFirst())) first = 1; _columnName = pkColumns.get(first).getName(); } @@ -380,7 +380,7 @@ public boolean allowImportByAlternateKey() if (!lookupColumn.isKeyField()) return false; - ColumnInfo pkCol = pkCols.get(0); + ColumnInfo pkCol = pkCols.getFirst(); Set seen = new HashSet<>(); List> candidates = new ArrayList<>(); @@ -392,7 +392,7 @@ public boolean allowImportByAlternateKey() if (def.columns().size() != 1) continue; - ColumnInfo col = def.columns().get(0); + ColumnInfo col = def.columns().getFirst(); if (seen.contains(col)) continue; seen.add(col); diff --git a/api/src/org/labkey/api/data/AbstractTableInfo.java b/api/src/org/labkey/api/data/AbstractTableInfo.java index d57ce93a665..fed3cb66180 100644 --- a/api/src/org/labkey/api/data/AbstractTableInfo.java +++ b/api/src/org/labkey/api/data/AbstractTableInfo.java @@ -506,7 +506,7 @@ protected SQLFragment getFromSQLExpanded(String alias, Set cols) } catch (Exception e) { - LOG.warn("Filtered lookup failed for column: " + firstColumn.getName(), e); + LOG.warn("Filtered lookup failed for column: {}", firstColumn.getName(), e); } Sort sort = new Sort(); sort.insertSortColumn(titleColumn.getFieldKey(), titleColumn.getSortDirection()); @@ -874,7 +874,7 @@ public void addCounterDefinition(@NotNull CounterDefinition counterDef) if (column == null) { valid = false; - LOG.warn("Error in counter definition '" + counterDef.getCounterName() + "': paired column does not exist: " + columnName); + LOG.warn("Error in counter definition '{}': paired column does not exist: {}", counterDef.getCounterName(), columnName); } } @@ -884,12 +884,12 @@ public void addCounterDefinition(@NotNull CounterDefinition counterDef) if (column == null) { valid = false; - LOG.warn("Error in counter definition '" + counterDef.getCounterName() + "': attached column does not exist: " + columnName); + LOG.warn("Error in counter definition '{}': attached column does not exist: {}", counterDef.getCounterName(), columnName); } else if (!column.getJdbcType().isInteger()) { valid = false; - LOG.warn("Error in counter definition '" + counterDef.getCounterName() + "': non-integer attached column: " + columnName); + LOG.warn("Error in counter definition '{}': non-integer attached column: {}", counterDef.getCounterName(), columnName); } } @@ -1248,7 +1248,7 @@ public static ForeignKey makeForeignKey(QuerySchema fromSchema, ContainerFilter if (MultiValuedFkType.junction.name().equals(type)) ret = new MultiValuedForeignKey(ret, fk.getFkJunctionLookup()); else - LOG.warn(String.format("Error in FK configuration for schema : \"%s\". The multi value FK type : \"%s\" is not supported.", fromSchema.getSchemaName(), type)); + LOG.warn("Error in FK configuration for schema : \"{}\". The multi value FK type : \"{}\" is not supported.", fromSchema.getSchemaName(), type); } return ret; @@ -1371,7 +1371,7 @@ protected void loadAllButCustomizerFromXML(QuerySchema schema, @Nullable TableTy } else { - LOG.debug("Query name in XML metadata in schema '" + schema.getSchemaName() + "' did not match expected. Was: [" + xmlTable.getTableName() + "], expected: [" + getName() + "] in container " + schema.getContainer().getPath()); + LOG.debug("Query name in XML metadata in schema '{}' did not match expected. Was: [{}], expected: [{}] in container {}", schema.getSchemaName(), xmlTable.getTableName(), getName(), schema.getContainer().getPath()); } } if (xmlTable.getTitleColumn() != null) @@ -1972,8 +1972,7 @@ private final Collection loadTriggers(@Nullable Container c) if (LOG.isDebugEnabled() && !scripts.isEmpty()) { - LOG.debug("Trigger scripts for '" + getPublicSchemaName() + "', '" + getName() + "': " + - scripts.stream().map(Trigger::getName).collect(Collectors.joining(", "))); + LOG.debug("Trigger scripts for '{}', '{}': {}", getPublicSchemaName(), getName(), scripts.stream().map(Trigger::getName).collect(Collectors.joining(", "))); } return scripts; diff --git a/api/src/org/labkey/api/data/AnalyticsProviderItem.java b/api/src/org/labkey/api/data/AnalyticsProviderItem.java index 9d8e7324be4..3cc12e3f766 100644 --- a/api/src/org/labkey/api/data/AnalyticsProviderItem.java +++ b/api/src/org/labkey/api/data/AnalyticsProviderItem.java @@ -227,7 +227,7 @@ else if ((BaseAggregatesAnalyticsProvider.PREFIX + "AVG").equalsIgnoreCase(type) if (analyticsProvider == null) { //throw new IllegalArgumentException("Invalid analytic provider name: '" + type + "'."); - LOG.warn("Invalid analytic provider name: '" + type + "'."); + LOG.warn("Invalid analytic provider name: '{}'.", type); } return analyticsProvider; diff --git a/api/src/org/labkey/api/data/AsyncQueryRequest.java b/api/src/org/labkey/api/data/AsyncQueryRequest.java index fd3df0adb9b..a9456b552d6 100644 --- a/api/src/org/labkey/api/data/AsyncQueryRequest.java +++ b/api/src/org/labkey/api/data/AsyncQueryRequest.java @@ -241,7 +241,7 @@ synchronized private void cancel() { try { - _log.debug("Aborting async statement on connection " + _statement.getConnection()); + _log.debug("Aborting async statement on connection {}", _statement.getConnection()); _statement.cancel(); } catch (SQLException e) @@ -262,7 +262,7 @@ private IOException checkCancelled() } catch (IOException ioe) { - _log.debug("ping client: failure: " + ioe.getMessage()); + _log.debug("ping client: failure: {}", ioe.getMessage()); cancel(); return ioe; } diff --git a/api/src/org/labkey/api/data/BaseColumnInfo.java b/api/src/org/labkey/api/data/BaseColumnInfo.java index f66c0a0146e..747dd400f92 100644 --- a/api/src/org/labkey/api/data/BaseColumnInfo.java +++ b/api/src/org/labkey/api/data/BaseColumnInfo.java @@ -991,6 +991,7 @@ public void setIsRootDbSequence(boolean isRootDbSequence) _isRootDbSequence = isRootDbSequence; } + @Override public boolean isMultiValued() { return _isMultiValued; @@ -1141,16 +1142,16 @@ public void loadFromXml(ColumnType xmlCol, boolean merge) displayColumnName = xfk.getFkDisplayColumnName().getStringValue(); useRawFKValue = xfk.getFkDisplayColumnName().getUseRawValue(); } - _fk = new SchemaForeignKey(this, key.pkSchemaName, key.pkTableName, key.pkColumnNames.get(0), key.fkName, false, displayColumnName, useRawFKValue); + _fk = new SchemaForeignKey(this, key.pkSchemaName, key.pkTableName, key.pkColumnNames.getFirst(), key.fkName, false, displayColumnName, useRawFKValue); } else { String type = xfk.getFkMultiValued(); if (AbstractTableInfo.MultiValuedFkType.junction.name().equals(type)) - _fk = new MultiValuedForeignKey(new SchemaForeignKey(this, key.pkSchemaName, key.pkTableName, key.pkColumnNames.get(0), key.fkName, false), xfk.getFkJunctionLookup()); + _fk = new MultiValuedForeignKey(new SchemaForeignKey(this, key.pkSchemaName, key.pkTableName, key.pkColumnNames.getFirst(), key.fkName, false), xfk.getFkJunctionLookup()); else - LOG.warn(String.format("Error in FK configuration for table : \"%s\". The multi value FK type : \"%s\" is not supported.", getParentTable().getName(), type)); + LOG.warn("Error in FK configuration for table : \"{}\". The multi value FK type : \"{}\" is not supported.", getParentTable().getName(), type); } } @@ -1304,7 +1305,7 @@ else if (xmlCol.isSetKeyVariable()) } else { - LOG.error("Class is not a DisplayColumnFactory: " + displayColumnClassName); + LOG.error("Class is not a DisplayColumnFactory: {}", displayColumnClassName); } } } @@ -1315,7 +1316,7 @@ else if (xmlCol.isSetKeyVariable()) // Defer logging an error until column is actually used, Issue #44103 // Substitute a factory that provides a renderer that displays and logs the error at render time LOG.debug(message, e); - _displayColumnFactory = colInfo -> { + _displayColumnFactory = _ -> { LOG.error(message, e); return new SimpleDisplayColumn() { @@ -1475,7 +1476,7 @@ static public class SchemaForeignKey implements ForeignKey private final String _dbSchemaName; private final String _tableName; private String _lookupKey; - private String _fkName; + private final String _fkName; private final String _displayColumnName; private final boolean _joinWithContainer; private final boolean _useRawFKValue; @@ -1607,7 +1608,7 @@ public String getLookupColumnName(@Nullable TableInfo tableInfo) List pkColumnNames = tableInfo.getPkColumnNames(); if (pkColumnNames.size() == 1) { - _lookupKey = pkColumnNames.get(0); + _lookupKey = pkColumnNames.getFirst(); } } return null; @@ -1783,7 +1784,7 @@ else if (key.pkColumnNames.size() == 2 && "container".equalsIgnoreCase(key.fkCol if (i == -1) { - LOG.warn("Skipping multiple column foreign key " + key.fkName + " ON " + parentTable.getName()); + LOG.warn("Skipping multiple column foreign key {} ON {}", key.fkName, parentTable.getName()); continue; } @@ -1792,13 +1793,13 @@ else if (key.pkColumnNames.size() == 2 && "container".equalsIgnoreCase(key.fkCol if (col == null) { - LOG.error("Column in FK definition was not found " + colName + ". Skipping constraint " + key.fkName); + LOG.error("Column in FK definition was not found {}. Skipping constraint {}", colName, key.fkName); continue; } if (col._fk != null) { - LOG.warn("More than one FK defined for column " + parentTable.getName() + "." + col.getName() + ". Skipping constraint " + key.fkName); + LOG.warn("More than one FK defined for column {}.{}. Skipping constraint {}", parentTable.getName(), col.getName(), key.fkName); continue; } diff --git a/api/src/org/labkey/api/data/BaseSelector.java b/api/src/org/labkey/api/data/BaseSelector.java index 29db54d144b..01a4f6a2d86 100644 --- a/api/src/org/labkey/api/data/BaseSelector.java +++ b/api/src/org/labkey/api/data/BaseSelector.java @@ -366,7 +366,7 @@ public ArrayList handle(ResultSet rs, Connection conn) throws SQLException }); if (list.size() == 1) - return list.get(0); + return list.getFirst(); else if (list.isEmpty()) return null; else diff --git a/api/src/org/labkey/api/data/BooleanFormat.java b/api/src/org/labkey/api/data/BooleanFormat.java index f3ca4c5e731..055b934c504 100644 --- a/api/src/org/labkey/api/data/BooleanFormat.java +++ b/api/src/org/labkey/api/data/BooleanFormat.java @@ -17,6 +17,7 @@ package org.labkey.api.data; import org.jetbrains.annotations.Nullable; +import org.jetbrains.annotations.NotNull; import org.junit.Assert; import org.junit.Test; @@ -157,7 +158,7 @@ protected void setPattern(String pattern) * @return The string buffer passed in */ @Override - public StringBuffer format(Object obj, StringBuffer toAppendTo, FieldPosition pos) + public StringBuffer format(Object obj, @NotNull StringBuffer toAppendTo, @NotNull FieldPosition pos) { assert null != toAppendTo; @@ -214,7 +215,7 @@ public Boolean parseObject(String source) throws ParseException * @return A corresponding Boolean for source or null */ @Override - public Boolean parseObject(String source, ParsePosition pos) + public Boolean parseObject(String source, @NotNull ParsePosition pos) { if(null == source || source.isEmpty() || !Character.isLetterOrDigit(source.codePointAt(0))) { @@ -260,30 +261,30 @@ public void testFormat() { //default BooleanFormat fmt = new BooleanFormat(); - assertTrue(fmt.format(Boolean.TRUE).equals(BooleanFormat.DEFAULT_TRUE)); - assertTrue(fmt.format(Boolean.FALSE).equals(BooleanFormat.DEFAULT_FALSE)); - assertTrue(fmt.format(null).equals(BooleanFormat.DEFAULT_NULL)); + assertEquals(BooleanFormat.DEFAULT_TRUE, fmt.format(Boolean.TRUE)); + assertEquals(BooleanFormat.DEFAULT_FALSE, fmt.format(Boolean.FALSE)); + assertEquals(BooleanFormat.DEFAULT_NULL, fmt.format(null)); //various format strings fmt = new BooleanFormat("Y;N;(null)"); - assertTrue(fmt.format(Boolean.TRUE).equals("Y")); - assertTrue(fmt.format(Boolean.FALSE).equals("N")); - assertTrue(fmt.format(null).equals("(null)")); + assertEquals("Y", fmt.format(Boolean.TRUE)); + assertEquals("N", fmt.format(Boolean.FALSE)); + assertEquals("(null)", fmt.format(null)); fmt = new BooleanFormat("Y;N; "); - assertTrue(fmt.format(Boolean.TRUE).equals("Y")); - assertTrue(fmt.format(Boolean.FALSE).equals("N")); + assertEquals("Y", fmt.format(Boolean.TRUE)); + assertEquals("N", fmt.format(Boolean.FALSE)); assertTrue(fmt.format(null).isEmpty()); fmt = new BooleanFormat("Yes;No"); - assertTrue(fmt.format(Boolean.TRUE).equals("Yes")); - assertTrue(fmt.format(Boolean.FALSE).equals("No")); - assertTrue(fmt.format(null).equals(BooleanFormat.DEFAULT_NULL)); + assertEquals("Yes", fmt.format(Boolean.TRUE)); + assertEquals("No", fmt.format(Boolean.FALSE)); + assertEquals(BooleanFormat.DEFAULT_NULL, fmt.format(null)); fmt = new BooleanFormat("Yea"); - assertTrue(fmt.format(Boolean.TRUE).equals("Yea")); - assertTrue(fmt.format(Boolean.FALSE).equals(BooleanFormat.DEFAULT_FALSE)); - assertTrue(fmt.format(null).equals(BooleanFormat.DEFAULT_NULL)); + assertEquals("Yea", fmt.format(Boolean.TRUE)); + assertEquals(BooleanFormat.DEFAULT_FALSE, fmt.format(Boolean.FALSE)); + assertEquals(BooleanFormat.DEFAULT_NULL, fmt.format(null)); } @Test diff --git a/api/src/org/labkey/api/data/BuilderObjectFactory.java b/api/src/org/labkey/api/data/BuilderObjectFactory.java index e488eec8280..d326db6777a 100644 --- a/api/src/org/labkey/api/data/BuilderObjectFactory.java +++ b/api/src/org/labkey/api/data/BuilderObjectFactory.java @@ -187,7 +187,7 @@ public K fromMap(Map m) } catch (IllegalArgumentException x) { - _log.error("could not set property: " + name + "=" + value, x); + _log.error("could not set property: {}={}", name, value, x); } } diff --git a/api/src/org/labkey/api/data/ButtonBar.java b/api/src/org/labkey/api/data/ButtonBar.java index a025bb67ba7..ad11321bead 100644 --- a/api/src/org/labkey/api/data/ButtonBar.java +++ b/api/src/org/labkey/api/data/ButtonBar.java @@ -175,7 +175,7 @@ public boolean hasRequiresSelectionButton(RenderContext ctx) public DataRegion.ButtonBarPosition getConfiguredPosition() { if (_configs != null && !_configs.isEmpty()) - return _configs.get(_configs.size() - 1).getPosition(); + return _configs.getLast().getPosition(); return null; } diff --git a/api/src/org/labkey/api/data/ButtonBarConfig.java b/api/src/org/labkey/api/data/ButtonBarConfig.java index 1bd24d5d096..fd561c4bffc 100644 --- a/api/src/org/labkey/api/data/ButtonBarConfig.java +++ b/api/src/org/labkey/api/data/ButtonBarConfig.java @@ -301,7 +301,7 @@ private Class getPermission(ButtonBarItem item) } else { - LOG.warn("Specified permission class " + permissionClassName + " was not found"); + LOG.warn("Specified permission class {} was not found", permissionClassName); } return null; } diff --git a/api/src/org/labkey/api/data/CachedResultSet.java b/api/src/org/labkey/api/data/CachedResultSet.java index f363a448d23..e84bfced37d 100644 --- a/api/src/org/labkey/api/data/CachedResultSet.java +++ b/api/src/org/labkey/api/data/CachedResultSet.java @@ -204,7 +204,7 @@ private void close() } @Override - public @Nullable Connection getConnection() throws SQLException + public @Nullable Connection getConnection() { return null; } diff --git a/api/src/org/labkey/api/data/CompareType.java b/api/src/org/labkey/api/data/CompareType.java index b0a02723e61..8cb97bf3b9e 100644 --- a/api/src/org/labkey/api/data/CompareType.java +++ b/api/src/org/labkey/api/data/CompareType.java @@ -1102,12 +1102,6 @@ public void appendFilterText(StringBuilder sb, ColumnNameFormatter formatter) sb.append("IS NOT EMPTY"); } - @Override - public String getFilterOpText() - { - return null; - } - } private static class ArrayContainsAllClause extends ArrayClause diff --git a/api/src/org/labkey/api/data/ConditionalFormat.java b/api/src/org/labkey/api/data/ConditionalFormat.java index 19b5877042e..5b97fee2af1 100644 --- a/api/src/org/labkey/api/data/ConditionalFormat.java +++ b/api/src/org/labkey/api/data/ConditionalFormat.java @@ -207,7 +207,7 @@ public static String buildFilterQueryString(@Nullable ConditionalFormatFiltersTy if (compareType != null) simpleFilter.addClause(compareType.createFilterClause(FieldKey.fromParts(COLUMN_NAME), filter.getValue())); else - LOG.warn("Could not find CompareType for " + filter.getOperator() + ", ignoring"); + LOG.warn("Could not find CompareType for {}, ignoring", filter.getOperator()); } } } @@ -274,7 +274,7 @@ public static void convertToXML(List formats, Co ConditionalFormatsType xmlFormats = xmlColumn.addNewConditionalFormats(); if (!addToXML(formats, xmlFormats)) { - LOG.warn("One or more invalid conditional formats were discovered on table \"" + tableName + "\", column \"" + xmlColumn.getColumnName() + "\""); + LOG.warn("One or more invalid conditional formats were discovered on table \"{}\", column \"{}\"", tableName, xmlColumn.getColumnName()); } } } @@ -291,7 +291,7 @@ public static void convertToXML(List formats, Pr ConditionalFormatsType xmlFormats = xmlProp.addNewConditionalFormats(); if (!addToXML(formats, xmlFormats)) { - LOG.warn("One or more invalid conditional formats were discovered on property \"" + xmlProp.getName() + "\""); + LOG.warn("One or more invalid conditional formats were discovered on property \"{}\"", xmlProp.getName()); } } } diff --git a/api/src/org/labkey/api/data/ConnectionWrapper.java b/api/src/org/labkey/api/data/ConnectionWrapper.java index 097db7aecc9..5c251847424 100644 --- a/api/src/org/labkey/api/data/ConnectionWrapper.java +++ b/api/src/org/labkey/api/data/ConnectionWrapper.java @@ -103,7 +103,7 @@ public void run() { if (_connection != null && !_closed) { - _log.error("Connection was not closed! " + _wrapper.toString()); + _log.error("Connection was not closed! {}", _wrapper.toString()); realClose(); } } @@ -418,7 +418,7 @@ public String nativeSQL(String sql) throws SQLException public void setAutoCommit(boolean autoCommit) throws SQLException { checkForSuspiciousClose(); - _log.debug("SPID=" + getSPID() + " setAutoCommit(" + (autoCommit?"TRUE)":"FALSE)")); + _log.debug("SPID={} setAutoCommit({}", getSPID(), autoCommit ? "TRUE)" : "FALSE)"); try { _connection.setAutoCommit(autoCommit); @@ -447,7 +447,7 @@ public boolean getAutoCommit() throws SQLException public void commit() throws SQLException { checkForSuspiciousClose(); - _log.debug("SPID=" + getSPID() + " commit()"); + _log.debug("SPID={} commit()", getSPID()); try { _connection.commit(); @@ -642,7 +642,7 @@ public void setTransactionIsolation(int level) throws SQLException checkForSuspiciousClose(); try { - _log.debug("SPID=" + getSPID() + " setTransactionIsolation(" + level + ")"); + _log.debug("SPID={} setTransactionIsolation({})", getSPID(), level); _connection.setTransactionIsolation(level); } catch (SQLException e) @@ -1163,7 +1163,7 @@ private void log(ResultSet rs, String methodName, String message, long start) long duration = System.currentTimeMillis() - start; if (getLogger().isDebugEnabled()) - getLogger().debug(message + " " + DateUtil.formatDuration(duration)); + getLogger().debug("{} {}", message, DateUtil.formatDuration(duration)); QueryProfiler.getInstance().track(null, "DatabaseMetaData." + methodName, null, duration, MiniProfiler.getTroubleshootingStackTrace(), ViewServlet.isRequestThread(), QueryLogging.emptyQueryLogging()); diff --git a/api/src/org/labkey/api/data/Constraint.java b/api/src/org/labkey/api/data/Constraint.java index e62d2aabccb..c2fd95c9fed 100644 --- a/api/src/org/labkey/api/data/Constraint.java +++ b/api/src/org/labkey/api/data/Constraint.java @@ -20,7 +20,6 @@ import org.jetbrains.annotations.Nullable; import java.util.Collection; -import java.util.LinkedHashSet; /** * Models a database constraint on a particular table, such as a primary key or UNIQUE constraint. diff --git a/api/src/org/labkey/api/data/Container.java b/api/src/org/labkey/api/data/Container.java index 0a397c0340d..eab3c0db7c6 100644 --- a/api/src/org/labkey/api/data/Container.java +++ b/api/src/org/labkey/api/data/Container.java @@ -1458,7 +1458,7 @@ public void setType(String typeString) { ContainerType type = ContainerTypeRegistry.get().getType(typeString); if (type == null) - LOG.warn("Unknown container type: " + typeString); + LOG.warn("Unknown container type: {}", typeString); else _containerType = type; } @@ -1800,7 +1800,7 @@ public String getIconHref() iconFile = dir.getFile(); if (!NetworkDrive.exists(iconFile)) { - LOG.warn("Could not find specified icon: " + iconPath); + LOG.warn("Could not find specified icon: {}", iconPath); iconPath = FolderType.NONE.getFolderIconPath(); } if (!iconPath.startsWith("/")) diff --git a/api/src/org/labkey/api/data/ContainerManager.java b/api/src/org/labkey/api/data/ContainerManager.java index 121d82885f3..9e3363e8e80 100644 --- a/api/src/org/labkey/api/data/ContainerManager.java +++ b/api/src/org/labkey/api/data/ContainerManager.java @@ -55,7 +55,6 @@ import org.labkey.api.data.dialect.SqlDialect; import org.labkey.api.data.validator.ColumnValidators; import org.labkey.api.event.PropertyChange; -import org.labkey.api.exp.ExperimentException; import org.labkey.api.exp.api.ExperimentService; import org.labkey.api.module.FolderType; import org.labkey.api.module.FolderTypeManager; @@ -1712,14 +1711,7 @@ public static boolean move(Container c, final Container newParent, User user) th clearCache(); - try - { - ExperimentService.get().moveContainer(c, oldParent, newParent); - } - catch (ExperimentException e) - { - throw new RuntimeException(e); - } + ExperimentService.get().moveContainer(c, oldParent, newParent); // Clear after the commit has propagated the state to other threads and transactions // Do this in a commit task in case we've joined another existing DbScope.Transaction instead of starting our own @@ -2598,7 +2590,7 @@ private static Container resolveContainerPathAlias(String path, boolean top) if (aliased == null) return null; - String leafPath = aliased.getPath() + "/" + splits.get(splits.size()-1); + String leafPath = aliased.getPath() + "/" + splits.getLast(); return resolveContainerPathAlias(leafPath, true); } diff --git a/api/src/org/labkey/api/data/ContainerTable.java b/api/src/org/labkey/api/data/ContainerTable.java index 571cf6987e6..ffb3e9fb2ec 100644 --- a/api/src/org/labkey/api/data/ContainerTable.java +++ b/api/src/org/labkey/api/data/ContainerTable.java @@ -309,7 +309,7 @@ public Object getValue(RenderContext ctx) { ft = FolderType.NONE; iconPath = Path.parse(ft.getFolderIconPath()); - LogManager.getLogger(ContainerTable.class).warn("Could not find specified icon: "+iconPath); + LogManager.getLogger(ContainerTable.class).warn("Could not find specified icon: {}", iconPath); } return AppProps.getInstance().getContextPath() + iconPath.toString("/",""); } diff --git a/api/src/org/labkey/api/data/ConvertHelper.java b/api/src/org/labkey/api/data/ConvertHelper.java index 516c30dbc57..39ac924633a 100644 --- a/api/src/org/labkey/api/data/ConvertHelper.java +++ b/api/src/org/labkey/api/data/ConvertHelper.java @@ -77,7 +77,6 @@ import java.io.File; import java.math.BigDecimal; import java.math.BigInteger; -import java.sql.Array; import java.sql.Blob; import java.sql.Clob; import java.sql.SQLException; diff --git a/api/src/org/labkey/api/data/CrosstabDataRegion.java b/api/src/org/labkey/api/data/CrosstabDataRegion.java index 624444804f8..167a3ee7011 100644 --- a/api/src/org/labkey/api/data/CrosstabDataRegion.java +++ b/api/src/org/labkey/api/data/CrosstabDataRegion.java @@ -78,7 +78,7 @@ protected void renderGridHeaderColumns(RenderContext ctx, HtmlWriter out, boolea List>> groupedByMember = CrosstabView.columnsByMember(renderers); // Output a group header for each column's crosstab member. - CrosstabDimension colDim = _settings.getColumnAxis().getDimensions().get(0); + CrosstabDimension colDim = _settings.getColumnAxis().getDimensions().getFirst(); boolean alternate = true; for (Pair> group : groupedByMember) { diff --git a/api/src/org/labkey/api/data/CrosstabMeasure.java b/api/src/org/labkey/api/data/CrosstabMeasure.java index b77371082e1..d7043b3b661 100644 --- a/api/src/org/labkey/api/data/CrosstabMeasure.java +++ b/api/src/org/labkey/api/data/CrosstabMeasure.java @@ -95,16 +95,12 @@ public String getSqlFunction(SqlDialect dialect) @NotNull public JdbcType getAggregateSqlType(ColumnInfo sourceCol) { - switch(this) + return switch (this) { - case COUNT: - return JdbcType.BIGINT; - case AVG: - case STDDEV: - return JdbcType.DECIMAL; - default: - return sourceCol.getJdbcType(); - } + case COUNT -> JdbcType.BIGINT; + case AVG, STDDEV -> JdbcType.DECIMAL; + default -> sourceCol.getJdbcType(); + }; } public SQLFragment getSqlExpression(SqlDialect sqlDialect, SQLFragment columnSQL) diff --git a/api/src/org/labkey/api/data/CrosstabTable.java b/api/src/org/labkey/api/data/CrosstabTable.java index 296f3ba89f7..b3036f27d71 100644 --- a/api/src/org/labkey/api/data/CrosstabTable.java +++ b/api/src/org/labkey/api/data/CrosstabTable.java @@ -405,19 +405,19 @@ protected Map addAggQuery(SQLFragment sql) protected String getMemberInstanceCountAlias(CrosstabMember member) { - return getSettings().getColumnAxis().getDimensions().get(0).getSourceColumn().getAlias().getId() + return getSettings().getColumnAxis().getDimensions().getFirst().getSourceColumn().getAlias().getId() + member.getValueSQLAlias(getSqlDialect()) + COL_INSTANCE_COUNT; } protected String getMemberSortPatternAlias(CrosstabMember member) { - return getSettings().getColumnAxis().getDimensions().get(0).getSourceColumn().getAlias().getId() + return getSettings().getColumnAxis().getDimensions().getFirst().getSourceColumn().getAlias().getId() + member.getValueSQLAlias(getSqlDialect()) + COL_SORT_PATTERN; } protected void addMemberCase(SQLFragment sql, CrosstabMember member, String queryAlias, String ifSql, String elseSql, String alias) { - CrosstabDimension colDimension = getSettings().getColumnAxis().getDimensions().get(0); + CrosstabDimension colDimension = getSettings().getColumnAxis().getDimensions().getFirst(); sql.append("(CASE WHEN "); sql.appendDottedIdentifiers(queryAlias, colDimension.getSourceColumn().getAlias()); diff --git a/api/src/org/labkey/api/data/DataColumn.java b/api/src/org/labkey/api/data/DataColumn.java index e6f2b90a50d..b01f2ef5862 100644 --- a/api/src/org/labkey/api/data/DataColumn.java +++ b/api/src/org/labkey/api/data/DataColumn.java @@ -756,7 +756,7 @@ private void renderSelectFormInput(HtmlWriter out, String formFieldName, Object options.add(new OptionBuilder().build()); Set selectedValues = strValues.isEmpty() ? Set.of() : - strValues.size()==1 ? (null == strValues.get(0) ? Set.of() : Set.of(strValues.get(0))) : + strValues.size()==1 ? (null == strValues.getFirst() ? Set.of() : Set.of(strValues.getFirst())) : new HashSet<>(strValues); for (NamedObject entry : entryList) { diff --git a/api/src/org/labkey/api/data/DataIteratorResultsImpl.java b/api/src/org/labkey/api/data/DataIteratorResultsImpl.java index 1f5213837d8..1943c4632ff 100644 --- a/api/src/org/labkey/api/data/DataIteratorResultsImpl.java +++ b/api/src/org/labkey/api/data/DataIteratorResultsImpl.java @@ -146,7 +146,7 @@ public Map getRowMap() } @Override - public @NotNull Connection getConnection() throws SQLException + public @NotNull Connection getConnection() { throw new UnsupportedOperationException(); } diff --git a/api/src/org/labkey/api/data/DataRegion.java b/api/src/org/labkey/api/data/DataRegion.java index ac454282646..5a6ea88828a 100644 --- a/api/src/org/labkey/api/data/DataRegion.java +++ b/api/src/org/labkey/api/data/DataRegion.java @@ -81,7 +81,6 @@ import java.io.IOException; import java.io.StringWriter; import java.sql.ResultSet; -import java.sql.ResultSetMetaData; import java.sql.SQLException; import java.util.ArrayList; import java.util.Arrays; @@ -857,7 +856,7 @@ public Map> getAggregateResults(RenderContext ctx //Issue 14863: add null check if (result != null && !result.isEmpty()) { - Aggregate.Result countStarResult = result.get(0); + Aggregate.Result countStarResult = result.getFirst(); _totalRows = 0L; if (countStarResult.getValue() instanceof Number) _totalRows = ((Number) countStarResult.getValue()).longValue(); @@ -2281,11 +2280,11 @@ private void renderForm(RenderContext ctx, HtmlWriter out) //Make sure all pks are included if (action == MODE_UPDATE) { - int span = (_groupTables.isEmpty() || _groupTables.get(0).getGroups().isEmpty()) ? + int span = (_groupTables.isEmpty() || _groupTables.getFirst().getGroups().isEmpty()) ? 1 : (_horizontalGroups ? - _groupTables.get(0).getGroups().get(0).getColumns().size() + 1 : - _groupTables.get(0).getGroups().size()); // One extra one for the column to reuse the same value + _groupTables.getFirst().getGroups().getFirst().getColumns().size() + 1 : + _groupTables.getFirst().getGroups().size()); // One extra one for the column to reuse the same value TR( TD( @@ -2380,7 +2379,7 @@ private void renderForm(RenderContext ctx, HtmlWriter out) TD(), (Renderable) ret -> { for (DisplayColumnGroup group : groups) - writeColRenderDetailsCaptionCell(ctx, out, group.getColumns().get(0)); + writeColRenderDetailsCaptionCell(ctx, out, group.getColumns().getFirst()); return ret; } ).appendTo(out); @@ -2413,7 +2412,7 @@ private void renderForm(RenderContext ctx, HtmlWriter out) { TR( (Renderable) ret -> { - writeColRenderDetailsCaptionCell(ctx, out, group.getColumns().get(0)); + writeColRenderDetailsCaptionCell(ctx, out, group.getColumns().getFirst()); if (group.isCopyable() && hasCopyableFinal) { group.writeSameCheckboxCell(ctx, out); @@ -2694,7 +2693,7 @@ private void prepareFilters(RenderContext ctx) // 4. If there are multiple (and maybe even if not) then show the FieldKey.toString() // in the tooltip hover so the user has a chance to disambiguate. - FieldKey filterKey = fieldKeys.get(0); + FieldKey filterKey = fieldKeys.getFirst(); if (filterKey != null) { @@ -2946,7 +2945,7 @@ public void setGroupHeadings(List headings) { if (_groupTables.isEmpty()) addGroupTable(); - _groupTables.get(_groupTables.size() - 1).setGroupHeadings(headings); + _groupTables.getLast().setGroupHeadings(headings); } public boolean getShowPagination() @@ -3040,8 +3039,8 @@ public void addGroup(DisplayColumnGroup group) { if (_groupTables.isEmpty()) addGroupTable(); - List groups = _groupTables.get(_groupTables.size() - 1).getGroups(); // always add to last (current) - assert groups.isEmpty() || groups.get(0).getColumns().size() == group.getColumns().size() : "Must have matching column counts"; + List groups = _groupTables.getLast().getGroups(); // always add to last (current) + assert groups.isEmpty() || groups.getFirst().getColumns().size() == group.getColumns().size() : "Must have matching column counts"; groups.add(group); } diff --git a/api/src/org/labkey/api/data/DataRegionSelection.java b/api/src/org/labkey/api/data/DataRegionSelection.java index acdf4b5c976..df5573b9c0b 100644 --- a/api/src/org/labkey/api/data/DataRegionSelection.java +++ b/api/src/org/labkey/api/data/DataRegionSelection.java @@ -533,7 +533,7 @@ private static Set getSelectedItems(QueryView view, @NotNull Collection< List pkCols = rgn.getTable().getPkColumns(); if (pkCols.size() == 1) { - ColumnInfo pkCol = pkCols.get(0); + ColumnInfo pkCol = pkCols.getFirst(); ctx.setBaseFilter(new SimpleFilter(pkCol.getFieldKey(), pkCol.isNumericType() ? selectedValues.stream().map(Integer::parseInt).toList() : selectedValues, CompareType.IN)); } diff --git a/api/src/org/labkey/api/data/DatabaseCache.java b/api/src/org/labkey/api/data/DatabaseCache.java index b9c0c367cfb..164cbc126d6 100644 --- a/api/src/org/labkey/api/data/DatabaseCache.java +++ b/api/src/org/labkey/api/data/DatabaseCache.java @@ -540,7 +540,7 @@ private MyScope() } @Override - public ConnectionWrapper getPooledConnection(ConnectionType type, Logger log) throws SQLException + public ConnectionWrapper getPooledConnection(ConnectionType type, Logger log) { return new ConnectionWrapper(null, null, null, type, log) { diff --git a/api/src/org/labkey/api/data/DbSchema.java b/api/src/org/labkey/api/data/DbSchema.java index c081519eb74..d6422b84ab4 100644 --- a/api/src/org/labkey/api/data/DbSchema.java +++ b/api/src/org/labkey/api/data/DbSchema.java @@ -239,7 +239,7 @@ protected TableMetaDataLoader(JdbcMetaDataLocator locator, boolean ignoreTemp) _ignoreTemp = ignoreTemp; } - protected abstract void handleTable(String tableName, DatabaseTableType tableType, String description) throws SQLException; + protected abstract void handleTable(String tableName, DatabaseTableType tableType, String description); protected T getReturnValue() {return null;} @@ -289,7 +289,7 @@ public T load() throws SQLException } catch (IllegalArgumentException e) { - _log.error("Malformed XML in " + ti.getSchema() + "." + xmlTable.getTableName(), e); + _log.error("Malformed XML in {}.{}", ti.getSchema(), xmlTable.getTableName(), e); } } @@ -733,7 +733,7 @@ private static Integer checkContainerColumns(DbSchema curSchema, SQLFragment sbS if (pkColumns.size() == 1) { - ColumnInfo pkColumn = pkColumns.get(0); + ColumnInfo pkColumn = pkColumns.getFirst(); sbSql.appendValue(pkColumn.getSelectIdentifier().getId()); sbSql.append(" AS FirstPKColName, "); sbSql.append(" CAST( ").appendDottedIdentifiers(t.getSelectName(),pkColumn.getSelectIdentifier()).append(" AS VARCHAR(100)) AS FirstPKValue, "); diff --git a/api/src/org/labkey/api/data/DbScope.java b/api/src/org/labkey/api/data/DbScope.java index e148df203fa..89937b7bff5 100644 --- a/api/src/org/labkey/api/data/DbScope.java +++ b/api/src/org/labkey/api/data/DbScope.java @@ -607,19 +607,7 @@ private static LabKeyDataSource setPrimaryDataSource(Map 2) - LOG.info("Transaction stack for thread '" + getEffectiveThread().getName() + "' is " + stackDepth); + LOG.info("Transaction stack for thread '{}' is {}", getEffectiveThread().getName(), stackDepth); } finally { @@ -1881,7 +1869,7 @@ private static void detectOtherLabKeyInstances(Connection conn, LabKeyDataSource } } - private static void detectUnexpectedConnections(Connection conn, LabKeyDataSource ds, String applicationName) throws ServletException, SQLException + private static void detectUnexpectedConnections(Connection conn, LabKeyDataSource ds, String applicationName) throws ServletException { SqlDialect dialect = ds.getDialect(); String databaseName = dialect.getDatabaseName(ds.getUrl()); @@ -1952,11 +1940,11 @@ private static void detectUnexpectedConnections(Connection conn, LabKeyDataSourc { // Set LabKey's default application name ("LabKey Server") into the connection properties applicationName = ds.setDefaultApplicationName(); - LOG.info(message + " (the default name); all subsequent connections will use \"" + applicationName + "\" instead."); + LOG.info("{} (the default name); all subsequent connections will use \"{}\" instead.", message, applicationName); } else { - LOG.info(message + "; this will continue to be used on all subsequent connections."); + LOG.info("{}; this will continue to be used on all subsequent connections.", message); } } else @@ -1966,7 +1954,7 @@ private static void detectUnexpectedConnections(Connection conn, LabKeyDataSourc } catch (SQLException e) { - LOG.warn("Attempt to determine application name failed: " + e.getMessage()); + LOG.warn("Attempt to determine application name failed: {}", e.getMessage()); applicationName = ds.setDefaultApplicationName(); } } @@ -2180,7 +2168,7 @@ public static void closeAllConnectionsForCurrentThread() if (count++ > 100) { // Avoid getting into an infinite loop if someone's messed up the transaction stack - LOG.error("Aborting trying to close connections after processing " + count + " transaction objects"); + LOG.error("Aborting trying to close connections after processing {} transaction objects", count); break; } try @@ -2194,7 +2182,7 @@ public static void closeAllConnectionsForCurrentThread() } catch (Exception x) { - LOG.error("Failed to force the still-pending transaction object closed on DB scope " + scope, x); + LOG.error("Failed to force the still-pending transaction object closed on DB scope {}", scope, x); } // We may have nested concurrent transactions for a given scope, so be sure we close them all @@ -2426,7 +2414,7 @@ public T add(TransactionImpl transaction, T task) T existing = (T)runnables.putIfAbsent(task, task); if (existing != null) { - LOG.debug("Skipping duplicate runnable: " + task.toString()); + LOG.debug("Skipping duplicate runnable: {}", task.toString()); } return existing == null ? task : existing; } @@ -2535,7 +2523,7 @@ private void popCurrentTransaction() synchronized (_transaction) { List transactions = _transaction.get(thread); - transactions.remove(transactions.size() - 1); + transactions.removeLast(); if (transactions.isEmpty()) { _transaction.remove(thread); @@ -3095,7 +3083,7 @@ public void testMultiScopeTransaction() throws SQLException TableInfo table = schema.getTable(name); if (null == table) - LOG.error("Table is null: " + schema.getName() + "." + name); + LOG.error("Table is null: {}.{}", schema.getName(), name); else if (table.getTableType() != DatabaseTableType.NOT_IN_DB) return table; } diff --git a/api/src/org/labkey/api/data/DbScopeLoader.java b/api/src/org/labkey/api/data/DbScopeLoader.java index c1589fe9ff6..a7d0fafe5a3 100644 --- a/api/src/org/labkey/api/data/DbScopeLoader.java +++ b/api/src/org/labkey/api/data/DbScopeLoader.java @@ -76,7 +76,7 @@ void clearDbScope() catch (Throwable t) { // Always log, but callers determine if null DbScope is fatal or not - LOG.error("Cannot connect to DataSource \"" + getDsName() + "\" defined in " + AppProps.getInstance().getWebappConfigurationFilename() + ". This DataSource will not be available during this server session unless a successful retry is initiated from the schema administration page.", t); + LOG.error("Cannot connect to DataSource \"{}\" defined in {}. This DataSource will not be available during this server session unless a successful retry is initiated from the schema administration page.", getDsName(), AppProps.getInstance().getWebappConfigurationFilename(), t); DbScope.addDataSourceFailure(getDsName(), t); scope = BAD_SCOPE; } diff --git a/api/src/org/labkey/api/data/DisplayColumnGroup.java b/api/src/org/labkey/api/data/DisplayColumnGroup.java index 47893aecb35..202063d4407 100644 --- a/api/src/org/labkey/api/data/DisplayColumnGroup.java +++ b/api/src/org/labkey/api/data/DisplayColumnGroup.java @@ -93,7 +93,7 @@ public void writeSameCheckboxCell(RenderContext ctx, HtmlWriter out) /** Use propName because DOM ids and function names can't have spaces */ private String getGroupFormFieldName(RenderContext ctx) { - return PageConfig.makeIdFromName(getColumns().get(0).getFormFieldName(ctx)); + return PageConfig.makeIdFromName(getColumns().getFirst().getFormFieldName(ctx)); } public void writeCopyableJavaScript(RenderContext ctx, Writer out) throws IOException @@ -107,10 +107,10 @@ public void writeCopyableJavaScript(RenderContext ctx, Writer out) throws IOExce out.write("function " + groupName + "Updated() {\n"); out.write(" if (document.getElementById('" + groupName + "CheckBox') != null && document.getElementById('" + groupName + "CheckBox').checked) {\n"); - if (getColumns().get(0).getColumnInfo() != null) + if (getColumns().getFirst().getColumnInfo() != null) { String valueProperty = "value"; - String inputType = getColumns().get(0).getColumnInfo().getInputType(); + String inputType = getColumns().getFirst().getColumnInfo().getInputType(); if ("select".equalsIgnoreCase(inputType)) { valueProperty = "selectedIndex"; @@ -119,7 +119,7 @@ else if ("checkbox".equalsIgnoreCase(inputType)) { valueProperty = "checked"; } - out.write(" var v = document.getElementsByName('" + getColumns().get(0).getFormFieldName(ctx) + "')[0]." + valueProperty + ";\n"); + out.write(" var v = document.getElementsByName('" + getColumns().getFirst().getFormFieldName(ctx) + "')[0]." + valueProperty + ";\n"); for (int i = 1; i < getColumns().size(); i++) { out.write(" document.getElementsByName('" + getColumns().get(i).getFormFieldName(ctx) + "')[0]." + valueProperty + " = v;\n"); @@ -128,7 +128,7 @@ else if ("checkbox".equalsIgnoreCase(inputType)) out.write(" }\n"); out.write("}\n"); - out.write("var e = document.getElementsByName('" + getColumns().get(0).getFormFieldName(ctx) + "');\n"); + out.write("var e = document.getElementsByName('" + getColumns().getFirst().getFormFieldName(ctx) + "');\n"); out.write("if (e.length > 0) {"); out.write(" e[0].onchange=" + groupName + "Updated;\n"); out.write(" e[0].onkeyup=" + groupName + "Updated;\n"); diff --git a/api/src/org/labkey/api/data/ExcelColumn.java b/api/src/org/labkey/api/data/ExcelColumn.java index bd869f07578..062cbec6e7b 100644 --- a/api/src/org/labkey/api/data/ExcelColumn.java +++ b/api/src/org/labkey/api/data/ExcelColumn.java @@ -183,7 +183,7 @@ private void setSimpleType(DisplayColumn dc) if (_simpleType == ExcelCellUtils.TYPE_UNKNOWN) { Class valueClass = dc.getDisplayValueClass(); - _log.error("init: Unknown Class " + valueClass + " " + getName()); + _log.error("init: Unknown Class {} {}", valueClass, getName()); } } @@ -385,13 +385,13 @@ else if (_simpleType == ExcelCellUtils.TYPE_BOOLEAN) } catch(ClassCastException cce) { - _log.error("Can't cast '" + o + "', class '" + o.getClass().getName() + "', to class corresponding to simple type '" + _simpleType + "'"); - _log.error("DisplayColumn.getCaption(): " + _dc.getCaption()); - _log.error("DisplayColumn.getClass().getName(): " + _dc.getClass().getName()); - _log.error("DisplayColumn.getDisplayValueClass(): " + _dc.getDisplayValueClass()); - _log.error("DisplayColumn.getValueClass(): " + _dc.getValueClass()); - _log.error("DisplayColumn.getColumnInfo().getJdbcType(): " + columnInfo.getJdbcType()); - _log.error("DisplayColumn.getColumnInfo().getSqlTypeName(): " + columnInfo.getSqlTypeName()); + _log.error("Can't cast '{}', class '{}', to class corresponding to simple type '{}'", o, o.getClass().getName(), _simpleType); + _log.error("DisplayColumn.getCaption(): {}", _dc.getCaption()); + _log.error("DisplayColumn.getClass().getName(): {}", _dc.getClass().getName()); + _log.error("DisplayColumn.getDisplayValueClass(): {}", _dc.getDisplayValueClass()); + _log.error("DisplayColumn.getValueClass(): {}", _dc.getValueClass()); + _log.error("DisplayColumn.getColumnInfo().getJdbcType(): {}", columnInfo.getJdbcType()); + _log.error("DisplayColumn.getColumnInfo().getSqlTypeName(): {}", columnInfo.getSqlTypeName()); throw cce; } diff --git a/api/src/org/labkey/api/data/FileSqlScriptProvider.java b/api/src/org/labkey/api/data/FileSqlScriptProvider.java index 43c42fd904a..7b6af36498a 100644 --- a/api/src/org/labkey/api/data/FileSqlScriptProvider.java +++ b/api/src/org/labkey/api/data/FileSqlScriptProvider.java @@ -323,7 +323,7 @@ public FileSqlScript(FileSqlScriptProvider provider, @Nullable DbSchema schema, { _schema = null; if (!fileName.endsWith("-create.sql") && !fileName.endsWith("-drop.sql")) - _log.info(provider.getProviderName() + ", ignoring file " + fileName + ": wrong format"); + _log.info("{}, ignoring file {}: wrong format", provider.getProviderName(), fileName); return; } @@ -345,7 +345,7 @@ public FileSqlScript(FileSqlScriptProvider provider, @Nullable DbSchema schema, } catch (NumberFormatException x) { - _log.info(_provider.getProviderName() + ", ignoring file " + fileName + ": couldn't parse version numbers"); + _log.info("{}, ignoring file {}: couldn't parse version numbers", _provider.getProviderName(), fileName); return; } @@ -363,7 +363,7 @@ public FileSqlScript(FileSqlScriptProvider provider, @Nullable DbSchema schema, throw new IllegalStateException("SQL scripts and null schema version do not compute"); if (_toVersion > schemaVersion) - _log.warn(fileName + " will never execute because " + _provider._module.getName() + " schema version is less than this script's \"to\" version"); + _log.warn("{} will never execute because {} schema version is less than this script's \"to\" version", fileName, _provider._module.getName()); } // Used for DROP and CREATE scripts... so we don't bother verifying filename or parsing info from it diff --git a/api/src/org/labkey/api/data/HtmlDisplayColumnFactory.java b/api/src/org/labkey/api/data/HtmlDisplayColumnFactory.java index cd38406c046..9607fd02626 100644 --- a/api/src/org/labkey/api/data/HtmlDisplayColumnFactory.java +++ b/api/src/org/labkey/api/data/HtmlDisplayColumnFactory.java @@ -55,7 +55,7 @@ public HtmlString getFormattedHtml(RenderContext ctx) if (errors.isEmpty()) return HtmlString.unsafe(tidyHtml); else - return HtmlString.of(errors.get(0)); + return HtmlString.of(errors.getFirst()); } } } diff --git a/api/src/org/labkey/api/data/ImportAliasable.java b/api/src/org/labkey/api/data/ImportAliasable.java index def16557b9a..d8c26135cfc 100644 --- a/api/src/org/labkey/api/data/ImportAliasable.java +++ b/api/src/org/labkey/api/data/ImportAliasable.java @@ -76,7 +76,7 @@ public static Map createImportMap(List // Reverse the order of the descriptors so that we can preserve the right priority for resolving by names, aliases, etc for (T prop : properties) { - reversedProperties.add(0, prop); + reversedProperties.addFirst(prop); } // PropertyURI is lowest priority, so put it in the map first so it will be overwritten by higher priority usages diff --git a/api/src/org/labkey/api/data/JdbcType.java b/api/src/org/labkey/api/data/JdbcType.java index 771dc7387aa..7d1bef55799 100644 --- a/api/src/org/labkey/api/data/JdbcType.java +++ b/api/src/org/labkey/api/data/JdbcType.java @@ -688,25 +688,17 @@ public Object convert(CharSequence cs) throws ConversionException public static Object add(@NotNull Object obj1, @NotNull Object obj2, JdbcType type) { - switch (type) - { - case BIGINT: - return ConvertHelper.convert(obj1, Long.class) + ConvertHelper.convert(obj2, Long.class); - case DECIMAL: - return ConvertHelper.convert(obj1, BigDecimal.class).add(ConvertHelper.convert(obj2, BigDecimal.class)); - case DOUBLE: - return ConvertHelper.convert(obj1, Double.class) + ConvertHelper.convert(obj2, Double.class); - case INTEGER: - return ConvertHelper.convert(obj1, Integer.class) + ConvertHelper.convert(obj2, Integer.class); - case REAL: - return ConvertHelper.convert(obj1, Float.class) + ConvertHelper.convert(obj2, Float.class); - case SMALLINT: - return ConvertHelper.convert(obj1, Short.class) + ConvertHelper.convert(obj2, Short.class); - case TINYINT: - return ConvertHelper.convert(obj1, Short.class) + ConvertHelper.convert(obj2, Short.class); - default: - throw new IllegalStateException("Cannot add non-numeric objects."); - } + return switch (type) + { + case BIGINT -> ConvertHelper.convert(obj1, Long.class) + ConvertHelper.convert(obj2, Long.class); + case DECIMAL -> ConvertHelper.convert(obj1, BigDecimal.class).add(ConvertHelper.convert(obj2, BigDecimal.class)); + case DOUBLE -> ConvertHelper.convert(obj1, Double.class) + ConvertHelper.convert(obj2, Double.class); + case INTEGER -> ConvertHelper.convert(obj1, Integer.class) + ConvertHelper.convert(obj2, Integer.class); + case REAL -> ConvertHelper.convert(obj1, Float.class) + ConvertHelper.convert(obj2, Float.class); + case SMALLINT -> ConvertHelper.convert(obj1, Short.class) + ConvertHelper.convert(obj2, Short.class); + case TINYINT -> ConvertHelper.convert(obj1, Short.class) + ConvertHelper.convert(obj2, Short.class); + default -> throw new IllegalStateException("Cannot add non-numeric objects."); + }; } protected Object _fromNumber(Number n) diff --git a/api/src/org/labkey/api/data/JsonWriter.java b/api/src/org/labkey/api/data/JsonWriter.java index be24261e652..b6666cc50b5 100644 --- a/api/src/org/labkey/api/data/JsonWriter.java +++ b/api/src/org/labkey/api/data/JsonWriter.java @@ -413,10 +413,7 @@ public static JSONObject getLookupInfo(ColumnInfo columnInfo, boolean includeDom TableInfo parentTable = columnInfo.getParentTable(); UserSchema userSchema = parentTable.getUserSchema(); String containerInfo = userSchema == null ? "" : " in container " + userSchema.getContainer().getPath(); - LOG.warn("Unable to resolve column '" + key + "' on lookup target " + schemaName + "." + - queryName + " referenced by column '" + columnInfo.getName() + "' from table " + - parentTable.getPublicSchemaName() + "." + parentTable.getPublicName() + containerInfo + - ". Using the table's PK instead"); + LOG.warn("Unable to resolve column '{}' on lookup target {}.{} referenced by column '{}' from table {}.{}{}. Using the table's PK instead", key, schemaName, queryName, columnInfo.getName(), parentTable.getPublicSchemaName(), parentTable.getPublicName(), containerInfo); key = null; } } diff --git a/api/src/org/labkey/api/data/MultiChoice.java b/api/src/org/labkey/api/data/MultiChoice.java index d46d506a5ad..d555408bb43 100644 --- a/api/src/org/labkey/api/data/MultiChoice.java +++ b/api/src/org/labkey/api/data/MultiChoice.java @@ -558,7 +558,7 @@ public int lastIndexOf(Object o) // @Override - public void free() throws SQLException + public void free() { } @@ -576,49 +576,49 @@ public int getBaseType() } @Override - public Object getArray() throws SQLException + public Object getArray() { return toArray(new String[size()]); } @Override - public Object getArray(Map> map) throws SQLException + public Object getArray(Map> map) { return toArray(new String[size()]); } @Override - public Object getArray(long index, int count) throws SQLException + public Object getArray(long index, int count) { return subList((int) index, (int) index + count).toArray(new String[0]); } @Override - public Object getArray(long index, int count, Map> map) throws SQLException + public Object getArray(long index, int count, Map> map) { return subList((int) index, (int) index + count).toArray(new String[0]); } @Override - public ResultSet getResultSet() throws SQLException + public ResultSet getResultSet() { throw new UnsupportedOperationException(); } @Override - public ResultSet getResultSet(Map> map) throws SQLException + public ResultSet getResultSet(Map> map) { throw new UnsupportedOperationException(); } @Override - public ResultSet getResultSet(long index, int count) throws SQLException + public ResultSet getResultSet(long index, int count) { throw new UnsupportedOperationException(); } @Override - public ResultSet getResultSet(long index, int count, Map> map) throws SQLException + public ResultSet getResultSet(long index, int count, Map> map) { throw new UnsupportedOperationException(); } @@ -773,7 +773,7 @@ public void testCSV() throws Exception { var maps = csvLoader.load(); assertEquals(1, maps.size()); - Map map = maps.get(0); + Map map = maps.getFirst(); assertTrue(map.get("column") instanceof String); String value = (String) map.get("column"); assertEquals(expected, Array.from(value)); @@ -782,7 +782,7 @@ public void testCSV() throws Exception { var maps = tsvLoader.load(); assertEquals(1, maps.size()); - Map map = maps.get(0); + Map map = maps.getFirst(); assertTrue(map.get("column") instanceof String); String value = (String) map.get("column"); assertEquals(expected, Array.from(value)); diff --git a/api/src/org/labkey/api/data/MultiValuedDisplayColumn.java b/api/src/org/labkey/api/data/MultiValuedDisplayColumn.java index 63923431091..4983248c5a2 100644 --- a/api/src/org/labkey/api/data/MultiValuedDisplayColumn.java +++ b/api/src/org/labkey/api/data/MultiValuedDisplayColumn.java @@ -66,7 +66,7 @@ public MultiValuedDisplayColumn(DisplayColumn dc, boolean boundColumnIsNotMultiV lookupCol = childKeyFk.createLookupColumn(childKey, childKeyFk.getLookupColumnName()); if (lookupCol == null) { - LOG.warn("Failed to create lookup column from '" + childKey.getName() + "' to '" + childKeyFk.getLookupSchemaName() + "." + childKeyFk.getLookupTableName() + "." + childKeyFk.getLookupColumnName() + "'"); + LOG.warn("Failed to create lookup column from '{}' to '{}.{}.{}'", childKey.getName(), childKeyFk.getLookupSchemaName(), childKeyFk.getLookupTableName(), childKeyFk.getLookupColumnName()); } else { diff --git a/api/src/org/labkey/api/data/MultiValuedRenderContext.java b/api/src/org/labkey/api/data/MultiValuedRenderContext.java index 20746d971eb..b3b522c1a19 100644 --- a/api/src/org/labkey/api/data/MultiValuedRenderContext.java +++ b/api/src/org/labkey/api/data/MultiValuedRenderContext.java @@ -15,11 +15,9 @@ */ package org.labkey.api.data; -import org.apache.commons.beanutils.ConvertUtils; import org.apache.commons.collections4.iterators.ArrayIterator; import org.junit.Assert; import org.junit.Test; -import org.labkey.api.exp.PropertyType; import org.labkey.api.query.FieldKey; import java.util.HashMap; diff --git a/api/src/org/labkey/api/data/NameGenerator.java b/api/src/org/labkey/api/data/NameGenerator.java index dc2801d40bd..1697902e92a 100644 --- a/api/src/org/labkey/api/data/NameGenerator.java +++ b/api/src/org/labkey/api/data/NameGenerator.java @@ -702,7 +702,7 @@ else if (nextClose > nextOpen) if (!unmatchedOpen.isEmpty()) { if (unmatchedOpen.size() == 1) - errors.add("No closing brace found for the substitution pattern starting at position " + unmatchedOpen.get(0) + "."); + errors.add("No closing brace found for the substitution pattern starting at position " + unmatchedOpen.getFirst() + "."); else errors.add("No closing braces found for the substitution patterns starting at positions " + StringUtils.join(unmatchedOpen, ", ") + "."); } @@ -809,7 +809,7 @@ public static boolean isParentInput(Object token, @NotNull CaseInsensitiveHashMa public static boolean isParentLookup(List fieldParts, @NotNull CaseInsensitiveHashMap importAliases, @Nullable String currentDataTypeName, Container container, User user) { - if (!isParentInputToken(fieldParts.get(0), importAliases, false)) + if (!isParentInputToken(fieldParts.getFirst(), importAliases, false)) return false; return fieldParts.size() != 2 || !isParentInputWithDataType(fieldParts.toArray(String[]::new), currentDataTypeName, false, container, user); @@ -817,13 +817,13 @@ public static boolean isParentLookup(List fieldParts, @NotNull CaseInsen public static boolean isAncestorSearch(List fieldParts, @NotNull CaseInsensitiveHashMap importAliases, Container container, User user) { - if (!fieldParts.get(0).startsWith("~")) + if (!fieldParts.getFirst().startsWith("~")) return false; if (fieldParts.size() == 1) - return importAliases.containsKey(fieldParts.get(0).substring(1)); + return importAliases.containsKey(fieldParts.getFirst().substring(1)); - if (!isParentInputToken(fieldParts.get(0), null, true)) + if (!isParentInputToken(fieldParts.getFirst(), null, true)) return false; return fieldParts.size() <= 3 && isParentInputWithDataType(fieldParts.subList(0, 2).toArray(String[]::new), null,true, container, user); @@ -911,7 +911,7 @@ private Object getParentLookupTokenPreview(String currentDataType, FieldKey fkTo else if (ancestorPaths != null && !ancestorPaths.isEmpty()) { isAncestor = true; - Pair ancestorType = ancestorPaths.get(ancestorPaths.size() - 1); + Pair ancestorType = ancestorPaths.getLast(); isMaterial = ExpLineageOptions.LineageExpType.Material == ancestorType.first; isData = ExpLineageOptions.LineageExpType.Data == ancestorType.first; if (!StringUtils.isEmpty(ancestorType.second)) @@ -1205,7 +1205,7 @@ private void initialize(@Nullable Map importAliasesMap) if (_validateSyntax) { - String fieldName = fieldParts.get(0); + String fieldName = fieldParts.getFirst(); if (isParentInputToken(fieldName, null, true)) _syntaxErrors.add("Invalid substitution token. Ancestor " + (fieldName.toLowerCase().contains("material") ? "sample type" : "dataclass") + " must be specified in lineage search syntax: ${" + fieldName + "}."); else if (!substitutionValues.contains(fieldName) && !isParentPart) @@ -1247,7 +1247,7 @@ else if (pt != null) String fieldKeyDisplay = QueryKey.decodePart(fkTok.toString()); if (isParentLookup || isAncestorSearch) { - String alias = fieldParts.get(0); + String alias = fieldParts.getFirst(); boolean isParentAlias = importAliasFieldKeys != null && importAliasFieldKeys.containsKey(isAncestorSearch ? alias.substring(1) : alias); Object lookupValuePreview = null; @@ -1476,7 +1476,7 @@ private List processFieldParts(FieldKey fkTok, Map processFieldParts(FieldKey fkTok, Map ancestorType = new Pair<>(isMaterialAncestor ? ExpLineageOptions.LineageExpType.Material : ExpLineageOptions.LineageExpType.Data, dataTypeLsid); - partAncestorOptions.put(fkTok, new NameExpressionAncestorPartOption(options, null, ancestorType, null, fieldParts.get(fieldParts.size() - 1))); + partAncestorOptions.put(fkTok, new NameExpressionAncestorPartOption(options, null, ancestorType, null, fieldParts.getLast())); } else { @@ -1570,7 +1570,7 @@ private List processFieldParts(FieldKey fkTok, Map processFieldParts(FieldKey fkTok, Map> p ArrayList parts = getParsedExpression(); if (parts.size() == 1) { - StringExpressionFactory.StringPart part = parts.get(0); + StringExpressionFactory.StringPart part = parts.getFirst(); try { if (part instanceof CounterExpressionPart counterExpressionPart) @@ -2009,13 +2009,6 @@ public Object getToken() return _prefixExpression; } - @NotNull - @Override - public Collection getFormats() - { - return Collections.emptyList(); - } - @Override public String getValue(Map map) { @@ -2109,12 +2102,6 @@ public FieldKeyStringExpression getParsedNameExpression() return _parsedNameExpression; } - @Override - public boolean hasSideEffects() - { - return false; - } - @Override public String toString() { @@ -2536,7 +2523,7 @@ public void testWithCounter() assertEquals(1, parsedExpressions.size()); assertEquals(2, se.getDeepParsedExpression().size()); - assertTrue(parsedExpressions.get(0) instanceof NameGenerator.CounterExpressionPart); + assertTrue(parsedExpressions.getFirst() instanceof NameGenerator.CounterExpressionPart); String s = se.eval(m); assertEquals("S100.1", s); @@ -2552,7 +2539,7 @@ public void testWithCounter() assertEquals(1, parsedExpressions.size()); assertEquals(4, se.getDeepParsedExpression().size()); - assertTrue(parsedExpressions.get(0) instanceof NameGenerator.CounterExpressionPart); + assertTrue(parsedExpressions.getFirst() instanceof NameGenerator.CounterExpressionPart); String s = se.eval(m); assertEquals("S100.mouse1.1", s); @@ -2599,7 +2586,7 @@ public void testWithCounter() assertEquals(1, parsedExpressions.size()); assertEquals(2, se.getDeepParsedExpression().size()); - assertTrue(parsedExpressions.get(0) instanceof NameGenerator.CounterExpressionPart); + assertTrue(parsedExpressions.getFirst() instanceof NameGenerator.CounterExpressionPart); String s = se.eval(m); assertEquals("S100_1", s); @@ -2617,8 +2604,8 @@ public void testWithCounter() assertEquals(1, parsedExpressions.size()); assertEquals(2, se.getDeepParsedExpression().size()); - assertTrue(parsedExpressions.get(0) instanceof NameGenerator.CounterExpressionPart); - NameGenerator.CounterExpressionPart counterPart = (NameGenerator.CounterExpressionPart) parsedExpressions.get(0); + assertTrue(parsedExpressions.getFirst() instanceof NameGenerator.CounterExpressionPart); + NameGenerator.CounterExpressionPart counterPart = (NameGenerator.CounterExpressionPart) parsedExpressions.getFirst(); assertEquals((Integer) 101, counterPart._startIndex); String s = se.eval(m); @@ -2635,7 +2622,7 @@ public void testWithCounter() assertEquals(1, parsedExpressions.size()); assertEquals(2, se.getDeepParsedExpression().size()); - assertTrue(parsedExpressions.get(0) instanceof NameGenerator.CounterExpressionPart); + assertTrue(parsedExpressions.getFirst() instanceof NameGenerator.CounterExpressionPart); String s = se.eval(m); assertEquals("S100...0111", s); diff --git a/api/src/org/labkey/api/data/NameGeneratorState.java b/api/src/org/labkey/api/data/NameGeneratorState.java index 7f69e445fcc..392508919fc 100644 --- a/api/src/org/labkey/api/data/NameGeneratorState.java +++ b/api/src/org/labkey/api/data/NameGeneratorState.java @@ -1,7 +1,6 @@ package org.labkey.api.data; import org.apache.commons.beanutils.ConversionException; -import org.apache.commons.beanutils.ConvertUtils; import org.apache.commons.lang3.StringUtils; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; @@ -675,7 +674,7 @@ else if (value.isEmpty()) ctx.putAll(inputValues); Map lookupValues = new HashMap<>(); - inputLookupValues.forEach((key, value) -> lookupValues.put(key, value.size() > 1 ? value : (value.size() == 1 ? value.iterator().next() : null))); + inputLookupValues.forEach((key, value) -> lookupValues.put(key, value.size() > 1 ? value : (value.size() == 1 ? value.getFirst() : null))); ctx.putAll(lookupValues); } @@ -696,7 +695,7 @@ else if (value.isEmpty()) if (pkCols.size() != 1) continue; - ColumnInfo pkCol = pkCols.get(0); + ColumnInfo pkCol = pkCols.getFirst(); // convert the rootValue to the target pkColumn type if (rootValue instanceof String && !pkCol.isStringType()) { diff --git a/api/src/org/labkey/api/data/NormalContainerType.java b/api/src/org/labkey/api/data/NormalContainerType.java index acfdb8792c4..a84abfa1a6b 100644 --- a/api/src/org/labkey/api/data/NormalContainerType.java +++ b/api/src/org/labkey/api/data/NormalContainerType.java @@ -104,19 +104,13 @@ public boolean isDuplicatedInContainerFilter() @Override public String getTitleFor(TitleContext tContext, Container currentContainer) { - switch (tContext) + return switch (tContext) { - case appBar: - return currentContainer.getName(); - case parentInNav: - return currentContainer.getTitle(); - case childInNav: - return currentContainer.getTitle(); - case importTarget: - return currentContainer.getPath(); - default: - return currentContainer.getTitle(); - } + case appBar -> currentContainer.getName(); + case parentInNav -> currentContainer.getTitle(); + case childInNav -> currentContainer.getTitle(); + case importTarget -> currentContainer.getPath(); + }; } @Override diff --git a/api/src/org/labkey/api/data/Parameter.java b/api/src/org/labkey/api/data/Parameter.java index 7f4dfe40c0e..77ceb3df351 100644 --- a/api/src/org/labkey/api/data/Parameter.java +++ b/api/src/org/labkey/api/data/Parameter.java @@ -170,7 +170,7 @@ public Parameter(String name, String uri, int index, JdbcType type) this(name, uri, new int[] { index }, type); } - public Parameter(String name, @Nullable String uri, @Nullable int[] indexes, JdbcType type) + public Parameter(String name, @Nullable String uri, @Nullable int[] indexes, @Nullable JdbcType type) { _name = name; _uri = uri; @@ -293,7 +293,7 @@ public void setValue(@Nullable Object in) } catch (SQLException e) { - LOG.error("Exception converting \"" + value + "\" to type " + _type); + LOG.error("Exception converting \"{}\" to type {}", value, _type); throw new RuntimeSQLException(e); } } diff --git a/api/src/org/labkey/api/data/ParameterMapStatement.java b/api/src/org/labkey/api/data/ParameterMapStatement.java index a1472e98ab8..442e7f67166 100644 --- a/api/src/org/labkey/api/data/ParameterMapStatement.java +++ b/api/src/org/labkey/api/data/ParameterMapStatement.java @@ -2,8 +2,9 @@ import org.apache.logging.log4j.Level; import java.lang.ref.Cleaner; -import org.jetbrains.annotations.NotNull; + import org.jetbrains.annotations.Nullable; +import org.jetbrains.annotations.NotNull; import org.labkey.api.arrays.IntegerArray; import org.labkey.api.collections.CaseInsensitiveHashMap; import org.labkey.api.data.dialect.SqlDialect; @@ -577,7 +578,7 @@ public void setDebugSql(String sql) _debugSql = sql; } - public DbScope getScope() + public @NotNull DbScope getScope() { return _scope; } diff --git a/api/src/org/labkey/api/data/PropertyStorageSpec.java b/api/src/org/labkey/api/data/PropertyStorageSpec.java index 9f0933fabdf..d1badf7d402 100644 --- a/api/src/org/labkey/api/data/PropertyStorageSpec.java +++ b/api/src/org/labkey/api/data/PropertyStorageSpec.java @@ -527,17 +527,13 @@ public enum CLUSTER_TYPE @Override public String toString() { - switch (this) + return switch (this) { - case CLUSTERED: - return "CLUSTERED"; - case NONCLUSTERED: - return "NONCLUSTERED"; - case CLUSTER: - return "CLUSTER"; - } - - return ""; + case CLUSTERED -> "CLUSTERED"; + case NONCLUSTERED -> "NONCLUSTERED"; + case CLUSTER -> "CLUSTER"; + }; + } } diff --git a/api/src/org/labkey/api/data/RecordFactory.java b/api/src/org/labkey/api/data/RecordFactory.java index 4b4c5a201c6..cb7f7e533f1 100644 --- a/api/src/org/labkey/api/data/RecordFactory.java +++ b/api/src/org/labkey/api/data/RecordFactory.java @@ -110,7 +110,7 @@ public K handle(ResultSet rs) throws SQLException } @Override - public ArrayList handleArrayList(ResultSet rs) throws SQLException + public ArrayList handleArrayList(ResultSet rs) { Iterable> iterable = () -> new ResultSetIterator(rs); return StreamSupport.stream(iterable.spliterator(), false) @@ -144,7 +144,7 @@ public void test() throws SQLException try (ResultSet rs = selector.getResultSet()) { rs.next(); - Assert.assertEquals(users.get(0), factory.handle(rs)); + Assert.assertEquals(users.getFirst(), factory.handle(rs)); } MiniUser randomUser = users.get((int)(Math.random() * users.size())); MiniUser selectedUser = new TableSelector(CoreSchema.getInstance().getTableInfoUsers(), new SimpleFilter(FieldKey.fromString("UserId"), randomUser.userid), null).getObject(MiniUser.class); diff --git a/api/src/org/labkey/api/data/RenderContext.java b/api/src/org/labkey/api/data/RenderContext.java index 731c9afa9e4..157c58308d0 100644 --- a/api/src/org/labkey/api/data/RenderContext.java +++ b/api/src/org/labkey/api/data/RenderContext.java @@ -21,8 +21,8 @@ import org.apache.commons.beanutils.ConvertUtils; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; -import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; +import org.jetbrains.annotations.NotNull; import org.labkey.api.action.LabKeyError; import org.labkey.api.collections.NullPreventingSet; import org.labkey.api.query.CustomView; @@ -353,7 +353,7 @@ public Map> getAggregates(List dis if (!ignoredAggregateFilters.equals(_ignoredColumnFilters)) { // This should never happen, but if it did, the totals wouldn't match, so we won't calculate them. - _log.error("Aggregate filter columns do not match main. Aggregate:" + ignoredAggregateFilters + " Main:" + _ignoredColumnFilters); + _log.error("Aggregate filter columns do not match main. Aggregate:{} Main:{}", ignoredAggregateFilters, _ignoredColumnFilters); return Collections.emptyMap(); } @@ -505,7 +505,7 @@ protected void buildSelectedFilter(SimpleFilter filter, TableInfo tinfo, boolean } else if (selectorColumns.size() == 1) { - clause = new SimpleFilter.InClause(FieldKey.fromString(selectorColumns.get(0)), selected, true); + clause = new SimpleFilter.InClause(FieldKey.fromString(selectorColumns.getFirst()), selected, true); } else { @@ -640,7 +640,7 @@ public boolean containsValue(Object value) * Overrides values() to combine keys from map and current row */ @Override - public Collection values() + public @NotNull Collection values() { Collection values = _extra.values(); if (null != _row) @@ -656,7 +656,7 @@ public Collection values() * Overrides entrySet to combine entries from map and current row */ @Override - public Set> entrySet() + public @NotNull Set> entrySet() { Set> entrySet = _extra.entrySet(); @@ -673,7 +673,7 @@ public Set> entrySet() * Overrides keySet to combine keys from map and current row */ @Override - public Set keySet() + public @NotNull Set keySet() { Set keySet = _extra.keySet(); @@ -764,7 +764,7 @@ public Object put(String key, Object value) { if (_row != null && _row.containsKey(key)) { - _log.warn("Attempted to update '" + key + "' in row"); + _log.warn("Attempted to update '{}' in row", key); return null; } @@ -776,7 +776,7 @@ public Object remove(Object key) { if (_row != null && _row.containsKey(key)) { - _log.warn("Attempted to remove '" + key + "' from row"); + _log.warn("Attempted to remove '{}' from row", key); return null; } @@ -784,7 +784,7 @@ public Object remove(Object key) } @Override - public void putAll(Map m) + public void putAll(@NotNull Map m) { throw new UnsupportedOperationException(); } diff --git a/api/src/org/labkey/api/data/RenderContextDecorator.java b/api/src/org/labkey/api/data/RenderContextDecorator.java index aab81873f7f..cf59ae49116 100644 --- a/api/src/org/labkey/api/data/RenderContextDecorator.java +++ b/api/src/org/labkey/api/data/RenderContextDecorator.java @@ -16,8 +16,8 @@ package org.labkey.api.data; import jakarta.servlet.http.HttpServletRequest; -import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; +import org.jetbrains.annotations.NotNull; import org.labkey.api.query.CustomView; import org.labkey.api.query.FieldKey; import org.labkey.api.query.QuerySettings; @@ -229,19 +229,19 @@ public boolean containsValue(Object value) } @Override - public Collection values() + public @NotNull Collection values() { return _ctx.values(); } @Override - public Set entrySet() + public @NotNull Set entrySet() { return _ctx.entrySet(); } @Override - public Set keySet() + public @NotNull Set keySet() { return _ctx.keySet(); } diff --git a/api/src/org/labkey/api/data/ReportingWriter.java b/api/src/org/labkey/api/data/ReportingWriter.java index 2ca89b8a328..50b0d0da00e 100644 --- a/api/src/org/labkey/api/data/ReportingWriter.java +++ b/api/src/org/labkey/api/data/ReportingWriter.java @@ -286,7 +286,7 @@ public static Map getLookupInfoMap(ColumnInfo columnInfo, boolea { schemaName = SchemaKey.decode(lookupTable.getSchema().getName()); TableInfo parentTable = columnInfo.getParentTable(); - LOG.debug("userSchema for non-public lookup table " + queryName + " was null on column " + columnInfo.getName() + " in table " + parentTable.getPublicSchemaName() + "." + parentTable.getPublicName() + ". Using " + lookupTable.getSchema().getName()); + LOG.debug("userSchema for non-public lookup table {} was null on column {} in table {}.{}. Using {}", queryName, columnInfo.getName(), parentTable.getPublicSchemaName(), parentTable.getPublicName(), lookupTable.getSchema().getName()); } } diff --git a/api/src/org/labkey/api/data/ResultSetImpl.java b/api/src/org/labkey/api/data/ResultSetImpl.java index 5f49cdf4f05..8c6b2246375 100644 --- a/api/src/org/labkey/api/data/ResultSetImpl.java +++ b/api/src/org/labkey/api/data/ResultSetImpl.java @@ -74,7 +74,7 @@ public void run() { if (!_wasClosed) { - _log.error("ResultSet was not closed. Created by thread " + _creatingThreadName + " with stacktrace: " + ExceptionUtil.renderStackTrace(_debugCreated)); + _log.error("ResultSet was not closed. Created by thread {} with stacktrace: {}", _creatingThreadName, ExceptionUtil.renderStackTrace(_debugCreated)); close(true); } } diff --git a/api/src/org/labkey/api/data/SQLFragment.java b/api/src/org/labkey/api/data/SQLFragment.java index bc4f6ded6c7..c944f3f6c7c 100644 --- a/api/src/org/labkey/api/data/SQLFragment.java +++ b/api/src/org/labkey/api/data/SQLFragment.java @@ -258,7 +258,7 @@ public String getSQL() StringBuilder ret = new StringBuilder("WITH" + (recursive ? " RECURSIVE" : "")); // generate final aliases for each CTE */ - SqlDialect dialect = Objects.requireNonNull(commonTableExpressions.get(0).dialect); + SqlDialect dialect = Objects.requireNonNull(commonTableExpressions.getFirst().dialect); AliasManager am = new AliasManager(dialect); List> ctes = commonTableExpressions.stream() .map(cte -> new Pair<>(am.decideAlias(cte.preferredName),cte)) @@ -1191,7 +1191,7 @@ public void nested_cte() \tCTE AS (SELECT 1 as i, 'one' as s, CAST('parameterONE' AS VARCHAR) as p) SELECT * FROM CTE WHERE p='parameterTWO'""", filterDebugString(b.toDebugString())); - assertEquals("parameterONE", b.getParams().get(0)); + assertEquals("parameterONE", b.getParams().getFirst()); } // two-level cte using cteTokens (CTE fragment 'b' contains a CTE of fragment a) diff --git a/api/src/org/labkey/api/data/SchemaColumnMetaData.java b/api/src/org/labkey/api/data/SchemaColumnMetaData.java index 50e842faa87..91f6af372c4 100644 --- a/api/src/org/labkey/api/data/SchemaColumnMetaData.java +++ b/api/src/org/labkey/api/data/SchemaColumnMetaData.java @@ -492,7 +492,7 @@ public String getTitleColumn() } if (null == _titleColumn) - _titleColumn = _columns.get(0).getName(); + _titleColumn = _columns.getFirst().getName(); } return _titleColumn; diff --git a/api/src/org/labkey/api/data/SchemaTableInfo.java b/api/src/org/labkey/api/data/SchemaTableInfo.java index fb5d4b6bb5b..4bc5f326133 100644 --- a/api/src/org/labkey/api/data/SchemaTableInfo.java +++ b/api/src/org/labkey/api/data/SchemaTableInfo.java @@ -558,7 +558,7 @@ public FieldKey getAuditRowPk() { List pks = getPkColumnNames(); if (pks.size() == 1) - _auditRowPk = FieldKey.fromParts(pks.get(0)); + _auditRowPk = FieldKey.fromParts(pks.getFirst()); else if (getColumn(FieldKey.fromParts("EntityId")) != null) _auditRowPk = FieldKey.fromParts("EntityId"); else if (getColumn(FieldKey.fromParts("RowId")) != null) @@ -642,7 +642,7 @@ public void loadTablePropertiesFromXml(TableType xmlTable, boolean dontSetName) } catch (IllegalArgumentException ignore) { - LOG.warn("Invalid AuditLogging: " + auditBehavior); + LOG.warn("Invalid AuditLogging: {}", auditBehavior); } } diff --git a/api/src/org/labkey/api/data/SchemaTableInfoCache.java b/api/src/org/labkey/api/data/SchemaTableInfoCache.java index 3652795e402..ecbaf74d033 100644 --- a/api/src/org/labkey/api/data/SchemaTableInfoCache.java +++ b/api/src/org/labkey/api/data/SchemaTableInfoCache.java @@ -62,14 +62,14 @@ SchemaTableInfo get(@NotNull OptionType void remove(@NotNull String schemaName, @NotNull String tableName, @NotNull DbSchemaType type) { - LOG.debug("remove " + type + " schema table: " + schemaName + "." + tableName); + LOG.debug("remove {} schema table: {}.{}", type, schemaName, tableName); String key = getCacheKey(schemaName, tableName, type); _blockingCache.remove(key); } void removeAllTables(@NotNull String schemaName, @NotNull DbSchemaType type) { - LOG.debug("remove all " + type + " schema tables: " + schemaName); + LOG.debug("remove all {} schema tables: {}", type, schemaName); final String prefix = type.getCacheKey(schemaName); // Note: A single database schema could be cached under multiple types, e.g., Module, Bare, Fast @@ -91,13 +91,13 @@ public SchemaTableInfo load(@NotNull String key, Object argument) try { - LOG.debug("loading schema table: " + fullName); + LOG.debug("loading schema table: {}", fullName); return options.getSchema().loadTable(options.getTableName(), options); } catch (SQLException e) { // Issue 49506: Log all problems for the admin and report to mothership and throw instead of returning null. - LOG.error("Exception while attempting to load schema table \"" + fullName + "\"", e); + LOG.error("Exception while attempting to load schema table \"{}\"", fullName, e); ExceptionUtil.logExceptionToMothership(null, e, false); throw new RuntimeSQLException(e); diff --git a/api/src/org/labkey/api/data/ServerPrimaryKeyLock.java b/api/src/org/labkey/api/data/ServerPrimaryKeyLock.java index bce48ea120e..ae82e5358c4 100644 --- a/api/src/org/labkey/api/data/ServerPrimaryKeyLock.java +++ b/api/src/org/labkey/api/data/ServerPrimaryKeyLock.java @@ -15,14 +15,11 @@ */ package org.labkey.api.data; -import org.jetbrains.annotations.NotNull; import org.labkey.api.exceptions.OptimisticConflictException; import java.util.Arrays; import java.util.List; import java.util.Map; -import java.util.concurrent.TimeUnit; -import java.util.concurrent.locks.Condition; /** * Created by matthew on 2/22/16. diff --git a/api/src/org/labkey/api/data/SimpleFilter.java b/api/src/org/labkey/api/data/SimpleFilter.java index 1cb5380207e..56e00b2607a 100644 --- a/api/src/org/labkey/api/data/SimpleFilter.java +++ b/api/src/org/labkey/api/data/SimpleFilter.java @@ -914,7 +914,7 @@ protected boolean meetsCriteria(ColumnRenderProperties col, Object value) for (Object params : getParamVals()) { // Loop through all the values and check if any of them are equals - FilterClause compareClause = CompareType.EQUAL.createFilterClause(getFieldKeys().get(0), params); + FilterClause compareClause = CompareType.EQUAL.createFilterClause(getFieldKeys().getFirst(), params); if (compareClause.meetsCriteria(col, value)) { return !_negated; @@ -1032,7 +1032,7 @@ protected boolean meetsCriteria(ColumnRenderProperties col, Object value) for (Object params : getParamVals()) { // Loop through all the values and check if any of them are equals - FilterClause compareClause = CompareType.CONTAINS.createFilterClause(getFieldKeys().get(0), params); + FilterClause compareClause = CompareType.CONTAINS.createFilterClause(getFieldKeys().getFirst(), params); if (compareClause.meetsCriteria(col, value)) { return !_negated; @@ -1514,13 +1514,13 @@ public boolean hasContainerEqualClause() { if (compClause.getCompareType() == CompareType.EQUAL && compClause.getFieldKeys().size() == 1 && - CONTAINER_FIELD_KEY.equals(compClause.getFieldKeys().get(0))) + CONTAINER_FIELD_KEY.equals(compClause.getFieldKeys().getFirst())) return true; } if (clause instanceof InClause inClause) { if (inClause.getFieldKeys().size() == 1 && - CONTAINER_FIELD_KEY.equals(inClause.getFieldKeys().get(0))) + CONTAINER_FIELD_KEY.equals(inClause.getFieldKeys().getFirst())) { return true; } @@ -1544,7 +1544,7 @@ public boolean meetsCriteria(TableInfo table, Map map) if (fieldKeys.size() > 1) throw new IllegalArgumentException("Can't check filter criteria of multi-column clauses"); - FieldKey fieldKey = fieldKeys.get(0); + FieldKey fieldKey = fieldKeys.getFirst(); ColumnInfo col = cols.get(fieldKey); Object value = map.get(fieldKey); if (!clause.meetsCriteria(col, value)) @@ -1818,7 +1818,7 @@ private void validateInClause(String url, boolean negated, boolean includeNull, { SimpleFilter f = new SimpleFilter(); f.addUrlFilters(new URLHelper(url), "query"); - InClause clause = (InClause)f.getClauses().get(0); + InClause clause = (InClause)f.getClauses().getFirst(); assertEquals("negated didn't match for IN clause", negated, clause._negated); assertEquals("includeNull didn't match for IN clause", includeNull, clause._includeNull); // Convert to sets because we don't care about order for IN clauses diff --git a/api/src/org/labkey/api/data/Sort.java b/api/src/org/labkey/api/data/Sort.java index 9dac8a7f567..e0edb6d4108 100644 --- a/api/src/org/labkey/api/data/Sort.java +++ b/api/src/org/labkey/api/data/Sort.java @@ -496,7 +496,7 @@ private SQLFragment _getOrderByClause(SqlDialect dialect, Map currentContainer.getParent(); + default -> currentContainer; + }; } } diff --git a/api/src/org/labkey/api/data/Table.java b/api/src/org/labkey/api/data/Table.java index 2b6d6266bbe..8ecb3cd9655 100644 --- a/api/src/org/labkey/api/data/Table.java +++ b/api/src/org/labkey/api/data/Table.java @@ -188,7 +188,7 @@ public static boolean isSelect(String sql) if (null != error) { - _log.warn(error + "!\n" + strippedSql); + _log.warn("{}!\n{}", error, strippedSql); return false; } @@ -592,7 +592,7 @@ static void logException(@Nullable SQLFragment sql, @Nullable Connection conn, S // Log this ConstraintException if log Level is WARN (the default) or lower. Skip logging for callers that request just ERRORs. if (Level.WARN.isMoreSpecificThan(logLevel)) { - _log.warn("SQL Exception" + (e.getSQLState() == null ? "" : (" with SQLState: " + e.getSQLState())), e); + _log.warn("SQL Exception{}", e.getSQLState() == null ? "" : (" with SQLState: " + e.getSQLState()), e); _logQuery(Level.WARN, sql, conn); } } @@ -601,7 +601,7 @@ static void logException(@Nullable SQLFragment sql, @Nullable Connection conn, S // Log this SQLException if log level is ERROR or lower. if (Level.ERROR.isMoreSpecificThan(logLevel)) { - _log.error("SQL Exception" + (e.getSQLState() == null ? "" : (" with SQLState: " + e.getSQLState())), e); + _log.error("SQL Exception{}", e.getSQLState() == null ? "" : (" with SQLState: " + e.getSQLState()), e); _logQuery(Level.ERROR, sql, conn); } } @@ -986,7 +986,7 @@ public static K update(@Nullable User user, TableInfo table, K fieldsIn, @Nu Map keys = new CaseInsensitiveHashMap<>(); if (columnPK.size() == 1 && !pkVals.getClass().isArray()) - keys.put(columnPK.get(0).getName(), pkVals); + keys.put(columnPK.getFirst().getName(), pkVals); else if (pkVals instanceof Map) keys.putAll((Map)pkVals); else @@ -1120,7 +1120,7 @@ else if (value instanceof NowTimestamp ts) } } else - _log.warn("Attempt to update table '" + table.getName() + "' with no valid fields."); + _log.warn("Attempt to update table '{}' with no valid fields.", table.getName()); return (fieldsIn instanceof Map && !(fieldsIn instanceof BoundMap)) ? (K)fields : fieldsIn; } @@ -1566,7 +1566,7 @@ SELECT CAST(COUNT(*) AS BIGINT) AS CountStar, private void verifyAggregates(Map expected, Map> aggregateMap) { - verifyAggregate(expected.get("CountStar"), aggregateMap.get("*").get(0).getValue()); + verifyAggregate(expected.get("CountStar"), aggregateMap.get("*").getFirst().getValue()); verifyAggregate(expected.get("CountRowId"), aggregateMap.get("RowId").get(0).getValue()); verifyAggregate(expected.get("SumRowId"), aggregateMap.get("RowId").get(1).getValue()); @@ -1577,14 +1577,14 @@ private void verifyAggregates(Map expected, Map co bad++; if (enforceUnique && !(column instanceof AliasedColumn) && null != (prev = mapAlias.put(column.getAlias().getId(), column)) && prev != column) { - _log.warn(prefix + ": Column " + column + " from table: " + column.getParentTable() + " is mapped to the same alias (" + column.getAlias().getId() + ") as column " + prev + " from table: " + prev.getParentTable()); + _log.warn("{}: Column {} from table: {} is mapped to the same alias ({}) as column {} from table: {}", prefix, column, column.getParentTable(), column.getAlias().getId(), prev, prev.getParentTable()); bad++; } } @@ -1682,7 +1682,7 @@ public static boolean checkColumn(TableInfo table, ColumnInfo column, String pre { if (column.getParentTable() != table) { - _log.warn(prefix + ": Column " + column + " is from the wrong table: " + column.getParentTable() + " instead of " + table); + _log.warn("{}: Column {} is from the wrong table: {} instead of {}", prefix, column, column.getParentTable(), table); return false; } else diff --git a/api/src/org/labkey/api/data/TableChange.java b/api/src/org/labkey/api/data/TableChange.java index 999b80ecb8d..1f93840a0ef 100644 --- a/api/src/org/labkey/api/data/TableChange.java +++ b/api/src/org/labkey/api/data/TableChange.java @@ -89,7 +89,7 @@ public void execute() { for (SQLFragment sql : scope.getSqlDialect().getChangeStatements(this)) { - LOG.debug("Will issue: " + sql.getSQL()); + LOG.debug("Will issue: {}", sql.getSQL()); executor.execute(sql); } success = true; diff --git a/api/src/org/labkey/api/data/TableExtension.java b/api/src/org/labkey/api/data/TableExtension.java index 1175f91901e..249bf031c5f 100644 --- a/api/src/org/labkey/api/data/TableExtension.java +++ b/api/src/org/labkey/api/data/TableExtension.java @@ -47,7 +47,7 @@ private TableExtension(AbstractTableInfo primaryTable, TableInfo extensionTable, public static TableExtension create(AbstractTableInfo primaryTable, TableInfo extensionTable) { - String pkColumn = extensionTable.getPkColumnNames().get(0); // Note this only works for simple primary keys, not compound. + String pkColumn = extensionTable.getPkColumnNames().getFirst(); // Note this only works for simple primary keys, not compound. String fkColumn = extensionTable.getColumn(pkColumn).getFk().getLookupColumnName(); return create(primaryTable, extensionTable, fkColumn, pkColumn, LookupColumn.JoinType.leftOuter); diff --git a/api/src/org/labkey/api/data/TableResultSet.java b/api/src/org/labkey/api/data/TableResultSet.java index e1127f87941..7434ad80942 100644 --- a/api/src/org/labkey/api/data/TableResultSet.java +++ b/api/src/org/labkey/api/data/TableResultSet.java @@ -47,7 +47,7 @@ default int countAll() throws SQLException * Implementations should prefer to return ConnectionWrapper instead of the underlying connection as it has * more context. */ @Nullable - Connection getConnection() throws SQLException; + Connection getConnection(); default T getWrapped(Class clz) { diff --git a/api/src/org/labkey/api/data/TableSelector.java b/api/src/org/labkey/api/data/TableSelector.java index dc2bde07a69..556344f0a27 100644 --- a/api/src/org/labkey/api/data/TableSelector.java +++ b/api/src/org/labkey/api/data/TableSelector.java @@ -155,7 +155,7 @@ private static Collection columnInfosList(@NotNull TableInfo table, if (null != column) selectColumns.add(column); else - LOG.warn("Requested column does not exist in table '" + table.getSelectName() + "': " + name); + LOG.warn("Requested column does not exist in table '{}': {}", table.getSelectName(), name); } } @@ -518,7 +518,7 @@ public Map> getAggregates(final List aggregates) // If we are only asking for the COUNT(*) aggregate, then we don't need to include all of the table columns in the subselect. // This can make a big performance difference for Sample Type and Data Class tables as they can then skip // the join between the exp schema base table and the materialized table for the given table. - Collection aggColumns = aggregates.size() == 1 && aggregates.get(0).isCountStar() ? getRowCountingSelectColumns(_table) : _columns; + Collection aggColumns = aggregates.size() == 1 && aggregates.getFirst().isCountStar() ? getRowCountingSelectColumns(_table) : _columns; final AggregateSqlFactory sqlFactory = new AggregateSqlFactory(_filter, aggregates, aggColumns); ResultSetFactory resultSetFactory = new ExecutingResultSetFactory(sqlFactory); diff --git a/api/src/org/labkey/api/data/TableViewForm.java b/api/src/org/labkey/api/data/TableViewForm.java index 71cfa5c3893..8233761b434 100644 --- a/api/src/org/labkey/api/data/TableViewForm.java +++ b/api/src/org/labkey/api/data/TableViewForm.java @@ -200,7 +200,7 @@ public void doDelete() if (null != pkVal && null != pkVal[0]) Table.delete(_tinfo, pkVal); else //Hmm, throw an exception here???? - _log.warn("Nothing to delete for table " + _tinfo.getName() + " on request " + _request.getRequestURI()); + _log.warn("Nothing to delete for table {} on request {}", _tinfo.getName(), _request.getRequestURI()); } } @@ -267,7 +267,7 @@ public String getPkName() { assertSinglePK(); - return _tinfo.getPkColumnNames().get(0); + return _tinfo.getPkColumnNames().getFirst(); } public List getPkNamesList() @@ -299,7 +299,7 @@ public void setPkVals(String s) //Issue 42042: Lists with text primary key don't handle commas in key value when viewing row details if (getPkNamesList().size() == 1) { - setValueToBind(getPkNamesList().get(0), s); + setValueToBind(getPkNamesList().getFirst(), s); } else { diff --git a/api/src/org/labkey/api/data/TempTableTracker.java b/api/src/org/labkey/api/data/TempTableTracker.java index 919b96633d3..613f9bf1826 100644 --- a/api/src/org/labkey/api/data/TempTableTracker.java +++ b/api/src/org/labkey/api/data/TempTableTracker.java @@ -72,7 +72,7 @@ public void run() { if (!deleted) { - _log.debug("Deleting table " + schema.getName() + "." + tableName); + _log.debug("Deleting table {}.{}", schema.getName(), tableName); schema.dropTableIfExists(tableName); deleted = true; @@ -130,7 +130,7 @@ private static TempTableTracker track(String schema, String name, Object ref) private static TempTableTracker track(TempTableTracker ttt) { - _log.debug("track(" + ttt.qualifiedName + ")"); + _log.debug("track({})", ttt.qualifiedName); synchronized(createdTableNames) { @@ -150,7 +150,7 @@ public synchronized void delete() private static void untrack(String qualifiedName, String schemaName, String tableName) { - _log.debug("untrack(" + qualifiedName + ")"); + _log.debug("untrack({})", qualifiedName); synchronized(createdTableNames) { diff --git a/api/src/org/labkey/api/data/UpgradeUtils.java b/api/src/org/labkey/api/data/UpgradeUtils.java index 0ac5957910c..619bdd8ef58 100644 --- a/api/src/org/labkey/api/data/UpgradeUtils.java +++ b/api/src/org/labkey/api/data/UpgradeUtils.java @@ -55,7 +55,7 @@ public class UpgradeUtils */ public static void uniquifyValues(ColumnInfo column, @Nullable ColumnInfo additionalGroupingColumn, @Nullable SimpleFilter filter, Sort sort, boolean caseSensitive, boolean ignoreNulls) { - LOG.info("Removing duplicate values from " + column.getParentTable().toString() + "." + column.getName()); + LOG.info("Removing duplicate values from {}.{}", column.getParentTable().toString(), column.getName()); // Do an aggregate query to determine all groups (containers or container + additional grouping column combinations) with uniqueness problems in this column List groupFilters = getFiltersForGroupsWithDuplicateValues(column, additionalGroupingColumn, filter, caseSensitive, ignoreNulls); @@ -81,7 +81,7 @@ private static void uniquifyValuesInGroup(ColumnInfo col, SimpleFilter filter, S String columnName = col.getName(); Set selectColumns = Collections.singleton(col); - LOG.info(" Updating duplicate values in group represented by: " + filter.getFilterText()); + LOG.info(" Updating duplicate values in group represented by: {}", filter.getFilterText()); // First, grab all the existing values so when we have to change a value we don't collide with another existing value. Set existingValues = getSet(caseSensitive); @@ -111,7 +111,7 @@ private static void uniquifyValuesInGroup(ColumnInfo col, SimpleFilter filter, S } while(newValues.contains(candidateValue) || existingValues.contains(candidateValue)); - LOG.info(" Changing " + value + " to " + candidateValue); + LOG.info(" Changing {} to {}", value, candidateValue); value = candidateValue; diff --git a/api/src/org/labkey/api/data/UserSchemaCustomizer.java b/api/src/org/labkey/api/data/UserSchemaCustomizer.java index 96c5423a628..123f99c5943 100644 --- a/api/src/org/labkey/api/data/UserSchemaCustomizer.java +++ b/api/src/org/labkey/api/data/UserSchemaCustomizer.java @@ -71,7 +71,7 @@ public static UserSchemaCustomizer create(SchemaCustomizerType xmlSchemaCustomiz Class c = Class.forName(className); if (!(UserSchemaCustomizer.class.isAssignableFrom(c))) { - LogManager.getLogger(UserSchemaCustomizer.class).warn("Class '" + c.getName() + "' is not an implementation of " + UserSchemaCustomizer.class.getName()); + LogManager.getLogger(UserSchemaCustomizer.class).warn("Class '{}' is not an implementation of {}", c.getName(), UserSchemaCustomizer.class.getName()); } else { diff --git a/api/src/org/labkey/api/data/WorkbookContainerType.java b/api/src/org/labkey/api/data/WorkbookContainerType.java index b3796ae673e..4b582542bc3 100644 --- a/api/src/org/labkey/api/data/WorkbookContainerType.java +++ b/api/src/org/labkey/api/data/WorkbookContainerType.java @@ -143,43 +143,28 @@ public String getContainerNoun(Container currentContainer) @Override public String getTitleFor(TitleContext context, Container currentContainer) { - switch (context) + return switch (context) { - case appBar: - return currentContainer.getTitle(); - case parentInNav: - return currentContainer.getParent() != null ? currentContainer.getParent().getTitle() : currentContainer.getTitle(); - case childInNav: - return currentContainer.getName(); - case importTarget: - return currentContainer.getTitle(); - default: - return currentContainer.getTitle(); - } + case appBar -> currentContainer.getTitle(); + case parentInNav -> + currentContainer.getParent() != null ? currentContainer.getParent().getTitle() : currentContainer.getTitle(); + case childInNav -> currentContainer.getName(); + case importTarget -> currentContainer.getTitle(); + default -> currentContainer.getTitle(); + }; } @Override public Container getContainerFor(DataType dataType, Container currentContainer) { - switch (dataType) + return switch (dataType) { //The intent is that outside of these specially supported actions, return the current container (parent otherwise) //Note: fileRoot has been deliberately removed to allow per-workbook override - case customQueryViews: - case domainDefinitions: - case dataspace: - case fileAdmin: - case navVisibility: - case permissions: - case properties: - case protocol: - case folderManagement: - case tabParent: - case sharedSchemaOwner: - return currentContainer.getParent(); - default: - return currentContainer; - } + case customQueryViews, domainDefinitions, dataspace, fileAdmin, navVisibility, permissions, properties, + protocol, folderManagement, tabParent, sharedSchemaOwner -> currentContainer.getParent(); + default -> currentContainer; + }; } @Override @@ -303,7 +288,7 @@ protected void testCrossContainerBehaviors(Container project, List wo throw errors2; } - toInsertWb.forEach(x -> x.put("container", workbooks.get(0).getId())); //store this for use downstream + toInsertWb.forEach(x -> x.put("container", workbooks.getFirst().getId())); //store this for use downstream List> allChildRows = new ArrayList<>(); allChildRows.addAll(toInsert2); @@ -311,7 +296,7 @@ protected void testCrossContainerBehaviors(Container project, List wo validateRowsByContainer(usProject, childTable, allChildRows, primaryChildField); List> wbRows = new ArrayList<>(allChildRows); - wbRows.removeIf(x -> !workbooks.get(0).getId().equals(x.get("container"))); + wbRows.removeIf(x -> !workbooks.getFirst().getId().equals(x.get("container"))); validateRowsByContainer(usWorkbook0, childTable, wbRows, primaryChildField); validateLookups(usProject, childTable, FieldKey.fromString(lookupField + "/" + parentField)); @@ -323,7 +308,7 @@ protected void testCrossContainerBehaviors(Container project, List wo if (tiChild.getPkColumnNames().contains(primaryChildField)) { List> duplicateKeyRows = new ArrayList<>(); - duplicateKeyRows.add(createChildRow(workbooks.get(0), primaryChildField, "Row" + (i - 1), lookupField, null, extraRowValues)); + duplicateKeyRows.add(createChildRow(workbooks.getFirst(), primaryChildField, "Row" + (i - 1), lookupField, null, extraRowValues)); BatchValidationException errors3 = new BatchValidationException(); usWorkbook0.getTable(childTable).getUpdateService().insertRows(_context.getUser(), usWorkbook0.getContainer(), duplicateKeyRows, errors3, Collections.emptyMap(), null); if (!errors3.hasErrors()) @@ -331,7 +316,7 @@ protected void testCrossContainerBehaviors(Container project, List wo throw new Exception("This indicates the duplicate key insert was allowed"); } - assertThat("Unexpected error message. Message was: " + errors3.getRowErrors().get(0).getMessage(), errors3.getRowErrors().get(0).getMessage(), containsString("duplicate key")); + assertThat("Unexpected error message. Message was: " + errors3.getRowErrors().getFirst().getMessage(), errors3.getRowErrors().getFirst().getMessage(), containsString("duplicate key")); } } diff --git a/api/src/org/labkey/api/data/bigiron/AbstractClrInstallationManager.java b/api/src/org/labkey/api/data/bigiron/AbstractClrInstallationManager.java index e001dc1f1ef..d0894785b01 100644 --- a/api/src/org/labkey/api/data/bigiron/AbstractClrInstallationManager.java +++ b/api/src/org/labkey/api/data/bigiron/AbstractClrInstallationManager.java @@ -128,7 +128,7 @@ private void install(ModuleContext context) try (Connection conn = getSchema().getScope().getUnpooledConnection()) { - LOG.info("Executing " + script.getDescription() + " against " + (rds ? "an RDS" : "a non-RDS") + " database"); + LOG.info("Executing {} against {} database", script.getDescription(), rds ? "an RDS" : "a non-RDS"); SqlScriptManager.get(script.getProvider(), script.getSchema()).runScript(context.getUpgradeUser(), script, context, conn); } catch (Throwable t) diff --git a/api/src/org/labkey/api/data/dialect/BasePostgreSqlDialect.java b/api/src/org/labkey/api/data/dialect/BasePostgreSqlDialect.java index 0ecd40466c3..da8a3382203 100644 --- a/api/src/org/labkey/api/data/dialect/BasePostgreSqlDialect.java +++ b/api/src/org/labkey/api/data/dialect/BasePostgreSqlDialect.java @@ -1073,7 +1073,7 @@ private Closer configureToDisableJdbcCaching(ConnectionWrapper connection, DbSco } catch (SQLException e) { - LOG.error("SQLException hit for " + connection); + LOG.error("SQLException hit for {}", connection); scope.logCurrentConnectionState(); throw e; } diff --git a/api/src/org/labkey/api/data/dialect/KeywordCandidates.java b/api/src/org/labkey/api/data/dialect/KeywordCandidates.java index 2ac3e0b257f..892307647cd 100644 --- a/api/src/org/labkey/api/data/dialect/KeywordCandidates.java +++ b/api/src/org/labkey/api/data/dialect/KeywordCandidates.java @@ -81,7 +81,7 @@ public boolean containsAll(Set reservedWordSet, String productName) if (notFound.isEmpty()) return true; - LOG.error("Keywords from " + productName + " dialect need to be added to sqlKeywords.txt file: " + notFound); + LOG.error("Keywords from {} dialect need to be added to sqlKeywords.txt file: {}", productName, notFound); return false; } diff --git a/api/src/org/labkey/api/data/dialect/SqlDialect.java b/api/src/org/labkey/api/data/dialect/SqlDialect.java index 868702be8e2..45952b986dc 100644 --- a/api/src/org/labkey/api/data/dialect/SqlDialect.java +++ b/api/src/org/labkey/api/data/dialect/SqlDialect.java @@ -1225,7 +1225,7 @@ public void testDialectKeywords(SqlExecutor executor) throw new IllegalStateException("Need to add " + StringUtilsLabKey.pluralize(shouldAdd.size(), "keyword") + " to " + getProductName() + " reserved word list: " + shouldAdd); if (!shouldRemove.isEmpty()) - LOG.info("Should remove " + StringUtilsLabKey.pluralize(shouldRemove.size(), "keyword") + " from " + getClass().getName() + " reserved word list: " + shouldRemove); + LOG.info("Should remove {} from {} reserved word list: {}", StringUtilsLabKey.pluralize(shouldRemove.size(), "keyword"), getClass().getName(), shouldRemove); } @@ -1620,7 +1620,7 @@ public Integer getMaxTotal() } catch (ServletException e) { - LOG.error("Could not extract connection pool max size from data source \"" + _dsName + "\""); + LOG.error("Could not extract connection pool max size from data source \"{}\"", _dsName); return null; } } @@ -1633,7 +1633,7 @@ public Integer getNumActive() } catch (ServletException e) { - LOG.error("Could not extract connection num active from data source \"" + _dsName + "\""); + LOG.error("Could not extract connection num active from data source \"{}\"", _dsName); return null; } } @@ -1645,7 +1645,7 @@ public Integer getNumIdle() } catch (ServletException e) { - LOG.error("Could not extract connection num idle from data source \"" + _dsName + "\""); + LOG.error("Could not extract connection num idle from data source \"{}\"", _dsName); return null; } } @@ -1658,7 +1658,7 @@ public Long getMaxWaitMillis() } catch (ServletException e) { - LOG.error("Could not extract connection pool max wait (ms) from data source \"" + _dsName + "\""); + LOG.error("Could not extract connection pool max wait (ms) from data source \"{}\"", _dsName); return null; } } @@ -1673,7 +1673,7 @@ public Long getMaxWaitMillis() } catch (InvocationTargetException | IllegalAccessException | NoSuchMethodException e) { - LOG.error("Could not extract connection properties from data source \"" + _dsName + "\""); + LOG.error("Could not extract connection properties from data source \"{}\"", _dsName); return null; } } diff --git a/api/src/org/labkey/api/data/dialect/StandardDialectStringHandler.java b/api/src/org/labkey/api/data/dialect/StandardDialectStringHandler.java index 2083f20b12e..00d1b250562 100644 --- a/api/src/org/labkey/api/data/dialect/StandardDialectStringHandler.java +++ b/api/src/org/labkey/api/data/dialect/StandardDialectStringHandler.java @@ -68,7 +68,7 @@ public String substituteParameters(SQLFragment frag) if (params.isEmpty()) ret.append("NULL /*?missing?*/"); else - ret.append(formatParameter(params.remove(0))); + ret.append(formatParameter(params.removeFirst())); current++; begin = current; } diff --git a/api/src/org/labkey/api/data/generator/DataGenerator.java b/api/src/org/labkey/api/data/generator/DataGenerator.java index 86928911e3f..d726658da11 100644 --- a/api/src/org/labkey/api/data/generator/DataGenerator.java +++ b/api/src/org/labkey/api/data/generator/DataGenerator.java @@ -41,7 +41,6 @@ import org.labkey.api.query.BatchValidationException; import org.labkey.api.query.DuplicateKeyException; import org.labkey.api.query.FieldKey; -import org.labkey.api.query.InvalidKeyException; import org.labkey.api.query.QueryService; import org.labkey.api.query.QueryUpdateService; import org.labkey.api.query.QueryUpdateServiceException; @@ -224,7 +223,7 @@ public List getSampleTypes(List sampleTypeNames { ExpSampleType sampleType = service.getSampleType(getContainer(), typeName, true); if (sampleType == null) - _log.warn(String.format("Unable to resolve sample type by name '%s'.", typeName)); + _log.warn("Unable to resolve sample type by name '{}'.", typeName); else _sampleTypes.add(sampleType); } @@ -255,7 +254,7 @@ public void generateFolders(String namePrefix) int numFolders = _config.getNumFolders(); if (numFolders <= 0) { - _log.info(String.format("No folders generated because %s=%d", Config.NUM_FOLDERS, numFolders)); + _log.info("No folders generated because {}={}", Config.NUM_FOLDERS, numFolders); return; } CPUTimer timer = addTimer(String.format("%d sub-folders", numFolders)); @@ -274,7 +273,7 @@ public void generateFolders(String namePrefix) i++; } timer.stop(); - _log.info(String.format("Generating %d sub-folders took %s", numFolders, timer.getDuration() + ".")); + _log.info("Generating {} sub-folders took {}", numFolders, timer.getDuration() + "."); } public void generateSampleTypes(String namePrefix, String namingPatternPrefix) throws ExperimentException, SQLException @@ -282,7 +281,7 @@ public void generateSampleTypes(String namePrefix, String namingPatternPrefix) t checkAlive(_job); int numSampleTypes = _config.getNumSampleTypes(); if (numSampleTypes <= 0) { - _log.info(String.format("No sample types generated because %s=%d", Config.NUM_SAMPLE_TYPES, numSampleTypes)); + _log.info("No sample types generated because {}={}", Config.NUM_SAMPLE_TYPES, numSampleTypes); return; } int minFields = _config.getMinFields(); @@ -312,7 +311,7 @@ public void generateSampleTypes(String namePrefix, String namingPatternPrefix) t } timer.stop(); - _log.info(String.format("Generating %d sample types took %s", numSampleTypes, timer.getDuration() + ".")); + _log.info("Generating {} sample types took {}", numSampleTypes, timer.getDuration() + "."); } private ExpSampleType generateSampleType(String sampleTypeName, @Nullable String namingPattern, int numFields) throws ExperimentException, SQLException @@ -324,7 +323,7 @@ private ExpSampleType generateSampleType(String sampleTypeName, @Nullable String addDomainProperties(props, numFields); SampleTypeService service = SampleTypeService.get(); - _log.info(String.format("Creating Sample Type '%s' with %d fields", sampleTypeName, numFields+2)); + _log.info("Creating Sample Type '{}' with {} fields", sampleTypeName, numFields + 2); return service.createSampleType(_container, _user, sampleTypeName, "Generated sample type", props, List.of(), -1, -1, -1, -1, namingPattern, null, null, null, randomIndex(LABEL_COLORS), randomIndex(UNITS)); @@ -338,7 +337,7 @@ public void generateSamplesForAllTypes() throws SQLException, BatchValidationExc int numSamples = config.getMinSamples(); if (numSamples <= 0 && config.getMaxSamples() <= 0) { - _log.info(String.format("No samples generated because %s=%d and %s=%d", Config.MIN_SAMPLES, numSamples, Config.MAX_SAMPLES, config.getMaxSamples())); + _log.info("No samples generated because {}={} and {}={}", Config.MIN_SAMPLES, numSamples, Config.MAX_SAMPLES, config.getMaxSamples()); return; } List parentTypes = new ArrayList<>(config.getSampleTypeParents()); @@ -352,12 +351,12 @@ public void generateSamplesForAllTypes() throws SQLException, BatchValidationExc dataClassParents.addAll(ExperimentService.get().getDataClasses(getContainer(), false).stream().map(ExpDataClass::getName).toList()); for (ExpSampleType sampleType : getSampleTypes(_config.getSampleTypeNames())) { - _log.info(String.format("Generating %d samples for sample type '%s'.", numSamples, sampleType.getName())); + _log.info("Generating {} samples for sample type '{}'.", numSamples, sampleType.getName()); CPUTimer timer = addTimer(String.format("%d '%s' samples", numSamples, sampleType.getName())); timer.start(); int numGenerated = generateSamples(sampleType, numSamples, dataClassParents, parentTypes); timer.stop(); - _log.info(String.format("Generating %d samples for sample type '%s' took %s.", numGenerated, sampleType.getName(), timer.getDuration())); + _log.info("Generating {} samples for sample type '{}' took {}.", numGenerated, sampleType.getName(), timer.getDuration()); numSamples = Math.min(numSamples + sampleIncrement, config.getMaxSamples()); if (!hasParentTypes) @@ -380,7 +379,7 @@ public int generateSamples(ExpSampleType sampleType, int numSamplesAndAliquots, sampleTypeParents.isEmpty() ? numDerived : Math.round(numDerived * _config.getPctDerivedFromSamples()); if (!dataClassParentTypes.isEmpty() && numDerivedFromDataClass > 0) { - _log.info(String.format("Generating %d samples derived from data class objects.", numDerivedFromDataClass)); + _log.info("Generating {} samples derived from data class objects.", numDerivedFromDataClass); int numPerParentGroup = numDerivedFromDataClass / dataClassParentTypes.size(); int numTypesPer = randomInt(_config.getMinDataClassParentTypesPerSample(), Math.min(_config.getMaxDataClassParentTypesPerSample(), dataClassParentTypes.size())); @@ -409,7 +408,7 @@ public int generateSamples(ExpSampleType sampleType, int numSamplesAndAliquots, if (!sampleTypeParents.isEmpty() && numDerivedFromSamples > 0) { checkAlive(_job); - _log.info(String.format("Generated %d samples derived from sample types", numDerivedFromSamples)); + _log.info("Generated {} samples derived from sample types", numDerivedFromSamples); int numPerParentType = numDerivedFromSamples / sampleTypeParents.size(); for (String parentType : sampleTypeParents) { @@ -427,7 +426,7 @@ public int generateAliquots(ExpSampleType sampleType, QueryUpdateService svc, in { if (_config.getMaxAliquotsPerParent() <= 0) { - _log.info(String.format("Generating no aliquots because %s is %d", Config.MAX_ALIQUOTS_PER_SAMPLE, _config.getMaxAliquotsPerParent())); + _log.info("Generating no aliquots because {} is {}", Config.MAX_ALIQUOTS_PER_SAMPLE, _config.getMaxAliquotsPerParent()); return 0; } @@ -440,7 +439,7 @@ public int generateAliquots(ExpSampleType sampleType, QueryUpdateService svc, in } - _log.info(String.format("Generating %d aliquots for sample type '%s' ...", quantity, sampleType.getName())); + _log.info("Generating {} aliquots for sample type '{}' ...", quantity, sampleType.getName()); CPUTimer timer = addTimer(String.format("%d '%s' aliquots", quantity, sampleType.getName())); timer.start(); int totalAliquots = 0; @@ -452,14 +451,14 @@ public int generateAliquots(ExpSampleType sampleType, QueryUpdateService svc, in List> parents = getRandomSamples(sampleType, Math.min(10, Math.max(quantity, quantity / 100))); numGenerated = generateAliquotsForParents(sampleType, parents, svc, quantity - totalAliquots, 0, 1, randomInt(1, _config.getMaxGenerations()), sampleStatuses); totalAliquots += numGenerated; - _log.info("... " + totalAliquots); + _log.info("... {}", totalAliquots); iterations++; } while (totalAliquots < quantity && numGenerated > 0); timer.stop(); if (totalAliquots < quantity) - _log.warn(String.format("Generated only %d aliquots after %d iterations", totalAliquots, iterations)); - _log.info(String.format("Generating %d aliquots for sample type '%s' in %d iterations took %s.", totalAliquots, sampleType.getName(), iterations, timer.getDuration())); + _log.warn("Generated only {} aliquots after {} iterations", totalAliquots, iterations); + _log.info("Generating {} aliquots for sample type '{}' in {} iterations took {}.", totalAliquots, sampleType.getName(), iterations, timer.getDuration()); return totalAliquots; } @@ -506,7 +505,7 @@ private int generateAliquotsForParents(ExpSampleType sampleType, List> selectExistingSamples(ExpSampleType sampleType, TableInfo tableInfo = getSamplesSchema().getTable(sampleType.getName()); if (tableInfo == null) { - _log.warn("Sample type '" + sampleType.getName() + "' not found."); + _log.warn("Sample type '{}' not found.", sampleType.getName()); return Collections.emptyList(); } SQLFragment sql = limitFromOffsetSqlFrag(tableInfo, "RowId, Name", limit, totalSampleCount); @@ -572,7 +571,7 @@ public List> selectExistingDataClassObjects(ExpDataClass dat TableInfo tableInfo = getDataClassSchema().getTable(dataClass.getName()); if (tableInfo == null) { - _log.warn("Data class '" + dataClass.getName() + "' not found."); + _log.warn("Data class '{}' not found.", dataClass.getName()); return Collections.emptyList(); } SQLFragment sql = limitFromOffsetSqlFrag(tableInfo, "RowId, Name", limit, totalSampleCount); @@ -613,7 +612,7 @@ protected List> getRowsByRandomNames(TableInfo tableInfo, Na } - public void poolSamples(ExpSampleType sampleType, QueryUpdateService service, int numPooled) throws SQLException, BatchValidationException, QueryUpdateServiceException, InvalidKeyException + public void poolSamples(ExpSampleType sampleType, QueryUpdateService service, int numPooled) { // // TODO This can pool samples from different generations, which seems a little odd, but we'll go with it for now. // List> rows = new ArrayList<>(); @@ -672,7 +671,7 @@ public ExpDataClass generateDataClass(String dataClassName, @Nullable String nam List props = new ArrayList<>(); addDomainProperties(props, numFields); - log.info(String.format("Creating Data Class '%s' with %d fields", dataClassName, numFields)); + log.info("Creating Data Class '{}' with {} fields", dataClassName, numFields); DataClassDomainKindProperties options = new DataClassDomainKindProperties(); options.setDescription("Custom data class with " + numFields + " fields"); options.setNameExpression(namingPattern); @@ -692,7 +691,7 @@ public int generateDerivedSamples(ExpSampleType sampleType, Collection p { if (_config.getMaxChildrenPerParent() <= 0) { - _log.info(String.format("No derivatives generated since maxChildrenPerParent is %d", _config.getMaxChildrenPerParent())); + _log.info("No derivatives generated since maxChildrenPerParent is {}", _config.getMaxChildrenPerParent()); return 0; } @@ -717,7 +716,7 @@ public int generateDerivedSamples(ExpSampleType sampleType, Collection p }); } - _log.info(String.format("Generating %d '%s' samples derived from '%s/%s' ...", quantity, sampleType.getName(), parentInput, parentQueryNames)); + _log.info("Generating {} '{}' samples derived from '{}/{}' ...", quantity, sampleType.getName(), parentInput, parentQueryNames); CPUTimer timer = addTimer(String.format("%d '%s/%s' derived samples", quantity, parentInput, parentQueryNames)); timer.start(); BatchValidationException errors = new BatchValidationException(); @@ -763,11 +762,11 @@ public int generateDerivedSamples(ExpSampleType sampleType, Collection p dataChanged = numImported > 0; totalImported += numImported; - _log.info("... " + totalImported); + _log.info("... {}", totalImported); } timer.stop(); - _log.info(String.format("Generating %d '%s' samples derived from '%s/%s' took %s.", quantity, sampleType.getName(), parentInput, parentQueryNames, timer.getDuration())); + _log.info("Generating {} '{}' samples derived from '{}/{}' took {}.", quantity, sampleType.getName(), parentInput, parentQueryNames, timer.getDuration()); return totalImported; } @@ -783,7 +782,7 @@ protected int importRows(List> rows, BatchValidationExceptio public void logTimes() { _log.info("===== Timing Summary ======"); - _timers.forEach((timer) -> _log.info(String.format("%s\t%s", timer.getName(), timer.getDuration()))); + _timers.forEach((timer) -> _log.info("{}\t{}", timer.getName(), timer.getDuration())); } public CPUTimer addTimer(String name) @@ -796,7 +795,7 @@ public CPUTimer addTimer(String name) private int generateDomainData(int totalRows, QueryUpdateService service, Domain domain, Container container) throws BatchValidationException, SQLException { checkAlive(_job); - _log.info(String.format("Generating %d rows of data ...", totalRows)); + _log.info("Generating {} rows of data ...", totalRows); int numImported = 0; int batchSize = Math.min(MAX_BATCH_SIZE, totalRows); BatchValidationException errors = new BatchValidationException(); @@ -804,7 +803,7 @@ private int generateDomainData(int totalRows, QueryUpdateService service, Domain { List> rows = createRows(Math.min(batchSize, totalRows - numImported), domain); numImported += importRows(rows, errors, service, container); - _log.info("... " + numImported); + _log.info("... {}", numImported); } return numImported; } @@ -812,7 +811,7 @@ private int generateDomainData(int totalRows, QueryUpdateService service, Domain private int generateSampleData(int totalRows, QueryUpdateService service, ExpSampleType sampleType, Container container) throws BatchValidationException, SQLException { checkAlive(_job); - _log.info(String.format("Generating %d rows of data ...", totalRows)); + _log.info("Generating {} rows of data ...", totalRows); int numImported = 0; int batchSize = Math.min(MAX_BATCH_SIZE, totalRows); BatchValidationException errors = new BatchValidationException(); @@ -820,7 +819,7 @@ private int generateSampleData(int totalRows, QueryUpdateService service, ExpSam { List> rows = createSampleRows(Math.min(batchSize, totalRows - numImported), sampleType); numImported += importRows(rows, errors, service, container); - _log.info("... " + numImported); + _log.info("... {}", numImported); } return numImported; } diff --git a/api/src/org/labkey/api/data/queryprofiler/QueryProfiler.java b/api/src/org/labkey/api/data/queryprofiler/QueryProfiler.java index d7384150846..8621791ccd6 100644 --- a/api/src/org/labkey/api/data/queryprofiler/QueryProfiler.java +++ b/api/src/org/labkey/api/data/queryprofiler/QueryProfiler.java @@ -466,7 +466,7 @@ public HttpView getExecutionPlanView(String sqlHash, ExecutionPlanType type, { // The log option is useful for retrieving actual timing information about very long-running queries when // proxy timeouts prevent viewing the plan via the web page - LOG.info("An administrator initiated the logging of this query execution plan with actual timing:\n" + sqlWithParameters + fullPlan); + LOG.info("An administrator initiated the logging of this query execution plan with actual timing:\n{}{}", sqlWithParameters, fullPlan); view = new HtmlView(HtmlString.of("Execution plan with actual timing was logged to the primary site log file")); } else @@ -619,7 +619,7 @@ else if (!preTrack) } catch (InterruptedException e) { - LOG.debug(getClass().getSimpleName() + " is terminating due to interruption"); + LOG.debug("{} is terminating due to interruption", getClass().getSimpleName()); } } @@ -629,7 +629,7 @@ private void manageLongSql(QueryTracker tracker) { while (_longSqlTextQueries.size() >= MAX_LONG_SQL_QUERIES) { - WeakReference ref = _longSqlTextQueries.remove(0); + WeakReference ref = _longSqlTextQueries.removeFirst(); QueryTracker oldTracker = ref.get(); if (oldTracker != null) { diff --git a/api/src/org/labkey/api/data/triggers/ScriptTriggerFactory.java b/api/src/org/labkey/api/data/triggers/ScriptTriggerFactory.java index a8a51a41c41..a167b6ffd17 100644 --- a/api/src/org/labkey/api/data/triggers/ScriptTriggerFactory.java +++ b/api/src/org/labkey/api/data/triggers/ScriptTriggerFactory.java @@ -109,7 +109,7 @@ private Collection getDefaultTriggers(@NotNull Container c, TableInfo t scripts.addAll(titleTriggers); if (!titleTriggers.isEmpty()) - LOG.warn("Rename the file from using title - " + title + ".js to use table name - " + name); + LOG.warn("Rename the file from using title - {}.js to use table name - {}", title, name); } diff --git a/api/src/org/labkey/api/data/validator/ColumnValidator.java b/api/src/org/labkey/api/data/validator/ColumnValidator.java index 8a8f1d511fa..7c6aa564e04 100644 --- a/api/src/org/labkey/api/data/validator/ColumnValidator.java +++ b/api/src/org/labkey/api/data/validator/ColumnValidator.java @@ -16,7 +16,6 @@ package org.labkey.api.data.validator; import org.jetbrains.annotations.Nullable; -import org.labkey.api.dataiterator.DataIterator; import org.labkey.api.exp.property.ValidatorContext; /** diff --git a/api/src/org/labkey/api/data/validator/PropertyValidator.java b/api/src/org/labkey/api/data/validator/PropertyValidator.java index 83b4fa24c3f..a5f7617bc94 100644 --- a/api/src/org/labkey/api/data/validator/PropertyValidator.java +++ b/api/src/org/labkey/api/data/validator/PropertyValidator.java @@ -61,7 +61,7 @@ public String validate(int rowNum, Object value, ValidatorContext validatorConte return null; if (errors.isEmpty()) return null; - String msg = errors.get(0).getMessage(); + String msg = errors.getFirst().getMessage(); errors.clear(); return msg; } diff --git a/api/src/org/labkey/api/dataiterator/BeanDataIterator.java b/api/src/org/labkey/api/dataiterator/BeanDataIterator.java index c8aa3e35f3c..232639ee808 100644 --- a/api/src/org/labkey/api/dataiterator/BeanDataIterator.java +++ b/api/src/org/labkey/api/dataiterator/BeanDataIterator.java @@ -42,7 +42,7 @@ public BeanDataIterator(DataIteratorContext context, Class cls, List rows) _class = cls; _cols.add(new BaseColumnInfo(ROWNUMBER_COLUMNNAME, JdbcType.INTEGER)); _readMethods.add(null); - K bean = rows.isEmpty() ? null : rows.get(0); + K bean = rows.isEmpty() ? null : rows.getFirst(); for (PropertyDescriptor origDescriptor : PropertyUtils.getPropertyDescriptors(cls)) { diff --git a/api/src/org/labkey/api/dataiterator/DataIteratorUtil.java b/api/src/org/labkey/api/dataiterator/DataIteratorUtil.java index 0922be2d010..cb60e9099fd 100644 --- a/api/src/org/labkey/api/dataiterator/DataIteratorUtil.java +++ b/api/src/org/labkey/api/dataiterator/DataIteratorUtil.java @@ -21,7 +21,6 @@ import org.apache.commons.io.IOUtils; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; -import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.junit.Assert; import org.junit.Test; @@ -252,7 +251,7 @@ protected static ArrayList> _matchColumns(DataIterato } if (null != to && null == to.first) { - LOG.info("Column Info is null here: - " + from.getColumnName() + " in " + target.getName()); + LOG.info("Column Info is null here: - {} in {}", from.getColumnName(), target.getName()); } matches.add(to); } diff --git a/api/src/org/labkey/api/dataiterator/ExistingRecordDataIterator.java b/api/src/org/labkey/api/dataiterator/ExistingRecordDataIterator.java index ba81874d07b..610e3ac8b48 100644 --- a/api/src/org/labkey/api/dataiterator/ExistingRecordDataIterator.java +++ b/api/src/org/labkey/api/dataiterator/ExistingRecordDataIterator.java @@ -204,7 +204,7 @@ public boolean next() throws BatchValidationException protected void checkDuplicateKeys(List pkKeys) { - Object pkKeysObj = pkKeys.size() == 1 ? pkKeys.get(0) : pkKeys; + Object pkKeysObj = pkKeys.size() == 1 ? pkKeys.getFirst() : pkKeys; if (_pkKeysSeen.contains(pkKeysObj)) _context.getErrors().addRowError(new ValidationException("Duplicate key provided: " + StringUtils.join(pkKeys, ", "))); _pkKeysSeen.add(pkKeysObj); diff --git a/api/src/org/labkey/api/dataiterator/MapDataIterator.java b/api/src/org/labkey/api/dataiterator/MapDataIterator.java index 18c94db9510..7aeffae365e 100644 --- a/api/src/org/labkey/api/dataiterator/MapDataIterator.java +++ b/api/src/org/labkey/api/dataiterator/MapDataIterator.java @@ -102,7 +102,7 @@ public MapDataIteratorImpl(DataIterator in, boolean mutable, Set skip) _findMap.put(in.getColumnInfo(i).getName(),i); } if (null != duplicates) - LOGGER.warn("Data has duplicate columns: '" + StringUtils.join(duplicates.toArray(), ", ") + "'"); + LOGGER.warn("Data has duplicate columns: '{}'", StringUtils.join(duplicates.toArray(), ", ")); } @Override diff --git a/api/src/org/labkey/api/dataiterator/QueryDataIteratorBuilder.java b/api/src/org/labkey/api/dataiterator/QueryDataIteratorBuilder.java index 7ed127c15a4..c2c938ef4d8 100644 --- a/api/src/org/labkey/api/dataiterator/QueryDataIteratorBuilder.java +++ b/api/src/org/labkey/api/dataiterator/QueryDataIteratorBuilder.java @@ -148,7 +148,7 @@ public DataIterator getDataIterator(DataIteratorContext context) if (!qerrors.isEmpty()) { - context.getErrors().addRowError(new ValidationException(qerrors.get(0).getMessage())); + context.getErrors().addRowError(new ValidationException(qerrors.getFirst().getMessage())); return null; } diff --git a/api/src/org/labkey/api/dataiterator/ResultSetDataIterator.java b/api/src/org/labkey/api/dataiterator/ResultSetDataIterator.java index 43043e0312f..f6a91fe9a61 100644 --- a/api/src/org/labkey/api/dataiterator/ResultSetDataIterator.java +++ b/api/src/org/labkey/api/dataiterator/ResultSetDataIterator.java @@ -178,7 +178,7 @@ public void test() throws Exception assertEquals(JdbcType.VARCHAR, it.getColumnInfo(2).getJdbcType()); assertTrue(it.next()); assertEquals(1, it.get(0)); - assertEquals(null, it.get(1)); + assertNull(it.get(1)); assertEquals("null", it.get(2)); assertTrue(it.next()); assertEquals(2, it.get(0)); diff --git a/api/src/org/labkey/api/dataiterator/SimpleTranslator.java b/api/src/org/labkey/api/dataiterator/SimpleTranslator.java index 8480f6f93bd..5dcd3249d5c 100644 --- a/api/src/org/labkey/api/dataiterator/SimpleTranslator.java +++ b/api/src/org/labkey/api/dataiterator/SimpleTranslator.java @@ -57,7 +57,6 @@ import org.labkey.api.data.TableSelector; import org.labkey.api.data.TestSchema; import org.labkey.api.exp.MvFieldWrapper; -import org.labkey.api.exp.PropertyDescriptor; import org.labkey.api.exp.PropertyType; import org.labkey.api.files.FileContentService; import org.labkey.api.ontology.Unit; @@ -226,7 +225,7 @@ public void setIncludePkLookup(boolean includePkLookup) public ColumnInfo getPkColumn() { - return _targetTable.getPkColumns().get(0); + return _targetTable.getPkColumns().getFirst(); } private List>> getMaps() @@ -251,7 +250,7 @@ public ColumnInfo getPkColumn() if (def.columns().size() != 1) continue; - ColumnInfo col = def.columns().get(0); + ColumnInfo col = def.columns().getFirst(); if (!seen.add(col)) continue; @@ -743,7 +742,7 @@ public Object get() if (!this.us.getContainer().allowRowMutationForContainer(rowContainer)) { getRowError().addError(new SimpleValidationError("Row supplied container value: " + rowContainerVal + " cannot be used for actions against the container: " + us.getContainer().getPath())); - LOG.warn("Resolved container to " + rowContainer.getPath() + " but rejected as valid location for import into " + us.getContainer().getPath() + " in " + us.getSchemaName() + "." + tableInfo.getPublicSchemaName()); + LOG.warn("Resolved container to {} but rejected as valid location for import into {} in {}.{}", rowContainer.getPath(), us.getContainer().getPath(), us.getSchemaName(), tableInfo.getPublicSchemaName()); } else { @@ -757,7 +756,7 @@ public Object get() // only log if the incoming value is GUID-like if (rowContainerVal instanceof String && GUID.isGUID((String)rowContainerVal)) { - LOG.warn("Failed to resolve container value '" + rowContainerVal + "' to container for import into " + us.getSchemaName() + "." + tableInfo.getPublicSchemaName() + ", defaulting to original target container of " + us.getContainer().getPath()); + LOG.warn("Failed to resolve container value '{}' to container for import into {}.{}, defaulting to original target container of {}", rowContainerVal, us.getSchemaName(), tableInfo.getPublicSchemaName(), us.getContainer().getPath()); } } } @@ -1402,7 +1401,7 @@ public int addSharedTableLookupColumn(int fromIndex, @Nullable FieldKey extraCol { Set columnNames = new HashSet<>(); final String lookupColumnName = extraColumnFieldKey.getName(); - final String lookupTablePkColumnName = tableInfo.getPkColumns().get(0).getName(); // Expect only 1 + final String lookupTablePkColumnName = tableInfo.getPkColumns().getFirst().getName(); // Expect only 1 columnNames.add(lookupColumnName); columnNames.add(lookupTablePkColumnName); new TableSelector(tableInfo, columnNames).forEachMap(row -> { @@ -2052,9 +2051,9 @@ public void passthroughTest() throws Exception SimpleTranslator t = new SimpleTranslator(simpleData, context); t.selectAll(); assert(t.getColumnCount() == simpleData.getColumnCount()); - assertTrue(t.getColumnInfo(0).getJdbcType() == JdbcType.INTEGER); + assertSame(t.getColumnInfo(0).getJdbcType(), JdbcType.INTEGER); for (int i=1 ; i<=t.getColumnCount() ; i++) - assertTrue(t.getColumnInfo(i).getJdbcType() == JdbcType.VARCHAR); + assertSame(t.getColumnInfo(i).getJdbcType(), JdbcType.VARCHAR); for (int i=1 ; i<=4 ; i++) { assertTrue(t.next()); diff --git a/api/src/org/labkey/api/dataiterator/StatementDataIterator.java b/api/src/org/labkey/api/dataiterator/StatementDataIterator.java index 0de013d9048..9bdf2b794d3 100644 --- a/api/src/org/labkey/api/dataiterator/StatementDataIterator.java +++ b/api/src/org/labkey/api/dataiterator/StatementDataIterator.java @@ -406,7 +406,7 @@ else if (_errors.getExtraContext() != null) if (_currentBatchSize > 0) // flush the statement batch buffer processBatch(_currentBatchSize, _currentRowNumber); if (_log != null) - _log.info("Committing " + Integer.toString(_txSize) + " rows"); + _log.info("Committing {} rows", Integer.toString(_txSize)); _currentStmt.getScope().getCurrentTransaction().commitAndKeepConnection(); } @@ -923,7 +923,7 @@ else if (i==1) } @Override - public boolean next() throws BatchValidationException + public boolean next() { currentRow++; if (currentRow == totalRows || (currentRow % rowsPerBatch == (rowsPerBatch-1))) diff --git a/api/src/org/labkey/api/defaults/SetDefaultValuesAction.java b/api/src/org/labkey/api/defaults/SetDefaultValuesAction.java index dfaac707803..9c1c64f304d 100644 --- a/api/src/org/labkey/api/defaults/SetDefaultValuesAction.java +++ b/api/src/org/labkey/api/defaults/SetDefaultValuesAction.java @@ -16,7 +16,6 @@ package org.labkey.api.defaults; import org.apache.commons.beanutils.ConversionException; -import org.apache.commons.beanutils.ConvertUtils; import org.labkey.api.action.SpringActionController; import org.labkey.api.data.ActionButton; import org.labkey.api.data.ButtonBar; @@ -337,7 +336,7 @@ public HttpView getView(FormType domainIdForm, boolean reshow, BindException err else overrideHtml.append("These values override defaults set in the following folder:"); overrideHtml.unsafeAppend("
"); - Container container = overridees.get(overridees.size() - 1); + Container container = overridees.getLast(); overrideHtml.append(editURL(container, domainIdForm)); } List overriders = DefaultValueService.get().getDefaultValueOverriders(domainIdForm.getContainer(), domain); diff --git a/api/src/org/labkey/api/docker/DockerService.java b/api/src/org/labkey/api/docker/DockerService.java index f92732529d8..316e3ca1dbe 100644 --- a/api/src/org/labkey/api/docker/DockerService.java +++ b/api/src/org/labkey/api/docker/DockerService.java @@ -329,18 +329,14 @@ enum ContainerStatus public static ContainerStatus mapDockerNativeStatus(String status) { // Map Docker API statuses to ours - switch (status) + return switch (status) { - case "running": - return RUNNING; - case "restarting": - return STARTING; - case "exited": - return STOPPED; + case "running" -> RUNNING; + case "restarting" -> STARTING; + case "exited" -> STOPPED; // TODO: Created, Paused, Dead - default: - return NOTSTARTED; - } + default -> NOTSTARTED; + }; } } diff --git a/api/src/org/labkey/api/exp/AbstractFileXarSource.java b/api/src/org/labkey/api/exp/AbstractFileXarSource.java index 83211296351..69290214e1a 100644 --- a/api/src/org/labkey/api/exp/AbstractFileXarSource.java +++ b/api/src/org/labkey/api/exp/AbstractFileXarSource.java @@ -32,7 +32,6 @@ import java.io.IOException; import java.io.InputStream; import java.net.URI; -import java.nio.file.Files; import java.nio.file.InvalidPathException; import java.nio.file.Path; import java.util.Map; diff --git a/api/src/org/labkey/api/exp/AbstractParameter.java b/api/src/org/labkey/api/exp/AbstractParameter.java index 33ad142c805..3f2af9f2b0b 100644 --- a/api/src/org/labkey/api/exp/AbstractParameter.java +++ b/api/src/org/labkey/api/exp/AbstractParameter.java @@ -275,15 +275,14 @@ else if (type.equals(SimpleTypeNames.PROPERTY_URI)) else { if (!type.equals(SimpleTypeNames.STRING)) - log.error("Unrecognized valueType '" + type + "' saved as string"); + log.error("Unrecognized valueType '{}' saved as string", type); type = SimpleTypeNames.STRING; val = stringValue; } } catch (ConversionException | NumberFormatException e) { - log.error("Failed to load value " + stringValue - + ". Declared as type ;" + type + "' Saved as string instead"); + log.error("Failed to load value {}. Declared as type ;{}' Saved as string instead", stringValue, type); type = SimpleTypeNames.STRING; val = stringValue; } diff --git a/api/src/org/labkey/api/exp/ExperimentRunListView.java b/api/src/org/labkey/api/exp/ExperimentRunListView.java index ce5827a8c43..9224c6746f6 100644 --- a/api/src/org/labkey/api/exp/ExperimentRunListView.java +++ b/api/src/org/labkey/api/exp/ExperimentRunListView.java @@ -296,12 +296,11 @@ protected DataRegion createDataRegion() @Override protected ActionURL urlFor(QueryAction action) { - switch (action) + return switch (action) { - case deleteQueryRows: - return null; - } - return super.urlFor(action); + case deleteQueryRows -> null; + default -> super.urlFor(action); + }; } /* override createTable, because some callers expect an unlocked TableInfo */ diff --git a/api/src/org/labkey/api/exp/FileXarSource.java b/api/src/org/labkey/api/exp/FileXarSource.java index ccdcc593f1c..c10b306971e 100644 --- a/api/src/org/labkey/api/exp/FileXarSource.java +++ b/api/src/org/labkey/api/exp/FileXarSource.java @@ -22,7 +22,6 @@ import org.labkey.vfs.FileLike; import java.io.IOException; -import java.nio.file.Path; import java.util.Map; /** diff --git a/api/src/org/labkey/api/exp/ImportTypesHelper.java b/api/src/org/labkey/api/exp/ImportTypesHelper.java index f694a2f3a28..1a0dd2ff9e8 100644 --- a/api/src/org/labkey/api/exp/ImportTypesHelper.java +++ b/api/src/org/labkey/api/exp/ImportTypesHelper.java @@ -50,7 +50,6 @@ import java.util.Arrays; import java.util.Collection; import java.util.Date; -import java.util.HashSet; import java.util.LinkedHashSet; import java.util.List; import java.util.Set; diff --git a/api/src/org/labkey/api/exp/Lsid.java b/api/src/org/labkey/api/exp/Lsid.java index e10744304dd..0cfa516eba4 100644 --- a/api/src/org/labkey/api/exp/Lsid.java +++ b/api/src/org/labkey/api/exp/Lsid.java @@ -587,7 +587,7 @@ public void testSimpleDecode() assertEquals("SampleSet", simpleLsid.getNamespacePrefix()); assertEquals("Folder-4", simpleLsid.getNamespaceSuffix()); assertEquals("ReproSet", simpleLsid.getObjectId()); - assertEquals(null, simpleLsid.getVersion()); + assertNull(simpleLsid.getVersion()); } @Test @@ -599,7 +599,7 @@ public void testSimpleEncode() assertEquals("SampleSet", simpleLsid.getNamespacePrefix()); assertEquals("Folder-4", simpleLsid.getNamespaceSuffix()); assertEquals("ReproSet", simpleLsid.getObjectId()); - assertEquals(null, simpleLsid.getVersion()); + assertNull(simpleLsid.getVersion()); } @Test @@ -611,7 +611,7 @@ public void testDecodeWithColon() assertEquals("SampleSet", lsid.getNamespacePrefix()); assertEquals("Folder-4", lsid.getNamespaceSuffix()); assertEquals("Repro:Set", lsid.getObjectId()); - assertEquals(null, lsid.getVersion()); + assertNull(lsid.getVersion()); } @Test @@ -623,7 +623,7 @@ public void testEncodeWithColon() assertEquals("SampleSet", lsid.getNamespacePrefix()); assertEquals("Folder-4", lsid.getNamespaceSuffix()); assertEquals("Repro:Set", lsid.getObjectId()); - assertEquals(null, lsid.getVersion()); + assertNull(lsid.getVersion()); } @Test @@ -635,7 +635,7 @@ public void testDecodeWithPercent() assertEquals("SampleSet", lsid.getNamespacePrefix()); assertEquals("Folder-4", lsid.getNamespaceSuffix()); assertEquals("Repro%Set", lsid.getObjectId()); - assertEquals(null, lsid.getVersion()); + assertNull(lsid.getVersion()); } @Test @@ -647,7 +647,7 @@ public void testDecodeWithSpace() assertEquals("SampleSet", lsid.getNamespacePrefix()); assertEquals("Folder-4", lsid.getNamespaceSuffix()); assertEquals("Repro Set", lsid.getObjectId()); - assertEquals(null, lsid.getVersion()); + assertNull(lsid.getVersion()); lsid = Lsid.parse("urn:lsid:labkey.com:SampleSet.Folder-4:Repro+Set"); assertEquals("urn:lsid:labkey.com:SampleSet.Folder-4:Repro+Set", lsid.toString()); @@ -655,7 +655,7 @@ public void testDecodeWithSpace() assertEquals("SampleSet", lsid.getNamespacePrefix()); assertEquals("Folder-4", lsid.getNamespaceSuffix()); assertEquals("Repro Set", lsid.getObjectId()); - assertEquals(null, lsid.getVersion()); + assertNull(lsid.getVersion()); } @Test @@ -667,7 +667,7 @@ public void testEncodeWithSpace() assertEquals("SampleSet", lsid.getNamespacePrefix()); assertEquals("Folder-4", lsid.getNamespaceSuffix()); assertEquals("Repro Set", lsid.getObjectId()); - assertEquals(null, lsid.getVersion()); + assertNull(lsid.getVersion()); } @Test @@ -679,7 +679,7 @@ public void testDecodeWithPlus() assertEquals("SampleSet", lsid.getNamespacePrefix()); assertEquals("Folder-4", lsid.getNamespaceSuffix()); assertEquals("Repro+Set", lsid.getObjectId()); - assertEquals(null, lsid.getVersion()); + assertNull(lsid.getVersion()); } @Test diff --git a/api/src/org/labkey/api/exp/LsidManager.java b/api/src/org/labkey/api/exp/LsidManager.java index a9a6bf43870..1a5fbfc59e2 100644 --- a/api/src/org/labkey/api/exp/LsidManager.java +++ b/api/src/org/labkey/api/exp/LsidManager.java @@ -397,11 +397,11 @@ public boolean testResolveAll(Container c) List objectURIs = new TableSelector(OntologyManager.getTinfoObject(), Set.of("ObjectURI"), SimpleFilter.createContainerFilter(c), new Sort("ObjectId")).getArrayList(String.class); if (objectURIs.isEmpty()) { - LOG.info("No objects to resolve in container (" + c.getId() + "): " + c); + LOG.info("No objects to resolve in container ({}): {}", c.getId(), c); return true; } - LOG.info("Resolving " + objectURIs.size() + " LSIDs in container (" + c.getId() + "): " + c.getPath()); + LOG.info("Resolving {} LSIDs in container ({}): {}", objectURIs.size(), c.getId(), c.getPath()); int success = 0; int failed = 0; @@ -412,23 +412,23 @@ public boolean testResolveAll(Container c) Identifiable obj = getObject(objectURI); if (obj == null) { - LOG.warn("Failed to resolve '" + objectURI + "'"); + LOG.warn("Failed to resolve '{}'", objectURI); failed++; } else { - LOG.info("Resolved '" + objectURI + "' to object (" + obj.getClass().getSimpleName() + "): " + obj.getName()); + LOG.info("Resolved '{}' to object ({}): {}", objectURI, obj.getClass().getSimpleName(), obj.getName()); success++; } } catch (Exception e) { - LOG.error("Error when resolving '" + objectURI + "'", e); + LOG.error("Error when resolving '{}'", objectURI, e); failed++; } } - LOG.info("Resolved " + success + " of " + objectURIs.size() + " LSIDs in container (" + c.getId() + "): " + c.getPath()); + LOG.info("Resolved {} of {} LSIDs in container ({}): {}", success, objectURIs.size(), c.getId(), c.getPath()); return failed == 0; } } diff --git a/api/src/org/labkey/api/exp/ObjectProperty.java b/api/src/org/labkey/api/exp/ObjectProperty.java index 5c3b0c3d4be..15fec7fd966 100644 --- a/api/src/org/labkey/api/exp/ObjectProperty.java +++ b/api/src/org/labkey/api/exp/ObjectProperty.java @@ -24,7 +24,6 @@ import org.labkey.api.util.GUID; import java.io.File; -import java.sql.Array; import java.util.Collections; import java.util.Date; import java.util.Map; diff --git a/api/src/org/labkey/api/exp/OntologyManager.java b/api/src/org/labkey/api/exp/OntologyManager.java index f509e343236..b284960bccf 100644 --- a/api/src/org/labkey/api/exp/OntologyManager.java +++ b/api/src/org/labkey/api/exp/OntologyManager.java @@ -119,7 +119,7 @@ public PropertyDescriptor load(@NotNull Pair key, @Nullable Object Container proj = c.getProject(); if (null == proj) proj = c; - _log.debug("Loading a property descriptor for key " + key + " using project " + proj); + _log.debug("Loading a property descriptor for key {} using project {}", key, proj); String sql = " SELECT * FROM " + getTinfoPropertyDescriptor() + " WHERE PropertyURI = ? AND Project IN (?,?)"; List pdArray = new SqlSelector(getExpSchema(), sql, propertyURI, proj, ContainerManager.getSharedContainer().getId()).getArrayList(PropertyDescriptor.class); if (!pdArray.isEmpty()) @@ -130,11 +130,11 @@ public PropertyDescriptor load(@NotNull Pair key, @Nullable Object // and one of the two is in the shared project, use the project-level descriptor. if (pdArray.size() > 1) { - _log.debug("Multiple PropertyDescriptors found for " + propertyURI); + _log.debug("Multiple PropertyDescriptors found for {}", propertyURI); if (pd.getProject().equals(ContainerManager.getSharedContainer())) pd = pdArray.get(1); } - _log.debug("Loaded property descriptor " + pd); + _log.debug("Loaded property descriptor {}", pd); ret = pd; } } @@ -471,10 +471,10 @@ public static void insertTabDelimited(Container c, } assert total.stop(); - _log.debug("\t" + total); - _log.debug("\t" + before); - _log.debug("\t" + ensure); - _log.debug("\t" + insert); + _log.debug("\t{}", total); + _log.debug("\t{}", before); + _log.debug("\t{}", ensure); + _log.debug("\t{}", insert); } /** @@ -717,7 +717,7 @@ private static void saveTabDelimited(TableInfo table, helper.afterBatchInsert(rowCount); if (logger != null) - logger.debug("inserted row " + rowCount + "."); + logger.debug("inserted row {}.", rowCount); } catch (ValidationException e) { @@ -796,9 +796,9 @@ public interface ImportHelper */ String beforeImportObject(Map map) throws SQLException; - void afterBatchInsert(int currentRow) throws SQLException; + void afterBatchInsert(int currentRow); - void updateStatistics(int currentRow) throws SQLException; + void updateStatistics(int currentRow); } @@ -808,7 +808,7 @@ public interface UpdateableTableImportHelper extends ImportHelper * may be used to process attachments, for auditing, etc * @return the LSID of the inserted row */ - String afterImportObject(Map map) throws SQLException; + String afterImportObject(Map map); /** * may set parameters directly for columns that are not exposed by tableinfo @@ -897,7 +897,7 @@ public Map load(@NotNull Pair key, @N } catch (ConversionException e) { - _log.warn("Failed to parse PropertyOrder integer list: " + order); + _log.warn("Failed to parse PropertyOrder integer list: {}", order); } } } @@ -1165,7 +1165,7 @@ public static void deleteObjectsOfType(String domainURI, Container container) dd = getDomainDescriptor(domainURI, container); if (null == dd) { - _log.debug("deleteObjectsOfType called on type not found in database: " + domainURI); + _log.debug("deleteObjectsOfType called on type not found in database: {}", domainURI); return; } @@ -1373,7 +1373,7 @@ public static void deleteAllObjects(Container c, User user) throws ValidationExc private static void copyDescriptors(final Container c, final Container project) throws ValidationException { - _log.debug("OntologyManager.copyDescriptors " + c.getName() + " " + project.getName()); + _log.debug("OntologyManager.copyDescriptors {} {}", c.getName(), project.getName()); // if c is (was) a project, then nothing to do if (c.getId().equals(project.getId())) @@ -1463,7 +1463,7 @@ private static void copyDescriptors(final Container c, final Container project) if (pd.getContainer().getId().equals(c.getId())) { - _log.debug("Removing property descriptor from cache. Key: " + getCacheKey(pd) + " descriptor: " + pd); + _log.debug("Removing property descriptor from cache. Key: {} descriptor: {}", getCacheKey(pd), pd); PROP_DESCRIPTOR_CACHE.remove(getCacheKey(pd)); DOMAIN_PROPERTIES_CACHE.clear(); pd.setContainer(project); @@ -1509,7 +1509,7 @@ private static void uncache(DomainDescriptor dd) public static void moveContainer(@NotNull final Container c, @NotNull Container oldParent, @NotNull Container newParent) throws SQLException { - _log.debug("OntologyManager.moveContainer " + c.getName() + " " + oldParent.getName() + "->" + newParent.getName()); + _log.debug("OntologyManager.moveContainer {} {}->{}", c.getName(), oldParent.getName(), newParent.getName()); final Container oldProject = oldParent.getProject(); Container newProject = newParent.getProject(); @@ -1717,7 +1717,7 @@ private static PropertyDescriptor ensurePropertyDescriptor(PropertyDescriptor pd pd = out[0]; if (1 == rowcount && null != pd) { - _log.debug("Removing property descriptor from cache. Key: " + getCacheKey(pd) + " descriptor: " + pd); + _log.debug("Removing property descriptor from cache. Key: {} descriptor: {}", getCacheKey(pd), pd); PROP_DESCRIPTOR_CACHE.remove(getCacheKey(pd)); return pd; } @@ -2174,7 +2174,7 @@ public static void deletePropertyDescriptor(PropertyDescriptor pd) executor.execute(deletePropDomSql); executor.execute(deletePropSql); Pair key = getCacheKey(pd); - _log.debug("Removing property descriptor from cache. Key: " + key + " descriptor: " + pd); + _log.debug("Removing property descriptor from cache. Key: {} descriptor: {}", key, pd); PROP_DESCRIPTOR_CACHE.remove(key); DOMAIN_PROPERTIES_CACHE.clear(); transaction.commit(); @@ -2666,7 +2666,7 @@ public static PropertyDescriptor insertOrUpdatePropertyDescriptor(PropertyDescri "excludefromshifting,mvindicatorstoragecolumnname,defaultscale,scannable"; static final String[] parametersArray = parameters.split(","); - static ParameterMapStatement getInsertStmt(Connection conn, User user, TableInfo t, boolean ifNotExists) throws SQLException + static ParameterMapStatement getInsertStmt(Connection conn, User user, TableInfo t, boolean ifNotExists) { user = null==user ? User.guest : user; SQLFragment sql = new SQLFragment("INSERT INTO exp.propertydescriptor\n\t\t("); @@ -2705,7 +2705,7 @@ public static PropertyDescriptor insertPropertyDescriptor(PropertyDescriptor pd) assert pd.getPropertyId() == 0; validatePropertyDescriptor(pd); pd = Table.insert(null, getTinfoPropertyDescriptor(), pd); - _log.debug("Adding property descriptor to cache. Key: " + getCacheKey(pd) + " descriptor: " + pd); + _log.debug("Adding property descriptor to cache. Key: {} descriptor: {}", getCacheKey(pd), pd); PROP_DESCRIPTOR_CACHE.remove(getCacheKey(pd)); return pd; } @@ -2715,7 +2715,7 @@ public static PropertyDescriptor updatePropertyDescriptor(PropertyDescriptor pd) { assert pd.getPropertyId() != 0; pd = Table.update(null, getTinfoPropertyDescriptor(), pd, pd.getPropertyId()); - _log.debug("Updating property descriptor in cache. Key: " + getCacheKey(pd) + " descriptor: " + pd); + _log.debug("Updating property descriptor in cache. Key: {} descriptor: {}", getCacheKey(pd), pd); PROP_DESCRIPTOR_CACHE.remove(getCacheKey(pd)); // It's possible that the propertyURI has changed, thus breaking our reference DOMAIN_PROPERTIES_CACHE.clear(); diff --git a/api/src/org/labkey/api/exp/PropertyDescriptor.java b/api/src/org/labkey/api/exp/PropertyDescriptor.java index 62efaecdd7e..50ab0f9d203 100644 --- a/api/src/org/labkey/api/exp/PropertyDescriptor.java +++ b/api/src/org/labkey/api/exp/PropertyDescriptor.java @@ -324,7 +324,7 @@ public JdbcType getJdbcType() PropertyType type = getPropertyType(); if (type == null) { - LOG.warn("Could not determine propertyType from RangeURI " + getRangeURI() + " and ConceptURI " + getConceptURI() + " for PropertyURI " + getPropertyURI() + ", defaulting to string"); + LOG.warn("Could not determine propertyType from RangeURI {} and ConceptURI {} for PropertyURI {}, defaulting to string", getRangeURI(), getConceptURI(), getPropertyURI()); type = PropertyType.STRING; } return type.getJdbcType(); diff --git a/api/src/org/labkey/api/exp/XarContext.java b/api/src/org/labkey/api/exp/XarContext.java index 1c368d4935f..cc5fbfbede4 100644 --- a/api/src/org/labkey/api/exp/XarContext.java +++ b/api/src/org/labkey/api/exp/XarContext.java @@ -29,8 +29,6 @@ import org.labkey.api.settings.AppProps; import org.labkey.api.util.GUID; import org.labkey.api.util.NetworkDrive; -import org.labkey.api.util.Path; -import org.labkey.vfs.FileLike; import java.io.File; import java.net.URI; diff --git a/api/src/org/labkey/api/exp/XarSource.java b/api/src/org/labkey/api/exp/XarSource.java index b3e4475bfe4..aab8a708df9 100644 --- a/api/src/org/labkey/api/exp/XarSource.java +++ b/api/src/org/labkey/api/exp/XarSource.java @@ -121,7 +121,7 @@ public final String getCanonicalDataFileURL(String dataFileURL) throws XarFormat return result; } - protected abstract String canonicalizeDataFileURL(String dataFileURL) throws XarFormatException; + protected abstract String canonicalizeDataFileURL(String dataFileURL); public abstract FileLike getLogFilePath() throws IOException; diff --git a/api/src/org/labkey/api/exp/api/AbstractExperimentDataHandler.java b/api/src/org/labkey/api/exp/api/AbstractExperimentDataHandler.java index 1ca266c0e90..4d4d43a0d49 100644 --- a/api/src/org/labkey/api/exp/api/AbstractExperimentDataHandler.java +++ b/api/src/org/labkey/api/exp/api/AbstractExperimentDataHandler.java @@ -36,11 +36,6 @@ */ public abstract class AbstractExperimentDataHandler implements ExperimentDataHandler { - @Override - public String getFileName(ExpData data, String defaultName) - { - return defaultName; - } @Override public void exportFile(ExpData data, FileLike dataFile, User user, OutputStream out) throws ExperimentException diff --git a/api/src/org/labkey/api/exp/api/AssayJSONConverter.java b/api/src/org/labkey/api/exp/api/AssayJSONConverter.java index cf3e1e514d8..1a5b8f7c830 100644 --- a/api/src/org/labkey/api/exp/api/AssayJSONConverter.java +++ b/api/src/org/labkey/api/exp/api/AssayJSONConverter.java @@ -121,7 +121,7 @@ public static JSONObject serializeRun(ExpRun run, AssayProvider provider, ExpPro if (datas.size() == 1) { - dataRows = serializeDataRows(datas.get(0), provider, protocol, user); + dataRows = serializeDataRows(datas.getFirst(), provider, protocol, user); } else if (datas.size() > 1) { @@ -129,7 +129,7 @@ else if (datas.size() > 1) List transformedDatas = run.getInputDatas(ExpDataRunInput.IMPORTED_DATA_ROLE, ExpProtocol.ApplicationType.ExperimentRunOutput); if (transformedDatas.size() == 1) { - dataRows = serializeDataRows(transformedDatas.get(0), provider, protocol, user); + dataRows = serializeDataRows(transformedDatas.getFirst(), provider, protocol, user); } } } diff --git a/api/src/org/labkey/api/exp/api/DefaultExperimentDataHandler.java b/api/src/org/labkey/api/exp/api/DefaultExperimentDataHandler.java index 8c4600200a1..229fdc6d7af 100644 --- a/api/src/org/labkey/api/exp/api/DefaultExperimentDataHandler.java +++ b/api/src/org/labkey/api/exp/api/DefaultExperimentDataHandler.java @@ -26,8 +26,6 @@ import org.labkey.api.view.ViewBackgroundInfo; import org.labkey.vfs.FileLike; -import java.io.File; - /** * A default, essentially no-op handler for {@link ExpData} that are not recognized by any other handlers. * User: jeckels @@ -44,7 +42,7 @@ public DataType getDataType() @Override public void importFile(@NotNull ExpData data, @NotNull FileLike dataFile, @NotNull ViewBackgroundInfo info, @NotNull Logger log, @NotNull XarContext context) { - log.debug("No ExperimentDataHandler registered for data file " + data.getDataFileURI() + ", no special loading will be done on this file."); + log.debug("No ExperimentDataHandler registered for data file {}, no special loading will be done on this file.", data.getDataFileURI()); } @Override diff --git a/api/src/org/labkey/api/exp/api/DefaultExperimentSaveHandler.java b/api/src/org/labkey/api/exp/api/DefaultExperimentSaveHandler.java index 6396392949d..cfd70dfeec1 100644 --- a/api/src/org/labkey/api/exp/api/DefaultExperimentSaveHandler.java +++ b/api/src/org/labkey/api/exp/api/DefaultExperimentSaveHandler.java @@ -172,7 +172,7 @@ private boolean checkRunsInBatch(ExpExperiment batch, Collection runs) { if (!batch.equals(run.getBatch())) { - LOG.warn("Run '" + run + "' is not in batch '" + batch + "'"); + LOG.warn("Run '{}' is not in batch '{}'", run, batch); return false; } } @@ -548,7 +548,7 @@ else if (sampleType != null && !sampleType.hasNameAsIdCol() && materialObject.ha if (materials.size() > 1) throw new NotFoundException("More than one material matches name '" + materialName + "'. Provide name and sampleType to disambiguate the desired material."); if (materials.size() == 1) - material = materials.get(0); + material = materials.getFirst(); } if (material == null) diff --git a/api/src/org/labkey/api/exp/api/ExpData.java b/api/src/org/labkey/api/exp/api/ExpData.java index dac0b81068c..81460141c6b 100644 --- a/api/src/org/labkey/api/exp/api/ExpData.java +++ b/api/src/org/labkey/api/exp/api/ExpData.java @@ -30,7 +30,6 @@ import java.io.File; import java.net.URI; import java.nio.file.Path; -import java.sql.SQLException; /** * Represents a virtual experiment object. Typically, a file on disk, but could be something pointed at by any URI including S3 objects. @@ -94,7 +93,7 @@ public interface ExpData extends ExpRunItem @Nullable ExpDataClass getDataClass(@Nullable User user); - void importDataFile(PipelineJob job, XarSource xarSource) throws ExperimentException, SQLException; + void importDataFile(PipelineJob job, XarSource xarSource) throws ExperimentException; /** @return the search document id for this material */ String getDocumentId(); diff --git a/api/src/org/labkey/api/exp/api/ExpLineage.java b/api/src/org/labkey/api/exp/api/ExpLineage.java index 772bd46f1f8..0075e13eb5e 100644 --- a/api/src/org/labkey/api/exp/api/ExpLineage.java +++ b/api/src/org/labkey/api/exp/api/ExpLineage.java @@ -16,9 +16,9 @@ package org.labkey.api.exp.api; import org.apache.commons.lang3.StringUtils; -import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.json.JSONObject; +import org.jetbrains.annotations.NotNull; import org.labkey.api.exp.Identifiable; import org.labkey.api.security.User; import org.labkey.api.util.Pair; @@ -419,7 +419,7 @@ private JSONObject toJSON(String target) } @Override - public String toString() + public @NotNull String toString() { return "[" + parent + "] -> [" + child + "]"; } @@ -512,7 +512,7 @@ public static Set getNodes(ExpLineageTree tree, List ancestorPath = ancestorPaths.get(0); + Pair ancestorPath = ancestorPaths.getFirst(); ExpLineageOptions.LineageExpType expType = ancestorPath.first; String cpas = ancestorPath.second; diff --git a/api/src/org/labkey/api/exp/api/ExpLineageEdge.java b/api/src/org/labkey/api/exp/api/ExpLineageEdge.java index daf1cb212d1..984049ceba1 100644 --- a/api/src/org/labkey/api/exp/api/ExpLineageEdge.java +++ b/api/src/org/labkey/api/exp/api/ExpLineageEdge.java @@ -2,7 +2,6 @@ import org.labkey.api.collections.LongHashSet; -import java.util.HashSet; import java.util.Objects; import java.util.Set; diff --git a/api/src/org/labkey/api/exp/api/ExperimentListener.java b/api/src/org/labkey/api/exp/api/ExperimentListener.java index 90afe48ddd9..9c90dd1b9df 100644 --- a/api/src/org/labkey/api/exp/api/ExperimentListener.java +++ b/api/src/org/labkey/api/exp/api/ExperimentListener.java @@ -41,7 +41,8 @@ default void afterRunDelete(ExpProtocol protocol, ExpRun run, User user) { } default void afterRunSaved(Container container, User user, ExpProtocol protocol, ExpRun run) { } /** Called before the experiment run is saved (in-transaction). */ - default void beforeRunSaved(Container container, User user, ExpProtocol protocol, ExpRun run) throws BatchValidationException { } + default void beforeRunSaved(Container container, User user, ExpProtocol protocol, ExpRun run) + { } /** Called after run data is uploaded. */ default void afterResultDataCreated(Container container, User user, ExpRun run, ExpProtocol protocol) throws BatchValidationException { } diff --git a/api/src/org/labkey/api/exp/api/ExperimentService.java b/api/src/org/labkey/api/exp/api/ExperimentService.java index 20634c5df22..0a73f2544f0 100644 --- a/api/src/org/labkey/api/exp/api/ExperimentService.java +++ b/api/src/org/labkey/api/exp/api/ExperimentService.java @@ -93,7 +93,6 @@ import java.io.IOException; import java.net.URI; import java.nio.file.Path; -import java.sql.SQLException; import java.util.Collection; import java.util.Date; import java.util.HashSet; @@ -847,7 +846,7 @@ static void validateParentAlias(Map aliasMap, Set reserv List getProtocolApplicationParameters(long rowId); - void moveContainer(Container c, Container cOldParent, Container cNewParent) throws ExperimentException; + void moveContainer(Container c, Container cOldParent, Container cNewParent); LsidType findType(Lsid lsid); @@ -1018,7 +1017,7 @@ List getExpProtocolsWithParameterValue( * @param job Pipeline job. * @return the run created from the job's actions. */ - ExpRun importRun(PipelineJob job, XarSource source) throws SQLException, PipelineJobException, ValidationException; + ExpRun importRun(PipelineJob job, XarSource source) throws PipelineJobException, ValidationException; /** * Provides access to an object that should be locked before inserting protocols. Locking when doing diff --git a/api/src/org/labkey/api/exp/api/SampleTypeDomainKind.java b/api/src/org/labkey/api/exp/api/SampleTypeDomainKind.java index 6b06f23ebb0..472427fbc1f 100644 --- a/api/src/org/labkey/api/exp/api/SampleTypeDomainKind.java +++ b/api/src/org/labkey/api/exp/api/SampleTypeDomainKind.java @@ -33,7 +33,6 @@ import org.labkey.api.data.NameExpressionValidationResult; import org.labkey.api.data.NameGenerator; import org.labkey.api.data.PropertyStorageSpec; -import org.labkey.api.data.RuntimeSQLException; import org.labkey.api.data.SQLFragment; import org.labkey.api.data.SqlSelector; import org.labkey.api.data.TableInfo; @@ -71,7 +70,6 @@ import org.labkey.data.xml.domainTemplate.SampleSetTemplateType; import java.io.IOException; -import java.sql.SQLException; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; @@ -295,7 +293,7 @@ public Set getBaseProperties(Domain domain) } catch (IOException e) { - logger.error(String.format("Failed to parse SampleType parent aliases for [%1$s]", st.getRowId()), e); + logger.error("Failed to parse SampleType parent aliases for [{}]", st.getRowId(), e); } return reserved; } @@ -571,10 +569,6 @@ public Domain createDomain(GWTDomain domain, @Nullable Sa st = SampleTypeService.get().createSampleType(container, user, name, description, properties, indices, idCol1, idCol2, idCol3, parentCol, nameExpression, aliquotNameExpression, templateInfo, aliases, labelColor, metricUnit, autoLinkTargetContainer, autoLinkCategory, category, domain.getDisabledSystemFields(), excludedContainerIds, excludedDashboardContainerIds, arguments != null ? arguments.getAuditRecordMap() : null); } - catch (SQLException e) - { - throw new RuntimeSQLException(e); - } catch (ExperimentException e) { throw new RuntimeException(e); diff --git a/api/src/org/labkey/api/exp/api/SampleTypeService.java b/api/src/org/labkey/api/exp/api/SampleTypeService.java index 1b6cd9eaf0b..36bea252fa5 100644 --- a/api/src/org/labkey/api/exp/api/SampleTypeService.java +++ b/api/src/org/labkey/api/exp/api/SampleTypeService.java @@ -131,7 +131,7 @@ static void setInstance(SampleTypeService impl) */ @NotNull ExpSampleType createSampleType(Container container, User user, String name, String description, List properties, List indices, int idCol1, int idCol2, int idCol3, int parentCol, String nameExpression) - throws ExperimentException, SQLException; + throws ExperimentException; /** * (MAB) todo need a builder interface, or at least parameter bean @@ -139,19 +139,19 @@ ExpSampleType createSampleType(Container container, User user, String name, Stri @NotNull ExpSampleType createSampleType(Container container, User user, String name, String description, List properties, List indices, int idCol1, int idCol2, int idCol3, int parentCol, String nameExpression, @Nullable TemplateInfo templateInfo) - throws ExperimentException, SQLException; + throws ExperimentException; @NotNull ExpSampleType createSampleType(Container container, User user, String name, String description, List properties, List indices, int idCol1, int idCol2, int idCol3, int parentCol, String nameExpression, String aliquotNameExpression, @Nullable TemplateInfo templateInfo, @Nullable Map> importAliases, @Nullable String labelColor, @Nullable String metricUnit) - throws ExperimentException, SQLException; + throws ExperimentException; @NotNull ExpSampleType createSampleType(Container c, User u, String name, String description, List properties, List indices, int idCol1, int idCol2, int idCol3, int parentCol, String nameExpression, String aliquotNameExpression, @Nullable TemplateInfo templateInfo, @Nullable Map> importAliases, @Nullable String labelColor, @Nullable String metricUnit, @Nullable Container autoLinkTargetContainer, @Nullable String autoLinkCategory, @Nullable String category, @Nullable List disabledSystemField, @Nullable List excludedContainerIds, @Nullable List excludedDashboardContainerIds, @Nullable Map changeDetails) - throws ExperimentException, SQLException; + throws ExperimentException; @NotNull ExpSampleType createSampleType(); diff --git a/api/src/org/labkey/api/exp/property/DomainKind.java b/api/src/org/labkey/api/exp/property/DomainKind.java index 3a49ee688e0..da4cda6b2d0 100644 --- a/api/src/org/labkey/api/exp/property/DomainKind.java +++ b/api/src/org/labkey/api/exp/property/DomainKind.java @@ -239,12 +239,12 @@ public void invalidate(Domain domain) if (null != storageTableName) { - LOG.debug("Invalidating " + schemaName + "." + storageTableName); + LOG.debug("Invalidating {}.{}", schemaName, storageTableName); getScope().invalidateTable(schemaName, storageTableName, getSchemaType()); } else { - LOG.debug("Invalidating " + schemaName); + LOG.debug("Invalidating {}", schemaName); getScope().invalidateSchema(schemaName, getSchemaType()); } } diff --git a/api/src/org/labkey/api/exp/property/DomainTemplate.java b/api/src/org/labkey/api/exp/property/DomainTemplate.java index 00b965e52b8..5eb5ec5b761 100644 --- a/api/src/org/labkey/api/exp/property/DomainTemplate.java +++ b/api/src/org/labkey/api/exp/property/DomainTemplate.java @@ -109,14 +109,14 @@ public static DomainTemplate findTemplate(String moduleName, String groupName, S Module module = ModuleLoader.getInstance().getModule(moduleName); if (module == null) { - LogManager.getLogger(DomainTemplate.class).warn("Module '" + moduleName + "' for domain template not found"); + LogManager.getLogger(DomainTemplate.class).warn("Module '{}' for domain template not found", moduleName); return null; } DomainTemplateGroup group = DomainTemplateGroup.get(module, groupName); if (group == null) { - LogManager.getLogger(DomainTemplate.class).warn("Domain template group '" + groupName + "' not found in module '" + moduleName + "'"); + LogManager.getLogger(DomainTemplate.class).warn("Domain template group '{}' not found in module '{}'", groupName, moduleName); return null; } @@ -377,7 +377,7 @@ public List getErrors() public void throwErrors() throws BatchValidationException { if (_errors != null && !_errors.isEmpty()) - throw new BatchValidationException(new ValidationException(_errors.get(0))); + throw new BatchValidationException(new ValidationException(_errors.getFirst())); } public Domain createAndImport(Container c, User u, @Nullable String domainName, boolean createDomain, boolean importData) throws BatchValidationException @@ -389,7 +389,7 @@ public Domain createAndImport(Container c, User u, @Nullable String domainName, { try (DbScope.Transaction tx = ExperimentService.get().getSchema().getScope().ensureTransaction()) { - DomainTemplateGroup.LOG.debug("creating domain '" + domainName + "'"); + DomainTemplateGroup.LOG.debug("creating domain '{}'", domainName); d = DomainUtil.createDomain(this, c, u, domainName, true); tx.commit(); } @@ -482,7 +482,7 @@ private int importData(String domainName, InitialDataSettings initialData, Conta try (DbScope.Transaction transaction = table.getSchema().getScope().ensureTransaction()) { - DomainTemplateGroup.LOG.debug("importing data for domain '" + domainName + "' from '" + initialData.file + "'"); + DomainTemplateGroup.LOG.debug("importing data for domain '{}' from '{}'", domainName, initialData.file); int count = updateService.loadRows(u, c, dl, context, new HashMap<>()); if (errors.hasErrors()) return 0; diff --git a/api/src/org/labkey/api/exp/property/DomainTemplateGroup.java b/api/src/org/labkey/api/exp/property/DomainTemplateGroup.java index 99e5f93b37a..8cb2a3ea7bb 100644 --- a/api/src/org/labkey/api/exp/property/DomainTemplateGroup.java +++ b/api/src/org/labkey/api/exp/property/DomainTemplateGroup.java @@ -114,7 +114,7 @@ private String getGroupId(Module module, String groupName) DomainTemplateGroup group = parse(module.getName(), groupName, doc); if (group.hasErrors()) { - LOG.warn("Error parsing domain template '" + groupName + "' in module '" + module.getName() + "'"); + LOG.warn("Error parsing domain template '{}' in module '{}'", groupName, module.getName()); group.getErrors().forEach(LOG::warn); } return group; @@ -126,12 +126,12 @@ private String getGroupId(Module module, String groupName) } catch (XmlValidationException e) { - LOG.warn("Error parsing domain template '" + resource + "'", e); + LOG.warn("Error parsing domain template '{}'", resource, e); return new DomainTemplateGroup(module.getName(), groupName, Collections.emptyList(), Arrays.asList(e.getMessage(), e.getDetails())); } catch (XmlException | IllegalArgumentException e) { - LOG.warn("Error parsing domain template '" + resource + "'", e); + LOG.warn("Error parsing domain template '{}'", resource, e); return new DomainTemplateGroup(module.getName(), groupName, Collections.emptyList(), Arrays.asList(e.getMessage())); } @@ -230,7 +230,7 @@ public List getErrors() public void throwErrors() throws BatchValidationException { if (_errors != null && !_errors.isEmpty()) - throw new BatchValidationException(new ValidationException(_errors.get(0))); + throw new BatchValidationException(new ValidationException(_errors.getFirst())); } public List createAndImport(Container c, User u, boolean createDomain, boolean importData) throws BatchValidationException @@ -329,7 +329,7 @@ public void testDomainTemplateCache() .mapToInt(Map::size) .sum(); - LOG.info(templateCount + " domain templates defined in all modules"); + LOG.info("{} domain templates defined in all modules", templateCount); // Make sure the cache retrieves the expected number of domain templates in the simpletest module, if present diff --git a/api/src/org/labkey/api/exp/property/DomainUtil.java b/api/src/org/labkey/api/exp/property/DomainUtil.java index 0152b74163d..a6c5113291c 100644 --- a/api/src/org/labkey/api/exp/property/DomainUtil.java +++ b/api/src/org/labkey/api/exp/property/DomainUtil.java @@ -786,7 +786,7 @@ public static ValidationException updateDomainDescriptor(GWTDomain orig, GWTDomain update, Container container, User user, boolean updateDomainName, @Nullable String auditComment, @Nullable String auditUserComment, @Nullable Map oldProps, @Nullable Map newProps) { - LOG.info("Updating domain descriptor for " + orig.getName()); + LOG.info("Updating domain descriptor for {}", orig.getName()); assert orig.getDomainURI().equals(update.getDomainURI()); // Issue 52824: when updating, remove domain descriptor from cache so others don't see a descriptor from the cache in a partially updated state @@ -1165,7 +1165,7 @@ public static DomainProperty addProperty(Domain domain, GWTPropertyDescriptor pd if (pd.getPropertyId() > 0) return null; - LOG.debug("Adding property for " + pd.getName()); + LOG.debug("Adding property for {}", pd.getName()); if (StringUtils.isEmpty(pd.getPropertyURI())) { String newPropertyURI = createUniquePropertyURI(domain.getTypeURI(), null, propertyUrisInUse); @@ -1179,7 +1179,7 @@ public static DomainProperty addProperty(Domain domain, GWTPropertyDescriptor pd LOG.debug("Property added as string property"); defaultValues.put(p, pd.getDefaultValue()); _copyProperties(p, pd, errors); - LOG.debug("Properties copied from " + pd + " to " + p.getPropertyDescriptor() ); + LOG.debug("Properties copied from {} to {}", pd, p.getPropertyDescriptor()); updatePropertyValidators(p, null, pd); return p; diff --git a/api/src/org/labkey/api/exp/query/DataClassUserSchema.java b/api/src/org/labkey/api/exp/query/DataClassUserSchema.java index 1dabfa3e55a..2d9e8a64589 100644 --- a/api/src/org/labkey/api/exp/query/DataClassUserSchema.java +++ b/api/src/org/labkey/api/exp/query/DataClassUserSchema.java @@ -15,8 +15,8 @@ */ package org.labkey.api.exp.query; -import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; +import org.jetbrains.annotations.NotNull; import org.labkey.api.collections.CaseInsensitiveTreeMap; import org.labkey.api.data.Container; import org.labkey.api.data.ContainerFilter; @@ -102,7 +102,7 @@ private ExpDataClassDataTable createTable(@NotNull ExpDataClass dataClass, Conta } @Override - public QueryView createView(ViewContext context, @NotNull QuerySettings settings, BindException errors) + public @NotNull QueryView createView(ViewContext context, @NotNull QuerySettings settings, BindException errors) { QueryView queryView = super.createView(context, settings, errors); diff --git a/api/src/org/labkey/api/exp/query/ExpSchema.java b/api/src/org/labkey/api/exp/query/ExpSchema.java index 11e038fa66f..c9b06bb61f1 100644 --- a/api/src/org/labkey/api/exp/query/ExpSchema.java +++ b/api/src/org/labkey/api/exp/query/ExpSchema.java @@ -295,7 +295,7 @@ public ExpExperimentTable createExperimentsTableWithRunMemberships(ExpRun run, C ret.addExperimentMembershipColumn(run); List defaultCols = new ArrayList<>(ret.getDefaultVisibleColumns()); - defaultCols.add(0, FieldKey.fromParts("RunMembership")); + defaultCols.addFirst(FieldKey.fromParts("RunMembership")); defaultCols.remove(FieldKey.fromParts(ExpExperimentTable.Column.RunCount.name())); ret.setDefaultVisibleColumns(defaultCols); diff --git a/api/src/org/labkey/api/exp/query/SamplesSchema.java b/api/src/org/labkey/api/exp/query/SamplesSchema.java index 0f4149ce05d..acdbdb07476 100644 --- a/api/src/org/labkey/api/exp/query/SamplesSchema.java +++ b/api/src/org/labkey/api/exp/query/SamplesSchema.java @@ -228,7 +228,7 @@ public ExpMaterialTable getTable(@NotNull ExpSampleType st, @Nullable ContainerF public ExpMaterialTable createSampleTable(@Nullable ExpSampleType st, ContainerFilter cf) { if (log.isTraceEnabled()) - log.trace("CREATE TABLE: " + (null==st ? "null" : st.getName()) + " schema=" + System.identityHashCode(this), new Throwable()); + log.trace("CREATE TABLE: {} schema={}", null == st ? "null" : st.getName(), System.identityHashCode(this), new Throwable()); ExpMaterialTable ret = ExperimentService.get().createMaterialTable(this, cf, st); ret.populate(); diff --git a/api/src/org/labkey/api/exp/xar/LsidUtils.java b/api/src/org/labkey/api/exp/xar/LsidUtils.java index 9e4aed71551..1cfb5068e38 100644 --- a/api/src/org/labkey/api/exp/xar/LsidUtils.java +++ b/api/src/org/labkey/api/exp/xar/LsidUtils.java @@ -165,7 +165,7 @@ private static String doReplacements(String template, Replacer replacer) throws String result = sb.toString(); if (!template.equals(result)) - _log.debug("template name " + template + " resolved to " + result); + _log.debug("template name {} resolved to {}", template, result); return result; } diff --git a/api/src/org/labkey/api/exp/xar/XarReaderDelegate.java b/api/src/org/labkey/api/exp/xar/XarReaderDelegate.java index f1ca78849f3..cac6c7890ad 100644 --- a/api/src/org/labkey/api/exp/xar/XarReaderDelegate.java +++ b/api/src/org/labkey/api/exp/xar/XarReaderDelegate.java @@ -2,16 +2,14 @@ import org.apache.logging.log4j.Logger; import org.labkey.api.data.Container; -import org.labkey.api.exp.ExperimentException; import org.labkey.api.exp.api.ExpProtocol; import org.labkey.api.exp.api.ExpRun; -import org.labkey.api.query.ValidationException; import org.labkey.api.security.User; public interface XarReaderDelegate { String getXarDelegateName(); - void postProcessImportedProtocol(Container container, User user, ExpProtocol experiment, Logger logger) throws ExperimentException, ValidationException; - void postProcessImportedRun(Container container, User user, ExpRun run, Logger logger) throws ExperimentException, ValidationException; + void postProcessImportedProtocol(Container container, User user, ExpProtocol experiment, Logger logger); + void postProcessImportedRun(Container container, User user, ExpRun run, Logger logger); } diff --git a/api/src/org/labkey/api/exp/xar/XarReaderRegistry.java b/api/src/org/labkey/api/exp/xar/XarReaderRegistry.java index 93a04417a85..8d687422621 100644 --- a/api/src/org/labkey/api/exp/xar/XarReaderRegistry.java +++ b/api/src/org/labkey/api/exp/xar/XarReaderRegistry.java @@ -28,7 +28,7 @@ public static XarReaderRegistry get() public void registerDelegate(String protocolPattern, XarReaderDelegate delegate) { if (_delegateMap.containsKey(protocolPattern)) - _logger.warn(String.format("Existing delegate '%s' for protocol pattern '%s' being replaced.", _delegateMap.get(protocolPattern).getXarDelegateName(), protocolPattern)); + _logger.warn("Existing delegate '{}' for protocol pattern '{}' being replaced.", _delegateMap.get(protocolPattern).getXarDelegateName(), protocolPattern); _delegateMap.put(protocolPattern, delegate); } @@ -46,7 +46,7 @@ public void postProcessImportedProtocol(Container container, User user, ExpProto } catch (Exception e) { - logger.error(String.format("There was a problem during postprocessing with delegate '%s'", delegate.getXarDelegateName()), e); + logger.error("There was a problem during postprocessing with delegate '{}'", delegate.getXarDelegateName(), e); } }); } @@ -64,7 +64,7 @@ public void postProcessImportedRun(Container container, User user, ExpRun run, L } catch (Exception e) { - logger.error(String.format("There was a problem during postprocessing with delegate '%s'", delegate.getXarDelegateName()), e); + logger.error("There was a problem during postprocessing with delegate '{}'", delegate.getXarDelegateName(), e); } }); } diff --git a/api/src/org/labkey/api/files/FileContentService.java b/api/src/org/labkey/api/files/FileContentService.java index 9e42834d866..aa2a929a8d1 100644 --- a/api/src/org/labkey/api/files/FileContentService.java +++ b/api/src/org/labkey/api/files/FileContentService.java @@ -161,10 +161,10 @@ static void setInstance(FileContentService impl) * @return AttachmentParent that can be passed to other methods of this interface */ @Nullable - AttachmentDirectory getMappedAttachmentDirectory(Container c, boolean createDir) throws UnsetRootDirectoryException, MissingRootDirectoryException; + AttachmentDirectory getMappedAttachmentDirectory(Container c, boolean createDir) throws UnsetRootDirectoryException; @Nullable - AttachmentDirectory getMappedAttachmentDirectory(Container c, ContentType contentType, boolean createDir) throws UnsetRootDirectoryException, MissingRootDirectoryException; + AttachmentDirectory getMappedAttachmentDirectory(Container c, ContentType contentType, boolean createDir) throws UnsetRootDirectoryException; /** * Return a named AttachmentParent for files in the directory mapped to this container diff --git a/api/src/org/labkey/api/files/FileSystemWatcherImpl.java b/api/src/org/labkey/api/files/FileSystemWatcherImpl.java index 5ba41e34bef..cbbbe84c31d 100644 --- a/api/src/org/labkey/api/files/FileSystemWatcherImpl.java +++ b/api/src/org/labkey/api/files/FileSystemWatcherImpl.java @@ -106,7 +106,7 @@ public class FileSystemWatcherImpl implements FileSystemWatcher LOG.warn("PollingFileWatcher exception", throwable); } }, - l -> LOG.debug("PollingWatchService pollTime: " + l)); + l -> LOG.debug("PollingWatchService pollTime: {}", l)); _pollingWatcher.start(); FileSystemWatcherThread pollingThread = new FileSystemWatcherThread("PollingFileWatcher", _pollingWatcher); @@ -161,13 +161,13 @@ private void addListener(Path directory, FileSystemDirectoryListener listener, B else { plm = previous; - LOG.debug("Detected previously registered file watcher service for file system of type '" + plm.getFileStoreType() + "'. for directory: " + directory.toAbsolutePath()); + LOG.debug("Detected previously registered file watcher service for file system of type '{}'. for directory: {}", plm.getFileStoreType(), directory.toAbsolutePath()); } // Add the listener and its requested events plm.addListener(listener, events); - LOG.debug("Registered a file listener on " + directory); + LOG.debug("Registered a file listener on {}", directory); } private void registerWithWatchService(Path directory, PathListenerManager plm) throws IOException @@ -190,12 +190,12 @@ private void registerWithWatchService(Path directory, PathListenerManager plm) t { if (pollingWatcher) { - LOG.debug("Detected network file system type '" + fileStoreType + "'. Create polling file watcher service and register this directory there for directory: " + directory.toAbsolutePath()); + LOG.debug("Detected network file system type '{}'. Create polling file watcher service and register this directory there for directory: {}", fileStoreType, directory.toAbsolutePath()); watchKey = _pollingWatcher.register(directory, StandardWatchEventKinds.ENTRY_CREATE, StandardWatchEventKinds.ENTRY_DELETE, StandardWatchEventKinds.ENTRY_MODIFY); } else { - LOG.debug("Detected local file system type '" + fileStoreType + "'. Register path with standard watcher service for directory: " + directory.toAbsolutePath()); + LOG.debug("Detected local file system type '{}'. Register path with standard watcher service for directory: {}", fileStoreType, directory.toAbsolutePath()); watchKey = directory.register(_watcher, ENTRY_CREATE, ENTRY_DELETE, ENTRY_MODIFY); // Register all events (future listener might request events that current listener doesn't) } } @@ -219,7 +219,7 @@ public void removeListener(@NotNull Path directory, FileSystemDirectoryListener if (plm != null) { plm.removeListener(listener); - LOG.debug("Removed a file listener on " + directory); + LOG.debug("Removed a file listener on {}", directory); if (FileUtil.hasCloudScheme(dir) && CloudWatchService.get() != null) { @@ -251,7 +251,7 @@ public void run() } finally { - LOG.info(getClass().getSimpleName() + " is terminating"); + LOG.info("{} is terminating", getClass().getSimpleName()); close(); } } @@ -318,14 +318,14 @@ protected void watch() throws InterruptedException // on this directory. If watch key is no longer valid, then it's probably been deleted. if (!watchKey.reset() && null != watchedPath ) { - LOG.debug("WatchKey is invalid: " + watchedPath); + LOG.debug("WatchKey is invalid: {}", watchedPath); if (!isInterrupted()) handleDeletedDirectory(watchedPath); } if (isInterrupted()) { - LOG.debug("File watcher interrupted: " + watchedPath); + LOG.debug("File watcher interrupted: {}", watchedPath); } } } @@ -430,7 +430,7 @@ public void fireEvents(WatchEvent event, Path watchedPath, Runnable callba else { Path entry = event.context(); - LOG.debug(kind.name() + " event on " + watchedPath.resolve(entry)); + LOG.debug("{} event on {}", kind.name(), watchedPath.resolve(entry)); for (ListenerContext listenerContext : _list) listenerContext.fireEvent(kind, watchedPath, entry, callback); diff --git a/api/src/org/labkey/api/files/view/FilesWebPart.java b/api/src/org/labkey/api/files/view/FilesWebPart.java index 6d20510d582..bf222726ae4 100644 --- a/api/src/org/labkey/api/files/view/FilesWebPart.java +++ b/api/src/org/labkey/api/files/view/FilesWebPart.java @@ -30,7 +30,6 @@ import org.labkey.api.files.FileContentService; import org.labkey.api.files.FileUrls; import org.labkey.api.files.FilesAdminOptions; -import org.labkey.api.files.MissingRootDirectoryException; import org.labkey.api.pipeline.PipeRoot; import org.labkey.api.pipeline.PipelineService; import org.labkey.api.pipeline.PipelineUrls; @@ -146,16 +145,9 @@ else if (legacyFileRoot.startsWith(FileContentService.CLOUD_LINK)) if (dir != null) { - try - { - getModelBean().setRoot(dir); - getModelBean().setRootDirectory(dir.getFileSystemDirectoryPath()); - } - catch (MissingRootDirectoryException e) - { - // this should never happen - throw new RuntimeException(e); - } + getModelBean().setRoot(dir); + getModelBean().setRootDirectory(dir.getFileSystemDirectoryPath()); + } getModelBean().setRootPath(getRootPath(c, FileContentService.FILE_SETS_LINK, legacyFileRoot)); setTitle(legacyFileRoot); @@ -200,7 +192,7 @@ public FilesWebPart(ViewContext ctx, Portal.WebPart webPartDescriptor) } catch (Throwable t) { - _log.warn("improper path passed to webpart: [" + path + "]"); + _log.warn("improper path passed to webpart: [{}]", path); } } @@ -422,30 +414,23 @@ public static URI getWebPartFolderRootPath(Container c, @Nullable String folderF protected boolean canDisplayPipelineActions() { - try - { - if (_isPipelineFiles) - return true; - else if (_isRootNotFilesPipeline) - return false; + if (_isPipelineFiles) + return true; + else if (_isRootNotFilesPipeline) + return false; - // since pipeline actions operate on the pipeline root, if the file content and pipeline roots do not - // reference the same location, then import and customize actions should be disabled + // since pipeline actions operate on the pipeline root, if the file content and pipeline roots do not + // reference the same location, then import and customize actions should be disabled - FileContentService svc = FileContentService.get(); - if (null == svc) - throw new IllegalStateException("FileContentService not found."); - AttachmentDirectory dir = svc.getMappedAttachmentDirectory(getViewContext().getContainer(), false); - PipeRoot root = PipelineService.get().findPipelineRoot(getViewContext().getContainer()); + FileContentService svc = FileContentService.get(); + if (null == svc) + throw new IllegalStateException("FileContentService not found."); + AttachmentDirectory dir = svc.getMappedAttachmentDirectory(getViewContext().getContainer(), false); + PipeRoot root = PipelineService.get().findPipelineRoot(getViewContext().getContainer()); - if (null != root && root.isValid() && null != dir && root.getRootNioPath().equals(dir.getFileSystemDirectoryPath())) - { - return true; - } - } - catch (MissingRootDirectoryException e) + if (null != root && root.isValid() && null != dir && root.getRootNioPath().equals(dir.getFileSystemDirectoryPath())) { - _log.error("Error determining whether pipeline actions can be shown", e); + return true; } return false; } @@ -477,22 +462,16 @@ public void setFileSet(String fileSet) if (null == svc) throw new IllegalStateException("FileContentService not found."); - try { - AttachmentDirectory dir; - if (null == fileSet) - dir = svc.getMappedAttachmentDirectory(container, false); - else - dir = svc.getRegisteredDirectory(container, fileSet); + AttachmentDirectory dir; + if (null == fileSet) + dir = svc.getMappedAttachmentDirectory(container, false); + else + dir = svc.getRegisteredDirectory(container, fileSet); - if (dir != null) - { - getModelBean().setRoot(dir); - getModelBean().setRootDirectory(dir.getFileSystemDirectoryPath()); - } - } - catch (MissingRootDirectoryException ex) + if (dir != null) { - setModelBean(null); + getModelBean().setRoot(dir); + getModelBean().setRootDirectory(dir.getFileSystemDirectoryPath()); } } diff --git a/api/src/org/labkey/api/iterator/MarkableIterator.java b/api/src/org/labkey/api/iterator/MarkableIterator.java index 6a83557ed92..1950b41d506 100644 --- a/api/src/org/labkey/api/iterator/MarkableIterator.java +++ b/api/src/org/labkey/api/iterator/MarkableIterator.java @@ -16,6 +16,7 @@ package org.labkey.api.iterator; import org.apache.commons.collections4.iterators.ArrayIterator; +import org.jetbrains.annotations.NotNull; import org.junit.Assert; import org.junit.Before; import org.junit.Test; @@ -95,12 +96,6 @@ private boolean bufferIterHasNext() return false; } - @Override - public void remove() - { - throw new UnsupportedOperationException("remove"); - } - public void mark() { if (null == _bufferIter) @@ -208,7 +203,7 @@ public String toString() } @Override - public SimpleLinkedListIterator iterator() + public @NotNull SimpleLinkedListIterator iterator() { return new SimpleLinkedListIterator(); } diff --git a/api/src/org/labkey/api/jsp/JspWriterWrapper.java b/api/src/org/labkey/api/jsp/JspWriterWrapper.java index 0a57e4bf224..8051d1f94ce 100644 --- a/api/src/org/labkey/api/jsp/JspWriterWrapper.java +++ b/api/src/org/labkey/api/jsp/JspWriterWrapper.java @@ -205,13 +205,13 @@ public void write(int c) throws IOException } @Override - public void write(@NotNull char[] cbuf) throws IOException + public void write(char @NotNull [] cbuf) throws IOException { _jspWriter.write(cbuf); } @Override - public void write(@NotNull char[] cbuf, int off, int len) throws IOException + public void write(char @NotNull [] cbuf, int off, int len) throws IOException { _jspWriter.write(cbuf, off, len); } diff --git a/api/src/org/labkey/api/jsp/RecompilingJspClassLoader.java b/api/src/org/labkey/api/jsp/RecompilingJspClassLoader.java index 4ec84fc0742..ff3d94e6fb6 100644 --- a/api/src/org/labkey/api/jsp/RecompilingJspClassLoader.java +++ b/api/src/org/labkey/api/jsp/RecompilingJspClassLoader.java @@ -105,7 +105,7 @@ private Class getCompiledClassFile(File classFile, File jspJavaFileBuildDirec if (requiresRecompile || requiresTestRecompile) { - _log.info("Recompiling " + relativePath); + _log.info("Recompiling {}", relativePath); // Copy .jsp file from source to build staging directory File stagingJsp = new File(jspJavaFileBuildDirectory.getParentFile().getParent() + "/jspWebappDir/webapp", relativePath); @@ -228,7 +228,7 @@ private static void logJspPath(File jspSource, String errors) if (end != -1) { path = jspSource.getAbsolutePath() + ":" + errors.substring(begin, end) + "\n"; - _log.error("Error compiling JSP:\n" + path); + _log.error("Error compiling JSP:\n{}", path); } } } diff --git a/api/src/org/labkey/api/jsp/taglib/ErrorsTag.java b/api/src/org/labkey/api/jsp/taglib/ErrorsTag.java index 72b75293e01..58fcc52c29b 100644 --- a/api/src/org/labkey/api/jsp/taglib/ErrorsTag.java +++ b/api/src/org/labkey/api/jsp/taglib/ErrorsTag.java @@ -74,7 +74,7 @@ public int doStartTag() throws JspException out.print(HtmlString.unsafe("Unknown error: " + m)); ExceptionUtil.logExceptionToMothership((HttpServletRequest)pageContext.getRequest(), nsme); Logger log = LogManager.getLogger(ErrorsTag.class); - log.error("Failed to find a message: " + m, nsme); + log.error("Failed to find a message: {}", m, nsme); } out.println(HtmlString.BR); } diff --git a/api/src/org/labkey/api/jsp/taglib/FormTag.java b/api/src/org/labkey/api/jsp/taglib/FormTag.java index 22df262a330..d4915dbe299 100644 --- a/api/src/org/labkey/api/jsp/taglib/FormTag.java +++ b/api/src/org/labkey/api/jsp/taglib/FormTag.java @@ -17,7 +17,6 @@ package org.labkey.api.jsp.taglib; import org.apache.commons.lang3.StringUtils; -import org.labkey.api.settings.AppProps; import org.labkey.api.util.DOM; import org.labkey.api.util.HtmlString; import org.labkey.api.util.UnexpectedException; @@ -26,7 +25,6 @@ import org.labkey.api.view.HttpView; import org.labkey.api.view.ViewContext; -import jakarta.servlet.jsp.JspException; import jakarta.servlet.jsp.tagext.BodyTagSupport; import java.io.IOException; @@ -168,7 +166,7 @@ public Boolean isNoValidate() HtmlString endTag; @Override - public int doStartTag() throws JspException + public int doStartTag() { var pageConfig = HttpView.currentPageConfig(); var id = getId(); @@ -206,7 +204,7 @@ public int doStartTag() throws JspException } @Override - public int doEndTag() throws JspException + public int doEndTag() { try { diff --git a/api/src/org/labkey/api/jsp/taglib/ScriptTag.java b/api/src/org/labkey/api/jsp/taglib/ScriptTag.java index a8234ff9e84..bea0c7039bf 100644 --- a/api/src/org/labkey/api/jsp/taglib/ScriptTag.java +++ b/api/src/org/labkey/api/jsp/taglib/ScriptTag.java @@ -20,7 +20,6 @@ import org.labkey.api.util.UnexpectedException; import org.labkey.api.view.HttpView; -import jakarta.servlet.jsp.JspException; import jakarta.servlet.jsp.tagext.BodyTagSupport; import java.io.IOException; @@ -30,7 +29,7 @@ public class ScriptTag extends BodyTagSupport static final HtmlString endTag = HtmlString.unsafe(""); @Override - public int doStartTag() throws JspException + public int doStartTag() { try { @@ -45,7 +44,7 @@ public int doStartTag() throws JspException } @Override - public int doEndTag() throws JspException + public int doEndTag() { try { diff --git a/api/src/org/labkey/api/mbean/LabKeyManagement.java b/api/src/org/labkey/api/mbean/LabKeyManagement.java index 28aa4684b86..415a8364b9b 100644 --- a/api/src/org/labkey/api/mbean/LabKeyManagement.java +++ b/api/src/org/labkey/api/mbean/LabKeyManagement.java @@ -119,7 +119,7 @@ public static void register(DynamicMBean bean, @Nullable ObjectName name) } catch (Exception x) { - LOG.error("error registering mbean : " + name, x); + LOG.error("error registering mbean : {}", name, x); } } } diff --git a/api/src/org/labkey/api/mcp/McpService.java b/api/src/org/labkey/api/mcp/McpService.java index 6ad04872537..5021a86ec90 100644 --- a/api/src/org/labkey/api/mcp/McpService.java +++ b/api/src/org/labkey/api/mcp/McpService.java @@ -5,7 +5,6 @@ import jakarta.servlet.http.HttpSession; import org.apache.logging.log4j.Logger; import org.jetbrains.annotations.NotNull; -import org.jspecify.annotations.NonNull; import org.labkey.api.data.Container; import org.labkey.api.security.User; import org.labkey.api.services.ServiceRegistry; @@ -152,7 +151,7 @@ default void register(McpImpl mcp) void registerResources(@NotNull List resources); @Override - ToolCallback @NonNull [] getToolCallbacks(); + ToolCallback @NotNull [] getToolCallbacks(); default ChatClient getChat(HttpSession session, String agentName, Supplier systemPromptSupplier) { diff --git a/api/src/org/labkey/api/mcp/NoopMcpService.java b/api/src/org/labkey/api/mcp/NoopMcpService.java index f6f63534ce0..0bc5813398e 100644 --- a/api/src/org/labkey/api/mcp/NoopMcpService.java +++ b/api/src/org/labkey/api/mcp/NoopMcpService.java @@ -3,7 +3,6 @@ import io.modelcontextprotocol.server.McpServerFeatures; import jakarta.servlet.http.HttpSession; import org.jetbrains.annotations.NotNull; -import org.jspecify.annotations.NonNull; import org.labkey.api.data.Container; import org.springframework.ai.chat.client.ChatClient; import org.springframework.ai.chat.model.ToolContext; @@ -47,7 +46,7 @@ public void registerResources(@NotNull List count == null ? 1 : count.intValue() + 1); _current.addObject(s); } } diff --git a/api/src/org/labkey/api/miniprofiler/Timing.java b/api/src/org/labkey/api/miniprofiler/Timing.java index f9c962d7078..f0da0750ce7 100644 --- a/api/src/org/labkey/api/miniprofiler/Timing.java +++ b/api/src/org/labkey/api/miniprofiler/Timing.java @@ -131,9 +131,7 @@ protected void addCustomTiming(String category, CustomTiming custom) return; assert custom._parent == this; - List timings = _customTimings.get(category); - if (timings == null) - _customTimings.put(category, timings = new LinkedList<>()); + List timings = _customTimings.computeIfAbsent(category, k -> new LinkedList<>()); collapseDuplicate(timings, custom); limitList(timings); @@ -227,8 +225,7 @@ protected void addObject(String s) if (!_timer.started()) return; - Integer count = _objects.get(s); - _objects.put(s, count == null ? 1 : count.intValue() + 1); + _objects.compute(s, (_, count) -> count == null ? 1 : count.intValue() + 1); } public Map getObjects() diff --git a/api/src/org/labkey/api/module/CustomFolderType.java b/api/src/org/labkey/api/module/CustomFolderType.java index cc34fba07c4..a9a71d00216 100644 --- a/api/src/org/labkey/api/module/CustomFolderType.java +++ b/api/src/org/labkey/api/module/CustomFolderType.java @@ -210,7 +210,7 @@ private List getSortedModuleList() } sortedModuleList.sort(Comparator.comparing(Module::getName, String.CASE_INSENSITIVE_ORDER)); if (portal != null) - sortedModuleList.add(0, portal); + sortedModuleList.addFirst(portal); return sortedModuleList; } diff --git a/api/src/org/labkey/api/module/DefaultFolderType.java b/api/src/org/labkey/api/module/DefaultFolderType.java index eb0dfbc7fc4..48671fd29c8 100644 --- a/api/src/org/labkey/api/module/DefaultFolderType.java +++ b/api/src/org/labkey/api/module/DefaultFolderType.java @@ -115,7 +115,7 @@ public ActionURL getURL(Container container, User user) @Override @NotNull public FolderTab getDefaultTab() { - return getDefaultTabs().get(0); + return getDefaultTabs().getFirst(); } @Override diff --git a/api/src/org/labkey/api/module/DefaultModule.java b/api/src/org/labkey/api/module/DefaultModule.java index 3ea64b0e05b..f5fb7c34b67 100644 --- a/api/src/org/labkey/api/module/DefaultModule.java +++ b/api/src/org/labkey/api/module/DefaultModule.java @@ -181,7 +181,7 @@ final public void initialize() // database. This can be helpful on test and dev machines. See #23730. DbScope scope = DbScope.getLabKeyScope(); - _log.warn("Module \"" + getName() + "\" requires a data source called \"" + dsName + "\". It's not configured, so it will be created against the primary labkey database (\"" + scope.getDatabaseName() + "\") instead."); + _log.warn("Module \"{}\" requires a data source called \"{}\". It's not configured, so it will be created against the primary labkey database (\"{}\") instead.", getName(), dsName, scope.getDatabaseName()); DbScope.addScope(dsName, scope.getLabKeyDataSource()); if (null == DbScope.getDbScope(dsName)) // Force immediate connection to test throw new ConfigurationException("Failed to connect to data source \"" + dsName + "\", created against the labkey database (\"" + scope.getDatabaseName() + "\")."); @@ -189,7 +189,7 @@ final public void initialize() else { // A module data source is missing and we're in production mode, so issue a warning. The data source might be optional, e.g., on staging servers. See #23830 - _log.warn("Module \"" + getName() + "\" requires a data source called \"" + dsName + "\" but it's not configured. This module will be loaded, but it might not operate correctly."); + _log.warn("Module \"{}\" requires a data source called \"{}\" but it's not configured. This module will be loaded, but it might not operate correctly.", getName(), dsName); } } diff --git a/api/src/org/labkey/api/module/FolderTypeManager.java b/api/src/org/labkey/api/module/FolderTypeManager.java index 8f9dae6c10a..c20a3de64a2 100644 --- a/api/src/org/labkey/api/module/FolderTypeManager.java +++ b/api/src/org/labkey/api/module/FolderTypeManager.java @@ -369,7 +369,7 @@ public void testModuleResourceCache() .mapToInt(Collection::size) .sum(); - LOG.info(folderTypeCount + " folder types defined in all modules"); + LOG.info("{} folder types defined in all modules", folderTypeCount); // Make sure the cache retrieves the expected number of folder types from the simpletest module, if present diff --git a/api/src/org/labkey/api/module/ModuleHtmlView.java b/api/src/org/labkey/api/module/ModuleHtmlView.java index 706958a33ae..2430097ddb8 100644 --- a/api/src/org/labkey/api/module/ModuleHtmlView.java +++ b/api/src/org/labkey/api/module/ModuleHtmlView.java @@ -208,7 +208,7 @@ public void testModuleResourceCache() .mapToInt(Map::size) .sum(); - LOG.info(viewCount + " HTML view definitions defined in all modules"); + LOG.info("{} HTML view definitions defined in all modules", viewCount); // Make sure the cache retrieves the expected number of HTML view definitions from the simpletest module, if present diff --git a/api/src/org/labkey/api/module/ModuleResourceCache.java b/api/src/org/labkey/api/module/ModuleResourceCache.java index 516bab1eacd..cfa81a24b29 100644 --- a/api/src/org/labkey/api/module/ModuleResourceCache.java +++ b/api/src/org/labkey/api/module/ModuleResourceCache.java @@ -261,7 +261,7 @@ public void ensureListener(Resource resource, Module module) if (_pathsWithListeners.add(getPathsWithListenersKey(module, mdr.getDir().toPath()))) { - LOG.debug("registering a listener on: " + resource); + LOG.debug("registering a listener on: {}", resource); mdr.registerListener(_watcher, getListener(module), ENTRY_CREATE, ENTRY_DELETE, ENTRY_MODIFY); } } diff --git a/api/src/org/labkey/api/module/ModuleResourceCaches.java b/api/src/org/labkey/api/module/ModuleResourceCaches.java index 494e37f3d18..a1853fad723 100644 --- a/api/src/org/labkey/api/module/ModuleResourceCaches.java +++ b/api/src/org/labkey/api/module/ModuleResourceCaches.java @@ -97,7 +97,7 @@ public static CacheId parseCacheKey(String cacheKey, Pattern pattern) if (!matcher.matches() || matcher.groupCount() != 2) { - LOGGER.warn("Unrecognized cache key format: " + cacheKey); + LOGGER.warn("Unrecognized cache key format: {}", cacheKey); return null; } diff --git a/api/src/org/labkey/api/module/ModuleResourceResolver.java b/api/src/org/labkey/api/module/ModuleResourceResolver.java index ecfcae2dd7b..0492f51a8a3 100644 --- a/api/src/org/labkey/api/module/ModuleResourceResolver.java +++ b/api/src/org/labkey/api/module/ModuleResourceResolver.java @@ -62,9 +62,9 @@ public class ModuleResourceResolver implements Resolver ensureListeners(r); if (null == r) - LOG.debug("missed resource: " + key); + LOG.debug("missed resource: {}", key); else if (r.exists()) - LOG.debug("resolved resource: " + key + " -> " + r); + LOG.debug("resolved resource: {} -> {}", key, r); return r; }; @@ -96,13 +96,13 @@ private void ensureListeners(Resource r) if (_pathsWithListeners.add(path)) { - LOG.debug("registering a listener on: " + r); + LOG.debug("registering a listener on: {}", r); ((DirectoryResource) r).registerListener(WATCHER, new ModuleResourceResolverListener(), ENTRY_CREATE, ENTRY_DELETE); } else { - LOG.debug("NOT registering a listener on: " + r); + LOG.debug("NOT registering a listener on: {}", r); // Short-circuit -- if a path is registered then we know its ancestors are registered, so no need to keep looping return; } @@ -180,7 +180,7 @@ private class ModuleResourceResolverListener implements FileSystemDirectoryListe @Override public void entryCreated(java.nio.file.Path directory, java.nio.file.Path entry) { - LOG.debug(entry + " created"); + LOG.debug("{} created", entry); java.nio.file.Path nioPath = directory.resolve(entry); if (Files.isDirectory(nioPath)) ensureListeners(resolve(_root.getRelativePath(nioPath))); @@ -190,7 +190,7 @@ public void entryCreated(java.nio.file.Path directory, java.nio.file.Path entry) @Override public void entryDeleted(java.nio.file.Path directory, java.nio.file.Path entry) { - LOG.debug(entry + " deleted"); + LOG.debug("{} deleted", entry); java.nio.file.Path nioPath = directory.resolve(entry); if (Files.isDirectory(nioPath)) _pathsWithListeners.remove(_root.getRelativePath(nioPath)); @@ -200,7 +200,7 @@ public void entryDeleted(java.nio.file.Path directory, java.nio.file.Path entry) @Override public void directoryDeleted(java.nio.file.Path directory) { - LOG.debug("Directory " + directory + " deleted"); + LOG.debug("Directory {} deleted", directory); _pathsWithListeners.remove(_root.getRelativePath(directory)); clear(); // Clear all resources and children in this module. A bit heavy-handed, but attempts at targeted approaches have been wrong. } diff --git a/api/src/org/labkey/api/module/ModuleXml.java b/api/src/org/labkey/api/module/ModuleXml.java index faade6310d9..dc12e8f2317 100644 --- a/api/src/org/labkey/api/module/ModuleXml.java +++ b/api/src/org/labkey/api/module/ModuleXml.java @@ -153,7 +153,7 @@ public ModuleXml(Module module, Resource r) } catch(Exception e) { - LOG.error("Error trying to read and parse the metadata XML for " + r, e); + LOG.error("Error trying to read and parse the metadata XML for {}", r, e); } _moduleProperties = Collections.unmodifiableMap(moduleProperties); @@ -198,7 +198,7 @@ public void testModuleResourceCache() .filter(mx->!mx.getClientDependencySuppliers().isEmpty() || !mx.getModuleProperties().isEmpty()) .count(); - LOG.info(nonTrivial + " non-trivial ModuleXml objects"); + LOG.info("{} non-trivial ModuleXml objects", nonTrivial); // Make sure the cache retrieves the expected ModuleXml for simpletest and restrictedModule modules, if present diff --git a/api/src/org/labkey/api/module/MultiPortalFolderType.java b/api/src/org/labkey/api/module/MultiPortalFolderType.java index 0b450be647d..f8f08fbd2e9 100644 --- a/api/src/org/labkey/api/module/MultiPortalFolderType.java +++ b/api/src/org/labkey/api/module/MultiPortalFolderType.java @@ -118,7 +118,7 @@ public AppBar getAppBar(ViewContext ctx, PageConfig pageConfig, Container childC List sortedPages = Portal.getTabPages(container, showHiddenTabs); // No page index should be 0 - assert !(!sortedPages.isEmpty() && sortedPages.get(0).getIndex() <= 0); + assert !(!sortedPages.isEmpty() && sortedPages.getFirst().getIndex() <= 0); String activePortalPage = null; Map navMap = new LinkedHashMap<>(); @@ -184,7 +184,7 @@ public AppBar getAppBar(ViewContext ctx, PageConfig pageConfig, Container childC } if (!foundSelected && nav.getChildCount() > 0 && !subContainerTabs.isEmpty()) - subContainerTabs.get(0).setSelected(true); + subContainerTabs.getFirst().setSelected(true); } } } @@ -269,7 +269,7 @@ public String getDefaultPageId(Container container) List defaults = getDefaultTabs(); if (!defaults.isEmpty()) { - return defaults.get(0).getName(); + return defaults.getFirst().getName(); } return Portal.DEFAULT_PORTAL_PAGE_ID; @@ -288,7 +288,7 @@ private boolean hasPermission(FolderTab folderTab, Container container, User use @Override @NotNull public FolderTab getDefaultTab() { - return _defaultTab == null ? getDefaultTabs().get(0) : _defaultTab; + return _defaultTab == null ? getDefaultTabs().getFirst() : _defaultTab; } private NavTree getTabMenu(ViewContext ctx, FolderTab folderTab, Portal.PortalPage portalPage, String folderLabel) diff --git a/api/src/org/labkey/api/module/SafeFlushResponseWrapper.java b/api/src/org/labkey/api/module/SafeFlushResponseWrapper.java index fad0793425b..812039e6b52 100644 --- a/api/src/org/labkey/api/module/SafeFlushResponseWrapper.java +++ b/api/src/org/labkey/api/module/SafeFlushResponseWrapper.java @@ -20,6 +20,8 @@ import jakarta.servlet.WriteListener; import jakarta.servlet.http.HttpServletResponse; import jakarta.servlet.http.HttpServletResponseWrapper; +import org.jetbrains.annotations.NotNull; + import java.io.IOException; import java.io.OutputStream; @@ -58,13 +60,13 @@ public OutputStreamWrapper(OutputStream out) } @Override - public void write(byte b[]) throws IOException + public void write(byte @NotNull[] b) throws IOException { _out.write(b); } @Override - public void write(byte b[], int off, int len) throws IOException + public void write(byte @NotNull[] b, int off, int len) throws IOException { _out.write(b, off, len); } diff --git a/api/src/org/labkey/api/module/SimpleAction.java b/api/src/org/labkey/api/module/SimpleAction.java index 03124a06ed9..b14468ec9f3 100644 --- a/api/src/org/labkey/api/module/SimpleAction.java +++ b/api/src/org/labkey/api/module/SimpleAction.java @@ -15,6 +15,7 @@ */ package org.labkey.api.module; +import org.jetbrains.annotations.NotNull; import org.labkey.api.action.BaseViewAction; import org.labkey.api.action.NavTrailAction; import org.labkey.api.data.Container; @@ -76,7 +77,7 @@ public ModelAndView handleRequest() throws Exception } @Override - public void validate(Object target, Errors errors) + public void validate(@NotNull Object target, @NotNull Errors errors) { //since simple HTML views don't interact with permanent storage (i.e., the database) //we really don't need to do much validation here diff --git a/api/src/org/labkey/api/module/SimpleFolderType.java b/api/src/org/labkey/api/module/SimpleFolderType.java index 181360a485a..fce74a41393 100644 --- a/api/src/org/labkey/api/module/SimpleFolderType.java +++ b/api/src/org/labkey/api/module/SimpleFolderType.java @@ -93,7 +93,7 @@ private SimpleFolderType(Resource folderTypeFile, FolderType type, List } } if (hasError) - LOG.error("Error in " + folderTypeFile.getName() + ". A folderType that contains folderTabs cannot also provide preferredWebparts or requiredWebparts with locations outside the menubar."); + LOG.error("Error in {}. A folderType that contains folderTabs cannot also provide preferredWebparts or requiredWebparts with locations outside the menubar.", folderTypeFile.getName()); } _folderTabs = createFolderTabs(type.getFolderTabs().getFolderTabArray()); } @@ -104,8 +104,8 @@ private SimpleFolderType(Resource folderTypeFile, FolderType type, List if (!_folderTabs.isEmpty()) { - _defaultTab = _folderTabs.get(0); - _folderTabs.get(0).setIsDefaultTab(true); + _defaultTab = _folderTabs.getFirst(); + _folderTabs.getFirst().setIsDefaultTab(true); } setWorkbookType(type.isSetWorkbookType() && type.getWorkbookType()); @@ -141,7 +141,7 @@ private SimpleFolderType(Resource folderTypeFile, FolderType type, List } else { - LOG.warn("Module '" + moduleName + "' not available for folder type '" + name + "'"); + LOG.warn("Module '{}' not available for folder type '{}'", moduleName, name); } } } @@ -169,7 +169,7 @@ private SimpleFolderType(Resource folderTypeFile, FolderType type, List } catch (XmlValidationException e) { - LOG.error("Unable to load custom folder type from file " + folderTypeFile + ".", e); + LOG.error("Unable to load custom folder type from file {}.", folderTypeFile, e); return null; } catch (XmlException | IOException e) @@ -234,7 +234,7 @@ private List createFolderTabs(FolderTabDocument.FolderTab[] reference } else { - LOG.error("Folder type '" + getName() + "' defines multiple tabs with the name '" + tab.getName() + "', only the first will be used."); + LOG.error("Folder type '{}' defines multiple tabs with the name '{}', only the first will be used.", getName(), tab.getName()); } } @@ -258,7 +258,7 @@ public static List createWebParts(WebPartDocument.WebPart[] references, //this is to debug intermittent team city failures and probably should not be merged if (perm == null) { - LOG.error("unknown permission class: " + permClass + " from the role: " + role.getName(), new Exception()); + LOG.error("unknown permission class: {} from the role: {}", permClass, role.getName(), new Exception()); continue; } diff --git a/api/src/org/labkey/api/module/SimpleModuleContainerListener.java b/api/src/org/labkey/api/module/SimpleModuleContainerListener.java index 92ab68b3959..96180081249 100644 --- a/api/src/org/labkey/api/module/SimpleModuleContainerListener.java +++ b/api/src/org/labkey/api/module/SimpleModuleContainerListener.java @@ -63,7 +63,7 @@ protected void purgeSchema(String schemaName, Container c, User user) if (userSchema == null) return; - LogManager.getLogger(SimpleModuleContainerListener.class).debug("Purging schema '" + schemaName + "' in container '" + c.getPath() + "'..."); + LogManager.getLogger(SimpleModuleContainerListener.class).debug("Purging schema '{}' in container '{}'...", schemaName, c.getPath()); // Walk over the dbSchema's tables -- it's faster than walking the UserSchema's tables List sorted = dbSchema.getSortedTables(); diff --git a/api/src/org/labkey/api/module/SpringModule.java b/api/src/org/labkey/api/module/SpringModule.java index e0fdf4f4956..0ddd1cae24d 100644 --- a/api/src/org/labkey/api/module/SpringModule.java +++ b/api/src/org/labkey/api/module/SpringModule.java @@ -215,7 +215,7 @@ protected void initWebApplicationContext() { ApplicationContext parentApplicationContext = getParentApplicationContext(); - _log.info("Loading Spring configuration for the " + getName() + " module from " + contextConfigFiles); + _log.info("Loading Spring configuration for the {} module from {}", getName(), contextConfigFiles); try { @@ -237,7 +237,7 @@ protected void loadBeanDefinitions(DefaultListableBeanFactory beanFactory) throw } catch (Exception x) { - _log.error("Failed to load spring application context for module: " + getName(), x); + _log.error("Failed to load spring application context for module: {}", getName(), x); ModuleLoader.getInstance().addModuleFailure(getName(), x); } } @@ -342,7 +342,7 @@ public InputStream getResourceAsStream(String string) } catch (FileNotFoundException e) { - _log.debug("Could not find config override " + string); + _log.debug("Could not find config override {}", string); } } diff --git a/api/src/org/labkey/api/pipeline/AbstractSpecimenTransformTask.java b/api/src/org/labkey/api/pipeline/AbstractSpecimenTransformTask.java index 42d9aa62f8a..d6cd1dc9a5b 100644 --- a/api/src/org/labkey/api/pipeline/AbstractSpecimenTransformTask.java +++ b/api/src/org/labkey/api/pipeline/AbstractSpecimenTransformTask.java @@ -22,10 +22,8 @@ import org.labkey.api.util.DateUtil; import org.labkey.api.util.FileUtil; -import java.io.File; import java.io.IOException; import java.io.PrintWriter; -import java.nio.file.Path; import java.util.ArrayList; import java.util.Collections; import java.util.Date; diff --git a/api/src/org/labkey/api/pipeline/AnalyzeForm.java b/api/src/org/labkey/api/pipeline/AnalyzeForm.java index 0fe86132e9a..bfb0566cb37 100644 --- a/api/src/org/labkey/api/pipeline/AnalyzeForm.java +++ b/api/src/org/labkey/api/pipeline/AnalyzeForm.java @@ -20,11 +20,8 @@ import org.labkey.api.pipeline.file.AbstractFileAnalysisProtocol; import org.labkey.api.security.User; import org.labkey.api.util.FileType; -import org.labkey.api.util.FileUtil; import org.labkey.vfs.FileLike; -import java.nio.file.Path; - /** * User: tgaluhn * Date: 2/1/2017 diff --git a/api/src/org/labkey/api/pipeline/LocalDirectory.java b/api/src/org/labkey/api/pipeline/LocalDirectory.java index 1e87d40e028..464f830a4df 100644 --- a/api/src/org/labkey/api/pipeline/LocalDirectory.java +++ b/api/src/org/labkey/api/pipeline/LocalDirectory.java @@ -18,8 +18,8 @@ import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonProperty; import org.apache.logging.log4j.Logger; -import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; +import org.jetbrains.annotations.NotNull; import org.labkey.api.data.Container; import org.labkey.api.util.FileUtil; import org.labkey.vfs.FileLike; @@ -61,7 +61,7 @@ public static LocalDirectory create(@NotNull PipeRoot root, @NotNull String base @JsonCreator private LocalDirectory( - @JsonProperty("_localDirectoryFile") FileLike localDirectoryFile, + @JsonProperty("_localDirectoryFile") @NotNull FileLike localDirectoryFile, @JsonProperty("_isTemporary") boolean isTemporary, @JsonProperty("_pipeRoot") PipeRoot pipeRoot, @JsonProperty("_baseLogFileName") String baseLogFileName, @@ -169,14 +169,14 @@ public FileLike copyToLocalDirectory(String url, Logger log) if (!tempFile.exists()) { FileUtil.copyFile(path, tempFile, StandardCopyOption.COPY_ATTRIBUTES); - log.info("Created temp file because input is from cloud: " + path); + log.info("Created temp file because input is from cloud: {}", path); } return tempFile; } } catch (IOException e) { - log.error("IO Error: " + e.getMessage()); + log.error("IO Error: {}", e.getMessage()); } } return null; @@ -203,16 +203,16 @@ public static FileLike copyToContainerDirectory(@NotNull Container container, @N FileLike tempFile = containerDir.resolveChild(tempFileName); if (!tempFile.exists()) { - log.debug("Copying file to container's temp directory: " + remotePath); + log.debug("Copying file to container's temp directory: {}", remotePath); FileUtil.copyFile(remotePath, tempFile, StandardCopyOption.COPY_ATTRIBUTES); - log.debug("Copied " + tempFile.getSize() + " bytes."); + log.debug("Copied {} bytes.", tempFile.getSize()); } return tempFile; } catch (NoSuchFileException e) { // Avoid a separate round-trip just to determine if file is available, as it adds ~1 overhead per call - log.debug("Could not find remote file: " + remotePath + ", unable to copy locally"); + log.debug("Could not find remote file: {}, unable to copy locally", remotePath); return null; } catch (IOException e) diff --git a/api/src/org/labkey/api/pipeline/PipelineJob.java b/api/src/org/labkey/api/pipeline/PipelineJob.java index b4aae8335a5..215a88e2a21 100644 --- a/api/src/org/labkey/api/pipeline/PipelineJob.java +++ b/api/src/org/labkey/api/pipeline/PipelineJob.java @@ -824,13 +824,13 @@ public void runActiveTask() throws IOException, PipelineJobException try { logStartStopInfo("Starting to run task '" + factory.getId() + "' for job '" + this + "' with log file " + getLogFilePath()); - getLogger().info("Starting to run task '" + factory.getId() + "' at location '" + factory.getExecutionLocation() + "'"); + getLogger().info("Starting to run task '{}' at location '{}'", factory.getId(), factory.getExecutionLocation()); if (PipelineJobService.get().getLocationType() != PipelineJobService.LocationType.WebServer) { PipelineJobService.RemoteServerProperties remoteProps = PipelineJobService.get().getRemoteServerProperties(); if (remoteProps != null) { - getLogger().info("on host: '" + remoteProps.getHostName() + "'"); + getLogger().info("on host: '{}'", remoteProps.getHostName()); } } @@ -845,7 +845,7 @@ public void runActiveTask() throws IOException, PipelineJobException } finally { - getLogger().info((success ? "Successfully completed" : "Failed to complete") + " task '" + factory.getId() + "'"); + getLogger().info("{} task '{}'", success ? "Successfully completed" : "Failed to complete", factory.getId()); logStartStopInfo((success ? "Successfully completed" : "Failed to complete") + " task '" + factory.getId() + "' for job '" + this + "' with log file " + getLogFile()); try @@ -886,7 +886,7 @@ public void runActiveTask() throws IOException, PipelineJobException else { logStartStopInfo("Skipping already completed task '" + factory.getId() + "' for job '" + this + "' with log file " + getLogFile()); - getLogger().info("Skipping already completed task '" + factory.getId() + "' at location '" + factory.getExecutionLocation() + "'"); + getLogger().info("Skipping already completed task '{}' at location '{}'", factory.getId(), factory.getExecutionLocation()); } if (getActiveTaskStatus() != TaskStatus.complete && getActiveTaskStatus() != TaskStatus.cancelled) @@ -1279,7 +1279,7 @@ public void runSubProcess(ProcessBuilder pb, FileLike dirWork, FileLike outputFi { Process proc; - String commandName = pb.command().get(0); + String commandName = pb.command().getFirst(); commandName = commandName.substring( Math.max(commandName.lastIndexOf('/'), commandName.lastIndexOf('\\')) + 1); header(commandName + " output"); @@ -1301,7 +1301,7 @@ public void runSubProcess(ProcessBuilder pb, FileLike dirWork, FileLike outputFi // If the command has a path, then prepend its parent directory to the PATH // environment variable as well. - String exePath = pb.command().get(0); + String exePath = pb.command().getFirst(); if (exePath != null && !exePath.isEmpty() && exePath.indexOf(File.separatorChar) != -1) { File fileExe = new File(exePath); @@ -1401,7 +1401,7 @@ else if (count == logLineInterval) int result = proc.exitValue(); if (result != 0) { - throw new ToolExecutionException("Failed running " + pb.command().get(0) + ", exit code " + result, result); + throw new ToolExecutionException("Failed running " + pb.command().getFirst() + ", exit code " + result, result); } int count = output.get(); diff --git a/api/src/org/labkey/api/pipeline/PipelineJobNotificationProvider.java b/api/src/org/labkey/api/pipeline/PipelineJobNotificationProvider.java index 25fa6653b5d..79eab7e2178 100644 --- a/api/src/org/labkey/api/pipeline/PipelineJobNotificationProvider.java +++ b/api/src/org/labkey/api/pipeline/PipelineJobNotificationProvider.java @@ -136,7 +136,7 @@ private static boolean canSendNotification(PipelineJob job) // don't attempt to add a notification if the Container has been deleted or is deleting if (!ContainerManager.exists(job.getContainer())) { - job.getLogger().info("Job container has been deleted or is being deleted; skipping notification for '" + Objects.toString(job.getDescription(), job.toString()) + "'"); + job.getLogger().info("Job container has been deleted or is being deleted; skipping notification for '{}'", Objects.toString(job.getDescription(), job.toString())); return false; } diff --git a/api/src/org/labkey/api/pipeline/PipelineProtocol.java b/api/src/org/labkey/api/pipeline/PipelineProtocol.java index c1fc87fd905..a0e823ea1c2 100644 --- a/api/src/org/labkey/api/pipeline/PipelineProtocol.java +++ b/api/src/org/labkey/api/pipeline/PipelineProtocol.java @@ -116,7 +116,7 @@ public void setProperty(String propertyName, String value) throws NoSuchMethodEx */ protected Map getSaveProperties() { - PropertyDescriptor props[] = PropertyUtils.getPropertyDescriptors(this); + PropertyDescriptor[] props = PropertyUtils.getPropertyDescriptors(this); Map propMap = new HashMap<>(); for (PropertyDescriptor prop : props) diff --git a/api/src/org/labkey/api/pipeline/PipelineProtocolFactory.java b/api/src/org/labkey/api/pipeline/PipelineProtocolFactory.java index 683707d5219..967bec79b01 100644 --- a/api/src/org/labkey/api/pipeline/PipelineProtocolFactory.java +++ b/api/src/org/labkey/api/pipeline/PipelineProtocolFactory.java @@ -175,8 +175,7 @@ public boolean changeArchiveStatus(PipeRoot root, String name, boolean moveToArc } else if (archiveDir.isFile()) { - LOG.error("Unable to create archived directory because a file with that name exists in the protocol directory: " - + getProtocolDir(root, false)); + LOG.error("Unable to create archived directory because a file with that name exists in the protocol directory: {}", getProtocolDir(root, false)); return false; } } @@ -222,7 +221,7 @@ public boolean deleteProtocolFile(PipeRoot root, String name) } catch (IOException e) { - LOG.debug("Error attempting to delete protocol file " + protocolFile, e); + LOG.debug("Error attempting to delete protocol file {}", protocolFile, e); return false; } } diff --git a/api/src/org/labkey/api/pipeline/PipelineService.java b/api/src/org/labkey/api/pipeline/PipelineService.java index f87384fb70d..1a1d4bbb3fd 100644 --- a/api/src/org/labkey/api/pipeline/PipelineService.java +++ b/api/src/org/labkey/api/pipeline/PipelineService.java @@ -40,7 +40,6 @@ import java.io.IOException; import java.net.URI; import java.nio.file.Path; -import java.sql.SQLException; import java.util.Collection; import java.util.Date; import java.util.List; @@ -121,7 +120,7 @@ static void setInstance(PipelineService instance) @Nullable PipeRoot getPipelineRootSetting(Container container, String type); - void setPipelineRoot(User user, Container container, String type, boolean searchable, URI... roots) throws SQLException; + void setPipelineRoot(User user, Container container, String type, boolean searchable, URI... roots); boolean canModifyPipelineRoot(User user, Container container); diff --git a/api/src/org/labkey/api/pipeline/PipelineStatusFile.java b/api/src/org/labkey/api/pipeline/PipelineStatusFile.java index 63a656e2ccc..6eb52fe0c77 100644 --- a/api/src/org/labkey/api/pipeline/PipelineStatusFile.java +++ b/api/src/org/labkey/api/pipeline/PipelineStatusFile.java @@ -22,7 +22,6 @@ import java.io.File; import java.io.IOException; import java.nio.file.Path; -import java.sql.SQLException; import java.util.Date; import java.util.List; @@ -47,9 +46,9 @@ default PipelineStatusFile getStatusFile(Container container, FileLike logFile) PipelineStatusFile getStatusFile(String jobGuid); - List getQueuedStatusFiles() throws SQLException; + List getQueuedStatusFiles(); - List getQueuedStatusFiles(Container c) throws SQLException; + List getQueuedStatusFiles(Container c); } interface StatusWriter diff --git a/api/src/org/labkey/api/pipeline/PipelineUrls.java b/api/src/org/labkey/api/pipeline/PipelineUrls.java index c0c098db078..f234371776e 100644 --- a/api/src/org/labkey/api/pipeline/PipelineUrls.java +++ b/api/src/org/labkey/api/pipeline/PipelineUrls.java @@ -24,8 +24,6 @@ import org.labkey.api.view.ActionURL; import org.labkey.vfs.FileLike; -import java.nio.file.Path; - /** * PipelineUrls a UrlProvider for the pipeline UI. */ diff --git a/api/src/org/labkey/api/pipeline/browse/PipelinePathForm.java b/api/src/org/labkey/api/pipeline/browse/PipelinePathForm.java index 7db45135681..77379e7fef9 100644 --- a/api/src/org/labkey/api/pipeline/browse/PipelinePathForm.java +++ b/api/src/org/labkey/api/pipeline/browse/PipelinePathForm.java @@ -173,7 +173,7 @@ public FileLike getValidatedSingleFile(Container c) { throw new IllegalArgumentException("Expected a single file but got " + files.size()); } - return files.get(0); + return files.getFirst(); } /** Verifies that only a single file was selected and returns it, throwing an exception if there isn't exactly one */ @@ -185,6 +185,6 @@ public Path getValidatedSinglePath(Container c) { throw new IllegalArgumentException("Expected a single file but got " + files.size()); } - return files.get(0); + return files.getFirst(); } } diff --git a/api/src/org/labkey/api/pipeline/file/AbstractFileAnalysisJob.java b/api/src/org/labkey/api/pipeline/file/AbstractFileAnalysisJob.java index dfc9b844271..e37a0dbb348 100644 --- a/api/src/org/labkey/api/pipeline/file/AbstractFileAnalysisJob.java +++ b/api/src/org/labkey/api/pipeline/file/AbstractFileAnalysisJob.java @@ -87,7 +87,7 @@ public AbstractFileAnalysisJob(@NotNull AbstractFileAnalysisProtocol protocol _filesInput = filesInput; _inputTypes = FileType.findTypes(protocol.getInputTypes(), _filesInput); - _dirData = filesInput.get(0).getParent(); + _dirData = filesInput.getFirst().getParent(); _protocolName = protocolName; _fileParameters = fileParameters; @@ -123,7 +123,7 @@ public AbstractFileAnalysisJob(@NotNull AbstractFileAnalysisProtocol protocol } else { - _baseName = protocol.getBaseName(_filesInput.get(0)); + _baseName = protocol.getBaseName(_filesInput.getFirst()); } String logFile = protocol.timestampLog() ? FileUtil.makeFileNameWithTimestamp(_baseName) : _baseName; @@ -162,7 +162,7 @@ public AbstractFileAnalysisJob(AbstractFileAnalysisJob job, List files // Change parameters which are specific to the fraction job. _filesInput = new ArrayList<>(filesInput); _inputTypes = FileType.findTypes(job._inputTypes, _filesInput); - _baseName = (_inputTypes.isEmpty() ? filesInput.get(0).getName() : _inputTypes.get(0).getBaseName(filesInput.get(0))); + _baseName = (_inputTypes.isEmpty() ? filesInput.getFirst().getName() : _inputTypes.getFirst().getBaseName(filesInput.getFirst())); setupLocalDirectoryAndJobLog(getPipeRoot(), _baseName); } @@ -289,7 +289,7 @@ public static FileLike getOutputFile(@NotNull String outputDir, @NotNull String if (!NetworkDrive.exists(dir)) { - log.info("Creating output directory under pipeline root: " + dir); + log.info("Creating output directory under pipeline root: {}", dir); try { dir.mkdirs(); @@ -305,7 +305,7 @@ public static FileLike getOutputFile(@NotNull String outputDir, @NotNull String dir = analysisDirectory.resolveChild(outputDir); if (!NetworkDrive.exists(dir)) { - log.info("Creating output directory under pipeline analysis dir: " + dir); + log.info("Creating output directory under pipeline analysis dir: {}", dir); try { dir.mkdirs(); @@ -381,9 +381,9 @@ public ParamParser getInputParameters(FileLike parametersFile) throws IOExceptio private void logParameters(String description, FileLike file, Map parameters) { - _log.debug(description + " " + parameters.size() + " parameters (" + file + "):"); + _log.debug("{} {} parameters ({}):", description, parameters.size(), file); for (Map.Entry entry : new TreeMap<>(parameters).entrySet()) - _log.debug(entry.getKey() + " = " + entry.getValue()); + _log.debug("{} = {}", entry.getKey(), entry.getValue()); _log.debug(""); } diff --git a/api/src/org/labkey/api/pipeline/file/AbstractFileAnalysisProtocol.java b/api/src/org/labkey/api/pipeline/file/AbstractFileAnalysisProtocol.java index 2f13f675526..35101b63d97 100644 --- a/api/src/org/labkey/api/pipeline/file/AbstractFileAnalysisProtocol.java +++ b/api/src/org/labkey/api/pipeline/file/AbstractFileAnalysisProtocol.java @@ -196,7 +196,7 @@ protected void save(FileLike file, Map addParams, Map void queueScan(@NotNull File f, @Nullable String originalName, ViewB default void warnAndAuditLog(Logger log, String logmessage, ViewBackgroundInfo info, @Nullable String originalName) { - log.warn((null != info.getUser() ? info.getUser().getEmail() + " " : "") + logmessage); + log.warn("{}{}", null != info.getUser() ? info.getUser().getEmail() + " " : "", logmessage); FileSystemAuditProvider.FileSystemAuditEvent event = new FileSystemAuditProvider.FileSystemAuditEvent( info.getContainer(), logmessage ); diff --git a/api/src/org/labkey/api/premium/DefaultAVMultipartResolver.java b/api/src/org/labkey/api/premium/DefaultAVMultipartResolver.java index 0899c3b8f77..db989cd6402 100644 --- a/api/src/org/labkey/api/premium/DefaultAVMultipartResolver.java +++ b/api/src/org/labkey/api/premium/DefaultAVMultipartResolver.java @@ -7,7 +7,6 @@ import org.jetbrains.annotations.NotNull; import org.labkey.api.action.ApiUsageException; import org.labkey.api.util.FileUtil; -import org.labkey.api.view.UnauthorizedException; import org.springframework.web.multipart.MultipartException; import org.springframework.web.multipart.MultipartHttpServletRequest; import org.springframework.web.multipart.support.StandardMultipartHttpServletRequest; diff --git a/api/src/org/labkey/api/products/ProductRegistry.java b/api/src/org/labkey/api/products/ProductRegistry.java index 49599278727..3d9c87ca38d 100644 --- a/api/src/org/labkey/api/products/ProductRegistry.java +++ b/api/src/org/labkey/api/products/ProductRegistry.java @@ -211,7 +211,7 @@ public String getPrimaryProductIdForContainer(@NotNull Container container) if (productIds.isEmpty()) return null; if (productIds.size() == 1) - return productIds.get(0); + return productIds.getFirst(); ProductMenuProvider provider = getPrimaryProductMenuForContainer(container); return provider != null ? provider.getProductId() : null; } @@ -227,7 +227,7 @@ public ProductMenuProvider getPrimaryProductMenuForContainer(@NotNull Container return null; if (providers.size() == 1) - return providers.get(0); + return providers.getFirst(); // see if there's a provider that matches the folder type (need to check this first so if LabKey LIMS or LKB is the configured product you can still show LKSM folders) Optional optionalProvider = providers.stream().filter(provider -> provider.getFolderTypeName() != null && provider.getFolderTypeName().equals(container.getFolderType().getName())).findFirst(); @@ -307,7 +307,7 @@ public MenuSection getMenuSection(@NotNull ViewContext context, @NotNull String } else { - _logger.warn("No product menu provider registered for menu section '" + name + "'."); + _logger.warn("No product menu provider registered for menu section '{}'.", name); return null; } } @@ -321,7 +321,7 @@ public List getMenuSections(@NotNull ViewContext context, @NotNull if (section != null) items.add(section); else - _logger.warn("No section provided for menu section name '" + name + "'."); + _logger.warn("No section provided for menu section name '{}'.", name); }); return items; } @@ -450,7 +450,7 @@ public void getMenuSectionsByProductId() sections = registry.getMenuSections(context, VALID_PRODUCT_ID_2); assertEquals("Number of menu sections not as expected when provider has no sections", 1, sections.size()); - assertEquals("User section label not as expected", UserInfoMenuSection.NAME, sections.get(0).getLabel()); + assertEquals("User section label not as expected", UserInfoMenuSection.NAME, sections.getFirst().getLabel()); } @Test diff --git a/api/src/org/labkey/api/qc/SampleStatusService.java b/api/src/org/labkey/api/qc/SampleStatusService.java index 1d067d2b48e..4a7d55e2fe8 100644 --- a/api/src/org/labkey/api/qc/SampleStatusService.java +++ b/api/src/org/labkey/api/qc/SampleStatusService.java @@ -32,7 +32,7 @@ static void registerProvider(SampleStatusService provider) static SampleStatusService get() { if (!_providers.isEmpty()) - return _providers.get(0); + return _providers.getFirst(); return _defaultProvider; } diff --git a/api/src/org/labkey/api/qc/TsvDataExchangeHandler.java b/api/src/org/labkey/api/qc/TsvDataExchangeHandler.java index 9fff1b0e1f0..4eca1295ce8 100644 --- a/api/src/org/labkey/api/qc/TsvDataExchangeHandler.java +++ b/api/src/org/labkey/api/qc/TsvDataExchangeHandler.java @@ -997,7 +997,7 @@ else if (String.valueOf(row.get("name")).equalsIgnoreCase(Props.runDataUploadedF { tempOutputFiles.addAll(runDataUploadedFiles); // Since there could be many input files, we'll use the parent directory of the first file we found as the working directory - setWorkingDirectory(context, new File(runDataUploadedFiles.get(0).getParentFile().getAbsolutePath())); + setWorkingDirectory(context, new File(runDataUploadedFiles.getFirst().getParentFile().getAbsolutePath())); } // Loop through all the files that are left after running the transform script @@ -1006,7 +1006,7 @@ else if (String.valueOf(row.get("name")).equalsIgnoreCase(Props.runDataUploadedF if (!isIgnorableOutput(file) && !runDataUploadedFiles.isEmpty()) { // Since there could be many uploaded data files, we'll just use the base name of the first one we found - File firstFile = runDataUploadedFiles.get(0); + File firstFile = runDataUploadedFiles.getFirst(); int extensionIndex = firstFile.getName().lastIndexOf("."); String baseName = extensionIndex >= 0 ? firstFile.getName().substring(0, extensionIndex) : firstFile.getName(); @@ -1055,7 +1055,7 @@ else if (String.valueOf(row.get("name")).equalsIgnoreCase(Props.runDataUploadedF { File file = entry.getValue(); String type = entry.getKey(); - log.debug("processing transformed data file: type=" + type + ", file=" + file.getPath()); + log.debug("processing transformed data file: type={}, file={}", type, file.getPath()); FileLike workingDir = getWorkingDirectory(context); if (workingDir == null) @@ -1071,7 +1071,7 @@ else if (String.valueOf(row.get("name")).equalsIgnoreCase(Props.runDataUploadedF FileLike tempDirCopy = workingDir.resolveChild(file.getName()); if (!file.toPath().equals(tempDirCopy.toNioPathForRead())) { - log.debug("moving to working directory=" + tempDirCopy); + log.debug("moving to working directory={}", tempDirCopy); FileUtils.moveFile(file, tempDirCopy.toNioPathForWrite().toFile()); file = tempDirCopy.toNioPathForWrite().toFile(); } diff --git a/api/src/org/labkey/api/qc/TsvDataSerializer.java b/api/src/org/labkey/api/qc/TsvDataSerializer.java index 839ef801867..c8c91e58b62 100644 --- a/api/src/org/labkey/api/qc/TsvDataSerializer.java +++ b/api/src/org/labkey/api/qc/TsvDataSerializer.java @@ -105,7 +105,7 @@ private List exportData(DataIteratorBuilder data, List columns, return columns; } - private static void writeRow(Map row, List columns, PrintWriter pw, TSVWriter tsvWriter) throws IOException, BatchValidationException + private static void writeRow(Map row, List columns, PrintWriter pw, TSVWriter tsvWriter) throws IOException { String sep; sep = ""; diff --git a/api/src/org/labkey/api/qc/export/AbstractDataStateImporter.java b/api/src/org/labkey/api/qc/export/AbstractDataStateImporter.java index 52c20ccdd01..7de54e58ec7 100644 --- a/api/src/org/labkey/api/qc/export/AbstractDataStateImporter.java +++ b/api/src/org/labkey/api/qc/export/AbstractDataStateImporter.java @@ -74,7 +74,7 @@ public static void importQCStates(ImportExportContext ctx, StudyqcDocument do if (!helper.isDataStateInUse(ctx.getContainer(), orphanedState)) QCStateManager.getInstance().deleteState(orphanedState); else - ctx.getLogger().info("Retaining existing Data State because it is still in use, even though it's missing from the new list: " + orphanedState.getLabel()); + ctx.getLogger().info("Retaining existing Data State because it is still in use, even though it's missing from the new list: {}", orphanedState.getLabel()); } Map finalStates = getExistingDataStates(ctx); diff --git a/api/src/org/labkey/api/qc/export/DataStateImportExportHelper.java b/api/src/org/labkey/api/qc/export/DataStateImportExportHelper.java index 1eb33b10b67..903152c9d97 100644 --- a/api/src/org/labkey/api/qc/export/DataStateImportExportHelper.java +++ b/api/src/org/labkey/api/qc/export/DataStateImportExportHelper.java @@ -34,7 +34,7 @@ static DataStateImportExportHelper getProvider(Container container) helpers.sort(Comparator.comparingInt(DataStateImportExportHelper::getPriority)); if (!helpers.isEmpty()) - return helpers.get(0); + return helpers.getFirst(); return null; } diff --git a/api/src/org/labkey/api/query/AbstractBeanQueryUpdateService.java b/api/src/org/labkey/api/query/AbstractBeanQueryUpdateService.java index 72dea5bf2f8..6c413ce36ac 100644 --- a/api/src/org/labkey/api/query/AbstractBeanQueryUpdateService.java +++ b/api/src/org/labkey/api/query/AbstractBeanQueryUpdateService.java @@ -18,6 +18,7 @@ import org.apache.commons.beanutils.BeanUtils; import org.apache.commons.beanutils.converters.IntegerConverter; import org.jetbrains.annotations.Nullable; +import org.jetbrains.annotations.NotNull; import org.labkey.api.collections.CaseInsensitiveHashMap; import org.labkey.api.data.Container; import org.labkey.api.data.ObjectFactory; @@ -61,7 +62,6 @@ public AbstractBeanQueryUpdateService(TableInfo queryTable) * @return A map of the bean's properties * @throws QueryUpdateServiceException Thrown if there were problems converting */ - @SuppressWarnings("unchecked") protected Map mapFromBean(T bean) throws QueryUpdateServiceException { if(null == bean) @@ -125,7 +125,7 @@ protected final Map insertRow(User user, Container container, Ma @Override protected final Map updateRow(User user, Container container, - Map row, Map oldRow, @Nullable Map configParameters) + Map row, @NotNull Map oldRow, @Nullable Map configParameters) throws InvalidKeyException, ValidationException, QueryUpdateServiceException, SQLException { K oldKey = null != oldRow ? keyFromMap(oldRow) : keyFromMap(row); @@ -179,11 +179,9 @@ protected final Map deleteRow(User user, Container container, Ma * @return The bean after insert. If the bean has a database-assigned key, they key value(s) should * be set on the bean. Callers will reload the bean if trigger-assigned values are needed. * @throws ValidationException Thrown if the bean is invalid. - * @throws DuplicateKeyException Thrown if the key is already used in the database. * @throws QueryUpdateServiceException Thrown for implementation-specific exceptions. - * @throws SQLException Thrown if there was a problem communicating with the database. */ - protected abstract T insert(User user, Container container, T bean) throws ValidationException, DuplicateKeyException, QueryUpdateServiceException, SQLException; + protected abstract T insert(User user, Container container, T bean) throws ValidationException, QueryUpdateServiceException; /** * Updates a bean in the database. @@ -194,9 +192,8 @@ protected final Map deleteRow(User user, Container container, Ma * @return The bean after update. Callers will reload the bean if trigger-assigned values are needed. * @throws ValidationException Thrown if the bean is invalid. * @throws QueryUpdateServiceException Thrown for implementation-specific exceptions. - * @throws SQLException Thrown if there is a problem communicating with the database. */ - protected abstract T update(User user, Container container, T bean, K oldKey) throws ValidationException, QueryUpdateServiceException, SQLException; + protected abstract T update(User user, Container container, T bean, K oldKey) throws ValidationException, QueryUpdateServiceException; /** * Deletes a bean in the database. diff --git a/api/src/org/labkey/api/query/AbstractQueryUpdateService.java b/api/src/org/labkey/api/query/AbstractQueryUpdateService.java index 4a7caf3c5a3..27d7080a0ab 100644 --- a/api/src/org/labkey/api/query/AbstractQueryUpdateService.java +++ b/api/src/org/labkey/api/query/AbstractQueryUpdateService.java @@ -578,9 +578,9 @@ protected DataIteratorBuilder _toDataIteratorBuilder(String debugName, List colNames; - if (!rows.isEmpty() && rows.get(0) instanceof ArrayListMap) + if (!rows.isEmpty() && rows.getFirst() instanceof ArrayListMap) { - colNames = ((ArrayListMap)rows.get(0)).getFindMap().keySet(); + colNames = ((ArrayListMap)rows.getFirst()).getFindMap().keySet(); } else { @@ -812,7 +812,7 @@ protected static boolean hasUniformKeys(List> rowsToUpdate) if (rowsToUpdate.size() == 1) return true; - Set keys = rowsToUpdate.get(0).keySet(); + Set keys = rowsToUpdate.getFirst().keySet(); int keySize = keys.size(); for (int i = 1 ; i < rowsToUpdate.size(); i ++) @@ -1542,7 +1542,7 @@ public void addRowError(ValidationException vex) int count=0; try (var tx = rTableInfo.getSchema().getScope().ensureTransaction()) { - var ret = qus.mergeRows(user, c, MapDataIterator.of(mergeRows.get(0).keySet(), mergeRows), errors, null, null); + var ret = qus.mergeRows(user, c, MapDataIterator.of(mergeRows.getFirst().keySet(), mergeRows), errors, null, null); if (!errors.hasErrors()) { tx.commit(); @@ -1565,7 +1565,7 @@ public void addRowError(ValidationException vex) mergeRows = new ArrayList<>(); mergeRows.add(CaseInsensitiveHashMap.of(pkName,2,colName,"TWO-UP-2")); mergeRows.add(CaseInsensitiveHashMap.of(pkName,2,colName,"TWO-UP-UP-2")); - qus.mergeRows(user, c, MapDataIterator.of(mergeRows.get(0).keySet(), mergeRows), errors, null, null); + qus.mergeRows(user, c, MapDataIterator.of(mergeRows.getFirst().keySet(), mergeRows), errors, null, null); assertTrue(errors.hasErrors()); assertTrue("Duplicate key error: " + errors.getMessage(), errors.getMessage().contains("Duplicate key provided: 2")); } @@ -1590,7 +1590,7 @@ public void UPDATE() throws Exception updateRows.add(CaseInsensitiveHashMap.of(pkName,2,colName,"TWO-UP")); DataIteratorContext context = new DataIteratorContext(); context.setInsertOption(InsertOption.UPDATE); - var count = qus.loadRows(user, c, MapDataIterator.of(updateRows.get(0).keySet(), updateRows), context, null); + var count = qus.loadRows(user, c, MapDataIterator.of(updateRows.getFirst().keySet(), updateRows), context, null); assertFalse(context.getErrors().hasErrors()); assertEquals(1, count); var rows = getRows(); @@ -1603,7 +1603,7 @@ public void UPDATE() throws Exception updateRows = new ArrayList<>(); updateRows.add(CaseInsensitiveHashMap.of(pkName,123,colName,"NEW")); updateRows.add(CaseInsensitiveHashMap.of(pkName,2,colName,"TWO-UP-2")); - qus.loadRows(user, c, MapDataIterator.of(updateRows.get(0).keySet(), updateRows), context, null); + qus.loadRows(user, c, MapDataIterator.of(updateRows.getFirst().keySet(), updateRows), context, null); assertTrue(context.getErrors().hasErrors()); // Issue 52728: update should fail if duplicate key is provide @@ -1614,7 +1614,7 @@ public void UPDATE() throws Exception // use DIB context = new DataIteratorContext(); context.setInsertOption(InsertOption.UPDATE); - qus.loadRows(user, c, MapDataIterator.of(updateRows.get(0).keySet(), updateRows), context, null); + qus.loadRows(user, c, MapDataIterator.of(updateRows.getFirst().keySet(), updateRows), context, null); assertTrue(context.getErrors().hasErrors()); assertTrue("Duplicate key error: " + context.getErrors().getMessage(), context.getErrors().getMessage().contains("Duplicate key provided: 2")); @@ -1655,7 +1655,7 @@ public void REPLACE() throws Exception mergeRows.add(CaseInsensitiveHashMap.of(pkName,3,colName,"THREE")); DataIteratorContext context = new DataIteratorContext(); context.setInsertOption(InsertOption.REPLACE); - var count = qus.loadRows(user, c, MapDataIterator.of(mergeRows.get(0).keySet(), mergeRows), context, null); + var count = qus.loadRows(user, c, MapDataIterator.of(mergeRows.getFirst().keySet(), mergeRows), context, null); assertFalse(context.getErrors().hasErrors()); assertEquals(2, count); var rows = getRows(); diff --git a/api/src/org/labkey/api/query/BatchValidationException.java b/api/src/org/labkey/api/query/BatchValidationException.java index 40b4f08d0cc..b971a986633 100644 --- a/api/src/org/labkey/api/query/BatchValidationException.java +++ b/api/src/org/labkey/api/query/BatchValidationException.java @@ -76,7 +76,7 @@ public ValidationException getLastRowError() { if (rowErrors.isEmpty()) return null; - return rowErrors.get(rowErrors.size()-1); + return rowErrors.getLast(); } public void addToErrors(Errors errorsTarget) diff --git a/api/src/org/labkey/api/query/CacheClearingQueryUpdateService.java b/api/src/org/labkey/api/query/CacheClearingQueryUpdateService.java index be629d315cc..bdb40f298c2 100644 --- a/api/src/org/labkey/api/query/CacheClearingQueryUpdateService.java +++ b/api/src/org/labkey/api/query/CacheClearingQueryUpdateService.java @@ -16,6 +16,7 @@ package org.labkey.api.query; import org.jetbrains.annotations.Nullable; +import org.jetbrains.annotations.NotNull; import org.labkey.api.data.Container; import org.labkey.api.dataiterator.DataIteratorBuilder; import org.labkey.api.dataiterator.DataIteratorContext; @@ -150,7 +151,7 @@ public boolean isBulkLoad() } @Override - public boolean hasPermission(UserPrincipal user, Class acl) + public boolean hasPermission(@NotNull UserPrincipal user, @NotNull Class acl) { return _service.hasPermission(user, acl); } diff --git a/api/src/org/labkey/api/query/CustomViewChangeListener.java b/api/src/org/labkey/api/query/CustomViewChangeListener.java index 40d3d88d78f..cb6d9009be3 100644 --- a/api/src/org/labkey/api/query/CustomViewChangeListener.java +++ b/api/src/org/labkey/api/query/CustomViewChangeListener.java @@ -154,7 +154,7 @@ static FieldKey getUpdatedFieldKeyReference(FieldKey col, @Nullable Map parts = getParts(); - if (parts.size() > 1 && parts.get(0).equalsIgnoreCase(rootPart)) + if (parts.size() > 1 && parts.getFirst().equalsIgnoreCase(rootPart)) { parts = parts.subList(1, parts.size()); return FieldKey.fromParts(parts); @@ -317,16 +317,16 @@ public static class TestCase extends Assert @Test public void testCompare() { - assertTrue(new FieldKey(null,"a").compareTo(new FieldKey(null,"a")) == 0); - assertTrue(new FieldKey(null,"a").compareTo(new FieldKey(null,"A")) == 0); + assertEquals(0, new FieldKey(null, "a").compareTo(new FieldKey(null, "a"))); + assertEquals(0, new FieldKey(null, "a").compareTo(new FieldKey(null, "A"))); assertTrue(new FieldKey(null,"a").compareTo(new FieldKey(null,"b")) < 0); assertTrue(new FieldKey(null,"a").compareTo(new FieldKey(null,"B")) < 0); - assertTrue(new FieldKey(null,"A").compareTo(new FieldKey(null,"a")) == 0); - assertTrue(new FieldKey(null,"A").compareTo(new FieldKey(null,"A")) == 0); + assertEquals(0, new FieldKey(null, "A").compareTo(new FieldKey(null, "a"))); + assertEquals(0, new FieldKey(null, "A").compareTo(new FieldKey(null, "A"))); assertTrue(new FieldKey(null,"A").compareTo(new FieldKey(null,"b")) < 0); assertTrue(new FieldKey(null,"A").compareTo(new FieldKey(null,"B")) < 0); - assertTrue(fromParts("a","b").compareTo(fromParts("a","b")) == 0); + assertEquals(0, fromParts("a", "b").compareTo(fromParts("a", "b"))); assertTrue(fromParts("a","b").compareTo(fromParts("b","a")) < 0); assertTrue(fromParts("b","a").compareTo(fromParts("a","b")) > 0); assertTrue(fromParts("a","b").compareTo(fromParts("a","c")) < 0); diff --git a/api/src/org/labkey/api/query/FilteredTableDelegating.java b/api/src/org/labkey/api/query/FilteredTableDelegating.java index 5d4195c3c9d..bd06b7ad560 100644 --- a/api/src/org/labkey/api/query/FilteredTableDelegating.java +++ b/api/src/org/labkey/api/query/FilteredTableDelegating.java @@ -60,13 +60,6 @@ public MutableColumnInfo wrapColumnFromJoinedTable(String name, ColumnInfo under } */ - @Override - public MutableColumnInfo wrapColumn(String alias, ColumnInfo underlyingColumn) - { - assert underlyingColumn.getParentTable() == _rootTable; - return wrapColumnFromJoinedTable(alias, underlyingColumn); - } - @Override public MutableColumnInfo wrapColumn(ColumnInfo underlyingColumn) { diff --git a/api/src/org/labkey/api/query/PdLookupForeignKey.java b/api/src/org/labkey/api/query/PdLookupForeignKey.java index d5afa9b9d81..921db49620d 100644 --- a/api/src/org/labkey/api/query/PdLookupForeignKey.java +++ b/api/src/org/labkey/api/query/PdLookupForeignKey.java @@ -16,7 +16,6 @@ package org.labkey.api.query; -import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.Strings; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; @@ -274,7 +273,7 @@ public StringExpression getURL(ColumnInfo parent) TableInfo lookupTable = getLookupTableInfo(); if (lookupTable == null) return null; - String columnName = lookupTable.getPkColumns().get(0).getName(); + String columnName = lookupTable.getPkColumns().getFirst().getName(); if (null == columnName) return null; return LookupForeignKey.getDetailsURL(parent, lookupTable, columnName); diff --git a/api/src/org/labkey/api/query/PropertyForeignKey.java b/api/src/org/labkey/api/query/PropertyForeignKey.java index 2e4e06f7133..28b775d3982 100644 --- a/api/src/org/labkey/api/query/PropertyForeignKey.java +++ b/api/src/org/labkey/api/query/PropertyForeignKey.java @@ -175,7 +175,7 @@ public TableInfo getLookupTableInfo() } else { - LOG.warn("Duplicate property name found with " + column.getName() + ", PropertyURI: " + entry.getValue().getPropertyURI()); + LOG.warn("Duplicate property name found with {}, PropertyURI: {}", column.getName(), entry.getValue().getPropertyURI()); } } } diff --git a/api/src/org/labkey/api/query/QueryDefinition.java b/api/src/org/labkey/api/query/QueryDefinition.java index 0ceb181ccca..44874cf8ae5 100644 --- a/api/src/org/labkey/api/query/QueryDefinition.java +++ b/api/src/org/labkey/api/query/QueryDefinition.java @@ -32,7 +32,6 @@ import org.labkey.data.xml.TableType; import org.labkey.data.xml.TablesDocument; -import java.sql.SQLException; import java.util.Collection; import java.util.List; import java.util.Map; @@ -155,16 +154,16 @@ public interface QueryDefinition * TableQueryDefinition and file-based queries cannot be deleted. * Fires the {@link QueryChangeListener#queryChanged(User, Container, ContainerFilter, SchemaKey, QueryProperty, Collection)} event. */ - Collection> save(User user, Container container) throws SQLException; - Collection> save(User user, Container container, boolean fireChangeEvent) throws SQLException; + Collection> save(User user, Container container); + Collection> save(User user, Container container, boolean fireChangeEvent); /** * Delete the QueryDefinition. * TableQueryDefinition and file-based queries cannot be deleted. * Fires the {@link QueryChangeListener#queryDeleted(User, Container, ContainerFilter, SchemaKey, Collection)} event. */ - void delete(User user) throws SQLException; - void delete(User user, boolean fireChangeEvent) throws SQLException; + void delete(User user); + void delete(User user, boolean fireChangeEvent); List getParseErrors(QuerySchema schema); boolean validateQuery(QuerySchema schema, List errors, List warnings); diff --git a/api/src/org/labkey/api/query/QueryImportPipelineJob.java b/api/src/org/labkey/api/query/QueryImportPipelineJob.java index c40ca372464..cc236d69a4f 100644 --- a/api/src/org/labkey/api/query/QueryImportPipelineJob.java +++ b/api/src/org/labkey/api/query/QueryImportPipelineJob.java @@ -305,7 +305,7 @@ public void run() try { setStatus(TaskStatus.running); - getLogger().info("Starting import " + getDescription()); + getLogger().info("Starting import {}", getDescription()); if (notificationProvider != null) notificationProvider.onJobStart(this); @@ -344,7 +344,7 @@ public void run() _transactionAuditId = auditEvent.getRowId(); setStatus(TaskStatus.complete); - getLogger().info("Done importing " + getDescription() + ". " + importedCount + " row(s) imported."); + getLogger().info("Done importing {}. {} row(s) imported.", getDescription(), importedCount); if (notificationProvider != null) { diff --git a/api/src/org/labkey/api/query/QueryKey.java b/api/src/org/labkey/api/query/QueryKey.java index 98cc178b914..c7fa7264c00 100644 --- a/api/src/org/labkey/api/query/QueryKey.java +++ b/api/src/org/labkey/api/query/QueryKey.java @@ -123,7 +123,7 @@ static protected > T fromParts(Factory factory, List> T fromParts(Factory factory, T... parts) diff --git a/api/src/org/labkey/api/query/QueryService.java b/api/src/org/labkey/api/query/QueryService.java index ca864247b89..63b143149a8 100644 --- a/api/src/org/labkey/api/query/QueryService.java +++ b/api/src/org/labkey/api/query/QueryService.java @@ -63,7 +63,6 @@ import java.io.IOException; import java.sql.ResultSet; -import java.sql.SQLException; import java.util.Collection; import java.util.LinkedHashMap; import java.util.List; @@ -193,7 +192,7 @@ UserSchema createLinkedSchema(User user, Container container, String name, Strin */ Map getCustomViewProperties(@Nullable CustomView view, @Nullable User user); - String getCustomViewNameFromEntityId(Container container, String entityId) throws SQLException; + String getCustomViewNameFromEntityId(Container container, String entityId); /** * Loops through the field keys and turns them into ColumnInfos based on the base table @@ -261,7 +260,7 @@ default ResultSet select(QuerySchema schema, String sql) Results select(QuerySchema schema, String sql, @Nullable Map tableMap, boolean strictColumnList, boolean cached); /** superseded by {@link QueryService#getSelectBuilder} */ - Results selectResults(@NotNull QuerySchema schema, String sql, @Nullable Map tableMap, Map parameters, boolean strictColumnList, boolean cached) throws SQLException; + Results selectResults(@NotNull QuerySchema schema, String sql, @Nullable Map tableMap, Map parameters, boolean strictColumnList, boolean cached); /** superseded by {@link QueryService#getSelectBuilder} */ default Results select(TableInfo table, Collection columns, @Nullable Filter filter, @Nullable Sort sort) diff --git a/api/src/org/labkey/api/query/QuerySettings.java b/api/src/org/labkey/api/query/QuerySettings.java index 9ba5ba0b963..389ebee210d 100644 --- a/api/src/org/labkey/api/query/QuerySettings.java +++ b/api/src/org/labkey/api/query/QuerySettings.java @@ -507,13 +507,11 @@ public URLHelper getReturnUrlHelper(URLHelper defaultURL) public String param(QueryParam param) { - switch (param) + return switch (param) { - case schemaName: - return param.toString(); - default: - return param(param.toString()); - } + case schemaName -> param.toString(); + default -> param(param.toString()); + }; } protected String param(String param) diff --git a/api/src/org/labkey/api/query/QueryView.java b/api/src/org/labkey/api/query/QueryView.java index bdf1e5c638e..00a520d703d 100644 --- a/api/src/org/labkey/api/query/QueryView.java +++ b/api/src/org/labkey/api/query/QueryView.java @@ -1724,7 +1724,7 @@ protected void addGridViews(MenuButton menu, URLHelper target, String currentVie { // don't pass getUser() as owner, we want the default view to appear as "public" CustomView defaultView = getQueryDef().createCustomView(); - views.add(0, defaultView); + views.addFirst(defaultView); } // sort the grid view alphabetically, with default first (null name), then private views over public ones @@ -2891,7 +2891,7 @@ public void exportToApiResponse(ApiQueryResponse response) //table was null--try to get parse errors List errors = getParseErrors(); if (null != errors && !errors.isEmpty()) - throw errors.get(0); + throw errors.getFirst(); } } @@ -3096,7 +3096,7 @@ protected void addDetailsAndUpdateColumns(List ret, TableInfo tab { DisplayColumn dc = createUpdateColumn(urlUpdate, table); if (null != dc) - ret.add(0, dc); + ret.addFirst(dc); } } } diff --git a/api/src/org/labkey/api/query/RowIdQueryUpdateService.java b/api/src/org/labkey/api/query/RowIdQueryUpdateService.java index 45f327254d0..cde9e4272b8 100644 --- a/api/src/org/labkey/api/query/RowIdQueryUpdateService.java +++ b/api/src/org/labkey/api/query/RowIdQueryUpdateService.java @@ -42,9 +42,9 @@ public RowIdQueryUpdateService(TableInfo table) { super(table); assert table.getPkColumns().size() == 1; - assert table.getPkColumns().get(0).getJavaClass() == Integer.class || table.getPkColumns().get(0).getJavaClass() == int.class; + assert table.getPkColumns().getFirst().getJavaClass() == Integer.class || table.getPkColumns().getFirst().getJavaClass() == int.class; - _keyColumn = table.getPkColumnNames().get(0); + _keyColumn = table.getPkColumnNames().getFirst(); } @Override @@ -71,10 +71,8 @@ public final void delete(User user, Container container, Integer key) throws Que * @param container The container in which the bean should live. * @param key The primary key. * @return The bean instance corresponding to the key. - * @throws QueryUpdateServiceException Thrown for provider-specific exceptions. - * @throws SQLException Thrown if there was a problem communicating with the database. */ - public abstract T get(User user, Container container, int key) throws QueryUpdateServiceException, SQLException; + public abstract T get(User user, Container container, int key); /** * Deletes the bean instance corresponding to the provided key value. @@ -82,8 +80,7 @@ public final void delete(User user, Container container, Integer key) throws Que * @param container The container in which the bean should live. * @param key The primary key. * @throws QueryUpdateServiceException Thrown for provider-specific exceptions. - * @throws SQLException Thrown if there was a problem communicating with the database. */ - public abstract void delete(User user, Container container, int key) throws QueryUpdateServiceException, SQLException; + public abstract void delete(User user, Container container, int key) throws QueryUpdateServiceException; } diff --git a/api/src/org/labkey/api/query/SchemaKey.java b/api/src/org/labkey/api/query/SchemaKey.java index f372c36b56f..f01f2e80885 100644 --- a/api/src/org/labkey/api/query/SchemaKey.java +++ b/api/src/org/labkey/api/query/SchemaKey.java @@ -75,10 +75,10 @@ static public SchemaKey fromParts(String...parts) return fromParts(Arrays.asList(parts)); } - static public SchemaKey fromParts(Enum... parts) + static public SchemaKey fromParts(Enum... parts) { List strings = new ArrayList<>(parts.length); - for (Enum part : parts) + for (Enum part : parts) { strings.add(part.toString()); } @@ -102,7 +102,7 @@ public SchemaKey(SchemaKey parent, @NotNull String name) super(parent, name); } - public SchemaKey(SchemaKey parent, Enum name) + public SchemaKey(SchemaKey parent, Enum name) { super(parent, name.toString()); } @@ -120,7 +120,7 @@ public SchemaKey getParent() } @Override - public int compareTo(SchemaKey o) + public int compareTo(@NotNull SchemaKey o) { return CASE_INSENSITIVE_ORDER.compare(this, o); } @@ -202,16 +202,16 @@ public static class TestCase extends Assert @Test public void test() { - assertTrue(new SchemaKey(null,"a").compareTo(new SchemaKey(null,"a")) == 0); - assertTrue(new SchemaKey(null,"a").compareTo(new SchemaKey(null,"A")) == 0); + assertEquals(0, new SchemaKey(null, "a").compareTo(new SchemaKey(null, "a"))); + assertEquals(0, new SchemaKey(null, "a").compareTo(new SchemaKey(null, "A"))); assertTrue(new SchemaKey(null,"a").compareTo(new SchemaKey(null,"b")) < 0); assertTrue(new SchemaKey(null,"a").compareTo(new SchemaKey(null,"B")) < 0); - assertTrue(new SchemaKey(null,"A").compareTo(new SchemaKey(null,"a")) == 0); - assertTrue(new SchemaKey(null,"A").compareTo(new SchemaKey(null,"A")) == 0); + assertEquals(0, new SchemaKey(null, "A").compareTo(new SchemaKey(null, "a"))); + assertEquals(0, new SchemaKey(null, "A").compareTo(new SchemaKey(null, "A"))); assertTrue(new SchemaKey(null,"A").compareTo(new SchemaKey(null,"b")) < 0); assertTrue(new SchemaKey(null,"A").compareTo(new SchemaKey(null,"B")) < 0); - assertTrue(fromParts("a","b").compareTo(fromParts("a","b")) == 0); + assertEquals(0, fromParts("a", "b").compareTo(fromParts("a", "b"))); assertTrue(fromParts("a","b").compareTo(fromParts("b","a")) < 0); assertTrue(fromParts("b","a").compareTo(fromParts("a","b")) > 0); assertTrue(fromParts("a","b").compareTo(fromParts("a","c")) < 0); diff --git a/api/src/org/labkey/api/query/SchemaTreeWalker.java b/api/src/org/labkey/api/query/SchemaTreeWalker.java index d9716a0f02c..0c18188b9c0 100644 --- a/api/src/org/labkey/api/query/SchemaTreeWalker.java +++ b/api/src/org/labkey/api/query/SchemaTreeWalker.java @@ -77,16 +77,4 @@ protected R visitTablesAndReduce(UserSchema schema, Iterable names, Path } return r; } - - @Override - public R visitTable(TableInfo table, Path path, P param) - { - return defaultAction(table, path, param); - } - - @Override - public R visitTableError(UserSchema schema, String name, Exception e, Path path, P param) - { - return defaultErrorAction(schema, name, e, path, param); - } } diff --git a/api/src/org/labkey/api/query/SimpleQueryUpdateService.java b/api/src/org/labkey/api/query/SimpleQueryUpdateService.java index 5d008f531ee..6c539411730 100644 --- a/api/src/org/labkey/api/query/SimpleQueryUpdateService.java +++ b/api/src/org/labkey/api/query/SimpleQueryUpdateService.java @@ -18,7 +18,6 @@ import org.apache.commons.lang3.StringUtils; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; -import org.labkey.api.audit.TransactionAuditProvider; import org.labkey.api.data.ColumnInfo; import org.labkey.api.data.Container; import org.labkey.api.data.DatabaseTableType; @@ -125,7 +124,7 @@ private boolean shouldPreferPKOverObjectUriAsUpdateKey(@NotNull List getReservedPropertyNames(Domain domain, User user) { diff --git a/api/src/org/labkey/api/query/SimpleUserSchema.java b/api/src/org/labkey/api/query/SimpleUserSchema.java index aad4da2e2ca..41ceaa9e8dd 100644 --- a/api/src/org/labkey/api/query/SimpleUserSchema.java +++ b/api/src/org/labkey/api/query/SimpleUserSchema.java @@ -91,7 +91,7 @@ public SimpleUserSchema(String name, @Nullable String description, @NotNull User if (null != table) _available.add(table.getName()); else - _log.error("Schema '" + dbschema.getName() + "' provided tableName '" + tableName + "', but not actual table."); + _log.error("Schema '{}' provided tableName '{}', but not actual table.", dbschema.getName(), tableName); } } } @@ -243,7 +243,7 @@ protected boolean acceptColumn(ColumnInfo col) { if (getColumn(col.getName()) != null) { - _log.warn("'" + col.getName() + "' column already exists in '" + col.getParentTable() + "' table. Duplicate column won't be displayed."); + _log.warn("'{}' column already exists in '{}' table. Duplicate column won't be displayed.", col.getName(), col.getParentTable()); return false; } return true; @@ -333,7 +333,7 @@ else if (col.getFk() != null) // Only create this TableInfo if we don't already know the pkColName since it might be expensive TableInfo fkTable = col.getFkTableInfo(); if (fkTable != null && fkTable.getPkColumnNames().size() == 1) - pkColName = fkTable.getPkColumnNames().get(0); + pkColName = fkTable.getPkColumnNames().getFirst(); } if (null != pkColName) diff --git a/api/src/org/labkey/api/query/SimpleValidationError.java b/api/src/org/labkey/api/query/SimpleValidationError.java index 6c6d0905cb8..2ff19e10cd5 100644 --- a/api/src/org/labkey/api/query/SimpleValidationError.java +++ b/api/src/org/labkey/api/query/SimpleValidationError.java @@ -94,7 +94,7 @@ public ValidationException.SEVERITY getSeverity() } @Override - public HelpTopic getHelp() + public @Nullable HelpTopic getHelp() { return _help; } diff --git a/api/src/org/labkey/api/query/UserSchemaAction.java b/api/src/org/labkey/api/query/UserSchemaAction.java index 4f267a9c678..a2c36f41dd2 100644 --- a/api/src/org/labkey/api/query/UserSchemaAction.java +++ b/api/src/org/labkey/api/query/UserSchemaAction.java @@ -225,7 +225,7 @@ else if (table.getPkColumnNames().size() > 1) else { Map row; - String pkName = table.getPkColumnNames().get(0); + String pkName = table.getPkColumnNames().getFirst(); for (String pkValue : pkValues) { row = new CaseInsensitiveHashMap<>(); diff --git a/api/src/org/labkey/api/query/ValidationException.java b/api/src/org/labkey/api/query/ValidationException.java index 88f76e1adf2..d2be07810ae 100644 --- a/api/src/org/labkey/api/query/ValidationException.java +++ b/api/src/org/labkey/api/query/ValidationException.java @@ -16,6 +16,7 @@ package org.labkey.api.query; import org.apache.logging.log4j.Level; +import org.jetbrains.annotations.NotNull; import org.labkey.api.action.SpringActionController; import org.labkey.api.data.RuntimeSQLException; import org.springframework.dao.DataAccessException; @@ -304,9 +305,7 @@ private ValidationException addFieldError(PropertyValidationError error) if (field == null) throw new IllegalArgumentException(); - List list = _fieldErrors.get(field); - if (list == null) - _fieldErrors.put(field, list = new ArrayList<>()); + List list = _fieldErrors.computeIfAbsent(field, _ -> new ArrayList<>()); list.add(error); return this; @@ -387,9 +386,7 @@ public List getFieldErrors(final String name) throw new IllegalArgumentException(); // For convenience in the script environment, create an empty list. - List list = _fieldErrors.get(name); - if (list == null) - _fieldErrors.put(name, list = new ArrayList<>()); + List list = _fieldErrors.computeIfAbsent(name, k -> new ArrayList<>()); final List wrapped = list; return new AbstractList<>() @@ -550,7 +547,7 @@ public List getErrors() } @Override - public Iterator iterator() + public @NotNull Iterator iterator() { return getErrors().iterator(); } diff --git a/api/src/org/labkey/api/query/ViewOptions.java b/api/src/org/labkey/api/query/ViewOptions.java index 9df90163f7f..b2ff1b35fc2 100644 --- a/api/src/org/labkey/api/query/ViewOptions.java +++ b/api/src/org/labkey/api/query/ViewOptions.java @@ -18,7 +18,6 @@ import org.labkey.api.security.User; -import java.sql.SQLException; import java.util.List; /** @@ -30,8 +29,8 @@ public interface ViewOptions List getViewFilterItems(); void setViewFilterItems(List items); - void save(User user) throws SQLException; - void delete(User user) throws SQLException; + void save(User user); + void delete(User user); interface ViewFilterItem { diff --git a/api/src/org/labkey/api/query/column/ContainerIdColumnInfoTransformer.java b/api/src/org/labkey/api/query/column/ContainerIdColumnInfoTransformer.java index f1efa01d1c1..d6d108a9a82 100644 --- a/api/src/org/labkey/api/query/column/ContainerIdColumnInfoTransformer.java +++ b/api/src/org/labkey/api/query/column/ContainerIdColumnInfoTransformer.java @@ -22,7 +22,7 @@ public MutableColumnInfo apply(MutableColumnInfo column) { if (column.getJdbcType() != JdbcType.GUID && column.getJdbcType() != JdbcType.VARCHAR) { - LogManager.getLogger(UserIdColumnInfoTransformer.class).warn("Column is not of type GUID: " + column.getName()); + LogManager.getLogger(UserIdColumnInfoTransformer.class).warn("Column is not of type GUID: {}", column.getName()); return column; } diff --git a/api/src/org/labkey/api/query/column/UserIdColumnInfoTransformer.java b/api/src/org/labkey/api/query/column/UserIdColumnInfoTransformer.java index edbf185ed78..3fe08a4dcab 100644 --- a/api/src/org/labkey/api/query/column/UserIdColumnInfoTransformer.java +++ b/api/src/org/labkey/api/query/column/UserIdColumnInfoTransformer.java @@ -20,7 +20,7 @@ public MutableColumnInfo apply(MutableColumnInfo column) { if (column.getJdbcType() != JdbcType.INTEGER) { - LogManager.getLogger(UserIdColumnInfoTransformer.class).error("Column is not of type INT: " + column.getName()); + LogManager.getLogger(UserIdColumnInfoTransformer.class).error("Column is not of type INT: {}", column.getName()); return column; } diff --git a/api/src/org/labkey/api/query/import.jsp b/api/src/org/labkey/api/query/import.jsp index c0713065ee1..3e1e5a0887a 100644 --- a/api/src/org/labkey/api/query/import.jsp +++ b/api/src/org/labkey/api/query/import.jsp @@ -56,7 +56,7 @@ { if (bean.urlExcelTemplates.size() == 1) { - Pair p = bean.urlExcelTemplates.get(0); + Pair p = bean.urlExcelTemplates.getFirst(); %><%= button(p.first).href(p.second).usePost() %>
 
<% } else diff --git a/api/src/org/labkey/api/query/snapshot/AbstractSnapshotProvider.java b/api/src/org/labkey/api/query/snapshot/AbstractSnapshotProvider.java index 61e9efdc79e..9dd77a19f3d 100644 --- a/api/src/org/labkey/api/query/snapshot/AbstractSnapshotProvider.java +++ b/api/src/org/labkey/api/query/snapshot/AbstractSnapshotProvider.java @@ -36,7 +36,6 @@ import org.springframework.validation.BindException; import java.util.HashMap; -import java.util.HashSet; import java.util.List; import java.util.Map; /* diff --git a/api/src/org/labkey/api/reader/AbstractDataLoaderFactory.java b/api/src/org/labkey/api/reader/AbstractDataLoaderFactory.java index 61d14e3dcfa..3148cfd37bd 100644 --- a/api/src/org/labkey/api/reader/AbstractDataLoaderFactory.java +++ b/api/src/org/labkey/api/reader/AbstractDataLoaderFactory.java @@ -72,7 +72,7 @@ public String getMediaType() { List contentType = getFileType().getContentTypes(); if (!contentType.isEmpty()) - return contentType.get(0); + return contentType.getFirst(); return null; } diff --git a/api/src/org/labkey/api/reader/DataLoader.java b/api/src/org/labkey/api/reader/DataLoader.java index 159db3f57d5..e29cc21f672 100644 --- a/api/src/org/labkey/api/reader/DataLoader.java +++ b/api/src/org/labkey/api/reader/DataLoader.java @@ -23,8 +23,8 @@ import org.apache.commons.lang3.StringUtils; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; -import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; +import org.jetbrains.annotations.NotNull; import org.labkey.api.collections.ArrayListMap; import org.labkey.api.collections.CaseInsensitiveHashMap; import org.labkey.api.collections.RowMapFactory; @@ -175,7 +175,7 @@ public final ColumnDescriptor[] getColumns(@NotNull Map renamedC return _columns; } - public Map getColumnInfoMap() + public @NotNull Map getColumnInfoMap() { return _columnInfoMap; } @@ -635,7 +635,7 @@ public Map next() Formatter formatter = new Formatter(sb); for (var entry : next.entrySet()) LoggingDataIterator.appendFormattedNameValue(formatter, entry.getKey(), entry.getValue()); - _log.debug(this.getClass().getName() + ".next():\n" + sb); + _log.debug("{}.next():\n{}", this.getClass().getName(), sb); } return next; @@ -914,7 +914,7 @@ else if (ERROR_VALUE_USE_ORIGINAL.equals(column.errorValues)) } if (null != _file) - _log.error("failed loading file " + _file.getName() + " at line: " + _lineNum + " " + e, e); + _log.error("failed loading file {} at line: {} {}", _file.getName(), _lineNum, e, e); } // Return null to signals there are no more rows diff --git a/api/src/org/labkey/api/reader/ExcelFactory.java b/api/src/org/labkey/api/reader/ExcelFactory.java index 83f1a895978..f52100de77c 100644 --- a/api/src/org/labkey/api/reader/ExcelFactory.java +++ b/api/src/org/labkey/api/reader/ExcelFactory.java @@ -226,7 +226,7 @@ public static WorkbookMetadata getMetadata(Workbook wb) throws IOException, Inva } - public static WorkbookMetadata getMetadata(Workbook wb, List names) throws IOException, InvalidFormatException + public static WorkbookMetadata getMetadata(Workbook wb, List names) throws IOException { if (wb instanceof XSSFWorkbook) return new WorkbookMetadata(null, true, names, ((XSSFWorkbook)wb).isDate1904(), ((XSSFWorkbook)wb).getSharedStringSource()); @@ -546,7 +546,7 @@ else if (cell.getCellType() == CellType.FORMULA && cell.getCachedFormulaResultTy catch (Exception e) { // Issue 41879 -- best effort, don't make a big fuss over bad formula - LOG.warn("Exception parsing Excel formula: " + e.getMessage()); + LOG.warn("Exception parsing Excel formula: {}", e.getMessage()); } } } diff --git a/api/src/org/labkey/api/reader/ExcelLoader.java b/api/src/org/labkey/api/reader/ExcelLoader.java index 658f6e0a972..818db495147 100644 --- a/api/src/org/labkey/api/reader/ExcelLoader.java +++ b/api/src/org/labkey/api/reader/ExcelLoader.java @@ -1008,7 +1008,7 @@ private static void checkData(ExcelLoader loader) assertEquals(18, map.size()); } - Map firstRow = data.get(0); + Map firstRow = data.getFirst(); checkFirstRow(firstRow); } diff --git a/api/src/org/labkey/api/reader/FastaDataLoader.java b/api/src/org/labkey/api/reader/FastaDataLoader.java index 09335f9392a..864b189b310 100644 --- a/api/src/org/labkey/api/reader/FastaDataLoader.java +++ b/api/src/org/labkey/api/reader/FastaDataLoader.java @@ -173,7 +173,7 @@ private void parseHeader(String header, Map rowMap) for (String part : header.split("\\s")) { - String field[] = part.split("="); + String[] field = part.split("="); if (field.length == 2) { @@ -198,7 +198,7 @@ private void parseHeader(String header, Map rowMap) } @Override - public GenericIterator iterator() + public @NotNull GenericIterator iterator() { return new GenericIterator(); } diff --git a/api/src/org/labkey/api/reader/FastaLoader.java b/api/src/org/labkey/api/reader/FastaLoader.java index 0e770d45f4a..335888ca465 100644 --- a/api/src/org/labkey/api/reader/FastaLoader.java +++ b/api/src/org/labkey/api/reader/FastaLoader.java @@ -15,6 +15,7 @@ */ package org.labkey.api.reader; +import org.jetbrains.annotations.NotNull; import org.labkey.vfs.FileLike; import java.io.BufferedReader; @@ -42,7 +43,7 @@ protected FastaLoader(FileLike fastaFile, FastaIteratorElementFactory factory // Force subclasses to implement to provide callers a more appropriate name. @Override - public abstract FastaIterator iterator(); + public abstract @NotNull FastaIterator iterator(); public void setCharacterFilter(CharacterFilter characterFilter) { diff --git a/api/src/org/labkey/api/reader/HTMLDataLoader.java b/api/src/org/labkey/api/reader/HTMLDataLoader.java index 33588aea171..c89190a4586 100644 --- a/api/src/org/labkey/api/reader/HTMLDataLoader.java +++ b/api/src/org/labkey/api/reader/HTMLDataLoader.java @@ -78,7 +78,7 @@ public class HTMLDataLoader extends DataLoader public static final FileType FILE_TYPE = new FileType(Arrays.asList(".html", ".xhtml"), ".html") { @Override - public boolean isHeaderMatch(@NotNull byte[] header) + public boolean isHeaderMatch(byte @NotNull [] header) { String s = new String(header, StringUtilsLabKey.DEFAULT_CHARSET); diff --git a/api/src/org/labkey/api/reader/JSONDataLoader.java b/api/src/org/labkey/api/reader/JSONDataLoader.java index 4eaf174608e..872fce5f5bd 100644 --- a/api/src/org/labkey/api/reader/JSONDataLoader.java +++ b/api/src/org/labkey/api/reader/JSONDataLoader.java @@ -110,7 +110,7 @@ public class JSONDataLoader extends DataLoader * @return True if the header looks like it will be a JSON selectRows response. */ @Override - public boolean isHeaderMatch(@NotNull byte[] header) + public boolean isHeaderMatch(byte @NotNull [] header) { boolean foundSchemaName = false; boolean foundQueryName = false; @@ -430,7 +430,7 @@ else if (fieldName.equals("jdbcType")) } else { - LogManager.getLogger(JSONDataLoader.class).warn("Failed to find jdbc type for " + value); + LogManager.getLogger(JSONDataLoader.class).warn("Failed to find jdbc type for {}", value); } parser.nextToken(); @@ -485,7 +485,7 @@ protected Object[] parseRow() throws IOException // Use previously parsed rows if they exist if (_firstRows != null) { - row = _firstRows.remove(0); + row = _firstRows.removeFirst(); if (_firstRows.isEmpty()) _firstRows = null; } diff --git a/api/src/org/labkey/api/reader/MapLoader.java b/api/src/org/labkey/api/reader/MapLoader.java index 3133307566a..98631a9e678 100644 --- a/api/src/org/labkey/api/reader/MapLoader.java +++ b/api/src/org/labkey/api/reader/MapLoader.java @@ -63,9 +63,9 @@ private void convertToArrays(List> rows) List lineFields = new ArrayList<>(rows.size()); Set colNames; - if (!rows.isEmpty() && rows.get(0) instanceof ArrayListMap) + if (!rows.isEmpty() && rows.getFirst() instanceof ArrayListMap) { - colNames = ((ArrayListMap)rows.get(0)).getFindMap().keySet(); + colNames = ((ArrayListMap)rows.getFirst()).getFindMap().keySet(); } else { @@ -216,7 +216,7 @@ public void testLoad() throws Exception assertEquals("other", cd[4].name); assertEquals(String.class, cd[4].clazz); List> data = loader.load(); - assertEquals("bob", data.get(0).get("name")); + assertEquals("bob", data.getFirst().get("name")); // "1/2/2006" will be parsed based on the current date parsing mode (US vs. non-US), so change the expected value based on the setting DateParsingMode mode = LookAndFeelProperties.getInstance(ContainerManager.getRoot()).getDateParsingMode(); @@ -224,13 +224,13 @@ public void testLoad() throws Exception assertEquals(cal.getTime(), data.get(0).get("date")); assertEquals(1.1, data.get(0).get("number")); - assertEquals(null, data.get(1).get("number")); + assertNull(data.get(1).get("number")); assertEquals(1.2, data.get(2).get("number")); // ensure keys are present for all rows even if no value provided - assertEquals(null, data.get(0).get("other")); + assertNull(data.get(0).get("other")); assertEquals("foo", data.get(1).get("other")); - assertEquals(null, data.get(2).get("other")); + assertNull(data.get(2).get("other")); // 11374: make sure we don't load inactive columns assertEquals(4, data.get(0).size()); diff --git a/api/src/org/labkey/api/reader/StrictBoundedReader.java b/api/src/org/labkey/api/reader/StrictBoundedReader.java index 2510f0c79db..336345acc94 100644 --- a/api/src/org/labkey/api/reader/StrictBoundedReader.java +++ b/api/src/org/labkey/api/reader/StrictBoundedReader.java @@ -1,7 +1,6 @@ package org.labkey.api.reader; import org.jetbrains.annotations.NotNull; -import org.jspecify.annotations.NonNull; import org.junit.Assert; import org.junit.Test; import org.labkey.api.test.TestWhen; @@ -62,7 +61,7 @@ public int read() throws IOException } @Override - public int read(char @NonNull [] cbuf, int off, int len) throws IOException + public int read(char @NotNull [] cbuf, int off, int len) throws IOException { ensureOpen(); if (charsRead >= maxChars) diff --git a/api/src/org/labkey/api/reader/TabFileType.java b/api/src/org/labkey/api/reader/TabFileType.java index 1e277de2798..e18441e6eb7 100644 --- a/api/src/org/labkey/api/reader/TabFileType.java +++ b/api/src/org/labkey/api/reader/TabFileType.java @@ -48,7 +48,7 @@ else if (".csv".equals(defaultSuffix)) // CONSIDER: sniff for the actual separator and quote character in TabLoader instead? @Override - public boolean isHeaderMatch(@NotNull byte[] header) + public boolean isHeaderMatch(byte @NotNull [] header) { String s = new String(header, StringUtilsLabKey.DEFAULT_CHARSET); // TODO: Detect encoding diff --git a/api/src/org/labkey/api/reader/TabLoader.java b/api/src/org/labkey/api/reader/TabLoader.java index 481013a20db..5635c60ead4 100644 --- a/api/src/org/labkey/api/reader/TabLoader.java +++ b/api/src/org/labkey/api/reader/TabLoader.java @@ -821,7 +821,7 @@ private void verifyMalformedData(File csv, boolean requireEnclosedQuotes, String assertEquals(String.class, l.getColumns()[2].clazz); assertEquals(2, maps.size()); - assertEquals("Header1", maps.get(0).get("column0")); + assertEquals("Header1", maps.getFirst().get("column0")); assertEquals("Header2", maps.get(0).get("column1")); assertEquals("Header3", maps.get(0).get("column2")); @@ -874,7 +874,7 @@ public void testWithQuotes() throws IOException assertEquals("number of columns not as expected", 3, l.getColumns().length); assertEquals("number of rows not as expected", 1, maps.size()); - Map firstRow = maps.get(0); + Map firstRow = maps.getFirst(); assertEquals("test1a", firstRow.get("Header1")); assertEquals("test1b", firstRow.get("Header2")); assertEquals(3, firstRow.get("Header3")); @@ -899,7 +899,7 @@ public void testWithInternalQuotes() throws IOException assertEquals("Number of columns not as expected", 3, l.getColumns().length); assertEquals("Number of rows not as expected", 1, maps.size()); - Map firstRow = maps.get(0); + Map firstRow = maps.getFirst(); assertEquals("\"test1/a\"/b", firstRow.get("Header1")); assertEquals("test1b", firstRow.get("Header2")); assertEquals(3, firstRow.get("Header3")); @@ -936,7 +936,7 @@ private void testTextFile(String data, String extension, Consumer con assertEquals(String.class, l.getColumns()[17].clazz); assertEquals(7, maps.size()); - Map firstRow = maps.get(0); + Map firstRow = maps.getFirst(); assertEquals(96, firstRow.get("scan")); assertEquals(false, firstRow.get("accurateMZ")); assertEquals("description", firstRow.get("description")); @@ -1077,7 +1077,7 @@ public void testUnescape() List> rows = loader.load(); assertEquals(2, rows.size()); - Map row = rows.get(0); + Map row = rows.getFirst(); assertEquals("a", row.get("A")); assertEquals("this\\nis\\tmulti-line", row.get("Multi-Line")); assertEquals("b", row.get("B")); @@ -1164,7 +1164,7 @@ public void testParseQuotes() List> rows = loader.load(); assertEquals(6, rows.size()); - Map row = rows.get(0); + Map row = rows.getFirst(); assertEquals("Bob", row.get("Name")); assertEquals("with\ttab\nwith\"quote", row.get("Multi-Line")); assertEquals(10, row.get("Age")); @@ -1232,7 +1232,7 @@ public void testMySql() throws IOException assertEquals(4, rows.size()); - Map row = rows.get(0); + Map row = rows.getFirst(); assertEquals("biotinylated antihuIgG antibody", row.get("name")); assertNull(row.get("description")); diff --git a/api/src/org/labkey/api/reader/jxl/JxlRow.java b/api/src/org/labkey/api/reader/jxl/JxlRow.java index abeb6cce6cd..1d38c4dcedf 100644 --- a/api/src/org/labkey/api/reader/jxl/JxlRow.java +++ b/api/src/org/labkey/api/reader/jxl/JxlRow.java @@ -20,6 +20,7 @@ import org.apache.poi.ss.usermodel.CellType; import org.apache.poi.ss.usermodel.Row; import org.apache.poi.ss.usermodel.Sheet; +import org.jetbrains.annotations.NotNull; import java.util.Iterator; @@ -147,7 +148,7 @@ public Sheet getSheet() } @Override - public Iterator iterator() + public @NotNull Iterator iterator() { return new JxlCellIterator(); } diff --git a/api/src/org/labkey/api/reader/jxl/JxlSheet.java b/api/src/org/labkey/api/reader/jxl/JxlSheet.java index 0dd510eb36a..cf6c3a55c82 100644 --- a/api/src/org/labkey/api/reader/jxl/JxlSheet.java +++ b/api/src/org/labkey/api/reader/jxl/JxlSheet.java @@ -36,6 +36,7 @@ import org.apache.poi.ss.util.CellAddress; import org.apache.poi.ss.util.CellRangeAddress; import org.apache.poi.ss.util.PaneInformation; +import org.jetbrains.annotations.NotNull; import java.util.Collection; import java.util.Iterator; @@ -627,7 +628,7 @@ public AutoFilter setAutoFilter(CellRangeAddress range) } @Override - public Iterator iterator() + public @NotNull Iterator iterator() { return new JxlRowIterator(); } diff --git a/api/src/org/labkey/api/reader/jxl/JxlWorkbook.java b/api/src/org/labkey/api/reader/jxl/JxlWorkbook.java index 4d1390b99c0..2d10a13ef50 100644 --- a/api/src/org/labkey/api/reader/jxl/JxlWorkbook.java +++ b/api/src/org/labkey/api/reader/jxl/JxlWorkbook.java @@ -32,6 +32,7 @@ import org.apache.poi.ss.usermodel.Sheet; import org.apache.poi.ss.usermodel.SheetVisibility; import org.apache.poi.ss.usermodel.Workbook; +import org.jetbrains.annotations.NotNull; import java.io.File; import java.io.IOException; @@ -416,7 +417,7 @@ public SpreadsheetVersion getSpreadsheetVersion() } @Override - public Iterator iterator() + public @NotNull Iterator iterator() { throw new UnsupportedOperationException("method not yet supported"); } diff --git a/api/src/org/labkey/api/reports/ExternalScriptEngine.java b/api/src/org/labkey/api/reports/ExternalScriptEngine.java index d1ec588c890..f31b0ff68d3 100644 --- a/api/src/org/labkey/api/reports/ExternalScriptEngine.java +++ b/api/src/org/labkey/api/reports/ExternalScriptEngine.java @@ -442,7 +442,7 @@ protected FileLike writeScriptFile(String script, ScriptContext context, List names = new ArrayList<>(); String[] originalAmps; - StringBuffer sb = new StringBuffer(); + StringBuilder sb = new StringBuilder(); String delim = ""; String trailing = ""; @@ -376,7 +376,7 @@ public String[] decode(String category) case '&' : // this is the section delimiter names.add(sb.toString()); - sb = new StringBuffer(); + sb = new StringBuilder(); break; default : sb.append(c); @@ -484,9 +484,9 @@ public void categoryUpdated(User user, ViewCategory category) // test serialization encoding and decoding String encoded = mgr.encode(cat); - String parts[] = mgr.decode(encoded); + String[] parts = mgr.decode(encoded); - assertTrue(parts.length == 1); + assertEquals(1, parts.length); assertEquals(parts[0], cat.getLabel()); // create sub categories @@ -508,7 +508,7 @@ public void categoryUpdated(User user, ViewCategory category) encoded = mgr.encode(subcat); parts = mgr.decode(encoded); - assertTrue(parts.length == 2); + assertEquals(2, parts.length); assertEquals(parts[0], cat.getLabel()); assertEquals(parts[1], subLabel); } @@ -554,7 +554,7 @@ public void categoryUpdated(User user, ViewCategory category) for (ViewCategory subCategory : cat.getSubcategories()) { assertTrue(subCategoryNames.contains(subCategory.getLabel())); - assertTrue(subCategory.getParentCategory().getRowId() == cat.getRowId()); + assertEquals(subCategory.getParentCategory().getRowId(), cat.getRowId()); } } @@ -577,8 +577,8 @@ public void testEnsureCategories() ViewCategory top = mgr.ensureViewCategory(c, user, "top"); assertNotNull(top); - assertTrue(top.getParentCategory() == null); - assertTrue(top.getLabel().equals("top")); + assertNull(top.getParentCategory()); + assertEquals("top", top.getLabel()); ViewCategory subTop = mgr.ensureViewCategory(c, user, "top", "sub"); // issue : 17123 @@ -586,14 +586,14 @@ public void testEnsureCategories() mgr.ensureViewCategory(c, user, "top"); assertNotNull(subTop); - assertTrue(subTop.getParentCategory().getLabel().equals("top")); - assertTrue(subTop.getLabel().equals("sub")); + assertEquals("top", subTop.getParentCategory().getLabel()); + assertEquals("sub", subTop.getLabel()); ViewCategory subBottom = mgr.ensureViewCategory(c, user, "bottom", "sub"); assertNotNull(subBottom); - assertTrue(subBottom.getParentCategory().getLabel().equals("bottom")); - assertTrue(subBottom.getLabel().equals("sub")); + assertEquals("bottom", subBottom.getParentCategory().getLabel()); + assertEquals("sub", subBottom.getLabel()); mgr.deleteCategory(c, user, top); mgr.deleteCategory(c, user, subBottom.getParentCategory()); diff --git a/api/src/org/labkey/api/reports/report/DbReportIdentifier.java b/api/src/org/labkey/api/reports/report/DbReportIdentifier.java index cd3f1e009f2..5409401cac4 100644 --- a/api/src/org/labkey/api/reports/report/DbReportIdentifier.java +++ b/api/src/org/labkey/api/reports/report/DbReportIdentifier.java @@ -65,7 +65,7 @@ public DbReportIdentifier(String id, @Nullable User user, @Nullable Container co } catch (NumberFormatException e) { - LOG.debug("Failed to parse reportId as a number: '" + id + "'. Attempting to resolve by name"); + LOG.debug("Failed to parse reportId as a number: '{}'. Attempting to resolve by name", id); // See if we can resolve the report by name instead of id // If no user or container was supplied, see if there's a ViewContext we can use. This is important @@ -86,11 +86,11 @@ public DbReportIdentifier(String id, @Nullable User user, @Nullable Container co // Filter all available reports by name to see if we get a single match List matchingReports = ReportService.get().getReports(user, container).stream().filter((r) -> suffix.equalsIgnoreCase(r.getDescriptor().getReportName())).toList(); - LOG.debug("Found " + matchingReports.size() + " matching DB-based reports for id '" + id + "' for user " + user.getEmail() + " in " + container.getPath()); + LOG.debug("Found {} matching DB-based reports for id '{}' for user {} in {}", matchingReports.size(), id, user.getEmail(), container.getPath()); if (matchingReports.size() == 1) { - resolvedId = matchingReports.get(0).getDescriptor().getReportId().getRowId(); + resolvedId = matchingReports.getFirst().getDescriptor().getReportId().getRowId(); } else { @@ -99,7 +99,7 @@ public DbReportIdentifier(String id, @Nullable User user, @Nullable Container co } else { - LOG.debug("No user or container available, unable to try resolving by report name for '" + id + "'"); + LOG.debug("No user or container available, unable to try resolving by report name for '{}'", id); throw e; } } diff --git a/api/src/org/labkey/api/reports/report/JavaScriptReport.java b/api/src/org/labkey/api/reports/report/JavaScriptReport.java index b0768ca1958..829b84ece59 100644 --- a/api/src/org/labkey/api/reports/report/JavaScriptReport.java +++ b/api/src/org/labkey/api/reports/report/JavaScriptReport.java @@ -75,18 +75,12 @@ public String getDefaultScript() } } - @Override - public boolean hasClientDependencies() - { - return false; - } - @Override public @NotNull String getDesignerHelpHtml() { try { - return new JspTemplate("/org/labkey/api/reports/report/view/javaScriptReportHelp.jsp").render(); + return new JspTemplate<>("/org/labkey/api/reports/report/view/javaScriptReportHelp.jsp").render(); } catch (Exception e) { diff --git a/api/src/org/labkey/api/reports/report/ModuleQueryReportResource.java b/api/src/org/labkey/api/reports/report/ModuleQueryReportResource.java index d8dcf4fdca4..c2f5673bf82 100644 --- a/api/src/org/labkey/api/reports/report/ModuleQueryReportResource.java +++ b/api/src/org/labkey/api/reports/report/ModuleQueryReportResource.java @@ -71,7 +71,7 @@ public ReportDescriptorType loadMetaData() } catch(IOException | XmlException e) { - LogManager.getLogger(ModuleQueryReportResource.class).warn("Unable to load query report metadata from file " + _sourceFile, e); + LogManager.getLogger(ModuleQueryReportResource.class).warn("Unable to load query report metadata from file {}", _sourceFile, e); } return d; diff --git a/api/src/org/labkey/api/reports/report/ModuleReportDependenciesResource.java b/api/src/org/labkey/api/reports/report/ModuleReportDependenciesResource.java index 88fa961a308..a2b3b577d2a 100644 --- a/api/src/org/labkey/api/reports/report/ModuleReportDependenciesResource.java +++ b/api/src/org/labkey/api/reports/report/ModuleReportDependenciesResource.java @@ -67,8 +67,7 @@ public ReportDescriptorType loadMetaData() } catch(XmlException e) { - LogManager.getLogger(ModuleReportDependenciesResource.class).warn("Unable to load report metadata from file " - + _metaDataFile, e); + LogManager.getLogger(ModuleReportDependenciesResource.class).warn("Unable to load report metadata from file {}", _metaDataFile, e); } } diff --git a/api/src/org/labkey/api/reports/report/ScriptEngineReport.java b/api/src/org/labkey/api/reports/report/ScriptEngineReport.java index 3bdeea35386..33970de1ff7 100644 --- a/api/src/org/labkey/api/reports/report/ScriptEngineReport.java +++ b/api/src/org/labkey/api/reports/report/ScriptEngineReport.java @@ -60,7 +60,7 @@ import org.labkey.api.reports.report.r.view.TsvOutput; import org.labkey.api.thumbnail.Thumbnail; import org.labkey.api.util.FileUtil; -import org.labkey.api.util.UnexpectedException; +import org.labkey.api.util.UnexpectedException; import org.labkey.api.view.HttpView; import org.labkey.api.view.VBox; import org.labkey.api.view.ViewContext; @@ -70,7 +70,7 @@ import javax.script.ScriptEngine; import javax.script.ScriptException; -import java.io.IOException; +import java.io.IOException; import java.io.PrintWriter; import java.sql.ResultSetMetaData; import java.sql.SQLException; @@ -210,41 +210,41 @@ public FileLike createInputDataFile(@NotNull ViewContext context) throws SQLExce * Note: This method used to stash results in members (_tempFolder and _tempFolderPipeline), but that no longer works * now that we cache reports between threads (e.g., Thread.currentThread().getId() is part of the path). */ - public FileLike getReportDirFileLike(@NotNull String executingContainerId) - { - boolean isPipeline = BooleanUtils.toBoolean(getDescriptor().getProperty(ScriptReportDescriptor.Prop.runInBackground)); - return getReportDirFileLike(executingContainerId, isPipeline); - } - - protected FileLike getBackgroundOutputDirFileLike(@NotNull String executingContainerId) - { - FileLike tempRoot = getTempRootFileLike(getDescriptor()); - String reportId = FileUtil.makeLegalName(String.valueOf(getDescriptor().getReportId())).replaceAll(" ", "_"); - - // Build FileLike paths from VFS path segments instead of File.separator so Windows - // backslashes do not get folded into a single org.labkey.api.util.Path segment. - return tempRoot.resolveChild(executingContainerId).resolveChild("Report_" + reportId); - } - - protected FileLike getReportDirFileLike(@NotNull String executingContainerId, boolean isPipeline) - { - FileLike tempFolder; - - try - { - tempFolder = getBackgroundOutputDirFileLike(executingContainerId); - - if (isPipeline) - { - String identifier = RReportJob.getJobIdentifier(); - if (identifier != null) - tempFolder = tempFolder.resolveChild(identifier); - } - else - tempFolder = tempFolder.resolveChild(String.valueOf(Thread.currentThread().getId())); - - FileUtil.mkdirs(tempFolder); - return tempFolder; + public FileLike getReportDirFileLike(@NotNull String executingContainerId) + { + boolean isPipeline = BooleanUtils.toBoolean(getDescriptor().getProperty(ScriptReportDescriptor.Prop.runInBackground)); + return getReportDirFileLike(executingContainerId, isPipeline); + } + + protected FileLike getBackgroundOutputDirFileLike(@NotNull String executingContainerId) + { + FileLike tempRoot = getTempRootFileLike(getDescriptor()); + String reportId = FileUtil.makeLegalName(String.valueOf(getDescriptor().getReportId())).replaceAll(" ", "_"); + + // Build FileLike paths from VFS path segments instead of File.separator so Windows + // backslashes do not get folded into a single org.labkey.api.util.Path segment. + return tempRoot.resolveChild(executingContainerId).resolveChild("Report_" + reportId); + } + + protected FileLike getReportDirFileLike(@NotNull String executingContainerId, boolean isPipeline) + { + FileLike tempFolder; + + try + { + tempFolder = getBackgroundOutputDirFileLike(executingContainerId); + + if (isPipeline) + { + String identifier = RReportJob.getJobIdentifier(); + if (identifier != null) + tempFolder = tempFolder.resolveChild(identifier); + } + else + tempFolder = tempFolder.resolveChild(String.valueOf(Thread.currentThread().getId())); + + FileUtil.mkdirs(tempFolder); + return tempFolder; } catch (IOException e) { @@ -278,7 +278,7 @@ public static void scheduledFileCleanup(Logger log) { if (file.isDirectory()) { - log.info("Deleting temporary report folder: " + file.getPath()); + log.info("Deleting temporary report folder: {}", file.getPath()); deleteReportDir(file, cutoff); } else @@ -290,7 +290,7 @@ public static void scheduledFileCleanup(Logger log) } catch (IOException e) { - log.info("Unable to delete temporary report file: " + file.getPath(), e); + log.info("Unable to delete temporary report file: {}", file.getPath(), e); } } } @@ -428,11 +428,11 @@ public boolean handleParameter(ViewContext context, Report report, ParamReplacem if (null != output) { scriptOutputs.add(output); - LOG.debug("ExecuteScript: Added output parameter for: " + param.getName()); + LOG.debug("ExecuteScript: Added output parameter for: {}", param.getName()); } else { - LOG.debug("ExecuteScript: Could not add output parameter for: " + param.getName()); + LOG.debug("ExecuteScript: Could not add output parameter for: {}", param.getName()); } } } @@ -629,7 +629,7 @@ protected String getDefaultExtension(FolderExportContext context) { ScriptEngine engine = getScriptEngine(context.getContainer()); if (engine != null) - return engine.getFactory().getExtensions().get(0); + return engine.getFactory().getExtensions().getFirst(); return super.getDefaultExtension(context); } diff --git a/api/src/org/labkey/api/reports/report/python/IpynbReport.java b/api/src/org/labkey/api/reports/report/python/IpynbReport.java index 5a9258f05f0..38719ce7d82 100644 --- a/api/src/org/labkey/api/reports/report/python/IpynbReport.java +++ b/api/src/org/labkey/api/reports/report/python/IpynbReport.java @@ -125,8 +125,8 @@ public static boolean isEnabled() List defs = mgr.getEngineDefinitions(ExternalScriptEngineDefinition.Type.Jupyter); // we currently only support a single site scoped engine - if (defs.size() == 1 && Arrays.asList(defs.get(0).getExtensions()).contains(EXTENSION)) - return defs.get(0).isEnabled(); + if (defs.size() == 1 && Arrays.asList(defs.getFirst().getExtensions()).contains(EXTENSION)) + return defs.getFirst().isEnabled(); } return false; } @@ -199,9 +199,9 @@ public HttpView renderReport(ViewContext context) throws Exception ExecuteStrategy ex = new WebServiceExecuteStrategy(); int exitCode = ex.execute(context, apikey, workingDirectory, scriptFile); - LOG.trace("EXIT: " + exitCode); + LOG.trace("EXIT: {}", exitCode); FileLike outputFile = ex.getOutputDocument(); - LOG.trace("OUTPUT: " + outputFile); + LOG.trace("OUTPUT: {}", outputFile); logFiles(workingDirectory, "AFTER"); try @@ -238,7 +238,7 @@ public HttpView renderReport(ViewContext context) throws Exception if (error.isFile() && error.getSize() > 0) vbox.addView(new ConsoleOutput(error).getView(context)); - LOG.trace("VIEWS: " + vbox.getViews().size()); + LOG.trace("VIEWS: {}", vbox.getViews().size()); return vbox; } catch (Exception x) @@ -252,9 +252,8 @@ private static void logFiles(FileLike parentDir, String label) { File dir = parentDir.toNioPathForRead().toFile(); Collection files = FileUtils.listFiles(dir, null, true); - LOG.trace(label + ": " + dir.getPath() + "\n\t" + - StringUtils.join(files.stream().map(f -> - f.getPath().replace(dir.getPath(), "") + " : " + f.length()).toArray(), "\n\t")); + LOG.trace("{}: {}\n\t{}", label, dir.getPath(), StringUtils.join(files.stream().map(f -> + f.getPath().replace(dir.getPath(), "") + " : " + f.length()).toArray(), "\n\t")); } diff --git a/api/src/org/labkey/api/reports/report/r/ModuleRReportResource.java b/api/src/org/labkey/api/reports/report/r/ModuleRReportResource.java index 25e5fd6d55f..4d699b6dee7 100644 --- a/api/src/org/labkey/api/reports/report/r/ModuleRReportResource.java +++ b/api/src/org/labkey/api/reports/report/r/ModuleRReportResource.java @@ -96,8 +96,7 @@ public ReportDescriptorType loadMetaData() } catch (XmlException e) { - LogManager.getLogger(ModuleRReportResource.class).warn("Unable to load R report metadata from file " - + _sourceFile, e); + LogManager.getLogger(ModuleRReportResource.class).warn("Unable to load R report metadata from file {}", _sourceFile, e); } } diff --git a/api/src/org/labkey/api/reports/report/r/ParamReplacementSvc.java b/api/src/org/labkey/api/reports/report/r/ParamReplacementSvc.java index 7986304942f..11863cdf35c 100644 --- a/api/src/org/labkey/api/reports/report/r/ParamReplacementSvc.java +++ b/api/src/org/labkey/api/reports/report/r/ParamReplacementSvc.java @@ -538,7 +538,7 @@ public String processParamReplacement(String script, FileLike parentDirectory, S // NOTE: dollar signs in the path will cause "java.lang.IllegalArgumentException: Illegal group reference" from Matcher.appendReplacement resultFileName = resultFileName.replaceAll("\\$", "\\\\\\$"); - _log.debug("Found output parameter '" + param.getName() + "'. Mapping local file '" + resultFile + "' to '" + resultFileName + "'"); + _log.debug("Found output parameter '{}'. Mapping local file '{}' to '{}'", param.getName(), resultFile, resultFileName); } String replacementStr = pattern.getReplacementStr(resultFileName, m.group(0), param.getName()); outputReplacements.add(param); diff --git a/api/src/org/labkey/api/reports/report/r/RDockerScriptEngine.java b/api/src/org/labkey/api/reports/report/r/RDockerScriptEngine.java index 926d88801db..27ad755d742 100644 --- a/api/src/org/labkey/api/reports/report/r/RDockerScriptEngine.java +++ b/api/src/org/labkey/api/reports/report/r/RDockerScriptEngine.java @@ -16,8 +16,6 @@ package org.labkey.api.reports.report.r; import org.apache.commons.io.FilenameUtils; -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.labkey.api.docker.DockerService; diff --git a/api/src/org/labkey/api/reports/report/r/RScriptEngine.java b/api/src/org/labkey/api/reports/report/r/RScriptEngine.java index 3684522b19b..a538cf7e0bd 100644 --- a/api/src/org/labkey/api/reports/report/r/RScriptEngine.java +++ b/api/src/org/labkey/api/reports/report/r/RScriptEngine.java @@ -109,10 +109,10 @@ protected String getKnitrExtension(ScriptContext context, List extension { // consider: make a format class and then just override the specified html, md, functions if (getKnitrFormat(context) == RReportDescriptor.KnitrFormat.Html) - return extensions.get(0) + "html"; + return extensions.getFirst() + "html"; if (getKnitrFormat(context) == RReportDescriptor.KnitrFormat.Markdown) - return extensions.get(0) + "md"; + return extensions.getFirst() + "md"; return null; } diff --git a/api/src/org/labkey/api/reports/report/r/RserveScriptEngine.java b/api/src/org/labkey/api/reports/report/r/RserveScriptEngine.java index 9a28711071d..e82ab91bebd 100644 --- a/api/src/org/labkey/api/reports/report/r/RserveScriptEngine.java +++ b/api/src/org/labkey/api/reports/report/r/RserveScriptEngine.java @@ -311,7 +311,7 @@ public Object eval(String script, ScriptContext context) throws ScriptException // if we have a session in the bindings then the connection holder better be there and marked as in use // assert (rh!=null) && (rh.isInUse()); - LOG.info("Reusing RServe connection in use: " + rh.isInUse()); + LOG.info("Reusing RServe connection in use: {}", rh.isInUse()); } FileLike scriptFile = prepareScriptFile(script, context, extensions); @@ -324,7 +324,7 @@ public Object eval(String script, ScriptContext context) throws ScriptException copyWorkingDirectoryToRemote(rconn); String remoteInputFile = getInputFilename(scriptFile); - LOG.debug("Executing remote script '" + remoteInputFile + "'..."); + LOG.debug("Executing remote script '{}'...", remoteInputFile); String cmdFormat = RReport.DEFAULT_RSERVE_CMD; // override our rserve invocation command if the exeCommand property is supplied in the engine definition @@ -332,9 +332,9 @@ public Object eval(String script, ScriptContext context) throws ScriptException cmdFormat = _def.getExeCommand(); String rserveCmd = String.format(cmdFormat, remoteInputFile); - LOG.debug("Evaluating command: " + rserveCmd); + LOG.debug("Evaluating command: {}", rserveCmd); String output = eval(rconn, rserveCmd); - LOG.debug("Executed remote script '" + scriptFile + "' successfully"); + LOG.debug("Executed remote script '{}' successfully", scriptFile); // no logging here, because this is a no-op by default copyWorkingDirectoryFromRemote(rconn); @@ -505,12 +505,12 @@ static public URI makeLocalToRemotePath(ExternalScriptEngineDefinition def, File if (pathMap != null && !pathMap.getURIPathMap().isEmpty()) { URI remoteURI = pathMap.localToRemote(localURI); - LOG.debug("Mapped path '" + localURI + "' ==> '" + remoteURI + "'"); + LOG.debug("Mapped path '{}' ==> '{}'", localURI, remoteURI); return remoteURI; } else { - LOG.warn("No path mapping configured; using localURI '" + localURI + "' on remote RServe"); + LOG.warn("No path mapping configured; using localURI '{}' on remote RServe", localURI); } return localURI; } @@ -540,7 +540,7 @@ protected void initEnv(RConnection rconn, ScriptContext context) throws IOExcept String workingDir = getRWorkingDir(context); if (workingDir != null) { - LOG.debug("Setting RServe working directory to '" + workingDir + "'"); + LOG.debug("Setting RServe working directory to '{}'", workingDir); eval(rconn, "setwd(" + toR(workingDir) + ")\n"); } @@ -563,12 +563,12 @@ private RConnection getConnection(RConnectionHolder rh, ScriptContext context) // // get a new connection (will HANG on a windows server) // - LOG.debug("Creating new RServe connection to " + _def.getMachine() + ":" + _def.getPort()); + LOG.debug("Creating new RServe connection to {}:{}", _def.getMachine(), _def.getPort()); rconn = new RConnection(_def.getMachine(), _def.getPort()); if (rconn.needLogin()) { - LOG.debug("Logging in to RServe as '" + _def.getUser() + "'"); + LOG.debug("Logging in to RServe as '{}'", _def.getUser()); String password = _def.getPassword(); if (password == null) { diff --git a/api/src/org/labkey/api/reports/report/r/view/DownloadParamReplacement.java b/api/src/org/labkey/api/reports/report/r/view/DownloadParamReplacement.java index 6cf1e810b70..280483dc7a1 100644 --- a/api/src/org/labkey/api/reports/report/r/view/DownloadParamReplacement.java +++ b/api/src/org/labkey/api/reports/report/r/view/DownloadParamReplacement.java @@ -22,7 +22,6 @@ import org.labkey.api.util.Path; import org.labkey.vfs.FileLike; -import java.io.File; import java.io.IOException; /** diff --git a/api/src/org/labkey/api/reports/report/r/view/ImageOutput.java b/api/src/org/labkey/api/reports/report/r/view/ImageOutput.java index 8304493b076..893c57eb204 100644 --- a/api/src/org/labkey/api/reports/report/r/view/ImageOutput.java +++ b/api/src/org/labkey/api/reports/report/r/view/ImageOutput.java @@ -141,7 +141,7 @@ protected String renderInternalAsString(FileLike file) throws IOException } else { - LOG.debug("No file exists for parameter: " + getName()); + LOG.debug("No file exists for parameter: {}", getName()); } return imgUrl; diff --git a/api/src/org/labkey/api/reports/report/r/view/KnitrOutput.java b/api/src/org/labkey/api/reports/report/r/view/KnitrOutput.java index a1b5c20f06c..0ed81c1c17a 100644 --- a/api/src/org/labkey/api/reports/report/r/view/KnitrOutput.java +++ b/api/src/org/labkey/api/reports/report/r/view/KnitrOutput.java @@ -26,9 +26,7 @@ import org.labkey.api.view.HttpView; import org.labkey.api.view.ViewContext; import org.labkey.vfs.FileLike; -import org.labkey.vfs.FileSystemLike; -import java.io.File; import java.io.PrintWriter; import java.net.URI; diff --git a/api/src/org/labkey/api/reports/report/r/view/ROutputView.java b/api/src/org/labkey/api/reports/report/r/view/ROutputView.java index 6ba467a370d..11c96681b17 100644 --- a/api/src/org/labkey/api/reports/report/r/view/ROutputView.java +++ b/api/src/org/labkey/api/reports/report/r/view/ROutputView.java @@ -153,11 +153,11 @@ protected FileLike moveToTemp(FileLike file) throws IOException FileLike newFile = root.resolveChild(FileUtil.makeFileNameWithTimestamp(FileUtil.getBaseName(file.getName()), FileUtil.getExtension(file))); newFile.delete(); - LOG.debug("Moving '" + file + "' to '" + newFile + "'"); + LOG.debug("Moving '{}' to '{}'", file, newFile); if (file.renameTo(newFile)) return newFile; - LOG.debug("Failed to move " + file + "' to '" + newFile + "'"); + LOG.debug("Failed to move {}' to '{}'", file, newFile); return null; } diff --git a/api/src/org/labkey/api/resource/AbstractResourceCollection.java b/api/src/org/labkey/api/resource/AbstractResourceCollection.java index 779d69576a5..061260cff74 100644 --- a/api/src/org/labkey/api/resource/AbstractResourceCollection.java +++ b/api/src/org/labkey/api/resource/AbstractResourceCollection.java @@ -52,12 +52,6 @@ public boolean isCollection() return exists(); } - @Override - public boolean isFile() - { - return false; - } - @Override public InputStream getInputStream() { diff --git a/api/src/org/labkey/api/resource/Resource.java b/api/src/org/labkey/api/resource/Resource.java index f821955ac86..39bd8809841 100644 --- a/api/src/org/labkey/api/resource/Resource.java +++ b/api/src/org/labkey/api/resource/Resource.java @@ -90,7 +90,6 @@ default Resource find(Path path) * Return false to force contentDisposition=attachment. * This does not mean the browser knows how to inline the document. see MimeType.canInline(). */ - @Nullable default boolean allowInline() { return true; diff --git a/api/src/org/labkey/api/security/AuthenticatedRequest.java b/api/src/org/labkey/api/security/AuthenticatedRequest.java index 86a31ca6a49..690e1f5b0ab 100644 --- a/api/src/org/labkey/api/security/AuthenticatedRequest.java +++ b/api/src/org/labkey/api/security/AuthenticatedRequest.java @@ -216,7 +216,7 @@ private HttpSession makeRealSession() } if (s.isNew()) { - _log.debug("Created HttpSession: " + s.getId() + " " + _user.getEmail()); + _log.debug("Created HttpSession: {} {}", s.getId(), _user.getEmail()); } return s; } @@ -334,7 +334,7 @@ public int getMaxInactiveInterval() public void setAttribute(String s, Object o) { if (_log.isDebugEnabled()) - _log.debug("Session.setAttribute(" + s + ", " + o + ")"); + _log.debug("Session.setAttribute({}, {})", s, o); if (null==_real) _attributes.put(s, o); else diff --git a/api/src/org/labkey/api/security/AuthenticationConfiguration.java b/api/src/org/labkey/api/security/AuthenticationConfiguration.java index 2761e19885d..5129da0ec2a 100644 --- a/api/src/org/labkey/api/security/AuthenticationConfiguration.java +++ b/api/src/org/labkey/api/security/AuthenticationConfiguration.java @@ -168,7 +168,7 @@ default boolean handleStartupLogo(Map map, String key, AuthLogoT } catch (Exception e) { - LOG.error("Failed to save authentication logo " + value, e); + LOG.error("Failed to save authentication logo {}", value, e); } } } diff --git a/api/src/org/labkey/api/security/AuthenticationManager.java b/api/src/org/labkey/api/security/AuthenticationManager.java index 4d498671541..7e844856185 100644 --- a/api/src/org/labkey/api/security/AuthenticationManager.java +++ b/api/src/org/labkey/api/security/AuthenticationManager.java @@ -22,8 +22,8 @@ import org.apache.commons.lang3.Strings; import org.apache.commons.lang3.mutable.MutableInt; import org.apache.logging.log4j.Logger; -import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; +import org.jetbrains.annotations.NotNull; import org.junit.Assert; import org.junit.Test; import org.labkey.api.action.ApiResponseWriter.Format; @@ -539,7 +539,7 @@ public static void registerProvider(AuthenticationProvider authProvider) public static void registerProvider(AuthenticationProvider authProvider, Priority priority) { if (Priority.High == priority) - _allProviders.add(0, authProvider); + _allProviders.addFirst(authProvider); else _allProviders.add(authProvider); @@ -931,7 +931,7 @@ public URLHelper getRedirectURL() { BindException errors = new BindException(new Object(), "dummy"); getStatus().addUserErrorMessage(errors, this, null, null, location); - return errors.hasErrors() ? errors.getAllErrors().get(0).getDefaultMessage() : null; + return errors.hasErrors() ? errors.getAllErrors().getFirst().getDefaultMessage() : null; } } @@ -1060,13 +1060,13 @@ public static void addAuditEvent(@NotNull User user, HttpServletRequest request, if (null != user) { addAuditEvent(user, request, user.getEmail() + message); - _log.warn(user.getEmail() + message); + _log.warn("{}{}", user.getEmail(), message); } else if (null != emailAddress) { // Funny audit case -- user doesn't exist, so there's no user to associate with the event. Use guest. addAuditEvent(User.guest, request, emailAddress + message); - _log.warn(emailAddress + message); + _log.warn("{}{}", emailAddress, message); } else { @@ -1765,7 +1765,7 @@ public void throttleLogin() throws Exception MockHttpServletRequest req = new MockHttpServletRequest("GET", "/home/project-begin.view") { @Override - public String getRemoteAddr() + public @NotNull String getRemoteAddr() { return remoteAddr[0]; } diff --git a/api/src/org/labkey/api/security/AuthenticationProvider.java b/api/src/org/labkey/api/security/AuthenticationProvider.java index 6d827947235..f3d612f36d4 100644 --- a/api/src/org/labkey/api/security/AuthenticationProvider.java +++ b/api/src/org/labkey/api/security/AuthenticationProvider.java @@ -462,7 +462,7 @@ enum FailureReason notApplicable(ReportType.never, "not applicable", null), badApiKey(ReportType.onFailure, "invalid API key", AuthenticationStatus.BadApiKey) { @Override - public @Nullable String getEmailAddress(ValidEmail email) throws InvalidEmailException + public @Nullable String getEmailAddress(ValidEmail email) { // This override prevents logging a strange "apikey@domain.com"-type failure message. Invalid API key // means email is unknown, so always return null. @@ -491,7 +491,7 @@ public String getMessage() return _message; } - public @Nullable String getEmailAddress(ValidEmail email) throws InvalidEmailException + public @Nullable String getEmailAddress(ValidEmail email) { return email.getEmailAddress(); } diff --git a/api/src/org/labkey/api/security/CSRF.java b/api/src/org/labkey/api/security/CSRF.java index e0c4088a436..3d043d4a6be 100644 --- a/api/src/org/labkey/api/security/CSRF.java +++ b/api/src/org/labkey/api/security/CSRF.java @@ -16,7 +16,6 @@ package org.labkey.api.security; -import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.Strings; import org.labkey.api.util.CSRFUtil; import org.labkey.api.view.ViewContext; diff --git a/api/src/org/labkey/api/security/EntropyPasswordValidator.java b/api/src/org/labkey/api/security/EntropyPasswordValidator.java index e76a49483e9..37d328d6cc5 100644 --- a/api/src/org/labkey/api/security/EntropyPasswordValidator.java +++ b/api/src/org/labkey/api/security/EntropyPasswordValidator.java @@ -172,10 +172,10 @@ private static List removeDuplicateSubstringsWithinEachSegment(List removeDuplicateSubstringsBetweenSegments(List segments) { - char[] firstSegment = segments.get(0); + char[] firstSegment = segments.getFirst(); List filtered = remove(segments.subList(1, segments.size()), firstSegment); List ret = filtered.size() > 1 ? removeDuplicateSubstringsBetweenSegments(filtered) : filtered; - ret.add(0, firstSegment); + ret.addFirst(firstSegment); return ret; } diff --git a/api/src/org/labkey/api/security/GroupManager.java b/api/src/org/labkey/api/security/GroupManager.java index a9d49fb0567..c89def1303c 100644 --- a/api/src/org/labkey/api/security/GroupManager.java +++ b/api/src/org/labkey/api/security/GroupManager.java @@ -288,7 +288,7 @@ public static void importGroupMembers(@Nullable Group group, GroupType xmlGroupT } else { - log.warn("Invalid group name for group member: " + xmlGroupMember.getName()); + log.warn("Invalid group name for group member: {}", xmlGroupMember.getName()); } } } @@ -314,12 +314,12 @@ public static void importGroupMembers(@Nullable Group group, GroupType xmlGroupT } else { - log.warn("User does not exist for group member: " + xmlMember.getName()); + log.warn("User does not exist for group member: {}", xmlMember.getName()); } } catch(ValidEmail.InvalidEmailException e) { - log.warn("Invalid email address for group member: " + xmlMember.getName()); + log.warn("Invalid email address for group member: {}", xmlMember.getName()); } } } diff --git a/api/src/org/labkey/api/security/NestedGroupsTest.java b/api/src/org/labkey/api/security/NestedGroupsTest.java index bd73527496d..4a6977b2d88 100644 --- a/api/src/org/labkey/api/security/NestedGroupsTest.java +++ b/api/src/org/labkey/api/security/NestedGroupsTest.java @@ -104,7 +104,7 @@ public void test() throws Throwable // Grab the first group (if there is one) in the home project Container home = ContainerManager.getHomeContainer(); List homeGroups = SecurityManager.getGroups(home, false); - @Nullable Group homeGroup = !homeGroups.isEmpty() ? homeGroups.get(0) : null; + @Nullable Group homeGroup = !homeGroups.isEmpty() ? homeGroups.getFirst() : null; final Group all = create(ALL); Group divA = create(DIV_A); diff --git a/api/src/org/labkey/api/security/SecurityLogger.java b/api/src/org/labkey/api/security/SecurityLogger.java index 9fe3445cded..160beed27b3 100644 --- a/api/src/org/labkey/api/security/SecurityLogger.java +++ b/api/src/org/labkey/api/security/SecurityLogger.java @@ -59,7 +59,7 @@ public static void log(String msg, @Nullable UserPrincipal p, @Nullable Securabl public static void pushSecurityContext(String description, User user) { List a = threadsecuritycontexts.get(); - a.add(new ThreadSecurityContext(user,description,a.get(a.size()-1))); + a.add(new ThreadSecurityContext(user,description,a.getLast())); if (null != description) indent("<" + description + (null == user ? "" : " " + user.getName()) + ">"); } @@ -71,10 +71,10 @@ public static void popSecurityContext() if (a.size()==1) return; outdent(); - String desc = a.get(a.size()-1).description; + String desc = a.getLast().description; if (null != desc) - instance.debug(""); - a.remove(a.size()-1); + instance.debug("", desc); + a.removeLast(); } @@ -83,7 +83,7 @@ public static boolean indent(@Nullable String msg) if (null != msg) instance.debug(msg); List a = threadsecuritycontexts.get(); - a.get(a.size()-1).indent++; + a.getLast().indent++; return true; } @@ -91,8 +91,8 @@ public static boolean indent(@Nullable String msg) public static boolean outdent() { List a = threadsecuritycontexts.get(); - if (a.get(a.size()-1).indent > 0) - a.get(a.size()-1).indent--; + if (a.getLast().indent > 0) + a.getLast().indent--; return true; } @@ -135,7 +135,7 @@ protected ArrayList initialValue() private static Object indentMsg(Object msg) { List a = threadsecuritycontexts.get(); - int indent = a.get(a.size()-1).indent; + int indent = a.getLast().indent; if (0 >= indent) return msg; return StringUtils.repeat(' ', indent * 2) + String.valueOf(msg); diff --git a/api/src/org/labkey/api/security/SecurityManager.java b/api/src/org/labkey/api/security/SecurityManager.java index 16a02ab4921..238ca522663 100644 --- a/api/src/org/labkey/api/security/SecurityManager.java +++ b/api/src/org/labkey/api/security/SecurityManager.java @@ -237,12 +237,12 @@ public static void registerAllowedConnectionSource(String key, String serviceURL if (StringUtils.trimToNull(serviceURL) == null) { ContentSecurityPolicyFilter.unregisterAllowedSources(key, Directive.Connection); - LOG.trace(String.format("Unregistered [%1$s] as an allowed connection source", key)); + LOG.trace("Unregistered [{}] as an allowed connection source", key); return; } ContentSecurityPolicyFilter.registerAllowedSources(key, Directive.Connection, serviceURL); - LOG.trace(String.format("Registered [%1$s] as an allowed connection source", serviceURL)); + LOG.trace("Registered [{}] as an allowed connection source", serviceURL); } public enum PermissionTypes @@ -527,17 +527,17 @@ public static User getSessionUser(HandshakeRequest request) public static Pair attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws UnsupportedEncodingException { - AUTH_LOG.debug("Starting authentication attempt via session, Basic auth, or API key header for request \"" + request.getRequestURI() + "\""); + AUTH_LOG.debug("Starting authentication attempt via session, Basic auth, or API key header for request \"{}\"", request.getRequestURI()); // Current best practice is to pass API keys via an "apikey" header, but they can be passed via basic auth // (username "apikey"), supported for backwards compatibility and clients that don't support custom headers. @Nullable Pair basicCredentials = getBasicCredentials(request); - AUTH_LOG.debug(" " + (null == basicCredentials ? "Basic auth credentials not provided" : "Basic auth credentials provided: " + basicCredentials.getKey() + " and " + basicCredentials.getValue().length() + " character password")); + AUTH_LOG.debug(" {}", null == basicCredentials ? "Basic auth credentials not provided" : "Basic auth credentials provided: " + basicCredentials.getKey() + " and " + basicCredentials.getValue().length() + " character password"); if (null == basicCredentials) { basicCredentials = getApiKey(request); - AUTH_LOG.debug(" " + (null == basicCredentials ? "API key not provided" : "API key provided: " + basicCredentials.getKey() + " and " + basicCredentials.getValue().length() + " character key")); + AUTH_LOG.debug(" {}", null == basicCredentials ? "API key not provided" : "API key provided: " + basicCredentials.getKey() + " and " + basicCredentials.getValue().length() + " character key"); } // Handle session API key early, if present and valid @@ -579,7 +579,7 @@ public static Pair attemptAuthentication(HttpServletRe if (null != sessionUser) { - AUTH_LOG.debug(" Session user present: " + sessionUser); + AUTH_LOG.debug(" Session user present: {}", sessionUser); if (!sessionUser.isImpersonated() && "true".equalsIgnoreCase(request.getHeader("LabKey-Disallow-Global-Roles"))) { @@ -627,7 +627,7 @@ public static Pair attemptAuthentication(HttpServletRe u = authenticateBasic(request, basicCredentials); if (null != u) { - AUTH_LOG.debug(" Basic authentication succeeded: " + u); + AUTH_LOG.debug(" Basic authentication succeeded: {}", u); request.setAttribute(AUTHENTICATION_METHOD, "Basic"); // accept Guest as valid credentials from authenticateBasic() return new Pair<>(u, request); @@ -648,7 +648,7 @@ public static Pair attemptAuthentication(HttpServletRe } finally { - AUTH_LOG.debug("Finishing authentication attempt via session, Basic auth, or API key header for request \"" + request.getRequestURI() + "\". User: " + u); + AUTH_LOG.debug("Finishing authentication attempt via session, Basic auth, or API key header for request \"{}\". User: {}", request.getRequestURI(), u); } } @@ -1074,7 +1074,7 @@ public static NewUserStatus addUser(ValidEmail email, @Nullable User currentUser { if (!"23000".equals(x.getSQLState())) { - LOG.debug("createUser: Something failed user: " + email, x); + LOG.debug("createUser: Something failed user: {}", email, x); throw x; } } @@ -1487,7 +1487,7 @@ static void addMemberWithoutValidation(Group group, UserPrincipal principal) catch (DataIntegrityViolationException e) { // Assume this is a race condition and ignore, see #14795 - LOG.warn("Member could not be added: " + e.getMessage()); + LOG.warn("Member could not be added: {}", e.getMessage()); } fireAddPrincipalToGroup(group, principal); @@ -2899,7 +2899,7 @@ public void handle(Collection entries) if (null == role) { // Issue 36611: The provisioner startup properties break deployment of older products - LOG.error("Invalid role for group specified in startup properties GroupRoles: " + roleName); + LOG.error("Invalid role for group specified in startup properties GroupRoles: {}", roleName); continue; } policy.addRoleAssignment(group, role); @@ -2952,7 +2952,7 @@ public void handle(Collection entries) if (null == role) { // Issue 36611: The provisioner startup properties break deployment of older products - LOG.warn("Invalid role for user specified in startup properties UserRoles: " + roleName); + LOG.warn("Invalid role for user specified in startup properties UserRoles: {}", roleName); continue; } policy.addRoleAssignment(user, role); diff --git a/api/src/org/labkey/api/security/SecurityPolicy.java b/api/src/org/labkey/api/security/SecurityPolicy.java index f86a631ab47..ccf8f09bf44 100644 --- a/api/src/org/labkey/api/security/SecurityPolicy.java +++ b/api/src/org/labkey/api/security/SecurityPolicy.java @@ -191,7 +191,7 @@ public boolean isEmpty() } // Throttle that limits warning logging to once per hour per permission class - private static final Throttle> NOT_REGISTERED_PERMISSION_THROTTLE = new Throttle<>("unregistered permissions", 100, CacheManager.HOUR, permission -> LOG.warn(permission + " is not registered!")); + private static final Throttle> NOT_REGISTERED_PERMISSION_THROTTLE = new Throttle<>("unregistered permissions", 100, CacheManager.HOUR, permission -> LOG.warn("{} is not registered!", permission)); static void testPermissionIsRegistered(Class permission) { diff --git a/api/src/org/labkey/api/security/SecurityPolicyManager.java b/api/src/org/labkey/api/security/SecurityPolicyManager.java index 93a1baf4486..a00ce3baf16 100644 --- a/api/src/org/labkey/api/security/SecurityPolicyManager.java +++ b/api/src/org/labkey/api/security/SecurityPolicyManager.java @@ -238,7 +238,7 @@ private static void savePolicyToDBAndValidate(@NotNull MutableSecurityPolicy pol UserPrincipal principal = SecurityManager.getPrincipal(assignment.getUserId()); if (principal == null) { - logger.info("Principal " + assignment.getUserId() + " no longer in database. Removing from policy."); + logger.info("Principal {} no longer in database. Removing from policy.", assignment.getUserId()); continue; } Table.insert(null, table, assignment); @@ -550,7 +550,7 @@ public static void importRoleAssignments(FolderImportContext ctx, MutableSecurit Role role = RoleManager.getRole(assignmentXml.getRole().getName()); if (role == null) { - ctx.getLogger().warn("Invalid role name ignored: " + assignmentXml.getRole()); + ctx.getLogger().warn("Invalid role name ignored: {}", assignmentXml.getRole()); continue; } try @@ -562,7 +562,7 @@ public static void importRoleAssignments(FolderImportContext ctx, MutableSecurit UserPrincipal principal = GroupManager.getGroup(ctx.getContainer(), groupRef.getName(), groupRef.getType()); if (principal == null) { - ctx.getLogger().warn("Non-existent group in role assignment for role " + assignmentXml.getRole().getName() + " will be ignored: " + groupRef.getName()); + ctx.getLogger().warn("Non-existent group in role assignment for role {} will be ignored: {}", assignmentXml.getRole().getName(), groupRef.getName()); } else { @@ -581,7 +581,7 @@ public static void importRoleAssignments(FolderImportContext ctx, MutableSecurit if (principal == null) { - ctx.getLogger().warn("Non-existent user in role assignment for role " + assignmentXml.getRole() + " will be ignored: " + userRef.getName()); + ctx.getLogger().warn("Non-existent user in role assignment for role {} will be ignored: {}", assignmentXml.getRole(), userRef.getName()); } else { @@ -590,7 +590,7 @@ public static void importRoleAssignments(FolderImportContext ctx, MutableSecurit } catch (ValidEmail.InvalidEmailException e) { - ctx.getLogger().error("Invalid email in role assignment for role " + assignmentXml.getRole()); + ctx.getLogger().error("Invalid email in role assignment for role {}", assignmentXml.getRole()); } } } diff --git a/api/src/org/labkey/api/security/ValidEmail.java b/api/src/org/labkey/api/security/ValidEmail.java index f3090f7e2e2..563bf87831a 100644 --- a/api/src/org/labkey/api/security/ValidEmail.java +++ b/api/src/org/labkey/api/security/ValidEmail.java @@ -124,7 +124,7 @@ private String normalize(String rawEmail) ColumnInfo uidColumn = usersTable.getColumn("uid"); if (uidColumn != null) { - LOG.debug("Found field in users table to use to match against login form: " + uidColumn.getName()); + LOG.debug("Found field in users table to use to match against login form: {}", uidColumn.getName()); // Do a case-insensitive search for the username Collection> matchingUsers = new TableSelector(usersTable, new SimpleFilter(new SimpleFilter.SQLClause(new SQLFragment("LOWER(uid) = LOWER(?)", rawEmail), uidColumn.getFieldKey())), null).getMapCollection(); if (matchingUsers.size() == 1) @@ -132,17 +132,17 @@ private String normalize(String rawEmail) String fullEmail = (String) matchingUsers.iterator().next().get("Email"); if (fullEmail != null) { - LOG.debug("Found match for '" + rawEmail + "', resolved to '" + fullEmail + "'"); + LOG.debug("Found match for '{}', resolved to '{}'", rawEmail, fullEmail); return fullEmail; } } else { - LOG.debug("Found " + matchingUsers.size() + " matches for '" + rawEmail + "', unable to resolve unique email address"); + LOG.debug("Found {} matches for '{}', unable to resolve unique email address", matchingUsers.size(), rawEmail); } } - LOG.debug("Resolving user name '" + rawEmail + "' using default domain '" + getDefaultDomain() + "'"); + LOG.debug("Resolving user name '{}' using default domain '{}'", rawEmail, getDefaultDomain()); String domain = getDefaultDomain(); if (!domain.isEmpty()) diff --git a/api/src/org/labkey/api/security/impersonation/RoleImpersonationContextFactory.java b/api/src/org/labkey/api/security/impersonation/RoleImpersonationContextFactory.java index 4dc07b5c023..73d5e514543 100644 --- a/api/src/org/labkey/api/security/impersonation/RoleImpersonationContextFactory.java +++ b/api/src/org/labkey/api/security/impersonation/RoleImpersonationContextFactory.java @@ -28,8 +28,6 @@ import org.labkey.api.security.PrincipalArray; import org.labkey.api.security.RoleSet; import org.labkey.api.security.SecurableResource; -import org.labkey.api.security.SecurityPolicy; -import org.labkey.api.security.SecurityPolicyManager; import org.labkey.api.security.User; import org.labkey.api.security.UserManager; import org.labkey.api.security.permissions.ImpersonatePermission; diff --git a/api/src/org/labkey/api/security/roles/FolderAdminRole.java b/api/src/org/labkey/api/security/roles/FolderAdminRole.java index 37e43396fc8..1b7e2798a3b 100644 --- a/api/src/org/labkey/api/security/roles/FolderAdminRole.java +++ b/api/src/org/labkey/api/security/roles/FolderAdminRole.java @@ -16,8 +16,6 @@ package org.labkey.api.security.roles; import org.labkey.api.admin.FolderExportPermission; -import org.labkey.api.data.Container; -import org.labkey.api.security.SecurableResource; import org.labkey.api.security.permissions.AdminPermission; import org.labkey.api.security.permissions.DesignDataClassPermission; import org.labkey.api.security.permissions.DesignSampleTypePermission; @@ -47,12 +45,6 @@ public FolderAdminRole() excludeUsers(); } - @Override - public boolean isApplicable(SecurableResource resource) - { - return resource instanceof Container && !((Container)resource).isRoot(); - } - @Override public void permissionRegistered(Class perm) { diff --git a/api/src/org/labkey/api/security/roles/RoleManager.java b/api/src/org/labkey/api/security/roles/RoleManager.java index 6743580f146..5387b8ae15d 100644 --- a/api/src/org/labkey/api/security/roles/RoleManager.java +++ b/api/src/org/labkey/api/security/roles/RoleManager.java @@ -23,7 +23,6 @@ import org.labkey.api.cache.CacheManager; import org.labkey.api.cache.Throttle; import org.labkey.api.data.ContainerManager; -import org.labkey.api.security.SecurityPolicy; import org.labkey.api.security.SecurityPolicyManager; import org.labkey.api.security.permissions.AdminPermission; import org.labkey.api.security.permissions.CanAccessLockedProjectsPermission; diff --git a/api/src/org/labkey/api/services/ServiceRegistry.java b/api/src/org/labkey/api/services/ServiceRegistry.java index 7fd27d32cfe..1e731d98cf9 100644 --- a/api/src/org/labkey/api/services/ServiceRegistry.java +++ b/api/src/org/labkey/api/services/ServiceRegistry.java @@ -15,8 +15,8 @@ */ package org.labkey.api.services; -import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; +import org.jetbrains.annotations.NotNull; import org.labkey.api.module.ModuleLoader; import org.springframework.beans.BeansException; import org.springframework.beans.factory.config.ConfigurableListableBeanFactory; @@ -181,7 +181,7 @@ ApplicationContext createWebApplicationContext() AbstractRefreshableWebApplicationContext ac = new AbstractRefreshableWebApplicationContext() { @Override - protected void loadBeanDefinitions(DefaultListableBeanFactory config) throws BeansException + protected void loadBeanDefinitions(@NotNull DefaultListableBeanFactory config) throws BeansException { for (_ServiceDef sd : _servicesByClass.values()) { diff --git a/api/src/org/labkey/api/settings/AppPropsImpl.java b/api/src/org/labkey/api/settings/AppPropsImpl.java index 8c63928c777..c438d1c2e85 100644 --- a/api/src/org/labkey/api/settings/AppPropsImpl.java +++ b/api/src/org/labkey/api/settings/AppPropsImpl.java @@ -522,7 +522,7 @@ public String getWebappConfigurationFilename() if (!admins.isEmpty()) { - String defaultValue = admins.get(0).getEmail(); + String defaultValue = admins.getFirst().getEmail(); String result = lookupStringValue(administratorContactEmail, defaultValue); // Check if the configured email is still an admin, otherwise return default value diff --git a/api/src/org/labkey/api/settings/LookAndFeelFolderPropertiesTest.java b/api/src/org/labkey/api/settings/LookAndFeelFolderPropertiesTest.java index 8e87f1ce10a..fb58272d351 100644 --- a/api/src/org/labkey/api/settings/LookAndFeelFolderPropertiesTest.java +++ b/api/src/org/labkey/api/settings/LookAndFeelFolderPropertiesTest.java @@ -7,7 +7,6 @@ import org.labkey.api.data.Container; import org.labkey.api.data.ContainerManager; import org.labkey.api.security.User; -import org.labkey.api.security.ValidEmail; import org.labkey.api.util.GUID; import org.labkey.api.util.TestContext; @@ -19,7 +18,7 @@ public class LookAndFeelFolderPropertiesTest extends Assert private User _testUser; @Before - public void setUp() throws ValidEmail.InvalidEmailException, org.labkey.api.security.SecurityManager.UserManagementException + public void setUp() { _testUser = TestContext.get().getUser(); _project = ContainerManager.createContainer(ContainerManager.getRoot(), GUID.makeGUID(), _testUser); @@ -31,7 +30,7 @@ public void setUp() throws ValidEmail.InvalidEmailException, org.labkey.api.secu } @After - public void cleanup() throws ValidEmail.InvalidEmailException, org.labkey.api.security.SecurityManager.UserManagementException + public void cleanup() { ContainerManager.deleteAll(_project, _testUser); } diff --git a/api/src/org/labkey/api/settings/LookAndFeelProperties.java b/api/src/org/labkey/api/settings/LookAndFeelProperties.java index be20a026cb6..0568005ef79 100644 --- a/api/src/org/labkey/api/settings/LookAndFeelProperties.java +++ b/api/src/org/labkey/api/settings/LookAndFeelProperties.java @@ -323,8 +323,7 @@ public String getSystemEmailAddress() //initial login will be used as the default value. During setup user will be prompted to change. String emailAddress = lookupStringValue(systemEmailAddress, ""); if (emailAddress.isEmpty()) - LOG.error(String.format("System Email Address became unset somehow. Visit '%s/admin-projectSettings.view' to fix it", - _settingsContainer.getTitle().isEmpty() ? "" : _settingsContainer.getPath())); + LOG.error("System Email Address became unset somehow. Visit '{}/admin-projectSettings.view' to fix it", _settingsContainer.getTitle().isEmpty() ? "" : _settingsContainer.getPath()); return emailAddress; } diff --git a/api/src/org/labkey/api/settings/RandomSiteSettingsPropertyHandler.java b/api/src/org/labkey/api/settings/RandomSiteSettingsPropertyHandler.java index f7dace93e4a..21f112138f6 100644 --- a/api/src/org/labkey/api/settings/RandomSiteSettingsPropertyHandler.java +++ b/api/src/org/labkey/api/settings/RandomSiteSettingsPropertyHandler.java @@ -21,7 +21,7 @@ public void handle(Map properties { WriteableAppProps writeable = AppProps.getWriteableInstance(); properties.forEach((rsp, cp) -> { - LOG.info("Setting additional site-level startup property '" + rsp.name() + "' to '" + cp.getValue() + "'"); + LOG.info("Setting additional site-level startup property '{}' to '{}'", rsp.name(), cp.getValue()); rsp.setValue(writeable, cp.getValue()); }); writeable.save(null); diff --git a/api/src/org/labkey/api/study/Dataset.java b/api/src/org/labkey/api/study/Dataset.java index c95a8847377..5c1499cbf18 100644 --- a/api/src/org/labkey/api/study/Dataset.java +++ b/api/src/org/labkey/api/study/Dataset.java @@ -43,7 +43,6 @@ import org.labkey.api.view.ActionURL; import org.labkey.api.view.UnauthorizedException; -import java.sql.SQLException; import java.util.Collection; import java.util.Date; import java.util.List; @@ -315,7 +314,7 @@ public String getRecallFromStudyAuditMessage(String label, int recordCount) Dataset createMutable(); // See Issue 52211 - void save(User user) throws SQLException; + void save(User user); boolean isQueryDataset(); diff --git a/api/src/org/labkey/api/study/SpecimenService.java b/api/src/org/labkey/api/study/SpecimenService.java index c52a55f0ded..97aed2a40d8 100644 --- a/api/src/org/labkey/api/study/SpecimenService.java +++ b/api/src/org/labkey/api/study/SpecimenService.java @@ -33,7 +33,6 @@ import org.labkey.api.view.ActionURL; import java.io.IOException; -import java.sql.SQLException; import java.util.Collection; import java.util.Date; import java.util.Map; @@ -54,11 +53,11 @@ static SpecimenService get() } /** Does a search for matching GlobalUniqueIds */ - ParticipantVisit getSampleInfo(Container studyContainer, User user, String globalUniqueId) throws SQLException; + ParticipantVisit getSampleInfo(Container studyContainer, User user, String globalUniqueId); - Set> getSampleInfo(Container studyContainer, User user, boolean truncateTime) throws SQLException; + Set> getSampleInfo(Container studyContainer, User user, boolean truncateTime); - Set> getSampleInfo(Container studyContainer, User user) throws SQLException; + Set> getSampleInfo(Container studyContainer, User user); Lsid getSpecimenMaterialLsid(@NotNull Container studyContainer, @NotNull String id); @@ -71,7 +70,7 @@ static SpecimenService get() @Nullable SpecimenTransform getSpecimenTransform(String name); - PipelineJob createSpecimenReloadJob(Container container, User user, SpecimenTransform transform, @Nullable ActionURL url) throws SQLException, IOException, ValidationException; + PipelineJob createSpecimenReloadJob(Container container, User user, SpecimenTransform transform, @Nullable ActionURL url) throws IOException, ValidationException; void registerSpecimenChangeListener(SpecimenChangeListener listener); diff --git a/api/src/org/labkey/api/study/SpecimenTransform.java b/api/src/org/labkey/api/study/SpecimenTransform.java index 9573eaa4c90..18fe8c50345 100644 --- a/api/src/org/labkey/api/study/SpecimenTransform.java +++ b/api/src/org/labkey/api/study/SpecimenTransform.java @@ -19,7 +19,6 @@ import org.labkey.api.data.Container; import org.labkey.api.pipeline.PipelineJob; import org.labkey.api.pipeline.PipelineJobException; -import org.labkey.api.query.ValidationException; import org.labkey.api.security.User; import org.labkey.api.util.FileType; import org.labkey.api.view.ActionURL; @@ -56,7 +55,7 @@ public interface SpecimenTransform /** * An optional post transform step. */ - void postTransform(@Nullable PipelineJob job, FileLike input, FileLike outputArchive) throws PipelineJobException; + void postTransform(@Nullable PipelineJob job, FileLike input, FileLike outputArchive); @Nullable ActionURL getManageAction(Container c, User user); @@ -64,7 +63,7 @@ public interface SpecimenTransform /** * Returns and saved configuration information */ - ExternalImportConfig getExternalImportConfig(Container c, User user) throws ValidationException; + ExternalImportConfig getExternalImportConfig(Container c, User user); /** * An optional capability to import from an external (API) source, data that can be transformed into diff --git a/api/src/org/labkey/api/study/Study.java b/api/src/org/labkey/api/study/Study.java index 39e27ccf72e..8239aa5ada6 100644 --- a/api/src/org/labkey/api/study/Study.java +++ b/api/src/org/labkey/api/study/Study.java @@ -24,7 +24,6 @@ import java.io.IOException; import java.math.BigDecimal; -import java.sql.SQLException; import java.util.Collection; import java.util.Date; import java.util.List; @@ -99,9 +98,9 @@ public interface Study extends StudyEntity String getAssayPlan(); - void attachProtocolDocument(List files , User user) throws SQLException, IOException; + void attachProtocolDocument(List files , User user) throws IOException; - void removeProtocolDocument(String name, User user) throws SQLException, IOException; + void removeProtocolDocument(String name, User user) throws IOException; List getProtocolDocuments (); diff --git a/api/src/org/labkey/api/study/actions/ParticipantVisitResolverChooser.java b/api/src/org/labkey/api/study/actions/ParticipantVisitResolverChooser.java index d0b733ea6b6..b11176d4803 100644 --- a/api/src/org/labkey/api/study/actions/ParticipantVisitResolverChooser.java +++ b/api/src/org/labkey/api/study/actions/ParticipantVisitResolverChooser.java @@ -90,7 +90,7 @@ public void renderInputHtml(RenderContext ctx, HtmlWriter out, Object value) } if (selected == null) { - selected = _resolvers.get(0); + selected = _resolvers.getFirst(); } ParticipantVisitResolverType finalSelected = selected; diff --git a/api/src/org/labkey/api/study/actions/TransformResultsAction.java b/api/src/org/labkey/api/study/actions/TransformResultsAction.java index 72ecff2a916..0a9f21c7654 100644 --- a/api/src/org/labkey/api/study/actions/TransformResultsAction.java +++ b/api/src/org/labkey/api/study/actions/TransformResultsAction.java @@ -24,7 +24,6 @@ import org.labkey.api.util.PageFlowUtil; import org.labkey.api.util.URIUtil; import org.labkey.vfs.FileLike; -import org.labkey.vfs.FileSystemLike; import org.springframework.validation.BindException; import org.springframework.web.servlet.ModelAndView; diff --git a/api/src/org/labkey/api/study/assay/SpecimenForeignKey.java b/api/src/org/labkey/api/study/assay/SpecimenForeignKey.java index 2575118d9de..64ee0823876 100644 --- a/api/src/org/labkey/api/study/assay/SpecimenForeignKey.java +++ b/api/src/org/labkey/api/study/assay/SpecimenForeignKey.java @@ -443,7 +443,7 @@ else if (_containerList != null && _containerList.size() == 1) { // We've determined that there is only one target study container (see .getTargetStudyContainers()) sql.append(" AND " + vialSubqueryAlias + ".Container = ?"); - sql.add(_containerList.get(0).getId()); + sql.add(_containerList.getFirst().getId()); } else { diff --git a/api/src/org/labkey/api/study/assay/StudyParticipantVisitResolver.java b/api/src/org/labkey/api/study/assay/StudyParticipantVisitResolver.java index 538ef25c61b..2a2cb67a07a 100644 --- a/api/src/org/labkey/api/study/assay/StudyParticipantVisitResolver.java +++ b/api/src/org/labkey/api/study/assay/StudyParticipantVisitResolver.java @@ -18,12 +18,10 @@ import org.jetbrains.annotations.NotNull; import org.labkey.api.data.Container; -import org.labkey.api.data.RuntimeSQLException; import org.labkey.api.security.User; import org.labkey.api.study.ParticipantVisit; import org.labkey.api.study.SpecimenService; -import java.sql.SQLException; import java.util.Date; /** @@ -66,16 +64,9 @@ protected ParticipantVisit resolveParticipantVisit(String specimenID, String par if (targetStudyContainer != null && SpecimenService.get() != null) { - try + if (specimenID != null) { - if (specimenID != null) - { - return mergeParticipantVisitInfo(originalInfo, SpecimenService.get().getSampleInfo(targetStudyContainer, getUser(), specimenID)); - } - } - catch (SQLException e) - { - throw new RuntimeSQLException(e); + return mergeParticipantVisitInfo(originalInfo, SpecimenService.get().getSampleInfo(targetStudyContainer, getUser(), specimenID)); } } diff --git a/api/src/org/labkey/api/study/assay/ThawListListResolver.java b/api/src/org/labkey/api/study/assay/ThawListListResolver.java index 7450146397c..67be8140795 100644 --- a/api/src/org/labkey/api/study/assay/ThawListListResolver.java +++ b/api/src/org/labkey/api/study/assay/ThawListListResolver.java @@ -17,7 +17,6 @@ package org.labkey.api.study.assay; import org.apache.commons.beanutils.ConversionException; -import org.apache.commons.beanutils.ConvertUtils; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.labkey.api.assay.AbstractAssayProvider; @@ -89,7 +88,7 @@ protected ParticipantVisit resolveParticipantVisit(String specimenID, String par FieldKey pkFieldKey; if (pkNames.size() == 1) - pkFieldKey = FieldKey.fromParts(pkNames.get(0)); + pkFieldKey = FieldKey.fromParts(pkNames.getFirst()); else pkFieldKey = FieldKey.fromParts(AbstractAssayProvider.SPECIMENID_PROPERTY_NAME); diff --git a/api/src/org/labkey/api/study/query/PublishResultsQueryView.java b/api/src/org/labkey/api/study/query/PublishResultsQueryView.java index 322ee37ac22..bc23f84d6fe 100644 --- a/api/src/org/labkey/api/study/query/PublishResultsQueryView.java +++ b/api/src/org/labkey/api/study/query/PublishResultsQueryView.java @@ -302,9 +302,9 @@ public static Object getColumnValue(ColumnInfo col, RenderContext ctx) // support for lineage and multivalue columns List values = ((IMultiValuedDisplayColumn)dc).getDisplayValues(ctx); if (values.size() == 1) - return values.get(0); + return values.getFirst(); else - LOG.warn("Unable to use the value returned from column : " + col.getName() + " because this multi-value column returned more than a single value."); + LOG.warn("Unable to use the value returned from column : {} because this multi-value column returned more than a single value.", col.getName()); } return col.getValue(ctx); } diff --git a/api/src/org/labkey/api/study/security/SecurityEscalator.java b/api/src/org/labkey/api/study/security/SecurityEscalator.java index e2242df516d..ee1113bfe44 100644 --- a/api/src/org/labkey/api/study/security/SecurityEscalator.java +++ b/api/src/org/labkey/api/study/security/SecurityEscalator.java @@ -94,7 +94,7 @@ public SecurityEscalator(User user, Container container, String comment) { // Get our caller List stackTraceElements = Arrays.asList(Thread.currentThread().getStackTrace()); - String thisFileName = stackTraceElements.get(0).getFileName(); + String thisFileName = stackTraceElements.getFirst().getFileName(); String serviceName = null; List relevantStackTraceElements = new ArrayList<>(); diff --git a/api/src/org/labkey/api/util/CheckedInputStream.java b/api/src/org/labkey/api/util/CheckedInputStream.java index 9c37b0edb58..88bbce097e9 100644 --- a/api/src/org/labkey/api/util/CheckedInputStream.java +++ b/api/src/org/labkey/api/util/CheckedInputStream.java @@ -51,7 +51,7 @@ public void run() { if (!_closed) { - LOG.error("InputStream was not closed. Creation stacktrace:" + ExceptionUtil.renderStackTrace(_creationStackTrace)); + LOG.error("InputStream was not closed. Creation stacktrace:{}", ExceptionUtil.renderStackTrace(_creationStackTrace)); close(); } } diff --git a/api/src/org/labkey/api/util/ContextListener.java b/api/src/org/labkey/api/util/ContextListener.java index 323628ae6de..db291806fa3 100644 --- a/api/src/org/labkey/api/util/ContextListener.java +++ b/api/src/org/labkey/api/util/ContextListener.java @@ -131,7 +131,7 @@ public static void callShutdownListeners() { try { - log.info("Calling " + listener.getName() + " shutdownPre()"); + log.info("Calling {} shutdownPre()", listener.getName()); listener.shutdownPre(); } catch (Throwable t) @@ -144,7 +144,7 @@ public static void callShutdownListeners() { try { - log.info("Calling " + listener.getName() + " shutdownStarted()"); + log.info("Calling {} shutdownStarted()", listener.getName()); listener.shutdownStarted(); } catch (Throwable t) diff --git a/api/src/org/labkey/api/util/CountLimiter.java b/api/src/org/labkey/api/util/CountLimiter.java index 7ec8408477d..828d9df856d 100644 --- a/api/src/org/labkey/api/util/CountLimiter.java +++ b/api/src/org/labkey/api/util/CountLimiter.java @@ -109,12 +109,12 @@ private synchronized void _updateCounts(long count) { while (!_history.isEmpty()) { - RateAccumulator last = _history.get(_history.size()-1); + RateAccumulator last = _history.getLast(); if (last.getStart() + accumulateInterval > now - historyInterval) break; - _history.remove(_history.size()-1); + _history.removeLast(); } - _history.add(0, _short); + _history.addFirst(_short); _short = new SimpleRateAccumulator(now); _long = aggregateRate(now); } diff --git a/api/src/org/labkey/api/util/DOM.java b/api/src/org/labkey/api/util/DOM.java index 676e2a9a737..81dc07221a3 100644 --- a/api/src/org/labkey/api/util/DOM.java +++ b/api/src/org/labkey/api/util/DOM.java @@ -918,7 +918,7 @@ public static Renderable ERRORS(List z) { ExceptionUtil.logExceptionToMothership(context.getRequest(), nsme); Logger log = LogManager.getLogger(ErrorsTag.class); - log.error("Failed to find a message: " + error, nsme); + log.error("Failed to find a message: {}", error, nsme); return createHtmlFragment("Unknown error: " + error, BR()); } }) diff --git a/api/src/org/labkey/api/util/DOMUtil.java b/api/src/org/labkey/api/util/DOMUtil.java index 16f53a98918..598e68e124a 100644 --- a/api/src/org/labkey/api/util/DOMUtil.java +++ b/api/src/org/labkey/api/util/DOMUtil.java @@ -143,7 +143,7 @@ public static List getChildNodesWithName(Node node, String name) public static Node getFirstChildNodeWithName(Node node, String name) { List nodes = getChildNodesWithName(node, name); - return !nodes.isEmpty() ? nodes.get(0) : null; + return !nodes.isEmpty() ? nodes.getFirst() : null; } /** @@ -154,6 +154,6 @@ public static Node getFirstChildNodeWithName(Node node, String name) public static Node getFirstChildElement(Node node) { List nodes = getChildNodes(node, Node.ELEMENT_NODE); - return !nodes.isEmpty() ? nodes.get(0) : null; + return !nodes.isEmpty() ? nodes.getFirst() : null; } } \ No newline at end of file diff --git a/api/src/org/labkey/api/util/DateUtil.java b/api/src/org/labkey/api/util/DateUtil.java index 1669e2bccca..a589241a980 100644 --- a/api/src/org/labkey/api/util/DateUtil.java +++ b/api/src/org/labkey/api/util/DateUtil.java @@ -2101,7 +2101,7 @@ public void testDuration() try { parseDuration("1m2d3h"); - assertFalse("unsupported conversion", true); + fail("unsupported conversion"); } catch (ConversionException x) { diff --git a/api/src/org/labkey/api/util/ExceptionUtil.java b/api/src/org/labkey/api/util/ExceptionUtil.java index 0a28c89becf..0434f794d78 100644 --- a/api/src/org/labkey/api/util/ExceptionUtil.java +++ b/api/src/org/labkey/api/util/ExceptionUtil.java @@ -16,9 +16,12 @@ package org.labkey.api.util; -import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Level; import org.apache.logging.log4j.Logger; -import org.apache.logging.log4j.core.LoggerContext; +import org.apache.logging.log4j.Marker; +import org.apache.logging.log4j.message.Message; +import org.apache.logging.log4j.simple.SimpleLogger; +import org.apache.logging.log4j.util.PropertiesUtil; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.junit.Assert; @@ -185,8 +188,8 @@ public static HtmlString renderException(Throwable e) StringWriter sw = new StringWriter(); e.printStackTrace(new PrintWriter(sw)); String s = PageFlowUtil.filter(sw.toString()); - s = s.replaceAll(" ", " "); - s = s.replaceAll("\t", "       "); + s = s.replace(" ", " "); + s = s.replace("\t", "       "); return HtmlString.unsafe("
\n" + s + "
\n"); } @@ -999,7 +1002,7 @@ else if (ex instanceof ConfigurationException) //don't log unauthorized (basic-auth challenge), forbiddens, or simple not found (404s) if (null != unhandledException && responseStatus != HttpServletResponse.SC_BAD_REQUEST) { - log.error("Unhandled exception: " + message, unhandledException); + log.error("Unhandled exception: {}", message, unhandledException); } ApiResponseWriter.Format responseFormat = ApiResponseWriter.getResponseFormat(request, null); @@ -1263,7 +1266,7 @@ public static boolean decorateException(Throwable t, Enum key, String value, HashMap, String> m = _exceptionDecorations.computeIfAbsent(t, _ -> new HashMap<>()); if (overwrite || !m.containsKey(key)) { - LOG.debug("add decoration to " + t.getClass() + "@" + System.identityHashCode(t) + " " + key + "=" + value); + LOG.debug("add decoration to {}@{} {}={}", t.getClass(), System.identityHashCode(t), key, value); m.put(key,value); return true; } @@ -1348,40 +1351,13 @@ ExceptionResponse handleIt(final User user, Exception ex) return null; }; SearchService dummySearch = (SearchService) Proxy.newProxyInstance(this.getClass().getClassLoader(), new Class[]{SearchService.class}, h); - Logger dummyLog = new org.apache.logging.log4j.core.Logger((LoggerContext) LogManager.getContext(), "mock logger", LogManager.getLogger("mock logger").getMessageFactory()) + Logger dummyLog = new SimpleLogger("mock logger", Level.ALL, false, false, false, false, "", null, new PropertiesUtil(PropertiesUtil.getSystemProperties()), null) { @Override - public void debug(Object message) - { - } - @Override - public void debug(Object message, Throwable t) - { - } - @Override - public void error(Object message) - { - } - @Override - public void error(String message, Throwable t) - { - res.addHeader("Logger.error", null!=message? message :null!=t?t.getMessage():""); - } - @Override - public void fatal(Object message) - { - } - @Override - public void fatal(Object message, Throwable t) - { - } - @Override - public void warn(Object message) - { - } - @Override - public void warn(Object message, Throwable t) + public void logMessage(String fqcn, Level level, Marker marker, Message message, Throwable throwable) { + if (level.isMoreSpecificThan(Level.ERROR)) + res.addHeader("Logger.error", message.getFormattedMessage()); } }; HttpServletRequestWrapper req = new HttpServletRequestWrapper(TestContext.get().getRequest()) diff --git a/api/src/org/labkey/api/util/FileLoggerWriter.java b/api/src/org/labkey/api/util/FileLoggerWriter.java index c71bff88067..d4bd188c090 100644 --- a/api/src/org/labkey/api/util/FileLoggerWriter.java +++ b/api/src/org/labkey/api/util/FileLoggerWriter.java @@ -14,7 +14,7 @@ * */ public class FileLoggerWriter implements LoggerWriter, AutoCloseable { - private final String LINE_SEP = System.getProperty("line.separator"); + private final String LINE_SEP = System.lineSeparator(); private static final Logger LOG = LogManager.getLogger(FileLoggerWriter.class); private final File _file; @@ -31,7 +31,7 @@ public FileLoggerWriter(File file) } catch (IOException e) { - LOG.error("Failed opening the file - " + _file.getName() , e); + LOG.error("Failed opening the file - {}", _file.getName(), e); } } @@ -45,7 +45,7 @@ public void close() } catch (IOException e) { - LOG.error("Unable to close the file - " + _file.getName(), e); + LOG.error("Unable to close the file - {}", _file.getName(), e); } } @@ -79,7 +79,7 @@ public void write(String message, @Nullable Throwable t) } catch (IOException e) { - LOG.error("Failed appending to file - " + _file.getName(), e); + LOG.error("Failed appending to file - {}", _file.getName(), e); } } else diff --git a/api/src/org/labkey/api/util/FileStream.java b/api/src/org/labkey/api/util/FileStream.java index 5556a5643c1..192babbfcf1 100644 --- a/api/src/org/labkey/api/util/FileStream.java +++ b/api/src/org/labkey/api/util/FileStream.java @@ -106,7 +106,7 @@ static void transferToImpl(FileStream s, File dest) throws IOException { if (!tempFile.delete() && tempFile.exists()) { - LOG.warn("Failed to delete temporary file [" + tempFile.getAbsolutePath() + "]"); + LOG.warn("Failed to delete temporary file [{}]", tempFile.getAbsolutePath()); } } } diff --git a/api/src/org/labkey/api/util/FileUtil.java b/api/src/org/labkey/api/util/FileUtil.java index a52d9d788fc..ec1e24b186d 100644 --- a/api/src/org/labkey/api/util/FileUtil.java +++ b/api/src/org/labkey/api/util/FileUtil.java @@ -37,7 +37,6 @@ import org.labkey.api.security.Crypt; import org.labkey.api.settings.AppProps; import org.labkey.api.util.logging.LogHelper; -import org.labkey.api.view.NotFoundException; import org.labkey.api.view.UnauthorizedException; import org.labkey.vfs.FileLike; import org.labkey.vfs.FileSystemLike; @@ -250,7 +249,7 @@ public static boolean deleteDir(@NotNull Path dir, @Nullable Logger log) } catch (IOException e) { - log.debug(String.format("Unable to clean dir [%1$s]", dir), e); + log.debug("Unable to clean dir [{}]", dir, e); return false; } } @@ -270,11 +269,11 @@ public static boolean deleteDir(@NotNull Path dir, @Nullable Logger log) lastException = e; // Issue 39579: Folder import sometimes fails to delete temp directory // wait a little then try again - log.warn("Failed to delete file. Sleep and try to delete again. " + e.getMessage()); + log.warn("Failed to delete file. Sleep and try to delete again. {}", e.getMessage()); try {Thread.sleep(1000);} catch (InterruptedException x) {/* pass */} } } - log.warn("Failed to delete file after 5 attempts: " + FileUtil.getAbsoluteCaseSensitiveFile(dir.toFile()), lastException); + log.warn("Failed to delete file after 5 attempts: {}", FileUtil.getAbsoluteCaseSensitiveFile(dir.toFile()), lastException); return false; } @@ -826,7 +825,7 @@ public static URI createUri(String str, boolean isEncoded) // Creating stack traces is expensive so only bother if we're really going to log it if (LOG.isDebugEnabled()) { - LOG.debug("CreateUri from: " + str + " [" + Thread.currentThread().getStackTrace()[2].toString() + "]"); + LOG.debug("CreateUri from: {} [{}]", str, Thread.currentThread().getStackTrace()[2].toString()); } if (isEncoded) str2 = str2.replace(" ", "%20"); // Spaces in paths make URI unhappy @@ -1025,7 +1024,7 @@ private static String getPathStringWithoutAccessId(URI uri) } catch (URISyntaxException e) { - LOG.debug("Error attempting to conform uri: " + e.getMessage()); + LOG.debug("Error attempting to conform uri: {}", e.getMessage()); return uri.toString(); } } @@ -1189,7 +1188,7 @@ public static void copyFile(ReadableByteChannel in, long expected, File dst) thr long actual = 0; long bytesCopied; - LOG.debug("Starting to transfer to " + dst + ", expecting " + (expected == -1 ? "an unknown number" : Long.toString(expected)) + " bytes"); + LOG.debug("Starting to transfer to {}, expecting {} bytes", dst, expected == -1 ? "an unknown number" : Long.toString(expected)); try (FileOutputStream os = new FileOutputStream(dst); FileChannel out = os.getChannel(); @@ -1201,7 +1200,7 @@ public static void copyFile(ReadableByteChannel in, long expected, File dst) thr actual += bytesCopied; if (actual != expected && bytesCopied != 0) { - LOG.debug("Still transferring to " + dst + ", " + actual + " bytes transferred so far"); + LOG.debug("Still transferring to {}, {} bytes transferred so far", dst, actual); } } while (bytesCopied != 0); @@ -1212,11 +1211,11 @@ public static void copyFile(ReadableByteChannel in, long expected, File dst) thr { if (success) { - LOG.debug("Finished transferring " + actual + " bytes to " + dst); + LOG.debug("Finished transferring {} bytes to {}", actual, dst); } else { - LOG.debug("Failed during transfer, but successfully copied at least " + actual + " bytes to " + dst); + LOG.debug("Failed during transfer, but successfully copied at least {} bytes to {}", actual, dst); } } } @@ -1344,7 +1343,7 @@ else if (part.equals("..")) { if (list.isEmpty()) return null; - list.remove(list.size()-1); + list.removeLast(); } else { diff --git a/api/src/org/labkey/api/util/HeartBeat.java b/api/src/org/labkey/api/util/HeartBeat.java index 66449aea24f..9ad819580ae 100644 --- a/api/src/org/labkey/api/util/HeartBeat.java +++ b/api/src/org/labkey/api/util/HeartBeat.java @@ -82,7 +82,7 @@ public void run() } catch (InterruptedException e) { - _log.debug(getName() + " interrupted"); + _log.debug("{} interrupted", getName()); } long ms = System.currentTimeMillis(); @@ -102,10 +102,5 @@ public void shutdownPre() _shutdown = true; interrupt(); } - - @Override - public void shutdownStarted() - { - } } } diff --git a/api/src/org/labkey/api/util/HttpUtil.java b/api/src/org/labkey/api/util/HttpUtil.java index 30e792100c7..21aedc0b515 100644 --- a/api/src/org/labkey/api/util/HttpUtil.java +++ b/api/src/org/labkey/api/util/HttpUtil.java @@ -88,7 +88,7 @@ public static Method valueOf(HttpServletRequest req) * @param uri resource * @return A String for the content and the final URI. */ - public static Pair getText(URI uri) throws IOException, URISyntaxException, ParseException + public static Pair getText(URI uri) throws IOException, URISyntaxException { try (CustomTiming ignored = MiniProfiler.custom("http", "HTTP get " + uri.getHost() + "/" + uri.getPath()); CloseableHttpClient client = HttpClientBuilder.create().build()) @@ -109,7 +109,7 @@ public static Pair getText(URI uri) throws IOException, URISyntaxEx throw new HttpException("Bad URI", e); } - LOG.debug("HTTP GET '" + uri + "' -> resolved to '" + finalURI + "'"); + LOG.debug("HTTP GET '{}' -> resolved to '{}'", uri, finalURI); HttpEntity entity = response.getEntity(); String content = EntityUtils.toString(entity); @@ -135,13 +135,13 @@ public static Pair getXHTML(URI uri) throws IOException, URISynta Document document = JSoupUtil.convertHtmlToDocument(content, true, errors); if (!errors.isEmpty()) { - LOG.warn("Error converting to XHTML document: " + uri + "\n" + errors.get(0)); + LOG.warn("Error converting to XHTML document: {}\n{}", uri, errors.getFirst()); return null; } if (document == null) { - LOG.warn("Error converting to XHTML document: " + uri); + LOG.warn("Error converting to XHTML document: {}", uri); return null; } @@ -150,7 +150,7 @@ public static Pair getXHTML(URI uri) throws IOException, URISynta if (refresh != null) { URI redirectURI = finalURI.resolve(refresh); - LOG.info("following meta refresh: " + redirectURI); + LOG.info("following meta refresh: {}", redirectURI); return getXHTML(redirectURI); } else diff --git a/api/src/org/labkey/api/util/ImageUtil.java b/api/src/org/labkey/api/util/ImageUtil.java index 26df16deb5d..0b35ee704e4 100644 --- a/api/src/org/labkey/api/util/ImageUtil.java +++ b/api/src/org/labkey/api/util/ImageUtil.java @@ -191,7 +191,7 @@ public static Thumbnail webThumbnail(ViewContext context, String html, URI baseU List errors = new ArrayList<>(); Document document = JSoupUtil.convertHtmlToDocument(html, true, errors); if (!errors.isEmpty()) - throw new RuntimeException(errors.get(0)); + throw new RuntimeException(errors.getFirst()); return renderThumbnail(webImage(context, document, baseURI, WEB_IMAGE_WIDTH, WEB_IMAGE_HEIGHT)); } diff --git a/api/src/org/labkey/api/util/InputBuilder.java b/api/src/org/labkey/api/util/InputBuilder.java index 3648f245284..6223cf5c6d6 100644 --- a/api/src/org/labkey/api/util/InputBuilder.java +++ b/api/src/org/labkey/api/util/InputBuilder.java @@ -702,7 +702,7 @@ public String getType() return _type; } - public HtmlString getValue() + public @Nullable HtmlString getValue() { return _value; } diff --git a/api/src/org/labkey/api/util/InputStreamWrapper.java b/api/src/org/labkey/api/util/InputStreamWrapper.java index 249991eb60e..9987e3174c0 100644 --- a/api/src/org/labkey/api/util/InputStreamWrapper.java +++ b/api/src/org/labkey/api/util/InputStreamWrapper.java @@ -15,6 +15,8 @@ */ package org.labkey.api.util; +import org.jetbrains.annotations.NotNull; + import java.io.IOException; import java.io.InputStream; @@ -39,13 +41,13 @@ public int read() throws IOException } @Override - public int read(byte[] b) throws IOException + public int read(byte @NotNull [] b) throws IOException { return _is.read(b); } @Override - public int read(byte[] b, int off, int len) throws IOException + public int read(byte @NotNull [] b, int off, int len) throws IOException { return _is.read(b, off, len); } diff --git a/api/src/org/labkey/api/util/Job.java b/api/src/org/labkey/api/util/Job.java index 3733a6bb9b9..ef1ca61ebcb 100644 --- a/api/src/org/labkey/api/util/Job.java +++ b/api/src/org/labkey/api/util/Job.java @@ -45,7 +45,7 @@ protected void starting(Thread t) protected void done(Throwable t) { if (null != t) - JobRunner._log.error("Uncaught exception in Job: " + this, t); + JobRunner._log.error("Uncaught exception in Job: {}", this, t); } // diff --git a/api/src/org/labkey/api/util/LimitedSizeInputStream.java b/api/src/org/labkey/api/util/LimitedSizeInputStream.java index de876306383..3d6e39e3406 100644 --- a/api/src/org/labkey/api/util/LimitedSizeInputStream.java +++ b/api/src/org/labkey/api/util/LimitedSizeInputStream.java @@ -1,5 +1,7 @@ package org.labkey.api.util; +import org.jetbrains.annotations.NotNull; + import java.io.IOException; import java.io.InputStream; @@ -28,13 +30,13 @@ public int read() throws IOException } @Override - public int read(byte[] b) throws IOException + public int read(byte @NotNull [] b) throws IOException { return read(b, 0, b.length); } @Override - public int read(byte[] b, int off, int len) throws IOException + public int read(byte @NotNull [] b, int off, int len) throws IOException { int i = original.read(b, off, len); if (i >= 0) incrementCounter(i); diff --git a/api/src/org/labkey/api/util/LogOutputStream.java b/api/src/org/labkey/api/util/LogOutputStream.java index dbb3ebb61c5..27cd3a9228e 100644 --- a/api/src/org/labkey/api/util/LogOutputStream.java +++ b/api/src/org/labkey/api/util/LogOutputStream.java @@ -54,14 +54,14 @@ public void write(int b) } @Override - public void write(@NotNull byte[] bytes) + public void write(@NotNull byte @NotNull [] bytes) { for (byte b : bytes) write(b); } @Override - public synchronized void write(byte[] bytes, int off, int len) + public synchronized void write(byte @NotNull [] bytes, int off, int len) { for (int i = off; i < len; i++) write(bytes[i]); diff --git a/api/src/org/labkey/api/util/MothershipReport.java b/api/src/org/labkey/api/util/MothershipReport.java index f0a01f0361d..a7a6c7a0b2b 100644 --- a/api/src/org/labkey/api/util/MothershipReport.java +++ b/api/src/org/labkey/api/util/MothershipReport.java @@ -33,7 +33,6 @@ import org.labkey.api.settings.OptionalFeatureService; import org.labkey.api.util.logging.LogHelper; -import javax.net.ssl.HttpsURLConnection; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; @@ -346,7 +345,7 @@ public void run() } } } - LOG.debug("Successfully submitted report to " + _url); + LOG.debug("Successfully submitted report to {}", _url); } finally { @@ -356,7 +355,7 @@ public void run() catch (Throwable t) { // Don't bother the client if this report fails - LOG.debug("Failed to submit report to " + this._target + " at " + _url, t); + LOG.debug("Failed to submit report to {} at {}", this._target, _url, t); } } diff --git a/api/src/org/labkey/api/util/NetworkDrive.java b/api/src/org/labkey/api/util/NetworkDrive.java index 7cf0b87ba76..69673ff2bfb 100644 --- a/api/src/org/labkey/api/util/NetworkDrive.java +++ b/api/src/org/labkey/api/util/NetworkDrive.java @@ -190,17 +190,17 @@ public static void ensureDrive(@Nullable String path) NetworkDrive drive = getNetworkDrive(path); if (drive != null) { - _log.info("Attempting to mount " + path.toUpperCase().charAt(0) + " drive at " + drive.getPath() + " with user " + drive.getUser()); + _log.info("Attempting to mount {} drive at {} with user {}", path.toUpperCase().charAt(0), drive.getPath(), drive.getUser()); String error = drive.mount(driveChar); if (error != null) { - _log.error("Failed to map network drive for " + path + ": " + error); + _log.error("Failed to map network drive for {}: {}", path, error); } } } catch (Exception e) { - _log.error("Exception trying to map network drive for " + path, e); + _log.error("Exception trying to map network drive for {}", path, e); } } diff --git a/api/src/org/labkey/api/util/OptionBuilder.java b/api/src/org/labkey/api/util/OptionBuilder.java index 58c4ab0efa9..fa3f3bfbb47 100644 --- a/api/src/org/labkey/api/util/OptionBuilder.java +++ b/api/src/org/labkey/api/util/OptionBuilder.java @@ -89,7 +89,7 @@ public boolean isDisabled() return _disabled; } - public HtmlString getLabel() + public @NotNull HtmlString getLabel() { return _label; } diff --git a/api/src/org/labkey/api/util/PageFlowUtil.java b/api/src/org/labkey/api/util/PageFlowUtil.java index cbb070693b6..d8794ff538d 100644 --- a/api/src/org/labkey/api/util/PageFlowUtil.java +++ b/api/src/org/labkey/api/util/PageFlowUtil.java @@ -107,7 +107,6 @@ import javax.xml.transform.TransformerFactoryConfigurationError; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamResult; -import java.awt.*; import java.io.BufferedReader; import java.io.ByteArrayOutputStream; import java.io.File; diff --git a/api/src/org/labkey/api/util/RateLimiter.java b/api/src/org/labkey/api/util/RateLimiter.java index 93e29e87d0c..e5f0247d753 100644 --- a/api/src/org/labkey/api/util/RateLimiter.java +++ b/api/src/org/labkey/api/util/RateLimiter.java @@ -151,12 +151,12 @@ private synchronized long _updateCounts(long count) { while (!_history.isEmpty()) { - RateAccumulator last = _history.get(_history.size()-1); + RateAccumulator last = _history.getLast(); if (last.getStart() + accumulateInterval > now - historyInterval) break; - _history.remove(_history.size()-1); + _history.removeLast(); } - _history.add(0, _short); + _history.addFirst(_short); _short = new SimpleRateAccumulator(now); _long = aggregateRate(now); // consider: reuse RateAccumulator instead of new } diff --git a/api/src/org/labkey/api/util/ResultSetUtil.java b/api/src/org/labkey/api/util/ResultSetUtil.java index b55342fd5ed..5c18d4948d6 100644 --- a/api/src/org/labkey/api/util/ResultSetUtil.java +++ b/api/src/org/labkey/api/util/ResultSetUtil.java @@ -130,21 +130,21 @@ public static void logMetaData(ResultSet rs) for (int i = 1; i <= md.getColumnCount(); i++) { - _log.info("Name: " + md.getColumnName(i)); - _log.info("Label: " + md.getColumnLabel(i)); - _log.info("Type: " + md.getColumnType(i)); - _log.info("Display Size: " + md.getColumnDisplaySize(i)); - _log.info("Type Name: " + md.getColumnTypeName(i)); - _log.info("Precision: " + md.getPrecision(i)); - _log.info("Scale: " + md.getScale(i)); - _log.info("Schema: " + md.getSchemaName(i)); - _log.info("Table: " + md.getTableName(i)); + _log.info("Name: {}", md.getColumnName(i)); + _log.info("Label: {}", md.getColumnLabel(i)); + _log.info("Type: {}", md.getColumnType(i)); + _log.info("Display Size: {}", md.getColumnDisplaySize(i)); + _log.info("Type Name: {}", md.getColumnTypeName(i)); + _log.info("Precision: {}", md.getPrecision(i)); + _log.info("Scale: {}", md.getScale(i)); + _log.info("Schema: {}", md.getSchemaName(i)); + _log.info("Table: {}", md.getTableName(i)); _log.info("========================"); } } catch (SQLException e) { - _log.error("logMetaData: " + e); + _log.error("logMetaData: {}", String.valueOf(e)); } } diff --git a/api/src/org/labkey/api/util/ReturnURLString.java b/api/src/org/labkey/api/util/ReturnURLString.java index a499f789164..f00e226cf13 100644 --- a/api/src/org/labkey/api/util/ReturnURLString.java +++ b/api/src/org/labkey/api/util/ReturnURLString.java @@ -21,7 +21,6 @@ import org.apache.logging.log4j.Logger; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; -import org.labkey.api.data.ConvertHelper; import org.labkey.api.util.logging.LogHelper; import org.labkey.api.view.ActionURL; import org.labkey.api.view.ViewServlet; @@ -81,7 +80,7 @@ private static URLHelper scrub(CharSequence cs) if (!urls.isEmpty()) { - URLHelper first = urls.get(0); + URLHelper first = urls.getFirst(); String s0 = first.toString(); // See if all the parts are identical diff --git a/api/src/org/labkey/api/util/StringExpressionFactory.java b/api/src/org/labkey/api/util/StringExpressionFactory.java index 847dd1feb2f..4e57acc990d 100644 --- a/api/src/org/labkey/api/util/StringExpressionFactory.java +++ b/api/src/org/labkey/api/util/StringExpressionFactory.java @@ -422,7 +422,7 @@ else if (rest.startsWith("join('") && rest.endsWith("')")) break; // Add in reverse order since we are parsing from back to front - formats.add(0, format); + formats.addFirst(format); value = value.substring(0, colon); } @@ -893,7 +893,7 @@ public String eval(Map context) ArrayList parts = getParsedExpression(); if (parts.size() == 1) { - StringExpressionFactory.StringPart part = parts.get(0); + StringExpressionFactory.StringPart part = parts.getFirst(); try { return nullFilter(part.getValue(context), part); @@ -1312,7 +1312,7 @@ protected void parse() // special case if entire pattern consists of one substitution, don't encode if (1 == _parsedExpression.size()) { - StringPart p = _parsedExpression.get(0); + StringPart p = _parsedExpression.getFirst(); if (p instanceof FieldPart fp) { _parsedExpression.set(0, new FieldPart(fp._key, SubstitutionFormat.passThrough)); diff --git a/api/src/org/labkey/api/util/StringUtilsLabKey.java b/api/src/org/labkey/api/util/StringUtilsLabKey.java index 4720a80d4d0..83d306a19eb 100644 --- a/api/src/org/labkey/api/util/StringUtilsLabKey.java +++ b/api/src/org/labkey/api/util/StringUtilsLabKey.java @@ -188,11 +188,11 @@ public static String findCommonPrefix(@NotNull Collection strings) List list = new ArrayList<>(strings); if (strings.size() == 1) - return list.get(0); + return list.getFirst(); Collections.sort(list); - String first = list.get(0); - String last = list.get(list.size() - 1); + String first = list.getFirst(); + String last = list.getLast(); int i = 0; while (i < Math.min(first.length(), last.length()) && first.charAt(i) == last.charAt(i)) diff --git a/api/src/org/labkey/api/util/SvgUtil.java b/api/src/org/labkey/api/util/SvgUtil.java index df148a80d9a..38201385741 100644 --- a/api/src/org/labkey/api/util/SvgUtil.java +++ b/api/src/org/labkey/api/util/SvgUtil.java @@ -2,7 +2,7 @@ import org.apache.commons.lang3.StringUtils; import org.jetbrains.annotations.Nullable; -import org.jspecify.annotations.NonNull; +import org.jetbrains.annotations.NotNull; import org.junit.Assert; import org.junit.Test; @@ -14,7 +14,7 @@ public class SvgUtil public record Size(Float value, @Nullable String units) { @Override - public @NonNull String toString() + public @NotNull String toString() { return value + (null != units ? units : ""); } diff --git a/api/src/org/labkey/api/util/SystemMaintenanceJob.java b/api/src/org/labkey/api/util/SystemMaintenanceJob.java index f19fc72e3a7..8ad3af623f0 100644 --- a/api/src/org/labkey/api/util/SystemMaintenanceJob.java +++ b/api/src/org/labkey/api/util/SystemMaintenanceJob.java @@ -115,7 +115,7 @@ public String call() try { PipelineJob job = new MaintenancePipelineJob(vbi, root, tasksToRun); - LOG.info("Queuing MaintenancePipelineJob [thread " + Thread.currentThread().getName() + " to " + PipelineService.get().toString() + "]"); + LOG.info("Queuing MaintenancePipelineJob [thread {} to {}]", Thread.currentThread().getName(), PipelineService.get().toString()); PipelineService.get().queueJob(job); jobGuid = job.getJobGUID(); } diff --git a/api/src/org/labkey/api/util/URLHelper.java b/api/src/org/labkey/api/util/URLHelper.java index 65a18fc3d42..fcf0dca04ba 100644 --- a/api/src/org/labkey/api/util/URLHelper.java +++ b/api/src/org/labkey/api/util/URLHelper.java @@ -670,7 +670,7 @@ public PropertyValues getPropertyValues() for (Map.Entry> m : map.asMap().entrySet()) { if (m.getValue().size() == 1) - mpvs.addPropertyValue(m.getKey(), ((List)m.getValue()).get(0)); + mpvs.addPropertyValue(m.getKey(), ((List)m.getValue()).getFirst()); else mpvs.addPropertyValue(m.getKey(), m.getValue().toArray(new String[0])); } diff --git a/api/src/org/labkey/api/util/emailTemplate/EmailTemplate.java b/api/src/org/labkey/api/util/emailTemplate/EmailTemplate.java index 57245e3e45b..3635fd11faf 100644 --- a/api/src/org/labkey/api/util/emailTemplate/EmailTemplate.java +++ b/api/src/org/labkey/api/util/emailTemplate/EmailTemplate.java @@ -518,7 +518,7 @@ public String getFormattedValue(Container c, @Nullable String templateFormat, Co } catch (MissingFormatArgumentException e) { - LOG.warn("Unable to format value '" + value + "' using format string '" + templateFormat + "' in email template '" + getName() + "'"); + LOG.warn("Unable to format value '{}' using format string '{}' in email template '{}'", value, templateFormat, getName()); formattedValue = value.toString(); } } diff --git a/api/src/org/labkey/api/util/emailTemplate/EmailTemplateService.java b/api/src/org/labkey/api/util/emailTemplate/EmailTemplateService.java index e3b6a6d7ebe..593f0a32398 100644 --- a/api/src/org/labkey/api/util/emailTemplate/EmailTemplateService.java +++ b/api/src/org/labkey/api/util/emailTemplate/EmailTemplateService.java @@ -67,7 +67,7 @@ public void registerTemplate(Class templateClass) { synchronized(_templates) { - _log.debug("Registering email template " + templateClass.getName()); + _log.debug("Registering email template {}", templateClass.getName()); if (_templates.contains(templateClass)) throw new IllegalStateException("Template : " + templateClass.getName() + " has previously been registered."); @@ -264,6 +264,6 @@ public void relocateEmailTemplateProperties(String oldClassName, String newClass sql.add(oldClassName + "%"); int updated = new SqlExecutor(tinfo.getSchema()).execute(sql); - _log.info("Migrated " + StringUtilsLabKey.pluralize(updated, "template property", "template properties") + " from " + oldClassName + " to " + newClassName); + _log.info("Migrated {} from {} to {}", StringUtilsLabKey.pluralize(updated, "template property", "template properties"), oldClassName, newClassName); } } \ No newline at end of file diff --git a/api/src/org/labkey/api/view/ActionURL.java b/api/src/org/labkey/api/view/ActionURL.java index b9a5f6df3f4..09278e638c2 100644 --- a/api/src/org/labkey/api/view/ActionURL.java +++ b/api/src/org/labkey/api/view/ActionURL.java @@ -672,7 +672,7 @@ public void test() // a is changed s = a.getLocalURIString(); - assertTrue(!stringA.equals(s)); + assertFalse(stringA.equals(s)); // b is not changed s = b.getLocalURIString(); diff --git a/api/src/org/labkey/api/view/BaseWebPartFactory.java b/api/src/org/labkey/api/view/BaseWebPartFactory.java index 5be4ee6dd77..b6691d84015 100644 --- a/api/src/org/labkey/api/view/BaseWebPartFactory.java +++ b/api/src/org/labkey/api/view/BaseWebPartFactory.java @@ -153,7 +153,7 @@ protected void populateProperties(WebPartView view, Map prope { // Unfortunately, we have to catch Exception here, since BeanUtils throws RuntimeExceptions // for various failures. - LOG.warn("Couldn't set property " + entry.getKey() + " on " + view.getClass() + " to value " + entry.getValue(), e); + LOG.warn("Couldn't set property {} on {} to value {}", entry.getKey(), view.getClass(), entry.getValue(), e); } } else diff --git a/api/src/org/labkey/api/view/FileServlet.java b/api/src/org/labkey/api/view/FileServlet.java index 2e832937595..3cdd31ca756 100644 --- a/api/src/org/labkey/api/view/FileServlet.java +++ b/api/src/org/labkey/api/view/FileServlet.java @@ -76,7 +76,7 @@ protected void service(HttpServletRequest request, HttpServletResponse response) SimpleMetricsService.get().increment("API", "FileServlet", "urlsDispatched"); String dispatchUrl = containerPath + "/filecontent-sendFile.view?" + (null == fileNameParam ? "fileName=" + PageFlowUtil.encodeURIComponent(fileName) : ""); - _log.info("FileServlet dispatching " + request.getRequestURL() + " to " + dispatchUrl); + _log.info("FileServlet dispatching {} to {}", request.getRequestURL(), dispatchUrl); // NOTE other parameters seem to get magically propagated... RequestDispatcher r = request.getRequestDispatcher(dispatchUrl); r.forward(request, response); diff --git a/api/src/org/labkey/api/view/HttpView.java b/api/src/org/labkey/api/view/HttpView.java index 89fe20f5c07..4f68f496182 100644 --- a/api/src/org/labkey/api/view/HttpView.java +++ b/api/src/org/labkey/api/view/HttpView.java @@ -176,7 +176,7 @@ public final void render(ModelBean model, HttpServletRequest request, HttpServle response.flushBuffer(); } if (!ExceptionUtil.isIgnorable(e)) - LogManager.getLogger(HttpView.class).error("Exception while rendering view; creation stacktrace:" + ExceptionUtil.renderStackTrace(_creationStackTrace)); + LogManager.getLogger(HttpView.class).error("Exception while rendering view; creation stacktrace:{}", ExceptionUtil.renderStackTrace(_creationStackTrace)); throw e; } } @@ -761,7 +761,7 @@ protected void setVisible(boolean v) */ @Override @Deprecated - public ModelAndView addObject(String key, Object value) + public @NotNull ModelAndView addObject(@NotNull String key, Object value) { getViewContext().put(key, value); return this; diff --git a/api/src/org/labkey/api/view/LabKeyKaptchaServlet.java b/api/src/org/labkey/api/view/LabKeyKaptchaServlet.java index c7f3d7482b4..d21bd491bc9 100644 --- a/api/src/org/labkey/api/view/LabKeyKaptchaServlet.java +++ b/api/src/org/labkey/api/view/LabKeyKaptchaServlet.java @@ -65,7 +65,7 @@ public void init(ServletConfig conf) throws ServletException /** */ @Override public void doGet(HttpServletRequest req, HttpServletResponse resp) - throws ServletException, IOException + throws IOException { // Set to expire far in the past. resp.setDateHeader("Expires", 0); diff --git a/api/src/org/labkey/api/view/NavTreeManager.java b/api/src/org/labkey/api/view/NavTreeManager.java index ce0bc026d4e..5be9c82314b 100644 --- a/api/src/org/labkey/api/view/NavTreeManager.java +++ b/api/src/org/labkey/api/view/NavTreeManager.java @@ -50,8 +50,8 @@ public static void expandCollapsePath(ViewContext viewContext, String navTreeId, { if (null == navTreeId) return; - - _log.debug("Expand/Collapse path navTreeId = " + navTreeId + " path=" + path + " collapse= " + collapse); + + _log.debug("Expand/Collapse path navTreeId = {} path={} collapse= {}", navTreeId, path, collapse); saveExpandState(viewContext, navTreeId, path, collapse); } diff --git a/api/src/org/labkey/api/view/Portal.java b/api/src/org/labkey/api/view/Portal.java index b71e9961fcf..0dd0c3eca05 100644 --- a/api/src/org/labkey/api/view/Portal.java +++ b/api/src/org/labkey/api/view/Portal.java @@ -1099,7 +1099,7 @@ private static void _insertOrUpdate(TableInfo portalTable, PortalPage p, boolean count = new SqlExecutor(portalTable.getSchema()).execute(updateSQL); if (0 == count) - LOG.warn((update ? "Update" : "Insert") + " failed for page '" + p.pageId + "' in container '" + ContainerManager.getForId(p.getContainer()).getPath() + "'"); + LOG.warn("{} failed for page '{}' in container '{}'", update ? "Update" : "Insert", p.pageId, ContainerManager.getForId(p.getContainer()).getPath()); } } @@ -1521,7 +1521,7 @@ private static PortalPage getPortalPageDirect(Container container, String pageId SimpleFilter filter = SimpleFilter.createContainerFilter(container).addCondition(FieldKey.fromString("pageId"), pageId); ArrayList pages = new TableSelector(getTableInfoPortalPages(), filter, null).getArrayList(PortalPage.class); if (!pages.isEmpty()) - return pages.get(0); // In rare cases there could be more than one. + return pages.getFirst(); // In rare cases there could be more than one. return null; } @@ -2212,7 +2212,7 @@ public void testModuleResourceCache() .mapToInt(Collection::size) .sum(); - LOG.info(viewCount + " webparts defined in all modules"); + LOG.info("{} webparts defined in all modules", viewCount); // Make sure the cache retrieves the expected number of webpart definitions from the simpletest module, if present diff --git a/api/src/org/labkey/api/view/SimpleFolderTab.java b/api/src/org/labkey/api/view/SimpleFolderTab.java index d5f90cf2a56..48ad0d19ed5 100644 --- a/api/src/org/labkey/api/view/SimpleFolderTab.java +++ b/api/src/org/labkey/api/view/SimpleFolderTab.java @@ -86,7 +86,7 @@ public SimpleFolderTab(FolderTabDocument.FolderTab tab, int defaultIndex) // else if (tabTypeString.equalsIgnoreCase("link")) // FUTURE // _tabType = TAB_TYPE.Link; else if (!tabTypeString.equalsIgnoreCase("portal")) - LOGGER.error("Container tab type " + tabTypeString + " is not a recognized tab type."); + LOGGER.error("Container tab type {} is not a recognized tab type.", tabTypeString); } if (tab.getPreferredWebParts() != null) @@ -131,13 +131,13 @@ else if (!tabTypeString.equalsIgnoreCase("portal")) } else { - LOGGER.error("Improper permission class: " + permClassName + ", for folder type: " + getFolderType() + ", tab: " + getName()); + LOGGER.error("Improper permission class: {}, for folder type: {}, tab: {}", permClassName, getFolderType(), getName()); } } catch (ClassNotFoundException e) { // ignore - LOGGER.error("Unable to find class for permission name: " + permClassName + ", for folder type: " + getFolderType() + ", tab: " + getName()); + LOGGER.error("Unable to find class for permission name: {}, for folder type: {}, tab: {}", permClassName, getFolderType(), getName()); } } } diff --git a/api/src/org/labkey/api/view/TabStripView.java b/api/src/org/labkey/api/view/TabStripView.java index 630a3f319a1..945913e694f 100644 --- a/api/src/org/labkey/api/view/TabStripView.java +++ b/api/src/org/labkey/api/view/TabStripView.java @@ -108,7 +108,7 @@ public String getSelectedTabId() { List tabs = getTabList(); if (!tabs.isEmpty()) - tabId = tabs.get(0).getId(); + tabId = tabs.getFirst().getId(); } return tabId; } diff --git a/api/src/org/labkey/api/view/ViewContext.java b/api/src/org/labkey/api/view/ViewContext.java index 23f87d60e18..ce54015ca89 100644 --- a/api/src/org/labkey/api/view/ViewContext.java +++ b/api/src/org/labkey/api/view/ViewContext.java @@ -15,8 +15,8 @@ */ package org.labkey.api.view; -import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; +import org.jetbrains.annotations.NotNull; import org.labkey.api.data.Container; import org.labkey.api.data.ContainerManager; import org.labkey.api.security.HasPermission; @@ -399,7 +399,7 @@ public List getList(Object key) public void pushMessageBundle(String path) { - _messageBundles.add(0,path); + _messageBundles.addFirst(path); _messageSource = null; } @@ -421,19 +421,19 @@ public MessageSource getMessageSource() } @Override - public String getMessage(String code, Object[] args, String defaultMessage, Locale locale) + public String getMessage(@NotNull String code, Object[] args, String defaultMessage, Locale locale) { return getMessageSource().getMessage(code, args, defaultMessage, locale); } @Override - public String getMessage(String code, Object[] args, Locale locale) throws NoSuchMessageException + public @NotNull String getMessage(@NotNull String code, Object[] args, Locale locale) throws NoSuchMessageException { return getMessageSource().getMessage(code, args, locale); } @Override - public String getMessage(MessageSourceResolvable resolvable, Locale locale) throws NoSuchMessageException + public @NotNull String getMessage(@NotNull MessageSourceResolvable resolvable, Locale locale) throws NoSuchMessageException { return getMessageSource().getMessage(resolvable, locale); } @@ -463,7 +463,7 @@ public ApplicationContext getApplicationContext() } @Override - public void setApplicationContext(ApplicationContext applicationContext) + public void setApplicationContext(@NotNull ApplicationContext applicationContext) { _applicationContext = applicationContext; } diff --git a/api/src/org/labkey/api/view/ViewHeadersAndMetaTestCase.jsp b/api/src/org/labkey/api/view/ViewHeadersAndMetaTestCase.jsp index 71669d5ff03..121f54165d1 100644 --- a/api/src/org/labkey/api/view/ViewHeadersAndMetaTestCase.jsp +++ b/api/src/org/labkey/api/view/ViewHeadersAndMetaTestCase.jsp @@ -1,7 +1,5 @@ <%@ page import="org.jetbrains.annotations.NotNull" %> -<%@ page import="org.labkey.api.settings.AppProps" %> <%@ page import="org.labkey.api.util.StringUtilsLabKey" %> -<%@ page import="org.springframework.mock.web.MockHttpServletRequest" %> <%@ page import="org.springframework.mock.web.MockHttpServletResponse" %> <%@ page import="java.io.ByteArrayOutputStream" %> <%@ page import="java.io.IOException" %> @@ -35,7 +33,7 @@ This tests uses MockRequest to test some expected Headers and Meta tags for vari PrintWriter printWriter = new PrintWriter(new ByteArrayOutputStream(), true, StringUtilsLabKey.DEFAULT_CHARSET) { @Override - public void write(@NotNull char[] buf, int off, int len) + public void write(@NotNull char @NotNull [] buf, int off, int len) { } diff --git a/api/src/org/labkey/api/view/ViewServlet.java b/api/src/org/labkey/api/view/ViewServlet.java index 7b312feabe0..1eb99b5afa9 100644 --- a/api/src/org/labkey/api/view/ViewServlet.java +++ b/api/src/org/labkey/api/view/ViewServlet.java @@ -71,7 +71,6 @@ import java.util.Objects; import java.util.concurrent.atomic.AtomicInteger; -import static org.apache.commons.lang3.StringUtils.startsWith; import static org.apache.commons.lang3.StringUtils.trimToEmpty; import static org.labkey.api.data.MultiChoice.ARRAY_MARKER; @@ -369,7 +368,7 @@ private ActionURL requestActionURL(HttpServletRequest request) } if ("GET".equals(request.getMethod())) throw new RedirectException(expand); - _log.warn(DataRegion.LAST_FILTER_PARAM + " not supported for " + request.getMethod()); + _log.warn(DataRegion.LAST_FILTER_PARAM + " not supported for {}", request.getMethod()); } } } @@ -620,8 +619,8 @@ public void init(ServletConfig config) throws ServletException _servletContext = config.getServletContext(); String realPath = config.getServletContext().getRealPath("/"); _log.info("ViewServlet initialized"); - _log.info(" WEBAPP: " + realPath); - _log.info(" PATH: " + System.getenv("PATH")); + _log.info(" WEBAPP: {}", realPath); + _log.info(" PATH: {}", System.getenv("PATH")); } @@ -788,7 +787,7 @@ public static Map adaptParameterMap(Map parame { String[] a = entry.getValue(); Object v = a; - if (null != a && 1 == a.length && !startsWith(entry.getKey(), ARRAY_MARKER)) + if (null != a && 1 == a.length && !Strings.CS.startsWith(entry.getKey(), ARRAY_MARKER)) v = a[0]; ret.put(entry.getKey(), v); } diff --git a/api/src/org/labkey/api/view/WebPartCache.java b/api/src/org/labkey/api/view/WebPartCache.java index 482e23b1468..92fd9652635 100644 --- a/api/src/org/labkey/api/view/WebPartCache.java +++ b/api/src/org/labkey/api/view/WebPartCache.java @@ -112,8 +112,7 @@ static WebPart getWebPart(@NotNull Container c, @NotNull String pageId, int inde p.setEntityId(g); } if (pages.containsKey(p.getPageId()) && null != container) - LOG.warn("Page '" + p.getPageId() + "' in container '" + container.getPath() + - "' is duplicated, meaning some expected web parts may be missing. Recommended to remove the page (tab), which should remove one of them, and set web parts as desired."); + LOG.warn("Page '{}' in container '{}' is duplicated, meaning some expected web parts may be missing. Recommended to remove the page (tab), which should remove one of them, and set web parts as desired.", p.getPageId(), container.getPath()); pages.put(p.getPageId(), p); pagesByRowId.put(p.getRowId(), p); } diff --git a/api/src/org/labkey/api/view/menu/FolderMenu.java b/api/src/org/labkey/api/view/menu/FolderMenu.java index 53c2e6ed02a..7e42aa0ae72 100644 --- a/api/src/org/labkey/api/view/menu/FolderMenu.java +++ b/api/src/org/labkey/api/view/menu/FolderMenu.java @@ -63,7 +63,7 @@ protected void renderView(Object model, HtmlWriter out) throws Exception ViewContext context = getViewContext(); // as shown above in getNavTree, if elements is not null, then there will be only one element. - if (null != elements && (root = elements.get(0)) != null && root.hasChildren()) + if (null != elements && (root = elements.getFirst()) != null && root.hasChildren()) { DIV( cl("folder-nav"), diff --git a/api/src/org/labkey/api/view/template/AppBar.java b/api/src/org/labkey/api/view/template/AppBar.java index 6dc6f4f1e5e..21b15489e86 100644 --- a/api/src/org/labkey/api/view/template/AppBar.java +++ b/api/src/org/labkey/api/view/template/AppBar.java @@ -168,7 +168,7 @@ private List fixCrumbTrail(List crumbTrail, ViewContext contex if (selected == null) { // No matches for previously selected tab, so just choose the first one - selected = buttons.get(0); + selected = buttons.getFirst(); } } else if (selected != null) @@ -188,7 +188,7 @@ else if (selected != null) else if (!crumbTrail.isEmpty()) { // Last item is page title, strip it off the crumb trail - setPageTitle(crumbTrail.get(crumbTrail.size() - 1).getText()); + setPageTitle(crumbTrail.getLast().getText()); List result = new ArrayList<>(); boolean stopLooking = false; diff --git a/api/src/org/labkey/api/view/template/ClientDependency.java b/api/src/org/labkey/api/view/template/ClientDependency.java index bcbc044ac91..4284126838c 100644 --- a/api/src/org/labkey/api/view/template/ClientDependency.java +++ b/api/src/org/labkey/api/view/template/ClientDependency.java @@ -69,7 +69,7 @@ public abstract class ClientDependency static { - ContextListener.addModuleChangeListener(m -> CACHE.clear()); + ContextListener.addModuleChangeListener(_ -> CACHE.clear()); } public enum TYPE @@ -134,7 +134,7 @@ static void logWarning(String message) if (null != ctx) url = HttpView.getContextURLHelper(); - LOG.warn(message + (null != url ? " URL: " + url.getLocalURIString() : "")); + LOG.warn("{}{}", message, null != url ? " URL: " + url.getLocalURIString() : ""); } public static boolean isExternalDependency(String path) @@ -235,7 +235,7 @@ public static List> getSuppliers(DependencyType[] dep return (Supplier) ()->{ var cd = supplier.get(); if (null == cd) - LOG.error("Unable to load in " + name); + LOG.error("Unable to load in {}", name); return cd; }; }) @@ -261,7 +261,7 @@ public static List> getSuppliers(RequiredModuleType[] if (m != null) return ClientDependency.fromModule(m); - LOG.error("Unable to find module: '" + moduleName + "' referenced in " + name); + LOG.error("Unable to find module: '{}' referenced in {}", moduleName, name); return null; }) .collect(Collectors.toList()); diff --git a/api/src/org/labkey/api/view/template/ClientDependencyCacheLoader.java b/api/src/org/labkey/api/view/template/ClientDependencyCacheLoader.java index c6fe7d32cba..59a4b324d1a 100644 --- a/api/src/org/labkey/api/view/template/ClientDependencyCacheLoader.java +++ b/api/src/org/labkey/api/view/template/ClientDependencyCacheLoader.java @@ -59,7 +59,7 @@ public ClientDependencyCacheLoader() if (primaryType == null) { - LOG.warn("Client dependency type not recognized: " + path); + LOG.warn("Client dependency type not recognized: {}", path); return null; } diff --git a/api/src/org/labkey/api/view/template/ExternalClientDependency.java b/api/src/org/labkey/api/view/template/ExternalClientDependency.java index 6a51fb1725d..b2b9a20ea23 100644 --- a/api/src/org/labkey/api/view/template/ExternalClientDependency.java +++ b/api/src/org/labkey/api/view/template/ExternalClientDependency.java @@ -40,7 +40,7 @@ private static TYPE getType(String uri) if (type == null) { - _log.warn("External client dependency type not recognized: " + uri); + _log.warn("External client dependency type not recognized: {}", uri); } return type; diff --git a/api/src/org/labkey/api/view/template/FilePathClientDependency.java b/api/src/org/labkey/api/view/template/FilePathClientDependency.java index 584c60bfc80..9a022e4ae7a 100644 --- a/api/src/org/labkey/api/view/template/FilePathClientDependency.java +++ b/api/src/org/labkey/api/view/template/FilePathClientDependency.java @@ -61,7 +61,7 @@ private void processScript(Path filePath) if (type == null) { - _log.warn("Invalid file type for resource: " + filePath); + _log.warn("Invalid file type for resource: {}", filePath); return; } diff --git a/api/src/org/labkey/api/view/template/LibClientDependency.java b/api/src/org/labkey/api/view/template/LibClientDependency.java index da86d263d4a..a1a908b3e73 100644 --- a/api/src/org/labkey/api/view/template/LibClientDependency.java +++ b/api/src/org/labkey/api/view/template/LibClientDependency.java @@ -75,7 +75,7 @@ protected void handleScript(Path filePath) //module contexts if (libDoc.getLibraries().isSetRequiredModuleContext()) - _suppliers.addAll(getSuppliers(libDoc.getLibraries().getRequiredModuleContext().getModuleArray(), _filePath.getName(), x->true)); + _suppliers.addAll(getSuppliers(libDoc.getLibraries().getRequiredModuleContext().getModuleArray(), _filePath.getName(), _ ->true)); LibraryType library = libDoc.getLibraries().getLibrary(); @@ -100,7 +100,7 @@ protected void handleScript(Path filePath) if (TYPE.lib != primaryType) _suppliers.add(supplier); else - _log.error("Libraries cannot include other libraries: " + _filePath); + _log.error("Libraries cannot include other libraries: {}", _filePath); if (compileInProductionMode && mode != ModeTypeEnum.PRODUCTION) { @@ -128,7 +128,7 @@ protected void handleScript(Path filePath) } catch (Exception e) { - _log.error("Invalid client library XML file: " + _filePath + ". " + e.getMessage()); + _log.error("Invalid client library XML file: {}. {}", _filePath, e.getMessage()); } } } diff --git a/api/src/org/labkey/api/view/template/PageConfig.java b/api/src/org/labkey/api/view/template/PageConfig.java index e0e5722bc19..ffdcc20e5ee 100644 --- a/api/src/org/labkey/api/view/template/PageConfig.java +++ b/api/src/org/labkey/api/view/template/PageConfig.java @@ -664,7 +664,7 @@ private void _addHandler(EventHandler eh) { if (_eventHandlers.size() == MAX_EVENT_HANDLERS) { - LOG.error("Limit of " + MAX_EVENT_HANDLERS + " JavaScript event handlers reached. Subsequent handlers will be dropped. Current handler for " + eh.event + ": " + eh.handler); + LOG.error("Limit of " + MAX_EVENT_HANDLERS + " JavaScript event handlers reached. Subsequent handlers will be dropped. Current handler for {}: {}", eh.event, eh.handler); } var prev = _eventHandlers.put(eh.getKey(), eh); assert null == prev || prev.handler.equals(eh.handler) : "Duplicate handler registered. event:" + eh.getKey() + " handler:" + eh.handler(); @@ -737,7 +737,7 @@ public void endOfBodyScript(Writer out) throws IOException final String eventId = h.getKey(); EventHandler prev = eventMap.put(eventId, h); if (null != prev && !Strings.CS.equals(prev.handler, h.handler)) - LOG.error("Malformed page. Multiple JavaScript handlers defined for the same '#': " + eventId); + LOG.error("Malformed page. Multiple JavaScript handlers defined for the same '#': {}", eventId); } } diff --git a/api/src/org/labkey/api/webdav/AbstractDocumentResource.java b/api/src/org/labkey/api/webdav/AbstractDocumentResource.java index 9d259ae34fa..3fd59e3c39f 100644 --- a/api/src/org/labkey/api/webdav/AbstractDocumentResource.java +++ b/api/src/org/labkey/api/webdav/AbstractDocumentResource.java @@ -17,9 +17,6 @@ import org.labkey.api.util.Path; -import java.util.Collection; -import java.util.Collections; - /** * Base class for WebDav entities, typically backed by rows in the database, that are exposed * as if they are files. An example is a custom SQL query created through the schema browser, stored @@ -44,22 +41,4 @@ public boolean isFile() { return exists(); } - - @Override - public WebdavResource find(Path.Part name) - { - return null; - } - - @Override - public Collection listNames() - { - return Collections.emptyList(); - } - - @Override - public boolean isCollection() - { - return false; - } } diff --git a/api/src/org/labkey/api/webdav/AbstractWebdavResource.java b/api/src/org/labkey/api/webdav/AbstractWebdavResource.java index 0d4f3211d70..74462e6899d 100644 --- a/api/src/org/labkey/api/webdav/AbstractWebdavResource.java +++ b/api/src/org/labkey/api/webdav/AbstractWebdavResource.java @@ -159,7 +159,7 @@ public User getCreatedBy() if (data == null || data.isEmpty()) return null; - return data.get(0).getCreatedBy(); + return data.getFirst().getCreatedBy(); } @Override @@ -169,7 +169,7 @@ public String getDescription() if (data == null || data.isEmpty()) return null; - return data.get(0).getComment(); + return data.getFirst().getComment(); } @Override @@ -179,7 +179,7 @@ public User getModifiedBy() if (data == null || data.isEmpty()) return null; - return data.get(0).getModifiedBy(); + return data.getFirst().getModifiedBy(); } @Override diff --git a/api/src/org/labkey/api/webdav/AbstractWebdavResourceCollection.java b/api/src/org/labkey/api/webdav/AbstractWebdavResourceCollection.java index 1f71d6c0298..6e64b6372bf 100644 --- a/api/src/org/labkey/api/webdav/AbstractWebdavResourceCollection.java +++ b/api/src/org/labkey/api/webdav/AbstractWebdavResourceCollection.java @@ -61,12 +61,6 @@ public boolean isCollection() return exists(); } - @Override - public boolean isFile() - { - return false; - } - @Override public InputStream getInputStream(User user) { diff --git a/api/src/org/labkey/api/webdav/FileSystemResource.java b/api/src/org/labkey/api/webdav/FileSystemResource.java index 8a1b316a4f8..618e64e4d19 100644 --- a/api/src/org/labkey/api/webdav/FileSystemResource.java +++ b/api/src/org/labkey/api/webdav/FileSystemResource.java @@ -212,7 +212,7 @@ protected FileLike getFileLike() if (file.exists()) return file; } - return _files.get(0); + return _files.getFirst(); } @Override @@ -291,7 +291,7 @@ public long copyFrom(User user, FileStream is) throws IOException } catch (IOException x) { - _log.error("Couldn't create file on server: " + file.getPath(), x); + _log.error("Couldn't create file on server: {}", file.getPath(), x); throw new ConfigurationException("Couldn't create file on server", x); } } @@ -433,7 +433,7 @@ public boolean canRead(User user, boolean forRead) if (!f.canRead()) { SecurityLogger.log("File.canRead()==false",user,null,false); - _log.warn(user.getEmail() + " attempted to read file that is not readable by LabKey Server. This may be a configuration problem. file: " + f.getPath()); + _log.warn("{} attempted to read file that is not readable by LabKey Server. This may be a configuration problem. file: {}", user.getEmail(), f.getPath()); return false; } return canReadPerm; @@ -464,7 +464,7 @@ public boolean canWrite(User user, boolean forWrite) if (!f.canWrite()) { SecurityLogger.log("File.canWrite()==false",user,null,false); - _log.warn(user.getEmail() + " attempted to write file that is not readable by LabKey Server. This may be a configuration problem. file: " + f.getPath()); + _log.warn("{} attempted to write file that is not readable by LabKey Server. This may be a configuration problem. file: {}", user.getEmail(), f.getPath()); return false; } return canWritePerm; @@ -495,7 +495,7 @@ public boolean canCreate(User user, boolean forCreate) if (!f.canWrite()) { SecurityLogger.log("File.canWrite()==false",user,null,false); - _log.warn(user.getEmail() + " attempted to write file that is not readable by LabKey Server. This may be a configuration problem. file: " + f.getPath()); + _log.warn("{} attempted to write file that is not readable by LabKey Server. This may be a configuration problem. file: {}", user.getEmail(), f.getPath()); return false; } return canCreatePerm; @@ -524,7 +524,7 @@ public boolean canDelete(User user, boolean forDelete, @Nullable List me { if (null != message) message.add("File is not writable on server"); - _log.warn(user.getEmail() + " attempted to delete file that is not writable by LabKey Server. This may be a configuration problem. file: " + f.getPath()); + _log.warn("{} attempted to delete file that is not writable by LabKey Server. This may be a configuration problem. file: {}", user.getEmail(), f.getPath()); } return false; } @@ -596,7 +596,7 @@ public boolean delete(User user) } boolean deleted = file.delete(); if (!deleted) - _log.warn("Unexpected file system error, could not delete file: " + file.getPath()); + _log.warn("Unexpected file system error, could not delete file: {}", file.getPath()); return deleted; } @@ -690,7 +690,7 @@ public Map getCustomProperties(User user) if (rows.size() == 1) { - for (Map.Entry entry : rows.get(0).entrySet()) + for (Map.Entry entry : rows.getFirst().entrySet()) { Object value = entry.getValue(); @@ -708,7 +708,6 @@ public Map getCustomProperties(User user) { throw UnexpectedException.wrap(re); } - boolean b = false; } } diff --git a/api/src/org/labkey/api/webdav/WebdavResolverImpl.java b/api/src/org/labkey/api/webdav/WebdavResolverImpl.java index 58158074865..13f270cd4b1 100644 --- a/api/src/org/labkey/api/webdav/WebdavResolverImpl.java +++ b/api/src/org/labkey/api/webdav/WebdavResolverImpl.java @@ -23,7 +23,6 @@ import org.labkey.api.cache.CacheManager; import org.labkey.api.data.Container; import org.labkey.api.data.ContainerManager; -import org.labkey.api.query.ValidationException; import org.labkey.api.security.Group; import org.labkey.api.security.MutableSecurityPolicy; import org.labkey.api.security.SecurityManager; @@ -186,7 +185,7 @@ public static class TestCase extends Assert private Container testContainer = null; @Test - public void testContainers() throws ValidationException + public void testContainers() { TestContext context = TestContext.get(); User guest = UserManager.getGuestUser(); diff --git a/api/src/org/labkey/api/webdav/WebdavResource.java b/api/src/org/labkey/api/webdav/WebdavResource.java index 6279e575029..46121632467 100644 --- a/api/src/org/labkey/api/webdav/WebdavResource.java +++ b/api/src/org/labkey/api/webdav/WebdavResource.java @@ -15,8 +15,8 @@ */ package org.labkey.api.webdav; -import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; +import org.jetbrains.annotations.NotNull; import org.labkey.api.resource.Resource; import org.labkey.api.security.User; import org.labkey.api.util.FileStream; @@ -25,7 +25,6 @@ import org.labkey.api.view.NavTree; import org.labkey.api.view.ViewContext; import org.labkey.api.writer.ContainerUser; -import org.springframework.util.MimeType; import java.io.File; import java.io.FileNotFoundException; @@ -274,7 +273,7 @@ public boolean exists() } @Override - public URL getURL() throws IOException + public @NotNull URL getURL() throws IOException { // Nnot sure why getExceuteHref() takes a view context. We ay not need for the moment. var href = r.getExecuteHref(null); @@ -284,7 +283,7 @@ public URL getURL() throws IOException } @Override - public URI getURI() throws IOException + public @NotNull URI getURI() throws IOException { // Not sure why getExecuteHref() takes a view context. We ay not need for the moment. var href = r.getExecuteHref(null); @@ -301,7 +300,7 @@ public URI getURI() throws IOException } @Override - public File getFile() throws IOException + public @NotNull File getFile() throws IOException { // UnsupportedOperationException – if the resource is a file but cannot be exposed as a java.io.File; an alternative to FileNotFoundException // FileNotFoundException – if the resource cannot be resolved as a file @@ -324,7 +323,7 @@ public long lastModified() throws IOException } @Override - public org.springframework.core.io.Resource createRelative(String relativePath) throws IOException + public org.springframework.core.io.@NotNull Resource createRelative(@NotNull String relativePath) throws IOException { // do we need this? throw new UnsupportedOperationException(); @@ -337,13 +336,13 @@ public String getFilename() } @Override - public String getDescription() + public @NotNull String getDescription() { return r.getDescription(); } @Override - public InputStream getInputStream() throws IOException + public @NotNull InputStream getInputStream() throws IOException { // FileStream.openInputStream() enforces one stream per instance, so don't use 'fs' var filestream = r.getFileStream(user); diff --git a/api/src/org/labkey/api/webdav/WebdavResourceReadOnly.java b/api/src/org/labkey/api/webdav/WebdavResourceReadOnly.java index e5cdd8c3def..36065f5e890 100644 --- a/api/src/org/labkey/api/webdav/WebdavResourceReadOnly.java +++ b/api/src/org/labkey/api/webdav/WebdavResourceReadOnly.java @@ -304,7 +304,7 @@ public boolean delete(User user) } @Override - public boolean createCollection(User user) throws DavException + public boolean createCollection(User user) { return false; } diff --git a/api/src/org/labkey/api/websocket/BrowserEndpoint.java b/api/src/org/labkey/api/websocket/BrowserEndpoint.java index 1e4e6cf5df3..f0cabf43641 100644 --- a/api/src/org/labkey/api/websocket/BrowserEndpoint.java +++ b/api/src/org/labkey/api/websocket/BrowserEndpoint.java @@ -251,7 +251,7 @@ public void onMessage(String s, boolean last) if (to.isOpen()) to.getBasicRemote().sendText(s); } - LOG.trace(debugName + ".onMessage(" + s + ")"); + LOG.trace("{}.onMessage({})", debugName, s); } catch (IOException x) { @@ -269,7 +269,7 @@ public void onMessage(String s, boolean last) if (to.isOpen()) to.getBasicRemote().sendBinary(byteBuffer); } - LOG.trace(debugName + ".onMessage()"); + LOG.trace("{}.onMessage()", debugName); } catch (IOException x) { @@ -286,7 +286,7 @@ public void onMessage(String s, boolean last) if (to.isOpen()) to.getBasicRemote().sendPong(pongMessage.getApplicationData()); } - LOG.trace(debugName + ".pong()"); + LOG.trace("{}.pong()", debugName); } catch (IOException x) { diff --git a/api/src/org/labkey/api/wiki/WikiRendererDisplayColumn.java b/api/src/org/labkey/api/wiki/WikiRendererDisplayColumn.java index 1eb5e4edc94..ef78a47de97 100644 --- a/api/src/org/labkey/api/wiki/WikiRendererDisplayColumn.java +++ b/api/src/org/labkey/api/wiki/WikiRendererDisplayColumn.java @@ -82,7 +82,7 @@ public HtmlString getFormattedHtml(RenderContext ctx) } catch (IllegalArgumentException err) { - _log.error("Bad wiki renderer type: " + rendererTypeName, err); + _log.error("Bad wiki renderer type: {}", rendererTypeName, err); } } diff --git a/api/src/org/labkey/api/workflow/Job.java b/api/src/org/labkey/api/workflow/Job.java index 7765baf45d0..43cad00c68e 100644 --- a/api/src/org/labkey/api/workflow/Job.java +++ b/api/src/org/labkey/api/workflow/Job.java @@ -337,7 +337,7 @@ public Task getNextTask(long taskId) List subsequent = getSubsequentTasks(taskId); if (subsequent.isEmpty()) return null; - return subsequent.get(0); + return subsequent.getFirst(); } public boolean isComplete() diff --git a/api/src/org/labkey/api/writer/ZipUtil.java b/api/src/org/labkey/api/writer/ZipUtil.java index 864c68305c1..e59bdf2e5a2 100644 --- a/api/src/org/labkey/api/writer/ZipUtil.java +++ b/api/src/org/labkey/api/writer/ZipUtil.java @@ -134,7 +134,7 @@ public static List unzipToDirectory(InputStream is, Path unzipDir, @Nullab } if (null != log) - log.info("Expanding " + entry.getName()); + log.info("Expanding {}", entry.getName()); FileUtil.createDirectories(destFile.getParent()); if (Files.exists(destFile)) diff --git a/api/src/org/labkey/vfs/FileSystemLike.java b/api/src/org/labkey/vfs/FileSystemLike.java index 072e462566f..fcb737f113c 100644 --- a/api/src/org/labkey/vfs/FileSystemLike.java +++ b/api/src/org/labkey/vfs/FileSystemLike.java @@ -1,8 +1,6 @@ package org.labkey.vfs; import com.fasterxml.jackson.databind.DeserializationContext; -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; import org.labkey.api.cloud.CloudStoreService; import org.labkey.api.collections.CaseInsensitiveHashMap; import org.labkey.api.data.Container; diff --git a/api/src/org/mitre/dsmiley/httpproxy/LabKeyProxyServlet.java b/api/src/org/mitre/dsmiley/httpproxy/LabKeyProxyServlet.java index 0d39813bb8c..9d41c8a5d91 100644 --- a/api/src/org/mitre/dsmiley/httpproxy/LabKeyProxyServlet.java +++ b/api/src/org/mitre/dsmiley/httpproxy/LabKeyProxyServlet.java @@ -116,10 +116,10 @@ protected String rewriteUrlFromResponse(HttpServletRequest servletRequest, Strin //TODO document example paths String targetUri = getTargetUri(servletRequest); - LOG.info("theUrl: " + theUrl); - LOG.info("getTargetUri(servletRequest): " + getTargetUri(servletRequest)); - LOG.info("getTargetHost(servletRequest): " + getTargetHost(servletRequest)); - LOG.info("servletRequest.getRequestURL(): " + servletRequest.getRequestURL()); + LOG.info("theUrl: {}", theUrl); + LOG.info("getTargetUri(servletRequest): {}", getTargetUri(servletRequest)); + LOG.info("getTargetHost(servletRequest): {}", getTargetHost(servletRequest)); + LOG.info("servletRequest.getRequestURL(): {}", servletRequest.getRequestURL()); if (flexRedirectProtocol && theUrl.startsWith("https://localhost:") && targetUri.startsWith("http://localhost:")) { @@ -156,7 +156,7 @@ protected String rewriteUrlFromResponse(HttpServletRequest servletRequest, Strin //Issue 42677: 404 Error when initiating a Jupyter Notebook session from RStudio Pro when integrated with LabKey // jupyter notebook redirect url contains context and servlet path, resulting in duplicate path String sourcePath = getSourcePath(servletRequest); - LOG.info("getSourcePath(servletRequest): " + getSourcePath(servletRequest)); + LOG.info("getSourcePath(servletRequest): {}", getSourcePath(servletRequest)); if (!theUrl.startsWith(sourcePath)) curUrl.append(sourcePath); diff --git a/api/src/org/mitre/dsmiley/httpproxy/ProxyServlet.java b/api/src/org/mitre/dsmiley/httpproxy/ProxyServlet.java index a1b2fe13fa3..996586df030 100644 --- a/api/src/org/mitre/dsmiley/httpproxy/ProxyServlet.java +++ b/api/src/org/mitre/dsmiley/httpproxy/ProxyServlet.java @@ -389,7 +389,7 @@ protected void service(HttpServletRequest servletRequest, HttpServletResponse se copyResponseEntity(proxyResponse, servletResponse, proxyRequest, servletRequest); } } catch (Exception e) { - handleRequestException(proxyRequest, proxyResponse, e); + handleRequestException(proxyResponse, e); } finally { // make sure the entire entity was consumed, so the connection is released if (proxyResponse != null) @@ -399,7 +399,7 @@ protected void service(HttpServletRequest servletRequest, HttpServletResponse se } } - protected void handleRequestException(HttpRequest proxyRequest, HttpResponse proxyResponse, Exception e) throws ServletException, IOException { + protected void handleRequestException(HttpResponse proxyResponse, Exception e) throws IOException { // LKS override // Note: We used to "abort" the request, but that doesn't seem possible anymore @@ -628,9 +628,9 @@ protected String buildProxyCookiePath(HttpServletRequest servletRequest) { */ protected String getRealCookie(String cookieValue) { StringBuilder escapedCookie = new StringBuilder(); - String cookies[] = cookieValue.split("[;,]"); + String[] cookies = cookieValue.split("[;,]"); for (String cookie : cookies) { - String cookieSplit[] = cookie.split("="); + String[] cookieSplit = cookie.split("="); if (cookieSplit.length == 2) { String cookieName = cookieSplit[0].trim(); if (cookieName.startsWith(getCookieNamePrefix(cookieName))) { diff --git a/assay/api-src/org/labkey/api/assay/AssayBatchDomainKind.java b/assay/api-src/org/labkey/api/assay/AssayBatchDomainKind.java index c9389967fe3..890cfec7691 100644 --- a/assay/api-src/org/labkey/api/assay/AssayBatchDomainKind.java +++ b/assay/api-src/org/labkey/api/assay/AssayBatchDomainKind.java @@ -16,7 +16,6 @@ package org.labkey.api.assay; import org.jetbrains.annotations.NotNull; -import org.labkey.api.collections.CaseInsensitiveHashSet; import org.labkey.api.exp.api.ExpProtocol; import org.labkey.api.exp.property.Domain; import org.labkey.api.exp.property.DomainUtil; diff --git a/assay/api-src/org/labkey/api/assay/AssayDomainKind.java b/assay/api-src/org/labkey/api/assay/AssayDomainKind.java index 582a4d43565..b86c33d24fe 100644 --- a/assay/api-src/org/labkey/api/assay/AssayDomainKind.java +++ b/assay/api-src/org/labkey/api/assay/AssayDomainKind.java @@ -20,7 +20,6 @@ import org.jetbrains.annotations.Nullable; import org.json.JSONObject; import org.labkey.api.assay.security.DesignAssayPermission; -import org.labkey.api.collections.CaseInsensitiveHashSet; import org.labkey.api.data.Container; import org.labkey.api.data.ContainerFilter; import org.labkey.api.data.SQLFragment; diff --git a/assay/api-src/org/labkey/api/assay/AssayResultUpdateService.java b/assay/api-src/org/labkey/api/assay/AssayResultUpdateService.java index 4a765e5aa81..9d20226f47c 100644 --- a/assay/api-src/org/labkey/api/assay/AssayResultUpdateService.java +++ b/assay/api-src/org/labkey/api/assay/AssayResultUpdateService.java @@ -33,7 +33,6 @@ import org.labkey.api.dataiterator.DataIteratorContext; import org.labkey.api.dataiterator.DataIteratorUtil; import org.labkey.api.dataiterator.MapDataIterator; -import org.labkey.api.exp.ExperimentException; import org.labkey.api.exp.OntologyManager; import org.labkey.api.exp.OntologyObject; import org.labkey.api.exp.api.ExpData; @@ -154,7 +153,7 @@ private List> transform( ColumnInfo keyCol = null; for (ColumnInfo colInfo : getDbTable().getPkColumns()) { - if (rows.get(0).containsKey(colInfo.getName())) + if (rows.getFirst().containsKey(colInfo.getName())) { keyCol = colInfo; break; @@ -336,7 +335,7 @@ protected Map deleteRow( Map oldRowMap, @Nullable Map configParameters, @Nullable Map extraScriptContext - ) throws InvalidKeyException, ValidationException, QueryUpdateServiceException, SQLException + ) throws InvalidKeyException, QueryUpdateServiceException, SQLException { ExpRun run = getRun(oldRowMap, user, DeletePermission.class); @@ -511,7 +510,7 @@ public Long getReRunId() } @Override - public void uploadComplete(ExpRun run) throws ExperimentException + public void uploadComplete(ExpRun run) { } diff --git a/assay/api-src/org/labkey/api/assay/AssayRunDomainKind.java b/assay/api-src/org/labkey/api/assay/AssayRunDomainKind.java index 0d3f46c04ee..2915b7a10d6 100644 --- a/assay/api-src/org/labkey/api/assay/AssayRunDomainKind.java +++ b/assay/api-src/org/labkey/api/assay/AssayRunDomainKind.java @@ -17,7 +17,6 @@ import org.jetbrains.annotations.NotNull; import org.labkey.api.assay.plate.AssayPlateMetadataService; -import org.labkey.api.collections.CaseInsensitiveHashSet; import org.labkey.api.exp.api.ExpProtocol; import org.labkey.api.exp.property.Domain; import org.labkey.api.exp.property.DomainUtil; diff --git a/assay/api-src/org/labkey/api/assay/actions/PlateBasedUploadWizardAction.java b/assay/api-src/org/labkey/api/assay/actions/PlateBasedUploadWizardAction.java index d21c2af8d6e..cc0eafffe55 100644 --- a/assay/api-src/org/labkey/api/assay/actions/PlateBasedUploadWizardAction.java +++ b/assay/api-src/org/labkey/api/assay/actions/PlateBasedUploadWizardAction.java @@ -29,7 +29,7 @@ import org.springframework.validation.ObjectError; import jakarta.servlet.ServletException; -import java.sql.SQLException; + import java.util.Map; /** @@ -92,7 +92,7 @@ public void validateStep(FormType form, Errors errors) } @Override - public boolean executeStep(FormType form, BindException errors) throws ServletException, SQLException, ExperimentException + public boolean executeStep(FormType form, BindException errors) throws ServletException, ExperimentException { form.setSampleProperties(_postedSampleProperties); for (Map.Entry> entry : _postedSampleProperties.entrySet()) diff --git a/assay/api-src/org/labkey/api/assay/dilution/AbstractDilutionAssayProvider.java b/assay/api-src/org/labkey/api/assay/dilution/AbstractDilutionAssayProvider.java index 6171b374f78..8c3c1a2d258 100644 --- a/assay/api-src/org/labkey/api/assay/dilution/AbstractDilutionAssayProvider.java +++ b/assay/api-src/org/labkey/api/assay/dilution/AbstractDilutionAssayProvider.java @@ -112,22 +112,12 @@ protected Pair> createSampleWellGroupDomain( protected Map> getRequiredDomainProperties() { Map> domainMap = super.getRequiredDomainProperties(); - Set sampleProperties = domainMap.get(ASSAY_DOMAIN_SAMPLE_WELLGROUP); - if (sampleProperties == null) - { - sampleProperties = new HashSet<>(); - domainMap.put(ASSAY_DOMAIN_SAMPLE_WELLGROUP, sampleProperties); - } + Set sampleProperties = domainMap.computeIfAbsent(ASSAY_DOMAIN_SAMPLE_WELLGROUP, _ -> new HashSet<>()); sampleProperties.add(SAMPLE_INITIAL_DILUTION_PROPERTY_NAME); sampleProperties.add(SAMPLE_DILUTION_FACTOR_PROPERTY_NAME); sampleProperties.add(SAMPLE_METHOD_PROPERTY_NAME); - Set runProperties = domainMap.get(ExpProtocol.ASSAY_DOMAIN_RUN); - if (runProperties == null) - { - runProperties = new HashSet<>(); - domainMap.put(ExpProtocol.ASSAY_DOMAIN_RUN, runProperties); - } + Set runProperties = domainMap.computeIfAbsent(ExpProtocol.ASSAY_DOMAIN_RUN, _ -> new HashSet<>()); runProperties.add(CURVE_FIT_METHOD_PROPERTY_NAME); runProperties.add(CUTOFF_PROPERTIES[0]); diff --git a/assay/api-src/org/labkey/api/assay/dilution/DilutionDataHandler.java b/assay/api-src/org/labkey/api/assay/dilution/DilutionDataHandler.java index e4eabafa1ff..4cdb440b8db 100644 --- a/assay/api-src/org/labkey/api/assay/dilution/DilutionDataHandler.java +++ b/assay/api-src/org/labkey/api/assay/dilution/DilutionDataHandler.java @@ -67,8 +67,6 @@ import org.labkey.api.view.ViewBackgroundInfo; import org.labkey.vfs.FileLike; -import java.io.File; -import java.sql.SQLException; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; @@ -297,7 +295,7 @@ public FileLike getDataFile(ExpRun run) List outputDatas = run.getOutputDatas(getDataType()); if (outputDatas == null || outputDatas.size() != 1) throw new IllegalStateException(getResourceName(run) + " runs should have a single data output."); - FileLike dataFile = outputDatas.get(0).getFileLike(); + FileLike dataFile = outputDatas.getFirst().getFileLike(); if (!dataFile.exists()) return null; return dataFile; @@ -447,7 +445,7 @@ else if (method == SampleInfoMethod.Concentration) protected Map> getMaterialWellGroupMapping(DilutionAssayProvider provider, List plates, Map sampleInputs)throws ExperimentException { - Plate plate = plates.get(0); + Plate plate = plates.getFirst(); List wellgroups = plate.getWellGroups(WellGroup.Type.SPECIMEN); Map nameToMaterial = new HashMap<>(); for (Map.Entry e : sampleInputs.entrySet()) @@ -471,7 +469,7 @@ protected Map> getMaterialWellGroupMapping(Dilution protected abstract DilutionAssayRun createDilutionAssayRun(DilutionAssayProvider provider, ExpRun run, List plates, User user, List sortedCutoffs, StatsService.CurveFitType fit); - public abstract Map getDilutionSummaries(User user, StatsService.CurveFitType fit, long... dataObjectIds) throws ExperimentException, SQLException; + public abstract Map getDilutionSummaries(User user, StatsService.CurveFitType fit, long... dataObjectIds) throws ExperimentException; final protected DilutionDataFileParser getDataFileParser(ExpData data, FileLike dataFile, ViewBackgroundInfo info) { diff --git a/assay/api-src/org/labkey/api/assay/dilution/DilutionManager.java b/assay/api-src/org/labkey/api/assay/dilution/DilutionManager.java index 5617d9622ec..04570c14d30 100644 --- a/assay/api-src/org/labkey/api/assay/dilution/DilutionManager.java +++ b/assay/api-src/org/labkey/api/assay/dilution/DilutionManager.java @@ -44,7 +44,6 @@ import org.labkey.api.security.User; import java.sql.SQLException; -import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashMap; @@ -228,7 +227,7 @@ private NabSpecimen getNabSpecimen(Filter filter) TableInfo tableInfo = getSchema().getTable(NAB_SPECIMEN_TABLE_NAME); List nabSpecimens = new TableSelector(tableInfo, filter, null).getArrayList(NabSpecimen.class); if (!nabSpecimens.isEmpty()) - return nabSpecimens.get(0); + return nabSpecimens.getFirst(); return null; } diff --git a/assay/api-src/org/labkey/api/assay/dilution/DilutionSummary.java b/assay/api-src/org/labkey/api/assay/dilution/DilutionSummary.java index e0de9c69dd7..56493aa841c 100644 --- a/assay/api-src/org/labkey/api/assay/dilution/DilutionSummary.java +++ b/assay/api-src/org/labkey/api/assay/dilution/DilutionSummary.java @@ -68,7 +68,7 @@ public DilutionSummary(Luc5Assay assay, List sampleGroups, String lsi ensureSameSample(sampleGroups); _curveFitType = curveFitType; _sampleGroups = sampleGroups; - _firstGroup = sampleGroups.get(0); + _firstGroup = sampleGroups.getFirst(); _assay = assay; _lsid = lsid; _container = container; @@ -76,8 +76,8 @@ public DilutionSummary(Luc5Assay assay, List sampleGroups, String lsi private void ensureSameSample(List groups) { - String templateName = groups.get(0).getPlate().getName(); - String wellgroupName = groups.get(0).getName(); + String templateName = groups.getFirst().getPlate().getName(); + String wellgroupName = groups.getFirst().getName(); for (int groupIndex = 1; groupIndex < groups.size(); groupIndex++) { if (!templateName.equals(groups.get(groupIndex).getPlate().getName())) diff --git a/assay/api-src/org/labkey/api/assay/dilution/query/DilutionProviderSchema.java b/assay/api-src/org/labkey/api/assay/dilution/query/DilutionProviderSchema.java index f030f4badec..e1d84651d4a 100644 --- a/assay/api-src/org/labkey/api/assay/dilution/query/DilutionProviderSchema.java +++ b/assay/api-src/org/labkey/api/assay/dilution/query/DilutionProviderSchema.java @@ -33,7 +33,6 @@ import org.labkey.api.assay.AssayService; import java.util.ArrayList; -import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; diff --git a/assay/api-src/org/labkey/api/assay/matrix/AbstractMatrixDataHandler.java b/assay/api-src/org/labkey/api/assay/matrix/AbstractMatrixDataHandler.java index 49e48917095..fec8a0c6251 100644 --- a/assay/api-src/org/labkey/api/assay/matrix/AbstractMatrixDataHandler.java +++ b/assay/api-src/org/labkey/api/assay/matrix/AbstractMatrixDataHandler.java @@ -173,7 +173,7 @@ public static Map ensureSamples(Container container, User u sampleNames.add(name); } } - LOG.debug("All samples in matrix: " + StringUtils.join(sampleNames, ", ")); + LOG.debug("All samples in matrix: {}", StringUtils.join(sampleNames, ", ")); Set unresolved = new HashSet<>(); Map sampleMap = new HashMap<>(sampleNames.size()); @@ -266,7 +266,7 @@ private static List createExpMaterials(Container c, User } else if (sampleTypes.size() == 1) { - return sampleTypes.get(0); + return sampleTypes.getFirst(); } else { @@ -279,16 +279,9 @@ else if (sampleTypes.size() == 1) // Create a new SampleSet in the current container List properties = new ArrayList<>(); properties.add(new GWTPropertyDescriptor("Name", "http://www.w3.org/2001/XMLSchema#string")); - try - { - ExpSampleType sampleType = SampleTypeService.get().createSampleType(c, user, "Samples", null, properties, emptyList(), -1, -1, -1, -1, "${Name}"); - LOG.info("Created new SampleType in " + c.getName() + ": " + sampleType.getLSID()); - return sampleType; - } - catch (SQLException e) - { - throw new RuntimeSQLException(e); - } + ExpSampleType sampleType = SampleTypeService.get().createSampleType(c, user, "Samples", null, properties, emptyList(), -1, -1, -1, -1, "${Name}"); + LOG.info("Created new SampleType in {}: {}", c.getName(), sampleType.getLSID()); + return sampleType; } public Map getRunPropertyValues(ExpRun run, Domain domain) diff --git a/assay/api-src/org/labkey/api/assay/nab/RenderAssayBean.java b/assay/api-src/org/labkey/api/assay/nab/RenderAssayBean.java index abcddfd6674..f238b1ef5c2 100644 --- a/assay/api-src/org/labkey/api/assay/nab/RenderAssayBean.java +++ b/assay/api-src/org/labkey/api/assay/nab/RenderAssayBean.java @@ -133,7 +133,7 @@ public Map getRunDisplayProperties() List qcFlags = AssayService.get().getFlags(_assay.getProvider(), getRunId(), ExpQCFlag.class); if (!qcFlags.isEmpty()) { - ExpQCFlag flag = qcFlags.iterator().next(); + ExpQCFlag flag = qcFlags.getFirst(); User user = UserManager.getUser(flag.getModifiedBy()); if (user != null) { @@ -231,7 +231,7 @@ public QueryView getDuplicateDataFileView(ViewContext context) return new DuplicateDataFileRunView(schema, setting, _assay, _assay.getRun()); } else - LOG.error("The assay: '" + _assay.getProtocol().getName() + "' run: " + _assay.getRun().getRowId() + " folder: '" + context.getContainer().getPath() + "' uses a data file by the same name as other runs but the data file could not be found"); + LOG.error("The assay: '{}' run: {} folder: '{}' uses a data file by the same name as other runs but the data file could not be found", _assay.getProtocol().getName(), _assay.getRun().getRowId(), context.getContainer().getPath()); } return null; diff --git a/assay/api-src/org/labkey/api/assay/nab/view/RunDetailsHeaderView.java b/assay/api-src/org/labkey/api/assay/nab/view/RunDetailsHeaderView.java index ba23ff8d6e0..352014f1094 100644 --- a/assay/api-src/org/labkey/api/assay/nab/view/RunDetailsHeaderView.java +++ b/assay/api-src/org/labkey/api/assay/nab/view/RunDetailsHeaderView.java @@ -15,7 +15,6 @@ */ package org.labkey.api.assay.nab.view; -import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.math.NumberUtils; import org.labkey.api.assay.dilution.DilutionAssayProvider; import org.labkey.api.assay.dilution.DilutionAssayRun; diff --git a/assay/api-src/org/labkey/api/assay/plate/PlateBasedRunCreator.java b/assay/api-src/org/labkey/api/assay/plate/PlateBasedRunCreator.java index 9872724fce5..a0602693625 100644 --- a/assay/api-src/org/labkey/api/assay/plate/PlateBasedRunCreator.java +++ b/assay/api-src/org/labkey/api/assay/plate/PlateBasedRunCreator.java @@ -46,7 +46,6 @@ import org.labkey.api.view.ViewBackgroundInfo; import org.labkey.vfs.FileLike; -import java.io.File; import java.util.Arrays; import java.util.Collections; import java.util.Date; @@ -256,7 +255,7 @@ private Map createDerivedMaterials(AssayRunUploadContext { List applications = derivationRun.getProtocolApplications(); assert applications.size() == 3 : "Expected three protocol applications in each sample derivation run."; - ExpProtocolApplication firstApplication = applications.get(0); + ExpProtocolApplication firstApplication = applications.getFirst(); assert firstApplication.getApplicationType() == ExpProtocol.ApplicationType.ExperimentRun : "Expected first protocol application to be of type ExperimentRun."; firstApplication.addDataInput(context.getUser(), sampleMetadataFile, AbstractPlateBasedAssayProvider.SAMPLE_METADATA_INPUT_ROLE); diff --git a/assay/api-src/org/labkey/api/assay/plate/PlateLayoutHandler.java b/assay/api-src/org/labkey/api/assay/plate/PlateLayoutHandler.java index 8a4c1e0ee1f..46f8c870ace 100644 --- a/assay/api-src/org/labkey/api/assay/plate/PlateLayoutHandler.java +++ b/assay/api-src/org/labkey/api/assay/plate/PlateLayoutHandler.java @@ -22,7 +22,6 @@ import org.labkey.api.query.ValidationException; import org.labkey.api.security.User; -import java.sql.SQLException; import java.util.List; import java.util.Map; @@ -39,7 +38,7 @@ public interface PlateLayoutHandler * createPlate will be given a null value for plateName when it is creating a new plate which is a * default for that assay type. */ - Plate createPlate(@Nullable String plateName, Container container, @NotNull PlateType plateType) throws SQLException; + Plate createPlate(@Nullable String plateName, Container container, @NotNull PlateType plateType); List getSupportedPlateTypes(); diff --git a/assay/api-src/org/labkey/api/assay/plate/PlateService.java b/assay/api-src/org/labkey/api/assay/plate/PlateService.java index b55634aa859..082865b759c 100644 --- a/assay/api-src/org/labkey/api/assay/plate/PlateService.java +++ b/assay/api-src/org/labkey/api/assay/plate/PlateService.java @@ -240,7 +240,6 @@ static PlateService get() * @param percentCalculator A callback to allow the caller to determine the plottable value for a given WellData within its WellGroup. * @param type The Type of fit desired. * @return A DilutionCurve instance of the appropriate type, if a fit was possible. - * @throws FitFailedException Thrown if a curve cannot be fit to the data points. */ DilutionCurve getDilutionCurve(List wellGroups, boolean assumeDecreasing, DilutionCurve.PercentCalculator percentCalculator, StatsService.CurveFitType type) throws FitFailedException; diff --git a/assay/api-src/org/labkey/api/assay/plate/PlateUtils.java b/assay/api-src/org/labkey/api/assay/plate/PlateUtils.java index 40c0c8ab60a..1304a6c80b8 100644 --- a/assay/api-src/org/labkey/api/assay/plate/PlateUtils.java +++ b/assay/api-src/org/labkey/api/assay/plate/PlateUtils.java @@ -25,7 +25,6 @@ import org.labkey.api.query.ValidationException; import org.labkey.vfs.FileLike; -import java.io.File; import java.util.ArrayList; import java.util.Collections; import java.util.List; @@ -88,7 +87,7 @@ public static List parseAllGrids(FileLike dataFile, List _parseGrids( matrix = parseGridAt(rows, loc.getRow(), loc.getCol(), expectedRows, expectedCols, reader); if (matrix != null) { - LOG.debug(String.format("found labeled grid style plate data at (%d,%d) in %s", rowIdx+1, colIdx+1, dataFile.getName())); + LOG.debug("found labeled grid style plate data at ({},{}) in {}", rowIdx + 1, colIdx + 1, dataFile.getName()); gridList.add(new GridInfo(matrix, parseGridAnnotations(rows, prevGridIdx, loc.getRow()-1))); if (!parseAllGrids) return gridList; @@ -144,7 +143,7 @@ else if (value instanceof String) matrix = parseGridAt(rows, loc.getRow(), loc.getCol(), expectedRows, expectedCols, reader); if (matrix != null) { - LOG.debug(String.format("found SpectraMax grid style plate data at (%d,%d) in %s", rowIdx+1, colIdx+1, dataFile.getName())); + LOG.debug("found SpectraMax grid style plate data at ({},{}) in {}", rowIdx + 1, colIdx + 1, dataFile.getName()); gridList.add(new GridInfo(matrix, parseGridAnnotations(rows, prevGridIdx, loc.getRow()-1))); if (!parseAllGrids) return gridList; @@ -202,7 +201,7 @@ private static List parseGridAnnotations(List> rows, if (row instanceof RowMap rowMap) { List values = rowMap.values().stream().filter(o -> o instanceof String str && !str.isBlank()).toList(); - if (values.size() == 1 && values.get(0) instanceof String strValue) + if (values.size() == 1 && values.getFirst() instanceof String strValue) annotations.add(strValue.trim()); } } @@ -246,7 +245,7 @@ public static double[][] parseGridAt(List> rows, int startRo // Check if this is a header row (numbered 1 through 12) // If it is, shift down one row and attempt to parse that. // If there is no header row or adding an additional row of numbers fails, accept the data as is. - if (isSequentialNumbers(values.get(0))) + if (isSequentialNumbers(values.getFirst())) { if (startRow + expectedRows + 1 <= rows.size()) { @@ -340,29 +339,30 @@ public static double[] parseRowAt(RowMap rowMap, int startCol, int expec // Get the value at the location and convert a double if possible. // If the value is not null or a number, stop parsing. Object value = rowMap.get(startCol + j); - if (value == null) - cells[j] = reader != null ? reader.getEmptyWellValue() : 0.0d; - else if (value instanceof String) + switch (value) { - try + case null -> cells[j] = reader != null ? reader.getEmptyWellValue() : 0.0d; + case String s -> { - if (reader != null) - cells[j] = reader.convertWellValue((String)value); - else - cells[j] = Double.parseDouble((String) value); + try + { + if (reader != null) + cells[j] = reader.convertWellValue(s); + else + cells[j] = Double.parseDouble(s); + } + catch (ValidationException | NumberFormatException e) + { + // failed + return null; + } } - catch (ValidationException | NumberFormatException e) + case Number number -> cells[j] = number.doubleValue(); + default -> { - // failed return null; } } - else if (value instanceof Number) - { - cells[j] = ((Number)value).doubleValue(); - } - else - return null; } return cells; @@ -444,19 +444,19 @@ public void testGetGridAnnotation() factory.getRowMap(Map.of("column0", "", "column1", "")), factory.getRowMap(Map.of("column0", "Plate1", "column1", "1"))), 0, 1); assertEquals("One grid annotation expected", 1, annotations.size()); - assertEquals("Annotation was not found", "Plate1", annotations.get(0)); + assertEquals("Annotation was not found", "Plate1", annotations.getFirst()); annotations = parseGridAnnotations(List.of( factory.getRowMap(Map.of("column0", "Plate1", "column1", "")), factory.getRowMap(Map.of("column0", "", "column1", "1"))), 0, 1); assertEquals("One grid annotation expected", 1, annotations.size()); - assertEquals("Annotation was not found", "Plate1", annotations.get(0)); + assertEquals("Annotation was not found", "Plate1", annotations.getFirst()); annotations = parseGridAnnotations(List.of( factory.getRowMap(Map.of("column0", "", "column1", "Plate1")), factory.getRowMap(Map.of("column0", "", "column1", "1"))), 0, 1); assertEquals("One grid annotation expected", 1, annotations.size()); - assertEquals("Annotation was not found", "Plate1", annotations.get(0)); + assertEquals("Annotation was not found", "Plate1", annotations.getFirst()); annotations = parseGridAnnotations(List.of( factory.getRowMap(Map.of("column0", "", "column1", "Measure")), diff --git a/assay/api-src/org/labkey/api/assay/plate/WellGroup.java b/assay/api-src/org/labkey/api/assay/plate/WellGroup.java index 5e21245c5c8..ed972b7f15c 100644 --- a/assay/api-src/org/labkey/api/assay/plate/WellGroup.java +++ b/assay/api-src/org/labkey/api/assay/plate/WellGroup.java @@ -17,10 +17,8 @@ package org.labkey.api.assay.plate; import org.apache.commons.lang3.StringUtils; -import org.jetbrains.annotations.Nullable; import org.labkey.api.exp.Identifiable; import org.labkey.api.study.PropertySet; -import org.labkey.api.view.ActionURL; import java.util.List; import java.util.Set; @@ -80,12 +78,6 @@ default void setPositions(List positions) String getPositionDescription(); - @Override - default @Nullable ActionURL detailsURL() - { - return null; - } - default boolean isZone() { return StringUtils.isEmpty(getName()); diff --git a/assay/src/org/labkey/api/assay/nab/view/controlSummary.jsp b/assay/src/org/labkey/api/assay/nab/view/controlSummary.jsp index 1cf23171104..2d17f41d000 100644 --- a/assay/src/org/labkey/api/assay/nab/view/controlSummary.jsp +++ b/assay/src/org/labkey/api/assay/nab/view/controlSummary.jsp @@ -62,7 +62,7 @@ } else { - Plate plate = assay.getPlates().get(0); + Plate plate = assay.getPlates().getFirst(); if (virusNames.isEmpty()) { %> diff --git a/assay/src/org/labkey/api/assay/nab/view/sampleProperties.jsp b/assay/src/org/labkey/api/assay/nab/view/sampleProperties.jsp index dfa8d65ebd7..a6eff83cb1b 100644 --- a/assay/src/org/labkey/api/assay/nab/view/sampleProperties.jsp +++ b/assay/src/org/labkey/api/assay/nab/view/sampleProperties.jsp @@ -81,7 +81,7 @@ <% - for (PropertyDescriptor pd : sampleData.get(0).keySet()) + for (PropertyDescriptor pd : sampleData.getFirst().keySet()) { if (!pdsWithData.contains(pd.getName())) continue; @@ -95,7 +95,7 @@ <% - for (PropertyDescriptor pd : sampleData.get(0).keySet()) + for (PropertyDescriptor pd : sampleData.getFirst().keySet()) { if (!pdsWithData.contains(pd.getName())) continue; diff --git a/assay/src/org/labkey/assay/AssayBatchDocumentProvider.java b/assay/src/org/labkey/assay/AssayBatchDocumentProvider.java index 723d70ee7d3..e52ffb9c79c 100644 --- a/assay/src/org/labkey/assay/AssayBatchDocumentProvider.java +++ b/assay/src/org/labkey/assay/AssayBatchDocumentProvider.java @@ -4,7 +4,6 @@ import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.labkey.api.collections.LongHashMap; -import org.labkey.api.data.Container; import org.labkey.api.exp.api.ExpExperiment; import org.labkey.api.exp.api.ExperimentJSONConverter; import org.labkey.api.exp.api.ExperimentService; diff --git a/assay/src/org/labkey/assay/AssayController.java b/assay/src/org/labkey/assay/AssayController.java index db0af234600..4a894e88402 100644 --- a/assay/src/org/labkey/assay/AssayController.java +++ b/assay/src/org/labkey/assay/AssayController.java @@ -1254,7 +1254,7 @@ public String getBatchIdFilterParam() // Unfortunately this seems to be the best way to figure out the name of the URL parameter to filter by batch id ActionURL fakeURL = new ActionURL(ShowSelectedRunsAction.class, ContainerManager.getHomeContainer()); fakeURL.addFilter(AssayProtocolSchema.RUNS_TABLE_NAME, AbstractAssayProvider.BATCH_ROWID_FROM_RUN, CompareType.EQUAL, "${RowId}"); - return fakeURL.getParameters().get(0).getKey(); + return fakeURL.getParameters().getFirst().getKey(); } } diff --git a/assay/src/org/labkey/assay/AssayFilesResourceProvider.java b/assay/src/org/labkey/assay/AssayFilesResourceProvider.java index 7a9da3090d0..0aa49449069 100644 --- a/assay/src/org/labkey/assay/AssayFilesResourceProvider.java +++ b/assay/src/org/labkey/assay/AssayFilesResourceProvider.java @@ -1,9 +1,9 @@ package org.labkey.assay; +import org.jetbrains.annotations.NotNull; import org.labkey.api.attachments.AttachmentDirectory; import org.labkey.api.data.Container; import org.labkey.api.files.FileContentService; -import org.labkey.api.files.MissingRootDirectoryException; import org.labkey.api.security.SecurableResource; import org.labkey.api.security.User; import org.labkey.api.security.permissions.AdminPermission; @@ -25,7 +25,7 @@ public class AssayFilesResourceProvider implements WebdavService.Provider { @Override - public Set addChildren(WebdavResource target, boolean isListing) + public Set addChildren(@NotNull WebdavResource target, boolean isListing) { if (!(target instanceof WebdavResolverImpl.WebFolderResource folder)) return null; @@ -50,7 +50,7 @@ public Set addChildren(WebdavResource target, boolean isListing) } @Override - public WebdavResource resolve(WebdavResource parent, String name) + public WebdavResource resolve(@NotNull WebdavResource parent, @NotNull String name) { if (!FileContentService.ASSAY_FILES.equalsIgnoreCase(name)) return null; @@ -77,10 +77,7 @@ public WebdavResource resolve(WebdavResource parent, String name) return new AssayFilesResource(parent, Path.toPathPart(name), dir.getFileSystemDirectory(), c); } } - catch (MissingRootDirectoryException e) - { - // Don't complain here, just hide the @assayfiles subfolder - } + // Don't complain here, just hide the @assayfiles subfolder catch (RuntimeException e) { // Don't complain here if AccessDeniedException, just hide the @scripts subfolder (Issue 50212) diff --git a/assay/src/org/labkey/assay/AssayIntegrationTestCase.jsp b/assay/src/org/labkey/assay/AssayIntegrationTestCase.jsp index ef861a19ca8..cb7e846a345 100644 --- a/assay/src/org/labkey/assay/AssayIntegrationTestCase.jsp +++ b/assay/src/org/labkey/assay/AssayIntegrationTestCase.jsp @@ -340,7 +340,7 @@ // verify the exp.data is attached to the run assertEquals(1, run.getDataOutputs().size()); - final ExpData originalOutputData = run.getDataOutputs().get(0); + final ExpData originalOutputData = run.getDataOutputs().getFirst(); assertEquals(file.getName(), originalOutputData.getName()); final long dataRowId = originalOutputData.getRowId(); @@ -479,7 +479,7 @@ // and that it has the same dataFileUrl as the input file var dataOutputs = assayRun.getDataOutputs(); assertEquals(1, dataOutputs.size()); - var assayOutputData = dataOutputs.get(0); + var assayOutputData = dataOutputs.getFirst(); assertNotEquals(firstData, assayOutputData); assertEquals(firstData.getDataFileUrl(), assayOutputData.getDataFileUrl()); @@ -491,7 +491,7 @@ log.info("delete the run and verify the duplicate exp.data was also deleted"); assayRun.delete(user); dataList = ExperimentService.get().getAllExpDataByURL(firstData.getDataFileUrl(), null); - assertEquals(firstData, dataList.get(0)); + assertEquals(firstData, dataList.getFirst()); assertEquals(1, dataList.size()); } diff --git a/assay/src/org/labkey/assay/AssayManager.java b/assay/src/org/labkey/assay/AssayManager.java index 4d0302e937d..871591e59cd 100644 --- a/assay/src/org/labkey/assay/AssayManager.java +++ b/assay/src/org/labkey/assay/AssayManager.java @@ -141,7 +141,7 @@ public Set getPermittedContainerIds(User user, Map co }; /** Cache the protocols defined in a given container, which we can quickly compose to get the protocols in scope */ - private static final Cache> PROTOCOL_CACHE = DatabaseCache.get(ExperimentService.get().getSchema().getScope(), CacheManager.UNLIMITED, TimeUnit.HOURS.toMillis(1), "Assay protocols", (c, argument) -> + private static final Cache> PROTOCOL_CACHE = DatabaseCache.get(ExperimentService.get().getSchema().getScope(), CacheManager.UNLIMITED, TimeUnit.HOURS.toMillis(1), "Assay protocols", (c, _) -> { List result = new ArrayList<>(); @@ -607,7 +607,7 @@ public ExpExperiment ensureUniqueBatchName(ExpExperiment batch, ExpProtocol prot batches = ExperimentService.get().getMatchingBatches(batch.getName(), batch.getContainer(), protocol); } - return batches.get(0); + return batches.getFirst(); } } @@ -661,14 +661,14 @@ public void indexAssay(SearchService.TaskIndexingQueue queue, ExpProtocol protoc ActionURL assayBeginURL = PageFlowUtil.urlProvider(AssayUrls.class).getProtocolURL(c, protocol, AssayController.AssayBeginAction.class); assayBeginURL.setExtraPath(c.getId()); String keywords = StringUtilsLabKey.joinNonBlank(" ", name, instrument, provider.getName()); - StringBuilder body = new StringBuilder(StringUtilsLabKey.joinNonBlank(" ", provider.getName(), description, comment)); + String body = StringUtilsLabKey.joinNonBlank(" ", provider.getName(), description, comment); Map m = new HashMap<>(); m.put(SearchService.PROPERTY.title.toString(), name); m.put(SearchService.PROPERTY.keywordsMed.toString(), keywords); m.put(SearchService.PROPERTY.categories.toString(), ASSAY_CATEGORY.getName()); String docId = protocol.getDocumentId(); - WebdavResource r = new SimpleDocumentResource(new Path(docId), docId, c.getEntityId(), "text/plain", body.toString(), assayBeginURL, createdBy, created, modifiedBy, modified, m); + WebdavResource r = new SimpleDocumentResource(new Path(docId), docId, c.getEntityId(), "text/plain", body, assayBeginURL, createdBy, created, modifiedBy, modified, m); queue.addResource(r); } @@ -955,7 +955,7 @@ public ExpProtocol findExpProtocol(GWTProtocol protocol, Container c) if (protocols.size() > 1) throw new NotFoundException("More than one assay protocol named '" + protocol.getName() + "' was found."); - expProtocol = protocols.get(0); + expProtocol = protocols.getFirst(); } return expProtocol; } @@ -1065,10 +1065,10 @@ List getRegisteredAssayProviders() return checker.getValidationSql(container, user, protocol, assayDataTable); } else - log.error(String.format("Assay data table not found for protocol : %s in folder : %s", protocol.getName(), container.getPath())); + log.error("Assay data table not found for protocol : {} in folder : {}", protocol.getName(), container.getPath()); } else - log.error(String.format("Assay provider not found for protocol : %s in folder : %s", protocol.getName(), container.getPath())); + log.error("Assay provider not found for protocol : {} in folder : {}", protocol.getName(), container.getPath()); return null; } diff --git a/assay/src/org/labkey/assay/AssayRunDocumentProvider.java b/assay/src/org/labkey/assay/AssayRunDocumentProvider.java index a45c937a85b..9e2a19eaa9b 100644 --- a/assay/src/org/labkey/assay/AssayRunDocumentProvider.java +++ b/assay/src/org/labkey/assay/AssayRunDocumentProvider.java @@ -4,7 +4,6 @@ import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.labkey.api.collections.LongHashMap; -import org.labkey.api.data.Container; import org.labkey.api.exp.api.ExpRun; import org.labkey.api.exp.api.ExperimentJSONConverter; import org.labkey.api.exp.api.ExperimentService; diff --git a/assay/src/org/labkey/assay/ModuleAssayCache.java b/assay/src/org/labkey/assay/ModuleAssayCache.java index 964d64942aa..34587cd9b37 100644 --- a/assay/src/org/labkey/assay/ModuleAssayCache.java +++ b/assay/src/org/labkey/assay/ModuleAssayCache.java @@ -130,7 +130,7 @@ public void testModuleResourceCache() .mapToInt(Collection::size) .sum(); - LOG.info(count + " assay providers defined in all modules"); + LOG.info("{} assay providers defined in all modules", count); // Make sure the cache retrieves the expected number of assay providers from the miniassay module, if present diff --git a/assay/src/org/labkey/assay/ModuleAssayProvider.java b/assay/src/org/labkey/assay/ModuleAssayProvider.java index 4a1f006de25..42916f39870 100644 --- a/assay/src/org/labkey/assay/ModuleAssayProvider.java +++ b/assay/src/org/labkey/assay/ModuleAssayProvider.java @@ -158,7 +158,7 @@ protected void init(ProviderType providerConfig) if (providerConfig.getInputDataFileSuffixArray().length > 0) { List suffixes = Arrays.asList(providerConfig.getInputDataFileSuffixArray()); - _dataType = new AssayDataType(TsvDataHandler.NAMESPACE, new FileType(suffixes, suffixes.get(0))); + _dataType = new AssayDataType(TsvDataHandler.NAMESPACE, new FileType(suffixes, suffixes.getFirst())); } if (providerConfig.isSetPrimaryDataFileType()) @@ -189,7 +189,7 @@ protected void init(ProviderType providerConfig) Module m = ModuleLoader.getInstance().getModule(moduleName); if (m == null) { - LOG.error("unknown required module referenced in assay provider " + providerConfig.getName() + " assay definition: [" + moduleName + "]"); + LOG.error("unknown required module referenced in assay provider {} assay definition: [{}]", providerConfig.getName(), moduleName); } else { @@ -233,7 +233,7 @@ private AssayDataType createAssayDataTypeFromXML(org.labkey.study.assay.xml.Assa } if (defaultSuffix == null) { - defaultSuffix = suffixes.get(0); + defaultSuffix = suffixes.getFirst(); } return new AssayDataType(namespacePrefix, new FileType(suffixes, defaultSuffix), role); } @@ -353,7 +353,7 @@ private DomainDescriptorType parseDomain(IAssayDomainType domainType) throws Mod StringBuilder sb = new StringBuilder(); while (!errors.isEmpty()) { - XmlError error = errors.remove(0); + XmlError error = errors.removeFirst(); sb.append(error.toString()); if (!errors.isEmpty()) sb.append("\n"); @@ -696,7 +696,7 @@ public List getValidationAndAnalysisScripts(ExpProtocol protocol // Prevent a later warning about the script file not existing if (_missingScriptWarnings.add(fileName)) { - LOG.warn("Unable to use script file '" + fileName + "' specified in metadata for assay type '" + getName() + "' because the required script engine is not configured."); + LOG.warn("Unable to use script file '{}' specified in metadata for assay type '{}' because the required script engine is not configured.", fileName, getName()); } } } @@ -736,7 +736,7 @@ private AnalysisScript findAndRemove(List scripts, String fileNa // Only warn the first time we notice that there's a script that's in the config.xml file but not on disk if (_missingScriptWarnings.add(fileName)) { - LOG.warn("Unable to find a script file '" + fileName + "' specified in metadata for assay type '" + getName() + "'"); + LOG.warn("Unable to find a script file '{}' specified in metadata for assay type '{}'", fileName, getName()); } return null; } diff --git a/assay/src/org/labkey/assay/PlateBasedAssaySampleTypeDomainKind.java b/assay/src/org/labkey/assay/PlateBasedAssaySampleTypeDomainKind.java index a87b0de7996..9ab3ad3a777 100644 --- a/assay/src/org/labkey/assay/PlateBasedAssaySampleTypeDomainKind.java +++ b/assay/src/org/labkey/assay/PlateBasedAssaySampleTypeDomainKind.java @@ -15,9 +15,9 @@ */ package org.labkey.assay; -import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.json.JSONObject; +import org.jetbrains.annotations.NotNull; import org.labkey.api.assay.AssayDomainKind; import org.labkey.api.assay.plate.AbstractPlateBasedAssayProvider; import org.labkey.api.data.Container; @@ -158,7 +158,7 @@ public Domain createDomain(GWTDomain domain, SampleTypeDomainKindProperties argu @NotNull @Override - public ValidationException updateDomain(GWTDomain original, GWTDomain update, @Nullable SampleTypeDomainKindProperties options, Container container, User user, boolean includeWarnings, @Nullable String auditUserComment) + public ValidationException updateDomain(GWTDomain original, @NotNull GWTDomain update, @Nullable SampleTypeDomainKindProperties options, Container container, User user, boolean includeWarnings, @Nullable String auditUserComment) { JSONObject args = options != null ? options.toJSONObject() : null; return _assayDelegate.updateDomain(original, update, args, container, user, includeWarnings, auditUserComment); diff --git a/assay/src/org/labkey/assay/PlateController.java b/assay/src/org/labkey/assay/PlateController.java index 362c014cc1c..e96f7f5cd2f 100644 --- a/assay/src/org/labkey/assay/PlateController.java +++ b/assay/src/org/labkey/assay/PlateController.java @@ -1839,7 +1839,7 @@ else if (form.getExportType() == PlateExportType.TSV) } else if (fileBytes.size() == 1) { - PlateManager.PlateFileBytes plateFileBytes = fileBytes.get(0); + PlateManager.PlateFileBytes plateFileBytes = fileBytes.getFirst(); String fileName = FileUtil.makeLegalName(plateFileBytes.plateName() + mapSuffix + "." + fileExtension); PageFlowUtil.streamFileBytes(getViewContext().getResponse(), fileName, plateFileBytes.bytes().toByteArray(), true); return null; diff --git a/assay/src/org/labkey/assay/TSVProtocolSchema.java b/assay/src/org/labkey/assay/TSVProtocolSchema.java index f666ba2d6e7..1b1288a672f 100644 --- a/assay/src/org/labkey/assay/TSVProtocolSchema.java +++ b/assay/src/org/labkey/assay/TSVProtocolSchema.java @@ -170,10 +170,10 @@ private class _AssayResultTable extends AssayResultTable plateHitsColumn.setConceptURI("hit-selection"); plateHitsColumn.setLabel("Hit Selection"); addColumn(plateHitsColumn); - defaultColumns.add(0, plateHitsColumn.getFieldKey()); + defaultColumns.addFirst(plateHitsColumn.getFieldKey()); } - defaultColumns.add(0, FieldKey.fromParts("Well", "SampleId")); + defaultColumns.addFirst(FieldKey.fromParts("Well", "SampleId")); // join to any replicate roll ups Domain replicateDomain = AssayPlateMetadataService.get().getPlateReplicateStatsDomain(getProtocol()); diff --git a/assay/src/org/labkey/assay/TsvAssayProvider.java b/assay/src/org/labkey/assay/TsvAssayProvider.java index cfad21024c7..23b2eee3aaf 100644 --- a/assay/src/org/labkey/assay/TsvAssayProvider.java +++ b/assay/src/org/labkey/assay/TsvAssayProvider.java @@ -167,7 +167,7 @@ public List getDataCollectors(@Nullable Map result = super.getDataCollectors(uploadedFiles, context); if (PipelineDataCollector.getFileQueue(context).isEmpty()) { - result.add(0, new TextAreaDataCollector<>()); + result.addFirst(new TextAreaDataCollector<>()); } return result; } @@ -887,7 +887,7 @@ public void testPipelineDataCollectorList() TsvAssayProvider provider = new TsvAssayProvider(); List dataCollectors = provider.getDataCollectors(null, _uploadContext); assertEquals(1, dataCollectors.size()); - assertEquals(PipelineDataCollector.class, dataCollectors.get(0).getClass()); + assertEquals(PipelineDataCollector.class, dataCollectors.getFirst().getClass()); } @Test diff --git a/assay/src/org/labkey/assay/actions/BaseProtocolAPIAction.java b/assay/src/org/labkey/assay/actions/BaseProtocolAPIAction.java index a8bc08e011f..bd12300ba2f 100644 --- a/assay/src/org/labkey/assay/actions/BaseProtocolAPIAction.java +++ b/assay/src/org/labkey/assay/actions/BaseProtocolAPIAction.java @@ -132,7 +132,7 @@ public static Pair getProtocolProvider(String protoc if (protocols.size() > 1) throw new NotFoundException("More than one assay protocol named '" + protocolName + "' was found."); - return Pair.of(protocols.get(0), provider); + return Pair.of(protocols.getFirst(), provider); } protected abstract ApiResponse executeAction(ExpProtocol protocol, FORM form, BindException errors) throws Exception; diff --git a/assay/src/org/labkey/assay/actions/ImportRunApiAction.java b/assay/src/org/labkey/assay/actions/ImportRunApiAction.java index 36302c7d5f3..7244c303b42 100644 --- a/assay/src/org/labkey/assay/actions/ImportRunApiAction.java +++ b/assay/src/org/labkey/assay/actions/ImportRunApiAction.java @@ -250,7 +250,7 @@ public ApiResponse execute(ImportRunApiForm form, BindException errors) throws E } catch (InvalidPathException e) { - LOG.info("Invalid path: " + runFilePath, e); + LOG.info("Invalid path: {}", runFilePath, e); throw new NotFoundException("File not found: " + runFilePath); } } diff --git a/assay/src/org/labkey/assay/actions/PipelineDataCollectorRedirectAction.java b/assay/src/org/labkey/assay/actions/PipelineDataCollectorRedirectAction.java index 552c913f6bd..83c8ce4508c 100644 --- a/assay/src/org/labkey/assay/actions/PipelineDataCollectorRedirectAction.java +++ b/assay/src/org/labkey/assay/actions/PipelineDataCollectorRedirectAction.java @@ -238,7 +238,7 @@ protected Pair, Map> filesWithExistingRuns(List< { ExpData data = ExperimentService.get().getExpDataByURL(file, getContainer()); if (data != null) - LOG.info("Found existing data: rowId=" + data.getRowId() + ", url=" + data.getDataFileUrl()); + LOG.info("Found existing data: rowId={}, url={}", data.getRowId(), data.getDataFileUrl()); if (data != null && data.getRun() != null) { ExpRun previousRun = data.getRun(); diff --git a/assay/src/org/labkey/assay/actions/SaveAssayBatchAction.java b/assay/src/org/labkey/assay/actions/SaveAssayBatchAction.java index f70210d13ef..d6bf68571aa 100644 --- a/assay/src/org/labkey/assay/actions/SaveAssayBatchAction.java +++ b/assay/src/org/labkey/assay/actions/SaveAssayBatchAction.java @@ -108,7 +108,7 @@ private ApiResponse executeAction(ExperimentSaveHandler saveHandler, ExpProtocol transaction.commit(); } saveHandler.afterSave(getViewContext(), batches, protocol); - return AssayJSONConverter.serializeResult(provider, protocol, batches.get(0), getUser()); + return AssayJSONConverter.serializeResult(provider, protocol, batches.getFirst(), getUser()); } } diff --git a/assay/src/org/labkey/assay/data/generator/AssayDesignGenerator.java b/assay/src/org/labkey/assay/data/generator/AssayDesignGenerator.java index 073f5b8f867..39880391775 100644 --- a/assay/src/org/labkey/assay/data/generator/AssayDesignGenerator.java +++ b/assay/src/org/labkey/assay/data/generator/AssayDesignGenerator.java @@ -32,7 +32,7 @@ public void generateAssayDesigns(String namePrefix) throws ValidationException int numAssayDesigns = _config.getNumAssayDesigns(); if (numAssayDesigns <= 0) { - _log.info(String.format("No assay designs generated because %s=%d", Config.NUM_ASSAY_DESIGNS, numAssayDesigns)); + _log.info("No assay designs generated because {}={}", Config.NUM_ASSAY_DESIGNS, numAssayDesigns); return; } checkAlive(_job); @@ -52,7 +52,7 @@ public void generateAssayDesigns(String namePrefix) throws ValidationException checkAlive(_job); } timer.stop(); - _log.info(String.format("Generating %d assay designs took %s", numAssayDesigns, timer.getDuration() + ".")); + _log.info("Generating {} assay designs took {}", numAssayDesigns, timer.getDuration() + "."); } private void createStandardAssayDesign(String name) throws ValidationException diff --git a/assay/src/org/labkey/assay/data/generator/AssayRunDataGenerator.java b/assay/src/org/labkey/assay/data/generator/AssayRunDataGenerator.java index b8fb4901755..eaa61e919ef 100644 --- a/assay/src/org/labkey/assay/data/generator/AssayRunDataGenerator.java +++ b/assay/src/org/labkey/assay/data/generator/AssayRunDataGenerator.java @@ -55,22 +55,22 @@ public void generateAssayRunData() throws ValidationException, ExperimentExcepti } if (_config.getMaxRunsPerDesign() <= 0) { - _log.info(String.format("No assay run data generated because %s=%d.", Config.MAX_RUNS_PER_DESIGN, _config.getMaxRunsPerDesign())); + _log.info("No assay run data generated because {}={}.", Config.MAX_RUNS_PER_DESIGN, _config.getMaxRunsPerDesign()); return; } if (_config.getMaxRunsPerDesign() < _config.getMinRunsPerDesign()) { - _log.info(String.format("No assay run data generated because %s (%d) is less than %s (%d).", Config.MAX_RUNS_PER_DESIGN, _config.getMaxRunsPerDesign(), Config.MIN_RUNS_PER_DESIGN, _config.getMinRunsPerDesign())); + _log.info("No assay run data generated because {} ({}) is less than {} ({}).", Config.MAX_RUNS_PER_DESIGN, _config.getMaxRunsPerDesign(), Config.MIN_RUNS_PER_DESIGN, _config.getMinRunsPerDesign()); return; } if (_config.getMaxRowsPerRun() <= 0) { - _log.info(String.format("No assay run data generated because %s=%s.", Config.MAX_ROWS_PER_RUN, _config.getMaxRowsPerRun())); + _log.info("No assay run data generated because {}={}.", Config.MAX_ROWS_PER_RUN, _config.getMaxRowsPerRun()); return; } if (_config.getMaxRowsPerRun() < _config.getMinRowsPerRun()) { - _log.info(String.format("No assay run data generated because %s (%d) is less than %s (%d).", Config.MAX_ROWS_PER_RUN, _config.getMaxRowsPerRun(), Config.MIN_ROWS_PER_RUN, _config.getMinRowsPerRun())); + _log.info("No assay run data generated because {} ({}) is less than {} ({}).", Config.MAX_ROWS_PER_RUN, _config.getMaxRowsPerRun(), Config.MIN_ROWS_PER_RUN, _config.getMinRowsPerRun()); return; } ViewContext context = new ViewContext(); @@ -87,7 +87,7 @@ public void generateAssayRunData() throws ValidationException, ExperimentExcepti { checkAlive(_job); int numRows = randomInt(_config.getMinRowsPerRun(), _config.getMaxRowsPerRun()); - _log.info(String.format("Generating %d rows of run data for run %d of design %s", numRows, i, protocol.getName())); + _log.info("Generating {} rows of run data for run {} of design {}", numRows, i, protocol.getName()); List> rawData = createRows(numRows, resultsDomain); updateSampleProps(protocol.getName(), rawData, resultsDomain); var factory = provider.createRunUploadFactory(protocol, context) @@ -118,7 +118,7 @@ private void updateSampleProps(String protocolName, List> ra ExpSampleType sampleType = SampleTypeService.get().getSampleType(getContainer(), sampleTypeName); if (sampleType == null) { - _log.warn(String.format("Sample type '%s' referenced in assay design %s not found.", sampleTypeName, protocolName)); + _log.warn("Sample type '{}' referenced in assay design {} not found.", sampleTypeName, protocolName); // remove the values set by the default data generator for the row since they won't be valid sample ids. rawData.forEach(row -> row.put(sampleProp.getName(), null)); } diff --git a/assay/src/org/labkey/assay/data/generator/PlateSetDataGenerator.java b/assay/src/org/labkey/assay/data/generator/PlateSetDataGenerator.java index 50cafb7d961..14ce9bb52ca 100644 --- a/assay/src/org/labkey/assay/data/generator/PlateSetDataGenerator.java +++ b/assay/src/org/labkey/assay/data/generator/PlateSetDataGenerator.java @@ -68,17 +68,15 @@ public void generatePlateSets() _plateType = getPlateType(); if (_plateType == null) { - _log.error(String.format("Unable to resolve plate type (%s). Plate types must be expressed in the format : x eg: 8x12", config.getPlateType())); + _log.error("Unable to resolve plate type ({}). Plate types must be expressed in the format : x eg: 8x12", config.getPlateType()); return; } // generate plates and plate sets if (config.getPlateLineageDepth() > 0) - _log.info(String.format("Generating %d root Plate set(s) with %d level(s)", - config.getNumPlatesets(), - config.getPlateLineageDepth())); + _log.info("Generating {} root Plate set(s) with {} level(s)", config.getNumPlatesets(), config.getPlateLineageDepth()); else - _log.info(String.format("Generating %d root Plate set(s)", config.getNumPlatesets())); + _log.info("Generating {} root Plate set(s)", config.getNumPlatesets()); try { @@ -93,7 +91,7 @@ public void generatePlateSets() if (config.getPlateLineageDepth() > 0) createLevel(parentPlateSet, 0); } - _log.info(String.format("Created a total of %d plate sets.", _plateSetsCreated)); + _log.info("Created a total of {} plate sets.", _plateSetsCreated); timer.stop(); if (config._importPlatesets) @@ -118,31 +116,31 @@ private boolean validateConfiguration(Config config) { if (config.getNumPlatesets() <= 0) { - _log.info(String.format("No plate sets generated because %s=%d", Config.NUM_PLATESETS, config.getNumPlatesets())); + _log.info("No plate sets generated because {}={}", Config.NUM_PLATESETS, config.getNumPlatesets()); return false; } if (config.getPlatesPerPlateset() > PlateSet.MAX_PLATES) { - _log.error(String.format("The number of plates per plates ets cannot exceed %d", PlateSet.MAX_PLATES)); + _log.error("The number of plates per plates ets cannot exceed {}", PlateSet.MAX_PLATES); return false; } if (config.getPlateLineageDepth() > MAX_LINEAGE_DEPTH) { - _log.error(String.format("The max plate set lineage depth cannot exceed %d", MAX_LINEAGE_DEPTH)); + _log.error("The max plate set lineage depth cannot exceed {}", MAX_LINEAGE_DEPTH); return false; } if ((config.getPrimaryPlateSetsPerLevel() + config.getAssayPlateSetsPerLevel()) > MAX_PLATE_SETS_PER_LEVEL) { - _log.error(String.format("The max number of plate sets per level cannot exceed %d", MAX_PLATE_SETS_PER_LEVEL)); + _log.error("The max number of plate sets per level cannot exceed {}", MAX_PLATE_SETS_PER_LEVEL); return false; } if (config.getMinCustomProperties() > config.getMaxCustomProperties()) { - _log.error(String.format("The max number of plate sets per level cannot exceed %d", MAX_PLATE_SETS_PER_LEVEL)); + _log.error("The max number of plate sets per level cannot exceed {}", MAX_PLATE_SETS_PER_LEVEL); return false; } @@ -295,7 +293,7 @@ private void importPlatesets() throws Exception { if (_assayPlateSets.isEmpty()) throw new ValidationException("There are no assay plate sets to import"); - _log.info(String.format("Importing data for %d plate sets.", _assayPlateSets.size())); + _log.info("Importing data for {} plate sets.", _assayPlateSets.size()); AssayProvider provider = AssayService.get().getProvider(TsvAssayProvider.NAME); if (provider == null) @@ -367,11 +365,11 @@ public void logTimes() { MathStat stats = StatsService.get().getStats(_plateTimings); - _log.info(String.format("%s\t%s", "Per Plate", DateUtil.formatDuration((long)stats.getMean()))); - _log.info(String.format("%s\t%s", "Per Plate (std dev)", stats.getStdDev())); + _log.info("{}\t{}", "Per Plate", DateUtil.formatDuration((long) stats.getMean())); + _log.info("{}\t{}", "Per Plate (std dev)", stats.getStdDev()); } else - _log.info(String.format("%s\t%s", "Per Plate", DateUtil.formatDuration(_plateTimings.get(0).longValue()))); + _log.info("{}\t{}", "Per Plate", DateUtil.formatDuration(_plateTimings.getFirst().longValue())); } public static class Config extends DataGenerator.Config diff --git a/assay/src/org/labkey/assay/pipeline/AssayImportRunTask.java b/assay/src/org/labkey/assay/pipeline/AssayImportRunTask.java index c5316c1a32c..1d1750a2b64 100644 --- a/assay/src/org/labkey/assay/pipeline/AssayImportRunTask.java +++ b/assay/src/org/labkey/assay/pipeline/AssayImportRunTask.java @@ -218,7 +218,7 @@ List getOutputs(PipelineJob job) { List outputs = new ArrayList<>(); FileLike dataFile = getDataFile(job); - job.getLogger().info("Importing output data file : " + dataFile.getName()); + job.getLogger().info("Importing output data file : {}", dataFile.getName()); outputs.add(new RecordedAction.DataFile(dataFile.toURI(), "RESULTS-DATA", false, false)); return outputs; @@ -230,7 +230,7 @@ private FileLike getDataFile(PipelineJob job) // guaranteed to have a single file upload assert support.getInputFiles().size() == 1; - return support.getInputFiles().get(0); + return support.getInputFiles().getFirst(); } @Override @@ -242,7 +242,7 @@ List> getRawData(PipelineJob job) throws PipelineJobExceptio { if (ExcelLoader.isExcel(dataFile)) { - job.getLogger().info("Processing excel file: " + dataFile.getName()); + job.getLogger().info("Processing excel file: {}", dataFile.getName()); // check to see if this is a multi-sheet format try (ExcelLoader loader = new ExcelLoader(new BufferedInputStream(dataFile.openInputStream()), true, null)) { @@ -272,8 +272,8 @@ else if ("zip".equalsIgnoreCase(FileUtil.getExtension(dataFile))) if (results.size() == 1) { - FileLike resultFile = results.get(0); - job.getLogger().info("Found results file named : " + resultFile + ", loading into results data."); + FileLike resultFile = results.getFirst(); + job.getLogger().info("Found results file named : {}, loading into results data.", resultFile); try (DataLoader loader = DataLoaderService.get().createLoader(resultFile, null, true, null, null)) { return loader.load(); @@ -305,8 +305,8 @@ else if ("zip".equalsIgnoreCase(FileUtil.getExtension(dataFile))) List results = dir.getChildren((f) -> BATCH_PROPS_NAME.equalsIgnoreCase(FileUtil.getBaseName(f))); if (results.size() == 1) { - FileLike resultFile = results.get(0); - job.getLogger().info("Found batch properties file named : " + resultFile + ", loading into results data."); + FileLike resultFile = results.getFirst(); + job.getLogger().info("Found batch properties file named : {}, loading into results data.", resultFile); try (DataLoader loader = DataLoaderService.get().createLoader(resultFile, null, true, null, null)) { return loadProperties(loader); @@ -338,8 +338,8 @@ else if ("zip".equalsIgnoreCase(FileUtil.getExtension(dataFile))) List results = dir.getChildren((f) -> RUN_PROPS_NAME.equalsIgnoreCase(FileUtil.getBaseName(f))); if (results.size() == 1) { - FileLike resultFile = results.get(0); - job.getLogger().info("Found run properties file named : " + resultFile + ", loading into results data."); + FileLike resultFile = results.getFirst(); + job.getLogger().info("Found run properties file named : {}, loading into results data.", resultFile); try (DataLoader loader = DataLoaderService.get().createLoader(resultFile, null, true, null, null)) { return loadProperties(loader); @@ -371,7 +371,7 @@ private Map loadProperties(FileLike dataFile, String sheetName, { if (loader.getSheetNames().contains(sheetName)) { - log.info("Found sheet named : " + sheetName + ", loading properties from this sheet."); + log.info("Found sheet named : {}, loading properties from this sheet.", sheetName); loader.setSheetName(sheetName); return loadProperties(loader); @@ -530,7 +530,7 @@ protected ExpProtocol getProtocol(PipelineJob job, AssayProvider provider) throw // If only one protocol exists in the container, use it if (protocols.size() == 1) - return protocols.get(0); + return protocols.getFirst(); // Otherwise, we require a name String protocolName = _protocolName; @@ -617,7 +617,7 @@ private List getOutputs(PipelineJob job) throws Pipelin outputs = new ArrayList<>(); - RecordedAction lastAction = actions.get(actions.size()-1); + RecordedAction lastAction = actions.getLast(); for (RecordedAction.DataFile dataFile : lastAction.getOutputs()) { if (dataFile.isTransient()) @@ -658,7 +658,7 @@ private Map getInputs(PipelineJob job) Map inputs = new LinkedHashMap<>(); - RecordedAction firstAction = actions.get(0); + RecordedAction firstAction = actions.getFirst(); for (RecordedAction.DataFile dataFile : firstAction.getInputs()) { if (dataFile.isTransient()) diff --git a/assay/src/org/labkey/assay/plate/AssayPlateMetadataServiceImpl.java b/assay/src/org/labkey/assay/plate/AssayPlateMetadataServiceImpl.java index 1dca54939e2..8bbbedd5c75 100644 --- a/assay/src/org/labkey/assay/plate/AssayPlateMetadataServiceImpl.java +++ b/assay/src/org/labkey/assay/plate/AssayPlateMetadataServiceImpl.java @@ -273,7 +273,7 @@ public DataIteratorBuilder parsePlateData( List plates = getPlatesForPlateSet(container, user, plateSetId, protocol); if (plates.isEmpty()) throw new ExperimentException("No plates were found for the plate set (" + plateSetId + ")."); - PlateSet plateSet = plates.get(0).getPlateSet(); + PlateSet plateSet = plates.getFirst().getPlateSet(); List> rows = _parsePlateData(container, user, data, provider, protocol, plateSet, plates, dataFile, settings); @@ -397,7 +397,7 @@ public DataIteratorBuilder mergeReRunData( // be able to proceed in that case by just passing through all run results to the transform script for the run being replaced. if (!rows.isEmpty()) { - Object plateObj = rows.get(0).get(AssayResultDomainKind.Column.Plate.name()); + Object plateObj = rows.getFirst().get(AssayResultDomainKind.Column.Plate.name()); if (plateObj instanceof String) plateFieldKey = FieldKey.fromParts(AssayResultDomainKind.Column.Plate.name(), PlateTable.Column.PlateId.name()); } @@ -534,7 +534,7 @@ private boolean isGridFormat(List> data) return true; // only the tabular formats will have the well location field - return !data.get(0).containsKey(AssayResultDomainKind.Column.WellLocation.name()) && !data.get(0).containsKey("Well Location"); + return !data.getFirst().containsKey(AssayResultDomainKind.Column.WellLocation.name()) && !data.getFirst().containsKey("Well Location"); } private List> parsePlateRows( @@ -549,7 +549,7 @@ private List> parsePlateRows( importAliases.add(AssayResultDomainKind.Column.Plate.name()); // check whether the data rows have plate identifiers - String plateIdField = data.get(0).keySet().stream().filter(importAliases::contains).findFirst().orElse(null); + String plateIdField = data.getFirst().keySet().stream().filter(importAliases::contains).findFirst().orElse(null); boolean hasPlateIdentifiers = plateIdField != null && (data.stream().filter(row -> row.get(plateIdField) != null).findFirst().orElse(null) != null); if (hasPlateIdentifiers) @@ -562,7 +562,7 @@ private List> parsePlateRows( if (types.size() > 1) throw new ExperimentException(String.format(ERROR_MESSAGE, "the plate set contains different plate types")); - PlateType type = types.stream().toList().get(0); + PlateType type = types.stream().toList().getFirst(); int plateSize = type.getRows() * type.getColumns(); if ((data.size() % plateSize) != 0) throw new ExperimentException(String.format(ERROR_MESSAGE, "the number of rows in the data (" + data.size() + ") does not fit evenly and would result in a plate with partial wells filled")); @@ -671,10 +671,10 @@ public PlateGridInfo(PlateUtils.GridInfo info, PlateSet plateSet, Set me // otherwise a single annotation can only be a plate identifier if (annotations.size() == 1) { - String annotation = annotations.get(0); + String annotation = annotations.getFirst(); if (plates.size() == 1 && measureAliases != null && measureAliases.contains(annotation)) { - _plate = plates.get(0); + _plate = plates.getFirst(); _measureName = annotation; } else @@ -781,7 +781,7 @@ else if (multipleMeasures && measureProperties.isEmpty()) throw new ExperimentException("There are multiple measures specified in the data file but the assay protocol does not define any measures"); } - String defaultMeasureName = measureProperties.get(0).getName(); + String defaultMeasureName = measureProperties.getFirst().getName(); // if any of the plateGrids keys have plate identifiers, import using those identifiers List> dataRows = new ArrayList<>(); @@ -1756,7 +1756,7 @@ public void testGridAnnotations() throws Exception PlateSet plateSet = PlateManager.get().createPlateSet(container, user, new PlateSetImpl(), plates, null, null); List plateSetPlates = PlateManager.get().getPlatesForPlateSet(plateSet); assertEquals("Expected two plates to be created.", 2, plateSetPlates.size()); - Plate plate = plateSetPlates.get(0); + Plate plate = plateSetPlates.getFirst(); PlateGridInfo gridInfo = new PlateGridInfo( new PlateUtils.GridInfo(new double[8][12], List.of(plate.getPlateId())), diff --git a/assay/src/org/labkey/assay/plate/CurveFitFactory.java b/assay/src/org/labkey/assay/plate/CurveFitFactory.java index fd29fa19986..836852ecaa4 100644 --- a/assay/src/org/labkey/assay/plate/CurveFitFactory.java +++ b/assay/src/org/labkey/assay/plate/CurveFitFactory.java @@ -39,19 +39,15 @@ public static DilutionCurve getCurveImpl(WellGroup wellGroup, boolean assumeDecr public static DilutionCurve getCurveImpl(List wellGroups, boolean assumeDecreasing, DilutionCurve.PercentCalculator percentCalculator, StatsService.CurveFitType type) throws FitFailedException { - switch (type) + return switch (type) { - case FOUR_PARAMETER: - return new ParameterCurveImpl.FourParameterCurve(wellGroups, assumeDecreasing, percentCalculator); - case FIVE_PARAMETER: - return new ParameterCurveImpl.FiveParameterCurve(wellGroups, assumeDecreasing, percentCalculator); - case POLYNOMIAL: - return new PolynomialCurveImpl(wellGroups, assumeDecreasing, percentCalculator); - case LINEAR: - return new LinearCurveImpl(wellGroups, assumeDecreasing, percentCalculator); - case NONE: - return new EmptyCurveImpl(wellGroups, assumeDecreasing, percentCalculator); - } - throw new IllegalArgumentException("Unable to find a DilutionCurve implementation for type: " + type.getLabel()); + case FOUR_PARAMETER -> new ParameterCurveImpl.FourParameterCurve(wellGroups, assumeDecreasing, percentCalculator); + case FIVE_PARAMETER -> new ParameterCurveImpl.FiveParameterCurve(wellGroups, assumeDecreasing, percentCalculator); + case POLYNOMIAL -> new PolynomialCurveImpl(wellGroups, assumeDecreasing, percentCalculator); + case LINEAR -> new LinearCurveImpl(wellGroups, assumeDecreasing, percentCalculator); + case NONE -> new EmptyCurveImpl(wellGroups, assumeDecreasing, percentCalculator); + default -> + throw new IllegalArgumentException("Unable to find a DilutionCurve implementation for type: " + type.getLabel()); + }; } } diff --git a/assay/src/org/labkey/assay/plate/PlateCache.java b/assay/src/org/labkey/assay/plate/PlateCache.java index 828a9674ccf..f88df6fd049 100644 --- a/assay/src/org/labkey/assay/plate/PlateCache.java +++ b/assay/src/org/labkey/assay/plate/PlateCache.java @@ -53,10 +53,10 @@ public PlateImpl load(@NotNull String key, @Nullable Object argument) if (plates.size() == 1) { - PlateBean bean = plates.get(0); + PlateBean bean = plates.getFirst(); PlateImpl plate = PlateManager.get().populatePlate(bean); - LOG.debug(String.format("Caching plate \"%s\" for folder %s", plate.getName(), cacheKey._container.getPath())); + LOG.debug("Caching plate \"{}\" for folder {}", plate.getName(), cacheKey._container.getPath()); // add all cache keys for this plate addCacheKeys(cacheKey, plate); @@ -173,7 +173,7 @@ private void addCacheKeys(PlateCacheKey cacheKey, PlateImpl plate) public static void uncache(Container c) { - LOG.debug(String.format("Clearing cache for folder %s", c.getPath())); + LOG.debug("Clearing cache for folder {}", c.getPath()); // uncache all plates for this container if (_loader._containerPlateMap.containsKey(c)) @@ -202,7 +202,7 @@ public static void uncache(Container c, long rowId) public static void uncache(Container c, Plate plate) { - LOG.debug(String.format("Un-caching plate \"%s\" for folder %s", plate.getPlateId(), c.getPath())); + LOG.debug("Un-caching plate \"{}\" for folder {}", plate.getPlateId(), c.getPath()); if (plate.getPlateId() == null) throw new IllegalArgumentException("Plate cannot be uncached, plateId is null"); diff --git a/assay/src/org/labkey/assay/plate/PlateManager.java b/assay/src/org/labkey/assay/plate/PlateManager.java index 72138aeca1b..4c1da61c95a 100644 --- a/assay/src/org/labkey/assay/plate/PlateManager.java +++ b/assay/src/org/labkey/assay/plate/PlateManager.java @@ -1189,7 +1189,7 @@ private long savePlateImpl( List> insertedRows = qus.insertRows(user, container, Collections.singletonList(plateRow), errors, null, extraScriptContext); if (errors.hasErrors()) throw errors; - Map row = insertedRows.get(0); + Map row = insertedRows.getFirst(); plateId = MapUtils.getLong(row,PlateTable.Column.RowId.name()); plate.setRowId(plateId); plate.setLsid((String) row.get(PlateTable.Column.Lsid.name())); @@ -2100,14 +2100,14 @@ private void clearCache(Collection plateRowIds) String containerId = (String) data.get("container"); if (StringUtils.trimToNull(containerId) == null) { - LOG.warn(String.format("clearCache: failed to resolve containerId for plate with rowId %d", rowId)); + LOG.warn("clearCache: failed to resolve containerId for plate with rowId {}", rowId); continue; } Container c = ContainerManager.getForId(containerId); if (c == null) { - LOG.warn(String.format("clearCache: failed to resolve container for plate with rowId %d with containerId %s.", rowId, containerId)); + LOG.warn("clearCache: failed to resolve container for plate with rowId {} with containerId {}.", rowId, containerId); continue; } PlateCache.uncache(c, rowId); @@ -2900,7 +2900,7 @@ public PlateSetImpl createPlateSet( if (errors.hasErrors()) throw errors; - Integer plateSetId = asInteger(rows.get(0).get(PlateSetTable.Column.RowId.name())); + Integer plateSetId = asInteger(rows.getFirst().get(PlateSetTable.Column.RowId.name())); savePlateSetHeritage(plateSetId, plateSet.getType(), parentPlateSet); @@ -3794,7 +3794,7 @@ private List getPlateExportFieldKeys(Plate plate, boolean isMapView) else { // For non-map export view we always want "position" first - fieldKeys.add(0, WellTable.Column.Position.fieldKey()); + fieldKeys.addFirst(WellTable.Column.Position.fieldKey()); } List customFields = plate.getCustomFields(); @@ -5141,7 +5141,7 @@ public void run() { for (Long plateId : entry.getValue()) { - LOG.debug("Indexing plate ID " + plateId); + LOG.debug("Indexing plate ID {}", plateId); indexPlate(entry.getKey(), plateId, true); } } diff --git a/assay/src/org/labkey/assay/plate/PlateSetCache.java b/assay/src/org/labkey/assay/plate/PlateSetCache.java index 41bcc0056c6..134afba73ed 100644 --- a/assay/src/org/labkey/assay/plate/PlateSetCache.java +++ b/assay/src/org/labkey/assay/plate/PlateSetCache.java @@ -48,8 +48,8 @@ public PlateSet load(@NotNull String key, @Nullable Object argument) List plateSets = new TableSelector(AssayDbSchema.getInstance().getTableInfoPlateSet(), filter, null).getArrayList(PlateSetImpl.class); if (plateSets.size() == 1) { - PlateSet plateSet = plateSets.get(0); - LOG.debug(String.format("Caching plate set \"%s\" for folder %s", plateSet.getName(), cacheKey._container.getPath())); + PlateSet plateSet = plateSets.getFirst(); + LOG.debug("Caching plate set \"{}\" for folder {}", plateSet.getName(), cacheKey._container.getPath()); // add all cache keys for this plate set addCacheKeys(cacheKey, plateSet); @@ -110,7 +110,7 @@ private void addCacheKeys(PlateSetCacheKey cacheKey, PlateSet plateSet) public static void uncache(Container c) { - LOG.debug(String.format("Clearing plate set cache for folder %s", c.getPath())); + LOG.debug("Clearing plate set cache for folder {}", c.getPath()); // uncache all plate sets for this container if (_loader._containerPlateSet.containsKey(c)) @@ -139,7 +139,7 @@ public static void uncache(Container c, long rowId) public static void uncache(Container c, PlateSet plateSet) { - LOG.debug(String.format("Un-caching plate set \"%s\"", plateSet.getPlateSetId())); + LOG.debug("Un-caching plate set \"{}\"", plateSet.getPlateSetId()); if (plateSet.getPlateSetId() == null) throw new IllegalArgumentException("Plate set cannot be uncached, plateSetId is null"); if (plateSet.getRowId() == null) diff --git a/assay/src/org/labkey/assay/plate/PlateSetExport.java b/assay/src/org/labkey/assay/plate/PlateSetExport.java index 37200d91749..25ffc92ad19 100644 --- a/assay/src/org/labkey/assay/plate/PlateSetExport.java +++ b/assay/src/org/labkey/assay/plate/PlateSetExport.java @@ -155,7 +155,7 @@ public List getWorklist( else if (sourceRows.size() == 1) { for (Object[] destinationRow : destinationRows) - plateDataRows.add(ArrayUtils.addAll(sourceRows.get(0), destinationRow)); + plateDataRows.add(ArrayUtils.addAll(sourceRows.getFirst(), destinationRow)); } // Catch many-to-many operations else if (sourceRows.size() != destinationRows.size()) diff --git a/assay/src/org/labkey/assay/plate/WellGroupImpl.java b/assay/src/org/labkey/assay/plate/WellGroupImpl.java index 19c7e530c8b..964a484211d 100644 --- a/assay/src/org/labkey/assay/plate/WellGroupImpl.java +++ b/assay/src/org/labkey/assay/plate/WellGroupImpl.java @@ -145,8 +145,8 @@ public String getPositionDescription() if (_positions == null || _positions.isEmpty()) return ""; if (_positions.size() == 1) - return _positions.get(0).getDescription(); - return _positions.get(0).getDescription() + "-" + _positions.get(_positions.size() - 1).getDescription(); + return _positions.getFirst().getDescription(); + return _positions.getFirst().getDescription() + "-" + _positions.getLast().getDescription(); } @Override @@ -189,7 +189,7 @@ public Position getTopLeft() { if (_positions.isEmpty()) return null; - return _positions.get(0); + return _positions.getFirst(); } /** @@ -468,7 +468,7 @@ private void populateStatsFromTable() Type.REPLICATE.equals(getType())); if (1 != dilutionDataRows.size()) throw new IllegalStateException("Expected a single DilutionData row to calculate wellgroup stats, but found " + dilutionDataRows.size() + " rows"); - _dilutionDataRow = dilutionDataRows.get(0); + _dilutionDataRow = dilutionDataRows.getFirst(); _mean = _dilutionDataRow.getMean(); _min = _dilutionDataRow.getMin(); _max = _dilutionDataRow.getMax(); diff --git a/assay/src/org/labkey/assay/plate/data/PlateMapExcelWriter.java b/assay/src/org/labkey/assay/plate/data/PlateMapExcelWriter.java index 3803002938b..a7d8506d25d 100644 --- a/assay/src/org/labkey/assay/plate/data/PlateMapExcelWriter.java +++ b/assay/src/org/labkey/assay/plate/data/PlateMapExcelWriter.java @@ -130,7 +130,7 @@ protected void renderGridRow(Sheet sheet, List displayColumns) if (row == null) { - logger.error("Well data not found for row " + rowIdx); + logger.error("Well data not found for row {}", rowIdx); continue; } @@ -138,13 +138,13 @@ protected void renderGridRow(Sheet sheet, List displayColumns) if (well == null) { - logger.error("Well data not found for row: " + rowIdx + ", col: " + (colIdx - 1)); + logger.error("Well data not found for row: {}, col: {}", rowIdx, colIdx - 1); continue; } if (displayColumns.size() == 1) { - DisplayColumn displayColumn = displayColumns.get(0); + DisplayColumn displayColumn = displayColumns.getFirst(); var col = getDisplayFieldColumnInfo(displayColumn); Object value = col.getValue(well); @@ -220,7 +220,7 @@ protected void renderSheet(Workbook workbook, int sheetNumber) displayColumns = displayCols.stream().filter(dc -> !excludeFromSummary.contains(dc.getColumnInfo().getFieldKey())).toList(); } else if (sheetNumber == 1) // Sample ID view - displayColumns = List.of(displayCols.get(0)); + displayColumns = List.of(displayCols.getFirst()); else // CustomField view { PlateCustomField customField = getCustomFields().get(sheetNumber - 2); @@ -232,7 +232,7 @@ else if (sheetNumber == 1) // Sample ID view } catch (Exception e) { - logger.error("Error rendering sheet " + sheetNumber + ": " + e.getMessage()); + logger.error("Error rendering sheet {}: {}", sheetNumber, e.getMessage()); } } diff --git a/assay/src/org/labkey/assay/plate/layout/ArrayOperation.java b/assay/src/org/labkey/assay/plate/layout/ArrayOperation.java index 4f7cefccfd5..cb915c84515 100644 --- a/assay/src/org/labkey/assay/plate/layout/ArrayOperation.java +++ b/assay/src/org/labkey/assay/plate/layout/ArrayOperation.java @@ -141,7 +141,7 @@ public List execute(ExecutionContext context) throws ValidationExcep { WellLayout layout; if (!targetLayouts.isEmpty()) - return targetLayouts.remove(0); + return targetLayouts.removeFirst(); if (targetPlateData != null && !targetPlateData.isEmpty()) layout = getPlateDataWellLayout(context, targetPlateData); @@ -158,7 +158,7 @@ else if (context.targetTemplate() != null) if (plateData.isEmpty()) return null; - PlateManager.PlateData targetPlateData = plateData.remove(0); + PlateManager.PlateData targetPlateData = plateData.removeFirst(); if (targetPlateData != null && targetPlateData.plateType() != null && targetPlateData.plateType() > 0) { PlateType targetPlateDataType = context.resolvePlateType(targetPlateData.plateType()); diff --git a/assay/src/org/labkey/assay/plate/layout/ReverseQuadrantOperation.java b/assay/src/org/labkey/assay/plate/layout/ReverseQuadrantOperation.java index f693656f712..b09de4cd7fd 100644 --- a/assay/src/org/labkey/assay/plate/layout/ReverseQuadrantOperation.java +++ b/assay/src/org/labkey/assay/plate/layout/ReverseQuadrantOperation.java @@ -17,7 +17,7 @@ public class ReverseQuadrantOperation implements LayoutOperation @Override public List execute(ExecutionContext context) { - Plate sourcePlate = context.sourcePlates().get(0); + Plate sourcePlate = context.sourcePlates().getFirst(); Long plateRowId = sourcePlate.getRowId(); List layouts = new ArrayList<>(); @@ -69,7 +69,7 @@ public void init(Container container, User user, ExecutionContext context) throw if (context.sourcePlates().size() != 1) throw new ValidationException("The reverse quadrant operation requires a single source plate."); - _targetPlateType = getTargetPlateType(context.sourcePlates().get(0).getPlateType(), context.allPlateTypes()); + _targetPlateType = getTargetPlateType(context.sourcePlates().getFirst().getPlateType(), context.allPlateTypes()); } private @NotNull PlateType getTargetPlateType(@NotNull PlateType sourcePlateType, List allPlateTypes) throws ValidationException diff --git a/assay/src/org/labkey/assay/plate/query/PlateSchemaTest.java b/assay/src/org/labkey/assay/plate/query/PlateSchemaTest.java index e658eb1a96e..ed0e9540a02 100644 --- a/assay/src/org/labkey/assay/plate/query/PlateSchemaTest.java +++ b/assay/src/org/labkey/assay/plate/query/PlateSchemaTest.java @@ -151,7 +151,7 @@ private void verifyTablePermissions(String tableName, boolean allowInsert, boole assertFalse("Expected no errors", errors.hasErrors()); assertEquals("Expected a single row", 1, plateRows.size()); - var plateRow = plateRows.get(0); + var plateRow = plateRows.getFirst(); var plateRowId = (int) plateRow.get(PlateTable.Column.RowId.name()); return getPlate(plateRowId); diff --git a/assay/src/org/labkey/assay/plate/query/WellTable.java b/assay/src/org/labkey/assay/plate/query/WellTable.java index 8782c5a259c..178fc7c1864 100644 --- a/assay/src/org/labkey/assay/plate/query/WellTable.java +++ b/assay/src/org/labkey/assay/plate/query/WellTable.java @@ -44,7 +44,6 @@ import org.labkey.api.query.InvalidKeyException; import org.labkey.api.query.QueryForeignKey; import org.labkey.api.query.QueryUpdateService; -import org.labkey.api.query.QueryUpdateServiceException; import org.labkey.api.query.SimpleUserSchema; import org.labkey.api.query.ValidationException; import org.labkey.api.security.User; @@ -473,7 +472,7 @@ public List> insertRows( } @Override - protected Map getRow(User user, Container container, Map keys) throws InvalidKeyException, QueryUpdateServiceException, SQLException + protected Map getRow(User user, Container container, Map keys) throws InvalidKeyException, SQLException { return getRow(user, container, keys, false); } diff --git a/assay/src/org/labkey/assay/query/AssaySchemaImpl.java b/assay/src/org/labkey/assay/query/AssaySchemaImpl.java index 34ab375cb05..1954bd00f9f 100644 --- a/assay/src/org/labkey/assay/query/AssaySchemaImpl.java +++ b/assay/src/org/labkey/assay/query/AssaySchemaImpl.java @@ -20,6 +20,7 @@ import org.jmock.Expectations; import org.jmock.Mockery; import org.jmock.lib.legacy.ClassImposteriser; +import org.jetbrains.annotations.NotNull; import org.junit.Assert; import org.junit.Test; import org.labkey.api.assay.AssayProtocolSchema; @@ -228,7 +229,7 @@ public TableInfo createTable(String name, ContainerFilter cf) } @Override - public QueryView createView(ViewContext context, QuerySettings settings, org.springframework.validation.BindException errors) + public @NotNull QueryView createView(ViewContext context, QuerySettings settings, org.springframework.validation.BindException errors) { // For backward compatibility with <12.2, resolve runs and results query views. String name = settings.getQueryName(); diff --git a/audit/src/org/labkey/audit/AuditController.java b/audit/src/org/labkey/audit/AuditController.java index acd22a9e9b5..de464e6c5d5 100644 --- a/audit/src/org/labkey/audit/AuditController.java +++ b/audit/src/org/labkey/audit/AuditController.java @@ -150,7 +150,7 @@ protected QueryView createQueryView(ShowAuditLogForm form, BindException errors, String selected = form.getView(); if (selected == null) - selected = AuditLogService.get().getAuditProviders().get(0).getEventName(); + selected = AuditLogService.get().getAuditProviders().getFirst().getEventName(); UserSchema schema = AuditLogService.getAuditLogSchema(getUser(), getContainer()); QuerySettings settings = new QuerySettings(getViewContext(), QueryView.DATAREGIONNAME_DEFAULT, selected); diff --git a/audit/src/org/labkey/audit/AuditLogImpl.java b/audit/src/org/labkey/audit/AuditLogImpl.java index dd38dba1fbe..3adc44bb5fe 100644 --- a/audit/src/org/labkey/audit/AuditLogImpl.java +++ b/audit/src/org/labkey/audit/AuditLogImpl.java @@ -157,7 +157,7 @@ private K _addEvents(@Nullable User user, List eve if (user == null) { if (HttpView.hasCurrentView() && HttpView.currentContext() != null) - _log.warn("user was not specified for event type " + event.getEventType() + " in container " + event.getContainer() + "; defaulting to guest user."); + _log.warn("user was not specified for event type {} in container {}; defaulting to guest user.", event.getEventType(), event.getContainer()); user = UserManager.getGuestUser(); } if (event.getTransactionId() != null && useTransactionAuditCache) @@ -196,7 +196,7 @@ private K _addEvents(@Nullable User user, List eve if (databaseReady) { if (reselectEvent && events.size()==1) - return LogManager.get().insertEvent(user, events.get(0)); + return LogManager.get().insertEvent(user, events.getFirst()); LogManager.get().insertEvents(user, events); } } diff --git a/audit/src/org/labkey/audit/auditLog.jsp b/audit/src/org/labkey/audit/auditLog.jsp index 9e4f4a98227..ccb2995a24d 100644 --- a/audit/src/org/labkey/audit/auditLog.jsp +++ b/audit/src/org/labkey/audit/auditLog.jsp @@ -29,8 +29,8 @@ AuditTypeProvider selectedProvider = null; if (currentView == null) { - currentView = providers.get(0).getEventName(); - selectedProvider = providers.get(0); + currentView = providers.getFirst().getEventName(); + selectedProvider = providers.getFirst(); } var selectId = makeId("formsSubmit"); diff --git a/audit/src/org/labkey/audit/model/LogManager.java b/audit/src/org/labkey/audit/model/LogManager.java index 801701f1db4..3e5b34b64b4 100644 --- a/audit/src/org/labkey/audit/model/LogManager.java +++ b/audit/src/org/labkey/audit/model/LogManager.java @@ -113,7 +113,7 @@ public void insertEvents(User user, List events) if (events.isEmpty()) return; - AuditTypeEvent type = events.get(0); + AuditTypeEvent type = events.getFirst(); // Out of an abundance of caution and backward compatible behavior, do one-at-a-time logging if // there is no transaction. Can revisit if this is not necessary. @@ -251,7 +251,7 @@ private K validateFields(@NotNull AuditTypeProvider p int scale = prop.getSize(); if (s.length() > scale) { - _log.warn("Audit field input : \n" + prop.getName() + "\nexceeded the maximum length : " + scale); + _log.warn("Audit field input : \n{}\nexceeded the maximum length : {}", prop.getName(), scale); String trimmed = s.substring(0, scale-3) + "..."; values.put(prop.getName(), trimmed); changed = true; @@ -269,7 +269,7 @@ private K validateFields(@NotNull AuditTypeProvider p int scale = dp.getScale(); if (scale > 0 && s.length() > scale) { - _log.warn("Audit field input : \n" + pd.getName() + "\nexceeded the maximum length : " + scale); + _log.warn("Audit field input : \n{}\nexceeded the maximum length : {}", pd.getName(), scale); String trimmed; if (scale > 100) trimmed = s.substring(0, scale-3) + "..."; diff --git a/core/api-src/org/labkey/api/admin/HealthCheckRegistry.java b/core/api-src/org/labkey/api/admin/HealthCheckRegistry.java index b54b2fdabc7..6a2373bdef9 100644 --- a/core/api-src/org/labkey/api/admin/HealthCheckRegistry.java +++ b/core/api-src/org/labkey/api/admin/HealthCheckRegistry.java @@ -78,7 +78,7 @@ public void registerHealthCheck(@NotNull String name, @NotNull String category, Map categoryChecks = _healthCheckCategories.get(category); if (categoryChecks.containsKey(name)) { - LOG.error("Health check with name '" + name + "' already exists in category '" + category + "'. New check not registered."); + LOG.error("Health check with name '{}' already exists in category '{}'. New check not registered.", name, category); return; } _healthCheckCategories.get(category).put(name, healthCheck); diff --git a/core/api-src/org/labkey/api/admin/TableXmlUtils.java b/core/api-src/org/labkey/api/admin/TableXmlUtils.java index 3e535567921..25896a3283f 100644 --- a/core/api-src/org/labkey/api/admin/TableXmlUtils.java +++ b/core/api-src/org/labkey/api/admin/TableXmlUtils.java @@ -87,7 +87,7 @@ public static SchemaValidationList compareXmlToMetaData(DbSchema schema, boolean } catch (Exception e) { - _log.error("Exception loading schema " + schema.getDisplayName(), e); + _log.error("Exception loading schema {}", schema.getDisplayName(), e); resultList.addError("+++ ERROR: Exception " + e.getMessage()); } diff --git a/core/src/org/labkey/core/CoreController.java b/core/src/org/labkey/core/CoreController.java index d80b090fa49..8142f50e0e7 100644 --- a/core/src/org/labkey/core/CoreController.java +++ b/core/src/org/labkey/core/CoreController.java @@ -429,7 +429,7 @@ else if (form.getSchemaName() != null && form.getQueryName() != null && form.get List pkCols = table.getPkColumns(); if (pkCols.size() != 1) throw new NotFoundException("Query must have only one pk column"); - ColumnInfo pkCol = pkCols.get(0); + ColumnInfo pkCol = pkCols.getFirst(); ColumnInfo col = table.getColumn(pd.getName()); if (col == null) @@ -701,12 +701,12 @@ public ModelAndView getView(GetAttachmentIconForm form, BindException errors) th } else { - _log.warn("Unable to retrieve icon file: " + path); + _log.warn("Unable to retrieve icon file: {}", path); } } else { - _log.warn("No icon file found for extension: " + StringUtils.trimToEmpty(form.getExtension())); + _log.warn("No icon file found for extension: {}", StringUtils.trimToEmpty(form.getExtension())); } return null; } diff --git a/core/src/org/labkey/core/CoreModule.java b/core/src/org/labkey/core/CoreModule.java index 803404e97ce..773c884faf2 100644 --- a/core/src/org/labkey/core/CoreModule.java +++ b/core/src/org/labkey/core/CoreModule.java @@ -1684,7 +1684,7 @@ private void populateSiteSettingsWithStartupProps() // using guest user since the server startup doesn't have a true user (this will be used for audit events) ContainerManager.getHomeContainer().setFolderType(folderType, User.guest); else - LOG.error("Unable to find folder type for home project during server startup: " + folderTypeEntry.getValue()); + LOG.error("Unable to find folder type for home project during server startup: {}", folderTypeEntry.getValue()); } StartupPropertyEntry resetPermissionsEntry = props.get(homeProjectResetPermissions); diff --git a/core/src/org/labkey/core/admin/AdminController.java b/core/src/org/labkey/core/admin/AdminController.java index 42521e5f2f9..d0907560eed 100644 --- a/core/src/org/labkey/core/admin/AdminController.java +++ b/core/src/org/labkey/core/admin/AdminController.java @@ -48,7 +48,6 @@ import org.jfree.data.category.DefaultCategoryDataset; import org.json.JSONArray; import org.json.JSONObject; -import org.jspecify.annotations.NonNull; import org.junit.Assert; import org.junit.Test; import org.labkey.api.Constants; @@ -129,7 +128,6 @@ import org.labkey.api.data.NormalContainerType; import org.labkey.api.data.PHI; import org.labkey.api.data.RenderContext; -import org.labkey.api.data.RuntimeSQLException; import org.labkey.api.data.SQLFragment; import org.labkey.api.data.Sort; import org.labkey.api.data.SqlExecutor; @@ -1668,7 +1666,7 @@ public static class SiteValidationForm { private List _providers; private boolean _includeSubfolders = false; - private transient Consumer _logger = s -> { + private transient Consumer _logger = _ -> { }; // No-op by default public List getProviders() @@ -3218,7 +3216,7 @@ public ModelAndView getView(MemForm form, BindException errors) { if (form.getDebugName().equals(cache.getDebugName())) { - LOG.info("Purging cache: " + cache.getDebugName()); + LOG.info("Purging cache: {}", cache.getDebugName()); cache.clear(); } } @@ -3785,7 +3783,7 @@ public ModelAndView getView(MemForm form, BindException errors) // Difference could be < 0 if JVM or other threads have performed gc, in which case we can't guesstimate cache memory usage String cacheMemUsed = cacheMemoryUsed > 0 ? FileUtils.byteCountToDisplaySize(cacheMemoryUsed) : "Unknown"; - LOG.info("Estimate of cache memory used: " + cacheMemUsed); + LOG.info("Estimate of cache memory used: {}", cacheMemUsed); lastCacheMemUsed = cacheMemUsed; } else if (cc) @@ -3886,12 +3884,12 @@ private MemBean(HttpServletRequest request, Set objectsToIgnore) { MemTracker memTracker = MemTracker.getInstance(); List all = memTracker.getReferences(); - long threadId = Thread.currentThread().getId(); + long threadId = Thread.currentThread().threadId(); // Attempt to detect other threads running labkey code -- mem tracker page will warn if any are found for (Thread thread : new ThreadsBean().threads) { - if (thread.getId() == threadId) + if (thread.threadId() == threadId) continue; Thread.State state = thread.getState(); @@ -4403,7 +4401,7 @@ public boolean handlePost(MemoryStressForm memoryStressForm, BindException error } } }); - t.setUncaughtExceptionHandler((t2, e) -> { + t.setUncaughtExceptionHandler((_, e) -> { LOG.error("Stress test exception", e); errors.reject(null, "Stress test exception: " + e); }); @@ -4988,7 +4986,7 @@ public void setOverrideDefault(String overrideDefault) public static class RConfigurationAction extends FolderManagementViewPostAction { @Override - protected HttpView getTabView(RConfigForm form, boolean reshow, BindException errors) + protected HttpView getTabView(RConfigForm form, boolean reshow, BindException errors) { return new JspView<>("/org/labkey/core/admin/rConfiguration.jsp", form, errors); } @@ -5421,7 +5419,7 @@ public class ImportFolderAction extends FolderManagementViewPostAction getTabView(ImportFolderForm form, boolean reshow, BindException errors) { // default the createSharedDatasets and validateQueries to true if this is not a form error reshow if (!errors.hasErrors()) @@ -5570,13 +5568,13 @@ public boolean handlePost(ImportFolderForm form, BindException errors) throws Ex } catch (FileNotFoundException e) { - LOG.debug("Failed to import '" + originalFilename + "'.", e); + LOG.debug("Failed to import '{}'.", originalFilename, e); errors.reject("folderImport", "File not found."); return null; } catch (IOException e) { - LOG.debug("Failed to import '" + originalFilename + "'.", e); + LOG.debug("Failed to import '{}'.", originalFilename, e); errors.reject("folderImport", "Unable to unzip folder archive."); return null; } @@ -6152,7 +6150,7 @@ public class FileRootsStandAloneAction extends FormViewAction @Override public ModelAndView getView(FileRootsForm form, boolean reShow, BindException errors) { - JspView view = getFileRootsView(form, errors, getReshow()); + JspView view = getFileRootsView(form, errors, getReshow()); view.setFrame(WebPartView.FrameType.NONE); getPageConfig().setNavTrail(ContainerManager.getCreateContainerWizardSteps(getContainer(), getContainer().getParent())); @@ -6204,7 +6202,7 @@ public class ManageFileRootAction extends FormViewAction @Override public ModelAndView getView(FileRootsForm form, boolean reShow, BindException errors) { - JspView view = getFileRootsView(form, errors, getReshow()); + JspView view = getFileRootsView(form, errors, getReshow()); getPageConfig().setTitle("Manage File Root"); return view; } @@ -6244,7 +6242,7 @@ public void addNavTrail(NavTree root) public class FileRootsAction extends FolderManagementViewPostAction { @Override - protected HttpView getTabView(FileRootsForm form, boolean reshow, BindException errors) + protected HttpView getTabView(FileRootsForm form, boolean reshow, BindException errors) { return getFileRootsView(form, errors, getReshow()); } @@ -6274,9 +6272,9 @@ public ActionURL getSuccessURL(FileRootsForm form) } } - private JspView getFileRootsView(FileRootsForm form, BindException errors, boolean reshow) + private JspView getFileRootsView(FileRootsForm form, BindException errors, boolean reshow) { - JspView view = new JspView<>("/org/labkey/core/admin/view/filesProjectSettings.jsp", form, errors); + JspView view = new JspView<>("/org/labkey/core/admin/view/filesProjectSettings.jsp", form, errors); String title = "Configure File Root"; if (CloudStoreService.get() != null) title += " And Enable Cloud Stores"; @@ -6383,30 +6381,23 @@ else if (form.isCloudFileRoot()) { service.setIsUseDefaultRoot(ctx.getContainer(), false); service.setCloudRoot(ctx.getContainer(), cloudRootName); - try + PipelineService.get().setPipelineRoot(ctx.getUser(), ctx.getContainer(), PipelineService.PRIMARY_ROOT, false); + if (form.isFolderSetup() && !sourceInfos.isEmpty()) { - PipelineService.get().setPipelineRoot(ctx.getUser(), ctx.getContainer(), PipelineService.PRIMARY_ROOT, false); - if (form.isFolderSetup() && !sourceInfos.isEmpty()) + // File root was set to cloud storage, remove folder created + Path fromPath = FileUtil.stringToPath(sourceInfos.getFirst().first, sourceInfos.getFirst().second); // sourceInfos paths should be encoded + if (FileContentService.FILES_LINK.equals(FileUtil.getFileName(fromPath))) { - // File root was set to cloud storage, remove folder created - Path fromPath = FileUtil.stringToPath(sourceInfos.get(0).first, sourceInfos.get(0).second); // sourceInfos paths should be encoded - if (FileContentService.FILES_LINK.equals(FileUtil.getFileName(fromPath))) + try { - try - { - Files.deleteIfExists(fromPath.getParent()); - } - catch (IOException e) - { - LOG.warn("Could not delete directory '" + FileUtil.pathToString(fromPath.getParent()) + "'"); - } + Files.deleteIfExists(fromPath.getParent()); + } + catch (IOException e) + { + LOG.warn("Could not delete directory '{}'", FileUtil.pathToString(fromPath.getParent())); } } } - catch (SQLException e) - { - throw new RuntimeSQLException(e); - } changed = true; shouldCopyMove = true; } @@ -6658,7 +6649,7 @@ else if (enabledCloudChanged) public static class ManageFoldersAction extends FolderManagementViewAction { @Override - protected HttpView getTabView() + protected HttpView getTabView() { return new JspView<>("/org/labkey/core/admin/manageFolders.jsp"); } @@ -6685,7 +6676,7 @@ public void setProvider(String provider) public static class NotificationsAction extends FolderManagementViewPostAction { @Override - protected HttpView getTabView(NotificationsForm form, boolean reshow, BindException errors) + protected HttpView getTabView(NotificationsForm form, boolean reshow, BindException errors) { final String key = DataRegionSelection.getSelectionKey("core", CoreQuerySchema.USERS_MSG_SETTINGS_TABLE_NAME, null, DATA_REGION_NAME); DataRegionSelection.clearAll(getViewContext(), key); @@ -6832,7 +6823,7 @@ public ApiResponse execute(NotifyOptionsForm form, BindException errors) ConfigTypeProvider provider = form.getProvider(); if (provider != null) { - List options = new ArrayList<>(); + List> options = new ArrayList<>(); // if the list of options is not for the folder default, add an option to use the folder default if (getViewContext().get("isDefault") == null) @@ -6996,7 +6987,7 @@ public void setQueryName(String queryName) public static class ConceptsAction extends FolderManagementViewPostAction { @Override - protected HttpView getTabView(ConceptsForm form, boolean reshow, BindException errors) + protected HttpView getTabView(ConceptsForm form, boolean reshow, BindException errors) { return new JspView<>("/org/labkey/core/admin/manageConcepts.jsp", form, errors); } @@ -8058,7 +8049,7 @@ public boolean handlePost(SetFolderPermissionsForm form, BindException errors) } else { - _successURL = new ActionURL(extraSteps.get(0).getHref()); + _successURL = new ActionURL(extraSteps.getFirst().getHref()); } } @@ -8247,7 +8238,7 @@ else if (c.hasPermission(getUser(), AdminOperationsPermission.class)) } else { - _successURL = new ActionURL(extraSteps.get(0).getHref()); + _successURL = new ActionURL(extraSteps.getFirst().getHref()); } return true; @@ -8365,7 +8356,7 @@ public ActionURL getSuccessURL(ManageFoldersForm form) { // Note: because in some scenarios we might be deleting children of the current contaner, in those cases we remain in this folder: // If we just deleted a project then redirect to the home page, otherwise back to managing the project folders - if (_deleted.size() == 1 && _deleted.get(0).equals(getContainer())) + if (_deleted.size() == 1 && _deleted.getFirst().equals(getContainer())) { Container c = getContainer(); if (c.isProject()) @@ -9562,7 +9553,7 @@ public ModelAndView getConfirmView(ModuleForm form, BindException errors) if (!deleteList.isEmpty()) { description.append(" and delete all data in "); - description.append(deleteList.size() > 1 ? "these schemas: " + StringUtils.join(deleteList, ", ") : "the \"" + deleteList.get(0) + "\" schema"); + description.append(deleteList.size() > 1 ? "these schemas: " + StringUtils.join(deleteList, ", ") : "the \"" + deleteList.getFirst() + "\" schema"); } // For unknown modules, also list the schemas that won't be deleted @@ -12105,10 +12096,10 @@ private void updateFields(TableInfo tInfo, Collection fieldNames, int de if (!sql.isEmpty()) { - logger.info(String.format("Updating %s in table %s.%s", updating, schema.getName(), tInfo.getName())); + logger.info("Updating {} in table {}.{}", updating, schema.getName(), tInfo.getName()); logger.debug(sql.toDebugString()); int numRows = new SqlExecutor(schema).execute(sql); - logger.info(String.format("Updated %d rows for table %s.%s", numRows, schema.getName(), tInfo.getName())); + logger.info("Updated {} rows for table {}.{}", numRows, schema.getName(), tInfo.getName()); } } @@ -12116,12 +12107,12 @@ private void updateFields(TableInfo tInfo, Collection fieldNames, int de public boolean handlePost(AdjustTimestampsForm form, BindException errors) throws Exception { List toUpdate = Arrays.asList("Created", "Modified", "lastIndexed", "diCreated", "diModified"); - logger.info("Adjusting all " + toUpdate + " timestamp fields in all tables by " + form.getHourDelta() + " hours."); + logger.info("Adjusting all {} timestamp fields in all tables by {} hours.", toUpdate, form.getHourDelta()); DbScope scope = DbScope.getLabKeyScope(); try (DbScope.Transaction t = scope.ensureTransaction()) { ModuleLoader.getInstance().getModules().forEach(module -> { - logger.info("==> Beginning update of timestamps for module: " + module.getName()); + logger.info("==> Beginning update of timestamps for module: {}", module.getName()); module.getSchemaNames().stream().sorted().forEach(schemaName -> { DbSchema schema = DbSchema.get(schemaName, DbSchemaType.Module); scope.invalidateSchema(schema); // Issue 44452: assure we have a fresh set of tables to work from @@ -12133,11 +12124,11 @@ public boolean handlePost(AdjustTimestampsForm form, BindException errors) throw } }); }); - logger.info("<== DONE updating timestamps for module: " + module.getName()); + logger.info("<== DONE updating timestamps for module: {}", module.getName()); }); t.commit(); } - logger.info("DONE Adjusting all " + toUpdate + " timestamp fields in all tables by " + form.getHourDelta() + " hours."); + logger.info("DONE Adjusting all {} timestamp fields in all tables by {} hours.", toUpdate, form.getHourDelta()); return true; } @@ -12407,7 +12398,7 @@ public boolean handlePost(Object o, BindException errors) throws Exception } @Override - public @NonNull URLHelper getSuccessURL(Object o) + public @NotNull URLHelper getSuccessURL(Object o) { return getShowAdminURL(); } diff --git a/core/src/org/labkey/core/admin/CopyFileRootPipelineJob.java b/core/src/org/labkey/core/admin/CopyFileRootPipelineJob.java index 155f3816c41..b14f9264b56 100644 --- a/core/src/org/labkey/core/admin/CopyFileRootPipelineJob.java +++ b/core/src/org/labkey/core/admin/CopyFileRootPipelineJob.java @@ -184,7 +184,7 @@ private TaskStatus copyOneFolder(Container container, Path sourceDir, Path destD } else if (Files.exists(destDir) && !Files.isDirectory(destDir)) // Dest doesn't have to exist { - getLogger().warn("Destination exists and is not directory: " + FileUtil.pathToString(destDir)); + getLogger().warn("Destination exists and is not directory: {}", FileUtil.pathToString(destDir)); status = TaskStatus.error; } else @@ -302,7 +302,7 @@ private TaskStatus copyFiles(Path sourceDir, Path destDir, List lastStatTi { if (FileUtil.hasCloudScheme(destDir) && StringUtils.contains(pathString, "%")) { - getLogger().warn("Cannot copy directory '" + pathString + "' to cloud, because its name contains '%'."); + getLogger().warn("Cannot copy directory '{}' to cloud, because its name contains '%'.", pathString); status = TaskStatus.error; } else @@ -413,7 +413,7 @@ private boolean matchesCopyFailureSimulatorRegex(String propertyName, String fil private void logStatTime(List lastStatTime, final Pair stats, final Pair origStats) { Long currentTime = System.currentTimeMillis(); - if (currentTime - lastStatTime.get(0) > 1000*60) + if (currentTime - lastStatTime.getFirst() > 1000*60) { info((origStats.first - stats.first) + " out of " + origStats.first + " files copied (" + (origStats.second - stats.second) + " out of " + origStats.second + " bytes)"); @@ -441,7 +441,7 @@ else if (Files.isRegularFile(path)) } catch (IOException e) { - getLogger().warn("Error deleting file '" + FileUtil.pathToString(path) + "'", e); + getLogger().warn("Error deleting file '{}'", FileUtil.pathToString(path), e); throw new UncheckedIOException(e); } }); @@ -457,7 +457,7 @@ else if (Files.isRegularFile(path)) } catch (IOException e) { - getLogger().warn("Error deleting directory '" + FileUtil.pathToString(dirPath) + "'", e); + getLogger().warn("Error deleting directory '{}'", FileUtil.pathToString(dirPath), e); throw new UncheckedIOException(e); } } diff --git a/core/src/org/labkey/core/admin/MenuViewFactory.java b/core/src/org/labkey/core/admin/MenuViewFactory.java index 5274c48e68d..abe0135f96c 100644 --- a/core/src/org/labkey/core/admin/MenuViewFactory.java +++ b/core/src/org/labkey/core/admin/MenuViewFactory.java @@ -342,7 +342,7 @@ private static void writeCells(ArrayList renderables, HtmlWriter out { List> lists = Lists.partition(renderables, MAX_PER_COLUMN); int columns = lists.size(); - int rows = lists.get(0).size(); + int rows = lists.getFirst().size(); for (int i = 0; i < rows; i++) { int idx = i; diff --git a/core/src/org/labkey/core/admin/ValidateDomainsPipelineJob.java b/core/src/org/labkey/core/admin/ValidateDomainsPipelineJob.java index 6cdc7d51b3f..f2d9638836d 100644 --- a/core/src/org/labkey/core/admin/ValidateDomainsPipelineJob.java +++ b/core/src/org/labkey/core/admin/ValidateDomainsPipelineJob.java @@ -70,7 +70,7 @@ public void run() setStatus(TaskStatus.running); getLogger().info("Starting to check domains"); StorageProvisioner.ProvisioningReport pr = StorageProvisioner.get().getProvisioningReport(); - getLogger().info(String.format("%d domains use Storage Provisioner", pr.getProvisionedDomains().size())); + getLogger().info("{} domains use Storage Provisioner", pr.getProvisionedDomains().size()); int errorCount = 0; for (StorageProvisioner.ProvisioningReport.DomainReport dr : pr.getProvisionedDomains()) { @@ -85,7 +85,7 @@ public void run() errorCount++; getLogger().error(error); } - getLogger().info("Check complete, " + errorCount + " errors found"); + getLogger().info("Check complete, {} errors found", errorCount); setStatus(TaskStatus.complete, "Job finished at: " + DateUtil.nowISO()); } } diff --git a/core/src/org/labkey/core/admin/deleteFolder.jsp b/core/src/org/labkey/core/admin/deleteFolder.jsp index dd6ae82706a..bb2b67ff689 100644 --- a/core/src/org/labkey/core/admin/deleteFolder.jsp +++ b/core/src/org/labkey/core/admin/deleteFolder.jsp @@ -37,7 +37,7 @@ Container primaryContainer = getContainer(); User user = getUser(); - String message = containersToDelete.size() == 1 ? containersToDelete.get(0).isProject() ? "project and its subfolders" : "folder" : "folders"; + String message = containersToDelete.size() == 1 ? containersToDelete.getFirst().isProject() ? "project and its subfolders" : "folder" : "folders"; %>
@@ -137,10 +137,10 @@ } - String containerType = containersToDelete.size() == 1 ? containersToDelete.get(0).getContainerNoun() : ""; - String name = containersToDelete.size() == 1 ? containersToDelete.get(0).getName() : "these " + containersToDelete.size() +" folders"; + String containerType = containersToDelete.size() == 1 ? containersToDelete.getFirst().getContainerNoun() : ""; + String name = containersToDelete.size() == 1 ? containersToDelete.getFirst().getName() : "these " + containersToDelete.size() +" folders"; boolean showSubfolder = containersToDelete.size() != 1; - boolean hasSubFolders = containersToDelete.size() == 1 && !containersToDelete.get(0).getChildren().isEmpty(); + boolean hasSubFolders = containersToDelete.size() == 1 && !containersToDelete.getFirst().getChildren().isEmpty(); boolean usePlural = containersToDelete.size() > 1 || hasSubFolders;; %> diff --git a/core/src/org/labkey/core/admin/importer/FolderTypeImporterFactory.java b/core/src/org/labkey/core/admin/importer/FolderTypeImporterFactory.java index d21035b2a76..e7f8b530a12 100644 --- a/core/src/org/labkey/core/admin/importer/FolderTypeImporterFactory.java +++ b/core/src/org/labkey/core/admin/importer/FolderTypeImporterFactory.java @@ -144,7 +144,7 @@ public void process(PipelineJob job, FolderImportContext ctx, VirtualFile root) { if (null != job) job.setStatus("IMPORT " + getDescription()); - ctx.getLogger().info("Loading " + getDescription()); + ctx.getLogger().info("Loading {}", getDescription()); org.labkey.folder.xml.FolderType folderTypeXml = folderXml.getFolderType(); FolderType folderType = FolderTypeManager.get().getFolderType(folderTypeXml.getName()); diff --git a/core/src/org/labkey/core/admin/importer/MissingValueImporterFactory.java b/core/src/org/labkey/core/admin/importer/MissingValueImporterFactory.java index bc62080d444..88b1918b62a 100644 --- a/core/src/org/labkey/core/admin/importer/MissingValueImporterFactory.java +++ b/core/src/org/labkey/core/admin/importer/MissingValueImporterFactory.java @@ -65,7 +65,7 @@ public void process(@Nullable PipelineJob job, FolderImportContext ctx, VirtualF { if (null != job) job.setStatus("IMPORT " + getDescription()); - ctx.getLogger().info("Loading " + getDescription()); + ctx.getLogger().info("Loading {}", getDescription()); // Create a map that looks just like the map returned by MvUtil.getIndicatorsAndLabels() Map newMvMap = new HashMap<>(); @@ -97,7 +97,7 @@ public void process(@Nullable PipelineJob job, FolderImportContext ctx, VirtualF String[] mvLabels = newMvMap.values().toArray(new String[0]); MvUtil.assignMvIndicators(ctx.getContainer(), mvIndicators, mvLabels); } - ctx.getLogger().info("Done importing " + getDescription()); + ctx.getLogger().info("Done importing {}", getDescription()); } } diff --git a/core/src/org/labkey/core/admin/importer/ModulePropertiesImporterFactory.java b/core/src/org/labkey/core/admin/importer/ModulePropertiesImporterFactory.java index ef216a8dd26..bdb290686e4 100644 --- a/core/src/org/labkey/core/admin/importer/ModulePropertiesImporterFactory.java +++ b/core/src/org/labkey/core/admin/importer/ModulePropertiesImporterFactory.java @@ -64,14 +64,14 @@ public void process(PipelineJob job, FolderImportContext ctx, VirtualFile root) if (null != job) job.setStatus("IMPORT " + getDescription()); - ctx.getLogger().info("Loading " + getDescription()); + ctx.getLogger().info("Loading {}", getDescription()); for(ModulePropertyType modulePropType: modulePropsType.getModulePropertyArray()) { Module module = ModuleLoader.getInstance().getModule(modulePropType.getModuleName()); if (module == null) { - ctx.getLogger().info("Module '" + modulePropType.getModuleName() + "' not deployed, skipping import of property '" + modulePropType.getPropertyName() + "'"); + ctx.getLogger().info("Module '{}' not deployed, skipping import of property '{}'", modulePropType.getModuleName(), modulePropType.getPropertyName()); } else { @@ -83,7 +83,7 @@ public void process(PipelineJob job, FolderImportContext ctx, VirtualFile root) } } - ctx.getLogger().info("Done importing " + getDescription()); + ctx.getLogger().info("Done importing {}", getDescription()); } } diff --git a/core/src/org/labkey/core/admin/importer/PageImporterFactory.java b/core/src/org/labkey/core/admin/importer/PageImporterFactory.java index 7e4a654b7a6..1ba5a4052f8 100644 --- a/core/src/org/labkey/core/admin/importer/PageImporterFactory.java +++ b/core/src/org/labkey/core/admin/importer/PageImporterFactory.java @@ -103,7 +103,7 @@ public void process(PipelineJob job, FolderImportContext ctx, VirtualFile root) if (null != job) job.setStatus("IMPORT " + getDescription()); - ctx.getLogger().info("Loading " + getDescription()); + ctx.getLogger().info("Loading {}", getDescription()); PagesDocument pagesDocXml; String pagesFileName = pagesXml.getFile(); @@ -199,7 +199,7 @@ public void process(PipelineJob job, FolderImportContext ctx, VirtualFile root) // Clear the cache one more time - attempt to avoid race condition on TeamCity WebPartCache.remove(ctx.getContainer()); - ctx.getLogger().info("Done importing " + pageXmls.size() + " page(s) with " + webpartCount + " webpart(s)"); + ctx.getLogger().info("Done importing {} page(s) with {} webpart(s)", pageXmls.size(), webpartCount); } } diff --git a/core/src/org/labkey/core/admin/importer/SearchSettingsImporterFactory.java b/core/src/org/labkey/core/admin/importer/SearchSettingsImporterFactory.java index e0769fd0007..bbc7cc59e3c 100644 --- a/core/src/org/labkey/core/admin/importer/SearchSettingsImporterFactory.java +++ b/core/src/org/labkey/core/admin/importer/SearchSettingsImporterFactory.java @@ -59,9 +59,9 @@ public void process(PipelineJob job, FolderImportContext ctx, VirtualFile root) { if (null != job) job.setStatus("IMPORT " + getDescription()); - ctx.getLogger().info("Loading " + getDescription()); + ctx.getLogger().info("Loading {}", getDescription()); ContainerManager.updateSearchable(c, ctx.getXml().getSearchable(), ctx.getUser()); - ctx.getLogger().info("Done importing " + getDescription()); + ctx.getLogger().info("Done importing {}", getDescription()); } } diff --git a/core/src/org/labkey/core/admin/importer/SubfolderImporterFactory.java b/core/src/org/labkey/core/admin/importer/SubfolderImporterFactory.java index 3ad64e86f61..6ead89688c2 100644 --- a/core/src/org/labkey/core/admin/importer/SubfolderImporterFactory.java +++ b/core/src/org/labkey/core/admin/importer/SubfolderImporterFactory.java @@ -75,7 +75,7 @@ public void process(PipelineJob job, FolderImportContext ctx, VirtualFile root) { if (null != job) job.setStatus("IMPORT " + getDescription()); - ctx.getLogger().info("Loading " + getDescription()); + ctx.getLogger().info("Loading {}", getDescription()); // fail if the user does not have admin permissions to the parent container if (!ctx.getContainer().hasPermission(ctx.getUser(), AdminPermission.class)) @@ -87,7 +87,7 @@ public void process(PipelineJob job, FolderImportContext ctx, VirtualFile root) InputStream subfoldersIS = subfoldersDir.getInputStream(SubfolderWriter.SUBFOLDERS_FILENAME); if (subfoldersIS == null) { - ctx.getLogger().error("Could not find expected file: " + getFilePath(subfoldersDir, SubfolderWriter.SUBFOLDERS_FILENAME)); + ctx.getLogger().error("Could not find expected file: {}", getFilePath(subfoldersDir, SubfolderWriter.SUBFOLDERS_FILENAME)); return; } @@ -98,7 +98,7 @@ public void process(PipelineJob job, FolderImportContext ctx, VirtualFile root) String subfolderName = subfoldersDir.makeLegalName(subfolderNode.getName()); if (!subfoldersDir.listDirs().contains(subfolderName)) { - ctx.getLogger().error("Could not find content directory for subfolder: " + getFilePath(subfoldersDir, subfolderName)); + ctx.getLogger().error("Could not find content directory for subfolder: {}", getFilePath(subfoldersDir, subfolderName)); } else { @@ -108,7 +108,7 @@ public void process(PipelineJob job, FolderImportContext ctx, VirtualFile root) InputStream folderXmlIS = subfolderDir.getInputStream("folder.xml"); if (folderXmlIS == null) { - ctx.getLogger().error("Could not find expected folder.xml file: " + getFilePath(subfoldersDir, subfolderName)); + ctx.getLogger().error("Could not find expected folder.xml file: {}", getFilePath(subfoldersDir, subfolderName)); continue; } FolderDocument folderXml = FolderDocument.Factory.parse(folderXmlIS); @@ -124,27 +124,27 @@ public void process(PipelineJob job, FolderImportContext ctx, VirtualFile root) // set the child container to inherit permissions from the parent by default SecurityManager.setInheritPermissions(childContainer); - ctx.getLogger().info("New folder created with inherited permissions: " + childContainer.getPath()); + ctx.getLogger().info("New folder created with inherited permissions: {}", childContainer.getPath()); } else { if (!childContainer.hasPermission(ctx.getUser(), AdminPermission.class)) { - ctx.getLogger().error("You must have admin permissions to replace this subfolder: " + childContainer.getPath()); + ctx.getLogger().error("You must have admin permissions to replace this subfolder: {}", childContainer.getPath()); continue; } } // import the subfolder with the folderDir as the root with a new import context - ctx.getLogger().info("Loading folder archive for " + subfolderName); + ctx.getLogger().info("Loading folder archive for {}", subfolderName); FolderImportContext folderCtx = new FolderImportContext(ctx.getUser(), childContainer, folderXml, ctx.getDataTypes(), ctx.getLoggerGetter(), subfolderDir); FolderImporterImpl importer = new FolderImporterImpl(job); importer.process(job, folderCtx, subfolderDir); - ctx.getLogger().info("Done importing folder archive for " + subfolderName); + ctx.getLogger().info("Done importing folder archive for {}", subfolderName); } } - ctx.getLogger().info("Done importing " + getDescription()); + ctx.getLogger().info("Done importing {}", getDescription()); } } diff --git a/core/src/org/labkey/core/admin/sitevalidation/SiteValidationServiceImpl.java b/core/src/org/labkey/core/admin/sitevalidation/SiteValidationServiceImpl.java index 50bd6653db1..80c2c0a603e 100644 --- a/core/src/org/labkey/core/admin/sitevalidation/SiteValidationServiceImpl.java +++ b/core/src/org/labkey/core/admin/sitevalidation/SiteValidationServiceImpl.java @@ -123,7 +123,7 @@ public Map findDuplicates(List files) File parentDir = null; - try - { - parentDir = parent instanceof AttachmentDirectory ? ((AttachmentDirectory) parent).getFileSystemDirectory() : null; - } - catch (MissingRootDirectoryException ex) - { - /* no problem */ - } + parentDir = parent instanceof AttachmentDirectory ? ((AttachmentDirectory) parent).getFileSystemDirectory() : null; if (null == parentDir || !parentDir.exists()) return attachmentsFromDatabase; @@ -1297,14 +1282,7 @@ public boolean exists() { if (null == ((AttachmentDirectory)_parent).getName()) { - try - { - return null != svc.getMappedAttachmentDirectory(ContainerManager.getForId(_parent.getContainerId()), false); - } - catch (MissingRootDirectoryException x) - { - return false; - } + return null != svc.getMappedAttachmentDirectory(ContainerManager.getForId(_parent.getContainerId()), false); } else { @@ -1481,12 +1459,6 @@ public boolean exists() return true; } - @Override - public boolean isCollection() - { - return false; - } - @Override public boolean canRename(User user, boolean forRename) { @@ -1511,7 +1483,7 @@ public FileStream getFileStream(User user) throws IOException List files = getAttachmentFiles(_parent, Collections.singletonList(r)); if (files.isEmpty()) throw new FileNotFoundException(r.getName()); - return files.get(0); + return files.getFirst(); } @Override @@ -1633,16 +1605,9 @@ public long getContentLength() if (_parent instanceof AttachmentDirectory) { - try - { - File dir = ((AttachmentDirectory)_parent).getFileSystemDirectory(); - File file = new File(dir,a.getName()); - return file.exists() ? file.length() : 0; - } - catch (MissingRootDirectoryException x) - { - return 0; - } + File dir = ((AttachmentDirectory)_parent).getFileSystemDirectory(); + File file = new File(dir,a.getName()); + return file.exists() ? file.length() : 0; } else { @@ -1679,15 +1644,8 @@ public File getFile() { if (_parent instanceof AttachmentDirectory) { - try - { - File dir = ((AttachmentDirectory)_parent).getFileSystemDirectory(); - return new File(dir,getName()); - } - catch (MissingRootDirectoryException x) - { - return null; - } + File dir = ((AttachmentDirectory)_parent).getFileSystemDirectory(); + return new File(dir,getName()); } return null; } @@ -1772,7 +1730,7 @@ public void testDirectories() throws IOException svc.addAttachments(attachParent, files, user); List att = svc.getAttachments(attachParent); assertEquals(1, att.size()); - assertTrue(att.get(0).getFile().exists()); + assertTrue(att.getFirst().getFile().exists()); // test rename String oldName = f.getName(); @@ -1797,8 +1755,8 @@ public void testDirectories() throws IOException svc.addAttachments(namedParent, files, user); att = svc.getAttachments(namedParent); assertEquals(1, att.size()); - assertTrue(att.get(0).getFile().exists()); - assertSameFile(FileUtil.appendName(otherDir, "file.txt"), att.get(0).getFile()); + assertTrue(att.getFirst().getFile().exists()); + assertSameFile(FileUtil.appendName(otherDir, "file.txt"), att.getFirst().getFile()); assertTrue(FileUtil.appendName(otherDir, UPLOAD_LOG).exists()); fileService.unregisterDirectory(folder, "test"); @@ -1817,7 +1775,7 @@ public void testDirectories() throws IOException att = svc.getAttachments(relativeParent); assertEquals(1, att.size()); - File expectedFile1 = att.get(0).getFile(); + File expectedFile1 = att.getFirst().getFile(); File expectedFile2 = FileUtil.appendName(relativeDir, UPLOAD_LOG); assertTrue(expectedFile1.exists()); diff --git a/core/src/org/labkey/core/dialect/PostgreSql92Dialect.java b/core/src/org/labkey/core/dialect/PostgreSql92Dialect.java index 540c61e0eda..6e9b51ddbe0 100644 --- a/core/src/org/labkey/core/dialect/PostgreSql92Dialect.java +++ b/core/src/org/labkey/core/dialect/PostgreSql92Dialect.java @@ -1118,7 +1118,7 @@ public void exec(ResultSet rs) throws SQLException } catch (BadSqlGrammarException x) { - LOG.warn("could not clean up postgres function : temp." + name, x); + LOG.warn("could not clean up postgres function : temp.{}", name, x); } } }); diff --git a/core/src/org/labkey/core/junit/JunitController.java b/core/src/org/labkey/core/junit/JunitController.java index 70645b658a9..cd99fce9a95 100644 --- a/core/src/org/labkey/core/junit/JunitController.java +++ b/core/src/org/labkey/core/junit/JunitController.java @@ -376,9 +376,9 @@ public Collection getStatus(@Nullable Integer offset) @Override public void run() { - for (Class testClass : _testClasses) + for (Class testClass : _testClasses) { - _log.info("Running " + testClass.getName()); + _log.info("Running {}", testClass.getName()); _results.add(JunitRunner.run(testClass)); } @@ -390,7 +390,7 @@ public void run() // Used by DRT JUnitTest to retrieve the current list of tests @SuppressWarnings({"UnusedDeclaration"}) @RequiresSiteAdmin - public static class Testlist extends ReadOnlyApiAction + public static class Testlist extends ReadOnlyApiAction { @Override public ApiResponse execute(Object o, BindException errors) @@ -443,7 +443,7 @@ public Object execute(TestForm form, BindException errors) throws Exception if (testCase == null) throw new RuntimeException("testCase parameter required"); - Class clazz = findTestClass(form.getTestCase()); + Class clazz = findTestClass(form.getTestCase()); JunitRunner.RunnerResult result = JunitRunner.run(clazz); if (!result.junitResult.wasSuccessful()) @@ -578,7 +578,7 @@ public ModelAndView getView(Object o, BindException errors) throws Exception HttpServletResponse response = getViewContext().getResponse(); TestContext.setTestContext(request, (User) request.getUserPrincipal()); - Class clazz = findTestClass("org.labkey.api.data.DbSchema$TestCase"); + Class clazz = findTestClass("org.labkey.api.data.DbSchema$TestCase"); JunitRunner.RunnerResult result = new JunitRunner.RunnerResult(); if (null != clazz) @@ -589,7 +589,7 @@ public ModelAndView getView(Object o, BindException errors) throws Exception status = HttpServletResponse.SC_INTERNAL_SERVER_ERROR; String time = format.format(new Date()); - String statusString = "" + status + ": " + time + " " + request.getHeader("User-Agent"); + String statusString = status + ": " + time + " " + request.getHeader("User-Agent"); if (list.size() > 20) list.removeFirst(); list.add(statusString); @@ -603,7 +603,7 @@ public ModelAndView getView(Object o, BindException errors) throws Exception out.println(status == HttpServletResponse.SC_OK ? "OK" : "ERROR"); out.println(); out.println("history"); - for (ListIterator it = list.listIterator(list.size()); it.hasPrevious();) + for (ListIterator it = list.listIterator(list.size()); it.hasPrevious();) out.println(it.previous()); response.flushBuffer(); diff --git a/core/src/org/labkey/core/junit/JunitRunner.java b/core/src/org/labkey/core/junit/JunitRunner.java index f5fad578609..da8a0c8223b 100644 --- a/core/src/org/labkey/core/junit/JunitRunner.java +++ b/core/src/org/labkey/core/junit/JunitRunner.java @@ -52,13 +52,13 @@ public static class RunnerResult Map> individualPerfResults; } - static RunnerResult run(Class clazz, String method) + static RunnerResult run(Class clazz, String method) { Request request = Request.method(clazz, method); return run(request); } - static RunnerResult run(Class clazz) + static RunnerResult run(Class clazz) { assert !TestCase.class.isAssignableFrom(clazz) : clazz + " is not a TestCase"; Request request = Request.classes(clazz); @@ -76,7 +76,7 @@ private static RunnerResult run(Request request) try { - LOG.info("Starting suite: " + description + " (" + StringUtilsLabKey.pluralize(desc.testCount(), "test") + ")"); + LOG.info("Starting suite: {} ({})", description, StringUtilsLabKey.pluralize(desc.testCount(), "test")); ArrayList allTimers = new ArrayList<>(); Map> testTimers = new LinkedHashMap<>(); @@ -86,14 +86,14 @@ private static RunnerResult run(Request request) @Override public void testStarted(Description description) { - LOG.debug("Starting test: " + description); + LOG.debug("Starting test: {}", description); TestContext.get().clearPerfResults(); } @Override public void testFinished(Description description) { - LOG.debug("Finished test: " + description); + LOG.debug("Finished test: {}", description); ArrayList timers = TestContext.get().getPerfResults(); testTimers.put(description, timers); allTimers.addAll(timers); @@ -103,7 +103,7 @@ public void testFinished(Description description) public void testFailure(Failure failure) { Throwable t = failure.getException(); - LOG.error("Test failed: " + failure.getDescription() + ":\n" + JunitController.renderTrace(t)); + LOG.error("Test failed: {}:\n{}", failure.getDescription(), JunitController.renderTrace(t)); } }); Result result = core.run(request); @@ -118,7 +118,7 @@ public void testFailure(Failure failure) finally { TestContext.get().clearPerfResults(); - LOG.info("Completed suite: " + description); + LOG.info("Completed suite: {}", description); } } } diff --git a/core/src/org/labkey/core/login/DbLoginAuthenticationProvider.java b/core/src/org/labkey/core/login/DbLoginAuthenticationProvider.java index bd17dc56082..d716b314bac 100644 --- a/core/src/org/labkey/core/login/DbLoginAuthenticationProvider.java +++ b/core/src/org/labkey/core/login/DbLoginAuthenticationProvider.java @@ -218,7 +218,7 @@ public boolean test(HttpServletRequest httpServletRequest) int c = _count.incrementAndGet(); if (c % 10 == 0) - LogManager.getLogger(DbLoginAuthenticationProvider.class).info(c + " requests"); + LogManager.getLogger(DbLoginAuthenticationProvider.class).info("{} requests", c); return c % 100 != 0; } diff --git a/core/src/org/labkey/core/login/LoginController.java b/core/src/org/labkey/core/login/LoginController.java index d9f0349a3bf..c270444e091 100644 --- a/core/src/org/labkey/core/login/LoginController.java +++ b/core/src/org/labkey/core/login/LoginController.java @@ -472,7 +472,7 @@ else if (UserManager.userExists(email)) { if (!expectedKatpcha.equalsIgnoreCase(StringUtils.trimToNull(form.getKaptchaText()))) { - logger.warn("Captcha text did not match for self-registration attempt for " + form.getEmail()); + logger.warn("Captcha text did not match for self-registration attempt for {}", form.getEmail()); errors.reject(ERROR_MSG,"Verification text does not match, please retry."); } } @@ -485,7 +485,7 @@ public Object execute(RegisterForm form, BindException errors) throws Exception if (!AuthenticationManager.isRegistrationEnabled()) { - _log.warn("Attempt to register user using email " + form.getEmail() + " with registration not enabled"); + _log.warn("Attempt to register user using email {} with registration not enabled", form.getEmail()); throw new NotFoundException("Registration is not enabled."); } @@ -1601,9 +1601,9 @@ protected void verifyBeforeView(SetPasswordForm form, boolean reshow, BindExcept if (errors.hasErrors()) { if (_unrecoverableError) - _log.warn("Verification failed: " + form.getEmail() + " " + form.getVerification()); + _log.warn("Verification failed: {} {}", form.getEmail(), form.getVerification()); else - _log.warn("Password entry error: " + form.getEmail()); + _log.warn("Password entry error: {}", form.getEmail()); } } diff --git a/core/src/org/labkey/core/notification/EmailServiceImpl.java b/core/src/org/labkey/core/notification/EmailServiceImpl.java index 15ece529e82..079712b3085 100644 --- a/core/src/org/labkey/core/notification/EmailServiceImpl.java +++ b/core/src/org/labkey/core/notification/EmailServiceImpl.java @@ -95,7 +95,7 @@ public void sendMessages(Collection msgs, User user, Container c) } catch (MessagingException e) { - _log.error("Failed to send message: " + msg.getSubject(), e); + _log.error("Failed to send message: {}", msg.getSubject(), e); } } diff --git a/core/src/org/labkey/core/notification/NotificationEndpoint.java b/core/src/org/labkey/core/notification/NotificationEndpoint.java index 8d57c876193..a03f29c895d 100644 --- a/core/src/org/labkey/core/notification/NotificationEndpoint.java +++ b/core/src/org/labkey/core/notification/NotificationEndpoint.java @@ -74,7 +74,7 @@ public void onOpen(Session session, EndpointConfig endpointConfig) Integer id = asInteger(endpointConfig.getUserProperties().get("userId")); this.userId = null==id ? 0 : id; - LOG.debug(this + " onOpen"); + LOG.debug("{} onOpen", this); synchronized (endpointsMap) { if (this.userId > 0) @@ -96,7 +96,7 @@ public void incoming(String message) @Override public void onClose(Session session, CloseReason closeReason) { - LOG.debug(this + " onClose: " + closeReason.toString()); + LOG.debug("{} onClose: {}", this, closeReason.toString()); synchronized (endpointsMap) { endpointsMap.removeMapping(this.userId, this); @@ -109,7 +109,7 @@ public void onClose(Session session, CloseReason closeReason) public void onError(Session session, Throwable throwable) { this.errored = true; - LOG.debug(this + " onError: " + throwable.getMessage()); + LOG.debug("{} onError: {}", this, throwable.getMessage()); super.onError(session, throwable); } @@ -183,7 +183,7 @@ private boolean safely(Fn fn) } catch (Exception x) { - LOG.debug(this + ": " + x.getMessage()); + LOG.debug("{}: {}", this, x.getMessage()); // NOTE: This NotificationEndpoint will be removed from the endpointsMap in onClose, called from WsSocket.close() // but remember it is a bad endpoint if someone tries to use it before the onClose method runs. this.errored = true; @@ -207,7 +207,7 @@ private static void sendEvent(List userIds, String eventName) { endpoint.safely(() -> { endpoint.session.getBasicRemote().sendText(data); - LOG.debug(endpoint + " sendText: " + eventName); + LOG.debug("{} sendText: {}", endpoint, eventName); }); count++; } @@ -215,9 +215,9 @@ private static void sendEvent(List userIds, String eventName) if (count == 0) { if (userIds.size() == 1) - LOG.debug("WebSocket: no sessions to send for " + userIds.get(0) + ": " + eventName); + LOG.debug("WebSocket: no sessions to send for {}: {}", userIds.getFirst(), eventName); else - LOG.debug("WebSocket: no sessions to send:" + eventName); + LOG.debug("WebSocket: no sessions to send:{}", eventName); } } diff --git a/core/src/org/labkey/core/portal/PortalJUnitTest.java b/core/src/org/labkey/core/portal/PortalJUnitTest.java index 08d4dfac9be..d67a2a8ec24 100644 --- a/core/src/org/labkey/core/portal/PortalJUnitTest.java +++ b/core/src/org/labkey/core/portal/PortalJUnitTest.java @@ -105,7 +105,7 @@ public void testPortal() //Make sure we have a part on our new page parts = Portal.getParts(folder, newPageGuid); assertEquals(1, parts.size()); - Map props = parts.get(0).getPropertyMap(); + Map props = parts.getFirst().getPropertyMap(); assertEquals("testPage", props.get("pageName")); Portal.addPart(folder, newPageGuid, filesFactory, location_body, -1, null); parts = Portal.getEditableParts(folder, newPageGuid); diff --git a/core/src/org/labkey/core/portal/ProjectController.java b/core/src/org/labkey/core/portal/ProjectController.java index 5ced5548be5..4a8a140d1a6 100644 --- a/core/src/org/labkey/core/portal/ProjectController.java +++ b/core/src/org/labkey/core/portal/ProjectController.java @@ -520,7 +520,7 @@ public void export(Object o, HttpServletResponse response, BindException errors) { iconPath = FolderType.NONE.getFolderIconPath(); iconFile = new File(ModuleLoader.getServletContext().getRealPath(iconPath)); //fall back to default - _log.warn("Could not find specified icon: "+iconPath); + _log.warn("Could not find specified icon: {}", iconPath); } Map headers = new HashMap<>(); headers.put("Cache-Control", "max-age=" + TimeUnit.DAYS.toSeconds(1)); diff --git a/core/src/org/labkey/core/products/ProductController.java b/core/src/org/labkey/core/products/ProductController.java index 12e9aa1c47a..353235aacea 100644 --- a/core/src/org/labkey/core/products/ProductController.java +++ b/core/src/org/labkey/core/products/ProductController.java @@ -92,7 +92,7 @@ public void validateForm(MenuItemsForm menuItemsForm, Errors errors) _productIds = Arrays.asList(menuItemsForm.getProductIds().split(",")); String missingProducts = _productIds.stream().filter(productId -> !registry.containsProductId(productId)).collect(Collectors.joining(", ")); if (!missingProducts.isEmpty()) - _log.warn("No such products: " + missingProducts); + _log.warn("No such products: {}", missingProducts); } } diff --git a/core/src/org/labkey/core/query/ApiKeysUpdateService.java b/core/src/org/labkey/core/query/ApiKeysUpdateService.java index 908f47e9706..7b4525d7ed5 100644 --- a/core/src/org/labkey/core/query/ApiKeysUpdateService.java +++ b/core/src/org/labkey/core/query/ApiKeysUpdateService.java @@ -9,14 +9,11 @@ import org.labkey.api.query.BatchValidationException; import org.labkey.api.query.DefaultQueryUpdateService; import org.labkey.api.query.FieldKey; -import org.labkey.api.query.InvalidKeyException; -import org.labkey.api.query.QueryUpdateServiceException; import org.labkey.api.security.ApiKeyManager; import org.labkey.api.security.User; import org.labkey.api.security.permissions.UserManagementPermission; import org.labkey.api.view.UnauthorizedException; -import java.sql.SQLException; import java.util.List; import java.util.Map; @@ -34,7 +31,7 @@ public ApiKeysUpdateService(TableInfo tableInfo, TableInfo dbTable) } @Override - public List> updateRows(User user, Container container, List> rows, List> oldKeys, BatchValidationException errors, @Nullable Map configParameters, Map extraScriptContext) throws InvalidKeyException, BatchValidationException, QueryUpdateServiceException, SQLException + public List> updateRows(User user, Container container, List> rows, List> oldKeys, BatchValidationException errors, @Nullable Map configParameters, Map extraScriptContext) { throw new UnsupportedOperationException("Updates are not allowed for this table."); } diff --git a/core/src/org/labkey/core/query/CoreQuerySchema.java b/core/src/org/labkey/core/query/CoreQuerySchema.java index 888c92a4bf0..939dacf093f 100644 --- a/core/src/org/labkey/core/query/CoreQuerySchema.java +++ b/core/src/org/labkey/core/query/CoreQuerySchema.java @@ -641,7 +641,7 @@ protected TableInfo getUsersAndGroupsTable() TableInfo t; t = def.getTable(this, errors, true); if (!errors.isEmpty()) - throw errors.get(0); + throw errors.getFirst(); ((BaseColumnInfo)t.getColumn("UserId")).setDisplayColumnFactory(new DisplayColumnFactory() { @Override diff --git a/core/src/org/labkey/core/query/UsersDomainKind.java b/core/src/org/labkey/core/query/UsersDomainKind.java index 20fc332bf43..34f17f07dbe 100644 --- a/core/src/org/labkey/core/query/UsersDomainKind.java +++ b/core/src/org/labkey/core/query/UsersDomainKind.java @@ -18,7 +18,6 @@ import org.jetbrains.annotations.NotNull; import org.json.JSONObject; import org.labkey.api.collections.CaseInsensitiveHashMap; -import org.labkey.api.collections.CaseInsensitiveHashSet; import org.labkey.api.data.ColumnInfo; import org.labkey.api.data.Container; import org.labkey.api.data.ContainerManager; diff --git a/core/src/org/labkey/core/query/UsersTable.java b/core/src/org/labkey/core/query/UsersTable.java index 06928e215fa..768aecb27c3 100644 --- a/core/src/org/labkey/core/query/UsersTable.java +++ b/core/src/org/labkey/core/query/UsersTable.java @@ -300,7 +300,7 @@ protected Collection addDomainColumns() if (!(col instanceof NullColumnInfo)) { if (col.getScale() != pd.getScale()) - LOG.warn("Scale doesn't match for column " + col.getName() + ": " + col.getScale() + " vs " + pd.getScale()); + LOG.warn("Scale doesn't match for column {}: {} vs {}", col.getName(), col.getScale(), pd.getScale()); pd.copyTo( (ColumnRenderPropertiesImpl)col ); if (!col.isHidden()) defaultCols.add(FieldKey.fromParts(col.getName())); @@ -471,13 +471,13 @@ public void fireRowTrigger(Container c, User user, TriggerType type, @Nullable Q private static class UsersTableQueryUpdateService extends SimpleQueryUpdateService { - public UsersTableQueryUpdateService(SimpleUserSchema.SimpleTable queryTable, TableInfo dbTable, DomainUpdateHelper helper) + public UsersTableQueryUpdateService(SimpleUserSchema.SimpleTable queryTable, TableInfo dbTable, DomainUpdateHelper helper) { super(queryTable, dbTable, helper); } @Override - protected Map deleteRow(User user, Container container, Map oldRowMap) throws QueryUpdateServiceException, SQLException, InvalidKeyException + protected Map deleteRow(User user, Container container, Map oldRowMap) { throw new UnsupportedOperationException("Delete not supported."); } diff --git a/core/src/org/labkey/core/reader/DataLoaderServiceImpl.java b/core/src/org/labkey/core/reader/DataLoaderServiceImpl.java index 951a98f0b16..424f8a85842 100644 --- a/core/src/org/labkey/core/reader/DataLoaderServiceImpl.java +++ b/core/src/org/labkey/core/reader/DataLoaderServiceImpl.java @@ -193,7 +193,7 @@ public DataLoaderFactory findFactory(String filename, @Nullable String contentTy if (matches.size() > 1) _log.warn("More than one DataLoader FileType matches"); - return matches.get(0); + return matches.getFirst(); } // No file extension or all FileType for that extension didn't match. @@ -210,7 +210,7 @@ public DataLoaderFactory findFactory(String filename, @Nullable String contentTy if (matches.size() > 1) _log.warn("More than one DataLoader FileType matches"); - return matches.get(0); + return matches.getFirst(); } return null; diff --git a/core/src/org/labkey/core/reports/ScriptEngineManagerImpl.java b/core/src/org/labkey/core/reports/ScriptEngineManagerImpl.java index fe719508720..75adc7c1b40 100644 --- a/core/src/org/labkey/core/reports/ScriptEngineManagerImpl.java +++ b/core/src/org/labkey/core/reports/ScriptEngineManagerImpl.java @@ -94,7 +94,7 @@ public class ScriptEngineManagerImpl extends ScriptEngineManager implements LabK // cache engine definitions by: // - "ALL" -> all engines // - container+context -> engines scoped to a single container and context enum - private static final BlockingCache> ENGINE_DEFINITION_CACHE = CacheManager.getBlockingStringKeyCache(100, CacheManager.DAY, "Script engine definitions", (key, argument) -> { + private static final BlockingCache> ENGINE_DEFINITION_CACHE = CacheManager.getBlockingStringKeyCache(100, CacheManager.DAY, "Script engine definitions", (key, _) -> { if (ALL_ENGINES.equals(key)) { // fetch all script engine definitions @@ -345,7 +345,7 @@ else if (def.isRemote()) } else if (def.getType().equals(ExternalScriptEngineDefinition.Type.Jupyter) && !PremiumService.get().isEnabled()) { - LOG.error(String.format("Jupyter Report engine [%1$s] requested, but premium module not available/enabled.", def.getName())); + LOG.error("Jupyter Report engine [{}] requested, but premium module not available/enabled.", def.getName()); throw new PremiumFeatureNotEnabledException("Jupyter Reports are not available. Please talk to your account representative for additional information."); } else @@ -557,7 +557,7 @@ public void deleteDefinition(@NotNull User user, @NotNull ExternalScriptEngineDe } } else - LOG.error("Script engine definition cannot be deleted: " + def.getName()); + LOG.error("Script engine definition cannot be deleted: {}", def.getName()); } @Override diff --git a/core/src/org/labkey/core/script/RhinoScriptEngine.java b/core/src/org/labkey/core/script/RhinoScriptEngine.java index 63b66749430..6e048a22979 100644 --- a/core/src/org/labkey/core/script/RhinoScriptEngine.java +++ b/core/src/org/labkey/core/script/RhinoScriptEngine.java @@ -181,7 +181,7 @@ protected ScriptableObject createTopLevel() "com.sun.phobos.script.javascript.JSAdapter", false); // add top level functions - String names[] = { "bindings", "scope", "sync" }; + String[] names = { "bindings", "scope", "sync" }; top.defineFunctionProperties(names, RhinoScriptEngine.class, ScriptableObject.DONTENUM); processAllTopLevelScripts(cx); diff --git a/core/src/org/labkey/core/script/RhinoService.java b/core/src/org/labkey/core/script/RhinoService.java index c317b9438fe..561000573ad 100644 --- a/core/src/org/labkey/core/script/RhinoService.java +++ b/core/src/org/labkey/core/script/RhinoService.java @@ -220,14 +220,14 @@ public void testModuleResourceCache() .mapToInt(Map::size) .sum(); - LOG.info(scriptCount + " scripts in all modules"); + LOG.info("{} scripts in all modules", scriptCount); // Load all the top-level script timestamps to ensure no exceptions and get a count int timestampCount = LabKeyModuleSourceProvider.TOP_LEVEL_SCRIPT_CACHE.streamAllResourceMaps() .mapToInt(Map::size) .sum(); - LOG.info(timestampCount + " top-level script timestamps in all modules"); + LOG.info("{} top-level script timestamps in all modules", timestampCount); assertEquals("Mismatch in counts for JavaScript scripts vs. script timestamps", scriptCount, timestampCount); @@ -285,7 +285,7 @@ public Map load(Stream resources, Modu RhinoEngine engine = RhinoService.RHINO_FACTORY.getScriptEngine(); Context ctx = Context.enter(); - LOG.debug("Compiling script '" + r.toString() + "'"); + LOG.debug("Compiling script '{}'", r.toString()); try (Reader reader = Readers.getReader(r.getInputStream())) { @@ -294,7 +294,7 @@ public Map load(Stream resources, Modu } catch (Throwable t) { - LOG.error("Failed to compile script '" + r + "': " + t.getMessage()); + LOG.error("Failed to compile script '{}': {}", r, t.getMessage()); return null; } finally @@ -412,7 +412,7 @@ public Object eval(Map map) throws ScriptException } ctxt.getBindings(ScriptContext.ENGINE_SCOPE).put(ScriptEngine.FILENAME, _path.toString()); - LOG.debug("Evaluating script '" + _path + "'"); + LOG.debug("Evaluating script '{}'", _path); Object result = _script.eval(ctxt); _evaluated = true; return result; @@ -456,7 +456,7 @@ public T invokeFn(Class resultType, Object thiz, String name, Object... a Context ctx = Context.enter(); try { - LOG.debug("Invoking method '" + name + "' in script '" + _path.toString() + "'"); + LOG.debug("Invoking method '{}' in script '{}'", name, _path.toString()); Object result = _engine.invokeMethod(thiz, name, args); if (result == null) return null; @@ -484,7 +484,7 @@ public T invokeFn(Class resultType, String name, Object... args) throws S Context ctx = Context.enter(); try { - LOG.debug("Invoking method '" + name + "' in script '" + _path.toString() + "'"); + LOG.debug("Invoking method '{}' in script '{}'", name, _path.toString()); ScriptContext ctxt = getContext(); Scriptable scope = _engine.getRuntimeScope(ctxt); Object result = _engine.invokeMethod(scope, name, args); @@ -586,7 +586,7 @@ protected ModuleSource load(String moduleScript, Object validator) return null; } - LOG.debug("Loading require()'ed resource '" + path.toString() + "'"); + LOG.debug("Loading require()'ed resource '{}'", path.toString()); RhinoScriptRef ref = new RhinoScriptRef(res); try diff --git a/core/src/org/labkey/core/statistics/FourParameterSimplex.java b/core/src/org/labkey/core/statistics/FourParameterSimplex.java index 0fc3f2293b7..fa0085928ca 100644 --- a/core/src/org/labkey/core/statistics/FourParameterSimplex.java +++ b/core/src/org/labkey/core/statistics/FourParameterSimplex.java @@ -77,8 +77,8 @@ protected SigmoidalParameters calculateFitParameters(double minValue, double max } } - _log.info("optimizer : " + _lastOptimizer + " fit error : " + calculateFitError(createParams(_bestFit))); - _log.info("params " + createParams(_bestFit).toMap()); + _log.info("optimizer : {} fit error : {}", _lastOptimizer, calculateFitError(createParams(_bestFit))); + _log.info("params {}", createParams(_bestFit).toMap()); return createParams(_bestFit); } diff --git a/core/src/org/labkey/core/statistics/ParameterCurveFit.java b/core/src/org/labkey/core/statistics/ParameterCurveFit.java index 12ed7d5723b..a9376623ed3 100644 --- a/core/src/org/labkey/core/statistics/ParameterCurveFit.java +++ b/core/src/org/labkey/core/statistics/ParameterCurveFit.java @@ -160,8 +160,8 @@ protected SigmoidalParameters computeParameters() values.add(point.getY()); Collections.sort(values); - double minValue = values.get(0); - double maxValue = values.get(values.size() - 1); + double minValue = values.getFirst(); + double maxValue = values.getLast(); return calculateFitParameters(minValue, maxValue); } diff --git a/core/src/org/labkey/core/statistics/StatsServiceImpl.java b/core/src/org/labkey/core/statistics/StatsServiceImpl.java index b991e1ea553..6b4b2c940cc 100644 --- a/core/src/org/labkey/core/statistics/StatsServiceImpl.java +++ b/core/src/org/labkey/core/statistics/StatsServiceImpl.java @@ -65,27 +65,17 @@ public CurveFit getCurveFit(CurveFitType type, DoublePoint[] data) @Override public CurveFit getCurveFit(CurveFitType type, DoublePoint[] data, @Nullable Double asymptoteMin, @Nullable Double asymptoteMax) { - switch (type) + return switch (type) { - case THREE_PARAMETER_ALT: - return new ThreeParameterCurveFit(data, asymptoteMax); - case FOUR_PARAMETER_SIMPLEX: - return new FourParameterSimplex(data); - case FIVE_PARAMETER_ALT: - return new FiveParameterCurveFit(data, asymptoteMin, asymptoteMax); - case THREE_PARAMETER: - return new ParameterCurveFit(data, type, 0.0, asymptoteMax); - case FOUR_PARAMETER: - case FIVE_PARAMETER: - return new ParameterCurveFit(data, type, asymptoteMin, asymptoteMax); - case POLYNOMIAL: - return new PolynomialCurveFit(data); - case LINEAR: - return new LinearCurveFit(data); - case NONE: - return new NoCurveFit(data); - } - throw new IllegalArgumentException("Unable to find a CurveFit implementation for type: " + type.name()); + case THREE_PARAMETER_ALT -> new ThreeParameterCurveFit(data, asymptoteMax); + case FOUR_PARAMETER_SIMPLEX -> new FourParameterSimplex(data); + case FIVE_PARAMETER_ALT -> new FiveParameterCurveFit(data, asymptoteMin, asymptoteMax); + case THREE_PARAMETER -> new ParameterCurveFit(data, type, 0.0, asymptoteMax); + case FOUR_PARAMETER, FIVE_PARAMETER -> new ParameterCurveFit(data, type, asymptoteMin, asymptoteMax); + case POLYNOMIAL -> new PolynomialCurveFit(data); + case LINEAR -> new LinearCurveFit(data); + case NONE -> new NoCurveFit(data); + }; } public static class TestCase extends Assert diff --git a/core/src/org/labkey/core/thumbnail/ThumbnailServiceImpl.java b/core/src/org/labkey/core/thumbnail/ThumbnailServiceImpl.java index a353e53b54b..3d160c31192 100644 --- a/core/src/org/labkey/core/thumbnail/ThumbnailServiceImpl.java +++ b/core/src/org/labkey/core/thumbnail/ThumbnailServiceImpl.java @@ -92,11 +92,11 @@ public void queueThumbnailRendering(ThumbnailProvider provider, ImageType imageT { if (!QUEUE.offer(new ThumbnailRenderingBean(provider, imageType, thumbnailType))) { - LOG.warn("Thumbnail rendering queue is full, skipping thumbnail rendering for " + provider); + LOG.warn("Thumbnail rendering queue is full, skipping thumbnail rendering for {}", provider); } else { - LOG.debug("Queued thumbnail rendering for " + provider); + LOG.debug("Queued thumbnail rendering for {}", provider); } } @@ -154,7 +154,7 @@ public void run() if (null == svc) { - LOG.warn(getClass().getSimpleName() + " is terminating because ThumbnailService is null"); + LOG.warn("{} is terminating because ThumbnailService is null", getClass().getSimpleName()); return; } @@ -164,7 +164,7 @@ public void run() while (!interrupted()) { ThumbnailRenderingBean bean = QUEUE.take(); - LOG.debug("Rendering thumbnail for " + bean.getProvider()); + LOG.debug("Rendering thumbnail for {}", bean.getProvider()); ThumbnailProvider provider = bean.getProvider(); ImageType type = bean.getImageType(); @@ -181,13 +181,13 @@ public void run() { // No matter what, clear this entry from the cache. ThumbnailCache.remove(provider, type); - LOG.debug("Finished rendering thumbnail for " + bean.getProvider()); + LOG.debug("Finished rendering thumbnail for {}", bean.getProvider()); } } } catch (InterruptedException e) { - LOG.debug(getClass().getSimpleName() + " is terminating due to interruption"); + LOG.debug("{} is terminating due to interruption", getClass().getSimpleName()); } } @@ -196,10 +196,5 @@ public void shutdownPre() { interrupt(); } - - @Override - public void shutdownStarted() - { - } } } diff --git a/core/src/org/labkey/core/vcs/VcsServiceImpl.java b/core/src/org/labkey/core/vcs/VcsServiceImpl.java index eef8701044f..287ffebc112 100644 --- a/core/src/org/labkey/core/vcs/VcsServiceImpl.java +++ b/core/src/org/labkey/core/vcs/VcsServiceImpl.java @@ -94,7 +94,7 @@ public void moveFile(File file, File destinationDirectory) private String log(File dir, String... command) { String cl = String.join(" ", command); - LOG.info(dir + ": " + cl); + LOG.info("{}: {}", dir, cl); return cl; } diff --git a/core/src/org/labkey/core/view/TableViewFormTestCase.java b/core/src/org/labkey/core/view/TableViewFormTestCase.java index 9638b4d2a75..61e77f8d5f6 100644 --- a/core/src/org/labkey/core/view/TableViewFormTestCase.java +++ b/core/src/org/labkey/core/view/TableViewFormTestCase.java @@ -220,7 +220,7 @@ public void testErrorHandling() tf.validateBind(errors); Assert.assertEquals("1 error", 1, errors.getErrorCount()); Assert.assertEquals("Date conversion error", 1, errors.getFieldErrors("datetimeNull").size()); - Assert.assertEquals("Date conversion error", "Could not convert value: garbage", errors.getFieldErrors("datetimeNull").get(0).getDefaultMessage()); + Assert.assertEquals("Date conversion error", "Could not convert value: garbage", errors.getFieldErrors("datetimeNull").getFirst().getDefaultMessage()); tf.setTypedValue("datetimeNull", new Date("6/20/2004")); Assert.assertTrue("Final form should be valid", tf.isValid()); diff --git a/core/src/org/labkey/core/view/template/bootstrap/PageTemplate.java b/core/src/org/labkey/core/view/template/bootstrap/PageTemplate.java index da1ff751f61..b1935f03ab3 100644 --- a/core/src/org/labkey/core/view/template/bootstrap/PageTemplate.java +++ b/core/src/org/labkey/core/view/template/bootstrap/PageTemplate.java @@ -127,7 +127,7 @@ private AppBar generateAppBarModel(ViewContext context, PageConfig page) { // Add the main page for the workbook to the nav trail navTrail = new ArrayList<>(navTrail); - navTrail.add(0, new NavTree(context.getContainer().getTitle(), context.getContainer().getStartURL(context.getUser()))); + navTrail.addFirst(new NavTree(context.getContainer().getTitle(), context.getContainer().getStartURL(context.getUser()))); } List appNavTrail = appBar.setNavTrail(navTrail, context); diff --git a/core/src/org/labkey/core/view/template/bootstrap/navigation.jsp b/core/src/org/labkey/core/view/template/bootstrap/navigation.jsp index d885448d20b..e778509d68e 100644 --- a/core/src/org/labkey/core/view/template/bootstrap/navigation.jsp +++ b/core/src/org/labkey/core/view/template/bootstrap/navigation.jsp @@ -127,7 +127,7 @@ <% } %> diff --git a/core/src/org/labkey/core/webdav/DavController.java b/core/src/org/labkey/core/webdav/DavController.java index c882f6dfde4..0b35dee218c 100644 --- a/core/src/org/labkey/core/webdav/DavController.java +++ b/core/src/org/labkey/core/webdav/DavController.java @@ -32,12 +32,12 @@ import org.apache.commons.lang3.time.FastDateFormat; import org.apache.logging.log4j.Level; import org.apache.logging.log4j.Logger; -import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import org.json.JSONWriter; +import org.jetbrains.annotations.NotNull; import org.junit.Assert; import org.junit.Test; import org.labkey.api.action.ApiUsageException; @@ -388,7 +388,7 @@ public ModelAndView handleRequest(HttpServletRequest request, HttpServletRespons { Closeable c = e.getKey(); Throwable t = e.getValue(); - _log.warn(c.getClass().getName() + " not closed", t); + _log.warn("{} not closed", c.getClass().getName(), t); } return null; } @@ -657,7 +657,7 @@ public void write(String str, int off, int len) throws IOException } @Override - public void write(@NotNull char[] cbuf) throws IOException + public void write(char @NotNull [] cbuf) throws IOException { super.write(cbuf); sbLogResponse.append(cbuf); @@ -708,7 +708,7 @@ protected DavAction(String method, boolean allow) } @Override - public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) + public ModelAndView handleRequest(@NotNull HttpServletRequest request, @NotNull HttpServletResponse response) { clearLastError(); @@ -719,10 +719,10 @@ public ModelAndView handleRequest(HttpServletRequest request, HttpServletRespons boolean isBasicAuthentication = SecurityManager.isBasicAuthentication(getRequest()); String username = getUser().getName(); String auth = username + (isBasicAuthentication ? ":basic" : !getUser().isGuest() ? ":session" : ""); - _log.debug(">>>> " + request.getMethod() + " " + getResourcePath() + " (" + auth + ") " + (modified==-1? "" : " (If-Modified-Since:" + DateUtil.toISO(modified) + ")")); + _log.debug(">>>> {} {} ({}) {}", request.getMethod(), getResourcePath(), auth, modified == -1 ? "" : " (If-Modified-Since:" + DateUtil.toISO(modified) + ")"); if (1==0) // verbose { - IteratorUtils.asIterator(request.getHeaderNames()).forEachRemaining(name -> _log.debug(name + ": " + request.getHeader(name))); + IteratorUtils.asIterator(request.getHeaderNames()).forEachRemaining(name -> _log.debug("{}: {}", name, request.getHeader(name))); } start = System.currentTimeMillis(); } @@ -808,9 +808,7 @@ else if ("GET".equals(method) && HttpUtil.isBrowser(getRequest())) if (!getResponse().sbLogResponse.isEmpty()) _log.debug(getResponse().sbLogResponse); WebdavStatus status = getResponse().getWebdavStatus(); - _log.debug("<<<< " + (status != null ? status.code : 0) + " " + - (null != status ? status.message : "") + " " + - DateUtil.formatDuration(System.currentTimeMillis()-start)); + _log.debug("<<<< {} {} {}", status != null ? status.code : 0, null != status ? status.message : "", DateUtil.formatDuration(System.currentTimeMillis() - start)); } return null; @@ -3185,7 +3183,7 @@ WebdavStatus doMethod() throws DavException, IOException, RedirectException { File f = resource.getFile(); if (null != f && f.exists()) - _log.debug(f.getName() + " length=" + f.length()); + _log.debug("{} length={}", f.getName(), f.length()); } } @@ -3310,7 +3308,7 @@ private void fireFileReplacedEvent(WebdavResource resource) if (null != file) FileContentService.get().fireFileReplacedEvent(file, getUser(), srcContainer); - _log.debug("fireFileReplaceEvent: " + DateUtil.formatDuration(System.currentTimeMillis() - start)); + _log.debug("fireFileReplaceEvent: {}", DateUtil.formatDuration(System.currentTimeMillis() - start)); } private void clearWebfilesFileCache(Container srcContainer) @@ -3329,7 +3327,7 @@ private void fireFileCreatedEvent(WebdavResource resource) java.nio.file.Path file = resource.getNioPath(); if (null != file) FileContentService.get().fireFileCreateEvent(file, getUser(), srcContainer); - _log.debug("fireFileCreatedEvent: " + DateUtil.formatDuration(System.currentTimeMillis() - start)); + _log.debug("fireFileCreatedEvent: {}", DateUtil.formatDuration(System.currentTimeMillis() - start)); } private void updateIndexAndDataObject(WebdavResource resource) @@ -3385,7 +3383,7 @@ private void fireFileDeletedEvent(WebdavResource resource) if (null != file) FileContentService.get().fireFileDeletedEvent(file, getUser(), srcContainer); - _log.debug("fireFileDeletedEvent: " + DateUtil.formatDuration(System.currentTimeMillis() - start)); + _log.debug("fireFileDeletedEvent: {}", DateUtil.formatDuration(System.currentTimeMillis() - start)); } private void removeFromDataObject(WebdavResource resource) @@ -3414,7 +3412,7 @@ private void deleteCollection(WebdavResource coll, Map errorL HttpServletRequest request = getRequest(); Path path = coll.getPath(); - _log.debug("Delete:" + path); + _log.debug("Delete:{}", path); String ifHeader = request.getHeader("If"); if (ifHeader == null) @@ -3441,7 +3439,7 @@ private void deleteCollection(WebdavResource coll, Map errorL if (!child.canDelete(getUser(),true,outMessage)) { child.notify(getViewContext(), "fileDeleteFailed"); - setLastError(new DavException(WebdavStatus.SC_FORBIDDEN, outMessage.isEmpty() ? null : outMessage.get(0), child.getPath())); + setLastError(new DavException(WebdavStatus.SC_FORBIDDEN, outMessage.isEmpty() ? null : outMessage.getFirst(), child.getPath())); errorList.put(childName, WebdavStatus.SC_FORBIDDEN); continue; } @@ -3657,20 +3655,20 @@ public void characters(char[] ch, int start, int length) { if (_inLastModified) { - lastModifieds.get(lastModifieds.size() - 1).append(ch, start, length); + lastModifieds.getLast().append(ch, start, length); } } }); if (lastModifieds.size() == 1) { - String lastModified = lastModifieds.get(0).toString(); + String lastModified = lastModifieds.getFirst().toString(); try { return FileTime.fromMillis(DateUtil.parseDateTime(lastModified, "EEE, dd MMM yyyy HH:mm:ss zzz").getTime()); } catch (ConversionException | ParseException e) { - _log.debug("Bad LastModified value for PROPPATCH: " + lastModified, e); + _log.debug("Bad LastModified value for PROPPATCH: {}", lastModified, e); } } } @@ -3867,7 +3865,7 @@ private void fireFileMovedEvent(@NotNull WebdavResource dest, @NotNull WebdavRes if (dest.isCollection() && dest.list() != null) dest.list().forEach(this::addToIndex); - _log.debug("fireFileMovedEvent: " + DateUtil.formatDuration(System.currentTimeMillis() - start)); + _log.debug("fireFileMovedEvent: {}", DateUtil.formatDuration(System.currentTimeMillis() - start)); } boolean isSafeCopy(WebdavResource src, WebdavResource dest) @@ -4385,7 +4383,7 @@ WebdavStatus doMethod() throws DavException, IOException, RedirectException close(writer, "lock writer"); if (_log.isDebugEnabled()) - _log.debug("lock: " + lock); + _log.debug("lock: {}", lock); if (null != resource && resource.exists()) return WebdavStatus.SC_OK; @@ -4424,7 +4422,7 @@ WebdavStatus doMethod() throws DavException if (lockTokenHeader == null) lockTokenHeader = ""; - _log.debug("lock token: " + lockTokenHeader); + _log.debug("lock token: {}", lockTokenHeader); // Checking resource locks @@ -4539,7 +4537,7 @@ private LockResult isLocked(Path path, String ifHeader) LockResult locked = _isLocked(path,ifHeader); if (_log.isDebugEnabled() && (locked!=LockResult.NOT_LOCKED || !StringUtils.isEmpty(ifHeader))) { - _log.debug(locked.name() + " " + path.toString() + " If:" + ifHeader); + _log.debug("{} {} If:{}", locked.name(), path.toString(), ifHeader); } return locked; } @@ -5029,7 +5027,7 @@ private WebdavStatus serveResource(WebdavResource resource, boolean content) request.setAttribute("org.apache.tomcat.sendfile.end", Long.valueOf(length)); request.setAttribute("org.apache.tomcat.sendfile.token", this); getResponse().setContentLength(length); - _log.debug("sendfile: " + absolutePath); + _log.debug("sendfile: {}", absolutePath); } else { @@ -5073,7 +5071,7 @@ else if (writer != null) if (ranges.size() == 1) { - Range range = ranges.get(0); + Range range = ranges.getFirst(); getResponse().addContentRange(range); long length = range.end - range.start + 1; getResponse().setContentLength(length); @@ -5857,7 +5855,7 @@ private WebdavStatus copyResource(int depth) throws DavException, IOException Path destinationPath = getDestinationPath(); if (destinationPath == null) throw new DavException(WebdavStatus.SC_BAD_REQUEST); - _log.debug("Dest path :" + destinationPath); + _log.debug("Dest path :{}", destinationPath); WebdavResource resource = resolvePath(); WebdavResource destination = resolvePath(destinationPath); @@ -5944,7 +5942,7 @@ private WebdavStatus copyResource(int depth) throws DavException, IOException */ private WebdavStatus copyResource(int depth, WebdavResource src, Map errorList, Path destPath) throws DavException { - _log.debug("Copy: " + src.getPath() + " To: " + destPath); + _log.debug("Copy: {} To: {}", src.getPath(), destPath); WebdavResource dest = resolvePath(destPath); @@ -6234,7 +6232,7 @@ public int read() throws IOException } @Override - public int read(byte[] b) throws IOException + public int read(byte @NotNull [] b) throws IOException { int r = super.read(b); if (null != bos && r > 0) @@ -6243,7 +6241,7 @@ public int read(byte[] b) throws IOException } @Override - public int read(byte[] b, int off, int len) throws IOException + public int read(byte @NotNull [] b, int off, int len) throws IOException { int r = super.read(b, off, len); if (null != bos && r > 0) @@ -6289,7 +6287,7 @@ WebdavStatus unauthorized(WebdavResource resource) throws DavException WebdavStatus unauthorized(WebdavResource resource, List messages) throws DavException { - String message = null!=messages && !messages.isEmpty() ? messages.get(0) : null; + String message = null!=messages && !messages.isEmpty() ? messages.getFirst() : null; throw new UnauthorizedException(resource, message); } @@ -6456,20 +6454,20 @@ public static ShutdownListener getShutdownListener() private void addToIndex(WebdavResource r) { - _log.debug("addToIndex: " + r.getPath()); + _log.debug("addToIndex: {}", r.getPath()); try { // a lot of tools up load temporary 0 length files, let's not index them if (!r.shouldIndex() || r.getContentLength() == 0 || r.getName().startsWith("._")) { - _log.debug("!shouldIndex(): " + r.getPath()); + _log.debug("!shouldIndex(): {}", r.getPath()); return; } } catch (IOException x) { - _log.debug("!shouldIndex(): " + r.getPath(), x); + _log.debug("!shouldIndex(): {}", r.getPath(), x); return; } @@ -6499,7 +6497,7 @@ private void addToIndex(WebdavResource r) private void removeFromIndex(WebdavResource r) { - _log.debug("removeFromIndex: " + r.getPath()); + _log.debug("removeFromIndex: {}", r.getPath()); SearchService.get().deleteResource(r.getDocumentId()); } @@ -6576,7 +6574,7 @@ public int read() throws IOException } @Override - public int read(@NotNull byte[] bytes) throws IOException + public int read(byte @NotNull [] bytes) throws IOException { access(); return super.read(bytes, 0, bytes.length); diff --git a/core/src/org/labkey/core/webdav/ModuleStaticResolverImpl.java b/core/src/org/labkey/core/webdav/ModuleStaticResolverImpl.java index 737e2d121f2..b35ad841e3b 100644 --- a/core/src/org/labkey/core/webdav/ModuleStaticResolverImpl.java +++ b/core/src/org/labkey/core/webdav/ModuleStaticResolverImpl.java @@ -165,9 +165,9 @@ public LookupResult lookupEx(Path path) if (r.exists()) { if (null != r.getFile()) - _log.debug(normalized + " -> " + r.getFile().getPath()); + _log.debug("{} -> {}", normalized, r.getFile().getPath()); else - _log.debug(normalized + " -> " + r); + _log.debug("{} -> {}", normalized, r); if (r instanceof _PublicResource) _allStaticFiles.put(normalized,r); } diff --git a/core/src/org/labkey/core/webdav/WebFilesResolverImpl.java b/core/src/org/labkey/core/webdav/WebFilesResolverImpl.java index b9c7549c1c4..d6e95fcb3f1 100644 --- a/core/src/org/labkey/core/webdav/WebFilesResolverImpl.java +++ b/core/src/org/labkey/core/webdav/WebFilesResolverImpl.java @@ -27,7 +27,6 @@ import org.labkey.api.data.SQLFragment; import org.labkey.api.files.FileContentService; import org.labkey.api.files.FileListener; -import org.labkey.api.files.MissingRootDirectoryException; import org.labkey.api.module.ModuleLoader; import org.labkey.api.security.User; import org.labkey.api.security.permissions.DeletePermission; @@ -449,16 +448,10 @@ private java.nio.file.Path getFileRootFile(Container container) FileContentService svc = FileContentService.get(); if (svc != null) { - try - { - AttachmentDirectory dir = svc.getMappedAttachmentDirectory(container, false); - if (dir != null) - return dir.getFileSystemDirectoryPath(); - } - catch (MissingRootDirectoryException e) - { - // Don't complain here, just hide the @files subfolders - } + AttachmentDirectory dir = svc.getMappedAttachmentDirectory(container, false); + if (dir != null) + return dir.getFileSystemDirectoryPath(); + } return null; } diff --git a/core/src/org/labkey/core/webdav/WebdavServlet.java b/core/src/org/labkey/core/webdav/WebdavServlet.java index 1df5580e822..cbfe8f3609c 100644 --- a/core/src/org/labkey/core/webdav/WebdavServlet.java +++ b/core/src/org/labkey/core/webdav/WebdavServlet.java @@ -74,7 +74,7 @@ protected void service(HttpServletRequest request, HttpServletResponse response) String fullPath = (null==request.getServletPath()?"":request.getServletPath()) + (null==request.getPathInfo()?"":request.getPathInfo()); - _log.debug(request.getMethod() + ": " + request.getRequestURL() + "; " + request.getPathInfo()); + _log.debug("{}: {}; {}", request.getMethod(), request.getRequestURL(), request.getPathInfo()); URLHelper helper; try { @@ -130,7 +130,7 @@ protected void service(HttpServletRequest request, HttpServletResponse response) catch (URISyntaxException e) { } - LogManager.getRootLogger().error("Improper welcome URL: " + AppProps.getInstance().getSiteWelcomePageUrlString()); + LogManager.getRootLogger().error("Improper welcome URL: {}", AppProps.getInstance().getSiteWelcomePageUrlString()); try {response.reset();}catch(IllegalStateException x){/*pass*/} } diff --git a/core/src/org/labkey/core/webdav/apache/XMLWriter.java b/core/src/org/labkey/core/webdav/apache/XMLWriter.java index 294f59c1336..6cb5dea2254 100644 --- a/core/src/org/labkey/core/webdav/apache/XMLWriter.java +++ b/core/src/org/labkey/core/webdav/apache/XMLWriter.java @@ -273,7 +273,7 @@ public void print(Node node) { } else { buffer.append(node.getLocalName()); } - Attr attrs[] = sortAttributes(node.getAttributes()); + Attr[] attrs = sortAttributes(node.getAttributes()); for ( int i = 0; i < attrs.length; i++ ) { Attr attr = attrs[i]; buffer.append(' '); @@ -375,7 +375,7 @@ protected Attr[] sortAttributes(NamedNodeMap attrs) { } int len = attrs.getLength(); - Attr array[] = new Attr[len]; + Attr[] array = new Attr[len]; for ( int i = 0; i < len; i++ ) { array[i] = (Attr)attrs.item(i); } diff --git a/core/src/org/labkey/core/wiki/HtmlRenderer.java b/core/src/org/labkey/core/wiki/HtmlRenderer.java index 8124e9da03f..e1df4970158 100644 --- a/core/src/org/labkey/core/wiki/HtmlRenderer.java +++ b/core/src/org/labkey/core/wiki/HtmlRenderer.java @@ -310,7 +310,7 @@ else if (!param.trim().isEmpty()) // Stick new definition at beginning of list -- we want to replace them in reverse order Definition definition = new Definition(substitutionType, substitutionMatcher.start(), substitutionMatcher.end(), paramMap); - definitions.add(0, definition); + definitions.addFirst(definition); wikiErrors.put(definition, paramErrors); } while (substitutionMatcher.find()); diff --git a/core/src/org/labkey/core/wiki/RadeoxMacroProxy.java b/core/src/org/labkey/core/wiki/RadeoxMacroProxy.java index d1301d0fc69..a9b26f8739e 100644 --- a/core/src/org/labkey/core/wiki/RadeoxMacroProxy.java +++ b/core/src/org/labkey/core/wiki/RadeoxMacroProxy.java @@ -16,6 +16,7 @@ package org.labkey.core.wiki; +import org.jetbrains.annotations.NotNull; import org.labkey.api.view.HttpView; import org.labkey.api.wiki.MacroProvider; import org.radeox.macro.BaseMacro; @@ -146,7 +147,7 @@ public String remove(Object key) } @Override - public void putAll(Map t) + public void putAll(@NotNull Map t) { throw new UnsupportedOperationException(); } @@ -158,7 +159,7 @@ public void clear() } @Override - public Set keySet() + public @NotNull Set keySet() { HashSet keys = new HashSet<>(); @@ -171,7 +172,7 @@ public Set keySet() } @Override - public Collection values() + public @NotNull Collection values() { ArrayList values = new ArrayList<>(); Set baseKeys = (Set) baseMap.keySet(); @@ -184,7 +185,7 @@ public Collection values() } @Override - public Set> entrySet() + public @NotNull Set> entrySet() { Set> values = new HashSet<>(); Set> baseEntries = (Set>) baseMap.entrySet(); diff --git a/core/src/org/labkey/core/wiki/RadeoxRenderer.java b/core/src/org/labkey/core/wiki/RadeoxRenderer.java index 1cf4179c142..fc018817d01 100644 --- a/core/src/org/labkey/core/wiki/RadeoxRenderer.java +++ b/core/src/org/labkey/core/wiki/RadeoxRenderer.java @@ -838,7 +838,7 @@ public void handleMatch(StringBuffer buffer, MatchResult result, FilterContext c } catch (IOException e) { - log.debug("InterWiki " + extSpace + " not found."); + log.debug("InterWiki {} not found.", extSpace); } } else diff --git a/core/src/org/radeox/EngineManager.java b/core/src/org/radeox/EngineManager.java index f7e812d5198..767ff9930c3 100644 --- a/core/src/org/radeox/EngineManager.java +++ b/core/src/org/radeox/EngineManager.java @@ -59,7 +59,7 @@ public class EngineManager { try { RenderEngine engine = iterator.next(); registerEngine(engine); - log.debug("Loaded RenderEngine: " + engine.getClass().getName()); + log.debug("Loaded RenderEngine: {}", engine.getClass().getName()); } catch (Exception e) { log.warn("EngineManager: unable to load RenderEngine", e); } diff --git a/core/src/org/radeox/filter/FilterPipe.java b/core/src/org/radeox/filter/FilterPipe.java index f205bfc3213..4c1e57250d3 100644 --- a/core/src/org/radeox/filter/FilterPipe.java +++ b/core/src/org/radeox/filter/FilterPipe.java @@ -107,7 +107,7 @@ public void addFilter(Filter filter) { } if (contains(filter.before(), FIRST_IN_PIPE)) { - filterList.add(0, filter); + filterList.addFirst(filter); } else if (minIndex != -1) { filterList.add(minIndex, filter); // } else if (contains(filter.before(), LAST_IN_PIPE)) { @@ -160,13 +160,13 @@ public String filter(String input, FilterContext context) { renderContext.setCacheable(true); } if (null == tmp) { - log.warn("FilterPipe.filter: error while filtering: " + f); + log.warn("FilterPipe.filter: error while filtering: {}", f); } else { output = tmp; } renderContext.commitCache(); } catch (Exception e) { - log.warn("Filtering exception: " + f + " in " + context.getRenderContext(), e); + log.warn("Filtering exception: {} in {}", f, context.getRenderContext(), e); } } return output; diff --git a/core/src/org/radeox/filter/LinkTestFilter.java b/core/src/org/radeox/filter/LinkTestFilter.java index b46e41fa2dd..5bf633cc185 100644 --- a/core/src/org/radeox/filter/LinkTestFilter.java +++ b/core/src/org/radeox/filter/LinkTestFilter.java @@ -137,7 +137,7 @@ public void handleMatch(StringBuffer buffer, MatchResult result, FilterContext c interWiki.expand(writer, extSpace, name, view); } } catch (IOException e) { - log.debug("InterWiki " + extSpace + " not found in " + context.getRenderContext()); + log.debug("InterWiki {} not found in {}", extSpace, context.getRenderContext()); } } else { buffer.append("["); diff --git a/core/src/org/radeox/filter/ListFilter.java b/core/src/org/radeox/filter/ListFilter.java index ee366e38066..7d4decae93f 100644 --- a/core/src/org/radeox/filter/ListFilter.java +++ b/core/src/org/radeox/filter/ListFilter.java @@ -60,12 +60,7 @@ protected String getLocaleKey() { return "filter.list"; } - @Override - protected boolean isSingleLine() { - return false; - } - - public ListFilter() { + public ListFilter() { super(); openList.put(Character.valueOf('-'), "
    "); openList.put(Character.valueOf('*'), "
      "); @@ -104,7 +99,7 @@ public void handleMatch(StringBuffer buffer, MatchResult result, FilterContext c BufferedReader reader = new BufferedReader(new StringReader(result.group(0))); addList(buffer, reader); } catch (Exception e) { - log.warn("ListFilter: unable get list content in " + context.getRenderContext(), e); + log.warn("ListFilter: unable get list content in {}", context.getRenderContext(), e); } } diff --git a/core/src/org/radeox/filter/MacroFilter.java b/core/src/org/radeox/filter/MacroFilter.java index e59c517babf..69c6baa5071 100644 --- a/core/src/org/radeox/filter/MacroFilter.java +++ b/core/src/org/radeox/filter/MacroFilter.java @@ -131,7 +131,7 @@ public void handleMatch(StringBuffer buffer, MatchResult result, FilterContext c } catch (IllegalArgumentException e) { buffer.append("
      " + PageFlowUtil.filter(command + ": " + e.getMessage()) + "
      "); } catch (Throwable e) { - log.warn("MacroFilter: unable to format macro: " + result.group(1) + " in " + context.getRenderContext(), e); + log.warn("MacroFilter: unable to format macro: {} in {}", result.group(1), context.getRenderContext(), e); buffer.append("
      " + PageFlowUtil.filter(command + ": " + e.getMessage()) + "
      "); return; } diff --git a/core/src/org/radeox/filter/WikiLinkFilter.java b/core/src/org/radeox/filter/WikiLinkFilter.java index 021e9370049..fa2335daaa3 100644 --- a/core/src/org/radeox/filter/WikiLinkFilter.java +++ b/core/src/org/radeox/filter/WikiLinkFilter.java @@ -47,9 +47,4 @@ protected String getLocaleKey() { return "filter.wikilink"; } - @Override - protected String getWikiView(String name) { - return name; - } - } diff --git a/core/src/org/radeox/filter/regex/RegexFilter.java b/core/src/org/radeox/filter/regex/RegexFilter.java index b41f3bcc2e6..783dc264ea2 100644 --- a/core/src/org/radeox/filter/regex/RegexFilter.java +++ b/core/src/org/radeox/filter/regex/RegexFilter.java @@ -109,7 +109,7 @@ public void addRegex(String regex, String substitute, boolean multiline) } catch (Exception e) { - log.warn("bad pattern: " + regex + " -> " + substitute, e); + log.warn("bad pattern: {} -> {}", regex, substitute, e); } } diff --git a/core/src/org/radeox/filter/regex/RegexTokenFilter.java b/core/src/org/radeox/filter/regex/RegexTokenFilter.java index a968ffe2c3b..78f5c1d444c 100644 --- a/core/src/org/radeox/filter/regex/RegexTokenFilter.java +++ b/core/src/org/radeox/filter/regex/RegexTokenFilter.java @@ -90,9 +90,9 @@ public String filter(String input, final FilterContext context) { // result = Util.substitute(matcher, p, new ActionSubstitution(s, this, context), result, limit); } catch (Exception e) { - log.warn("Exception: " + this + " in " + context.getRenderContext(), e); + log.warn("Exception: {} in {}", this, context.getRenderContext(), e); } catch (Error err) { - log.warn("Error: " + this + " in " + context.getRenderContext(), err); + log.warn("Error: {} in {}", this, context.getRenderContext(), err); } input = result; } diff --git a/core/src/org/radeox/macro/BaseLocaleMacro.java b/core/src/org/radeox/macro/BaseLocaleMacro.java index 38b8fe48d22..a2b9c918bfd 100644 --- a/core/src/org/radeox/macro/BaseLocaleMacro.java +++ b/core/src/org/radeox/macro/BaseLocaleMacro.java @@ -67,7 +67,7 @@ public void setInitialContext(InitialRenderContext context) { try { description = messages.getString(getLocaleKey()+".description"); } catch (Exception e) { - log.warn("Cannot read description from properties " + inputName + " for " + getLocaleKey() + " from " + context); + log.warn("Cannot read description from properties {} for {} from {}", inputName, getLocaleKey(), context); } } } \ No newline at end of file diff --git a/core/src/org/radeox/macro/CodeMacro.java b/core/src/org/radeox/macro/CodeMacro.java index e24eacb4b87..97382261715 100644 --- a/core/src/org/radeox/macro/CodeMacro.java +++ b/core/src/org/radeox/macro/CodeMacro.java @@ -97,11 +97,11 @@ public CodeMacro() { SourceCodeFormatter existing = formatters.get(name); if (existing.getPriority() < formatter.getPriority()) { formatters.put(name, formatter); - log.debug("Replacing formatter: " + formatter.getClass() + " (" + name + ")"); + log.debug("Replacing formatter: {} ({})", formatter.getClass(), name); } } else { formatters.put(name, formatter); - log.debug("Loaded formatter: " + formatter.getClass() + " (" + name +")"); + log.debug("Loaded formatter: {} ({})", formatter.getClass(), name); } } catch (Exception e) { log.warn("CodeMacro: unable to load code formatter", e); diff --git a/core/src/org/radeox/macro/LocalePreserved.java b/core/src/org/radeox/macro/LocalePreserved.java index be15a72b9be..d807792db78 100644 --- a/core/src/org/radeox/macro/LocalePreserved.java +++ b/core/src/org/radeox/macro/LocalePreserved.java @@ -59,7 +59,7 @@ public void setInitialContext(InitialRenderContext context) { try { description = messages.getString(getLocaleKey() + ".description"); } catch (Exception e) { - log.warn("Cannot read description from properties " + inputName + " for " + getLocaleKey()); + log.warn("Cannot read description from properties {} for {}", inputName, getLocaleKey()); } } } diff --git a/core/src/org/radeox/macro/MacroRepository.java b/core/src/org/radeox/macro/MacroRepository.java index 72dd245003d..72e5a56cde2 100644 --- a/core/src/org/radeox/macro/MacroRepository.java +++ b/core/src/org/radeox/macro/MacroRepository.java @@ -86,7 +86,7 @@ private void load() { while (iterator.hasNext()) { MacroLoader loader = (MacroLoader) iterator.next(); loader.setRepository(this); - log.debug("Loading from: " + loader.getClass()); + log.debug("Loading from: {}", loader.getClass()); loader.loadPlugins(this); } } diff --git a/core/src/org/radeox/macro/PluginLoader.java b/core/src/org/radeox/macro/PluginLoader.java index 69ffce93bbd..7188cdb07a7 100644 --- a/core/src/org/radeox/macro/PluginLoader.java +++ b/core/src/org/radeox/macro/PluginLoader.java @@ -63,7 +63,7 @@ public PluginRepository loadPlugins(PluginRepository repository, Class try { T plugin = iterator.next(); add(repository, plugin); - log.debug("PluginLoader: Loaded plugin: " + plugin.getClass()); + log.debug("PluginLoader: Loaded plugin: {}", plugin.getClass()); } catch (Exception e) { log.warn("PluginLoader: unable to load plugin", e); } diff --git a/core/src/org/radeox/macro/table/AvgFunction.java b/core/src/org/radeox/macro/table/AvgFunction.java index 48e36bbd5a6..090cb5cc019 100644 --- a/core/src/org/radeox/macro/table/AvgFunction.java +++ b/core/src/org/radeox/macro/table/AvgFunction.java @@ -59,7 +59,7 @@ public void execute(Table table, int posx, int posy, int startX, int startY, int sum += Float.parseFloat((String) table.getXY(x, y)); count++; } catch (NumberFormatException e1) { - log.debug("SumFunction: unable to parse " + table.getXY(x, y)); + log.debug("SumFunction: unable to parse {}", table.getXY(x, y)); } } } diff --git a/core/src/org/radeox/macro/table/FunctionLoader.java b/core/src/org/radeox/macro/table/FunctionLoader.java index 25274d51a89..3d975d465b9 100644 --- a/core/src/org/radeox/macro/table/FunctionLoader.java +++ b/core/src/org/radeox/macro/table/FunctionLoader.java @@ -64,7 +64,7 @@ public void add(PluginRepository repository, Object plugin) { if (plugin instanceof Function) { repository.put(((Function) plugin).getName().toLowerCase(), plugin); } else { - log.debug("FunctionLoader: " + plugin.getClass() + " not of Type " + getLoadClass()); + log.debug("FunctionLoader: {} not of Type {}", plugin.getClass(), getLoadClass()); } } diff --git a/core/src/org/radeox/macro/table/MaxFunction.java b/core/src/org/radeox/macro/table/MaxFunction.java index 544969c5a4f..4e83ff7adbf 100644 --- a/core/src/org/radeox/macro/table/MaxFunction.java +++ b/core/src/org/radeox/macro/table/MaxFunction.java @@ -59,7 +59,7 @@ public void execute(Table table, int posx, int posy, int startX, int startY, int value += Float.parseFloat((String) table.getXY(x, y)); floating = true; } catch (NumberFormatException e1) { - log.debug("SumFunction: unable to parse " + table.getXY(x, y)); + log.debug("SumFunction: unable to parse {}", table.getXY(x, y)); } } if (max < value) { diff --git a/core/src/org/radeox/macro/table/MinFunction.java b/core/src/org/radeox/macro/table/MinFunction.java index 75cc874f80d..363940fa09a 100644 --- a/core/src/org/radeox/macro/table/MinFunction.java +++ b/core/src/org/radeox/macro/table/MinFunction.java @@ -59,7 +59,7 @@ public void execute(Table table, int posx, int posy, int startX, int startY, int value += Float.parseFloat((String) table.getXY(x, y)); floating = true; } catch (NumberFormatException e1) { - log.debug("SumFunction: unable to parse " + table.getXY(x, y)); + log.debug("SumFunction: unable to parse {}", table.getXY(x, y)); } } if (min > value) { diff --git a/core/src/org/radeox/macro/table/SumFunction.java b/core/src/org/radeox/macro/table/SumFunction.java index 2e3132df1d5..325ff818e9b 100644 --- a/core/src/org/radeox/macro/table/SumFunction.java +++ b/core/src/org/radeox/macro/table/SumFunction.java @@ -58,7 +58,7 @@ public void execute(Table table, int posx, int posy, int startX, int startY, int sum += Float.parseFloat((String) table.getXY(x, y)); floating = true; } catch (NumberFormatException e1) { - log.debug("SumFunction: unable to parse " + table.getXY(x, y)); + log.debug("SumFunction: unable to parse {}", table.getXY(x, y)); } } } diff --git a/core/src/org/radeox/test/filter/BasicRegexTest.java b/core/src/org/radeox/test/filter/BasicRegexTest.java index 3d8e420b7f6..6e96c389827 100644 --- a/core/src/org/radeox/test/filter/BasicRegexTest.java +++ b/core/src/org/radeox/test/filter/BasicRegexTest.java @@ -43,6 +43,7 @@ import java.text.MessageFormat; import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; @@ -98,7 +99,7 @@ public void testWordBorders() { Matcher m = Matcher.create("test xsl test", p); assertTrue("Word found", m.contains()); m = Matcher.create("testxsltest", p); - assertTrue("Word not found", !m.contains()); + assertFalse("Word not found", m.contains()); } @org.junit.Test diff --git a/core/src/org/radeox/util/StringBufferWriter.java b/core/src/org/radeox/util/StringBufferWriter.java index 80998280523..e18fb3abda0 100644 --- a/core/src/org/radeox/util/StringBufferWriter.java +++ b/core/src/org/radeox/util/StringBufferWriter.java @@ -25,6 +25,8 @@ package org.radeox.util; +import org.jetbrains.annotations.NotNull; + import java.io.IOException; import java.io.Writer; @@ -66,7 +68,7 @@ public void write(int c) { } @Override - public void write(char cbuf[], int off, int len) { + public void write(@NotNull char[] cbuf, int off, int len) { if ((off < 0) || (off > cbuf.length) || (len < 0) || ((off + len) > cbuf.length) || ((off + len) < 0)) { throw new IndexOutOfBoundsException(); @@ -77,7 +79,7 @@ public void write(char cbuf[], int off, int len) { } @Override - public void write(String str) { + public void write(@NotNull String str) { buffer.append(str); } diff --git a/devtools/src/org/labkey/devtools/TestController.java b/devtools/src/org/labkey/devtools/TestController.java index 4e7bc2c726e..97984fa3f53 100644 --- a/devtools/src/org/labkey/devtools/TestController.java +++ b/devtools/src/org/labkey/devtools/TestController.java @@ -407,11 +407,6 @@ public MultipartFormAction() _enctype = "multipart/form-data"; } - @Override - public boolean handlePost(SimpleForm simpleForm, BindException errors) - { - return false; - } } @@ -810,21 +805,13 @@ public static class MultiExceptionAction extends SimpleViewAction @Override public ModelAndView getView(ExceptionForm form, BindException errors) throws Exception { - Exception exception; - switch (form.getMessage()) + Exception exception = switch (form.getMessage()) { - case "ISE": - exception = new IllegalStateException(); - break; - case "NPE": - exception = new NullPointerException(); - break; - case "NPE2": - exception = new NullPointerException(); - break; - default: - throw new IllegalArgumentException(form.getMessage()); - } + case "ISE" -> new IllegalStateException(); + case "NPE" -> new NullPointerException(); + case "NPE2" -> new NullPointerException(); + default -> throw new IllegalArgumentException(form.getMessage()); + }; ExceptionUtil.decorateException(exception, ExceptionUtil.ExceptionInfo.ExtraMessage, "testing", true); throw exception; } diff --git a/devtools/src/org/labkey/devtools/mascot/MockMascotServletContextListener.java b/devtools/src/org/labkey/devtools/mascot/MockMascotServletContextListener.java index 86da911e042..b517b1fd6f9 100644 --- a/devtools/src/org/labkey/devtools/mascot/MockMascotServletContextListener.java +++ b/devtools/src/org/labkey/devtools/mascot/MockMascotServletContextListener.java @@ -14,9 +14,4 @@ public void contextInitialized(ServletContextEvent servletContextEvent) ServletRegistration.Dynamic servlet = servletContextEvent.getServletContext().addServlet("MockMascotServlet", MockMascotServlet.class); servlet.addMapping("/mockmascot/*"); } - - @Override - public void contextDestroyed(ServletContextEvent servletContextEvent) - { - } } diff --git a/devtools/src/org/labkey/devtools/test/JspTestCaseTest.jsp b/devtools/src/org/labkey/devtools/test/JspTestCaseTest.jsp index 8142402c005..0a6c2d7dcd4 100644 --- a/devtools/src/org/labkey/devtools/test/JspTestCaseTest.jsp +++ b/devtools/src/org/labkey/devtools/test/JspTestCaseTest.jsp @@ -1,18 +1,20 @@ <%@ page import="org.junit.Test" %> <%@ page import="static org.junit.Assert.*" %> +<%@ page import="static org.junit.Assert.assertNotEquals" %> +<%@ page import="static org.junit.Assert.assertEquals" %> <%@ page extends="org.labkey.api.jsp.JspTest.DRT" %> <%! @Test public void test1() { - assertTrue(1==1); + assertEquals(1, 1); } @Test public void test2() { - assertFalse(0==1); + assertNotEquals(0, 1); } %> diff --git a/devtools/src/org/labkey/devtools/view/complex.jsp b/devtools/src/org/labkey/devtools/view/complex.jsp index ebc408b2c7b..aeace22aa37 100644 --- a/devtools/src/org/labkey/devtools/view/complex.jsp +++ b/devtools/src/org/labkey/devtools/view/complex.jsp @@ -73,17 +73,17 @@
<%errorRow(out,"form.beans["+i+"].c");%> - + <%errorRow(out,"form.beans["+i+"].int");%> - + <%errorRow(out,"form.beans["+i+"].positive");%> - + <%errorRow(out,"form.beans["+i+"].required");%> - - - - - + + + + + <% if (enctype.startsWith("multipart")) { diff --git a/devtools/test/src/org/labkey/test/tests/devtools/SecondaryAuthenticationTest.java b/devtools/test/src/org/labkey/test/tests/devtools/SecondaryAuthenticationTest.java index 73ee5ca71f9..67676029353 100644 --- a/devtools/test/src/org/labkey/test/tests/devtools/SecondaryAuthenticationTest.java +++ b/devtools/test/src/org/labkey/test/tests/devtools/SecondaryAuthenticationTest.java @@ -178,7 +178,7 @@ public void testSecondaryAuthentication() // validate the delete entry in the audit log after deleting selectRowsResponse = getLatestAuditEntries(); - row = selectRowsResponse.getRows().get(0); + row = selectRowsResponse.getRows().getFirst(); commentColVal = (String) row.get("Comment"); //get a value from Comment column change = (String)row.get("Changes"); diff --git a/experiment/src/org/labkey/experiment/CompressedInputStreamXarSource.java b/experiment/src/org/labkey/experiment/CompressedInputStreamXarSource.java index 58b2572578e..d6841f0947f 100644 --- a/experiment/src/org/labkey/experiment/CompressedInputStreamXarSource.java +++ b/experiment/src/org/labkey/experiment/CompressedInputStreamXarSource.java @@ -5,7 +5,6 @@ import org.jetbrains.annotations.Nullable; import org.labkey.api.data.Container; import org.labkey.api.exp.AbstractFileXarSource; -import org.labkey.api.exp.ExperimentException; import org.labkey.api.pipeline.PipelineJob; import org.labkey.api.security.User; import org.labkey.api.util.FileUtil; @@ -44,7 +43,7 @@ public CompressedInputStreamXarSource(InputStream xarInputStream, FileLike xarFi } @Override - public void init() throws IOException, ExperimentException + public void init() throws IOException { ByteArrayOutputStream byteStream = new ByteArrayOutputStream(); try (OutputStream stream = new BufferedOutputStream(byteStream)) diff --git a/experiment/src/org/labkey/experiment/CustomProperties.java b/experiment/src/org/labkey/experiment/CustomProperties.java index 1fb6f08e96b..8410c860f95 100644 --- a/experiment/src/org/labkey/experiment/CustomProperties.java +++ b/experiment/src/org/labkey/experiment/CustomProperties.java @@ -37,14 +37,14 @@ public static void iterate(Container c, Collection properties, M while (!stack.isEmpty()) { - List values = stack.get(stack.size() - 1); - int currentIndex = indices.get(indices.size() - 1); + List values = stack.getLast(); + int currentIndex = indices.getLast(); indices.set(indices.size() - 1, currentIndex + 1); if (currentIndex == values.size()) { - stack.remove(stack.size() - 1); - indices.remove(indices.size() - 1); + stack.removeLast(); + indices.removeLast(); } else { diff --git a/experiment/src/org/labkey/experiment/DataURLRelativizer.java b/experiment/src/org/labkey/experiment/DataURLRelativizer.java index 341668d4a63..39ddd2bb5a6 100644 --- a/experiment/src/org/labkey/experiment/DataURLRelativizer.java +++ b/experiment/src/org/labkey/experiment/DataURLRelativizer.java @@ -16,7 +16,6 @@ package org.labkey.experiment; -import org.labkey.api.exp.ExperimentException; import org.labkey.api.exp.api.ExpData; import org.labkey.api.exp.api.ExpRun; import org.labkey.api.security.User; @@ -25,7 +24,6 @@ import org.labkey.experiment.api.ExperimentServiceImpl; import org.labkey.experiment.controllers.exp.ExperimentController; -import java.io.IOException; import java.nio.file.Path; /** @@ -74,7 +72,7 @@ public URLRewriter createURLRewriter() return new URLRewriter() { @Override - public String rewriteURL(Path path, ExpData data, String roleName, ExpRun expRun, User user, String rootFilePath) throws ExperimentException + public String rewriteURL(Path path, ExpData data, String roleName, ExpRun expRun, User user, String rootFilePath) { if (path == null) return null; diff --git a/experiment/src/org/labkey/experiment/DerivedSamplePropertyHelper.java b/experiment/src/org/labkey/experiment/DerivedSamplePropertyHelper.java index 3c75cfb073d..aa6746e6942 100644 --- a/experiment/src/org/labkey/experiment/DerivedSamplePropertyHelper.java +++ b/experiment/src/org/labkey/experiment/DerivedSamplePropertyHelper.java @@ -164,7 +164,7 @@ protected Pair getObjectWithName(int index, @NotNull Map index) { - colName = UploadWizardAction.getInputName(getNamePDs().get(0), getSampleNames().get(index)); + colName = UploadWizardAction.getInputName(getNamePDs().getFirst(), getSampleNames().get(index)); } throw new DuplicateMaterialException("Duplicate material name: " + name, colName); } @@ -217,7 +217,7 @@ public String determineMaterialName(Map sampleProperties } else { - assert _domainProperties.get(0).getName().equals("Name"); + assert _domainProperties.getFirst().getName().equals("Name"); return sampleProperties.get(_nameProperty); } } @@ -250,8 +250,8 @@ public List getNamePDs() } else { - assert _domainProperties.get(0).getName().equals("Name"); - return Collections.singletonList(_domainProperties.get(0)); + assert _domainProperties.getFirst().getName().equals("Name"); + return Collections.singletonList(_domainProperties.getFirst()); } } } diff --git a/experiment/src/org/labkey/experiment/ExpDataIterators.java b/experiment/src/org/labkey/experiment/ExpDataIterators.java index 108fdb61148..cafc1fc8f07 100644 --- a/experiment/src/org/labkey/experiment/ExpDataIterators.java +++ b/experiment/src/org/labkey/experiment/ExpDataIterators.java @@ -943,7 +943,7 @@ public static String getAliquotParent(Object parentObj, DataIteratorContext cont { if (parents.size() > 1) context.getErrors().addRowError(new ValidationException(String.format("Multiple %s values are provided.", ALIQUOTED_FROM_INPUT))); - return parents.get(0); + return parents.getFirst(); } } @@ -1622,7 +1622,7 @@ private static Pair, Set> clea if ((dataOutputs.isEmpty() && (materialOutputs.isEmpty() || (materialOutputs.size() == 1 && materialOutputs.contains(runItem)))) || (materialOutputs.isEmpty() && dataOutputs.size() == 1 && dataOutputs.contains(runItem))) { - LOG.debug("Run item '" + runItem.getName() + "' has existing source derivation run '" + existingDerivationRun.getRowId() + "' -- run has no other outputs, deleting run"); + LOG.debug("Run item '{}' has existing source derivation run '{}' -- run has no other outputs, deleting run", runItem.getName(), existingDerivationRun.getRowId()); // if run has no other outputs, delete the run completely runItem.setSourceApplication(null); try @@ -1640,7 +1640,7 @@ private static Pair, Set> clea } else { - LOG.debug("Run item '" + runItem.getName() + "' has existing source derivation run '" + existingDerivationRun.getRowId() + "' -- run has other " + dataOutputs.size() + " data outputs and " + materialOutputs.size() + " material outputs, removing sample from run"); + LOG.debug("Run item '{}' has existing source derivation run '{}' -- run has other {} data outputs and {} material outputs, removing sample from run", runItem.getName(), existingDerivationRun.getRowId(), dataOutputs.size(), materialOutputs.size()); // if the existing run has other outputs, remove the run as the source application for this sample // and remove it as an output from the run runItem.setSourceApplication(null); diff --git a/experiment/src/org/labkey/experiment/ExperimentModule.java b/experiment/src/org/labkey/experiment/ExperimentModule.java index e4fc5989e8f..5c9c65763ae 100644 --- a/experiment/src/org/labkey/experiment/ExperimentModule.java +++ b/experiment/src/org/labkey/experiment/ExperimentModule.java @@ -133,7 +133,6 @@ import org.labkey.experiment.api.LogDataType; import org.labkey.experiment.api.Protocol; import org.labkey.experiment.api.SampleTypeServiceImpl; -import org.labkey.experiment.api.SampleTypeUpdateServiceDI; import org.labkey.experiment.api.UniqueValueCounterTestCase; import org.labkey.experiment.api.VocabularyDomainKind; import org.labkey.experiment.api.data.ChildOfCompareType; diff --git a/experiment/src/org/labkey/experiment/ExperimentQueryChangeListener.java b/experiment/src/org/labkey/experiment/ExperimentQueryChangeListener.java index f0a6c6d5201..1386efd999d 100644 --- a/experiment/src/org/labkey/experiment/ExperimentQueryChangeListener.java +++ b/experiment/src/org/labkey/experiment/ExperimentQueryChangeListener.java @@ -27,9 +27,7 @@ import java.util.Map; import java.util.regex.Pattern; -import static org.labkey.api.exp.api.ExperimentJSONConverter.DATA_INPUTS; import static org.labkey.api.exp.api.ExperimentJSONConverter.DATA_INPUTS_ALIAS_PREFIX; -import static org.labkey.api.exp.api.ExperimentJSONConverter.MATERIAL_INPUTS; import static org.labkey.api.exp.api.ExperimentJSONConverter.MATERIAL_INPUTS_ALIAS_PREFIX; public class ExperimentQueryChangeListener implements QueryChangeListener diff --git a/experiment/src/org/labkey/experiment/ExperimentUpgradeCode.java b/experiment/src/org/labkey/experiment/ExperimentUpgradeCode.java index a1825ca0bd5..8f98ff730f7 100644 --- a/experiment/src/org/labkey/experiment/ExperimentUpgradeCode.java +++ b/experiment/src/org/labkey/experiment/ExperimentUpgradeCode.java @@ -483,13 +483,13 @@ private record ProvisionedSampleTypeContext(Domain domain, SchemaTableInfo provi if (kind == null) { - LOG.info("Sample type '" + st.getName() + "' (" + st.getRowId() + ") has no domain kind."); + LOG.info("Sample type '{}' ({}) has no domain kind.", st.getName(), st.getRowId()); return null; } else if (kind.getStorageSchemaName() == null) { // e.g., SpecimenSampleTypeDomainKind is not provisioned - LOG.info("Sample type '" + st.getName() + "' (" + st.getRowId() + ") has no provisioned storage schema."); + LOG.info("Sample type '{}' ({}) has no provisioned storage schema.", st.getName(), st.getRowId()); return null; } @@ -501,7 +501,7 @@ else if (kind.getStorageSchemaName() == null) SchemaTableInfo provisionedTable = schema.getTable(domain.getStorageTableName()); if (provisionedTable == null) { - LOG.error("Sample type '" + st.getName() + "' (" + st.getRowId() + ") has no provisioned table."); + LOG.error("Sample type '{}' ({}) has no provisioned table.", st.getName(), st.getRowId()); return null; } @@ -567,7 +567,7 @@ private static void upgradeProvisionedDataClassTable(ExpDataClassImpl dc) } if (null == kind || null == kind.getStorageSchemaName()) { - LOG.error("DataClass '" + dc.getName() + "' (" + dc.getRowId() + ") has no provisioned storage schema."); + LOG.error("DataClass '{}' ({}) has no provisioned storage schema.", dc.getName(), dc.getRowId()); return; } @@ -583,7 +583,7 @@ private static void upgradeProvisionedDataClassTable(ExpDataClassImpl dc) SchemaTableInfo provisionedTable = schema.getTable(domain.getStorageTableName()); if (provisionedTable == null) { - LOG.error("DataClass '" + dc.getName() + "' (" + dc.getRowId() + ") has no provisioned table."); + LOG.error("DataClass '{}' ({}) has no provisioned table.", dc.getName(), dc.getRowId()); return; } @@ -878,7 +878,7 @@ private static boolean dropDataClassLsid(ExpDataClassImpl dc) SchemaTableInfo provisionedTable = schema.getTable(domain.getStorageTableName()); if (provisionedTable == null) { - LOG.error("DataClass '" + dc.getName() + "' (" + dc.getRowId() + ") has no provisioned table."); + LOG.error("DataClass '{}' ({}) has no provisioned table.", dc.getName(), dc.getRowId()); return false; } diff --git a/experiment/src/org/labkey/experiment/FileLinkFileListener.java b/experiment/src/org/labkey/experiment/FileLinkFileListener.java index 83b1e7ff358..a6258ff57c0 100644 --- a/experiment/src/org/labkey/experiment/FileLinkFileListener.java +++ b/experiment/src/org/labkey/experiment/FileLinkFileListener.java @@ -118,7 +118,7 @@ private int updateObjectProperty(Path srcFile, Path destFile) singleEntrySQL.add(srcPath); int rows = new SqlExecutor(OntologyManager.getExpSchema()).execute(singleEntrySQL); - LOG.info("Updated " + rows + " row in exp.ObjectProperty for move from " + srcFile + " to " + destFile); + LOG.info("Updated {} row in exp.ObjectProperty for move from {} to {}", rows, srcFile, destFile); if (rows > 0) { // Clear potential object values @@ -152,7 +152,7 @@ private int updateObjectProperty(Path srcFile, Path destFile) // Clear potential object values OntologyManager.clearPropertyCache(); } - LOG.info("Updated " + childRows + " child paths in exp.ObjectProperty rows for move from " + srcFile + " to " + destFile); + LOG.info("Updated {} child paths in exp.ObjectProperty rows for move from {} to {}", childRows, srcFile, destFile); return rows + childRows; } return rows; diff --git a/experiment/src/org/labkey/experiment/ScriptsResourceProvider.java b/experiment/src/org/labkey/experiment/ScriptsResourceProvider.java index 910bff397f1..8e42e00d262 100644 --- a/experiment/src/org/labkey/experiment/ScriptsResourceProvider.java +++ b/experiment/src/org/labkey/experiment/ScriptsResourceProvider.java @@ -5,7 +5,6 @@ import org.labkey.api.attachments.AttachmentDirectory; import org.labkey.api.data.Container; import org.labkey.api.files.FileContentService; -import org.labkey.api.files.MissingRootDirectoryException; import org.labkey.api.security.SecurableResource; import org.labkey.api.security.User; import org.labkey.api.util.FileUtil; @@ -72,10 +71,7 @@ public WebdavResource resolve(@NotNull WebdavResource parent, @NotNull String na return new ScriptsResource(parent, Path.toPathPart(name), dir.getFileSystemDirectory(), c); } } - catch (MissingRootDirectoryException e) - { - // Don't complain here, just hide the @scripts subfolder - } + // Don't complain here, just hide the @scripts subfolder catch (RuntimeException e) { // Don't complain here if AccessDeniedException, just hide the @scripts subfolder (Issue 50212) diff --git a/experiment/src/org/labkey/experiment/XarExportPipelineJob.java b/experiment/src/org/labkey/experiment/XarExportPipelineJob.java index 660d6bc1ef2..432252f01fa 100644 --- a/experiment/src/org/labkey/experiment/XarExportPipelineJob.java +++ b/experiment/src/org/labkey/experiment/XarExportPipelineJob.java @@ -97,7 +97,7 @@ public void run() try { - getLogger().info("Starting to write XAR to " + _exportFile.getPath()); + getLogger().info("Starting to write XAR to {}", _exportFile.getPath()); XarExporter exporter = new XarExporter(_lsidRelativizer, _selection, getUser(), _xarXmlFileName, getLogger(), getContainer()); FileUtil.mkdirs(_exportFile.getParentFile()); try (FileOutputStream fOut = new FileOutputStream(_exportFile); diff --git a/experiment/src/org/labkey/experiment/XarExporter.java b/experiment/src/org/labkey/experiment/XarExporter.java index f3a658db3cd..700cd21182d 100644 --- a/experiment/src/org/labkey/experiment/XarExporter.java +++ b/experiment/src/org/labkey/experiment/XarExporter.java @@ -105,7 +105,6 @@ import java.util.List; import java.util.Map; import java.util.Objects; -import java.util.Optional; import java.util.Set; import java.util.TreeMap; import java.util.zip.ZipEntry; diff --git a/experiment/src/org/labkey/experiment/XarReader.java b/experiment/src/org/labkey/experiment/XarReader.java index a455b73c05e..b4fa459b94f 100644 --- a/experiment/src/org/labkey/experiment/XarReader.java +++ b/experiment/src/org/labkey/experiment/XarReader.java @@ -345,7 +345,7 @@ private void checkValidationErrors(ExperimentArchiveDocument xd, ArrayList getExperimentRuns() @@ -1106,13 +1099,13 @@ private void loadExperimentRun(ExperimentRunType a, List startingMa ExpRun existingRun = ExperimentService.get().getExpRun(runLSID); if (existingRun != null) { - getLog().debug("Experiment run already exists, it will NOT be reimported, LSID '" + runLSID + "'"); + getLog().debug("Experiment run already exists, it will NOT be reimported, LSID '{}'", runLSID); for (ExpData d : existingRun.getAllDataUsedByRun()) { _deferredDataLoads.add(new DeferredDataLoad(d, existingRun)); } - getLog().info("Experiment run '" + existingRun.getName() + "' complete"); - getLog().debug("Experiment run import complete, LSID '" + runLSID + "'"); + getLog().info("Experiment run '{}' complete", existingRun.getName()); + getLog().debug("Experiment run import complete, LSID '{}'", runLSID); return; } @@ -1248,7 +1241,7 @@ private void loadExperimentRun(ExperimentRunType a, List startingMa assert loadedRun != null; XarReaderRegistry.get().postProcessImportedRun(getContainer(), getUser(), loadedRun, getLog()); _loadedRuns.add(loadedRun); - getLog().debug("Finished loading ExperimentRun with LSID '" + runLSID + "'"); + getLog().debug("Finished loading ExperimentRun with LSID '{}'", runLSID); } public List getProcessedRunsLSIDs() @@ -1443,7 +1436,7 @@ private void loadProtocolApplication(ProtocolApplicationBaseType xmlProtocolApp, { loadData(d, experimentRun, protAppId, context); } - getLog().debug("Finished loading ProtocolApplication with LSID '" + protocolLSID + "'"); + getLog().debug("Finished loading ProtocolApplication with LSID '{}'", protocolLSID); } private @Nullable String getOperationNotPermittedMessage(String protocolLSID, ExpMaterial material) @@ -1573,7 +1566,7 @@ private ExpMaterial loadMaterial( _xarSource.addMaterial(run == null ? null : run.getLSID(), material, null); - getLog().debug("Finished loading material with LSID '" + materialLSID + "'"); + getLog().debug("Finished loading material with LSID '{}'", materialLSID); return material; } @@ -1586,14 +1579,14 @@ private void updateSourceInfo(RunItem output, Long sourceApplicationId, boolean changed = false; boolean isAliquot = aliquotedFromLSID != null; - getLog().debug("Found an existing entry for " + description + " LSID " + lsid + ", not reloading its values from scratch"); + getLog().debug("Found an existing entry for {} LSID {}, not reloading its values from scratch", description, lsid); // if the output is an aliquot, we need to allow for changing from a null value to a non-null value. if (sourceApplicationId != null) { if (output.getSourceApplicationId() == null) { - getLog().debug("Updating " + description + " with LSID '" + lsid + "', setting SourceApplicationId"); + getLog().debug("Updating {} with LSID '{}', setting SourceApplicationId", description, lsid); output.setSourceApplicationId(sourceApplicationId); changed = true; } @@ -1606,7 +1599,7 @@ else if (!isAliquot) { if (output.getRunId() == null) { - getLog().debug("Updating " + description + " with LSID '" + lsid + "', setting its RunId"); + getLog().debug("Updating {} with LSID '{}', setting its RunId", description, lsid); output.setRunId(run.getRowId()); changed = true; } @@ -1625,7 +1618,7 @@ else if (!isAliquot) ExpMaterial rootMaterial = null; if (run != null) rootMaterial = _xarSource.getMaterial(run.getExpObject(), null, rootMaterialLSID); - getLog().debug("Updating " + description + " with aliquot root"); + getLog().debug("Updating {} with aliquot root", description); long newRootRowId = rootMaterial != null ? rootMaterial.getRowId() : output.getRowId(); long rowId = output.getRowId(); @@ -1634,7 +1627,7 @@ else if (!isAliquot) // When importing over existing samples, if the root rowId does not match the rowId, we only log an info message here and don't update. if (!Objects.equals(existingRootRowId, rowId)) { - getLog().info(description + " with LSID '" + lsid + "' already has root material rowId of " + existingRootRowId + "; not updating to " + newRootRowId + "."); + getLog().info("{} with LSID '{}' already has root material rowId of {}; not updating to {}.", description, lsid, existingRootRowId, newRootRowId); } else if (!Objects.equals(existingRootRowId, newRootRowId)) { @@ -1647,13 +1640,13 @@ else if (!Objects.equals(existingRootRowId, newRootRowId)) ExpMaterial aliquotParent = null; if (run != null) aliquotParent = _xarSource.getMaterial(run.getExpObject(), null, aliquotedFromLSID); - getLog().debug("Updating " + description + " with aliquot parent LSID"); + getLog().debug("Updating {} with aliquot parent LSID", description); String newParentLsid = aliquotParent != null ? aliquotParent.getLSID() : aliquotedFromLSID; // When importing over existing samples, the LSIDs will never match, so we only log an info message here and don't update. if (((Material) output).getAliquotedFromLSID() != null && !((Material) output).getAliquotedFromLSID().equalsIgnoreCase(aliquotedFromLSID)) { - getLog().info(description + " with LSID '" + lsid + "' already has aliquot parent LSID of " + ((Material) output).getAliquotedFromLSID() + "; not updating to " + newParentLsid + "."); + getLog().info("{} with LSID '{}' already has aliquot parent LSID of {}; not updating to {}.", description, lsid, ((Material) output).getAliquotedFromLSID(), newParentLsid); } else { @@ -1738,14 +1731,13 @@ private Data loadData(DataBaseType xbData, boolean newFileExists = !Files.isDirectory(newFile) && Files.exists(newFile); if (!newFileExists) { - getLog().warn("The data file with LSID " + dataLSID + " (referenced as " - + xbData.getAbout() + " in the xar.xml, does not exist."); + getLog().warn("The data file with LSID {} (referenced as {} in the xar.xml, does not exist.", dataLSID, xbData.getAbout()); } // Issue 37561: if the existing file does not exist, don't try to keep using it or compare its contents if (!Files.exists(existingFile)) { - getLog().debug("Updating " + data.getClass().getSimpleName() + " with LSID '" + dataLSID + "', setting dataFileUrl"); + getLog().debug("Updating {} with LSID '{}', setting dataFileUrl", data.getClass().getSimpleName(), dataLSID); data.setDataFileUrl(uri); } else if (newFileExists && !newFile.equals(existingFile)) @@ -1852,12 +1844,12 @@ else if (_useOriginalFileUrl) } else { - getLog().info("No data file found for " + expData.getName() + ". (LSID: " + expData.getLSID() + ", path: " + expData.getDataFileUrl() + ")"); + getLog().info("No data file found for {}. (LSID: {}, path: {})", expData.getName(), expData.getLSID(), expData.getDataFileUrl()); } _xarSource.addData(experimentRun == null ? null : experimentRun.getLSID(), expData, null); - getLog().debug("Finished loading Data with LSID '" + dataLSID + "'"); + getLog().debug("Finished loading Data with LSID '{}'", dataLSID); return expData.getDataObject(); } @@ -2158,7 +2150,7 @@ private void loadProtocol(ProtocolBaseType p) throws ExperimentException, SQLExc } else if (!diffs.isEmpty()) { - getLog().error("The protocol specified in the file with LSID '" + protocolLSID + "' has " + diffs.size() + " differences from the protocol that has already been loaded"); + getLog().error("The protocol specified in the file with LSID '{}' has {} differences from the protocol that has already been loaded", protocolLSID, diffs.size()); for (IdentifiableEntity.Difference diff : diffs) { getLog().error(diff.toString()); @@ -2166,7 +2158,7 @@ else if (!diffs.isEmpty()) throw new XarFormatException("Protocol with LSID '" + protocolLSID + "' does not match existing protocol"); } protocol = existingProtocol.getDataObject(); - getLog().debug("Protocol with LSID '" + protocolLSID + "' matches a protocol with the same LSID that has already been loaded."); + getLog().debug("Protocol with LSID '{}' matches a protocol with the same LSID that has already been loaded.", protocolLSID); if (useName) _loadedProtocols.put(protocolLSID, existingProtocol); } @@ -2194,7 +2186,7 @@ else if (!diffs.isEmpty()) else protocol = ExperimentServiceImpl.get().saveProtocol(getUser(), xarProtocol); - getLog().debug("Finished loading Protocol with LSID '" + protocolLSID + "'"); + getLog().debug("Finished loading Protocol with LSID '{}'", protocolLSID); } ExpProtocolImpl protocolImpl = new ExpProtocolImpl(protocol); @@ -2623,7 +2615,7 @@ private void loadWildcardProperties(XmlObject xObj, } catch (Exception e) { - getLog().debug("Skipped element " + key + " exception " + e.getMessage(), e); + getLog().debug("Skipped element {} exception {}", key, e.getMessage(), e); } } diff --git a/experiment/src/org/labkey/experiment/api/AbstractRunItemImpl.java b/experiment/src/org/labkey/experiment/api/AbstractRunItemImpl.java index a9a94cb4034..268aa98411b 100644 --- a/experiment/src/org/labkey/experiment/api/AbstractRunItemImpl.java +++ b/experiment/src/org/labkey/experiment/api/AbstractRunItemImpl.java @@ -441,7 +441,7 @@ else if (isIntegral(o)) if (!values.isEmpty()) { if (values.size() == 1) - jsonData.put(fieldKey.toString(), values.get(0)); + jsonData.put(fieldKey.toString(), values.getFirst()); else jsonData.put(fieldKey.toString(), values); } @@ -472,7 +472,8 @@ else if (isIntegral(o)) keywordsLo.addAll(values); continue; } - default -> LOG.debug("Unable to index column " + fieldKey.toString() + " with property: " + searchProperty.name() + ". Not yet supported."); + default -> + LOG.debug("Unable to index column {} with property: {}. Not yet supported.", fieldKey.toString(), searchProperty.name()); } } diff --git a/experiment/src/org/labkey/experiment/api/BaseFieldsTable.java b/experiment/src/org/labkey/experiment/api/BaseFieldsTable.java index 4bf53d7b80c..820657018b3 100644 --- a/experiment/src/org/labkey/experiment/api/BaseFieldsTable.java +++ b/experiment/src/org/labkey/experiment/api/BaseFieldsTable.java @@ -14,7 +14,6 @@ import org.labkey.api.query.FieldKey; import org.labkey.api.query.FilteredTable; import org.labkey.api.security.permissions.AdminPermission; -import org.labkey.api.security.permissions.Permission; public abstract class BaseFieldsTable extends FilteredTable { diff --git a/experiment/src/org/labkey/experiment/api/ClosureQueryHelper.java b/experiment/src/org/labkey/experiment/api/ClosureQueryHelper.java index 1626108d87c..276cea0f63e 100644 --- a/experiment/src/org/labkey/experiment/api/ClosureQueryHelper.java +++ b/experiment/src/org/labkey/experiment/api/ClosureQueryHelper.java @@ -379,17 +379,17 @@ public static void populateMaterialAncestors(Logger logger) ContainerManager.getAllChildren(ContainerManager.getRoot()).forEach( container -> { int totalRows = 0; - logger.info("Adding rows to exp.materialAncestors from sample types in container " + container.getPath()); + logger.info("Adding rows to exp.materialAncestors from sample types in container {}", container.getPath()); for (ExpSampleType sampleType : SampleTypeService.get().getSampleTypes(container, false)) { - logger.debug(" Adding rows from samples in sampleType " + sampleType.getName()); + logger.debug(" Adding rows from samples in sampleType {}", sampleType.getName()); SQLFragment from = new SQLFragment(" FROM exp.material WHERE materialSourceId = ?").add(sampleType.getRowId()); SQLFragment sql = ClosureQueryHelper.selectAndInsertSql(schema.getSqlDialect(), from, null, "INSERT INTO exp.materialAncestors (RowId, AncestorRowId, AncestorTypeId) "); int numRows = new SqlExecutor(schema.getScope()).execute(sql); totalRows += numRows; - logger.debug(" Added " + numRows + " rows for data class " + sampleType.getName()); + logger.debug(" Added {} rows for data class {}", numRows, sampleType.getName()); } - logger.info("Added " + totalRows + " rows for sample types in container " + container.getPath()); + logger.info("Added {} rows for sample types in container {}", totalRows, container.getPath()); } ); logger.info("Finished populating exp.materialAncestors"); @@ -402,18 +402,18 @@ public static void populateDataAncestors(Logger logger) ContainerManager.getAllChildren(ContainerManager.getRoot()).forEach( container -> { int totalRows = 0; - logger.info("Adding rows to exp.dataAncestors from data classes in container " + container.getPath()); + logger.info("Adding rows to exp.dataAncestors from data classes in container {}", container.getPath()); for (ExpDataClass dataClass : ExperimentService.get().getDataClasses(container, false)) { - logger.debug(" Adding rows to exp.dataAncestors from data class " + dataClass.getName()); + logger.debug(" Adding rows to exp.dataAncestors from data class {}", dataClass.getName()); SQLFragment from = new SQLFragment(" FROM exp.data WHERE classId = ?").add(dataClass.getRowId()); SQLFragment sql = ClosureQueryHelper.selectAndInsertSql(schema.getSqlDialect(), from, null, "INSERT INTO exp.dataAncestors (RowId, AncestorRowId, AncestorTypeId) "); int numRows = new SqlExecutor(schema.getScope()).execute(sql); totalRows += numRows; - logger.debug(" Added " + numRows + " rows for data class " + dataClass.getName()); + logger.debug(" Added {} rows for data class {}", numRows, dataClass.getName()); } - logger.info("Added " + totalRows + " rows for data classes in container " + container.getPath()); + logger.info("Added {} rows for data classes in container {}", totalRows, container.getPath()); } ); logger.info("Finished populating exp.dataAncestors"); diff --git a/experiment/src/org/labkey/experiment/api/CountOfUniqueValueTableCustomizer.java b/experiment/src/org/labkey/experiment/api/CountOfUniqueValueTableCustomizer.java index f1cf8b33442..098e9e35118 100644 --- a/experiment/src/org/labkey/experiment/api/CountOfUniqueValueTableCustomizer.java +++ b/experiment/src/org/labkey/experiment/api/CountOfUniqueValueTableCustomizer.java @@ -91,13 +91,13 @@ public CountOfUniqueValueTableCustomizer(MultiValuedMap props) } if (null == counterType) { - _log.warn("Error in counter definition '" + counterName + "': CounterType required"); + _log.warn("Error in counter definition '{}': CounterType required", counterName); valid = false; } if (!Collections.disjoint(pairedColumnNames, attachedColumnNames)) { - _log.warn("Error in counter definition '" + counterName + "': column included as both a paired and an attached column"); + _log.warn("Error in counter definition '{}': column included as both a paired and an attached column", counterName); valid = false; } @@ -112,7 +112,7 @@ public CountOfUniqueValueTableCustomizer(MultiValuedMap props) } catch (ClassNotFoundException | NoSuchMethodException | InstantiationException | IllegalAccessException | InvocationTargetException e) { - _log.warn("Error instantiating counter '" + counterName + "' of type " + counterType + ": " + e.getMessage(), e); + _log.warn("Error instantiating counter '{}' of type {}: {}", counterName, counterType, e.getMessage(), e); } } _counterDefinition = counterDefinition; diff --git a/experiment/src/org/labkey/experiment/api/DataClassDomainKind.java b/experiment/src/org/labkey/experiment/api/DataClassDomainKind.java index c83453b6618..3b9d5d1cc8e 100644 --- a/experiment/src/org/labkey/experiment/api/DataClassDomainKind.java +++ b/experiment/src/org/labkey/experiment/api/DataClassDomainKind.java @@ -443,7 +443,7 @@ public void deleteDomain(User user, Domain domain, @Nullable String auditUserCom @Override public TableInfo getTableInfo(User user, Container container, String name, @Nullable ContainerFilter cf) { - LOG.debug("Getting tableInfo for table " + name); + LOG.debug("Getting tableInfo for table {}", name); UserSchema schema = new DataClassUserSchema(container, user); return schema.getTable(name, cf); } diff --git a/experiment/src/org/labkey/experiment/api/ExpDataClassDataTableImpl.java b/experiment/src/org/labkey/experiment/api/ExpDataClassDataTableImpl.java index 9a08e7c055f..8f3bd242924 100644 --- a/experiment/src/org/labkey/experiment/api/ExpDataClassDataTableImpl.java +++ b/experiment/src/org/labkey/experiment/api/ExpDataClassDataTableImpl.java @@ -771,10 +771,10 @@ public List> getImportTemplates(ViewContext ctx) url.addParameter("excludeColumn", excludeKey); url.addParameter("excludeColumn", "Flag"); url.addParameter("filenamePrefix", this.getName()); - if (templates.get(0).first.equals(DOWNLOAD_TEMPLATE_LABEL)) + if (templates.getFirst().first.equals(DOWNLOAD_TEMPLATE_LABEL)) templates.set(0, Pair.of(DOWNLOAD_TEMPLATE_LABEL, url.toString())); else - templates.add(0, Pair.of(DOWNLOAD_TEMPLATE_LABEL, url.toString())); + templates.addFirst(Pair.of(DOWNLOAD_TEMPLATE_LABEL, url.toString())); } @@ -1234,7 +1234,7 @@ public int mergeRows(User user, Container container, DataIteratorBuilder rows, B } @Override - public Map moveRows(User user, Container container, Container targetContainer, List> rows, BatchValidationException errors, @Nullable Map configParameters, @Nullable Map extraScriptContext) throws InvalidKeyException, BatchValidationException, QueryUpdateServiceException, SQLException + public Map moveRows(User user, Container container, Container targetContainer, List> rows, BatchValidationException errors, @Nullable Map configParameters, @Nullable Map extraScriptContext) throws BatchValidationException, QueryUpdateServiceException { Map allContainerResponse = new HashMap<>(); @@ -1454,7 +1454,7 @@ protected Map _update(User user, Container c, Map> updateRows(User user, Container container, List> rows, List> oldKeys, BatchValidationException errors, @Nullable Map configParameters, Map extraScriptContext) throws InvalidKeyException, BatchValidationException, QueryUpdateServiceException, SQLException + public List> updateRows(User user, Container container, List> rows, List> oldKeys, BatchValidationException errors, @Nullable Map configParameters, Map extraScriptContext) throws BatchValidationException { if (rows == null || rows.isEmpty()) return Collections.emptyList(); diff --git a/experiment/src/org/labkey/experiment/api/ExpDataClassDataTestCase.jsp b/experiment/src/org/labkey/experiment/api/ExpDataClassDataTestCase.jsp index efbcf19c39a..1d316902bd2 100644 --- a/experiment/src/org/labkey/experiment/api/ExpDataClassDataTestCase.jsp +++ b/experiment/src/org/labkey/experiment/api/ExpDataClassDataTestCase.jsp @@ -286,10 +286,10 @@ private void testNameExpressionGeneration(ExpDataClassImpl dataClass, TableInfo } assertEquals(1, ret.size()); - assertEquals(1, ret.get(0).get("genId")); - assertEquals(expectedName, ret.get(0).get("name")); + assertEquals(1, ret.getFirst().get("genId")); + assertEquals(expectedName, ret.getFirst().get("name")); - Long rowId = asLong(ret.get(0).get("RowId")); + Long rowId = asLong(ret.getFirst().get("RowId")); ExpData data = ExperimentService.get().getExpData(rowId); ExpData data1 = ExperimentService.get().getExpData(dataClass, expectedName); assertEquals(data, data1); @@ -316,7 +316,7 @@ private void testInsertIntoSubfolder(ExpDataClassImpl dataClass, TableInfo table } assertEquals(1, ret.size()); - assertEquals(sub.getId(), ret.get(0).get("folder")); + assertEquals(sub.getId(), ret.getFirst().get("folder")); ExpData data = ExperimentService.get().getExpData(dataClass, expectedSubName); assertNotNull(data); @@ -395,7 +395,7 @@ private void testDeleteExpData(ExpDataClassImpl dataClass, User user, int expect List datas = dataClass.getDatas(); assertEquals(expectedCount, datas.size()); - datas.get(0).delete(user); + datas.getFirst().delete(user); assertEquals(expectedCount-1, dataClass.getDatas().size()); } @@ -434,7 +434,7 @@ private void testInsertAliases(ExpDataClassImpl dataClass, TableInfo table) thro try (DbScope.Transaction tx = table.getSchema().getScope().beginTransaction()) { List> ret = helper.insertRows(c, rows, table.getName()); - insertedRowId = asLong(ret.get(0).get("rowId")); + insertedRowId = asLong(ret.getFirst().get("rowId")); tx.commit(); } @@ -471,7 +471,7 @@ private void verifyAliasesViaSelectRows(String schemaName, String queryName, lon SelectRowsResponse resp = cmd.execute(conn, c.getPath()); assertEquals(1, resp.getRowCount().intValue()); - Map row0 = resp.getRows().get(0); + Map row0 = resp.getRows().getFirst(); Map row0data = (Map)row0.get("data"); // expected 17.1 format for the row's data: // { @@ -645,8 +645,8 @@ public void testDomainTemplate() throws Exception } assertEquals(1, ret.size()); - assertEquals(5, asInteger(ret.get(0).get("pri")).intValue()); - assertEquals("p5", ret.get(0).get("title")); + assertEquals(5, asInteger(ret.getFirst().get("pri")).intValue()); + assertEquals("p5", ret.getFirst().get("title")); } // Issue 35579: Cannot create non-auto-increment Integer PK list via Domain.create @@ -673,8 +673,8 @@ public void testDomainTemplate() throws Exception } assertEquals(1, ret.size()); - assertEquals(3, asInteger(ret.get(0).get("m")).intValue()); - assertEquals("Milestone 3", ret.get(0).get("title")); + assertEquals(3, asInteger(ret.getFirst().get("m")).intValue()); + assertEquals("Milestone 3", ret.getFirst().get("title")); } // verify the "TodoList" DataClass was created and data was imported @@ -728,7 +728,7 @@ public void testContainerDelete() throws Exception } assertEquals(1, ret.size()); - dataRowId1 = asLong(ret.get(0).get("RowId")); + dataRowId1 = asLong(ret.getFirst().get("RowId")); } // setup: insert into sub container @@ -748,7 +748,7 @@ public void testContainerDelete() throws Exception } assertEquals(1, ret.size()); - dataRowId2 = asLong(ret.get(0).get("RowId")); + dataRowId2 = asLong(ret.getFirst().get("RowId")); } // test: delete container, ensure everything is removed @@ -911,7 +911,7 @@ public void testDataClassWithVocabularyProperties() throws Exception var insertedDataClassRows = helper.insertRows(c, rowsToInsert, dataClassName); assertEquals(1, insertedDataClassRows.size()); - var insertedDataClass = insertedDataClassRows.get(0); + var insertedDataClass = insertedDataClassRows.getFirst(); Long insertedRowId = asLong(insertedDataClass.get("RowId")); String insertedLsid = (String)insertedDataClass.get("LSID"); @@ -974,7 +974,7 @@ public void testViewSupportForVocabularyDomains() throws Exception var insertedSampleRows = helper.insertRows(c, rows ,sampleName, schema); - var insertedSample = insertedSampleRows.get(0); + var insertedSample = insertedSampleRows.getFirst(); Long insertedSampleRowId = asLong(insertedSample.get("RowId")); // Create a vocab domain with lookup prop to the sample type @@ -1256,7 +1256,7 @@ public void testUpdateAuditForLongField() throws Exception filter.addCondition(FieldKey.fromParts("queryName"), dataClassName); List events = AuditLogService.get().getAuditEvents(c, user, "QueryUpdateAuditEvent", filter, new Sort("-RowId")); assertEquals("Number of audit events not as expected", 2, events.size()); // should have one for insert and one for update - String oldRecordMap = ((DetailedAuditTypeEvent) events.get(0)).getOldRecordMap(); + String oldRecordMap = ((DetailedAuditTypeEvent) events.getFirst()).getOldRecordMap(); assertTrue("Old record map (" + oldRecordMap + ") does not contain expected field", oldRecordMap.contains(encodeURIComponent(fieldName) + "=Initial")); } } diff --git a/experiment/src/org/labkey/experiment/api/ExpDataTableImpl.java b/experiment/src/org/labkey/experiment/api/ExpDataTableImpl.java index 74c1e9305da..fce20cafcc2 100644 --- a/experiment/src/org/labkey/experiment/api/ExpDataTableImpl.java +++ b/experiment/src/org/labkey/experiment/api/ExpDataTableImpl.java @@ -34,14 +34,12 @@ import org.labkey.api.data.Container; import org.labkey.api.data.ContainerFilter; import org.labkey.api.data.ContainerManager; -import org.labkey.api.data.CoreSchema; import org.labkey.api.data.ExcelWriter; import org.labkey.api.data.JdbcType; import org.labkey.api.data.MutableColumnInfo; import org.labkey.api.data.RenderContext; import org.labkey.api.data.SQLFragment; import org.labkey.api.data.SimpleFilter; -import org.labkey.api.data.SqlSelector; import org.labkey.api.exp.DomainDescriptor; import org.labkey.api.exp.OntologyManager; import org.labkey.api.exp.PropertyColumn; @@ -87,7 +85,6 @@ import org.labkey.api.writer.HtmlWriter; import org.labkey.api.writer.MemoryVirtualFile; import org.labkey.api.writer.VirtualFile; -import org.labkey.experiment.FileLinkFileListener; import org.labkey.experiment.controllers.exp.ExperimentController; import org.labkey.experiment.lineage.LineageMethod; import org.labkey.vfs.FileLike; diff --git a/experiment/src/org/labkey/experiment/api/ExpIdentifiableBaseImpl.java b/experiment/src/org/labkey/experiment/api/ExpIdentifiableBaseImpl.java index b3368808580..546bc7144ff 100644 --- a/experiment/src/org/labkey/experiment/api/ExpIdentifiableBaseImpl.java +++ b/experiment/src/org/labkey/experiment/api/ExpIdentifiableBaseImpl.java @@ -17,13 +17,11 @@ package org.labkey.experiment.api; import org.jetbrains.annotations.Nullable; -import org.labkey.api.data.CompareType; import org.labkey.api.data.DbScope; import org.labkey.api.data.SQLFragment; import org.labkey.api.data.SqlSelector; import org.labkey.api.data.Table; import org.labkey.api.data.TableInfo; -import org.labkey.api.data.dialect.SqlDialect; import org.labkey.api.exp.IdentifiableBase; import org.labkey.api.exp.Lsid; import org.labkey.api.exp.OntologyManager; diff --git a/experiment/src/org/labkey/experiment/api/ExpObjectImpl.java b/experiment/src/org/labkey/experiment/api/ExpObjectImpl.java index 6f93eedb6db..6048d10225c 100644 --- a/experiment/src/org/labkey/experiment/api/ExpObjectImpl.java +++ b/experiment/src/org/labkey/experiment/api/ExpObjectImpl.java @@ -18,6 +18,7 @@ import org.apache.commons.lang3.StringUtils; import org.jetbrains.annotations.Nullable; +import org.jetbrains.annotations.NotNull; import org.labkey.api.exp.ObjectProperty; import org.labkey.api.exp.OntologyManager; import org.labkey.api.exp.OntologyObject; @@ -180,7 +181,7 @@ public int hashCode() } @Override - public int compareTo(ExpObject o2) + public int compareTo(@NotNull ExpObject o2) { if (getName() != null) { diff --git a/experiment/src/org/labkey/experiment/api/ExpRunImpl.java b/experiment/src/org/labkey/experiment/api/ExpRunImpl.java index 4db94a4e583..23ef65fe7e7 100644 --- a/experiment/src/org/labkey/experiment/api/ExpRunImpl.java +++ b/experiment/src/org/labkey/experiment/api/ExpRunImpl.java @@ -187,13 +187,13 @@ private boolean checkBatch(ExpExperimentImpl batch) List exps = getExperiments(); if (!exps.contains(batch)) { - LOG.warn("Expected batch '" + batch.getRowId() + "' to be in list of experiments: " + exps); + LOG.warn("Expected batch '{}' to be in list of experiments: {}", batch.getRowId(), exps); return false; } if (!getProtocol().equals(batch.getBatchProtocol())) { - LOG.warn("Expected batch '" + batch.getRowId() + "' to have same protocol as run. Expected protocol '" + getProtocol() + "', but found '" + batch.getBatchProtocol() + "'"); + LOG.warn("Expected batch '{}' to have same protocol as run. Expected protocol '{}', but found '{}'", batch.getRowId(), getProtocol(), batch.getBatchProtocol()); return false; } @@ -803,7 +803,7 @@ public void trimRunTree(Integer id, String type) throws ExperimentException listM.add(m); if (getMaterialInputs().containsKey(m)) { - ExpProtocolApplication runNode = getProtocolApplications().get(0); + ExpProtocolApplication runNode = getProtocolApplications().getFirst(); assert runNode.getApplicationType() == ExpProtocol.ApplicationType.ExperimentRun; listPA.add(runNode); continue; @@ -816,7 +816,7 @@ public void trimRunTree(Integer id, String type) throws ExperimentException listD.add(d); if (getDataInputs().containsKey(d)) { - ExpProtocolApplication runNode = getProtocolApplications().get(0); + ExpProtocolApplication runNode = getProtocolApplications().getFirst(); assert runNode.getApplicationType() == ExpProtocol.ApplicationType.ExperimentRun; listPA.add(runNode); continue; @@ -972,12 +972,12 @@ public void archiveDataFiles(User user) // Warn if the move fails for some reason (file is open / file deleted during archive) catch (IOException e) { - LOG.warn("Unable to archive file: " + e.getMessage()); + LOG.warn("Unable to archive file: {}", e.getMessage()); } // Fail silently if the parent directory does not exist - archiving is a best effort action catch (ExperimentException e) { - LOG.warn("Unable to read parent directory: " + e.getMessage()); + LOG.warn("Unable to read parent directory: {}", e.getMessage()); } } diff --git a/experiment/src/org/labkey/experiment/api/ExpRunItemTableImpl.java b/experiment/src/org/labkey/experiment/api/ExpRunItemTableImpl.java index 381f9c15355..fc689a0e712 100644 --- a/experiment/src/org/labkey/experiment/api/ExpRunItemTableImpl.java +++ b/experiment/src/org/labkey/experiment/api/ExpRunItemTableImpl.java @@ -186,7 +186,7 @@ protected String getExpNameExpressionPreview(String schemaName, String queryName { List previews = domain.getDomainKind().getDomainNamePreviews(schemaName, queryName, getContainer(), user); if (previews != null && !previews.isEmpty()) - return previews.get(0); + return previews.getFirst(); } } catch (Exception ignore) diff --git a/experiment/src/org/labkey/experiment/api/ExpRunTableImpl.java b/experiment/src/org/labkey/experiment/api/ExpRunTableImpl.java index 648152e6067..79db0e2203a 100644 --- a/experiment/src/org/labkey/experiment/api/ExpRunTableImpl.java +++ b/experiment/src/org/labkey/experiment/api/ExpRunTableImpl.java @@ -1157,7 +1157,7 @@ private void appendPropertyIfChanged(StringBuilder sb, String label, Object oldV } @Override - public Map moveRows(User user, Container container, Container targetContainer, List> rows, BatchValidationException errors, @Nullable Map configParameters, @Nullable Map extraScriptContext) throws InvalidKeyException, BatchValidationException, QueryUpdateServiceException, SQLException + public Map moveRows(User user, Container container, Container targetContainer, List> rows, BatchValidationException errors, @Nullable Map configParameters, @Nullable Map extraScriptContext) throws BatchValidationException { Map allContainerResponse = new HashMap<>(); diff --git a/experiment/src/org/labkey/experiment/api/ExpSampleTypeImpl.java b/experiment/src/org/labkey/experiment/api/ExpSampleTypeImpl.java index 48f94b3eeed..cc440e134dd 100644 --- a/experiment/src/org/labkey/experiment/api/ExpSampleTypeImpl.java +++ b/experiment/src/org/labkey/experiment/api/ExpSampleTypeImpl.java @@ -276,7 +276,7 @@ public DomainProperty getIdCol1() List props = getDomain().getProperties(); if (!props.isEmpty()) { - result = props.get(0); + result = props.getFirst(); } } return result; diff --git a/experiment/src/org/labkey/experiment/api/ExpSampleTypeTestCase.jsp b/experiment/src/org/labkey/experiment/api/ExpSampleTypeTestCase.jsp index 04332ea21c8..9cc144a4f9f 100644 --- a/experiment/src/org/labkey/experiment/api/ExpSampleTypeTestCase.jsp +++ b/experiment/src/org/labkey/experiment/api/ExpSampleTypeTestCase.jsp @@ -406,7 +406,7 @@ public void testNameExpression() throws Exception assertEquals(3, ret.size()); - assertEquals(1, ret.get(0).get("genId")); + assertEquals(1, ret.getFirst().get("genId")); assertEquals(expectedName1, ret.get(0).get("name")); assertExpectedName(st, expectedName1); @@ -426,38 +426,38 @@ public void testNameExpression() throws Exception aliquotRows.add(CaseInsensitiveHashMap.of("aliquotedFrom", expectedName1, "AliquotCount", 10)); List> aliquots = insertSampleRows(sampleTypeName, aliquotRows); assertExpectedName(st, expectedName1 + "-ALI-0004"); - assertEquals(expectedName1, aliquots.get(0).get("AliquotedFrom")); + assertEquals(expectedName1, aliquots.getFirst().get("AliquotedFrom")); aliquotRows = new ArrayList<>(); aliquotRows.add(CaseInsensitiveHashMap.of("Aliquotedfrom", expectedName2, "aliquotCount", 5)); aliquots = insertSampleRows(sampleTypeName, aliquotRows); assertExpectedName(st, expectedName2 + "-ALI-0005"); - assertEquals(expectedName2, aliquots.get(0).get("aliquotedFrom")); + assertEquals(expectedName2, aliquots.getFirst().get("aliquotedFrom")); aliquotRows = new ArrayList<>(); aliquotRows.add(CaseInsensitiveHashMap.of("ALIQUOTEDFROM", expectedName1, "Aliquotcount", 15)); aliquots = insertSampleRows(sampleTypeName, aliquotRows); assertExpectedName(st, expectedName1 + "-ALI-0006"); - assertEquals(expectedName1, aliquots.get(0).get("aliquotedfrom")); + assertEquals(expectedName1, aliquots.getFirst().get("aliquotedfrom")); aliquotRows = new ArrayList<>(); aliquotRows.add(CaseInsensitiveHashMap.of("AliquotedFrom", expectedName3, "ALIQUOTCOUNT", 2)); aliquots = insertSampleRows(sampleTypeName, aliquotRows); assertExpectedName(st, expectedName3 + "-ALI-0007"); - assertEquals(expectedName3, aliquots.get(0).get("ALIQUOTEDFROM")); + assertEquals(expectedName3, aliquots.getFirst().get("ALIQUOTEDFROM")); // Issue 53063: Support "Aliquoted From" aliquotRows = new ArrayList<>(); aliquotRows.add(CaseInsensitiveHashMap.of("Aliquoted From", expectedName2, "ALIQUOTCOUNT", 2)); aliquots = insertSampleRows(sampleTypeName, aliquotRows); assertExpectedName(st, expectedName2 + "-ALI-0008"); - assertEquals(expectedName2, aliquots.get(0).get("ALIQUOTEDFROM")); + assertEquals(expectedName2, aliquots.getFirst().get("ALIQUOTEDFROM")); aliquotRows = new ArrayList<>(); aliquotRows.add(CaseInsensitiveHashMap.of("aliquoted from", expectedName3, "ALIQUOTCOUNT", 3)); aliquots = insertSampleRows(sampleTypeName, aliquotRows); assertExpectedName(st, expectedName3 + "-ALI-0009"); - assertEquals(expectedName3, aliquots.get(0).get("aliquotedFrom")); + assertEquals(expectedName3, aliquots.getFirst().get("aliquotedFrom")); // test the default aliquot naming pattern (${${AliquotedFrom}-:withCounter} st.setAliquotNameExpression(""); @@ -467,37 +467,37 @@ public void testNameExpression() throws Exception aliquotRows.add(CaseInsensitiveHashMap.of("aliquotedFrom", expectedName1)); aliquots = insertSampleRows(sampleTypeName, aliquotRows); assertExpectedName(st, expectedName1 + "-1"); - assertEquals(expectedName1, aliquots.get(0).get("AliquotedFrom")); + assertEquals(expectedName1, aliquots.getFirst().get("AliquotedFrom")); aliquotRows = new ArrayList<>(); aliquotRows.add(CaseInsensitiveHashMap.of("Aliquotedfrom", expectedName1)); aliquots = insertSampleRows(sampleTypeName, aliquotRows); assertExpectedName(st, expectedName1 + "-2"); - assertEquals(expectedName1, aliquots.get(0).get("aliquotedFrom")); + assertEquals(expectedName1, aliquots.getFirst().get("aliquotedFrom")); aliquotRows = new ArrayList<>(); aliquotRows.add(CaseInsensitiveHashMap.of("ALIQUOTEDFROM", expectedName1)); aliquots = insertSampleRows(sampleTypeName, aliquotRows); assertExpectedName(st, expectedName1 + "-3"); - assertEquals(expectedName1, aliquots.get(0).get("aliquotedfrom")); + assertEquals(expectedName1, aliquots.getFirst().get("aliquotedfrom")); aliquotRows = new ArrayList<>(); aliquotRows.add(CaseInsensitiveHashMap.of("AliquotedFrom", expectedName1)); aliquots = insertSampleRows(sampleTypeName, aliquotRows); assertExpectedName(st, expectedName1 + "-4"); - assertEquals(expectedName1, aliquots.get(0).get("ALIQUOTEDFROM")); + assertEquals(expectedName1, aliquots.getFirst().get("ALIQUOTEDFROM")); aliquotRows = new ArrayList<>(); aliquotRows.add(CaseInsensitiveHashMap.of("Aliquoted From", expectedName1)); aliquots = insertSampleRows(sampleTypeName, aliquotRows); assertExpectedName(st, expectedName1 + "-5"); - assertEquals(expectedName1, aliquots.get(0).get("ALIQUOTEDFROM")); + assertEquals(expectedName1, aliquots.getFirst().get("ALIQUOTEDFROM")); aliquotRows = new ArrayList<>(); aliquotRows.add(CaseInsensitiveHashMap.of("aliquoted from", expectedName1)); aliquots = insertSampleRows(sampleTypeName, aliquotRows); assertExpectedName(st, expectedName1 + "-6"); - assertEquals(expectedName1, aliquots.get(0).get("aliquotedFrom")); + assertEquals(expectedName1, aliquots.getFirst().get("aliquotedFrom")); } @Test @@ -639,12 +639,12 @@ public void testBlankRows() throws Exception assertEquals("Expected to generate 3 sample rows, got: " + inserted, 3, inserted.size()); - String name1 = (String)inserted.get(0).get("name"); + String name1 = (String)inserted.getFirst().get("name"); assertTrue("Expected generated sample name to start with 'S-', got: " + name1, name1 != null && name1.startsWith("S-")); allSamples = st.getSamples(c); assertEquals("Expected 3 total samples", 3, allSamples.size()); - assertEquals(0, allSamples.get(0).getAliquotCount()); + assertEquals(0, allSamples.getFirst().getAliquotCount()); // insert as if we pasted a tsv in the "upload samples" page -- blank rows should be skipped // data has three lines, one blank. expect to insert only two samples @@ -662,9 +662,9 @@ public void testBlankRows() throws Exception throw errors; assertEquals("Expected to insert 2 samples, got: " + insertedRows.size(), 2, insertedRows.size()); - assertEquals(0, insertedRows.get(0).get("AliquotCount")); + assertEquals(0, insertedRows.getFirst().get("AliquotCount")); - ExpMaterial material1 = ExperimentService.get().getExpMaterial(asLong(insertedRows.get(0).get("rowid"))); + ExpMaterial material1 = ExperimentService.get().getExpMaterial(asLong(insertedRows.getFirst().get("rowid"))); assertNotNull(material1); Map map = material1.getPropertyValues(); assertEquals("Expected to only have 'age' property, got: " + map, 1, map.size()); @@ -1081,7 +1081,7 @@ public void testSampleTypeWithVocabularyProperties() throws Exception List> rows = helper.buildRows(row); UserSchema schema = getSampleSchema(); - var insertedSample = helper.insertRows(c, rows, sampleTypeName, schema).get(0); + var insertedSample = helper.insertRows(c, rows, sampleTypeName, schema).getFirst(); var sampleLsid = insertedSample.get("LSID").toString(); var sampleRowId = insertedSample.get("RowId"); @@ -1139,16 +1139,16 @@ public void testDetailedAuditLog() throws Exception // insert a sample List> ret = insertSampleRows(st.getName(), List.of(CaseInsensitiveHashMap.of("Name", "A1", "Measure", "Initial", "Value", 1.0))); assertEquals(1, ret.size()); - assertNotNull(ret.get(0).get("rowid")); - int rowid = (int) JdbcType.INTEGER.convert(ret.get(0).get("rowid")); + assertNotNull(ret.getFirst().get("rowid")); + int rowid = (int) JdbcType.INTEGER.convert(ret.getFirst().get("rowid")); // check audit log SimpleFilter f = new SimpleFilter(new FieldKey(null, "RowId"), auditMaxRowid, CompareType.GT); List events = AuditLogService.get().getAuditEvents(c, user, SampleTimelineAuditEvent.EVENT_TYPE, f, new Sort("-RowId")); assertFalse(events.isEmpty()); - assertNull(events.get(0).getOldRecordMap()); - assertNotNull(events.get(0).getNewRecordMap()); - Map newRecordMap = new CaseInsensitiveHashMap<>(PageFlowUtil.mapFromQueryString(events.get(0).getNewRecordMap())); + assertNull(events.getFirst().getOldRecordMap()); + assertNotNull(events.getFirst().getNewRecordMap()); + Map newRecordMap = new CaseInsensitiveHashMap<>(PageFlowUtil.mapFromQueryString(events.getFirst().getNewRecordMap())); assertEquals("Initial", newRecordMap.get("Measure")); assertEquals("1.0", newRecordMap.get("Value")); assertNull(newRecordMap.get("AliquotCount")); @@ -1163,10 +1163,10 @@ public void testDetailedAuditLog() throws Exception // check audit log events = AuditLogService.get().getAuditEvents(c, user, SampleTimelineAuditEvent.EVENT_TYPE, f, new Sort("-RowId")); assertFalse(events.isEmpty()); - assertNotNull(events.get(0).getOldRecordMap()); - Map oldRecordMap = new CaseInsensitiveHashMap<>(PageFlowUtil.mapFromQueryString(events.get(0).getOldRecordMap())); - assertNotNull(events.get(0).getNewRecordMap()); - newRecordMap = new CaseInsensitiveHashMap<>(PageFlowUtil.mapFromQueryString(events.get(0).getNewRecordMap())); + assertNotNull(events.getFirst().getOldRecordMap()); + Map oldRecordMap = new CaseInsensitiveHashMap<>(PageFlowUtil.mapFromQueryString(events.getFirst().getOldRecordMap())); + assertNotNull(events.getFirst().getNewRecordMap()); + newRecordMap = new CaseInsensitiveHashMap<>(PageFlowUtil.mapFromQueryString(events.getFirst().getNewRecordMap())); assertFalse(oldRecordMap.containsKey("lsid")); assertEquals("Initial", oldRecordMap.get("Measure")); assertEquals("1.0", oldRecordMap.get("Value")); @@ -1184,10 +1184,10 @@ public void testDetailedAuditLog() throws Exception // check audit log events = AuditLogService.get().getAuditEvents(c, user, SampleTimelineAuditEvent.EVENT_TYPE, f, new Sort("-RowId")); assertFalse(events.isEmpty()); - assertNotNull(events.get(0).getOldRecordMap()); - oldRecordMap = new CaseInsensitiveHashMap<>(PageFlowUtil.mapFromQueryString(events.get(0).getOldRecordMap())); - assertNotNull(events.get(0).getNewRecordMap()); - newRecordMap = new CaseInsensitiveHashMap<>(PageFlowUtil.mapFromQueryString(events.get(0).getNewRecordMap())); + assertNotNull(events.getFirst().getOldRecordMap()); + oldRecordMap = new CaseInsensitiveHashMap<>(PageFlowUtil.mapFromQueryString(events.getFirst().getOldRecordMap())); + assertNotNull(events.getFirst().getNewRecordMap()); + newRecordMap = new CaseInsensitiveHashMap<>(PageFlowUtil.mapFromQueryString(events.getFirst().getNewRecordMap())); assertFalse(oldRecordMap.containsKey("lsid")); assertEquals("Updated", oldRecordMap.get("Measure")); assertEquals("2.0", oldRecordMap.get("Value")); @@ -1212,8 +1212,8 @@ public void testExpMaterialPermissions() throws Exception // insert a sample List> ret = insertSampleRows(st.getName(), List.of(CaseInsensitiveHashMap.of("name", "SampleInSampleType"))); assertEquals(1, ret.size()); - assertNotNull(ret.get(0).get("rowid")); - long stSampleId = (long) JdbcType.BIGINT.convert(ret.get(0).get("rowid")); + assertNotNull(ret.getFirst().get("rowid")); + long stSampleId = (long) JdbcType.BIGINT.convert(ret.getFirst().get("rowid")); // verify insert, update aren't allowed, but read and delete are allowed User user = TestContext.get().getUser(); @@ -1258,7 +1258,7 @@ public void testExpMaterialPermissions() throws Exception // verify read via QUS var rows = qus.getRows(user, c, List.of(CaseInsensitiveHashMap.of("rowId", m.getRowId()))); assertEquals("Failed to fetch material via QUS", 1, rows.size()); - assertEquals(m.getLSID(), rows.get(0).get("lsid")); + assertEquals(m.getLSID(), rows.getFirst().get("lsid")); // verify delete via QUS rows = qus.deleteRows(user, c, List.of(CaseInsensitiveHashMap.of("rowId", m.getRowId())), null, null); @@ -1319,11 +1319,11 @@ public void testInsertOptionUpdate() throws Exception } rows = getSampleRows(sampleTypeName); - assertEquals("S-1", rows.get(0).get("name")); - assertEquals(1, rows.get(0).get("aliquotcount")); - assertEquals(0.0, rows.get(0).get("aliquotvolume")); - assertEquals(0, rows.get(0).get("availablealiquotcount")); - assertEquals(0.0, rows.get(0).get("availablealiquotvolume")); + assertEquals("S-1", rows.getFirst().get("name")); + assertEquals(1, rows.getFirst().get("aliquotcount")); + assertEquals(0.0, rows.getFirst().get("aliquotvolume")); + assertEquals(0, rows.getFirst().get("availablealiquotcount")); + assertEquals(0.0, rows.getFirst().get("availablealiquotvolume")); assertEquals("a", rows.get(0).get(requiredColName)); assertEquals(String.format("Failed insert for field \"%s\"", longFieldName), "Very", rows.get(0).get(longFieldAlias)); @@ -1361,10 +1361,10 @@ public void testInsertOptionUpdate() throws Exception rows = getSampleRows(sampleTypeName); // test existing row value is updated - assertEquals(100, rows.get(0).get("intVal")); - assertEquals(1, rows.get(0).get("aliquotcount")); - assertEquals(0.0, rows.get(0).get("aliquotvolume")); - assertEquals(0, rows.get(0).get("availablealiquotcount")); + assertEquals(100, rows.getFirst().get("intVal")); + assertEquals(1, rows.getFirst().get("aliquotcount")); + assertEquals(0.0, rows.getFirst().get("aliquotvolume")); + assertEquals(0, rows.getFirst().get("availablealiquotcount")); assertEquals(0.0, rows.get(0).get("availablealiquotvolume")); assertEquals(String.format("Data for field \"%s\" unexpectedly changed", longFieldName), "Very", rows.get(0).get(longFieldAlias)); @@ -1390,7 +1390,7 @@ public void testInsertOptionUpdate() throws Exception context.setInsertOption(QueryUpdateService.InsertOption.UPDATE); qus.loadRows(user, c, MapDataIterator.of(rowsToUpdate), context, null); assertTrue(context.getErrors().hasErrors()); - String msg = !context.getErrors().getRowErrors().isEmpty() ? context.getErrors().getRowErrors().get(0).toString() : "no message"; + String msg = !context.getErrors().getRowErrors().isEmpty() ? context.getErrors().getRowErrors().getFirst().toString() : "no message"; assertTrue(msg.contains("Sample does not exist: S-1-absent.")); context = new DataIteratorContext(); @@ -1401,7 +1401,7 @@ public void testInsertOptionUpdate() throws Exception context.setConfigParameters(auditOptions); qus.loadRows(user, c, MapDataIterator.of(rowsToUpdate), context, null); assertTrue(context.getErrors().hasErrors()); - msg = !context.getErrors().getRowErrors().isEmpty() ? context.getErrors().getRowErrors().get(0).toString() : "no message"; + msg = !context.getErrors().getRowErrors().isEmpty() ? context.getErrors().getRowErrors().getFirst().toString() : "no message"; assertTrue(msg.contains("Sample does not exist: S-1-absent.")); // AliquotedFrom is supplied but doesn't match the current aliquot status / parents should get ignored diff --git a/experiment/src/org/labkey/experiment/api/ExpUnreferencedSampleFilesTableImpl.java b/experiment/src/org/labkey/experiment/api/ExpUnreferencedSampleFilesTableImpl.java index ffd0e429609..4819eac630e 100644 --- a/experiment/src/org/labkey/experiment/api/ExpUnreferencedSampleFilesTableImpl.java +++ b/experiment/src/org/labkey/experiment/api/ExpUnreferencedSampleFilesTableImpl.java @@ -7,10 +7,8 @@ import org.labkey.api.data.CoreSchema; import org.labkey.api.data.JdbcType; import org.labkey.api.data.SQLFragment; -import org.labkey.api.data.SqlSelector; import org.labkey.api.data.TableInfo; import org.labkey.api.data.VirtualTable; -import org.labkey.api.exp.api.ExpData; import org.labkey.api.exp.api.ExperimentService; import org.labkey.api.exp.query.ExpSchema; import org.labkey.api.exp.query.ExpUnreferencedSampleFilesTable; @@ -19,8 +17,6 @@ import org.labkey.api.query.FilteredTable; import org.labkey.api.query.UserIdQueryForeignKey; import org.labkey.api.query.column.BuiltInColumnTypes; -import org.labkey.api.writer.HtmlWriter; -import org.labkey.experiment.FileLinkFileListener; public class ExpUnreferencedSampleFilesTableImpl extends FilteredTable implements ExpUnreferencedSampleFilesTable diff --git a/experiment/src/org/labkey/experiment/api/ExperimentServiceImpl.java b/experiment/src/org/labkey/experiment/api/ExperimentServiceImpl.java index 843bd1e491a..f79db389506 100644 --- a/experiment/src/org/labkey/experiment/api/ExperimentServiceImpl.java +++ b/experiment/src/org/labkey/experiment/api/ExperimentServiceImpl.java @@ -153,7 +153,6 @@ import org.labkey.api.exp.api.ProvenanceService; import org.labkey.api.exp.api.SampleTypeService; import org.labkey.api.exp.api.SimpleRunRecord; -import org.labkey.api.exp.list.ListDefinition; import org.labkey.api.exp.list.ListService; import org.labkey.api.exp.property.Domain; import org.labkey.api.exp.property.DomainKind; @@ -370,7 +369,7 @@ private Cache> getDataClassCache() public void clearDataClassCache(@Nullable Container c) { - LOG.debug("clearDataClassCache: " + (c == null ? "all" : c.getPath())); + LOG.debug("clearDataClassCache: {}", c == null ? "all" : c.getPath()); if (c == null) dataClassCache.clear(); else @@ -2902,7 +2901,7 @@ private void removeEdgesForRun(long runId) { TableInfo edge = getTinfoEdge(); int count = new SqlExecutor(edge.getSchema().getScope()).execute("DELETE FROM " + edge /* + (edge.getSqlDialect().isSqlServer() ? " WITH (TABLOCK, HOLDLOCK)" : "") */ + " WHERE runId=?", runId); - LOG.debug("Removed edges for run " + runId + "; count = " + count); + LOG.debug("Removed edges for run {}; count = {}", runId, count); } // prepare for bulk insert of edges @@ -2942,7 +2941,7 @@ private void ensureNodeObjects(TableInfo expTable, Map missingObjectRow = allNodesByLsid.get(missingObjectLsid); @@ -2996,7 +2995,7 @@ private Long ensureOwnerObject(@Nullable String cpasType, @NotNull Map> par if (paramEdgesNotInDb.isEmpty() && dbEdgesNotInParams.isEmpty()) { - LOG.debug(" all " + params.size() + " run edges and exp.edges match"); + LOG.debug(" all {} run edges and exp.edges match", params.size()); return true; } else { Map identifiableMap = new LongHashMap<>(); - LOG.warn("*** Run " + runId + " failed verification: " + (params.size() - paramEdgesNotInDb.size()) + " run edges and exp.edges match"); + LOG.warn("*** Run {} failed verification: {} run edges and exp.edges match", runId, params.size() - paramEdgesNotInDb.size()); if (!paramEdgesNotInDb.isEmpty()) { - LOG.warn(" " + paramEdgesNotInDb.size() + " run edges not in exp.edges table:"); + LOG.warn(" {} run edges not in exp.edges table:", paramEdgesNotInDb.size()); if (LOG.isDebugEnabled()) { for (List e : paramEdgesNotInDb) @@ -3063,7 +3062,7 @@ private boolean verifyEdges(long runId, Long runObjectId, List> par if (!dbEdgesNotInParams.isEmpty()) { - LOG.warn(" " + dbEdgesNotInParams.size() + " exp.edge table edges not in run:"); + LOG.warn(" {} exp.edge table edges not in run:", dbEdgesNotInParams.size()); if (LOG.isDebugEnabled()) { for (List e : dbEdgesNotInParams) @@ -3161,7 +3160,7 @@ public SyncRunEdgesTask(long runId) this(runId, null, null, null); } - public SyncRunEdgesTask(long runId, Long runObjectId, String runLsid, Container runContainer) + public SyncRunEdgesTask(long runId, Long runObjectId, @Nullable String runLsid, @Nullable Container runContainer) { _runId = runId; _runObjectId = runObjectId; @@ -3200,7 +3199,7 @@ public void queueSyncRunEdges(long runId) DbScope scope = getExpSchema().getScope(); if (scope.isTransactionActive()) { - LOG.debug("queueing syncRunEdges for run: " + runId); + LOG.debug("queueing syncRunEdges for run: {}", runId); DbScope.Transaction tx = scope.getCurrentTransaction(); tx.addCommitTask(new SyncRunEdgesTask(runId), POSTCOMMIT); } @@ -3216,7 +3215,7 @@ public void queueSyncRunEdges(ExpRun run) DbScope scope = getExpSchema().getScope(); if (scope.isTransactionActive()) { - LOG.debug("queueing syncRunEdges for run: " + run.getRowId() + " - " + run.getName()); + LOG.debug("queueing syncRunEdges for run: {} - {}", run.getRowId(), run.getName()); DbScope.Transaction tx = scope.getCurrentTransaction(); tx.addCommitTask(new SyncRunEdgesTask(run.getRowId(), run.getObjectId(), run.getLSID(), run.getContainer()), POSTCOMMIT); } @@ -3320,7 +3319,7 @@ private void syncInner(@Nullable Map cpasTypeToObjectId) CPUTimer timer = new CPUTimer("sync edges"); timer.start(); - LOG.debug((verifyEdgesNoInsert ? "Verifying" : "Rebuilding") + " edges for runId " + runId); + LOG.debug("{} edges for runId {}", verifyEdgesNoInsert ? "Verifying" : "Rebuilding", runId); Set dataToCpasTypes = new HashSet<>(); // NOTE: Originally, we just filtered exp.data by runId. This works for most runs but includes intermediate exp.data nodes and caused the ExpTest to fail SQLFragment dataObjects = new SQLFragment() @@ -3343,9 +3342,9 @@ private void syncInner(@Nullable Map cpasTypeToObjectId) if (LOG.isDebugEnabled()) { if (!fromDataLsids.isEmpty()) - LOG.debug(" fromDataLsids:\n " + StringUtils.join(fromDataLsids, "\n ")); + LOG.debug(" fromDataLsids:\n {}", StringUtils.join(fromDataLsids, "\n ")); if (!toDataLsids.isEmpty()) - LOG.debug(" toDataLsids:\n " + StringUtils.join(toDataLsids, "\n ")); + LOG.debug(" toDataLsids:\n {}", StringUtils.join(toDataLsids, "\n ")); } SQLFragment materials = new SQLFragment() @@ -3390,8 +3389,7 @@ private void syncInner(@Nullable Map cpasTypeToObjectId) removeEdgesForRun(runId); int edgeCount = fromDataLsids.size() + fromMaterialLsids.size() + toDataLsids.size() + toMaterialLsids.size() + provenanceStartingInputs.size() + provenanceFinalOutputs.size(); - LOG.debug(String.format(" edge counts: input data=%d, input materials=%d, output data=%d, output materials=%d, input prov=%d, output prov=%d, total=%d", - fromDataLsids.size(), fromMaterialLsids.size(), toDataLsids.size(), toMaterialLsids.size(), provenanceStartingInputs.size(), provenanceFinalOutputs.size(), edgeCount)); + LOG.debug(" edge counts: input data={}, input materials={}, output data={}, output materials={}, input prov={}, output prov={}, total={}", fromDataLsids.size(), fromMaterialLsids.size(), toDataLsids.size(), toMaterialLsids.size(), provenanceStartingInputs.size(), provenanceFinalOutputs.size(), edgeCount); if (edgeCount > 0) { @@ -3402,7 +3400,7 @@ private void syncInner(@Nullable Map cpasTypeToObjectId) { OntologyObject runObj = OntologyManager.getOntologyObject(runContainer, runLsid); if (runObj == null) - LOG.debug(" run exp.object is null, creating: " + runLsid); + LOG.debug(" run exp.object is null, creating: {}", runLsid); } if (!verifyEdgesNoInsert) runObjectId = OntologyManager.ensureObject(runContainer, runLsid, (Long) null); @@ -3503,7 +3501,7 @@ private void syncInner(@Nullable Map cpasTypeToObjectId) } timer.stop(); - LOG.debug(" " + (verifyEdgesNoInsert ? "verified" : "synced") + " edges in " + timer.getDuration()); + LOG.debug(" {} edges in {}", verifyEdgesNoInsert ? "verified" : "synced", timer.getDuration()); if (!verifyEdgesNoInsert && doIncrementalClosureInvalidation) { @@ -3530,7 +3528,7 @@ public void rebuildAllRunEdges() getTinfoExperimentRun().getColumns("rowId", "objectid", "lsid", "container"), null, new Sort("rowId")).getMapCollection(); try (Timing ignored = MiniProfiler.step("create edges")) { - LOG.debug("Rebuilding edges for " + runs.size() + " runs"); + LOG.debug("Rebuilding edges for {} runs", runs.size()); for (Map run : runs) { var runId = asLong(run.get("rowId")); @@ -3549,7 +3547,7 @@ public void rebuildAllRunEdges() if (timing != null) { timing.stop(); - LOG.debug("Rebuilt all run-based edges: " + timing.getDuration() + " ms"); + LOG.debug("Rebuilt all run-based edges: {} ms", timing.getDuration()); } } ClosureQueryHelper.truncateAndRecreate(LOG); @@ -3595,7 +3593,7 @@ private void _verifyAllEdges(Container c, @Nullable Integer limit) int runCount = 0; try (Timing ignored = MiniProfiler.step("create edges")) { - LOG.info("Verifying edges for " + runs.size() + " runs in " + c.getPath()); + LOG.info("Verifying edges for {} runs in {}", runs.size(), c.getPath()); for (Map run : runs) { var runId = asLong(run.get("rowId")); @@ -3611,7 +3609,7 @@ private void _verifyAllEdges(Container c, @Nullable Integer limit) if (runCount % 1000 == 0) { - LOG.info(" verified " + runCount + " runs..."); + LOG.info(" verified {} runs...", runCount); } } } @@ -3619,7 +3617,7 @@ private void _verifyAllEdges(Container c, @Nullable Integer limit) if (timing != null) { timing.stop(); - LOG.info("Verified edges for " + (limit == null ? "all " : "only ") + runCount + " runs: " + timing.getDuration() + " ms"); + LOG.info("Verified edges for {}{} runs: {} ms", limit == null ? "all " : "only ", runCount, timing.getDuration()); } } } @@ -4336,7 +4334,7 @@ public void deleteExperimentRuns(Container container, final User user, @Nullable otherUsages.remove(run); if (!otherUsages.isEmpty()) { - LOG.debug("Skipping delete of cross-run output data '" + output.getName() + "' (" + output.getRowId() + ") used by other runs: " + otherUsages.stream().map(ExpRun::getName).collect(Collectors.joining(", "))); + LOG.debug("Skipping delete of cross-run output data '{}' ({}) used by other runs: {}", output.getName(), output.getRowId(), otherUsages.stream().map(ExpRun::getName).collect(Collectors.joining(", "))); break; } @@ -4349,7 +4347,7 @@ public void deleteExperimentRuns(Container container, final User user, @Nullable // CONSIDER: move these properties to the matching output exp.data with the same dataFileUrl? if (hasFileProperties(container, input)) { - LOG.debug("Skipping delete of cross-run input data '" + input.getName() + "' (" + input.getRowId() + ") with custom file properties"); + LOG.debug("Skipping delete of cross-run input data '{}' ({}) with custom file properties", input.getName(), input.getRowId()); continue; } @@ -4388,12 +4386,12 @@ public void deleteExperimentRuns(Container container, final User user, @Nullable // Delete the cross run data completely for (ExpDataImpl data : crossRunInputs) { - LOG.debug("Deleting cross-run input data: name=" + data.getName() + ", rowId=" + data.getRowId() + ", dataFileUrl=" + data.getDataFileUrl()); + LOG.debug("Deleting cross-run input data: name={}, rowId={}, dataFileUrl={}", data.getName(), data.getRowId(), data.getDataFileUrl()); data.delete(user, false); } for (ExpDataImpl data : crossRunOutputs) { - LOG.debug("Deleting cross-run output data: name=" + data.getName() + ", rowId=" + data.getRowId() + ", dataFileUrl=" + data.getDataFileUrl()); + LOG.debug("Deleting cross-run output data: name={}, rowId={}, dataFileUrl={}", data.getName(), data.getRowId(), data.getDataFileUrl()); data.delete(user, false); } @@ -4853,7 +4851,7 @@ public int deleteMaterialBySqlFilter( { ExpSampleTypeImpl st = material.getSampleType(); if (st == null && !ExpMaterial.DEFAULT_CPAS_TYPE.equals(material.getCpasType())) - LOG.warn("SampleType '" + material.getCpasType() + "' not found while deleting sample '" + material.getName() + "'"); + LOG.warn("SampleType '{}' not found while deleting sample '{}'", material.getCpasType(), material.getName()); sampleTypes.put(cpasType, st); } } @@ -4892,7 +4890,7 @@ public int deleteMaterialBySqlFilter( deleteRunsUsingInputs(user, null, rawMaterials); } } - LOG.debug("Completed batch of sample deletion. " + count + " rows processed so far"); + LOG.debug("Completed batch of sample deletion. {} rows processed so far", count); } // generate in clause for the Material LSIDs @@ -5043,7 +5041,7 @@ public int deleteMaterialBySqlFilter( transaction.commit(); if (timing != null) - LOG.info("SampleType delete timings\n" + timing.dump()); + LOG.info("SampleType delete timings\n{}", timing.dump()); return count; } } @@ -6128,7 +6126,7 @@ public void deleteDataClass(long rowId, Container c, User user, @Nullable final if (null == dataClass) { // this can happen if the DataClass wasn't created completely - LOG.warn("Can't find DataClass with rowId " + rowId + " for deletion"); + LOG.warn("Can't find DataClass with rowId {} for deletion", rowId); return; } if (!dataClass.getContainer().equals(c)) @@ -6455,7 +6453,7 @@ private ExpProtocolApplicationImpl resolveProtApp(ExpRunImpl expRun, Map insertSamples(User user, Container c, String sampleTypeName else noun = "derived samples"; } - LOG.info("** inserting " + rowCount + " " + noun + " " + "..."); + LOG.info("** inserting {} {} ...", rowCount, noun); int existingNameCount = existingNames != null ? existingNames.size() : 0; // generate some data @@ -120,7 +120,7 @@ private List insertSamples(User user, Container c, String sampleTypeName throw errors; tx.commit(); - LOG.info("** inserted " + inserted.size() + " " + noun); + LOG.info("** inserted {} {}", inserted.size(), noun); // get the inserted names return inserted.stream().map(row -> (String)row.get("name")).collect(Collectors.toList()); @@ -175,7 +175,7 @@ private void _sampleTypeInserts(RunMode mode) throws Throwable Assume.assumeFalse("Issue 47033: Test does not yet pass on SQL Server. Skipping.", CoreSchema.getInstance().getSqlDialect().isSqlServer()); - LOG.info("** starting sample type insert test " + mode._description); + LOG.info("** starting sample type insert test {}", mode._description); final User user = TestContext.get().getUser(); final Container c = JunitUtil.getTestContainer(); @@ -199,7 +199,7 @@ private void _sampleTypeInserts(RunMode mode) throws Throwable final int threads = mode._thread; final int races = mode._race; - LOG.info("** starting racy inserts (threads=" + threads + ", races=" + races + ", rows=" + rowsToInsert + ")"); + LOG.info("** starting racy inserts (threads={}, races={}, rows=" + rowsToInsert + ")", threads, races); JunitUtil.createRaces(() -> { try diff --git a/experiment/src/org/labkey/experiment/api/LineageTest.java b/experiment/src/org/labkey/experiment/api/LineageTest.java index 77122db05ed..e33eaf5b8c8 100644 --- a/experiment/src/org/labkey/experiment/api/LineageTest.java +++ b/experiment/src/org/labkey/experiment/api/LineageTest.java @@ -776,7 +776,7 @@ public void testPropertySerialization() throws Exception "DataInputs/" + dataClassName, List.of(dad, son) )); var rows = insertRows(c, sampleRows, sampleTypeName, QueryService.get().getUserSchema(user, c, SchemaKey.fromParts("Samples"))); - var gameSample = expSvc.getExpMaterial((Integer) rows.get(0).get("RowId")); + var gameSample = expSvc.getExpMaterial((Integer) rows.getFirst().get("RowId")); var options = new ExpLineageOptions(false, true, 2); options.setIncludeProperties(true); diff --git a/experiment/src/org/labkey/experiment/api/LogDataType.java b/experiment/src/org/labkey/experiment/api/LogDataType.java index 5e0b675cc56..d5d1ca73cda 100644 --- a/experiment/src/org/labkey/experiment/api/LogDataType.java +++ b/experiment/src/org/labkey/experiment/api/LogDataType.java @@ -17,8 +17,6 @@ package org.labkey.experiment.api; import org.labkey.api.exp.api.DataType; -import org.labkey.api.exp.api.ExpData; -import org.labkey.api.view.ActionURL; public class LogDataType extends DataType { @@ -26,9 +24,4 @@ public LogDataType() { super("Log"); } - @Override - public ActionURL getDetailsURL(ExpData dataObject) - { - return null; - } } diff --git a/experiment/src/org/labkey/experiment/api/PhiFieldsTable.java b/experiment/src/org/labkey/experiment/api/PhiFieldsTable.java index 7f394aa1f1d..67f6e1eb667 100644 --- a/experiment/src/org/labkey/experiment/api/PhiFieldsTable.java +++ b/experiment/src/org/labkey/experiment/api/PhiFieldsTable.java @@ -4,7 +4,6 @@ import org.jetbrains.annotations.Nullable; import org.labkey.api.data.CompareType; import org.labkey.api.data.ContainerFilter; -import org.labkey.api.data.JdbcType; import org.labkey.api.data.MutableColumnInfo; import org.labkey.api.data.SQLFragment; import org.labkey.api.data.SimpleFilter; diff --git a/experiment/src/org/labkey/experiment/api/ReferenceCountDisplayColumnFactory.java b/experiment/src/org/labkey/experiment/api/ReferenceCountDisplayColumnFactory.java index 8a089234f32..70ba92a500b 100644 --- a/experiment/src/org/labkey/experiment/api/ReferenceCountDisplayColumnFactory.java +++ b/experiment/src/org/labkey/experiment/api/ReferenceCountDisplayColumnFactory.java @@ -3,7 +3,6 @@ import org.apache.commons.lang3.StringUtils; import org.labkey.api.data.ColumnInfo; import org.labkey.api.data.CoreSchema; -import org.labkey.api.data.DataColumn; import org.labkey.api.data.DisplayColumn; import org.labkey.api.data.DisplayColumnFactory; import org.labkey.api.data.SQLFragment; diff --git a/experiment/src/org/labkey/experiment/api/SampleTypeServiceImpl.java b/experiment/src/org/labkey/experiment/api/SampleTypeServiceImpl.java index 75c38a5d465..8cbd4c9ad87 100644 --- a/experiment/src/org/labkey/experiment/api/SampleTypeServiceImpl.java +++ b/experiment/src/org/labkey/experiment/api/SampleTypeServiceImpl.java @@ -266,7 +266,7 @@ else if (u.getKindOfQuantity() != defaultUnits.getKindOfQuantity()) public void clearMaterialSourceCache(@Nullable Container c) { - LOG.debug("clearMaterialSourceCache: " + (c == null ? "all" : c.getPath())); + LOG.debug("clearMaterialSourceCache: {}", c == null ? "all" : c.getPath()); if (c == null) materialSourceCache.clear(); else @@ -696,7 +696,7 @@ public void deleteSampleType(long rowId, Container c, User user, @Nullable Strin } timer.stop(); - LOG.info("Deleted SampleType '" + source.getName() + "' from '" + c.getPath() + "' in " + timer.getDuration()); + LOG.info("Deleted SampleType '{}' from '{}' in {}", source.getName(), c.getPath(), timer.getDuration()); } private void addSampleTypeDeletedAuditEvent(User user, Container c, ExpSampleType sampleType, @Nullable String auditUserComment) @@ -1710,12 +1710,12 @@ private AliquotAvailableAmountUnit computeAliquotTotalAmounts(List> updateSampleFilePaths(ExpSampleType if (fileService.getFileRoot(targetContainer) == null) { - LOG.warn("No file root found for target container " + targetContainer + "'. Files cannot be moved."); + LOG.warn("No file root found for target container {}'. Files cannot be moved.", targetContainer); return sampleFileRenames; } @@ -2206,7 +2206,7 @@ private Map> updateSampleFilePaths(ExpSampleType { boolean hasSourceRoot = hasFileRoot.computeIfAbsent(sample.getContainer(), (container) -> fileService.getFileRoot(container) != null); if (!hasSourceRoot) - LOG.warn("No file root found for source container " + sample.getContainer() + ". Files cannot be moved."); + LOG.warn("No file root found for source container {}. Files cannot be moved.", sample.getContainer()); else for (DomainProperty fileProp : fileDomainProps ) { @@ -2272,7 +2272,7 @@ private boolean moveFile(FileFieldRenameData renameData, Container sourceContain } catch (IOException e) { - LOG.warn(errorMsg + e.getMessage()); + LOG.warn("{}{}", errorMsg, e.getMessage()); } } diff --git a/experiment/src/org/labkey/experiment/api/SampleTypeUpdateServiceDI.java b/experiment/src/org/labkey/experiment/api/SampleTypeUpdateServiceDI.java index cff9c3bff22..0c9ab919886 100644 --- a/experiment/src/org/labkey/experiment/api/SampleTypeUpdateServiceDI.java +++ b/experiment/src/org/labkey/experiment/api/SampleTypeUpdateServiceDI.java @@ -257,11 +257,11 @@ private Pair, Set> getSampleParentsForRecalc(List rootRowIds = new LongHashSet(); Set parentNames = new HashSet<>(); - if (outputRows.size() == 1 && outputRows.get(0).containsKey(ROOT_RECOMPUTE_ROWID_SET)) + if (outputRows.size() == 1 && outputRows.getFirst().containsKey(ROOT_RECOMPUTE_ROWID_SET)) { - rootRowIds.addAll((Collection) outputRows.get(0).get(ROOT_RECOMPUTE_ROWID_SET)); - if (outputRows.get(0).containsKey(PARENT_RECOMPUTE_NAME_SET)) - parentNames.addAll((Collection) outputRows.get(0).get(PARENT_RECOMPUTE_NAME_SET)); + rootRowIds.addAll((Collection) outputRows.getFirst().get(ROOT_RECOMPUTE_ROWID_SET)); + if (outputRows.getFirst().containsKey(PARENT_RECOMPUTE_NAME_SET)) + parentNames.addAll((Collection) outputRows.getFirst().get(PARENT_RECOMPUTE_NAME_SET)); } else { @@ -482,7 +482,7 @@ public int mergeRows(User user, Container container, DataIteratorBuilder rows, B } @Override - public List> insertRows(User user, Container container, List> rows, BatchValidationException errors, @Nullable Map configParameters, Map extraScriptContext) throws SQLException + public List> insertRows(User user, Container container, List> rows, BatchValidationException errors, @Nullable Map configParameters, Map extraScriptContext) { assert _sampleType != null : "SampleType required for insert/update, but not required for read/delete"; // insertRows with lineage is pretty good at deadlocking against itself, so use retry loop @@ -527,7 +527,7 @@ public List> updateRows( BatchValidationException errors, @Nullable Map configParameters, Map extraScriptContext - ) throws InvalidKeyException, BatchValidationException, QueryUpdateServiceException, SQLException + ) throws BatchValidationException { assert _sampleType != null : "SampleType required for insert/update, but not required for read/delete"; if (rows == null || rows.isEmpty()) diff --git a/experiment/src/org/labkey/experiment/api/UniqueValueCounterTestCase.java b/experiment/src/org/labkey/experiment/api/UniqueValueCounterTestCase.java index 464dff92606..5cdd6397ac5 100644 --- a/experiment/src/org/labkey/experiment/api/UniqueValueCounterTestCase.java +++ b/experiment/src/org/labkey/experiment/api/UniqueValueCounterTestCase.java @@ -155,7 +155,7 @@ sampTypeName, null, props, emptyList(), if (errors.hasErrors()) throw errors; assertEquals(1, inserted.size()); - assertEquals("STP.12.1.SUF4B", inserted.get(0).get("name")); + assertEquals("STP.12.1.SUF4B", inserted.getFirst().get("name")); // GOOD INSERT - not including the attached column 'three' is ok @@ -166,7 +166,7 @@ sampTypeName, null, props, emptyList(), if (errors.hasErrors()) throw errors; assertEquals(1, inserted.size()); - assertEquals("STP.10.5.SUF1", inserted.get(0).get("name")); + assertEquals("STP.10.5.SUF1", inserted.getFirst().get("name")); // BAD INSERT - Duplicate name @@ -294,7 +294,7 @@ public void dataClassWithCounter() throws Exception inserted = svc.insertRows(user, c, rows, errors, null, null); assertFalse(errors.hasErrors()); assertEquals(1, inserted.size()); - assertEquals("DC-10.1.5", inserted.get(0).get("name")); + assertEquals("DC-10.1.5", inserted.getFirst().get("name")); // NOTE: This test case doesn't repro for SampleType because the CoerceDataIterator is run before the CounterDataIteratorBuilder and will include null values for any missing columns diff --git a/experiment/src/org/labkey/experiment/api/property/DomainImpl.java b/experiment/src/org/labkey/experiment/api/property/DomainImpl.java index 40cc0aa1632..c388e6a139f 100644 --- a/experiment/src/org/labkey/experiment/api/property/DomainImpl.java +++ b/experiment/src/org/labkey/experiment/api/property/DomainImpl.java @@ -17,7 +17,6 @@ package org.labkey.experiment.api.property; import org.apache.commons.beanutils.ConversionException; -import org.apache.commons.beanutils.ConvertUtils; import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.time.FastDateFormat; import org.jetbrains.annotations.NotNull; diff --git a/experiment/src/org/labkey/experiment/api/property/DomainPropertyImpl.java b/experiment/src/org/labkey/experiment/api/property/DomainPropertyImpl.java index af7734719c9..3130117c0b6 100644 --- a/experiment/src/org/labkey/experiment/api/property/DomainPropertyImpl.java +++ b/experiment/src/org/labkey/experiment/api/property/DomainPropertyImpl.java @@ -1267,7 +1267,7 @@ public void testUpdateDomainPropertyFromDescriptor() OntologyManager.updateDomainPropertyFromDescriptor(_dp, _pd); assertTrue(_dp.isDirty()); assertFalse(_dp._schemaChanged); - assertTrue(_dp.getPHI() == _pd.getPHI()); + assertSame(_dp.getPHI(), _pd.getPHI()); // Issue #18738 change the schema outside of a schema reload and verify that the column // change the schema but don't mark the property as "Schema Import" @@ -1329,7 +1329,7 @@ private void verifyLookup(String containerId, String schema, String query, Boole _pd.setLookupQuery(query); _pd.setLookupSchema(schema); OntologyManager.updateDomainPropertyFromDescriptor(_dp, _pd); - assertTrue(_dp.isDirty() == expectedDirty); + assertEquals(_dp.isDirty(), (boolean) expectedDirty); assertFalse(_dp._schemaChanged); // verify the lookup object returned @@ -1344,7 +1344,7 @@ private void verifyLookup(String containerId, String schema, String query, Boole else if (query == null || schema == null) assertTrue(true); else - assertTrue(false); + fail(); } else { diff --git a/experiment/src/org/labkey/experiment/api/property/LookupValidator.java b/experiment/src/org/labkey/experiment/api/property/LookupValidator.java index f4183c0354b..0ae6e4ec17c 100644 --- a/experiment/src/org/labkey/experiment/api/property/LookupValidator.java +++ b/experiment/src/org/labkey/experiment/api/property/LookupValidator.java @@ -21,7 +21,6 @@ import org.labkey.api.data.ColumnRenderProperties; import org.labkey.api.data.Container; import org.labkey.api.data.ContainerManager; -import org.labkey.api.data.ConvertHelper; import org.labkey.api.data.ForeignKey; import org.labkey.api.data.JdbcType; import org.labkey.api.data.TableInfo; @@ -199,7 +198,7 @@ private void processTableInfo(TableInfo tableInfo, JdbcType jdbcType, String que } else { - ColumnInfo lookupTargetCol = keyCols.get(0); + ColumnInfo lookupTargetCol = keyCols.getFirst(); // Hack for sample types - see also revision 37612 if (lookupTargetCol.getJdbcType() != jdbcType && jdbcType.isText() && tableInfo instanceof ExpMaterialTableImpl) { diff --git a/experiment/src/org/labkey/experiment/api/property/StorageProvisionerImpl.java b/experiment/src/org/labkey/experiment/api/property/StorageProvisionerImpl.java index 238e3eaa869..4148bb6de9c 100644 --- a/experiment/src/org/labkey/experiment/api/property/StorageProvisionerImpl.java +++ b/experiment/src/org/labkey/experiment/api/property/StorageProvisionerImpl.java @@ -193,7 +193,7 @@ private String _create(DbScope scope, DomainKind kind, Domain domain, boolean // apparently this is a case where the domain allows a propertydescriptor to be defined with the same // name as a built-in column. e.g. to allow setting overrides? if (!kind.hasPropertiesIncludeBaseProperties()) - log.info("StorageProvisioner ignored property with name of built-in column: " + property.getPropertyURI()); + log.info("StorageProvisioner ignored property with name of built-in column: {}", property.getPropertyURI()); continue; } @@ -217,7 +217,7 @@ private String _create(DbScope scope, DomainKind kind, Domain domain, boolean try { - log.info("Attempting to create " + tableName); + log.info("Attempting to create {}", tableName); change.execute(); RECENTLY_CREATED_TABLES.put(tableName, Thread.currentThread().getStackTrace()); } @@ -226,7 +226,7 @@ private String _create(DbScope scope, DomainKind kind, Domain domain, boolean StackTraceElement[] previousCreationStack = RECENTLY_CREATED_TABLES.getIfPresent(tableName); if (null != previousCreationStack) - log.error(re.getMessage() + " while attempting to create storage table. Previous creation stack trace:" + ExceptionUtil.renderStackTrace(previousCreationStack)); + log.error("{} while attempting to create storage table. Previous creation stack trace:{}", re.getMessage(), ExceptionUtil.renderStackTrace(previousCreationStack)); throw re; } @@ -280,7 +280,7 @@ public void drop(Domain domain) if (kind == null) { if (null != domain.getStorageTableName()) - log.warn("Domain " + domain.getName() + " has no DomainKind, it cannot be dropped. URI: " + domain.getTypeURI(), new IllegalStateException()); + log.warn("Domain {} has no DomainKind, it cannot be dropped. URI: {}", domain.getName(), domain.getTypeURI(), new IllegalStateException()); return; } @@ -304,13 +304,13 @@ public void drop(Domain domain) } catch (RuntimeSQLException e) { - log.warn(String.format("Failed to drop table in schema %s for domain %s - %s", schemaName, domain.getName(), e.getMessage()), e); + log.warn("Failed to drop table in schema {} for domain {} - {}", schemaName, domain.getName(), e.getMessage(), e); throw e; } } else { - log.warn(String.format("Table %s in schema %s for domain %s does not exist. Ignoring drop.", tableName, schemaName, domain.getName())); + log.warn("Table {} in schema {} for domain {} does not exist. Ignoring drop.", tableName, schemaName, domain.getName()); } // Issue 44467: Update DbSchema caches kind.invalidate(domain); @@ -340,7 +340,7 @@ public void addStorageProperties(Domain domain, Collection { // apparently this is a case where the domain allows a propertydescriptor to be defined with the same // name as a built-in column. e.g. to allow setting overrides? - log.warn("StorageProvisioner ignored property with name of built-in column: " + prop.getName()); + log.warn("StorageProvisioner ignored property with name of built-in column: {}", prop.getName()); continue; } @@ -384,12 +384,12 @@ public void addProperties(Domain domain, Collection properties, { // apparently this is a case where the domain allows a propertydescriptor to be defined with the same // name as a built-in column. e.g. to allow setting overrides? - log.warn("StorageProvisioner ignored property with name of built-in column: " + prop.getPropertyURI()); + log.warn("StorageProvisioner ignored property with name of built-in column: {}", prop.getPropertyURI()); continue; } if (CoreSchema.getInstance().getSqlDialect().isReserved(prop.getName())) - log.warn("Property name '" + prop.getName() + "' is a reserved word in the current SQL dialect."); + log.warn("Property name '{}' is a reserved word in the current SQL dialect.", prop.getName()); PropertyStorageSpec spec = kind.getPropertySpec(prop.getPropertyDescriptor(), domain); if (null != spec) @@ -401,7 +401,7 @@ public void addProperties(Domain domain, Collection properties, change.addColumn(makeMvColumn(prop)); } } - log.debug("addingProperties to " + domain.getName()); + log.debug("addingProperties to {}", domain.getName()); change.execute(); } @@ -1099,7 +1099,7 @@ public void fixupProvisionedDomain(SchemaTableInfo ti, DomainKind kind, Domai if (null == c) { - log.info("Column not found in storage table: " + tableName + "." + s.getName()); + log.info("Column not found in storage table: {}.{}", tableName, s.getName()); continue; } @@ -1133,11 +1133,11 @@ public void fixupProvisionedDomain(SchemaTableInfo ti, DomainKind kind, Domai { if (p.getPropertyDescriptor().getStorageColumnName() == null) { - log.warn("No storage column name set for property " + p.getName() + " on table " + tableName); + log.warn("No storage column name set for property {} on table {}", p.getName(), tableName); } else { - log.info("Column not found in storage table: " + tableName + "." + p.getPropertyDescriptor().getStorageColumnName()); + log.info("Column not found in storage table: {}.{}", tableName, p.getPropertyDescriptor().getStorageColumnName()); } continue; } diff --git a/experiment/src/org/labkey/experiment/api/property/TextChoiceValidator.java b/experiment/src/org/labkey/experiment/api/property/TextChoiceValidator.java index dcca8bba1e5..ce57c5a6a6b 100644 --- a/experiment/src/org/labkey/experiment/api/property/TextChoiceValidator.java +++ b/experiment/src/org/labkey/experiment/api/property/TextChoiceValidator.java @@ -18,7 +18,6 @@ import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.labkey.api.data.ColumnRenderProperties; -import org.labkey.api.data.MultiChoice; import org.labkey.api.exp.property.IPropertyValidator; import org.labkey.api.exp.property.PropertyService; import org.labkey.api.exp.property.ValidatorContext; diff --git a/experiment/src/org/labkey/experiment/controllers/exp/ExperimentController.java b/experiment/src/org/labkey/experiment/controllers/exp/ExperimentController.java index 83b083b723b..7ea9f73f761 100644 --- a/experiment/src/org/labkey/experiment/controllers/exp/ExperimentController.java +++ b/experiment/src/org/labkey/experiment/controllers/exp/ExperimentController.java @@ -604,7 +604,7 @@ public ModelAndView getView(Object o, BindException errors) List rowsWithNull = new ArrayList<>(); ColumnInfo entityIdCol = table.getColumn("EntityId"); - ColumnInfo pkCol = table.getPkColumns().get(0); + ColumnInfo pkCol = table.getPkColumns().getFirst(); new TableSelector(table, List.of(entityIdCol, pkCol), @@ -626,7 +626,7 @@ public ModelAndView getView(Object o, BindException errors) if (!fixupsNeeded.isEmpty()) { - listSummaries.put(new ProblemType(table.getName(), fieldName, table.getPkColumnNames().get(0)), fixupsNeeded); + listSummaries.put(new ProblemType(table.getName(), fieldName, table.getPkColumnNames().getFirst()), fixupsNeeded); } } @@ -3362,7 +3362,7 @@ public ModelAndView getView(DeleteForm deleteForm, boolean reshow, BindException if (!idToRunMap.isEmpty() && assayService != null ) { // using the first run as a representative, since all interactions here are (I believe) using the same protocol. - ExpProtocol protocol = runs.get(0).getProtocol(); + ExpProtocol protocol = runs.getFirst().getProtocol(); AssayProvider provider = assayService.getProvider(protocol); if (provider != null) { @@ -4488,7 +4488,7 @@ protected void initRequest(QueryForm form) throws ServletException TableInfo t = query.getTable(form.getSchema(), qpe, true); if (!qpe.isEmpty()) - throw qpe.get(0); + throw qpe.getFirst(); if (!getOptionParamValue(Params.crossTypeImport) && null != t) { setTarget(t); @@ -5434,7 +5434,7 @@ public void addNavTrail(NavTree root) setHelpTopic("sampleSets"); addRootNavTrail(root); root.addChild("Sample Types", ExperimentUrlsImpl.get().getShowSampleTypeListURL(getContainer())); - ExpSampleType sampleType = _materials != null && !_materials.isEmpty() ? _materials.get(0).getSampleType() : null; + ExpSampleType sampleType = _materials != null && !_materials.isEmpty() ? _materials.getFirst().getSampleType() : null; if (sampleType != null) { root.addChild(sampleType.getName(), ExperimentUrlsImpl.get().getShowSampleTypeURL(sampleType)); @@ -5633,7 +5633,7 @@ public void addNavTrail(NavTree root) setHelpTopic("sampleSets"); addRootNavTrail(root); root.addChild("Sample Types", ExperimentUrlsImpl.get().getShowSampleTypeListURL(getContainer())); - ExpSampleType sampleType = _materials != null && !_materials.isEmpty() ? _materials.get(0).getSampleType() : null; + ExpSampleType sampleType = _materials != null && !_materials.isEmpty() ? _materials.getFirst().getSampleType() : null; if (sampleType != null) { root.addChild(sampleType.getName(), ExperimentUrlsImpl.get().getShowSampleTypeURL(sampleType)); diff --git a/experiment/src/org/labkey/experiment/controllers/property/PropertyController.java b/experiment/src/org/labkey/experiment/controllers/property/PropertyController.java index 752ff23da99..5ba3dfc65d8 100644 --- a/experiment/src/org/labkey/experiment/controllers/property/PropertyController.java +++ b/experiment/src/org/labkey/experiment/controllers/property/PropertyController.java @@ -116,7 +116,6 @@ import org.springframework.web.multipart.MultipartHttpServletRequest; import org.springframework.web.servlet.ModelAndView; -import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; import jakarta.servlet.http.HttpSession; import java.io.File; @@ -762,7 +761,7 @@ public void validateForm(UpdateDomainApiForm form, Errors errors) } if (domains.size() == 1) - _domain = domains.get(0); + _domain = domains.getFirst(); } if (_domain == null) @@ -1364,12 +1363,12 @@ public void setCheckCommentLineCount(boolean checkCommentLineCount) _checkCommentLineCount = checkCommentLineCount; } - public Collection getDistinctValueColumns() + public @Nullable Collection getDistinctValueColumns() { return _distinctValueColumns; } - public void setDistinctValueColumns(Collection distinctValueColumns) + public void setDistinctValueColumns(@Nullable Collection distinctValueColumns) { _distinctValueColumns = distinctValueColumns; } @@ -2107,12 +2106,12 @@ public void setDomainNames(Set domainNames) this.domainNames = domainNames; } - public String getSearch() + public @Nullable String getSearch() { return search; } - public void setSearch(String search) + public void setSearch(@Nullable String search) { this.search = search; } @@ -2322,20 +2321,20 @@ public void testGetProperties() throws ValidationException domains = OntologyManager.getDomains(c, user, Set.of(domain.getTypeId()), null, null); pds = OntologyManager.getPropertyDescriptors(c, user, domains,"howdy", null, null, null, null); assertEquals(1, pds.size()); - assertEquals("testStringField", pds.get(0).getName()); + assertEquals("testStringField", pds.getFirst().getName()); // find by domainId and property descriptor feature domains = OntologyManager.getDomains(c, user, Set.of(domain.getTypeId()), null, null); pds = OntologyManager.getPropertyDescriptors(c, user, domains, null, new SimpleFilter(FieldKey.fromParts("propertyId", "dimension"), true), null, null, null); assertEquals(1, pds.size()); - assertEquals("testIntField", pds.get(0).getName()); + assertEquals("testIntField", pds.getFirst().getName()); // pagination domains = OntologyManager.getDomains(c, user, Set.of(domain.getTypeId()), null, null); pds = OntologyManager.getPropertyDescriptors(c, user, domains, null, null, null, 1, 1L); assertEquals(1, pds.size()); // sorted by propertyId, testStringField is after testIntField - assertEquals("testStringField", pds.get(0).getName()); + assertEquals("testStringField", pds.getFirst().getName()); long totalCount = OntologyManager.getPropertyDescriptorsRowCount(c, user, domains, null, null); assertEquals(domain.getProperties().size(), totalCount); @@ -2377,7 +2376,7 @@ public void testPropertyUsages() throws Exception var intPropUsages = OntologyManager.findPropertyUsages(user, intProp.getPropertyDescriptor(), 1); assertEquals(1, intPropUsages.usageCount); assertEquals(1, intPropUsages.objects.size()); - assertEquals(a1Lsid.toString(), intPropUsages.objects.get(0).getLSID()); + assertEquals(a1Lsid.toString(), intPropUsages.objects.getFirst().getLSID()); } } } diff --git a/experiment/src/org/labkey/experiment/defaults/DefaultValueServiceImpl.java b/experiment/src/org/labkey/experiment/defaults/DefaultValueServiceImpl.java index aabf1fb6965..615e553c166 100644 --- a/experiment/src/org/labkey/experiment/defaults/DefaultValueServiceImpl.java +++ b/experiment/src/org/labkey/experiment/defaults/DefaultValueServiceImpl.java @@ -173,7 +173,7 @@ private void replaceObject(Container container, Domain domain, String objectLSID } catch (ConversionException e) { - LogManager.getLogger(DefaultValueServiceImpl.class).warn("Unable to convert default value '" + value + "' for property " + property.getName() + ", dropping it"); + LogManager.getLogger(DefaultValueServiceImpl.class).warn("Unable to convert default value '{}' for property {}, dropping it", value, property.getName()); } } } diff --git a/experiment/src/org/labkey/experiment/lineage/ExpLineageServiceImpl.java b/experiment/src/org/labkey/experiment/lineage/ExpLineageServiceImpl.java index 29229a9dabe..4dbbf20b22e 100644 --- a/experiment/src/org/labkey/experiment/lineage/ExpLineageServiceImpl.java +++ b/experiment/src/org/labkey/experiment/lineage/ExpLineageServiceImpl.java @@ -104,7 +104,7 @@ else if (seed instanceof IdentifiableBase identifiableSeed) if (seed instanceof ExpRunItem && ExperimentServiceImpl.get().isUnknownMaterial((ExpRunItem) seed)) { - LOG.warn("Lineage not available for unknown material: " + seed.getLSID()); + LOG.warn("Lineage not available for unknown material: {}", seed.getLSID()); continue; } @@ -173,8 +173,7 @@ public LineageResult getLineageResult(Container container, User user, @NotNull S if (parentRowId == null || childRowId == null) { - LOG.error(String.format("Node not found for lineage: %s.\n depth=%d, parentLsid=%s, parentType=%s, parentRowId=%d, childLsid=%s, childType=%s, childRowId=%d", - StringUtils.join(seedIdentifiers.lsids(), ", "), depth, parentLSID, parentExpType, parentRowId, childLSID, childExpType, childRowId)); + LOG.error("Node not found for lineage: {}.\n depth={}, parentLsid={}, parentType={}, parentRowId={}, childLsid={}, childType={}, childRowId={}", StringUtils.join(seedIdentifiers.lsids(), ", "), depth, parentLSID, parentExpType, parentRowId, childLSID, childExpType, childRowId); } else { diff --git a/experiment/src/org/labkey/experiment/lineage/LineagePerfTest.java b/experiment/src/org/labkey/experiment/lineage/LineagePerfTest.java index e007ba9a5e8..f7781b9f39b 100644 --- a/experiment/src/org/labkey/experiment/lineage/LineagePerfTest.java +++ b/experiment/src/org/labkey/experiment/lineage/LineagePerfTest.java @@ -101,7 +101,7 @@ private int generateNewData(List> data, List> data, List> data, List childNames = new ArrayList<>(); @@ -190,7 +190,7 @@ private int generateDerived(List> data, List generateJunk(CPUTimer generateRowsTimer, CPU List> insertedDatas = dcTable.getUpdateService().insertRows(_user, _container, data, errors, null, null); if (errors.hasErrors()) throw errors; - LOG.info("inserted " + data.size() + " data"); + LOG.info("inserted {} data", data.size()); insertDataTimer.stop(); - Map firstDataMap = insertedDatas.get(0); + Map firstDataMap = insertedDatas.getFirst(); Long firstDataRowId = asLong(firstDataMap.get("rowId")); assertNotNull(firstDataRowId); firstData = ExperimentService.get().getExpData(firstDataRowId); @@ -378,7 +378,7 @@ public Pair generateJunk(CPUTimer generateRowsTimer, CPU ssTable.getUpdateService().insertRows(_user, _container, samples, errors, null, null); if (errors.hasErrors()) throw errors; - LOG.info("inserted " + samples.size() + " samples"); + LOG.info("inserted {} samples", samples.size()); insertSamplesTimer.stop(); tx.commit(); @@ -431,7 +431,7 @@ private void lineageQueries(String prefix, CPUTimer lineageQuery, CPUTimer linea for (int i = 0; i < 10; i++) { - LOG.info("iteration: " + i); + LOG.info("iteration: {}", i); // insert a new sample LOG.info(" creating sample"); diff --git a/experiment/src/org/labkey/experiment/pipeline/ExpGeneratorHelper.java b/experiment/src/org/labkey/experiment/pipeline/ExpGeneratorHelper.java index b6400e73e43..159b45fd85e 100644 --- a/experiment/src/org/labkey/experiment/pipeline/ExpGeneratorHelper.java +++ b/experiment/src/org/labkey/experiment/pipeline/ExpGeneratorHelper.java @@ -309,8 +309,8 @@ static private ExpRunImpl _insertRun(Container container, Map datas = new LinkedHashMap<>(); // Set up the inputs to the whole run - ExpProtocolApplication inputApp = run.addProtocolApplication(user, expActions.get(0), protocol.getApplicationType(), "Run inputs"); - ExpProtocolApplication outputApp = run.addProtocolApplication(user, expActions.get(expActions.size() - 1), ExpProtocol.ApplicationType.ExperimentRunOutput, "Run outputs"); + ExpProtocolApplication inputApp = run.addProtocolApplication(user, expActions.getFirst(), protocol.getApplicationType(), "Run inputs"); + ExpProtocolApplication outputApp = run.addProtocolApplication(user, expActions.getLast(), ExpProtocol.ApplicationType.ExperimentRunOutput, "Run outputs"); for (Map.Entry runInput : runInputsWithRoles.entrySet()) { URI uri = runInput.getKey(); @@ -589,17 +589,17 @@ static public ExpProtocol ensureProtocol(Container container, User user, Map protocolCache, List protocolSequence, ExpProtocol parentProtocol, String description, Logger log) { - log.debug("Checking " + parentProtocol.getLSID() + " to see if it is a match"); + log.debug("Checking {} to see if it is a match", parentProtocol.getLSID()); List existingSteps = parentProtocol.getSteps(); // Two extra steps in the database, one to mark the run inputs, one to mark the run outputs if (existingSteps.size() != protocolSequence.size() + 2) { - log.debug("Wrong number of steps in existing protocol, expected " + (protocolSequence.size() + 2) + " but was " + existingSteps.size()); + log.debug("Wrong number of steps in existing protocol, expected {} but was {}", protocolSequence.size() + 2, existingSteps.size()); return false; } if (!description.equals(parentProtocol.getName())) { - log.debug("Parent protocol names do not match, expected " + description + " but was " + parentProtocol.getName()); + log.debug("Parent protocol names do not match, expected {} but was {}", description, parentProtocol.getName()); return false; } @@ -609,19 +609,19 @@ static private boolean validateProtocol(Map protocolCache, ExpProtocol childProtocol = step.getChildProtocol(); if (step.getActionSequence() != sequence) { - log.debug("Wrong sequence number, expected " + sequence + " but was " + step.getActionSequence()); + log.debug("Wrong sequence number, expected {} but was {}", sequence, step.getActionSequence()); return false; } if (sequence == 1) { if (childProtocol.getApplicationType() != ExpProtocol.ApplicationType.ExperimentRun) { - log.debug("Expected first step to be of type ExperimentRun, but was " + childProtocol.getApplicationType()); + log.debug("Expected first step to be of type ExperimentRun, but was {}", childProtocol.getApplicationType()); return false; } if (childProtocol.getRowId() != parentProtocol.getRowId()) { - log.debug("Expected first step to match up with parent protocol rowId " + parentProtocol.getRowId() + " but was " + childProtocol.getRowId()); + log.debug("Expected first step to match up with parent protocol rowId {} but was {}", parentProtocol.getRowId(), childProtocol.getRowId()); return false; } } @@ -629,19 +629,19 @@ else if (sequence == protocolSequence.size() + 2) { if (childProtocol.getApplicationType() != ExpProtocol.ApplicationType.ExperimentRunOutput) { - log.debug("Expected last step to be of type ExperimentRunOutput, but was " + childProtocol.getApplicationType()); + log.debug("Expected last step to be of type ExperimentRunOutput, but was {}", childProtocol.getApplicationType()); return false; } Lsid outputLsid = createOutputProtocolLSID(new Lsid(parentProtocol.getLSID())); String outputName = outputLsid.getObjectId(); if (!childProtocol.getName().equals(outputName)) { - log.debug("Expected last step to have name " + outputName + " but was " + childProtocol.getName()); + log.debug("Expected last step to have name {} but was {}", outputName, childProtocol.getName()); return false; } if (!childProtocol.getLSID().equals(outputLsid.toString())) { - log.debug("Expected last step to have LSID " + outputLsid + " but was " + childProtocol.getLSID()); + log.debug("Expected last step to have LSID {} but was {}", outputLsid, childProtocol.getLSID()); return false; } } @@ -650,17 +650,17 @@ else if (sequence == protocolSequence.size() + 2) String protocolName = protocolSequence.get(sequence - 2); if (childProtocol.getApplicationType() != ExpProtocol.ApplicationType.ProtocolApplication) { - log.debug("Expected step with sequence " + sequence + " to be of type ProtocolApplication, but was " + childProtocol.getApplicationType()); + log.debug("Expected step with sequence {} to be of type ProtocolApplication, but was {}", sequence, childProtocol.getApplicationType()); return false; } if (!childProtocol.getName().equals(protocolName)) { - log.debug("Expected step with sequence " + sequence + " to have name " + protocolName + " but was " + childProtocol.getName()); + log.debug("Expected step with sequence {} to have name {} but was {}", sequence, protocolName, childProtocol.getName()); return false; } if (childProtocol.getRowId() != protocolCache.get(protocolName).getRowId()) { - log.debug("Expected step with sequence " + sequence + " to match up with protocol rowId " + protocolCache.get(protocolName).getRowId() + " but was " + childProtocol.getRowId()); + log.debug("Expected step with sequence {} to match up with protocol rowId {} but was {}", sequence, protocolCache.get(protocolName).getRowId(), childProtocol.getRowId()); return false; } } diff --git a/experiment/src/org/labkey/experiment/pipeline/ExperimentPipelineJob.java b/experiment/src/org/labkey/experiment/pipeline/ExperimentPipelineJob.java index 1571ec5d2f2..3fe0df078db 100644 --- a/experiment/src/org/labkey/experiment/pipeline/ExperimentPipelineJob.java +++ b/experiment/src/org/labkey/experiment/pipeline/ExperimentPipelineJob.java @@ -100,7 +100,7 @@ private XarSource getXarSource() } catch (IOException e) { - _log.error("Failed to get log file for " + _xarFile, e); + _log.error("Failed to get log file for {}", _xarFile, e); } } return _xarSource; @@ -144,7 +144,7 @@ public static boolean loadExperiment(PipelineJob job, XarSource source, boolean List runs = ExperimentService.get().importXar(source, job, deleteExistingRuns); if (!runs.isEmpty()) { - source.setExperimentRunRowId(runs.get(0).getRowId()); + source.setExperimentRunRowId(runs.getFirst().getRowId()); } job.getLogger().info(""); diff --git a/experiment/src/org/labkey/experiment/pipeline/MoveRunsPipelineJob.java b/experiment/src/org/labkey/experiment/pipeline/MoveRunsPipelineJob.java index 52833951636..219316073fb 100644 --- a/experiment/src/org/labkey/experiment/pipeline/MoveRunsPipelineJob.java +++ b/experiment/src/org/labkey/experiment/pipeline/MoveRunsPipelineJob.java @@ -64,11 +64,11 @@ public MoveRunsPipelineJob(ViewBackgroundInfo info, Container sourceContainer, l ExpRun run = ExperimentService.get().getExpRun(runId); if (run == null) { - getLogger().info("No run found for RowId " + runId); + getLogger().info("No run found for RowId {}", runId); } else { - getLogger().info(run.getName() + " (RowId = " + runId + ")"); + getLogger().info("{} (RowId = {})", run.getName(), runId); } } } diff --git a/experiment/src/org/labkey/experiment/pipeline/MoveRunsTask.java b/experiment/src/org/labkey/experiment/pipeline/MoveRunsTask.java index 12d9ec8b57f..faeb9efa85f 100644 --- a/experiment/src/org/labkey/experiment/pipeline/MoveRunsTask.java +++ b/experiment/src/org/labkey/experiment/pipeline/MoveRunsTask.java @@ -135,7 +135,7 @@ private void moveRun(MoveRunsPipelineJob job, ExpRunImpl experimentRun) throws E if (newData != null) { ExperimentDataHandler handler = newData.findDataHandler(); - handler.runMoved(newData, experimentRun.getContainer(), job.getContainer(), experimentRun.getLSID(), runLSIDs.get(0), job.getUser(), dataFiles.get(dataURL)); + handler.runMoved(newData, experimentRun.getContainer(), job.getContainer(), experimentRun.getLSID(), runLSIDs.getFirst(), job.getUser(), dataFiles.get(dataURL)); } } transaction.commit(); diff --git a/experiment/src/org/labkey/experiment/pipeline/SampleReloadTask.java b/experiment/src/org/labkey/experiment/pipeline/SampleReloadTask.java index eec9c9e2a45..ed6d1f2acef 100644 --- a/experiment/src/org/labkey/experiment/pipeline/SampleReloadTask.java +++ b/experiment/src/org/labkey/experiment/pipeline/SampleReloadTask.java @@ -75,15 +75,15 @@ public RecordedActionSet run() // guaranteed to only have a single file assert support.getInputFiles().size() == 1; - FileLike dataFile = support.getInputFiles().get(0); + FileLike dataFile = support.getInputFiles().getFirst(); Logger log = job.getLogger(); - log.info("Loading " + dataFile.getName()); + log.info("Loading {}", dataFile.getName()); if (params.containsKey(INSERT_OPTION)) { String insertOption = params.get(INSERT_OPTION); - log.info("data insert option set as : " + insertOption); + log.info("data insert option set as : {}", insertOption); if (QueryUpdateService.InsertOption.MERGE.name().equalsIgnoreCase(insertOption)) _insertOption = QueryUpdateService.InsertOption.MERGE; @@ -93,7 +93,7 @@ else if (QueryUpdateService.InsertOption.UPDATE.name().equalsIgnoreCase(insertOp if (params.containsKey(AUDIT_OPTION)) { String auditLevel = params.get(AUDIT_OPTION); - log.info("data audit behavior set as : " + auditLevel); + log.info("data audit behavior set as : {}", auditLevel); if ("detailed".equalsIgnoreCase(auditLevel)) _auditBehavior = DETAILED; @@ -103,7 +103,7 @@ else if ("summary".equalsIgnoreCase(auditLevel)) if (params.containsKey(ALTERNATE_KEY_LOOKUP_OPTION)) _alternateKeyLookup = Boolean.parseBoolean(params.get(ALTERNATE_KEY_LOOKUP_OPTION)); - log.info("import by alternate key option set as : " + _alternateKeyLookup); + log.info("import by alternate key option set as : {}", _alternateKeyLookup); if (params.containsKey(SAMPLE_NAME_KEY) && params.containsKey(SAMPLE_ID_KEY)) { @@ -119,10 +119,10 @@ else if ("summary".equalsIgnoreCase(auditLevel)) sampleName = params.get(SAMPLE_NAME_KEY); sampleType = SampleTypeService.get().getSampleType(job.getContainer(), sampleName, true); if (sampleType != null) - log.info("Sample Type matching the 'name' capture group was resolved : " + sampleName); + log.info("Sample Type matching the 'name' capture group was resolved : {}", sampleName); else { - log.error("Sample Type matching the 'name' capture group was not resolved : " + sampleName); + log.error("Sample Type matching the 'name' capture group was not resolved : {}", sampleName); return new RecordedActionSet(); } } @@ -131,10 +131,10 @@ else if (params.containsKey(SAMPLE_ID_KEY)) int id = Integer.parseInt(params.get(SAMPLE_ID_KEY)); sampleType = SampleTypeService.get().getSampleType(id); if (sampleType != null) - log.info("Sample Type matching the 'id' capture group was resolved : " + sampleType.getName()); + log.info("Sample Type matching the 'id' capture group was resolved : {}", sampleType.getName()); else { - log.error("Sample Type matching the 'id' capture group was not resolved : " + params.get(SAMPLE_ID_KEY)); + log.error("Sample Type matching the 'id' capture group was not resolved : {}", params.get(SAMPLE_ID_KEY)); return new RecordedActionSet(); } } @@ -149,7 +149,7 @@ else if (params.containsKey(SAMPLE_ID_KEY)) // still no resolution to an existing sample type, create a new one inferring the schema from the data file if (sampleType == null) { - log.info("Creating a new Sample Type of name : " + sampleName); + log.info("Creating a new Sample Type of name : {}", sampleName); try (DataLoader loader = DataLoader.get().createLoader(dataFile, null, true, job.getContainer(), null)) { @@ -183,7 +183,7 @@ else if (params.containsKey(SAMPLE_ID_KEY)) } } importSamples(job.getContainer(), job.getUser(), sampleType, dataFile, log); - job.getLogger().info("Done importing " + job.getDescription()); + job.getLogger().info("Done importing {}", job.getDescription()); return new RecordedActionSet(); } @@ -226,7 +226,7 @@ private void importSamples(Container c, User user, @Nullable ExpSampleType sampl context.setAllowImportLookupByAlternateKey(_alternateKeyLookup); int count = qus.loadRows(user, c, loader, context, null); - log.info("Imported a total of " + count + " rows into : " + sampleType.getName()); + log.info("Imported a total of {} rows into : {}", count, sampleType.getName()); if (context.getErrors().hasErrors()) { for (ValidationException error : context.getErrors().getRowErrors()) @@ -242,10 +242,10 @@ private void importSamples(Container c, User user, @Nullable ExpSampleType sampl } } else - log.warn("Could not get the update service for sample : " + sampleType.getName()); + log.warn("Could not get the update service for sample : {}", sampleType.getName()); } else - log.warn("Could not get the tableInfo for sample : " + sampleType.getName()); + log.warn("Could not get the tableInfo for sample : {}", sampleType.getName()); } else log.warn("Could not get the samples schema"); diff --git a/experiment/src/org/labkey/experiment/pipeline/XarGeneratorSource.java b/experiment/src/org/labkey/experiment/pipeline/XarGeneratorSource.java index be9b9cf220e..93090eef105 100644 --- a/experiment/src/org/labkey/experiment/pipeline/XarGeneratorSource.java +++ b/experiment/src/org/labkey/experiment/pipeline/XarGeneratorSource.java @@ -20,8 +20,6 @@ import org.labkey.api.pipeline.PipelineJob; import org.labkey.vfs.FileLike; -import java.nio.file.Path; - /* * User: jeckels * Date: Jul 30, 2008 diff --git a/experiment/src/org/labkey/experiment/pipeline/XarTestPipelineJob.java b/experiment/src/org/labkey/experiment/pipeline/XarTestPipelineJob.java index 3505a179f0f..1c3e032dd8f 100644 --- a/experiment/src/org/labkey/experiment/pipeline/XarTestPipelineJob.java +++ b/experiment/src/org/labkey/experiment/pipeline/XarTestPipelineJob.java @@ -492,7 +492,7 @@ private void doXarTest(String jobName, List inputFiles, List if (duration > timeout) { //NOTE: it's possible a job could time out on a busy cluster. rather than fail, continue in case there's a second engine to test - _log.warn("timed out waiting for job: " + job1.getDescription()); + _log.warn("timed out waiting for job: {}", job1.getDescription()); break; } } @@ -503,7 +503,7 @@ private void doXarTest(String jobName, List inputFiles, List List runs = ExperimentService.get().getExpRunsForJobId(sf.getRowId()); Assert.assertEquals("Wrong run number", 1, runs.size()); - ExpRun run = runs.get(0); + ExpRun run = runs.getFirst(); List inputs = run.getInputDatas(INPUT_ROLE, null); Assert.assertEquals("Wrong input number", inputFiles.size(), inputs.size()); diff --git a/experiment/src/org/labkey/experiment/samples/AbstractExpFolderImporter.java b/experiment/src/org/labkey/experiment/samples/AbstractExpFolderImporter.java index eb5163bec66..672c52c1422 100644 --- a/experiment/src/org/labkey/experiment/samples/AbstractExpFolderImporter.java +++ b/experiment/src/org/labkey/experiment/samples/AbstractExpFolderImporter.java @@ -97,7 +97,7 @@ public void process(@Nullable PipelineJob job, FolderImportContext ctx, VirtualF if (null != job) job.setStatus("IMPORT " + getDescription()); - log.info("Starting " + getDescription()); + log.info("Starting {}", getDescription()); for (String file: xarDir.list()) { @@ -155,7 +155,7 @@ else if (file.equalsIgnoreCase(XAR_RUNS_NAME) || file.equalsIgnoreCase(XAR_RUNS_ log.error("Failed to initialize runs XAR source", e); throw(e); } - log.info("Importing the runs XAR file: " + runsXarFile.getName()); + log.info("Importing the runs XAR file: {}", runsXarFile.getName()); XarReader runsReader = new FolderXarImporterFactory.FolderExportXarReader(runsXarSource, job, ctx); runsReader.setStrictValidateExistingSampleType(xarCtx.isStrictValidateExistingSampleType()); runsReader.parseAndLoad(false, ctx.getAuditBehaviorType()); @@ -183,7 +183,7 @@ else if (file.equalsIgnoreCase(XAR_RUNS_NAME) || file.equalsIgnoreCase(XAR_RUNS_ log.info("No types XAR file to process."); transaction.commit(); - log.info("Finished " + getDescription()); + log.info("Finished {}", getDescription()); } } } @@ -280,7 +280,7 @@ protected void importTsvData(FolderImportContext ctx, XarContext xarContext, Str TableInfo tinfo = userSchema.getTable(tableName); if (tinfo != null) { - log.info("Importing data file: " + dataFileName); + log.info("Importing data file: {}", dataFileName); try (InputStream is = dir.getInputStream(dataFileName)) { if (null != is) @@ -314,7 +314,7 @@ protected void importTsvData(FolderImportContext ctx, XarContext xarContext, Str DataIterator data = new ResolveLsidAndFileLinkDataIterator(loader.getDataIterator(context), xarContext, expObject instanceof ExpDataClass ? "DataClass" : ExpMaterial.DEFAULT_CPAS_TYPE, tinfo); int count = qus.loadRows(ctx.getUser(), ctx.getContainer(), data, context, null); - log.info("Imported a total of " + count + " rows into : " + tableName); + log.info("Imported a total of {} rows into : {}", count, tableName); if (context.getErrors().hasErrors()) { @@ -323,24 +323,24 @@ protected void importTsvData(FolderImportContext ctx, XarContext xarContext, Str } } else - log.error("Unable to import TSV data for " + dataFileName + ". Could not find query update service for table " + tableName + "."); + log.error("Unable to import TSV data for {}. Could not find query update service for table {}.", dataFileName, tableName); } } } else { - log.error("Failed to find table '" + schemaName + "." + tableName + "' to import data file: " + dataFileName); + log.error("Failed to find table '{}.{}' to import data file: {}", schemaName, tableName, dataFileName); } } else if (fileRequired && !excludeTable(tableName)) { - log.error("Unable to import TSV data for table " + tableName + ". File not found."); + log.error("Unable to import TSV data for table {}. File not found.", tableName); } } } else { - log.error("Could not find " + schemaName + " schema."); + log.error("Could not find {} schema.", schemaName); } } diff --git a/experiment/src/org/labkey/experiment/samples/AbstractExpFolderWriter.java b/experiment/src/org/labkey/experiment/samples/AbstractExpFolderWriter.java index 1962f24ffc6..652837b6300 100644 --- a/experiment/src/org/labkey/experiment/samples/AbstractExpFolderWriter.java +++ b/experiment/src/org/labkey/experiment/samples/AbstractExpFolderWriter.java @@ -179,7 +179,7 @@ else if (col.getFk() instanceof MultiValuedForeignKey) // NOTE: This assumes that we are exporting the junction table and lookup target tables. Is that ok? // NOTE: This needs to happen after the Alias column is handled since it has a MultiValuedForeignKey. // CONSIDER: Alternate strategy would be to export the lookup target values? - ctx.getLogger().info("Skipping multi-value column: " + col.getName()); + ctx.getLogger().info("Skipping multi-value column: {}", col.getName()); } else if (ExpMaterialTable.Column.AliquotedFromLSID.name().equalsIgnoreCase(col.getName())) { diff --git a/experiment/src/org/labkey/experiment/xar/CompressedXarSource.java b/experiment/src/org/labkey/experiment/xar/CompressedXarSource.java index 2c8ed5d4738..af1e0302339 100644 --- a/experiment/src/org/labkey/experiment/xar/CompressedXarSource.java +++ b/experiment/src/org/labkey/experiment/xar/CompressedXarSource.java @@ -27,11 +27,8 @@ import org.labkey.vfs.FileLike; import java.io.IOException; -import java.nio.file.Files; -import java.nio.file.Path; import java.util.List; import java.util.Map; -import java.util.stream.Collectors; /** * User: jeckels @@ -102,7 +99,7 @@ else if (xarFiles.size() > 1) } else { - _xmlFile = xarFiles.get(0); + _xmlFile = xarFiles.getFirst(); } } diff --git a/experiment/src/org/labkey/experiment/xar/FileResolver.java b/experiment/src/org/labkey/experiment/xar/FileResolver.java index bd5af06f6c3..9e03ae261d1 100644 --- a/experiment/src/org/labkey/experiment/xar/FileResolver.java +++ b/experiment/src/org/labkey/experiment/xar/FileResolver.java @@ -104,7 +104,7 @@ private String getFileNameVariation(final String filter) throws XarFormatExcepti throw new XarFormatException("Insufficient files found for FileNameVariation filter " + filter); } _fileNameVariationsToAdvance.add(filter); - return nameVariations.get(0); + return nameVariations.getFirst(); } private String getFileName(final String filter) throws XarFormatException @@ -120,7 +120,7 @@ private String getFileName(final String filter) throws XarFormatException { throw new XarFormatException("Insufficient files found for FileName filter " + filter); } - File f = files.get(0); + File f = files.getFirst(); _fileNamesToAdvance.add(filter); try { @@ -135,7 +135,7 @@ private String getFileName(final String filter) throws XarFormatException private int getCommonCharStartCount(List names) { int commonStart = 0; - String firstName = names.get(0); + String firstName = names.getFirst(); while (commonStart < firstName.length()) { char firstNameChar = firstName.charAt(commonStart); @@ -155,7 +155,7 @@ private int getCommonCharStartCount(List names) private int getCommonCharEndCount(List names) { int commonEnd = 0; - String firstName = names.get(0); + String firstName = names.getFirst(); while (commonEnd < firstName.length()) { char firstNameChar = firstName.charAt(firstName.length() - commonEnd - 1); @@ -354,7 +354,7 @@ private String getFileBaseName(final String originalFilter) throws XarFormatExce throw new XarFormatException("Insufficient files found for FileBaseName filter " + originalFilter); } _fileBaseNamesToAdvance.add(originalFilter); - return names.get(0); + return names.getFirst(); } public void advance() @@ -371,7 +371,7 @@ private void advanceMap(Map> map, Set dataTableRow = selResp.getRows().get(0); + Map dataTableRow = selResp.getRows().getFirst(); return dataTableRow.get("LSID").toString(); } @@ -137,7 +137,7 @@ protected String getResultRowLsid(Connection cn) throws IOException, CommandExce SelectRowsCommand cmd = new SelectRowsCommand("assay.General.Provenance Assay", "Data"); cmd.setColumns(List.of("LSID")); SelectRowsResponse response = cmd.execute(cn, getProjectName()); - Map resultRow = response.getRows().get(0); + Map resultRow = response.getRows().getFirst(); return resultRow.get("LSID").toString(); } } diff --git a/experiment/test/src/org/labkey/test/tests/experiment/VocabularyViewSupportTest.java b/experiment/test/src/org/labkey/test/tests/experiment/VocabularyViewSupportTest.java index df09bbadf80..b8715c37c3a 100644 --- a/experiment/test/src/org/labkey/test/tests/experiment/VocabularyViewSupportTest.java +++ b/experiment/test/src/org/labkey/test/tests/experiment/VocabularyViewSupportTest.java @@ -259,8 +259,8 @@ public void testAssayViewSupport() throws IOException, CommandException .findElement(runsTable.findCell(0, "Properties"))); assertEquals("Embedded properties table", expectedProperties, propertiesTable.getTableData()); - assertEquals("Run does not contain " + propNameLab + " vocabulary property.", propValueLab, runsTable.getColumnDataAsText(domainProperty + "/" + propNameLab).get(0)); - assertEquals("Run does not contain " + propNameLab + " vocabulary property.", labLocation, runsTable.getColumnDataAsText(domainProperty + "/" + propNameLocation).get(0)); + assertEquals("Run does not contain " + propNameLab + " vocabulary property.", propValueLab, runsTable.getColumnDataAsText(domainProperty + "/" + propNameLab).getFirst()); + assertEquals("Run does not contain " + propNameLab + " vocabulary property.", labLocation, runsTable.getColumnDataAsText(domainProperty + "/" + propNameLocation).getFirst()); } private DataRegionTable createListForVocabPropertyLookup(String listName) throws IOException, CommandException diff --git a/filecontent/src/org/labkey/filecontent/FileContentController.java b/filecontent/src/org/labkey/filecontent/FileContentController.java index 34c7a8c4223..77bf9bbc72f 100644 --- a/filecontent/src/org/labkey/filecontent/FileContentController.java +++ b/filecontent/src/org/labkey/filecontent/FileContentController.java @@ -61,7 +61,6 @@ import org.labkey.api.files.FileContentService; import org.labkey.api.files.FileUrls; import org.labkey.api.files.FilesAdminOptions; -import org.labkey.api.files.MissingRootDirectoryException; import org.labkey.api.files.UnsetRootDirectoryException; import org.labkey.api.files.view.FilesWebPart; import org.labkey.api.message.settings.AbstractConfigTypeProvider; @@ -538,7 +537,7 @@ public ModelAndView getView(FileContentForm form, boolean reshow, BindException } catch (Exception e) { - logger.error("Could not get canonical path for " + strPath + ", using path as entered.", e); + logger.error("Could not get canonical path for {}, using path as entered.", strPath, e); } } form.setRootPath(strPath); @@ -783,7 +782,7 @@ protected Set> getChildren(NodeForm form, BindException erro children.add(node); } } - catch (MissingRootDirectoryException | UnsetRootDirectoryException ignored) {} + catch (UnsetRootDirectoryException ignored) {} // include all child containers for (Container child : c.getChildren()) diff --git a/filecontent/src/org/labkey/filecontent/FileContentModule.java b/filecontent/src/org/labkey/filecontent/FileContentModule.java index c8aaf60b736..dfd531ae0fa 100644 --- a/filecontent/src/org/labkey/filecontent/FileContentModule.java +++ b/filecontent/src/org/labkey/filecontent/FileContentModule.java @@ -133,7 +133,7 @@ public Collection getSummary(Container c) } if (fileCount == 1) { - result.add("One file: " + fileNames.get(0)); + result.add("One file: " + fileNames.getFirst()); } if (fileCount > 1) { @@ -141,7 +141,7 @@ public Collection getSummary(Container c) } if (directoryCount == 1) { - result.add("One directory in the file system, which may contain additional files: " + directoryNames.get(0)); + result.add("One directory in the file system, which may contain additional files: " + directoryNames.getFirst()); } if (directoryCount > 1) { diff --git a/filecontent/src/org/labkey/filecontent/FileContentServiceImpl.java b/filecontent/src/org/labkey/filecontent/FileContentServiceImpl.java index fc286a966e2..64fd31bbfe6 100644 --- a/filecontent/src/org/labkey/filecontent/FileContentServiceImpl.java +++ b/filecontent/src/org/labkey/filecontent/FileContentServiceImpl.java @@ -665,11 +665,11 @@ public void setIsUseDefaultRoot(Container c, boolean useDefaultRoot) { if (FileUtil.mkdirs(root)) { - _log.info("Created site-wide file root " + root); + _log.info("Created site-wide file root {}", root); } else { - _log.error("Failed when attempting to create site-wide file root " + root); + _log.error("Failed when attempting to create site-wide file root {}", root); } } } @@ -766,7 +766,7 @@ public void unregisterDirectory(Container c, String name) } @Override - public @Nullable AttachmentDirectory getMappedAttachmentDirectory(Container c, boolean createDir) throws UnsetRootDirectoryException, MissingRootDirectoryException + public @Nullable AttachmentDirectory getMappedAttachmentDirectory(Container c, boolean createDir) throws UnsetRootDirectoryException { return getMappedAttachmentDirectory(c, ContentType.files, createDir); } @@ -786,7 +786,7 @@ else if (null == getMappedDirectory(c, false)) } catch (IOException e) { - _log.error("Cannot get mapped directory for " + c.getPath(), e); + _log.error("Cannot get mapped directory for {}", c.getPath(), e); return null; } } @@ -1161,7 +1161,7 @@ public void moveFileRoot(File prev, File dest, @Nullable User user, @Nullable Co { try { - _log.info("moving " + prev.getPath() + " to " + dest.getPath()); + _log.info("moving {} to {}", prev.getPath(), dest.getPath()); boolean doRename = true; // Our best bet for perf is to do a rename, which doesn't require creating an actual copy. @@ -1406,7 +1406,7 @@ public Set> getNodes(boolean isShowOverridesOnly, @Nullable } } } - catch (IOException | UnsetRootDirectoryException ignored) {} + catch (UnsetRootDirectoryException ignored) {} return children; } @@ -1472,7 +1472,7 @@ else if (assayFilesPath != null && URIUtil.isDescendant(assayFilesPath.toUri(), } catch (InvalidPathException | URISyntaxException e) { - _log.error("Invalid WebDav URL from: " + path, e); + _log.error("Invalid WebDav URL from: {}", path, e); } return null; @@ -1583,14 +1583,7 @@ private void ensureFileDataUnsynchronized(@NotNull ExpDataTable table) { if (fileset.getName().equals(rootName)) { - try - { - file = fileset.getFileSystemDirectory(); - } - catch (MissingRootDirectoryException e) - { - _log.error("Unable to list files for fileset: " + rootName, e); - } + file = fileset.getFileSystemDirectory(); break; } } @@ -1613,12 +1606,12 @@ private void ensureFileDataUnsynchronized(@NotNull ExpDataTable table) rows.add(new CaseInsensitiveHashMap<>(Collections.singletonMap("DataFileUrl", path.toUri().toString()))); }); } - _log.debug("Inserting " + rows.size() + " rows into " + table); + _log.debug("Inserting {} rows into {}", rows.size(), table); qus.insertRows(user, container, rows, errors, null, null); } catch (Exception e) { - _log.error("Error listing content of directory: " + file.getAbsolutePath(), e); + _log.error("Error listing content of directory: {}", file.getAbsolutePath(), e); } } } @@ -1720,7 +1713,7 @@ public File getMoveTargetFile(String absoluteFilePath, @NotNull Container source File file = new File(absoluteFilePath); if (!NetworkDrive.exists(file)) { - _log.warn("File '" + absoluteFilePath + "' not found and cannot be moved"); + _log.warn("File '{}' not found and cannot be moved", absoluteFilePath); return null; } @@ -1731,7 +1724,7 @@ public File getMoveTargetFile(String absoluteFilePath, @NotNull Container source String sourceRootPath = sourceFileRoot.getAbsolutePath(); if (!absoluteFilePath.startsWith(sourceRootPath)) { - _log.warn("File '" + absoluteFilePath + "' not currently located in source folder '" + sourceRootPath + "'. Not moving."); + _log.warn("File '{}' not currently located in source folder '{}'. Not moving.", absoluteFilePath, sourceRootPath); return null; } File targetFileRoot = getFileRoot(targetContainer); diff --git a/filecontent/src/org/labkey/filecontent/FileImporter.java b/filecontent/src/org/labkey/filecontent/FileImporter.java index ac9576b7d4d..a5aa7242745 100644 --- a/filecontent/src/org/labkey/filecontent/FileImporter.java +++ b/filecontent/src/org/labkey/filecontent/FileImporter.java @@ -89,11 +89,11 @@ private boolean processRoot(FolderImportContext ctx, VirtualFile root, FileConte FileUtil.createDirectories(rootFile); if (Files.isDirectory(rootFile)) { - ctx.getLogger().info("Starting to copy files to @" + fileType.name()); + ctx.getLogger().info("Starting to copy files to @{}", fileType.name()); AtomicInteger count = new AtomicInteger(); copy(filesVF, rootFile, ctx.getLogger(), System.currentTimeMillis() + LOG_INTERVAL, count); - ctx.getLogger().info("Copied " + count.get() + " files to @" + fileType.name()); + ctx.getLogger().info("Copied {} files to @{}", count.get(), fileType.name()); return true; } @@ -111,7 +111,7 @@ private void copy(VirtualFile virtualFile, Path realPath, Logger log, long nextL { if (nextLogTime < System.currentTimeMillis()) { - log.info(count.get() + " files copied, now copying " + child); + log.info("{} files copied, now copying {}", count.get(), child); nextLogTime = System.currentTimeMillis() + LOG_INTERVAL; } diff --git a/filecontent/src/org/labkey/filecontent/FilePropertiesDomainKind.java b/filecontent/src/org/labkey/filecontent/FilePropertiesDomainKind.java index 1ba6a86b513..3c61bf8678d 100644 --- a/filecontent/src/org/labkey/filecontent/FilePropertiesDomainKind.java +++ b/filecontent/src/org/labkey/filecontent/FilePropertiesDomainKind.java @@ -16,7 +16,6 @@ package org.labkey.filecontent; import org.jetbrains.annotations.NotNull; -import org.labkey.api.collections.CaseInsensitiveHashSet; import org.labkey.api.compliance.ComplianceService; import org.labkey.api.data.SQLFragment; import org.labkey.api.exp.Lsid; diff --git a/filecontent/src/org/labkey/filecontent/FileQueryUpdateService.java b/filecontent/src/org/labkey/filecontent/FileQueryUpdateService.java index 47af36698ce..e6f3c31ac60 100644 --- a/filecontent/src/org/labkey/filecontent/FileQueryUpdateService.java +++ b/filecontent/src/org/labkey/filecontent/FileQueryUpdateService.java @@ -20,8 +20,8 @@ import org.apache.commons.lang3.StringUtils; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; -import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; +import org.jetbrains.annotations.NotNull; import org.labkey.api.action.ApiQueryResponse; import org.labkey.api.data.ColumnInfo; import org.labkey.api.data.CompareType; @@ -169,7 +169,7 @@ protected Map getRow(User user, Container container, Map rowMap = rows[0]; if (rows.length > 1) - _log.error("More than one row returned for data file: " + filter); + _log.error("More than one row returned for data file: {}", filter); if (rowMap != null) { @@ -393,7 +393,7 @@ private Map _setRow(final User user, final Container container, if (data == null) { - _log.debug("Auto-creating ExpData object, as one was not already available. DataFileURL : " + dataFileUrl); + _log.debug("Auto-creating ExpData object, as one was not already available. DataFileURL : {}", dataFileUrl); data = ExperimentService.get().createData(container, UPLOADED_FILE); data.setName(resource.getName()); @@ -460,7 +460,7 @@ else if (!(StringUtils.isEmpty(dataFileUrl) || "null".equals(dataFileUrl))) } @Override - protected Map updateRow(User user, Container container, Map row, Map oldRow, @Nullable Map configParameters) throws ValidationException + protected Map updateRow(User user, Container container, Map row, @NotNull Map oldRow, @Nullable Map configParameters) throws ValidationException { return _setRow(user, container, row, true); } @@ -569,7 +569,7 @@ private WebdavResource getWebdavUrlFromAbsoluteFilePath(@NotNull String absolute targetResource = resource; else { - _log.error("More than one webdav resource found for file: " + absoluteFilePath); + _log.error("More than one webdav resource found for file: {}", absoluteFilePath); return null; } } diff --git a/filecontent/src/org/labkey/filecontent/FileWebdavProvider.java b/filecontent/src/org/labkey/filecontent/FileWebdavProvider.java index 04fca3cfb83..ac4d7177f73 100644 --- a/filecontent/src/org/labkey/filecontent/FileWebdavProvider.java +++ b/filecontent/src/org/labkey/filecontent/FileWebdavProvider.java @@ -24,7 +24,6 @@ import org.labkey.api.data.Container; import org.labkey.api.data.ContainerManager; import org.labkey.api.files.FileContentService; -import org.labkey.api.files.MissingRootDirectoryException; import org.labkey.api.security.SecurableResource; import org.labkey.api.security.User; import org.labkey.api.settings.AppProps; @@ -111,18 +110,12 @@ public WebdavResource resolve(@NotNull WebdavResource parent, @NotNull String na if (FileContentService.FILES_LINK.equalsIgnoreCase(name)) { - try - { - AttachmentDirectory dir = service.getMappedAttachmentDirectory(c, false); - if (dir != null) - { - return new _FilesResource(parent, Path.toPathPart(name), dir.getFileSystemDirectory(), c); - } - } - catch (MissingRootDirectoryException e) + AttachmentDirectory dir = service.getMappedAttachmentDirectory(c, false); + if (dir != null) { - // Don't complain here, just hide the @files subfolder + return new _FilesResource(parent, Path.toPathPart(name), dir.getFileSystemDirectory(), c); } + } return null; @@ -207,12 +200,6 @@ public long getCreated() return Long.MIN_VALUE; } - @Override - public long getLastModified() - { - return Long.MIN_VALUE; - } - @Override @NotNull public Collection listNames() diff --git a/filecontent/src/org/labkey/filecontent/message/FileContentDigestProvider.java b/filecontent/src/org/labkey/filecontent/message/FileContentDigestProvider.java index b7a3a118baf..542cf51eaf8 100644 --- a/filecontent/src/org/labkey/filecontent/message/FileContentDigestProvider.java +++ b/filecontent/src/org/labkey/filecontent/message/FileContentDigestProvider.java @@ -191,7 +191,7 @@ private void sendDigest(Container c, Date min, Date max) catch (Exception e) { // Don't fail the request because of this error - _log.warn("Unable to send email for the file notification: " + e.getMessage()); + _log.warn("Unable to send email for the file notification: {}", e.getMessage()); } } diff --git a/issues/src/org/labkey/issue/actions/ChangeSummary.java b/issues/src/org/labkey/issue/actions/ChangeSummary.java index 0ab82c7c0cd..6b605370a44 100644 --- a/issues/src/org/labkey/issue/actions/ChangeSummary.java +++ b/issues/src/org/labkey/issue/actions/ChangeSummary.java @@ -418,11 +418,11 @@ public void sendUpdateEmail(Container container, User user, String comment, Acti } catch (ConfigurationException | AddressException e) { - _log.error("error sending update email to " + to, e); + _log.error("error sending update email to {}", to, e); } catch (Exception e) { - _log.error("error sending update email to " + to, e); + _log.error("error sending update email to {}", to, e); ExceptionUtil.logExceptionToMothership(null, e); } } diff --git a/issues/src/org/labkey/issue/actions/InsertIssueDefAction.java b/issues/src/org/labkey/issue/actions/InsertIssueDefAction.java index 5f708306588..4eeba69be50 100644 --- a/issues/src/org/labkey/issue/actions/InsertIssueDefAction.java +++ b/issues/src/org/labkey/issue/actions/InsertIssueDefAction.java @@ -113,7 +113,7 @@ public ActionURL getSuccessURL(QueryUpdateForm form) { if (_results.size() == 1) { - String name = String.valueOf(_results.get(0).get("name")); + String name = String.valueOf(_results.getFirst().get("name")); IssueListDef issueListDef = IssueManager.getIssueListDef(getContainer(), name); if (issueListDef != null) diff --git a/issues/src/org/labkey/issue/model/IssueManager.java b/issues/src/org/labkey/issue/model/IssueManager.java index d598e313e94..4254960b59d 100644 --- a/issues/src/org/labkey/issue/model/IssueManager.java +++ b/issues/src/org/labkey/issue/model/IssueManager.java @@ -385,8 +385,8 @@ public static void saveIssue(User user, Container container, IssueObject issue) if (!batchErrors.hasErrors()) { assert results.size() == 1; - issue.setIssueId(asInteger(results.get(0).get("IssueId"))); - issue.setIssueDefId(asInteger(results.get(0).get("issueDefId"))); + issue.setIssueId(asInteger(results.getFirst().get("IssueId"))); + issue.setIssueDefId(asInteger(results.getFirst().get("issueDefId"))); } else throw batchErrors; @@ -1504,7 +1504,7 @@ public void testIssues() TestContext context = TestContext.get(); User user = context.getUser(); - assertTrue("login before running this test", null != user); + assertNotNull("login before running this test", user); assertFalse("login before running this test", user.isGuest()); Container c = JunitUtil.getTestContainer(); @@ -1540,7 +1540,7 @@ public void testIssues() assertEquals(IssueObject.statusOPEN, issue.getStatus()); assertEquals(1, issue.getCommentObjects().size()); String comment = (issue.getCommentObjects().iterator().next()).getHtmlComment().toString(); - assertTrue("new issue".equals(comment)); + assertEquals("new issue", comment); } // diff --git a/issues/src/org/labkey/issue/model/IssueObject.java b/issues/src/org/labkey/issue/model/IssueObject.java index 800c86554f7..2d38589e383 100644 --- a/issues/src/org/labkey/issue/model/IssueObject.java +++ b/issues/src/org/labkey/issue/model/IssueObject.java @@ -431,7 +431,7 @@ public CommentObject getLastComment() if (null == _comments || _comments.isEmpty()) return null; - return _comments.get(_comments.size()-1); + return _comments.getLast(); } public boolean setComments(List comments) @@ -656,7 +656,7 @@ public void setProperty(String name, Object value) public IssueEvent getMostRecentEvent(User user) { ArrayList arr = getOrderedEventArray(user); - return !arr.isEmpty() ? arr.get(0) : null; + return !arr.isEmpty() ? arr.getFirst() : null; } public ArrayList getOrderedEventArray(User user) diff --git a/issues/src/org/labkey/issue/model/IssuesListDefServiceImpl.java b/issues/src/org/labkey/issue/model/IssuesListDefServiceImpl.java index 739acf89d65..da347857083 100644 --- a/issues/src/org/labkey/issue/model/IssuesListDefServiceImpl.java +++ b/issues/src/org/labkey/issue/model/IssuesListDefServiceImpl.java @@ -241,11 +241,11 @@ public Domain getDomainFromIssueDefId(int issueDefId, Container container, User { Domain domain = issueListDef.getDomain(user, forUpdate); if (domain == null) - LOG.warn("Unable to find the domain for issue list definition id: " + issueDefId + " and container: " + container); + LOG.warn("Unable to find the domain for issue list definition id: {} and container: {}", issueDefId, container); return domain; } else - LOG.warn("Unable to find the issue list definition for id: " + issueDefId + " and container: " + container); + LOG.warn("Unable to find the issue list definition for id: {} and container: {}", issueDefId, container); return null; } diff --git a/issues/src/org/labkey/issue/query/IssueDefDomainKind.java b/issues/src/org/labkey/issue/query/IssueDefDomainKind.java index c13921cea88..423b63a5e97 100644 --- a/issues/src/org/labkey/issue/query/IssueDefDomainKind.java +++ b/issues/src/org/labkey/issue/query/IssueDefDomainKind.java @@ -17,7 +17,6 @@ import com.google.common.collect.Sets; import org.jetbrains.annotations.NotNull; -import org.labkey.api.collections.CaseInsensitiveHashSet; import org.labkey.api.data.Container; import org.labkey.api.data.JdbcType; import org.labkey.api.data.PropertyStorageSpec; @@ -120,12 +119,6 @@ public String getKindName() return RESERVED_NAMES; } - @Override - public Set getPropertyIndices(Domain domain) - { - return INDEXES; - } - @Override public Set getRequiredProperties() { @@ -223,11 +216,5 @@ public DefaultValueType[] getDefaultValueOptions(Domain domain) { return DefaultValueType.values(); } - - @Override - public DefaultValueType getDefaultDefaultType(Domain domain) - { - return DefaultValueType.FIXED_EDITABLE; - } } diff --git a/issues/src/org/labkey/issue/query/IssuesTable.java b/issues/src/org/labkey/issue/query/IssuesTable.java index f9f526319d1..e2a0549ecd0 100644 --- a/issues/src/org/labkey/issue/query/IssuesTable.java +++ b/issues/src/org/labkey/issue/query/IssuesTable.java @@ -336,7 +336,7 @@ else if (colName.equalsIgnoreCase("PullRequests")) { ((BaseColumnInfo)col).setFk(new IssuesPdLookupForeignKey(schema, pd)); TableInfo target = col.getFk().getLookupTableInfo(); - if (null != target && target.getPkColumnNames().size() == 1 && Strings.CI.equals(target.getTitleColumn(),target.getPkColumnNames().get(0))) + if (null != target && target.getPkColumnNames().size() == 1 && Strings.CI.equals(target.getTitleColumn(),target.getPkColumnNames().getFirst())) { ((BaseColumnInfo)col).setDisplayColumnFactory(ColumnInfo.NOLOOKUP_FACTORY); } diff --git a/issues/src/org/labkey/issue/view/RelatedIssuesView.java b/issues/src/org/labkey/issue/view/RelatedIssuesView.java index 8c303155771..5c7e8406147 100644 --- a/issues/src/org/labkey/issue/view/RelatedIssuesView.java +++ b/issues/src/org/labkey/issue/view/RelatedIssuesView.java @@ -43,7 +43,6 @@ import org.springframework.validation.BindException; import java.util.Collection; -import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; diff --git a/list/src/org/labkey/list/model/FolderListImporter.java b/list/src/org/labkey/list/model/FolderListImporter.java index 878e51137f7..ab430ff8df5 100644 --- a/list/src/org/labkey/list/model/FolderListImporter.java +++ b/list/src/org/labkey/list/model/FolderListImporter.java @@ -55,7 +55,7 @@ public void process(PipelineJob job, FolderImportContext ctx, VirtualFile root) if (null != job) job.setStatus("IMPORT " + getDescription()); - ctx.getLogger().info("Loading " + getDescription()); + ctx.getLogger().info("Loading {}", getDescription()); ListImporter importer = new ListImporter(); Logger log = ctx.getLogger(); @@ -65,7 +65,7 @@ public void process(PipelineJob job, FolderImportContext ctx, VirtualFile root) for (String error : errors) log.error(error); - ctx.getLogger().info("Done importing " + getDescription()); + ctx.getLogger().info("Done importing {}", getDescription()); } } diff --git a/list/src/org/labkey/list/model/IntegerListDomainKind.java b/list/src/org/labkey/list/model/IntegerListDomainKind.java index 890ae45c5af..9975d7e70bf 100644 --- a/list/src/org/labkey/list/model/IntegerListDomainKind.java +++ b/list/src/org/labkey/list/model/IntegerListDomainKind.java @@ -19,7 +19,6 @@ import org.labkey.api.data.PropertyStorageSpec; import org.labkey.api.exp.list.ListDefinition; -import java.util.Arrays; import java.util.Collection; import java.util.List; diff --git a/list/src/org/labkey/list/model/ListImporter.java b/list/src/org/labkey/list/model/ListImporter.java index 32a625c893a..fd250ecbd48 100644 --- a/list/src/org/labkey/list/model/ListImporter.java +++ b/list/src/org/labkey/list/model/ListImporter.java @@ -110,7 +110,7 @@ public boolean processSingle(VirtualFile sourceDir, String fileName, Container c { def = lists.get(dataKey.second); if (def == null) - log.error("Could not locate a list with name:" + dataKey.second); + log.error("Could not locate a list with name:{}", dataKey.second); } else if (dataKey.first.equals(ListReloadTask.LIST_ID_KEY)) { @@ -118,7 +118,7 @@ else if (dataKey.first.equals(ListReloadTask.LIST_ID_KEY)) { def = ListService.get().getList(c, Integer.parseInt(dataKey.second)); if (def == null) - log.error("Could not locate a list with Id:" + dataKey.second); + log.error("Could not locate a list with Id:{}", dataKey.second); } catch (NumberFormatException e) { @@ -161,7 +161,7 @@ private boolean processSingle(VirtualFile sourceDir, ListDefinition def, String if (!hasXmlMetadata && !resolveDomainChanges(c, user, loader, def, log, errors)) { - log.warn("Skipping filed-based import of '" + def.getName() + "' due to domain resolution errors."); + log.warn("Skipping filed-based import of '{}' due to domain resolution errors.", def.getName()); return false; } @@ -215,15 +215,15 @@ private boolean processSingle(VirtualFile sourceDir, ListDefinition def, String if (!batchErrors.hasErrors()) { if (0 < b.getDeleted()) - log.info("Deleted " + b.getDeleted() + " row(s) from list: " + def.getName()); + log.info("Deleted {} row(s) from list: {}", b.getDeleted(), def.getName()); if (0 < b.getMerged()) - log.info("Merged " + b.getMerged() + " row(s) into list: " + def.getName()); + log.info("Merged {} row(s) into list: {}", b.getMerged(), def.getName()); if (0 < b.getUpdated()) - log.info("Updated " + b.getUpdated() + " row(s) into list: " + def.getName()); + log.info("Updated {} row(s) into list: {}", b.getUpdated(), def.getName()); if (0 < b.getInserted()) - log.info("Inserted " + b.getInserted() + " row(s) into list: " + def.getName()); + log.info("Inserted {} row(s) into list: {}", b.getInserted(), def.getName()); if (0>=b.getDeleted() && 0>=b.getMerged() && 0>=b.getUpdated() && 0>=b.getInserted()) - log.info("No rows changed from list: " + def.getName()); + log.info("No rows changed from list: {}", def.getName()); } } } @@ -237,7 +237,7 @@ private boolean processSingle(VirtualFile sourceDir, ListDefinition def, String if (qus != null && !_importContext.useMerge()) { int deletedRows = ti.getUpdateService().truncateRows(user, c, null, null); - log.info("Deleted " + deletedRows + " row(s) from list: " + def.getName() + " for reload preparation"); + log.info("Deleted {} row(s) from list: {} for reload preparation", deletedRows, def.getName()); } } @@ -339,7 +339,7 @@ else if (_importContext.isTriggeredReload()) } else { - log.info("Could not retrieve file stream for dir: " + sourceDir.getLocation() + " and file: " + fileName); + log.info("Could not retrieve file stream for dir: {} and file: {}", sourceDir.getLocation(), fileName); } } return true; @@ -393,17 +393,17 @@ public void processMany(VirtualFile listsDir, Container c, User user, List 0) { - log.warn(StringUtilsLabKey.pluralize(failedLists, "list") + " failed to import"); + log.warn("{} failed to import", StringUtilsLabKey.pluralize(failedLists, "list")); } if (!fileNameMap.isEmpty()) { log.info("The following files were not imported because the server could not find a list with matching name: "); for (String s : fileNameMap.values()) { - log.info("\tSkipped " + s); + log.info("\tSkipped {}", s); } } } @@ -583,7 +583,7 @@ private void createDefinedLists(VirtualFile listsDir, XmlObject listXml, Contain try { - log.info("Truncating list: " + def.getName()); + log.info("Truncating list: {}", def.getName()); def.delete(user); replaced = true; } @@ -598,7 +598,7 @@ private void createDefinedLists(VirtualFile listsDir, XmlObject listXml, Contain { try { - log.info("Recreating list: " + name); + log.info("Recreating list: {}", name); boolean success = createNewList(c, user, name, preferredListIds, tableType, listSettingsMap.get(name), validatorImporters, errors, log); assert success; } @@ -682,7 +682,7 @@ private boolean resolveDomainChanges(Container c, User user, DataLoader loader, boolean isDirty = false; if (domain != null) { - log.info("resolving domain of list: " + listDef.getName()); + log.info("resolving domain of list: {}", listDef.getName()); Map currentColumns = listDef.getDomain().getProperties().stream().collect(Collectors.toMap(DomainProperty::getName, e -> e)); // Do a pass over the loader's columns @@ -696,7 +696,7 @@ private boolean resolveDomainChanges(Container c, User user, DataLoader loader, PropertyDescriptor pd = new PropertyDescriptor(domain.getTypeURI() + "." + loaderCol.name, type, loaderCol.name, c); domain.addPropertyOfPropertyDescriptor(pd); isDirty = true; - log.info("\tAdded column " + loaderCol.name + " of type \"" + type.getXarName() + "\" to " + listDef.getName()); + log.info("\tAdded column {} of type \"{}\" to {}", loaderCol.name, type.getXarName(), listDef.getName()); } currentColumns.remove(loaderCol.name); } @@ -706,14 +706,14 @@ private boolean resolveDomainChanges(Container c, User user, DataLoader loader, { if (listDef.getKeyName().equals(columnName) && !listDef.getKeyType().getLabel().equals("Auto-Increment Integer")) { - log.warn("Failed to import data for '" + listDef.getName() + "'. Primary Key '" + columnName + "' not present in file."); + log.warn("Failed to import data for '{}'. Primary Key '{}' not present in file.", listDef.getName(), columnName); return false; } else if (!listDef.getKeyName().equals(columnName) && !currentColumns.get(columnName).isRequired()) { currentColumns.get(columnName).delete(); isDirty = true; - log.info("\tDeleted column " + columnName); + log.info("\tDeleted column {}", columnName); } } diff --git a/list/src/org/labkey/list/model/ListManager.java b/list/src/org/labkey/list/model/ListManager.java index f65e898963c..36f779060fc 100644 --- a/list/src/org/labkey/list/model/ListManager.java +++ b/list/src/org/labkey/list/model/ListManager.java @@ -552,7 +552,7 @@ public void enumerateDocuments(SearchService.TaskIndexingQueue queue, @Nullable } catch (Exception ex) { - LOG.error("Error indexing list '" + list.getName() + "' in container '" + q.getContainer().getPath() + "'.", ex); + LOG.error("Error indexing list '{}' in container '{}'.", list.getName(), q.getContainer().getPath(), ex); } } } @@ -579,7 +579,7 @@ public void indexList(final ListDef def) Container c = def.lookupContainer(); if (!ContainerManager.exists(c)) { - LOG.info("List container has been deleted or is being deleted; not indexing list \"" + def.getName() + "\""); + LOG.info("List container has been deleted or is being deleted; not indexing list \"{}\"", def.getName()); } else { @@ -593,7 +593,7 @@ public void indexList(final ListDef def) Container c = def.lookupContainer(); if (!ContainerManager.exists(c)) { - LOG.info("List container has been deleted or is being deleted; not indexing list \"" + def.getName() + "\""); + LOG.info("List container has been deleted or is being deleted; not indexing list \"{}\"", def.getName()); } else { @@ -763,7 +763,7 @@ public void setLastIndexed(long ms, long modified) r.getMutableProperties().put(SearchService.PROPERTY.navtrail.toString(), nav); queue.addResource(r); - LOG.debug("List \"" + list + "\": Queued indexing of item with PK = " + pk); + LOG.debug("List \"{}\": Queued indexing of item with PK = {}", list, pk); }); } } @@ -824,7 +824,7 @@ private void indexAttachments(@NotNull final SearchService.TaskIndexingQueue que attachmentRes.getMutableProperties().put(SearchService.PROPERTY.navtrail.toString(), nav); queue.addResource(attachmentRes); - LOG.debug("List \"" + list + "\": Queued indexing of attachment \"" + documentName + "\" for item with PK = " + map.get(list.getKeyName())); + LOG.debug("List \"{}\": Queued indexing of attachment \"{}\" for item with PK = {}", list, documentName, map.get(list.getKeyName())); }); }); }); @@ -927,7 +927,7 @@ public void setLastIndexed(long ms, long modified) }; queue.addResource(r); - LOG.debug("List \"" + list + "\": Queued indexing of entire list document"); + LOG.debug("List \"{}\": Queued indexing of entire list document", list); } } } @@ -1122,7 +1122,7 @@ private void setLastIndexed(ListDefinition list, long ms) list = ListDefinitionImpl.of(getList(list.getContainer(), list.getListId())); long modified = list.getModified().getTime(); String warning = ms < modified ? ". WARNING: LastIndexed is less than Modified! " + ms + " vs. " + modified : ""; - LOG.debug("List \"" + list + "\": Set LastIndexed for entire list document" + warning); + LOG.debug("List \"{}\": Set LastIndexed for entire list document{}", list, warning); } @@ -1143,7 +1143,7 @@ private void setItemLastIndexed(ListDefinition list, Object pk, TableInfo ti, lo new SqlExecutor(sti.getSchema()).execute(sqlf); } String warning = ms < modified ? ". WARNING: LastIndexed is less than Modified! " + ms + " vs. " + modified : ""; - LOG.debug("List \"" + list + "\": Set LastIndexed for item with PK = " + pk + warning); + LOG.debug("List \"{}\": Set LastIndexed for item with PK = {}{}", list, pk, warning); } } @@ -1172,7 +1172,7 @@ private void clearLastIndexed(DbScope scope, String listSchemaName, ListDef list Domain domain = list.getDomain(); if (null != domain && null != domain.getStorageTableName()) { - LOG.info("List " + listDef.getContainerPath() + " - " + listDef.getName() + ": Set to index each item, so clearing last indexed"); + LOG.info("List {} - {}: Set to index each item, so clearing last indexed", listDef.getContainerPath(), listDef.getName()); clearLastIndexed(scope, listSchemaName + "." + domain.getStorageTableName()); } } diff --git a/list/src/org/labkey/list/model/ListTable.java b/list/src/org/labkey/list/model/ListTable.java index 46b8a23ce59..8688a9e4913 100644 --- a/list/src/org/labkey/list/model/ListTable.java +++ b/list/src/org/labkey/list/model/ListTable.java @@ -163,7 +163,7 @@ public ListTable(ListQuerySchema schema, @NotNull ListDefinition listDef, @NotNu } else { - LOG.warn(_list.getName() + "." + _list.getKeyName() + " (primary key) " + "has not yet been provisioned."); + LOG.warn("{}.{} (primary key) has not yet been provisioned.", _list.getName(), _list.getKeyName()); } colKey.setKeyField(true); diff --git a/list/src/org/labkey/list/model/ListWriter.java b/list/src/org/labkey/list/model/ListWriter.java index d24af3d794c..29515196266 100644 --- a/list/src/org/labkey/list/model/ListWriter.java +++ b/list/src/org/labkey/list/model/ListWriter.java @@ -177,7 +177,7 @@ private void writeLists(List> listsToExport, Virtua .collect(Collectors.toCollection(LinkedList::new)); // Sort the data rows by PK, #11261 - Sort sort = ti.getPkColumns().size() != 1 ? null : new Sort(ti.getPkColumns().get(0).getFieldKey()); + Sort sort = ti.getPkColumns().size() != 1 ? null : new Sort(ti.getPkColumns().getFirst().getFieldKey()); // NOTE: TSVGridWriter generates and closes Results @@ -290,7 +290,7 @@ private void writeAttachments(TableInfo ti, ListDefinition def, Container c, Vir uniquifiers.put(attachmentColumn.getName(), new FileNameUniquifier()); List selectColumns = new ArrayList<>(attachmentColumns); - selectColumns.add(0, ti.getColumn("EntityId")); + selectColumns.addFirst(ti.getColumn("EntityId")); try (ResultSet rs = QueryService.get().getSelectBuilder(ti).columns(selectColumns).select(null, false)) { diff --git a/list/src/org/labkey/list/pipeline/ListReloadJob.java b/list/src/org/labkey/list/pipeline/ListReloadJob.java index 1250c4644cc..0ca8c466e14 100644 --- a/list/src/org/labkey/list/pipeline/ListReloadJob.java +++ b/list/src/org/labkey/list/pipeline/ListReloadJob.java @@ -71,7 +71,7 @@ public void run() String fileName = _dataFile.getName(); - getLogger().info("Loading " + fileName); + getLogger().info("Loading {}", fileName); List errors = new LinkedList<>(); try @@ -89,6 +89,6 @@ public void run() for (String error : errors) getLogger().error(error); - getLogger().info("Done importing " + getDescription()); + getLogger().info("Done importing {}", getDescription()); } } diff --git a/list/src/org/labkey/list/pipeline/ListReloadTask.java b/list/src/org/labkey/list/pipeline/ListReloadTask.java index d395170a651..e90ffce47c2 100644 --- a/list/src/org/labkey/list/pipeline/ListReloadTask.java +++ b/list/src/org/labkey/list/pipeline/ListReloadTask.java @@ -60,7 +60,7 @@ public RecordedActionSet run() // guaranteed to only have a single file assert support.getInputFiles().size() == 1; - FileLike dataFile = support.getInputFiles().get(0); + FileLike dataFile = support.getInputFiles().getFirst(); PipeRoot pr = PipelineService.get().findPipelineRoot(job.getContainer()); if (pr != null) diff --git a/mothership/src/org/labkey/mothership/ExceptionStackTrace.java b/mothership/src/org/labkey/mothership/ExceptionStackTrace.java index 4744985c79d..92b08837049 100644 --- a/mothership/src/org/labkey/mothership/ExceptionStackTrace.java +++ b/mothership/src/org/labkey/mothership/ExceptionStackTrace.java @@ -463,7 +463,7 @@ public void testMessageHashCombining() "\tat org.apache.commons.beanutils.BeanUtils.populate(BeanUtils.java:298)"); assertEquals(stackTrace1.getStackTraceHash(), stackTrace2.getStackTraceHash()); - assertFalse(stackTrace1.getStackTraceHash().equals(stackTrace3.getStackTraceHash())); + assertNotEquals(stackTrace1.getStackTraceHash(), stackTrace3.getStackTraceHash()); } @Test diff --git a/mothership/src/org/labkey/mothership/MothershipController.java b/mothership/src/org/labkey/mothership/MothershipController.java index 724f554bd5b..59c0127107b 100644 --- a/mothership/src/org/labkey/mothership/MothershipController.java +++ b/mothership/src/org/labkey/mothership/MothershipController.java @@ -559,7 +559,7 @@ public Object execute(ExceptionForm form, BindException errors) ServerInstallation installation = new ServerInstallation(); if (form.getServerGUID() == null) { - logger.warn("No serverGUID specified in exception report from " + serverIP + ", making one up so we don't lose the exception"); + logger.warn("No serverGUID specified in exception report from {}, making one up so we don't lose the exception", serverIP); installation.setServerInstallationGUID(GUID.makeGUID()); } else diff --git a/mothership/src/org/labkey/mothership/MothershipManager.java b/mothership/src/org/labkey/mothership/MothershipManager.java index 91b2b0efc12..8b5bcf91999 100644 --- a/mothership/src/org/labkey/mothership/MothershipManager.java +++ b/mothership/src/org/labkey/mothership/MothershipManager.java @@ -396,7 +396,7 @@ private String getBestJson(String currentValue, String newValue, String serverSe ObjectMapper mapper = JsonUtil.createDefaultMapper(); try { - log.debug("Merging JSON. Old is " + currentValue.length() + " characters, new is " + newValue.length()); + log.debug("Merging JSON. Old is {} characters, new is {}", currentValue.length(), newValue.length()); Map currentMap = mapper.readValue(currentValue, Map.class); Map newMap = mapper.readValue(newValue, Map.class); merge(currentMap, newMap); @@ -429,7 +429,7 @@ private void merge(Map currentMap, Map newMap) private void logJsonError(String newValue, String serverSessionGUID, Exception e) { - log.error("Malformed json in mothership report from server session '"+serverSessionGUID + "': " + newValue, e); + log.error("Malformed json in mothership report from server session '{}': {}", serverSessionGUID, newValue, e); } public TableInfo getTableInfoExceptionStackTrace() diff --git a/mothership/src/org/labkey/mothership/query/MothershipSchema.java b/mothership/src/org/labkey/mothership/query/MothershipSchema.java index 560f4f729cc..b4fc75f7476 100644 --- a/mothership/src/org/labkey/mothership/query/MothershipSchema.java +++ b/mothership/src/org/labkey/mothership/query/MothershipSchema.java @@ -398,7 +398,7 @@ public FilteredTable createExceptionReportTableWithStack(Conta { FilteredTable result = createExceptionReportTable(cf); List defaultCols = new ArrayList<>(result.getDefaultVisibleColumns()); - defaultCols.removeIf(fieldKey -> fieldKey.getParts().get(0).equals("ServerSessionId")); + defaultCols.removeIf(fieldKey -> fieldKey.getParts().getFirst().equals("ServerSessionId")); defaultCols.add(0, FieldKey.fromParts("ExceptionStackTraceId")); defaultCols.add(1, FieldKey.fromParts("ExceptionStackTraceId", "StackTrace")); result.setDefaultVisibleColumns(defaultCols); diff --git a/mothership/src/org/labkey/mothership/statuscake/StatusCakeMaintenanceTask.java b/mothership/src/org/labkey/mothership/statuscake/StatusCakeMaintenanceTask.java index ec3ecb989f3..2fd17a02499 100644 --- a/mothership/src/org/labkey/mothership/statuscake/StatusCakeMaintenanceTask.java +++ b/mothership/src/org/labkey/mothership/statuscake/StatusCakeMaintenanceTask.java @@ -118,7 +118,7 @@ public void run(Logger log) Container targetContainer = ContainerManager.getForPath(containerPath); if (targetContainer == null) { - log.error("No such target container " + containerPath + " found for StatusCake maintenance task"); + log.error("No such target container {} found for StatusCake maintenance task", containerPath); return; } @@ -180,7 +180,7 @@ public void run(Logger log) Server s = new Server(id, name, tags); List history = getUptime(s, client, since, statusCakeAPIKey, log); - log.info("Fetched " + s + " with " + history.size() + " history rows"); + log.info("Fetched {} with {} history rows", s, history.size()); serverRows.add(s.toMap()); historyRows.addAll(history.stream().map(History::toMap).toList()); @@ -229,7 +229,7 @@ public void run(Logger log) private void insertRows(Logger log, TableInfo table, User user, Container targetContainer, List> rows) throws DuplicateKeyException, BatchValidationException, QueryUpdateServiceException, SQLException { - log.info("Populating " + table.getName() + " with " + rows.size() + " rows"); + log.info("Populating {} with {} rows", table.getName(), rows.size()); BatchValidationException errors = new BatchValidationException(); // Skip detailed audit via BulkLoad table.getUpdateService().insertRows(user, targetContainer, rows, errors, Map.of(BulkLoad, true), null); @@ -285,7 +285,7 @@ private List getUptime(Server server, if (result.size() == limit) { - History h = result.get(result.size() - 1); + History h = result.getLast(); result.addAll(getUptime(server, client, h.end(), statusCakeAPIKey ,log)); } diff --git a/mothership/test/src/org/labkey/test/tests/mothership/MothershipTest.java b/mothership/test/src/org/labkey/test/tests/mothership/MothershipTest.java index 7bd1317d08b..90e0ccfdb93 100644 --- a/mothership/test/src/org/labkey/test/tests/mothership/MothershipTest.java +++ b/mothership/test/src/org/labkey/test/tests/mothership/MothershipTest.java @@ -20,7 +20,6 @@ import org.hamcrest.CoreMatchers; import org.junit.Before; import org.junit.BeforeClass; -import org.junit.Ignore; import org.junit.Test; import org.junit.experimental.categories.Category; import org.labkey.test.BaseWebDriverTest; @@ -29,7 +28,6 @@ import org.labkey.test.SortDirection; import org.labkey.test.TestTimeoutException; import org.labkey.test.categories.Daily; -import org.labkey.test.pages.issues.InsertPage; import org.labkey.test.pages.mothership.ClientExceptionPage; import org.labkey.test.pages.mothership.ShowExceptionsPage; import org.labkey.test.pages.mothership.ShowExceptionsPage.ExceptionSummaryDataRegion; diff --git a/mothership/test/src/org/labkey/test/util/mothership/MothershipHelper.java b/mothership/test/src/org/labkey/test/util/mothership/MothershipHelper.java index 88650a972a5..71d15d47716 100644 --- a/mothership/test/src/org/labkey/test/util/mothership/MothershipHelper.java +++ b/mothership/test/src/org/labkey/test/util/mothership/MothershipHelper.java @@ -145,7 +145,7 @@ private Map getServerInstallationInfo(String hostName) throws IO throw new NotFoundException(String.format("Unable to find server installation [%s]. Found: %s", hostName, hostNames)); } } - return response.getRows().get(0); + return response.getRows().getFirst(); } public int getLatestStackTraceId() @@ -168,7 +168,7 @@ public int getLatestStackTraceId() SelectRowsResponse response = command.execute(connection, MOTHERSHIP_PROJECT); if (response.getRows().isEmpty()) return null; - return response.getRows().get(0); + return response.getRows().getFirst(); } catch (IOException|CommandException e) { @@ -215,7 +215,7 @@ public int getReportCount(int stackTraceId) try { SelectRowsResponse response = command.execute(connection, MOTHERSHIP_PROJECT); - return (int) response.getRows().get(0).get("instances"); + return (int) response.getRows().getFirst().get("instances"); } catch (IOException|CommandException e) { @@ -319,7 +319,7 @@ public void disableExceptionReporting() public int triggerException(TestActions.ExceptionActions action) { - return triggerExceptions(action).get(0); + return triggerExceptions(action).getFirst(); } public List triggerExceptions(TestActions.ExceptionActions... actions) diff --git a/pipeline/src/org/labkey/pipeline/AbstractPipelineStartup.java b/pipeline/src/org/labkey/pipeline/AbstractPipelineStartup.java index ab1af3cbc65..85c4faafaa3 100644 --- a/pipeline/src/org/labkey/pipeline/AbstractPipelineStartup.java +++ b/pipeline/src/org/labkey/pipeline/AbstractPipelineStartup.java @@ -81,7 +81,7 @@ else if ("experiment".equalsIgnoreCase(module.getName())) if (pipelineModule != null) { modules.remove(pipelineModule); - modules.add(0, pipelineModule); + modules.addFirst(pipelineModule); } if (experimentModule != null) { diff --git a/pipeline/src/org/labkey/pipeline/PipelineCommandTestCase.java b/pipeline/src/org/labkey/pipeline/PipelineCommandTestCase.java index fd5fb564eab..7b5af78395d 100644 --- a/pipeline/src/org/labkey/pipeline/PipelineCommandTestCase.java +++ b/pipeline/src/org/labkey/pipeline/PipelineCommandTestCase.java @@ -25,7 +25,6 @@ import org.labkey.api.pipeline.cmd.ListToCommandArgs; import org.labkey.api.pipeline.cmd.RequiredSwitch; import org.labkey.api.pipeline.cmd.SubstitutionWithSwitch; -import org.labkey.api.pipeline.cmd.TaskToCommandArgs; import org.labkey.api.pipeline.cmd.UnixCompactSwitchFormat; import org.labkey.api.pipeline.cmd.UnixNewSwitchFormat; import org.labkey.api.pipeline.cmd.UnixSwitchFormat; @@ -116,7 +115,7 @@ public void testPipelineIndividualCmds() throws Exception test2.setSwitchName("b"); List args2 = test2.toArgs("yes"); assertEquals("Unexpected length for BooleanToSwitch args", 1, args2.size()); - assertEquals("Unexpected arg for ValueWithSwitch", "-b", args2.get(0)); + assertEquals("Unexpected arg for ValueWithSwitch", "-b", args2.getFirst()); args2 = test2.toArgs("no"); assertEquals("Unexpected length for BooleanToSwitch args", 0, args2.size()); args2 = test2.toArgs("somethingNotYesOrNo"); @@ -133,18 +132,18 @@ public void testPipelineIndividualCmds() throws Exception test3.setSwitchName("c"); List args3 = test3.toArgsInner(null, null, null); assertEquals("Unexpected length for RequiredSwitch args", 1, args3.size()); - assertEquals("Unexpected arg for RequiredSwitch", "--c", args3.get(0)); + assertEquals("Unexpected arg for RequiredSwitch", "--c", args3.getFirst()); test3.setValue("Test3"); args3 = test3.toArgsInner(null, null, null); assertEquals("Unexpected length for RequiredSwitch args", 1, args3.size()); - assertEquals("Unexpected arg for RequiredSwitch", "--c=Test3", args3.get(0)); + assertEquals("Unexpected arg for RequiredSwitch", "--c=Test3", args3.getFirst()); ValueToSwitch test4 = new ValueToSwitch(); test4.setSwitchFormat(new UnixCompactSwitchFormat()); test4.setSwitchName("d"); List args4 = test4.toArgs("anything"); assertEquals("Unexpected length for ValueToSwitch args", 1, args4.size()); - assertEquals("Unexpected arg for ValueToSwitch", "-d", args4.get(0)); + assertEquals("Unexpected arg for ValueToSwitch", "-d", args4.getFirst()); args4 = test4.toArgs(null); assertEquals("Unexpected length for ValueToSwitch args", 0, args4.size()); diff --git a/pipeline/src/org/labkey/pipeline/PipelineDirectoryImpl.java b/pipeline/src/org/labkey/pipeline/PipelineDirectoryImpl.java index 0d739260f04..4bca531fa03 100644 --- a/pipeline/src/org/labkey/pipeline/PipelineDirectoryImpl.java +++ b/pipeline/src/org/labkey/pipeline/PipelineDirectoryImpl.java @@ -16,6 +16,7 @@ package org.labkey.pipeline; import org.apache.logging.log4j.Logger; +import org.jetbrains.annotations.NotNull; import org.labkey.api.pipeline.PipelineAction; import org.labkey.api.pipeline.PipelineDirectory; import org.labkey.api.pipeline.PipelineProvider; @@ -96,19 +97,18 @@ protected void ensureFiles() throws IOException Files.walkFileTree(dir, Collections.emptySet(), 1, new SimpleFileVisitor<>() { @Override - public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) + public @NotNull FileVisitResult visitFile(@NotNull Path file, @NotNull BasicFileAttributes attrs) { _files.put(file.getFileName().toString(), file); return FileVisitResult.CONTINUE; } @Override - public FileVisitResult visitFileFailed(Path file, IOException exc) + public @NotNull FileVisitResult visitFileFailed(@NotNull Path file, @NotNull IOException exc) { // Issue 44843 - be tolerant of not being able to get the full metadata (which we aren't even using) // Don't output a full stack trace since it'll be very verbose - LOG.warn("Failed to visit " + file + " in container " + _root.getContainer().getPath() + - ". Its permissions may prevent retrieving metadata. Error: " + exc); + LOG.warn("Failed to visit {} in container {}. Its permissions may prevent retrieving metadata. Error: {}", file, _root.getContainer().getPath(), exc); _files.put(file.getFileName().toString(), file); return FileVisitResult.CONTINUE; } @@ -136,7 +136,7 @@ public boolean fileExists(Path f) } catch (IOException e) { - LOG.error("Error attempting to determine if File exists." + f, e); + LOG.error("Error attempting to determine if File exists.{}", f, e); return false; } } @@ -237,7 +237,7 @@ public void orderActions() return rc; if (!files1.isEmpty()) { - rc = FileUtil.getFileName(files1.get(0)).compareToIgnoreCase(FileUtil.getFileName(files2.get(0))); + rc = FileUtil.getFileName(files1.getFirst()).compareToIgnoreCase(FileUtil.getFileName(files2.getFirst())); if (rc != 0) return rc; } diff --git a/pipeline/src/org/labkey/pipeline/PipelineModule.java b/pipeline/src/org/labkey/pipeline/PipelineModule.java index 096b3f8fb8e..eda849d4490 100644 --- a/pipeline/src/org/labkey/pipeline/PipelineModule.java +++ b/pipeline/src/org/labkey/pipeline/PipelineModule.java @@ -399,7 +399,7 @@ private void moveJobToError(PipelineStatusFileImpl incompleteFile) } catch (RuntimeSQLException e) { - _log.error("Unable to move job into error - " + incompleteFile.getFilePath(), e); + _log.error("Unable to move job into error - {}", incompleteFile.getFilePath(), e); } } } diff --git a/pipeline/src/org/labkey/pipeline/analysis/CommandTaskImpl.java b/pipeline/src/org/labkey/pipeline/analysis/CommandTaskImpl.java index 35c7772c1cb..864c736bb1b 100644 --- a/pipeline/src/org/labkey/pipeline/analysis/CommandTaskImpl.java +++ b/pipeline/src/org/labkey/pipeline/analysis/CommandTaskImpl.java @@ -284,7 +284,7 @@ public boolean isParticipant(PipelineJob job) throws IOException List converters = getConverters(); assert converters != null && !converters.isEmpty() : "No converters found in " + getId(); - TaskToCommandArgs commandNameConverter = converters.get(0); + TaskToCommandArgs commandNameConverter = converters.getFirst(); CommandTaskImpl task = createTask(job); // Need to set up the work directory so that it can figure out what arguments will be used in the call @@ -539,7 +539,7 @@ else if (inputPaths.length == 1) List originalFiles = getOriginalFiles(key); if (originalFiles.size() == 1) { - replacements.put(DataTransformService.ORIGINAL_SOURCE_PATH, Matcher.quoteReplacement(originalFiles.get(0).replaceAll("\\\\", "/"))); + replacements.put(DataTransformService.ORIGINAL_SOURCE_PATH, Matcher.quoteReplacement(originalFiles.getFirst().replaceAll("\\\\", "/"))); } } @@ -710,7 +710,7 @@ protected boolean runCommand(RecordedAction action, @Nullable String apiKey, @Nu // Just output the command line, if debug mode is set. if (_factory.isPreview()) { - getJob().header(args.get(0) + " output"); + getJob().header(args.getFirst() + " output"); getJob().info(commandLine); return false; diff --git a/pipeline/src/org/labkey/pipeline/analysis/ConvertTaskFactory.java b/pipeline/src/org/labkey/pipeline/analysis/ConvertTaskFactory.java index 78aa5037035..a9fe5f950d2 100644 --- a/pipeline/src/org/labkey/pipeline/analysis/ConvertTaskFactory.java +++ b/pipeline/src/org/labkey/pipeline/analysis/ConvertTaskFactory.java @@ -105,7 +105,7 @@ private FileLike getInputFile(PipelineJob job) { List files = job.getJobSupport(FileAnalysisJobSupport.class).getInputFiles(); assert files != null && files.size() == 1 : "Conversion job must have one file."; - return files.get(0); + return files.getFirst(); } private TaskFactory findCommandFactory(PipelineJob job) @@ -113,20 +113,20 @@ private TaskFactory findCommandFactory(PipelineJob job) // If this job is not actually running a conversion, then no // converter command can be determined. List files = job.getJobSupport(FileAnalysisJobSupport.class).getInputFiles(); - LOG.debug("Checking " + files + " for possible converters"); + LOG.debug("Checking {} for possible converters", files); if (files == null || files.size() != 1) return null; // Otherwise, find the appropriate converter. FileLike fileInput = getInputFile(job); - LOG.debug("Checking " + fileInput + " against up to " + _commands.length + " possible converters"); + LOG.debug("Checking {} against up to {} possible converters", fileInput, _commands.length); for (TaskId tid : _commands) { - LOG.debug("Checking " + fileInput + " against " + tid); + LOG.debug("Checking {} against {}", fileInput, tid); TaskFactory factory = PipelineJobService.get().getTaskFactory(tid); for (FileType ft : factory.getInputTypes()) { - LOG.debug("Checking " + fileInput + " against " + tid + ": " + ft); + LOG.debug("Checking {} against {}: {}", fileInput, tid, ft); try { // If we have a match based on the file type and the factory says that it's a participant based @@ -140,7 +140,7 @@ private TaskFactory findCommandFactory(PipelineJob job) } catch (IOException e) { - LOG.debug("Exception when checking " + fileInput + ", reporting that " + tid + " is not available", e); + LOG.debug("Exception when checking {}, reporting that {} is not available", fileInput, tid, e); // Consider this command out of the running, caller will report an error if there are no other options } } @@ -211,7 +211,7 @@ public boolean isJobComplete(PipelineJob job) if (factory == null) { job.warn("Unexpected missing converter for job. The pipeline configuration may have changed to remove a previously configured converter."); - LOG.warn("Unexpected missing converter for job. The pipeline configuration may have changed to remove a previously configured converter. \n" + job.serializeJob(false)); + LOG.warn("Unexpected missing converter for job. The pipeline configuration may have changed to remove a previously configured converter. \n{}", job.serializeJob(false)); return true; } diff --git a/pipeline/src/org/labkey/pipeline/analysis/FileAnalysisJob.java b/pipeline/src/org/labkey/pipeline/analysis/FileAnalysisJob.java index 5b69c649c47..7f62d18b982 100644 --- a/pipeline/src/org/labkey/pipeline/analysis/FileAnalysisJob.java +++ b/pipeline/src/org/labkey/pipeline/analysis/FileAnalysisJob.java @@ -110,7 +110,7 @@ public FileAnalysisTaskPipeline getTaskPipeline() TaskPipeline tp = super.getTaskPipeline(); if (tp == null) { - LOG.warn("Task pipeline " + _taskPipelineId + " not found."); + LOG.warn("Task pipeline {} not found.", _taskPipelineId); } return (FileAnalysisTaskPipeline) tp; } diff --git a/pipeline/src/org/labkey/pipeline/analysis/FileAnalysisPipelineProvider.java b/pipeline/src/org/labkey/pipeline/analysis/FileAnalysisPipelineProvider.java index d98171d68cc..2b7693a95b0 100644 --- a/pipeline/src/org/labkey/pipeline/analysis/FileAnalysisPipelineProvider.java +++ b/pipeline/src/org/labkey/pipeline/analysis/FileAnalysisPipelineProvider.java @@ -175,7 +175,7 @@ public void preDeleteStatusFile(User user, PipelineStatusFile sf) { if (FileUtil.deleteDir(analysisDir)) { - getLogger().info(String.format("Job '%s' analysis directory no longer referenced by any runs and was moved to .deleted: %s", sf.getInfo(), analysisDir)); + getLogger().info("Job '{}' analysis directory no longer referenced by any runs and was moved to .deleted: {}", sf.getInfo(), analysisDir); // Delete any ExpData remains for (ExpData data : children) @@ -190,7 +190,7 @@ public void preDeleteStatusFile(User user, PipelineStatusFile sf) { if (FileUtil.deleteDir(parent)) { - getLogger().info(String.format("Job '%s' parent analysis directory no longer referenced by any runs and was moved to .deleted: %s", sf.getInfo(), parent)); + getLogger().info("Job '{}' parent analysis directory no longer referenced by any runs and was moved to .deleted: {}", sf.getInfo(), parent); parent = parent.getParentFile(); contents = parent.list(); } @@ -198,7 +198,7 @@ public void preDeleteStatusFile(User user, PipelineStatusFile sf) } else { - getLogger().warn(String.format("Failed to move job '%s' analysis directory to .deleted: %s", sf.getDescription(), analysisDir)); + getLogger().warn("Failed to move job '{}' analysis directory to .deleted: {}", sf.getDescription(), analysisDir); } } } diff --git a/pipeline/src/org/labkey/pipeline/analysis/FileAnalysisTaskPipelineImpl.java b/pipeline/src/org/labkey/pipeline/analysis/FileAnalysisTaskPipelineImpl.java index 180da172b4c..3651c6247cf 100644 --- a/pipeline/src/org/labkey/pipeline/analysis/FileAnalysisTaskPipelineImpl.java +++ b/pipeline/src/org/labkey/pipeline/analysis/FileAnalysisTaskPipelineImpl.java @@ -396,7 +396,7 @@ public static FileAnalysisTaskPipeline create(Module module, Resource pipelineCo } catch (XmlException |IOException e) { - PipelineJobServiceImpl.LOG.error("Error loading task pipeline '" + pipelineConfig + "':\n", e); + PipelineJobServiceImpl.LOG.error("Error loading task pipeline '{}':\n", pipelineConfig, e); return null; } @@ -490,7 +490,7 @@ else if (xobj instanceof TaskType xtask) if (progression.isEmpty()) throw new IllegalArgumentException("Expected at least one task factory in the task pipeline"); - TaskFactory initialTaskFactory = PipelineJobService.get().getTaskFactory(progression.get(0)); + TaskFactory initialTaskFactory = PipelineJobService.get().getTaskFactory(progression.getFirst()); if (initialTaskFactory == null) throw new IllegalArgumentException("Expected at least one task factory in the task pipeline"); diff --git a/pipeline/src/org/labkey/pipeline/api/AbstractPipelineQueue.java b/pipeline/src/org/labkey/pipeline/api/AbstractPipelineQueue.java index ae0470edce2..809e7981b6d 100644 --- a/pipeline/src/org/labkey/pipeline/api/AbstractPipelineQueue.java +++ b/pipeline/src/org/labkey/pipeline/api/AbstractPipelineQueue.java @@ -57,7 +57,7 @@ public void addJob(final PipelineJob job) throws PipelineValidationException throw new PipelineValidationException("User " + user + " does not have access to " + job.getContainer()); } - LOG.debug("PENDING: " + job); + LOG.debug("PENDING: {}", job); // Make sure status file path and Job ID are in sync. Path logFile = job.getLogFilePath(); @@ -69,7 +69,7 @@ public void addJob(final PipelineJob job) throws PipelineValidationException PipelineStatusManager.setStatusFile(job, user, PipelineJob.TaskStatus.waiting, null, true); } - job.getLogger().debug("Resetting Job ID: " + job.getJobGUID()); + job.getLogger().debug("Resetting Job ID: {}", job.getJobGUID()); PipelineStatusManager.resetJobId(job.getContainer(), job.getLogFilePath(), job.getJobGUID()); } @@ -80,7 +80,7 @@ public void addJob(final PipelineJob job) throws PipelineValidationException } else { - LOG.debug("Unable to set status to waiting for job: " + job + ", GUID: " + job.getJobGUID()); + LOG.debug("Unable to set status to waiting for job: {}, GUID: {}", job, job.getJobGUID()); } } diff --git a/pipeline/src/org/labkey/pipeline/api/AbstractWorkDirectory.java b/pipeline/src/org/labkey/pipeline/api/AbstractWorkDirectory.java index 42a3b7df228..067c323d3eb 100644 --- a/pipeline/src/org/labkey/pipeline/api/AbstractWorkDirectory.java +++ b/pipeline/src/org/labkey/pipeline/api/AbstractWorkDirectory.java @@ -160,20 +160,20 @@ public void acceptFilesAsOutputs(Map expectedOutputs, Recorded copiedFiles.addAll(outputFile(taskPath, role, action)); } - _jobLog.debug("Already copied files: " + copiedFiles); + _jobLog.debug("Already copied files: {}", copiedFiles); // Slurp up any other files too List additionalFiles = getDir().getChildren(); if (!additionalFiles.isEmpty()) { - _jobLog.debug("Additional files: " + Arrays.asList(additionalFiles)); + _jobLog.debug("Additional files: {}", Arrays.asList(additionalFiles)); } for (FileLike workFile : remainingFiles) { if (copiedFiles.contains(workFile)) { - _jobLog.debug("Skipping copy of file that was already copied as an expected output: " + workFile); + _jobLog.debug("Skipping copy of file that was already copied as an expected output: {}", workFile); int attempts = 0; boolean deleted = false; // Issue 40138 - large files not deleting immediately, so retry and log @@ -181,7 +181,7 @@ public void acceptFilesAsOutputs(Map expectedOutputs, Recorded { if (attempts > 0) { - _jobLog.debug("Attempted to discard " + workFile + " but it still exists. Try #" + attempts + ", delete attempt reported " + deleted); + _jobLog.debug("Attempted to discard {} but it still exists. Try #{}, delete attempt reported {}", workFile, attempts, deleted); try { Thread.sleep(5000); } catch (InterruptedException ignored) {} } attempts++; @@ -321,7 +321,7 @@ private void copyFile(FileLike source, FileLike target) throws IOException try (WorkDirectory.CopyingResource lock = ensureCopyingLock()) { - _jobLog.info("Copying " + source + " to " + target); + _jobLog.info("Copying {} to {}", source, target); if (source.isDirectory()) { FileUtil.copyDirectory(source.toNioPathForRead(), target.toNioPathForWrite()); @@ -445,13 +445,13 @@ public FileLike outputFile(FileLike fileWork, FileLike fileDest) throws IOExcept // If the destination exists, rename it out of the way while we try to // replace it. Rename within the same directory is always an atomic action. fileReplace = FT_MOVE.newFile(fileDest.getParent(), fileDest.getName()); - _jobLog.info("Moving " + fileDest + " to " + fileReplace); + _jobLog.info("Moving {} to {}", fileDest, fileReplace); if (!fileDest.renameTo(fileReplace)) { throw new IOException("Failed to move file " + fileDest + " to " + fileReplace); } } - _jobLog.info("Moving " + fileWork + " to " + fileDest); + _jobLog.info("Moving {} to {}", fileWork, fileDest); boolean directory = fileWork.isDirectory(); if (fileWork.renameTo(fileDest)) fileWork = null; @@ -496,7 +496,7 @@ public FileLike outputFile(FileLike fileWork, FileLike fileDest) throws IOExcept FileLike fileRemove = fileReplace; fileReplace = null; // Output file is successfully in place. - _jobLog.info("Removing " + fileRemove); + _jobLog.info("Removing {}", fileRemove); fileRemove.delete(); } if (fileWork != null) @@ -533,7 +533,7 @@ else if (!fileWork.delete()) @Override public void discardFile(FileLike fileWork) throws IOException { - _jobLog.debug("discarding file: " + fileWork.getPath()); + _jobLog.debug("discarding file: {}", fileWork.getPath()); ensureDescendant(fileWork); int attempts = 0; // Issue 40138 - large files not deleting immediately, so retry and log @@ -549,7 +549,7 @@ public void discardFile(FileLike fileWork) throws IOException if (fileWork.exists()) { - _jobLog.debug("Attempted to discard " + fileWork + " but it still exists. Try #" + attempts + ", delete attempt reported " + deleted); + _jobLog.debug("Attempted to discard {} but it still exists. Try #{}, delete attempt reported {}", fileWork, attempts, deleted); // Wait five seconds try { Thread.sleep(5000); } catch (InterruptedException ignored) {} } @@ -582,7 +582,7 @@ public void remove(boolean success) throws IOException if (!success && _transferToDirOnFailure != null) { FileLike dest = FileUtil.findUniqueFileName(_dir.getName(), _transferToDirOnFailure); - _jobLog.debug("after failure, moving working directory to: " + dest.getPath()); + _jobLog.debug("after failure, moving working directory to: {}", dest.getPath()); try { @@ -590,8 +590,8 @@ public void remove(boolean success) throws IOException } catch (IOException e) { - _jobLog.error("failed moving working directory from : " + _dir.getPath()); - _jobLog.error("to: " + dest.getPath()); + _jobLog.error("failed moving working directory from : {}", _dir.getPath()); + _jobLog.error("to: {}", dest.getPath()); throw e; } diff --git a/pipeline/src/org/labkey/pipeline/api/JobStatusRetryJob.java b/pipeline/src/org/labkey/pipeline/api/JobStatusRetryJob.java index 94563e6d86e..ef5fc9b8152 100644 --- a/pipeline/src/org/labkey/pipeline/api/JobStatusRetryJob.java +++ b/pipeline/src/org/labkey/pipeline/api/JobStatusRetryJob.java @@ -9,7 +9,6 @@ import org.quartz.JobBuilder; import org.quartz.JobDetail; import org.quartz.JobExecutionContext; -import org.quartz.JobExecutionException; import org.quartz.Scheduler; import org.quartz.SchedulerException; import org.quartz.SimpleScheduleBuilder; @@ -53,7 +52,7 @@ public class JobStatusRetryJob implements org.quartz.Job } @Override - public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException + public void execute(JobExecutionContext jobExecutionContext) { // Attempt the updates to the DB rows again in the hopes that the DB is back online if (!_queuedUpdates.isEmpty()) diff --git a/pipeline/src/org/labkey/pipeline/api/ParamParserImpl.java b/pipeline/src/org/labkey/pipeline/api/ParamParserImpl.java index 8109cb019f7..c5a28c25b37 100644 --- a/pipeline/src/org/labkey/pipeline/api/ParamParserImpl.java +++ b/pipeline/src/org/labkey/pipeline/api/ParamParserImpl.java @@ -381,7 +381,7 @@ public void writeFromMap(Map params, FileLike fileDest) throws I try (BufferedWriter inputWriter = new BufferedWriter(PrintWriters.getPrintWriter(fileDest.openOutputStream()))) { String xml = getXMLFromMap(params); - _log.debug("Writing " + params.size() + " parameters (" + fileDest + "):"); + _log.debug("Writing {} parameters ({}):", params.size(), fileDest); _log.debug(xml); inputWriter.write(xml); } diff --git a/pipeline/src/org/labkey/pipeline/api/PipeRootImpl.java b/pipeline/src/org/labkey/pipeline/api/PipeRootImpl.java index 7c646c11f66..cc9bac7b982 100644 --- a/pipeline/src/org/labkey/pipeline/api/PipeRootImpl.java +++ b/pipeline/src/org/labkey/pipeline/api/PipeRootImpl.java @@ -189,7 +189,7 @@ public URI getUri() { if (_uris.isEmpty()) throw new IllegalStateException("No URI."); - return _uris.get(0); + return _uris.getFirst(); } @Override @@ -198,7 +198,7 @@ public File getRootPath() { if (getRootPaths().isEmpty()) throw new RuntimeException("No root path set."); - return getRootPaths().get(0); + return getRootPaths().getFirst(); } @Override @@ -208,7 +208,7 @@ public Path getRootNioPath() assert !_uris.isEmpty(); if (ROOT_BASE.cloud.equals(_defaultRoot)) { - return CloudStoreService.get().getPath(getContainer(), _cloudStoreName, new org.labkey.api.util.Path(_uris.get(0).getPath())); + return CloudStoreService.get().getPath(getContainer(), _cloudStoreName, new org.labkey.api.util.Path(_uris.getFirst().getPath())); } else return getRootPath().toPath(); @@ -374,8 +374,8 @@ public FileLike resolvePathToFileLike(String relativePath) if (ROOT_BASE.cloud.equals(_defaultRoot)) { // Return the path to the default location - var combinedPath = StringUtils.isNotBlank(_uris.get(0).getPath()) ? - org.labkey.api.util.Path.parse(_uris.get(0).getPath()).append(parsedPath) : + var combinedPath = StringUtils.isNotBlank(_uris.getFirst().getPath()) ? + org.labkey.api.util.Path.parse(_uris.getFirst().getPath()).append(parsedPath) : parsedPath; return CloudStoreService.get().getFileLike(getContainer(), _cloudStoreName, combinedPath); } @@ -433,8 +433,8 @@ public Path resolveToNioPath(String pathStr) if (ROOT_BASE.cloud.equals(_defaultRoot)) { // Return the path to the default location - var combinedPath = StringUtils.isNotBlank(_uris.get(0).getPath()) ? - org.labkey.api.util.Path.parse(_uris.get(0).getPath()).append(path) : + var combinedPath = StringUtils.isNotBlank(_uris.getFirst().getPath()) ? + org.labkey.api.util.Path.parse(_uris.getFirst().getPath()).append(path) : path; return CloudStoreService.get().getPath(getContainer(), _cloudStoreName, combinedPath); // TODO: Do we need? Check that it's under the root to protect against ../../ type paths diff --git a/pipeline/src/org/labkey/pipeline/api/PipelineEmailPreferences.java b/pipeline/src/org/labkey/pipeline/api/PipelineEmailPreferences.java index 5b8374c20f1..35a90aab6c5 100644 --- a/pipeline/src/org/labkey/pipeline/api/PipelineEmailPreferences.java +++ b/pipeline/src/org/labkey/pipeline/api/PipelineEmailPreferences.java @@ -431,10 +431,5 @@ public void shutdownPre() ContextListener.removeShutdownListener(this); _timer.cancel(); } - - @Override - public void shutdownStarted() - { - } } } diff --git a/pipeline/src/org/labkey/pipeline/api/PipelineJobMarshaller.java b/pipeline/src/org/labkey/pipeline/api/PipelineJobMarshaller.java index 54e02aafbd1..b157e1ab4c3 100644 --- a/pipeline/src/org/labkey/pipeline/api/PipelineJobMarshaller.java +++ b/pipeline/src/org/labkey/pipeline/api/PipelineJobMarshaller.java @@ -123,7 +123,7 @@ public String serializeToJSON(PipelineJob job, boolean ensureDeserialize) { throw new IllegalStateException("Job exceeds serialization limit of " + SERIALIZATION_SIZE_LIMIT + " characters. It was " + serialized.length() + " characters long."); } - LOG.debug("Serialized JSON for " + job + " was " + serialized.length() + " characters"); + LOG.debug("Serialized JSON for {} was {} characters", job, serialized.length()); if (ensureDeserialize) // Some callers round trip, so we don't need to here { @@ -132,11 +132,11 @@ public String serializeToJSON(PipelineJob job, boolean ensureDeserialize) PipelineJob unserialized = deserializeFromJSON(serialized, job.getClass()); List errors = job.compareJobs(unserialized); if (!errors.isEmpty()) - LOG.error("Deserialized object differs from original: " + StringUtils.join(errors, ",")); + LOG.error("Deserialized object differs from original: {}", StringUtils.join(errors, ",")); } catch (Exception e) { - LOG.error("Serializing round-trip test failed: " + job.getClass(), e); + LOG.error("Serializing round-trip test failed: {}", job.getClass(), e); } } return serialized; diff --git a/pipeline/src/org/labkey/pipeline/api/PipelineJobServiceImpl.java b/pipeline/src/org/labkey/pipeline/api/PipelineJobServiceImpl.java index 2c14abd8626..a6728f6b850 100644 --- a/pipeline/src/org/labkey/pipeline/api/PipelineJobServiceImpl.java +++ b/pipeline/src/org/labkey/pipeline/api/PipelineJobServiceImpl.java @@ -686,7 +686,7 @@ public FormSchema getFormSchema(Container container, User user) String typeDefaultValue = null; if (!typeOptions.isEmpty()) - typeDefaultValue = typeOptions.get(0).getValue(); + typeDefaultValue = typeOptions.getFirst().getValue(); List> taskOptions = new ArrayList<>(); List tasks = getTaskPipelines(container) @@ -1264,13 +1264,13 @@ public void testModuleCaches() .mapToInt(Map::size) .sum(); - LOG.info(pipelineCount + " task pipelines defined in all modules"); + LOG.info("{} task pipelines defined in all modules", pipelineCount); int factoryCount = TASK_FACTORY_CACHE.streamAllResourceMaps() .mapToInt(Map::size) .sum(); - LOG.info(factoryCount + " task factories defined in all modules"); + LOG.info("{} task factories defined in all modules", factoryCount); // Make sure the cache retrieves the expected number of pipelines and factories from a couple test modules, // if an R engine is configured and the test modules are present diff --git a/pipeline/src/org/labkey/pipeline/api/PipelineJobStoreImpl.java b/pipeline/src/org/labkey/pipeline/api/PipelineJobStoreImpl.java index 809bb73aa26..bc78af347f8 100644 --- a/pipeline/src/org/labkey/pipeline/api/PipelineJobStoreImpl.java +++ b/pipeline/src/org/labkey/pipeline/api/PipelineJobStoreImpl.java @@ -91,9 +91,8 @@ public void retry(PipelineStatusFile sf) throws IOException, NoSuchJobException PipelineService.get().queueJob(job); job.getLogger().info("Retrying job."); - job.getLogger().debug("Database indicates active task ID is " + job.getActiveTaskId() + (sf.getActiveHostName() == null ? "" : ", assigned to host '" + sf.getActiveHostName() + "'")); - job.getLogger().debug("Retry details: Old Job ID: " + oldJobId + - (Strings.CI.equals(sf.getJobId(), job.getJobGUID()) ? "" : ", new Job ID: " + job.getJobGUID())); + job.getLogger().debug("Database indicates active task ID is {}{}", job.getActiveTaskId(), sf.getActiveHostName() == null ? "" : ", assigned to host '" + sf.getActiveHostName() + "'"); + job.getLogger().debug("Retry details: Old Job ID: {}{}", oldJobId, Strings.CI.equals(sf.getJobId(), job.getJobGUID()) ? "" : ", new Job ID: " + job.getJobGUID()); } catch (PipelineValidationException e) { diff --git a/pipeline/src/org/labkey/pipeline/api/PipelineManager.java b/pipeline/src/org/labkey/pipeline/api/PipelineManager.java index 44f2b9682bb..1088d221358 100644 --- a/pipeline/src/org/labkey/pipeline/api/PipelineManager.java +++ b/pipeline/src/org/labkey/pipeline/api/PipelineManager.java @@ -287,7 +287,7 @@ public static void sendNotificationEmail(PipelineStatusFileImpl statusFile, Cont String interval = PipelineEmailPreferences.get().getFailureNotificationInterval(c); if (!"0".equals(interval) && interval != null) { - _log.info("Deciding not to send error notification email based on interval " + interval); + _log.info("Deciding not to send error notification email based on interval {}", interval); return; } @@ -369,7 +369,7 @@ private static PipelineMessage createPipelineMessage(Container c, PipelineStatus } catch (ValidEmail.InvalidEmailException e) { - _log.warn("Pipeline job status file uses an invalid email: " + statusFile.getEmail() + ". RowId: " + statusFile.getRowId()); + _log.warn("Pipeline job status file uses an invalid email: {}. RowId: {}", statusFile.getEmail(), statusFile.getRowId()); } } diff --git a/pipeline/src/org/labkey/pipeline/api/PipelineQueueImpl.java b/pipeline/src/org/labkey/pipeline/api/PipelineQueueImpl.java index 0306b3bb478..2926467f697 100644 --- a/pipeline/src/org/labkey/pipeline/api/PipelineQueueImpl.java +++ b/pipeline/src/org/labkey/pipeline/api/PipelineQueueImpl.java @@ -91,7 +91,7 @@ public synchronized void starting(PipelineJob job, Thread thread) // WARNING: This method is for pipeline maintenance only. Do not put // important functionality side-effects in here, since this // function is not supported in the Enterprise Pipeline. - LOG.debug("RUNNING: " + job.toString()); + LOG.debug("RUNNING: {}", job.toString()); boolean removed = _pending.remove(job); assert removed; _running.add(job); @@ -112,7 +112,7 @@ public synchronized void done(PipelineJob job) // function is not supported in the Enterprise Pipeline. try { - LOG.debug("COMPLETED: " + job.toString()); + LOG.debug("COMPLETED: {}", job.toString()); // Clear centrally to avoid needing to set in each job. See PipelineJobRunner for equivalent functionality // when running through Enterprise Pipeline @@ -188,7 +188,7 @@ public synchronized boolean cancelJob(User user, Container c, PipelineStatusFile PipelineJob job = PipelineJob.deserializeJob(statusFile.getJobStore()); if (job != null) { - job.getLogger().info("Attempting to cancel as requested by " + user); + job.getLogger().info("Attempting to cancel as requested by {}", user); PipelineJob.logStartStopInfo("Attempting to cancel job ID " + job.getJobGUID() + ", " + statusFile.getFilePath() + " as requested by " + user); } } diff --git a/pipeline/src/org/labkey/pipeline/api/PipelineServiceImpl.java b/pipeline/src/org/labkey/pipeline/api/PipelineServiceImpl.java index 41a86ec5bfb..2f2e68fc45e 100644 --- a/pipeline/src/org/labkey/pipeline/api/PipelineServiceImpl.java +++ b/pipeline/src/org/labkey/pipeline/api/PipelineServiceImpl.java @@ -192,7 +192,7 @@ public PipelineServiceImpl() { _jmsType = JmsType.unknown; } - LOG.info("Found " + _jmsType + " JMS queue."); + LOG.info("Found {} JMS queue.", _jmsType); } } @@ -711,12 +711,12 @@ public void refreshLocalJobs() } catch (UMOException e) { - LOG.error("Failed to get implementation class from descriptor " + descriptor, e); + LOG.error("Failed to get implementation class from descriptor {}", descriptor, e); } catch (IllegalAccessException | InstantiationException | NoSuchMethodException | InvocationTargetException e) { - LOG.error("Failed to resume jobs for descriptor " + descriptor, e); + LOG.error("Failed to resume jobs for descriptor {}", descriptor, e); } } } @@ -1024,7 +1024,7 @@ public boolean isProtocolDefined(AnalyzeForm form) @Override public File getProtocolParametersFile(ExpRun expRun) { - return expRun.getInputDatas(ANALYSIS_PARAMETERS_ROLE_NAME, null).get(0).getFile(); + return expRun.getInputDatas(ANALYSIS_PARAMETERS_ROLE_NAME, null).getFirst().getFile(); } @Override diff --git a/pipeline/src/org/labkey/pipeline/api/PipelineStatusManager.java b/pipeline/src/org/labkey/pipeline/api/PipelineStatusManager.java index 6cbcfedb093..48c421f4513 100644 --- a/pipeline/src/org/labkey/pipeline/api/PipelineStatusManager.java +++ b/pipeline/src/org/labkey/pipeline/api/PipelineStatusManager.java @@ -218,7 +218,7 @@ public static boolean setStatusFile(PipelineJob job, User user, String status, @ } else { - job.getLogger().error("Could not find job in database for job GUID " + job.getJobGUID() + ", unable to set its status to '" + status + "'"); + job.getLogger().error("Could not find job in database for job GUID {}, unable to set its status to '{}'", job.getJobGUID(), status); return false; } } @@ -477,7 +477,7 @@ public static void resetJobId(Container container, Path path, String jobId) List children = getSplitStatusFiles(sfExist.getJobId()); for (PipelineStatusFileImpl child : children) { - LOG.debug("Resetting parent job ID for child job " + child.getRowId() + " - " + child.getFilePath()); + LOG.debug("Resetting parent job ID for child job {} - {}", child.getRowId(), child.getFilePath()); child.setJobParent(null); child.beforeUpdate(null, child); updateStatusFile(child); @@ -700,7 +700,7 @@ public static void completeStatus(User user, Collection rowIds) throw new UnauthorizedException(); } - LOG.info("Job " + sf.getFilePath() + " was marked as complete by " + user); + LOG.info("Job {} was marked as complete by {}", sf.getFilePath(), user); sf.setStatus(PipelineJob.TaskStatus.complete.toString()); sf.setInfo(null); PipelineStatusManager.updateStatusFile(sf); @@ -802,7 +802,7 @@ private static void deleteStatus(Container container, User user, boolean deleteE if (provider != null) provider.preDeleteStatusFile(user, pipelineStatusFile); - LOG.info("Job " + pipelineStatusFile.getFilePath() + " was deleted by " + user); + LOG.info("Job {} was deleted by {}", pipelineStatusFile.getFilePath(), user); statusFileIds.add(pipelineStatusFile.getRowId()); } _schema.getSqlDialect().appendInClauseSql(sql, statusFileIds); diff --git a/pipeline/src/org/labkey/pipeline/api/ScriptTaskImpl.java b/pipeline/src/org/labkey/pipeline/api/ScriptTaskImpl.java index 44ec80cef57..f8c1f508f86 100644 --- a/pipeline/src/org/labkey/pipeline/api/ScriptTaskImpl.java +++ b/pipeline/src/org/labkey/pipeline/api/ScriptTaskImpl.java @@ -51,7 +51,6 @@ import javax.script.ScriptException; import java.io.File; import java.io.IOException; -import java.io.OutputStream; import java.net.URI; import java.util.ArrayList; import java.util.Arrays; diff --git a/pipeline/src/org/labkey/pipeline/api/SimpleTaskFactory.java b/pipeline/src/org/labkey/pipeline/api/SimpleTaskFactory.java index 112414fa788..9a0c29da6fb 100644 --- a/pipeline/src/org/labkey/pipeline/api/SimpleTaskFactory.java +++ b/pipeline/src/org/labkey/pipeline/api/SimpleTaskFactory.java @@ -315,7 +315,7 @@ private static FileType createFileType(List suffixes, boolean dir, List< { String defaultSuffix = null; if (!suffixes.isEmpty()) - defaultSuffix = suffixes.get(0); + defaultSuffix = suffixes.getFirst(); return new FileType(suffixes, defaultSuffix, dir, FileType.gzSupportLevel.NO_GZ, contentTypes); } diff --git a/pipeline/src/org/labkey/pipeline/api/TaskFactoryCacheHandler.java b/pipeline/src/org/labkey/pipeline/api/TaskFactoryCacheHandler.java index 305c14d2813..df0a3a83843 100644 --- a/pipeline/src/org/labkey/pipeline/api/TaskFactoryCacheHandler.java +++ b/pipeline/src/org/labkey/pipeline/api/TaskFactoryCacheHandler.java @@ -75,7 +75,7 @@ public Map> load(Stream resources, Mo } catch (IllegalArgumentException|IllegalStateException e) { - LOG.warn("Error registering '" + taskId + "' task: " + e.getMessage()); + LOG.warn("Error registering '{}' task: {}", taskId, e.getMessage()); return null; } } @@ -111,7 +111,7 @@ private TaskFactory create(TaskId taskId, Resource taskConfig) } catch (XmlException |IOException e) { - LOG.error("Error loading task factory '" + taskConfig.getPath() + "':\n" + e.getMessage()); + LOG.error("Error loading task factory '{}':\n{}", taskConfig.getPath(), e.getMessage()); return null; } diff --git a/pipeline/src/org/labkey/pipeline/api/TaskPipelineCacheHandler.java b/pipeline/src/org/labkey/pipeline/api/TaskPipelineCacheHandler.java index 75c017da377..d234e6edd39 100644 --- a/pipeline/src/org/labkey/pipeline/api/TaskPipelineCacheHandler.java +++ b/pipeline/src/org/labkey/pipeline/api/TaskPipelineCacheHandler.java @@ -83,7 +83,7 @@ public Map> load(Stream resources, M } catch (IllegalArgumentException|IllegalStateException e) { - LOG.warn("Error registering '" + taskId + "' pipeline: " + e.getMessage()); + LOG.warn("Error registering '{}' pipeline: {}", taskId, e.getMessage()); return null; } } diff --git a/pipeline/src/org/labkey/pipeline/api/WorkDirectoryRemote.java b/pipeline/src/org/labkey/pipeline/api/WorkDirectoryRemote.java index 56c19ee62ef..a9557bbd7f1 100644 --- a/pipeline/src/org/labkey/pipeline/api/WorkDirectoryRemote.java +++ b/pipeline/src/org/labkey/pipeline/api/WorkDirectoryRemote.java @@ -138,7 +138,7 @@ public WorkDirectory createWorkDirectory(String jobId, FileAnalysisJobSupport su if (_allowReuseExistingTempDirectory && dirParent.exists()) { - log.info("parent directory exists, reusing: " + dirParent.getPath()); + log.info("parent directory exists, reusing: {}", dirParent.getPath()); } else { @@ -172,7 +172,7 @@ else if (name.length() < 3) if (_allowReuseExistingTempDirectory && tempDir.exists()) { - log.info("working directory exists, reusing: " + dirParent.getPath()); + log.info("working directory exists, reusing: {}", dirParent.getPath()); } else { @@ -396,12 +396,7 @@ private MasterLockInfo parseMasterLock(RandomAccessFile masterIn, File masterLoc */ private static synchronized Lock getInMemoryLockObject(File f) { - Lock result = _locks.get(f); - if (result == null) - { - result = new ReentrantLock(); - _locks.put(f, result); - } + Lock result = _locks.computeIfAbsent(f, _ -> new ReentrantLock()); return result; } @@ -412,11 +407,11 @@ public void remove(boolean success) throws IOException // Issue 25166: this was a pre-existing potential bug. If _sharedTempDirectory is true, we create a second level // of temp directory above the primary working dir. this is added to make sure we clean this up. - _jobLog.debug("inspecting remote work dir: " + (_folderToClean == null ? _dir.getPath() : _folderToClean.getPath())); + _jobLog.debug("inspecting remote work dir: {}", _folderToClean == null ? _dir.getPath() : _folderToClean.getPath()); if (success && _folderToClean != null && !_dir.equals(_folderToClean)) { - _jobLog.debug("removing entire work dir through: " + _folderToClean.getPath()); - _jobLog.debug("starting with: " + _dir.getPath()); + _jobLog.debug("removing entire work dir through: {}", _folderToClean.getPath()); + _jobLog.debug("starting with: {}", _dir.getPath()); FileLike toCheck = _dir; //debugging only: @@ -429,7 +424,7 @@ public void remove(boolean success) throws IOException { if (!toCheck.exists()) { - _jobLog.debug("directory does not exist: " + toCheck.getPath()); + _jobLog.debug("directory does not exist: {}", toCheck.getPath()); toCheck = toCheck.getParent(); continue; } @@ -437,13 +432,13 @@ public void remove(boolean success) throws IOException List children = toCheck.getChildren(); if (children.isEmpty()) { - _jobLog.debug("removing directory: " + toCheck.getPath()); + _jobLog.debug("removing directory: {}", toCheck.getPath()); FileUtil.deleteDir(toCheck); toCheck = toCheck.getParent(); } else { - _jobLog.debug("work directory has children, will not delete: " + toCheck.getPath()); + _jobLog.debug("work directory has children, will not delete: {}", toCheck.getPath()); _jobLog.debug("files:"); for (FileLike fn : children) { @@ -491,11 +486,11 @@ protected CopyingResource createCopyingLock() throws IOException } } - _jobLog.debug("Acquiring lock #" + lockInfo.getCurrentLock()); + _jobLog.debug("Acquiring lock #{}", lockInfo.getCurrentLock()); File f = _lockDirectory.resolveChild("lock" + lockInfo.getCurrentLock()).toNioPathForWrite().toFile(); FileChannel lockChannel = new FileOutputStream(f, true).getChannel(); FileLockCopyingResource result = new FileLockCopyingResource(lockChannel, lockInfo.getCurrentLock(), f); - _jobLog.debug("Lock #" + lockInfo.getCurrentLock() + " acquired"); + _jobLog.debug("Lock #{} acquired", lockInfo.getCurrentLock()); return result; } @@ -630,7 +625,7 @@ public void close() { _state.close(); _cleanable.clean(); - _jobLog.debug("Lock #" + _lockNumber + " released"); + _jobLog.debug("Lock #{} released", _lockNumber); _lock = null; _channel = null; super.close(); diff --git a/pipeline/src/org/labkey/pipeline/importer/FolderImportJob.java b/pipeline/src/org/labkey/pipeline/importer/FolderImportJob.java index b18cc778537..6a88ad59dce 100644 --- a/pipeline/src/org/labkey/pipeline/importer/FolderImportJob.java +++ b/pipeline/src/org/labkey/pipeline/importer/FolderImportJob.java @@ -85,7 +85,7 @@ public FolderImportJob(Container c, User user, ActionURL url, FileLike folderXml _ctx.setActivity(options.getActivity()); _ctx.setNewFolderImport(options.isNewFolderImport()); - LOG.info("Pipeline job initialized for importing folder archive to folder " + c.getPath()); + LOG.info("Pipeline job initialized for importing folder archive to folder {}", c.getPath()); } @Override diff --git a/pipeline/src/org/labkey/pipeline/mule/EPipelineContextListener.java b/pipeline/src/org/labkey/pipeline/mule/EPipelineContextListener.java index 29db15410c3..469cc9dccc1 100644 --- a/pipeline/src/org/labkey/pipeline/mule/EPipelineContextListener.java +++ b/pipeline/src/org/labkey/pipeline/mule/EPipelineContextListener.java @@ -47,11 +47,6 @@ public void moduleStartupComplete(ServletContext servletContext) } } - @Override - public void shutdownPre() - { - } - @Override public void shutdownStarted() { diff --git a/pipeline/src/org/labkey/pipeline/mule/EPipelineQueueImpl.java b/pipeline/src/org/labkey/pipeline/mule/EPipelineQueueImpl.java index ecd93f7eee1..15bb4d0a2d0 100644 --- a/pipeline/src/org/labkey/pipeline/mule/EPipelineQueueImpl.java +++ b/pipeline/src/org/labkey/pipeline/mule/EPipelineQueueImpl.java @@ -118,7 +118,7 @@ public boolean cancelJob(User user, Container c, PipelineStatusFile statusFile) PipelineJob job = PipelineJob.deserializeJob(statusFile.getJobStore()); if (job != null) { - job.getLogger().info("Attempting to cancel job as requested by " + user + "."); + job.getLogger().info("Attempting to cancel job as requested by {}.", user); PipelineJob.logStartStopInfo("Attempting to cancel job ID " + job.getJobGUID() + ", " + statusFile.getFilePath() + " as requested by " + user); } @@ -147,13 +147,13 @@ private boolean cancelRemoteExecutionEngineJob(final PipelineStatusFile statusFi JobRunner.getDefault().execute(() -> { try { - job.getLogger().info("Cancelling remote job by submitting request to " + engine); + job.getLogger().info("Cancelling remote job by submitting request to {}", engine); PipelineJob.logStartStopInfo("Cancelling job by submitting request to " + engine + ". Job ID: " + job.getJobGUID() + ", " + statusFile.getFilePath()); engine.cancelJob(job.getJobGUID()); } catch (Exception e) { - _log.error("Error attempting to cancel job " + statusFile.getFilePath(), e); + _log.error("Error attempting to cancel job {}", statusFile.getFilePath(), e); } }); return true; @@ -211,7 +211,7 @@ private boolean removeFromJMSQueue(PipelineStatusFile statusFile, PipelineJob jo } catch (JMSException e) { - _log.error("Error browsing message queue at '" + ep.getEndpointURI(), e); + _log.error("Error browsing message queue at '{}", ep.getEndpointURI(), e); } finally { @@ -255,7 +255,7 @@ public List findJobs(String location) } catch (JMSException e) { - _log.error("Error browsing message queue at '" + ep.getEndpointURI(), e); + _log.error("Error browsing message queue at '{}", ep.getEndpointURI(), e); } finally { @@ -313,13 +313,13 @@ public static void dispatchJob(PipelineJob job) throws UMOException MuleClient client = null; try { - _log.debug("Dispatching job: " + job); + _log.debug("Dispatching job: {}", job); client = new MuleClient(); client.dispatch(EPipelineQueueImpl.PIPELINE_QUEUE_NAME, job, null); } catch (Exception e) { - _log.debug("Error dispatching job: " + job, e); + _log.debug("Error dispatching job: {}", job, e); throw e; } finally diff --git a/pipeline/src/org/labkey/pipeline/mule/LabKeyWebappMuleXmlConfigurationBuilder.java b/pipeline/src/org/labkey/pipeline/mule/LabKeyWebappMuleXmlConfigurationBuilder.java index e54b1e885c4..9b9bb4789c4 100644 --- a/pipeline/src/org/labkey/pipeline/mule/LabKeyWebappMuleXmlConfigurationBuilder.java +++ b/pipeline/src/org/labkey/pipeline/mule/LabKeyWebappMuleXmlConfigurationBuilder.java @@ -42,11 +42,11 @@ protected InputStream loadResource(String resource) throws ConfigurationExceptio if (is != null) { - LOG.debug("Resource " + resource + " is found in Servlet Context."); + LOG.debug("Resource {} is found in Servlet Context.", resource); } else { - LOG.debug("Resource " + resourcePath + " is not found in Servlet Context, loading from classpath or as external file"); + LOG.debug("Resource {} is not found in Servlet Context, loading from classpath or as external file", resourcePath); } if (is == null && webappClasspath != null) @@ -59,7 +59,7 @@ protected InputStream loadResource(String resource) throws ConfigurationExceptio } catch (ConfigurationException e) { - LOG.debug("Resource " + resourcePath + " is not found in filesystem"); + LOG.debug("Resource {} is not found in filesystem", resourcePath); } } diff --git a/pipeline/src/org/labkey/pipeline/mule/MuleListenerHelper.java b/pipeline/src/org/labkey/pipeline/mule/MuleListenerHelper.java index f51d39a6867..9c1010a45ca 100644 --- a/pipeline/src/org/labkey/pipeline/mule/MuleListenerHelper.java +++ b/pipeline/src/org/labkey/pipeline/mule/MuleListenerHelper.java @@ -80,7 +80,7 @@ public MuleListenerHelper(ServletContext parentContext) File muleFile = FileUtil.appendName(configDir, "webserverMuleConfig.xml"); if (muleFile.isFile()) { - _log.info("Found Mule configuration file override at " + muleFile.getPath()); + _log.info("Found Mule configuration file override at {}", muleFile.getPath()); muleConfigPath = muleFile.getName(); } } @@ -130,7 +130,7 @@ public Object convert(Class clazz, Object obj) Integer val = POOL_EXHAUSTED_ACTIONS.get(obj); if (val != null) { - _log.info("Hack for MULE-2289, converting " + obj + " to integer value " + val); + _log.info("Hack for MULE-2289, converting {} to integer value {}", obj, val); return val.intValue(); } return conv.convert(clazz, obj); @@ -225,7 +225,7 @@ public InputStream getResourceAsStream(String string) } catch (FileNotFoundException e) { - _log.debug("Could not find mule config override " + string); + _log.debug("Could not find mule config override {}", string); } } diff --git a/pipeline/src/org/labkey/pipeline/mule/PipelineJobRunnerRemoteExecution.java b/pipeline/src/org/labkey/pipeline/mule/PipelineJobRunnerRemoteExecution.java index 2096b6b7727..b4cac513c6c 100644 --- a/pipeline/src/org/labkey/pipeline/mule/PipelineJobRunnerRemoteExecution.java +++ b/pipeline/src/org/labkey/pipeline/mule/PipelineJobRunnerRemoteExecution.java @@ -82,7 +82,7 @@ public void run() String location = entry.getKey(); List filesToCheck = entry.getValue(); - _log.info("Starting to check status for " + filesToCheck.size() + " jobs on remote location '" + location + "'"); + _log.info("Starting to check status for {} jobs on remote location '{}'", filesToCheck.size(), location); RemoteExecutionEngine engine = configuredLocations.get(location); Set jobIds = new HashSet<>(); for (PipelineStatusFileImpl sf : filesToCheck) @@ -90,16 +90,18 @@ public void run() jobIds.add(sf.getJobId()); } - _log.info("Starting to check for status of " + jobIds.size() + " jobs for engine: " + engine.getType()); + _log.info("Starting to check for status of {} jobs for engine: {}", jobIds.size(), engine.getType()); try { engine.updateStatusForJobs(jobIds); - _log.info("Finished checking status jobs on remote location '" + location + "'"); + _log.info("Finished checking status jobs on remote location '{}'", location); } catch (PipelineJobException e) { - _log.error("Unable to update status for engine: " + engine.getType(), e); + _log.error("Unable to update status for engine: {}", engine.getType(), e); } + + _log.info("Finished checking status jobs on remote location '{}'", location); } _log.info("Finished checking status jobs for all remote locations"); } @@ -161,7 +163,7 @@ public Object onCall(UMOEventContext eventContext) throws Exception RemoteExecutionEngine engine = getEngine(job); engine.submitJob(job); - _log.info("Job " + job.getJobGUID() + " submitted to remote engine " + engine.getType()); + _log.info("Job {} submitted to remote engine {}", job.getJobGUID(), engine.getType()); submitted = true; } finally diff --git a/pipeline/src/org/labkey/pipeline/mule/RequeueLostJobsRequest.java b/pipeline/src/org/labkey/pipeline/mule/RequeueLostJobsRequest.java index f5675d37356..eab5fb2e05b 100644 --- a/pipeline/src/org/labkey/pipeline/mule/RequeueLostJobsRequest.java +++ b/pipeline/src/org/labkey/pipeline/mule/RequeueLostJobsRequest.java @@ -56,8 +56,7 @@ public void performRequest() { if (PipelineService.get().getPipelineQueue().isLocal()) { - _log.error("Attempted to requeue lost jobs for location " + Arrays.asList(_locations) + " but this server " + - "is not using an external JMS queue. Change your configuration to point to a different JMS queue."); + _log.error("Attempted to requeue lost jobs for location {} but this server is not using an external JMS queue. Change your configuration to point to a different JMS queue.", Arrays.asList(_locations)); } // Do this in a separate thread because Mule doesn't deal with queuing different events while processing an @@ -75,14 +74,14 @@ public void run() */ synchronized(LOCK) { - _log.info("Requeueing jobs for location " + location + (_hostName == null ? "" : " and host name " + _hostName)); + _log.info("Requeueing jobs for location {}{}", location, _hostName == null ? "" : " and host name " + _hostName); for (PipelineStatusFileImpl sf : PipelineStatusManager.getStatusFilesForLocation(location, true)) { if (!_jobIds.contains(sf.getJobId()) && sf.getJobStore() != null && (sf.getActiveHostName() == null || sf.getActiveHostName().equals(_hostName))) { try { - _log.info("Requeueing job: " + sf.getDescription()); + _log.info("Requeueing job: {}", sf.getDescription()); PipelineJobService.get().getJobStore().retry(sf); } catch (IOException | NoSuchJobException e) diff --git a/pipeline/src/org/labkey/pipeline/mule/filters/JobIncompleteFilter.java b/pipeline/src/org/labkey/pipeline/mule/filters/JobIncompleteFilter.java index 5e6a453dfbc..27b948cb0aa 100644 --- a/pipeline/src/org/labkey/pipeline/mule/filters/JobIncompleteFilter.java +++ b/pipeline/src/org/labkey/pipeline/mule/filters/JobIncompleteFilter.java @@ -39,16 +39,11 @@ public boolean accept(UMOMessage message) return true; PipelineJob job = (PipelineJob) payload; - switch (job.getActiveTaskStatus()) + return switch (job.getActiveTaskStatus()) { - case error: - return false; - - case complete: - return (job.getActiveTaskId() != null); - - default: - return true; - } + case error -> false; + case complete -> (job.getActiveTaskId() != null); + default -> true; + }; } } diff --git a/pipeline/src/org/labkey/pipeline/mule/filters/TaskJmsSelectorFilter.java b/pipeline/src/org/labkey/pipeline/mule/filters/TaskJmsSelectorFilter.java index bd9b391caa0..a2a439a99e7 100644 --- a/pipeline/src/org/labkey/pipeline/mule/filters/TaskJmsSelectorFilter.java +++ b/pipeline/src/org/labkey/pipeline/mule/filters/TaskJmsSelectorFilter.java @@ -103,7 +103,7 @@ public String getExpression() expr.append("'"); expr.append(")"); - _log.debug("JMS Select: " + expr); + _log.debug("JMS Select: {}", expr); return expr.toString(); } diff --git a/pipeline/src/org/labkey/pipeline/mule/transformers/JMSMessageToPipelineJob.java b/pipeline/src/org/labkey/pipeline/mule/transformers/JMSMessageToPipelineJob.java index d5a5477711d..7352f05f0f5 100644 --- a/pipeline/src/org/labkey/pipeline/mule/transformers/JMSMessageToPipelineJob.java +++ b/pipeline/src/org/labkey/pipeline/mule/transformers/JMSMessageToPipelineJob.java @@ -46,7 +46,7 @@ public Object transform(Object src, String encoding, UMOEventContext context) th String xml = (String) getJMSTransformer().doTransform(src, encoding); PipelineJob result = PipelineJob.deserializeJob(xml); if (null != result) - LOG.debug("Transformed XML to job: " + result); + LOG.debug("Transformed XML to job: {}", result); return result; } diff --git a/pipeline/src/org/labkey/pipeline/status/StatusDetailsBean.java b/pipeline/src/org/labkey/pipeline/status/StatusDetailsBean.java index 4fd7c79012a..5ba03be279b 100644 --- a/pipeline/src/org/labkey/pipeline/status/StatusDetailsBean.java +++ b/pipeline/src/org/labkey/pipeline/status/StatusDetailsBean.java @@ -159,7 +159,7 @@ public static StatusDetailsBean create(Container c, PipelineStatusFile psf, long } catch (IOException e) { - LOG.warn("Error reading log file '" + strPath + "' at offset " + logOffset + ": " + e.getMessage(), e); + LOG.warn("Error reading log file '{}' at offset {}: {}", strPath, logOffset, e.getMessage(), e); statusLog = StatusDetailLog.createError("Error reading log file at offset " + logOffset + ": " + e.getMessage(), logOffset); } } diff --git a/query/api-src/org/labkey/remoteapi/SelectRowsStreamHack.java b/query/api-src/org/labkey/remoteapi/SelectRowsStreamHack.java index 856d5356909..eca130b41e9 100644 --- a/query/api-src/org/labkey/remoteapi/SelectRowsStreamHack.java +++ b/query/api-src/org/labkey/remoteapi/SelectRowsStreamHack.java @@ -101,7 +101,7 @@ public DataIterator getDataIterator(DataIteratorContext context) try (OutputStream os = new BufferedOutputStream(new GZIPOutputStream(new FileOutputStream(tempFile))); InputStream ris = (alternateInputStream == null ? response.getInputStream() : alternateInputStream)) { - _log.debug("Downloading SelectRows JSON to file: " + tempFile); + _log.debug("Downloading SelectRows JSON to file: {}", tempFile); IOUtils.copy(ris, os); _log.debug("Finished saving SelectRows results"); } diff --git a/query/src/org/labkey/query/AutoGeneratedCustomView.java b/query/src/org/labkey/query/AutoGeneratedCustomView.java index 26b7499f3f6..352f638146f 100644 --- a/query/src/org/labkey/query/AutoGeneratedCustomView.java +++ b/query/src/org/labkey/query/AutoGeneratedCustomView.java @@ -150,13 +150,13 @@ public boolean serialize(VirtualFile dir) } @Override - public String getName() + public @NotNull String getName() { return _name; } @Override - public String getLabel() + public @NotNull String getLabel() { return _name; } @@ -192,25 +192,25 @@ public User getModifiedBy() } @Override - public Date getModified() + public @NotNull Date getModified() { return new Date(); } @Override - public String getSchemaName() + public @NotNull String getSchemaName() { return _queryDef.getSchema().getSchemaName(); } @Override - public SchemaKey getSchemaPath() + public @NotNull SchemaKey getSchemaPath() { return _queryDef.getSchema().getSchemaPath(); } @Override - public String getQueryName() + public @NotNull String getQueryName() { return _queryDef.getName(); } diff --git a/query/src/org/labkey/query/CustomQueryDefinitionImpl.java b/query/src/org/labkey/query/CustomQueryDefinitionImpl.java index 906e4396ff7..226cc051f5c 100644 --- a/query/src/org/labkey/query/CustomQueryDefinitionImpl.java +++ b/query/src/org/labkey/query/CustomQueryDefinitionImpl.java @@ -55,12 +55,6 @@ public boolean isUserDefined() return true; } - @Override - public boolean isMetadataEditable() - { - return true; - } - @Override public String getSql() { diff --git a/query/src/org/labkey/query/CustomViewImpl.java b/query/src/org/labkey/query/CustomViewImpl.java index 77a63c8baf9..5285a2a45aa 100644 --- a/query/src/org/labkey/query/CustomViewImpl.java +++ b/query/src/org/labkey/query/CustomViewImpl.java @@ -404,7 +404,7 @@ public boolean serialize(VirtualFile dir) throws IOException if (fas.getContainerFilterNames() != null && !fas.getContainerFilterNames().isEmpty()) { - String containerFilter = fas.getContainerFilterNames().get(0); + String containerFilter = fas.getContainerFilterNames().getFirst(); ContainerFilterType.Enum containerFilterType = ContainerFilterType.Enum.forString(containerFilter); if (containerFilterType != null) customViewXml.setContainerFilter(containerFilterType); @@ -412,7 +412,7 @@ public boolean serialize(VirtualFile dir) throws IOException } catch (URISyntaxException e) { - _log.error("Bad filter/sort URL in custom view: " + _cstmView.getFilter()); + _log.error("Bad filter/sort URL in custom view: {}", _cstmView.getFilter()); } String filename = (null != getName() ? getName() : "default") + ".db_" + getCstmView().getCustomViewId() + CustomViewXmlReader.XML_FILE_EXTENSION; diff --git a/query/src/org/labkey/query/CustomViewImporter.java b/query/src/org/labkey/query/CustomViewImporter.java index 9c0dee5122e..4b08fc11a93 100644 --- a/query/src/org/labkey/query/CustomViewImporter.java +++ b/query/src/org/labkey/query/CustomViewImporter.java @@ -54,12 +54,12 @@ public void process(PipelineJob job, FolderImportContext ctx, VirtualFile root) if (null != job) job.setStatus("IMPORT " + getDescription()); - ctx.getLogger().info("Loading " + getDescription()); + ctx.getLogger().info("Loading {}", getDescription()); int count = QueryService.get().importCustomViews(ctx.getUser(), ctx.getContainer(), viewDir); - - ctx.getLogger().info(count + " custom view" + (1 == count ? "" : "s") + " imported"); - ctx.getLogger().info("Done importing " + getDescription()); + + ctx.getLogger().info("{} custom view{} imported", count, 1 == count ? "" : "s"); + ctx.getLogger().info("Done importing {}", getDescription()); } } diff --git a/query/src/org/labkey/query/CustomViewInfoImpl.java b/query/src/org/labkey/query/CustomViewInfoImpl.java index 011a4c07b93..a563b08192e 100644 --- a/query/src/org/labkey/query/CustomViewInfoImpl.java +++ b/query/src/org/labkey/query/CustomViewInfoImpl.java @@ -203,19 +203,19 @@ public void isSession(boolean b) } @Override - public String getSchemaName() + public @NotNull String getSchemaName() { return _cstmView.getSchema(); } @Override - public SchemaKey getSchemaPath() + public @NotNull SchemaKey getSchemaPath() { return SchemaKey.fromString(_cstmView.getSchema()); } @Override - public String getQueryName() + public @NotNull String getQueryName() { return _cstmView.getQueryName(); } @@ -250,7 +250,7 @@ public String getContainerFilterName() URLHelper src = new URLHelper(_cstmView.getFilter()); List containerFilterNames = src.getParameterValues(FILTER_PARAM_PREFIX + "." + CONTAINER_FILTER_NAME); if (!containerFilterNames.isEmpty()) - return containerFilterNames.get(containerFilterNames.size() - 1); + return containerFilterNames.getLast(); return null; } catch (URISyntaxException use) diff --git a/query/src/org/labkey/query/CustomViewXmlReader.java b/query/src/org/labkey/query/CustomViewXmlReader.java index ed18ae96f32..1c4f87d6505 100644 --- a/query/src/org/labkey/query/CustomViewXmlReader.java +++ b/query/src/org/labkey/query/CustomViewXmlReader.java @@ -311,7 +311,7 @@ public static CustomViewXmlReader loadDefinition(InputStream is, String path) } catch (XmlException | IOException | XmlValidationException e) { - LOG.error("Failed to parse custom view file from custom module at location " + path + ", falling back on default view", e); + LOG.error("Failed to parse custom view file from custom module at location {}, falling back on default view", path, e); CustomViewXmlReader reader = new CustomViewXmlReader(); reader.addError(e.getMessage()); return reader; @@ -425,7 +425,7 @@ protected static List loadAggregates(AggregatesType aggre ret.add(new AnalyticsProviderItem(agg)); } else - LOG.warn("Invalid summary statistic type: " + type); + LOG.warn("Invalid summary statistic type: {}", type); } return ret; } @@ -449,7 +449,7 @@ protected static List loadAnalyticsProviders(AnalyticsPro if (analyticsProvider != null) ret.add(new AnalyticsProviderItem(FieldKey.fromString(column), type, analytic.getLabel())); else - LOG.warn("Invalid analytics provider name: " + type); + LOG.warn("Invalid analytics provider name: {}", type); } return ret; diff --git a/query/src/org/labkey/query/ExternalSchemaDefImporterFactory.java b/query/src/org/labkey/query/ExternalSchemaDefImporterFactory.java index 49471c6a4c1..fd04dd32ce1 100644 --- a/query/src/org/labkey/query/ExternalSchemaDefImporterFactory.java +++ b/query/src/org/labkey/query/ExternalSchemaDefImporterFactory.java @@ -78,7 +78,7 @@ public void process(PipelineJob job, FolderImportContext ctx, VirtualFile root) if (null != job) job.setStatus("IMPORT " + getDescription()); - ctx.getLogger().info("Loading " + getDescription()); + ctx.getLogger().info("Loading {}", getDescription()); List schemaXmlFileNames = externalSchemaDir.list(); @@ -88,8 +88,8 @@ public void process(PipelineJob job, FolderImportContext ctx, VirtualFile root) importSchema(ctx, root, externalSchemaDir, schemaFileName); } - ctx.getLogger().info(StringUtilsLabKey.pluralize(schemaXmlFileNames.size(), "external schema definition") + " imported"); - ctx.getLogger().info("Done importing " + getDescription()); + ctx.getLogger().info("{} imported", StringUtilsLabKey.pluralize(schemaXmlFileNames.size(), "external schema definition")); + ctx.getLogger().info("Done importing {}", getDescription()); ExternalSchemaDefCache.uncache(ctx.getContainer()); // issue 25498 } @@ -140,7 +140,7 @@ else if (schemaXmlFile instanceof LinkedSchemaDocument schemaDoc) if (container != null) form.setTypedValue("dataSource", container.getId()); else - ctx.getLogger().warn("LinkedSchemaDef's source container '" + containerPath + "' does not exist; ignoring schema."); + ctx.getLogger().warn("LinkedSchemaDef's source container '{}' does not exist; ignoring schema.", containerPath); } else throw new ImportException("Unable to get an instance of external or linked schema from " + relativePath); diff --git a/query/src/org/labkey/query/LinkedSchemaQueryDefinition.java b/query/src/org/labkey/query/LinkedSchemaQueryDefinition.java index 1d8df49f5f5..13d1fc54149 100644 --- a/query/src/org/labkey/query/LinkedSchemaQueryDefinition.java +++ b/query/src/org/labkey/query/LinkedSchemaQueryDefinition.java @@ -359,12 +359,6 @@ public boolean isSqlEditable() return false; } - @Override - public boolean isMetadataEditable() - { - return true; - } - @Override public ActionURL urlFor(QueryAction action, Container container) { diff --git a/query/src/org/labkey/query/MetadataTableJSON.java b/query/src/org/labkey/query/MetadataTableJSON.java index 8e795f33b5a..f6df551fe98 100644 --- a/query/src/org/labkey/query/MetadataTableJSON.java +++ b/query/src/org/labkey/query/MetadataTableJSON.java @@ -234,7 +234,7 @@ else if (updatedQueryName != null) } else if (metadataColumnJSON.getValueExpression() == null) { - log.info("No such column: " + metadataColumnJSON.getName() + " in table: " + schemaName + "." + queryDef.getName() + " in folder: " + container.getName()); + log.info("No such column: {} in table: {}.{} in folder: {}", metadataColumnJSON.getName(), schemaName, queryDef.getName(), container.getName()); } } diff --git a/query/src/org/labkey/query/ModuleCustomViewInfo.java b/query/src/org/labkey/query/ModuleCustomViewInfo.java index 28128eed232..052b2b4dede 100644 --- a/query/src/org/labkey/query/ModuleCustomViewInfo.java +++ b/query/src/org/labkey/query/ModuleCustomViewInfo.java @@ -50,7 +50,7 @@ public String getName() } @Override - public String getLabel() + public @NotNull String getLabel() { return _customViewDef.getLabel(); } @@ -81,7 +81,7 @@ public User getCreatedBy() } @Override - public Date getCreated() + public @NotNull Date getCreated() { return _customViewDef.getLastModified(); } @@ -93,25 +93,25 @@ public User getModifiedBy() } @Override - public Date getModified() + public @NotNull Date getModified() { return _customViewDef.getLastModified(); } @Override - public String getSchemaName() + public @NotNull String getSchemaName() { return _customViewDef.getSchema(); } @Override - public SchemaKey getSchemaPath() + public @NotNull SchemaKey getSchemaPath() { return SchemaKey.fromString(_customViewDef.getSchema()); } @Override - public String getQueryName() + public @NotNull String getQueryName() { return _customViewDef.getQuery(); } diff --git a/query/src/org/labkey/query/MultiValueTest.jsp b/query/src/org/labkey/query/MultiValueTest.jsp index ebe587b1f4c..144d3d66e73 100644 --- a/query/src/org/labkey/query/MultiValueTest.jsp +++ b/query/src/org/labkey/query/MultiValueTest.jsp @@ -133,7 +133,7 @@ ); List> insertedAntigens = antigensTable.getUpdateService().insertRows(getUser(), c, antigenRows, errors, null, null); throwErrors(errors); - Integer antigenId = asInteger(insertedAntigens.get(0).get("rowId")); + Integer antigenId = asInteger(insertedAntigens.getFirst().get("rowId")); // insert a Label errors = new BatchValidationException(); @@ -143,7 +143,7 @@ ); List> insertedLabels = labelsTable.getUpdateService().insertRows(getUser(), c, labelRows, errors, null, null); throwErrors(errors); - Long labelId = asLong(insertedLabels.get(0).get("rowId")); + Long labelId = asLong(insertedLabels.getFirst().get("rowId")); // insert Species errors = new BatchValidationException(); @@ -169,7 +169,7 @@ ); List> insertedReagents = reagentsTable.getUpdateService().insertRows(getUser(), c, reagentRows, errors, null, null); throwErrors(errors); - Long reagentId = asLong(insertedReagents.get(0).get("rowId")); + Long reagentId = asLong(insertedReagents.getFirst().get("rowId")); // insert ReagentSpecies errors = new BatchValidationException(); diff --git a/query/src/org/labkey/query/QueryDefinitionImpl.java b/query/src/org/labkey/query/QueryDefinitionImpl.java index ff326e382de..3f10b7d7170 100644 --- a/query/src/org/labkey/query/QueryDefinitionImpl.java +++ b/query/src/org/labkey/query/QueryDefinitionImpl.java @@ -217,7 +217,7 @@ public CustomView getCustomView(@NotNull User owner, @Nullable HttpServletReques String referrer = request.getHeader("Referer"); extra = " [url=" + request.getRequestURI() + (null != referrer ? ", referrer=" + referrer : "") + "]"; } - log.info("Could not find the requested custom view named '" + name + "'" + " in " + getSchemaPath() + "." + getQueryDef().getName() + " in the container " + _container.getPath() + " for user " + owner + extra); + log.info("Could not find the requested custom view named '{}' in {}.{} in the container {} for user {}{}", name, getSchemaPath(), getQueryDef().getName(), _container.getPath(), owner, extra); } return result; } @@ -482,7 +482,7 @@ public Query getQuery(@NotNull QuerySchema schema, List errors, String sql = getSql(); if (sql != null) { - log.debug("Parsing query " + schema.getSchemaName() + "." + getName()); + log.debug("Parsing query {}.{}", schema.getSchemaName(), getName()); query.parse(sql, skipSuggestedColumns); } if (includeMetadata) @@ -569,12 +569,12 @@ public TableInfo getTable(@NotNull UserSchema schema, @Nullable List error instanceof QueryParseException && ((QueryParseException)error).isWarning()))) return null; - log.debug("Caching table " + schema.getName() + "." + table.getName()); + log.debug("Caching table {}.{}", schema.getName(), table.getName()); _cache.put(key, table); } else { - log.debug("Returning cached table '" + getName() + "', " + (includeMetadata ? "with" : "without") + " metadata"); + log.debug("Returning cached table '{}', {} metadata", getName(), includeMetadata ? "with" : "without"); } return table; @@ -1075,7 +1075,7 @@ public ViewOptionsImpl(String metadataXml) { // Don't completely die if someone specified invalid metadata XML. Log a warning // and render without the custom metadata. - log.warn("Unable to parse metadata XML for " + getSchemaName() + "." + getName() + " in " + getContainer(), e); + log.warn("Unable to parse metadata XML for {}.{} in {}", getSchemaName(), getName(), getContainer(), e); } } if (_document == null) diff --git a/query/src/org/labkey/query/QueryImporter.java b/query/src/org/labkey/query/QueryImporter.java index 8ef843cc460..67191eaacd8 100644 --- a/query/src/org/labkey/query/QueryImporter.java +++ b/query/src/org/labkey/query/QueryImporter.java @@ -90,7 +90,7 @@ public void process(PipelineJob job, FolderImportContext ctx, VirtualFile root) if (null != job) job.setStatus("IMPORT " + getDescription()); - ctx.getLogger().info("Loading " + getDescription()); + ctx.getLogger().info("Loading {}", getDescription()); // get the list of files and split them into sql and xml file name arrays ArrayList sqlFileNames = new ArrayList<>(); @@ -168,14 +168,14 @@ else if (fileName.endsWith(QueryWriter.META_FILE_EXTENSION)) UserSchema schema = QueryService.get().getUserSchema(ctx.getUser(), ctx.getContainer(), schemaKey); if (schema == null) { - ctx.getLogger().warn("Skipping import: " + queryImportMessage(schemaName, queryName, null, metaFileName, "schema doesn't exist.")); + ctx.getLogger().warn("Skipping import: {}", queryImportMessage(schemaName, queryName, null, metaFileName, "schema doesn't exist.")); continue; } if (!schema.getTableNames().contains(queryName)) { // warn if the table doesn't exist -- it may be created later during the import (e.g., a SampleType may be created as a part of the import process) - ctx.getLogger().warn("Importing: " + queryImportMessage(schemaName, queryName, null, metaFileName, "Creating metadata xml override for table that doesn't exist")); + ctx.getLogger().warn("Importing: {}", queryImportMessage(schemaName, queryName, null, metaFileName, "Creating metadata xml override for table that doesn't exist")); qic.unresolvedMetadataFiles.put(metaFileName, queryDoc);// } @@ -199,8 +199,8 @@ else if (fileName.endsWith(QueryWriter.META_FILE_EXTENSION)) QueryService.get().fireQueryChanged(ctx.getUser(), ctx.getContainer(), null, schemaKey, property, changes); } - ctx.getLogger().info(sqlFileNames.size() + " quer" + (1 == sqlFileNames.size() ? "y" : "ies") + " imported"); - ctx.getLogger().info("Done importing " + getDescription()); + ctx.getLogger().info("{} quer{} imported", sqlFileNames.size(), 1 == sqlFileNames.size() ? "y" : "ies"); + ctx.getLogger().info("Done importing {}", getDescription()); } } @@ -238,7 +238,7 @@ private void createQueryDef(FolderImportContext ctx, // Don't attempt to replace an existing module-based query... that won't go well. Just warn and move on. #30081 if (!StringUtils.isEmpty(queryDef.getModuleName())) { - ctx.getLogger().warn("Skipping import: " + queryImportMessage(schemaName, queryName, sqlFileName, metaFileName, "can't overwrite existing module-based query")); + ctx.getLogger().warn("Skipping import: {}", queryImportMessage(schemaName, queryName, sqlFileName, metaFileName, "can't overwrite existing module-based query")); return; } @@ -274,7 +274,7 @@ private void createQueryDef(FolderImportContext ctx, } else if (queryDef.getSql() != null) { - ctx.getLogger().warn("Skipping import: " + queryImportMessage(schemaName, queryName, sqlFileName, metaFileName, "can't overwrite existing custom query with only metadata xml override")); + ctx.getLogger().warn("Skipping import: {}", queryImportMessage(schemaName, queryName, sqlFileName, metaFileName, "can't overwrite existing custom query with only metadata xml override")); return; } @@ -286,7 +286,7 @@ else if (queryDef.getSql() != null) Collection> changes = queryDef.save(ctx.getUser(), ctx.getContainer(), false); if (created) { - List queries = createdQueries.computeIfAbsent(schemaKey, k -> new ArrayList<>()); + List queries = createdQueries.computeIfAbsent(schemaKey, _ -> new ArrayList<>()); queries.add(queryName); } else if (changes != null) @@ -295,7 +295,7 @@ else if (changes != null) { // Group changed queries by schemaKey/QueryProperty Pair key = Pair.of(schemaKey, change.getProperty()); - List> changesBySchemaProperty = changedQueries.computeIfAbsent(key, k -> new ArrayList<>()); + List> changesBySchemaProperty = changedQueries.computeIfAbsent(key, _ -> new ArrayList<>()); changesBySchemaProperty.add(change); } } @@ -322,7 +322,7 @@ public Collection postProcess(FolderImportContext ctx, Virtu List warnings = new ArrayList<>(); //validate all queries in all schemas in the container - ctx.getLogger().info("Post-processing " + getDescription()); + ctx.getLogger().info("Post-processing {}", getDescription()); if (ctx.isSkipQueryValidation()) { @@ -380,11 +380,11 @@ public Collection postProcess(FolderImportContext ctx, Virtu if (valid != null && valid) { assert validator.getTotalCount() == validator.getValidCount(); - ctx.getLogger().info(String.format("Finished validating queries: All %d passed validation.", validator.getTotalCount())); + ctx.getLogger().info("Finished validating queries: All {} passed validation.", validator.getTotalCount()); } else { - ctx.getLogger().info(String.format("Finished validating queries: %d of %d failed validation.", validator.getInvalidCount(), validator.getTotalCount())); + ctx.getLogger().info("Finished validating queries: {} of {} failed validation.", validator.getInvalidCount(), validator.getTotalCount()); } @@ -402,7 +402,7 @@ public Collection postProcess(FolderImportContext ctx, Virtu } } - ctx.getLogger().info("Done post-processing " + getDescription()); + ctx.getLogger().info("Done post-processing {}", getDescription()); return warnings; } diff --git a/query/src/org/labkey/query/QueryServiceImpl.java b/query/src/org/labkey/query/QueryServiceImpl.java index 77d62dbad87..34f80fd5459 100644 --- a/query/src/org/labkey/query/QueryServiceImpl.java +++ b/query/src/org/labkey/query/QueryServiceImpl.java @@ -398,7 +398,7 @@ private static SQLFragment getColumnInSql(@NotNull FieldKey fieldKey, Object val .append(negate ? " NOT" : "") .append(" IN (") .append(" SELECT ") - .append(t.getColumns().get(0).getValueSql("_")) + .append(t.getColumns().getFirst().getValueSql("_")) .append(" FROM ") .append(fromSql) .append(")"); @@ -490,7 +490,7 @@ private static class WhereClause extends QueryCompareClause parseResult = new SqlParser(null, null).parseExpr(expression, errors); expr = parseResult; if (!errors.isEmpty()) - throw new ConversionException(errors.get(0)); + throw new ConversionException(errors.getFirst()); } @Override @@ -526,7 +526,7 @@ protected void collectKeys(QExpr expr, Set set) QExpr methodName = null; if (expr instanceof QMethodCall) { - methodName = (QExpr) expr.childList().get(0); + methodName = (QExpr) expr.childList().getFirst(); if (null == methodName.getFieldKey()) methodName = null; } @@ -569,7 +569,7 @@ public SQLFragment toSQLFragment(Map columnMap, { if (query.getParseErrors().isEmpty()) query.getParseErrors().add(new QueryException("Unexpected error parsing where filter")); - throw query.getParseErrors().get(0); + throw query.getParseErrors().getFirst(); } return ret; } @@ -605,7 +605,7 @@ private QExpr bind(QExpr expr, Map columnMap) QExpr methodName = null; if (expr instanceof QMethodCall) { - methodName = (QExpr) expr.childList().get(0); + methodName = (QExpr) expr.childList().getFirst(); if (null == methodName.getFieldKey()) methodName = null; } @@ -872,7 +872,7 @@ private Map, QueryDefinition> getAllQueryDefs( // helper function to add a queryDef to the return map if it hasn't already been added Consumer addQueryDefToMap = (queryDef) -> { Entry key = new Pair<>(queryDef.getSchema(), queryDef.getName()); - ret.computeIfAbsent(key, (key2) -> new CustomQueryDefinitionImpl(user, container, queryDef)); + ret.computeIfAbsent(key, (_) -> new CustomQueryDefinitionImpl(user, container, queryDef)); }; // session queries have highest priority @@ -967,7 +967,7 @@ private Map, QueryDefinition> getAllQueryDefs( private void addCustomQueryDefToMap(User user, Container c, Map, QueryDefinition> map, QueryDef queryDef) { Entry key = new Pair<>(queryDef.getSchema(), queryDef.getName()); - map.computeIfAbsent(key, (key2) -> new CustomQueryDefinitionImpl(user, c, queryDef)); + map.computeIfAbsent(key, (_) -> new CustomQueryDefinitionImpl(user, c, queryDef)); } @Override @@ -1362,7 +1362,7 @@ public List getDatabaseCustomViews(@NotNull User user, @NotNull Cont { Container viewContainer = cstmView.lookupContainer(); if (viewContainer != null) - containerViews.computeIfAbsent(viewContainer, k -> new ArrayList<>()).add(cstmView); + containerViews.computeIfAbsent(viewContainer, _ -> new ArrayList<>()).add(cstmView); } for (Map.Entry> containerCstmViews: containerViews.entrySet()) @@ -1698,12 +1698,7 @@ private Map getSessionQueryMap(@NotNull HttpSession sessio } ContainerSchemaKey key = new ContainerSchemaKey(container, schemaName); - Map queries = containerQueries.get(key); - if (queries == null) - { - queries = new ConcurrentHashMap<>(); - containerQueries.put(key, queries); - } + Map queries = containerQueries.computeIfAbsent(key, _ -> new ConcurrentHashMap<>()); return queries; } @@ -2025,7 +2020,7 @@ else if (columnMap.containsKey(field.getFieldKey())) if (unresolvedColumns != null && !unresolvedColumns.isEmpty()) { - LOG.debug("Unable to resolve the following columns on table " + table.getName() + ": " + unresolvedColumns); + LOG.debug("Unable to resolve the following columns on table {}: {}", table.getName(), unresolvedColumns); for (FieldKey field : unresolvedColumns) { @@ -2096,7 +2091,7 @@ private ColumnInfo resolveFieldKey(FieldKey fieldKey, TableInfo table, Map expTable) { ColumnInfo expObjectColumn = expTable.getExpObjectColumn(); if (null != expObjectColumn) @@ -2165,7 +2160,7 @@ public Map getExternalSchemas(User user, Container c) } catch (Exception e) { - LOG.warn("Could not load schema " + def.getSourceSchemaName() + " from " + def.getDataSource(), e); + LOG.warn("Could not load schema {} from {}", def.getSourceSchemaName(), def.getDataSource(), e); } } @@ -2184,7 +2179,7 @@ public UserSchema getExternalSchema(User user, Container c, String name) } catch (Exception e) { - LOG.warn("Could not load schema " + def.getSourceSchemaName() + " from " + def.getDataSource(), e); + LOG.warn("Could not load schema {} from {}", def.getSourceSchemaName(), def.getDataSource(), e); } } @@ -2206,7 +2201,7 @@ public Map getLinkedSchemas(User user, Container c) } catch (Exception e) { - LOG.error("Error creating linked schema " + def.getUserSchemaName(), e); + LOG.error("Error creating linked schema {}", def.getUserSchemaName(), e); } } @@ -2226,7 +2221,7 @@ public UserSchema getLinkedSchema(User user, Container c, String name) } catch (Exception e) { - LOG.error("Error creating linked schema " + def.getUserSchemaName(), e); + LOG.error("Error creating linked schema {}", def.getUserSchemaName(), e); } } @@ -2258,7 +2253,7 @@ public void deleteLinkedSchema(User user, Container c, String name) } catch (Exception e) { - LOG.error("Error deleting linked schema " + name, e); + LOG.error("Error deleting linked schema {}", name, e); } } @@ -2285,7 +2280,7 @@ public TemplateSchemaType getSchemaTemplate(Container c, String templateName) } catch (XmlException | XmlValidationException | IOException e) { - LOG.error("Skipping '" + name + "' schema template file: " + e.getMessage()); + LOG.error("Skipping '{}' schema template file: {}", name, e.getMessage()); } } } @@ -2322,7 +2317,7 @@ public Map getSchemaTemplates(Container c) } catch (XmlException e) { - LOG.error("Skipping '" + name + "' schema template file: " + XmlBeansUtil.getErrorMessage(e)); + LOG.error("Skipping '{}' schema template file: {}", name, XmlBeansUtil.getErrorMessage(e)); } catch (XmlValidationException e) { @@ -2334,7 +2329,7 @@ public Map getSchemaTemplates(Container c) } catch (IOException e) { - LOG.error("Skipping '" + name + "' schema template file: " + e.getMessage()); + LOG.error("Skipping '{}' schema template file: {}", name, e.getMessage()); } } } @@ -2896,12 +2891,12 @@ class SelectBuilderImpl implements SelectBuilder this.query = query; if (!query.getParseErrors().isEmpty()) - throw query.getParseErrors().get(0); + throw query.getParseErrors().getFirst(); this.table = query.getTableInfo(); if (!query.getParseErrors().isEmpty()) - throw query.getParseErrors().get(0); + throw query.getParseErrors().getFirst(); } @Override @@ -3445,7 +3440,7 @@ public Collection getOlapHierarchies(String configId, Co if (null == descriptor) { - LOG.warn("OLAP schema descriptor not found: " + configId); + LOG.warn("OLAP schema descriptor not found: {}", configId); } else { @@ -3846,19 +3841,19 @@ public void testModuleResources() .mapToInt(MultiValuedMap::size) .sum(); - LOG.info(moduleCustomViewCount + " custom views defined in all modules"); + LOG.info("{} custom views defined in all modules", moduleCustomViewCount); int moduleQueryCount = MODULE_QUERY_DEF_CACHE.streamAllResourceMaps() .mapToInt(MultiValuedMap::size) .sum(); - LOG.info(moduleQueryCount + " module queries defined in all modules"); + LOG.info("{} module queries defined in all modules", moduleQueryCount); int moduleQueryMetadataCount = MODULE_QUERY_METADATA_DEF_CACHE.streamAllResourceMaps() .mapToInt(MultiValuedMap::size) .sum(); - LOG.info(moduleQueryMetadataCount + " module query metadata overrides defined in all modules"); + LOG.info("{} module query metadata overrides defined in all modules", moduleQueryMetadataCount); // Make sure the cache retrieves the expected number of custom views, queries, and metadata overrides from the simpletest module, if present diff --git a/query/src/org/labkey/query/QuerySnapshotDefImpl.java b/query/src/org/labkey/query/QuerySnapshotDefImpl.java index 2e1e89131e1..27d1fbcfcbd 100644 --- a/query/src/org/labkey/query/QuerySnapshotDefImpl.java +++ b/query/src/org/labkey/query/QuerySnapshotDefImpl.java @@ -142,7 +142,7 @@ public QueryDefinition getQueryDefinition(User user) } if (_queryDef == null) { - LOG.warn("Could not find query with queryDefId " + _snapshotDef.getQueryDefId() + " for query snapshot " + _snapshotDef.getName() + " in " + _snapshotDef.lookupContainer()); + LOG.warn("Could not find query with queryDefId {} for query snapshot {} in {}", _snapshotDef.getQueryDefId(), _snapshotDef.getName(), _snapshotDef.lookupContainer()); } return _queryDef == null ? null : new CustomQueryDefinitionImpl(user, getContainer(), _queryDef); } @@ -154,21 +154,21 @@ else if (_snapshotDef.getQueryTableName() != null) UserSchema schema = QueryService.get().getUserSchema(user, queryTableContainer, _snapshotDef.getSchema()); if (schema == null) { - LOG.warn("Could not find query with schema " + _snapshotDef.getSchema() + " for query snapshot " + _snapshotDef.getName() + " in " + _snapshotDef.lookupContainer()); + LOG.warn("Could not find query with schema {} for query snapshot {} in {}", _snapshotDef.getSchema(), _snapshotDef.getName(), _snapshotDef.lookupContainer()); } else { QueryDefinition result = schema.getQueryDefForTable(_snapshotDef.getQueryTableName()); if (result == null) { - LOG.warn("Could not find query with queryTableName " + _snapshotDef.getQueryTableName() + " for query snapshot " + _snapshotDef.getName() + " in " + _snapshotDef.lookupContainer()); + LOG.warn("Could not find query with queryTableName {} for query snapshot {} in {}", _snapshotDef.getQueryTableName(), _snapshotDef.getName(), _snapshotDef.lookupContainer()); } return result; } } else { - LOG.warn("Could not find query with queryTableContainer " + _snapshotDef.getQueryTableContainer() + " for query snapshot " + _snapshotDef.getName() + " in " + _snapshotDef.lookupContainer()); + LOG.warn("Could not find query with queryTableContainer {} for query snapshot {} in {}", _snapshotDef.getQueryTableContainer(), _snapshotDef.getName(), _snapshotDef.lookupContainer()); } } return null; diff --git a/query/src/org/labkey/query/QueryTestCase.jsp b/query/src/org/labkey/query/QueryTestCase.jsp index 47b7a37c520..9f0b7ae3155 100644 --- a/query/src/org/labkey/query/QueryTestCase.jsp +++ b/query/src/org/labkey/query/QueryTestCase.jsp @@ -651,7 +651,7 @@ d,seven,twelve,day,month,date,duration,guid assertNotNull(table); if (!errors.isEmpty()) - throw new RuntimeException(errors.get(0)); + throw new RuntimeException(errors.getFirst()); try (Results results = new TableSelector(table).getResults()) { @@ -1219,7 +1219,7 @@ d,seven,twelve,day,month,date,duration,guid DataIteratorContext context = new DataIteratorContext(); rTableInfo.getUpdateService().importRows(user, c, new TestDataLoader(R.getName() + hash, Rsize), context.getErrors(), null, null); if (context.getErrors().hasErrors()) - Assert.fail(context.getErrors().getRowErrors().get(0).toString()); + Assert.fail(context.getErrors().getRowErrors().getFirst().toString()); ListDefinition S = listService.createList(qtest, "S", ListDefinition.KeyType.AutoIncrementInteger); S.setKeyName("rowid"); @@ -1230,7 +1230,7 @@ d,seven,twelve,day,month,date,duration,guid context = new DataIteratorContext(); sTableInfo.getUpdateService().importRows(user, qtest, new TestDataLoader(S.getName() + hash, Rsize), context.getErrors(), null, null); if (context.getErrors().hasErrors()) - Assert.fail(context.getErrors().getRowErrors().get(0).toString()); + Assert.fail(context.getErrors().getRowErrors().getFirst().toString()); } @@ -1406,7 +1406,7 @@ d,seven,twelve,day,month,date,duration,guid } else if (!qerrors.isEmpty()) { - throw qerrors.get(0); + throw qerrors.getFirst(); } else { @@ -1443,7 +1443,7 @@ d,seven,twelve,day,month,date,duration,guid } else if (!qerrors.isEmpty()) { - throw qerrors.get(0); + throw qerrors.getFirst(); } else { @@ -1867,7 +1867,7 @@ d,seven,twelve,day,month,date,duration,guid q.parse(sql); if (!q.getParseErrors().isEmpty()) - throw q.getParseErrors().get(0); + throw q.getParseErrors().getFirst(); Map involvedColumnMap = new CaseInsensitiveHashMap<>(); for (QueryTable.TableColumn column : q.getInvolvedTableColumns()) diff --git a/query/src/org/labkey/query/QueryWebdavProvider.java b/query/src/org/labkey/query/QueryWebdavProvider.java index ab93c519a1c..e6d896ccf2d 100644 --- a/query/src/org/labkey/query/QueryWebdavProvider.java +++ b/query/src/org/labkey/query/QueryWebdavProvider.java @@ -19,7 +19,6 @@ import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.labkey.api.data.Container; -import org.labkey.api.data.RuntimeSQLException; import org.labkey.api.query.DefaultSchema; import org.labkey.api.query.QueryDefinition; import org.labkey.api.query.QuerySchema; @@ -42,7 +41,6 @@ import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; -import java.sql.SQLException; import java.util.ArrayList; import java.util.Collection; import java.util.List; @@ -126,11 +124,6 @@ public long getCreated() return Long.MIN_VALUE; } - @Override - public long getLastModified() - { - return Long.MIN_VALUE; - } } @@ -180,11 +173,6 @@ public long getCreated() return Long.MIN_VALUE; } - @Override - public long getLastModified() - { - return Long.MIN_VALUE; - } } @@ -266,15 +254,8 @@ public long copyFrom(User user, FileStream in) throws IOException { String sql = PageFlowUtil.getStreamContentsAsString(in.openInputStream()); _q.setSql(sql); - try - { - _q.save(user, _q.getDefinitionContainer()); - } - catch (SQLException sqlx) - { - throw new RuntimeSQLException(sqlx); - } - return getContentLength(); + _q.save(user, _q.getDefinitionContainer()); + return getContentLength(); } @Override diff --git a/query/src/org/labkey/query/QueryWriter.java b/query/src/org/labkey/query/QueryWriter.java index da193c89eee..b20ffd5e2a5 100644 --- a/query/src/org/labkey/query/QueryWriter.java +++ b/query/src/org/labkey/query/QueryWriter.java @@ -121,7 +121,7 @@ public void write(Container c, FolderExportContext ctx, VirtualFile root) throws } catch (XmlValidationException e) { - _log.error("Invalid meta data set on query " + query.getSchemaName() + "." + query.getName() + ". Meta data will not be exported for this query.", e); + _log.error("Invalid meta data set on query {}.{}. Meta data will not be exported for this query.", query.getSchemaName(), query.getName(), e); } } diff --git a/query/src/org/labkey/query/TableQueryDefinition.java b/query/src/org/labkey/query/TableQueryDefinition.java index db8fa75882f..131d7ec5197 100644 --- a/query/src/org/labkey/query/TableQueryDefinition.java +++ b/query/src/org/labkey/query/TableQueryDefinition.java @@ -90,21 +90,14 @@ public ActionURL urlFor(QueryAction action, Container container) TableInfo table = getTable(errors, true); if (table != null) { - switch (action) + url = switch (action) { - case insertQueryRow: - url = table.getInsertURL(container); - break; - case deleteQueryRows: - url = table.getDeleteURL(container); - break; - case executeQuery: - url = table.getGridURL(container); - break; - case importData: - url = table.getImportDataURL(container); - break; - } + case insertQueryRow -> table.getInsertURL(container); + case deleteQueryRows -> table.getDeleteURL(container); + case executeQuery -> table.getGridURL(container); + case importData -> table.getImportDataURL(container); + default -> url; + }; } if (url == AbstractTableInfo.LINK_DISABLER_ACTION_URL) @@ -188,7 +181,7 @@ public TableInfo createTable(@NotNull UserSchema schema, @Nullable List> list = doInsertUpdate(tableForm, errors, true); if (null != list && list.size() == 1) - insertedRow = list.get(0); + insertedRow = list.getFirst(); return 0 == errors.getErrorCount(); } @@ -3586,7 +3565,7 @@ public ApiResponse execute(APIQueryForm form, BindException errors) { List qpes = view.getParseErrors(); if (!qpes.isEmpty()) - throw qpes.get(0); + throw qpes.getFirst(); throw new NotFoundException(form.getQueryName()); } @@ -3962,10 +3941,10 @@ private SqlSelector getDistinctSql(TableInfo table, ContainerFilterQueryForm for return null; } - ColumnInfo col = columns.get(settings.getFieldKeys().get(0)); + ColumnInfo col = columns.get(settings.getFieldKeys().getFirst()); if (col == null) { - errors.reject(ERROR_MSG, "\"" + settings.getFieldKeys().get(0).getName() + "\" is not a valid column."); + errors.reject(ERROR_MSG, "\"" + settings.getFieldKeys().getFirst().getName() + "\" is not a valid column."); return null; } @@ -3994,7 +3973,7 @@ private SqlSelector getDistinctSql(TableInfo table, ContainerFilterQueryForm for // Regenerate the column since the alias may have changed after call to getSelectSQL() columns = service.getColumns(table, settings.getFieldKeys()); - var colGetAgain = columns.get(settings.getFieldKeys().get(0)); + var colGetAgain = columns.get(settings.getFieldKeys().getFirst()); // I don't believe the above comment, so here's an assert assert(colGetAgain.getAlias().equals(col.getAlias())); @@ -4063,7 +4042,7 @@ public void validateForm(QueryForm form, Errors errors) if (null == fieldKeys || fieldKeys.size() != 1) errors.reject(ERROR_MSG, "GetColumnSummaryStats requires that only one column be requested."); else - _colFieldKey = fieldKeys.get(0); + _colFieldKey = fieldKeys.getFirst(); } @Override @@ -4172,7 +4151,7 @@ protected void initRequest(QueryForm form) throws ServletException List qpe = new ArrayList<>(); TableInfo t = query.getTable(form.getSchema(), qpe, true); if (!qpe.isEmpty()) - throw qpe.get(0); + throw qpe.getFirst(); if (null != t) setTarget(t); _auditBehaviorType = form.getAuditBehavior(); @@ -4387,7 +4366,7 @@ public List> saveRows(QueryUpdateService qus, List { @Override - public Object execute(SqlForm form, BindException errors) throws ServletException + public Object execute(SqlForm form, BindException errors) throws ServletException, SQLException, IOException { String schemaString = form.getSchema(); SchemaKey schemaKey = null == schemaString ? new SchemaKey(null,"core") : SchemaKey.decode(schemaString); @@ -223,10 +224,6 @@ public Object execute(SqlForm form, BindException errors) throws ServletExceptio { errors.reject(ERROR_MSG, x.getMessage()); } - catch (SQLException|IOException x) - { - throw new ServletException(x); - } return null; } } diff --git a/query/src/org/labkey/query/data/ExternalSchemaTable.java b/query/src/org/labkey/query/data/ExternalSchemaTable.java index 51bbf884d6b..7a4f0deeb81 100644 --- a/query/src/org/labkey/query/data/ExternalSchemaTable.java +++ b/query/src/org/labkey/query/data/ExternalSchemaTable.java @@ -70,7 +70,7 @@ public SimpleUserSchema.SimpleTable init() } catch (IllegalArgumentException e) { - _logger.error("Malformed XML for external table: " + getSchema() + "." + getName(), e); + _logger.error("Malformed XML for external table: {}.{}", getSchema(), getName(), e); //otherwise ignore malformed XML } return this; diff --git a/query/src/org/labkey/query/jdbc/QueryDriver.java b/query/src/org/labkey/query/jdbc/QueryDriver.java index 83431d6d577..6f559591317 100644 --- a/query/src/org/labkey/query/jdbc/QueryDriver.java +++ b/query/src/org/labkey/query/jdbc/QueryDriver.java @@ -33,8 +33,6 @@ import java.util.Properties; import java.util.logging.Logger; -import static org.labkey.api.util.IntegerUtils.asInteger; - /** * User: matthewb * Date: 4/25/12 diff --git a/query/src/org/labkey/query/olap/BitSetQueryImpl.java b/query/src/org/labkey/query/olap/BitSetQueryImpl.java index 6ebb6a8097b..e41f9fbf1b4 100644 --- a/query/src/org/labkey/query/olap/BitSetQueryImpl.java +++ b/query/src/org/labkey/query/olap/BitSetQueryImpl.java @@ -15,7 +15,6 @@ */ package org.labkey.query.olap; -import org.apache.commons.lang3.Strings; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.jetbrains.annotations.NotNull; @@ -229,7 +228,7 @@ void initDistinctMeasure() assert ((CachedCube._NamedList)h.getLevels()).isReadOnly(); qq.countDistinctLevel = h.getLevels().get(h.getName()); if (null == qq.countDistinctLevel) - qq.countDistinctLevel = h.getLevels().get(h.getLevels().size() - 1); + qq.countDistinctLevel = h.getLevels().getLast(); } } @@ -508,7 +507,7 @@ void toMdxSet(StringBuilder sb) { if (results.size() == 1) { - results.get(0).toMdxSet(sb); + results.getFirst().toMdxSet(sb); return; } sb.append(" UNION("); @@ -562,7 +561,7 @@ void toMdxSet(StringBuilder sb) { if (results.size() == 1) { - results.get(0).toMdxSet(sb); + results.getFirst().toMdxSet(sb); } else if (results.size() == 2) { @@ -582,7 +581,7 @@ else if (results.size() == 2) public String toString() { if (results.size() == 1) - return results.get(0).toString(); + return results.getFirst().toString(); StringBuilder sb = new StringBuilder(); String x = ""; @@ -786,7 +785,7 @@ else if (null != expr.sql || null != expr.getData || null != expr.getDataCDS) Result processExpr(QubeQuery.QubeExpr expr) throws SQLException { while (null != expr && null != expr.arguments && expr.arguments.size() == 1 && expr.op != QubeQuery.OP.MEMBERS) - expr = expr.arguments.get(0); + expr = expr.arguments.getFirst(); if (null == expr) throw new IllegalArgumentException("Missing/malformed expression"); @@ -805,31 +804,14 @@ Result processExpr(QubeQuery.QubeExpr expr) throws SQLException results.add(processExpr(in)); } - switch (expr.op) - { - case CROSSJOIN: - case XINTERSECT: - { - return crossjoin(expr.op, results); - } - case INTERSECT: - { - return intersect(expr.op, results); - } - case UNION: + return switch (expr.op) { - return union(expr.op, results); - } - case EXCEPT: - { - return except(expr.op, results); - } - default: - case MEMBERS: - { - throw new IllegalStateException(); - } - } + case CROSSJOIN, XINTERSECT -> crossjoin(expr.op, results); + case INTERSECT -> intersect(expr.op, results); + case UNION -> union(expr.op, results); + case EXCEPT -> except(expr.op, results); + default -> throw new IllegalStateException(); + }; } @@ -851,10 +833,10 @@ boolean setContainsAllLevelMembers(@NotNull MemberSet set, @NotNull Level l) thr Member getAllNullMember(Hierarchy h, int depth) throws OlapException { - if (1 != h.getRootMembers().size() || !h.getRootMembers().get(0).isAll()) + if (1 != h.getRootMembers().size() || !h.getRootMembers().getFirst().isAll()) return null; - Member ret = h.getRootMembers().get(0); + Member ret = h.getRootMembers().getFirst(); while (ret.getLevel().getDepth() < depth) { ret = ret.getChildMembers().get("#null"); @@ -1307,7 +1289,7 @@ Result union(OP op, Collection resultsIN) throws OlapException if (results.isEmpty()) return new EmptyResult(); if (results.size() == 1) - return results.get(0); + return results.getFirst(); // if all members are part of the same hierarchy just return a simple MemberSetResult // if there is more than one hierarchy involved, return a UnionResult @@ -1994,7 +1976,7 @@ public MemberSet membersQuery(MemberSetResult outer, MemberSetResult sub) throws } // add in the all member if (!union.isEmpty()) - union.add(outer.hierarchy.getLevels().get(0).getMembers().get(0)); + union.add(outer.hierarchy.getLevels().getFirst().getMembers().getFirst()); return union; } @@ -2159,7 +2141,7 @@ public MemberSet sqlMembersQuery(Level level, String sql) throws SQLException return set; int depth = level.getDepth(); - CachedCube._Member all = (CachedCube._Member)level.getHierarchy().getLevels().get(0).getMembers().get(0); + CachedCube._Member all = (CachedCube._Member)level.getHierarchy().getLevels().getFirst().getMembers().getFirst(); MemberSet ret = new MemberSet(); try (ResultSet rs = execute(serviceUser, sql)) @@ -2209,7 +2191,7 @@ public MemberSet sqlMembersQuery(Level level, String sql) throws SQLException if (null == child) { - _log.info("Child not found: parent=" + m.getUniqueName() + " key=" + String.valueOf(key)); + _log.info("Child not found: parent={} key={}", m.getUniqueName(), String.valueOf(key)); continue resultLoop; } m = child; @@ -2408,19 +2390,19 @@ public Member getParentMember() @Override public Level getLevel() { - return cube.getMeasures().get(0).getLevel(); + return cube.getMeasures().getFirst().getLevel(); } @Override public Hierarchy getHierarchy() { - return cube.getMeasures().get(0).getHierarchy(); + return cube.getMeasures().getFirst().getHierarchy(); } @Override public Dimension getDimension() { - return cube.getMeasures().get(0).getDimension(); + return cube.getMeasures().getFirst().getDimension(); } @Override diff --git a/query/src/org/labkey/query/olap/MdxQueryImpl.java b/query/src/org/labkey/query/olap/MdxQueryImpl.java index 9707361aa60..3fdb2f633cb 100644 --- a/query/src/org/labkey/query/olap/MdxQueryImpl.java +++ b/query/src/org/labkey/query/olap/MdxQueryImpl.java @@ -122,7 +122,7 @@ else if (null != membersDef.hierarchy) } else if (null != membersDef.membersSet && !membersDef.membersSet.isEmpty()) { - Level l = null != membersDef.level ? membersDef.level : membersDef.hierarchy.getLevels().get(membersDef.hierarchy.getLevels().size()-1); + Level l = null != membersDef.level ? membersDef.level : membersDef.hierarchy.getLevels().getLast(); return new _MDX(FN.MemberSet, l, membersDef.membersSet.toArray()); } else @@ -132,7 +132,7 @@ else if (null != membersDef.membersSet && !membersDef.membersSet.isEmpty()) errors.reject(SpringActionController.ERROR_MSG, "level or hiearchy must be specified"); throw errors; } - Level l = null != membersDef.level ? membersDef.level : membersDef.hierarchy.getLevels().get(membersDef.hierarchy.getLevels().size()-1); + Level l = null != membersDef.level ? membersDef.level : membersDef.hierarchy.getLevels().getLast(); _MDX levelExpr = new _MDX(FN.MemberSet, l, new Object[]{l.getUniqueName() + ".members"}); if (null == membersDef.membersQuery) return levelExpr; @@ -152,11 +152,11 @@ _MDX _toIntersectExpr(QubeExpr expr) throws BindException } if (sets.size() == 1) { - return (_MDX) sets.get(0); + return (_MDX) sets.getFirst(); } else { - Level level = ((_MDX)sets.get(0)).level; + Level level = ((_MDX)sets.getFirst()).level; for (Object set : sets) { Level next = ((_MDX) set).level; @@ -185,12 +185,12 @@ _MDX _toSmartCrossJoinExpr(QubeExpr expr) throws BindException { List arr = setsByLevel.get(k); if (arr.size() == 1) - sets.add(arr.get(0)); + sets.add(arr.getFirst()); else - sets.add(new _MDX(FN.Intersect, ((_MDX) arr.get(0)).level, arr)); + sets.add(new _MDX(FN.Intersect, ((_MDX) arr.getFirst()).level, arr)); } if (sets.size() == 1) - return (_MDX)sets.get(0); + return (_MDX)sets.getFirst(); else return new _MDX(FN.CrossJoin, sets); } @@ -205,7 +205,7 @@ _MDX _toCrossJoinExpr(QubeExpr expr) throws BindException sets.add(set); } if (sets.size() == 1) - return (_MDX)sets.get(0); + return (_MDX)sets.getFirst(); else return new _MDX(FN.CrossJoin, sets); } @@ -236,7 +236,7 @@ else if (null == level || null == next || !level.getUniqueName().equals(next.get } } if (sets.size() == 1) - return (_MDX)sets.get(0); + return (_MDX)sets.getFirst(); else return new _MDX(FN.Union, level, sets); } @@ -255,17 +255,19 @@ private _MDX _processExpr(QubeExpr expr) throws BindException // else // op = defaultOperator || "MEMBERS"; - switch (expr.op) + return switch (expr.op) { - case UNION: return _toUnionExpr(expr); - case MEMBERS: return _toMembersExpr(expr); - case INTERSECT: return _toIntersectExpr(expr); - case CROSSJOIN: return _toCrossJoinExpr(expr); - case XINTERSECT:return _toSmartCrossJoinExpr(expr); - default: + case UNION -> _toUnionExpr(expr); + case MEMBERS -> _toMembersExpr(expr); + case INTERSECT -> _toIntersectExpr(expr); + case CROSSJOIN -> _toCrossJoinExpr(expr); + case XINTERSECT -> _toSmartCrossJoinExpr(expr); + default -> + { errors.reject(SpringActionController.ERROR_MSG, "unexpected operator: " + expr.op); throw errors; - } + } + }; } diff --git a/query/src/org/labkey/query/olap/MemberSet.java b/query/src/org/labkey/query/olap/MemberSet.java index b73e84bb90a..4d22b891c9e 100644 --- a/query/src/org/labkey/query/olap/MemberSet.java +++ b/query/src/org/labkey/query/olap/MemberSet.java @@ -16,8 +16,8 @@ package org.labkey.query.olap; import org.apache.commons.collections4.iterators.IteratorChain; -import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; +import org.jetbrains.annotations.NotNull; import org.junit.Assert; import org.junit.Test; import org.labkey.api.cache.CacheManager; @@ -588,13 +588,13 @@ public Iterator iterator() } @Override - public @NotNull Object[] toArray() + public @NotNull Object @NotNull [] toArray() { throw new UnsupportedOperationException(); } @Override - public @NotNull T[] toArray(T @NotNull [] a) + public @NotNull T @NotNull [] toArray(T @NotNull [] a) { throw new UnsupportedOperationException(); } @@ -738,17 +738,13 @@ static class MockOlapProxy implements InvocationHandler @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { - switch (method.getName()) + return switch (method.getName()) { - case "getUniqueName": - return getUniqueName(); - case "getOrdinal": - return getOrdinal(); - case "equals": - throw new IllegalStateException("equals doesn't work use getUniqueName().equals(...)"); - default: - return null; - } + case "getUniqueName" -> getUniqueName(); + case "getOrdinal" -> getOrdinal(); + case "equals" -> throw new IllegalStateException("equals doesn't work use getUniqueName().equals(...)"); + default -> null; + }; } String getUniqueName() diff --git a/query/src/org/labkey/query/olap/QubeCellSet.java b/query/src/org/labkey/query/olap/QubeCellSet.java index 18683842309..7074498de98 100644 --- a/query/src/org/labkey/query/olap/QubeCellSet.java +++ b/query/src/org/labkey/query/olap/QubeCellSet.java @@ -15,6 +15,7 @@ */ package org.labkey.query.olap; +import org.jetbrains.annotations.NotNull; import org.labkey.api.util.MemTracker; import org.olap4j.AllocationPolicy; import org.olap4j.Axis; @@ -88,7 +89,7 @@ public class QubeCellSet implements CellSet _axes.add(new _MeasureAxis(Axis.ROWS, measure)); else _axes.add(new _MemberAxis(Axis.ROWS, rows)); - _columnCount = _axes.get(0).getPositionCount(); + _columnCount = _axes.getFirst().getPositionCount(); _results = results; assert MemTracker.getInstance().put(this); } @@ -1430,7 +1431,7 @@ public int getPositionCount() } @Override - public ListIterator iterator() + public @NotNull ListIterator iterator() { return (Collections.unmodifiableList(_positions)).listIterator(); } diff --git a/query/src/org/labkey/query/olap/QubeQuery.java b/query/src/org/labkey/query/olap/QubeQuery.java index 24c33f251cd..6b2778ed62f 100644 --- a/query/src/org/labkey/query/olap/QubeQuery.java +++ b/query/src/org/labkey/query/olap/QubeQuery.java @@ -169,7 +169,7 @@ void initMetadataCache() { if (d.getHierarchies().size() == 1) { - Hierarchy h = d.getHierarchies().get(0); + Hierarchy h = d.getHierarchies().getFirst(); _cubeHierarchyMap.put(d.getName(),h); _cubeHierarchyMap.put(d.getUniqueName(), h); } diff --git a/query/src/org/labkey/query/olap/ServerManager.java b/query/src/org/labkey/query/olap/ServerManager.java index dbddcfc40cb..7e4d2054ec4 100644 --- a/query/src/org/labkey/query/olap/ServerManager.java +++ b/query/src/org/labkey/query/olap/ServerManager.java @@ -369,7 +369,7 @@ private static ServerReferenceCount getServer(Container c, User user) LOG.debug(sb.toString()); RepositoryContentFinder rcf = new StringRepositoryContentFinder(sb.toString()); s = MondrianServer.createWithRepository(rcf, new _CatalogLocator(c)); - LOG.debug("Create new Mondrian server: " + c.getPath() + " " + s.toString()); + LOG.debug("Create new Mondrian server: {} {}", c.getPath(), s.toString()); ref = new ServerReferenceCount(s, c); SERVERS.put(getServerCacheKey(c), ref); } @@ -428,7 +428,7 @@ public static String warmCube(User user, Container c, String schemaName, String if (null == cube) return "Error: No cached cube for " + cubeName + " in container " + fullContainerPath; long e = System.currentTimeMillis(); - LOG.debug(DateUtil.formatDuration(e-s) + " CUBE DEFINITION"); + LOG.debug("{} CUBE DEFINITION", DateUtil.formatDuration(e - s)); JSONArray jsonOnRows = new JSONArray(); JSONObject jsonQuery = new JSONObject(); @@ -444,7 +444,7 @@ public static String warmCube(User user, Container c, String schemaName, String { try { - Level l = h.getLevels().get(h.getLevels().size()-1); + Level l = h.getLevels().getLast(); Map map = new HashMap<>(); map.put("hierarchy", h.getUniqueName()); @@ -461,7 +461,7 @@ public static String warmCube(User user, Container c, String schemaName, String s = System.currentTimeMillis(); execCountDistinct(c, null, sd, conn, cube, jsonQuery, getDummyBindException()); e = System.currentTimeMillis(); - LOG.info(DateUtil.formatDuration(e - s) + " " + jsonQuery); + LOG.info("{} {}", DateUtil.formatDuration(e - s), jsonQuery); } @@ -476,7 +476,7 @@ public static String warmCube(User user, Container c, String schemaName, String s = System.currentTimeMillis(); execCountDistinct(c, null, sd, conn, cube, jsonQuery, getDummyBindException()); e = System.currentTimeMillis(); - LOG.info(DateUtil.formatDuration(e - s) + " " + jsonQuery); + LOG.info("{} {}", DateUtil.formatDuration(e - s), jsonQuery); jsonQuery.remove("countDistinctLevel"); } @@ -484,7 +484,7 @@ public static String warmCube(User user, Container c, String schemaName, String catch (Exception ignore) { - LOG.warn("Error trying to warm the " + cubeName + " in container " + fullContainerPath, ignore); + LOG.warn("Error trying to warm the {} in container {}", cubeName, fullContainerPath, ignore); } } } @@ -634,7 +634,7 @@ static void invalidateCaches(Container c) static void closeServer(MondrianServer s, @NotNull Container container) { - LOG.debug("Shutdown Mondrian server: " + s.toString()); + LOG.debug("Shutdown Mondrian server: {}", s.toString()); try { @@ -649,7 +649,7 @@ static void closeServer(MondrianServer s, @NotNull Container container) } catch (Exception x) { - LOG.debug("Shutdown Mondrian server flush cache failed: " + s); + LOG.debug("Shutdown Mondrian server flush cache failed: {}", s); LOG.debug(x.getMessage()); } @@ -768,13 +768,13 @@ MondrianServer get() void increment() { super.increment(); - LOG.debug("increment reference: " + counter.get() + " " + _server.toString()); + LOG.debug("increment reference: {} {}", counter.get(), _server.toString()); } @Override void decrement() { - LOG.debug("decrement reference: " + (counter.get() - 1) + " " + _server.toString()); + LOG.debug("decrement reference: {} {}", counter.get() - 1, _server.toString()); super.decrement(); } @@ -901,7 +901,7 @@ public void testModuleResourceCache() .mapToInt(Map::size) .sum(); - LOG.info(descriptorCount + " OLAP descriptors defined in all modules"); + LOG.info("{} OLAP descriptors defined in all modules", descriptorCount); // Make sure the cache retrieves the test OLAP descriptor from this module diff --git a/query/src/org/labkey/query/olap/metadata/CachedCube.java b/query/src/org/labkey/query/olap/metadata/CachedCube.java index 9dfb62dbe52..c841a769e03 100644 --- a/query/src/org/labkey/query/olap/metadata/CachedCube.java +++ b/query/src/org/labkey/query/olap/metadata/CachedCube.java @@ -15,6 +15,7 @@ */ package org.labkey.query.olap.metadata; +import org.jetbrains.annotations.NotNull; import org.labkey.api.collections.ArrayListMap; import org.labkey.api.collections.CaseInsensitiveHashMap; import org.labkey.api.data.JdbcType; @@ -146,7 +147,7 @@ public NamedList getHierarchies() public List getMeasures() { Dimension measures = getDimensions().get("Measures"); - Level l = measures.getHierarchies().get(0).getLevels().get(0); + Level l = measures.getHierarchies().getFirst().getLevels().getFirst(); try { return (List)(List)l.getMembers(); @@ -283,7 +284,7 @@ public Member getDefaultMember() @Override public NamedList getRootMembers() throws OlapException { - return (NamedList)getLevels().get(0).getMembers(); + return (NamedList)getLevels().getFirst().getMembers(); } } @@ -1033,7 +1034,7 @@ public _Member put(Object key, _Member value) } @Override - public Set> entrySet() + public @NotNull Set> entrySet() { return impl.entrySet(); } diff --git a/query/src/org/labkey/query/olap/metadata/RolapCachedCubeFactory.java b/query/src/org/labkey/query/olap/metadata/RolapCachedCubeFactory.java index a2ed9d5b640..d98b0b7fcec 100644 --- a/query/src/org/labkey/query/olap/metadata/RolapCachedCubeFactory.java +++ b/query/src/org/labkey/query/olap/metadata/RolapCachedCubeFactory.java @@ -135,7 +135,7 @@ void generateMeasuresDimension(CachedCube cube) */ void generateHierarchyMembers(CachedCube cube, HierarchyDef hdef, CachedCube._Hierarchy h) throws SQLException { - CachedCube._Level allLevel = (CachedCube._Level)h.getLevels().get(0); + CachedCube._Level allLevel = (CachedCube._Level)h.getLevels().getFirst(); CachedCube._Member allMember = new CachedCube._Member(cube, allLevel, Member.Type.ALL); allLevel.members.add(allMember); @@ -239,7 +239,7 @@ void generateHierarchyMembers(CachedCube cube, HierarchyDef hdef, CachedCube._Hi } // add #NOTNULL members - CachedCube._Member parent = (CachedCube._Member)levelList.get(0).getMembers().get(0); + CachedCube._Member parent = (CachedCube._Member)levelList.getFirst().getMembers().getFirst(); for (int l = 1; l < levelCount; l++) { CachedCube._Level level = levelList.get(l); @@ -301,7 +301,7 @@ static void orderChildMembers(CachedCube._NamedList continue; m.childMembers.sort(MEMBER_COMPARATOR); // We also create a map using the KEY value - JdbcType childType = ((CachedCube._Member) m.childMembers.get(0)).level.jdbcType; + JdbcType childType = ((CachedCube._Member) m.childMembers.getFirst()).level.jdbcType; m._keyMap = CachedCube.KeyMap.create(childType, m.childMembers); } } diff --git a/query/src/org/labkey/query/olap/rolap/RolapCubeDef.java b/query/src/org/labkey/query/olap/rolap/RolapCubeDef.java index 647fc6355b1..cf36e32771f 100644 --- a/query/src/org/labkey/query/olap/rolap/RolapCubeDef.java +++ b/query/src/org/labkey/query/olap/rolap/RolapCubeDef.java @@ -122,7 +122,7 @@ public Map getAnnotations() public String getMembersSQL(HierarchyDef hdef) { - LevelDef lowest = hdef.levels.get(hdef.levels.size()-1); + LevelDef lowest = hdef.levels.getLast(); String selectColumns = lowest.getAllColumnsSQL(null); String joins; @@ -679,7 +679,7 @@ public Map getAnnotations() @Override public String getTableName() { - return getLevels().get(0).getTableName(); + return getLevels().getFirst().getTableName(); } } @@ -911,7 +911,7 @@ public JdbcType computeKeyType(ResultSet rs) throws SQLException JdbcType j = JdbcType.valueOf(columnType); if (j.isText() != jdbcType.isText() || j.isDateOrTime() != jdbcType.isDateOrTime()) { - LogManager.getLogger(RolapCubeDef.class).info("jdbc types do not match, expected: " + jdbcType + " found: " + j + ". Alias: \"" + keyAlias + "\""); + LogManager.getLogger(RolapCubeDef.class).info("jdbc types do not match, expected: {} found: {}. Alias: \"{}\"", jdbcType, j, keyAlias); } return jdbcType; } diff --git a/query/src/org/labkey/query/olap/rolap/RolapReader.java b/query/src/org/labkey/query/olap/rolap/RolapReader.java index d7e9a5a2b0c..b987e3934cd 100644 --- a/query/src/org/labkey/query/olap/rolap/RolapReader.java +++ b/query/src/org/labkey/query/olap/rolap/RolapReader.java @@ -303,7 +303,7 @@ private void parseHierarchy(Node hierNode) break; } } - RolapCubeDef.LevelDef lowest = _currentHier.levels.get(_currentHier.levels.size()-1); + RolapCubeDef.LevelDef lowest = _currentHier.levels.getLast(); lowest.isLeaf = true; _currentDim.hierarchies.add(_currentHier); diff --git a/query/src/org/labkey/query/olap/rolap/RolapTestCase.java b/query/src/org/labkey/query/olap/rolap/RolapTestCase.java index 1b17a184e6e..17e3ac5190e 100644 --- a/query/src/org/labkey/query/olap/rolap/RolapTestCase.java +++ b/query/src/org/labkey/query/olap/rolap/RolapTestCase.java @@ -137,7 +137,7 @@ public void testCachedCube() throws Exception Hierarchy hParticipant = cube.getHierarchies().get("Participant"); assertNotNull(hParticipant); - Level lAll = hParticipant.getLevels().get(0); + Level lAll = hParticipant.getLevels().getFirst(); assertNotNull(lAll); assertEquals("(All)", lAll.getName()); Level lParticipant = hParticipant.getLevels().get(1); @@ -196,10 +196,10 @@ private Map oneAxisQuery(JSONObject query) throws Exception private Map oneColumnResult(CellSet cs) { Map ret = new CaseInsensitiveTreeMap<>(); - Position colPosition = cs.getAxes().get(0).getPositions().get(0); + Position colPosition = cs.getAxes().get(0).getPositions().getFirst(); for (Position rowPosition : cs.getAxes().get(1).getPositions()) { - Member m = rowPosition.getMembers().get(0); + Member m = rowPosition.getMembers().getFirst(); Cell cell = cs.getCell(colPosition, rowPosition); Object v = cell.getValue(); Integer i = null==v ? null : ((Number)v).intValue(); diff --git a/query/src/org/labkey/query/olap/rolap/RolapTestSchema.java b/query/src/org/labkey/query/olap/rolap/RolapTestSchema.java index ec3cacbf703..c0dcdd20923 100644 --- a/query/src/org/labkey/query/olap/rolap/RolapTestSchema.java +++ b/query/src/org/labkey/query/olap/rolap/RolapTestSchema.java @@ -49,15 +49,15 @@ public RolapTestSchema(User user, Container c) @Override public TableInfo createTable(String name, ContainerFilter cf) { - switch (name.toLowerCase()) + return switch (name.toLowerCase()) { - case "fact": return createFact(); - case "study": return createStudy(); - case "participant": return createParticipant(); - case "visit": return createVisit(); - case "assay": return createAssay(); - } - return null; + case "fact" -> createFact(); + case "study" -> createStudy(); + case "participant" -> createParticipant(); + case "visit" -> createVisit(); + case "assay" -> createAssay(); + default -> null; + }; } diff --git a/query/src/org/labkey/query/persist/QueryManager.java b/query/src/org/labkey/query/persist/QueryManager.java index a9a80b692bc..a7ce8996a35 100644 --- a/query/src/org/labkey/query/persist/QueryManager.java +++ b/query/src/org/labkey/query/persist/QueryManager.java @@ -585,17 +585,17 @@ private boolean checkChanges(QueryChangeListener.QueryProperty property, Collect { if (change.getProperty() != property) { - _log.error(String.format("Property '%s' doesn't match change property '%s'", property, change.getProperty())); + _log.error("Property '{}' doesn't match change property '{}'", property, change.getProperty()); valid = false; } if (change.getOldValue() != null && !property.getPropertyClass().isInstance(change.getOldValue())) { - _log.error(String.format("Old value '%s' isn't an instance of property '%s' class '%s'", change.getOldValue(), property, property.getPropertyClass())); + _log.error("Old value '{}' isn't an instance of property '{}' class '{}'", change.getOldValue(), property, property.getPropertyClass()); valid = false; } if (change.getNewValue() != null && !property.getPropertyClass().isInstance(change.getNewValue())) { - _log.error(String.format("New value '%s' isn't an instance of property '%s' class '%s'", change.getNewValue(), property, property.getPropertyClass())); + _log.error("New value '{}' isn't an instance of property '{}' class '{}'", change.getNewValue(), property, property.getPropertyClass()); valid = false; } } @@ -1119,9 +1119,9 @@ private static Map getSchemaCustomViewCounts(String schema) private static Long percentile(double percentile, List sortedCounts) { if (percentile <= 0.01) - return sortedCounts.get(0); + return sortedCounts.getFirst(); if (percentile >= 99.99) - return sortedCounts.get(sortedCounts.size() - 1); + return sortedCounts.getLast(); return sortedCounts.get((int) Math.round(percentile / 100.0 * (sortedCounts.size() - 1))); } diff --git a/query/src/org/labkey/query/reports/ModuleReportCache.java b/query/src/org/labkey/query/reports/ModuleReportCache.java index f0d681ecdb8..efd49cccfbd 100644 --- a/query/src/org/labkey/query/reports/ModuleReportCache.java +++ b/query/src/org/labkey/query/reports/ModuleReportCache.java @@ -227,7 +227,7 @@ public void testModuleResourceCache() .mapToInt(ReportCollections::size) .sum(); - LOG.info(descriptorCount + " report descriptors defined in all modules"); + LOG.info("{} report descriptors defined in all modules", descriptorCount); // Make sure the cache retrieves the expected number of report descriptors from a couple test modules, if present diff --git a/query/src/org/labkey/query/reports/ReportAndDatasetChangeDigestProviderImpl.java b/query/src/org/labkey/query/reports/ReportAndDatasetChangeDigestProviderImpl.java index 9ccb1896997..690189682c9 100644 --- a/query/src/org/labkey/query/reports/ReportAndDatasetChangeDigestProviderImpl.java +++ b/query/src/org/labkey/query/reports/ReportAndDatasetChangeDigestProviderImpl.java @@ -42,7 +42,6 @@ import java.util.ArrayList; import java.util.Collections; import java.util.Date; -import java.util.HashMap; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; diff --git a/query/src/org/labkey/query/reports/ReportImporter.java b/query/src/org/labkey/query/reports/ReportImporter.java index e6086e7bac9..f0664d467f6 100644 --- a/query/src/org/labkey/query/reports/ReportImporter.java +++ b/query/src/org/labkey/query/reports/ReportImporter.java @@ -60,7 +60,7 @@ public void process(PipelineJob job, FolderImportContext ctx, VirtualFile root) if (null != job) job.setStatus("IMPORT " + getDescription()); - ctx.getLogger().info("Loading " + getDescription()); + ctx.getLogger().info("Loading {}", getDescription()); int count = 0; @@ -78,7 +78,7 @@ public void process(PipelineJob job, FolderImportContext ctx, VirtualFile root) if (ReportService.get().importReport(ctx, reportsDir.getXmlBean(reportFileName), reportsDir, reportFileName) != null) count++; else - ctx.getLogger().warn("Unable to import report file: " + reportFileName); + ctx.getLogger().warn("Unable to import report file: {}", reportFileName); } catch (XmlValidationException e) { @@ -86,8 +86,8 @@ public void process(PipelineJob job, FolderImportContext ctx, VirtualFile root) } } - ctx.getLogger().info(StringUtilsLabKey.pluralize(count, "report") + " imported"); - ctx.getLogger().info("Done importing " + getDescription()); + ctx.getLogger().info("{} imported", StringUtilsLabKey.pluralize(count, "report")); + ctx.getLogger().info("Done importing {}", getDescription()); } } diff --git a/query/src/org/labkey/query/reports/ReportQueryChangeListener.java b/query/src/org/labkey/query/reports/ReportQueryChangeListener.java index 57ff5483034..84a360bd3dc 100644 --- a/query/src/org/labkey/query/reports/ReportQueryChangeListener.java +++ b/query/src/org/labkey/query/reports/ReportQueryChangeListener.java @@ -15,7 +15,6 @@ */ package org.labkey.query.reports; -import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.Strings; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; @@ -182,7 +181,7 @@ private void _updateReportQueryNameChange(User user, Container container, Schema } else { - logger.warn("The owner of the '" + descriptor.getReportName() + "' report does not exist: UserId " + descriptor.getModifiedBy()); + logger.warn("The owner of the '{}' report does not exist: UserId {}", descriptor.getReportName(), descriptor.getModifiedBy()); } } } @@ -254,7 +253,7 @@ private void _updateReportSchemaNameChange(User user, Container container, Colle } else { - logger.warn("The owner of the '" + descriptor.getReportName() + "' report does not exist: UserId " + descriptor.getModifiedBy()); + logger.warn("The owner of the '{}' report does not exist: UserId {}", descriptor.getReportName(), descriptor.getModifiedBy()); } } } diff --git a/query/src/org/labkey/query/reports/ReportServiceImpl.java b/query/src/org/labkey/query/reports/ReportServiceImpl.java index 392bf647df9..f51daf758c9 100644 --- a/query/src/org/labkey/query/reports/ReportServiceImpl.java +++ b/query/src/org/labkey/query/reports/ReportServiceImpl.java @@ -167,7 +167,7 @@ public void registerDescriptor(ReportDescriptor descriptor) throw new IllegalArgumentException("Invalid descriptor instance"); if (null != _descriptors.putIfAbsent(descriptor.getDescriptorType(), descriptor.getClass())) - _log.warn("Descriptor type : " + descriptor.getDescriptorType() + " has previously been registered."); + _log.warn("Descriptor type : {} has previously been registered.", descriptor.getDescriptorType()); } @Override @@ -920,8 +920,7 @@ public Report importReport(FolderImportContext ctx, XmlObject reportXml, Virtual Dataset dataset = study.getDatasetByLabel(queryName); if (dataset != null && !dataset.getName().equals(dataset.getLabel())) { - ctx.getLogger().error("Report \"" + xmlFileName + "\" could not be imported. Its queryName is \"" + queryName + - ",\" which is a dataset label. Dataset labels are no longer supported; queryName should be set to the dataset name (\"" + dataset.getName() + "\") instead."); + ctx.getLogger().error("Report \"{}\" could not be imported. Its queryName is \"{},\" which is a dataset label. Dataset labels are no longer supported; queryName should be set to the dataset name (\"{}\") instead.", xmlFileName, queryName, dataset.getName()); return null; } } diff --git a/query/src/org/labkey/query/reports/ReportWebdavProvider.java b/query/src/org/labkey/query/reports/ReportWebdavProvider.java index 27990c04cfe..5d422f1f713 100644 --- a/query/src/org/labkey/query/reports/ReportWebdavProvider.java +++ b/query/src/org/labkey/query/reports/ReportWebdavProvider.java @@ -27,7 +27,6 @@ import org.labkey.api.util.StringUtilsLabKey; import org.labkey.api.webdav.AbstractDocumentResource; import org.labkey.api.webdav.AbstractWebdavResourceCollection; -import org.labkey.api.webdav.WebdavResolver; import org.labkey.api.webdav.WebdavResolverImpl; import org.labkey.api.webdav.WebdavResource; import org.labkey.api.webdav.WebdavService; @@ -37,7 +36,6 @@ import java.io.InputStream; import java.util.ArrayList; import java.util.Collection; -import java.util.Collections; import java.util.HashMap; import java.util.Map; import java.util.Set; @@ -133,12 +131,6 @@ public boolean exists() { return true; } - - @Override - public boolean isFile() - { - return false; - } } public static class ViewResource extends AbstractDocumentResource @@ -156,25 +148,12 @@ public static class ViewResource extends AbstractDocumentResource _folder = folder; } - @Override - @NotNull - public Collection getHistory() - { - return Collections.emptyList(); - } - @Override public boolean exists() { return true; } - @Override - public boolean isCollection() - { - return false; - } - @Override public boolean isFile() { @@ -262,10 +241,5 @@ public long getContentLength() } } - @Override - public WebdavResource find(Path.Part name) - { - return null; - } } } diff --git a/query/src/org/labkey/query/reports/ReportsController.java b/query/src/org/labkey/query/reports/ReportsController.java index 4be4cb7f4c5..1cd756f3f0b 100644 --- a/query/src/org/labkey/query/reports/ReportsController.java +++ b/query/src/org/labkey/query/reports/ReportsController.java @@ -837,7 +837,7 @@ public ApiResponse execute(BEAN bean, BindException errors) throws Exception Report report = bean.getReport(getViewContext()); if (report != null) { - _log.trace("Executing report: " + report.getClass().getSimpleName()); + _log.trace("Executing report: {}", report.getClass().getSimpleName()); if (bean.getIsDirty()) report.clearCache(); @@ -852,9 +852,9 @@ public ApiResponse execute(BEAN bean, BindException errors) throws Exception else { HttpView renderedReport = report.renderReport(getViewContext()); - _log.trace("Report views: " + (renderedReport == null ? null : ( + _log.trace("Report views: {}", renderedReport == null ? null : ( renderedReport.getViews() == null ? renderedReport.getClass().getSimpleName() : - renderedReport.getViews().stream().map(mv -> mv.getClass().getSimpleName()).collect(Collectors.joining(", "))))); + renderedReport.getViews().stream().map(mv -> mv.getClass().getSimpleName()).collect(Collectors.joining(", ")))); resultsView.addView(renderedReport); } } @@ -894,13 +894,13 @@ public ApiResponse execute(BEAN bean, BindException errors) throws Exception if (mr.getStatus() != HttpServletResponse.SC_OK) { - _log.trace("Report error. Status: " + mr.getStatus()); + _log.trace("Report error. Status: {}", mr.getStatus()); resultsView.render(getViewContext().getRequest(), getViewContext().getResponse()); return null; } final String html = mr.getContentAsString(); - _log.trace("Report rendered. Size: " + html.length()); + _log.trace("Report rendered. Size: {}", html.length()); resultProperties.put("html", html); resultProperties.put("requiredJsScripts", includes); resultProperties.put("requiredCssScripts", cssScripts); @@ -1245,7 +1245,7 @@ protected void validatePermissions(ViewContext context, ScriptReport report, Lis if (engine != null) { - if (!ReportUtil.canCreateScript(context, engine.getFactory().getExtensions().get(0))) + if (!ReportUtil.canCreateScript(context, engine.getFactory().getExtensions().getFirst())) //TODO update the message text errors.add(new SimpleValidationError("Only users with the site Analyst permission are allowed to create script views.")); } @@ -1521,13 +1521,13 @@ public ModelAndView getView(Object o, BindException errors) throws Exception responseHeaders.put("Pragma", "private"); responseHeaders.put("Cache-Control", "private, max-age=3600"); - _log.debug("Caching file: " + file); + _log.debug("Caching file: {}", file); } PageFlowUtil.streamFile(getViewContext().getResponse(), responseHeaders, file, BooleanUtils.toBoolean(attachment)); if (BooleanUtils.toBoolean(deleteFile)) { file.delete(); - _log.debug("Deleting file: " + file); + _log.debug("Deleting file: {}", file); } return null; } diff --git a/query/src/org/labkey/query/reports/ViewCategoryImporter.java b/query/src/org/labkey/query/reports/ViewCategoryImporter.java index 57aca95f21b..0c6f5d5d5a4 100644 --- a/query/src/org/labkey/query/reports/ViewCategoryImporter.java +++ b/query/src/org/labkey/query/reports/ViewCategoryImporter.java @@ -127,7 +127,7 @@ public boolean isValidForImportArchive(FolderImportContext ctx) throws ImportExc private void process(Container c, User user, Logger logger, @NotNull CategoriesDocument doc) throws Exception { - logger.info("Loading " + getDescription()); + logger.info("Loading {}", getDescription()); DbScope scope = CoreSchema.getInstance().getSchema().getScope(); @@ -155,12 +155,12 @@ private void process(Container c, User user, Logger logger, @NotNull CategoriesD transaction.commit(); } - logger.info("Done importing " + getDescription()); + logger.info("Done importing {}", getDescription()); } private void process(Container c, User user, Logger logger, @NotNull org.labkey.study.xml.viewCategory.CategoriesDocument doc) throws Exception { - logger.info("Loading " + getDescription()); + logger.info("Loading {}", getDescription()); DbScope scope = CoreSchema.getInstance().getSchema().getScope(); @@ -188,7 +188,7 @@ private void process(Container c, User user, Logger logger, @NotNull org.labkey. transaction.commit(); } - logger.info("Done importing " + getDescription()); + logger.info("Done importing {}", getDescription()); } public static class Factory extends AbstractFolderImportFactory diff --git a/query/src/org/labkey/query/reports/getdata/AbstractBaseQueryReportDataSource.java b/query/src/org/labkey/query/reports/getdata/AbstractBaseQueryReportDataSource.java index e928bac5c67..1bc40b0cb34 100644 --- a/query/src/org/labkey/query/reports/getdata/AbstractBaseQueryReportDataSource.java +++ b/query/src/org/labkey/query/reports/getdata/AbstractBaseQueryReportDataSource.java @@ -40,7 +40,7 @@ public Map getColumnMap(Collection requiredInput TableInfo table = sourceQueryDef.getTable(getSchema(), errors, true); if (!errors.isEmpty()) { - throw errors.get(0); + throw errors.getFirst(); } return QueryService.get().getColumns(table, requiredInputs); } diff --git a/query/src/org/labkey/query/reports/getdata/SchemaQueryReportDataSource.java b/query/src/org/labkey/query/reports/getdata/SchemaQueryReportDataSource.java index 9e5eebba667..2f2f4011555 100644 --- a/query/src/org/labkey/query/reports/getdata/SchemaQueryReportDataSource.java +++ b/query/src/org/labkey/query/reports/getdata/SchemaQueryReportDataSource.java @@ -21,7 +21,6 @@ import org.labkey.api.data.ContainerFilter; import org.labkey.api.data.TableInfo; import org.labkey.api.query.QueryDefinition; -import org.labkey.api.query.QueryException; import org.labkey.api.query.SchemaKey; import org.labkey.api.security.User; import org.labkey.api.view.NotFoundException; diff --git a/query/src/org/labkey/query/reports/view/ReportUIProvider.java b/query/src/org/labkey/query/reports/view/ReportUIProvider.java index 4af0e8028c0..58c893461ae 100644 --- a/query/src/org/labkey/query/reports/view/ReportUIProvider.java +++ b/query/src/org/labkey/query/reports/view/ReportUIProvider.java @@ -161,11 +161,11 @@ public List getDesignerInfo(ViewContext context, Que // don't add an entry for R, since we have a specific report type above. if (!factory.getLanguageName().equalsIgnoreCase("R")) { - if (!factory.getExtensions().isEmpty() && ReportUtil.canCreateScript(context, factory.getExtensions().get(0)) && manager.isFactoryEnabled(factory)) + if (!factory.getExtensions().isEmpty() && ReportUtil.canCreateScript(context, factory.getExtensions().getFirst()) && manager.isFactoryEnabled(factory)) { ScriptReportBean bean = new ScriptReportBean(settings); bean.setRedirectUrl(returnUrl.getLocalURIString()); - bean.setScriptExtension(factory.getExtensions().get(0)); + bean.setScriptExtension(factory.getExtensions().getFirst()); if (factory instanceof ExternalScriptEngineFactory) { diff --git a/query/src/org/labkey/query/reports/view/ReportsWebPart.java b/query/src/org/labkey/query/reports/view/ReportsWebPart.java index ff537f7413b..8f3079f985f 100644 --- a/query/src/org/labkey/query/reports/view/ReportsWebPart.java +++ b/query/src/org/labkey/query/reports/view/ReportsWebPart.java @@ -33,7 +33,6 @@ import org.labkey.api.view.WebPartView; import org.labkey.api.writer.HtmlWriter; -import java.io.PrintWriter; import java.util.Map; import java.util.Objects; diff --git a/query/src/org/labkey/query/sql/AbstractQueryRelation.java b/query/src/org/labkey/query/sql/AbstractQueryRelation.java index 3222583c07f..a710b77ec2c 100644 --- a/query/src/org/labkey/query/sql/AbstractQueryRelation.java +++ b/query/src/org/labkey/query/sql/AbstractQueryRelation.java @@ -317,7 +317,7 @@ public String toString() public int addRef(@NotNull Object refer) { int i = ref.increment(refer); - _log.debug("addRef( " + this.getDebugString() + ", " + refer + " ) = " + i); + _log.debug("addRef( {}, {} ) = {}", this.getDebugString(), refer, i); return i; } diff --git a/query/src/org/labkey/query/sql/Builder.java b/query/src/org/labkey/query/sql/Builder.java index fee36397f81..fcca057efce 100644 --- a/query/src/org/labkey/query/sql/Builder.java +++ b/query/src/org/labkey/query/sql/Builder.java @@ -57,7 +57,7 @@ public void pushPrefix(String prefix) */ public void popPrefix(String suffix) { - String cur = _prefix.remove(_prefix.size() - 1); + String cur = _prefix.removeLast(); if (cur == null) { super.append(suffix); @@ -75,7 +75,7 @@ public void popPrefix() */ public boolean nextPrefix(String newPrefix) { - String prefix = _prefix.get(_prefix.size() - 1); + String prefix = _prefix.getLast(); if (prefix != null) return false; _prefix.set(_prefix.size() - 1, newPrefix); diff --git a/query/src/org/labkey/query/sql/CalculatedExpressionColumn.java b/query/src/org/labkey/query/sql/CalculatedExpressionColumn.java index cf05dafaf9f..cd63c700ca9 100644 --- a/query/src/org/labkey/query/sql/CalculatedExpressionColumn.java +++ b/query/src/org/labkey/query/sql/CalculatedExpressionColumn.java @@ -182,7 +182,7 @@ private QExpr parse() .setFailOnUnrecognizedMethodName(true); QExpr expr = parser.parseExpr(_labKeySql, errors); if (!errors.isEmpty()) - throw errors.get(0); + throw errors.getFirst(); _parsedExpr = expr; } @@ -271,7 +271,7 @@ private QExpr _resolveFields(QExpr expr, Map col QExpr methodName = null; if (expr instanceof QMethodCall) { - methodName = (QExpr) expr.childList().get(0); + methodName = (QExpr) expr.childList().getFirst(); if (null == methodName.getFieldKey()) methodName = null; } diff --git a/query/src/org/labkey/query/sql/Method.java b/query/src/org/labkey/query/sql/Method.java index 8789835eb94..2ef2a709611 100644 --- a/query/src/org/labkey/query/sql/Method.java +++ b/query/src/org/labkey/query/sql/Method.java @@ -238,9 +238,9 @@ public void validate(CommonTree fn, List args, List parseError super.validate(fn, args, parseErrors, parseWarnings); if (args.size() != 1) return; - int line = args.get(0).getLine(); - int column = args.get(0).getColumn(); - if (args.get(0).getTokenType() != SqlBaseLexer.QUOTED_STRING) + int line = args.getFirst().getLine(); + int column = args.getFirst().getColumn(); + if (args.getFirst().getTokenType() != SqlBaseLexer.QUOTED_STRING) { parseErrors.add(new QueryParseException(_name.toUpperCase() + "() function expects quoted string arguments", null, line, column)); return; @@ -250,7 +250,7 @@ public void validate(CommonTree fn, List args, List parseError String propertyName = ""; try { - String param = toSimpleString(new SQLFragment(args.get(0).getTokenText())); + String param = toSimpleString(new SQLFragment(args.getFirst().getTokenText())); int dot = param.lastIndexOf('.'); if (dot < 0) { @@ -330,7 +330,7 @@ public void validate(CommonTree fn, List args, List parseError return; if (args.get(0).getTokenType() != SqlBaseLexer.QUOTED_STRING) { - parseErrors.add(new QueryParseException(_name.toUpperCase() + "() function expects quoted string arguments", null, args.get(0).getLine(), args.get(0).getColumn())); + parseErrors.add(new QueryParseException(_name.toUpperCase() + "() function expects quoted string arguments", null, args.getFirst().getLine(), args.getFirst().getColumn())); return; } if (args.get(1).getTokenType() != SqlBaseLexer.QUOTED_STRING) @@ -343,7 +343,7 @@ public void validate(CommonTree fn, List args, List parseError Module module = ModuleLoader.getInstance().getModule(moduleName); if (null == module) { - parseWarnings.add(new QueryParseWarning(_name.toUpperCase() + "() module not found: " + moduleName, null, args.get(0).getLine(), args.get(0).getColumn())); + parseWarnings.add(new QueryParseWarning(_name.toUpperCase() + "() module not found: " + moduleName, null, args.getFirst().getLine(), args.getFirst().getColumn())); return; } String propertyName = toSimpleString(new SQLFragment(args.get(1).getTokenText())); @@ -1483,7 +1483,7 @@ public static boolean isSimpleString(SQLFragment f) String s = f.getSQL(); // am I a simple bound parameter? if ("?".equals(s) && f.getParams().size() == 1) - return f.getParams().get(0) instanceof String; + return f.getParams().getFirst() instanceof String; if (!f.getParams().isEmpty()) return false; if (s.endsWith("::VARCHAR")) @@ -1506,7 +1506,7 @@ public static String toSimpleString(SQLFragment f) throw new IllegalArgumentException(f.toDebugString()); String s = f.getSQL(); if ("?".equals(s) && f.getParams().size() == 1) - return (String) f.getParams().get(0); + return (String) f.getParams().getFirst(); assert (s.startsWith("'") || s.startsWith("N'")); assert (s.endsWith("'") || s.endsWith("'::VARCHAR")); if (s.endsWith("::VARCHAR")) diff --git a/query/src/org/labkey/query/sql/QAggregate.java b/query/src/org/labkey/query/sql/QAggregate.java index a42ae32fbc0..1f7bbcf70bf 100644 --- a/query/src/org/labkey/query/sql/QAggregate.java +++ b/query/src/org/labkey/query/sql/QAggregate.java @@ -466,7 +466,7 @@ public ColumnInfo createColumnInfo(TableInfo table, String alias, Query query) { var ret = (MutableColumnInfo)super.createColumnInfo(table, alias, query); List children = childList(); - if (children.size() == 1 && children.get(0) instanceof QField field) + if (children.size() == 1 && children.getFirst() instanceof QField field) { if (getType()._propagateAttributes) { diff --git a/query/src/org/labkey/query/sql/QCase.java b/query/src/org/labkey/query/sql/QCase.java index c6236434159..17eca41615d 100644 --- a/query/src/org/labkey/query/sql/QCase.java +++ b/query/src/org/labkey/query/sql/QCase.java @@ -60,7 +60,7 @@ public void appendSource(SourceBuilder builder) // skip the first expression ArrayList list = new ArrayList<>(childList()); - list.remove(0); + list.removeFirst(); return getChildrenSqlType(list); } diff --git a/query/src/org/labkey/query/sql/QIdentifier.java b/query/src/org/labkey/query/sql/QIdentifier.java index 34500e87c3c..82c3320d4ab 100644 --- a/query/src/org/labkey/query/sql/QIdentifier.java +++ b/query/src/org/labkey/query/sql/QIdentifier.java @@ -101,10 +101,4 @@ public boolean equalsNode(QNode other) { return other instanceof QIdentifier && getIdentifier().equalsIgnoreCase(((QIdentifier) other).getIdentifier()); } - - @Override - public boolean isConstant() - { - return false; - } } diff --git a/query/src/org/labkey/query/sql/QIfDefined.java b/query/src/org/labkey/query/sql/QIfDefined.java index f1bbef1be47..59553299738 100644 --- a/query/src/org/labkey/query/sql/QIfDefined.java +++ b/query/src/org/labkey/query/sql/QIfDefined.java @@ -23,7 +23,6 @@ import org.labkey.api.data.TableInfo; import org.labkey.api.data.dialect.SqlDialect; import org.labkey.api.query.FieldKey; -import org.labkey.api.query.QueryParseException; /** * User: matthewb @@ -114,12 +113,6 @@ public BaseColumnInfo createColumnInfo(TableInfo table, String name, Query query throw new IllegalStateException(); } - @Override - public QueryParseException fieldCheck(QNode parent, SqlDialect d) - { - return null; - } - @Override protected JdbcType getChildrenSqlType() { diff --git a/query/src/org/labkey/query/sql/QNode.java b/query/src/org/labkey/query/sql/QNode.java index 2a5e272f526..48d9e2b0862 100644 --- a/query/src/org/labkey/query/sql/QNode.java +++ b/query/src/org/labkey/query/sql/QNode.java @@ -443,7 +443,7 @@ QExpr resolveFields(QExpr expr, @Nullable QNode parent, @Nullable Object referan QExpr methodName = null; if (expr instanceof QMethodCall) { - methodName = (QExpr)expr.childList().get(0); + methodName = (QExpr)expr.childList().getFirst(); if (null == methodName.getFieldKey()) methodName = null; } diff --git a/query/src/org/labkey/query/sql/QPivot.java b/query/src/org/labkey/query/sql/QPivot.java index 062ecf8c0db..4915f1e69ca 100644 --- a/query/src/org/labkey/query/sql/QPivot.java +++ b/query/src/org/labkey/query/sql/QPivot.java @@ -32,7 +32,7 @@ public void appendSource(SourceBuilder builder) if (children.isEmpty()) return; - QNode exprList = children.get(0); + QNode exprList = children.getFirst(); // NO PARENS for (QNode child : exprList.children()) { diff --git a/query/src/org/labkey/query/sql/QResolveTableColumn.java b/query/src/org/labkey/query/sql/QResolveTableColumn.java index f55d6d1401e..f26f21fa404 100644 --- a/query/src/org/labkey/query/sql/QResolveTableColumn.java +++ b/query/src/org/labkey/query/sql/QResolveTableColumn.java @@ -73,22 +73,10 @@ private AbstractQueryRelation.RelationColumn resolveColumn(QueryRelation table, } /* have to call getColumn() so table knows column is in use */ - return table.getColumn(list.get(0).getFieldKey().getName()); + return table.getColumn(list.getFirst().getFieldKey().getName()); } - @Override - public void appendSql(SqlBuilder builder, Query query) - { - throw new IllegalStateException(); - } - - @Override - public boolean isConstant() - { - return false; - } - @Override public void appendSource(SourceBuilder builder) { diff --git a/query/src/org/labkey/query/sql/QValuesTable.java b/query/src/org/labkey/query/sql/QValuesTable.java index 1e0b7798f9f..ec2c26e5776 100644 --- a/query/src/org/labkey/query/sql/QValuesTable.java +++ b/query/src/org/labkey/query/sql/QValuesTable.java @@ -34,7 +34,7 @@ public class QValuesTable extends QTable this.values = values; setAlias(alias); var rows = values.childList(); - countOfColumns = rows.isEmpty() ? 0 : rows.get(0).childList().size(); + countOfColumns = rows.isEmpty() ? 0 : rows.getFirst().childList().size(); relation = new _QueryRelation(); } @@ -126,7 +126,7 @@ QExpr _resolveFields(QExpr expr, @Nullable QNode parent, @Nullable Object refera QExpr methodName = null; if (expr instanceof QMethodCall) { - methodName = (QExpr)expr.childList().get(0); + methodName = (QExpr)expr.childList().getFirst(); if (null == methodName.getFieldKey()) methodName = null; } @@ -264,7 +264,7 @@ String getConceptURI() @Override public @NotNull JdbcType getJdbcType() { - var firstRow = values.childList().get(0).childList(); + var firstRow = values.childList().getFirst().childList(); final QExpr expr = (QExpr)firstRow.get(index); return expr.getJdbcType(); } diff --git a/query/src/org/labkey/query/sql/Query.java b/query/src/org/labkey/query/sql/Query.java index 7b0c47a6ea5..3f8ea83d61b 100644 --- a/query/src/org/labkey/query/sql/Query.java +++ b/query/src/org/labkey/query/sql/Query.java @@ -221,7 +221,7 @@ public void parseQuerySource(boolean skipSuggestedColumns) if (null == _querySource) throw new IllegalStateException("SQL has not been specified"); - LogManager.getLogger(Query.class).debug("Query.parse()\n" + _querySource); + LogManager.getLogger(Query.class).debug("Query.parse()\n{}", _querySource); _parse(_querySource, skipSuggestedColumns); for (QueryException e : _parseErrors) @@ -715,7 +715,7 @@ static QueryRecursionReturn queryRecursionCheck(String message, @Nullable QNode { ArrayList list = new ArrayList<>(); parseError(list, message, node); - throw list.get(0); + throw list.getFirst(); } ai.incrementAndGet(); return new QueryRecursionReturn(); @@ -771,7 +771,7 @@ AbstractQueryRelation resolveTable(QuerySchema currentSchema, QNode node, FieldK } } if (null == firstError && !resolveExceptions.isEmpty()) - firstError = resolveExceptions.get(0); + firstError = resolveExceptions.getFirst(); if (null != firstError) { diff --git a/query/src/org/labkey/query/sql/QueryLineage.java b/query/src/org/labkey/query/sql/QueryLineage.java index 706fa516610..e4a772c7817 100644 --- a/query/src/org/labkey/query/sql/QueryLineage.java +++ b/query/src/org/labkey/query/sql/QueryLineage.java @@ -1,6 +1,5 @@ package org.labkey.query.sql; -import org.apache.commons.lang3.Strings; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.labkey.api.data.BaseColumnInfo; diff --git a/query/src/org/labkey/query/sql/QueryLookupWrapper.java b/query/src/org/labkey/query/sql/QueryLookupWrapper.java index 42f63432bb2..88de8ac7cb5 100644 --- a/query/src/org/labkey/query/sql/QueryLookupWrapper.java +++ b/query/src/org/labkey/query/sql/QueryLookupWrapper.java @@ -17,8 +17,8 @@ import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; -import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; +import org.jetbrains.annotations.NotNull; import org.labkey.api.collections.ArrayListMap; import org.labkey.api.collections.CaseInsensitiveHashMap; import org.labkey.api.collections.CaseInsensitiveHashSet; @@ -152,7 +152,7 @@ protected void setHasLookup() @Override public void declareFields() { - _log.debug("declareFields " + this.toStringDebug()); + _log.debug("declareFields {}", this.toStringDebug()); _source.declareFields(); } @@ -375,7 +375,7 @@ public RelationColumn getLookupColumn(@NotNull RelationColumn parentRelCol, @Not @Override - public RelationColumn getLookupColumn(@NotNull RelationColumn parentRelCol, ColumnType.Fk fk, @NotNull String name) + public RelationColumn getLookupColumn(@NotNull RelationColumn parentRelCol, ColumnType.@NotNull Fk fk, @NotNull String name) { QLWColumn parent = (QLWColumn)parentRelCol; FieldKey k = new FieldKey(parent._key, name); diff --git a/query/src/org/labkey/query/sql/QueryPivot.java b/query/src/org/labkey/query/sql/QueryPivot.java index 42175beebcc..49f6eaea1db 100644 --- a/query/src/org/labkey/query/sql/QueryPivot.java +++ b/query/src/org/labkey/query/sql/QueryPivot.java @@ -16,8 +16,8 @@ package org.labkey.query.sql; import org.apache.commons.beanutils.ConvertUtils; -import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; +import org.jetbrains.annotations.NotNull; import org.labkey.api.collections.CaseInsensitiveMapWrapper; import org.labkey.api.collections.NamedObjectList; import org.labkey.api.data.*; @@ -124,7 +124,7 @@ public QueryPivot(Query query, QuerySelect from, QQuery root) } QNode source = col._node; if (source instanceof QAs) - source = source.childList().get(0); + source = source.childList().getFirst(); QAggregate.Type rollupType = null; if (source instanceof QAggregate) { @@ -497,7 +497,7 @@ String getConceptURI() } @Override - void copyColumnAttributesTo(BaseColumnInfo to) + void copyColumnAttributesTo(@NotNull BaseColumnInfo to) { _s.copyColumnAttributesTo(to); if (_aggregates.containsKey(_s.getFieldKey().getName())) @@ -694,7 +694,7 @@ public JdbcType getJdbcType() } @Override - void copyColumnAttributesTo(BaseColumnInfo to) + void copyColumnAttributesTo(@NotNull BaseColumnInfo to) { _agg.copyColumnAttributesTo(to); @@ -810,7 +810,7 @@ public SQLFragment getSql() if (!getParseErrors().isEmpty()) { - QueryException qe = getParseErrors().get(0); + QueryException qe = getParseErrors().getFirst(); _query.decorateException(qe); throw qe; } @@ -911,7 +911,7 @@ public SQLFragment getFromSQL(String pivotTableAlias) if (null == fromSql) { if (!getParseErrors().isEmpty()) - throw getParseErrors().get(0); + throw getParseErrors().getFirst(); QueryParseException qpe = new QueryParseException("Error compiling query" + (null != _query._debugName ? ": " + _query._debugName : ""), null, 0, 0); _query.decorateException(qpe); throw qpe; @@ -1013,7 +1013,7 @@ public List getColMembers() Map pivotValues = getPivotValues(); if (!getParseErrors().isEmpty()) { - throw getParseErrors().get(0); + throw getParseErrors().getFirst(); } _members = new ArrayList<>(pivotValues.size()); @@ -1063,19 +1063,18 @@ private CrosstabMeasure.AggregateFunction toAggFn(QAggregate.Type aggType) if (aggType == null) return null; - switch (aggType) - { - case AVG: return CrosstabMeasure.AggregateFunction.AVG; - case COUNT: return CrosstabMeasure.AggregateFunction.COUNT; - case GROUP_CONCAT: return CrosstabMeasure.AggregateFunction.GROUP_CONCAT; - case MAX: return CrosstabMeasure.AggregateFunction.MAX; - case MIN: return CrosstabMeasure.AggregateFunction.MIN; - case STDDEV: return CrosstabMeasure.AggregateFunction.STDDEV; - case STDERR: return CrosstabMeasure.AggregateFunction.STDERR; - case SUM: return CrosstabMeasure.AggregateFunction.SUM; - default: - throw new IllegalArgumentException(aggType.toString()); - } + return switch (aggType) + { + case AVG -> CrosstabMeasure.AggregateFunction.AVG; + case COUNT -> CrosstabMeasure.AggregateFunction.COUNT; + case GROUP_CONCAT -> CrosstabMeasure.AggregateFunction.GROUP_CONCAT; + case MAX -> CrosstabMeasure.AggregateFunction.MAX; + case MIN -> CrosstabMeasure.AggregateFunction.MIN; + case STDDEV -> CrosstabMeasure.AggregateFunction.STDDEV; + case STDERR -> CrosstabMeasure.AggregateFunction.STDERR; + case SUM -> CrosstabMeasure.AggregateFunction.SUM; + default -> throw new IllegalArgumentException(aggType.toString()); + }; } private CrosstabMember createCrosstabMember(Object value, String caption) @@ -1161,7 +1160,7 @@ public UserSchema getUserSchema() if (!getParseErrors().isEmpty()) { - throw getParseErrors().get(0); + throw getParseErrors().getFirst(); } for (String displayField : pivotValues.keySet()) diff --git a/query/src/org/labkey/query/sql/QuerySelect.java b/query/src/org/labkey/query/sql/QuerySelect.java index 98adee324e7..a09d1795f66 100644 --- a/query/src/org/labkey/query/sql/QuerySelect.java +++ b/query/src/org/labkey/query/sql/QuerySelect.java @@ -672,7 +672,7 @@ else if (r.getTokenType() == SqlBaseParser.JOIN) private QTable parseLineage(final QNode range) { - QMethodCall methodCall = (QMethodCall)range.childList().get(0); + QMethodCall methodCall = (QMethodCall)range.childList().getFirst(); var methodIdentifier = methodCall.childList().get(0); int methodType = methodIdentifier.getTokenType(); QQuery subQuery = (QQuery)methodCall.childList().get(1); @@ -699,7 +699,7 @@ else if (_tables.containsKey(aliasKey)) private QTable parseValues(QNode node) { int countChildren = node.childList().size(); - if (2 < countChildren || !(node.childList().get(0) instanceof QValues)) + if (2 < countChildren || !(node.childList().getFirst() instanceof QValues)) { parseError("Syntax error in JOIN clause", node); return null; @@ -730,7 +730,7 @@ private QTable parseValues(QNode node) private QTable parseRange(QNode node) { int countChildren = node.childList().size(); - if (countChildren < 1 || 2 < countChildren || !(node.childList().get(0) instanceof QExpr)) + if (countChildren < 1 || 2 < countChildren || !(node.childList().getFirst() instanceof QExpr)) { parseError("Syntax error in JOIN clause", node); return null; @@ -831,19 +831,19 @@ private QJoin parseJoin(QNode join) if (children.size() > childIndex) { on = children.get(childIndex); - if (on.childList().size() != 1 || !(on.childList().get(0) instanceof QExpr)) + if (on.childList().size() != 1 || !(on.childList().getFirst() instanceof QExpr)) { parseError("Error in ON expression", on); return null; } - _ons.add((QExpr) on.childList().get(0)); + _ons.add((QExpr) on.childList().getFirst()); } if (joinType == JoinType.cross && null != on) parseError("ON unexpected in a CROSS JOIN", on); else if (joinType != JoinType.cross && null == on) parseError("ON expected", rightNode); - QJoin qjoin = new QJoin(left, right, joinType, null == on ? null : (QExpr) on.childList().get(0)); + QJoin qjoin = new QJoin(left, right, joinType, null == on ? null : (QExpr) on.childList().getFirst()); return qjoin; } } @@ -890,7 +890,7 @@ private QField getFieldInternal(FieldKey key, QNode expr, Object referant, boole if (isDebugEnabled) { debugMsg = "getField( " + this.toStringDebug() + ", " + key.toDisplayString() + " )\n referant: " + referant; - _log.debug(">>" + debugMsg); + _log.debug(">>{}", debugMsg); } if (!methodName) @@ -929,7 +929,7 @@ private QField getFieldInternal(FieldKey key, QNode expr, Object referant, boole } finally { - _log.debug("<<" + debugMsg); + _log.debug("<<{}", debugMsg); } } @@ -953,7 +953,7 @@ public RelationColumn declareField(FieldKey declareKey, QExpr location) if (parts.size() >= 2) { // Attempt to resolve a simple table prefix - tableKey = new FieldKey(null, parts.get(0)); + tableKey = new FieldKey(null, parts.getFirst()); table = getTable(tableKey); if (table == null) @@ -976,7 +976,7 @@ public RelationColumn declareField(FieldKey declareKey, QExpr location) if (null == table) { - String name = parts.get(0); + String name = parts.getFirst(); for (Map.Entry e : _tables.entrySet()) { if (null != e.getValue().getColumn(name)) @@ -1018,7 +1018,7 @@ public RelationColumn declareField(FieldKey declareKey, QExpr location) qualified = false; } - FieldKey key = new FieldKey(tableKey, parts.get(0)); + FieldKey key = new FieldKey(tableKey, parts.getFirst()); RelationColumn colParent = _declaredFields.get(key); if (colParent == null) { @@ -1132,7 +1132,7 @@ public void declareFields() if (_declareCalled) return; _declareCalled = true; - _log.debug("declareFields " + this.toStringDebug()); + _log.debug("declareFields {}", this.toStringDebug()); for (Map.Entry entry : _tables.entrySet()) entry.getValue().declareFields(); @@ -1257,7 +1257,7 @@ QExpr resolveFields(QExpr expr, @Nullable QNode parent, @Nullable Object referan QExpr methodName = null; if (expr instanceof QMethodCall) { - methodName = (QExpr)expr.childList().get(0); + methodName = (QExpr)expr.childList().getFirst(); if (null == methodName.getFieldKey()) methodName = null; } @@ -1403,7 +1403,7 @@ public SQLFragment getFromSQLExpanded(String alias, Set selectedFieldK SQLFragment s = getSql(); if (!getParseErrors().isEmpty()) - throw getParseErrors().get(0); + throw getParseErrors().getFirst(); SQLFragment f = new SQLFragment(); f.append("(").append(s).append(") ").appendIdentifier(alias); @@ -1639,11 +1639,11 @@ private SQLFragment _getSql(boolean asFromSql) int count = 0; boolean isDebugEnabled = _log.isDebugEnabled(); if (isDebugEnabled) - _log.debug("SELECT COLUMN LIST: " + this.toStringDebug()); + _log.debug("SELECT COLUMN LIST: {}", this.toStringDebug()); for (SelectColumn col : _columns.values()) { if (isDebugEnabled) - _log.debug(" " + col.getDebugString() + " ref=" + col.ref.count()); + _log.debug(" {} ref={}", col.getDebugString(), col.ref.count()); // NOTE: container columns are sometimes used by lookups without being explicitly REF'd if (col.getJdbcType() == JdbcType.GUID) col.addRef(col); diff --git a/query/src/org/labkey/query/sql/QueryTable.java b/query/src/org/labkey/query/sql/QueryTable.java index c179b59185e..41e20c9c8b9 100644 --- a/query/src/org/labkey/query/sql/QueryTable.java +++ b/query/src/org/labkey/query/sql/QueryTable.java @@ -128,7 +128,7 @@ public List getSortFields() @Override public void declareFields() { - _log.debug("declareFields " + toStringDebug()); + _log.debug("declareFields {}", toStringDebug()); } diff --git a/query/src/org/labkey/query/sql/QueryTableInfo.java b/query/src/org/labkey/query/sql/QueryTableInfo.java index 797b26d057f..a8304e1bb59 100644 --- a/query/src/org/labkey/query/sql/QueryTableInfo.java +++ b/query/src/org/labkey/query/sql/QueryTableInfo.java @@ -76,7 +76,7 @@ public SQLFragment getFromSQL(String alias) if (null == sql) { if (!_relation._query.getParseErrors().isEmpty()) - throw _relation._query.getParseErrors().get(0); + throw _relation._query.getParseErrors().getFirst(); else throw new QueryException("Error generating SQL"); } diff --git a/query/src/org/labkey/query/sql/SqlParser.java b/query/src/org/labkey/query/sql/SqlParser.java index cca976db057..80ae4653c9c 100644 --- a/query/src/org/labkey/query/sql/SqlParser.java +++ b/query/src/org/labkey/query/sql/SqlParser.java @@ -132,7 +132,7 @@ public synchronized T get() { while (!_pool.isEmpty()) { - SoftReference r = _pool.remove(0); + SoftReference r = _pool.removeFirst(); T t = r.get(); if (null != t) return t; @@ -200,7 +200,7 @@ public Tree rawQuery(String str) throws Exception parser.reset(str, _parseErrors); ParserRuleReturnScope selectScope = parser.statement(); if (!_parseErrors.isEmpty()) - throw _parseErrors.get(0); + throw _parseErrors.getFirst(); return (Tree) selectScope.getTree(); } } @@ -250,10 +250,10 @@ else if (null != warnings) // PARAMETERS - if (!list.isEmpty() && list.get(0).getType() == SqlBaseParser.PARAMETERS) + if (!list.isEmpty() && list.getFirst().getType() == SqlBaseParser.PARAMETERS) { _parameters = new ArrayList<>(); - parameters = list.remove(0); + parameters = list.removeFirst(); for (Object parameter : parameters.getChildren()) { QParameter p = convertParameter((CommonTree)parameter); @@ -270,9 +270,9 @@ else if (null != warnings) // COMMON TABLE EXPRESSIONS QNode qnodeWith = null; - if (!list.isEmpty() && list.get(0).getType() == SqlBaseParser.WITH) + if (!list.isEmpty() && list.getFirst().getType() == SqlBaseParser.WITH) { - CommonTree withStmt = list.remove(0); + CommonTree withStmt = list.removeFirst(); if (null == _dialect || _dialect.isLabKeyWithSupported()) // Check dialect if we have one qnodeWith = convertParseTree(withStmt); else @@ -288,7 +288,7 @@ else if (null != warnings) return null; } - CommonTree selectStmt = list.remove(0); + CommonTree selectStmt = list.removeFirst(); if (selectStmt.getType() != QUERY && !isSetOperator(selectStmt.getType())) { errors.add(new QueryParseException(tokenName(selectStmt.getType()) + " statements are not supported", null, parseRoot.getLine(), parseRoot.getCharPositionInLine())); @@ -338,16 +338,11 @@ else if (null != warnings) private boolean isSetOperator(int type) { - switch (type) + return switch (type) { - case UNION: - case UNION_ALL: - case INTERSECT: - case EXCEPT: - return true; - default: - return false; - } + case UNION, UNION_ALL, INTERSECT, EXCEPT -> true; + default -> false; + }; } @@ -678,121 +673,121 @@ static String formatRecognitionException(RecognitionException re) public static String tokenName(int type) { - switch (type) - { - case EOF: return "EOF"; - case AGGREGATE: return "AGGREGATE FUNCTION"; - case ALIAS: return "AS"; - case EXPR_LIST: return "EXPR LIST"; - case IN_LIST: return "IN LIST"; - case IS_NOT: return "IS NOT"; - case METHOD_CALL: return "METHOD CALL"; - case NOT_BETWEEN: return "NOT BETWEEN"; - case NOT_IN: return "NOT IN"; - case NOT_LIKE: return "NOT LIKE"; - case QUERY: return "QUERY"; - case RANGE: return "RANGE"; - case ROW_STAR: return "*"; - case SELECT_FROM: return "SELECT FROM"; - case UNARY_MINUS: return "-"; - case UNARY_PLUS: return "+"; - case UNION_ALL: return "UNION ALL"; - case ALL: return "ALL"; - case ANY: return "ANY"; - case AND: return "AND"; - case AS: return "AS"; - case ASCENDING: return "ASCENDING"; - case AVG: return "AVG"; - case BETWEEN: return "BETWEEN"; - case CASE: return "CASE"; - case CASE2: return "CASE"; - case CAST: return "CAST"; - case COUNT: return "COUNT"; - case DATATYPE: return "DATATYPE"; - case DELETE: return "DELETE"; - case DESCENDING: return "DESCENDING"; - case DISTINCT: return "DISTINCT"; - case DOT: return "DOT"; - case ELSE: return "ELSE"; - case END: return "END"; - case ESCAPE: return "ESCAPE"; - case EXISTS: return "EXISTS"; - case FALSE: return "FALSE"; - case FROM: return "FROM"; - case FULL: return "FULL"; - case GROUP: return "GROUP"; - case HAVING: return "HAVING"; - case IFDEFINED: return "IFDEFINED"; - case IN: return "IN"; - case INNER: return "INNER"; - case INSERT: return "INSERT"; - case INTO: return "INTO"; - case IS: return "IS"; - case JOIN: return "JOIN"; - case LEFT: return "LEFT"; - case LIKE: return "LIKE"; - case LIMIT: return "LIMIT"; - case MAX: return "MAX"; - case GROUP_CONCAT: return "GROUP_CONCAT"; - case MIN: return "MIN"; - case NOT: return "NOT"; - case NULL: return "NULL"; - case ON: return "ON"; - case OR: return "OR"; - case ORDER: return "ORDER"; - case OUTER: return "OUTER"; - case RIGHT: return "RIGHT"; - case SELECT: return "SELECT"; - case SET: return "SET"; - case SOME: return "SOME"; - case STDDEV: return "STDDEV"; - case SUM: return "SUM"; - case THEN: return "THEN"; - case TRUE: return "TRUE"; - case UNION: return "UNION"; - case UPDATE: return "UPDATE"; - case WHERE: return "WHERE"; - case WHEN: return "WHEN"; - case COMMA: return ","; - case EQ: return "="; - case OPEN: return "("; - case CLOSE: return ")"; - case NUM_INT: return "NUMBER"; - case BIT_OR: return "|"; - case BIT_XOR: return "^"; - case NE: return "!="; - case SQL_NE: return "<>"; - case LT: return "<"; - case GT: return ">"; - case LE: return "<="; - case GE: return ">="; - case CONCAT: return "||"; - case PLUS: return "+"; - case MINUS: return "-"; - case BIT_AND: return "&"; - case STAR: return "*"; - case DIV: return "/"; - case MODULO: return "%"; - case PARAM: return "?"; - case QUOTED_STRING: return "QUOTED STRING"; - case NUM_LONG: return "NUMBER"; - case NUM_DOUBLE: return "NUMBER"; - case NUM_FLOAT: return "NUMBER"; - case IDENT: return "IDENTIFIER"; - case QUOTED_IDENTIFIER: return "QUOTED IDENTIFIER"; - case COLON: return ":"; - case ID_START_LETTER: return "ID_START_LETTER"; - case ID_LETTER: return "ID_LETTER"; - case WS: return "WHITE SPACE"; - case EXPONENT: return "EXPONENT"; - case FLOAT_SUFFIX: return "FLOAT_SUFFIX"; - case HEX_DIGIT: return "HEX_DIGIT"; - case COMMENT: return "COMMENT"; - case LINE_COMMENT: return "LINE COMMENT"; - case EXCEPT: return "EXCEPT"; - case INTERSECT: return "INTERSECT"; - } - return null; + return switch (type) + { + case EOF -> "EOF"; + case AGGREGATE -> "AGGREGATE FUNCTION"; + case ALIAS -> "AS"; + case EXPR_LIST -> "EXPR LIST"; + case IN_LIST -> "IN LIST"; + case IS_NOT -> "IS NOT"; + case METHOD_CALL -> "METHOD CALL"; + case NOT_BETWEEN -> "NOT BETWEEN"; + case NOT_IN -> "NOT IN"; + case NOT_LIKE -> "NOT LIKE"; + case QUERY -> "QUERY"; + case RANGE -> "RANGE"; + case ROW_STAR -> "*"; + case SELECT_FROM -> "SELECT FROM"; + case UNARY_MINUS -> "-"; + case UNARY_PLUS -> "+"; + case UNION_ALL -> "UNION ALL"; + case ALL -> "ALL"; + case ANY -> "ANY"; + case AND -> "AND"; + case AS -> "AS"; + case ASCENDING -> "ASCENDING"; + case AVG -> "AVG"; + case BETWEEN -> "BETWEEN"; + case CASE -> "CASE"; + case CASE2 -> "CASE"; + case CAST -> "CAST"; + case COUNT -> "COUNT"; + case DATATYPE -> "DATATYPE"; + case DELETE -> "DELETE"; + case DESCENDING -> "DESCENDING"; + case DISTINCT -> "DISTINCT"; + case DOT -> "DOT"; + case ELSE -> "ELSE"; + case END -> "END"; + case ESCAPE -> "ESCAPE"; + case EXISTS -> "EXISTS"; + case FALSE -> "FALSE"; + case FROM -> "FROM"; + case FULL -> "FULL"; + case GROUP -> "GROUP"; + case HAVING -> "HAVING"; + case IFDEFINED -> "IFDEFINED"; + case IN -> "IN"; + case INNER -> "INNER"; + case INSERT -> "INSERT"; + case INTO -> "INTO"; + case IS -> "IS"; + case JOIN -> "JOIN"; + case LEFT -> "LEFT"; + case LIKE -> "LIKE"; + case LIMIT -> "LIMIT"; + case MAX -> "MAX"; + case GROUP_CONCAT -> "GROUP_CONCAT"; + case MIN -> "MIN"; + case NOT -> "NOT"; + case NULL -> "NULL"; + case ON -> "ON"; + case OR -> "OR"; + case ORDER -> "ORDER"; + case OUTER -> "OUTER"; + case RIGHT -> "RIGHT"; + case SELECT -> "SELECT"; + case SET -> "SET"; + case SOME -> "SOME"; + case STDDEV -> "STDDEV"; + case SUM -> "SUM"; + case THEN -> "THEN"; + case TRUE -> "TRUE"; + case UNION -> "UNION"; + case UPDATE -> "UPDATE"; + case WHERE -> "WHERE"; + case WHEN -> "WHEN"; + case COMMA -> ","; + case EQ -> "="; + case OPEN -> "("; + case CLOSE -> ")"; + case NUM_INT -> "NUMBER"; + case BIT_OR -> "|"; + case BIT_XOR -> "^"; + case NE -> "!="; + case SQL_NE -> "<>"; + case LT -> "<"; + case GT -> ">"; + case LE -> "<="; + case GE -> ">="; + case CONCAT -> "||"; + case PLUS -> "+"; + case MINUS -> "-"; + case BIT_AND -> "&"; + case STAR -> "*"; + case DIV -> "/"; + case MODULO -> "%"; + case PARAM -> "?"; + case QUOTED_STRING -> "QUOTED STRING"; + case NUM_LONG -> "NUMBER"; + case NUM_DOUBLE -> "NUMBER"; + case NUM_FLOAT -> "NUMBER"; + case IDENT -> "IDENTIFIER"; + case QUOTED_IDENTIFIER -> "QUOTED IDENTIFIER"; + case COLON -> ":"; + case ID_START_LETTER -> "ID_START_LETTER"; + case ID_LETTER -> "ID_LETTER"; + case WS -> "WHITE SPACE"; + case EXPONENT -> "EXPONENT"; + case FLOAT_SUFFIX -> "FLOAT_SUFFIX"; + case HEX_DIGIT -> "HEX_DIGIT"; + case COMMENT -> "COMMENT"; + case LINE_COMMENT -> "LINE COMMENT"; + case EXCEPT -> "EXCEPT"; + case INTERSECT -> "INTERSECT"; + default -> null; + }; } @@ -896,7 +891,7 @@ private QNode convertNode(CommonTree node, LinkedList children, boolean c var divisorType = children.size() > 1 ? children.get(1).getTokenType() : 0; if (divisorType==METHOD_CALL) { - var method = children.get(1).childList().get(0); + var method = children.get(1).childList().getFirst(); if ("NULLIF".equalsIgnoreCase(method.getTokenText())) usesNullIf = true; } @@ -1008,7 +1003,7 @@ else if (name.equals("timestampadd") || name.equals("timestampdiff")) args.add(exprList.childList().get(1)); args.add(exprList.childList().get(2)); exprList._replaceChildren(args); - validateTimestampConstant(args.get(0)); + validateTimestampConstant(args.getFirst()); } else if (name.equals("age")) { @@ -1065,7 +1060,7 @@ else if (name.equals("age")) if (children.size() > 1 && first(children) instanceof QDistinct) { - children.remove(0); + children.removeFirst(); distinct = true; } @@ -1871,8 +1866,8 @@ static QExpr resolveMethods(QExpr expr) QIdentifier methodName = null; if (expr instanceof QMethodCall) { - if (expr.childList().get(0) instanceof QIdentifier) - methodName = (QIdentifier)expr.childList().get(0); + if (expr.childList().getFirst() instanceof QIdentifier) + methodName = (QIdentifier)expr.childList().getFirst(); } QExpr ret = (QExpr) expr.clone(); @@ -2139,7 +2134,7 @@ private void good(String sql) List errors = new ArrayList<>(); QNode q = (new SqlParser()).parseQuery(sql,errors,null); if (!errors.isEmpty()) - fail(errors.get(0), sql); + fail(errors.getFirst(), sql); assertNotNull(q); } diff --git a/query/src/org/labkey/query/view/testDataSource.jsp b/query/src/org/labkey/query/view/testDataSource.jsp index 3b14006f074..244283d9287 100644 --- a/query/src/org/labkey/query/view/testDataSource.jsp +++ b/query/src/org/labkey/query/view/testDataSource.jsp @@ -60,19 +60,19 @@ Set skipTablePrefixes = new HashSet<>(); populateSets(skipTables, skipTablePrefixes, form.getExcludeTables()); - LOG.info("Started test of data source " + scope.getDataSourceName()); + LOG.info("Started test of data source {}", scope.getDataSourceName()); Collection schemaNames = scope.getSchemaNames(); for (String schemaName : schemaNames) { if (skipSchemas.contains(schemaName) || skipSchemaPrefixes.stream().anyMatch(schemaName::startsWith)) { - LOG.info("Schema " + schemaName + " SKIPPED"); + LOG.info("Schema {} SKIPPED", schemaName); %>Schema <%=h(schemaName)%> SKIPPED
<% } else { - LOG.info("Schema " + schemaName + ":"); + LOG.info("Schema {}:", schemaName); DbSchema schema = scope.getSchema(schemaName, DbSchemaType.Bare); %>Schema <%=h(schemaName)%> has <%=h(StringUtilsLabKey.pluralize(schema.getTableNames().size(), "table"))%>
<% List tableNames = new ArrayList<>(schema.getTableNames()); @@ -83,14 +83,14 @@ String fullName = schemaName + "." + tableName; if (skipTables.contains(fullName) || skipTablePrefixes.stream().anyMatch(tableName::startsWith)) { - LOG.info("Table " + fullName + " SKIPPED"); + LOG.info("Table {} SKIPPED", fullName); %>  <%=h(tableName)%> SKIPPED
<% continue; } TableInfo table = schema.getTable(tableName); %>  <%=h(tableName)%><% - LOG.info("Table " + fullName + ":"); + LOG.info("Table {}:", fullName); TableSelector selector = new TableSelector(table); long count; try @@ -114,7 +114,7 @@ while (results.next()) rowCount++; } - LOG.info(StringUtilsLabKey.pluralize(rowCount, "row") + " read"); + LOG.info("{} read", StringUtilsLabKey.pluralize(rowCount, "row")); %>
<% } catch (Throwable t) @@ -125,5 +125,5 @@ } } - LOG.info("Completed test of data source " + scope.getDataSourceName()); + LOG.info("Completed test of data source {}", scope.getDataSourceName()); %> diff --git a/query/test/src/org/labkey/test/tests/query/CrossFolderDataClassTest.java b/query/test/src/org/labkey/test/tests/query/CrossFolderDataClassTest.java index ba58c16657f..3ba13129bce 100644 --- a/query/test/src/org/labkey/test/tests/query/CrossFolderDataClassTest.java +++ b/query/test/src/org/labkey/test/tests/query/CrossFolderDataClassTest.java @@ -97,7 +97,7 @@ public void testIssue45664() throws Exception 1, shownData.size()); // ensure the record shows the expected rowId and DataClass/Name values - var newRecord = shownData.get(0); + var newRecord = shownData.getFirst(); assertEquals("Expect Jeff to be the name value", "Jeff", newRecord.get("Name")); assertNotNull("Expect metadata rowId to be shown in subfolder view", diff --git a/search/src/org/labkey/search/model/AbstractSearchService.java b/search/src/org/labkey/search/model/AbstractSearchService.java index 1fb09fbf135..c63159cb4ed 100644 --- a/search/src/org/labkey/search/model/AbstractSearchService.java +++ b/search/src/org/labkey/search/model/AbstractSearchService.java @@ -1362,7 +1362,7 @@ private void _indexLoop() GUID containerId = i._res.getContainerId(); Container c = ContainerManager.getForId(containerId); String containerPath = c != null ? c.getPath() : "UNKNOWN PATH: Container not found!"; - categoryLogger.debug(category + " " + i._res.getDocumentId() + " " + containerPath + " " + containerId); + categoryLogger.debug("{} {} {} {}", category, i._res.getDocumentId(), containerPath, containerId); } } } diff --git a/search/src/org/labkey/search/model/DavCrawler.java b/search/src/org/labkey/search/model/DavCrawler.java index 30ae722d79a..72a2d868ab2 100644 --- a/search/src/org/labkey/search/model/DavCrawler.java +++ b/search/src/org/labkey/search/model/DavCrawler.java @@ -203,7 +203,7 @@ public void shutdownStarted() public void startFull(Path path, boolean force) { - _log.debug("START FULL: " + path); + _log.debug("START FULL: {}", path); if (null == path) path = WebdavService.get().getResolver().getRootPath(); @@ -225,7 +225,7 @@ public void addPathToCrawl(@Nullable Path start, @Nullable Date nextCrawl) { if (null != start) { - _log.debug("START CONTINUOUS " + start); + _log.debug("START CONTINUOUS {}", start); // make sure path exists if (null == nextCrawl) { @@ -291,7 +291,7 @@ public void run() _listingRateLimiter.add(1, isCrawlerThread); - _log.debug("IndexDirectoryJob.run(" + _path + ")"); + _log.debug("IndexDirectoryJob.run({})", _path); _directory = getResolver().lookup(_path); @@ -417,7 +417,6 @@ public void setLastIndexed(long ms, long modified) } else if (!child.shouldIndex()) { - continue; } else if (!skipContainer(child)) { @@ -559,7 +558,7 @@ IndexDirectoryJob findSomeWork() if (!Path.rootPath.equals(path)) { - _log.debug("findSomeWork(): adding path to in memory queue: " + path.toString() + " (lastCrawl=" + lastCrawl + ", nextCrawl=" + nextCrawl); + _log.debug("findSomeWork(): adding path to in memory queue: {} (lastCrawl={}, nextCrawl={}", path.toString(), lastCrawl, nextCrawl); crawlQueue.add(new IndexDirectoryJob(path, lastCrawl, nextCrawl)); } } @@ -573,7 +572,7 @@ IndexDirectoryJob findSomeWork() else { var path = crawlQueue.removeFirst(); - _log.debug("findSomeWork(): now crawling " + path._directory); + _log.debug("findSomeWork(): now crawling {}", path._directory); return path; } } diff --git a/search/src/org/labkey/search/model/LuceneSearchServiceImpl.java b/search/src/org/labkey/search/model/LuceneSearchServiceImpl.java index 18edf6df9fd..2cd48890464 100644 --- a/search/src/org/labkey/search/model/LuceneSearchServiceImpl.java +++ b/search/src/org/labkey/search/model/LuceneSearchServiceImpl.java @@ -711,7 +711,7 @@ public boolean processAndIndex(String id, WebdavResource r, Throwable[] handledE if (null == c) { - _log.debug("skipping item " + r.getDocumentId() + " because container is not found: " + r.getContainerId()); + _log.debug("skipping item {} because container is not found: {}", r.getDocumentId(), r.getContainerId()); return false; } @@ -806,7 +806,7 @@ public boolean processAndIndex(String id, WebdavResource r, Throwable[] handledE if (null == title) logBadDocument("Null title", r); - _log.debug("parsed " + url); + _log.debug("parsed {}", url); if (null == props.get(PROPERTY.keywordsMed.toString()) && StringUtils.isBlank(keywordsMed.toString())) keywordsMed = new StringBuilder(title); @@ -911,9 +911,9 @@ else if (owner instanceof User) if (_log.isDebugEnabled()) { if (_log.isTraceEnabled()) - _log.trace("indexing " + dump(r, doc)); + _log.trace("indexing {}", dump(r, doc)); else - _log.debug("indexing docid: " + r.getDocumentId()); + _log.debug("indexing docid: {}", r.getDocumentId()); } boolean result = index(r.getDocumentId(), doc); @@ -921,9 +921,9 @@ else if (owner instanceof User) if (_log.isDebugEnabled()) { if (_log.isTraceEnabled()) - _log.trace("finished indexing " + dump(r, doc)); + _log.trace("finished indexing {}", dump(r, doc)); else - _log.debug("finished indexing docid: " + r.getDocumentId()); + _log.debug("finished indexing docid: {}", r.getDocumentId()); } return result; @@ -1178,7 +1178,7 @@ private void addDateField(Document doc, FIELD_NAME fieldName, long date) private void logBadDocument(String problem, WebdavResource r) { - _log.error(problem + " for " + r.getDocumentId()); + _log.error("{} for {}", problem, r.getDocumentId()); throw new IllegalStateException(problem); } @@ -1334,7 +1334,7 @@ private void logAsWarning(WebdavResource r, String message) private void logAsWarning(WebdavResource r, String message, @Nullable String rootMessage) { - _log.warn("Can't index file \"" + getNameToLog(r) + "\" due to: " + message + (null != rootMessage ? " [" + rootMessage + "]" : "")); + _log.warn("Can't index file \"{}\" due to: {}{}", getNameToLog(r), message, null != rootMessage ? " [" + rootMessage + "]" : ""); } private static class PreProcessingException extends Exception @@ -1445,7 +1445,7 @@ protected void deleteDocumentsForPrefix(String prefix) // Run the query before delete, but only if Log4J debug level is set if (_log.isDebugEnabled() && _indexManager.isReal()) { - _log.debug("Deleting " + getDocCount(query) + " docs with prefix \"" + prefix + "\""); + _log.debug("Deleting {} docs with prefix \"{}\"", getDocCount(query), prefix); } _indexManager.deleteQuery(query); @@ -1516,7 +1516,7 @@ private boolean index(String id, Document doc) } catch(Throwable e) { - _log.error("Indexing error with " + id, e); + _log.error("Indexing error with {}", id, e); } return false; @@ -1532,7 +1532,7 @@ protected void deleteIndexedContainer(String id) // Count the docs and log before deleting them, but only if Log4J debug level is set if (_log.isDebugEnabled() && _indexManager.isReal()) { - _log.debug("Deleting " + getDocCount(query) + " docs from container " + id); + _log.debug("Deleting {} docs from container {}", getDocCount(query), id); } _indexManager.deleteQuery(query); @@ -1561,7 +1561,7 @@ protected void clearIndexedFileSystemFiles(Container container) // Run the query before delete, but only if Log4J debug level is set if (_log.isDebugEnabled() && _indexManager.isReal()) { - _log.debug("Deleting " + getDocCount(query) + " docs from container " + container); + _log.debug("Deleting {} docs from container {}", getDocCount(query), container); } _indexManager.deleteQuery(query); @@ -1997,7 +1997,7 @@ public void testTikaParsing() throws IOException, TikaException, SAXException for (File file : sampledata.listFiles(File::isFile)) { - _log.info("Attempting to parse: " + file.getName()); + _log.info("Attempting to parse: {}", file.getName()); String docId = "testtika"; SimpleDocumentResource resource = new SimpleDocumentResource(new Path(file.getName()), docId, null, null, null, null, null); ContentHandler handler = new BodyContentHandler(-1); @@ -2060,7 +2060,7 @@ public void testTikaParsing() throws IOException, TikaException, SAXException if (strict) fail(file.getName() + ": " + message); else - _log.info(file.getName() + ": " + message); + _log.info("{}: {}", file.getName(), message); } } } diff --git a/search/src/org/labkey/search/model/NoopWritableIndex.java b/search/src/org/labkey/search/model/NoopWritableIndex.java index 910e14fafd8..ad15c116100 100644 --- a/search/src/org/labkey/search/model/NoopWritableIndex.java +++ b/search/src/org/labkey/search/model/NoopWritableIndex.java @@ -112,7 +112,7 @@ public boolean isClosed() private void log(String action) { if (0 == (_errors.get() % 10000)) - _log.warn("Unable to " + action + "; " + _statusMessage); + _log.warn("Unable to {}; {}", action, _statusMessage); _errors.incrementAndGet(); } diff --git a/search/src/org/labkey/search/model/SavePaths.java b/search/src/org/labkey/search/model/SavePaths.java index 7ff93620012..dfea23c46b1 100644 --- a/search/src/org/labkey/search/model/SavePaths.java +++ b/search/src/org/labkey/search/model/SavePaths.java @@ -199,7 +199,7 @@ private int _ensure(Path path) throws SQLException Integer ident = new SqlSelector(getSearchSchema(),insert).setLogLevel(Level.ERROR).getObject(Integer.class); if (null != ident) { - _log.debug("insertPath(" + path + ", " + valueNextCrawl + ")"); + _log.debug("insertPath({}, {})", path, valueNextCrawl); return ident; } return getId(path); @@ -243,7 +243,7 @@ public boolean insertPath(Path path, Date nextCrawl) f.append(")"); int count = new SqlExecutor(getSearchSchema()).execute(f); if (count == 1) - _log.debug("insertPath(" + path + ", " + nextCrawl + ")"); + _log.debug("insertPath({}, {})", path, nextCrawl); return count==1; } catch (SQLException x) @@ -319,7 +319,7 @@ public void clearFailedDocuments() @Override public void deletePath(Path path) { - _log.debug("deleting crawler paths that start with '" + path + "'"); + _log.debug("deleting crawler paths that start with '{}'", path); // UNDONE LIKE ESCAPE new SqlExecutor(getSearchSchema()).execute("DELETE FROM search.CrawlResources WHERE Parent IN (SELECT id FROM search.CrawlCollections WHERE Path LIKE ?)", toPathString(path) + "%"); new SqlExecutor(getSearchSchema()).execute("DELETE FROM search.CrawlCollections WHERE Path LIKE ?", toPathString(path) + "%"); diff --git a/search/src/org/labkey/search/model/SearchStartupProperties.java b/search/src/org/labkey/search/model/SearchStartupProperties.java index 4fa606dbeec..c6a3f547fee 100644 --- a/search/src/org/labkey/search/model/SearchStartupProperties.java +++ b/search/src/org/labkey/search/model/SearchStartupProperties.java @@ -25,7 +25,7 @@ public void setProperty(@NotNull SearchService ss, SearchIndexStartupHandler ind { LuceneDirectoryType type = EnumUtils.getEnum(LuceneDirectoryType.class, value); if (null == type) - LOG.error("Unrecognized value for \"directoryType\": \"" + value + "\""); + LOG.error("Unrecognized value for \"directoryType\": \"{}\"", value); else SearchPropertyManager.setDirectoryType(null, type); } @@ -43,7 +43,7 @@ public void setProperty(@NotNull SearchService ss, SearchIndexStartupHandler ind { CrawlerRunningState state = EnumUtils.getEnum(CrawlerRunningState.class, value); if (null == state) - LOG.error("Unrecognized value for \"crawlerState\": \"" + value + "\""); + LOG.error("Unrecognized value for \"crawlerState\": \"{}\"", value); else SearchPropertyManager.setCrawlerRunningState(null, state); } diff --git a/search/src/org/labkey/search/model/WritableIndexManagerImpl.java b/search/src/org/labkey/search/model/WritableIndexManagerImpl.java index 48a13ad5ed1..071aebafe1e 100644 --- a/search/src/org/labkey/search/model/WritableIndexManagerImpl.java +++ b/search/src/org/labkey/search/model/WritableIndexManagerImpl.java @@ -201,7 +201,7 @@ public void deleteDocuments(Collection ids) } catch (Throwable e) { - _log.error("Indexing error deleting " + StringUtils.trimToEmpty(currentId), e); + _log.error("Indexing error deleting {}", StringUtils.trimToEmpty(currentId), e); ExceptionUtil.logExceptionToMothership(null, e); } } diff --git a/specimen/src/org/labkey/specimen/RequestedSpecimens.java b/specimen/src/org/labkey/specimen/RequestedSpecimens.java index fb16332945b..3662eb4c4c1 100644 --- a/specimen/src/org/labkey/specimen/RequestedSpecimens.java +++ b/specimen/src/org/labkey/specimen/RequestedSpecimens.java @@ -43,7 +43,7 @@ public List getProvidingLocations() _providingLocations = Collections.emptyList(); else { - Container container = _vials.get(0).getContainer(); + Container container = _vials.getFirst().getContainer(); _providingLocations = new ArrayList<>(_providingLocationIds.size()); for (Integer locationId : _providingLocationIds) diff --git a/specimen/src/org/labkey/specimen/SpecimenManager.java b/specimen/src/org/labkey/specimen/SpecimenManager.java index 8b1cef9dfc3..0f53cbe877a 100644 --- a/specimen/src/org/labkey/specimen/SpecimenManager.java +++ b/specimen/src/org/labkey/specimen/SpecimenManager.java @@ -193,7 +193,7 @@ public Map getSpecimenComments(List vials) if (vials == null || vials.isEmpty()) return Collections.emptyMap(); - Container container = vials.get(0).getContainer(); + Container container = vials.getFirst().getContainer(); final Map result = new HashMap<>(); int offset = 0; @@ -392,7 +392,7 @@ public AdditiveType getAdditiveType(Container c, int rowId) { List additiveTypes = getAdditiveTypes(c, new SimpleFilter(FieldKey.fromParts("RowId"), rowId)); if (!additiveTypes.isEmpty()) - return additiveTypes.get(0); + return additiveTypes.getFirst(); return null; } @@ -408,7 +408,7 @@ public DerivativeType getDerivativeType(Container c, int rowId) { List derivativeTypes = getDerivativeTypes(c, new SimpleFilter(FieldKey.fromParts("RowId"), rowId)); if (!derivativeTypes.isEmpty()) - return derivativeTypes.get(0); + return derivativeTypes.getFirst(); return null; } @@ -444,7 +444,7 @@ public Vial getVial(Container container, User user, String globalUniqueId) throw new IllegalStateException("Expected at least one vial to exactly match the specified global unique ID: " + globalUniqueId); } else - return matches.get(0); + return matches.getFirst(); } /** Looks for any specimens that have the given id as a globalUniqueId */ @@ -452,7 +452,7 @@ public PrimaryType getPrimaryType(Container c, int rowId) { List primaryTypes = getPrimaryTypes(c, new SimpleFilter(FieldKey.fromParts("RowId"), rowId), null); if (!primaryTypes.isEmpty()) - return primaryTypes.get(0); + return primaryTypes.getFirst(); return null; } @@ -529,7 +529,7 @@ public Vial getVial(Container container, User user, long rowId) List vials = getVials(container, user, filter); if (vials.isEmpty()) return null; - return vials.get(0); + return vials.getFirst(); } public void deleteSpecimen(@NotNull Vial vial, boolean clearCaches) @@ -564,7 +564,7 @@ public long getMaxExternalId(Container container) TableInfo tableInfo = SpecimenSchema.get().getTableInfoSpecimenEvent(container); SQLFragment sql = new SQLFragment("SELECT MAX(ExternalId) FROM "); sql.append(tableInfo); - return new SqlSelector(tableInfo.getSchema(), sql).getArrayList(Long.class).get(0); + return new SqlSelector(tableInfo.getSchema(), sql).getArrayList(Long.class).getFirst(); } public String getFirstProcessedByInitials(List dateOrderedEvents) diff --git a/specimen/src/org/labkey/specimen/SpecimenModule.java b/specimen/src/org/labkey/specimen/SpecimenModule.java index 833af41d63d..798e90c4c6f 100644 --- a/specimen/src/org/labkey/specimen/SpecimenModule.java +++ b/specimen/src/org/labkey/specimen/SpecimenModule.java @@ -41,7 +41,6 @@ import org.labkey.api.query.QueryUpdateService; import org.labkey.api.query.QueryView; import org.labkey.api.query.UserSchema; -import org.labkey.api.query.ValidationException; import org.labkey.api.security.User; import org.labkey.api.security.roles.RoleManager; import org.labkey.api.specimen.SpecimenMigrationService; @@ -174,7 +173,7 @@ public ActionURL getSpecimensURL(Container c) } @Override - public void importSpecimenArchive(@Nullable FileLike inputFile, PipelineJob job, SimpleStudyImportContext ctx, boolean merge, boolean syncParticipantVisit) throws PipelineJobException, ValidationException + public void importSpecimenArchive(@Nullable FileLike inputFile, PipelineJob job, SimpleStudyImportContext ctx, boolean merge, boolean syncParticipantVisit) throws PipelineJobException { AbstractSpecimenTask.doImport(inputFile, job, ctx, merge, syncParticipantVisit); } diff --git a/specimen/src/org/labkey/specimen/SpecimenRequestManager.java b/specimen/src/org/labkey/specimen/SpecimenRequestManager.java index 9a62c131090..2089c35b338 100644 --- a/specimen/src/org/labkey/specimen/SpecimenRequestManager.java +++ b/specimen/src/org/labkey/specimen/SpecimenRequestManager.java @@ -106,7 +106,7 @@ public List getRequestStatuses(Container c, User user) List statuses = new ArrayList<>(_requestStatusHelper.getCollection(c)); // if the 'not-yet-submitted' status doesn't exist, create it here, with sort order -1, // so it's always first. - if (statuses.isEmpty() || statuses.get(0).getSortOrder() != -1) + if (statuses.isEmpty() || statuses.getFirst().getSortOrder() != -1) { SpecimenRequestStatus notYetSubmittedStatus = new SpecimenRequestStatus(); notYetSubmittedStatus.setContainer(c); @@ -127,9 +127,9 @@ public List getRequestStatuses(Container c, User user) public SpecimenRequestStatus getRequestShoppingCartStatus(Container c, User user) { List statuses = getRequestStatuses(c, user); - if (statuses.get(0).getSortOrder() != -1) + if (statuses.getFirst().getSortOrder() != -1) throw new IllegalStateException("Shopping cart status should be created automatically."); - return statuses.get(0); + return statuses.getFirst(); } public SpecimenRequestStatus getInitialRequestStatus(Container c, User user, boolean nonCart) @@ -651,7 +651,7 @@ private void updateRequestabilityAndCounts(List vials, User user) throws R private Container getContainer(List vials) { - Container container = vials.get(0).getContainer(); + Container container = vials.getFirst().getContainer(); if (AppProps.getInstance().isDevMode()) { for (int i = 1; i < vials.size(); i++) @@ -1253,7 +1253,7 @@ else if (preferredLocations.size() > 1) { Vial selectedVial = null; if (preferredLocation == null) - selectedVial = vials.get(0); + selectedVial = vials.getFirst(); else { for (Iterator it = vials.iterator(); it.hasNext() && selectedVial == null;) diff --git a/specimen/src/org/labkey/specimen/actions/ReportConfigurationBean.java b/specimen/src/org/labkey/specimen/actions/ReportConfigurationBean.java index 9cdd98a0e35..54c6edc450d 100644 --- a/specimen/src/org/labkey/specimen/actions/ReportConfigurationBean.java +++ b/specimen/src/org/labkey/specimen/actions/ReportConfigurationBean.java @@ -82,13 +82,7 @@ private void registerReportFactory(String category, SpecimenVisitReportParameter { // we have to explicitly set the view context for these reports, since the factories aren't being newed-up by Spring in the usual way: factory.setViewContext(_viewContext); - List factories = _reportFactories.get(category); - - if (factories == null) - { - factories = new ArrayList<>(); - _reportFactories.put(category, factories); - } + List factories = _reportFactories.computeIfAbsent(category, _ -> new ArrayList<>()); factories.add(factory); } diff --git a/specimen/src/org/labkey/specimen/actions/SpecimenController.java b/specimen/src/org/labkey/specimen/actions/SpecimenController.java index e2fd64a0701..5fb8abaa709 100644 --- a/specimen/src/org/labkey/specimen/actions/SpecimenController.java +++ b/specimen/src/org/labkey/specimen/actions/SpecimenController.java @@ -5680,7 +5680,7 @@ private String getExistingComment(QueryView queryView) } catch (Exception e) { - LOG.error("Error encountered trying to get " + StudyService.get().getSubjectNounSingular(getContainer()) + " comments", e); + LOG.error("Error encountered trying to get {} comments", StudyService.get().getSubjectNounSingular(getContainer()), e); } } return null; diff --git a/specimen/src/org/labkey/specimen/actions/UpdateSpecimenCommentsBean.java b/specimen/src/org/labkey/specimen/actions/UpdateSpecimenCommentsBean.java index 46ba8d4d0b7..c4dce3161c4 100644 --- a/specimen/src/org/labkey/specimen/actions/UpdateSpecimenCommentsBean.java +++ b/specimen/src/org/labkey/specimen/actions/UpdateSpecimenCommentsBean.java @@ -35,7 +35,7 @@ public UpdateSpecimenCommentsBean(ViewContext context, List vials, String Map currentComments = SpecimenManager.get().getSpecimenComments(vials); boolean mixedComments = false; boolean mixedFlagState = false; - SpecimenComment prevComment = currentComments.get(vials.get(0)); + SpecimenComment prevComment = currentComments.get(vials.getFirst()); for (int i = 1; i < vials.size() && (!mixedFlagState || !mixedComments); i++) { diff --git a/specimen/src/org/labkey/specimen/importer/AbstractSpecimenTask.java b/specimen/src/org/labkey/specimen/importer/AbstractSpecimenTask.java index 951b261b880..e61925678ed 100644 --- a/specimen/src/org/labkey/specimen/importer/AbstractSpecimenTask.java +++ b/specimen/src/org/labkey/specimen/importer/AbstractSpecimenTask.java @@ -223,12 +223,12 @@ public VirtualFile getSpecimenDir(PipelineJob job, SimpleStudyImportContext ctx, if (job != null) job.setStatus("UNZIPPING SPECIMEN ARCHIVE"); - ctx.getLogger().info("Unzipping specimen archive " + specimenArchive); + ctx.getLogger().info("Unzipping specimen archive {}", specimenArchive); String tempDirName = DateUtil.formatDateTime(new Date(), "yyMMddHHmmssSSS"); _unzipDir = specimenArchive.getParent().resolveChild(tempDirName); ZipUtil.unzipToDirectory(specimenArchive, _unzipDir, ctx.getLogger()); - ctx.getLogger().info("Archive unzipped to " + _unzipDir); + ctx.getLogger().info("Archive unzipped to {}", _unzipDir); return new FileSystemFile(_unzipDir); } } diff --git a/specimen/src/org/labkey/specimen/importer/RequestabilityManager.java b/specimen/src/org/labkey/specimen/importer/RequestabilityManager.java index cc6ccdc0045..f9afa4a6478 100644 --- a/specimen/src/org/labkey/specimen/importer/RequestabilityManager.java +++ b/specimen/src/org/labkey/specimen/importer/RequestabilityManager.java @@ -824,10 +824,10 @@ private void updateRequestability(Container container, User user, boolean resetT { String action = rule.getMarkType().getLabel().toLowerCase(); if (logger != null) - logger.info("\tMarking vials " + action + " based on " + rule.getName()); + logger.info("\tMarking vials {} based on {}", action, rule.getName()); int updatedCount = rule.updateRequestability(user, vials); if (logger != null) - logger.info("\t" + updatedCount + " vials marked " + action + "."); + logger.info("\t{} vials marked {}.", updatedCount, action); } if (logger != null) diff --git a/specimen/src/org/labkey/specimen/importer/SpecimenImporter.java b/specimen/src/org/labkey/specimen/importer/SpecimenImporter.java index 86e5d0465a8..26f620a5b8b 100644 --- a/specimen/src/org/labkey/specimen/importer/SpecimenImporter.java +++ b/specimen/src/org/labkey/specimen/importer/SpecimenImporter.java @@ -2561,15 +2561,15 @@ protected void checkForConflictingSpecimens(DbSchema schema, String tempTable, L { throw new IllegalStateException("Expected one and only one count of rows."); } - else if (0 != counts.get(0) && _generateGlobalUniqueIds > 0) + else if (0 != counts.getFirst() && _generateGlobalUniqueIds > 0) { // We were trying to generate globalUniqueIds throw new OptimisticConflictException("Attempt to generate global unique ids failed.", null, 0); } - else if (0 != counts.get(0)) + else if (0 != counts.getFirst()) { throw new IllegalStateException("With an editable specimen repository, importing may not reference any existing specimen. " + - counts.get(0) + " imported specimen events refer to existing specimens.") ; + counts.getFirst() + " imported specimen events refer to existing specimens.") ; } info("No conflicting specimens found"); } @@ -2724,7 +2724,7 @@ private TempTablesHolder createTempTable() sql.append("\n(\n RowId ").append(dialect.getUniqueIdentType()).append(", "); columns.add(new BaseColumnInfo("RowId", JdbcType.INTEGER, 0, false)); - columns.get(0).setAutoIncrement(true); + columns.getFirst().setAutoIncrement(true); sql.append("LSID ").append(strType).append("(300) NOT NULL, "); columns.add(new BaseColumnInfo("LSID", JdbcType.VARCHAR, 300, false)); @@ -2837,7 +2837,7 @@ public void createTable() columns.add(new BaseColumnInfo("Container", JdbcType.GUID, 0, false)); columns.add(new BaseColumnInfo("id", JdbcType.VARCHAR, 0, false)); columns.add(new BaseColumnInfo("s", JdbcType.VARCHAR, 30, true)); - columns.get(columns.size()-1).setKeyField(true); + columns.getLast().setKeyField(true); columns.add(new BaseColumnInfo("i", JdbcType.INTEGER, 0, true)); columns.add(new BaseColumnInfo("entityid", JdbcType.GUID, 0, false)); _simpleTable = new TempTableInfo(TABLE, (List)(List)columns, Arrays.asList("s")); @@ -2929,7 +2929,7 @@ public Object getValue(Map row) sallyGUID = (String)row1.get("entityid"); // assertNotNull(sallyGUID); - assertEquals(null, row2.get("s")); + assertNull(row2.get("s")); assertEquals(300, row2.get("i")); assertEquals("3", row2.get("id")); nullGUID = (String)row2.get("entityid"); @@ -2971,7 +2971,7 @@ public Object getValue(Map row) assertEquals("2", row1.get("id")); assertEquals(sallyGUID, row1.get("entityid")); - assertEquals(null, row2.get("s")); + assertNull(row2.get("s")); assertEquals(305, row2.get("i")); assertEquals("3", row2.get("id")); assertEquals(nullGUID, row2.get("entityid")); diff --git a/specimen/src/org/labkey/specimen/importer/SpecimenSettingsImporter.java b/specimen/src/org/labkey/specimen/importer/SpecimenSettingsImporter.java index 8cbd2ad4a71..cc6d224e9cf 100644 --- a/specimen/src/org/labkey/specimen/importer/SpecimenSettingsImporter.java +++ b/specimen/src/org/labkey/specimen/importer/SpecimenSettingsImporter.java @@ -113,7 +113,7 @@ public void process(SimpleStudyImportContext ctx, VirtualFile studyDir, BindExce SpecimensDocument specimensDoc = (SpecimensDocument)settingsDir.getXmlBean(xmlSettings.getSettings()); importSettings(ctx, specimensDoc.getSpecimens()); - ctx.getLogger().info("Done importing " + getDescription()); + ctx.getLogger().info("Done importing {}", getDescription()); } } } @@ -203,7 +203,7 @@ private void importRequestStatuses(SimpleStudyImportContext ctx, SpecimenSetting String newStatusLabel = xmlStatusArray[i].isSetLabel() && xmlStatusArray[i].getLabel() != null && !xmlStatusArray[i].getLabel().isEmpty() ? xmlStatusArray[i].getLabel() : null; if (inUseStatusLabels.contains(newStatusLabel)) { - ctx.getLogger().warn("Skipping request status that matches an existing status label: " + newStatusLabel); + ctx.getLogger().warn("Skipping request status that matches an existing status label: {}", newStatusLabel); } else if (newStatusLabel != null) { @@ -289,8 +289,7 @@ private void importRequestActors(SimpleStudyImportContext ctx, SpecimenSettingsT if (location == null) { - ctx.getLogger().warn("Request actor group not created for \"" + actor.getLabel() - + ", " + newActorGroup.getName() + "\". Could not find matching study location."); + ctx.getLogger().warn("Request actor group not created for \"{}, {}\". Could not find matching study location.", actor.getLabel(), newActorGroup.getName()); continue; } } @@ -354,14 +353,14 @@ private void createDefaultRequirement(DefaultRequirementsType xmlReqs, SimpleStu { SpecimenRequestRequirement requirement = new SpecimenRequestRequirement(); requirement.setContainer(ctx.getContainer()); - requirement.setActorId(matchingActors.get(0).getRowId()); + requirement.setActorId(matchingActors.getFirst().getRowId()); requirement.setDescription(xmlReq.getDescription()); requirement.setRequestId(-1); SpecimenRequestRequirementProvider.get().createDefaultRequirement(ctx.getUser(), requirement, type); } else { - ctx.getLogger().warn("Could not find matching actor with label: " + xmlReq.getActor()); + ctx.getLogger().warn("Could not find matching actor with label: {}", xmlReq.getActor()); } } } @@ -425,7 +424,7 @@ private void importRequestForm(SimpleStudyImportContext ctx, SpecimenSettingsTyp inputs.add(input); } else - ctx.getLogger().info("There is currently a form with the same title: " + form.getTitle() + ", skipping this from import"); + ctx.getLogger().info("There is currently a form with the same title: {}, skipping this from import", form.getTitle()); } inputs.sort(Comparator.comparingInt(SpecimenRequestInput::getDisplayOrder)); SpecimenRequestManager.get().saveNewSpecimenRequestInputs(ctx.getContainer(), inputs.toArray(new SpecimenRequestInput[0])); diff --git a/specimen/src/org/labkey/specimen/pipeline/FileAnalysisSpecimenTask.java b/specimen/src/org/labkey/specimen/pipeline/FileAnalysisSpecimenTask.java index 546b5e0d37d..680c5b438d8 100644 --- a/specimen/src/org/labkey/specimen/pipeline/FileAnalysisSpecimenTask.java +++ b/specimen/src/org/labkey/specimen/pipeline/FileAnalysisSpecimenTask.java @@ -41,7 +41,7 @@ protected FileLike getSpecimenFile(PipelineJob job) List paths = support.getInputFiles(); // there should only be a single file associated with this task assert paths.size() == 1; - return paths.get(0); + return paths.getFirst(); } @Override diff --git a/specimen/src/org/labkey/specimen/pipeline/SpecimenJobSupport.java b/specimen/src/org/labkey/specimen/pipeline/SpecimenJobSupport.java index 11043224c5e..198155dfaf2 100644 --- a/specimen/src/org/labkey/specimen/pipeline/SpecimenJobSupport.java +++ b/specimen/src/org/labkey/specimen/pipeline/SpecimenJobSupport.java @@ -16,7 +16,6 @@ package org.labkey.specimen.pipeline; -import org.labkey.api.admin.ImportException; import org.labkey.api.study.importer.SimpleStudyImportContext; import org.labkey.vfs.FileLike; @@ -27,7 +26,7 @@ */ public interface SpecimenJobSupport { - FileLike getSpecimenArchivePath() throws ImportException; + FileLike getSpecimenArchivePath(); boolean isMerge(); SimpleStudyImportContext getImportContext(); } diff --git a/specimen/src/org/labkey/specimen/pipeline/SpecimenReloadJob.java b/specimen/src/org/labkey/specimen/pipeline/SpecimenReloadJob.java index 4ddbbb6e6ac..819dc54c718 100644 --- a/specimen/src/org/labkey/specimen/pipeline/SpecimenReloadJob.java +++ b/specimen/src/org/labkey/specimen/pipeline/SpecimenReloadJob.java @@ -24,7 +24,6 @@ import org.labkey.api.view.ViewBackgroundInfo; import org.labkey.vfs.FileLike; -import java.io.File; import java.io.Serializable; /** diff --git a/specimen/src/org/labkey/specimen/pipeline/SpecimenReloadJobSupport.java b/specimen/src/org/labkey/specimen/pipeline/SpecimenReloadJobSupport.java index 2ecc7cd0306..5732b0b60f4 100644 --- a/specimen/src/org/labkey/specimen/pipeline/SpecimenReloadJobSupport.java +++ b/specimen/src/org/labkey/specimen/pipeline/SpecimenReloadJobSupport.java @@ -18,8 +18,6 @@ import org.labkey.api.study.SpecimenTransform; import org.labkey.vfs.FileLike; -import java.io.File; - /** * Created by klum on 5/24/2014. */ diff --git a/specimen/src/org/labkey/specimen/pipeline/SpecimenReloadTask.java b/specimen/src/org/labkey/specimen/pipeline/SpecimenReloadTask.java index 6a88f0e86a9..eade63b4347 100644 --- a/specimen/src/org/labkey/specimen/pipeline/SpecimenReloadTask.java +++ b/specimen/src/org/labkey/specimen/pipeline/SpecimenReloadTask.java @@ -28,9 +28,7 @@ import org.labkey.api.util.FileType; import org.labkey.api.util.FileUtil; import org.labkey.vfs.FileLike; -import org.labkey.vfs.FileSystemLike; -import java.io.File; import java.util.Collections; import java.util.List; diff --git a/specimen/src/org/labkey/specimen/query/BaseSpecimenPivotTable.java b/specimen/src/org/labkey/specimen/query/BaseSpecimenPivotTable.java index 03455d2336f..5d733c1a04f 100644 --- a/specimen/src/org/labkey/specimen/query/BaseSpecimenPivotTable.java +++ b/specimen/src/org/labkey/specimen/query/BaseSpecimenPivotTable.java @@ -181,11 +181,7 @@ public BaseSpecimenPivotTable(final TableInfo tinfo, final UserSchema schema) { super(tinfo, schema); - LogManager.getLogger(BaseSpecimenPivotTable.class).debug("creating specimen pivot\n" + - "SCHEMA=" + schema.getName() + " " + schema.getClass().getSimpleName()+"@"+System.identityHashCode(schema) + "\n" + - "TABLE=" + tinfo.getName() + " " + this.getClass().getSimpleName() + "@" + System.identityHashCode(this), - new Throwable("stack trace") - ); + LogManager.getLogger(BaseSpecimenPivotTable.class).debug("creating specimen pivot\nSCHEMA={} {}@{}\nTABLE={} {}@{}", schema.getName(), schema.getClass().getSimpleName(), System.identityHashCode(schema), tinfo.getName(), this.getClass().getSimpleName(), System.identityHashCode(this), new Throwable("stack trace")); addWrapColumn(_rootTable.getColumn(StudyService.get().getSubjectColumnName(getContainer()))); addWrapColumn(_rootTable.getColumn(StudyService.get().getSubjectVisitColumnName(getContainer()))); diff --git a/specimen/src/org/labkey/specimen/query/SpecimenQueryView.java b/specimen/src/org/labkey/specimen/query/SpecimenQueryView.java index 1126886f4ff..151d7875722 100644 --- a/specimen/src/org/labkey/specimen/query/SpecimenQueryView.java +++ b/specimen/src/org/labkey/specimen/query/SpecimenQueryView.java @@ -21,7 +21,6 @@ import org.labkey.api.collections.ResultSetRowMapFactory; import org.labkey.api.data.AbstractTableInfo; import org.labkey.api.data.Aggregate; -import org.labkey.api.data.ColumnHeaderType; import org.labkey.api.data.ColumnInfo; import org.labkey.api.data.Container; import org.labkey.api.data.ContainerManager; @@ -71,7 +70,6 @@ import org.labkey.specimen.settings.RepositorySettings; import org.labkey.specimen.settings.SettingsManager; -import java.io.IOException; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; @@ -871,19 +869,19 @@ public List getDisplayColumns() if (_viewType.isForExport()) { // Remove rowId column and update column, if present - DisplayColumn column = cols.get(0); + DisplayColumn column = cols.getFirst(); if (column.getName().equalsIgnoreCase("rowid") || column.getName().equalsIgnoreCase("update")) - cols.remove(0); - column = cols.get(0); + cols.removeFirst(); + column = cols.getFirst(); if (column.getName().equalsIgnoreCase("rowid") || column.getName().equalsIgnoreCase("update")) - cols.remove(0); + cols.removeFirst(); } if (_viewType.isVialView()) { if (_showHistoryLinks) { - cols.add(0, new SimpleDisplayColumn("[history]") + cols.addFirst(new SimpleDisplayColumn("[history]") { @Override public String renderURL(RenderContext ctx) @@ -913,7 +911,7 @@ public String renderURL(RenderContext ctx) if (settings.isEnableRequests() && !_viewType.isForExport() && getViewContext().getContainer().hasPermission(getUser(), RequestSpecimensPermission.class)) { // Only add this column if we're using advanced specimen management and not exported to email or attachment - cols.add(0, new SpecimenRequestDisplayColumn(this, getTable(), zeroVialIndicator, oneVialIndicator, + cols.addFirst(new SpecimenRequestDisplayColumn(this, getTable(), zeroVialIndicator, oneVialIndicator, SettingsManager.get().isSpecimenShoppingCartEnabled(getContainer()) && _showRecordSelectors)); } @@ -982,7 +980,7 @@ public void setShowRecordSelectors(boolean showRecordSelectors) _showRecordSelectors = showRecordSelectors; } - public String getSimpleHtmlTable() throws SQLException, IOException + public String getSimpleHtmlTable() throws SQLException { getSettings().setMaxRows(Table.ALL_ROWS); DataView view = createDataView(); @@ -1037,10 +1035,4 @@ public void addManageViewItems(MenuButton button, Map params) button.addMenuItem("Manage Views", url); } - - @Override - protected ColumnHeaderType getColumnHeaderType() - { - return ColumnHeaderType.Caption; - } } diff --git a/specimen/src/org/labkey/specimen/query/SpecimenUpdateService.java b/specimen/src/org/labkey/specimen/query/SpecimenUpdateService.java index 9368188076c..e42a9afaa36 100644 --- a/specimen/src/org/labkey/specimen/query/SpecimenUpdateService.java +++ b/specimen/src/org/labkey/specimen/query/SpecimenUpdateService.java @@ -396,7 +396,7 @@ public List> updateRows(User user, Container container, List } catch (ValidationException e) { - e.fillIn(getQueryTable().getPublicSchemaName(), getQueryTable().getName(), newRows.get(0), 0); + e.fillIn(getQueryTable().getPublicSchemaName(), getQueryTable().getName(), newRows.getFirst(), 0); errors.addRowError(e); throw errors; } @@ -516,7 +516,7 @@ private void checkEditability(Container container, Vial vial) throws ValidationE ArrayList counts = new SqlSelector(getQueryTable().getSchema(), sql).getArrayList(Integer.class); if (counts.size() > 1) throw new IllegalStateException("Expected one and only one count of rows."); - else if (!counts.isEmpty() && counts.get(0) != 0) + else if (!counts.isEmpty() && counts.getFirst() != 0) throw new ValidationException("Specimen may not be edited when it's in a non-final request."); } @@ -529,7 +529,7 @@ private void checkDeletability(Container container, Vial vial) throws Validation ArrayList counts = new SqlSelector(getQueryTable().getSchema(), sql).getArrayList(Integer.class); if (counts.size() > 1) throw new ValidationException("Expected one and only one count of rows."); - else if (!counts.isEmpty() && counts.get(0) != 0) + else if (!counts.isEmpty() && counts.getFirst() != 0) throw new ValidationException("Specimen may not be deleted because it has been used in a request."); } diff --git a/specimen/src/org/labkey/specimen/report/SpecimenVisitReport.java b/specimen/src/org/labkey/specimen/report/SpecimenVisitReport.java index d6c08bee3fa..eee91eb4be4 100644 --- a/specimen/src/org/labkey/specimen/report/SpecimenVisitReport.java +++ b/specimen/src/org/labkey/specimen/report/SpecimenVisitReport.java @@ -38,7 +38,6 @@ import java.util.ArrayList; import java.util.Collection; -import java.util.HashMap; import java.util.List; import java.util.Map; @@ -307,7 +306,7 @@ protected SimpleFilter replaceFilterParameterName(SimpleFilter filter, String ol FieldKey oldFieldKey = FieldKey.fromString(oldKey); for (SimpleFilter.FilterClause clause : filter.getClauses()) { - if (clause.getFieldKeys().size() == 1 && oldFieldKey.equals(clause.getFieldKeys().get(0))) + if (clause.getFieldKeys().size() == 1 && oldFieldKey.equals(clause.getFieldKeys().getFirst())) { if (clause.getParamVals().length > 1) throw new UnsupportedOperationException("Only single filters are supported on column " + newKey); diff --git a/specimen/src/org/labkey/specimen/report/request/RequestParticipantReportFactory.java b/specimen/src/org/labkey/specimen/report/request/RequestParticipantReportFactory.java index a8c6f66e6eb..59a1aa7dff8 100644 --- a/specimen/src/org/labkey/specimen/report/request/RequestParticipantReportFactory.java +++ b/specimen/src/org/labkey/specimen/report/request/RequestParticipantReportFactory.java @@ -37,7 +37,6 @@ import java.util.ArrayList; import java.util.Collection; import java.util.Collections; -import java.util.HashMap; import java.util.List; import java.util.Map; diff --git a/specimen/src/org/labkey/specimen/report/specimentype/TypeParticipantReportFactory.java b/specimen/src/org/labkey/specimen/report/specimentype/TypeParticipantReportFactory.java index eef11f44934..72f8e31b0ae 100644 --- a/specimen/src/org/labkey/specimen/report/specimentype/TypeParticipantReportFactory.java +++ b/specimen/src/org/labkey/specimen/report/specimentype/TypeParticipantReportFactory.java @@ -38,7 +38,6 @@ import java.util.ArrayList; import java.util.Collection; import java.util.Collections; -import java.util.HashMap; import java.util.List; import java.util.Map; diff --git a/specimen/src/org/labkey/specimen/view/SpecimenReportWebPartFactory.java b/specimen/src/org/labkey/specimen/view/SpecimenReportWebPartFactory.java index 8c1ae4c6e48..31521b9445b 100644 --- a/specimen/src/org/labkey/specimen/view/SpecimenReportWebPartFactory.java +++ b/specimen/src/org/labkey/specimen/view/SpecimenReportWebPartFactory.java @@ -48,7 +48,7 @@ private SpecimenVisitReportParameters getFactory(ViewContext context, Portal.Web Set categories = bean.getCategories(); // First element of first category is the default (should be "TypeSummary") - SpecimenVisitReportParameters factory = bean.getFactories(categories.iterator().next()).get(0); + SpecimenVisitReportParameters factory = bean.getFactories(categories.iterator().next()).getFirst(); assert "TypeSummary".equals(factory.getReportType()); if (null == name) diff --git a/specimen/src/org/labkey/specimen/writer/AbstractSpecimenWriter.java b/specimen/src/org/labkey/specimen/writer/AbstractSpecimenWriter.java index c8cc3c11333..189b389b1f4 100644 --- a/specimen/src/org/labkey/specimen/writer/AbstractSpecimenWriter.java +++ b/specimen/src/org/labkey/specimen/writer/AbstractSpecimenWriter.java @@ -27,12 +27,6 @@ abstract class AbstractSpecimenWriter implements SimpleStudyWriter { protected static final String DEFAULT_DIRECTORY = "specimens"; - @Override - public boolean includeWithTemplate() - { - return true; - } - protected StudyDocument.Study.Specimens ensureSpecimensElement(AbstractStudyContext ctx) throws Exception { StudyDocument.Study studyXml = ctx.getXml(); diff --git a/specimen/src/org/labkey/specimen/writer/SpecimenWriter.java b/specimen/src/org/labkey/specimen/writer/SpecimenWriter.java index de1b2b40b68..966ec35a9db 100644 --- a/specimen/src/org/labkey/specimen/writer/SpecimenWriter.java +++ b/specimen/src/org/labkey/specimen/writer/SpecimenWriter.java @@ -94,8 +94,7 @@ public void write(Study study, SimpleStudyExportContext ctx, VirtualFile vf) thr ColumnInfo ci = tinfo.getColumn(column.getDbColumnName()); if (null == ci) { - ctx.getLogger().warn("Specimen Column '" + column.getDbColumnName() + "' not found in table '" + - tinfo.getPublicName() + "'"); + ctx.getLogger().warn("Specimen Column '{}' not found in table '{}'", column.getDbColumnName(), tinfo.getPublicName()); continue; } DataColumn dc = new DataColumn(ci); diff --git a/study/api-src/org/labkey/api/specimen/SpecimenEventManager.java b/study/api-src/org/labkey/api/specimen/SpecimenEventManager.java index 8a8f92f7c08..9aaebbf1425 100644 --- a/study/api-src/org/labkey/api/specimen/SpecimenEventManager.java +++ b/study/api-src/org/labkey/api/specimen/SpecimenEventManager.java @@ -29,7 +29,7 @@ public SpecimenEvent getFirstEvent(List dateOrderedEvents) { if (!dateOrderedEvents.isEmpty()) { - SpecimenEvent firstEvent = dateOrderedEvents.get(0); + SpecimenEvent firstEvent = dateOrderedEvents.getFirst(); // walk backwards through the events until we find an event with at least one date field filled in that isn't // the first event. Leaving all specimen event dates blank shouldn't make an event the processing location. for (int i = 1; i < dateOrderedEvents.size() - 1 && skipAsProcessingLocation(firstEvent); i++) @@ -59,7 +59,7 @@ public SpecimenEvent getLastEvent(List dateOrderedEvents) { if (dateOrderedEvents.isEmpty()) return null; - return dateOrderedEvents.get(dateOrderedEvents.size() - 1); + return dateOrderedEvents.getLast(); } public List getSpecimenEvents(final Container container, Filter filter) diff --git a/study/api-src/org/labkey/api/specimen/SpecimenManager.java b/study/api-src/org/labkey/api/specimen/SpecimenManager.java index a9e1aef42dd..cd9a2167465 100644 --- a/study/api-src/org/labkey/api/specimen/SpecimenManager.java +++ b/study/api-src/org/labkey/api/specimen/SpecimenManager.java @@ -91,7 +91,7 @@ public int getSpecimenCountForVisit(Visit visit) List results = new SqlSelector(SpecimenSchema.get().getSchema(), sql).getArrayList(Integer.class); if (1 != results.size()) throw new IllegalStateException("Expected value from Select Count(*)"); - return results.get(0); + return results.getFirst(); } public void deleteSpecimensForVisit(Visit visit) @@ -179,8 +179,8 @@ private SQLFragment getVisitRangeSql(Visit visit, TableInfo tinfoSpecimen, Strin } else { - sqlVisitRange.add(visitValues.get(0)); - sqlVisitRange.add(visitValues.get(visitValues.size() - 1)); + sqlVisitRange.add(visitValues.getFirst()); + sqlVisitRange.add(visitValues.getLast()); } } return sqlVisitRange; diff --git a/study/api-src/org/labkey/api/specimen/SpecimenMigrationService.java b/study/api-src/org/labkey/api/specimen/SpecimenMigrationService.java index c5feb8ec739..f0a10eaf6dd 100644 --- a/study/api-src/org/labkey/api/specimen/SpecimenMigrationService.java +++ b/study/api-src/org/labkey/api/specimen/SpecimenMigrationService.java @@ -10,7 +10,6 @@ import org.labkey.api.query.QueryUpdateService; import org.labkey.api.query.QueryView; import org.labkey.api.query.UserSchema; -import org.labkey.api.query.ValidationException; import org.labkey.api.security.User; import org.labkey.api.services.ServiceRegistry; import org.labkey.api.study.Study; @@ -42,7 +41,7 @@ static void setInstance(SpecimenMigrationService impl) ActionURL getSpecimensURL(Container c); void importSpecimenArchive(@Nullable FileLike inputFile, PipelineJob job, SimpleStudyImportContext ctx, boolean merge, - boolean syncParticipantVisit) throws PipelineJobException, ValidationException; + boolean syncParticipantVisit) throws PipelineJobException; void clearRequestCaches(Container c); diff --git a/study/api-src/org/labkey/api/specimen/location/LocationManager.java b/study/api-src/org/labkey/api/specimen/location/LocationManager.java index 34c68f40cce..6ea179c30f5 100644 --- a/study/api-src/org/labkey/api/specimen/location/LocationManager.java +++ b/study/api-src/org/labkey/api/specimen/location/LocationManager.java @@ -151,7 +151,7 @@ public boolean isLocationInUse(Location loc, TableInfo table, String... columnNa } else if (table.getName().contains("_specimen")) { - params.remove(0); + params.removeFirst(); containerColumn = ""; } else @@ -233,7 +233,7 @@ public Integer getCurrentLocationId(List dateOrderedEvents) { if (!dateOrderedEvents.isEmpty()) { - SpecimenEvent lastEvent = dateOrderedEvents.get(dateOrderedEvents.size() - 1); + SpecimenEvent lastEvent = dateOrderedEvents.getLast(); if (lastEvent.getShipDate() == null && (lastEvent.getShipBatchNumber() == null || lastEvent.getShipBatchNumber() == 0) && diff --git a/study/api-src/org/labkey/api/specimen/model/AbstractSpecimenDomainKind.java b/study/api-src/org/labkey/api/specimen/model/AbstractSpecimenDomainKind.java index ff6e23acca5..bb600684f34 100644 --- a/study/api-src/org/labkey/api/specimen/model/AbstractSpecimenDomainKind.java +++ b/study/api-src/org/labkey/api/specimen/model/AbstractSpecimenDomainKind.java @@ -34,7 +34,6 @@ import org.labkey.api.exp.property.BaseAbstractDomainKind; import org.labkey.api.exp.property.Domain; import org.labkey.api.exp.property.DomainProperty; -import org.labkey.api.exp.property.DomainUtil; import org.labkey.api.gwt.client.model.GWTDomain; import org.labkey.api.gwt.client.model.GWTPropertyDescriptor; import org.labkey.api.query.SimpleValidationError; @@ -56,7 +55,6 @@ import java.util.ArrayList; import java.util.Collections; -import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; diff --git a/study/api-src/org/labkey/api/study/pipeline/StudyBatch.java b/study/api-src/org/labkey/api/study/pipeline/StudyBatch.java index a3711ad82a7..d942055d5f7 100644 --- a/study/api-src/org/labkey/api/study/pipeline/StudyBatch.java +++ b/study/api-src/org/labkey/api/study/pipeline/StudyBatch.java @@ -26,7 +26,6 @@ import org.labkey.api.view.ViewBackgroundInfo; import org.labkey.vfs.FileLike; -import java.io.File; import java.io.IOException; import java.io.Serializable; diff --git a/study/api-src/org/labkey/api/studydesign/query/AbstractStudyDesignDomainKind.java b/study/api-src/org/labkey/api/studydesign/query/AbstractStudyDesignDomainKind.java index d5e4df0f9dd..715af4274b6 100644 --- a/study/api-src/org/labkey/api/studydesign/query/AbstractStudyDesignDomainKind.java +++ b/study/api-src/org/labkey/api/studydesign/query/AbstractStudyDesignDomainKind.java @@ -16,7 +16,6 @@ package org.labkey.api.studydesign.query; import org.jetbrains.annotations.NotNull; -import org.labkey.api.collections.CaseInsensitiveHashSet; import org.labkey.api.data.Container; import org.labkey.api.data.DbScope; import org.labkey.api.data.JdbcType; diff --git a/study/api-src/org/labkey/api/studydesign/query/StudyObjectiveTable.java b/study/api-src/org/labkey/api/studydesign/query/StudyObjectiveTable.java index d892c2e254a..2629bc91d2d 100644 --- a/study/api-src/org/labkey/api/studydesign/query/StudyObjectiveTable.java +++ b/study/api-src/org/labkey/api/studydesign/query/StudyObjectiveTable.java @@ -92,12 +92,6 @@ public QueryUpdateService getUpdateService() return new DefaultQueryUpdateService(this, this.getRealTable()); } - @Override - public boolean supportsContainerFilter() - { - return true; - } - @Override public boolean hasPermission(@NotNull UserPrincipal user, @NotNull Class perm) { diff --git a/study/src/org/labkey/study/CohortFilterFactory.java b/study/src/org/labkey/study/CohortFilterFactory.java index d4c07a3ae1b..7714fdbc34f 100644 --- a/study/src/org/labkey/study/CohortFilterFactory.java +++ b/study/src/org/labkey/study/CohortFilterFactory.java @@ -333,7 +333,7 @@ private static FieldKey _normalizeParticipantFieldKey(Study study, String s) List parts = fk.getParts(); if (!parts.isEmpty()) { - String first = parts.get(0); + String first = parts.getFirst(); if (Strings.CI.equals(first, subject)) { ArrayList t = new ArrayList<>(parts); diff --git a/study/src/org/labkey/study/MasterPatientIndexMaintenanceTask.java b/study/src/org/labkey/study/MasterPatientIndexMaintenanceTask.java index c10e7b260bb..f11b00f0922 100644 --- a/study/src/org/labkey/study/MasterPatientIndexMaintenanceTask.java +++ b/study/src/org/labkey/study/MasterPatientIndexMaintenanceTask.java @@ -57,7 +57,7 @@ public void run(Logger log) MasterPatientIndexService.FolderSettings settings = svc.getFolderSettings(container); if (settings.isEnabled()) { - log.info("Starting Master Patient Index Job for folder: " + container.getPath()); + log.info("Starting Master Patient Index Job for folder: {}", container.getPath()); User reloadUser = UserManager.getUser(settings.getReloadUser()); if (reloadUser != null) { @@ -70,11 +70,11 @@ public void run(Logger log) } catch (Exception e) { - log.error("Master Patient Index Maintenance Task failed for folder : " + container.getPath() + " due to : " + e.getMessage()); + log.error("Master Patient Index Maintenance Task failed for folder : {} due to : {}", container.getPath(), e.getMessage()); } } else - log.error("Unable to resolve the reload user: " + settings.getReloadUser()); + log.error("Unable to resolve the reload user: {}", settings.getReloadUser()); } } } diff --git a/study/src/org/labkey/study/SpecimenRefreshMaintenanceTask.java b/study/src/org/labkey/study/SpecimenRefreshMaintenanceTask.java index a80d624a88a..acee4732797 100644 --- a/study/src/org/labkey/study/SpecimenRefreshMaintenanceTask.java +++ b/study/src/org/labkey/study/SpecimenRefreshMaintenanceTask.java @@ -94,8 +94,7 @@ public void run(Logger log) { try { - log.info("Refreshing specimen data from \"" + sourceStudy.getContainer().getPath() + "\" (" + sourceStudy.getLabel() + - ") to \"" + destinationStudy.getContainer().getPath() + "\" (" + destinationStudy.getLabel() + ")"); + log.info("Refreshing specimen data from \"{}\" ({}) to \"{}\" ({})", sourceStudy.getContainer().getPath(), sourceStudy.getLabel(), destinationStudy.getContainer().getPath(), destinationStudy.getLabel()); SnapshotSettings settings = snapshot.getSnapshotSettings(); User user = UserManager.getUser(snapshot.getModifiedBy()); diff --git a/study/src/org/labkey/study/StudyUnionTableInfo.java b/study/src/org/labkey/study/StudyUnionTableInfo.java index 574b6b1a5b1..46dca1722e5 100644 --- a/study/src/org/labkey/study/StudyUnionTableInfo.java +++ b/study/src/org/labkey/study/StudyUnionTableInfo.java @@ -117,7 +117,7 @@ public void init(Collection defs) String visitPropertyName = def.getVisitDateColumnName(); ColumnInfo visitColumn = null == visitPropertyName ? null : ti.getColumn(visitPropertyName); if (null != visitPropertyName && (null == visitColumn || visitColumn.getJdbcType() != JdbcType.TIMESTAMP)) - LogManager.getLogger(StudySchema.class).info("Could not find visit column of correct type '" + visitPropertyName + "' in dataset '" + def.getName() + "'"); + LogManager.getLogger(StudySchema.class).info("Could not find visit column of correct type '{}' in dataset '{}'", visitPropertyName, def.getName()); if (null != visitColumn && visitColumn.getJdbcType() == JdbcType.TIMESTAMP) sqlf.append(", ").append(visitColumn.getValueSql("D")).append(" AS _visitdate"); else diff --git a/study/src/org/labkey/study/assay/AssayPublishConfirmAction.java b/study/src/org/labkey/study/assay/AssayPublishConfirmAction.java index 53c177ee588..b5c41686bbe 100644 --- a/study/src/org/labkey/study/assay/AssayPublishConfirmAction.java +++ b/study/src/org/labkey/study/assay/AssayPublishConfirmAction.java @@ -239,7 +239,7 @@ protected Map getAdditionalColumns(AssayPublishConfir .toList(); if (sampleCols.size() == 1) - additionalCols.put(LinkToStudyKeys.SampleId, sampleCols.get(0).getFieldKey()); + additionalCols.put(LinkToStudyKeys.SampleId, sampleCols.getFirst().getFieldKey()); if (!selectColumns.containsKey(additionalCols.get(LinkToStudyKeys.Date))) { @@ -250,7 +250,7 @@ protected Map getAdditionalColumns(AssayPublishConfir .toList(); if (dateCols.size() == 1) - additionalCols.put(LinkToStudyKeys.Date, dateCols.get(0).getFieldKey()); + additionalCols.put(LinkToStudyKeys.Date, dateCols.getFirst().getFieldKey()); } // Add the TargetStudy FieldKey only if it exists on the Result domain. diff --git a/study/src/org/labkey/study/assay/ExperimentListenerImpl.java b/study/src/org/labkey/study/assay/ExperimentListenerImpl.java index ec8c6e027b9..0e7bb8a71ca 100644 --- a/study/src/org/labkey/study/assay/ExperimentListenerImpl.java +++ b/study/src/org/labkey/study/assay/ExperimentListenerImpl.java @@ -46,8 +46,6 @@ import java.util.Map; import java.util.Set; -import static java.util.Collections.singleton; - public class ExperimentListenerImpl implements ExperimentListener { @Override diff --git a/study/src/org/labkey/study/assay/StudyPublishManager.java b/study/src/org/labkey/study/assay/StudyPublishManager.java index 119b7ef05db..13c9826c20d 100644 --- a/study/src/org/labkey/study/assay/StudyPublishManager.java +++ b/study/src/org/labkey/study/assay/StudyPublishManager.java @@ -516,7 +516,7 @@ private void createProvenanceRun(User user, @NotNull Container targetContainer, if (provider.getResultRowLSIDPrefix() == null) { - LOG.info("Can't create provenance run; Assay provider '" + provider.getName() + "' for assay '" + protocol.getName() + "' has no result row lsid prefix"); + LOG.info("Can't create provenance run; Assay provider '{}' for assay '{}' has no result row lsid prefix", provider.getName(), protocol.getName()); return; } @@ -1078,7 +1078,7 @@ public boolean hasMismatchedInfo(List dataRowPKs, AssayProtocolSchema sche @Nullable public ActionURL autoLinkAssayResults(ExpProtocol protocol, ExpRun run, User user, Container container, List errors) { - LOG.debug("Considering whether to attempt auto-link results from assay run " + run.getName() + " from container " + container.getPath()); + LOG.debug("Considering whether to attempt auto-link results from assay run {} from container {}", run.getName(), container.getPath()); AssayProvider provider = AssayService.get().getProvider(protocol); if (protocol.getObjectProperties().get(StudyPublishService.AUTO_LINK_TARGET_PROPERTY_URI) != null) { @@ -1086,7 +1086,7 @@ public ActionURL autoLinkAssayResults(ExpProtocol protocol, ExpRun run, User use String targetStudyContainerId = protocol.getObjectProperties().get(StudyPublishService.AUTO_LINK_TARGET_PROPERTY_URI).getStringValue(); if (targetStudyContainerId != null) { - LOG.debug("Found configured target study container ID, " + targetStudyContainerId + " for auto-linking with " + run.getName() + " from container " + container.getPath()); + LOG.debug("Found configured target study container ID, {} for auto-linking with {} from container {}", targetStudyContainerId, run.getName(), container.getPath()); final Container targetStudyContainer = ContainerManager.getForId(targetStudyContainerId); // Determine if the category is predefined @@ -1094,7 +1094,7 @@ public ActionURL autoLinkAssayResults(ExpProtocol protocol, ExpRun run, User use if (protocol.getObjectProperties().get(StudyPublishService.AUTO_LINK_CATEGORY_PROPERTY_URI) != null) { categoryName = protocol.getObjectProperties().get(StudyPublishService.AUTO_LINK_CATEGORY_PROPERTY_URI).getStringValue(); - LOG.debug("Obtained predefined Dataset Category to assign, " + categoryName); + LOG.debug("Obtained predefined Dataset Category to assign, {}", categoryName); } return autoLinkResults(protocol, provider, run, user, container, targetStudyContainer, categoryName, errors, LOG); @@ -1185,7 +1185,7 @@ private void getColumnValue(@Nullable FieldKey fieldKey, RenderContext ctx, Map< @Override public void autoLinkSamples(ExpSampleType sampleType, List> results, Container container, User user) { - LOG.debug(String.format("Considering whether to attempt auto-link results for row insert to %s from container %s", sampleType.getName(), container.getPath())); + LOG.debug("Considering whether to attempt auto-link results for row insert to {} from container {}", sampleType.getName(), container.getPath()); Container targetContainer = sampleType.getAutoLinkTargetContainer(); List publishErrors = new ArrayList<>(); @@ -1202,7 +1202,7 @@ public void autoLinkSamples(ExpSampleType sampleType, List String sampleTypeName = sampleType.getName(); String containerPath = container.getPath(); - LOG.debug(String.format("Found configured target study container ID, %s for auto-linking with %s from container %s", study.getShortName(), sampleTypeName, containerPath)); + LOG.debug("Found configured target study container ID, {} for auto-linking with {} from container {}", study.getShortName(), sampleTypeName, containerPath); Set validStudies = StudyPublishService.get().getValidPublishTargets(user, InsertPermission.class); if (validStudies.contains(study)) @@ -1210,7 +1210,7 @@ public void autoLinkSamples(ExpSampleType sampleType, List // Issue 49253 : QueryView needs a view context to initialize properly. Ensure a mock view context when running in the background try (EnsureViewContext ignore = new EnsureViewContext(container, user)) { - LOG.debug(String.format("Resolved target study in container %s for auto-linking with %s from container %s", targetContainerPath, sampleTypeName, containerPath)); + LOG.debug("Resolved target study in container {} for auto-linking with {} from container {}", targetContainerPath, sampleTypeName, containerPath); List> dataMaps = new ArrayList<>(); // attempt to match up the subject/timepoint information even if the sample has not been published to @@ -1267,12 +1267,12 @@ public void autoLinkSamples(ExpSampleType sampleType, List } else { - LOG.error("Insufficient permission to link assay data to study in folder : " + targetContainerPath); + LOG.error("Insufficient permission to link assay data to study in folder : {}", targetContainerPath); } } else { - LOG.info("Unable to link the assay data, there is no study in the folder: " + targetContainerPath); + LOG.info("Unable to link the assay data, there is no study in the folder: {}", targetContainerPath); } } } @@ -1334,11 +1334,11 @@ public ActionURL autoLinkResults(ExpProtocol protocol, AssayProvider provider, E if (!hasPermission) { // We don't have permission to create or add to - log.error("Insufficient permission to link assay data to study in folder : " + targetStudyContainer.getPath()); + log.error("Insufficient permission to link assay data to study in folder : {}", targetStudyContainer.getPath()); return null; } - log.debug("Resolved target study in container " + targetStudyContainer.getPath() + " for auto-linking with " + run.getName() + " from container " + container.getPath()); + log.debug("Resolved target study in container {} for auto-linking with {} from container {}", targetStudyContainer.getPath(), run.getName(), container.getPath()); FieldKey ptidFK = provider.getTableMetadata(protocol).getParticipantIDFieldKey(); FieldKey visitFK = provider.getTableMetadata(protocol).getVisitIDFieldKey(study.getTimepointType()); @@ -1388,27 +1388,27 @@ public ActionURL autoLinkResults(ExpProtocol protocol, AssayProvider provider, E { float visitId = Float.parseFloat(visit.toString()); key = new PublishKey(targetContainer, ptid, visitId, objectId); - log.debug("Resolved info (" + ptid + "/" + visitId + ") for auto-linking of row " + objectId + " for " + run.getName() + " from container " + container.getPath()); + log.debug("Resolved info ({}/{}) for auto-linking of row {} for {} from container {}", ptid, visitId, objectId, run.getName(), container.getPath()); } else { Date date = (Date) ConvertUtils.convert(visit.toString(), Date.class); key = new PublishKey(targetContainer, ptid, date, objectId); - log.debug("Resolved info (" + ptid + "/" + date + ") for auto-linking of row " + objectId + " for " + run.getName() + " from container " + container.getPath()); + log.debug("Resolved info ({}/{}) for auto-linking of row {} for {} from container {}", ptid, date, objectId, run.getName(), container.getPath()); } keys.put(objectId, key); } else { - log.debug("Missing ptid and/or visit info for auto-linking of row " + objectId + " for " + run.getName() + " from container " + container.getPath()); + log.debug("Missing ptid and/or visit info for auto-linking of row {} for {} from container {}", objectId, run.getName(), container.getPath()); } }); - log.debug("Identified " + keys + " rows with sufficient data to link to " + targetStudyContainer.getPath() + " for auto-linking with " + run.getName() + " from container " + container.getPath()); + log.debug("Identified {} rows with sufficient data to link to {} for auto-linking with {} from container {}", keys, targetStudyContainer.getPath(), run.getName(), container.getPath()); return provider.linkToStudy(user, container, protocol, targetStudyContainer, datasetCategory, keys, errors); } else - log.info("Unable to link the assay data, there is no study in the folder: " + targetStudyContainer.getPath()); + log.info("Unable to link the assay data, there is no study in the folder: {}", targetStudyContainer.getPath()); } return null; } diff --git a/study/src/org/labkey/study/controllers/ParticipantGroupController.java b/study/src/org/labkey/study/controllers/ParticipantGroupController.java index b37e76997f2..5ab663d44e3 100644 --- a/study/src/org/labkey/study/controllers/ParticipantGroupController.java +++ b/study/src/org/labkey/study/controllers/ParticipantGroupController.java @@ -344,7 +344,7 @@ public ApiResponse execute(ParticipantCategoryImpl form, BindException errors) t // try to match a single category by label/container List defs = ParticipantGroupManager.getInstance().getParticipantCategoriesByLabel(getContainer(), getUser(), form.getLabel()); if (defs.size() == 1) - category = defs.get(0); + category = defs.getFirst(); } else { diff --git a/study/src/org/labkey/study/controllers/StudyController.java b/study/src/org/labkey/study/controllers/StudyController.java index a4674a3a571..0b1dab537da 100644 --- a/study/src/org/labkey/study/controllers/StudyController.java +++ b/study/src/org/labkey/study/controllers/StudyController.java @@ -888,7 +888,7 @@ private DatasetDefinition getDatasetDefinition() if (datasetKeyObject instanceof List list) { // bug 7365: It's been specified twice -- once in the POST, once in the GET. Just need one of them. - datasetKeyObject = list.get(0); + datasetKeyObject = list.getFirst(); } if (null != datasetKeyObject) { @@ -1510,7 +1510,7 @@ public Object execute(DeleteParticipantForm deleteParticipantForm, BindException try (DbScope.Transaction transaction = schema.getScope().ensureTransaction()) { - _log.info("Starting participant deletion for ID: " + participantId); + _log.info("Starting participant deletion for ID: {}", participantId); List datasets = study.getDatasets(); //delete participant rows from datasets @@ -2313,7 +2313,7 @@ public boolean handlePost(IdForm form, BindException errors) StudyManager.getInstance().deleteVisits(study, getUnusedVisits(), getUser(), true); - _log.info("Delete unused visits took: " + DateUtil.formatDuration(System.currentTimeMillis() - start)); + _log.info("Delete unused visits took: {}", DateUtil.formatDuration(System.currentTimeMillis() - start)); return true; } @@ -2399,7 +2399,7 @@ public boolean handlePost(DeleteVisitsForm form, BindException errors) long start = System.currentTimeMillis(); StudyImpl study = getStudyThrowIfNull(); StudyManager.getInstance().deleteVisits(study, _visitsToDelete, getUser(), false); - _log.info("Bulk delete visits took: " + DateUtil.formatDuration(System.currentTimeMillis() - start)); + _log.info("Bulk delete visits took: {}", DateUtil.formatDuration(System.currentTimeMillis() - start)); return true; } @@ -2925,22 +2925,22 @@ public static class PublishHistoryDetailsForm private String _sourceLsid; private int _recordCount; - public Integer getProtocolId() + public @Nullable Integer getProtocolId() { return _protocolId; } - public void setProtocolId(Integer protocolId) + public void setProtocolId(@Nullable Integer protocolId) { _protocolId = protocolId; } - public Integer getSampleTypeId() + public @Nullable Integer getSampleTypeId() { return _sampleTypeId; } - public void setSampleTypeId(Integer sampleTypeId) + public void setSampleTypeId(@Nullable Integer sampleTypeId) { _sampleTypeId = sampleTypeId; } @@ -3970,7 +3970,7 @@ public URLHelper getSuccessURL(ResetPipelinePathForm form) } catch (URISyntaxException e) { - _log.warn("ResetPipelineAction redirect string invalid: " + redirect); + _log.warn("ResetPipelineAction redirect string invalid: {}", redirect); } } return urlProvider(PipelineStatusUrls.class).urlBegin(getContainer()); @@ -6528,7 +6528,7 @@ public boolean handlePost(VisitAliasesForm form, BindException errors) } // TODO: Change to audit log - _log.info("The visit import custom mapping was " + (hadCustomMapping ? "replaced" : "imported")); + _log.info("The visit import custom mapping was {}", hadCustomMapping ? "replaced" : "imported"); return true; } @@ -7473,7 +7473,7 @@ protected int importData(DataLoader dl, FileStream file, String originalName, Ba { List rowErrors = errors.getRowErrors(); int count = rowErrors.size(); - rowErrors.add(0, new ValidationException("Warning: NONE of participant mappings have been imported because this mapping file contains " + (1 == count ? "an error" : "errors") + "! Please correct the following:")); + rowErrors.addFirst(new ValidationException("Warning: NONE of participant mappings have been imported because this mapping file contains " + (1 == count ? "an error" : "errors") + "! Please correct the following:")); } return rows; diff --git a/study/src/org/labkey/study/controllers/reports/ReportsController.java b/study/src/org/labkey/study/controllers/reports/ReportsController.java index 1834a1a68a7..67cce89bcb1 100644 --- a/study/src/org/labkey/study/controllers/reports/ReportsController.java +++ b/study/src/org/labkey/study/controllers/reports/ReportsController.java @@ -874,7 +874,7 @@ public static HttpView getParticipantNavTrail(ViewContext context, List dependencies = getDependencies(data); for (QuerySnapshotDefinition snapshotDef : dependencies) { - LOG.info("Scheduling update of snapshot data : " + snapshotDef.getName()); + LOG.info("Scheduling update of snapshot data : {}", snapshotDef.getName()); autoUpdateSnapshot(snapshotDef); } } @@ -690,7 +690,7 @@ public void run() } catch (InterruptedException e) { - LOG.info(getClass().getSimpleName() + " is terminating due to interruption"); + LOG.info("{} is terminating due to interruption", getClass().getSimpleName()); } } @@ -763,7 +763,7 @@ public SnapshotUpdateTask(QuerySnapshotDefinition def, boolean suppressVisitMana @Override public void run() { - LOG.info("Updating snapshot data : " + _def.getName()); + LOG.info("Updating snapshot data : {}", _def.getName()); try { @@ -852,7 +852,7 @@ public void run() DatasetDefinition deferredDataset = StudyManager.getInstance().getDatasetDefinitionByName(study, def.getName()); if (deferredDataset == null) { - LOG.warn("Unable to find dataset " + def.getName() + " to update for query snapshot " + def.getName() + " in study in " + snapshotContainer.getPath() + ", skipping"); + LOG.warn("Unable to find dataset {} to update for query snapshot {} in study in {}, skipping", def.getName(), def.getName(), snapshotContainer.getPath()); } else { diff --git a/study/src/org/labkey/study/dataset/SnapshotDependency.java b/study/src/org/labkey/study/dataset/SnapshotDependency.java index a5d169a586a..0eeb3c4ca10 100644 --- a/study/src/org/labkey/study/dataset/SnapshotDependency.java +++ b/study/src/org/labkey/study/dataset/SnapshotDependency.java @@ -138,12 +138,12 @@ public List getDependencies(SourceDataType sourceData) catch (Throwable e) { // issue : 45996 don't fail all snapshots due to a dependency checking error - _log.warn("An error occurred checking dependencies for snapshot : " + snapshot.getName() + " in folder : " + snapshot.getContainer().getPath(), e); + _log.warn("An error occurred checking dependencies for snapshot : {} in folder : {}", snapshot.getName(), snapshot.getContainer().getPath(), e); } } } else - _log.debug("Failed checking dependencies for container: " + dsDef.getContainer().getPath() + ", it has been deleted."); + _log.debug("Failed checking dependencies for container: {}, it has been deleted.", dsDef.getContainer().getPath()); return new ArrayList<>(dependencies.values()); } @@ -151,7 +151,7 @@ public List getDependencies(SourceDataType sourceData) { // ignore container conversion errors, most likely a race condition where the container has been deleted but // the dependency thread continues to check (issue: 11659) - _log.info("Failed checking dependencies for container: " + sourceData.getContainer().getPath(), e); + _log.info("Failed checking dependencies for container: {}", sourceData.getContainer().getPath(), e); } } return Collections.emptyList(); @@ -194,7 +194,7 @@ private boolean hasDependency(QuerySnapshotDefinition qsDef, @NotNull org.labkey { if (datasetKey.equals(key)) { - _log.info("Snapshot: " + qsDef.getName() + " base table: " + key + " matched modified dataset table"); + _log.info("Snapshot: {} base table: {} matched modified dataset table", qsDef.getName(), key); return true; } } diff --git a/study/src/org/labkey/study/designer/view/studySummary.jsp b/study/src/org/labkey/study/designer/view/studySummary.jsp index ca096fb234c..5d3fa0e9f13 100644 --- a/study/src/org/labkey/study/designer/view/studySummary.jsp +++ b/study/src/org/labkey/study/designer/view/studySummary.jsp @@ -82,7 +82,7 @@ <% if (protocolDocs.size() == 1) { - Attachment attachment = protocolDocs.get(0); + Attachment attachment = protocolDocs.getFirst(); %> <%=attachment.renderDownloadLink(StudyController.getProtocolDocumentDownloadURL(c, attachment.getName()), "Study Protocol Document")%> <% diff --git a/study/src/org/labkey/study/importer/AssayScheduleImporter.java b/study/src/org/labkey/study/importer/AssayScheduleImporter.java index 317973441d5..53ff881e7d0 100644 --- a/study/src/org/labkey/study/importer/AssayScheduleImporter.java +++ b/study/src/org/labkey/study/importer/AssayScheduleImporter.java @@ -162,7 +162,7 @@ public List> transform(StudyImportContext ctx, List importCohortSettings(StudyImportContext ctx, Virtua // ITN12.2 branch and newer releases will always export a separate cohorts.xml table to // round-trip the 'enrolled' bit. // - ctx.getLogger().info("Importing cohort settings from " + root.getRelativePath(cohortFileName)); + ctx.getLogger().info("Importing cohort settings from {}", root.getRelativePath(cohortFileName)); CohortsDocument cohortAssignmentXml; try diff --git a/study/src/org/labkey/study/importer/DatasetCohortAssigner.java b/study/src/org/labkey/study/importer/DatasetCohortAssigner.java index 37d9dbc67ed..48e79d233c4 100644 --- a/study/src/org/labkey/study/importer/DatasetCohortAssigner.java +++ b/study/src/org/labkey/study/importer/DatasetCohortAssigner.java @@ -56,7 +56,7 @@ public void process(StudyImportContext ctx, VirtualFile root, BindException erro StudyImpl study = ctx.getStudyImpl(); DatasetsDocument.Datasets datasets = DatasetDefinitionImporter.getDatasetsManifest(ctx, root, false); - ctx.getLogger().info("Loading " + getDescription()); + ctx.getLogger().info("Loading {}", getDescription()); Container c = ctx.getContainer(); User user = ctx.getUser(); diff --git a/study/src/org/labkey/study/importer/DatasetDefinitionImporter.java b/study/src/org/labkey/study/importer/DatasetDefinitionImporter.java index 0bb84f6f9e6..e17f7142492 100644 --- a/study/src/org/labkey/study/importer/DatasetDefinitionImporter.java +++ b/study/src/org/labkey/study/importer/DatasetDefinitionImporter.java @@ -161,7 +161,7 @@ public static DatasetsDocument.Datasets getDatasetsManifest(StudyImportContext c try { if (log) - ctx.getLogger().info("Loading datasets manifest from " + datasetsXmlFilename); + ctx.getLogger().info("Loading datasets manifest from {}", datasetsXmlFilename); XmlObject doc = datasetDir.getXmlBean(datasetsXmlFilename); if (doc instanceof DatasetsDocument) diff --git a/study/src/org/labkey/study/importer/DefaultStudyDesignImporter.java b/study/src/org/labkey/study/importer/DefaultStudyDesignImporter.java index 9e6cbdbd0f7..1f4fb2ed468 100644 --- a/study/src/org/labkey/study/importer/DefaultStudyDesignImporter.java +++ b/study/src/org/labkey/study/importer/DefaultStudyDesignImporter.java @@ -96,7 +96,7 @@ protected void importTableinfo(StudyImportContext ctx, VirtualFile root, String } else { - ctx.getLogger().info("No table metadata file found to import: " + schemaFileName); + ctx.getLogger().info("No table metadata file found to import: {}", schemaFileName); return; } } @@ -158,7 +158,7 @@ protected void importTableinfo(StudyImportContext ctx, VirtualFile root, String isDirty = true; } else - ctx.getLogger().warn("Table: " + tableName + " already has a field named: " + ipd.pd.getName() + ", ignoring the imported field"); + ctx.getLogger().warn("Table: {} already has a field named: {}, ignoring the imported field", tableName, ipd.pd.getName()); } if (isDirty) @@ -166,14 +166,14 @@ protected void importTableinfo(StudyImportContext ctx, VirtualFile root, String if (domain.getDomainKind().canEditDefinition(ctx.getUser(), domain)) domain.save(ctx.getUser()); else - ctx.getLogger().error("Unable to update the domain for table: " + tableName + " because the user does not have edit privileges."); + ctx.getLogger().error("Unable to update the domain for table: {} because the user does not have edit privileges.", tableName); } } else - ctx.getLogger().warn("Unable to get domain for table: " + tableName); + ctx.getLogger().warn("Unable to get domain for table: {}", tableName); } else - ctx.getLogger().warn("No tableinfo for table : " + tableName); + ctx.getLogger().warn("No tableinfo for table : {}", tableName); } } @@ -244,7 +244,7 @@ protected void importTableData(StudyImportContext ctx, VirtualFile vf, StudyQuer } } else - ctx.getLogger().warn("Unable to open the file at: " + fileName); + ctx.getLogger().warn("Unable to open the file at: {}", fileName); } } else diff --git a/study/src/org/labkey/study/importer/ParticipantCommentImporter.java b/study/src/org/labkey/study/importer/ParticipantCommentImporter.java index 6537a577030..1efb39ed0af 100644 --- a/study/src/org/labkey/study/importer/ParticipantCommentImporter.java +++ b/study/src/org/labkey/study/importer/ParticipantCommentImporter.java @@ -49,7 +49,7 @@ public void process(StudyImportContext ctx, VirtualFile root, BindException erro StudyImpl study = ctx.getStudyImpl(); StudyDocument.Study.Comments commentsXml = ctx.getXml().getComments(); - ctx.getLogger().info("Loading " + getDescription()); + ctx.getLogger().info("Loading {}", getDescription()); if (commentsXml.isSetParticipantCommentDatasetId()) { @@ -63,7 +63,7 @@ public void process(StudyImportContext ctx, VirtualFile root, BindException erro study.setParticipantVisitCommentProperty(commentsXml.getParticipantVisitCommentDatasetProperty()); } - ctx.getLogger().info("Done importing " + getDescription()); + ctx.getLogger().info("Done importing {}", getDescription()); } } diff --git a/study/src/org/labkey/study/importer/ParticipantGroupImporter.java b/study/src/org/labkey/study/importer/ParticipantGroupImporter.java index 94fe54983c2..23180e3e209 100644 --- a/study/src/org/labkey/study/importer/ParticipantGroupImporter.java +++ b/study/src/org/labkey/study/importer/ParticipantGroupImporter.java @@ -98,7 +98,7 @@ public void process(StudyImpl study, StudyImportContext ctx, XmlObject xmlObject { if (xmlObject instanceof ParticipantGroupsDocument doc) { - ctx.getLogger().info("Loading " + getDescription()); + ctx.getLogger().info("Loading {}", getDescription()); DbScope scope = StudySchema.getInstance().getSchema().getScope(); @@ -164,7 +164,7 @@ public void process(StudyImpl study, StudyImportContext ctx, XmlObject xmlObject } else { - ctx.getLogger().info("Skipping participant group " + group.getLabel() + " since none of its members could be found"); + ctx.getLogger().info("Skipping participant group {} since none of its members could be found", group.getLabel()); } } } @@ -172,7 +172,7 @@ public void process(StudyImpl study, StudyImportContext ctx, XmlObject xmlObject ParticipantGroupManager.getInstance().clearCache(ctx.getContainer()); } - ctx.getLogger().info("Done importing " + getDescription()); + ctx.getLogger().info("Done importing {}", getDescription()); } } } diff --git a/study/src/org/labkey/study/importer/ProtocolDocumentImporter.java b/study/src/org/labkey/study/importer/ProtocolDocumentImporter.java index 29cf7feff8d..9986c344ead 100644 --- a/study/src/org/labkey/study/importer/ProtocolDocumentImporter.java +++ b/study/src/org/labkey/study/importer/ProtocolDocumentImporter.java @@ -55,7 +55,7 @@ public void process(StudyImportContext ctx, VirtualFile root, BindException erro Study study = ctx.getStudy(); ExportDirType protocolXml = ctx.getXml().getProtocolDocs(); - ctx.getLogger().info("Loading " + getDescription()); + ctx.getLogger().info("Loading {}", getDescription()); VirtualFile folder = root.getDir(protocolXml.getDir()); List attachments = new ArrayList<>(); @@ -66,7 +66,7 @@ public void process(StudyImportContext ctx, VirtualFile root, BindException erro for (String fileName : folder.list()) { - ctx.getLogger().info("importing protocol document: " + fileName); + ctx.getLogger().info("importing protocol document: {}", fileName); if (existing.contains(fileName)) study.removeProtocolDocument(fileName, ctx.getUser()); @@ -76,7 +76,7 @@ public void process(StudyImportContext ctx, VirtualFile root, BindException erro study.attachProtocolDocument(attachments, ctx.getUser()); - ctx.getLogger().info("Done importing " + getDescription()); + ctx.getLogger().info("Done importing {}", getDescription()); } } diff --git a/study/src/org/labkey/study/importer/StudyImportInitialTask.java b/study/src/org/labkey/study/importer/StudyImportInitialTask.java index 0ee5c50035a..49c2abf6d3e 100644 --- a/study/src/org/labkey/study/importer/StudyImportInitialTask.java +++ b/study/src/org/labkey/study/importer/StudyImportInitialTask.java @@ -90,7 +90,7 @@ public static void doImport(PipelineJob job, StudyImportContext ctx, BindExcepti StudyImpl study = StudyManager.getInstance().getStudy(ctx.getContainer()); if (null == study) { - ctx.getLogger().info("Loading study from " + originalFileName); + ctx.getLogger().info("Loading study from {}", originalFileName); ctx.getLogger().info("Creating study"); // Create study @@ -114,7 +114,7 @@ else if (studyXml.isSetDateBased()) } else { - ctx.getLogger().info("Reloading study from " + originalFileName); + ctx.getLogger().info("Reloading study from {}", originalFileName); TimepointType timepointType = study.getTimepointType(); if (studyXml.isSetTimepointType()) @@ -182,7 +182,7 @@ private static void processImporter(StudyImportContext ctx, PipelineJob job, Bin private static void throwFirstErrorAsPipelineJobException(BindException errors) throws PipelineJobException { - ObjectError firstError = errors.getAllErrors().get(0); + ObjectError firstError = errors.getAllErrors().getFirst(); throw new PipelineJobException("ERROR: " + firstError.getDefaultMessage()); } } diff --git a/study/src/org/labkey/study/importer/StudyImporterFactory.java b/study/src/org/labkey/study/importer/StudyImporterFactory.java index 7f297fe49d8..99562044484 100644 --- a/study/src/org/labkey/study/importer/StudyImporterFactory.java +++ b/study/src/org/labkey/study/importer/StudyImporterFactory.java @@ -98,7 +98,7 @@ public void process(@Nullable PipelineJob job, FolderImportContext ctx, VirtualF if (job != null) job.setStatus("IMPORT " + getDescription()); - ctx.getLogger().info("Loading " + getDescription()); + ctx.getLogger().info("Loading {}", getDescription()); String studyFileName = "study.xml"; Container c = ctx.getContainer(); @@ -174,7 +174,7 @@ public void process(@Nullable PipelineJob job, FolderImportContext ctx, VirtualF // the final study import task handles registered study importers like: cohorts, participant comments, categories, etc. StudyImportFinalTask.doImport(job, studyImportContext, errors); - ctx.getLogger().info("Done importing " + getDescription()); + ctx.getLogger().info("Done importing {}", getDescription()); } } diff --git a/study/src/org/labkey/study/importer/StudyPropertiesImporter.java b/study/src/org/labkey/study/importer/StudyPropertiesImporter.java index 503265b675f..891c2fd2742 100644 --- a/study/src/org/labkey/study/importer/StudyPropertiesImporter.java +++ b/study/src/org/labkey/study/importer/StudyPropertiesImporter.java @@ -146,7 +146,7 @@ public List> transform(StudyImportContext ctx, List errors.reject(null, ve.getMessage())); } - ctx.getLogger().info("Done importing " + getDescription()); + ctx.getLogger().info("Done importing {}", getDescription()); } } } diff --git a/study/src/org/labkey/study/importer/TreatmentVisitMapImporter.java b/study/src/org/labkey/study/importer/TreatmentVisitMapImporter.java index 5b7cd80b5a4..9481c83bf31 100644 --- a/study/src/org/labkey/study/importer/TreatmentVisitMapImporter.java +++ b/study/src/org/labkey/study/importer/TreatmentVisitMapImporter.java @@ -75,7 +75,7 @@ public void process(StudyImportContext ctx, VirtualFile root, BindException erro { ExportDirType dirType = ctx.getXml().getTreatmentData(); - ctx.getLogger().info("Loading " + getDescription()); + ctx.getLogger().info("Loading {}", getDescription()); VirtualFile vf = root.getDir(dirType.getDir()); if (vf != null) @@ -96,7 +96,7 @@ public void process(StudyImportContext ctx, VirtualFile root, BindException erro else throw new ImportException("Unable to open the folder at : " + dirType.getDir()); - ctx.getLogger().info("Done importing " + getDescription()); + ctx.getLogger().info("Done importing {}", getDescription()); } } @@ -152,7 +152,7 @@ public List> transform(StudyImportContext ctx, List> transform(StudyImportContext ctx, List records) records.sort(Comparator.comparing(VisitMapRecord::getSequenceNumMin)); // Initialize to less than the smallest min - BigDecimal max = records.get(0).getSequenceNumMin().subtract(BigDecimal.ONE); + BigDecimal max = records.getFirst().getSequenceNumMin().subtract(BigDecimal.ONE); for (VisitMapRecord r : records) { diff --git a/study/src/org/labkey/study/model/ChildStudyDefinition.java b/study/src/org/labkey/study/model/ChildStudyDefinition.java index e1c3fd47506..2145ae52b0e 100644 --- a/study/src/org/labkey/study/model/ChildStudyDefinition.java +++ b/study/src/org/labkey/study/model/ChildStudyDefinition.java @@ -359,18 +359,18 @@ public void setTimepointType(String timepointType) public void logSelections(Logger logger) { logger.info("----- Start Selected Properties -----"); - logger.info("Name: " + getName()); - logger.info("Timepoint Type: " + getTimepointType()); - logger.info("Source Path: " + getSrcPath()); - logger.info("Destination Path: " + getDstPath()); - logger.info("Participant Groups: " + (isParticipantGroupsAll() ? "All" : Arrays.toString(getGroups()))); - logger.info("Datasets: " + Arrays.toString(getDatasets())); - logger.info("Data Refresh: " + (isUpdate() ? (getUpdateDelay() > 0 ? "Automatic" : "Manual") : "None")); - logger.info("Visits: " + arrayToString(getVisits())); - logger.info("Specimens: " + (isIncludeSpecimens() ? (isSpecimenRefresh() ? "Nightly refresh" : "One-time snapshot") : "None")); - logger.info("Study Objects: " + arrayToString(getStudyProps())); - logger.info("Folder Objects: " + arrayToString(getFolderProps())); - logger.info("Publish Options: [" + String.join("; ", getPublishOptionsArr()) + "]"); + logger.info("Name: {}", getName()); + logger.info("Timepoint Type: {}", getTimepointType()); + logger.info("Source Path: {}", getSrcPath()); + logger.info("Destination Path: {}", getDstPath()); + logger.info("Participant Groups: {}", isParticipantGroupsAll() ? "All" : Arrays.toString(getGroups())); + logger.info("Datasets: {}", Arrays.toString(getDatasets())); + logger.info("Data Refresh: {}", isUpdate() ? (getUpdateDelay() > 0 ? "Automatic" : "Manual") : "None"); + logger.info("Visits: {}", arrayToString(getVisits())); + logger.info("Specimens: {}", isIncludeSpecimens() ? (isSpecimenRefresh() ? "Nightly refresh" : "One-time snapshot") : "None"); + logger.info("Study Objects: {}", arrayToString(getStudyProps())); + logger.info("Folder Objects: {}", arrayToString(getFolderProps())); + logger.info("Publish Options: [{}]", String.join("; ", getPublishOptionsArr())); logger.info("----- End Selected Properties -----"); } diff --git a/study/src/org/labkey/study/model/DatasetDefinition.java b/study/src/org/labkey/study/model/DatasetDefinition.java index 13678c5f513..0780180ed02 100644 --- a/study/src/org/labkey/study/model/DatasetDefinition.java +++ b/study/src/org/labkey/study/model/DatasetDefinition.java @@ -853,7 +853,7 @@ public int deleteRows(@Nullable Date cutoff) transaction.commit(); time.stop(); - _log.debug("purgeDataset " + getDisplayString() + " " + DateUtil.formatDuration(time.getTotal()/1000)); + _log.debug("purgeDataset {} {}", getDisplayString(), DateUtil.formatDuration(time.getTotal() / 1000)); } return count; @@ -1553,7 +1553,7 @@ private ColumnInfo getStorageColumn(Domain d, DomainProperty p) if (col == null) { - _log.error("didn't find column for property: " + p.getPropertyURI()); + _log.error("didn't find column for property: {}", p.getPropertyURI()); continue; } @@ -1984,16 +1984,12 @@ public Domain getDomain(boolean forUpdate) public DomainKind getDomainKind() { - switch (getStudy().getTimepointType()) + return switch (getStudy().getTimepointType()) { - case VISIT: - return new VisitDatasetDomainKind(); - case DATE: - case CONTINUOUS: - return new DateDatasetDomainKind(); - default: - return null; - } + case VISIT -> new VisitDatasetDomainKind(); + case DATE, CONTINUOUS -> new DateDatasetDomainKind(); + default -> null; + }; } @@ -2312,7 +2308,7 @@ private List insertData(User user, DataIteratorBuilder in, DataIteratorC if (errors.hasErrors()) throw errors; - _log.debug("imported " + getName() + " : " + DateUtil.formatDuration(Math.max(0,end-start))); + _log.debug("imported {} : {}", getName(), DateUtil.formatDuration(Math.max(0, end - start))); transaction.commit(); if (logger != null) logger.debug("commit complete"); @@ -2735,7 +2731,7 @@ public Map getDatasetRow(User u, String lsid) return null; List> rows = getDatasetRows(u, Collections.singleton(lsid)); assert rows.size() <= 1 : "Expected zero or one matching row, but found " + rows.size(); - return rows.isEmpty() ? null : rows.get(0); + return rows.isEmpty() ? null : rows.getFirst(); } @@ -2856,9 +2852,9 @@ public static void cleanupOrphanedDatasetDomains() DomainDescriptor domainDescriptor = OntologyManager.getDomainDescriptor(domain.getTypeId()); if (domainDescriptor != null) { - _log.error("Likely domain project/container mismatch for " + domain + ". Container: " + domainDescriptor.getContainer().getPath() + ", marked as project: " + domainDescriptor.getProject().getPath()); + _log.error("Likely domain project/container mismatch for {}. Container: {}, marked as project: {}", domain, domainDescriptor.getContainer().getPath(), domainDescriptor.getProject().getPath()); } - _log.error("Failed to delete orphaned dataset domain " + domain + " in container " + domain.getContainer().getPath(), x); + _log.error("Failed to delete orphaned dataset domain {} in container {}", domain, domain.getContainer().getPath(), x); } } } diff --git a/study/src/org/labkey/study/model/DatasetImportTestCase.jsp b/study/src/org/labkey/study/model/DatasetImportTestCase.jsp index c6c58c6570c..f36e10980df 100644 --- a/study/src/org/labkey/study/model/DatasetImportTestCase.jsp +++ b/study/src/org/labkey/study/model/DatasetImportTestCase.jsp @@ -266,7 +266,7 @@ public void test() throws Throwable { List l = x.getRowErrors(); if (!l.isEmpty()) - throw l.get(0); + throw l.getFirst(); throw x; } finally @@ -291,9 +291,9 @@ private void _testDatasetUpdateService(StudyImpl study) throws Throwable // insert one row rows.add(PageFlowUtil.mapInsensitive("SubjectId", "A1", "Date", Jan1, "Measure", "Test" + (++this.counterRow), "Value", 1.0)); List> ret = qus.insertRows(_context.getUser(), study.getContainer(), rows, errors, null, null); - String msg = !errors.getRowErrors().isEmpty() ? errors.getRowErrors().get(0).toString() : "no message"; + String msg = !errors.getRowErrors().isEmpty() ? errors.getRowErrors().getFirst().toString() : "no message"; assertFalse(msg, errors.hasErrors()); - Map firstRowMap = ret.get(0); + Map firstRowMap = ret.getFirst(); String lsidRet = (String)firstRowMap.get("lsid"); assertNotNull(lsidRet); assertTrue("lsid should end with "+":101.A1.20110101.0000.Test"+counterRow + ". Was: " + lsidRet, lsidRet.endsWith(":101.A1.20110101.0000.Test"+counterRow)); @@ -310,7 +310,7 @@ private void _testDatasetUpdateService(StudyImpl study) throws Throwable // duplicate row qus.insertRows(_context.getUser(), study.getContainer(), rows, errors, null, null); //study:Label: Only one row is allowed for each Subject/Visit/Measure Triple. Duplicates were found in the database or imported data.; Duplicate: Subject = A1Date = Sat Jan 01 00:00:00 PST 2011, Measure = Test1 - assertTrue(errors.getRowErrors().get(0).getMessage().contains("Duplicates were found")); + assertTrue(errors.getRowErrors().getFirst().getMessage().contains("Duplicates were found")); // different participant rows.clear(); errors.clear(); @@ -336,39 +336,39 @@ private void _testDatasetUpdateService(StudyImpl study) throws Throwable rows.add(PageFlowUtil.mapInsensitive("SubjectId", "A1", "Date", Jan1, "Measure", "Test" + (counterRow), "Value", 1.0)); qus.insertRows(_context.getUser(), study.getContainer(), rows, errors, null, null); //study:Label: Only one row is allowed for each Subject/Visit/Measure Triple. Duplicates were found in the database or imported data.; Duplicate: Subject = A1Date = Sat Jan 01 00:00:00 PST 2011, Measure = Test3 - assertTrue(errors.getRowErrors().get(0).getMessage().contains("Duplicates were found in the database or imported data")); + assertTrue(errors.getRowErrors().getFirst().getMessage().contains("Duplicates were found in the database or imported data")); // missing participantid rows.clear(); errors.clear(); rows.add(PageFlowUtil.mapInsensitive("SubjectId", null, "Date", Jan1, "Measure", "Test" + (++counterRow), "Value", 1.0)); qus.insertRows(_context.getUser(), study.getContainer(), rows, errors, null, null); //study:Label: All dataset rows must include a value for SubjectID - msg = errors.getRowErrors().get(0).getMessage(); + msg = errors.getRowErrors().getFirst().getMessage(); assertTrue(msg.contains("required") || msg.contains("must include")); - assertTrue(errors.getRowErrors().get(0).getMessage().contains("SubjectID")); + assertTrue(errors.getRowErrors().getFirst().getMessage().contains("SubjectID")); // missing date rows.clear(); errors.clear(); rows.add(PageFlowUtil.mapInsensitive("SubjectId", "A1", "Date", null, "Measure", "Test" + (++counterRow), "Value", 1.0)); qus.insertRows(_context.getUser(), study.getContainer(), rows, errors, null, null); //study:Label: Row 1 does not contain required field date. - assertTrue(errors.getRowErrors().get(0).getMessage().toLowerCase().contains("date")); + assertTrue(errors.getRowErrors().getFirst().getMessage().toLowerCase().contains("date")); // missing required property field (Measure in map) rows.clear(); errors.clear(); rows.add(PageFlowUtil.mapInsensitive("SubjectId", "A1", "Date", Jan1, "Measure", null, "Value", 1.0)); qus.insertRows(_context.getUser(), study.getContainer(), rows, errors, null, null); //study:Label: Row 1 does not contain required field Measure. - assertTrue(errors.getRowErrors().get(0).getMessage().contains("required")); - assertTrue(errors.getRowErrors().get(0).getMessage().contains("Measure")); + assertTrue(errors.getRowErrors().getFirst().getMessage().contains("required")); + assertTrue(errors.getRowErrors().getFirst().getMessage().contains("Measure")); // missing required property field (Measure not in map) rows.clear(); errors.clear(); rows.add(PageFlowUtil.mapInsensitive("SubjectId", "A1", "Date", Jan1, "Value", 1.0)); qus.insertRows(_context.getUser(), study.getContainer(), rows, errors, null, null); //study:Label: Row 1 does not contain required field Measure. - assertTrue(errors.getRowErrors().get(0).getMessage().contains("does not contain required field")); - assertTrue(errors.getRowErrors().get(0).getMessage().contains("Measure")); + assertTrue(errors.getRowErrors().getFirst().getMessage().contains("does not contain required field")); + assertTrue(errors.getRowErrors().getFirst().getMessage().contains("Measure")); // legal MV indicator rows.clear(); errors.clear(); @@ -381,7 +381,7 @@ private void _testDatasetUpdateService(StudyImpl study) throws Throwable rows.add(PageFlowUtil.mapInsensitive("SubjectId", "A1", "Date", Jan1, "Measure", "Test" + (++counterRow), "Value", "N/A")); qus.insertRows(_context.getUser(), study.getContainer(), rows, errors, null, null); //study:Label: Value: Could not convert value 'N/A' (String) for Double field 'Value' - assertTrue(errors.getRowErrors().get(0).getMessage().endsWith(ConvertHelper.getStandardConversionErrorMessage("N/A", "Value", Double.class))); + assertTrue(errors.getRowErrors().getFirst().getMessage().endsWith(ConvertHelper.getStandardConversionErrorMessage("N/A", "Value", Double.class))); // conversion test rows.clear(); errors.clear(); @@ -394,7 +394,7 @@ private void _testDatasetUpdateService(StudyImpl study) throws Throwable rows.add(PageFlowUtil.mapInsensitive("SubjectId", "A1", "Date", Jan1, "Measure", "Test" + (++counterRow), "Value", 1, "Number", 101)); qus.insertRows(_context.getUser(), study.getContainer(), rows, errors, null, null); //study:Label: Value '101.0' for field 'Number' is invalid. - assertTrue(errors.getRowErrors().get(0).getMessage().contains("is invalid")); + assertTrue(errors.getRowErrors().getFirst().getMessage().contains("is invalid")); rows.clear(); errors.clear(); rows.add(PageFlowUtil.mapInsensitive("SubjectId", "A1", "Date", Jan1, "Measure", "Test" + (counterRow), "Value", 1, "Number", 99)); @@ -410,7 +410,7 @@ private void _testDatasetUpdateService(StudyImpl study) throws Throwable assertFalse(errors.hasErrors()); qcstates = QCStateManager.getInstance().getStates(study.getContainer()); assertEquals(1, qcstates.size()); - assertEquals("dirty" , qcstates.get(0).getLabel()); + assertEquals("dirty" , qcstates.getFirst().getLabel()); // let's try to update a row rows.clear(); errors.clear(); @@ -454,18 +454,18 @@ private void _testDatasetDetailedLogging(StudyImpl study) throws Throwable errors.clear(); rows.add(PageFlowUtil.mapInsensitive("SubjectId", "A1", "Date", Jan1, "Measure", "Initial", "Value", 1.0)); List> ret = qus.insertRows(_context.getUser(), study.getContainer(), rows, errors, config, null); - String msg = !errors.getRowErrors().isEmpty() ? errors.getRowErrors().get(0).toString() : "no message"; + String msg = !errors.getRowErrors().isEmpty() ? errors.getRowErrors().getFirst().toString() : "no message"; assertFalse(msg, errors.hasErrors()); - Map firstRowMap = ret.get(0); + Map firstRowMap = ret.getFirst(); String lsidRet = (String)firstRowMap.get("lsid"); assertNotNull(lsidRet); SimpleFilter f = new SimpleFilter(new FieldKey(null,"RowId"),rowid, CompareType.GT); List events = AuditLogService.get().getAuditEvents(study.getContainer(),_context.getUser(),DATASET_AUDIT_EVENT,f,new Sort("-RowId")); assertFalse(events.isEmpty()); - assertNull(events.get(0).getOldRecordMap()); - assertNotNull(events.get(0).getNewRecordMap()); - Map newRecordMap = new CaseInsensitiveHashMap<>(PageFlowUtil.mapFromQueryString(events.get(0).getNewRecordMap())); + assertNull(events.getFirst().getOldRecordMap()); + assertNotNull(events.getFirst().getNewRecordMap()); + Map newRecordMap = new CaseInsensitiveHashMap<>(PageFlowUtil.mapFromQueryString(events.getFirst().getNewRecordMap())); assertEquals(lsidRet, newRecordMap.get("lsid")); assertEquals("Initial", newRecordMap.get("Measure")); assertEquals("1.0", newRecordMap.get("Value")); @@ -479,14 +479,14 @@ private void _testDatasetDetailedLogging(StudyImpl study) throws Throwable events = AuditLogService.get().getAuditEvents(study.getContainer(),_context.getUser(),DATASET_AUDIT_EVENT,f,new Sort("-RowId")); assertFalse(events.isEmpty()); - assertNotNull(events.get(0).getOldRecordMap()); - Map oldRecordMap = new CaseInsensitiveHashMap<>(PageFlowUtil.mapFromQueryString(events.get(0).getOldRecordMap())); + assertNotNull(events.getFirst().getOldRecordMap()); + Map oldRecordMap = new CaseInsensitiveHashMap<>(PageFlowUtil.mapFromQueryString(events.getFirst().getOldRecordMap())); assertFalse(oldRecordMap.containsKey("lsid")); assertEquals("Initial", newRecordMap.get("Measure")); assertEquals("1.0", newRecordMap.get("Value")); assertEquals(2, oldRecordMap.size()); - assertNotNull(events.get(0).getNewRecordMap()); - newRecordMap = new CaseInsensitiveHashMap<>(PageFlowUtil.mapFromQueryString(events.get(0).getNewRecordMap())); + assertNotNull(events.getFirst().getNewRecordMap()); + newRecordMap = new CaseInsensitiveHashMap<>(PageFlowUtil.mapFromQueryString(events.getFirst().getNewRecordMap())); assertFalse(newRecordMap.containsKey("lsid")); assertEquals("Updated",newRecordMap.get("Measure")); assertEquals("2.0", newRecordMap.get("Value")); @@ -501,14 +501,14 @@ private void _testDatasetDetailedLogging(StudyImpl study) throws Throwable events = AuditLogService.get().getAuditEvents(study.getContainer(),_context.getUser(),DATASET_AUDIT_EVENT,f,new Sort("-RowId")); assertFalse(events.isEmpty()); - assertNotNull(events.get(0).getOldRecordMap()); - oldRecordMap = new CaseInsensitiveHashMap<>(PageFlowUtil.mapFromQueryString(events.get(0).getOldRecordMap())); + assertNotNull(events.getFirst().getOldRecordMap()); + oldRecordMap = new CaseInsensitiveHashMap<>(PageFlowUtil.mapFromQueryString(events.getFirst().getOldRecordMap())); assertFalse(oldRecordMap.containsKey("lsid")); assertEquals("Updated", newRecordMap.get("Measure")); assertEquals("2.0", newRecordMap.get("Value")); assertEquals(2, oldRecordMap.size()); - assertNotNull(events.get(0).getNewRecordMap()); - newRecordMap = new CaseInsensitiveHashMap<>(PageFlowUtil.mapFromQueryString(events.get(0).getNewRecordMap())); + assertNotNull(events.getFirst().getNewRecordMap()); + newRecordMap = new CaseInsensitiveHashMap<>(PageFlowUtil.mapFromQueryString(events.getFirst().getNewRecordMap())); assertFalse(newRecordMap.containsKey("lsid")); assertEquals("Merged",newRecordMap.get("Measure")); assertEquals("3.0", newRecordMap.get("Value")); @@ -805,7 +805,7 @@ private void _testDaysSinceStartCalculation(Study study) throws Throwable rows.add(PageFlowUtil.mapInsensitive("SubjectId", "A2", "Date", "2016-02-02 10:00", "Measure", "Test"+(++counterRow), "Value", 1.0)); List> ret = qus.insertRows(_context.getUser(), study.getContainer(), rows, qusErrors, null, null); - String msg = !qusErrors.getRowErrors().isEmpty() ? qusErrors.getRowErrors().get(0).toString() : "no message"; + String msg = !qusErrors.getRowErrors().isEmpty() ? qusErrors.getRowErrors().getFirst().toString() : "no message"; assertFalse(msg, qusErrors.hasErrors()); try (ResultSet rs = new TableSelector(tableInfo).getResultSet()) @@ -842,7 +842,7 @@ private void _testDatasetTransformExport(Study study) throws Throwable rows.add(PageFlowUtil.mapInsensitive("SubjectId", "DS1", "Date", jan1, "Measure", "Test" + (++this.counterRow), "Value", 0.0)); List> ret = qus.insertRows(_context.getUser(), study.getContainer(), rows, errors, null, null); assertFalse(errors.hasErrors()); - Map firstRowMap = ret.get(0); + Map firstRowMap = ret.getFirst(); // Ensure alternateIds are generated for all participants StudyManager.getInstance().generateNeededAlternateParticipantIds(study, _context.getUser()); diff --git a/study/src/org/labkey/study/model/ParticipantDataMapKey.java b/study/src/org/labkey/study/model/ParticipantDataMapKey.java index 83613add5ec..b40deb5300a 100644 --- a/study/src/org/labkey/study/model/ParticipantDataMapKey.java +++ b/study/src/org/labkey/study/model/ParticipantDataMapKey.java @@ -16,6 +16,8 @@ package org.labkey.study.model; +import org.jetbrains.annotations.NotNull; + /** * User: Matthew * Date: Feb 1, 2006 @@ -63,7 +65,7 @@ public int hashCode() @Override - public int compareTo(Object o) + public int compareTo(@NotNull Object o) { ParticipantDataMapKey k = (ParticipantDataMapKey) o; if (this.sequenceNum != k.sequenceNum) diff --git a/study/src/org/labkey/study/model/ParticipantGroupManager.java b/study/src/org/labkey/study/model/ParticipantGroupManager.java index 04cf8d18ba3..1b34d68907a 100644 --- a/study/src/org/labkey/study/model/ParticipantGroupManager.java +++ b/study/src/org/labkey/study/model/ParticipantGroupManager.java @@ -753,7 +753,7 @@ private ParticipantCategoryImpl modifyParticipantCategory(Container c, User user List groups = getParticipantGroups(c, user, def); if (groups.size() != 1) throw new RuntimeException("Expected one group in category " + def.getLabel()); - ParticipantGroup group = groups.get(0); + ParticipantGroup group = groups.getFirst(); switch (ParticipantCategory.Type.valueOf(def.getType())) { @@ -926,7 +926,7 @@ private void updateListTypeDef(Container c, User user, ParticipantCategoryImpl d List groups = getParticipantGroups(c, user, def); if (groups.size() == 1) { - group = groups.get(0); + group = groups.getFirst(); deleteGroupParticipants(c, user, group); } } @@ -1009,7 +1009,7 @@ public void deleteParticipantGroup(Container c, User user, ParticipantGroup grou if (cat.getType().equals("list")) { List groups = getParticipantGroups(c, user, cat); - if (groups.size() == 1 && groups.get(0).equals(group)) + if (groups.size() == 1 && groups.getFirst().equals(group)) { // delete the participant category SQLFragment sqlCat = new SQLFragment("DELETE FROM ").append(getTableInfoParticipantCategory(), "").append(" WHERE RowId = ? "); diff --git a/study/src/org/labkey/study/model/StudyImpl.java b/study/src/org/labkey/study/model/StudyImpl.java index 1f18609dff5..45845139042 100644 --- a/study/src/org/labkey/study/model/StudyImpl.java +++ b/study/src/org/labkey/study/model/StudyImpl.java @@ -1305,7 +1305,7 @@ public void _testAttachProtocolDoc(Study testStudy) throws SQLException, IOExcep testStudy.attachProtocolDocument(Collections.singletonList(file), _context.getUser()); attachedFiles = testStudy.getProtocolDocuments(); assertEquals("Expected 1 attached document", 1, attachedFiles.size()); - assertTrue("Expected filename to be \"Protocol.txt\", but it was \"" + attachedFiles.get(0).getName() + "\"", attachedFiles.get(0).getName().equals("Protocol.txt")); + assertEquals("Expected filename to be \"Protocol.txt\", but it was \"" + attachedFiles.getFirst().getName() + "\"", "Protocol.txt", attachedFiles.getFirst().getName()); } public void _testDeleteProtocolDoc(Study testStudy) throws SQLException, IOException diff --git a/study/src/org/labkey/study/model/StudyManager.java b/study/src/org/labkey/study/model/StudyManager.java index fb1174eb8a6..395b3b49248 100644 --- a/study/src/org/labkey/study/model/StudyManager.java +++ b/study/src/org/labkey/study/model/StudyManager.java @@ -812,12 +812,12 @@ else if (datasetDefinition.getKeyPropertyName() == null) } catch (DataIntegrityViolationException x) { - _log.debug("Old Dataset: " + old.getName()); - _log.debug(" Demographic: " + old.isDemographicData()); - _log.debug(" Key: " + old.getKeyPropertyName()); - _log.debug("New Dataset: " + datasetDefinition.getName()); - _log.debug(" Demographic: " + datasetDefinition.isDemographicData()); - _log.debug(" Key: " + datasetDefinition.getKeyPropertyName()); + _log.debug("Old Dataset: {}", old.getName()); + _log.debug(" Demographic: {}", old.isDemographicData()); + _log.debug(" Key: {}", old.getKeyPropertyName()); + _log.debug("New Dataset: {}", datasetDefinition.getName()); + _log.debug(" Demographic: {}", datasetDefinition.isDemographicData()); + _log.debug(" Key: {}", datasetDefinition.getKeyPropertyName()); if (datasetDefinition.isDemographicData()) throw new IllegalArgumentException("Can not change dataset type to demographic for dataset " + datasetDefinition.getName()); @@ -1267,7 +1267,7 @@ public int importVisitAliases(final Study study, User user, DataIteratorBuilder p.run(); if (context.getErrors().hasErrors()) - throw context.getErrors().getRowErrors().get(0); + throw context.getErrors().getRowErrors().getFirst(); transaction.commit(); @@ -1473,7 +1473,7 @@ public Map importVisitTags(Study study, User user, List 1) throw new IllegalStateException("Expected only one visit tag with given name."); - return visitTags.get(0); + return visitTags.getFirst(); } public Map> getVisitTagMapMap(Study study) @@ -2037,7 +2037,7 @@ public CohortImpl getCohortByLabel(Container container, User user, String label) .toList(); if (cohorts.size() == 1) - return cohorts.get(0); + return cohorts.getFirst(); return null; } @@ -2382,7 +2382,7 @@ public void uncache(DatasetDefinition def) if (null == def) return; - _log.debug("Uncaching dataset: " + def.getName(), new Throwable()); + _log.debug("Uncaching dataset: {}", def.getName(), new Throwable()); _datasetHelper.clearCache(def.getContainer()); String uri = def.getTypeURI(); @@ -3956,16 +3956,12 @@ public VisitManager getVisitManager(Study study) { @Migrate // TODO: Switch VisitManager() to take Study and get rid of cast StudyImpl studyImpl = (StudyImpl)study; - switch (study.getTimepointType()) + return switch (study.getTimepointType()) { - case VISIT: - return new SequenceVisitManager(studyImpl); - case CONTINUOUS: - return new AbsoluteDateVisitManager(studyImpl); - case DATE: - default: - return new RelativeDateVisitManager(studyImpl); - } + case VISIT -> new SequenceVisitManager(studyImpl); + case CONTINUOUS -> new AbsoluteDateVisitManager(studyImpl); + default -> new RelativeDateVisitManager(studyImpl); + }; } public static SQLFragment timePortionFromDateSQL(String dateColumnName) @@ -4038,7 +4034,7 @@ else if (!study.isDataspaceStudy()) if (containers.isEmpty()) return null; else if (containers.size() == 1) - return ContainerManager.getForId(containers.get(0)); + return ContainerManager.getForId(containers.getFirst()); throw new ParticipantNotUniqueException(ptid); } diff --git a/study/src/org/labkey/study/model/StudySnapshot.java b/study/src/org/labkey/study/model/StudySnapshot.java index a0555735f81..94bba84859a 100644 --- a/study/src/org/labkey/study/model/StudySnapshot.java +++ b/study/src/org/labkey/study/model/StudySnapshot.java @@ -35,7 +35,6 @@ import org.labkey.study.writer.StudyExportContext; import java.io.IOException; -import java.sql.SQLException; import java.util.ArrayList; import java.util.Arrays; import java.util.Date; @@ -363,16 +362,9 @@ else if (def.getViews() != null && def.getViews().length > 0) // write out view names instead of entityIds for (String entityid : def.getViews()) { - try - { - String viewName = QueryService.get().getCustomViewNameFromEntityId(ctx.getContainer(), entityid); - if (viewName != null) - views.add(viewName); - } - catch (SQLException e) - { - throw new RuntimeException(e); - } + String viewName = QueryService.get().getCustomViewNameFromEntityId(ctx.getContainer(), entityid); + if (viewName != null) + views.add(viewName); } } } diff --git a/study/src/org/labkey/study/model/VisitDatasetDomainKind.java b/study/src/org/labkey/study/model/VisitDatasetDomainKind.java index a0ce687a04c..aab7b23f71c 100644 --- a/study/src/org/labkey/study/model/VisitDatasetDomainKind.java +++ b/study/src/org/labkey/study/model/VisitDatasetDomainKind.java @@ -16,7 +16,6 @@ package org.labkey.study.model; import org.jetbrains.annotations.NotNull; -import org.labkey.api.collections.CaseInsensitiveHashSet; import org.labkey.api.data.PropertyStorageSpec; import org.labkey.api.data.TableInfo; import org.labkey.api.exp.property.Domain; diff --git a/study/src/org/labkey/study/model/VisitMapKey.java b/study/src/org/labkey/study/model/VisitMapKey.java index 8092497c799..cf4668fe783 100644 --- a/study/src/org/labkey/study/model/VisitMapKey.java +++ b/study/src/org/labkey/study/model/VisitMapKey.java @@ -16,6 +16,8 @@ package org.labkey.study.model; +import org.jetbrains.annotations.NotNull; + /** * User: Matthew * Date: Feb 1, 2006 @@ -47,7 +49,7 @@ public int hashCode() } @Override - public int compareTo(Object o) + public int compareTo(@NotNull Object o) { VisitMapKey k = (VisitMapKey) o; return this.visitRowId != k.visitRowId ? this.visitRowId - k.visitRowId : diff --git a/study/src/org/labkey/study/pipeline/AbstractDatasetImportTask.java b/study/src/org/labkey/study/pipeline/AbstractDatasetImportTask.java index 13941c1ff3a..e90ca6d257f 100644 --- a/study/src/org/labkey/study/pipeline/AbstractDatasetImportTask.java +++ b/study/src/org/labkey/study/pipeline/AbstractDatasetImportTask.java @@ -64,8 +64,8 @@ public AbstractDatasetImportTask(FactoryType factory, PipelineJob job, StudyImpo } public abstract StudyImpl getStudy(); - protected abstract String getDatasetsFileName() throws ImportException; - protected abstract VirtualFile getDatasetsDirectory() throws ImportException; + protected abstract String getDatasetsFileName(); + protected abstract VirtualFile getDatasetsDirectory(); protected StudyManager getStudyManager() { @@ -106,7 +106,7 @@ public static List doImport(VirtualFile datasetsDirectory, St } else { - ctx.getLogger().info("Dataset file \"" + datasetsFileName + "\" not found, inferring columns from the dataset files."); + ctx.getLogger().info("Dataset file \"{}\" not found, inferring columns from the dataset files.", datasetsFileName); reader = new DatasetInferSchemaReader(datasetsDirectory, datasetsFileName, study, ctx); } @@ -131,17 +131,17 @@ public static List doImport(VirtualFile datasetsDirectory, St Set notFound = reader.getDatasetsNotFound(); if (!notFound.isEmpty()) { - ctx.getLogger().warn("Could not find definitions for " + notFound.size() + " dataset data files: " + StringUtils.join(notFound, ", ")); + ctx.getLogger().warn("Could not find definitions for {} dataset data files: {}", notFound.size(), StringUtils.join(notFound, ", ")); } } catch (Exception x) { - ctx.getLogger().error("Parse failed: " + datasetsFileName, x); + ctx.getLogger().error("Parse failed: {}", datasetsFileName, x); return Collections.emptyList(); } List runnables = reader.getRunnables(); - ctx.getLogger().info("Start batch " + datasetsFileName); + ctx.getLogger().info("Start batch {}", datasetsFileName); List datasets = new ArrayList<>(); @@ -168,11 +168,11 @@ public static List doImport(VirtualFile datasetsDirectory, St } catch (Exception x) { - ctx.getLogger().error("Unexpected error loading " + runnable.getFileName(), x); + ctx.getLogger().error("Unexpected error loading {}", runnable.getFileName(), x); } } - ctx.getLogger().info("Finish batch " + datasetsFileName); + ctx.getLogger().info("Finish batch {}", datasetsFileName); if (syncParticipantVisit) { diff --git a/study/src/org/labkey/study/pipeline/DatasetFileReader.java b/study/src/org/labkey/study/pipeline/DatasetFileReader.java index 4c65683c420..78b1381f7b8 100644 --- a/study/src/org/labkey/study/pipeline/DatasetFileReader.java +++ b/study/src/org/labkey/study/pipeline/DatasetFileReader.java @@ -18,6 +18,7 @@ import org.apache.commons.lang3.StringUtils; import org.jetbrains.annotations.Nullable; +import org.jetbrains.annotations.NotNull; import org.labkey.api.collections.CaseInsensitiveHashMap; import org.labkey.api.exp.PropertyDescriptor; import org.labkey.api.util.DateUtil; @@ -485,7 +486,7 @@ public boolean containsKey(Object key) } @Override - public Set> entrySet() + public @NotNull Set> entrySet() { Set> set = new HashSet<>(); set.addAll(keyMap.values()); diff --git a/study/src/org/labkey/study/pipeline/DatasetImportRunnable.java b/study/src/org/labkey/study/pipeline/DatasetImportRunnable.java index 769e68d07b4..e5d5b932add 100644 --- a/study/src/org/labkey/study/pipeline/DatasetImportRunnable.java +++ b/study/src/org/labkey/study/pipeline/DatasetImportRunnable.java @@ -98,7 +98,7 @@ public String validate() { List errors = new ArrayList<>(5); validate(errors); - return errors.isEmpty() ? null : errors.get(0); + return errors.isEmpty() ? null : errors.getFirst(); } public void validate(List errors) @@ -131,7 +131,7 @@ public ColumnDescriptor[] getColumns() } catch (Exception x) { - _logger.error("Exception while importing dataset " + _datasetDefinition.getName() + " from " + _fileName, x); + _logger.error("Exception while importing dataset {} from {}", _datasetDefinition.getName(), _fileName, x); } return new ColumnDescriptor[0]; } @@ -155,7 +155,7 @@ public void run() if (!validateErrors.isEmpty()) { for (String e : validateErrors) - _logger.error(_fileName + " -- " + e); + _logger.error("{} -- {}", _fileName, e); return; } @@ -215,7 +215,7 @@ public void run() } assert cpuImport.start(); - _logger.info(_datasetDefinition.getLabel() + ": Starting import from " + _fileName); + _logger.info("{}: Starting import from {}", _datasetDefinition.getLabel(), _fileName); boolean tryDataDiffing = null != DataIntegrationService.get() && _datasetDefinition.getKeyManagementType() == Dataset.KeyManagementType.None && @@ -284,14 +284,14 @@ public void run() if (_action == AbstractDatasetImportTask.Action.REPLACE || _action == AbstractDatasetImportTask.Action.DELETE) { assert cpuDelete.start(); - _logger.info(_datasetDefinition.getLabel() + ": Starting delete" + (useCutoff ? " of rows newer than " + _replaceCutoff : "")); + _logger.info("{}: Starting delete{}", _datasetDefinition.getLabel(), useCutoff ? " of rows newer than " + _replaceCutoff : ""); int rows = StudyManager.getInstance().purgeDataset(_datasetDefinition, useCutoff ? _replaceCutoff : null); - _logger.info(_datasetDefinition.getLabel() + ": Deleted " + rows + " rows"); + _logger.info("{}: Deleted {} rows", _datasetDefinition.getLabel(), rows); assert cpuDelete.stop(); } assert cpuImport.start(); - _logger.info(_datasetDefinition.getLabel() + ": Starting import from " + _fileName); + _logger.info("{}: Starting import from {}", _datasetDefinition.getLabel(), _fileName); count = qus.importRows(user, c, loader, batchErrors, config, null); @@ -336,21 +336,21 @@ public void run() } catch (Exception x) { - _logger.error("Exception while importing dataset " + _datasetDefinition.getName() + " from " + _fileName, x); + _logger.error("Exception while importing dataset {} from {}", _datasetDefinition.getName(), _fileName, x); } finally { IOUtils.closeQuietly(is); for (ValidationException err : batchErrors.getRowErrors()) - _logger.error(_fileName + " -- " + err.getMessage()); + _logger.error("{} -- {}", _fileName, err.getMessage()); if (_deleteAfterImport) { boolean success = _root.delete(_fileName); if (success) - _logger.info("Deleted file " + _fileName); + _logger.info("Deleted file {}", _fileName); else - _logger.error("Could not delete file " + _fileName); + _logger.error("Could not delete file {}", _fileName); } if (loader != null) diff --git a/study/src/org/labkey/study/pipeline/DatasetInferSchemaReader.java b/study/src/org/labkey/study/pipeline/DatasetInferSchemaReader.java index aec62c765c7..c5c46e75b35 100644 --- a/study/src/org/labkey/study/pipeline/DatasetInferSchemaReader.java +++ b/study/src/org/labkey/study/pipeline/DatasetInferSchemaReader.java @@ -109,7 +109,7 @@ private void initialize() .toList(); // next available dataset ID - int nextId = datasetIds.isEmpty() ? 1000 : datasetIds.get(datasetIds.size()-1) + 1; + int nextId = datasetIds.isEmpty() ? 1000 : datasetIds.getLast() + 1; for (DatasetImportRunnable runnable : getRunnables()) { diff --git a/study/src/org/labkey/study/pipeline/FileAnalysisDatasetTask.java b/study/src/org/labkey/study/pipeline/FileAnalysisDatasetTask.java index 136b69eacc1..03a6ada2717 100644 --- a/study/src/org/labkey/study/pipeline/FileAnalysisDatasetTask.java +++ b/study/src/org/labkey/study/pipeline/FileAnalysisDatasetTask.java @@ -33,7 +33,6 @@ import org.labkey.vfs.FileLike; import org.springframework.validation.BindException; -import java.io.File; import java.util.ArrayList; import java.util.HashMap; import java.util.List; diff --git a/study/src/org/labkey/study/pipeline/ParticipantImportRunnable.java b/study/src/org/labkey/study/pipeline/ParticipantImportRunnable.java index 3d64ba32834..38cac1b11c6 100644 --- a/study/src/org/labkey/study/pipeline/ParticipantImportRunnable.java +++ b/study/src/org/labkey/study/pipeline/ParticipantImportRunnable.java @@ -69,7 +69,7 @@ public void run() } catch (Exception x) { - _logger.error("Unexpected error importing file: " + _fileName, x); + _logger.error("Unexpected error importing file: {}", _fileName, x); } } @@ -106,7 +106,7 @@ public void _run() throws IOException, SQLException String subjectIdCol = StudyService.get().getSubjectColumnName(container); if (!columnMap.containsKey(subjectIdCol)) { - _logger.error("Dataset does not contain column " + subjectIdCol + "."); + _logger.error("Dataset does not contain column {}.", subjectIdCol); return; } diff --git a/study/src/org/labkey/study/query/AssayDatasetTable.java b/study/src/org/labkey/study/query/AssayDatasetTable.java index 203cebf0c08..e32b94c5c99 100644 --- a/study/src/org/labkey/study/query/AssayDatasetTable.java +++ b/study/src/org/labkey/study/query/AssayDatasetTable.java @@ -255,7 +255,7 @@ else if (!"SpecimenLsid".equalsIgnoreCase(name)) if (assayResultTable != null) { sqlf.append(" LEFT OUTER JOIN ").append(assayResultTable.getFromSQL(assayResultAlias)).append("\n"); - sqlf.append(" ON ").append(assayResultAlias).append(".").append(assayResultTable.getPkColumnNames().get(0)).append(" = "); + sqlf.append(" ON ").append(assayResultAlias).append(".").append(assayResultTable.getPkColumnNames().getFirst()).append(" = "); sqlf.appendDottedIdentifiers(alias, getSqlDialect().getColumnSelectName(_dsd.getKeyPropertyName())); } diff --git a/study/src/org/labkey/study/query/CohortUpdateService.java b/study/src/org/labkey/study/query/CohortUpdateService.java index 4e22b4cf6e9..804800c6063 100644 --- a/study/src/org/labkey/study/query/CohortUpdateService.java +++ b/study/src/org/labkey/study/query/CohortUpdateService.java @@ -18,6 +18,7 @@ import org.apache.commons.beanutils.converters.IntegerConverter; import org.apache.commons.lang3.Strings; import org.jetbrains.annotations.Nullable; +import org.jetbrains.annotations.NotNull; import org.labkey.api.data.Container; import org.labkey.api.data.DbScope; import org.labkey.api.data.TableInfo; @@ -112,7 +113,7 @@ protected Map insertRow(User user, Container container, Map updateRow(User user, Container container, Map row, Map oldRow, @Nullable Map configParameters) + protected Map updateRow(User user, Container container, Map row, @NotNull Map oldRow, @Nullable Map configParameters) throws InvalidKeyException, ValidationException { int rowId = oldRow != null ? keyFromMap(oldRow) : keyFromMap(row); diff --git a/study/src/org/labkey/study/query/DatasetQueryView.java b/study/src/org/labkey/study/query/DatasetQueryView.java index 556a1a16d90..749f90a9956 100644 --- a/study/src/org/labkey/study/query/DatasetQueryView.java +++ b/study/src/org/labkey/study/query/DatasetQueryView.java @@ -145,7 +145,7 @@ public DatasetQueryView(UserSchema schema, DatasetQuerySettings settings, BindEx if (!_dataset.getName().equalsIgnoreCase(settings.getQueryName())) { // settings has label instead of name; warn that label is being used to lookup - _systemLog.warn("Dataset in schema'" + schema.getName() + "' was referenced by label (" + settings.getQueryName() + "), not name (" + _dataset.getName() + ")."); + _systemLog.warn("Dataset in schema'{}' was referenced by label ({}), not name ({}).", schema.getName(), settings.getQueryName(), _dataset.getName()); } _showSourceLinks = settings.isShowSourceLinks(); @@ -851,7 +851,7 @@ public SQLFragment getValidationSql(Container container, User user, ExpProtocol SQLFragment sql = new SQLFragment("SELECT DS.lsid") .append(" FROM ").append(rootTable,"DS") .append(" JOIN ").append(dataTable, "AT") - .append(" ON DS.").append(_dataset.getKeyPropertyName()).append(" = ").append("AT.").append(dataTable.getPkColumnNames().get(0)) + .append(" ON DS.").append(_dataset.getKeyPropertyName()).append(" = ").append("AT.").append(dataTable.getPkColumnNames().getFirst()) .append(" WHERE DS.").append(studyVisit).append(" <> AT.").append(_assayVisit).append(" OR ") .append(" DS.ParticipantId <> ").append(rootTable.getSqlDialect().getVarcharCast(new SQLFragment("AT." + _assaySubject.getName()))); diff --git a/study/src/org/labkey/study/query/DatasetTableImpl.java b/study/src/org/labkey/study/query/DatasetTableImpl.java index f32b85fbbc4..ce12a9416f9 100644 --- a/study/src/org/labkey/study/query/DatasetTableImpl.java +++ b/study/src/org/labkey/study/query/DatasetTableImpl.java @@ -885,13 +885,13 @@ public void overlayMetadata(String tableName, UserSchema schema, Collection row, Tab } @Override - protected Map _update(User user, Container container, Map row, Map oldRow, Object[] keys) throws SQLException, ValidationException + protected Map _update(User user, Container container, Map row, Map oldRow, Object[] keys) throws ValidationException { try (DbScope.Transaction transaction = StudyService.get().getDatasetSchema().getScope().ensureTransaction()) { @@ -1034,7 +1033,7 @@ public void updateRowTest() throws Exception assertFalse(errors.hasErrors()); assertNotNull(result); assertEquals(1, result.size()); - var map = result.get(0); + var map = result.getFirst(); assertEquals("S1", map.get(SUBJECT_COLUMN_NAME)); assertEquals("f", map.get("Field1")); assertEquals("s", map.get("SELECT")); @@ -1059,7 +1058,7 @@ public void updateRowTest() throws Exception fail(errors.getMessage()); assertNotNull(result); assertEquals(1, result.size()); - map = result.get(0); + map = result.getFirst(); assertEquals("S2", map.get(SUBJECT_COLUMN_NAME)); // All other columns are preserved assertEquals("f", map.get("Field1")); @@ -1092,7 +1091,7 @@ public void updateRowTest() throws Exception fail(errors.getMessage()); assertNotNull(result); assertEquals(1, result.size()); - map = result.get(0); + map = result.getFirst(); assertEquals("S2", map.get(SUBJECT_COLUMN_NAME)); assertEquals("fUpdated", map.get("Field1")); assertEquals("sUpdated", map.get("SELECT")); diff --git a/study/src/org/labkey/study/query/LocationQueryView.java b/study/src/org/labkey/study/query/LocationQueryView.java index 83ac4446e37..aa144b77e11 100644 --- a/study/src/org/labkey/study/query/LocationQueryView.java +++ b/study/src/org/labkey/study/query/LocationQueryView.java @@ -109,7 +109,7 @@ public void renderGridCellContents(RenderContext ctx, HtmlWriter out) out.write(HtmlString.NBSP); } }; - ret.add(0, update); + ret.addFirst(update); } } } diff --git a/study/src/org/labkey/study/query/LocationTable.java b/study/src/org/labkey/study/query/LocationTable.java index dc22c4919ce..962ca39d30f 100644 --- a/study/src/org/labkey/study/query/LocationTable.java +++ b/study/src/org/labkey/study/query/LocationTable.java @@ -161,7 +161,7 @@ public List> updateRows(User user, Container c, List map = rows.get(0); + Map map = rows.getFirst(); Integer locId = asInteger(map.get("RowId")); if (null == locId) diff --git a/study/src/org/labkey/study/query/SampleDatasetTable.java b/study/src/org/labkey/study/query/SampleDatasetTable.java index f83d1925fdb..f5ea78bda2d 100644 --- a/study/src/org/labkey/study/query/SampleDatasetTable.java +++ b/study/src/org/labkey/study/query/SampleDatasetTable.java @@ -94,7 +94,7 @@ public List getDefaultVisibleColumns() if (sampleTable != null) { sqlf.append(" LEFT OUTER JOIN ").append(sampleTable.getFromSQL(sampleTableAlias)).append("\n"); - sqlf.append(" ON ").appendDottedIdentifiers(sampleTableAlias, sampleTable.getPkColumns().get(0).getAlias()).append(" = "); + sqlf.append(" ON ").appendDottedIdentifiers(sampleTableAlias, sampleTable.getPkColumns().getFirst().getAlias()).append(" = "); var key = getColumn(_dsd.getKeyPropertyName()); sqlf.append(key.getValueSql(alias)); } diff --git a/study/src/org/labkey/study/reports/ReportManager.java b/study/src/org/labkey/study/reports/ReportManager.java index 25427e6459a..f86440151d4 100644 --- a/study/src/org/labkey/study/reports/ReportManager.java +++ b/study/src/org/labkey/study/reports/ReportManager.java @@ -99,7 +99,7 @@ public List> getReportLabelsForDataset(ViewContext context, }); // add the default grid as the first element - labels.add(0, new Pair<>("Default Grid View", "")); + labels.addFirst(new Pair<>("Default Grid View", "")); return labels; } @@ -223,7 +223,7 @@ public void datasetChanged(final Dataset def) { if (def != null) { - _log.debug("Cache cleared notification on dataset : " + def.getDatasetId()); + _log.debug("Cache cleared notification on dataset : {}", def.getDatasetId()); String reportKey = ReportUtil.getReportKey(StudySchema.getInstance().getSchemaName(), def.getName()); for (Report report : ReportUtil.getReportsIncludingInherited(def.getContainer(), null, reportKey)) { diff --git a/study/src/org/labkey/study/reports/StudyCrosstabReport.java b/study/src/org/labkey/study/reports/StudyCrosstabReport.java index c9b827edd68..4259de3c6ab 100644 --- a/study/src/org/labkey/study/reports/StudyCrosstabReport.java +++ b/study/src/org/labkey/study/reports/StudyCrosstabReport.java @@ -100,11 +100,4 @@ public ActionURL getRunReportURL(ViewContext context) } return super.getRunReportURL(context); } - - - @Override - public boolean isSandboxed() - { - return true; - } } diff --git a/study/src/org/labkey/study/reports/StudyQueryReport.java b/study/src/org/labkey/study/reports/StudyQueryReport.java index 9dc7b99db45..407c44c9514 100644 --- a/study/src/org/labkey/study/reports/StudyQueryReport.java +++ b/study/src/org/labkey/study/reports/StudyQueryReport.java @@ -138,10 +138,4 @@ public ActionURL getRunReportURL(ViewContext context) return PageFlowUtil.urlProvider(ReportUrls.class).urlQueryReport(context.getContainer(), this); } - - @Override - public boolean isSandboxed() - { - return true; - } } diff --git a/study/src/org/labkey/study/view/studySummary.jsp b/study/src/org/labkey/study/view/studySummary.jsp index 444497b4d33..fbdd99e72a8 100644 --- a/study/src/org/labkey/study/view/studySummary.jsp +++ b/study/src/org/labkey/study/view/studySummary.jsp @@ -110,7 +110,7 @@ <% if (protocolDocs.size() == 1) { - Attachment attachment = protocolDocs.get(0); + Attachment attachment = protocolDocs.getFirst(); %> <%=attachment.renderDownloadLink(StudyController.getProtocolDocumentDownloadURL(c, attachment.getName()), "Study Protocol Document")%> <% diff --git a/study/src/org/labkey/study/visitmanager/PurgeParticipantsTask.java b/study/src/org/labkey/study/visitmanager/PurgeParticipantsTask.java index 7ee4b849702..ad7a9cb2269 100644 --- a/study/src/org/labkey/study/visitmanager/PurgeParticipantsTask.java +++ b/study/src/org/labkey/study/visitmanager/PurgeParticipantsTask.java @@ -66,7 +66,7 @@ public void run() { // Queue a pipeline job to prevent participant purge from running in parallel with study import, #42641 PipelineJob job = new PurgeParticipantsJob(vbi, root); - LOG.debug("Queuing PurgeParticipantsJob [thread " + Thread.currentThread().getName() + " to " + PipelineService.get().toString() + "]"); + LOG.debug("Queuing PurgeParticipantsJob [thread {} to {}]", Thread.currentThread().getName(), PipelineService.get().toString()); PipelineService.get().queueJob(job); JOB_QUEUED = true; } diff --git a/study/src/org/labkey/study/visitmanager/SequenceVisitManager.java b/study/src/org/labkey/study/visitmanager/SequenceVisitManager.java index 184e744e187..9c0b13d62e1 100644 --- a/study/src/org/labkey/study/visitmanager/SequenceVisitManager.java +++ b/study/src/org/labkey/study/visitmanager/SequenceVisitManager.java @@ -499,7 +499,7 @@ private void _updateVisitRowId(boolean updateAll, @Nullable Logger logger) long start = System.currentTimeMillis(); (null==logger?LogManager.getLogger(SequenceVisitManager.class):logger).trace("START UPDATE", new Throwable()); new SqlExecutor(schema).execute(sqlUpdateVisitRowId); - (null==logger?LogManager.getLogger(SequenceVisitManager.class):logger).trace("DONE UPDATE " + DateUtil.formatDuration(System.currentTimeMillis()-start)); + (null == logger ? LogManager.getLogger(SequenceVisitManager.class) : logger).trace("DONE UPDATE {}", DateUtil.formatDuration(System.currentTimeMillis() - start)); } /** Make sure there is a Visit for each row in StudyData otherwise rows will be orphaned */ diff --git a/study/src/org/labkey/study/visitmanager/VisitManager.java b/study/src/org/labkey/study/visitmanager/VisitManager.java index 60ab0de44f7..79855ec6fee 100644 --- a/study/src/org/labkey/study/visitmanager/VisitManager.java +++ b/study/src/org/labkey/study/visitmanager/VisitManager.java @@ -787,9 +787,6 @@ public String getName() return "Participant purge timer"; } - @Override - public void shutdownPre() {} - @Override public void shutdownStarted() { @@ -802,7 +799,7 @@ public void shutdownStarted() void _dump(String sql) { - LOGGER.debug("DUMP -- " + sql); + LOGGER.debug("DUMP -- {}", sql); DbScope s = StudySchema.getInstance().getScope(); new SqlExecutor(s).executeWithResults(new SQLFragment(sql), (rs, conn) -> { diff --git a/study/src/org/labkey/study/writer/DatasetDataWriter.java b/study/src/org/labkey/study/writer/DatasetDataWriter.java index 8755c2b4896..1a84aa28704 100644 --- a/study/src/org/labkey/study/writer/DatasetDataWriter.java +++ b/study/src/org/labkey/study/writer/DatasetDataWriter.java @@ -274,7 +274,7 @@ public static Collection getColumnsToExport(TableInfo tinfo, Dataset if (null == ptidColumn) ptidColumn = in; else - LOG.error("More than one ptid column found: " + ptidColumn.getName() + " and " + in.getName()); + LOG.error("More than one ptid column found: {} and {}", ptidColumn.getName(), in.getName()); } if (in.getPropertyURI().equals(sequenceURI)) @@ -282,7 +282,7 @@ public static Collection getColumnsToExport(TableInfo tinfo, Dataset if (null == sequenceColumn) sequenceColumn = in; else - LOG.error("More than one sequence number column found: " + sequenceColumn.getName() + " and " + in.getName()); + LOG.error("More than one sequence number column found: {} and {}", sequenceColumn.getName(), in.getName()); } if (in.getPropertyURI().equals(qcStateURI)) @@ -290,7 +290,7 @@ public static Collection getColumnsToExport(TableInfo tinfo, Dataset if (null == qcStateColumn) qcStateColumn = in; else - LOG.error("More than one qc state column found: " + qcStateColumn.getName() + " and " + in.getName()); + LOG.error("More than one qc state column found: {} and {}", qcStateColumn.getName(), in.getName()); } } diff --git a/study/src/org/labkey/study/writer/StudyWriter.java b/study/src/org/labkey/study/writer/StudyWriter.java index e1c66a95f32..c8a8edc8728 100644 --- a/study/src/org/labkey/study/writer/StudyWriter.java +++ b/study/src/org/labkey/study/writer/StudyWriter.java @@ -45,7 +45,7 @@ public String getDataType() @Override public void write(StudyImpl study, StudyExportContext ctx, VirtualFile vf) throws Exception { - LOG.info("Exporting study to " + vf.getLocation()); + LOG.info("Exporting study to {}", vf.getLocation()); Set dataTypes = ctx.getDataTypes(); @@ -89,7 +89,7 @@ public void write(StudyImpl study, StudyExportContext ctx, VirtualFile vf) throw throw e; } - LOG.info("Done exporting study to " + vf.getLocation()); + LOG.info("Done exporting study to {}", vf.getLocation()); } public static boolean includeDatasetMetadata(StudyExportContext ctx) diff --git a/study/test/src/org/labkey/test/tests/search/DataClassSearchTest.java b/study/test/src/org/labkey/test/tests/search/DataClassSearchTest.java index f200a9ef836..8d1f0883cd7 100644 --- a/study/test/src/org/labkey/test/tests/search/DataClassSearchTest.java +++ b/study/test/src/org/labkey/test/tests/search/DataClassSearchTest.java @@ -274,7 +274,7 @@ private void modifySearchableDataClasses() throws Exception insertRowsCommand.addRow(row1); RowsResponse insertResponse = insertRowsCommand.execute(connection, getCurrentContainerPath()); List> responseRows = insertResponse.getRows(); - dataClassRowIds[2] = (int)responseRows.get(0).get("rowid"); + dataClassRowIds[2] = (int)responseRows.getFirst().get("rowid"); _searchHelper.enqueueSearchItem("dataclass:" + DATA_CLASS_DOMAIN_1 + " AND " + DATA_CLASS_ICE_CREAM, Locator.linkContainingText(DATA_CLASS_1_NAME_1)); diff --git a/study/test/src/org/labkey/test/tests/study/AssayTest.java b/study/test/src/org/labkey/test/tests/study/AssayTest.java index 809dab33433..e4f1f414e8c 100644 --- a/study/test/src/org/labkey/test/tests/study/AssayTest.java +++ b/study/test/src/org/labkey/test/tests/study/AssayTest.java @@ -121,9 +121,9 @@ public void testAssayNameMaxLength() throws Exception ReactAssayDesignerPage assayDesignerPage = _assayHelper.createAssayDesign("General", "a" + "0123456789".repeat(15)); List errors = assayDesignerPage.clickSaveExpectingErrors(); checker().verifyEquals("Wrong number of errors", 1, errors.size()); - checker().verifyEquals("Wrong error message: " + errors.get(0), + checker().verifyEquals("Wrong error message: " + errors.getFirst(), "Value is too long for assay design name, a maximum length of 150 is allowed. The supplied value, 'a01234567890123456789012...78901234567890123456789', was 151 characters long.", - errors.get(0)); + errors.getFirst()); assayDesignerPage.clickCancel(); } @@ -196,7 +196,7 @@ public void testFailedCreation() throws Exception log("Save initial assay design with sample field set to 'All Samples'"); List errors = assayDesignerPage.clickSaveExpectingErrors(); assertEquals("Wrong number of errors", 1, errors.size()); - assertTrue("Wrong error message: " + errors.get(0), errors.get(0).startsWith("Name cannot exceed 200 characters, but was")); + assertTrue("Wrong error message: " + errors.getFirst(), errors.getFirst().startsWith("Name cannot exceed 200 characters, but was")); resultsPanel.removeAllFields(false); resultsPanel.addField("ShortAndSweet"); diff --git a/study/test/src/org/labkey/test/tests/study/CohortTest.java b/study/test/src/org/labkey/test/tests/study/CohortTest.java index 2a6c4d87c14..7c3f6d9902f 100644 --- a/study/test/src/org/labkey/test/tests/study/CohortTest.java +++ b/study/test/src/org/labkey/test/tests/study/CohortTest.java @@ -654,7 +654,7 @@ private void verifyParticipantList(String[] ptids, boolean expectEnrolledText) // we should not see the "enrolled" text in the participant list status message if no participants are unenrolled if (!expectEnrolledText) { - assertTrue("Should not see text: enrolled", !statusText.contains("enrolled")); + assertFalse("Should not see text: enrolled", statusText.contains("enrolled")); } else { diff --git a/study/test/src/org/labkey/test/tests/study/LinkAssayToStudyTest.java b/study/test/src/org/labkey/test/tests/study/LinkAssayToStudyTest.java index 03dba8fb0f6..6104f9780ab 100644 --- a/study/test/src/org/labkey/test/tests/study/LinkAssayToStudyTest.java +++ b/study/test/src/org/labkey/test/tests/study/LinkAssayToStudyTest.java @@ -31,7 +31,6 @@ import org.labkey.test.util.LogMethod; import org.labkey.test.util.StudyHelper; -import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; diff --git a/study/test/src/org/labkey/test/tests/study/SharedStudyTest.java b/study/test/src/org/labkey/test/tests/study/SharedStudyTest.java index d54c8b68973..19e573c38d1 100644 --- a/study/test/src/org/labkey/test/tests/study/SharedStudyTest.java +++ b/study/test/src/org/labkey/test/tests/study/SharedStudyTest.java @@ -52,6 +52,7 @@ import java.util.Set; import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNull; import static org.labkey.test.util.PermissionsHelper.READER_ROLE; @Category({Daily.class}) @@ -411,7 +412,7 @@ public void testSharedDatasetOverrides() clickAndWait(Locator.linkWithText("Change Properties")); // verify the shared dataset label is readonly while the local dataset is not - assertEquals(null, getAttribute(Locator.xpath("//input[@type='text' and @value='" + STUDY2_DATASET + "']"), "readonly")); + assertNull(getAttribute(Locator.xpath("//input[@type='text' and @value='" + STUDY2_DATASET + "']"), "readonly")); assertEquals("true", getAttribute(Locator.xpath("//input[@type='text' and @value='" + SHARED_DEMOGRAPHICS + "']"), "readonly")); // hide the demographics dataset in STUDY2 diff --git a/study/test/src/org/labkey/test/tests/study/StudyDatasetFileFieldTest.java b/study/test/src/org/labkey/test/tests/study/StudyDatasetFileFieldTest.java index 81b436d8f6b..22aa6360448 100644 --- a/study/test/src/org/labkey/test/tests/study/StudyDatasetFileFieldTest.java +++ b/study/test/src/org/labkey/test/tests/study/StudyDatasetFileFieldTest.java @@ -1,7 +1,6 @@ package org.labkey.test.tests.study; import org.apache.commons.io.FileUtils; -import org.apache.commons.lang3.SystemUtils; import org.jetbrains.annotations.Nullable; import org.junit.BeforeClass; import org.junit.Test; @@ -296,7 +295,7 @@ public void testFileRenamingAndAuditing() throws IOException, CommandException protected void verifyFileAuditLogs(List> expectedFileData) throws IOException, CommandException { - List columnNames = expectedFileData.get(0).keySet().stream().map(Object::toString).toList(); + List columnNames = expectedFileData.getFirst().keySet().stream().map(Object::toString).toList(); AuditLogHelper auditLogHelper = new AuditLogHelper(this, () -> WebTestHelper.getRemoteApiConnection(false)); List> events = auditLogHelper.getAuditLogsFromLKS(getProjectName(), AuditLogHelper.AuditEvent.FILE_SYSTEM_EVENT, columnNames, null, expectedFileData.size(), null).getRows(); assertEquals("Number of file audit log events not as expected", expectedFileData.size(), events.size()); diff --git a/study/test/src/org/labkey/test/tests/study/StudyManualTest.java b/study/test/src/org/labkey/test/tests/study/StudyManualTest.java index 542ab3bfab0..ca7fa6b6c28 100644 --- a/study/test/src/org/labkey/test/tests/study/StudyManualTest.java +++ b/study/test/src/org/labkey/test/tests/study/StudyManualTest.java @@ -34,12 +34,6 @@ public abstract class StudyManualTest extends StudyTest protected final File VISIT_MAP = TestFileUtils.getSampleData("study/v068_visit_map.xml"); protected final StudyHelper _studyHelper = new StudyHelper(this); - @Override - protected BrowserType bestBrowser() - { - return BrowserType.CHROME; - } - @Override protected void doCreateSteps() { diff --git a/study/test/src/org/labkey/test/tests/study/StudyPHIExportTest.java b/study/test/src/org/labkey/test/tests/study/StudyPHIExportTest.java index bd199bd16b1..4eac6b365a2 100644 --- a/study/test/src/org/labkey/test/tests/study/StudyPHIExportTest.java +++ b/study/test/src/org/labkey/test/tests/study/StudyPHIExportTest.java @@ -256,13 +256,13 @@ protected void verifyMaskedClinics(int clinicCount) waitAndClickAndWait(Locator.linkWithText("Blood (Whole)")); DataRegionTable vialsTable = new DataRegionTable("SpecimenDetail", this); List procLocs = vialsTable.getColumnDataAsText("Processing Location"); - procLocs.remove(procLocs.size() - 1); // Skip aggregate row + procLocs.removeLast(); // Skip aggregate row for (String procLoc : procLocs) { assertTrue("Processing Locations was not masked", procLoc.equals("Clinic") || nonClinics.contains(procLoc)); } List siteNames = vialsTable.getColumnDataAsText("Site Name"); - siteNames.remove(siteNames.size() - 1); // Skip aggregate row + siteNames.removeLast(); // Skip aggregate row for (String siteName : siteNames) { assertTrue("Site Name was not masked", siteName.equals("Clinic") || siteName.equals("In Transit")); diff --git a/study/test/src/org/labkey/test/tests/study/StudyProtocolDesignerTest.java b/study/test/src/org/labkey/test/tests/study/StudyProtocolDesignerTest.java index 24a448d5a98..1eb76b98a0e 100644 --- a/study/test/src/org/labkey/test/tests/study/StudyProtocolDesignerTest.java +++ b/study/test/src/org/labkey/test/tests/study/StudyProtocolDesignerTest.java @@ -225,7 +225,7 @@ public void testTreatmentSchedule() // add visit/treatment mappings for the Positive cohort treatmentsPage.addCohortTreatmentMapping(VISITS.get(0), TREATMENTS[0], 1); treatmentsPage.addCohortTreatmentMapping(VISITS.get(1), TREATMENTS[0], 1); - treatmentsPage.addCohortTreatmentMapping(NEW_VISITS.get(0), TREATMENTS[1], 1); + treatmentsPage.addCohortTreatmentMapping(NEW_VISITS.getFirst(), TREATMENTS[1], 1); // add the first new cohort and define the treatment/visit mappings for it treatmentsPage.addNewCohortRow(NEW_COHORTS[0], 2, 2); @@ -258,7 +258,7 @@ public void testAssaySchedule() // add the first assay and define the properties for it assaySchedulePage.addNewAssayRow(NEW_ASSAYS[0] + " Label", null, 0); assaySchedulePage.setBaseProperties(LABS[0] + " Label", null, null, null, null, 0); - assaySchedulePage.selectVisits(Arrays.asList(VISITS.get(0), NEW_VISITS.get(0)), 0); + assaySchedulePage.selectVisits(Arrays.asList(VISITS.getFirst(), NEW_VISITS.getFirst()), 0); // add the second assay and define the properties for it assaySchedulePage.addNewAssayRow(NEW_ASSAYS[1] + " Label", null, 1); @@ -424,7 +424,7 @@ public void testManageTreatmentsSingleTable() treatmentDialog = singleManagementTable.clickCell(1,5); treatmentDialog.selectOption(TreatmentDialog.Sections.Immunogen, EXPECTED_IMMUNOGEN_VALUES.get(0)) .selectOption(TreatmentDialog.Sections.Immunogen, EXPECTED_IMMUNOGEN_VALUES.get(1)) - .selectOption(TreatmentDialog.Sections.Adjuvant, EXPECTED_ADJUVANT_VALUES.get(0)) + .selectOption(TreatmentDialog.Sections.Adjuvant, EXPECTED_ADJUVANT_VALUES.getFirst()) .selectOption(TreatmentDialog.Sections.Challenge, EXPECTED_CHALLENGE_VALUES.get(1)); treatmentDialog.clickOk(); sleep(500); @@ -507,7 +507,7 @@ private Integer queryVisitRowId(String folderPath, BaseManageVaccineDesignVisitP List> rows = response.getRows(); if (rows.size() == 1) - return Integer.parseInt(rows.get(0).get("RowId").toString()); + return Integer.parseInt(rows.getFirst().get("RowId").toString()); return null; } @@ -602,14 +602,14 @@ private void verifyTreatmentSchedule() verifyCohortRow(immunizationScheduleWebpart, 0, COHORTS[1], null, visitTreatments, allVisitLabels); visitTreatments = new HashMap<>(); - visitTreatments.put(VISITS.get(0).getLabel(), TREATMENTS[0]); + visitTreatments.put(VISITS.getFirst().getLabel(), TREATMENTS[0]); visitTreatments.put(NEW_VISITS.get(1).getLabel(), TREATMENTS[1]); verifyCohortRow(immunizationScheduleWebpart, 1, NEW_COHORTS[1], 5, visitTreatments, allVisitLabels); visitTreatments = new HashMap<>(); visitTreatments.put(VISITS.get(0).getLabel(), TREATMENTS[0]); visitTreatments.put(VISITS.get(1).getLabel(), TREATMENTS[0]); - visitTreatments.put(NEW_VISITS.get(0).getLabel(), TREATMENTS[1]); + visitTreatments.put(NEW_VISITS.getFirst().getLabel(), TREATMENTS[1]); verifyCohortRow(immunizationScheduleWebpart, 2, COHORTS[0], null, visitTreatments, allVisitLabels); visitTreatments = new HashMap<>(); @@ -657,7 +657,7 @@ private void verifyAssaySchedule() assertFalse("Expected rows in the immunization schedule table", assayScheduleWebpart.isEmpty()); assertEquals("Unexpected number of assay rows", NEW_ASSAYS.length + 1, assayScheduleWebpart.getAssayRowCount()); - verifyAssayRow(assayScheduleWebpart, 0, NEW_ASSAYS[0] + " Label", LABS[0] + " Label", Arrays.asList(VISITS.get(0), NEW_VISITS.get(0))); + verifyAssayRow(assayScheduleWebpart, 0, NEW_ASSAYS[0] + " Label", LABS[0] + " Label", Arrays.asList(VISITS.get(0), NEW_VISITS.getFirst())); verifyAssayRow(assayScheduleWebpart, 1, NEW_ASSAYS[2] + " Label", LABS[2] + " Label", Arrays.asList(VISITS.get(2))); verifyAssayRow(assayScheduleWebpart, 2, NEW_ASSAYS[2] + " Label", LABS[3] + " Label", Collections.emptyList()); verifyAssayRow(assayScheduleWebpart, 3, NEW_ASSAYS[1] + " Label", LABS[1] + " Label", Arrays.asList(VISITS.get(1), NEW_VISITS.get(1))); diff --git a/study/test/src/org/labkey/test/tests/study/StudyReloadColumnInferenceTest.java b/study/test/src/org/labkey/test/tests/study/StudyReloadColumnInferenceTest.java index 108a9c37244..f727d87e1e5 100644 --- a/study/test/src/org/labkey/test/tests/study/StudyReloadColumnInferenceTest.java +++ b/study/test/src/org/labkey/test/tests/study/StudyReloadColumnInferenceTest.java @@ -306,13 +306,13 @@ private void verifyDataset(boolean isDataset, DataToVerify... datas) DataRegionTable datasetTable = isDataset ? gotoDataset(name) : gotoList(name); List columnLabels = datasetTable.getColumnLabels(); - Assert.assertTrue(name + " columns are not as expected", columnLabels.size() == data.getColumns().size()); + Assert.assertEquals(name + " columns are not as expected", columnLabels.size(), data.getColumns().size()); for (String expectedColumn : data.getColumns()) { Assert.assertTrue(name + " doesn't contain column " + expectedColumn, columnLabels.contains(expectedColumn)); } - Assert.assertTrue(name + " row count is not as expected: " + datasetTable.getDataRowCount(), data.getRowCount() == datasetTable.getDataRowCount()); + Assert.assertEquals(name + " row count is not as expected: " + datasetTable.getDataRowCount(), data.getRowCount(), datasetTable.getDataRowCount()); String columnToVerify = data.getColumnNameToVerify(); if (!StringUtils.isEmpty(columnToVerify) && data.getColumnValuesToVerify() != null) diff --git a/study/test/src/org/labkey/test/tests/study/StudyTest.java b/study/test/src/org/labkey/test/tests/study/StudyTest.java index 2a5c07180e2..198496ecd93 100644 --- a/study/test/src/org/labkey/test/tests/study/StudyTest.java +++ b/study/test/src/org/labkey/test/tests/study/StudyTest.java @@ -156,10 +156,10 @@ public void runApiTests() throws Exception RowsResponse saveResp = insertCmd.execute(cn, getProjectName() + "/" + getFolderName()); // Spot check return values for inserted values and user defined and built-in columns in response - assertEquals("Save rows return has incorrect value for: MouseId", "92104", saveResp.getRows().get(0).get("MouseId")); - assertEquals("Save rows return has incorrect value for: DEMraco", "first", saveResp.getRows().get(0).get("DEMraco")); - assertTrue("Save rows return is missing field: DEMasian", saveResp.getRows().get(0).keySet().contains("DEMasian")); - assertTrue("Save rows return is missing field: ModifiedBy", saveResp.getRows().get(0).keySet().contains("ModifiedBy")); + assertEquals("Save rows return has incorrect value for: MouseId", "92104", saveResp.getRows().getFirst().get("MouseId")); + assertEquals("Save rows return has incorrect value for: DEMraco", "first", saveResp.getRows().getFirst().get("DEMraco")); + assertTrue("Save rows return is missing field: DEMasian", saveResp.getRows().getFirst().keySet().contains("DEMasian")); + assertTrue("Save rows return is missing field: ModifiedBy", saveResp.getRows().getFirst().keySet().contains("ModifiedBy")); } catch (IOException | CommandException e) { @@ -178,10 +178,10 @@ public void runApiTests() throws Exception selectResp = selectCmd.execute(cn, "/" + getProjectName() + "/" + getFolderName()); // Spot check response values for inserted values and user defined and built-in columns - assertEquals("Select rows return has incorrect value for: MouseId", "92104", selectResp.getRows().get(0).get("MouseId")); - assertEquals("Select rows return has incorrect value for: DEMraco", "first", selectResp.getRows().get(0).get("DEMraco")); - assertTrue("Select rows return is missing field: DEMasian", selectResp.getRows().get(0).keySet().contains("DEMasian")); - assertTrue("Save rows return is missing field: ModifiedBy", selectResp.getRows().get(0).keySet().contains("ModifiedBy")); + assertEquals("Select rows return has incorrect value for: MouseId", "92104", selectResp.getRows().getFirst().get("MouseId")); + assertEquals("Select rows return has incorrect value for: DEMraco", "first", selectResp.getRows().getFirst().get("DEMraco")); + assertTrue("Select rows return is missing field: DEMasian", selectResp.getRows().getFirst().keySet().contains("DEMasian")); + assertTrue("Save rows return is missing field: ModifiedBy", selectResp.getRows().getFirst().keySet().contains("ModifiedBy")); } catch (IOException | CommandException e) { @@ -190,17 +190,17 @@ public void runApiTests() throws Exception log("Updating dataset row via API"); UpdateRowsCommand updateCmd = new UpdateRowsCommand("study", "DEM-1"); - updateCmd.addRow(Map.of("MouseId", "92104", "SequenceNum", 0, "DEMraco", "second", "lsid", selectResp.getRows().get(0).get("lsid"))); + updateCmd.addRow(Map.of("MouseId", "92104", "SequenceNum", 0, "DEMraco", "second", "lsid", selectResp.getRows().getFirst().get("lsid"))); try { RowsResponse updateResp = updateCmd.execute(cn, getProjectName() + "/" + getFolderName()); // Spot check response values for updated values and user defined and built-in columns - assertEquals("Save rows return has incorrect value for: MouseId", "92104", updateResp.getRows().get(0).get("MouseId")); - assertEquals("Save rows return has incorrect value for: DEMraco", "second", updateResp.getRows().get(0).get("DEMraco")); - assertTrue("Save rows return is missing field: DEMasian", updateResp.getRows().get(0).keySet().contains("DEMasian")); - assertTrue("Save rows return is missing field: ModifiedBy", updateResp.getRows().get(0).keySet().contains("ModifiedBy")); + assertEquals("Save rows return has incorrect value for: MouseId", "92104", updateResp.getRows().getFirst().get("MouseId")); + assertEquals("Save rows return has incorrect value for: DEMraco", "second", updateResp.getRows().getFirst().get("DEMraco")); + assertTrue("Save rows return is missing field: DEMasian", updateResp.getRows().getFirst().keySet().contains("DEMasian")); + assertTrue("Save rows return is missing field: ModifiedBy", updateResp.getRows().getFirst().keySet().contains("ModifiedBy")); } catch (IOException | CommandException e) { @@ -218,10 +218,10 @@ public void runApiTests() throws Exception selectResp = selectCmd.execute(cn, "/" + getProjectName() + "/" + getFolderName()); // Spot check response values for updated values and user defined and built-in columns - assertEquals("Select rows return has incorrect value for: MouseId", "92104", selectResp.getRows().get(0).get("MouseId")); - assertEquals("Select rows return has incorrect value for: DEMraco", "second", selectResp.getRows().get(0).get("DEMraco")); - assertTrue("Select rows return is missing field: DEMasian", selectResp.getRows().get(0).keySet().contains("DEMasian")); - assertTrue("Save rows return is missing field: ModifiedBy", selectResp.getRows().get(0).keySet().contains("ModifiedBy")); + assertEquals("Select rows return has incorrect value for: MouseId", "92104", selectResp.getRows().getFirst().get("MouseId")); + assertEquals("Select rows return has incorrect value for: DEMraco", "second", selectResp.getRows().getFirst().get("DEMraco")); + assertTrue("Select rows return is missing field: DEMasian", selectResp.getRows().getFirst().keySet().contains("DEMasian")); + assertTrue("Save rows return is missing field: ModifiedBy", selectResp.getRows().getFirst().keySet().contains("ModifiedBy")); } catch (IOException | CommandException e) { @@ -438,7 +438,7 @@ protected void manageSubjectClassificationTest() persistingLists.remove(allList); attemptCreateExpectError("1", "does not exist in this study.", "bad List "); - String id = pIDs.get(0); + String id = pIDs.getFirst(); attemptCreateExpectError(id + ", " + id, "Duplicates are not allowed in a group", "Bad List 2"); } @@ -794,7 +794,7 @@ protected void verifyStudyAndDatasets(boolean isVisitBased) clickAndWait(Locator.tagWithAttribute("a", "data-original-title","edit").index(0)); setFormElement(Locator.input("quf_TextField"), newText); clickButton("Submit"); - List updatedTextField = Arrays.asList(newText, textField.get(0)); + List updatedTextField = Arrays.asList(newText, textField.getFirst()); // Verify new state table = new DataRegionTable("Dataset", this); @@ -999,7 +999,7 @@ private void verifyAuditEventAdded(int previousCount) List> rows = selectResp.getRows(); assertEquals("Unexpected size of datasetAuditEvent log", previousCount + 1, rows.size()); log("Dataset audit log contents: " + rows); - assertEquals("A new dataset record was inserted", rows.get(rows.size() - 1).get("Comment")); + assertEquals("A new dataset record was inserted", rows.getLast().get("Comment")); } private SelectRowsResponse getDatasetAuditLog() diff --git a/study/test/src/org/labkey/test/tests/study/StudyVisitManagementTest.java b/study/test/src/org/labkey/test/tests/study/StudyVisitManagementTest.java index 8f62b78ab52..87f2e5d4506 100644 --- a/study/test/src/org/labkey/test/tests/study/StudyVisitManagementTest.java +++ b/study/test/src/org/labkey/test/tests/study/StudyVisitManagementTest.java @@ -45,6 +45,7 @@ import java.util.Map; import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; @Category({Daily.class, Study.class}) @@ -267,7 +268,7 @@ private void verifyStudyVisits(@NotNull List definedVisits, @Nullable Li if (undefinedVisits != null && !undefinedVisits.isEmpty()) { for (String visitSeqRangeStr : undefinedVisits) - assertTrue("Unexpected visit range found: " + visitSeqRangeStr, !manageVisitPage.hasVisitForSequenceRange(visitSeqRangeStr)); + assertFalse("Unexpected visit range found: " + visitSeqRangeStr, manageVisitPage.hasVisitForSequenceRange(visitSeqRangeStr)); } } diff --git a/study/test/src/org/labkey/test/tests/study/TruncationTest.java b/study/test/src/org/labkey/test/tests/study/TruncationTest.java index 917b8e32e83..504e45711f1 100644 --- a/study/test/src/org/labkey/test/tests/study/TruncationTest.java +++ b/study/test/src/org/labkey/test/tests/study/TruncationTest.java @@ -26,7 +26,6 @@ import org.labkey.test.categories.Specimen; import org.labkey.test.pages.DatasetPropertiesPage; import org.labkey.test.pages.ManageDatasetsPage; -import org.labkey.test.util.Ext4Helper; import java.io.File; import java.util.Arrays; diff --git a/survey/src/org/labkey/survey/SurveyController.java b/survey/src/org/labkey/survey/SurveyController.java index 3f78d0406ea..1fecfada92b 100644 --- a/survey/src/org/labkey/survey/SurveyController.java +++ b/survey/src/org/labkey/survey/SurveyController.java @@ -22,7 +22,6 @@ import org.apache.commons.beanutils.Converter; import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.math.NumberUtils; -import org.jetbrains.annotations.NotNull; import org.json.JSONObject; import org.labkey.api.action.ApiJsonForm; import org.labkey.api.action.ApiQueryResponse; @@ -525,14 +524,7 @@ public ApiResponse execute(SurveyResponseForm form, BindException errors) throws DbSchema dbschema = table.getSchema(); try (DbScope.Transaction transaction = dbschema.getScope().ensureTransaction()) { - TableViewForm tvf = new TableViewForm(table) - { - @Override - public String getFormFieldName(@NotNull ColumnInfo column) - { - return column.getName(); - } - }; + TableViewForm tvf = new TableViewForm(table); Survey survey = getSurvey(form); tvf.setViewContext(getViewContext()); @@ -566,7 +558,7 @@ public String getFormFieldName(@NotNull ColumnInfo column) List updateErrors = SurveyManager.get().fireBeforeUpdateSurveyResponses(getContainer(), getUser(), survey); if (!updateErrors.isEmpty()) { - Throwable first = updateErrors.get(0); + Throwable first = updateErrors.getFirst(); response.put("errorInfo", first.getMessage()); response.put("success", false); } @@ -680,7 +672,7 @@ protected Map doInsertUpdate(TableViewForm form, BindException e throw batchErrors; assert(updated.size() == 1); - row = updated.get(0); + row = updated.getFirst(); } else { @@ -695,7 +687,7 @@ protected Map doInsertUpdate(TableViewForm form, BindException e if (batchErrors.hasErrors()) throw batchErrors; assert(updated.size() == 1); - row = updated.get(0); + row = updated.getFirst(); } return row; } @@ -871,16 +863,11 @@ public ApiResponse execute(SurveyAttachmentForm form, BindException errors) thro { TableViewForm tvf = new TableViewForm(table) { - @Override - public String getFormFieldName(@NotNull ColumnInfo column) - { - return column.getName(); - } }; tvf.setViewContext(getViewContext()); - AttachmentFile af = files.get(0); + AttachmentFile af = files.getFirst(); tvf.setTypedValues(Collections.singletonMap(form.getQuestionName(), af), false); // add the survey answer row pk diff --git a/survey/src/org/labkey/survey/SurveyManager.java b/survey/src/org/labkey/survey/SurveyManager.java index 2d35c13b839..46db35d401f 100644 --- a/survey/src/org/labkey/survey/SurveyManager.java +++ b/survey/src/org/labkey/survey/SurveyManager.java @@ -252,7 +252,7 @@ public Survey saveSurvey(Container container, User user, Survey survey) if (!errors.isEmpty()) { - Throwable first = errors.get(0); + Throwable first = errors.getFirst(); if (first instanceof RuntimeException) throw (RuntimeException)first; else @@ -415,7 +415,7 @@ public void deleteSurvey(Container c, User user, int surveyId) if (!errors.isEmpty()) { - Throwable first = errors.get(0); + Throwable first = errors.getFirst(); if (first instanceof RuntimeException) throw (RuntimeException)first; else @@ -503,7 +503,7 @@ public static FieldKey getSurveyPk(TableInfo table) { List pks = table.getPkColumnNames(); if (pks.size() == 1) - return FieldKey.fromParts(pks.get(0)); + return FieldKey.fromParts(pks.getFirst()); else if (table.getColumn(FieldKey.fromParts("EntityId")) != null) return FieldKey.fromParts("EntityId"); else if (table.getColumn(FieldKey.fromParts("RowId")) != null) @@ -773,13 +773,13 @@ public void testGetMetaDataForColumn() } // check a few of the key properties - assertTrue("Unexpected property value", trimmedMap.get("name").equals("test")); - assertTrue("Unexpected property value", trimmedMap.get("caption").equals("Test")); - assertTrue("Unexpected property value", trimmedMap.get("shortCaption").equals("Test")); - assertTrue("Unexpected property value", trimmedMap.get("hidden").equals(false)); - assertTrue("Unexpected property value", trimmedMap.get("jsonType").equals("string")); - assertTrue("Unexpected property value", trimmedMap.get("inputType").equals("text")); - assertTrue("Unexpected property value", trimmedMap.get("required").equals(true)); + assertEquals("Unexpected property value", "test", trimmedMap.get("name")); + assertEquals("Unexpected property value", "Test", trimmedMap.get("caption")); + assertEquals("Unexpected property value", "Test", trimmedMap.get("shortCaption")); + assertEquals("Unexpected property value", false, trimmedMap.get("hidden")); + assertEquals("Unexpected property value", "string", trimmedMap.get("jsonType")); + assertEquals("Unexpected property value", "text", trimmedMap.get("inputType")); + assertEquals("Unexpected property value", true, trimmedMap.get("required")); } } } diff --git a/survey/src/org/labkey/survey/query/SurveyQuerySchema.java b/survey/src/org/labkey/survey/query/SurveyQuerySchema.java index 6f59f3c2e1c..d291ce7fd6e 100644 --- a/survey/src/org/labkey/survey/query/SurveyQuerySchema.java +++ b/survey/src/org/labkey/survey/query/SurveyQuerySchema.java @@ -15,6 +15,7 @@ */ package org.labkey.survey.query; +import org.jetbrains.annotations.NotNull; import org.labkey.api.data.Container; import org.labkey.api.data.ContainerFilter; import org.labkey.api.data.TableInfo; @@ -72,7 +73,7 @@ protected QuerySettings createQuerySettings(String dataRegionName, String queryN } @Override - public QueryView createView(ViewContext context, QuerySettings settings, BindException errors) + public @NotNull QueryView createView(ViewContext context, QuerySettings settings, BindException errors) { if (SURVEY_DESIGN_TABLE_NAME.equalsIgnoreCase(settings.getQueryName())) return new SurveyDesignQueryView(this, settings, errors); diff --git a/survey/src/org/labkey/survey/query/SurveysTable.java b/survey/src/org/labkey/survey/query/SurveysTable.java index 8e492136c5e..ba7a63383ab 100644 --- a/survey/src/org/labkey/survey/query/SurveysTable.java +++ b/survey/src/org/labkey/survey/query/SurveysTable.java @@ -203,7 +203,7 @@ protected Map deleteRow(User user, Container c, Map errors = SurveyManager.get().fireBeforeDeleteSurvey(c, user, survey); if (!errors.isEmpty()) - throw new QueryUpdateServiceException(errors.get(0).getMessage()); + throw new QueryUpdateServiceException(errors.getFirst().getMessage()); Map row = super.deleteRow(user, c, oldRowMap); diff --git a/visualization/src/org/labkey/visualization/VisualizationController.java b/visualization/src/org/labkey/visualization/VisualizationController.java index c55ec658702..22a566ce07e 100644 --- a/visualization/src/org/labkey/visualization/VisualizationController.java +++ b/visualization/src/org/labkey/visualization/VisualizationController.java @@ -23,10 +23,10 @@ import org.apache.commons.lang3.StringUtils; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; -import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.json.JSONArray; import org.json.JSONObject; +import org.jetbrains.annotations.NotNull; import org.junit.Assert; import org.junit.Test; import org.labkey.api.action.Action; @@ -499,7 +499,7 @@ public ApiResponse execute(Object o, BindException errors) public static class GetDataAction extends MutatingApiAction { @Override - protected ObjectReader getObjectReader(Class c) + protected ObjectReader getObjectReader(Class c) { ObjectReader r = super.getObjectReader(c); return r.without(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES); @@ -520,7 +520,7 @@ public ApiResponse execute(VisDataRequest form, BindException errors) throws Exc catch (SQLGenerationException e) { errors.reject(ERROR_MSG, e.getMessage()); - _log.warn("Unable to generate visualization SQL. " + e.getMessage()); + _log.warn("Unable to generate visualization SQL. {}", e.getMessage()); return null; } @@ -592,7 +592,7 @@ public void addNavTrail(NavTree root) public class cdsGetDataAction extends GetDataAction { @Override - protected ObjectReader getObjectReader(Class c) + protected ObjectReader getObjectReader(Class c) { ObjectReader r = super.getObjectReader(c); return r.without(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES); @@ -611,7 +611,7 @@ public ApiResponse execute(VisDataRequest form, BindException errors) throws Exc catch (SQLGenerationException e) { errors.reject(ERROR_MSG, e.getMessage()); - _log.warn("Unable to generate visualization SQL. " + e.getMessage()); + _log.warn("Unable to generate visualization SQL. {}", e.getMessage()); return null; } @@ -692,7 +692,7 @@ protected String getCommandClassMethodName() } @Override - public void validate(Object o, Errors errors) + public void validate(@NotNull Object o, @NotNull Errors errors) { return; //TODO: Validate XML } @@ -1698,7 +1698,7 @@ public void testJacksonBinding() throws Exception assertTrue(vs.isMetaDataOnly()); assertTrue(vs.isJoinToFirst()); assertEquals(1, vs.getMeasures().size()); - VisDataRequest.MeasureInfo mi = vs.getMeasures().get(0); + VisDataRequest.MeasureInfo mi = vs.getMeasures().getFirst(); { VisDataRequest.Measure m = mi.getMeasure(); assertNotNull(m); diff --git a/visualization/src/org/labkey/visualization/sql/VisualizationCDSGenerator.java b/visualization/src/org/labkey/visualization/sql/VisualizationCDSGenerator.java index e159afa4cd2..e92a4d8a116 100644 --- a/visualization/src/org/labkey/visualization/sql/VisualizationCDSGenerator.java +++ b/visualization/src/org/labkey/visualization/sql/VisualizationCDSGenerator.java @@ -310,7 +310,7 @@ else if (Strings.CI.equals(m.getName(), sequenceNumColumnName)) // Default to 'date' (same as Measure), but align ourselves with the measures if any are requested String timeType = "date"; if (!datasetMeasures.isEmpty()) - timeType = datasetMeasures.get(0).getTime(); + timeType = datasetMeasures.getFirst().getTime(); if (null == container) { @@ -351,7 +351,7 @@ else if (Strings.CI.equals(m.getName(), sequenceNumColumnName)) if (_log.isDebugEnabled()) { String sql = generator.getSQL(); - _log.debug("---------------------------------------\n" + datasetPath + "\n\n" + sql); + _log.debug("---------------------------------------\n{}\n\n{}", datasetPath, sql); } } @@ -469,7 +469,7 @@ else if (type != JdbcType.VARCHAR) if (_log.isDebugEnabled()) { - _log.debug("----------------------\nunion sql\n\n" + fullSQL + "\n\n"); + _log.debug("----------------------\nunion sql\n\n{}\n\n", fullSQL); var select = QueryService.get().getSelectBuilder(schema.getSchema("study"), fullSQL.toString()); try (ResultSet rs = select.select()) { diff --git a/visualization/src/org/labkey/visualization/sql/VisualizationSQLGenerator.java b/visualization/src/org/labkey/visualization/sql/VisualizationSQLGenerator.java index 73c022848b2..dd7d491082d 100644 --- a/visualization/src/org/labkey/visualization/sql/VisualizationSQLGenerator.java +++ b/visualization/src/org/labkey/visualization/sql/VisualizationSQLGenerator.java @@ -484,7 +484,6 @@ public String getSQL() throws SQLGenerationException private String wrapInGroupBy(IVisualizationSourceQuery joinQuery, List queries, String sql) - throws SQLGenerationException { Map> columnAliases = getColumnMapping(_columnFactory, queries); @@ -610,7 +609,7 @@ private String getSubselectSQL(IVisualizationSourceQuery parentQuery, Visualizat { if (query.getJoinTarget() == null) { - reorderedQueries.add(0, query); + reorderedQueries.addFirst(query); } else { @@ -1006,12 +1005,7 @@ public Map getColumnMapping() private static void addToColMap(Map> colMap, String name, Set newAliases) { - Set aliases = colMap.get(name); - if (aliases == null) - { - aliases = new LinkedHashSet<>(); - colMap.put(name, aliases); - } + Set aliases = colMap.computeIfAbsent(name, _ -> new LinkedHashSet<>()); aliases.addAll(newAliases); } @@ -1258,7 +1252,7 @@ public void testOneTableWithGrouping() throws Exception try (ResultsImpl r = (ResultsImpl)getResults(q)) { // this is a surprise! we're implicitly grouping by participant,visit as well as gender - assertTrue(48 == r.getSize()); // Female, female, Male, male, null + assertEquals(48, r.getSize()); // Female, female, Male, male, null assertEquals(8, r.getMetaData().getColumnCount()); // gender, count(*), avg(), stddev(), stderr() } @@ -1315,7 +1309,7 @@ public void testTwoTablesDemStudy() throws Exception q.addMeasure(ptid).addMeasure(condition); try (ResultsImpl r = (ResultsImpl)getResults(q)) { - assertTrue(48 == r.getSize()); + assertEquals(48, r.getSize()); assertEquals(4, r.getMetaData().getColumnCount()); } diff --git a/visualization/src/org/labkey/visualization/sql/VisualizationSourceQuery.java b/visualization/src/org/labkey/visualization/sql/VisualizationSourceQuery.java index 026663f1ac0..34f34ea15f6 100644 --- a/visualization/src/org/labkey/visualization/sql/VisualizationSourceQuery.java +++ b/visualization/src/org/labkey/visualization/sql/VisualizationSourceQuery.java @@ -28,7 +28,6 @@ import org.labkey.api.util.Pair; import org.labkey.api.view.NotFoundException; import org.labkey.api.visualization.IVisualizationSourceQuery; -import org.labkey.api.visualization.SQLGenerationException; import org.labkey.api.visualization.VisualizationAggregateColumn; import org.labkey.api.visualization.VisualizationSourceColumn; @@ -590,7 +589,7 @@ public String getWhereClause() } @Override - public String getSQL(VisualizationSourceColumn.Factory factory) throws SQLGenerationException + public String getSQL(VisualizationSourceColumn.Factory factory) { return getSelectClause(factory) + "\n" + getFromClause() + "\n" + diff --git a/wiki/src/org/labkey/wiki/DiffMatchPatch.java b/wiki/src/org/labkey/wiki/DiffMatchPatch.java index 816d27b677a..ebd10b533d7 100644 --- a/wiki/src/org/labkey/wiki/DiffMatchPatch.java +++ b/wiki/src/org/labkey/wiki/DiffMatchPatch.java @@ -223,7 +223,7 @@ protected LinkedList diff_compute(String text1, String text2, ArrayList linearray = null; if (checklines) { // Scan the text on a line-by-line basis first. - Object b[] = diff_linesToChars(text1, text2); + Object[] b = diff_linesToChars(text1, text2); text1 = (String) b[0]; text2 = (String) b[1]; // The following Java warning is harmless. @@ -1580,13 +1580,10 @@ protected int match_bitap(String text, String pattern, int loc) { for (int j = finish - 1; j >= start; j--) { if (d == 0) { // First pass: exact match. - rd[j] = ((rd[j + 1] << 1) | 1) & (s.containsKey(text.charAt(j)) - ? s.get(text.charAt(j)) - : 0); + rd[j] = ((rd[j + 1] << 1) | 1) & (s.getOrDefault(text.charAt(j), 0)); } else { // Subsequent passes: fuzzy match. - rd[j] = ((rd[j + 1] << 1) | 1) & (s.containsKey(text.charAt(j)) - ? s.get(text.charAt(j)) : 0) | ((last_rd[j + 1] << 1) | 1) + rd[j] = ((rd[j + 1] << 1) | 1) & (s.getOrDefault(text.charAt(j), 0)) | ((last_rd[j + 1] << 1) | 1) | ((last_rd[j] << 1) | 1) | last_rd[j + 1]; } if ((rd[j] & matchmask) != 0) { diff --git a/wiki/src/org/labkey/wiki/WikiController.java b/wiki/src/org/labkey/wiki/WikiController.java index 603ffb045d0..771890a6013 100644 --- a/wiki/src/org/labkey/wiki/WikiController.java +++ b/wiki/src/org/labkey/wiki/WikiController.java @@ -196,7 +196,7 @@ public void prepareWebPart(Portal.WebPart webPart) throws ServletException //get all containers that include wiki pages _containerList = populateWikiContainerList(context); if (!_containerList.contains(context.getContainer())) - _containerList.add(0, context.getContainer()); + _containerList.addFirst(context.getContainer()); //get wiki page list for the currently stored container (or current container if null) Container cStored; @@ -348,7 +348,7 @@ public static Wiki getDefaultPage(Container c) } else { - String firstName = WikiSelectManager.getPageNames(c).iterator().next(); + String firstName = WikiSelectManager.getPageNames(c).getFirst(); wiki = WikiSelectManager.getWiki(c, firstName); } } @@ -2300,7 +2300,7 @@ protected ApiResponse insertWiki(SaveWikiForm form) throws Exception throw new UnauthorizedException("You do not have permissions to create a new wiki page in this folder!"); String wikiname = form.getName(); - LOG.debug("Inserting wiki " + wikiname); + LOG.debug("Inserting wiki {}", wikiname); Container c = getContainer(); Wiki wiki = new Wiki(c, wikiname); @@ -2377,9 +2377,9 @@ private ApiResponse updateWiki(SaveWikiForm form) // issue 12960: if the wiki was updated by a different user, don't allow the save if (!wikiUpdate.getPageVersionId().equals(form.getPageVersionId())) - throw new NotFoundException("This wiki version has already been updated by a different user."); + throw new NotFoundException("This wiki version has already been updated by a different user."); - LOG.debug("Updating wiki " + wikiUpdate.getName()); + LOG.debug("Updating wiki {}", wikiUpdate.getName()); if (!getPermissions().allowUpdate(wikiUpdate)) throw new UnauthorizedException("You are not allowed to edit this wiki page."); diff --git a/wiki/src/org/labkey/wiki/WikiManager.java b/wiki/src/org/labkey/wiki/WikiManager.java index c487e0e1259..0b50287a105 100644 --- a/wiki/src/org/labkey/wiki/WikiManager.java +++ b/wiki/src/org/labkey/wiki/WikiManager.java @@ -169,7 +169,7 @@ public void insertWiki(User user, Container c, Wiki wikiInsert, WikiVersion wiki { wikiInsert.beforeInsert(user, c.getId()); wikiInsert.setPageVersionId(null); - LOG.debug("Table.insert() for wiki " + wikiInsert.getName()); + LOG.debug("Table.insert() for wiki {}", wikiInsert.getName()); Table.insert(user, comm.getTableInfoPages(), wikiInsert); String entityId = wikiInsert.getEntityId(); @@ -181,7 +181,7 @@ public void insertWiki(User user, Container c, Wiki wikiInsert, WikiVersion wiki wikiversion.setCreatedBy(wikiInsert.getCreatedBy()); } wikiversion.setVersion(1); - LOG.debug("Table.insert() for wiki version " + wikiInsert.getName()); + LOG.debug("Table.insert() for wiki version {}", wikiInsert.getName()); //if copying wiki with history, avoid overwriting 'created by' user User userToInsert = (copyHistory) ? null : user; @@ -207,7 +207,7 @@ public void insertWiki(User user, Container c, Wiki wikiInsert, WikiVersion wiki { WikiCache.uncache(c, wikiInsert, true); - LOG.debug("indexWiki() for " + wikiInsert.getName()); + LOG.debug("indexWiki() for {}", wikiInsert.getName()); indexWiki(wikiInsert); } @@ -344,7 +344,7 @@ public void addAliases(Wiki wiki, @NotNull Collection aliases, @Nullable if (null != errors) errors.rejectValue("name", ERROR_MSG, "Warning: Alias '" + alias + "' already exists in this folder."); else - LOG.warn("Attempt to add alias to wiki \"" + wiki.getName() + "\" failed; \"" + alias + "\" already exists in this folder."); + LOG.warn("Attempt to add alias to wiki \"{}\" failed; \"{}\" already exists in this folder.", wiki.getName(), alias); } }); } @@ -714,7 +714,7 @@ public void indexWikis(SearchService.TaskIndexingQueue queue, @Nullable Date mod private void indexWikiContainerFast(SearchService.TaskIndexingQueue queue, @Nullable Date modifiedSince, @Nullable String wikiName) { - LOG.debug("indexWikiContainerFast(" + wikiName + ")"); + LOG.debug("indexWikiContainerFast({})", wikiName); Container c = queue.getContainer(); SQLFragment f = new SQLFragment(); f.append("SELECT P.entityid, P.container, P.name, P.owner, P.createdby, P.created, P.modifiedby, P.modified, P.shouldindex,") @@ -750,14 +750,14 @@ private void indexWikiContainerFast(SearchService.TaskIndexingQueue queue, @Null if (!rs.getBoolean("shouldindex")) { - LOG.debug(String.format("Wiki [%1$s] set to not index, skipping.", wikiName)); + LOG.debug("Wiki [{}] set to not index, skipping.", wikiName); continue; } String entityId = rs.getString("entityid"); assert null != entityId; - LOG.debug("Indexing wiki " + wikiName + ":" + entityId); + LOG.debug("Indexing wiki {}:{}", wikiName, entityId); String wikiTitle = rs.getString("title"); String keywords; @@ -782,7 +782,7 @@ private void indexWikiContainerFast(SearchService.TaskIndexingQueue queue, @Null catch (Throwable t) { // Log rendering exception and details about the culprit, but continue indexing wikis in this container - LOG.error("Could not render wiki \"" + wikiName + "\" in folder \"" + c.getPath() + "\""); + LOG.error("Could not render wiki \"{}\" in folder \"{}\"", wikiName, c.getPath()); ExceptionUtil.logExceptionToMothership(null, t); continue; } diff --git a/wiki/src/org/labkey/wiki/WikiModule.java b/wiki/src/org/labkey/wiki/WikiModule.java index b02c6974d1d..995aaafa127 100644 --- a/wiki/src/org/labkey/wiki/WikiModule.java +++ b/wiki/src/org/labkey/wiki/WikiModule.java @@ -189,7 +189,7 @@ private void loadWikiContent(@Nullable Container c, User user, String name, Stri } catch (IOException e) { - _log.error("Failed to insert wiki in " + c.getPath() + " from " + resource, e); + _log.error("Failed to insert wiki in {} from {}", c.getPath(), resource, e); } } } diff --git a/wiki/src/org/labkey/wiki/WikiWebdavProvider.java b/wiki/src/org/labkey/wiki/WikiWebdavProvider.java index c8209b9190b..1492704616b 100644 --- a/wiki/src/org/labkey/wiki/WikiWebdavProvider.java +++ b/wiki/src/org/labkey/wiki/WikiWebdavProvider.java @@ -59,7 +59,6 @@ import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; -import java.io.File; import java.io.IOException; import java.io.InputStream; import java.lang.ref.WeakReference; @@ -180,12 +179,6 @@ public boolean canDelete(User user, boolean forDelete, List message) { return false; } - - @Override - public boolean isFile() - { - return false; - } @Override public long getCreated() @@ -193,12 +186,6 @@ public long getCreated() return Long.MIN_VALUE; } - @Override - public long getLastModified() - { - return Long.MIN_VALUE; - } - @Override public String getExecuteHref(ViewContext context) { @@ -384,13 +371,6 @@ public long getCreated() { return Long.MIN_VALUE; } - - @Override - public long getLastModified() - { - return Long.MIN_VALUE; - } - @Override public String getExecuteHref(ViewContext context) { @@ -513,12 +493,6 @@ public boolean exists() } - @Override - public boolean isCollection() - { - return false; - } - @Override public User getCreatedBy() { @@ -724,10 +698,5 @@ public Set> getPermissions(User user) return perms; } - @Override - public File getFile() - { - return null; - } } } diff --git a/wiki/src/org/labkey/wiki/export/WikiImporterFactory.java b/wiki/src/org/labkey/wiki/export/WikiImporterFactory.java index 9b436fc0148..06ebd99c113 100644 --- a/wiki/src/org/labkey/wiki/export/WikiImporterFactory.java +++ b/wiki/src/org/labkey/wiki/export/WikiImporterFactory.java @@ -89,7 +89,7 @@ public void process(PipelineJob job, FolderImportContext ctx, VirtualFile root) if (null != job) job.setStatus("IMPORT " + getDescription()); - ctx.getLogger().info("Loading " + getDescription()); + ctx.getLogger().info("Loading {}", getDescription()); Set importedFolderNames = new CaseInsensitiveHashSet(); Map parentsToBeSet = new HashMap<>(); @@ -110,7 +110,7 @@ public void process(PipelineJob job, FolderImportContext ctx, VirtualFile root) VirtualFile wikiSubDir = wikisDir.getDir(wikiXml.getName()); if (null == wikiSubDir) { - ctx.getLogger().error("Could not find content subdirectory for wiki with name \"" + wikiXml.getName() + "\""); + ctx.getLogger().error("Could not find content subdirectory for wiki with name \"{}\"", wikiXml.getName()); continue; } // ensure that older versions of exported wikis that do not have the shouldIndex bit set @@ -141,8 +141,8 @@ public void process(PipelineJob job, FolderImportContext ctx, VirtualFile root) setParents(ctx, parentsToBeSet); - ctx.getLogger().info(importedFolderNames.size() + " wiki" + (1 == importedFolderNames.size() ? "" : "s") + " imported"); - ctx.getLogger().info("Done importing " + getDescription()); + ctx.getLogger().info("{} wiki{} imported", importedFolderNames.size(), 1 == importedFolderNames.size() ? "" : "s"); + ctx.getLogger().info("Done importing {}", getDescription()); } } } @@ -156,7 +156,7 @@ private void setParents(FolderImportContext ctx, Map parentsToBeSe Wiki parentWiki = WikiSelectManager.getWiki(ctx.getContainer(), entry.getValue()); if (parentWiki == null) { - ctx.getLogger().warn("Could not find parent wiki: " + entry.getValue()); + ctx.getLogger().warn("Could not find parent wiki: {}", entry.getValue()); } else { diff --git a/wiki/src/org/labkey/wiki/model/WikiVersion.java b/wiki/src/org/labkey/wiki/model/WikiVersion.java index 78994bfe4eb..1917067b435 100644 --- a/wiki/src/org/labkey/wiki/model/WikiVersion.java +++ b/wiki/src/org/labkey/wiki/model/WikiVersion.java @@ -16,7 +16,6 @@ package org.labkey.wiki.model; -import org.apache.commons.lang3.Strings; import org.jetbrains.annotations.Nullable; import org.labkey.api.attachments.Attachment; import org.labkey.api.data.Container;
b
<%=formatErrorsForPath("form.c")%>
c
c
int
int
Positive Number
Positive Number
Required String
Text
x
y
z
Required String
Text
x
y
z