index
int64
repo_id
string
file_path
string
content
string
0
java-sources/ai/yda-framework/rag-streaming-assistant-starter/0.1.0/ai/yda/framework/assistant/rag
java-sources/ai/yda-framework/rag-streaming-assistant-starter/0.1.0/ai/yda/framework/assistant/rag/autoconfigure/StreamingRagAssistantAutoConfiguration.java
/* * YDA - Open-Source Java AI Assistant. * Copyright (C) 2024 Love Vector OÜ <https://vector-inc.dev/> * This file is part of YDA. * YDA is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * YDA is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * You should have received a copy of the GNU Lesser General Public License * along with YDA. If not, see <https://www.gnu.org/licenses/>. */ package ai.yda.framework.assistant.rag.autoconfigure; import org.springframework.boot.autoconfigure.AutoConfiguration; import org.springframework.context.annotation.Bean; import ai.yda.framework.core.assistant.StreamingRagAssistant; import ai.yda.framework.rag.core.StreamingRag; import ai.yda.framework.rag.core.model.RagRequest; import ai.yda.framework.rag.core.model.RagResponse; /** * Autoconfiguration class for setting up a {@link StreamingRagAssistant} bean. This class is responsible for * automatically configuring a {@link StreamingRagAssistant} instance within the Spring application context. The * {@link StreamingRagAssistant} bean is created using a provided {@link StreamingRag} instance, which is injected as a * dependency. The configuration is applied automatically when the application starts, thanks to the * {@link AutoConfiguration} annotation. * <p> * This setup allows the {@link StreamingRagAssistant} to be readily available for use in the application wherever it's * needed, without requiring manual bean configuration. * </p> * * @author Nikita Litvinov * @see StreamingRagAssistant * @see StreamingRag * @since 0.1.0 */ @AutoConfiguration public class StreamingRagAssistantAutoConfiguration { /** * Default constructor for {@link StreamingRagAssistantAutoConfiguration}. */ public StreamingRagAssistantAutoConfiguration() {} /** * Creates and configures a {@link StreamingRagAssistant} bean in the Spring application context. * * @param rag the {@link StreamingRag} instance used by the {@link StreamingRagAssistant} to perform its operations. * This parameter is expected to be provided by the application or other autoconfiguration. * @return a configured {@link StreamingRagAssistant} bean. */ @Bean public StreamingRagAssistant streamingRagAssistant(final StreamingRag<RagRequest, RagResponse> rag) { return new StreamingRagAssistant(rag); } }
0
java-sources/ai/yda-framework/rag-streaming-starter/0.1.0/ai/yda/framework/rag
java-sources/ai/yda-framework/rag-streaming-starter/0.1.0/ai/yda/framework/rag/autoconfigure/StreamingRagAutoConfiguration.java
/* * YDA - Open-Source Java AI Assistant. * Copyright (C) 2024 Love Vector OÜ <https://vector-inc.dev/> * This file is part of YDA. * YDA is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * YDA is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * You should have received a copy of the GNU Lesser General Public License * along with YDA. If not, see <https://www.gnu.org/licenses/>. */ package ai.yda.framework.rag.autoconfigure; import java.util.List; import org.springframework.boot.autoconfigure.AutoConfiguration; import org.springframework.context.annotation.Bean; import ai.yda.framework.rag.core.DefaultStreamingRag; import ai.yda.framework.rag.core.augmenter.Augmenter; import ai.yda.framework.rag.core.generator.StreamingGenerator; import ai.yda.framework.rag.core.model.RagContext; import ai.yda.framework.rag.core.model.RagRequest; import ai.yda.framework.rag.core.model.RagResponse; import ai.yda.framework.rag.core.retriever.Retriever; /** * Autoconfiguration class for setting up a {@link DefaultStreamingRag} bean. This class provides the automatic * configuration for a {@link DefaultStreamingRag} instance, which is a key component in the Retrieval-Augmented * Generation (RAG) framework. The {@link DefaultStreamingRag} is configured with a list of Retrievers that fetch * relevant Context, Augmenters that enhance the Context, and a Generator that produces the final Response based on the * augmented Context. * * @author Nikita Litvinov * @see DefaultStreamingRag * @see Retriever * @see Augmenter * @see StreamingGenerator * @since 0.1.0 */ @AutoConfiguration public class StreamingRagAutoConfiguration { /** * Default constructor for {@link StreamingRagAutoConfiguration}. */ public StreamingRagAutoConfiguration() {} /** * Defines a {@link DefaultStreamingRag} bean, which is configured with the provided lists of {@link Retriever} and * {@link Augmenter}, along with the {@link StreamingGenerator} used to generate Responses. * * @param retrievers the list of {@link Retriever} beans used for retrieving Context based on the Request. * @param augmenters the list of {@link Augmenter} beans used for enhancing the retrieved Context. * @param generator the {@link StreamingGenerator} bean used for generating Responses in streaming manner based on * the augmented Context. * @return a configured {@link DefaultStreamingRag} instance. */ @Bean public DefaultStreamingRag defaultStreamingRag( final List<Retriever<RagRequest, RagContext>> retrievers, final List<Augmenter<RagRequest, RagContext>> augmenters, final StreamingGenerator<RagRequest, RagResponse> generator) { return new DefaultStreamingRag(retrievers, augmenters, generator); } }
0
java-sources/ai/yda-framework/rest-spring-channel/0.1.0/ai/yda/framework/channel/rest
java-sources/ai/yda-framework/rest-spring-channel/0.1.0/ai/yda/framework/channel/rest/spring/RestSpringAutoConfiguration.java
/* * YDA - Open-Source Java AI Assistant. * Copyright (C) 2024 Love Vector OÜ <https://vector-inc.dev/> * This file is part of YDA. * YDA is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * YDA is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * You should have received a copy of the GNU Lesser General Public License * along with YDA. If not, see <https://www.gnu.org/licenses/>. */ package ai.yda.framework.channel.rest.spring; import org.springframework.boot.autoconfigure.AutoConfiguration; import org.springframework.boot.context.properties.EnableConfigurationProperties; import org.springframework.context.annotation.Import; import ai.yda.framework.channel.rest.spring.security.SecurityConfiguration; import ai.yda.framework.channel.rest.spring.session.RestSessionProvider; import ai.yda.framework.channel.rest.spring.web.RestChannel; /** * Contains an autoconfiguration for the REST Channel in the Spring application. This class is responsible for * automatically configuring the necessary beans and components for the REST Channel, security and session management. * It simplifies the setup by ensuring that all the required configurations, properties, and components are loaded and * initialized without needing explicit configuration by the developer. It is loaded, initialized and imported without * developer's interference * * @author Nikita Litvinov * @see RestSpringProperties * @see RestChannel * @see SecurityConfiguration * @see RestSessionProvider * @since 0.1.0 */ @AutoConfiguration @EnableConfigurationProperties({RestSpringProperties.class}) @Import({RestChannel.class, SecurityConfiguration.class, RestSessionProvider.class}) public class RestSpringAutoConfiguration { /** * Default constructor for {@link RestSpringAutoConfiguration}. */ public RestSpringAutoConfiguration() {} }
0
java-sources/ai/yda-framework/rest-spring-channel/0.1.0/ai/yda/framework/channel/rest
java-sources/ai/yda-framework/rest-spring-channel/0.1.0/ai/yda/framework/channel/rest/spring/RestSpringProperties.java
/* * YDA - Open-Source Java AI Assistant. * Copyright (C) 2024 Love Vector OÜ <https://vector-inc.dev/> * This file is part of YDA. * YDA is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * YDA is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * You should have received a copy of the GNU Lesser General Public License * along with YDA. If not, see <https://www.gnu.org/licenses/>. */ package ai.yda.framework.channel.rest.spring; import org.springframework.boot.context.properties.ConfigurationProperties; import ai.yda.framework.channel.shared.RestChannelProperties; /** * Provides configuration properties for the REST Spring Channel. This class holds the configurable properties used in * the REST Channel. These properties can be customized through the application’s external configuration, such as * a properties file, YAML file, or environment variables. The properties include settings like the endpoint's relative * path and other configurations relevant to the REST API. * <p> * The properties are prefixed with {@link #CONFIG_PREFIX} and can be customized by defining values under this prefix * in the external configuration. Below are the properties that can be configured: * </p> * <pre> * Example configuration in a YAML file: * * ai: * yda: * framework: * channel: * rest: * spring: * endpointRelativePath: /api/v1 * securityToken: your-security-token * </pre> * * @author Nikita Litvinov * @since 0.1.0 */ @ConfigurationProperties(RestSpringProperties.CONFIG_PREFIX) public class RestSpringProperties extends RestChannelProperties { /** * The configuration prefix used to reference properties related to this Channel in application configurations. * This prefix is used for binding properties within the particular namespace. */ public static final String CONFIG_PREFIX = "ai.yda.framework.channel.rest.spring"; /** * Default constructor for {@link RestSpringProperties}. */ public RestSpringProperties() {} }
0
java-sources/ai/yda-framework/rest-spring-channel/0.1.0/ai/yda/framework/channel/rest/spring
java-sources/ai/yda-framework/rest-spring-channel/0.1.0/ai/yda/framework/channel/rest/spring/security/SecurityConfiguration.java
/* * YDA - Open-Source Java AI Assistant. * Copyright (C) 2024 Love Vector OÜ <https://vector-inc.dev/> * This file is part of YDA. * YDA is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * YDA is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * You should have received a copy of the GNU Lesser General Public License * along with YDA. If not, see <https://www.gnu.org/licenses/>. */ package ai.yda.framework.channel.rest.spring.security; import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer; import org.springframework.security.config.http.SessionCreationPolicy; import org.springframework.security.web.SecurityFilterChain; import org.springframework.security.web.authentication.AnonymousAuthenticationFilter; import org.springframework.web.cors.CorsConfiguration; import ai.yda.framework.channel.rest.spring.RestSpringProperties; /** * This is a Spring Security configuration that sets up security settings for the synchronized REST Channel. * * @author Nikita Litvinov * @see RestSpringProperties * @since 0.1.0 */ @Configuration @EnableWebSecurity public class SecurityConfiguration { /** * Default constructor for {@link SecurityConfiguration}. */ public SecurityConfiguration() {} /** * This Channel security configuration is used when 'security-token' property is configured. * <p> * Defines security filters, user authentication mechanisms, and authorization rules to control access to the * Channel. This configuration includes settings for {@link TokenAuthenticationFilter}, HTTP security configurations * such as enabling or disabling CORS, disabling CSRF, and setting the session management creation policy to always. * It also specifies authorization rules: requests to the endpoint are authorized and require authentication, while * all other requests are not authorized and do not require authentication. * </p> * * @param http the {@link HttpSecurity} to configure. * @param properties the {@link RestSpringProperties} containing configuration properties for the security setup. * @return a {@link SecurityFilterChain} instance configured with the specified HTTP security settings. * @throws Exception if an error occurs during configuration. */ @Bean @ConditionalOnProperty(prefix = RestSpringProperties.CONFIG_PREFIX, name = "security-token") public SecurityFilterChain combinedFilterChain(final HttpSecurity http, final RestSpringProperties properties) throws Exception { http.csrf(AbstractHttpConfigurer::disable) .authorizeHttpRequests(authorize -> authorize .requestMatchers(properties.getEndpointRelativePath()) .authenticated() .anyRequest() .permitAll()) .addFilterAfter( new TokenAuthenticationFilter(properties.getSecurityToken()), AnonymousAuthenticationFilter.class); configureCors(http, properties); configureSessionManagement(http); return http.build(); } /** * This Channel security configuration is used when 'security-token' property is not configured. * <p> * This configuration disables CSRF protection and CORS, and sets up authorization rules such that all HTTP requests * are permitted without authentication. * </p> * * @param http the {@link HttpSecurity} to configure. * @return a {@link SecurityFilterChain} instance configured with the specified HTTP security settings. * @throws Exception if an error occurs during configuration. */ @Bean @ConditionalOnMissingBean public SecurityFilterChain defaultFilterChain(final HttpSecurity http, final RestSpringProperties properties) throws Exception { http.csrf(AbstractHttpConfigurer::disable) .authorizeHttpRequests(authorize -> authorize.anyRequest().permitAll()); configureCors(http, properties); configureSessionManagement(http); return http.build(); } /** * Configures CORS with provided properties. * * @param http the {@link HttpSecurity} to configure. * @param properties for configuring CORS * @throws Exception if an error occurs during configuration. */ private void configureCors(final HttpSecurity http, final RestSpringProperties properties) throws Exception { if (properties.getCorsEnabled()) { http.cors(cors -> { var config = new CorsConfiguration(); config.setAllowedOrigins(properties.getAllowedOrigins()); config.setAllowedMethods(properties.getAllowedMethods()); config.setAllowCredentials(true); config.addAllowedHeader("*"); cors.configurationSource(request -> config); }); } else { http.cors(AbstractHttpConfigurer::disable); } } /** * Configures session management to always create a session and limits the number of sessions to 1. * * @param http the {@link HttpSecurity} to configure. * @throws Exception if an error occurs during configuration. */ private void configureSessionManagement(final HttpSecurity http) throws Exception { http.sessionManagement(sessionManagement -> sessionManagement .sessionCreationPolicy(SessionCreationPolicy.ALWAYS) .maximumSessions(1)); } }
0
java-sources/ai/yda-framework/rest-spring-channel/0.1.0/ai/yda/framework/channel/rest/spring
java-sources/ai/yda-framework/rest-spring-channel/0.1.0/ai/yda/framework/channel/rest/spring/security/TokenAuthenticationConverter.java
/* * YDA - Open-Source Java AI Assistant. * Copyright (C) 2024 Love Vector OÜ <https://vector-inc.dev/> * This file is part of YDA. * YDA is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * YDA is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * You should have received a copy of the GNU Lesser General Public License * along with YDA. If not, see <https://www.gnu.org/licenses/>. */ package ai.yda.framework.channel.rest.spring.security; import jakarta.servlet.http.HttpServletRequest; import org.springframework.http.HttpHeaders; import org.springframework.security.authentication.BadCredentialsException; import org.springframework.security.core.Authentication; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.security.web.authentication.AuthenticationConverter; import org.springframework.util.StringUtils; import ai.yda.framework.channel.shared.TokenAuthentication; /** * Provides strategy used for converting from a {@link HttpServletRequest} to an {@link TokenAuthentication}. Used to * authenticate with {@link TokenAuthenticationManager}. If the result is null, then it signals that no authentication * attempt should be made. * * @author Nikita Litvinov * @see TokenAuthentication * @since 0.1.0 */ public class TokenAuthenticationConverter implements AuthenticationConverter { /** * The authentication scheme used for Bearer tokens in the authorization header. This constant is used to indicate * that the token should be prefixed with the word "Bearer". */ private static final String AUTHENTICATION_SCHEME_BEARER = "Bearer"; /** * The starting position of the token in the authorization header. This constant represents the index from which the * actual token starts, after the "Bearer " prefix. */ private static final Short TOKEN_START_POSITION = 7; /** * Default constructor for {@link TokenAuthenticationConverter}. */ public TokenAuthenticationConverter() {} /** * Converts the given {@link HttpServletRequest} to an {@link TokenAuthentication}. If the result is null, then it * signals that no authentication attempt should be made. * * @param request the {@link HttpServletRequest} to be converted. * @return the {@link Authentication} that is a result of conversion or null if there is no authentication. */ @Override public Authentication convert(final HttpServletRequest request) { var authHeader = request.getHeader(HttpHeaders.AUTHORIZATION); if (authHeader == null) { return null; } authHeader = authHeader.trim(); if (!StringUtils.startsWithIgnoreCase(authHeader, AUTHENTICATION_SCHEME_BEARER)) { return null; } if (authHeader.equalsIgnoreCase(AUTHENTICATION_SCHEME_BEARER)) { throw new BadCredentialsException("Empty bearer authentication token"); } var token = authHeader.substring(TOKEN_START_POSITION); var currentAuthentication = SecurityContextHolder.getContextHolderStrategy().getContext().getAuthentication(); return currentAuthentication == null ? new TokenAuthentication(token) : new TokenAuthentication( token, currentAuthentication.getPrincipal(), currentAuthentication.getAuthorities()); } }
0
java-sources/ai/yda-framework/rest-spring-channel/0.1.0/ai/yda/framework/channel/rest/spring
java-sources/ai/yda-framework/rest-spring-channel/0.1.0/ai/yda/framework/channel/rest/spring/security/TokenAuthenticationFilter.java
/* * YDA - Open-Source Java AI Assistant. * Copyright (C) 2024 Love Vector OÜ <https://vector-inc.dev/> * This file is part of YDA. * YDA is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * YDA is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * You should have received a copy of the GNU Lesser General Public License * along with YDA. If not, see <https://www.gnu.org/licenses/>. */ package ai.yda.framework.channel.rest.spring.security; import java.io.IOException; import jakarta.servlet.FilterChain; import jakarta.servlet.ServletException; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; import lombok.RequiredArgsConstructor; import org.springframework.lang.NonNull; import org.springframework.security.authentication.AnonymousAuthenticationToken; import org.springframework.security.core.Authentication; import org.springframework.security.core.AuthenticationException; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.security.core.context.SecurityContextHolderStrategy; import org.springframework.security.web.authentication.AuthenticationConverter; import org.springframework.web.filter.OncePerRequestFilter; /** * Provides a Spring Security filter that processes authentication requests containing a Bearer token in the * Authorization header. The filter converts the Bearer token into an {@link Authentication} object and attempts to * authenticate it using the {@link TokenAuthenticationManager}. If the authentication is successful, the authenticated * user is stored in the {@link SecurityContextHolder}. * * @author Nikita Litvinov * @see TokenAuthenticationConverter * @see TokenAuthenticationManager * @since 0.1.0 */ @RequiredArgsConstructor public class TokenAuthenticationFilter extends OncePerRequestFilter { private final AuthenticationConverter authenticationConverter = new TokenAuthenticationConverter(); private final TokenAuthenticationManager authenticationManager; private final SecurityContextHolderStrategy securityContextHolderStrategy = SecurityContextHolder.getContextHolderStrategy(); /** * Constructs a new {@link TokenAuthenticationFilter} instance with the provided token. * * @param token the token used to authenticate incoming requests. */ public TokenAuthenticationFilter(final String token) { this.authenticationManager = new TokenAuthenticationManager(token); } /** * Processes the authentication request by extracting the Bearer token from the Authorization header, converting it * to an {@link Authentication} object, and attempting to authenticate it. The request and response is then * forwarded to the next filter in the chain. * * @param request the current {@link HttpServletRequest}. * @param response the current {@link HttpServletResponse}. * @param filterChain the {@link FilterChain} to proceed with the request processing. * @throws ServletException if an error occurs during the filtering process. * @throws IOException if an I/O error occurs during the filtering process. */ @Override protected void doFilterInternal( final @NonNull HttpServletRequest request, final @NonNull HttpServletResponse response, final @NonNull FilterChain filterChain) throws ServletException, IOException { try { var authRequest = this.authenticationConverter.convert(request); if (authRequest == null) { this.logger.trace("Did not process authentication request since failed" + " to find token in Bearer Authorization header"); filterChain.doFilter(request, response); return; } if (authenticationIsRequired(authRequest)) { var authResult = authenticationManager.authenticate(authRequest); securityContextHolderStrategy.getContext().setAuthentication(authResult); } } catch (final AuthenticationException ignored) { } filterChain.doFilter(request, response); } /** * Determines whether re-authentication is required based on the current authentication context. * * @param authentication the new {@link Authentication} request to be processed. * @return {@code true} if re-authentication is required and {@code false} otherwise. */ protected boolean authenticationIsRequired(final Authentication authentication) { // Only reauthenticate if token doesn't match SecurityContextHolder and user // isn't authenticated (see SEC-53) var currentAuthentication = securityContextHolderStrategy.getContext().getAuthentication(); if (currentAuthentication == null || !currentAuthentication.getCredentials().equals(authentication.getCredentials()) || !currentAuthentication.isAuthenticated()) { return true; } return (currentAuthentication instanceof AnonymousAuthenticationToken); } }
0
java-sources/ai/yda-framework/rest-spring-channel/0.1.0/ai/yda/framework/channel/rest/spring
java-sources/ai/yda-framework/rest-spring-channel/0.1.0/ai/yda/framework/channel/rest/spring/security/TokenAuthenticationManager.java
/* * YDA - Open-Source Java AI Assistant. * Copyright (C) 2024 Love Vector OÜ <https://vector-inc.dev/> * This file is part of YDA. * YDA is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * YDA is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * You should have received a copy of the GNU Lesser General Public License * along with YDA. If not, see <https://www.gnu.org/licenses/>. */ package ai.yda.framework.channel.rest.spring.security; import org.springframework.security.authentication.AuthenticationManager; import org.springframework.security.core.Authentication; import org.springframework.security.core.AuthenticationException; import ai.yda.framework.channel.shared.TokenAuthentication; import ai.yda.framework.channel.shared.TokenAuthenticationException; /** * Provides mechanism to processes an {@link Authentication} request with {@link TokenAuthentication}. * * @author Nikita Litvinov * @see TokenAuthentication * @since 0.1.0 */ public class TokenAuthenticationManager implements AuthenticationManager { private final Integer tokenKeyHash; /** * Constructs a new {@link TokenAuthenticationManager} instance with the provided token. * * @param token the token from which the key hash is extracted and stored for authentication purposes. */ public TokenAuthenticationManager(final String token) { this.tokenKeyHash = TokenAuthentication.extractKeyHash(token); } /** * Authenticates the given {@link Authentication} request by comparing its credentials with the stored token key * hash. * * @param authentication the {@link Authentication} request to be processed. * @return the authenticated {@link Authentication} object if the credentials match the token key hash. * @throws AuthenticationException if the credentials do not match the token key hash. */ @Override public Authentication authenticate(final Authentication authentication) throws AuthenticationException { if (tokenKeyHash.equals(authentication.getCredentials())) { return authentication; } throw new TokenAuthenticationException(); } }
0
java-sources/ai/yda-framework/rest-spring-channel/0.1.0/ai/yda/framework/channel/rest/spring
java-sources/ai/yda-framework/rest-spring-channel/0.1.0/ai/yda/framework/channel/rest/spring/session/RestSessionProvider.java
/* * YDA - Open-Source Java AI Assistant. * Copyright (C) 2024 Love Vector OÜ <https://vector-inc.dev/> * This file is part of YDA. * YDA is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * YDA is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * You should have received a copy of the GNU Lesser General Public License * along with YDA. If not, see <https://www.gnu.org/licenses/>. */ package ai.yda.framework.channel.rest.spring.session; import java.util.Optional; import jakarta.servlet.http.HttpSession; import org.springframework.stereotype.Component; import ai.yda.framework.session.core.SessionProvider; /** * Provides methods for storing and retrieving data associated with a Session using a key-value store in the REST * context. * <p> * This component interacts with the {@link HttpSession} to manage Session attributes. It provides methods to * add and retrieve objects from the Session based on a key. * </p> * * @author Nikita Litvinov * @since 0.1.0 */ @Component public class RestSessionProvider implements SessionProvider { private final HttpSession httpSession; /** * Constructs a new {@link RestSessionProvider} instance with the specified {@link HttpSession}. * * @param httpSession the {@link HttpSession} to be used for storing and retrieving Session attributes. */ public RestSessionProvider(final HttpSession httpSession) { this.httpSession = httpSession; } /** * Stores an object in the Session with the specified key. * * @param key the key with which the object is to be associated. * @param value the object to be stored in the Session. */ @Override public void put(final String key, final Object value) { httpSession.setAttribute(key, value); } /** * Retrieves an object from the Session associated with the specified key. * * @param key the key whose associated value is to be retrieved. * @return an {@link Optional} containing the value associated with the key, or an empty {@link Optional} if the key * does not exist in the Session. */ @Override public Optional<Object> get(final String key) { return Optional.ofNullable(httpSession.getAttribute(key)); } }
0
java-sources/ai/yda-framework/rest-spring-channel/0.1.0/ai/yda/framework/channel/rest/spring
java-sources/ai/yda-framework/rest-spring-channel/0.1.0/ai/yda/framework/channel/rest/spring/web/RestChannel.java
/* * YDA - Open-Source Java AI Assistant. * Copyright (C) 2024 Love Vector OÜ <https://vector-inc.dev/> * This file is part of YDA. * YDA is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * YDA is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * You should have received a copy of the GNU Lesser General Public License * along with YDA. If not, see <https://www.gnu.org/licenses/>. */ package ai.yda.framework.channel.rest.spring.web; import org.springframework.validation.annotation.Validated; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import ai.yda.framework.channel.core.Channel; import ai.yda.framework.channel.rest.spring.RestSpringProperties; import ai.yda.framework.core.assistant.Assistant; import ai.yda.framework.rag.core.model.RagRequest; import ai.yda.framework.rag.core.model.RagResponse; /** * Provides REST controller logic that handles incoming requests for processing using an assistant. The path of the * endpoint is configurable via properties, allowing for flexibility in deployment. * * @author Nikita Litvinov * @see Assistant * @since 0.1.0 */ @RestController @RequestMapping( path = "${" + RestSpringProperties.CONFIG_PREFIX + ".endpoint-relative-path:" + RestSpringProperties.DEFAULT_ENDPOINT_RELATIVE_PATH + "}") public class RestChannel implements Channel<RagRequest, RagResponse> { private final Assistant<RagRequest, RagResponse> assistant; /** * Constructs a new {@link RestChannel} instance with the specified {@link Assistant} instance. * * @param assistant the {@link Assistant} instance used to process {@link RagRequest} and generate * {@link RagResponse}. */ public RestChannel(final Assistant<RagRequest, RagResponse> assistant) { this.assistant = assistant; } /** * Processes the incoming {@link RagRequest} by delegating it to the {@link Assistant}. * * <p> * This method is mapped to the HTTP POST method and handles the logic for processing a validated * {@link RagRequest}. The request is passed to the assistant, which performs the necessary operations * to generate a {@link RagResponse}. * </p> * * @param ragRequest the {@link RagRequest} object containing the data to be processed. * @return the {@link RagResponse} object generated by the assistant. */ @Override @PostMapping public RagResponse processRequest(@RequestBody @Validated final RagRequest ragRequest) { return assistant.assist(ragRequest); } }
0
java-sources/ai/yda-framework/rest-spring-streaming-channel/0.1.0/ai/yda/framework/channel/rest/spring
java-sources/ai/yda-framework/rest-spring-streaming-channel/0.1.0/ai/yda/framework/channel/rest/spring/streaming/RestSpringStreamingAutoConfiguration.java
/* * YDA - Open-Source Java AI Assistant. * Copyright (C) 2024 Love Vector OÜ <https://vector-inc.dev/> * This file is part of YDA. * YDA is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * YDA is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * You should have received a copy of the GNU Lesser General Public License * along with YDA. If not, see <https://www.gnu.org/licenses/>. */ package ai.yda.framework.channel.rest.spring.streaming; import org.springframework.boot.autoconfigure.AutoConfiguration; import org.springframework.boot.context.properties.EnableConfigurationProperties; import org.springframework.context.annotation.Import; import ai.yda.framework.channel.rest.spring.streaming.security.SecurityConfiguration; import ai.yda.framework.channel.rest.spring.streaming.session.RestReactiveSessionProvider; import ai.yda.framework.channel.rest.spring.streaming.web.RestStreamingChannel; /** * Contains an autoconfiguration for the streaming REST Channel in the Spring application. This class is responsible for * automatically configuring the necessary beans and components required for the REST Channel, security and session * management. It simplifies the setup by ensuring that all the required configurations, properties, and components are * loaded and initialized without needing explicit configuration by the developer. It is loaded, initialized and * imported without developer's interference * * @author Nikita Litvinov * @see RestSpringStreamingProperties * @see RestStreamingChannel * @see SecurityConfiguration * @see RestReactiveSessionProvider * @since 0.1.0 */ @AutoConfiguration @EnableConfigurationProperties({RestSpringStreamingProperties.class}) @Import({RestStreamingChannel.class, SecurityConfiguration.class, RestReactiveSessionProvider.class}) public class RestSpringStreamingAutoConfiguration { /** * Default constructor for {@link RestSpringStreamingAutoConfiguration}. */ public RestSpringStreamingAutoConfiguration() {} }
0
java-sources/ai/yda-framework/rest-spring-streaming-channel/0.1.0/ai/yda/framework/channel/rest/spring
java-sources/ai/yda-framework/rest-spring-streaming-channel/0.1.0/ai/yda/framework/channel/rest/spring/streaming/RestSpringStreamingProperties.java
/* * YDA - Open-Source Java AI Assistant. * Copyright (C) 2024 Love Vector OÜ <https://vector-inc.dev/> * This file is part of YDA. * YDA is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * YDA is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * You should have received a copy of the GNU Lesser General Public License * along with YDA. If not, see <https://www.gnu.org/licenses/>. */ package ai.yda.framework.channel.rest.spring.streaming; import org.springframework.boot.context.properties.ConfigurationProperties; import ai.yda.framework.channel.shared.RestChannelProperties; /** * Provides configuration properties for the streaming REST Spring Channel. This class holds the configurable properties * used in the streaming REST Channel. These properties can be customized through the application’s external * configuration, such as a properties file, YAML file, or environment variables. The properties include settings like * the endpoint's relative path and other configurations relevant to the REST API. * <p> * The properties are prefixed with {@link #CONFIG_PREFIX} and can be customized by defining values under this prefix * in the external configuration.Below are the properties that can be configured: * </p> * <pre> * Example configuration in a YAML file: * * ai: * yda: * framework: * channel: * rest: * spring: * streaming: * endpointRelativePath: /api/v1 * securityToken: your-security-token * </pre> * * @author Nikita Litvinov * @since 0.1.0 */ @ConfigurationProperties(RestSpringStreamingProperties.CONFIG_PREFIX) public class RestSpringStreamingProperties extends RestChannelProperties { /** * The configuration prefix used to reference properties related to this Channel in application configurations. * This prefix is used for binding properties within the particular namespace. */ public static final String CONFIG_PREFIX = "ai.yda.framework.channel.rest.spring.streaming"; /** * Default constructor for {@link RestSpringStreamingProperties}. */ public RestSpringStreamingProperties() {} }
0
java-sources/ai/yda-framework/rest-spring-streaming-channel/0.1.0/ai/yda/framework/channel/rest/spring/streaming
java-sources/ai/yda-framework/rest-spring-streaming-channel/0.1.0/ai/yda/framework/channel/rest/spring/streaming/security/SecurityConfiguration.java
/* * YDA - Open-Source Java AI Assistant. * Copyright (C) 2024 Love Vector OÜ <https://vector-inc.dev/> * This file is part of YDA. * YDA is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * YDA is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * You should have received a copy of the GNU Lesser General Public License * along with YDA. If not, see <https://www.gnu.org/licenses/>. */ package ai.yda.framework.channel.rest.spring.streaming.security; import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.reactive.EnableWebFluxSecurity; import org.springframework.security.config.web.server.SecurityWebFiltersOrder; import org.springframework.security.config.web.server.ServerHttpSecurity; import org.springframework.security.web.server.SecurityWebFilterChain; import org.springframework.security.web.server.context.WebSessionServerSecurityContextRepository; import org.springframework.web.cors.CorsConfiguration; import ai.yda.framework.channel.rest.spring.streaming.RestSpringStreamingProperties; import ai.yda.framework.channel.rest.spring.streaming.session.SessionHandlerFilter; /** * This is a Web Flux Spring Security configuration that sets up security settings for the streaming REST Channel. * * @author Nikita Litvinov * @see RestSpringStreamingProperties * @since 0.1.0 */ @Configuration @EnableWebFluxSecurity public class SecurityConfiguration { /** * Default constructor for {@link SecurityConfiguration}. */ public SecurityConfiguration() {} /** * This Channel security configuration is used when 'security-token' property is configured. * <p> * Defines security filters, user authentication mechanisms, and authorization rules to control access to the * Channel. This configuration includes settings for {@link TokenAuthenticationFilter}, HTTP security configurations * such as enabling or disabling CORS, disabling CSRF, and adding the {@link SessionHandlerFilter} after an * AnonymousAuthenticationWebFilter. It also specifies authorization rules: requests to the endpoint are authorized * and require authentication, while all other requests are not authorized and do not require authentication. * </p> * * @param http the {@link ServerHttpSecurity} to configure. * @param properties the {@link RestSpringStreamingProperties} containing configuration properties for the security * setup. * @return a {@link SecurityWebFilterChain} instance configured with the specified HTTP security settings. */ @Bean @ConditionalOnProperty(prefix = RestSpringStreamingProperties.CONFIG_PREFIX, name = "security-token") public SecurityWebFilterChain filterChain( final ServerHttpSecurity http, final RestSpringStreamingProperties properties) { var securityContextRepository = new WebSessionServerSecurityContextRepository(); http.csrf(ServerHttpSecurity.CsrfSpec::disable) .authorizeExchange(exchange -> exchange.pathMatchers(properties.getEndpointRelativePath()) .authenticated() .anyExchange() .permitAll()) .securityContextRepository(securityContextRepository) .addFilterAfter( new TokenAuthenticationFilter(properties.getSecurityToken(), securityContextRepository), SecurityWebFiltersOrder.ANONYMOUS_AUTHENTICATION); configureCors(http, properties); configureSessionManagement(http); return http.build(); } /** * This Channel security configuration is used when 'security-token' property is not configured. * <p> * This configuration disables CSRF protection and CORS, and sets up authorization rules such that all HTTP requests * are permitted without authentication. * </p> * * @param http the {@link ServerHttpSecurity} to configure. * @return a {@link SecurityWebFilterChain} instance configured with the specified HTTP security settings. */ @Bean @ConditionalOnMissingBean public SecurityWebFilterChain defaultFilterChain( final ServerHttpSecurity http, final RestSpringStreamingProperties properties) { http.csrf(ServerHttpSecurity.CsrfSpec::disable) .authorizeExchange(exchange -> exchange.anyExchange().permitAll()) .securityContextRepository(new WebSessionServerSecurityContextRepository()); configureCors(http, properties); configureSessionManagement(http); return http.build(); } /** * Configures CORS with provided properties. * * @param http the {@link HttpSecurity} to configure. * @param properties for configuring CORS */ private void configureCors(final ServerHttpSecurity http, final RestSpringStreamingProperties properties) { if (properties.getCorsEnabled()) { http.cors(cors -> { var config = new CorsConfiguration(); config.setAllowedOrigins(properties.getAllowedOrigins()); config.setAllowedMethods(properties.getAllowedMethods()); config.setAllowCredentials(true); config.addAllowedHeader("*"); cors.configurationSource(request -> config); }); } else { http.cors(ServerHttpSecurity.CorsSpec::disable); } } /** * Adds the {@link SessionHandlerFilter} after an AnonymousAuthenticationWebFilter to handle session creation. * * @param http the {@link ServerHttpSecurity} to configure. */ private void configureSessionManagement(final ServerHttpSecurity http) { http.addFilterAfter(new SessionHandlerFilter(), SecurityWebFiltersOrder.ANONYMOUS_AUTHENTICATION); } }
0
java-sources/ai/yda-framework/rest-spring-streaming-channel/0.1.0/ai/yda/framework/channel/rest/spring/streaming
java-sources/ai/yda-framework/rest-spring-streaming-channel/0.1.0/ai/yda/framework/channel/rest/spring/streaming/security/TokenAuthenticationConverter.java
/* * YDA - Open-Source Java AI Assistant. * Copyright (C) 2024 Love Vector OÜ <https://vector-inc.dev/> * This file is part of YDA. * YDA is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * YDA is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * You should have received a copy of the GNU Lesser General Public License * along with YDA. If not, see <https://www.gnu.org/licenses/>. */ package ai.yda.framework.channel.rest.spring.streaming.security; import reactor.core.publisher.Mono; import org.springframework.http.HttpHeaders; import org.springframework.security.authentication.BadCredentialsException; import org.springframework.security.core.Authentication; import org.springframework.security.web.server.authentication.ServerAuthenticationConverter; import org.springframework.util.StringUtils; import org.springframework.web.server.ServerWebExchange; import ai.yda.framework.channel.shared.TokenAuthentication; /** * Provides strategy used for converting from a {@link ServerWebExchange} to an {@link Mono<TokenAuthentication>}. Used * to authenticate with {@link TokenAuthenticationManager}. If the result is null, then it signals that no * authentication attempt should be made. * * @author Nikita Litvinov * @see TokenAuthentication * @since 0.1.0 */ public class TokenAuthenticationConverter implements ServerAuthenticationConverter { /** * The authentication scheme used for Bearer tokens in the authorization header. This constant is used to indicate * that the token should be prefixed with the word "Bearer". */ private static final String AUTHENTICATION_SCHEME_BEARER = "Bearer"; /** * The starting position of the token in the authorization header. This constant represents the index from which the * actual token starts, after the "Bearer " prefix. */ private static final Short TOKEN_START_POSITION = 7; /** * Default constructor for {@link TokenAuthenticationConverter}. */ public TokenAuthenticationConverter() {} /** * Converts the given {@link ServerWebExchange} to an {@link Mono<TokenAuthentication>}. If the result is null, * then it signals that no authentication attempt should be made. * * @param exchange the {@link ServerWebExchange} to be converted. * @return the {@link Mono<Authentication>} that is a result of conversion or null if there is no authentication. */ @Override public Mono<Authentication> convert(final ServerWebExchange exchange) { var authHeaders = exchange.getRequest().getHeaders().get(HttpHeaders.AUTHORIZATION); if (authHeaders == null) { return Mono.empty(); } var authHeader = authHeaders.get(0).trim(); if (!StringUtils.startsWithIgnoreCase(authHeader, AUTHENTICATION_SCHEME_BEARER)) { return Mono.empty(); } if (authHeader.equalsIgnoreCase(AUTHENTICATION_SCHEME_BEARER)) { return Mono.error(new BadCredentialsException("Empty bearer authentication token")); } var token = authHeader.substring(TOKEN_START_POSITION); return Mono.just(new TokenAuthentication(token)); } }
0
java-sources/ai/yda-framework/rest-spring-streaming-channel/0.1.0/ai/yda/framework/channel/rest/spring/streaming
java-sources/ai/yda-framework/rest-spring-streaming-channel/0.1.0/ai/yda/framework/channel/rest/spring/streaming/security/TokenAuthenticationFilter.java
/* * YDA - Open-Source Java AI Assistant. * Copyright (C) 2024 Love Vector OÜ <https://vector-inc.dev/> * This file is part of YDA. * YDA is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * YDA is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * You should have received a copy of the GNU Lesser General Public License * along with YDA. If not, see <https://www.gnu.org/licenses/>. */ package ai.yda.framework.channel.rest.spring.streaming.security; import lombok.extern.slf4j.Slf4j; import reactor.core.publisher.Mono; import org.springframework.lang.NonNull; import org.springframework.security.core.Authentication; import org.springframework.security.core.context.ReactiveSecurityContextHolder; import org.springframework.security.core.context.SecurityContextImpl; import org.springframework.security.web.server.WebFilterExchange; import org.springframework.security.web.server.authentication.HttpBasicServerAuthenticationEntryPoint; import org.springframework.security.web.server.authentication.ServerAuthenticationEntryPointFailureHandler; import org.springframework.security.web.server.authentication.ServerAuthenticationFailureHandler; import org.springframework.security.web.server.authentication.ServerAuthenticationSuccessHandler; import org.springframework.security.web.server.authentication.WebFilterChainServerAuthenticationSuccessHandler; import org.springframework.security.web.server.context.ServerSecurityContextRepository; import org.springframework.web.server.ServerWebExchange; import org.springframework.web.server.WebFilter; import org.springframework.web.server.WebFilterChain; import ai.yda.framework.channel.shared.TokenAuthenticationException; /** * Provides a reactive Spring Security filter that processes authentication requests containing a Bearer token in the * Authorization header. The filter converts the Bearer token into an {@link Authentication} object and attempts to * authenticate it using the {@link TokenAuthenticationManager}. If the authentication is successful, the authenticated * user is stored in the {@link ServerSecurityContextRepository}. * * @author Nikita Litvinov * @see TokenAuthenticationConverter * @see TokenAuthenticationManager * @since 0.1.0 */ @Slf4j public class TokenAuthenticationFilter implements WebFilter { private final TokenAuthenticationConverter authenticationConverter = new TokenAuthenticationConverter(); private final TokenAuthenticationManager authenticationManager; private final ServerSecurityContextRepository securityContextRepository; private final ServerAuthenticationSuccessHandler authenticationSuccessHandler = new WebFilterChainServerAuthenticationSuccessHandler(); private final ServerAuthenticationFailureHandler authenticationFailureHandler = new ServerAuthenticationEntryPointFailureHandler(new HttpBasicServerAuthenticationEntryPoint()); /** * Constructs a new {@link TokenAuthenticationFilter} instance with the specified token and security context * repository. * * @param token the token used for authentication. * @param securityContextRepository the {@link ServerSecurityContextRepository} to manage the security context. */ public TokenAuthenticationFilter( final String token, final ServerSecurityContextRepository securityContextRepository) { this.authenticationManager = new TokenAuthenticationManager(token); this.securityContextRepository = securityContextRepository; } /** * Filters the request to authenticate the user based on the token. * <p> * This method attempts to convert the token from the request using {@link TokenAuthenticationConverter}. * If successful, it proceeds with authentication using {@link TokenAuthenticationManager}. Upon successful * authentication, it saves the security context and triggers the success handler. In case of authentication * failure, it invokes the failure handler. * </p> * * @param exchange the {@link ServerWebExchange} that contains the request and response objects. * @param chain the {@link WebFilterChain} that allows further processing of the request. * @return a {@link Mono<Void>} object. */ @NonNull @Override public Mono<Void> filter(@NonNull final ServerWebExchange exchange, @NonNull final WebFilterChain chain) { return this.authenticationConverter .convert(exchange) .switchIfEmpty(chain.filter(exchange).then(Mono.empty())) .flatMap(authenticationManager::authenticate) .flatMap(authentication -> onAuthenticationSuccess(authentication, new WebFilterExchange(exchange, chain))) .onErrorResume( TokenAuthenticationException.class, (exception) -> this.authenticationFailureHandler.onAuthenticationFailure( new WebFilterExchange(exchange, chain), exception)); } /** * Handles the success of authentication by saving the security context and invoking the success handler. * * @param authentication the successful {@link Authentication} result. * @param webFilterExchange the {@link WebFilterExchange} containing the current request and response. * @return a {@link Mono<Void>} object. */ protected Mono<Void> onAuthenticationSuccess( final Authentication authentication, final WebFilterExchange webFilterExchange) { ServerWebExchange exchange = webFilterExchange.getExchange(); SecurityContextImpl securityContext = new SecurityContextImpl(); securityContext.setAuthentication(authentication); return this.securityContextRepository .save(exchange, securityContext) .then(this.authenticationSuccessHandler.onAuthenticationSuccess(webFilterExchange, authentication)) .contextWrite(ReactiveSecurityContextHolder.withSecurityContext(Mono.just(securityContext))); } }
0
java-sources/ai/yda-framework/rest-spring-streaming-channel/0.1.0/ai/yda/framework/channel/rest/spring/streaming
java-sources/ai/yda-framework/rest-spring-streaming-channel/0.1.0/ai/yda/framework/channel/rest/spring/streaming/security/TokenAuthenticationManager.java
/* * YDA - Open-Source Java AI Assistant. * Copyright (C) 2024 Love Vector OÜ <https://vector-inc.dev/> * This file is part of YDA. * YDA is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * YDA is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * You should have received a copy of the GNU Lesser General Public License * along with YDA. If not, see <https://www.gnu.org/licenses/>. */ package ai.yda.framework.channel.rest.spring.streaming.security; import reactor.core.publisher.Mono; import org.springframework.security.authentication.ReactiveAuthenticationManager; import org.springframework.security.core.Authentication; import org.springframework.security.core.AuthenticationException; import ai.yda.framework.channel.shared.TokenAuthentication; import ai.yda.framework.channel.shared.TokenAuthenticationException; /** * Provide mechanism to processes an {@link Authentication} request with {@link TokenAuthentication} in the reactive * manner. * * @author Nikita Litvinov * @see TokenAuthentication * @since 0.1.0 */ public class TokenAuthenticationManager implements ReactiveAuthenticationManager { private final Integer tokenKeyHash; /** * Constructs a new {@link TokenAuthenticationManager} instance with the provided token. * * @param token the token from which the key hash is extracted and stored for authentication purposes. */ public TokenAuthenticationManager(final String token) { this.tokenKeyHash = TokenAuthentication.extractKeyHash(token); } /** * Authenticates the given {@link Authentication} request by comparing its credentials with the stored token key * hash. * * @param authentication the {@link Authentication} request to be processed. * @return the authenticated {@link Mono<Authentication>} object if the credentials match the token key hash. * @throws AuthenticationException if the credentials do not match the token key hash. */ @Override public Mono<Authentication> authenticate(final Authentication authentication) throws AuthenticationException { if (tokenKeyHash.equals(authentication.getCredentials())) { return Mono.just(authentication); } return Mono.error(new TokenAuthenticationException()); } }
0
java-sources/ai/yda-framework/rest-spring-streaming-channel/0.1.0/ai/yda/framework/channel/rest/spring/streaming
java-sources/ai/yda-framework/rest-spring-streaming-channel/0.1.0/ai/yda/framework/channel/rest/spring/streaming/session/RestReactiveSessionProvider.java
/* * YDA - Open-Source Java AI Assistant. * Copyright (C) 2024 Love Vector OÜ <https://vector-inc.dev/> * This file is part of YDA. * YDA is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * YDA is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * You should have received a copy of the GNU Lesser General Public License * along with YDA. If not, see <https://www.gnu.org/licenses/>. */ package ai.yda.framework.channel.rest.spring.streaming.session; import reactor.core.publisher.Mono; import org.springframework.stereotype.Component; import org.springframework.web.server.WebSession; import ai.yda.framework.session.core.ReactiveSessionProvider; /** * Provides methods for storing and retrieving data associated with a Session using a key-value store within a REST * context in a reactive manner. * * @author Nikita Litvinov * @since 0.1.0 */ @Component public class RestReactiveSessionProvider implements ReactiveSessionProvider { /** * Default constructor for {@link RestReactiveSessionProvider}. */ public RestReactiveSessionProvider() {} /** * Stores an object in the Session with the specified key. * * @param key the key with which the object is to be associated. * @param value the object to be stored in the Session. */ @Override public Mono<Void> put(final String key, final Object value) { return Mono.deferContextual(contextView -> { var session = contextView.getOrEmpty(WebSession.class); session.ifPresent(s -> ((WebSession) s).getAttributes().put(key, value)); return Mono.empty(); }); } /** * Retrieves an object from the Session associated with the specified key. * * @param key the key whose associated value is to be retrieved. * @return an {@link Mono<Object>} containing the value associated with the key, or an empty {@link Mono} if the key * does not exist in the Session. */ @Override public Mono<Object> get(final String key) { return Mono.deferContextual(contextView -> { var session = contextView.getOrEmpty(WebSession.class); return session.map(s -> { var attributes = ((WebSession) s).getAttributes(); return attributes.containsKey(key) ? Mono.just(attributes.get(key)) : Mono.empty(); }) .orElseGet(Mono::empty); }); } }
0
java-sources/ai/yda-framework/rest-spring-streaming-channel/0.1.0/ai/yda/framework/channel/rest/spring/streaming
java-sources/ai/yda-framework/rest-spring-streaming-channel/0.1.0/ai/yda/framework/channel/rest/spring/streaming/session/SessionHandlerFilter.java
/* * YDA - Open-Source Java AI Assistant. * Copyright (C) 2024 Love Vector OÜ <https://vector-inc.dev/> * This file is part of YDA. * YDA is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * YDA is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * You should have received a copy of the GNU Lesser General Public License * along with YDA. If not, see <https://www.gnu.org/licenses/>. */ package ai.yda.framework.channel.rest.spring.streaming.session; import reactor.core.publisher.Mono; import reactor.util.context.Context; import org.springframework.lang.NonNull; import org.springframework.web.server.ServerWebExchange; import org.springframework.web.server.WebFilter; import org.springframework.web.server.WebFilterChain; import org.springframework.web.server.WebSession; /** * Detects if a {@link WebSession} for the current {@link ServerWebExchange} has been started and starts one if it's * not. * * @author Nikita Litvinov * @since 0.1.0 */ public class SessionHandlerFilter implements WebFilter { /** * Default constructor for {@link SessionHandlerFilter}. */ public SessionHandlerFilter() {} /** * {@inheritDoc} */ @NonNull @Override public Mono<Void> filter(@NonNull final ServerWebExchange exchange, @NonNull final WebFilterChain chain) { return exchange.getSession().flatMap(webSession -> { if (!webSession.isStarted()) { webSession.start(); } return chain.filter(exchange).contextWrite(Context.of(WebSession.class, webSession)); }); } }
0
java-sources/ai/yda-framework/rest-spring-streaming-channel/0.1.0/ai/yda/framework/channel/rest/spring/streaming
java-sources/ai/yda-framework/rest-spring-streaming-channel/0.1.0/ai/yda/framework/channel/rest/spring/streaming/web/RestStreamingChannel.java
/* * YDA - Open-Source Java AI Assistant. * Copyright (C) 2024 Love Vector OÜ <https://vector-inc.dev/> * This file is part of YDA. * YDA is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * YDA is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * You should have received a copy of the GNU Lesser General Public License * along with YDA. If not, see <https://www.gnu.org/licenses/>. */ package ai.yda.framework.channel.rest.spring.streaming.web; import reactor.core.publisher.Flux; import org.springframework.http.MediaType; import org.springframework.validation.annotation.Validated; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import ai.yda.framework.channel.core.StreamingChannel; import ai.yda.framework.channel.rest.spring.streaming.RestSpringStreamingProperties; import ai.yda.framework.core.assistant.StreamingAssistant; import ai.yda.framework.rag.core.model.RagRequest; import ai.yda.framework.rag.core.model.RagResponse; /** * Provides REST controller logic that handles incoming requests for processing using a streaming assistant. The path * of the endpoint is configurable via properties, allowing for flexibility in deployment. * * @author Nikita Litvinov * @see StreamingAssistant * @since 0.1.0 */ @RestController @RequestMapping( path = "${" + RestSpringStreamingProperties.CONFIG_PREFIX + ".endpoint-relative-path:" + RestSpringStreamingProperties.DEFAULT_ENDPOINT_RELATIVE_PATH + "}") public class RestStreamingChannel implements StreamingChannel<RagRequest, RagResponse> { private final StreamingAssistant<RagRequest, RagResponse> assistant; /** * Constructs a new {@link RestStreamingChannel} instance with the specified {@link StreamingAssistant} instance. * * @param assistant the {@link StreamingAssistant} instance used to process {@link RagRequest} and generate * {@link RagResponse} in streaming manner. */ public RestStreamingChannel(final StreamingAssistant<RagRequest, RagResponse> assistant) { this.assistant = assistant; } /** * Processes the incoming {@link RagRequest} by delegating it to the {@link StreamingAssistant}. This method is * mapped to the HTTP POST method and handles the logic for processing a validated {@link RagRequest}. The request * is passed to the streaming assistant, which performs the necessary operations to generate a {@link RagResponse}. * * @param ragRequest the {@link RagRequest} object containing the data to be processed. * @return the {@link Flux stream} of {@link RagResponse} objects generated by the assistant. */ @Override @PostMapping(produces = MediaType.TEXT_EVENT_STREAM_VALUE) public Flux<RagResponse> processRequest(@RequestBody @Validated final RagRequest ragRequest) { return assistant.streamAssistance(ragRequest); } }
0
java-sources/ai/yda-framework/retriever-shared-starter/0.1.0/ai/yda/framework/rag/retriever
java-sources/ai/yda-framework/retriever-shared-starter/0.1.0/ai/yda/framework/rag/retriever/shared/MilvusVectorStoreUtil.java
/* * YDA - Open-Source Java AI Assistant. * Copyright (C) 2024 Love Vector OÜ <https://vector-inc.dev/> * This file is part of YDA. * YDA is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * YDA is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * You should have received a copy of the GNU Lesser General Public License * along with YDA. If not, see <https://www.gnu.org/licenses/>. */ package ai.yda.framework.rag.retriever.shared; import io.milvus.client.MilvusServiceClient; import io.milvus.param.ConnectParam; import io.milvus.param.IndexType; import io.milvus.param.MetricType; import org.springframework.ai.autoconfigure.openai.OpenAiConnectionProperties; import org.springframework.ai.autoconfigure.openai.OpenAiEmbeddingProperties; import org.springframework.ai.autoconfigure.vectorstore.milvus.MilvusServiceClientProperties; import org.springframework.ai.autoconfigure.vectorstore.milvus.MilvusVectorStoreProperties; import org.springframework.ai.document.MetadataMode; import org.springframework.ai.embedding.EmbeddingModel; import org.springframework.ai.openai.OpenAiEmbeddingModel; import org.springframework.ai.openai.OpenAiEmbeddingOptions; import org.springframework.ai.openai.api.OpenAiApi; import org.springframework.ai.retry.RetryUtils; import org.springframework.ai.vectorstore.MilvusVectorStore; /** * Utility class for creating and configuring instances of {@link MilvusVectorStore}. This class provides static methods * to initialize a {@link MilvusVectorStore} with the necessary configuration and dependencies. * * @author Iryna Kopchak * @see MilvusVectorStore * @see RetrieverProperties * @see MilvusVectorStore * @see OptimizedMilvusVectorStore * @since 0.1.0 */ public final class MilvusVectorStoreUtil { private MilvusVectorStoreUtil() {} /** * Constructs a new {@link MilvusVectorStore} instance with the specified properties and configurations. * * @param retrieverProperties the properties related to the Retriever configuration. * @param milvusProperties the properties specific to Milvus configuration. * @param milvusClientProperties the properties for Milvus Service Client. * @param openAiConnectionProperties the properties for connecting to OpenAI API. * @param openAiEmbeddingProperties the properties related to OpenAI Embedding Model. * @return a configured {@link MilvusVectorStore} instance. */ public static MilvusVectorStore createMilvusVectorStore( final RetrieverProperties retrieverProperties, final MilvusVectorStoreProperties milvusProperties, final MilvusServiceClientProperties milvusClientProperties, final OpenAiConnectionProperties openAiConnectionProperties, final OpenAiEmbeddingProperties openAiEmbeddingProperties) { var milvusClient = createMilvusClient(milvusClientProperties); var embeddingModel = createEmbeddingModel(openAiConnectionProperties, openAiEmbeddingProperties); var collectionName = retrieverProperties.getCollectionName(); var databaseName = milvusProperties.getDatabaseName(); var config = MilvusVectorStore.MilvusVectorStoreConfig.builder() .withCollectionName(collectionName) .withDatabaseName(databaseName) .withIndexType(IndexType.valueOf(milvusProperties.getIndexType().name())) .withMetricType( MetricType.valueOf(milvusProperties.getMetricType().name())) .withEmbeddingDimension(milvusProperties.getEmbeddingDimension()) .build(); return new OptimizedMilvusVectorStore( milvusClient, embeddingModel, config, milvusProperties.isInitializeSchema(), collectionName, databaseName, retrieverProperties.getClearCollectionOnStartup()); } /** * Creates an {@link EmbeddingModel} for OpenAI using the specified connection and embedding properties. * * @param connectionProperties the properties for connecting to OpenAI API. * @param openAiEmbeddingProperties the properties related to OpenAI embedding model. * @return a configured {@link EmbeddingModel} instance. */ private static EmbeddingModel createEmbeddingModel( final OpenAiConnectionProperties connectionProperties, final OpenAiEmbeddingProperties openAiEmbeddingProperties) { var openAiApi = new OpenAiApi(connectionProperties.getApiKey()); return new OpenAiEmbeddingModel( openAiApi, MetadataMode.EMBED, OpenAiEmbeddingOptions.builder() .withModel(openAiEmbeddingProperties.getOptions().getModel()) .withUser("user") .build(), RetryUtils.DEFAULT_RETRY_TEMPLATE); } /** * Creates a {@link MilvusServiceClient} using the specified connection properties. * * @param properties the properties for Milvus service client connection. * @return a configured {@link MilvusServiceClient} instance. */ private static MilvusServiceClient createMilvusClient(final MilvusServiceClientProperties properties) { return new MilvusServiceClient(ConnectParam.newBuilder() .withAuthorization(properties.getUsername(), properties.getPassword()) .withPort(properties.getPort()) .withHost(properties.getHost()) .build()); } }
0
java-sources/ai/yda-framework/retriever-shared-starter/0.1.0/ai/yda/framework/rag/retriever
java-sources/ai/yda-framework/retriever-shared-starter/0.1.0/ai/yda/framework/rag/retriever/shared/OptimizedMilvusVectorStore.java
/* * YDA - Open-Source Java AI Assistant. * Copyright (C) 2024 Love Vector OÜ <https://vector-inc.dev/> * This file is part of YDA. * YDA is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * YDA is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * You should have received a copy of the GNU Lesser General Public License * along with YDA. If not, see <https://www.gnu.org/licenses/>. */ package ai.yda.framework.rag.retriever.shared; import java.util.ArrayList; import java.util.List; import java.util.Optional; import com.alibaba.fastjson.JSONObject; import io.milvus.client.MilvusServiceClient; import io.milvus.param.collection.HasCollectionParam; import io.milvus.param.dml.InsertParam; import io.milvus.param.dml.QueryParam; import io.milvus.response.QueryResultsWrapper; import org.springframework.ai.document.Document; import org.springframework.ai.embedding.EmbeddingModel; import org.springframework.ai.vectorstore.MilvusVectorStore; import org.springframework.util.Assert; /** * The implementation of the {@link MilvusVectorStore} class that provides methods for optimized adding documents to the * vector storage and clearing collection on startup. * * @author Iryna Kopchak * @see EmbeddingModel * @see MilvusServiceClient * @see MilvusVectorStoreConfig * @since 0.1.0 */ public class OptimizedMilvusVectorStore extends MilvusVectorStore { /** * The maximum number of dimensions for an embedding array. This is the limitation of the OpenAi API. */ private static final int MAX_EMBEDDING_ARRAY_DIMENSIONS = 2048; private final MilvusServiceClient milvusClient; private final EmbeddingModel embeddingModel; private final String databaseName; private final String collectionName; private final boolean clearCollectionOnStartup; /** * Constructs a new {@link OptimizedMilvusVectorStore} instance with the specified parameters. * * @param milvusClient the Client for interacting with the Milvus Service. * @param embeddingModel the Model used for Embedding document content. * @param config the configuration for the Milvus Vector Store. * @param initializeSchema whether to initialize the schema in the database. * @param collectionName the name of the collection in the Milvus database. * @param databaseName the name of the database in Milvus. * @param clearCollectionOnStartup whether to clear the collection on startup. */ public OptimizedMilvusVectorStore( final MilvusServiceClient milvusClient, final EmbeddingModel embeddingModel, final MilvusVectorStoreConfig config, final boolean initializeSchema, final String collectionName, final String databaseName, final boolean clearCollectionOnStartup) { super(milvusClient, embeddingModel, config, initializeSchema); this.milvusClient = milvusClient; this.embeddingModel = embeddingModel; this.collectionName = collectionName; this.databaseName = databaseName; this.clearCollectionOnStartup = clearCollectionOnStartup; } /** * Adds a list of documents to the Milvus collection. The documents are embedded using the specified * {@link EmbeddingModel} before insertion. * * @param documents the list of documents to be added to the collection. * @throws RuntimeException if the insertion fails. */ @Override public void add(final List<Document> documents) { Assert.notNull(documents, "Documents must not be null"); var docIdArray = new ArrayList<String>(); var contentArray = new ArrayList<String>(); var metadataArray = new ArrayList<JSONObject>(); documents.forEach(document -> { docIdArray.add(document.getId()); contentArray.add(document.getContent()); metadataArray.add(new JSONObject(document.getMetadata())); }); var embeddingArray = embedDocuments(List.copyOf(contentArray)); var fields = List.of( new InsertParam.Field("doc_id", docIdArray), new InsertParam.Field("content", contentArray), new InsertParam.Field("metadata", metadataArray), new InsertParam.Field("embedding", embeddingArray)); var insertParam = InsertParam.newBuilder() .withDatabaseName(this.databaseName) .withCollectionName(this.collectionName) .withFields(fields) .build(); var status = this.milvusClient.insert(insertParam); if (status.getException() != null) { throw new RuntimeException("Failed to insert:", status.getException()); } } /** * Initializes the Vector Store after properties are set. Optionally clears the collection on startup if configured * to do so. * * @throws Exception if an error occurs during initialization. */ @Override public void afterPropertiesSet() throws Exception { if (this.clearCollectionOnStartup) { clearCollection(); } super.afterPropertiesSet(); } /** * Embeds the content of documents using the {@link EmbeddingModel}. * * @param documentsContent the content of the documents to be embedded. * @return a list of embedded vectors. */ private List<List<Float>> embedDocuments(final List<String> documentsContent) { var embeddings = new ArrayList<List<Float>>(); var totalSize = documentsContent.size(); for (int start = 0; start < totalSize; start += MAX_EMBEDDING_ARRAY_DIMENSIONS) { var end = Math.min(start + MAX_EMBEDDING_ARRAY_DIMENSIONS, totalSize); var limitedDocumentContentSublist = documentsContent.subList(start, end); var embeddingsSublist = embeddingModel.embed(limitedDocumentContentSublist).stream() .map(list -> list.stream().map(Number::floatValue).toList()) .toList(); embeddings.addAll(embeddingsSublist); } return embeddings; } /** * Clears the Milvus collection if it exists. This method deletes all entities from the collection. */ private void clearCollection() { if (isDatabaseCollectionExists()) { var allEntitiesIds = getAllEntitiesIds(); delete(allEntitiesIds); } } /** * Checks whether the specified collection exists in the Milvus database. * * @return {@code true} if the collection exists, {@code false} otherwise. * @throws RuntimeException if the collection existence check fails. */ private Boolean isDatabaseCollectionExists() { var collectionExistsResult = milvusClient.hasCollection(HasCollectionParam.newBuilder() .withDatabaseName(this.databaseName) .withCollectionName(this.collectionName) .build()); if (collectionExistsResult.getException() != null) { throw new RuntimeException( "Failed to check if database collection exists", collectionExistsResult.getException()); } return collectionExistsResult.getData(); } /** * Retrieves all entity IDs from the Milvus collection. * * @return a list of entity IDs. * @throws RuntimeException if the query fails. */ private List<String> getAllEntitiesIds() { var getAllIdsQueryResult = milvusClient.query(QueryParam.newBuilder() .withCollectionName(this.collectionName) .withExpr(DOC_ID_FIELD_NAME + " >= \"\"") .withOutFields(List.of(DOC_ID_FIELD_NAME)) .build()); if (getAllIdsQueryResult.getException() != null) { throw new RuntimeException("Failed to retrieve all entities ids", getAllIdsQueryResult.getException()); } return Optional.ofNullable(getAllIdsQueryResult.getData()) .map(data -> new QueryResultsWrapper(data) .getFieldWrapper(DOC_ID_FIELD_NAME).getFieldData().parallelStream() .map(Object::toString) .toList()) .orElse(List.of()); } }
0
java-sources/ai/yda-framework/retriever-shared-starter/0.1.0/ai/yda/framework/rag/retriever
java-sources/ai/yda-framework/retriever-shared-starter/0.1.0/ai/yda/framework/rag/retriever/shared/RetrieverProperties.java
/* * YDA - Open-Source Java AI Assistant. * Copyright (C) 2024 Love Vector OÜ <https://vector-inc.dev/> * This file is part of YDA. * YDA is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * YDA is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * You should have received a copy of the GNU Lesser General Public License * along with YDA. If not, see <https://www.gnu.org/licenses/>. */ package ai.yda.framework.rag.retriever.shared; import lombok.Getter; import lombok.Setter; import org.springframework.ai.vectorstore.MilvusVectorStore; import org.springframework.ai.vectorstore.SearchRequest; /** * Serves as the parent class for properties related to the Retriever configuration. It provides common settings such as * collection name, top K search results, processing enablement, and whether to clear the collection on startup. */ @Setter @Getter public class RetrieverProperties { private String collectionName = MilvusVectorStore.DEFAULT_COLLECTION_NAME; private Integer topK = SearchRequest.DEFAULT_TOP_K; private Boolean isProcessingEnabled = Boolean.FALSE; private Boolean clearCollectionOnStartup = Boolean.FALSE; /** * Default constructor for {@link RetrieverProperties}. */ public RetrieverProperties() {} }
0
java-sources/ai/yda-framework/session-core/0.1.0/ai/yda/framework/session
java-sources/ai/yda-framework/session-core/0.1.0/ai/yda/framework/session/core/ReactiveSessionProvider.java
/* * YDA - Open-Source Java AI Assistant. * Copyright (C) 2024 Love Vector OÜ <https://vector-inc.dev/> * This file is part of YDA. * YDA is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * YDA is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * You should have received a copy of the GNU Lesser General Public License * along with YDA. If not, see <https://www.gnu.org/licenses/>. */ package ai.yda.framework.session.core; import reactor.core.publisher.Mono; /** * Defines methods for storing and retrieving data associated with a reactive Session using a key-value store. * * @author Nikita Litvinov * @see SessionProvider * @since 0.1.0 */ public interface ReactiveSessionProvider { /** * Stores a value in the Session associated with the specified key. * * @param key the key under which the value is to be stored. * @param value the value to be stored in the Session. * @return a {@link Mono} that completes when the value is successfully stored. */ Mono<Void> put(String key, Object value); /** * Retrieves the value associated with the specified key from the Session. * * @param key the key whose associated value is to be retrieved. * @return a {@link Mono} that emits the value associated with the key, or completes without emitting a value * if the key does not exist in the Session. */ Mono<Object> get(String key); }
0
java-sources/ai/yda-framework/session-core/0.1.0/ai/yda/framework/session
java-sources/ai/yda-framework/session-core/0.1.0/ai/yda/framework/session/core/SessionProvider.java
/* * YDA - Open-Source Java AI Assistant. * Copyright (C) 2024 Love Vector OÜ <https://vector-inc.dev/> * This file is part of YDA. * YDA is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * YDA is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * You should have received a copy of the GNU Lesser General Public License * along with YDA. If not, see <https://www.gnu.org/licenses/>. */ package ai.yda.framework.session.core; import java.util.Optional; /** * Defines methods for storing and retrieving data associated with a Session using a key-value store. * * @author Dmitry Marchuk * @author Nikita Litvinov * @see ReactiveSessionProvider * @see ThreadLocalSessionProvider * @since 0.1.0 */ public interface SessionProvider { /** * Stores a value in the Session associated with the specified key. * * @param key the key under which the value is to be stored. * @param value the value to be stored in the Session. */ void put(String key, Object value); /** * Retrieves the value associated with the specified key from the Session. * * @param key the key whose associated value is to be retrieved. * @return an {@link Optional} containing the value associated with the key, or an empty {@link Optional} if the key * does not exist in the Session */ Optional<Object> get(String key); }
0
java-sources/ai/yda-framework/session-core/0.1.0/ai/yda/framework/session
java-sources/ai/yda-framework/session-core/0.1.0/ai/yda/framework/session/core/ThreadLocalSessionProvider.java
/* * YDA - Open-Source Java AI Assistant. * Copyright (C) 2024 Love Vector OÜ <https://vector-inc.dev/> * This file is part of YDA. * YDA is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * YDA is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * You should have received a copy of the GNU Lesser General Public License * along with YDA. If not, see <https://www.gnu.org/licenses/>. */ package ai.yda.framework.session.core; import java.util.HashMap; import java.util.Map; import java.util.Optional; /** * Provides a way to store and retrieve Session data that is specific to the current thread of execution. Each thread * has its own separate storage. * * @author Nikita Litvinov * @see SessionProvider * @see ThreadLocal * @since 0.1.0 */ public class ThreadLocalSessionProvider implements SessionProvider { private final ThreadLocal<Map<String, Object>> threadLocal = new ThreadLocal<>(); /** * Default constructor for {@link ThreadLocalSessionProvider}. */ public ThreadLocalSessionProvider() {} /** * Stores a value associated with a specific key in the current thread's Session storage. If the Session storage * for the current thread does not exist, a new {@link HashMap} will be created and associated with the thread. * * @param key the key to associate with the value. * @param value the value to store in the Session. */ @Override public void put(final String key, final Object value) { var threadLocalMap = threadLocal.get(); if (threadLocalMap == null) { threadLocalMap = new HashMap<>(); threadLocal.set(threadLocalMap); } threadLocalMap.put(key, value); } /** * Retrieves a value associated with the specified key from the current thread's Session storage. If the Session * storage for the current thread does not exist or does not contain the key, this method returns * an empty {@link Optional}. * * @param key the key associated with the value to retrieve. * @return an {@link Optional} containing the value if present, or an empty {@link Optional} if not. */ @Override public Optional<Object> get(final String key) { var threadLocalMap = threadLocal.get(); return threadLocalMap == null ? Optional.empty() : Optional.ofNullable(threadLocalMap.get(key)); } }
0
java-sources/ai/yda-framework/website-retriever/0.1.0/ai/yda/framework/rag/retriever
java-sources/ai/yda-framework/website-retriever/0.1.0/ai/yda/framework/rag/retriever/website/WebsiteRetriever.java
/* * YDA - Open-Source Java AI Assistant. * Copyright (C) 2024 Love Vector OÜ <https://vector-inc.dev/> * This file is part of YDA. * YDA is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * YDA is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * You should have received a copy of the GNU Lesser General Public License * along with YDA. If not, see <https://www.gnu.org/licenses/>. */ package ai.yda.framework.rag.retriever.website; import lombok.extern.slf4j.Slf4j; import org.springframework.ai.vectorstore.SearchRequest; import org.springframework.ai.vectorstore.VectorStore; import org.springframework.lang.NonNull; import ai.yda.framework.rag.core.model.RagContext; import ai.yda.framework.rag.core.model.RagRequest; import ai.yda.framework.rag.core.retriever.Retriever; import ai.yda.framework.rag.retriever.website.service.WebsiteService; /** * Retrieves website Context data from a Vector Store based on a User Request. It processes website sitemap and uses a * Vector Store to perform similarity searches. If website processing is enabled, it processes website urls during * initialization. * * @author Iryna Kopchak * @author Bogdan Synenko * @see WebsiteService * @see VectorStore * @since 0.1.0 */ @Slf4j public class WebsiteRetriever implements Retriever<RagRequest, RagContext> { /** * The Vector Store used to retrieve Context data for user Request through similarity search. */ private final VectorStore vectorStore; /** * The website's sitemap url. */ private final String sitemapUrl; /** * The number of top results to retrieve from the Vector Store. */ private final Integer topK; private final WebsiteService websiteService = new WebsiteService(); /** * Constructs a new {@link WebsiteRetriever} instance with the specified vectorStore, sitemapUrl, topK and * isProcessingEnabled parameters. * * @param vectorStore the {@link VectorStore} instance used for storing and retrieving vector data. * This parameter cannot be {@code null} and is used to interact with the Vector Store. * @param sitemapUrl the website's sitemap url. This parameter cannot be {@code null} and is used to * process and store data to the Vector Store. * @param topK the number of top results to retrieve from the Vector Store. This value must be a * positive integer. * @param isProcessingEnabled a {@link Boolean} flag indicating whether website processing should be enabled during * initialization. If {@code true}, the method {@link #processWebsite()} will * be called to process the files in the specified storage path. * @throws IllegalArgumentException if {@code topK} is not a positive number. */ public WebsiteRetriever( final @NonNull VectorStore vectorStore, final @NonNull String sitemapUrl, final @NonNull Integer topK, final @NonNull Boolean isProcessingEnabled) { if (topK <= 0) { throw new IllegalArgumentException("TopK must be a positive number."); } this.vectorStore = vectorStore; this.sitemapUrl = sitemapUrl; this.topK = topK; if (isProcessingEnabled) { processWebsite(); } } /** * Retrieves Context data based on the given Request by performing a similarity search in the Vector Store. * * @param request the Request object containing the User query for the similarity search. * @return a {@link RagContext} object containing the Knowledge obtained from the similarity search. */ @Override public RagContext retrieve(final RagRequest request) { return RagContext.builder() .knowledge( vectorStore .similaritySearch( SearchRequest.query(request.getQuery()).withTopK(topK)) .parallelStream() .map(document -> { log.debug("Document metadata: {}", document.getMetadata()); return document.getContent(); }) .toList()) .build(); } /** * Processes all website urls by creating document chunks and adding them to the Vector Store. */ private void processWebsite() { var pageDocuments = websiteService.createChunkDocumentsFromSitemapUrl(sitemapUrl); vectorStore.add(pageDocuments); } }
0
java-sources/ai/yda-framework/website-retriever/0.1.0/ai/yda/framework/rag/retriever/website
java-sources/ai/yda-framework/website-retriever/0.1.0/ai/yda/framework/rag/retriever/website/exception/WebsiteReadException.java
/* * YDA - Open-Source Java AI Assistant. * Copyright (C) 2024 Love Vector OÜ <https://vector-inc.dev/> * This file is part of YDA. * YDA is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * YDA is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * You should have received a copy of the GNU Lesser General Public License * along with YDA. If not, see <https://www.gnu.org/licenses/>. */ package ai.yda.framework.rag.retriever.website.exception; /** * Thrown to indicate that website processing operation has failed. * * @author Bogdan Synenko * @since 0.1.0 */ public class WebsiteReadException extends RuntimeException { /** * Constructs a new {@link WebsiteReadException} instance with the specified cause. * This constructor initializes the exception with a predefined message "Failed to process site". * * @param cause the cause of the exception, which can be retrieved later using {@link Throwable#getCause()}. */ public WebsiteReadException(final Throwable cause) { super("Failed to process site", cause); } }
0
java-sources/ai/yda-framework/website-retriever/0.1.0/ai/yda/framework/rag/retriever/website
java-sources/ai/yda-framework/website-retriever/0.1.0/ai/yda/framework/rag/retriever/website/service/WebsiteService.java
/* * YDA - Open-Source Java AI Assistant. * Copyright (C) 2024 Love Vector OÜ <https://vector-inc.dev/> * This file is part of YDA. * YDA is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * YDA is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * You should have received a copy of the GNU Lesser General Public License * along with YDA. If not, see <https://www.gnu.org/licenses/>. */ package ai.yda.framework.rag.retriever.website.service; import java.io.IOException; import java.util.List; import java.util.Map; import lombok.extern.slf4j.Slf4j; import org.jsoup.Jsoup; import org.springframework.ai.document.Document; import ai.yda.framework.rag.core.util.ContentUtil; import ai.yda.framework.rag.retriever.website.exception.WebsiteReadException; /** * Provides methods to process website sitemap, specifically for creating chunked documents from website's pages. This * class handles the retrieval of sitemaps and individual web pages, processes their content, and splits it into * manageable chunks. Each chunk is then converted into a {@link Document} object. This service is used for indexing and * analyzing content from websites based on their sitemaps. * * @author Iryna Kopchak * @author Bogdan Synenko * @see ContentUtil * @since 0.1.0 */ @Slf4j public class WebsiteService { /** * The maximum length of a chunk in characters. */ public static final int CHUNK_MAX_LENGTH = 1000; /** * Default constructor for {@link WebsiteService}. */ public WebsiteService() {} /** * Processes a sitemap urls and creates chunked {@link Document} objects from them. This method connects to the * provided sitemap URL, retrieves and parses it to find individual website URLs. Each URL is then processed to * either recursively handle other sitemaps or directly split website pages into chunks. * * @param sitemapUrl a sitemap url to be processed. * @return a list of {@link Document} objects created from the chunks of website urls. */ public List<Document> createChunkDocumentsFromSitemapUrl(final String sitemapUrl) { var document = safeConnect(sitemapUrl); var sitemapIndexElements = document.select("loc"); return sitemapIndexElements.parallelStream() .map(element -> { var currentUrl = element.text(); return currentUrl.contains("sitemap") ? createChunkDocumentsFromSitemapUrl(currentUrl) : splitWebsitePageIntoChunksDocuments(currentUrl); }) .flatMap(List::stream) .toList(); } /** * Preprocesses and split of each website page into chunks of a maximum length defined by {@link #CHUNK_MAX_LENGTH}. * The method connects to the specified website page URL, retrieves its content, preprocesses it, and then splits * it into smaller chunks based on the maximum length. Each chunk is converted into a {@link Document} with * metadata about the source URL. * * @param websitePageUrl the website page url to be processed. * @return a list of {@link Document} objects created from the chunks of the website page. */ private List<Document> splitWebsitePageIntoChunksDocuments(final String websitePageUrl) { var documentContent = safeConnect(websitePageUrl).text(); if (documentContent.trim().isEmpty()) { return List.of(); } log.debug("Processing website's page url: {}", websitePageUrl); return ContentUtil.preprocessAndSplitContent(documentContent, CHUNK_MAX_LENGTH).parallelStream() .map(chunkContent -> new Document(chunkContent, Map.of("url", websitePageUrl))) .toList(); } /** * Safely connects to the given URL and retrieve its HTML Document. * * @param url the URL to connect to. * @return the {@link org.jsoup.nodes.Document} object retrieved from the URL. * @throws WebsiteReadException if an IOException occurs during the connection attempt. */ private org.jsoup.nodes.Document safeConnect(final String url) { try { return Jsoup.connect(url).get(); } catch (IOException e) { log.error("HTTP error fetching URL: {}", e.getMessage()); throw new WebsiteReadException(e); } } }
0
java-sources/ai/yda-framework/website-retriever-starter/0.1.0/ai/yda/framework/rag/retriever/website
java-sources/ai/yda-framework/website-retriever-starter/0.1.0/ai/yda/framework/rag/retriever/website/autoconfigure/RetrieverWebsiteAutoConfiguration.java
/* * YDA - Open-Source Java AI Assistant. * Copyright (C) 2024 Love Vector OÜ <https://vector-inc.dev/> * This file is part of YDA. * YDA is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * YDA is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * You should have received a copy of the GNU Lesser General Public License * along with YDA. If not, see <https://www.gnu.org/licenses/>. */ package ai.yda.framework.rag.retriever.website.autoconfigure; import org.springframework.ai.autoconfigure.openai.OpenAiConnectionProperties; import org.springframework.ai.autoconfigure.openai.OpenAiEmbeddingProperties; import org.springframework.ai.autoconfigure.vectorstore.milvus.MilvusServiceClientProperties; import org.springframework.ai.autoconfigure.vectorstore.milvus.MilvusVectorStoreProperties; import org.springframework.boot.autoconfigure.AutoConfiguration; import org.springframework.boot.context.properties.EnableConfigurationProperties; import org.springframework.context.annotation.Bean; import ai.yda.framework.rag.retriever.shared.MilvusVectorStoreUtil; import ai.yda.framework.rag.retriever.website.WebsiteRetriever; /** * Autoconfiguration class for setting up the {@link WebsiteRetriever} bean with the necessary properties and * dependencies. The configuration is based on properties defined in the external configuration files. * <p> * The configuration is based on properties defined in the external configuration files (e.g., application.properties * or application.yml) under {@link RetrieverWebsiteProperties#CONFIG_PREFIX}, * {@link MilvusVectorStoreProperties#CONFIG_PREFIX} and {@link OpenAiConnectionProperties#CONFIG_PREFIX} namespaces. * </p> * * @author Iryna Kopchak * @author Bogdan Synenko * @see WebsiteRetriever * @see RetrieverWebsiteProperties * @see MilvusVectorStoreProperties * @see MilvusServiceClientProperties * @see OpenAiConnectionProperties * @see OpenAiEmbeddingProperties * @since 1.0.0 */ @AutoConfiguration @EnableConfigurationProperties(RetrieverWebsiteProperties.class) public class RetrieverWebsiteAutoConfiguration { /** * Default constructor for {@link RetrieverWebsiteAutoConfiguration}. */ public RetrieverWebsiteAutoConfiguration() {} /** * Creates and configures an instance of {@link WebsiteRetriever} using the provided properties and services. * * <p>This method performs the following steps:</p> * <ul> * <li>Creates a {@code MilvusVectorStore} instance using the provided properties and services.</li> * <li>Initializes the {@code MilvusVectorStore} instance by calling {@code afterPropertiesSet()}.</li> * <li>Creates and returns a {@link WebsiteRetriever} instance with the initialized parameters</li> * </ul> * * @param websiteProperties properties for configuring the {@link RetrieverWebsiteProperties}, including * file storage path, topK value, and processing enablement. * @param milvusProperties properties for configuring the Milvus Vector Store. * @param milvusClientProperties properties for configuring the Milvus Service Client. * @param openAiConnectionProperties properties for configuring the OpenAI connection. * @param openAiEmbeddingProperties properties for configuring the OpenAI Embeddings. * @return a fully configured {@link WebsiteRetriever} instance. * @throws Exception if an error occurs during initialization. */ @Bean public WebsiteRetriever websiteRetriever( final RetrieverWebsiteProperties websiteProperties, final MilvusVectorStoreProperties milvusProperties, final MilvusServiceClientProperties milvusClientProperties, final OpenAiConnectionProperties openAiConnectionProperties, final OpenAiEmbeddingProperties openAiEmbeddingProperties) throws Exception { var milvusVectorStore = MilvusVectorStoreUtil.createMilvusVectorStore( websiteProperties, milvusProperties, milvusClientProperties, openAiConnectionProperties, openAiEmbeddingProperties); milvusVectorStore.afterPropertiesSet(); return new WebsiteRetriever( milvusVectorStore, websiteProperties.getSitemapUrl(), websiteProperties.getTopK(), websiteProperties.getIsProcessingEnabled()); } }
0
java-sources/ai/yda-framework/website-retriever-starter/0.1.0/ai/yda/framework/rag/retriever/website
java-sources/ai/yda-framework/website-retriever-starter/0.1.0/ai/yda/framework/rag/retriever/website/autoconfigure/RetrieverWebsiteProperties.java
/* * YDA - Open-Source Java AI Assistant. * Copyright (C) 2024 Love Vector OÜ <https://vector-inc.dev/> * This file is part of YDA. * YDA is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * YDA is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * You should have received a copy of the GNU Lesser General Public License * along with YDA. If not, see <https://www.gnu.org/licenses/>. */ package ai.yda.framework.rag.retriever.website.autoconfigure; import lombok.Getter; import lombok.Setter; import org.springframework.boot.context.properties.ConfigurationProperties; import ai.yda.framework.rag.retriever.shared.RetrieverProperties; /** * Provides configuration properties for website Retriever. These properties can be customized through the * application’s external configuration, such as a properties file, YAML file, or environment variables. The * properties include collectionName, topK, isProcessingEnabled, clearCollectionOnStartup and sitemapUrl settings. * <p> * The properties are prefixed with {@link #CONFIG_PREFIX} and can be customized by defining values under this prefix * in the external configuration. * <pre> * Example configuration in a YAML file: * ai: * yda: * framework: * rag: * retriever: * website: * collectionName: your-collection-name * topK: your-top-k * isProcessingEnabled: true/false * clearCollectionOnStartup: true/false * sitemapUrl: your-file-storage-path * </pre> * * @author Dmitry Marchuk * @author Iryna Kopchak * @since 0.1.0 */ @Getter @Setter @ConfigurationProperties(RetrieverWebsiteProperties.CONFIG_PREFIX) public class RetrieverWebsiteProperties extends RetrieverProperties { /** * The configuration prefix used to reference properties related to the website Retriever in application * configurations. This prefix is used for binding properties within the particular namespace. */ public static final String CONFIG_PREFIX = "ai.yda.framework.rag.retriever.website"; private String sitemapUrl; /** * Default constructor for {@link RetrieverWebsiteProperties}. */ public RetrieverWebsiteProperties() {} }
0
java-sources/ai/ylyue/yue-library-auth-client/2.1.0/ai/yue/library/auth
java-sources/ai/ylyue/yue-library-auth-client/2.1.0/ai/yue/library/auth/client/package-info.java
/** * auth-client为auth-service客户端模块,提供获取当前登录用户状态信息等特性 * * @author ylyue * @since 2019年10月14日 */ package ai.yue.library.auth.client;
0
java-sources/ai/ylyue/yue-library-auth-client/2.1.0/ai/yue/library/auth/client
java-sources/ai/ylyue/yue-library-auth-client/2.1.0/ai/yue/library/auth/client/client/User.java
package ai.yue.library.auth.client.client; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServletRequest; import org.springframework.beans.factory.annotation.Autowired; import com.alibaba.fastjson.JSONObject; import ai.yue.library.auth.client.config.properties.AuthProperties; import ai.yue.library.base.exception.LoginException; import ai.yue.library.base.util.StringUtils; import ai.yue.library.data.redis.client.Redis; import ai.yue.library.web.util.servlet.ServletUtils; import lombok.NoArgsConstructor; /** * <b>User客户端</b> * <p>token自动解析获取用户信息 * * @author ylyue * @since 2018年4月24日 */ @NoArgsConstructor public class User { @Autowired protected Redis redis; @Autowired protected HttpServletRequest request; @Autowired protected AuthProperties authProperties; /** * 获得请求token * @return */ public String getRequestToken() { Cookie cookie = ServletUtils.getCookie(authProperties.getCookieTokenKey()); String token = ""; if (cookie != null) { token = cookie.getValue(); } else { token = request.getHeader(authProperties.getCookieTokenKey()); } return token; } /** * 获得用户ID * <p><code style="color:red"><b>注意:若 userId == null ,请先确认 {@linkplain ai.yue.library.auth.service.client.User#login(Object)} 方法是否存入 {@linkplain AuthProperties#getUserKey()} 字段,此处可以传 JSON 与 POJO 对象</b></code> * * @return userId */ public Long getUserId() { try { // 1. 获得请求token String token = getRequestToken(); // 2. 确认token if (StringUtils.isEmpty(token)) { throw new LoginException("token == null"); } // 3. 查询Redis中token的值 String tokenValue = redis.get(authProperties.getRedisTokenPrefix() + token); // 4. 返回userId return JSONObject.parseObject(tokenValue).getLong(authProperties.getUserKey()); } catch (Exception e) { throw new LoginException(e.getMessage()); } } /** * 获得用户相关信息 * @param <T> 泛型 * @param clazz 泛型类型 * @return POJO对象 */ public <T> T getUser(Class<T> clazz) { try { // 1. 获得请求token String token = getRequestToken(); // 2. 确认token if (StringUtils.isEmpty(token)) { throw new LoginException("token == null"); } // 3. 查询Redis中token的值 String tokenValue = redis.get(authProperties.getRedisTokenPrefix() + token); // 4. 返回POJO T t = JSONObject.parseObject(tokenValue, clazz); if (t == null) { throw new LoginException(null); } return t; } catch (Exception e) { throw new LoginException(e.getMessage()); } } }
0
java-sources/ai/ylyue/yue-library-auth-client/2.1.0/ai/yue/library/auth/client
java-sources/ai/ylyue/yue-library-auth-client/2.1.0/ai/yue/library/auth/client/client/package-info.java
/** * AuthClient客户端 * * @author ylyue * @since 2019年10月14日 */ package ai.yue.library.auth.client.client;
0
java-sources/ai/ylyue/yue-library-auth-client/2.1.0/ai/yue/library/auth/client
java-sources/ai/ylyue/yue-library-auth-client/2.1.0/ai/yue/library/auth/client/config/AuthClientAutoConfig.java
package ai.yue.library.auth.client.config; import org.springframework.boot.autoconfigure.AutoConfigureAfter; import org.springframework.boot.autoconfigure.condition.ConditionalOnBean; import org.springframework.boot.context.properties.EnableConfigurationProperties; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import ai.yue.library.auth.client.client.User; import ai.yue.library.auth.client.config.properties.AuthProperties; import ai.yue.library.data.redis.client.Redis; import ai.yue.library.data.redis.config.RedisAutoConfig; import lombok.extern.slf4j.Slf4j; /** * AuthClient自动配置 * * @author ylyue * @since 2018年6月11日 */ @Slf4j @Configuration @AutoConfigureAfter(RedisAutoConfig.class) @EnableConfigurationProperties({ AuthProperties.class }) public class AuthClientAutoConfig { @Bean @ConditionalOnBean(Redis.class) public User user() { log.info("【初始化配置-AuthClient-User客户端】配置项:" + AuthProperties.PREFIX + "。Bean:User ... 已初始化完毕。"); return new User(); } }
0
java-sources/ai/ylyue/yue-library-auth-client/2.1.0/ai/yue/library/auth/client
java-sources/ai/ylyue/yue-library-auth-client/2.1.0/ai/yue/library/auth/client/config/package-info.java
/** * AuthClient自动配置 * * @author ylyue * @since 2019年10月14日 */ package ai.yue.library.auth.client.config;
0
java-sources/ai/ylyue/yue-library-auth-client/2.1.0/ai/yue/library/auth/client/config
java-sources/ai/ylyue/yue-library-auth-client/2.1.0/ai/yue/library/auth/client/config/properties/AuthProperties.java
package ai.yue.library.auth.client.config.properties; import org.springframework.boot.context.properties.ConfigurationProperties; import ai.yue.library.auth.client.client.User; import lombok.Data; /** * Auth可配置属性,适用于auth所有模块的通用可配置属性 * * @author ylyue * @since 2018年11月6日 */ @Data @ConfigurationProperties(AuthProperties.PREFIX) public class AuthProperties { /** * Prefix of {@link AuthProperties}. */ public static final String PREFIX = "yue.auth"; public static final String PREFIX_REDIS = "yue:auth:"; /** * Cookie Token Key * <p>默认:token */ private String cookieTokenKey = "token"; /** * Redis Token 前缀(自定义值,请保留“<code style="color:red">:</code>”部分) * <p>默认:token: */ private String redisTokenPrefix = PREFIX_REDIS + "token:"; /** * Redis Token Value 序列化后的key,反序列化时需使用,如:{@linkplain User#getUserId()} * <p>默认:userId */ private String userKey = "userId"; /** * IP前缀(自定义值,请保留“<code style="color:red">_%s</code>”部分) * <p>默认:ip_%s */ private String ipPrefix = "ip_%s"; }
0
java-sources/ai/ylyue/yue-library-auth-client/2.1.0/ai/yue/library/auth/client/config
java-sources/ai/ylyue/yue-library-auth-client/2.1.0/ai/yue/library/auth/client/config/properties/package-info.java
/** * Auth与AuthClient可配置属性 * * @author ylyue * @since 2019年10月14日 */ package ai.yue.library.auth.client.config.properties;
0
java-sources/ai/ylyue/yue-library-auth-service/2.1.0/ai/yue/library/auth
java-sources/ai/ylyue/yue-library-auth-service/2.1.0/ai/yue/library/auth/service/package-info.java
/** * auth-service库基于SpringSecurity进行二次封装,更简单灵活,提供全局token与登录等特性 * * @author ylyue * @since 2019年10月14日 */ package ai.yue.library.auth.service;
0
java-sources/ai/ylyue/yue-library-auth-service/2.1.0/ai/yue/library/auth/service
java-sources/ai/ylyue/yue-library-auth-service/2.1.0/ai/yue/library/auth/service/client/User.java
package ai.yue.library.auth.service.client; import java.awt.image.BufferedImage; import java.io.IOException; import java.io.OutputStream; import java.util.UUID; import javax.imageio.ImageIO; import javax.servlet.http.HttpServletResponse; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.client.RestTemplate; import com.alibaba.fastjson.JSONObject; import ai.yue.library.auth.client.config.properties.AuthProperties; import ai.yue.library.auth.service.config.properties.AuthServiceProperties; import ai.yue.library.auth.service.config.properties.QqProperties; import ai.yue.library.auth.service.config.properties.WxOpenProperties; import ai.yue.library.auth.service.dto.QqUserDTO; import ai.yue.library.auth.service.dto.WxUserDTO; import ai.yue.library.auth.service.vo.wx.open.AccessTokenVO; import ai.yue.library.base.exception.ResultException; import ai.yue.library.base.util.StringUtils; import ai.yue.library.base.view.Result; import ai.yue.library.base.view.ResultInfo; import ai.yue.library.base.view.ResultPrompt; import ai.yue.library.web.ipo.CaptchaIPO; import ai.yue.library.web.util.CaptchaUtils; import ai.yue.library.web.util.servlet.ServletUtils; import ai.yue.library.web.vo.CaptchaVO; import lombok.NoArgsConstructor; /** * <b>User客户端</b> * <p>登录登出、第三方登录、token自动解析获取用户信息、分布式验证码 * * @author ylyue * @since 2018年4月24日 */ @NoArgsConstructor public class User extends ai.yue.library.auth.client.client.User { @Autowired RestTemplate restTemplate; @Autowired HttpServletResponse response; @Autowired AuthServiceProperties authServiceProperties; @Autowired WxOpenProperties wxOpenProperties; @Autowired QqProperties qqProperties; // 微信-URI /** 通过code获取access_token */ private static final String WX_URI_ACCESS_TOKEN = "https://api.weixin.qq.com/sns/oauth2/access_token?appid={appid}&secret={secret}&code={code}&grant_type=authorization_code"; /** 获取用户个人信息 */ private static final String WX_URI_USER_INFO = "https://api.weixin.qq.com/sns/userinfo?access_token={access_token}&openid={openid}"; // QQ-URI /** 获取用户个人信息 */ private static final String QQ_URI_USER_INFO = "https://graph.qq.com/user/get_user_info?oauth_consumer_key={oauth_consumer_key}&access_token={access_token}&openid={openid}"; /** * 微信-获取access_token * @param code 微信授权code码 * @return accessTokenVO,参考微信返回说明文档 */ public AccessTokenVO getWxAccessToken(String code) { JSONObject paramJson = new JSONObject(); paramJson.put("appid", wxOpenProperties.getAppid()); paramJson.put("secret", wxOpenProperties.getSecret()); paramJson.put("code", code); String result = restTemplate.getForObject(WX_URI_ACCESS_TOKEN, String.class, paramJson); AccessTokenVO accessTokenVO = JSONObject.parseObject(result, AccessTokenVO.class); return accessTokenVO; } /** * 微信-获取用户个人信息 * @param access_token 调用凭证 * @param openid 普通用户的标识,对当前开发者帐号唯一 * @return {@linkplain WxUserDTO},开发者最好保存unionID信息,以便以后在不同应用之间进行用户信息互通。 */ public WxUserDTO getWxUserInfo(String access_token, String openid) { JSONObject paramJson = new JSONObject(); paramJson.put("access_token", access_token); paramJson.put("openid", openid); String result = restTemplate.getForObject(WX_URI_USER_INFO, String.class, paramJson); WxUserDTO wxUserDTO = JSONObject.parseObject(result, WxUserDTO.class); if (null == wxUserDTO.getOpenid()) { throw new ResultException(ResultInfo.error(result)); } return wxUserDTO; } /** * 获取用户个人信息 * @param access_token 调用凭证 * @param openid 普通用户的标识,对当前开发者帐号唯一 * @return {@linkplain QqUserDTO} */ public QqUserDTO getQqUserInfo(String access_token, String openid) { JSONObject paramJson = new JSONObject(); paramJson.put("oauth_consumer_key", qqProperties.getQqAppid()); paramJson.put("access_token", access_token); paramJson.put("openid", openid); String result = restTemplate.getForObject(QQ_URI_USER_INFO, String.class, paramJson); QqUserDTO qqUserDTO = JSONObject.parseObject(result, QqUserDTO.class); if (null == qqUserDTO.getGender()) { throw new ResultException(ResultInfo.error(result)); } return qqUserDTO; } /** * 获得-验证码图片(基于redis解决分布式验证的问题) * <p>将验证码设置到redis * <p>将验证码图片写入response,并设置ContentType为image/png */ public void getCaptchaImage() { // 1. 创建图片验证码 CaptchaVO captchaVO = CaptchaUtils.createCaptchaImage(CaptchaIPO.builder().build()); String captcha = captchaVO.getCaptcha(); BufferedImage captchaImage = captchaVO.getCaptchaImage(); // 2. 设置验证码到Redis String captcha_redis_key = String.format(CaptchaUtils.CAPTCHA_REDIS_PREFIX, captcha); redis.set(captcha_redis_key, captcha, authServiceProperties.getCaptchaTimeout()); // 3. 设置验证码到响应输出流 HttpServletResponse response = ServletUtils.getResponse(); response.setContentType("image/png"); OutputStream output; try { output = response.getOutputStream(); // 响应结束时servlet会自动将output关闭 ImageIO.write(captchaImage, "png", output); } catch (IOException e) { e.printStackTrace(); } } /** * 验证-验证码(基于redis解决分布式验证的问题) * <p>验证码错误会抛出一个{@linkplain ResultException}异常,作为结果提示...<br> * * @param captcha 验证码 * @throws ResultException 验证码错误 */ public void captchaValidate(String captcha) { String captcha_redis_key = String.format(CaptchaUtils.CAPTCHA_REDIS_PREFIX, captcha); String randCaptcha = redis.get(captcha_redis_key); if (StringUtils.isEmpty(randCaptcha) || !randCaptcha.equalsIgnoreCase(captcha)) { throw new ResultException(ResultInfo.devCustomTypePrompt(ResultPrompt.CAPTCHA_ERROR)); } redis.del(captcha_redis_key); } /** * 登录 * <p>登录成功-设置token至Cookie * <p>登录成功-设置token至Header * <p><code style="color:red"><b>注意:登录之后的所有相关操作,都是基于请求报文中所携带的token,若Cookie与Header皆没有token或Redis中匹配不到值,将视为未登录状态 * </b></code> * * @param userInfo 用户信息(必须包含:<code style="color:red">{@linkplain AuthProperties#getUserKey()},默认:userId,可通过配置文件进行配置</code>) * @return <b>token</b> 身份认证令牌 <code style="color:red"><b>(不建议使用,最好是忽略这个返回值,哪怕你只是将他放在响应体里面,也不推荐这样做)</b></code> * <p>支持Cookie:建议使用默认的机制即可 * <p>不支持Cookie:建议从响应Header中获取token,之后的请求都将token放入请求Header中即可 */ public String login(Object userInfo) { // 1. 获得请求token String token = getRequestToken(); // 2. 注销会话 String redisTokenKey = null; if (StringUtils.isNotEmpty(token)) { redisTokenKey = authProperties.getRedisTokenPrefix() + token; String tokenValue = redis.get(redisTokenKey); if (StringUtils.isNotEmpty(tokenValue)) { redis.del(redisTokenKey); } } // 3. 生成新的token token = UUID.randomUUID().toString(); redisTokenKey = authProperties.getRedisTokenPrefix() + token; // 4. 登录成功-设置token至Redis Integer tokenTimeout = authServiceProperties.getTokenTimeout(); redis.set(redisTokenKey, JSONObject.toJSONString(userInfo), tokenTimeout); // 5. 登录成功-设置token至Cookie ServletUtils.addCookie(authProperties.getCookieTokenKey(), token, tokenTimeout); // 6. 登录成功-设置token至Header response.setHeader(authProperties.getCookieTokenKey(), token); // 7. 登录成功-返回token return token; } /** * 登出 * <p>清除Redis-token * <p>清除Cookie-token * * @return 成功 */ public Result<?> logout() { // 1. 获得请求token String token = getRequestToken(); // 2. 确认token if (StringUtils.isEmpty(token)) { return ResultInfo.unauthorized(); } // 3. 清除Redis-token redis.del(authProperties.getRedisTokenPrefix() + token); // 4. 清除Cookie-token ServletUtils.addCookie(authProperties.getCookieTokenKey(), null, 0); // 5. 返回结果 return ResultInfo.success(); } }
0
java-sources/ai/ylyue/yue-library-auth-service/2.1.0/ai/yue/library/auth/service
java-sources/ai/ylyue/yue-library-auth-service/2.1.0/ai/yue/library/auth/service/client/WxMaUser.java
package ai.yue.library.auth.service.client; import java.util.List; import java.util.Map; import java.util.stream.Collectors; import javax.annotation.PostConstruct; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.boot.context.properties.EnableConfigurationProperties; import org.springframework.context.annotation.Configuration; import com.google.common.collect.Maps; import ai.yue.library.auth.service.config.properties.WxMaProperties; import ai.yue.library.base.exception.ParamException; import ai.yue.library.base.exception.ResultException; import ai.yue.library.base.util.ListUtils; import ai.yue.library.base.view.ResultInfo; import cn.binarywang.wx.miniapp.api.WxMaService; import cn.binarywang.wx.miniapp.api.impl.WxMaServiceImpl; import cn.binarywang.wx.miniapp.bean.WxMaJscode2SessionResult; import cn.binarywang.wx.miniapp.bean.WxMaPhoneNumberInfo; import cn.binarywang.wx.miniapp.bean.WxMaUserInfo; import cn.binarywang.wx.miniapp.config.WxMaInMemoryConfig; import me.chanjar.weixin.common.error.WxErrorException; /** * 微信小程序用户接口 * * @author ylyue * @since 2019年6月18日 */ @Configuration @EnableConfigurationProperties(WxMaProperties.class) @ConditionalOnProperty(prefix = WxMaProperties.PREFIX, name = "enabled", havingValue = "true") public class WxMaUser { @Autowired private WxMaProperties wxMaProperties; private Map<String, WxMaService> maServices = Maps.newHashMap(); @PostConstruct private void init() { List<WxMaProperties.Config> configs = wxMaProperties.getConfigs(); if (ListUtils.isEmpty(configs)) { throw new RuntimeException("无效的小程序配置..."); } maServices = configs.stream() .map(a -> { WxMaInMemoryConfig config = new WxMaInMemoryConfig(); config.setAppid(a.getAppid()); config.setSecret(a.getSecret()); WxMaService service = new WxMaServiceImpl(); service.setWxMaConfig(config); return service; }).collect(Collectors.toMap(s -> s.getWxMaConfig().getAppid(), a -> a)); } private WxMaService getMaService(String appid) { WxMaService wxService = maServices.get(appid); if (wxService == null) { throw new IllegalArgumentException(String.format("未找到对应appid=[%s]的配置,请核实!", appid)); } return wxService; } /** * 获取登录后的session信息 * * @param appid APPID * @param code 授权CODE码 * @return {@linkplain WxMaJscode2SessionResult} <code style="color:red">unionid 用户在开放平台的唯一标识符,在满足 UnionID 下发条件的情况下会返回,详见 <a href="https://developers.weixin.qq.com/miniprogram/dev/framework/open-ability/union-id.html">UnionID 机制说明</a> 。</code> */ public WxMaJscode2SessionResult getSessionInfo(String appid, String code) { WxMaService wxService = getMaService(appid); WxMaJscode2SessionResult wxMaJscode2SessionResult = null; try { wxMaJscode2SessionResult = wxService.getUserService().getSessionInfo(code); } catch (WxErrorException e) { String msg = e.getMessage(); throw new ResultException(ResultInfo.devCustomTypePrompt(msg)); } return wxMaJscode2SessionResult; } /** * <pre> * 获取用户信息 * </pre> * * @param appid APPID * @param sessionKey 会话密钥 * @param signature 数据签名 * @param rawData 微信用户基本信息 * @param encryptedData 消息密文 * @param iv 加密算法的初始向量 * @return {@linkplain WxMaUserInfo} 微信小程序用户信息 */ public WxMaUserInfo getUserInfo(String appid, String sessionKey, String signature, String rawData, String encryptedData, String iv) { WxMaService wxService = getMaService(appid); // 用户信息校验 if (!wxService.getUserService().checkUserInfo(sessionKey, rawData, signature)) { throw new ParamException("user check failed"); } // 解密用户信息 WxMaUserInfo wxMaUserInfo = wxService.getUserService().getUserInfo(sessionKey, encryptedData, iv); return wxMaUserInfo; } /** * <pre> * 获取用户绑定手机号信息 * </pre> * * @param appid APPID * @param sessionKey 会话密钥 * @param encryptedData 消息密文 * @param iv 加密算法的初始向量 * @return {@linkplain WxMaPhoneNumberInfo} 微信小程序手机号信息 */ public WxMaPhoneNumberInfo getCellphone(String appid, String sessionKey, String encryptedData, String iv) { WxMaService wxService = getMaService(appid); // 解密 WxMaPhoneNumberInfo wxMaPhoneNumberInfo = wxService.getUserService().getPhoneNoInfo(sessionKey, encryptedData, iv); return wxMaPhoneNumberInfo; } }
0
java-sources/ai/ylyue/yue-library-auth-service/2.1.0/ai/yue/library/auth/service
java-sources/ai/ylyue/yue-library-auth-service/2.1.0/ai/yue/library/auth/service/client/package-info.java
/** * AuthService客户端 * * @author ylyue * @since 2019年10月14日 */ package ai.yue.library.auth.service.client;
0
java-sources/ai/ylyue/yue-library-auth-service/2.1.0/ai/yue/library/auth/service
java-sources/ai/ylyue/yue-library-auth-service/2.1.0/ai/yue/library/auth/service/config/AuthServiceAutoConfig.java
package ai.yue.library.auth.service.config; import org.springframework.boot.autoconfigure.AutoConfigureAfter; import org.springframework.boot.autoconfigure.condition.ConditionalOnBean; import org.springframework.boot.context.properties.EnableConfigurationProperties; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Import; import org.springframework.context.annotation.Primary; import ai.yue.library.auth.client.config.AuthClientAutoConfig; import ai.yue.library.auth.service.client.User; import ai.yue.library.auth.service.client.WxMaUser; import ai.yue.library.auth.service.config.properties.AuthServiceProperties; import ai.yue.library.auth.service.config.properties.QqProperties; import ai.yue.library.auth.service.config.properties.WxOpenProperties; import ai.yue.library.data.redis.client.Redis; import lombok.extern.slf4j.Slf4j; /** * AuthService自动配置 * * @author ylyue * @since 2018年6月11日 */ @Slf4j @Configuration @Import({ WxMaUser.class }) @AutoConfigureAfter(AuthClientAutoConfig.class) @EnableConfigurationProperties({ AuthServiceProperties.class, WxOpenProperties.class, QqProperties.class }) public class AuthServiceAutoConfig { @Bean @Primary @ConditionalOnBean(Redis.class) public User user() { log.info("【初始化配置-AuthService-User客户端】配置项:" + AuthServiceProperties.PREFIX + "。Bean:User ... 已初始化完毕。"); return new User(); } }
0
java-sources/ai/ylyue/yue-library-auth-service/2.1.0/ai/yue/library/auth/service
java-sources/ai/ylyue/yue-library-auth-service/2.1.0/ai/yue/library/auth/service/config/package-info.java
/** * AuthService自动配置 * * @author ylyue * @since 2019年10月14日 */ package ai.yue.library.auth.service.config;
0
java-sources/ai/ylyue/yue-library-auth-service/2.1.0/ai/yue/library/auth/service/config
java-sources/ai/ylyue/yue-library-auth-service/2.1.0/ai/yue/library/auth/service/config/properties/AuthServiceProperties.java
package ai.yue.library.auth.service.config.properties; import org.springframework.boot.context.properties.ConfigurationProperties; import lombok.Data; /** * AuthService可配置属性 * * @author ylyue * @since 2018年11月6日 */ @Data @ConfigurationProperties(AuthServiceProperties.PREFIX) public class AuthServiceProperties { /** * Prefix of {@link AuthServiceProperties}. */ public static final String PREFIX = "yue.auth.service"; /** * Token超时时间(单位:秒) * <p>默认:36000(10小时) */ private Integer tokenTimeout = 36000; /** * 验证码超时时间(单位:秒) * <p>默认:360(6分钟) */ private Integer captchaTimeout = 360; }
0
java-sources/ai/ylyue/yue-library-auth-service/2.1.0/ai/yue/library/auth/service/config
java-sources/ai/ylyue/yue-library-auth-service/2.1.0/ai/yue/library/auth/service/config/properties/QqProperties.java
package ai.yue.library.auth.service.config.properties; import org.springframework.boot.context.properties.ConfigurationProperties; import lombok.Data; /** * QQ可配置属性 * * @author ylyue * @since 2018年11月6日 */ @Data @ConfigurationProperties(QqProperties.PREFIX) public class QqProperties { /** * Prefix of {@link QqProperties}. */ public static final String PREFIX = AuthServiceProperties.PREFIX + ".qq"; /** * QQ-appid */ private String qqAppid; }
0
java-sources/ai/ylyue/yue-library-auth-service/2.1.0/ai/yue/library/auth/service/config
java-sources/ai/ylyue/yue-library-auth-service/2.1.0/ai/yue/library/auth/service/config/properties/WxMaProperties.java
package ai.yue.library.auth.service.config.properties; import java.util.List; import org.springframework.boot.context.properties.ConfigurationProperties; import lombok.Data; /** * 微信小程序可配置属性 * * @author ylyue * @since 2019年6月18日 */ @Data @ConfigurationProperties(WxMaProperties.PREFIX) public class WxMaProperties { /** * Prefix of {@link WxMaProperties}. */ public static final String PREFIX = AuthServiceProperties.PREFIX + ".wx.miniapp"; /** * 是否启用 <code style="color:red">微信小程序</code> 自动配置 * <p> * 默认:false */ private boolean enabled = false; /** * 配置列表 */ private List<Config> configs; @Data public static class Config { /** * 设置微信小程序的appid */ private String appid; /** * 设置微信小程序的Secret */ private String secret; // /** // * 设置微信小程序消息服务器配置的token // */ // private String token; // // /** // * 设置微信小程序消息服务器配置的EncodingAESKey // */ // private String aesKey; // // /** // * 消息格式,XML或者JSON // */ // private String msgDataFormat; } }
0
java-sources/ai/ylyue/yue-library-auth-service/2.1.0/ai/yue/library/auth/service/config
java-sources/ai/ylyue/yue-library-auth-service/2.1.0/ai/yue/library/auth/service/config/properties/WxOpenProperties.java
package ai.yue.library.auth.service.config.properties; import org.springframework.boot.context.properties.ConfigurationProperties; import lombok.Data; /** * 微信开放平台可配置属性 * * @author ylyue * @since 2018年11月6日 */ @Data @ConfigurationProperties(WxOpenProperties.PREFIX) public class WxOpenProperties { /** * Prefix of {@link WxOpenProperties}. */ public static final String PREFIX = AuthServiceProperties.PREFIX + ".wx.open"; /** * 微信开放平台-appid */ private String appid; /** * 微信开放平台-密钥 */ private String secret; }
0
java-sources/ai/ylyue/yue-library-auth-service/2.1.0/ai/yue/library/auth/service/config
java-sources/ai/ylyue/yue-library-auth-service/2.1.0/ai/yue/library/auth/service/config/properties/package-info.java
/** * AuthService自动配置属性 * * @author ylyue * @since 2019年10月14日 */ package ai.yue.library.auth.service.config.properties;
0
java-sources/ai/ylyue/yue-library-auth-service/2.1.0/ai/yue/library/auth/service
java-sources/ai/ylyue/yue-library-auth-service/2.1.0/ai/yue/library/auth/service/dto/QqUserDTO.java
package ai.yue.library.auth.service.dto; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; /** * QQ用户信息 * * @author ylyue * @since 2018年9月11日 */ @Data @NoArgsConstructor @AllArgsConstructor public class QqUserDTO { String nickname; String figureurl_qq_1; Character gender; }
0
java-sources/ai/ylyue/yue-library-auth-service/2.1.0/ai/yue/library/auth/service
java-sources/ai/ylyue/yue-library-auth-service/2.1.0/ai/yue/library/auth/service/dto/WxUserDTO.java
package ai.yue.library.auth.service.dto; import com.alibaba.fastjson.JSONArray; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; /** * 微信用户信息 * * @author ylyue * @since 2018年9月11日 */ @Data @NoArgsConstructor @AllArgsConstructor public class WxUserDTO { String openid; String nickname; Character sex; String country; String province; String city; String headimgurl; JSONArray privilege; String unionid; }
0
java-sources/ai/ylyue/yue-library-auth-service/2.1.0/ai/yue/library/auth/service
java-sources/ai/ylyue/yue-library-auth-service/2.1.0/ai/yue/library/auth/service/dto/package-info.java
/** * DTO定义 * * @author ylyue * @since 2019年10月14日 */ package ai.yue.library.auth.service.dto;
0
java-sources/ai/ylyue/yue-library-auth-service/2.1.0/ai/yue/library/auth/service
java-sources/ai/ylyue/yue-library-auth-service/2.1.0/ai/yue/library/auth/service/vo/package-info.java
/** * VO定义 * * @author ylyue * @since 2019年10月14日 */ package ai.yue.library.auth.service.vo;
0
java-sources/ai/ylyue/yue-library-auth-service/2.1.0/ai/yue/library/auth/service/vo/wx
java-sources/ai/ylyue/yue-library-auth-service/2.1.0/ai/yue/library/auth/service/vo/wx/open/AccessTokenVO.java
package ai.yue.library.auth.service.vo.wx.open; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; /** * 访问授权令牌信息-微信开放平台 * * @author ylyue * @since 2018年9月11日 */ @Data @NoArgsConstructor @AllArgsConstructor public class AccessTokenVO { String access_token;// 接口调用凭证 Integer expires_in;// access_token接口调用凭证超时时间,单位(秒) String refresh_token;// 用户刷新access_token String openid;// 授权用户唯一标识 String scope;// 用户授权的作用域,使用逗号(,)分隔 }
0
java-sources/ai/ylyue/yue-library-auth-service/2.1.0/ai/yue/library/auth/service/vo/wx
java-sources/ai/ylyue/yue-library-auth-service/2.1.0/ai/yue/library/auth/service/vo/wx/open/package-info.java
/** * VO定义-微信开放平台 * * @author ylyue * @since 2019年10月14日 */ package ai.yue.library.auth.service.vo.wx.open;
0
java-sources/ai/ylyue/yue-library-base/2.1.0/ai/yue/library
java-sources/ai/ylyue/yue-library-base/2.1.0/ai/yue/library/base/package-info.java
/** * yue-library是一个基于SpringBoot封装的基础库,内置丰富的JDK工具,自动装配了一系列的基础Bean与环境配置项,可用于快速构建SpringCloud项目,让微服务变得更简单。 * * @author ylyue * @since 2019年10月13日 */ package ai.yue.library.base;
0
java-sources/ai/ylyue/yue-library-base/2.1.0/ai/yue/library/base/annotation/api
java-sources/ai/ylyue/yue-library-base/2.1.0/ai/yue/library/base/annotation/api/version/ApiVersion.java
package ai.yue.library.base.annotation.api.version; import java.lang.annotation.Documented; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * Restful API接口版本定义 * <p>为接口提供优雅的版本路径,效果如下: * <blockquote> * <p>&#064;ApiVersion(1) * <p>&#064;RequestMapping("/{version}/user") * </blockquote> * 实际请求路径值:/v1/user * * @author ylyue * @since 2020年2月24日 */ @Documented @Retention(RetentionPolicy.RUNTIME) @Target({ ElementType.TYPE, ElementType.METHOD }) public @interface ApiVersion { /** * Restful API接口版本号 * <p>最近优先原则:在方法上的 {@link ApiVersion} 可覆盖在类上面的 {@link ApiVersion},如下: * <p>类上面的 {@link #value()} 值 = 1.1, * <p>方法上面的 {@link #value()} 值 = 2.1, * <p>最终效果:v2.1 */ double value() default 1; /** * 是否废弃版本接口 * <p>客户端请求废弃版本接口时将抛出错误提示: * <p>当前版本已停用,请升级到最新版本 */ boolean deprecated() default false; }
0
java-sources/ai/ylyue/yue-library-base/2.1.0/ai/yue/library/base/annotation/api
java-sources/ai/ylyue/yue-library-base/2.1.0/ai/yue/library/base/annotation/api/version/ApiVersionProperties.java
package ai.yue.library.base.annotation.api.version; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.web.bind.annotation.RequestMapping; import lombok.Data; /** * Restful API接口版本定义自动配置属性 * * @author ylyue * @since 2018年11月6日 */ @Data @ConfigurationProperties("yue.api-version") public class ApiVersionProperties { /** * 是否启用 <code style="color:red">Restful API接口版本控制</code> * <p> * 默认:true */ private boolean enabled = true; /** * 最小版本号,小于该版本号返回版本过时。 */ private double minimumVersion; /** * {@link RequestMapping} 版本占位符,如下所示: * <p>/{version}/user * <p>/user/{version} */ private String versionPlaceholder = "{version}"; }
0
java-sources/ai/ylyue/yue-library-base/2.1.0/ai/yue/library/base
java-sources/ai/ylyue/yue-library-base/2.1.0/ai/yue/library/base/config/BaseAutoConfig.java
package ai.yue.library.base.config; import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; import org.springframework.boot.context.properties.EnableConfigurationProperties; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Import; import org.springframework.web.client.RestTemplate; import ai.yue.library.base.annotation.api.version.ApiVersionProperties; import ai.yue.library.base.config.datetime.DateTimeFormatConfig; import ai.yue.library.base.config.handler.ExceptionHandlerProperties; import ai.yue.library.base.config.http.HttpsRequestFactory; import ai.yue.library.base.config.http.RestProperties; import ai.yue.library.base.config.properties.CorsProperties; import ai.yue.library.base.config.thread.pool.AsyncConfig; import ai.yue.library.base.util.ApplicationContextUtils; import ai.yue.library.base.util.SpringUtils; import ai.yue.library.base.validation.Validator; import lombok.extern.slf4j.Slf4j; /** * base bean 自动配置 * * @author ylyue * @since 2018年11月26日 */ @Slf4j @Configuration @Import({ AsyncConfig.class, ApplicationContextUtils.class, SpringUtils.class, DateTimeFormatConfig.class }) @EnableConfigurationProperties({ ApiVersionProperties.class, ExceptionHandlerProperties.class, RestProperties.class, CorsProperties.class, }) public class BaseAutoConfig { // RestTemplate-HTTPS客户端 @Bean @ConditionalOnMissingBean public RestTemplate restTemplate(RestProperties restProperties){ HttpsRequestFactory factory = new HttpsRequestFactory(); // 设置链接超时时间 Integer connectTimeout = restProperties.getConnectTimeout(); if (connectTimeout != null) { factory.setConnectTimeout(connectTimeout); } // 设置读取超时时间 Integer readTimeout = restProperties.getReadTimeout(); if (readTimeout != null) { factory.setReadTimeout(readTimeout); } log.info("【初始化配置-HTTPS客户端】Bean:RestTemplate ... 已初始化完毕。"); return new RestTemplate(factory); } // Validator-校验器 @Bean @ConditionalOnMissingBean public Validator validator(){ log.info("【初始化配置-校验器】Bean:Validator ... 已初始化完毕。"); return new Validator(); } }
0
java-sources/ai/ylyue/yue-library-base/2.1.0/ai/yue/library/base
java-sources/ai/ylyue/yue-library-base/2.1.0/ai/yue/library/base/config/package-info.java
/** * base配置包,提供自动配置项支持与增强 * * @author ylyue * @since 2019年9月16日 */ package ai.yue.library.base.config;
0
java-sources/ai/ylyue/yue-library-base/2.1.0/ai/yue/library/base/config
java-sources/ai/ylyue/yue-library-base/2.1.0/ai/yue/library/base/config/datetime/DateTimeFormatConfig.java
package ai.yue.library.base.config.datetime; import java.time.LocalDate; import java.time.LocalDateTime; import java.time.LocalTime; import org.springframework.boot.autoconfigure.jackson.Jackson2ObjectMapperBuilderCustomizer; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.core.convert.converter.Converter; import org.springframework.web.bind.annotation.RequestBody; import com.fasterxml.jackson.datatype.jsr310.deser.LocalDateDeserializer; import com.fasterxml.jackson.datatype.jsr310.deser.LocalDateTimeDeserializer; import com.fasterxml.jackson.datatype.jsr310.deser.LocalTimeDeserializer; import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateSerializer; import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateTimeSerializer; import com.fasterxml.jackson.datatype.jsr310.ser.LocalTimeSerializer; import ai.yue.library.base.util.DateUtils; /** * 日期时间格式化配置 * * @author ylyue * @since 2020年2月28日 */ @Configuration public class DateTimeFormatConfig { /** * 关于日期时间反序列化,只有在使用 {@link RequestBody} 时有效 * * @return 自定义序列化器 */ @Bean public Jackson2ObjectMapperBuilderCustomizer jackson2ObjectMapperBuilderCustomizer() { return builder -> builder.serializerByType(LocalDateTime.class, new LocalDateTimeSerializer(DateUtils.DATE_TIME_FORMATTER)) .serializerByType(LocalDate.class, new LocalDateSerializer(DateUtils.DATE_FORMATTER)) .serializerByType(LocalTime.class, new LocalTimeSerializer(DateUtils.TIME_FORMATTER)) .deserializerByType(LocalDateTime.class, new LocalDateTimeDeserializer(DateUtils.DATE_TIME_FORMATTER)) .deserializerByType(LocalDate.class, new LocalDateDeserializer(DateUtils.DATE_FORMATTER)) .deserializerByType(LocalTime.class, new LocalTimeDeserializer(DateUtils.TIME_FORMATTER)); } // ~ 没有使用 {@link RequestBody} 反序列化时生效 // ================================================================================================ /** * 日期参数接收转换器,将json字符串转为日期类型 * * @return MVC LocalDateTime 参数接收转换器 */ @Bean public Converter<String, LocalDateTime> localDateTimeConvert() { return new Converter<String, LocalDateTime>() { @Override public LocalDateTime convert(String source) { return LocalDateTime.parse(source, DateUtils.DATE_TIME_FORMATTER); } }; } /** * 日期参数接收转换器,将json字符串转为日期类型 * * @return MVC LocalDate 参数接收转换器 */ @Bean public Converter<String, LocalDate> localDateConvert() { return new Converter<String, LocalDate>() { @Override public LocalDate convert(String source) { return LocalDate.parse(source, DateUtils.DATE_FORMATTER); } }; } /** * 日期参数接收转换器,将json字符串转为日期类型 * * @return MVC LocalTime 参数接收转换器 */ @Bean public Converter<String, LocalTime> localTimeConvert() { return new Converter<String, LocalTime>() { @Override public LocalTime convert(String source) { return LocalTime.parse(source, DateUtils.TIME_FORMATTER); } }; } }
0
java-sources/ai/ylyue/yue-library-base/2.1.0/ai/yue/library/base/config
java-sources/ai/ylyue/yue-library-base/2.1.0/ai/yue/library/base/config/handler/AbstractExceptionHandler.java
package ai.yue.library.base.config.handler; import java.io.IOException; import javax.annotation.PostConstruct; import javax.validation.Valid; import org.springframework.http.HttpStatus; import org.springframework.validation.BindException; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.bind.annotation.ResponseStatus; import ai.yue.library.base.exception.ApiVersionDeprecatedException; import ai.yue.library.base.exception.AttackException; import ai.yue.library.base.exception.AuthorizeException; import ai.yue.library.base.exception.ClientFallbackException; import ai.yue.library.base.exception.DbException; import ai.yue.library.base.exception.ForbiddenException; import ai.yue.library.base.exception.LoginException; import ai.yue.library.base.exception.ParamDecryptException; import ai.yue.library.base.exception.ParamException; import ai.yue.library.base.exception.ParamVoidException; import ai.yue.library.base.exception.ResultException; import ai.yue.library.base.util.ExceptionUtils; import ai.yue.library.base.view.Result; import ai.yue.library.base.view.ResultInfo; import cn.hutool.core.convert.ConvertException; import cn.hutool.core.exceptions.ValidateException; import lombok.extern.slf4j.Slf4j; /** * 全局统一异常处理 * * @author ylyue * @since 2017年10月8日 */ @Slf4j public abstract class AbstractExceptionHandler { @PostConstruct private void init() { log.info("【初始化配置-全局统一异常处理】拦截所有Controller层异常,返回HTTP请求最外层对象 ... 已初始化完毕。"); } // Restful 异常拦截 /** * 异常结果处理-synchronized * * @param e 结果异常 * @return 结果 */ @ResponseBody @ExceptionHandler(ResultException.class) public abstract Result<?> resultExceptionHandler(ResultException e); /** * 拦截登录异常(User)-401 * @param e 登录异常 * @return 结果 */ @ResponseBody @ResponseStatus(code = HttpStatus.UNAUTHORIZED) @ExceptionHandler(LoginException.class) public Result<?> loginExceptionHandler(LoginException e) { ExceptionUtils.printException(e); return ResultInfo.unauthorized(); } /** * 非法请求异常拦截-402 * @param e 非法请求异常 * @return 结果 */ @ResponseBody @ResponseStatus(code = HttpStatus.PAYMENT_REQUIRED) @ExceptionHandler(AttackException.class) public Result<?> attackExceptionHandler(AttackException e) { ExceptionUtils.printException(e); return ResultInfo.attack(e.getMessage()); } /** * 无权限异常访问处理-403 * @param e 无权限异常 * @return 结果 */ @ResponseBody @ResponseStatus(code = HttpStatus.FORBIDDEN) @ExceptionHandler(ForbiddenException.class) public Result<?> forbiddenExceptionHandler(ForbiddenException e) { ExceptionUtils.printException(e); return ResultInfo.forbidden(); } /** * 拦截API接口版本弃用异常-410 * * @param e API接口版本弃用异常 * @return 结果 */ @ResponseBody @ResponseStatus(code = HttpStatus.GONE) @ExceptionHandler(ApiVersionDeprecatedException.class) public Result<?> apiVersionDeprecatedExceptionHandler(ApiVersionDeprecatedException e) { ExceptionUtils.printException(e); return ResultInfo.gone(); } /** * 参数效验为空统一处理-432 * @return 结果 */ @ResponseBody @ExceptionHandler(ParamVoidException.class) public abstract Result<?> paramVoidExceptionHandler(); /** * 参数效验未通过统一处理-433 * @param e 参数校验未通过异常 * @return 结果 */ @ResponseBody @ExceptionHandler(ParamException.class) public abstract Result<?> paramExceptionHandler(ParamException e); /** * {@linkplain Valid} 验证异常统一处理-433 * @param e 验证异常 * @return 结果 */ @ResponseBody @ExceptionHandler(BindException.class) public abstract Result<?> bindExceptionHandler(BindException e); /** * 验证异常统一处理-433 * @param e 验证异常 * @return 结果 */ @ResponseBody @ExceptionHandler(ValidateException.class) public abstract Result<?> validateExceptionHandler(ValidateException e); /** * 解密异常统一处理-435 * * @param e 解密异常 * @return 结果 */ @ResponseBody @ExceptionHandler(ParamDecryptException.class) public abstract Result<?> paramDecryptExceptionHandler(ParamDecryptException e); /** * 拦截所有未处理异常-500 * @param e 异常 * @return 结果 */ @ResponseBody @ResponseStatus @ExceptionHandler(Exception.class) public Result<?> exceptionHandler(Exception e) { e.printStackTrace(); return ResultInfo.internalServerError(e.toString()); } /** * DB异常统一处理-506 * @param e DB异常 * @return 结果 */ @ResponseBody @ResponseStatus(code = HttpStatus.VARIANT_ALSO_NEGOTIATES) @ExceptionHandler(DbException.class) public Result<?> dbExceptionHandler(DbException e) { e.printStackTrace(); if (e.isShowMsg()) { return ResultInfo.dbError(e.getMessage()); } return ResultInfo.dbError(); } /** * 服务降级-507 * @param e 服务降级异常 * @return 结果 */ @ResponseBody @ResponseStatus(code = HttpStatus.INSUFFICIENT_STORAGE) @ExceptionHandler(ClientFallbackException.class) public Result<?> clientFallbackExceptionHandler(ClientFallbackException e) { ExceptionUtils.printException(e); return ResultInfo.clientFallback(); } /** * 类型转换异常统一处理-509 * * @param e 转换异常 * @return 结果 */ @ResponseBody @ResponseStatus(code = HttpStatus.BANDWIDTH_LIMIT_EXCEEDED) @ExceptionHandler(ConvertException.class) public Result<?> convertExceptionHandler(ConvertException e) { log.error("【类型转换异常】转换类型失败,错误信息如下:{}", e.getMessage()); ExceptionUtils.printException(e); return ResultInfo.typeConvertError(e.getMessage()); } // WEB 异常拦截 /** * 拦截登录异常(Admin)-301 * * @param e 认证异常 * @throws IOException 重定向失败 */ @ExceptionHandler(AuthorizeException.class) public abstract void authorizeExceptionHandler(AuthorizeException e) throws IOException; }
0
java-sources/ai/ylyue/yue-library-base/2.1.0/ai/yue/library/base/config
java-sources/ai/ylyue/yue-library-base/2.1.0/ai/yue/library/base/config/handler/ExceptionHandlerProperties.java
package ai.yue.library.base.config.handler; import org.springframework.boot.context.properties.ConfigurationProperties; import lombok.Data; /** * 全局统一异常处理自动配置属性 * * @author ylyue * @since 2018年11月6日 */ @Data @ConfigurationProperties("yue.exception-handler") public class ExceptionHandlerProperties { /** * 是否启用 <code style="color:red">全局统一异常处理</code> 自动配置 * <p> * 默认:true */ private boolean enabled = true; }
0
java-sources/ai/ylyue/yue-library-base/2.1.0/ai/yue/library/base/config
java-sources/ai/ylyue/yue-library-base/2.1.0/ai/yue/library/base/config/handler/package-info.java
/** * 全局统一异常处理 * * @author ylyue * @since 2019年10月13日 */ package ai.yue.library.base.config.handler;
0
java-sources/ai/ylyue/yue-library-base/2.1.0/ai/yue/library/base/config
java-sources/ai/ylyue/yue-library-base/2.1.0/ai/yue/library/base/config/http/HttpsRequestFactory.java
package ai.yue.library.base.config.http; import java.io.IOException; import java.net.HttpURLConnection; import java.security.SecureRandom; import java.security.cert.X509Certificate; import javax.net.ssl.HostnameVerifier; import javax.net.ssl.HttpsURLConnection; import javax.net.ssl.SSLContext; import javax.net.ssl.SSLSession; import javax.net.ssl.SSLSocketFactory; import javax.net.ssl.TrustManager; import javax.net.ssl.X509TrustManager; import org.springframework.http.client.SimpleClientHttpRequestFactory; /** * @author ylyue * @since 2018年11月10日 */ public class HttpsRequestFactory extends SimpleClientHttpRequestFactory { @Override protected void prepareConnection(HttpURLConnection connection, String httpMethod) throws IOException { if (connection instanceof HttpsURLConnection) { prepareHttpsConnection((HttpsURLConnection) connection); } super.prepareConnection(connection, httpMethod); } private void prepareHttpsConnection(HttpsURLConnection connection) { connection.setHostnameVerifier(new SkipHostnameVerifier()); try { connection.setSSLSocketFactory(createSslSocketFactory()); } catch (Exception ex) { // Ignore } } private SSLSocketFactory createSslSocketFactory() throws Exception { SSLContext context = SSLContext.getInstance("TLS"); context.init(null, new TrustManager[] { new SkipX509TrustManager() }, new SecureRandom()); return context.getSocketFactory(); } private class SkipHostnameVerifier implements HostnameVerifier { @Override public boolean verify(String s, SSLSession sslSession) { return true; } } private static class SkipX509TrustManager implements X509TrustManager { @Override public X509Certificate[] getAcceptedIssuers() { return new X509Certificate[0]; } @Override public void checkClientTrusted(X509Certificate[] chain, String authType) { } @Override public void checkServerTrusted(X509Certificate[] chain, String authType) { } } }
0
java-sources/ai/ylyue/yue-library-base/2.1.0/ai/yue/library/base/config
java-sources/ai/ylyue/yue-library-base/2.1.0/ai/yue/library/base/config/http/RestProperties.java
package ai.yue.library.base.config.http; import org.springframework.boot.context.properties.ConfigurationProperties; import lombok.Data; /** * @author ylyue * @since 2018年11月6日 */ @Data @ConfigurationProperties("yue.rest") public class RestProperties { /** * 链接超时时间(单位:毫秒) * <p>0 = 不超时 * <p>默认:系统“默认”的超时设置 */ private Integer connectTimeout; /** * 读取超时时间(单位:毫秒) * <p>0 = 不超时 * <p>默认:系统“默认”的超时设置 */ private Integer readTimeout; }
0
java-sources/ai/ylyue/yue-library-base/2.1.0/ai/yue/library/base/config
java-sources/ai/ylyue/yue-library-base/2.1.0/ai/yue/library/base/config/http/package-info.java
/** * RestTemplate-HTTPS客户端 * * @author ylyue * @since 2019年10月13日 */ package ai.yue.library.base.config.http;
0
java-sources/ai/ylyue/yue-library-base/2.1.0/ai/yue/library/base/config
java-sources/ai/ylyue/yue-library-base/2.1.0/ai/yue/library/base/config/properties/CorsProperties.java
package ai.yue.library.base.config.properties; import java.util.List; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.web.cors.CorsConfiguration; import lombok.Data; /** * 跨域自动配置属性 * * @author ylyue * @since 2018年11月6日 */ @Data @ConfigurationProperties("yue.cors") public class CorsProperties { /** * 是否允许 <code style="color:red">跨域</code> * <p> * 默认:true */ private boolean allow = true; /** * response允许暴露的Headers * <p> * 默认:{@linkplain CorsConfiguration#setExposedHeaders(List)} * ({@code Cache-Control}, {@code Content-Language}, {@code Content-Type}, * {@code Expires}, {@code Last-Modified}, or {@code Pragma}) * 此外在此基础之上还额外的增加了一个名为 <b>token</b> 的Headers */ private List<String> exposedHeaders; }
0
java-sources/ai/ylyue/yue-library-base/2.1.0/ai/yue/library/base/config
java-sources/ai/ylyue/yue-library-base/2.1.0/ai/yue/library/base/config/properties/package-info.java
/** * 属性配置 * * @author ylyue * @since 2019年10月13日 */ package ai.yue.library.base.config.properties;
0
java-sources/ai/ylyue/yue-library-base/2.1.0/ai/yue/library/base/config/thread
java-sources/ai/ylyue/yue-library-base/2.1.0/ai/yue/library/base/config/thread/pool/AsyncConfig.java
package ai.yue.library.base.config.thread.pool; import java.lang.reflect.Method; import java.util.concurrent.Executor; import javax.annotation.PostConstruct; import org.springframework.aop.interceptor.AsyncUncaughtExceptionHandler; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.boot.context.properties.EnableConfigurationProperties; import org.springframework.context.annotation.Configuration; import org.springframework.scheduling.annotation.AsyncConfigurer; import org.springframework.scheduling.annotation.EnableAsync; import lombok.extern.slf4j.Slf4j; /** * <b>异步线程池</b> * <p> * 共用父线程上下文环境,异步执行任务时不丢失token * <p> * <b style="color:red">注意,@Async异步执行方法,不要和同步调用方法,写在同一个类中,否则异步执行将失效。</b> * @author ylyue * @since 2017年10月13日 */ @Slf4j @EnableAsync @Configuration @EnableConfigurationProperties(AsyncProperties.class) @ConditionalOnProperty(prefix = "yue.thread-pool.async", name = "enabled", havingValue = "true") public class AsyncConfig implements AsyncConfigurer { @Autowired AsyncProperties asyncProperties; @PostConstruct private void init() { log.info("【初始化配置-异步线程池】异步线程池配置已加载,待使用时初始化 ..."); } /** * 自定义异常处理类 */ @Override public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() { return new AsyncUncaughtExceptionHandler() { @Override public void handleUncaughtException(Throwable arg0, Method arg1, Object... arg2) { log.error("=========================={}=======================", arg0.getMessage(), arg0); log.error("exception method: {}", arg1.getName()); for (Object param : arg2) { log.error("Parameter value - {}", param); } } }; } /** * 异步线程池<br> * 实现AsyncConfigurer接口并重写getAsyncExecutor方法,返回一个ThreadPoolTaskExecutor,这样我们就获得了一个基本线程池TaskExecutor。 */ @Override public Executor getAsyncExecutor() { ContextAwareAsyncExecutor executor = new ContextAwareAsyncExecutor(); executor.setThreadNamePrefix(asyncProperties.getThreadNamePrefix());// 线程池名的前缀 executor.setCorePoolSize(asyncProperties.getCorePoolSize());// 核心线程数 executor.setMaxPoolSize(asyncProperties.getMaxPoolSize());// 最大线程数 executor.setKeepAliveSeconds(asyncProperties.getKeepAliveSeconds());// 允许线程的空闲时间 executor.setQueueCapacity(asyncProperties.getQueueCapacity());// 缓冲队列数 executor.setAllowCoreThreadTimeOut(asyncProperties.getAllowCoreThreadTimeOut());// 是否允许核心线程超时 executor.setWaitForTasksToCompleteOnShutdown(asyncProperties.getWaitForTasksToCompleteOnShutdown());// 应用关闭时-是否等待未完成任务继续执行,再继续销毁其他的Bean executor.setAwaitTerminationSeconds(asyncProperties.getAwaitTerminationSeconds());// 应用关闭时-继续等待时间(单位:秒) executor.setRejectedExecutionHandler(asyncProperties.getRejectedExecutionHandlerPolicy().getRejectedExecutionHandler());// 线程池拒绝策略 executor.initialize(); log.info("【初始化配置-异步线程池】共用父线程上下文环境,异步执行任务时不丢失token ... 已初始化完毕。"); return executor; } }
0
java-sources/ai/ylyue/yue-library-base/2.1.0/ai/yue/library/base/config/thread
java-sources/ai/ylyue/yue-library-base/2.1.0/ai/yue/library/base/config/thread/pool/AsyncProperties.java
package ai.yue.library.base.config.thread.pool; import org.springframework.boot.context.properties.ConfigurationProperties; import lombok.Data; /** * 异步线程池自动配置属性 * * @author ylyue * @since 2018年11月6日 */ @Data @ConfigurationProperties("yue.thread-pool.async") public class AsyncProperties { /** * 是否启用 <code style="color:red">异步线程池</code> 自动配置 * <p> * 默认:false * <p> * <b style="color:red">注意,@Async异步执行方法,不要和同步调用方法,写在同一个类中,否则异步执行将失效。</b> */ private boolean enabled = false; /** * 线程池名的前缀 * <p> * 设置好了之后可以方便我们定位处理任务所在的线程池 * <p> * 默认:async-exec- */ private String threadNamePrefix = "async-exec-"; /** * 核心线程数 * <p> * 线程池创建时候初始化的线程数 * <p> * 默认:10 */ private Integer corePoolSize = 10; /** * 最大线程数 * <p> * 线程池最大的线程数,只有在缓冲队列满了之后才会申请超过核心线程数的线程 * <p> * 默认:20 */ private Integer maxPoolSize = 20; /** * 允许线程的空闲时间(单位:秒) * <p> * 当超过了核心线程数之外的线程在空闲时间到达之后会被销毁 * <p> * 默认:60 */ private Integer keepAliveSeconds = 60; /** * 缓冲队列 * <p> * 用来缓冲执行任务的队列 * <p> * 默认:200 */ private Integer queueCapacity = 200; /** * 是否允许核心线程超时 * <p> * 默认:false */ private Boolean allowCoreThreadTimeOut = false; /** * 应用关闭时-是否等待未完成任务继续执行,再继续销毁其他的Bean * <p> * 默认:true */ private Boolean waitForTasksToCompleteOnShutdown = true; /** * 依赖 {@linkplain #waitForTasksToCompleteOnShutdown} 为true * <p> * 应用关闭时-继续等待时间(单位:秒) * <p> * 如果超过这个时间还没有销毁就强制销毁,以确保应用最后能够被关闭,而不是阻塞住 * <p> * 默认:10 */ private Integer awaitTerminationSeconds = 10; /** * 线程池拒绝策略 * <p> * 默认:{@linkplain RejectedExecutionHandlerPolicy#CALLER_RUNS_POLICY} */ private RejectedExecutionHandlerPolicy rejectedExecutionHandlerPolicy = RejectedExecutionHandlerPolicy.CALLER_RUNS_POLICY; }
0
java-sources/ai/ylyue/yue-library-base/2.1.0/ai/yue/library/base/config/thread
java-sources/ai/ylyue/yue-library-base/2.1.0/ai/yue/library/base/config/thread/pool/ContextAwareAsyncExecutor.java
package ai.yue.library.base.config.thread.pool; import java.util.concurrent.Callable; import java.util.concurrent.Future; import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor; import org.springframework.util.concurrent.ListenableFuture; import org.springframework.web.context.request.RequestContextHolder; /** * @author ylyue * @since 2018年11月27日 */ public class ContextAwareAsyncExecutor extends ThreadPoolTaskExecutor { private static final long serialVersionUID = -946431910133805893L; @Override public <T> Future<T> submit(Callable<T> task) { return super.submit(new ContextAwareCallable<T>(task, RequestContextHolder.currentRequestAttributes())); } @Override public <T> ListenableFuture<T> submitListenable(Callable<T> task) { return super.submitListenable(new ContextAwareCallable<T>(task, RequestContextHolder.currentRequestAttributes())); } }
0
java-sources/ai/ylyue/yue-library-base/2.1.0/ai/yue/library/base/config/thread
java-sources/ai/ylyue/yue-library-base/2.1.0/ai/yue/library/base/config/thread/pool/ContextAwareCallable.java
package ai.yue.library.base.config.thread.pool; import java.util.concurrent.Callable; import org.springframework.web.context.request.RequestAttributes; import org.springframework.web.context.request.RequestContextHolder; /** * @author ylyue * @since 2018年11月27日 */ public class ContextAwareCallable<T> implements Callable<T> { private Callable<T> task; private RequestAttributes context; public ContextAwareCallable(Callable<T> task, RequestAttributes context) { this.task = task; this.context = context; } @Override public T call() throws Exception { if (context != null) { RequestContextHolder.setRequestAttributes(context); } try { return task.call(); } finally { RequestContextHolder.resetRequestAttributes(); } } }
0
java-sources/ai/ylyue/yue-library-base/2.1.0/ai/yue/library/base/config/thread
java-sources/ai/ylyue/yue-library-base/2.1.0/ai/yue/library/base/config/thread/pool/RejectedExecutionHandlerPolicy.java
package ai.yue.library.base.config.thread.pool; import java.util.concurrent.RejectedExecutionException; import java.util.concurrent.RejectedExecutionHandler; import java.util.concurrent.ThreadPoolExecutor; import lombok.AllArgsConstructor; import lombok.Getter; /** * @author ylyue * @since 2019年7月9日 */ @Getter @AllArgsConstructor public enum RejectedExecutionHandlerPolicy { /** * 当线程池的所有线程都已经被占用时抛出 {@link RejectedExecutionException} 异常。 */ ABORT_POLICY(new ThreadPoolExecutor.AbortPolicy()), /** * 当线程池的所有线程都已经被占用时,将由原始线程来执行任务(若原始线程已关闭将直接丢弃任务)。 */ CALLER_RUNS_POLICY(new ThreadPoolExecutor.CallerRunsPolicy()), /** * 当线程池的所有线程都已经被占用时,它丢弃最古老的未处理请求,然后重试执行(若执行程序已关闭将直接丢弃任务)。 */ DISCARD_OLDEST_POLICY(new ThreadPoolExecutor.DiscardOldestPolicy()), /** * 当线程池的所有线程都已经被占用时,将悄悄地丢弃被拒绝的任务。 */ DISCARD_POLICY(new ThreadPoolExecutor.DiscardPolicy()); RejectedExecutionHandler rejectedExecutionHandler; }
0
java-sources/ai/ylyue/yue-library-base/2.1.0/ai/yue/library/base/config/thread
java-sources/ai/ylyue/yue-library-base/2.1.0/ai/yue/library/base/config/thread/pool/package-info.java
/** * 异步线程池配置 * * @author ylyue * @since 2019年10月13日 */ package ai.yue.library.base.config.thread.pool;
0
java-sources/ai/ylyue/yue-library-base/2.1.0/ai/yue/library/base
java-sources/ai/ylyue/yue-library-base/2.1.0/ai/yue/library/base/constant/Constant.java
package ai.yue.library.base.constant; /** * yue-library 定义的标识常量 * * @author ylyue * @since 2020年7月25日 */ public interface Constant { /** yue-library前缀 */ String PREFIX = "yue-library-"; /** body参数传递 */ String BODY_PARAM_TRANSMIT = PREFIX + "Body-Param-Transmit"; }
0
java-sources/ai/ylyue/yue-library-base/2.1.0/ai/yue/library/base
java-sources/ai/ylyue/yue-library-base/2.1.0/ai/yue/library/base/constant/FieldNamingStrategyEnum.java
package ai.yue.library.base.constant; import com.alibaba.fastjson.PropertyNamingStrategy; import lombok.AllArgsConstructor; import lombok.Getter; /** * 字段命名策略 * * @author ylyue * @since 2020年2月20日 */ @Getter @AllArgsConstructor public enum FieldNamingStrategyEnum { /** * 驼峰命名法,即:小驼峰命名法 * <p>CAMEL_CASE策略,Java对象属性:personId,序列化后属性:persionId */ CAMEL_CASE(PropertyNamingStrategy.CamelCase), /** * 小驼峰命名法 * <p>{@link #CAMEL_CASE} */ LOWER_CAMEL_CASE(PropertyNamingStrategy.CamelCase), /** * 大驼峰命名法 * <p>{@link #PASCAL_CASE} */ UPPER_CAMEL_CASE(PropertyNamingStrategy.PascalCase), /** * 帕斯卡命名法,即:大驼峰命名法 * <p>PASCAL_CASE策略,Java对象属性:personId,序列化后属性:PersonId */ PASCAL_CASE(PropertyNamingStrategy.PascalCase), /** * 下划线命名法 * <p>SNAKE_CASE策略,Java对象属性:personId,序列化后属性:person_id */ SNAKE_CASE(PropertyNamingStrategy.SnakeCase), /** * 中划线命名法 * <p>KEBAB_CASE策略,Java对象属性:personId,序列化后属性:person-id */ KEBAB_CASE(PropertyNamingStrategy.KebabCase); private PropertyNamingStrategy propertyNamingStrategy; }
0
java-sources/ai/ylyue/yue-library-base/2.1.0/ai/yue/library/base
java-sources/ai/ylyue/yue-library-base/2.1.0/ai/yue/library/base/constant/FilterModeEnum.java
package ai.yue.library.base.constant; import lombok.AllArgsConstructor; import lombok.Getter; /** * 筛选方式枚举 * * @author ylyue * @since 2018年9月18日 */ @Getter @AllArgsConstructor public enum FilterModeEnum { 小于(" < "), 大于(" > "), 等于(" = "), 小于等于(" <= "), 大于等于(" >= "), 不等于(" != "), 包含(" LIKE ") { @Override public String processFilterSqlCode(String value) { return value = filterSqlCode + "'%" + value + "%'"; } }, 不包含(" NOT LIKE ") { @Override public String processFilterSqlCode(String value) { return value = filterSqlCode + "'%" + value + "%'"; } }; /** * 筛选SQL代码 */ String filterSqlCode; /** * 加工筛选SQL代码 * <p>需要加工的枚举:{@linkplain #包含},{@linkplain #不包含} * @param value 处理的值 * @return 筛选SQL代码 */ public String processFilterSqlCode(String value) { return filterSqlCode; } }
0
java-sources/ai/ylyue/yue-library-base/2.1.0/ai/yue/library/base
java-sources/ai/ylyue/yue-library-base/2.1.0/ai/yue/library/base/constant/MaxOrMinEnum.java
package ai.yue.library.base.constant; /** * 最大值 <i>或</i> 最小值 * * @author ylyue * @since 2018年8月29日 */ public enum MaxOrMinEnum { 最大值, 最小值; }
0
java-sources/ai/ylyue/yue-library-base/2.1.0/ai/yue/library/base
java-sources/ai/ylyue/yue-library-base/2.1.0/ai/yue/library/base/constant/SortEnum.java
package ai.yue.library.base.constant; /** * 排序方式 * * @author ylyue * @since 2018年8月29日 */ public enum SortEnum { 降序, 升序; }
0
java-sources/ai/ylyue/yue-library-base/2.1.0/ai/yue/library/base
java-sources/ai/ylyue/yue-library-base/2.1.0/ai/yue/library/base/constant/package-info.java
/** * 常量 * * @author ylyue * @since 2019年10月13日 */ package ai.yue.library.base.constant;
0
java-sources/ai/ylyue/yue-library-base/2.1.0/ai/yue/library/base
java-sources/ai/ylyue/yue-library-base/2.1.0/ai/yue/library/base/convert/Convert.java
package ai.yue.library.base.convert; import static com.alibaba.fastjson.JSON.toJSON; import static com.alibaba.fastjson.util.TypeUtils.cast; import static com.alibaba.fastjson.util.TypeUtils.castToJavaBean; import java.lang.reflect.Type; import java.time.LocalDate; import java.time.LocalDateTime; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Map; import com.alibaba.fastjson.JSONArray; import com.alibaba.fastjson.JSONObject; import com.alibaba.fastjson.parser.ParserConfig; import ai.yue.library.base.convert.converter.JSONArrayConverter; import ai.yue.library.base.convert.converter.JSONObjectConverter; import ai.yue.library.base.util.ExceptionUtils; import ai.yue.library.base.util.ListUtils; import cn.hutool.core.convert.ConvertException; import cn.hutool.core.convert.ConverterRegistry; import cn.hutool.core.lang.TypeReference; import lombok.extern.slf4j.Slf4j; /** * <b>类型转换器</b> * <p>提供简单全面的类型转换,适合更多的业务场景,内置hutool、fastjson、yue三种类型转换器,判断精确性能强大,未知类型兼容性更强 * * @author ylyue * @since 2019年7月23日 */ @Slf4j public class Convert extends cn.hutool.core.convert.Convert { // 注册自定义转换器 static { ConverterRegistry converterRegistry = ConverterRegistry.getInstance(); converterRegistry.putCustom(JSONObject.class, JSONObjectConverter.class); converterRegistry.putCustom(JSONArray.class, JSONArrayConverter.class); } // --------------------------------------- 覆盖hutool转换方法,防止直接调用父类静态方法,导致因为本类未加载,从而自定义转换器未注册 /** * 转换值为指定类型,类型采用字符串表示 * * @param <T> 目标类型 * @param className 类的字符串表示 * @param value 值 * @return 转换后的值 * @throws ConvertException 转换器不存在 */ public static <T> T convertByClassName(String className, Object value) throws ConvertException { return cn.hutool.core.convert.Convert.convertByClassName(className, value); } /** * 转换值为指定类型 * * @deprecated 请使用 {@linkplain #convert(Object, Class)} * @param <T> 目标类型 * @param type 类型 * @param value 值 * @return 转换后的值 * @throws ConvertException 转换器不存在 */ @Deprecated public static <T> T convert(Class<T> type, Object value) throws ConvertException { return cn.hutool.core.convert.Convert.convert(type, value); } /** * 转换值为指定类型 * * @param <T> 目标类型 * @param reference 类型参考,用于持有转换后的泛型类型 * @param value 值 * @return 转换后的值 * @throws ConvertException 转换器不存在 */ public static <T> T convert(TypeReference<T> reference, Object value) throws ConvertException { return cn.hutool.core.convert.Convert.convert(reference, value); } /** * 转换值为指定类型 * * @param <T> 目标类型 * @param type 类型 * @param value 值 * @return 转换后的值 * @throws ConvertException 转换器不存在 */ public static <T> T convert(Type type, Object value) throws ConvertException { return cn.hutool.core.convert.Convert.convert(type, value); } /** * 转换值为指定类型 * * @param <T> 目标类型 * @param type 类型 * @param value 值 * @param defaultValue 默认值 * @return 转换后的值 * @throws ConvertException 转换器不存在 */ public static <T> T convert(Class<T> type, Object value, T defaultValue) throws ConvertException { return cn.hutool.core.convert.Convert.convert(type, value, defaultValue); } /** * 转换值为指定类型 * * @param <T> 目标类型 * @param type 类型 * @param value 值 * @param defaultValue 默认值 * @return 转换后的值 * @throws ConvertException 转换器不存在 */ public static <T> T convert(Type type, Object value, T defaultValue) throws ConvertException { return cn.hutool.core.convert.Convert.convert(type, value, defaultValue); } /** * 转换值为指定类型,不抛异常转换<br> * 当转换失败时返回{@code null} * * @param <T> 目标类型 * @param type 目标类型 * @param value 值 * @return 转换后的值,转换失败返回null */ public static <T> T convertQuietly(Type type, Object value) { return cn.hutool.core.convert.Convert.convertQuietly(type, value); } /** * 转换值为指定类型,不抛异常转换<br> * 当转换失败时返回默认值 * * @param <T> 目标类型 * @param type 目标类型 * @param value 值 * @param defaultValue 默认值 * @return 转换后的值 */ public static <T> T convertQuietly(Type type, Object value, T defaultValue) { return cn.hutool.core.convert.Convert.convertQuietly(type, value, defaultValue); } // ----------------------------------------------------------------------- 推荐转换方法 /** * 转换值为指定类型 <code style="color:red">(推荐)</code> * * @param <T> 泛型 * @param value 被转换的值 * @param clazz 泛型类型 * @return 转换后的对象 * @since Greenwich.SR1.2 * @see #toObject(Object, Class) */ public static <T> T convert(Object value, Class<T> clazz) { return toObject(value, clazz); } /** * 转换值为指定类型 * * @param <T> 泛型 * @param value 被转换的值 * @param clazz 泛型类型 * @return 转换后的对象 */ @SuppressWarnings("unchecked") public static <T> T toObject(Object value, Class<T> clazz) { // 不用转换 if (value != null && clazz != null && (clazz == value.getClass() || clazz.isInstance(value))) { return (T) value; } // JDK8日期时间转换 if (value != null && value instanceof String) { String str = (String) value; if (clazz == LocalDate.class) { return (T) LocalDate.parse(str); } else if (clazz == LocalDateTime.class) { return (T) LocalDateTime.parse(str); } } // JSONObject转换 if (clazz == JSONObject.class) { return (T) toJSONObject(value); } // JSONArray转换 if (clazz == JSONArray.class) { return (T) toJSONArray(value); } // 采用 fastjson 转换 try { return cast(value, clazz, ParserConfig.getGlobalInstance()); } catch (Exception e) { ExceptionUtils.printException(e); log.warn("【Convert】采用 fastjson 类型转换器转换失败,正尝试 hutool 类型转换器转换。"); } // 采用 hutool 转换 return cn.hutool.core.convert.Convert.convert(clazz, value); } /** * 转换值为指定 POJO 类型 * * @param <T> 泛型 * @param value 被转换的值 * @param clazz 泛型类型 * @return 转换后的POJO */ @SuppressWarnings("unchecked") public static <T> T toJavaBean(Object value, Class<T> clazz) { // 不用转换 if (value != null && clazz != null && (clazz == value.getClass() || clazz.isInstance(value))) { return (T) value; } // 采用 fastjson 转换 try { if (value instanceof JSONObject) { return castToJavaBean((JSONObject) value, clazz, ParserConfig.getGlobalInstance()); } if (value instanceof String) { return JSONObject.parseObject((String) value, clazz); } return castToJavaBean(toJSONObject(value), clazz, ParserConfig.getGlobalInstance()); } catch (Exception e) { ExceptionUtils.printException(e); log.warn("【Convert】采用 fastjson 类型转换器转换失败,正尝试 yue-library 类型转换器转换。"); } // 采用 yue-library 转换 if (value instanceof String) { return convert(JSONObject.parseObject((String) value), clazz); } return convert(value, clazz); } /** * 转换为 {@linkplain JSONObject} * * @param value 被转换的值 * @return JSON */ @SuppressWarnings("unchecked") public static JSONObject toJSONObject(Object value) { if (value instanceof JSONObject) { return (JSONObject) value; } if (value instanceof Map) { return new JSONObject((Map<String, Object>) value); } if (value instanceof String) { return JSONObject.parseObject((String) value); } return (JSONObject) toJSON(value); } /** * 转换为 {@linkplain JSONArray} * * @param value 被转换的值 * @return JSON数组 */ @SuppressWarnings("unchecked") public static JSONArray toJSONArray(Object value) { if (value instanceof JSONArray) { return (JSONArray) value; } if (value instanceof List) { return new JSONArray((List<Object>) value); } if (value instanceof String) { return JSONArray.parseArray((String) value); } return (JSONArray) toJSON(value); } // ----------------------------------------------------------------------- List转换方法 /** * 数组转List * <p>此方法为 {@linkplain Arrays#asList(Object...)} 的安全实现</p> * * @param <T> 数组中的对象类 * @param array 将被转换的数组 * @return 被转换数组的列表视图 * @see ListUtils#toList(Object[]) */ public static <T> ArrayList<T> toList(T[] array) { return ListUtils.toList(array); } /** * {@linkplain List}-{@linkplain JSONObject} 转 {@linkplain List}-{@linkplain Class} * * @param <T> 泛型 * @param list 需要转换的List * @param clazz json转换的POJO类型 * @return 转换后的List * @see ListUtils#toList(List, Class) */ public static <T> List<T> toList(List<JSONObject> list, Class<T> clazz) { return ListUtils.toList(list, clazz); } /** * {@linkplain List}-{@linkplain JSONObject} 转 {@linkplain List}-{@linkplain String} * * @param list 需要转换的List * @param keepKey 保留值的key * @return 转换后的List * @see ListUtils#toList(List, String) */ public static List<String> toList(List<JSONObject> list, String keepKey) { return ListUtils.toList(list, keepKey); } /** * {@linkplain List}-{@linkplain JSONObject} 转 {@linkplain List}-{@linkplain Class} * * @param <T> 泛型 * @param list 需要转换的List * @param keepKey 保留值的key * @param clazz 类型 * @return 转换后的List * @see ListUtils#toList(List, String, Class) */ public static <T> List<T> toList(List<JSONObject> list, String keepKey, Class<T> clazz) { return ListUtils.toList(list, keepKey, clazz); } /** * {@linkplain List} - {@linkplain JSONObject} 转 {@linkplain List} - {@linkplain String}并去除重复元素 * * @param list 需要转换的List * @param keepKey 保留值的key * @return 处理后的List * @see ListUtils#toListAndDistinct(List, String) */ public static List<String> toListAndDistinct(List<JSONObject> list, String keepKey) { return ListUtils.toListAndDistinct(list, keepKey); } /** * {@linkplain List}-{@linkplain JSONObject} 转 {@linkplain List}-{@linkplain Class}并去除重复元素 * * @param <T> 泛型 * @param list 需要转换的List * @param keepKey 保留值的key * @param clazz 类型 * @return 处理后的List * @see ListUtils#toListAndDistinct(List, String, Class) */ public static <T> List<T> toListAndDistinct(List<JSONObject> list, String keepKey, Class<T> clazz) { return ListUtils.toListAndDistinct(list, keepKey, clazz); } /** * {@linkplain List} - {@linkplain Map} 转 {@linkplain List} - {@linkplain JSONObject} * <p> * <b><i>性能测试说明:</i></b><br> * <i>测试CPU:</i>i7-4710MQ<br> * <i>测试结果:</i>百万级数据平均200ms(毫秒)<br> * </p> * * @param list 需要转换的List * @return 转换后的List * @see ListUtils#toJsonList(List) */ public static List<JSONObject> toJsonList(List<Map<String, Object>> list) { return ListUtils.toJsonList(list); } /** * {@linkplain JSONArray} 转 {@linkplain List} - {@linkplain JSONObject} * <p> * <b><i>性能测试报告:</i></b><br> * <i>无类型转换(类型推断):</i>见 {@linkplain #toJsonList(List)}<br> * <i>安全模式强制类型转换:</i>暂未测试<br> * </p> * * @param jsonArray 需要转换的JSONArray * @return 转换后的jsonList * @see ListUtils#toJsonList(JSONArray) */ public static List<JSONObject> toJsonList(JSONArray jsonArray) { return ListUtils.toJsonList(jsonArray); } /** * {@linkplain List} - {@linkplain Class} 转 {@linkplain List} - {@linkplain JSONObject} * <p> * <b><i>性能测试报告:</i></b><br> * <i>安全模式强制类型转换:</i>暂未测试<br> * </p> * * @param <T> 泛型 * @param list 需要转换的List * @return 转换后的jsonList * @see ListUtils#toJsonListT(List) */ public static <T> List<JSONObject> toJsonListT(List<T> list) { return ListUtils.toJsonListT(list); } /** * {@linkplain JSONArray} 转 {@linkplain JSONObject}[] * <p>对象引用转换,内存指针依旧指向元数据 * * @param jsonArray 需要转换的JSONArray * @return 转换后的jsons * @see ListUtils#toJsons(JSONArray) */ public static JSONObject[] toJsons(JSONArray jsonArray) { return ListUtils.toJsons(jsonArray); } /** * {@linkplain List}-{@linkplain JSONObject} 转 {@linkplain JSONObject}[] * <p>对象引用转换,内存指针依旧指向元数据 * * @param list 需要转换的List * @return 转换后的jsons * @see ListUtils#toJsons(List) */ public static JSONObject[] toJsons(List<JSONObject> list) { return ListUtils.toJsons(list); } /** * {@linkplain List} - {@linkplain Class} 转 {@linkplain JSONObject}[] * <p> * <b><i>性能测试报告:</i></b><br> * <i>安全模式强制类型转换:</i>暂未测试<br> * </p> * * @param <T> 泛型 * @param list 需要转换的List * @return 转换后的jsons * @see ListUtils#toJsonsT(List) */ public static <T> JSONObject[] toJsonsT(List<T> list) { return ListUtils.toJsonsT(list); } /** * {@linkplain List} - {@linkplain Class} 转 {@linkplain JSONObject}[] 并移除空对象 * <p> * <b><i>性能测试报告:</i></b><br> * <i>安全模式强制类型转换:</i>暂未测试<br> * </p> * * @param <T> 泛型 * @param list 需要转换的List * @return 转换后的jsons * @see ListUtils#toJsonsTAndRemoveEmpty(List) */ public static <T> JSONObject[] toJsonsTAndRemoveEmpty(List<T> list) { return ListUtils.toJsonsTAndRemoveEmpty(list); } /** * {@linkplain String} 转 {@linkplain JSONObject}[] * * @param jsonString 需要转换的JSON字符串 * @return JSON数组 * @see ListUtils#toJsons(String) */ public static JSONObject[] toJsons(String jsonString) { return ListUtils.toJsons(jsonString); } /** * {@linkplain String} 转 {@linkplain JSONObject}[] * <blockquote>示例: * <pre> * {@code * String text = "1,3,5,9"; * JSONObject[] jsons = toJsons(text, ",", "id"); * System.out.println(Arrays.toString(jsons)); * } * </pre> * 结果: * [{"id":"1"}, {"id":"3"}, {"id":"5"}, {"id":"9"}] * </blockquote> * * @param text 需要转换的文本 * @param regex 文本分割表达式,同{@linkplain String}类的split()方法 * @param key JSON的key名称 * @return 转换后的jsons * @see ListUtils#toJsons(String, String, String) */ public static JSONObject[] toJsons(String text, String regex, String key) { return ListUtils.toJsons(text, regex, key); } }
0
java-sources/ai/ylyue/yue-library-base/2.1.0/ai/yue/library/base
java-sources/ai/ylyue/yue-library-base/2.1.0/ai/yue/library/base/convert/package-info.java
/** * 类型转换器 * * @author ylyue * @since 2019年10月13日 */ package ai.yue.library.base.convert;
0
java-sources/ai/ylyue/yue-library-base/2.1.0/ai/yue/library/base/convert
java-sources/ai/ylyue/yue-library-base/2.1.0/ai/yue/library/base/convert/converter/JSONArrayConverter.java
package ai.yue.library.base.convert.converter; import com.alibaba.fastjson.JSONArray; import ai.yue.library.base.convert.Convert; import cn.hutool.core.convert.AbstractConverter; /** * JSONArray类型转换器 * * @author ylyue * @since 2019年7月25日 */ public class JSONArrayConverter extends AbstractConverter<JSONArray> { private static final long serialVersionUID = 1L; @Override protected JSONArray convertInternal(Object value) { return Convert.toJSONArray(value); } }
0
java-sources/ai/ylyue/yue-library-base/2.1.0/ai/yue/library/base/convert
java-sources/ai/ylyue/yue-library-base/2.1.0/ai/yue/library/base/convert/converter/JSONObjectConverter.java
package ai.yue.library.base.convert.converter; import com.alibaba.fastjson.JSONObject; import ai.yue.library.base.convert.Convert; import cn.hutool.core.convert.AbstractConverter; /** * JSONObject类型转换器 * * @author ylyue * @since 2019年7月25日 */ public class JSONObjectConverter extends AbstractConverter<JSONObject> { private static final long serialVersionUID = 1L; @Override protected JSONObject convertInternal(Object value) { return Convert.toJSONObject(value); } }
0
java-sources/ai/ylyue/yue-library-base/2.1.0/ai/yue/library/base/convert
java-sources/ai/ylyue/yue-library-base/2.1.0/ai/yue/library/base/convert/converter/package-info.java
/** * yue所提供的类型转换器 * * @author ylyue * @since 2019年10月18日 */ package ai.yue.library.base.convert.converter;
0
java-sources/ai/ylyue/yue-library-base/2.1.0/ai/yue/library/base
java-sources/ai/ylyue/yue-library-base/2.1.0/ai/yue/library/base/exception/ApiVersionDeprecatedException.java
package ai.yue.library.base.exception; import lombok.NoArgsConstructor; /** * Restful API接口版本弃用异常 * * @author ylyue * @since 2018年2月3日 */ @NoArgsConstructor public class ApiVersionDeprecatedException extends RuntimeException { private static final long serialVersionUID = -8929648099790728526L; public ApiVersionDeprecatedException(String message) { super(message); } }
0
java-sources/ai/ylyue/yue-library-base/2.1.0/ai/yue/library/base
java-sources/ai/ylyue/yue-library-base/2.1.0/ai/yue/library/base/exception/AttackException.java
package ai.yue.library.base.exception; import lombok.NoArgsConstructor; /** * 非法访问异常 * * @author ylyue * @since 2018年2月3日 */ @NoArgsConstructor public class AttackException extends RuntimeException { private static final long serialVersionUID = 8503754532487989211L; public AttackException(String message) { super(message); } }
0
java-sources/ai/ylyue/yue-library-base/2.1.0/ai/yue/library/base
java-sources/ai/ylyue/yue-library-base/2.1.0/ai/yue/library/base/exception/AuthorizeException.java
package ai.yue.library.base.exception; import lombok.NoArgsConstructor; /** * Admin登录异常 * * @author ylyue * @since 2018年2月3日 */ @NoArgsConstructor public class AuthorizeException extends RuntimeException { private static final long serialVersionUID = -4374582170487392015L; public AuthorizeException(String message) { super(message); } }
0
java-sources/ai/ylyue/yue-library-base/2.1.0/ai/yue/library/base
java-sources/ai/ylyue/yue-library-base/2.1.0/ai/yue/library/base/exception/ClientFallbackException.java
package ai.yue.library.base.exception; import lombok.NoArgsConstructor; /** * 服务降级异常 * * @author ylyue * @since 2018年2月3日 */ @NoArgsConstructor public class ClientFallbackException extends RuntimeException { private static final long serialVersionUID = -3620957053991110208L; public ClientFallbackException(String message) { super(message); } }
0
java-sources/ai/ylyue/yue-library-base/2.1.0/ai/yue/library/base
java-sources/ai/ylyue/yue-library-base/2.1.0/ai/yue/library/base/exception/DbException.java
package ai.yue.library.base.exception; import lombok.NoArgsConstructor; /** * <h3>Db异常</h3><br> * * Created by sunJinChuan on 2016/6/8. */ @NoArgsConstructor public class DbException extends RuntimeException { private static final long serialVersionUID = 5869945193750586067L; /** * 统一异常处理后是否显示异常提示 */ private boolean showMsg = false; public DbException(String msg) { super(msg); } /** * DB异常 * * @param msg 异常提示 * @param showMsg 统一异常处理后是否显示异常提示 */ public DbException(String msg, boolean showMsg) { super(msg); this.showMsg = showMsg; } /** * 统一异常处理后是否显示异常提示 * * @return 是否显示 */ public boolean isShowMsg() { return showMsg; } /** * 设置统一异常处理后是否显示异常提示 * @param showMsg 是否显示 */ public void setShowMsg(boolean showMsg) { this.showMsg = showMsg; } }
0
java-sources/ai/ylyue/yue-library-base/2.1.0/ai/yue/library/base
java-sources/ai/ylyue/yue-library-base/2.1.0/ai/yue/library/base/exception/ForbiddenException.java
package ai.yue.library.base.exception; import lombok.NoArgsConstructor; /** * 无权限异常 * * @author ylyue * @since 2018年3月28日 */ @NoArgsConstructor public class ForbiddenException extends RuntimeException { private static final long serialVersionUID = -477721736529522496L; public ForbiddenException(String message) { super(message); } }
0
java-sources/ai/ylyue/yue-library-base/2.1.0/ai/yue/library/base
java-sources/ai/ylyue/yue-library-base/2.1.0/ai/yue/library/base/exception/LoginException.java
package ai.yue.library.base.exception; import lombok.NoArgsConstructor; /** * 登录异常 * * @author ylyue * @since 2018年2月3日 */ @NoArgsConstructor public class LoginException extends RuntimeException { private static final long serialVersionUID = -4747910085674257587L; public LoginException(String message) { super(message); } }
0
java-sources/ai/ylyue/yue-library-base/2.1.0/ai/yue/library/base
java-sources/ai/ylyue/yue-library-base/2.1.0/ai/yue/library/base/exception/ParamDecryptException.java
package ai.yue.library.base.exception; import lombok.NoArgsConstructor; /** * 解密异常 * * @author ylyue * @since 2018年2月3日 */ @NoArgsConstructor public class ParamDecryptException extends RuntimeException { private static final long serialVersionUID = 5325379409661261173L; public ParamDecryptException(String message) { super(message); } }
0
java-sources/ai/ylyue/yue-library-base/2.1.0/ai/yue/library/base
java-sources/ai/ylyue/yue-library-base/2.1.0/ai/yue/library/base/exception/ParamException.java
package ai.yue.library.base.exception; /** * 参数校验不通过异常 * * @author ylyue * @since 2017年10月9日 */ public class ParamException extends RuntimeException { private static final long serialVersionUID = -7818277682527873103L; public ParamException(String msg) { super(msg); } }
0
java-sources/ai/ylyue/yue-library-base/2.1.0/ai/yue/library/base
java-sources/ai/ylyue/yue-library-base/2.1.0/ai/yue/library/base/exception/ParamVoidException.java
package ai.yue.library.base.exception; import lombok.NoArgsConstructor; /** * 参数为空异常 * * @author ylyue * @since 2017年10月9日 */ @NoArgsConstructor public class ParamVoidException extends RuntimeException { private static final long serialVersionUID = -8552913006333383718L; }
0
java-sources/ai/ylyue/yue-library-base/2.1.0/ai/yue/library/base
java-sources/ai/ylyue/yue-library-base/2.1.0/ai/yue/library/base/exception/ResultException.java
package ai.yue.library.base.exception; import ai.yue.library.base.view.Result; import ai.yue.library.base.view.ResultInfo; import lombok.Getter; /** * @author ylyue * @since 2018年2月3日 */ @Getter public class ResultException extends RuntimeException { private static final long serialVersionUID = -4332073495864145387L; private Result<?> result; public <T> ResultException(String msg) { this.result = ResultInfo.devCustomTypePrompt(msg); } public <T> ResultException(Result<T> result) { this.result = result; } }
0
java-sources/ai/ylyue/yue-library-base/2.1.0/ai/yue/library/base
java-sources/ai/ylyue/yue-library-base/2.1.0/ai/yue/library/base/exception/package-info.java
/** * 异常定义 * * @author ylyue * @since 2019年10月13日 */ package ai.yue.library.base.exception;
0
java-sources/ai/ylyue/yue-library-base/2.1.0/ai/yue/library/base
java-sources/ai/ylyue/yue-library-base/2.1.0/ai/yue/library/base/ipo/LocationIPO.java
package ai.yue.library.base.ipo; import com.alibaba.fastjson.JSONObject; import lombok.AllArgsConstructor; import lombok.Builder; import lombok.Data; import lombok.NoArgsConstructor; /** * @author ylyue * @since 2018年7月31日 */ @Data @Builder @NoArgsConstructor @AllArgsConstructor public class LocationIPO { /** 经度 */ double lng; /** 纬度 */ double lat; /** * 将经纬度参数转换为位置对象 * <p> * {@linkplain JSONObject} 转 {@linkplain LocationIPO} * @param location 标准的经纬度JSON对象,包含的key有("lng", "lat") * @return 经纬度对象 */ public static LocationIPO toLocationIPO(JSONObject location) { double lng = location.getDouble("lng"); double lat = location.getDouble("lat"); return LocationIPO.builder().lng(lng).lat(lat).build(); } }
0
java-sources/ai/ylyue/yue-library-base/2.1.0/ai/yue/library/base
java-sources/ai/ylyue/yue-library-base/2.1.0/ai/yue/library/base/ipo/ParamFormatIPO.java
package ai.yue.library.base.ipo; import lombok.AllArgsConstructor; import lombok.Builder; import lombok.Data; import lombok.NoArgsConstructor; /** * 参数美化IPO * * @author ylyue * @since 2018年6月22日 */ @Data @Builder @NoArgsConstructor @AllArgsConstructor public class ParamFormatIPO { String key; Class<?> clazz; }
0
java-sources/ai/ylyue/yue-library-base/2.1.0/ai/yue/library/base
java-sources/ai/ylyue/yue-library-base/2.1.0/ai/yue/library/base/ipo/package-info.java
/** * IPO定义 * * @author ylyue * @since 2019年10月13日 */ package ai.yue.library.base.ipo;