HuaweiCredential.java 4.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168
  1. /*
  2. * Copyright 2020. Huawei Technologies Co., Ltd. All rights reserved.
  3. Licensed under the Apache License, Version 2.0 (the "License");
  4. you may not use this file except in compliance with the License.
  5. You may obtain a copy of the License at
  6. http://www.apache.org/licenses/LICENSE-2.0
  7. Unless required by applicable law or agreed to in writing, software
  8. distributed under the License is distributed on an "AS IS" BASIS,
  9. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. See the License for the specific language governing permissions and
  11. limitations under the License.
  12. */
  13. package cn.seecoder.courselearning.messaging;
  14. import com.alibaba.fastjson.JSONObject;
  15. import org.apache.http.client.methods.CloseableHttpResponse;
  16. import org.apache.http.client.methods.HttpPost;
  17. import org.apache.http.entity.StringEntity;
  18. import org.apache.http.impl.client.CloseableHttpClient;
  19. import org.apache.http.impl.client.HttpClients;
  20. import org.apache.http.util.EntityUtils;
  21. import org.slf4j.Logger;
  22. import org.slf4j.LoggerFactory;
  23. import java.io.IOException;
  24. import java.text.MessageFormat;
  25. import java.util.ResourceBundle;
  26. import java.util.concurrent.locks.Lock;
  27. import java.util.concurrent.locks.ReentrantLock;
  28. /**
  29. * Accept the appId and appSecret given by the user and build the credential
  30. * Every app has a credential which is for certification
  31. */
  32. public class HuaweiCredential {
  33. private static final Logger logger = LoggerFactory.getLogger(HuaweiCredential.class);
  34. private final String PUSH_AT_URL = ResourceBundle.getBundle("url").getString("token_server");
  35. private String appId;
  36. private String appSecret;
  37. private String accessToken;
  38. private long expireIn;
  39. private Lock lock;
  40. private CloseableHttpClient httpClient;
  41. private HuaweiCredential(Builder builder) {
  42. this.lock = new ReentrantLock();
  43. this.appId = builder.appId;
  44. this.appSecret = builder.appSecret;
  45. if (builder.httpClient == null) {
  46. httpClient = HttpClients.createDefault();
  47. } else {
  48. this.httpClient = builder.httpClient;
  49. }
  50. }
  51. /**
  52. * Refresh accessToken via HCM manually.
  53. */
  54. public final void refreshToken() {
  55. try {
  56. executeRefresh();
  57. } catch (IOException e) {
  58. logger.debug("Fail to refresh token!", e);
  59. }
  60. }
  61. private void executeRefresh() throws IOException {
  62. String requestBody = createRequestBody(appId, appSecret);
  63. HttpPost httpPost = new HttpPost(PUSH_AT_URL);
  64. StringEntity entity = new StringEntity(requestBody);
  65. httpPost.setHeader("Content-Type", "application/x-www-form-urlencoded;charset=utf-8");
  66. httpPost.setEntity(entity);
  67. CloseableHttpResponse response = httpClient.execute(httpPost);
  68. String jsonStr = EntityUtils.toString(response.getEntity());
  69. int statusCode = response.getStatusLine().getStatusCode();
  70. if (statusCode == 200) {
  71. JSONObject jsonObject = JSONObject.parseObject(jsonStr);
  72. this.accessToken = jsonObject.getString("access_token");
  73. this.expireIn = jsonObject.getLong("expires_in") * 1000L;
  74. } else {
  75. logger.debug("Fail to refresh token!");
  76. }
  77. }
  78. private String createRequestBody(String appId, String appSecret) {
  79. return MessageFormat.format("grant_type=client_credentials&client_secret={0}&client_id={1}", appSecret, appId);
  80. }
  81. /**
  82. * getter
  83. */
  84. public final String getAccessToken() {
  85. this.lock.lock();
  86. String tmp;
  87. try {
  88. tmp = this.accessToken;
  89. } finally {
  90. this.lock.unlock();
  91. }
  92. return tmp;
  93. }
  94. public final long getExpireIn() {
  95. this.lock.lock();
  96. long tmp;
  97. try {
  98. tmp = this.expireIn;
  99. } finally {
  100. this.lock.unlock();
  101. }
  102. return tmp;
  103. }
  104. protected CloseableHttpClient getHttpClient() {
  105. return httpClient;
  106. }
  107. public String getAppId() {
  108. return appId;
  109. }
  110. /**
  111. * Builder for constructing {@link HuaweiCredential}.
  112. */
  113. public static Builder builder() {
  114. return new Builder();
  115. }
  116. public static class Builder {
  117. private String appId;
  118. private String appSecret;
  119. private CloseableHttpClient httpClient;
  120. private Builder() {
  121. }
  122. public Builder setAppId(String appId) {
  123. this.appId = appId;
  124. return this;
  125. }
  126. public Builder setAppSecret(String appSecret) {
  127. this.appSecret = appSecret;
  128. return this;
  129. }
  130. public Builder setHttpClient(CloseableHttpClient httpClient) {
  131. this.httpClient = httpClient;
  132. return this;
  133. }
  134. public HuaweiCredential build() {
  135. return new HuaweiCredential(this);
  136. }
  137. }
  138. }