From b2e7675f6a6b505a67fb6db502079d695325c7b6 Mon Sep 17 00:00:00 2001 From: trydofor Date: Wed, 18 Oct 2023 17:18:19 +0800 Subject: [PATCH] =?UTF-8?q?=E2=9C=A8=20customize=20terminal=20logger=20#14?= =?UTF-8?q?4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../codegen/ConstantEnumGenerator.java | 6 ++ .../faceless/jooqgen/WingsCodeGenerator.java | 34 ++++++++ .../faceless/util/FlywaveRevisionScanner.java | 1 + .../faceless/database/DataSourceContext.java | 5 ++ .../spring/conf/WingsBindAuthnConfigurer.java | 7 ++ .../spring/conf/WingsBindLoginConfigurer.java | 12 ++- .../slardar/context/TerminalInterceptor.java | 83 ++++++++++++++----- .../bean/SlardarTerminalConfiguration.java | 22 ++--- .../slardar/context/TerminalContext.java | 63 ++++++++++++-- .../api/AbstractApiAuthController.java | 4 +- 10 files changed, 191 insertions(+), 46 deletions(-) diff --git a/wings/faceless-codegen/src/main/java/pro/fessional/wings/faceless/codegen/ConstantEnumGenerator.java b/wings/faceless-codegen/src/main/java/pro/fessional/wings/faceless/codegen/ConstantEnumGenerator.java index f178ce390..fc80a6330 100644 --- a/wings/faceless-codegen/src/main/java/pro/fessional/wings/faceless/codegen/ConstantEnumGenerator.java +++ b/wings/faceless-codegen/src/main/java/pro/fessional/wings/faceless/codegen/ConstantEnumGenerator.java @@ -3,6 +3,7 @@ import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; +import org.jetbrains.annotations.Contract; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import pro.fessional.meepo.Meepo; @@ -87,21 +88,25 @@ public static class Builder { private String pkg; private final Map flt = new HashMap<>(); + @Contract("_->this") public Builder targetDirectory(File src) { this.src = src; return this; } + @Contract("_->this") public Builder targetDirectory(String src) { this.src = new File(src); return this; } + @Contract("_->this") public Builder targetPackage(String pkg) { this.pkg = pkg; return this; } + @Contract("_->this") public Builder excludeType(String... typ) { for (String s : typ) { this.flt.put(s, Boolean.FALSE); @@ -109,6 +114,7 @@ public Builder excludeType(String... typ) { return this; } + @Contract("_->this") public Builder includeType(String... typ) { for (String s : typ) { this.flt.put(s, Boolean.TRUE); diff --git a/wings/faceless-codegen/src/main/java/pro/fessional/wings/faceless/jooqgen/WingsCodeGenerator.java b/wings/faceless-codegen/src/main/java/pro/fessional/wings/faceless/jooqgen/WingsCodeGenerator.java index 0ec8e84ea..13d1f53e8 100644 --- a/wings/faceless-codegen/src/main/java/pro/fessional/wings/faceless/jooqgen/WingsCodeGenerator.java +++ b/wings/faceless-codegen/src/main/java/pro/fessional/wings/faceless/jooqgen/WingsCodeGenerator.java @@ -1,6 +1,8 @@ package pro.fessional.wings.faceless.jooqgen; import lombok.val; +import org.jetbrains.annotations.Contract; +import org.jetbrains.annotations.NotNull; import org.jooq.Converter; import org.jooq.codegen.GenerationTool; import org.jooq.meta.TableDefinition; @@ -90,18 +92,22 @@ public class WingsCodeGenerator { } + @NotNull public static Builder builder() { return builder(config()); } + @NotNull public static Builder builder(Configuration conf) { return new Builder(conf == null ? config() : conf); } + @NotNull public static Configuration config() { return config(WingsCodeGenerator.class.getResourceAsStream(JOOQ_XML)); } + @NotNull public static Configuration config(InputStream ins) { Objects.requireNonNull(ins); try (ins) { @@ -197,16 +203,19 @@ public Builder(Configuration conf) { /** * Whether to generate incrementally. That is, not to delete files that do not exist in this time. */ + @Contract("_->this") public Builder incremental(boolean t) { incr = t; return this; } + @Contract("_->this") public Builder setGlobalSuffix(String suffix) { this.suffix = suffix; return this; } + @Contract("_->this") public Builder setLiveDataByMax(boolean asMax) { WingsCodeGenConf.setLiveDataByMax(asMax); return this; @@ -223,11 +232,13 @@ public Configuration configuration() { return conf; } + @Contract("_->this") public Builder springRepository(boolean b) { this.conf.getGenerator().getGenerate().withSpringAnnotations(b); return this; } + @Contract("->this") public Builder h2() { jdbcDriver("org.h2.Driver"); databaseName("org.jooq.meta.h2.H2Database"); @@ -235,11 +246,13 @@ public Builder h2() { return this; } + @Contract("_->this") public Builder jdbcDriver(String str) { this.conf.getJdbc().setDriver(str); return this; } + @Contract("_->this") public Builder jdbcUrl(String str) { this.conf.getJdbc().setUrl(str); if (str.contains(":h2:")) { @@ -258,26 +271,31 @@ public Builder jdbcUrl(String str) { return this; } + @Contract("_->this") public Builder jdbcUser(String str) { this.conf.getJdbc().setUser(str); return this; } + @Contract("_->this") public Builder jdbcPassword(String str) { this.conf.getJdbc().setPassword(str); return this; } + @Contract("_->this") public Builder targetPackage(String str) { this.conf.getGenerator().getTarget().setPackageName(str); return this; } + @Contract("_->this") public Builder targetDirectory(String str) { this.conf.getGenerator().getTarget().setDirectory(str); return this; } + @Contract("_->this") public Builder databaseSchema(String str) { this.conf.getGenerator().getDatabase().setInputSchema(str); return this; @@ -317,6 +335,7 @@ public Builder databaseSchema(String str) { * @param str AbstractDatabase * @return Builder */ + @Contract("_->this") public Builder databaseName(String str) { this.conf.getGenerator().getDatabase().setName(str); return this; @@ -349,6 +368,7 @@ public Builder databaseIncludes(String... reg) { /** * append or replace configuration/generator/database/includes */ + @Contract("_,_->this") public Builder databaseIncludes(boolean append, String... reg) { final String join = String.join("|", reg); final Database db = this.conf.getGenerator().getDatabase(); @@ -374,6 +394,7 @@ public Builder databaseIncludes(boolean append, String... reg) { * @return Builder * @see Pattern#COMMENTS */ + @Contract("_->this") public Builder databaseExcludes(String... reg) { return databaseExcludes(false, reg); } @@ -381,6 +402,7 @@ public Builder databaseExcludes(String... reg) { /** * append or replace configuration/generator/database/excludes */ + @Contract("_,_->this") public Builder databaseExcludes(boolean append, String... reg) { final String join = String.join("|", reg); final Database db = this.conf.getGenerator().getDatabase(); @@ -415,6 +437,7 @@ public Builder databaseExcludes(boolean append, String... reg) { * @param str sql * @return Builder */ + @Contract("_->this") public Builder databaseVersionProvider(String str) { this.conf.getGenerator().getDatabase().setSchemaVersionProvider(str); return this; @@ -425,11 +448,13 @@ public Builder databaseVersionProvider(String str) { * * @return Builder */ + @Contract("->this") public Builder forceRegenerate() { this.conf.getGenerator().getDatabase().setSchemaVersionProvider(Null.Str); return this; } + @Contract("_,_->this") public Builder forcedType(String name, String type) { ForcedType ft = new ForcedType(); ft.setName(name); @@ -437,12 +462,14 @@ public Builder forcedType(String name, String type) { return forcedType(ft); } + @Contract("_->this") public Builder forcedType(ForcedType... ft) { final List fts = this.conf.getGenerator().getDatabase().getForcedTypes(); fts.addAll(Arrays.asList(ft)); return this; } + @Contract("_,_,_->this") public Builder forcedType(Class userType, Class> converter, String... reg) { ForcedType ft = new ForcedType() .withUserType(userType.getName()) @@ -459,23 +486,28 @@ public Builder forcedType(Class userType, Class> co * @param sortImport Replacing fully qualified references with import is only valid for wingsGenerator. * @return this */ + @Contract("_,_->this") public Builder forcedType(ForcedType ft, String sortImport) { WingsCodeGenConf.shortImport4Table(sortImport); return forcedType(ft); } + @Contract("_,_->this") public & CodeEnum> Builder forcedStrCodeEnum(Class en, String... reg) { return forcedJooqEnum(en, JooqCodeEnumConverter.class, reg); } + @Contract("_,_->this") public & ConstantEnum> Builder forcedIntConsEnum(Class en, String... reg) { return forcedJooqEnum(en, JooqConsEnumConverter.class, reg); } + @Contract("_->this") public Builder forcedLocale(String... reg) { return forcedType(Locale.class, JooqLocaleConverter.class, reg); } + @Contract("_->this") public Builder forcedZoneId(String... reg) { final String zid = ZoneId.class.getName(); final String exp = String.join("|", reg); @@ -492,12 +524,14 @@ public Builder forcedZoneId(String... reg) { return forcedType(ft1, ft2); } + @Contract("_->this") public Builder funSeqName(Function fn) { WingsJooqGenHelper.funSeqName.set(fn); return this; } // + @Contract("_,_,_->this") private > Builder forcedJooqEnum(Class userType, Class converter, String... reg) { final String cv = converter.getName(); ForcedType ft = new ForcedType() diff --git a/wings/faceless-flywave/src/main/java/pro/fessional/wings/faceless/util/FlywaveRevisionScanner.java b/wings/faceless-flywave/src/main/java/pro/fessional/wings/faceless/util/FlywaveRevisionScanner.java index f3c9bfb71..b5227be79 100644 --- a/wings/faceless-flywave/src/main/java/pro/fessional/wings/faceless/util/FlywaveRevisionScanner.java +++ b/wings/faceless-flywave/src/main/java/pro/fessional/wings/faceless/util/FlywaveRevisionScanner.java @@ -604,6 +604,7 @@ public Helper exclude(String info, Predicate exc) { return this; } + @NotNull public SortedMap scan() { TreeMap result = new TreeMap<>(); diff --git a/wings/faceless/src/main/java/pro/fessional/wings/faceless/database/DataSourceContext.java b/wings/faceless/src/main/java/pro/fessional/wings/faceless/database/DataSourceContext.java index e702440a2..7ff2d4bb0 100644 --- a/wings/faceless/src/main/java/pro/fessional/wings/faceless/database/DataSourceContext.java +++ b/wings/faceless/src/main/java/pro/fessional/wings/faceless/database/DataSourceContext.java @@ -1,5 +1,6 @@ package pro.fessional.wings.faceless.database; +import org.jetbrains.annotations.Contract; import org.jetbrains.annotations.NotNull; import org.springframework.jdbc.support.JdbcUtils; import org.springframework.jdbc.support.MetaDataAccessException; @@ -30,16 +31,19 @@ public DataSource getCurrent() { return current; } + @Contract("_->this") public DataSourceContext setCurrent(DataSource current) { this.current = current; return this; } + @Contract("->this") public DataSourceContext clearBackend() { backendMap.clear(); return this; } + @Contract("_,_->this") public DataSourceContext addBackend(String name, DataSource ds) { if (name != null && ds != null) { backendMap.put(name, ds); @@ -47,6 +51,7 @@ public DataSourceContext addBackend(String name, DataSource ds) { return this; } + @Contract("_->this") public DataSourceContext addBackend(Map map) { if (map != null) { backendMap.putAll(map); diff --git a/wings/slardar-sprint/src/main/java/pro/fessional/wings/slardar/spring/conf/WingsBindAuthnConfigurer.java b/wings/slardar-sprint/src/main/java/pro/fessional/wings/slardar/spring/conf/WingsBindAuthnConfigurer.java index 2973c3bd8..c22c31474 100644 --- a/wings/slardar-sprint/src/main/java/pro/fessional/wings/slardar/spring/conf/WingsBindAuthnConfigurer.java +++ b/wings/slardar-sprint/src/main/java/pro/fessional/wings/slardar/spring/conf/WingsBindAuthnConfigurer.java @@ -1,5 +1,6 @@ package pro.fessional.wings.slardar.spring.conf; +import org.jetbrains.annotations.Contract; import org.springframework.security.config.annotation.ObjectPostProcessor; import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; import org.springframework.security.config.annotation.authentication.configurers.userdetails.UserDetailsAwareConfigurer; @@ -21,31 +22,37 @@ public class WingsBindAuthnConfigurer extends User private WingsAuthCheckService wingsAuthCheckService; private boolean wingsBindAuthnProvider = true; + @Contract("_->this") public WingsBindAuthnConfigurer userDetailsService(U userDetailsService) { this.userDetailsService = userDetailsService; return this; } + @Contract("_->this") public WingsBindAuthnConfigurer withObjectPostProcessor(ObjectPostProcessor objectPostProcessor) { addObjectPostProcessor(objectPostProcessor); return this; } + @Contract("_->this") public WingsBindAuthnConfigurer passwordEncoder(PasswordEncoder passwordEncoder) { this.passwordEncoder = passwordEncoder; return this; } + @Contract("_->this") public WingsBindAuthnConfigurer userDetailsPasswordManager(UserDetailsPasswordService passwordManager) { this.userDetailsPasswordService = passwordManager; return this; } + @Contract("_->this") public WingsBindAuthnConfigurer wingsBindAuthnProvider(boolean bool) { this.wingsBindAuthnProvider = bool; return this; } + @Contract("_->this") public WingsBindAuthnConfigurer wingsAuthCheckService(WingsAuthCheckService wingsAuthCheckService) { this.wingsAuthCheckService = wingsAuthCheckService; return this; diff --git a/wings/slardar-sprint/src/main/java/pro/fessional/wings/slardar/spring/conf/WingsBindLoginConfigurer.java b/wings/slardar-sprint/src/main/java/pro/fessional/wings/slardar/spring/conf/WingsBindLoginConfigurer.java index 186ab1a9e..91a19f7cc 100644 --- a/wings/slardar-sprint/src/main/java/pro/fessional/wings/slardar/spring/conf/WingsBindLoginConfigurer.java +++ b/wings/slardar-sprint/src/main/java/pro/fessional/wings/slardar/spring/conf/WingsBindLoginConfigurer.java @@ -1,6 +1,7 @@ package pro.fessional.wings.slardar.spring.conf; import jakarta.servlet.http.HttpServletRequest; +import org.jetbrains.annotations.Contract; import org.springframework.context.ApplicationContext; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configurers.AbstractAuthenticationFilterConfigurer; @@ -44,27 +45,31 @@ public WingsBindLoginConfigurer loginPage(String loginPage) { return super.loginPage(loginPage); } + @Contract("_->this") public WingsBindLoginConfigurer loginForward(boolean forward) { ((LoginUrlAuthenticationEntryPoint) getAuthenticationEntryPoint()).setUseForward(forward); return this; } + @Contract("_->this") public WingsBindLoginConfigurer usernameParameter(String usernameParameter) { getAuthenticationFilter().setUsernameParameter(usernameParameter); return this; } - + @Contract("_->this") public WingsBindLoginConfigurer passwordParameter(String passwordParameter) { getAuthenticationFilter().setPasswordParameter(passwordParameter); return this; } + @Contract("_->this") public WingsBindLoginConfigurer failureForwardUrl(String forwardUrl) { failureHandler(new ForwardAuthenticationFailureHandler(forwardUrl)); return this; } + @Contract("_->this") public WingsBindLoginConfigurer successForwardUrl(String forwardUrl) { successHandler(new ForwardAuthenticationSuccessHandler(forwardUrl)); return this; @@ -77,26 +82,31 @@ public WingsBindLoginConfigurer successForwardUrl(String forwardUrl) { private Enum defaultAuthType = null; private final Map> authTypes = new HashMap<>(); + @Contract("_,_->this") public WingsBindLoginConfigurer bindAuthTypeToEnums(String type, Enum authType) { this.authTypes.put(type, authType); return this; } + @Contract("_->this") public WingsBindLoginConfigurer bindAuthTypeToEnums(Map> authType) { this.authTypes.putAll(authType); return this; } + @Contract("_->this") public WingsBindLoginConfigurer bindAuthTypeDefault(Enum authType) { this.defaultAuthType = authType; return this; } + @Contract("_->this") public WingsBindLoginConfigurer bindAuthTypeSource(WingsAuthTypeSource wingsAuthTypeSource) { this.wingsAuthTypeSource = wingsAuthTypeSource; return this; } + @Contract("_->this") public WingsBindLoginConfigurer bindAuthDetailsSource(WingsAuthDetailsSource wingsAuthDetailsSource) { this.wingsAuthDetailsSource = wingsAuthDetailsSource; return this; diff --git a/wings/slardar-webmvc/src/main/java/pro/fessional/wings/slardar/context/TerminalInterceptor.java b/wings/slardar-webmvc/src/main/java/pro/fessional/wings/slardar/context/TerminalInterceptor.java index d8615b487..8554f394f 100644 --- a/wings/slardar-webmvc/src/main/java/pro/fessional/wings/slardar/context/TerminalInterceptor.java +++ b/wings/slardar-webmvc/src/main/java/pro/fessional/wings/slardar/context/TerminalInterceptor.java @@ -6,6 +6,8 @@ import lombok.Setter; import lombok.extern.slf4j.Slf4j; import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; +import pro.fessional.mirana.best.DummyBlock; import pro.fessional.wings.slardar.context.TerminalContext.Builder; import pro.fessional.wings.slardar.context.TerminalContext.Context; import pro.fessional.wings.slardar.webmvc.AutoRegisterInterceptor; @@ -22,12 +24,13 @@ * @since 2019-11-16 */ @Slf4j +@Getter public class TerminalInterceptor implements AutoRegisterInterceptor { - @Getter private final List terminalBuilders = new ArrayList<>(); + private final List terminalLoggers = new ArrayList<>(); - @Setter @Getter + @Setter @NotNull private List excludePatterns = Collections.emptyList(); @@ -37,64 +40,102 @@ public void addTerminalBuilder(TerminalBuilder builder) { } } - @NotNull - public Builder buildTerminal(@NotNull HttpServletRequest request) { - final Builder builder = new Builder(); - for (TerminalBuilder build : terminalBuilders) { - build.build(builder, request); + public void addTerminalLogger(TerminalLogger logger) { + if (logger != null) { + terminalLoggers.add(logger); } - return builder; } /** * Login terminal, which must appear as a try-finally with logoutTerminal. */ - public Context loginTerminal(@NotNull HttpServletRequest request, @NotNull Builder builder) { + @NotNull + public Context loginTerminal(@NotNull HttpServletRequest request) { try { + final Builder builder = new Builder(); + for (TerminalBuilder build : terminalBuilders) { + build.build(builder, request); + } + + if (request.getAttribute(AttrTerminalLogin) == Boolean.TRUE) { + log.warn("should NOT loginTerminal more than once"); + } + else { + request.setAttribute(AttrTerminalLogin, Boolean.TRUE); + } + final Context ctx = builder.build(); TerminalContext.login(ctx); - request.setAttribute(AttrTerminalLogin, Boolean.TRUE); return ctx; } - catch (Exception e) { + catch (RuntimeException e) { log.error("should NOT be here", e); TerminalContext.logout(); - return null; + throw e; } } /** - * Logout terminal, and return whether the previous login was successful + * Logout terminal, and return the previous context if logined successfully */ - public boolean logoutTerminal(@NotNull HttpServletRequest request) { + @Nullable + public Context logoutTerminal(@NotNull HttpServletRequest request) { if (request.getAttribute(AttrTerminalLogin) == Boolean.TRUE) { - TerminalContext.logout(); - return true; + Context ctx = TerminalContext.logout(); + request.removeAttribute(AttrTerminalLogin); + return ctx; } else { - return false; + return null; } } - @Getter @Setter + @Setter private int order = OrderedSlardarConst.MvcTerminalInterceptor; @Override public boolean preHandle(@NotNull HttpServletRequest request, @NotNull HttpServletResponse response, @NotNull Object handler) { - final Builder builder = buildTerminal(request); - return loginTerminal(request, builder) != null; + final Context ctx = loginTerminal(request); + for (TerminalLogger log : terminalLoggers) { + try { + log.log(true, ctx, request, response, null); + } + catch (Exception e) { + DummyBlock.ignore(e); + } + } + return true; } @Override public void afterCompletion(@NotNull HttpServletRequest request, @NotNull HttpServletResponse response, @NotNull Object handler, Exception ex) { - logoutTerminal(request); + final Context ctx = logoutTerminal(request); + for (TerminalLogger log : terminalLoggers) { + try { + log.log(false, ctx, request, response, ex); + } + catch (Exception e) { + DummyBlock.ignore(e); + } + } } public interface TerminalBuilder { void build(@NotNull Builder builder, @NotNull HttpServletRequest request); } + + public interface TerminalLogger { + /** + * @param login login or logout + * @param context the context + * @param request the request + * @param response the response + * @param ex the exception if throw in afterCompletion + */ + void log(boolean login, @Nullable Context context, @NotNull HttpServletRequest request, @NotNull HttpServletResponse response, @Nullable Exception ex); + } } diff --git a/wings/slardar-webmvc/src/main/java/pro/fessional/wings/slardar/spring/bean/SlardarTerminalConfiguration.java b/wings/slardar-webmvc/src/main/java/pro/fessional/wings/slardar/spring/bean/SlardarTerminalConfiguration.java index 4cfbf47c8..7f2970c50 100644 --- a/wings/slardar-webmvc/src/main/java/pro/fessional/wings/slardar/spring/bean/SlardarTerminalConfiguration.java +++ b/wings/slardar-webmvc/src/main/java/pro/fessional/wings/slardar/spring/bean/SlardarTerminalConfiguration.java @@ -9,7 +9,6 @@ import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; -import org.springframework.context.i18n.TimeZoneAwareLocaleContext; import org.springframework.security.core.Authentication; import org.springframework.security.core.GrantedAuthority; import pro.fessional.wings.slardar.constants.SlardarServletConst; @@ -59,19 +58,10 @@ public TerminalInterceptor.TerminalBuilder securityTerminalBuilder(WingsLocaleRe final WingsUserDetails details = SecurityContextUtil.getUserDetails(authn); if (details == null) { final Long userId = (Long) request.getAttribute(SlardarServletConst.AttrUserId); - if (userId != null) { - TimeZoneAwareLocaleContext locale = resolver.resolveI18nContext(request, userId); - builder.locale(locale.getLocale()) - .timeZone(locale.getTimeZone()) - .user(userId); - } - else { - // The default value has the lowest priority - TimeZoneAwareLocaleContext locale = resolver.resolveI18nContext(request, null); - builder.localeIfAbsent(locale.getLocale()) - .timeZoneIfAbsent(locale.getTimeZone()) - .guest(); - } + final var locale = resolver.resolveI18nContext(request, userId); + builder.locale(locale.getLocale()) + .timeZone(locale.getTimeZone()) + .userOrGuest(userId); } else { builder.locale(details.getLocale()) @@ -90,11 +80,13 @@ public TerminalInterceptor.TerminalBuilder securityTerminalBuilder(WingsLocaleRe @Bean @ConditionalOnMissingBean(TerminalInterceptor.class) - public TerminalInterceptor terminalInterceptor(SlardarTerminalProp prop, ObjectProvider builders) { + public TerminalInterceptor terminalInterceptor(SlardarTerminalProp prop, ObjectProvider builders, ObjectProvider loggers) { log.info("SlardarWebmvc spring-bean terminalInterceptor"); final TerminalInterceptor bean = new TerminalInterceptor(); builders.orderedStream().forEach(bean::addTerminalBuilder); + loggers.orderedStream().forEach(bean::addTerminalLogger); + // final Map ex = prop.getExcludePatterns(); if (!ex.isEmpty()) { diff --git a/wings/slardar/src/main/java/pro/fessional/wings/slardar/context/TerminalContext.java b/wings/slardar/src/main/java/pro/fessional/wings/slardar/context/TerminalContext.java index 8794f8751..732c20a19 100644 --- a/wings/slardar/src/main/java/pro/fessional/wings/slardar/context/TerminalContext.java +++ b/wings/slardar/src/main/java/pro/fessional/wings/slardar/context/TerminalContext.java @@ -192,18 +192,20 @@ public static void login(@Nullable Context ctx) { } /** - * logout and fireContextChange + * logout the context and fireContextChange */ - public static void logout() { - logout(true); + @Nullable + public static Context logout() { + return logout(true); } /** - * logout and whether to fireContextChange + * logout the context and whether to fireContextChange * * @param fire whether to fireContextChange */ - public static void logout(boolean fire) { + @Nullable + public static Context logout(boolean fire) { final Context old = ContextLocal.get(); if (old != null) { ContextLocal.remove(); @@ -211,6 +213,7 @@ public static void logout(boolean fire) { fireContextChange(true, old); } } + return old; } private static void fireContextChange(boolean del, @NotNull Context ctx) { @@ -371,7 +374,8 @@ public int hashCode() { return Objects.hash(userId, locale, timeZone, terminal); } - @Override public String toString() { + @Override + public String toString() { return "Context{" + "userId=" + userId + ", locale=" + locale + @@ -391,11 +395,13 @@ public static class Builder { private final Set authPerm = new HashSet<>(); private final Map, Object> terminal = new HashMap<>(); + @Contract("_->this") public Builder locale(Locale lcl) { locale = lcl; return this; } + @Contract("_->this") public Builder localeIfAbsent(Locale lcl) { if (locale == null) { locale = lcl; @@ -403,11 +409,13 @@ public Builder localeIfAbsent(Locale lcl) { return this; } + @Contract("_->this") public Builder timeZone(TimeZone tz) { timeZone = tz; return this; } + @Contract("_->this") public Builder timeZoneIfAbsent(TimeZone tz) { if (timeZone == null) { timeZone = tz; @@ -415,11 +423,13 @@ public Builder timeZoneIfAbsent(TimeZone tz) { return this; } + @Contract("_->this") public Builder timeZone(ZoneId tz) { timeZone = TimeZone.getTimeZone(tz); return this; } + @Contract("_->this") public Builder timeZoneIfAbsent(ZoneId tz) { if (timeZone == null) { timeZone = TimeZone.getTimeZone(tz); @@ -427,36 +437,59 @@ public Builder timeZoneIfAbsent(ZoneId tz) { return this; } + @Contract("_->this") public Builder authType(Enum at) { authType = at; return this; } + @Contract("_->this") + public Builder authTypeIfAbsent(Enum at) { + if (authType == null) { + authType = at; + } + return this; + } + + @Contract("_->this") public Builder username(String un) { username = un; return this; } + @Contract("_->this") + public Builder usernameIfAbsent(String un) { + if (username == null) { + username = un; + } + return this; + } + + @Contract("_->this") public Builder authPerm(String pm) { authPerm.add(pm); return this; } + @Contract("_->this") public Builder authPerm(Collection pm) { authPerm.addAll(pm); return this; } + @Contract("_,_->this") public Builder terminal(TypedKey key, V value) { terminal.put(key, value); return this; } + @Contract("_,_->this") public Builder terminalIfAbsent(TypedKey key, V value) { terminal.putIfAbsent(key, value); return this; } + @Contract("_->this") public Builder terminal(Map, Object> kvs) { if (kvs != null) { terminal.putAll(kvs); @@ -464,6 +497,7 @@ public Builder terminal(Map, Object> kvs) { return this; } + @Contract("_->this") public Builder terminalIfAbsent(Map, Object> kvs) { if (kvs != null) { for (Map.Entry, Object> en : kvs.entrySet()) { @@ -473,15 +507,32 @@ public Builder terminalIfAbsent(Map, Object> kvs) { return this; } + @Contract("_->this") public Builder user(long uid) { userId = uid; return this; } + @Contract("_->this") + public Builder userIfAbsent(Long uid) { + if (userId == Null.userId && uid != null) { + userId = uid; + } + return this; + } + + @Contract("_->this") + public Builder userOrGuest(Long uid) { + userId = uid == null ? DefaultUserId.Guest : uid; + return this; + } + + @Contract("->this") public Builder guest() { return user(DefaultUserId.Guest); } + @NotNull public Context build() { if (userId == Null.userId) { throw new IllegalArgumentException("invalid userid"); diff --git a/wings/warlock-shadow/src/main/java/pro/fessional/wings/warlock/controller/api/AbstractApiAuthController.java b/wings/warlock-shadow/src/main/java/pro/fessional/wings/warlock/controller/api/AbstractApiAuthController.java index 625d11d3e..8d84ceb31 100644 --- a/wings/warlock-shadow/src/main/java/pro/fessional/wings/warlock/controller/api/AbstractApiAuthController.java +++ b/wings/warlock-shadow/src/main/java/pro/fessional/wings/warlock/controller/api/AbstractApiAuthController.java @@ -105,10 +105,8 @@ public void requestMapping(@NotNull HttpServletRequest request, @NotNull HttpSer } request.setAttribute(SlardarServletConst.AttrUserId, pass.getUserId()); - // - final TerminalContext.Builder builder = terminalInterceptor.buildTerminal(request); // NOTE can build authPerm by scope - final Context ctx = terminalInterceptor.loginTerminal(request, builder); + final Context ctx = terminalInterceptor.loginTerminal(request); boolean handled = false; try { entity.terminal = ctx;