From 063a7143706186f707a1ed832a3fb51b1c1550ae Mon Sep 17 00:00:00 2001 From: Shinsuke Sugaya Date: Sat, 12 Oct 2024 06:11:58 +0900 Subject: [PATCH] fix #2848 Refactor code: Replace redundant conditions and enhance readability across several classes. --- src/main/java/org/codelibs/fess/FessBoot.java | 4 +- .../fess/api/json/SearchApiManager.java | 24 ++-- .../web/admin/backup/AdminBackupAction.java | 14 +-- .../web/admin/design/AdminDesignAction.java | 9 +- .../maintenance/AdminMaintenanceAction.java | 4 +- .../admin/scheduler/AdminSchedulerAction.java | 12 +- .../web/admin/upgrade/AdminUpgradeAction.java | 109 ++++++++++++------ .../codelibs/fess/app/web/api/ApiResult.java | 2 +- .../admin/backup/ApiAdminBackupAction.java | 14 +-- .../web/api/admin/searchlist/SearchBody.java | 2 +- .../base/login/OpenIdConnectCredential.java | 7 +- .../AbstractFessFileTransformer.java | 6 +- .../crawler/transformer/FessTransformer.java | 8 +- .../transformer/FessXpathTransformer.java | 6 +- .../fess/crawler/util/FieldConfigs.java | 10 +- .../codelibs/fess/dict/DictionaryFile.java | 2 +- .../fess/dict/kuromoji/KuromojiFile.java | 2 +- .../fess/dict/kuromoji/KuromojiItem.java | 2 +- .../fess/dict/mapping/CharMappingFile.java | 2 +- .../fess/dict/mapping/CharMappingItem.java | 2 +- .../fess/dict/protwords/ProtwordsFile.java | 2 +- .../fess/dict/protwords/ProtwordsItem.java | 2 +- .../stemmeroverride/StemmerOverrideFile.java | 2 +- .../stemmeroverride/StemmerOverrideItem.java | 4 +- .../fess/dict/stopwords/StopwordsFile.java | 2 +- .../fess/dict/stopwords/StopwordsItem.java | 2 +- .../fess/dict/synonym/SynonymFile.java | 2 +- .../fess/dict/synonym/SynonymItem.java | 2 +- .../codelibs/fess/entity/HighlightInfo.java | 8 +- .../codelibs/fess/entity/QueryContext.java | 4 +- .../fess/es/client/SearchEngineClient.java | 77 ++++++------- .../fess/es/config/exentity/DataConfig.java | 17 ++- .../es/config/exentity/WebAuthentication.java | 14 ++- .../fess/es/config/exentity/WebConfig.java | 11 +- .../fess/es/query/StoredLtrQueryBuilder.java | 4 +- .../ContainerNotAvailableException.java | 2 +- .../java/org/codelibs/fess/exec/Crawler.java | 3 +- .../fess/helper/CrawlerLogHelper.java | 4 +- .../codelibs/fess/helper/IndexingHelper.java | 4 +- .../fess/helper/IntervalControlHelper.java | 4 +- .../codelibs/fess/helper/LabelTypeHelper.java | 4 +- .../codelibs/fess/helper/ProcessHelper.java | 2 +- .../codelibs/fess/helper/SearchHelper.java | 4 +- .../codelibs/fess/helper/SuggestHelper.java | 4 +- .../org/codelibs/fess/helper/ViewHelper.java | 5 +- .../fess/helper/WebFsIndexHelper.java | 3 +- .../fess/indexer/DocBoostMatcher.java | 4 +- .../codelibs/fess/indexer/IndexUpdater.java | 4 +- .../java/org/codelibs/fess/job/ExecJob.java | 4 +- .../fess/job/GenerateThumbnailJob.java | 2 +- .../fess/mylasta/direction/FessConfig.java | 8 +- .../fess/mylasta/direction/FessProp.java | 21 ++-- .../sponsor/FessMultipartRequestHandler.java | 6 +- .../fess/query/DefaultQueryBuilder.java | 2 +- .../org/codelibs/fess/query/QueryCommand.java | 2 +- .../codelibs/fess/query/TermQueryCommand.java | 15 +-- .../fess/query/TermRangeQueryCommand.java | 4 +- .../fess/query/parser/QueryParser.java | 15 +-- .../fess/rank/fusion/RankFusionProcessor.java | 4 +- .../org/codelibs/fess/score/ScoreBooster.java | 4 +- .../sso/oic/OpenIdConnectAuthenticator.java | 74 ++++++------ .../fess/sso/spnego/SpnegoAuthenticator.java | 40 +++---- .../fess/thumbnail/ThumbnailManager.java | 8 +- .../fess/thumbnail/impl/CommandGenerator.java | 4 +- .../codelibs/fess/timer/MonitorTarget.java | 4 +- .../org/codelibs/fess/util/PrunedTag.java | 6 +- .../codelibs/fess/util/QueryResponseList.java | 2 +- .../codelibs/fess/util/RenderDataUtil.java | 2 +- .../org/codelibs/fess/util/ResourceUtil.java | 2 +- .../oic/OpenIdConnectAuthenticatorTest.java | 13 ++- 70 files changed, 368 insertions(+), 315 deletions(-) diff --git a/src/main/java/org/codelibs/fess/FessBoot.java b/src/main/java/org/codelibs/fess/FessBoot.java index 5dfdc3030..767c44453 100644 --- a/src/main/java/org/codelibs/fess/FessBoot.java +++ b/src/main/java/org/codelibs/fess/FessBoot.java @@ -181,8 +181,8 @@ public void setupServerConfigIfNeeds(final BootLogger logger, final Tomcat serve }); doSetupServerConfig(logger, props, "sameSiteCookies", value -> { for (final Container container : server.getHost().findChildren()) { - if ((container instanceof final Context context) - && (context.getCookieProcessor() instanceof final CookieProcessorBase cookieProcessor)) { + if (container instanceof final Context context + && context.getCookieProcessor() instanceof final CookieProcessorBase cookieProcessor) { cookieProcessor.setSameSiteCookies(value); } } diff --git a/src/main/java/org/codelibs/fess/api/json/SearchApiManager.java b/src/main/java/org/codelibs/fess/api/json/SearchApiManager.java index 56de84d98..64a9f26bb 100644 --- a/src/main/java/org/codelibs/fess/api/json/SearchApiManager.java +++ b/src/main/java/org/codelibs/fess/api/json/SearchApiManager.java @@ -120,7 +120,8 @@ protected FormatType detectFormatType(final HttpServletRequest request) { return FormatType.SEARCH; } final String type = value.toLowerCase(Locale.ROOT); - if ("documents".equals(type)) { + switch (type) { + case "documents": if (values.length > 5 && "favorite".equals(values[5])) { request.setAttribute(DOC_ID_FIELD, values[4]); return FormatType.FAVORITE; @@ -129,21 +130,18 @@ protected FormatType detectFormatType(final HttpServletRequest request) { return FormatType.SCROLL; } return FormatType.SEARCH; - } - if ("labels".equals(type)) { + case "labels": return FormatType.LABEL; - } - if ("popular-words".equals(type)) { + case "popular-words": return FormatType.POPULARWORD; - } - if ("favorites".equals(type)) { + case "favorites": return FormatType.FAVORITES; - } - if ("health".equals(type)) { + case "health": return FormatType.PING; - } - if ("suggest-words".equals(type)) { + case "suggest-words": return FormatType.SUGGEST; + default: + break; } // default return FormatType.OTHER; @@ -1247,8 +1245,8 @@ protected String escapeJson(final Object obj) { buf.append(escapeJson(entry.getKey())).append(':').append(escapeJson(entry.getValue())); } buf.append('}'); - } else if ((obj instanceof Integer) || (obj instanceof Long) || (obj instanceof Float) || (obj instanceof Double)) { - buf.append((obj)); + } else if (obj instanceof Integer || obj instanceof Long || obj instanceof Float || obj instanceof Double) { + buf.append(obj); } else if (obj instanceof Boolean) { buf.append(obj.toString()); } else if (obj instanceof Date) { diff --git a/src/main/java/org/codelibs/fess/app/web/admin/backup/AdminBackupAction.java b/src/main/java/org/codelibs/fess/app/web/admin/backup/AdminBackupAction.java index 6714c01da..8491b4c5d 100644 --- a/src/main/java/org/codelibs/fess/app/web/admin/backup/AdminBackupAction.java +++ b/src/main/java/org/codelibs/fess/app/web/admin/backup/AdminBackupAction.java @@ -319,17 +319,17 @@ public ActionResponse download(final String id) { } if (id.endsWith(NDJSON_EXTENTION)) { final String name = id.substring(0, id.length() - NDJSON_EXTENTION.length()); - if ("search_log".equals(name)) { + switch (name) { + case "search_log": return writeNdjsonResponse(id, getSearchLogNdjsonWriteCall()); - } - if ("user_info".equals(name)) { + case "user_info": return writeNdjsonResponse(id, getUserInfoNdjsonWriteCall()); - } - if ("click_log".equals(name)) { + case "click_log": return writeNdjsonResponse(id, getClickLogNdjsonWriteCall()); - } - if ("favorite_log".equals(name)) { + case "favorite_log": return writeNdjsonResponse(id, getFavoriteLogNdjsonWriteCall()); + default: + break; } } else if ("fess.json".equals(id)) { return asStream(id).contentTypeOctetStream().stream(out -> { diff --git a/src/main/java/org/codelibs/fess/app/web/admin/design/AdminDesignAction.java b/src/main/java/org/codelibs/fess/app/web/admin/design/AdminDesignAction.java index 2a6e17195..ee9a9a6a5 100644 --- a/src/main/java/org/codelibs/fess/app/web/admin/design/AdminDesignAction.java +++ b/src/main/java/org/codelibs/fess/app/web/admin/design/AdminDesignAction.java @@ -22,7 +22,6 @@ import java.util.ArrayList; import java.util.List; import java.util.Locale; -import java.util.regex.Pattern; import org.apache.commons.io.FileUtils; import org.apache.logging.log4j.LogManager; @@ -359,12 +358,12 @@ private HtmlResponse asEditHtml(final EditForm form) { public static String decodeJsp(final String value) { return value.replaceAll("<%(?![@-])([\\s\\S]*?)%>", "<%$1%>").replaceAll("<%=([\\s\\S]*?)%>", "<%=$1%>") - .replaceAll(TRY_STATEMENT, "<% try{ %>") - .replaceAll(CACHE_AND_SESSION_INVALIDATE_STATEMENT, "<% }catch(Exception e){session.invalidate();} %>"); + .replace(TRY_STATEMENT, "<% try{ %>") + .replace(CACHE_AND_SESSION_INVALIDATE_STATEMENT, "<% }catch(Exception e){session.invalidate();} %>"); } public static String encodeJsp(final String value) { - return value.replaceAll(Pattern.quote("<% try{ %>"), TRY_STATEMENT) - .replaceAll(Pattern.quote("<% }catch(Exception e){session.invalidate();} %>"), CACHE_AND_SESSION_INVALIDATE_STATEMENT); + return value.replace("<% try{ %>", TRY_STATEMENT).replace("<% }catch(Exception e){session.invalidate();} %>", + CACHE_AND_SESSION_INVALIDATE_STATEMENT); } } diff --git a/src/main/java/org/codelibs/fess/app/web/admin/maintenance/AdminMaintenanceAction.java b/src/main/java/org/codelibs/fess/app/web/admin/maintenance/AdminMaintenanceAction.java index 0223edb73..73725f1b7 100644 --- a/src/main/java/org/codelibs/fess/app/web/admin/maintenance/AdminMaintenanceAction.java +++ b/src/main/java/org/codelibs/fess/app/web/admin/maintenance/AdminMaintenanceAction.java @@ -304,8 +304,8 @@ protected boolean startReindex(final boolean replaceAliases, final boolean reset if (searchEngineClient.createIndex(docIndex, toIndex, numberOfShards, autoExpandReplicas, resetDictionaries)) { searchEngineClient.admin().cluster().prepareHealth(toIndex).setWaitForYellowStatus().execute(ActionListener.wrap(response -> { searchEngineClient.addMapping(docIndex, "doc", toIndex); - if (searchEngineClient.copyDocIndex(fromIndex, toIndex, replaceAliases) - && (replaceAliases && !searchEngineClient.updateAlias(toIndex))) { + if (searchEngineClient.copyDocIndex(fromIndex, toIndex, replaceAliases) && replaceAliases + && !searchEngineClient.updateAlias(toIndex)) { logger.warn("Failed to update aliases for {} and {}", fromIndex, toIndex); } }, e -> logger.warn("Failed to reindex from {} to {}", fromIndex, toIndex, e))); diff --git a/src/main/java/org/codelibs/fess/app/web/admin/scheduler/AdminSchedulerAction.java b/src/main/java/org/codelibs/fess/app/web/admin/scheduler/AdminSchedulerAction.java index 8db4569f4..3c3b48125 100644 --- a/src/main/java/org/codelibs/fess/app/web/admin/scheduler/AdminSchedulerAction.java +++ b/src/main/java/org/codelibs/fess/app/web/admin/scheduler/AdminSchedulerAction.java @@ -144,12 +144,18 @@ public HtmlResponse createnewjob(final String type, final String id, final Strin final String decodedName = new String(Base64.getUrlDecoder().decode(name), Constants.CHARSET_UTF_8); scheduledJobForm.name = MessageFormat.format(fessConfig.getJobTemplateTitle(type), decodedName); final String[] ids = { "", "", "" }; - if (Constants.WEB_CRAWLER_TYPE.equals(type)) { + switch (type) { + case Constants.WEB_CRAWLER_TYPE: ids[0] = "\"" + id + "\""; - } else if (Constants.FILE_CRAWLER_TYPE.equals(type)) { + break; + case Constants.FILE_CRAWLER_TYPE: ids[1] = "\"" + id + "\""; - } else if (Constants.DATA_CRAWLER_TYPE.equals(type)) { + break; + case Constants.DATA_CRAWLER_TYPE: ids[2] = "\"" + id + "\""; + break; + default: + break; } scheduledJobForm.scriptData = MessageFormat.format(fessConfig.getJobTemplateScript(), ids[0], ids[1], ids[2], id.replace('-', '_')); diff --git a/src/main/java/org/codelibs/fess/app/web/admin/upgrade/AdminUpgradeAction.java b/src/main/java/org/codelibs/fess/app/web/admin/upgrade/AdminUpgradeAction.java index 0d1a51ee8..ade87ad7e 100644 --- a/src/main/java/org/codelibs/fess/app/web/admin/upgrade/AdminUpgradeAction.java +++ b/src/main/java/org/codelibs/fess/app/web/admin/upgrade/AdminUpgradeAction.java @@ -191,7 +191,8 @@ public HtmlResponse upgradeFrom(final UpgradeForm form) { validate(form, messages -> {}, this::asIndexHtml); verifyToken(this::asIndexHtml); - if (VERSION_13_0.equals(form.targetVersion)) { + switch (form.targetVersion) { + case VERSION_13_0: try { upgradeFrom13_0(); upgradeFrom13_1(); @@ -236,7 +237,8 @@ public HtmlResponse upgradeFrom(final UpgradeForm form) { logger.warn("Failed to upgrade data.", e); saveError(messages -> messages.addErrorsFailedToUpgradeFrom(GLOBAL, VERSION_13_0, e.getLocalizedMessage())); } - } else if (VERSION_13_1.equals(form.targetVersion)) { + break; + case VERSION_13_1: try { upgradeFrom13_1(); upgradeFrom13_2(); @@ -281,7 +283,8 @@ public HtmlResponse upgradeFrom(final UpgradeForm form) { logger.warn("Failed to upgrade data.", e); saveError(messages -> messages.addErrorsFailedToUpgradeFrom(GLOBAL, VERSION_13_1, e.getLocalizedMessage())); } - } else if (VERSION_13_2.equals(form.targetVersion)) { + break; + case VERSION_13_2: try { upgradeFrom13_2(); upgradeFrom13_3(); @@ -325,7 +328,8 @@ public HtmlResponse upgradeFrom(final UpgradeForm form) { logger.warn("Failed to upgrade data.", e); saveError(messages -> messages.addErrorsFailedToUpgradeFrom(GLOBAL, VERSION_13_2, e.getLocalizedMessage())); } - } else if (VERSION_13_3.equals(form.targetVersion)) { + break; + case VERSION_13_3: try { upgradeFrom13_3(); upgradeFrom13_4(); @@ -368,7 +372,8 @@ public HtmlResponse upgradeFrom(final UpgradeForm form) { logger.warn("Failed to upgrade data.", e); saveError(messages -> messages.addErrorsFailedToUpgradeFrom(GLOBAL, VERSION_13_3, e.getLocalizedMessage())); } - } else if (VERSION_13_4.equals(form.targetVersion)) { + break; + case VERSION_13_4: try { upgradeFrom13_4(); upgradeFrom13_5(); @@ -410,7 +415,8 @@ public HtmlResponse upgradeFrom(final UpgradeForm form) { logger.warn("Failed to upgrade data.", e); saveError(messages -> messages.addErrorsFailedToUpgradeFrom(GLOBAL, VERSION_13_4, e.getLocalizedMessage())); } - } else if (VERSION_13_5.equals(form.targetVersion)) { + break; + case VERSION_13_5: try { upgradeFrom13_5(); upgradeFrom13_6(); @@ -451,7 +457,8 @@ public HtmlResponse upgradeFrom(final UpgradeForm form) { logger.warn("Failed to upgrade data.", e); saveError(messages -> messages.addErrorsFailedToUpgradeFrom(GLOBAL, VERSION_13_5, e.getLocalizedMessage())); } - } else if (VERSION_13_6.equals(form.targetVersion)) { + break; + case VERSION_13_6: try { upgradeFrom13_6(); upgradeFrom13_7(); @@ -491,7 +498,8 @@ public HtmlResponse upgradeFrom(final UpgradeForm form) { logger.warn("Failed to upgrade data.", e); saveError(messages -> messages.addErrorsFailedToUpgradeFrom(GLOBAL, VERSION_13_6, e.getLocalizedMessage())); } - } else if (VERSION_13_7.equals(form.targetVersion)) { + break; + case VERSION_13_7: try { upgradeFrom13_7(); upgradeFrom13_8(); @@ -530,7 +538,8 @@ public HtmlResponse upgradeFrom(final UpgradeForm form) { logger.warn("Failed to upgrade data.", e); saveError(messages -> messages.addErrorsFailedToUpgradeFrom(GLOBAL, VERSION_13_7, e.getLocalizedMessage())); } - } else if (VERSION_13_8.equals(form.targetVersion)) { + break; + case VERSION_13_8: try { upgradeFrom13_8(); upgradeFrom13_9(); @@ -568,7 +577,8 @@ public HtmlResponse upgradeFrom(final UpgradeForm form) { logger.warn("Failed to upgrade data.", e); saveError(messages -> messages.addErrorsFailedToUpgradeFrom(GLOBAL, VERSION_13_8, e.getLocalizedMessage())); } - } else if (VERSION_13_9.equals(form.targetVersion)) { + break; + case VERSION_13_9: try { upgradeFrom13_9(); upgradeFrom13_10(); @@ -605,7 +615,8 @@ public HtmlResponse upgradeFrom(final UpgradeForm form) { logger.warn("Failed to upgrade data.", e); saveError(messages -> messages.addErrorsFailedToUpgradeFrom(GLOBAL, VERSION_13_9, e.getLocalizedMessage())); } - } else if (VERSION_13_10.equals(form.targetVersion)) { + break; + case VERSION_13_10: try { upgradeFrom13_10(); upgradeFrom13_11(); @@ -641,7 +652,8 @@ public HtmlResponse upgradeFrom(final UpgradeForm form) { logger.warn("Failed to upgrade data.", e); saveError(messages -> messages.addErrorsFailedToUpgradeFrom(GLOBAL, VERSION_13_10, e.getLocalizedMessage())); } - } else if (VERSION_13_11.equals(form.targetVersion)) { + break; + case VERSION_13_11: try { upgradeFrom13_11(); upgradeFrom13_12(); @@ -675,7 +687,8 @@ public HtmlResponse upgradeFrom(final UpgradeForm form) { logger.warn("Failed to upgrade data.", e); saveError(messages -> messages.addErrorsFailedToUpgradeFrom(GLOBAL, VERSION_13_11, e.getLocalizedMessage())); } - } else if (VERSION_13_12.equals(form.targetVersion)) { + break; + case VERSION_13_12: try { upgradeFrom13_12(); upgradeFrom13_13(); @@ -708,7 +721,8 @@ public HtmlResponse upgradeFrom(final UpgradeForm form) { logger.warn("Failed to upgrade data.", e); saveError(messages -> messages.addErrorsFailedToUpgradeFrom(GLOBAL, VERSION_13_12, e.getLocalizedMessage())); } - } else if (VERSION_13_13.equals(form.targetVersion)) { + break; + case VERSION_13_13: try { upgradeFrom13_13(); upgradeFrom13_14(); @@ -740,7 +754,8 @@ public HtmlResponse upgradeFrom(final UpgradeForm form) { logger.warn("Failed to upgrade data.", e); saveError(messages -> messages.addErrorsFailedToUpgradeFrom(GLOBAL, VERSION_13_13, e.getLocalizedMessage())); } - } else if (VERSION_13_14.equals(form.targetVersion)) { + break; + case VERSION_13_14: try { upgradeFrom13_14(); upgradeFrom13_15(); @@ -771,7 +786,8 @@ public HtmlResponse upgradeFrom(final UpgradeForm form) { logger.warn("Failed to upgrade data.", e); saveError(messages -> messages.addErrorsFailedToUpgradeFrom(GLOBAL, VERSION_13_14, e.getLocalizedMessage())); } - } else if (VERSION_13_15.equals(form.targetVersion)) { + break; + case VERSION_13_15: try { upgradeFrom13_15(); upgradeFrom13_16(); @@ -802,7 +818,8 @@ public HtmlResponse upgradeFrom(final UpgradeForm form) { logger.warn("Failed to upgrade data.", e); saveError(messages -> messages.addErrorsFailedToUpgradeFrom(GLOBAL, VERSION_13_15, e.getLocalizedMessage())); } - } else if (VERSION_13_16.equals(form.targetVersion)) { + break; + case VERSION_13_16: try { upgradeFrom13_16(); upgradeFrom13_17(); @@ -832,7 +849,8 @@ public HtmlResponse upgradeFrom(final UpgradeForm form) { logger.warn("Failed to upgrade data.", e); saveError(messages -> messages.addErrorsFailedToUpgradeFrom(GLOBAL, VERSION_13_16, e.getLocalizedMessage())); } - } else if (VERSION_13_17.equals(form.targetVersion)) { + break; + case VERSION_13_17: try { upgradeFrom13_17(); upgradeFrom14_0(); @@ -861,7 +879,8 @@ public HtmlResponse upgradeFrom(final UpgradeForm form) { logger.warn("Failed to upgrade data.", e); saveError(messages -> messages.addErrorsFailedToUpgradeFrom(GLOBAL, VERSION_13_17, e.getLocalizedMessage())); } - } else if (VERSION_14_0.equals(form.targetVersion)) { + break; + case VERSION_14_0: try { upgradeFrom14_0(); upgradeFrom14_1(); @@ -889,7 +908,8 @@ public HtmlResponse upgradeFrom(final UpgradeForm form) { logger.warn("Failed to upgrade data.", e); saveError(messages -> messages.addErrorsFailedToUpgradeFrom(GLOBAL, VERSION_14_0, e.getLocalizedMessage())); } - } else if (VERSION_14_1.equals(form.targetVersion)) { + break; + case VERSION_14_1: try { upgradeFrom14_1(); upgradeFrom14_2(); @@ -916,7 +936,8 @@ public HtmlResponse upgradeFrom(final UpgradeForm form) { logger.warn("Failed to upgrade data.", e); saveError(messages -> messages.addErrorsFailedToUpgradeFrom(GLOBAL, VERSION_14_1, e.getLocalizedMessage())); } - } else if (VERSION_14_2.equals(form.targetVersion)) { + break; + case VERSION_14_2: try { upgradeFrom14_2(); upgradeFrom14_3(); @@ -942,7 +963,8 @@ public HtmlResponse upgradeFrom(final UpgradeForm form) { logger.warn("Failed to upgrade data.", e); saveError(messages -> messages.addErrorsFailedToUpgradeFrom(GLOBAL, VERSION_14_2, e.getLocalizedMessage())); } - } else if (VERSION_14_3.equals(form.targetVersion)) { + break; + case VERSION_14_3: try { upgradeFrom14_3(); upgradeFrom14_4(); @@ -967,7 +989,8 @@ public HtmlResponse upgradeFrom(final UpgradeForm form) { logger.warn("Failed to upgrade data.", e); saveError(messages -> messages.addErrorsFailedToUpgradeFrom(GLOBAL, VERSION_14_3, e.getLocalizedMessage())); } - } else if (VERSION_14_4.equals(form.targetVersion)) { + break; + case VERSION_14_4: try { upgradeFrom14_4(); upgradeFrom14_5(); @@ -991,7 +1014,8 @@ public HtmlResponse upgradeFrom(final UpgradeForm form) { logger.warn("Failed to upgrade data.", e); saveError(messages -> messages.addErrorsFailedToUpgradeFrom(GLOBAL, VERSION_14_4, e.getLocalizedMessage())); } - } else if (VERSION_14_5.equals(form.targetVersion)) { + break; + case VERSION_14_5: try { upgradeFrom14_5(); upgradeFrom14_6(); @@ -1014,7 +1038,8 @@ public HtmlResponse upgradeFrom(final UpgradeForm form) { logger.warn("Failed to upgrade data.", e); saveError(messages -> messages.addErrorsFailedToUpgradeFrom(GLOBAL, VERSION_14_5, e.getLocalizedMessage())); } - } else if (VERSION_14_6.equals(form.targetVersion)) { + break; + case VERSION_14_6: try { upgradeFrom14_6(); upgradeFrom14_7(); @@ -1036,7 +1061,8 @@ public HtmlResponse upgradeFrom(final UpgradeForm form) { logger.warn("Failed to upgrade data.", e); saveError(messages -> messages.addErrorsFailedToUpgradeFrom(GLOBAL, VERSION_14_6, e.getLocalizedMessage())); } - } else if (VERSION_14_7.equals(form.targetVersion)) { + break; + case VERSION_14_7: try { upgradeFrom14_7(); upgradeFrom14_8(); @@ -1057,7 +1083,8 @@ public HtmlResponse upgradeFrom(final UpgradeForm form) { logger.warn("Failed to upgrade data.", e); saveError(messages -> messages.addErrorsFailedToUpgradeFrom(GLOBAL, VERSION_14_7, e.getLocalizedMessage())); } - } else if (VERSION_14_8.equals(form.targetVersion)) { + break; + case VERSION_14_8: try { upgradeFrom14_8(); upgradeFrom14_9(); @@ -1077,7 +1104,8 @@ public HtmlResponse upgradeFrom(final UpgradeForm form) { logger.warn("Failed to upgrade data.", e); saveError(messages -> messages.addErrorsFailedToUpgradeFrom(GLOBAL, VERSION_14_8, e.getLocalizedMessage())); } - } else if (VERSION_14_9.equals(form.targetVersion)) { + break; + case VERSION_14_9: try { upgradeFrom14_9(); upgradeFrom14_10(); @@ -1096,7 +1124,8 @@ public HtmlResponse upgradeFrom(final UpgradeForm form) { logger.warn("Failed to upgrade data.", e); saveError(messages -> messages.addErrorsFailedToUpgradeFrom(GLOBAL, VERSION_14_9, e.getLocalizedMessage())); } - } else if (VERSION_14_10.equals(form.targetVersion)) { + break; + case VERSION_14_10: try { upgradeFrom14_10(); upgradeFrom14_11(); @@ -1114,7 +1143,8 @@ public HtmlResponse upgradeFrom(final UpgradeForm form) { logger.warn("Failed to upgrade data.", e); saveError(messages -> messages.addErrorsFailedToUpgradeFrom(GLOBAL, VERSION_14_10, e.getLocalizedMessage())); } - } else if (VERSION_14_11.equals(form.targetVersion)) { + break; + case VERSION_14_11: try { upgradeFrom14_11(); upgradeFrom14_12(); @@ -1131,7 +1161,8 @@ public HtmlResponse upgradeFrom(final UpgradeForm form) { logger.warn("Failed to upgrade data.", e); saveError(messages -> messages.addErrorsFailedToUpgradeFrom(GLOBAL, VERSION_14_11, e.getLocalizedMessage())); } - } else if (VERSION_14_12.equals(form.targetVersion)) { + break; + case VERSION_14_12: try { upgradeFrom14_12(); upgradeFrom14_13(); @@ -1147,7 +1178,8 @@ public HtmlResponse upgradeFrom(final UpgradeForm form) { logger.warn("Failed to upgrade data.", e); saveError(messages -> messages.addErrorsFailedToUpgradeFrom(GLOBAL, VERSION_14_12, e.getLocalizedMessage())); } - } else if (VERSION_14_13.equals(form.targetVersion)) { + break; + case VERSION_14_13: try { upgradeFrom14_13(); upgradeFrom14_14(); @@ -1162,7 +1194,8 @@ public HtmlResponse upgradeFrom(final UpgradeForm form) { logger.warn("Failed to upgrade data.", e); saveError(messages -> messages.addErrorsFailedToUpgradeFrom(GLOBAL, VERSION_14_13, e.getLocalizedMessage())); } - } else if (VERSION_14_14.equals(form.targetVersion)) { + break; + case VERSION_14_14: try { upgradeFrom14_14(); upgradeFrom14_15(); @@ -1176,7 +1209,8 @@ public HtmlResponse upgradeFrom(final UpgradeForm form) { logger.warn("Failed to upgrade data.", e); saveError(messages -> messages.addErrorsFailedToUpgradeFrom(GLOBAL, VERSION_14_14, e.getLocalizedMessage())); } - } else if (VERSION_14_15.equals(form.targetVersion)) { + break; + case VERSION_14_15: try { upgradeFrom14_15(); upgradeFrom14_16(); @@ -1189,7 +1223,8 @@ public HtmlResponse upgradeFrom(final UpgradeForm form) { logger.warn("Failed to upgrade data.", e); saveError(messages -> messages.addErrorsFailedToUpgradeFrom(GLOBAL, VERSION_14_15, e.getLocalizedMessage())); } - } else if (VERSION_14_16.equals(form.targetVersion)) { + break; + case VERSION_14_16: try { upgradeFrom14_16(); upgradeFromAll(); @@ -1201,8 +1236,10 @@ public HtmlResponse upgradeFrom(final UpgradeForm form) { logger.warn("Failed to upgrade data.", e); saveError(messages -> messages.addErrorsFailedToUpgradeFrom(GLOBAL, VERSION_14_16, e.getLocalizedMessage())); } - } else { + break; + default: saveError(messages -> messages.addErrorsUnknownVersionForUpgrade(GLOBAL)); + break; } return redirect(getClass()); } diff --git a/src/main/java/org/codelibs/fess/app/web/api/ApiResult.java b/src/main/java/org/codelibs/fess/app/web/api/ApiResult.java index 59e7d287f..30560a2f8 100644 --- a/src/main/java/org/codelibs/fess/app/web/api/ApiResult.java +++ b/src/main/java/org/codelibs/fess/app/web/api/ApiResult.java @@ -120,7 +120,7 @@ public static class ApiConfigsResponse extends ApiResponse { public ApiConfigsResponse settings(final List settings) { this.settings = settings; - this.total = settings.size(); + total = settings.size(); return this; } diff --git a/src/main/java/org/codelibs/fess/app/web/api/admin/backup/ApiAdminBackupAction.java b/src/main/java/org/codelibs/fess/app/web/api/admin/backup/ApiAdminBackupAction.java index b373f1a0d..c21a0adf5 100644 --- a/src/main/java/org/codelibs/fess/app/web/api/admin/backup/ApiAdminBackupAction.java +++ b/src/main/java/org/codelibs/fess/app/web/api/admin/backup/ApiAdminBackupAction.java @@ -102,17 +102,17 @@ public JsonResponse files() { }); } final String name = id.substring(0, id.length() - NDJSON_EXTENTION.length()); - if ("search_log".equals(name)) { + switch (name) { + case "search_log": return writeNdjsonResponse(id, getSearchLogNdjsonWriteCall()); - } - if ("user_info".equals(name)) { + case "user_info": return writeNdjsonResponse(id, getUserInfoNdjsonWriteCall()); - } - if ("click_log".equals(name)) { + case "click_log": return writeNdjsonResponse(id, getClickLogNdjsonWriteCall()); - } - if ("favorite_log".equals(name)) { + case "favorite_log": return writeNdjsonResponse(id, getFavoriteLogNdjsonWriteCall()); + default: + break; } } diff --git a/src/main/java/org/codelibs/fess/app/web/api/admin/searchlist/SearchBody.java b/src/main/java/org/codelibs/fess/app/web/api/admin/searchlist/SearchBody.java index 2e11376ef..1fc793095 100644 --- a/src/main/java/org/codelibs/fess/app/web/api/admin/searchlist/SearchBody.java +++ b/src/main/java/org/codelibs/fess/app/web/api/admin/searchlist/SearchBody.java @@ -28,7 +28,7 @@ public class SearchBody extends ListForm { @Override public void initialize() { if (size != null) { - num = (num == null || num < size) ? size : num; + num = num == null || num < size ? size : num; } super.initialize(); } diff --git a/src/main/java/org/codelibs/fess/app/web/base/login/OpenIdConnectCredential.java b/src/main/java/org/codelibs/fess/app/web/base/login/OpenIdConnectCredential.java index c27248367..035593a17 100644 --- a/src/main/java/org/codelibs/fess/app/web/base/login/OpenIdConnectCredential.java +++ b/src/main/java/org/codelibs/fess/app/web/base/login/OpenIdConnectCredential.java @@ -26,6 +26,7 @@ import org.codelibs.fess.entity.FessUser; import org.codelibs.fess.helper.SystemHelper; import org.codelibs.fess.util.ComponentUtil; +import org.codelibs.fess.util.DocumentUtil; import org.lastaflute.web.login.credential.LoginCredential; public class OpenIdConnectCredential implements LoginCredential, FessCredential { @@ -43,15 +44,15 @@ public String toString() { @Override public String getUserId() { - return (String) attributes.get("email"); + return DocumentUtil.getValue(attributes, "email", String.class); } public String[] getUserGroups() { - String[] userGroups = (String[]) attributes.get("groups"); + String[] userGroups = DocumentUtil.getValue(attributes, "groups", String[].class); if (userGroups == null) { userGroups = getDefaultGroupsAsArray(); } - return (userGroups); + return userGroups; } public OpenIdUser getUser() { diff --git a/src/main/java/org/codelibs/fess/crawler/transformer/AbstractFessFileTransformer.java b/src/main/java/org/codelibs/fess/crawler/transformer/AbstractFessFileTransformer.java index af0fce7f4..7c24bf2db 100644 --- a/src/main/java/org/codelibs/fess/crawler/transformer/AbstractFessFileTransformer.java +++ b/src/main/java/org/codelibs/fess/crawler/transformer/AbstractFessFileTransformer.java @@ -222,8 +222,8 @@ protected Map generateData(final ResponseData responseData) { responseData.addMetaData(Extractor.class.getSimpleName(), extractor); final String body = documentHelper.getContent(crawlingConfig, responseData, bodyBase, dataMap); putResultDataBody(dataMap, fessConfig.getIndexFieldContent(), body); - if ((fieldConfigs.getConfig(fessConfig.getIndexFieldCache()).map(config -> config.isCache()).orElse(false) - || fessConfig.isCrawlerDocumentCacheEnabled()) && fessConfig.isSupportedDocumentCacheMimetypes(mimeType)) { + if ((fieldConfigs.getConfig(fessConfig.getIndexFieldCache()).map(org.codelibs.fess.crawler.util.FieldConfigs.Config::isCache) + .orElse(false) || fessConfig.isCrawlerDocumentCacheEnabled()) && fessConfig.isSupportedDocumentCacheMimetypes(mimeType)) { if (responseData.getContentLength() > 0 && responseData.getContentLength() <= fessConfig.getCrawlerDocumentCacheMaxSizeAsInteger().longValue()) { @@ -348,7 +348,7 @@ protected Date getLastModified(final Map dataMap, final Response if (lastModified != null) { return lastModified; } - } else if ((lastModifiedObj instanceof final String[] lastModifieds) && (lastModifieds.length > 0)) { + } else if (lastModifiedObj instanceof final String[] lastModifieds && lastModifieds.length > 0) { final Date lastModified = FessFunctions.parseDate(lastModifieds[0]); if (lastModified != null) { return lastModified; diff --git a/src/main/java/org/codelibs/fess/crawler/transformer/FessTransformer.java b/src/main/java/org/codelibs/fess/crawler/transformer/FessTransformer.java index 77430ebe9..babb3c1e8 100644 --- a/src/main/java/org/codelibs/fess/crawler/transformer/FessTransformer.java +++ b/src/main/java/org/codelibs/fess/crawler/transformer/FessTransformer.java @@ -88,8 +88,8 @@ default String getSite(final String u, final String encoding) { if (encoding != null) { String enc; if (StringUtil.isNotBlank(getFessConfig().getCrawlerDocumentSiteEncoding()) - && (!getFessConfig().isCrawlerDocumentUseSiteEncodingOnEnglish() - || ("ISO-8859-1".equalsIgnoreCase(encoding) || "US-ASCII".equalsIgnoreCase(encoding)))) { + && (!getFessConfig().isCrawlerDocumentUseSiteEncodingOnEnglish() || "ISO-8859-1".equalsIgnoreCase(encoding) + || "US-ASCII".equalsIgnoreCase(encoding))) { enc = getFessConfig().getCrawlerDocumentSiteEncoding(); } else { enc = encoding; @@ -253,9 +253,9 @@ default String getParentEncoding(final String parentUrl, final String sessionId) default Map processFieldConfigs(final Map dataMap, final FieldConfigs fieldConfigs) { final Map newDataMap = new LinkedHashMap<>(); - for (Map.Entry e : dataMap.entrySet()) { + for (final Map.Entry e : dataMap.entrySet()) { if (fieldConfigs.getConfig(e.getKey()).map(FieldConfigs.Config::isOverwrite).orElse(false) - && e.getValue() instanceof Object[] values && values.length > 0) { + && e.getValue() instanceof final Object[] values && values.length > 0) { newDataMap.put(e.getKey(), values[values.length - 1]); } else { newDataMap.put(e.getKey(), e.getValue()); diff --git a/src/main/java/org/codelibs/fess/crawler/transformer/FessXpathTransformer.java b/src/main/java/org/codelibs/fess/crawler/transformer/FessXpathTransformer.java index 541097da4..aad286a17 100644 --- a/src/main/java/org/codelibs/fess/crawler/transformer/FessXpathTransformer.java +++ b/src/main/java/org/codelibs/fess/crawler/transformer/FessXpathTransformer.java @@ -396,8 +396,8 @@ && isValidCanonicalUrl(responseData.getUrl(), canonicalUrl)) { prunedContent ? node -> pruneNode(node, crawlingConfig) : node -> node); final String fileName = getFileName(url, urlEncoding); putResultDataContent(dataMap, responseData, fessConfig, crawlingConfig, documentHelper, body, fileName); - if ((fieldConfigs.getConfig(fessConfig.getIndexFieldCache()).map(config -> config.isCache()).orElse(false) - || fessConfig.isCrawlerDocumentCacheEnabled()) && fessConfig.isSupportedDocumentCacheMimetypes(mimeType)) { + if ((fieldConfigs.getConfig(fessConfig.getIndexFieldCache()).map(org.codelibs.fess.crawler.util.FieldConfigs.Config::isCache) + .orElse(false) || fessConfig.isCrawlerDocumentCacheEnabled()) && fessConfig.isSupportedDocumentCacheMimetypes(mimeType)) { if (responseData.getContentLength() > 0 && responseData.getContentLength() <= fessConfig.getCrawlerDocumentCacheMaxSizeAsInteger().longValue()) { String charSet = responseData.getCharSet(); @@ -977,6 +977,6 @@ public void setConvertUrlMap(final Map convertUrlMap) { } public void addConvertUrl(final String regex, final String replacement) { - this.convertUrlMap.put(regex, replacement); + convertUrlMap.put(regex, replacement); } } diff --git a/src/main/java/org/codelibs/fess/crawler/util/FieldConfigs.java b/src/main/java/org/codelibs/fess/crawler/util/FieldConfigs.java index 112819466..368efd847 100644 --- a/src/main/java/org/codelibs/fess/crawler/util/FieldConfigs.java +++ b/src/main/java/org/codelibs/fess/crawler/util/FieldConfigs.java @@ -27,12 +27,12 @@ public class FieldConfigs { private final Map params; - public FieldConfigs(Map params) { + public FieldConfigs(final Map params) { this.params = params; } - public OptionalThing getConfig(String fieldName) { - String value = params.get(fieldName); + public OptionalThing getConfig(final String fieldName) { + final String value = params.get(fieldName); if (StringUtil.isNotBlank(value)) { return OptionalThing.of(new Config(value)); } @@ -43,8 +43,8 @@ public static class Config { private final String[] values; - public Config(String value) { - values = StreamUtil.split(value, Pattern.quote("|")).get(stream -> stream.map(s -> s.trim()).toArray(n -> new String[n])); + public Config(final String value) { + values = StreamUtil.split(value, Pattern.quote("|")).get(stream -> stream.map(String::trim).toArray(n -> new String[n])); } public boolean isCache() { diff --git a/src/main/java/org/codelibs/fess/dict/DictionaryFile.java b/src/main/java/org/codelibs/fess/dict/DictionaryFile.java index 379582a3e..194ae1a71 100644 --- a/src/main/java/org/codelibs/fess/dict/DictionaryFile.java +++ b/src/main/java/org/codelibs/fess/dict/DictionaryFile.java @@ -94,7 +94,7 @@ public static class PagingList implements List { protected int pageRangeSize; public PagingList(final List list, final int offset, final int size, final int allRecordCount) { - this.parent = list; + parent = list; this.allRecordCount = allRecordCount; pageSize = size; currentPageNumber = offset / size + 1; diff --git a/src/main/java/org/codelibs/fess/dict/kuromoji/KuromojiFile.java b/src/main/java/org/codelibs/fess/dict/kuromoji/KuromojiFile.java index b8dd1a743..733c41f89 100644 --- a/src/main/java/org/codelibs/fess/dict/kuromoji/KuromojiFile.java +++ b/src/main/java/org/codelibs/fess/dict/kuromoji/KuromojiFile.java @@ -222,7 +222,7 @@ protected KuromojiUpdater(final KuromojiItem newItem) { public KuromojiItem write(final KuromojiItem oldItem) { try { - if ((item == null) || (item.getId() != oldItem.getId()) || !item.isUpdated()) { + if (item == null || item.getId() != oldItem.getId() || !item.isUpdated()) { writer.write(oldItem.toLineString()); writer.write(Constants.LINE_SEPARATOR); return oldItem; diff --git a/src/main/java/org/codelibs/fess/dict/kuromoji/KuromojiItem.java b/src/main/java/org/codelibs/fess/dict/kuromoji/KuromojiItem.java index 14be01eac..6394ade63 100644 --- a/src/main/java/org/codelibs/fess/dict/kuromoji/KuromojiItem.java +++ b/src/main/java/org/codelibs/fess/dict/kuromoji/KuromojiItem.java @@ -118,7 +118,7 @@ public boolean equals(final Object obj) { if (this == obj) { return true; } - if ((obj == null) || (getClass() != obj.getClass())) { + if (obj == null || getClass() != obj.getClass()) { return false; } final KuromojiItem other = (KuromojiItem) obj; diff --git a/src/main/java/org/codelibs/fess/dict/mapping/CharMappingFile.java b/src/main/java/org/codelibs/fess/dict/mapping/CharMappingFile.java index b063a956a..2b789430c 100644 --- a/src/main/java/org/codelibs/fess/dict/mapping/CharMappingFile.java +++ b/src/main/java/org/codelibs/fess/dict/mapping/CharMappingFile.java @@ -236,7 +236,7 @@ protected MappingUpdater(final CharMappingItem newItem) { public CharMappingItem write(final CharMappingItem oldItem) { try { - if ((item == null) || (item.getId() != oldItem.getId()) || !item.isUpdated()) { + if (item == null || item.getId() != oldItem.getId() || !item.isUpdated()) { writer.write(oldItem.toLineString()); writer.write(Constants.LINE_SEPARATOR); return oldItem; diff --git a/src/main/java/org/codelibs/fess/dict/mapping/CharMappingItem.java b/src/main/java/org/codelibs/fess/dict/mapping/CharMappingItem.java index c613332a2..7a9daa4a0 100644 --- a/src/main/java/org/codelibs/fess/dict/mapping/CharMappingItem.java +++ b/src/main/java/org/codelibs/fess/dict/mapping/CharMappingItem.java @@ -102,7 +102,7 @@ public boolean equals(final Object obj) { if (this == obj) { return true; } - if ((obj == null) || (getClass() != obj.getClass())) { + if (obj == null || getClass() != obj.getClass()) { return false; } final CharMappingItem other = (CharMappingItem) obj; diff --git a/src/main/java/org/codelibs/fess/dict/protwords/ProtwordsFile.java b/src/main/java/org/codelibs/fess/dict/protwords/ProtwordsFile.java index d50e31743..f5d31a147 100644 --- a/src/main/java/org/codelibs/fess/dict/protwords/ProtwordsFile.java +++ b/src/main/java/org/codelibs/fess/dict/protwords/ProtwordsFile.java @@ -221,7 +221,7 @@ protected ProtwordsUpdater(final ProtwordsItem newItem) { public ProtwordsItem write(final ProtwordsItem oldItem) { try { - if ((item == null) || (item.getId() != oldItem.getId()) || !item.isUpdated()) { + if (item == null || item.getId() != oldItem.getId() || !item.isUpdated()) { writer.write(oldItem.toLineString()); writer.write(Constants.LINE_SEPARATOR); return oldItem; diff --git a/src/main/java/org/codelibs/fess/dict/protwords/ProtwordsItem.java b/src/main/java/org/codelibs/fess/dict/protwords/ProtwordsItem.java index 0808913ba..81c0bebac 100644 --- a/src/main/java/org/codelibs/fess/dict/protwords/ProtwordsItem.java +++ b/src/main/java/org/codelibs/fess/dict/protwords/ProtwordsItem.java @@ -73,7 +73,7 @@ public boolean equals(final Object obj) { if (this == obj) { return true; } - if ((obj == null) || (getClass() != obj.getClass())) { + if (obj == null || getClass() != obj.getClass()) { return false; } final ProtwordsItem other = (ProtwordsItem) obj; diff --git a/src/main/java/org/codelibs/fess/dict/stemmeroverride/StemmerOverrideFile.java b/src/main/java/org/codelibs/fess/dict/stemmeroverride/StemmerOverrideFile.java index 040cc97b9..ab6a71ea3 100644 --- a/src/main/java/org/codelibs/fess/dict/stemmeroverride/StemmerOverrideFile.java +++ b/src/main/java/org/codelibs/fess/dict/stemmeroverride/StemmerOverrideFile.java @@ -233,7 +233,7 @@ protected StemmerOverrideUpdater(final StemmerOverrideItem newItem) { public StemmerOverrideItem write(final StemmerOverrideItem oldItem) { try { - if ((item == null) || (item.getId() != oldItem.getId()) || !item.isUpdated()) { + if (item == null || item.getId() != oldItem.getId() || !item.isUpdated()) { writer.write(oldItem.toLineString()); writer.write(Constants.LINE_SEPARATOR); return oldItem; diff --git a/src/main/java/org/codelibs/fess/dict/stemmeroverride/StemmerOverrideItem.java b/src/main/java/org/codelibs/fess/dict/stemmeroverride/StemmerOverrideItem.java index c5509b713..3a26278e6 100644 --- a/src/main/java/org/codelibs/fess/dict/stemmeroverride/StemmerOverrideItem.java +++ b/src/main/java/org/codelibs/fess/dict/stemmeroverride/StemmerOverrideItem.java @@ -54,7 +54,7 @@ public String getNewOutput() { } public void setNewOutput(final String newOutputs) { - this.newOutput = newOutputs; + newOutput = newOutputs; } public String getInput() { @@ -83,7 +83,7 @@ public boolean equals(final Object obj) { if (this == obj) { return true; } - if ((obj == null) || (getClass() != obj.getClass())) { + if (obj == null || getClass() != obj.getClass()) { return false; } final StemmerOverrideItem other = (StemmerOverrideItem) obj; diff --git a/src/main/java/org/codelibs/fess/dict/stopwords/StopwordsFile.java b/src/main/java/org/codelibs/fess/dict/stopwords/StopwordsFile.java index 10f6ae67f..2f0b4aeb5 100644 --- a/src/main/java/org/codelibs/fess/dict/stopwords/StopwordsFile.java +++ b/src/main/java/org/codelibs/fess/dict/stopwords/StopwordsFile.java @@ -221,7 +221,7 @@ protected SynonymUpdater(final StopwordsItem newItem) { public StopwordsItem write(final StopwordsItem oldItem) { try { - if ((item == null) || (item.getId() != oldItem.getId()) || !item.isUpdated()) { + if (item == null || item.getId() != oldItem.getId() || !item.isUpdated()) { writer.write(oldItem.toLineString()); writer.write(Constants.LINE_SEPARATOR); return oldItem; diff --git a/src/main/java/org/codelibs/fess/dict/stopwords/StopwordsItem.java b/src/main/java/org/codelibs/fess/dict/stopwords/StopwordsItem.java index 7b6b49632..b4f5f4d62 100644 --- a/src/main/java/org/codelibs/fess/dict/stopwords/StopwordsItem.java +++ b/src/main/java/org/codelibs/fess/dict/stopwords/StopwordsItem.java @@ -73,7 +73,7 @@ public boolean equals(final Object obj) { if (this == obj) { return true; } - if ((obj == null) || (getClass() != obj.getClass())) { + if (obj == null || getClass() != obj.getClass()) { return false; } final StopwordsItem other = (StopwordsItem) obj; diff --git a/src/main/java/org/codelibs/fess/dict/synonym/SynonymFile.java b/src/main/java/org/codelibs/fess/dict/synonym/SynonymFile.java index fa6d861fd..676b2a002 100644 --- a/src/main/java/org/codelibs/fess/dict/synonym/SynonymFile.java +++ b/src/main/java/org/codelibs/fess/dict/synonym/SynonymFile.java @@ -297,7 +297,7 @@ protected SynonymUpdater(final SynonymItem newItem) { public SynonymItem write(final SynonymItem oldItem) { try { - if ((item == null) || (item.getId() != oldItem.getId()) || !item.isUpdated()) { + if (item == null || item.getId() != oldItem.getId() || !item.isUpdated()) { writer.write(oldItem.toLineString()); writer.write(Constants.LINE_SEPARATOR); return oldItem; diff --git a/src/main/java/org/codelibs/fess/dict/synonym/SynonymItem.java b/src/main/java/org/codelibs/fess/dict/synonym/SynonymItem.java index 10cf67a69..82a4b0359 100644 --- a/src/main/java/org/codelibs/fess/dict/synonym/SynonymItem.java +++ b/src/main/java/org/codelibs/fess/dict/synonym/SynonymItem.java @@ -100,7 +100,7 @@ public boolean equals(final Object obj) { if (this == obj) { return true; } - if ((obj == null) || (getClass() != obj.getClass())) { + if (obj == null || getClass() != obj.getClass()) { return false; } final SynonymItem other = (SynonymItem) obj; diff --git a/src/main/java/org/codelibs/fess/entity/HighlightInfo.java b/src/main/java/org/codelibs/fess/entity/HighlightInfo.java index 814c416a7..207bb9cf4 100644 --- a/src/main/java/org/codelibs/fess/entity/HighlightInfo.java +++ b/src/main/java/org/codelibs/fess/entity/HighlightInfo.java @@ -26,10 +26,10 @@ public class HighlightInfo { public HighlightInfo() { final FessConfig fessConfig = ComponentUtil.getFessConfig(); - this.type = fessConfig.getQueryHighlightType(); - this.fragmentSize = fessConfig.getQueryHighlightFragmentSizeAsInteger(); - this.numOfFragments = fessConfig.getQueryHighlightNumberOfFragmentsAsInteger(); - this.fragmentOffset = fessConfig.getQueryHighlightFragmentOffsetAsInteger(); + type = fessConfig.getQueryHighlightType(); + fragmentSize = fessConfig.getQueryHighlightFragmentSizeAsInteger(); + numOfFragments = fessConfig.getQueryHighlightNumberOfFragmentsAsInteger(); + fragmentOffset = fessConfig.getQueryHighlightFragmentOffsetAsInteger(); } public String getType() { diff --git a/src/main/java/org/codelibs/fess/entity/QueryContext.java b/src/main/java/org/codelibs/fess/entity/QueryContext.java index ff770767e..942755249 100644 --- a/src/main/java/org/codelibs/fess/entity/QueryContext.java +++ b/src/main/java/org/codelibs/fess/entity/QueryContext.java @@ -61,10 +61,10 @@ public class QueryContext { public QueryContext(final String queryString, final boolean isQuery) { if (queryString != null) { if (queryString.startsWith(ALLINURL_FIELD_PREFIX)) { - this.defaultField = ComponentUtil.getFessConfig().getIndexFieldUrl(); + defaultField = ComponentUtil.getFessConfig().getIndexFieldUrl(); this.queryString = queryString.substring(ALLINURL_FIELD_PREFIX.length()); } else if (queryString.startsWith(ALLINTITLE_FIELD_PREFIX)) { - this.defaultField = ComponentUtil.getFessConfig().getIndexFieldTitle(); + defaultField = ComponentUtil.getFessConfig().getIndexFieldTitle(); this.queryString = queryString.substring(ALLINTITLE_FIELD_PREFIX.length()); } else { this.queryString = queryString; diff --git a/src/main/java/org/codelibs/fess/es/client/SearchEngineClient.java b/src/main/java/org/codelibs/fess/es/client/SearchEngineClient.java index 550f39fed..454c09276 100644 --- a/src/main/java/org/codelibs/fess/es/client/SearchEngineClient.java +++ b/src/main/java/org/codelibs/fess/es/client/SearchEngineClient.java @@ -248,11 +248,11 @@ public void setRunner(final OpenSearchRunner runner) { } public boolean isEmbedded() { - return this.runner != null; + return runner != null; } public void usePipeline() { - this.usePipeline = true; + usePipeline = true; } protected InetAddress getInetAddressByName(final String host) { @@ -283,7 +283,7 @@ public void open() { } String httpAddress = SystemUtil.getSearchEngineHttpAddress(); - if (StringUtil.isBlank(httpAddress) && (runner == null)) { + if (StringUtil.isBlank(httpAddress) && runner == null) { switch (fessConfig.getFesenType()) { case Constants.FESEN_TYPE_CLOUD: case Constants.FESEN_TYPE_AWS: @@ -752,43 +752,42 @@ protected void insertBulkData(final FessConfig fessConfig, final String configIn final BulkRequestBuilder builder = client.prepareBulk(); final ObjectMapper mapper = new ObjectMapper(); final String userIndex = fessConfig.getIndexUserIndex() + ".user"; - Arrays.stream(FileUtil.readUTF8(dataPath).split("\n")).map(line -> { - return line// - .replace("\"_index\":\"fess_config.", "\"_index\":\"" + fessConfig.getIndexConfigIndex() + ".")// - .replace("\"_index\":\"fess_user.", "\"_index\":\"" + fessConfig.getIndexUserIndex() + ".")// - .replace("\"_index\":\"fess_log.", "\"_index\":\"" + fessConfig.getIndexLogIndex() + "."); - }).reduce((prev, line) -> { - try { - if (StringUtil.isBlank(prev)) { - final Map> result = - mapper.readValue(line, new TypeReference>>() { - }); - if (result.containsKey("index") || result.containsKey("update")) { - return line; - } - if (result.containsKey("delete")) { - return StringUtil.EMPTY; - } - } else { - final Map> result = - mapper.readValue(prev, new TypeReference>>() { - }); - if (result.containsKey("index")) { - String source = line; - if (userIndex.equals(configIndex)) { - source = source.replace("${fess.index.initial_password}", ComponentUtil.getComponent(FessLoginAssist.class) - .encryptPassword(fessConfig.getIndexUserInitialPassword())); + Arrays.stream(FileUtil.readUTF8(dataPath).split("\n")).map(line -> line// + .replace("\"_index\":\"fess_config.", "\"_index\":\"" + fessConfig.getIndexConfigIndex() + ".")// + .replace("\"_index\":\"fess_user.", "\"_index\":\"" + fessConfig.getIndexUserIndex() + ".")// + .replace("\"_index\":\"fess_log.", "\"_index\":\"" + fessConfig.getIndexLogIndex() + ".")).reduce((prev, line) -> { + try { + if (StringUtil.isBlank(prev)) { + final Map> result = + mapper.readValue(line, new TypeReference>>() { + }); + if (result.containsKey("index") || result.containsKey("update")) { + return line; + } + if (result.containsKey("delete")) { + return StringUtil.EMPTY; + } + } else { + final Map> result = + mapper.readValue(prev, new TypeReference>>() { + }); + if (result.containsKey("index")) { + String source = line; + if (userIndex.equals(configIndex)) { + source = source.replace("${fess.index.initial_password}", + ComponentUtil.getComponent(FessLoginAssist.class) + .encryptPassword(fessConfig.getIndexUserInitialPassword())); + } + final IndexRequestBuilder requestBuilder = client.prepareIndex().setIndex(configIndex) + .setId(result.get("index").get("_id")).setSource(source, XContentType.JSON); + builder.add(requestBuilder); + } } - final IndexRequestBuilder requestBuilder = client.prepareIndex().setIndex(configIndex) - .setId(result.get("index").get("_id")).setSource(source, XContentType.JSON); - builder.add(requestBuilder); + } catch (final Exception e) { + logger.warn("Failed to parse {}", dataPath); } - } - } catch (final Exception e) { - logger.warn("Failed to parse {}", dataPath); - } - return StringUtil.EMPTY; - }); + return StringUtil.EMPTY; + }); final BulkResponse response = builder.execute().actionGet(fessConfig.getIndexBulkTimeout()); if (response.hasFailures()) { logger.warn("Failed to register {}: {}", dataPath, response.buildFailureMessage()); @@ -1327,7 +1326,7 @@ public SearchConditionBuilder facetInfo(final FacetInfo facetInfo) { } public SearchConditionBuilder scroll() { - this.isScroll = true; + isScroll = true; return this; } diff --git a/src/main/java/org/codelibs/fess/es/config/exentity/DataConfig.java b/src/main/java/org/codelibs/fess/es/config/exentity/DataConfig.java index 548a61bbe..d0a3c26e2 100644 --- a/src/main/java/org/codelibs/fess/es/config/exentity/DataConfig.java +++ b/src/main/java/org/codelibs/fess/es/config/exentity/DataConfig.java @@ -299,21 +299,30 @@ public CrawlerClientFactory initializeClientFactory(final Supplier paramMap, final String webAuthName, final String scheme) { AuthScheme authScheme = null; - if (Constants.BASIC.equals(scheme)) { + switch (scheme) { + case Constants.BASIC: authScheme = new BasicScheme(); - } else if (Constants.DIGEST.equals(scheme)) { + break; + case Constants.DIGEST: authScheme = new DigestScheme(); - } else if (Constants.NTLM.equals(scheme)) { + break; + case Constants.NTLM: { final Properties props = new Properties(); paramMap.entrySet().stream().filter(e -> e.getKey().startsWith("jcifs.")).forEach(e -> { props.setProperty(e.getKey(), e.getValue()); }); authScheme = new NTLMScheme(new JcifsEngine(props)); - } else if (Constants.FORM.equals(scheme)) { + break; + } + case Constants.FORM: { final String prefix = CRAWLER_WEB_AUTH + "." + webAuthName + "."; final Map parameterMap = paramMap.entrySet().stream().filter(e -> e.getKey().startsWith(prefix)) .collect(Collectors.toMap(e -> e.getKey().substring(prefix.length()), Entry::getValue)); authScheme = new FormScheme(parameterMap); + break; + } + default: + break; } return authScheme; } diff --git a/src/main/java/org/codelibs/fess/es/config/exentity/WebAuthentication.java b/src/main/java/org/codelibs/fess/es/config/exentity/WebAuthentication.java index 242229115..cd60ad425 100644 --- a/src/main/java/org/codelibs/fess/es/config/exentity/WebAuthentication.java +++ b/src/main/java/org/codelibs/fess/es/config/exentity/WebAuthentication.java @@ -59,13 +59,12 @@ public Authentication getAuthentication() { private AuthScheme getAuthScheme() { final String scheme = getProtocolScheme(); - if (Constants.BASIC.equals(scheme)) { + switch (scheme) { + case Constants.BASIC: return new BasicScheme(); - } - if (Constants.DIGEST.equals(scheme)) { + case Constants.DIGEST: return new DigestScheme(); - } - if (Constants.NTLM.equals(scheme)) { + case Constants.NTLM: { final Properties props = new Properties(); getWebConfig().getConfigParameterMap(ConfigName.CONFIG).entrySet().stream() .filter(e -> e.getKey().startsWith(Config.JCIFS_PREFIX)).forEach(e -> { @@ -73,10 +72,13 @@ private AuthScheme getAuthScheme() { }); return new NTLMScheme(new JcifsEngine(props)); } - if (Constants.FORM.equals(scheme)) { + case Constants.FORM: { final Map parameterMap = ParameterUtil.parse(getParameters()); return new FormScheme(parameterMap); } + default: + break; + } return null; } diff --git a/src/main/java/org/codelibs/fess/es/config/exentity/WebConfig.java b/src/main/java/org/codelibs/fess/es/config/exentity/WebConfig.java index b6f8220b4..39486ee3e 100644 --- a/src/main/java/org/codelibs/fess/es/config/exentity/WebConfig.java +++ b/src/main/java/org/codelibs/fess/es/config/exentity/WebConfig.java @@ -172,14 +172,11 @@ public CrawlerClientFactory initializeClientFactory(final Supplier webAuthList = webAuthenticationService.getWebAuthenticationList(getId()); diff --git a/src/main/java/org/codelibs/fess/es/query/StoredLtrQueryBuilder.java b/src/main/java/org/codelibs/fess/es/query/StoredLtrQueryBuilder.java index cd7f99dc6..3507bceb8 100644 --- a/src/main/java/org/codelibs/fess/es/query/StoredLtrQueryBuilder.java +++ b/src/main/java/org/codelibs/fess/es/query/StoredLtrQueryBuilder.java @@ -87,8 +87,8 @@ protected void doXContent(final XContentBuilder builder, final Params params) th if (this.params != null && !this.params.isEmpty()) { builder.field(PARAMS.getPreferredName(), this.params); } - if (this.activeFeatures != null && !this.activeFeatures.isEmpty()) { - builder.field(ACTIVE_FEATURES.getPreferredName(), this.activeFeatures); + if (activeFeatures != null && !activeFeatures.isEmpty()) { + builder.field(ACTIVE_FEATURES.getPreferredName(), activeFeatures); } printBoostAndQueryName(builder); builder.endObject(); diff --git a/src/main/java/org/codelibs/fess/exception/ContainerNotAvailableException.java b/src/main/java/org/codelibs/fess/exception/ContainerNotAvailableException.java index b425cbb6f..f575b6d87 100644 --- a/src/main/java/org/codelibs/fess/exception/ContainerNotAvailableException.java +++ b/src/main/java/org/codelibs/fess/exception/ContainerNotAvailableException.java @@ -32,7 +32,7 @@ public ContainerNotAvailableException(final String componentName, final Throwabl public ContainerNotAvailableException(final Throwable cause) { super("Container is not avaiable."); - this.componentName = "container"; + componentName = "container"; } public String getComponentName() { diff --git a/src/main/java/org/codelibs/fess/exec/Crawler.java b/src/main/java/org/codelibs/fess/exec/Crawler.java index 821cc60fb..08275ce18 100644 --- a/src/main/java/org/codelibs/fess/exec/Crawler.java +++ b/src/main/java/org/codelibs/fess/exec/Crawler.java @@ -495,8 +495,7 @@ public int doCrawl(final Options options) { } // delete expired sessions - SystemHelper systemHelper2 = ComponentUtil.getSystemHelper(); - crawlingInfoService.deleteSessionIdsBefore(options.sessionId, options.name, systemHelper2.getCurrentTimeAsLong()); + crawlingInfoService.deleteSessionIdsBefore(options.sessionId, options.name, systemHelper.getCurrentTimeAsLong()); final List webConfigIdList = options.getWebConfigIdList(); final List fileConfigIdList = options.getFileConfigIdList(); diff --git a/src/main/java/org/codelibs/fess/helper/CrawlerLogHelper.java b/src/main/java/org/codelibs/fess/helper/CrawlerLogHelper.java index d0ef0a190..d0644086d 100644 --- a/src/main/java/org/codelibs/fess/helper/CrawlerLogHelper.java +++ b/src/main/java/org/codelibs/fess/helper/CrawlerLogHelper.java @@ -92,7 +92,7 @@ protected void processCrawlingAccessException(final Object... objs) { final CrawlingAccessException cae = (CrawlingAccessException) objs[2]; try { Throwable t = cae; - if (t instanceof MultipleCrawlingAccessException mcae) { + if (t instanceof final MultipleCrawlingAccessException mcae) { final Throwable[] causes = mcae.getCauses(); if (causes.length > 0) { t = causes[causes.length - 1]; @@ -106,7 +106,7 @@ protected void processCrawlingAccessException(final Object... objs) { } else { errorName = t.getClass().getCanonicalName(); } - FailureUrl failureUrl = storeFailureUrl(crawlerContext, urlQueue, errorName, t); + final FailureUrl failureUrl = storeFailureUrl(crawlerContext, urlQueue, errorName, t); if (failureUrl != null) { failureUrlId = failureUrl.getId(); } diff --git a/src/main/java/org/codelibs/fess/helper/IndexingHelper.java b/src/main/java/org/codelibs/fess/helper/IndexingHelper.java index 368abe520..756dba06b 100644 --- a/src/main/java/org/codelibs/fess/helper/IndexingHelper.java +++ b/src/main/java/org/codelibs/fess/helper/IndexingHelper.java @@ -101,10 +101,10 @@ public void sendDocuments(final SearchEngineClient searchEngineClient, final Doc if (logger.isInfoEnabled()) { if (docList.getContentSize() > 0) { logger.info("Sent {} docs (Doc:{process {}ms, send {}ms, size {}}, {})", docList.size(), docList.getProcessingTime(), - (systemHelper.getCurrentTimeAsLong() - execTime), MemoryUtil.byteCountToDisplaySize(docList.getContentSize()), + systemHelper.getCurrentTimeAsLong() - execTime, MemoryUtil.byteCountToDisplaySize(docList.getContentSize()), MemoryUtil.getMemoryUsageLog()); } else { - logger.info("Sent {} docs (Doc:{send {}ms}, {})", docList.size(), (systemHelper.getCurrentTimeAsLong() - execTime), + logger.info("Sent {} docs (Doc:{send {}ms}, {})", docList.size(), systemHelper.getCurrentTimeAsLong() - execTime, MemoryUtil.getMemoryUsageLog()); } } diff --git a/src/main/java/org/codelibs/fess/helper/IntervalControlHelper.java b/src/main/java/org/codelibs/fess/helper/IntervalControlHelper.java index 85a90d472..40e763063 100644 --- a/src/main/java/org/codelibs/fess/helper/IntervalControlHelper.java +++ b/src/main/java/org/codelibs/fess/helper/IntervalControlHelper.java @@ -124,8 +124,8 @@ public boolean isTarget(final int hours, final int minutes, final int day) { return compareTime(fromHours, fromMinutes, hours, minutes) >= 0 && compareTime(hours, minutes, toHours, toMinutes) >= 0 && isInDays(day); } - if ((compareTime(hours, minutes, toHours, toMinutes) >= 0 && isInDays(day + 1)) - || (compareTime(fromHours, fromMinutes, hours, minutes) >= 0 && isInDays(day))) { + if (compareTime(hours, minutes, toHours, toMinutes) >= 0 && isInDays(day + 1) + || compareTime(fromHours, fromMinutes, hours, minutes) >= 0 && isInDays(day)) { return true; } return false; diff --git a/src/main/java/org/codelibs/fess/helper/LabelTypeHelper.java b/src/main/java/org/codelibs/fess/helper/LabelTypeHelper.java index 324e2e6e6..d55f32aeb 100644 --- a/src/main/java/org/codelibs/fess/helper/LabelTypeHelper.java +++ b/src/main/java/org/codelibs/fess/helper/LabelTypeHelper.java @@ -134,8 +134,8 @@ protected boolean matchLocale(final Locale requestLocale, final Locale targetLoc if (targetLocale.equals(requestLocale) || targetLocale.equals(Locale.ROOT)) { return true; } - if ((requestLocale == null) || !requestLocale.getLanguage().equals(targetLocale.getLanguage()) - || (targetLocale.getCountry().length() > 0 && !requestLocale.getCountry().equals(targetLocale.getCountry()))) { + if (requestLocale == null || !requestLocale.getLanguage().equals(targetLocale.getLanguage()) + || targetLocale.getCountry().length() > 0 && !requestLocale.getCountry().equals(targetLocale.getCountry())) { return false; } return true; diff --git a/src/main/java/org/codelibs/fess/helper/ProcessHelper.java b/src/main/java/org/codelibs/fess/helper/ProcessHelper.java index 13c32d552..9e00b7350 100644 --- a/src/main/java/org/codelibs/fess/helper/ProcessHelper.java +++ b/src/main/java/org/codelibs/fess/helper/ProcessHelper.java @@ -49,7 +49,7 @@ public void destroy() { if (logger.isInfoEnabled()) { logger.info("Stopping process {}", sessionId); } - if ((destroyProcess(sessionId) == 0) && logger.isInfoEnabled()) { + if (destroyProcess(sessionId) == 0 && logger.isInfoEnabled()) { logger.info("Stopped process {}", sessionId); } } diff --git a/src/main/java/org/codelibs/fess/helper/SearchHelper.java b/src/main/java/org/codelibs/fess/helper/SearchHelper.java index 9178e19ab..d9d86edf9 100644 --- a/src/main/java/org/codelibs/fess/helper/SearchHelper.java +++ b/src/main/java/org/codelibs/fess/helper/SearchHelper.java @@ -77,7 +77,7 @@ public class SearchHelper { // Variable // - protected SearchRequestParamsRewriter[] searchRequestParamsRewriters = new SearchRequestParamsRewriter[0]; + protected SearchRequestParamsRewriter[] searchRequestParamsRewriters = {}; // =================================================================================== // Method @@ -173,7 +173,7 @@ protected List> searchInternal(final String query, final Sea final OptionalThing userBean) { final RankFusionProcessor rankFusionProcessor = ComponentUtil.getRankFusionProcessor(); final List> documentItems = rankFusionProcessor.search(query, params, userBean); - if (documentItems instanceof QueryResponseList queryResponseList) { + if (documentItems instanceof final QueryResponseList queryResponseList) { final FessConfig fessConfig = ComponentUtil.getFessConfig(); if (queryResponseList.getAllRecordCount() <= fessConfig.getQueryOrsearchMinHitCountAsInteger()) { return LaRequestUtil.getOptionalRequest().map(request -> { diff --git a/src/main/java/org/codelibs/fess/helper/SuggestHelper.java b/src/main/java/org/codelibs/fess/helper/SuggestHelper.java index 1d755f139..07bfef73e 100644 --- a/src/main/java/org/codelibs/fess/helper/SuggestHelper.java +++ b/src/main/java/org/codelibs/fess/helper/SuggestHelper.java @@ -171,8 +171,8 @@ public void indexFromSearchLog(final List searchLogList) { } final LocalDateTime requestedAt = searchLog.getRequestedAt(); - if ((sessionId == null) || (duplicateSessionMap.containsKey(sessionId) - && duplicateSessionMap.get(sessionId).plusMinutes(searchStoreInterval).isAfter(requestedAt))) { + if (sessionId == null || duplicateSessionMap.containsKey(sessionId) + && duplicateSessionMap.get(sessionId).plusMinutes(searchStoreInterval).isAfter(requestedAt)) { return; } diff --git a/src/main/java/org/codelibs/fess/helper/ViewHelper.java b/src/main/java/org/codelibs/fess/helper/ViewHelper.java index a7e5c588e..47f9fddda 100644 --- a/src/main/java/org/codelibs/fess/helper/ViewHelper.java +++ b/src/main/java/org/codelibs/fess/helper/ViewHelper.java @@ -313,7 +313,7 @@ public HighlightInfo createHighlightInfo() { protected void updateHighlightInfo(final HighlightInfo highlightInfo, final int width) { if (width < TABLET_WIDTH) { - float ratio = ((float) width) / ((float) TABLET_WIDTH); + float ratio = (float) width / (float) TABLET_WIDTH; if (ratio < 0.5) { ratio = 0.5f; } @@ -638,7 +638,8 @@ public Object getSitePath(final Map docMap) { final int size = fessConfig.getResponseMaxSitePathLengthAsInteger(); if (size > 3) { return StringUtils.abbreviate(site, size); - } else if (size >= 0) { + } + if (size >= 0) { return site; } } diff --git a/src/main/java/org/codelibs/fess/helper/WebFsIndexHelper.java b/src/main/java/org/codelibs/fess/helper/WebFsIndexHelper.java index e9849e57c..c7be673f6 100644 --- a/src/main/java/org/codelibs/fess/helper/WebFsIndexHelper.java +++ b/src/main/java/org/codelibs/fess/helper/WebFsIndexHelper.java @@ -43,7 +43,6 @@ import org.codelibs.fess.es.config.exentity.FileConfig; import org.codelibs.fess.es.config.exentity.WebConfig; import org.codelibs.fess.indexer.IndexUpdater; -import org.codelibs.fess.mylasta.direction.FessConfig; import org.codelibs.fess.util.ComponentUtil; public class WebFsIndexHelper { @@ -92,7 +91,7 @@ protected void doCrawl(final String sessionId, final List webConfigLi final int multiprocessCrawlingCount = ComponentUtil.getFessConfig().getCrawlingThreadCount(); final SystemHelper systemHelper = ComponentUtil.getSystemHelper(); - final FessConfig fessConfig = ComponentUtil.getFessConfig(); + ComponentUtil.getFessConfig(); final ProtocolHelper protocolHelper = ComponentUtil.getProtocolHelper(); final long startTime = systemHelper.getCurrentTimeAsLong(); diff --git a/src/main/java/org/codelibs/fess/indexer/DocBoostMatcher.java b/src/main/java/org/codelibs/fess/indexer/DocBoostMatcher.java index cc9878d13..cc6831ad3 100644 --- a/src/main/java/org/codelibs/fess/indexer/DocBoostMatcher.java +++ b/src/main/java/org/codelibs/fess/indexer/DocBoostMatcher.java @@ -47,7 +47,7 @@ public boolean match(final Map map) { final Object value = ComponentUtil.getScriptEngineFactory().getScriptEngine(scriptType).evaluate(matchExpression, map); if (value instanceof Boolean) { - return ((Boolean) value); + return (Boolean) value; } return false; @@ -66,7 +66,7 @@ public float getValue(final Map map) { return ((Long) value).floatValue(); } if (value instanceof Float) { - return ((Float) value); + return (Float) value; } if (value instanceof Double) { return ((Double) value).floatValue(); diff --git a/src/main/java/org/codelibs/fess/indexer/IndexUpdater.java b/src/main/java/org/codelibs/fess/indexer/IndexUpdater.java index aee00e342..b2038157f 100644 --- a/src/main/java/org/codelibs/fess/indexer/IndexUpdater.java +++ b/src/main/java/org/codelibs/fess/indexer/IndexUpdater.java @@ -553,13 +553,13 @@ private void cleanupFinishedSessionData() { deleteBySessionId(sessionId); if (logger.isDebugEnabled()) { logger.debug("Deleted {} documents. The execution time is {}ms.", sessionId, - (systemHelper.getCurrentTimeAsLong() - execTime2)); + systemHelper.getCurrentTimeAsLong() - execTime2); } } finishedSessionIdList.clear(); if (logger.isInfoEnabled()) { - logger.info("Deleted completed document data. The execution time is {}ms.", (systemHelper.getCurrentTimeAsLong() - execTime)); + logger.info("Deleted completed document data. The execution time is {}ms.", systemHelper.getCurrentTimeAsLong() - execTime); } } diff --git a/src/main/java/org/codelibs/fess/job/ExecJob.java b/src/main/java/org/codelibs/fess/job/ExecJob.java index 173033480..695f20ce1 100644 --- a/src/main/java/org/codelibs/fess/job/ExecJob.java +++ b/src/main/java/org/codelibs/fess/job/ExecJob.java @@ -124,12 +124,12 @@ public ExecJob gcLogging() { } public ExecJob jvmOptions(final String... options) { - Collections.addAll(this.jvmOptions, options); + Collections.addAll(jvmOptions, options); return this; } public ExecJob lastaEnv(final String env) { - this.lastaEnv = env; + lastaEnv = env; return this; } diff --git a/src/main/java/org/codelibs/fess/job/GenerateThumbnailJob.java b/src/main/java/org/codelibs/fess/job/GenerateThumbnailJob.java index ed08e37c4..14b1b523f 100644 --- a/src/main/java/org/codelibs/fess/job/GenerateThumbnailJob.java +++ b/src/main/java/org/codelibs/fess/job/GenerateThumbnailJob.java @@ -53,7 +53,7 @@ public GenerateThumbnailJob numOfThreads(final int numOfThreads) { } public GenerateThumbnailJob cleanup() { - this.cleanup = true; + cleanup = true; return this; } diff --git a/src/main/java/org/codelibs/fess/mylasta/direction/FessConfig.java b/src/main/java/org/codelibs/fess/mylasta/direction/FessConfig.java index 737862b42..3db7e1d81 100644 --- a/src/main/java/org/codelibs/fess/mylasta/direction/FessConfig.java +++ b/src/main/java/org/codelibs/fess/mylasta/direction/FessConfig.java @@ -862,7 +862,7 @@ public interface FessConfig extends FessEnv, org.codelibs.fess.mylasta.direction /** The key of the configuration. e.g. true */ String QUERY_REPLACE_TERM_WITH_PREFIX_QUERY = "query.replace.term.with.prefix.query"; - /** The key of the configuration. e.g. 0 */ + /** The key of the configuration. e.g. -1 */ String QUERY_ORSEARCH_MIN_HIT_COUNT = "query.orsearch.min.hit.count"; /** The key of the configuration. e.g. u0021u002Cu002Eu003Fu0589u061Fu06D4u0700u0701u0702u0964u104Au104Bu1362u1367u1368u166Eu1803u1809u203Cu203Du2047u2048u2049u3002uFE52uFE57uFF01uFF0EuFF1FuFF61 */ @@ -4441,14 +4441,14 @@ public interface FessConfig extends FessEnv, org.codelibs.fess.mylasta.direction /** * Get the value for the key 'query.orsearch.min.hit.count'.
- * The value is, e.g. 0
+ * The value is, e.g. -1
* @return The value of found property. (NotNull: if not found, exception but basically no way) */ String getQueryOrsearchMinHitCount(); /** * Get the value for the key 'query.orsearch.min.hit.count' as {@link Integer}.
- * The value is, e.g. 0
+ * The value is, e.g. -1
* @return The value of found property. (NotNull: if not found, exception but basically no way) * @throws NumberFormatException When the property is not integer. */ @@ -11263,7 +11263,7 @@ protected java.util.Map prepareGeneratedDefaultMap() { defaultMap.put(FessConfig.QUERY_GEO_FIELDS, "location"); defaultMap.put(FessConfig.QUERY_BROWSER_LANG_PARAMETER_NAME, "browser_lang"); defaultMap.put(FessConfig.QUERY_REPLACE_TERM_WITH_PREFIX_QUERY, "true"); - defaultMap.put(FessConfig.QUERY_ORSEARCH_MIN_HIT_COUNT, "0"); + defaultMap.put(FessConfig.QUERY_ORSEARCH_MIN_HIT_COUNT, "-1"); defaultMap.put(FessConfig.QUERY_HIGHLIGHT_TERMINAL_CHARS, "u0021u002Cu002Eu003Fu0589u061Fu06D4u0700u0701u0702u0964u104Au104Bu1362u1367u1368u166Eu1803u1809u203Cu203Du2047u2048u2049u3002uFE52uFE57uFF01uFF0EuFF1FuFF61"); defaultMap.put(FessConfig.QUERY_HIGHLIGHT_FRAGMENT_SIZE, "60"); diff --git a/src/main/java/org/codelibs/fess/mylasta/direction/FessProp.java b/src/main/java/org/codelibs/fess/mylasta/direction/FessProp.java index 1a741a69f..baa4f7514 100644 --- a/src/main/java/org/codelibs/fess/mylasta/direction/FessProp.java +++ b/src/main/java/org/codelibs/fess/mylasta/direction/FessProp.java @@ -909,14 +909,15 @@ default String[] getSupportedUploadedMediaExtentionsAsArray() { String getJobTemplateTitleData(); default String getJobTemplateTitle(final String type) { - if (Constants.WEB_CRAWLER_TYPE.equals(type)) { + switch (type) { + case Constants.WEB_CRAWLER_TYPE: return getJobTemplateTitleWeb(); - } - if (Constants.FILE_CRAWLER_TYPE.equals(type)) { + case Constants.FILE_CRAWLER_TYPE: return getJobTemplateTitleFile(); - } - if (Constants.DATA_CRAWLER_TYPE.equals(type)) { + case Constants.DATA_CRAWLER_TYPE: return getJobTemplateTitleData(); + default: + break; } return "None"; } @@ -1527,25 +1528,25 @@ default Map convertToStorableDoc(final Map sourc value = FessFunctions.parseDate(value.toString()); } } else if (integerFieldSet.contains(key)) { - if (value instanceof Number num) { + if (value instanceof final Number num) { value = num.intValue(); } else { value = DfTypeUtil.toInteger(value.toString()); } } else if (longFieldSet.contains(key)) { - if (value instanceof Number num) { + if (value instanceof final Number num) { value = num.longValue(); } else { value = DfTypeUtil.toLong(value.toString()); } } else if (floatFieldSet.contains(key)) { - if (value instanceof Number num) { + if (value instanceof final Number num) { value = num.floatValue(); } else { value = DfTypeUtil.toFloat(value.toString()); } } else if (doubleFieldSet.contains(key)) { - if (value instanceof Number num) { + if (value instanceof final Number num) { value = num.doubleValue(); } else { value = DfTypeUtil.toDouble(value.toString()); @@ -1855,7 +1856,7 @@ default boolean validateThumbnailSize(final int width, final int height) { } final float ratio = getThumbnailHtmlImageMaxAspectRatioAsDecimal().floatValue(); - if (((float) width) / ((float) height) > ratio || ((float) height) / ((float) width) > ratio) { + if ((float) width / (float) height > ratio || (float) height / (float) width > ratio) { return false; } diff --git a/src/main/java/org/codelibs/fess/mylasta/direction/sponsor/FessMultipartRequestHandler.java b/src/main/java/org/codelibs/fess/mylasta/direction/sponsor/FessMultipartRequestHandler.java index e4d5e899a..94353ad53 100644 --- a/src/main/java/org/codelibs/fess/mylasta/direction/sponsor/FessMultipartRequestHandler.java +++ b/src/main/java/org/codelibs/fess/mylasta/direction/sponsor/FessMultipartRequestHandler.java @@ -122,7 +122,7 @@ protected DiskFileItemFactory createDiskFileItemFactory() { } protected int getSizeThreshold() { - return ComponentUtil.getFessConfig().getHttpFileuploadThresholdSizeAsInteger().intValue(); + return ComponentUtil.getFessConfig().getHttpFileuploadThresholdSizeAsInteger(); } protected File createRepositoryFile() { @@ -308,9 +308,7 @@ protected void handleSizeLimitExceededException(final HttpServletRequest request final InputStream is = request.getInputStream(); try { final byte[] buf = new byte[1024]; - @SuppressWarnings("unused") - int len = 0; - while ((len = is.read(buf)) != -1) {} + while ((is.read(buf)) != -1) {} } catch (final Exception ignored) {} finally { try { is.close(); diff --git a/src/main/java/org/codelibs/fess/query/DefaultQueryBuilder.java b/src/main/java/org/codelibs/fess/query/DefaultQueryBuilder.java index b0682e2ef..a93710b5e 100644 --- a/src/main/java/org/codelibs/fess/query/DefaultQueryBuilder.java +++ b/src/main/java/org/codelibs/fess/query/DefaultQueryBuilder.java @@ -133,7 +133,7 @@ public boolean equals(final Object obj) { if (this == obj) { return true; } - if ((obj == null) || (getClass() != obj.getClass())) { + if (obj == null || getClass() != obj.getClass()) { return false; } final DefaultQueryBuilder other = (DefaultQueryBuilder) obj; diff --git a/src/main/java/org/codelibs/fess/query/QueryCommand.java b/src/main/java/org/codelibs/fess/query/QueryCommand.java index 6b70450c8..2aabf8d4c 100644 --- a/src/main/java/org/codelibs/fess/query/QueryCommand.java +++ b/src/main/java/org/codelibs/fess/query/QueryCommand.java @@ -120,7 +120,7 @@ protected DefaultQueryBuilder createDefaultQueryBuilder() { protected QueryBuilder buildMatchPhraseQuery(final String f, final String text) { final FessConfig fessConfig = ComponentUtil.getFessConfig(); if (text == null || text.length() != 1 - || (!fessConfig.getIndexFieldTitle().equals(f) && !fessConfig.getIndexFieldContent().equals(f))) { + || !fessConfig.getIndexFieldTitle().equals(f) && !fessConfig.getIndexFieldContent().equals(f)) { return QueryBuilders.matchPhraseQuery(f, text); } diff --git a/src/main/java/org/codelibs/fess/query/TermQueryCommand.java b/src/main/java/org/codelibs/fess/query/TermQueryCommand.java index 6eb86f157..1b8b5d959 100644 --- a/src/main/java/org/codelibs/fess/query/TermQueryCommand.java +++ b/src/main/java/org/codelibs/fess/query/TermQueryCommand.java @@ -72,17 +72,18 @@ protected QueryBuilder convertTermQuery(final FessConfig fessConfig, final Query if (fessConfig.getQueryReplaceTermWithPrefixQueryAsBoolean() && text.length() > 1 && text.endsWith("*")) { return convertPrefixQuery(fessConfig, context, termQuery, boost, field, text); } - if (DEFAULT_FIELD.equals(field)) { + switch (field) { + case DEFAULT_FIELD: return convertDefaultTermQuery(fessConfig, context, termQuery, boost, field, text); - } - if (SORT_FIELD.equals(field)) { + case SORT_FIELD: return convertSortQuery(fessConfig, context, termQuery, boost, field, text); - } - if (SITE_FIELD.equals(field)) { + case SITE_FIELD: return convertSiteQuery(fessConfig, context, termQuery, boost, field, text); + default: + break; } - if (INURL_FIELD.equals(field) || (StringUtil.equals(field, context.getDefaultField()) - && fessConfig.getIndexFieldUrl().equals(context.getDefaultField()))) { + if (INURL_FIELD.equals(field) + || StringUtil.equals(field, context.getDefaultField()) && fessConfig.getIndexFieldUrl().equals(context.getDefaultField())) { return convertWildcardQuery(fessConfig, context, termQuery, boost, field, text); } if (!isSearchField(field)) { diff --git a/src/main/java/org/codelibs/fess/query/TermRangeQueryCommand.java b/src/main/java/org/codelibs/fess/query/TermRangeQueryCommand.java index 5a547dcc6..48af83fe2 100644 --- a/src/main/java/org/codelibs/fess/query/TermRangeQueryCommand.java +++ b/src/main/java/org/codelibs/fess/query/TermRangeQueryCommand.java @@ -59,10 +59,10 @@ protected QueryBuilder convertTermRangeQuery(final QueryContext context, final T final StringBuilder queryBuf = new StringBuilder(); queryBuf.append(termRangeQuery.includesLower() ? '[' : '{'); final BytesRef lowerTerm = termRangeQuery.getLowerTerm(); - queryBuf.append(lowerTerm != null ? ("*".equals(Term.toString(lowerTerm)) ? "\\*" : Term.toString(lowerTerm)) : "*"); + queryBuf.append(lowerTerm != null ? "*".equals(Term.toString(lowerTerm)) ? "\\*" : Term.toString(lowerTerm) : "*"); queryBuf.append(" TO "); final BytesRef upperTerm = termRangeQuery.getUpperTerm(); - queryBuf.append(upperTerm != null ? ("*".equals(Term.toString(upperTerm)) ? "\\*" : Term.toString(upperTerm)) : "*"); + queryBuf.append(upperTerm != null ? "*".equals(Term.toString(upperTerm)) ? "\\*" : Term.toString(upperTerm) : "*"); queryBuf.append(termRangeQuery.includesUpper() ? ']' : '}'); final String origQuery = queryBuf.toString(); context.addFieldLog(Constants.DEFAULT_FIELD, origQuery); diff --git a/src/main/java/org/codelibs/fess/query/parser/QueryParser.java b/src/main/java/org/codelibs/fess/query/parser/QueryParser.java index aa715d0b4..5faefc3e1 100644 --- a/src/main/java/org/codelibs/fess/query/parser/QueryParser.java +++ b/src/main/java/org/codelibs/fess/query/parser/QueryParser.java @@ -60,7 +60,7 @@ protected org.apache.lucene.queryparser.classic.QueryParser createQueryParser() final LuceneQueryParser parser = new LuceneQueryParser(defaultField, analyzer); parser.setAllowLeadingWildcard(allowLeadingWildcard); LaRequestUtil.getOptionalRequest().ifPresent(req -> { - if (req.getAttribute(Constants.DEFAULT_QUERY_OPERATOR) instanceof String op) { + if (req.getAttribute(Constants.DEFAULT_QUERY_OPERATOR) instanceof final String op) { parser.setDefaultOperator(Operator.valueOf(op)); } else { parser.setDefaultOperator(defaultOperator); @@ -134,13 +134,13 @@ protected static class LuceneQueryParser extends org.apache.lucene.queryparser.c */ public LuceneQueryParser(final String f, final Analyzer a) { super(f, a); - this.defaultField = f; + defaultField = f; } @Override - protected Query getFieldQuery(final String field, final String queryText, boolean quoted) throws ParseException { + protected Query getFieldQuery(final String field, final String queryText, final boolean quoted) throws ParseException { final org.apache.lucene.search.Query query = super.getFieldQuery(field, queryText, quoted); - if (quoted && query instanceof TermQuery termQuery) { + if (quoted && query instanceof final TermQuery termQuery) { final Pair splitField = splitField(defaultField, field); if (defaultField.equals(splitField.cur)) { final PhraseQuery.Builder builder = new PhraseQuery.Builder(); @@ -151,10 +151,11 @@ protected Query getFieldQuery(final String field, final String queryText, boolea return query; } - protected Pair splitField(String defaultField, String field) { - int indexOf = field.indexOf(':'); - if (indexOf < 0) + protected Pair splitField(final String defaultField, final String field) { + final int indexOf = field.indexOf(':'); + if (indexOf < 0) { return new Pair<>(field, null); + } final String indexField = indexOf == 0 ? defaultField : field.substring(0, indexOf); final String extensionKey = field.substring(indexOf + 1); return new Pair<>(indexField, extensionKey); diff --git a/src/main/java/org/codelibs/fess/rank/fusion/RankFusionProcessor.java b/src/main/java/org/codelibs/fess/rank/fusion/RankFusionProcessor.java index 86a16b783..f3c6e6d2c 100644 --- a/src/main/java/org/codelibs/fess/rank/fusion/RankFusionProcessor.java +++ b/src/main/java/org/codelibs/fess/rank/fusion/RankFusionProcessor.java @@ -450,7 +450,7 @@ public String toString() { } public void setSeacher(final RankFusionSearcher searcher) { - this.searchers[0] = searcher; + searchers[0] = searcher; } public void register(final RankFusionSearcher searcher) { @@ -464,7 +464,7 @@ public void register(final RankFusionSearcher searcher) { if (executorService == null) { int numThreads = ComponentUtil.getFessConfig().getRankFusionThreadsAsInteger(); if (numThreads <= 0) { - numThreads = (Runtime.getRuntime().availableProcessors() * 3) / 2 + 1; + numThreads = Runtime.getRuntime().availableProcessors() * 3 / 2 + 1; } executorService = Executors.newFixedThreadPool(numThreads); } diff --git a/src/main/java/org/codelibs/fess/score/ScoreBooster.java b/src/main/java/org/codelibs/fess/score/ScoreBooster.java index 93626a4a1..ab5903e11 100644 --- a/src/main/java/org/codelibs/fess/score/ScoreBooster.java +++ b/src/main/java/org/codelibs/fess/score/ScoreBooster.java @@ -110,7 +110,7 @@ protected void flush() { } public int getPriority() { - return this.priority; + return priority; } public void setPriority(final int priority) { @@ -118,7 +118,7 @@ public void setPriority(final int priority) { } public void setRequestTimeout(final String bulkRequestTimeout) { - this.requestTimeout = bulkRequestTimeout; + requestTimeout = bulkRequestTimeout; } public void setRequestCacheSize(final int requestCacheSize) { diff --git a/src/main/java/org/codelibs/fess/sso/oic/OpenIdConnectAuthenticator.java b/src/main/java/org/codelibs/fess/sso/oic/OpenIdConnectAuthenticator.java index 5fb0924b4..827aaea14 100644 --- a/src/main/java/org/codelibs/fess/sso/oic/OpenIdConnectAuthenticator.java +++ b/src/main/java/org/codelibs/fess/sso/oic/OpenIdConnectAuthenticator.java @@ -53,13 +53,18 @@ import com.google.api.client.json.JsonFactory; import com.google.api.client.json.JsonParser; import com.google.api.client.json.JsonToken; -import com.google.api.client.json.jackson2.JacksonFactory; -import com.google.api.client.util.Base64; +import com.google.api.client.json.gson.GsonFactory; +import com.google.common.io.BaseEncoding; +import com.google.common.io.BaseEncoding.DecodingException; public class OpenIdConnectAuthenticator implements SsoAuthenticator { private static final Logger logger = LogManager.getLogger(OpenIdConnectAuthenticator.class); + private static final BaseEncoding BASE64_DECODER = BaseEncoding.base64().withSeparator("\n", 64); + + private static final BaseEncoding BASE64URL_DECODER = BaseEncoding.base64Url().withSeparator("\n", 64); + protected static final String OIC_AUTH_SERVER_URL = "oic.auth.server.url"; protected static final String OIC_CLIENT_ID = "oic.client.id"; @@ -76,7 +81,7 @@ public class OpenIdConnectAuthenticator implements SsoAuthenticator { protected final HttpTransport httpTransport = new NetHttpTransport(); - protected final JsonFactory jsonFactory = JacksonFactory.getDefaultInstance(); + protected final JsonFactory jsonFactory = GsonFactory.getDefaultInstance(); @PostConstruct public void init() { @@ -123,14 +128,28 @@ protected String getAuthUrl(final HttpServletRequest request) { .build(); } + protected byte[] decodeBase64(String base64String) { + if (base64String == null) { + return null; + } + try { + return BASE64_DECODER.decode(base64String); + } catch (IllegalArgumentException e) { + if (e.getCause() instanceof DecodingException) { + return BASE64URL_DECODER.decode(base64String.trim()); + } + throw e; + } + } + protected LoginCredential processCallback(final HttpServletRequest request, final String code) { try { final TokenResponse tr = getTokenUrl(code); final String[] jwt = ((String) tr.get("id_token")).split("\\."); - final String jwtHeader = new String(Base64.decodeBase64(jwt[0]), Constants.UTF_8_CHARSET); - final String jwtClaim = new String(Base64.decodeBase64(jwt[1]), Constants.UTF_8_CHARSET); - final String jwtSigniture = new String(Base64.decodeBase64(jwt[2]), Constants.UTF_8_CHARSET); + final String jwtHeader = new String(decodeBase64(jwt[0]), Constants.UTF_8_CHARSET); + final String jwtClaim = new String(decodeBase64(jwt[1]), Constants.UTF_8_CHARSET); + final String jwtSigniture = new String(decodeBase64(jwt[2]), Constants.UTF_8_CHARSET); if (logger.isDebugEnabled()) { logger.debug("jwtHeader: {}", jwtHeader); @@ -185,28 +204,21 @@ protected void parseJwtClaim(final String jwtClaim, final Map at } } - private Object parsePrimitive(JsonParser jsonParser) throws IOException { - JsonToken token = jsonParser.getCurrentToken(); - switch (token) { - case VALUE_STRING: - return jsonParser.getText(); - case VALUE_NUMBER_INT: - return jsonParser.getLongValue(); - case VALUE_NUMBER_FLOAT: - return jsonParser.getDoubleValue(); - case VALUE_TRUE: - return true; - case VALUE_FALSE: - return false; - case VALUE_NULL: - return null; - default: - return null; // Or throw an exception if unexpected token - } + protected Object parsePrimitive(final JsonParser jsonParser) throws IOException { + final JsonToken token = jsonParser.getCurrentToken(); + return switch (token) { + case VALUE_STRING -> jsonParser.getText(); + case VALUE_NUMBER_INT -> jsonParser.getLongValue(); + case VALUE_NUMBER_FLOAT -> jsonParser.getDoubleValue(); + case VALUE_TRUE -> true; + case VALUE_FALSE -> false; + case VALUE_NULL -> null; + default -> null; // Or throw an exception if unexpected token + }; } - private Object parseArray(JsonParser jsonParser) throws IOException { - List list = new ArrayList<>(); + protected Object parseArray(final JsonParser jsonParser) throws IOException { + final List list = new ArrayList<>(); while (jsonParser.nextToken() != JsonToken.END_ARRAY) { if (jsonParser.getCurrentToken() == JsonToken.START_OBJECT) { list.add(parseObject(jsonParser)); @@ -217,17 +229,13 @@ private Object parseArray(JsonParser jsonParser) throws IOException { } } - if (list.stream().allMatch(String.class::isInstance)) { - return list.toArray(new String[list.size()]); - } - return list; } - private Map parseObject(JsonParser jsonParser) throws IOException { - Map nestedMap = new HashMap<>(); + protected Map parseObject(final JsonParser jsonParser) throws IOException { + final Map nestedMap = new HashMap<>(); while (jsonParser.nextToken() != JsonToken.END_OBJECT) { - String fieldName = jsonParser.getCurrentName(); + final String fieldName = jsonParser.getCurrentName(); if (fieldName != null) { jsonParser.nextToken(); // Move to the value of the current field diff --git a/src/main/java/org/codelibs/fess/sso/spnego/SpnegoAuthenticator.java b/src/main/java/org/codelibs/fess/sso/spnego/SpnegoAuthenticator.java index fa8dc0c43..093c59d0f 100644 --- a/src/main/java/org/codelibs/fess/sso/spnego/SpnegoAuthenticator.java +++ b/src/main/java/org/codelibs/fess/sso/spnego/SpnegoAuthenticator.java @@ -173,7 +173,8 @@ public ServletContext getServletContext() { @Override public String getInitParameter(final String name) { - if (SpnegoHttpFilter.Constants.LOGGER_LEVEL.equals(name)) { + switch (name) { + case SpnegoHttpFilter.Constants.LOGGER_LEVEL: { final String logLevel = getProperty(SPNEGO_LOGGER_LEVEL, StringUtil.EMPTY); if (StringUtil.isNotBlank(logLevel)) { return logLevel; @@ -192,41 +193,32 @@ public String getInitParameter(final String name) { } return "0"; } - if (SpnegoHttpFilter.Constants.LOGIN_CONF.equals(name)) { + case SpnegoHttpFilter.Constants.LOGIN_CONF: return getResourcePath(getProperty(SPNEGO_LOGIN_CONF, "auth_login.conf")); - } - if (SpnegoHttpFilter.Constants.KRB5_CONF.equals(name)) { + case SpnegoHttpFilter.Constants.KRB5_CONF: return getResourcePath(getProperty(SPNEGO_KRB5_CONF, "krb5.conf")); - } - if (SpnegoHttpFilter.Constants.CLIENT_MODULE.equals(name)) { + case SpnegoHttpFilter.Constants.CLIENT_MODULE: return getProperty(SPNEGO_LOGIN_CLIENT_MODULE, "spnego-client"); - } - if (SpnegoHttpFilter.Constants.SERVER_MODULE.equals(name)) { + case SpnegoHttpFilter.Constants.SERVER_MODULE: return getProperty(SPNEGO_LOGIN_SERVER_MODULE, "spnego-server"); - } - if (SpnegoHttpFilter.Constants.PREAUTH_USERNAME.equals(name)) { + case SpnegoHttpFilter.Constants.PREAUTH_USERNAME: return getProperty(SPNEGO_PREAUTH_USERNAME, "username"); - } - if (SpnegoHttpFilter.Constants.PREAUTH_PASSWORD.equals(name)) { + case SpnegoHttpFilter.Constants.PREAUTH_PASSWORD: return getProperty(SPNEGO_PREAUTH_PASSWORD, "password"); - } - if (SpnegoHttpFilter.Constants.ALLOW_BASIC.equals(name)) { + case SpnegoHttpFilter.Constants.ALLOW_BASIC: return getProperty(SPNEGO_ALLOW_BASIC, "true"); - } - if (SpnegoHttpFilter.Constants.ALLOW_UNSEC_BASIC.equals(name)) { + case SpnegoHttpFilter.Constants.ALLOW_UNSEC_BASIC: return getProperty(SPNEGO_ALLOW_UNSECURE_BASIC, "true"); - } - if (SpnegoHttpFilter.Constants.PROMPT_NTLM.equals(name)) { + case SpnegoHttpFilter.Constants.PROMPT_NTLM: return getProperty(SPNEGO_PROMPT_NTLM, "true"); - } - if (SpnegoHttpFilter.Constants.ALLOW_LOCALHOST.equals(name)) { + case SpnegoHttpFilter.Constants.ALLOW_LOCALHOST: return getProperty(SPNEGO_ALLOW_LOCALHOST, "true"); - } - if (SpnegoHttpFilter.Constants.ALLOW_DELEGATION.equals(name)) { + case SpnegoHttpFilter.Constants.ALLOW_DELEGATION: return getProperty(SPNEGO_ALLOW_DELEGATION, "false"); - } - if (SpnegoHttpFilter.Constants.EXCLUDE_DIRS.equals(name)) { + case SpnegoHttpFilter.Constants.EXCLUDE_DIRS: return getProperty(SPNEGO_EXCLUDE_DIRS, StringUtil.EMPTY); + default: + break; } return null; } diff --git a/src/main/java/org/codelibs/fess/thumbnail/ThumbnailManager.java b/src/main/java/org/codelibs/fess/thumbnail/ThumbnailManager.java index 6377448c3..b566408a8 100644 --- a/src/main/java/org/codelibs/fess/thumbnail/ThumbnailManager.java +++ b/src/main/java/org/codelibs/fess/thumbnail/ThumbnailManager.java @@ -289,7 +289,7 @@ public boolean offer(final Map docMap) { } } if (logger.isDebugEnabled()) { - logger.debug("Thumbnail generator is not found: {}", (docMap != null ? docMap.get("url") : docMap)); + logger.debug("Thumbnail generator is not found: {}", docMap != null ? docMap.get("url") : docMap); } return false; } @@ -370,9 +370,9 @@ protected static class FilePurgeVisitor implements FileVisitor { this.basePath = basePath; this.imageExtention = imageExtention; this.expiry = expiry; - this.fessConfig = ComponentUtil.getFessConfig(); - this.maxPurgeSize = fessConfig.getPageThumbnailPurgeMaxFetchSizeAsInteger(); - this.searchEngineClient = ComponentUtil.getSearchEngineClient(); + fessConfig = ComponentUtil.getFessConfig(); + maxPurgeSize = fessConfig.getPageThumbnailPurgeMaxFetchSizeAsInteger(); + searchEngineClient = ComponentUtil.getSearchEngineClient(); } protected void deleteFiles() { diff --git a/src/main/java/org/codelibs/fess/thumbnail/impl/CommandGenerator.java b/src/main/java/org/codelibs/fess/thumbnail/impl/CommandGenerator.java index b44db2b4a..33547963e 100644 --- a/src/main/java/org/codelibs/fess/thumbnail/impl/CommandGenerator.java +++ b/src/main/java/org/codelibs/fess/thumbnail/impl/CommandGenerator.java @@ -65,11 +65,11 @@ protected void updateProperties() { final FessConfig fessConfig = ComponentUtil.getFessConfig(); final String commandTimeoutStr = fessConfig.getSystemProperty("thumbnail.command.timeout"); if (commandTimeoutStr != null) { - commandTimeout = Long.valueOf(commandTimeoutStr); + commandTimeout = Long.parseLong(commandTimeoutStr); } final String commandDestroyTimeoutStr = fessConfig.getSystemProperty("thumbnail.command.destroy.timeout"); if (commandDestroyTimeoutStr != null) { - commandDestroyTimeout = Long.valueOf(commandDestroyTimeoutStr); + commandDestroyTimeout = Long.parseLong(commandDestroyTimeoutStr); } } diff --git a/src/main/java/org/codelibs/fess/timer/MonitorTarget.java b/src/main/java/org/codelibs/fess/timer/MonitorTarget.java index e6749551c..126650f5c 100644 --- a/src/main/java/org/codelibs/fess/timer/MonitorTarget.java +++ b/src/main/java/org/codelibs/fess/timer/MonitorTarget.java @@ -37,8 +37,8 @@ protected StringBuilder append(final StringBuilder buf, final String key, final final Object value = supplier.get(); if (value == null) { tempBuf.append("null"); - } else if ((value instanceof Integer) || (value instanceof Long)) { - tempBuf.append((value)); + } else if (value instanceof Integer || value instanceof Long) { + tempBuf.append(value); } else if (value instanceof Short) { tempBuf.append(((Short) value).shortValue()); } else if (value instanceof double[]) { diff --git a/src/main/java/org/codelibs/fess/util/PrunedTag.java b/src/main/java/org/codelibs/fess/util/PrunedTag.java index 9e712e811..91e384430 100644 --- a/src/main/java/org/codelibs/fess/util/PrunedTag.java +++ b/src/main/java/org/codelibs/fess/util/PrunedTag.java @@ -78,7 +78,7 @@ public boolean equals(final Object obj) { if (this == obj) { return true; } - if ((obj == null) || (getClass() != obj.getClass())) { + if (obj == null || getClass() != obj.getClass()) { return false; } final PrunedTag other = (PrunedTag) obj; @@ -98,8 +98,8 @@ public void setCss(final String css) { } public void setAttr(final String name, final String value) { - this.attrName = name; - this.attrValue = value; + attrName = name; + attrValue = value; } @Override diff --git a/src/main/java/org/codelibs/fess/util/QueryResponseList.java b/src/main/java/org/codelibs/fess/util/QueryResponseList.java index df361bf84..b24634474 100644 --- a/src/main/java/org/codelibs/fess/util/QueryResponseList.java +++ b/src/main/java/org/codelibs/fess/util/QueryResponseList.java @@ -64,7 +64,7 @@ public class QueryResponseList implements List> { // for testing protected QueryResponseList(final List> documentList, final int start, final int pageSize, final int offset) { - this.parent = documentList; + parent = documentList; this.offset = offset; this.start = start; this.pageSize = pageSize; diff --git a/src/main/java/org/codelibs/fess/util/RenderDataUtil.java b/src/main/java/org/codelibs/fess/util/RenderDataUtil.java index 95442258a..8977a1fdd 100644 --- a/src/main/java/org/codelibs/fess/util/RenderDataUtil.java +++ b/src/main/java/org/codelibs/fess/util/RenderDataUtil.java @@ -33,7 +33,7 @@ public static void register(final RenderData data, final String key, final Objec if (value instanceof Entity) { data.register(key, BeanUtil.copyBeanToNewMap(value)); } else { - if ((value instanceof final Collection coll) && !coll.isEmpty()) { + if (value instanceof final Collection coll && !coll.isEmpty()) { // care performance for List that the most frequent pattern final Object first = coll instanceof List ? ((List) coll).get(0) : coll.iterator().next(); if (first instanceof Entity) { diff --git a/src/main/java/org/codelibs/fess/util/ResourceUtil.java b/src/main/java/org/codelibs/fess/util/ResourceUtil.java index 958679da0..be86d47b0 100644 --- a/src/main/java/org/codelibs/fess/util/ResourceUtil.java +++ b/src/main/java/org/codelibs/fess/util/ResourceUtil.java @@ -148,7 +148,7 @@ protected static Path getPath(final String root, final String base, final String try { final ServletContext servletContext = ComponentUtil.getComponent(ServletContext.class); final String webinfPath = servletContext.getRealPath("/" + root + base); - if ((webinfPath != null) && Files.exists(Paths.get(webinfPath))) { + if (webinfPath != null && Files.exists(Paths.get(webinfPath))) { return Paths.get(webinfPath, names); } } catch (final Throwable e) { diff --git a/src/test/java/org/codelibs/fess/sso/oic/OpenIdConnectAuthenticatorTest.java b/src/test/java/org/codelibs/fess/sso/oic/OpenIdConnectAuthenticatorTest.java index 1219c35b0..fbea59078 100644 --- a/src/test/java/org/codelibs/fess/sso/oic/OpenIdConnectAuthenticatorTest.java +++ b/src/test/java/org/codelibs/fess/sso/oic/OpenIdConnectAuthenticatorTest.java @@ -21,14 +21,17 @@ import java.util.HashMap; import java.util.Map; +import org.codelibs.fess.app.web.base.login.OpenIdConnectCredential; import org.codelibs.fess.unit.UnitFessTestCase; +import org.codelibs.fess.util.DocumentUtil; public class OpenIdConnectAuthenticatorTest extends UnitFessTestCase { public void test_parseJwtClaim() throws IOException { // Setup OpenIdConnectAuthenticator authenticator = new OpenIdConnectAuthenticator(); final Map attributes = new HashMap<>(); - String jwtClaim = "{\"sub\":\"1234567890\",\"name\":\"John Doe\",\"groups\":[\"group1\",\"group2\"]}"; + String jwtClaim = + "{\"email\":\"test@codelibs.org\",\"sub\":\"1234567890\",\"name\":\"John Doe\",\"groups\":[\"group1\",\"group2\"]}"; // Execute authenticator.parseJwtClaim(jwtClaim, attributes); @@ -38,9 +41,11 @@ public void test_parseJwtClaim() throws IOException { assertEquals("John Doe", attributes.get("name")); // Check groups array - assertTrue(attributes.get("groups") instanceof String[]); - String[] groupArray = (String[]) attributes.get("groups"); - assertArrayEquals(new String[] { "group1", "group2" }, groupArray); + final String[] groups = DocumentUtil.getValue(attributes, "groups", String[].class); + assertArrayEquals(new String[] { "group1", "group2" }, groups); + OpenIdConnectCredential credential = new OpenIdConnectCredential(attributes); + assertEquals("test@codelibs.org", credential.getUserId()); + assertArrayEquals(new String[] { "group1", "group2" }, credential.getUserGroups()); } }