|
| 1 | +package de.pfadfinden.ica; |
| 2 | + |
| 3 | +import com.google.common.util.concurrent.RateLimiter; |
| 4 | +import com.google.gson.Gson; |
| 5 | +import com.google.gson.GsonBuilder; |
| 6 | +import com.google.gson.reflect.TypeToken; |
| 7 | +import de.pfadfinden.ica.converter.LocalDateConverter; |
| 8 | +import de.pfadfinden.ica.converter.LocalDateTimeConverter; |
| 9 | +import de.pfadfinden.ica.converter.LocalTimeConverter; |
| 10 | +import de.pfadfinden.ica.execption.IcaApiException; |
| 11 | +import de.pfadfinden.ica.execption.IcaAuthenticationException; |
| 12 | +import de.pfadfinden.ica.model.IcaApiResponse; |
| 13 | +import de.pfadfinden.ica.model.IcaResponse; |
| 14 | +import okhttp3.*; |
| 15 | +import org.slf4j.Logger; |
| 16 | +import org.slf4j.LoggerFactory; |
| 17 | + |
| 18 | +import java.io.Closeable; |
| 19 | +import java.io.IOException; |
| 20 | +import java.lang.reflect.Type; |
| 21 | +import java.time.LocalDate; |
| 22 | +import java.time.LocalDateTime; |
| 23 | +import java.time.LocalTime; |
| 24 | +import java.util.Collections; |
| 25 | + |
| 26 | +import static com.google.common.base.Preconditions.checkNotNull; |
| 27 | +import static com.google.common.base.Strings.emptyToNull; |
| 28 | + |
| 29 | +public class IcaConnection implements Closeable { |
| 30 | + |
| 31 | + private OkHttpClient okHttpClient; |
| 32 | + |
| 33 | + private Gson gson; |
| 34 | + |
| 35 | + private final Logger logger = LoggerFactory.getLogger(IcaConnection.class); |
| 36 | + private final RateLimiter apiRateLimiter = RateLimiter.create(3.0); // rate is "3 permits per second" |
| 37 | + |
| 38 | + private CookieJar cookieJar = new MemoryCookieJar(); |
| 39 | + |
| 40 | + private IcaServer icaServer; |
| 41 | + |
| 42 | + private static final String URL_STARTUP = "rest/nami/auth/manual/sessionStartup"; |
| 43 | + |
| 44 | + public IcaConnection(IcaServer icaServer, String username, String password) throws IcaAuthenticationException { |
| 45 | + this.init(icaServer); |
| 46 | + |
| 47 | + try { |
| 48 | + authenticate(username, password); |
| 49 | + } catch (IOException e) { |
| 50 | + e.printStackTrace(); |
| 51 | + } |
| 52 | + } |
| 53 | + |
| 54 | + public IcaConnection(IcaServer icaServer, String session) { |
| 55 | + this.init(icaServer); |
| 56 | + |
| 57 | + Cookie cookie = new Cookie.Builder() |
| 58 | + .domain(icaServer.getHost()) |
| 59 | + .path("/ica") |
| 60 | + .name("JSESSIONID") |
| 61 | + .value(session) |
| 62 | + .secure() |
| 63 | + .build(); |
| 64 | + |
| 65 | + // ToDo: httpURL! |
| 66 | + this.cookieJar.saveFromResponse(null, Collections.singletonList(cookie)); |
| 67 | + } |
| 68 | + |
| 69 | + private void init(IcaServer icaServer){ |
| 70 | + gson = new GsonBuilder() |
| 71 | + .registerTypeAdapter(LocalDate.class, new LocalDateConverter()) |
| 72 | + .registerTypeAdapter(LocalDateTime.class, new LocalDateTimeConverter()) |
| 73 | + .registerTypeAdapter(LocalTime.class, new LocalTimeConverter()) |
| 74 | + .create(); |
| 75 | + |
| 76 | + this.icaServer = icaServer; |
| 77 | + |
| 78 | + this.okHttpClient = new OkHttpClient.Builder() |
| 79 | + .cookieJar(this.cookieJar) |
| 80 | + .build(); |
| 81 | + } |
| 82 | + |
| 83 | + private void authenticate(String username, String password) throws IOException, IcaAuthenticationException { |
| 84 | + |
| 85 | + checkNotNull(emptyToNull(username),"username null or empty"); |
| 86 | + checkNotNull(emptyToNull(password),"password null or empty"); |
| 87 | + |
| 88 | + this.apiRateLimiter.acquire(); // may wait |
| 89 | + |
| 90 | + HttpUrl httpUrl = this.getUrlBuilder(false) |
| 91 | + .addPathSegments(URL_STARTUP) |
| 92 | + .build(); |
| 93 | + |
| 94 | + RequestBody formBody = new FormBody.Builder() |
| 95 | + .add("username", username) |
| 96 | + .add("password", password) |
| 97 | + .add("Login", "API") |
| 98 | + .add("redirectTo", "./pages/loggedin.jsp") |
| 99 | + .build(); |
| 100 | + |
| 101 | + Request request = new Request.Builder() |
| 102 | + .url(httpUrl) |
| 103 | + .post(formBody) |
| 104 | + .build(); |
| 105 | + |
| 106 | + logger.debug("Authenticating on ICA via URI '{}'.",httpUrl); |
| 107 | + |
| 108 | + try ( |
| 109 | + Response response = okHttpClient.newCall(request).execute() |
| 110 | + ) { |
| 111 | + if (response.code() == 200 && response.body() != null) { |
| 112 | + String resultData = response.body().string(); |
| 113 | + IcaApiResponse<Object> resp = gson.fromJson(resultData, new TypeToken<IcaApiResponse<Object>>() {}.getType()); |
| 114 | + logger.debug("Security: Authenticated to ICA using API token: {}.",resp.getApiSessionToken()); |
| 115 | + } else { |
| 116 | + logger.warn("Security: Authentication on ICA failed with response code {}.",response.code()); |
| 117 | + throw new IcaAuthenticationException("Authentication on ICA failed."); |
| 118 | + } |
| 119 | + } |
| 120 | + } |
| 121 | + |
| 122 | + public <T> T executeApiRequest(HttpUrl httpUrl, Type resultType) throws IcaApiException { |
| 123 | + Request request = new Request.Builder() |
| 124 | + .url(httpUrl) |
| 125 | + .build(); |
| 126 | + return this.executeApiRequest(request,resultType); |
| 127 | + } |
| 128 | + |
| 129 | + public <T> T executeApiRequest(Request request, Type resultType) throws IcaApiException { |
| 130 | + |
| 131 | + this.apiRateLimiter.acquire(); // may wait |
| 132 | + |
| 133 | + logger.info("Executing ICA API request. URI: '{}' Method: '{}' ResultType: '{}'", |
| 134 | + request.url(), |
| 135 | + request.method(), |
| 136 | + resultType.getTypeName() |
| 137 | + ); |
| 138 | + |
| 139 | + try ( |
| 140 | + Response response = okHttpClient.newCall(request).execute() |
| 141 | + ) { |
| 142 | + if(response.code() != 200){ |
| 143 | + logger.error("ICA API returns error: RequestURI {} RequestType {} API ResultStatusCode {}", |
| 144 | + request.url(), |
| 145 | + request.method(), |
| 146 | + response.code() |
| 147 | + ); |
| 148 | + } |
| 149 | + |
| 150 | + Type typeWithResponse = IcaResponse.getType(resultType); |
| 151 | + Type typeWithApiResponse = IcaApiResponse.getType(typeWithResponse); |
| 152 | + |
| 153 | + IcaApiResponse<IcaResponse<T>> result = gson.fromJson(response.body().string(), typeWithApiResponse); |
| 154 | + |
| 155 | + if (result == null || result.getResponse() == null || result.getStatusCode() != 0) { |
| 156 | + logger.error("Ica API returns error: RequestURI {} RequestType {} API ResultStatusCode {}", |
| 157 | + request.url(), |
| 158 | + request.method(), |
| 159 | + response.code() |
| 160 | + ); |
| 161 | + throw new IcaApiException(result); |
| 162 | + } |
| 163 | + |
| 164 | + return result.getResponse().getData(); |
| 165 | + } catch (IOException e) { |
| 166 | + throw new IcaApiException(e); |
| 167 | + } |
| 168 | + } |
| 169 | + |
| 170 | + public HttpUrl.Builder getUrlBuilder(){ |
| 171 | + return this.getUrlBuilder(true); |
| 172 | + } |
| 173 | + |
| 174 | + public HttpUrl.Builder getUrlBuilder(Boolean apiEndpoint){ |
| 175 | + HttpUrl.Builder builder = new HttpUrl.Builder() |
| 176 | + .host(icaServer.getHost()) |
| 177 | + .addPathSegment(icaServer.getDeployment()) |
| 178 | + .scheme("https"); |
| 179 | + if(apiEndpoint) builder.addPathSegments("rest/api/1/2/service"); |
| 180 | + return builder; |
| 181 | + } |
| 182 | + |
| 183 | + public OkHttpClient getCloseableHttpClient() { |
| 184 | + return this.okHttpClient; |
| 185 | + } |
| 186 | + |
| 187 | + public String toJson(Object o) { |
| 188 | + return gson.toJson(o); |
| 189 | + } |
| 190 | + |
| 191 | + @Override |
| 192 | + public void close() { |
| 193 | + |
| 194 | + } |
| 195 | +} |
0 commit comments