fix #2848 Refactor code: Replace redundant conditions and enhance readability across several classes.

This commit is contained in:
Shinsuke Sugaya 2024-10-12 06:11:58 +09:00
parent 173a05dd23
commit 063a714370
70 changed files with 368 additions and 315 deletions

View file

@ -181,8 +181,8 @@ public class FessBoot extends TomcatBoot {
});
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);
}
}

View file

@ -120,7 +120,8 @@ public class SearchApiManager extends BaseApiManager {
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 @@ public class SearchApiManager extends BaseApiManager {
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 @@ public class SearchApiManager extends BaseApiManager {
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) {

View file

@ -319,17 +319,17 @@ public class AdminBackupAction extends FessAdminAction {
}
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 -> {

View file

@ -22,7 +22,6 @@ import java.net.URLDecoder;
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 @@ public class AdminDesignAction extends FessAdminAction {
public static String decodeJsp(final String value) {
return value.replaceAll("<%(?![@-])([\\s\\S]*?)%>", "&lt;%$1%&gt;").replaceAll("<%=([\\s\\S]*?)%>", "&lt;%=$1%&gt;")
.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);
}
}

View file

@ -304,8 +304,8 @@ public class AdminMaintenanceAction extends FessAdminAction {
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)));

View file

@ -144,12 +144,18 @@ public class AdminSchedulerAction extends FessAdminAction {
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('-', '_'));

View file

@ -191,7 +191,8 @@ public class AdminUpgradeAction extends FessAdminAction {
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 class AdminUpgradeAction extends FessAdminAction {
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 class AdminUpgradeAction extends FessAdminAction {
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 class AdminUpgradeAction extends FessAdminAction {
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 class AdminUpgradeAction extends FessAdminAction {
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 class AdminUpgradeAction extends FessAdminAction {
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 class AdminUpgradeAction extends FessAdminAction {
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 class AdminUpgradeAction extends FessAdminAction {
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 class AdminUpgradeAction extends FessAdminAction {
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 class AdminUpgradeAction extends FessAdminAction {
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 class AdminUpgradeAction extends FessAdminAction {
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 class AdminUpgradeAction extends FessAdminAction {
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 class AdminUpgradeAction extends FessAdminAction {
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 class AdminUpgradeAction extends FessAdminAction {
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 class AdminUpgradeAction extends FessAdminAction {
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 class AdminUpgradeAction extends FessAdminAction {
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 class AdminUpgradeAction extends FessAdminAction {
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 class AdminUpgradeAction extends FessAdminAction {
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 class AdminUpgradeAction extends FessAdminAction {
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 class AdminUpgradeAction extends FessAdminAction {
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 class AdminUpgradeAction extends FessAdminAction {
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 class AdminUpgradeAction extends FessAdminAction {
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 class AdminUpgradeAction extends FessAdminAction {
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 class AdminUpgradeAction extends FessAdminAction {
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 class AdminUpgradeAction extends FessAdminAction {
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 class AdminUpgradeAction extends FessAdminAction {
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 class AdminUpgradeAction extends FessAdminAction {
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 class AdminUpgradeAction extends FessAdminAction {
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 class AdminUpgradeAction extends FessAdminAction {
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 class AdminUpgradeAction extends FessAdminAction {
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 class AdminUpgradeAction extends FessAdminAction {
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 class AdminUpgradeAction extends FessAdminAction {
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 class AdminUpgradeAction extends FessAdminAction {
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 class AdminUpgradeAction extends FessAdminAction {
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 class AdminUpgradeAction extends FessAdminAction {
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 class AdminUpgradeAction extends FessAdminAction {
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());
}

View file

@ -120,7 +120,7 @@ public class ApiResult {
public ApiConfigsResponse<T> settings(final List<T> settings) {
this.settings = settings;
this.total = settings.size();
total = settings.size();
return this;
}

View file

@ -102,17 +102,17 @@ public class ApiAdminBackupAction extends FessApiAdminAction {
});
}
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;
}
}

View file

@ -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();
}

View file

@ -26,6 +26,7 @@ import org.codelibs.core.lang.StringUtil;
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 class OpenIdConnectCredential implements LoginCredential, FessCredential
@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() {

View file

@ -222,8 +222,8 @@ public abstract class AbstractFessFileTransformer extends AbstractTransformer im
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 @@ public abstract class AbstractFessFileTransformer extends AbstractTransformer im
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;

View file

@ -88,8 +88,8 @@ public interface FessTransformer {
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 @@ public interface FessTransformer {
default Map<String, Object> processFieldConfigs(final Map<String, Object> dataMap, final FieldConfigs fieldConfigs) {
final Map<String, Object> newDataMap = new LinkedHashMap<>();
for (Map.Entry<String, Object> e : dataMap.entrySet()) {
for (final Map.Entry<String, Object> 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());

View file

@ -396,8 +396,8 @@ public class FessXpathTransformer extends XpathTransformer implements FessTransf
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 class FessXpathTransformer extends XpathTransformer implements FessTransf
}
public void addConvertUrl(final String regex, final String replacement) {
this.convertUrlMap.put(regex, replacement);
convertUrlMap.put(regex, replacement);
}
}

View file

@ -27,12 +27,12 @@ public class FieldConfigs {
private final Map<String, String> params;
public FieldConfigs(Map<String, String> params) {
public FieldConfigs(final Map<String, String> params) {
this.params = params;
}
public OptionalThing<Config> getConfig(String fieldName) {
String value = params.get(fieldName);
public OptionalThing<Config> 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 class FieldConfigs {
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() {

View file

@ -94,7 +94,7 @@ public abstract class DictionaryFile<T extends DictionaryItem> {
protected int pageRangeSize;
public PagingList(final List<E> list, final int offset, final int size, final int allRecordCount) {
this.parent = list;
parent = list;
this.allRecordCount = allRecordCount;
pageSize = size;
currentPageNumber = offset / size + 1;

View file

@ -222,7 +222,7 @@ public class KuromojiFile extends DictionaryFile<KuromojiItem> {
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;

View file

@ -118,7 +118,7 @@ public class KuromojiItem extends DictionaryItem {
if (this == obj) {
return true;
}
if ((obj == null) || (getClass() != obj.getClass())) {
if (obj == null || getClass() != obj.getClass()) {
return false;
}
final KuromojiItem other = (KuromojiItem) obj;

View file

@ -236,7 +236,7 @@ public class CharMappingFile extends DictionaryFile<CharMappingItem> {
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;

View file

@ -102,7 +102,7 @@ public class CharMappingItem extends DictionaryItem {
if (this == obj) {
return true;
}
if ((obj == null) || (getClass() != obj.getClass())) {
if (obj == null || getClass() != obj.getClass()) {
return false;
}
final CharMappingItem other = (CharMappingItem) obj;

View file

@ -221,7 +221,7 @@ public class ProtwordsFile extends DictionaryFile<ProtwordsItem> {
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;

View file

@ -73,7 +73,7 @@ public class ProtwordsItem extends DictionaryItem {
if (this == obj) {
return true;
}
if ((obj == null) || (getClass() != obj.getClass())) {
if (obj == null || getClass() != obj.getClass()) {
return false;
}
final ProtwordsItem other = (ProtwordsItem) obj;

View file

@ -233,7 +233,7 @@ public class StemmerOverrideFile extends DictionaryFile<StemmerOverrideItem> {
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;

View file

@ -54,7 +54,7 @@ public class StemmerOverrideItem extends DictionaryItem {
}
public void setNewOutput(final String newOutputs) {
this.newOutput = newOutputs;
newOutput = newOutputs;
}
public String getInput() {
@ -83,7 +83,7 @@ public class StemmerOverrideItem extends DictionaryItem {
if (this == obj) {
return true;
}
if ((obj == null) || (getClass() != obj.getClass())) {
if (obj == null || getClass() != obj.getClass()) {
return false;
}
final StemmerOverrideItem other = (StemmerOverrideItem) obj;

View file

@ -221,7 +221,7 @@ public class StopwordsFile extends DictionaryFile<StopwordsItem> {
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;

View file

@ -73,7 +73,7 @@ public class StopwordsItem extends DictionaryItem {
if (this == obj) {
return true;
}
if ((obj == null) || (getClass() != obj.getClass())) {
if (obj == null || getClass() != obj.getClass()) {
return false;
}
final StopwordsItem other = (StopwordsItem) obj;

View file

@ -297,7 +297,7 @@ public class SynonymFile extends DictionaryFile<SynonymItem> {
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;

View file

@ -100,7 +100,7 @@ public class SynonymItem extends DictionaryItem {
if (this == obj) {
return true;
}
if ((obj == null) || (getClass() != obj.getClass())) {
if (obj == null || getClass() != obj.getClass()) {
return false;
}
final SynonymItem other = (SynonymItem) obj;

View file

@ -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() {

View file

@ -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;

View file

@ -248,11 +248,11 @@ public class SearchEngineClient implements Client {
}
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 class SearchEngineClient implements Client {
}
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 @@ public class SearchEngineClient implements Client {
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<String, Map<String, String>> result =
mapper.readValue(line, new TypeReference<Map<String, Map<String, String>>>() {
});
if (result.containsKey("index") || result.containsKey("update")) {
return line;
}
if (result.containsKey("delete")) {
return StringUtil.EMPTY;
}
} else {
final Map<String, Map<String, String>> result =
mapper.readValue(prev, new TypeReference<Map<String, Map<String, String>>>() {
});
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<String, Map<String, String>> result =
mapper.readValue(line, new TypeReference<Map<String, Map<String, String>>>() {
});
if (result.containsKey("index") || result.containsKey("update")) {
return line;
}
if (result.containsKey("delete")) {
return StringUtil.EMPTY;
}
} else {
final Map<String, Map<String, String>> result =
mapper.readValue(prev, new TypeReference<Map<String, Map<String, String>>>() {
});
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 class SearchEngineClient implements Client {
}
public SearchConditionBuilder scroll() {
this.isScroll = true;
isScroll = true;
return this;
}

View file

@ -299,21 +299,30 @@ public class DataConfig extends BsDataConfig implements CrawlingConfig {
private AuthScheme getAuthScheme(final Map<String, String> 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<String, String> 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;
}

View file

@ -59,13 +59,12 @@ public class WebAuthentication extends BsWebAuthentication {
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 @@ public class WebAuthentication extends BsWebAuthentication {
});
return new NTLMScheme(new JcifsEngine(props));
}
if (Constants.FORM.equals(scheme)) {
case Constants.FORM: {
final Map<String, String> parameterMap = ParameterUtil.parse(getParameters());
return new FormScheme(parameterMap);
}
default:
break;
}
return null;
}

View file

@ -172,14 +172,11 @@ public class WebConfig extends BsWebConfig implements CrawlingConfig {
}
final String userAgent = getUserAgent();
if (StringUtil.isNotBlank(userAgent)) {
if (userAgent.startsWith(Constants.CRAWLING_USER_AGENT_PREFIX) && userAgent.endsWith(Constants.CRAWLING_USER_AGENT_SUFFIX)) {
paramMap.put(Client.USER_AGENT, fessConfig.getUserAgentName());
} else {
paramMap.put(Client.USER_AGENT, userAgent);
}
} else {
if (!StringUtil.isNotBlank(userAgent) || (userAgent.startsWith(Constants.CRAWLING_USER_AGENT_PREFIX)
&& userAgent.endsWith(Constants.CRAWLING_USER_AGENT_SUFFIX))) {
paramMap.put(Client.USER_AGENT, fessConfig.getUserAgentName());
} else {
paramMap.put(Client.USER_AGENT, userAgent);
}
final List<WebAuthentication> webAuthList = webAuthenticationService.getWebAuthenticationList(getId());

View file

@ -87,8 +87,8 @@ public class StoredLtrQueryBuilder extends AbstractQueryBuilder<StoredLtrQueryBu
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();

View file

@ -32,7 +32,7 @@ public class ContainerNotAvailableException extends FessSystemException {
public ContainerNotAvailableException(final Throwable cause) {
super("Container is not avaiable.");
this.componentName = "container";
componentName = "container";
}
public String getComponentName() {

View file

@ -495,8 +495,7 @@ public class Crawler {
}
// 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<String> webConfigIdList = options.getWebConfigIdList();
final List<String> fileConfigIdList = options.getFileConfigIdList();

View file

@ -92,7 +92,7 @@ public class CrawlerLogHelper extends LogHelperImpl {
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 @@ public class CrawlerLogHelper extends LogHelperImpl {
} 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();
}

View file

@ -101,10 +101,10 @@ public class IndexingHelper {
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());
}
}

View file

@ -124,8 +124,8 @@ public class IntervalControlHelper {
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;

View file

@ -134,8 +134,8 @@ public class LabelTypeHelper extends AbstractConfigHelper {
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;

View file

@ -49,7 +49,7 @@ public class ProcessHelper {
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);
}
}

View file

@ -77,7 +77,7 @@ public class SearchHelper {
// Variable
//
protected SearchRequestParamsRewriter[] searchRequestParamsRewriters = new SearchRequestParamsRewriter[0];
protected SearchRequestParamsRewriter[] searchRequestParamsRewriters = {};
// ===================================================================================
// Method
@ -173,7 +173,7 @@ public class SearchHelper {
final OptionalThing<FessUserBean> userBean) {
final RankFusionProcessor rankFusionProcessor = ComponentUtil.getRankFusionProcessor();
final List<Map<String, Object>> 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 -> {

View file

@ -171,8 +171,8 @@ public class SuggestHelper {
}
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;
}

View file

@ -313,7 +313,7 @@ public class ViewHelper {
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 class ViewHelper {
final int size = fessConfig.getResponseMaxSitePathLengthAsInteger();
if (size > 3) {
return StringUtils.abbreviate(site, size);
} else if (size >= 0) {
}
if (size >= 0) {
return site;
}
}

View file

@ -43,7 +43,6 @@ import org.codelibs.fess.es.config.exentity.CrawlingConfig.Param.Config;
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 @@ public class WebFsIndexHelper {
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();

View file

@ -47,7 +47,7 @@ public class DocBoostMatcher {
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 class DocBoostMatcher {
return ((Long) value).floatValue();
}
if (value instanceof Float) {
return ((Float) value);
return (Float) value;
}
if (value instanceof Double) {
return ((Double) value).floatValue();

View file

@ -553,13 +553,13 @@ public class IndexUpdater extends Thread {
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);
}
}

View file

@ -124,12 +124,12 @@ public abstract class ExecJob {
}
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;
}

View file

@ -53,7 +53,7 @@ public class GenerateThumbnailJob extends ExecJob {
}
public GenerateThumbnailJob cleanup() {
this.cleanup = true;
cleanup = true;
return this;
}

View file

@ -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'. <br>
* The value is, e.g. 0 <br>
* The value is, e.g. -1 <br>
* @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}. <br>
* The value is, e.g. 0 <br>
* The value is, e.g. -1 <br>
* @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 @@ public interface FessConfig extends FessEnv, org.codelibs.fess.mylasta.direction
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");

View file

@ -909,14 +909,15 @@ public interface FessProp {
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 @@ public interface FessProp {
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 @@ public interface FessProp {
}
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;
}

View file

@ -122,7 +122,7 @@ public class FessMultipartRequestHandler implements MultipartRequestHandler {
}
protected int getSizeThreshold() {
return ComponentUtil.getFessConfig().getHttpFileuploadThresholdSizeAsInteger().intValue();
return ComponentUtil.getFessConfig().getHttpFileuploadThresholdSizeAsInteger();
}
protected File createRepositoryFile() {
@ -308,9 +308,7 @@ public class FessMultipartRequestHandler implements MultipartRequestHandler {
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();

View file

@ -133,7 +133,7 @@ public class DefaultQueryBuilder implements QueryBuilder {
if (this == obj) {
return true;
}
if ((obj == null) || (getClass() != obj.getClass())) {
if (obj == null || getClass() != obj.getClass()) {
return false;
}
final DefaultQueryBuilder other = (DefaultQueryBuilder) obj;

View file

@ -120,7 +120,7 @@ public abstract class QueryCommand {
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);
}

View file

@ -72,17 +72,18 @@ public class TermQueryCommand extends QueryCommand {
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)) {

View file

@ -59,10 +59,10 @@ public class TermRangeQueryCommand extends QueryCommand {
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);

View file

@ -60,7 +60,7 @@ public class QueryParser {
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 @@ public class QueryParser {
*/
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<String, String> splitField = splitField(defaultField, field);
if (defaultField.equals(splitField.cur)) {
final PhraseQuery.Builder builder = new PhraseQuery.Builder();
@ -151,10 +151,11 @@ public class QueryParser {
return query;
}
protected Pair<String, String> splitField(String defaultField, String field) {
int indexOf = field.indexOf(':');
if (indexOf < 0)
protected Pair<String, String> 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);

View file

@ -450,7 +450,7 @@ public class RankFusionProcessor implements AutoCloseable {
}
public void setSeacher(final RankFusionSearcher searcher) {
this.searchers[0] = searcher;
searchers[0] = searcher;
}
public void register(final RankFusionSearcher searcher) {
@ -464,7 +464,7 @@ public class RankFusionProcessor implements AutoCloseable {
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);
}

View file

@ -110,7 +110,7 @@ public abstract class ScoreBooster {
}
public int getPriority() {
return this.priority;
return priority;
}
public void setPriority(final int priority) {
@ -118,7 +118,7 @@ public abstract class ScoreBooster {
}
public void setRequestTimeout(final String bulkRequestTimeout) {
this.requestTimeout = bulkRequestTimeout;
requestTimeout = bulkRequestTimeout;
}
public void setRequestCacheSize(final int requestCacheSize) {

View file

@ -53,13 +53,18 @@ import com.google.api.client.http.javanet.NetHttpTransport;
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 @@ public class OpenIdConnectAuthenticator implements SsoAuthenticator {
.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 @@ public class OpenIdConnectAuthenticator implements SsoAuthenticator {
}
}
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<Object> list = new ArrayList<>();
protected Object parseArray(final JsonParser jsonParser) throws IOException {
final List<Object> list = new ArrayList<>();
while (jsonParser.nextToken() != JsonToken.END_ARRAY) {
if (jsonParser.getCurrentToken() == JsonToken.START_OBJECT) {
list.add(parseObject(jsonParser));
@ -217,17 +229,13 @@ public class OpenIdConnectAuthenticator implements SsoAuthenticator {
}
}
if (list.stream().allMatch(String.class::isInstance)) {
return list.toArray(new String[list.size()]);
}
return list;
}
private Map<String, Object> parseObject(JsonParser jsonParser) throws IOException {
Map<String, Object> nestedMap = new HashMap<>();
protected Map<String, Object> parseObject(final JsonParser jsonParser) throws IOException {
final Map<String, Object> 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

View file

@ -173,7 +173,8 @@ public class SpnegoAuthenticator implements SsoAuthenticator {
@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 class SpnegoAuthenticator implements SsoAuthenticator {
}
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;
}

View file

@ -289,7 +289,7 @@ public class ThumbnailManager {
}
}
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 @@ public class ThumbnailManager {
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() {

View file

@ -65,11 +65,11 @@ public class CommandGenerator extends BaseThumbnailGenerator {
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);
}
}

View file

@ -37,8 +37,8 @@ public abstract class MonitorTarget implements TimeoutTarget {
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[]) {

View file

@ -78,7 +78,7 @@ public class PrunedTag {
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 class PrunedTag {
}
public void setAttr(final String name, final String value) {
this.attrName = name;
this.attrValue = value;
attrName = name;
attrValue = value;
}
@Override

View file

@ -64,7 +64,7 @@ public class QueryResponseList implements List<Map<String, Object>> {
// for testing
protected QueryResponseList(final List<Map<String, Object>> documentList, final int start, final int pageSize, final int offset) {
this.parent = documentList;
parent = documentList;
this.offset = offset;
this.start = start;
this.pageSize = pageSize;

View file

@ -33,7 +33,7 @@ public class RenderDataUtil {
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) {

View file

@ -148,7 +148,7 @@ public class ResourceUtil {
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) {

View file

@ -21,14 +21,17 @@ import java.io.IOException;
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<String, Object> 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 class OpenIdConnectAuthenticatorTest extends UnitFessTestCase {
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());
}
}