package foundation.icall.connector;
|
|
import java.util.Date;
|
|
import com.alibaba.fastjson.JSON;
|
import com.alibaba.fastjson.JSONObject;
|
|
import foundation.icall.ICall;
|
import foundation.icall.callout.ICallRequest;
|
import foundation.util.Util;
|
import foundation.workflow.WorkStep;
|
import okhttp3.MediaType;
|
import okhttp3.OkHttpClient;
|
import okhttp3.Request;
|
import okhttp3.RequestBody;
|
import okhttp3.Response;
|
import okhttp3.ResponseBody;
|
|
|
public class FoundationConn extends HttpServerConn {
|
|
private static FoundationConn instance;
|
private static int TimeOutMinute = 60;
|
private static String monitorId = "FoundationSource";
|
public Date lastTime;
|
private String token;
|
|
private FoundationConn() {
|
|
}
|
|
public static synchronized FoundationConn getInstance() {
|
if (instance == null) {
|
instance = new FoundationConn();
|
}
|
|
return instance;
|
}
|
|
@Override
|
public void login(WorkStep step, ICall iCall) throws Exception {
|
if (!tokenExpired()) {
|
return;
|
}
|
|
//1. 获取 token
|
getToken();
|
}
|
|
@Override
|
public void logout(WorkStep step, ICall iCall) throws Exception {
|
|
}
|
|
@Override
|
public ICallRequest createRequest(String url) {
|
String requestUrl = meta.getString("url") + url;
|
ICallRequest request = new ICallRequest(requestUrl);
|
|
request.addHeader("Content-Type", "application/json");
|
request.addFormData("token", token);
|
|
return request;
|
}
|
|
private boolean tokenExpired() {
|
if (Util.isEmpty(token)) {
|
return true;
|
}
|
|
Date now = new Date();
|
boolean result = now.getTime() - lastTime.getTime() >= TimeOutMinute * 60 * 1000;
|
|
logger.info("是否重新获取token:{}, 上次获取token时间:{}, 本次获取token时间:{}", result, lastTime, now);
|
|
return result;
|
}
|
|
private void getToken() throws Exception {
|
//1. create request
|
String baseUrl = meta.getString("base_url");
|
String loginUrl = meta.getString("login_url");
|
|
JSONObject jsonBody = new JSONObject();
|
jsonBody.put("username", meta.getString("username"));
|
jsonBody.put("password", meta.getString("password"));
|
String bodyStr = JSON.toJSONString(jsonBody);
|
|
Request request = new Request.Builder()
|
.url(baseUrl + loginUrl)
|
.post(RequestBody.create(MediaType.get("application/json"), bodyStr))
|
.build();
|
|
//2. get response
|
OkHttpClient httpClient = new OkHttpClient();
|
Response response = httpClient.newCall(request).execute();
|
|
if (!response.isSuccessful()) {
|
return ;
|
}
|
|
//2. get token
|
ResponseBody body = response.body();
|
bodyStr = body.string();
|
JSONObject tokenJson = JSONObject.parseObject(bodyStr);
|
|
token = tokenJson.getString("token");
|
lastTime = new Date();
|
}
|
|
public String getName() {
|
return meta.getName();
|
}
|
}
|