系列文章目录
提示:这里可以添加系列文章的所有文章的目录,目录需要自己手动添加
例如:第一章 Java设计模式之装饰者模式
提示:写完文章后,目录可以自动生成,如何生成可参考右边的帮助文档
前言
提示:这里可以添加本文要记录的大概内容:
例如:随着人工智能的不断发展,机器学习这门技术也越来越重要,很多人都开启了学习机器学习,本文就介绍了机器学习的基础内容。
提示:以下是本篇文章正文内容,下面案例可供参考
一、pandas是什么?
示例:pandas 是基于NumPy 的一种工具,该工具是为了解决数据分析任务而创建的。
二、Spring中装饰者模式的使用
1.UML类图
2.源码
代码如下(示例):
public interface ServletRequest {
public Object getAttribute(String name);
public Enumeration<String> getAttributeNames();
public String getCharacterEncoding();
public void setCharacterEncoding(String env) throws UnsupportedEncodingException;
public int getContentLength();
public long getContentLengthLong();
public String getContentType();
public ServletInputStream getInputStream() throws IOException;
public String getParameter(String name);
public Enumeration<String> getParameterNames();
public String[] getParameterValues(String name);
public Map<String, String[]> getParameterMap();
public String getProtocol();
public String getScheme();
public String getServerName();
public int getServerPort();
public BufferedReader getReader() throws IOException;
public String getRemoteAddr();
public String getRemoteHost();
public void setAttribute(String name, Object o);
public void removeAttribute(String name);
public Locale getLocale();
public Enumeration<Locale> getLocales();
public boolean isSecure();
public RequestDispatcher getRequestDispatcher(String path);
public String getRealPath(String path);
public int getRemotePort();
public String getLocalName();
public String getLocalAddr();
public int getLocalPort();
public ServletContext getServletContext();
public AsyncContext startAsync() throws IllegalStateException;
public AsyncContext startAsync(ServletRequest servletRequest,
ServletResponse servletResponse)
throws IllegalStateException;
public boolean isAsyncStarted();
public boolean isAsyncSupported();
public AsyncContext getAsyncContext();
public DispatcherType getDispatcherType();
}
public class ServletRequestWrapper implements ServletRequest {
private ServletRequest request;
public ServletRequestWrapper(ServletRequest request) {
if (request == null) {
throw new IllegalArgumentException("Request cannot be null");
}
this.request = request;
}
public ServletRequest getRequest() {
return this.request;
}
public void setRequest(ServletRequest request) {
if (request == null) {
throw new IllegalArgumentException("Request cannot be null");
}
this.request = request;
}
public Object getAttribute(String name) {
return this.request.getAttribute(name);
}
public Enumeration<String> getAttributeNames() {
return this.request.getAttributeNames();
}
public String getCharacterEncoding() {
return this.request.getCharacterEncoding();
}
public void setCharacterEncoding(String enc)
throws UnsupportedEncodingException {
this.request.setCharacterEncoding(enc);
}
public int getContentLength() {
return this.request.getContentLength();
}
public long getContentLengthLong() {
return this.request.getContentLengthLong();
}
public String getContentType() {
return this.request.getContentType();
}
public ServletInputStream getInputStream() throws IOException {
return this.request.getInputStream();
}
public String getParameter(String name) {
return this.request.getParameter(name);
}
public Map<String, String[]> getParameterMap() {
return this.request.getParameterMap();
}
public Enumeration<String> getParameterNames() {
return this.request.getParameterNames();
}
public String[] getParameterValues(String name) {
return this.request.getParameterValues(name);
}
public String getProtocol() {
return this.request.getProtocol();
}
public String getScheme() {
return this.request.getScheme();
}
public String getServerName() {
return this.request.getServerName();
}
public int getServerPort() {
return this.request.getServerPort();
}
public BufferedReader getReader() throws IOException {
return this.request.getReader();
}
public String getRemoteAddr() {
return this.request.getRemoteAddr();
}
public String getRemoteHost() {
return this.request.getRemoteHost();
}
public void setAttribute(String name, Object o) {
this.request.setAttribute(name, o);
}
public void removeAttribute(String name) {
this.request.removeAttribute(name);
}
public Locale getLocale() {
return this.request.getLocale();
}
public Enumeration<Locale> getLocales() {
return this.request.getLocales();
}
public boolean isSecure() {
return this.request.isSecure();
}
public RequestDispatcher getRequestDispatcher(String path) {
return this.request.getRequestDispatcher(path);
}
@Deprecated
public String getRealPath(String path) {
return this.request.getRealPath(path);
}
public int getRemotePort(){
return this.request.getRemotePort();
}
public String getLocalName(){
return this.request.getLocalName();
}
public String getLocalAddr(){
return this.request.getLocalAddr();
}
public int getLocalPort(){
return this.request.getLocalPort();
}
public ServletContext getServletContext() {
return request.getServletContext();
}
public AsyncContext startAsync() throws IllegalStateException {
return request.startAsync();
}
public AsyncContext startAsync(ServletRequest servletRequest,
ServletResponse servletResponse)
throws IllegalStateException {
return request.startAsync(servletRequest, servletResponse);
}
public boolean isAsyncStarted() {
return request.isAsyncStarted();
}
public boolean isAsyncSupported() {
return request.isAsyncSupported();
}
public AsyncContext getAsyncContext() {
return request.getAsyncContext();
}
public boolean isWrapperFor(ServletRequest wrapped) {
if (request == wrapped) {
return true;
} else if (request instanceof ServletRequestWrapper) {
return ((ServletRequestWrapper) request).isWrapperFor(wrapped);
} else {
return false;
}
}
public boolean isWrapperFor(Class<?> wrappedType) {
if (!ServletRequest.class.isAssignableFrom(wrappedType)) {
throw new IllegalArgumentException("Given class " +
wrappedType.getName() + " not a subinterface of " +
ServletRequest.class.getName());
}
if (wrappedType.isAssignableFrom(request.getClass())) {
return true;
} else if (request instanceof ServletRequestWrapper) {
return ((ServletRequestWrapper) request).isWrapperFor(wrappedType);
} else {
return false;
}
}
public DispatcherType getDispatcherType() {
return request.getDispatcherType();
}
}
public class ContentCachingRequestWrapper extends HttpServletRequestWrapper {
private static final String FORM_CONTENT_TYPE = "application/x-www-form-urlencoded";
private final ByteArrayOutputStream cachedContent;
@Nullable
private final Integer contentCacheLimit;
@Nullable
private ServletInputStream inputStream;
@Nullable
private BufferedReader reader;
public ContentCachingRequestWrapper(HttpServletRequest request) {
super(request);
int contentLength = request.getContentLength();
this.cachedContent = new ByteArrayOutputStream(contentLength >= 0 ? contentLength : 1024);
this.contentCacheLimit = null;
}
public ContentCachingRequestWrapper(HttpServletRequest request, int contentCacheLimit) {
super(request);
this.cachedContent = new ByteArrayOutputStream(contentCacheLimit);
this.contentCacheLimit = contentCacheLimit;
}
@Override
public ServletInputStream getInputStream() throws IOException {
if (this.inputStream == null) {
this.inputStream = new ContentCachingInputStream(getRequest().getInputStream());
}
return this.inputStream;
}
@Override
public String getCharacterEncoding() {
String enc = super.getCharacterEncoding();
return (enc != null ? enc : WebUtils.DEFAULT_CHARACTER_ENCODING);
}
@Override
public BufferedReader getReader() throws IOException {
if (this.reader == null) {
this.reader = new BufferedReader(new InputStreamReader(getInputStream(), getCharacterEncoding()));
}
return this.reader;
}
@Override
public String getParameter(String name) {
if (this.cachedContent.size() == 0 && isFormPost()) {
writeRequestParametersToCachedContent();
}
return super.getParameter(name);
}
@Override
public Map<String, String[]> getParameterMap() {
if (this.cachedContent.size() == 0 && isFormPost()) {
writeRequestParametersToCachedContent();
}
return super.getParameterMap();
}
@Override
public Enumeration<String> getParameterNames() {
if (this.cachedContent.size() == 0 && isFormPost()) {
writeRequestParametersToCachedContent();
}
return super.getParameterNames();
}
@Override
public String[] getParameterValues(String name) {
if (this.cachedContent.size() == 0 && isFormPost()) {
writeRequestParametersToCachedContent();
}
return super.getParameterValues(name);
}
private boolean isFormPost() {
String contentType = getContentType();
return (contentType != null && contentType.contains(FORM_CONTENT_TYPE) &&
HttpMethod.POST.matches(getMethod()));
}
private void writeRequestParametersToCachedContent() {
try {
if (this.cachedContent.size() == 0) {
String requestEncoding = getCharacterEncoding();
Map<String, String[]> form = super.getParameterMap();
for (Iterator<String> nameIterator = form.keySet().iterator(); nameIterator.hasNext(); ) {
String name = nameIterator.next();
List<String> values = Arrays.asList(form.get(name));
for (Iterator<String> valueIterator = values.iterator(); valueIterator.hasNext(); ) {
String value = valueIterator.next();
this.cachedContent.write(URLEncoder.encode(name, requestEncoding).getBytes());
if (value != null) {
this.cachedContent.write('=');
this.cachedContent.write(URLEncoder.encode(value, requestEncoding).getBytes());
if (valueIterator.hasNext()) {
this.cachedContent.write('&');
}
}
}
if (nameIterator.hasNext()) {
this.cachedContent.write('&');
}
}
}
}
catch (IOException ex) {
throw new IllegalStateException("Failed to write request parameters to cached content", ex);
}
}
public byte[] getContentAsByteArray() {
return this.cachedContent.toByteArray();
}
protected void handleContentOverflow(int contentCacheLimit) {
}
private class ContentCachingInputStream extends ServletInputStream {
private final ServletInputStream is;
private boolean overflow = false;
public ContentCachingInputStream(ServletInputStream is) {
this.is = is;
}
@Override
public int read() throws IOException {
int ch = this.is.read();
if (ch != -1 && !this.overflow) {
if (contentCacheLimit != null && cachedContent.size() == contentCacheLimit) {
this.overflow = true;
handleContentOverflow(contentCacheLimit);
}
else {
cachedContent.write(ch);
}
}
return ch;
}
@Override
public int read(byte[] b) throws IOException {
int count = this.is.read(b);
writeToCache(b, 0, count);
return count;
}
private void writeToCache(final byte[] b, final int off, int count) {
if (!this.overflow && count > 0) {
if (contentCacheLimit != null &&
count + cachedContent.size() > contentCacheLimit) {
this.overflow = true;
cachedContent.write(b, off, contentCacheLimit - cachedContent.size());
handleContentOverflow(contentCacheLimit);
return;
}
cachedContent.write(b, off, count);
}
}
@Override
public int read(final byte[] b, final int off, final int len) throws IOException {
int count = this.is.read(b, off, len);
writeToCache(b, off, count);
return count;
}
@Override
public int readLine(final byte[] b, final int off, final int len) throws IOException {
int count = this.is.readLine(b, off, len);
writeToCache(b, off, count);
return count;
}
@Override
public boolean isFinished() {
return this.is.isFinished();
}
@Override
public boolean isReady() {
return this.is.isReady();
}
@Override
public void setReadListener(ReadListener readListener) {
this.is.setReadListener(readListener);
}
}
}
public class HttpServletRequestWrapper extends ServletRequestWrapper implements HttpServletRequest {
public HttpServletRequestWrapper(HttpServletRequest request) {
super(request);
}
private HttpServletRequest _getHttpServletRequest() {
return (HttpServletRequest) super.getRequest();
}
@Override
public String getAuthType() {
return this._getHttpServletRequest().getAuthType();
}
@Override
public Cookie[] getCookies() {
return this._getHttpServletRequest().getCookies();
}
@Override
public long getDateHeader(String name) {
return this._getHttpServletRequest().getDateHeader(name);
}
@Override
public String getHeader(String name) {
return this._getHttpServletRequest().getHeader(name);
}
@Override
public Enumeration<String> getHeaders(String name) {
return this._getHttpServletRequest().getHeaders(name);
}
@Override
public Enumeration<String> getHeaderNames() {
return this._getHttpServletRequest().getHeaderNames();
}
@Override
public int getIntHeader(String name) {
return this._getHttpServletRequest().getIntHeader(name);
}
@Override
public HttpServletMapping getHttpServletMapping() {
return this._getHttpServletRequest().getHttpServletMapping();
}
@Override
public String getMethod() {
return this._getHttpServletRequest().getMethod();
}
@Override
public String getPathInfo() {
return this._getHttpServletRequest().getPathInfo();
}
@Override
public String getPathTranslated() {
return this._getHttpServletRequest().getPathTranslated();
}
@Override
public String getContextPath() {
return this._getHttpServletRequest().getContextPath();
}
@Override
public String getQueryString() {
return this._getHttpServletRequest().getQueryString();
}
@Override
public String getRemoteUser() {
return this._getHttpServletRequest().getRemoteUser();
}
@Override
public boolean isUserInRole(String role) {
return this._getHttpServletRequest().isUserInRole(role);
}
@Override
public java.security.Principal getUserPrincipal() {
return this._getHttpServletRequest().getUserPrincipal();
}
@Override
public String getRequestedSessionId() {
return this._getHttpServletRequest().getRequestedSessionId();
}
@Override
public String getRequestURI() {
return this._getHttpServletRequest().getRequestURI();
}
@Override
public StringBuffer getRequestURL() {
return this._getHttpServletRequest().getRequestURL();
}
@Override
public String getServletPath() {
return this._getHttpServletRequest().getServletPath();
}
@Override
public HttpSession getSession(boolean create) {
return this._getHttpServletRequest().getSession(create);
}
@Override
public HttpSession getSession() {
return this._getHttpServletRequest().getSession();
}
@Override
public String changeSessionId() {
return this._getHttpServletRequest().changeSessionId();
}
@Override
public boolean isRequestedSessionIdValid() {
return this._getHttpServletRequest().isRequestedSessionIdValid();
}
@Override
public boolean isRequestedSessionIdFromCookie() {
return this._getHttpServletRequest().isRequestedSessionIdFromCookie();
}
@Override
public boolean isRequestedSessionIdFromURL() {
return this._getHttpServletRequest().isRequestedSessionIdFromURL();
}
@Deprecated
@Override
public boolean isRequestedSessionIdFromUrl() {
return this._getHttpServletRequest().isRequestedSessionIdFromUrl();
}
@Override
public boolean authenticate(HttpServletResponse response)
throws IOException, ServletException {
return this._getHttpServletRequest().authenticate(response);
}
@Override
public void login(String username, String password)
throws ServletException {
this._getHttpServletRequest().login(username,password);
}
@Override
public void logout() throws ServletException {
this._getHttpServletRequest().logout();
}
@Override
public Collection<Part> getParts() throws IOException, ServletException {
return this._getHttpServletRequest().getParts();
}
@Override
public Part getPart(String name) throws IOException, ServletException {
return this._getHttpServletRequest().getPart(name);
}
@Override
public <T extends HttpUpgradeHandler> T upgrade(Class<T> handlerClass)
throws IOException, ServletException {
return this._getHttpServletRequest().upgrade(handlerClass);
}
@Override
public PushBuilder newPushBuilder() {
return this._getHttpServletRequest().newPushBuilder();
}
@Override
public Map<String, String> getTrailerFields() {
return this._getHttpServletRequest().getTrailerFields();
}
@Override
public boolean isTrailerFieldsReady() {
return this._getHttpServletRequest().isTrailerFieldsReady();
}
}
public interface HttpServletRequest extends ServletRequest {
public static final String BASIC_AUTH = "BASIC";
public static final String FORM_AUTH = "FORM";
public static final String CLIENT_CERT_AUTH = "CLIENT_CERT";
public static final String DIGEST_AUTH = "DIGEST";
public String getAuthType();
public Cookie[] getCookies();
public long getDateHeader(String name);
public String getHeader(String name);
public Enumeration<String> getHeaders(String name);
public Enumeration<String> getHeaderNames();
public int getIntHeader(String name);
default public HttpServletMapping getHttpServletMapping() {
return new HttpServletMapping() {
@Override
public String getMatchValue() {
return "";
}
@Override
public String getPattern() {
return "";
}
@Override
public String getServletName() {
return "";
}
@Override
public MappingMatch getMappingMatch() {
return null;
}
@Override
public String toString() {
return "MappingImpl{" + "matchValue=" + getMatchValue()
+ ", pattern=" + getPattern() + ", servletName="
+ getServletName() + ", mappingMatch=" + getMappingMatch()
+ "} HttpServletRequest {" + HttpServletRequest.this.toString()
+ '}';
}
};
}
public String getMethod();
public String getPathInfo();
public String getPathTranslated();
default public PushBuilder newPushBuilder() {
return null;
}
public String getContextPath();
public String getQueryString();
public String getRemoteUser();
public boolean isUserInRole(String role);
public java.security.Principal getUserPrincipal();
public String getRequestedSessionId();
public String getRequestURI();
public StringBuffer getRequestURL();
public String getServletPath();
public HttpSession getSession(boolean create);
public HttpSession getSession();
public String changeSessionId();
public boolean isRequestedSessionIdValid();
public boolean isRequestedSessionIdFromCookie();
public boolean isRequestedSessionIdFromURL();
@Deprecated
public boolean isRequestedSessionIdFromUrl();
public boolean authenticate(HttpServletResponse response)
throws IOException,ServletException;
public void login(String username, String password)
throws ServletException;
public void logout() throws ServletException;
public Collection<Part> getParts() throws IOException, ServletException;
public Part getPart(String name) throws IOException, ServletException;
public <T extends HttpUpgradeHandler> T upgrade(Class<T> handlerClass)
throws IOException, ServletException;
default public Map<String, String> getTrailerFields() {
return Collections.emptyMap();
}
default public boolean isTrailerFieldsReady() {
return true;
}
}
3.个人案例
由来:
项目中使用Authing作为第三方登录,需要在后台对用户进行管理,Authing官方提供了SDK、API等多种方式进行操作,第一版代码只有SDK方式实现;后来产品想要在用户创建成功后发送一条回调邮件(Authing官方提供了这样的API,但是SDK方式还没有来得及更新),于是博主决定使用装饰者模式对SDK方式增强
账户接口:
public interface AccountRepository {
Account insert(Account account);
int deleteById(String id);
int deleteByIds(List<String> idList);
int updateById(Account account);
Account selectById(String id);
List<Account> selectList();
CommonPageInfoResponseData<Account> selectPage(PageInfoParam pageInfoParam);
CommonPageInfoResponseData<Account> selectPage(PageInfoParam pageInfoParam, Account account);
Account selectByEmail(String email);
CommonPageInfoResponseData<Account> pageByPartnerCode(PageInfoParam pageInfoParam, String partnerCode, String query);
}
Authing账户接口:
public interface AuthingAccountRepository extends AccountRepository {
}
SDK方式Authing账户实现类:
@Slf4j
@Repository
public class AuthingAccountRepositoryImpl implements AuthingAccountRepository {
@Autowired
private ManagementClient managementClient;
@SneakyThrows
@Override
public Account insert(Account account) {
CreateUserInput createUserInput = toSaveUser(account);
User authingUser = managementClient.users().create(createUserInput).execute();
return toLinksUser(authingUser);
}
@SneakyThrows
@Override
public int deleteById(String id) {
}
@SneakyThrows
@Override
public int deleteByIds(List<String> idList) {
}
@SneakyThrows
@Override
public int updateById(Account account) {
}
@SneakyThrows
@Override
public Account selectById(String id) {
}
/**
* 单页最大查询200条数据
*/
@SneakyThrows
@Override
public List<Account> selectList() {
}
@Override
public CommonPageInfoResponseData<Account> selectPage(PageInfoParam pageInfoParam) {
}
/**
* authing提供的查询能力不满足当前业务需求,将所有数据加载到内存中进行筛选过滤
*/
@Override
public CommonPageInfoResponseData<Account> selectPage(PageInfoParam pageInfoParam, Account account) {
}
@SneakyThrows
@Override
public Account selectByEmail(String email) {
}
@Override
public CommonPageInfoResponseData<Account> pageByPartnerCode(PageInfoParam pageInfoParam, String partnerCode, String query) {
}
@SneakyThrows
public Account selectByExternalId(String externalId) {
}
@SneakyThrows
public boolean setUdfValue(String userId, String key, String value) {
}
@SneakyThrows
public Map<String, String> getUdfValue(String userId) {
}
@SneakyThrows
public Map<String, Map<String, String>> getUdfValueList(List<String> userIdList) {
}
}
Authing账户装饰者抽象类:
public abstract class AbstractAuthingAccountRepositoryWrapper implements AuthingAccountRepository {
private AuthingAccountRepository authingAccountRepository;
public AbstractAuthingAccountRepositoryWrapper(AuthingAccountRepository authingAccountRepository) {
if (authingAccountRepository == null) {
throw new IllegalArgumentException("authingAccountRepository cannot be null");
}
this.authingAccountRepository = authingAccountRepository;
}
public AuthingAccountRepository getAuthingAccountRepository() {
return authingAccountRepository;
}
public void setAuthingAccountRepository(AuthingAccountRepositoryImpl authingAccountRepository) {
if (authingAccountRepository == null) {
throw new IllegalArgumentException("AccountRepository cannot be null");
}
this.authingAccountRepository = authingAccountRepository;
}
@Override
public Account insert(Account account) {
return authingAccountRepository.insert(account);
}
@Override
public int deleteById(String id) {
return authingAccountRepository.deleteById(id);
}
@Override
public int deleteByIds(List<String> idList) {
return authingAccountRepository.deleteByIds(idList);
}
@Override
public int updateById(Account account) {
return authingAccountRepository.updateById(account);
}
@Override
public Account selectById(String id) {
return authingAccountRepository.selectById(id);
}
@Override
public List<Account> selectList() {
return authingAccountRepository.selectList();
}
@Override
public CommonPageInfoResponseData<Account> selectPage(PageInfoParam pageInfoParam) {
return authingAccountRepository.selectPage(pageInfoParam);
}
@Override
public CommonPageInfoResponseData<Account> selectPage(PageInfoParam pageInfoParam, Account account) {
return authingAccountRepository.selectPage(pageInfoParam, account);
}
@Override
public Account selectByEmail(String email) {
return authingAccountRepository.selectByEmail(email);
}
@Override
public CommonPageInfoResponseData<Account> pageByPartnerCode(PageInfoParam pageInfoParam, String partnerCode, String query) {
return authingAccountRepository.pageByPartnerCode(pageInfoParam, partnerCode, query);
}
}
API方式Authing账户装饰者实现类:
可对insert()进行增强,在创建成功后发送一条邮件
@Slf4j
@Repository
public class ApiAuthingAccountRepositoryWrapper extends AbstractAuthingAccountRepositoryWrapper {
@Autowired
private AuthingFeignClient authingFeignClient;
@Autowired
private ManagementClient managementClient;
public ApiAuthingAccountRepositoryWrapper(AuthingAccountRepositoryImpl accountRepository) {
super(accountRepository);
}
// 账户创建成功后发送邮件回调
@Override
public Account insert(Account account) {
SendNotification sendNotification = new SendNotification();
sendNotification.setSendEmailNotification(true);
return insert(account, sendNotification);
}
// 账户创建成功后发送回调
public Account insert(Account account, SendNotification sendNotification) {
// 1.API接口注册
AuthingCreateUserReq authingCreateUserReq = new AuthingCreateUserReq();
authingCreateUserReq.setEmail(account.getEmail());
authingCreateUserReq.setPassword(account.getPassword());
// 设置自定义数据
Map<String, String> customData = new HashMap<>();
customData.put(AuthingAccountRepositoryImpl.PARTNER_CODE, account.getPartnerCode());
authingCreateUserReq.setCustomData(customData);
// 设置操作
AuthingCreateUserReq.Options options = new AuthingCreateUserReq.Options();
AuthingCreateUserReq.SendNotification authingCreateUserSendNotification = new AuthingCreateUserReq.SendNotification();
BeanUtils.copyProperties(sendNotification, authingCreateUserSendNotification);
options.setSendNotification(authingCreateUserSendNotification);
authingCreateUserReq.setOptions(options);
AuthingResult<AuthingCreateUserRes> authingResult = authingFeignClient.createUser(managementClient.getToken(), managementClient.getUserPoolId(), authingCreateUserReq);
if (authingResult.getStatusCode() != 200) {
throw new RuntimeException(authingResult.getMessage());
}
String userId = authingResult.getData().getUserId();
account.setId(userId);
return account;
}
}
总结
提示:这里对文章进行总结:
例如:以上就是今天要讲的内容,本文仅仅简单介绍了pandas的使用,而pandas提供了大量能使我们快速便捷地处理数据的函数和方法。