View Javadoc
1   package org.oxerr.spring.security.wechat.web.authentication;
2   
3   import java.io.IOException;
4   import java.io.InputStreamReader;
5   import java.io.Reader;
6   import java.nio.charset.StandardCharsets;
7   
8   import javax.servlet.ServletException;
9   import javax.servlet.http.HttpServletRequest;
10  import javax.servlet.http.HttpServletResponse;
11  
12  import org.oxerr.spring.security.wechat.core.WeChatMessageSource;
13  import org.springframework.context.MessageSource;
14  import org.springframework.context.MessageSourceAware;
15  import org.springframework.context.support.MessageSourceAccessor;
16  import org.springframework.util.FileCopyUtils;
17  
18  public abstract class AbstractJavaScriptRedirectWeChatService extends
19  		AbstractSimpleRedirectWeChatService implements MessageSourceAware {
20  
21  	protected MessageSourceAccessor messages = WeChatMessageSource.getAccessor();
22  	private final String template;
23  
24  	public AbstractJavaScriptRedirectWeChatService() {
25  		try (Reader reader = new InputStreamReader(
26  			AbstractJavaScriptRedirectWeChatService.class
27  				.getResourceAsStream("loading.html"),
28  			StandardCharsets.UTF_8)) {
29  			template = FileCopyUtils.copyToString(reader);
30  		} catch (IOException e) {
31  			throw new RuntimeException(e);
32  		}
33  	}
34  
35  	/**
36  	 * {@inheritDoc}
37  	 */
38  	@Override
39  	public void setMessageSource(MessageSource messageSource) {
40  		this.messages = new MessageSourceAccessor(messageSource);
41  	}
42  
43  	/**
44  	 * {@inheritDoc}
45  	 */
46  	@Override
47  	public void redirectToAuthorize(HttpServletRequest request,
48  			HttpServletResponse response) throws ServletException, IOException {
49  		String redirectionPageHtml = generateRedirectionPageHtml(request, response);
50  
51  		response.setContentType("text/html;charset=UTF-8");
52  		response.setContentLength(redirectionPageHtml.length());
53  		response.getWriter().write(redirectionPageHtml);
54  	}
55  
56  	private String generateRedirectionPageHtml(HttpServletRequest request,
57  			HttpServletResponse response) throws ServletException, IOException {
58  		String url = this.getAuthorizationURL(request, response);
59  		String s = template.replaceFirst("#\\{loading\\}",
60  			messages.getMessage(
61  				"AbstractJavaScriptRedirectWeChatService.loading",
62  				"Loading..."));
63  		s = s.replaceFirst("\\$\\{url\\}", url);
64  		return s;
65  	}
66  
67  }