Skip to content

Commit

Permalink
#349 add a simplehttpclient
Browse files Browse the repository at this point in the history
(cherry picked from commit 3cfe7ee)
  • Loading branch information
syjer authored and cbellone committed Mar 26, 2018
1 parent 2273e54 commit 4e3cc24
Show file tree
Hide file tree
Showing 3 changed files with 176 additions and 3 deletions.
6 changes: 4 additions & 2 deletions src/main/java/alfio/extension/ScriptingExecutionService.java
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,7 @@ public class ScriptingExecutionService {

private static final OkHttpClient HTTP_CLIENT = new OkHttpClient();
private static final RestTemplate REST_TEMPLATE = new RestTemplate();
private static final SimpleHttpClient SIMPLE_HTTP_CLIENT = new SimpleHttpClient(HTTP_CLIENT);

private final static Compilable engine = (Compilable) new ScriptEngineManager().getEngineByName("nashorn");
private final Cache<String, CompiledScript> compiledScriptCache = Caffeine.newBuilder()
Expand All @@ -67,7 +68,7 @@ public <T> T executeScript(String name, String hash, Supplier<String> scriptFetc
CompiledScript compiledScript = compiledScriptCache.get(hash, (key) -> {
try {
return engine.compile(scriptFetcher.get());
} catch (ScriptException se) {
} catch (Throwable se) {
log.warn("Was not able to compile script " + name, se);
extensionLogger.logError("Was not able to compile script: " + se.getMessage());
throw new IllegalStateException(se);
Expand Down Expand Up @@ -107,12 +108,13 @@ private static <T> T executeScript(String name, CompiledScript script, Map<Strin
engineScope.put("GSON", Json.GSON);
engineScope.put("restTemplate", REST_TEMPLATE);
engineScope.put("httpClient", HTTP_CLIENT);
engineScope.put("simpleHttpClient", SIMPLE_HTTP_CLIENT);
engineScope.put("returnClass", clazz);
engineScope.putAll(params);
T res = (T) script.eval(newContext);
extensionLogger.logSuccess("Script executed successfully");
return res;
} catch (ScriptException ex) {
} catch (Throwable ex) { //
log.warn("Error while executing script " + name + ":", ex);
extensionLogger.logError("Error while executing script: " + ex.getMessage());
throw new IllegalStateException(ex);
Expand Down
171 changes: 171 additions & 0 deletions src/main/java/alfio/extension/SimpleHttpClient.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,171 @@
/**
* This file is part of alf.io.
*
* alf.io is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* alf.io is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with alf.io. If not, see <http://www.gnu.org/licenses/>.
*/
package alfio.extension;

import alfio.util.Json;
import com.google.gson.JsonSyntaxException;
import lombok.AllArgsConstructor;
import lombok.Getter;
import okhttp3.*;

import java.io.IOException;
import java.util.*;

public class SimpleHttpClient {


private static final RequestBody EMPTY_REQUEST = RequestBody.create(null, new byte[0]);
private static final Set<String> NULL_REQUEST_BODY = new HashSet<>(Arrays.asList("GET", "HEAD"));

private final OkHttpClient okHttpClient;

public SimpleHttpClient(OkHttpClient okHttpClient) {
this.okHttpClient = okHttpClient;
}

public HttpClientResponse get(String url) throws IOException {
return get(url, Collections.emptyMap());
}

public HttpClientResponse get(String url, Map<String, String> headers) throws IOException {
return doRequest(url, headers, "GET", null);
}


public HttpClientResponse head(String url) throws IOException {
return head(url, Collections.emptyMap());
}

public HttpClientResponse head(String url, Map<String, String> headers) throws IOException {
return doRequest(url, headers, "HEAD", null);
}

public HttpClientResponse post(String url) throws IOException {
return post(url, Collections.emptyMap());
}

public HttpClientResponse post(String url, Map<String, String> headers) throws IOException {
return post(url, headers, null);
}

public HttpClientResponse post(String url, Map<String, String> headers, Object body) throws IOException {
return doRequest(url, headers, "POST", body);
}


public HttpClientResponse delete(String url) throws IOException {
return delete(url, Collections.emptyMap());
}

public HttpClientResponse delete(String url, Map<String, String> headers) throws IOException {
return delete(url, headers, null);
}

public HttpClientResponse delete(String url, Map<String, String> headers, Object body) throws IOException {
return doRequest(url, headers, "DELETE", body);
}


public HttpClientResponse put(String url) throws IOException {
return put(url, Collections.emptyMap());
}

public HttpClientResponse put(String url, Map<String, String> headers) throws IOException {
return put(url, headers, null);
}

public HttpClientResponse put(String url, Map<String, String> headers, Object body) throws IOException {
return doRequest(url, headers, "POST", body);
}


public HttpClientResponse patch(String url) throws IOException {
return patch(url, Collections.emptyMap());
}

public HttpClientResponse patch(String url, Map<String, String> headers) throws IOException {
return patch(url, headers, null);
}

public HttpClientResponse patch(String url, Map<String, String> headers, Object body) throws IOException {
return doRequest(url, headers, "PATCH", body);
}

public HttpClientResponse method(String method, String url, Map<String, String> headers, Object body) throws IOException {
return doRequest(url, headers, method, body);
}

private HttpClientResponse doRequest(String url, Map<String, String> headers, String method, Object requestBody) throws IOException {

Request.Builder requestBuilder = buildUrlAndHeader(url, headers);

Request req = requestBuilder.method(method, NULL_REQUEST_BODY.contains(method)? null : buildRequestBody(requestBody)).build();

try (Response response = okHttpClient.newCall(req).execute()) {
ResponseBody body = response.body();
return new HttpClientResponse(
response.isSuccessful(),
response.code(),
response.message(),
response.headers().toMultimap(),
body == null ? null : body.string());
}
}


public String basicCredentials(String username, String password) {
return Credentials.basic(username, password);
}

private static Request.Builder buildUrlAndHeader(String url, Map<String, String> headers) {
Request.Builder requestBuilder = new Request.Builder().url(url);
if (headers != null) {
headers.forEach((k,v) -> {
requestBuilder.header(k,v);
});
}
return requestBuilder;
}

private static RequestBody buildRequestBody(Object body) {
return body == null ? EMPTY_REQUEST : RequestBody.create(MediaType.parse("application/json"), Json.GSON.toJson(body));
}


@Getter
@AllArgsConstructor
public static class HttpClientResponse {
private final boolean successful;
private final int code;
private final String message;
private final Map<String, List<String>> headers;
private final String body;


public Object getJsonBody() {
return tryParse(body, Object.class);
}

private static Object tryParse(String body, Class<?> clazz) {
try {
return Json.GSON.fromJson(body, clazz);
} catch (JsonSyntaxException jse) {
return null;
}
}
}
}
2 changes: 1 addition & 1 deletion src/main/resources/alfio/extension/sample.js
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ function executeScript(scriptEvent) {
log.warn('hello from script with event: ' + scriptEvent);
log.warn('extension parameters are: ' + extensionParameters);
//this sample calls the https://csrng.net/ website and generates a random invoice number
var randomNumber = restTemplate.getForObject('https://csrng.net/csrng/csrng.php?min=0&max=100', Java.type('java.util.ArrayList').class)[0].random;
var randomNumber = simpleHttpClient.get('https://csrng.net/csrng/csrng.php?min=0&max=100').getJsonBody()[0].random;
log.warn('the invoice number will be: ' + randomNumber);
return {
invoiceNumber: randomNumber
Expand Down

0 comments on commit 4e3cc24

Please sign in to comment.