Search in sources :

Example 1 with JsonProfileRequest

use of io.kamax.mxisd.profile.JsonProfileRequest in project mxisd by kamax-io.

the class RestProfileProvider method doRequest.

private <T> Optional<T> doRequest(_MatrixID userId, Function<RestBackendConfig.ProfileEndpoints, Optional<String>> endpoint, Function<JsonProfileResult, Optional<T>> value) {
    Optional<String> url = endpoint.apply(cfg.getEndpoints().getProfile());
    if (!url.isPresent()) {
        return Optional.empty();
    }
    try {
        URIBuilder builder = new URIBuilder(url.get());
        HttpPost req = new HttpPost(builder.build());
        req.setEntity(new StringEntity(GsonUtil.get().toJson(new JsonProfileRequest(userId)), ContentType.APPLICATION_JSON));
        try (CloseableHttpResponse res = client.execute(req)) {
            int sc = res.getStatusLine().getStatusCode();
            if (sc == 404) {
                log.info("Got 404 - No result found");
                return Optional.empty();
            }
            if (sc != 200) {
                throw new InternalServerError("Unexpected backed status code: " + sc);
            }
            String body = IOUtils.toString(res.getEntity().getContent(), StandardCharsets.UTF_8);
            if (StringUtils.isBlank(body)) {
                log.warn("Backend response body is empty/blank, expected JSON object with profile key");
                return Optional.empty();
            }
            Optional<JsonObject> pJson = GsonUtil.findObj(GsonUtil.parseObj(body), "profile");
            if (!pJson.isPresent()) {
                log.warn("Backend response body is invalid, expected JSON object with profile key");
                return Optional.empty();
            }
            JsonProfileResult profile = gson.fromJson(pJson.get(), JsonProfileResult.class);
            return value.apply(profile);
        }
    } catch (JsonSyntaxException | InvalidJsonException e) {
        log.error("Unable to parse backend response as JSON", e);
        throw new InternalServerError(e);
    } catch (URISyntaxException e) {
        log.error("Unable to build a valid request URL", e);
        throw new InternalServerError(e);
    } catch (IOException e) {
        log.error("I/O Error during backend request", e);
        throw new InternalServerError();
    }
}
Also used : HttpPost(org.apache.http.client.methods.HttpPost) JsonProfileRequest(io.kamax.mxisd.profile.JsonProfileRequest) JsonObject(com.google.gson.JsonObject) URISyntaxException(java.net.URISyntaxException) IOException(java.io.IOException) InternalServerError(io.kamax.mxisd.exception.InternalServerError) URIBuilder(org.apache.http.client.utils.URIBuilder) StringEntity(org.apache.http.entity.StringEntity) JsonSyntaxException(com.google.gson.JsonSyntaxException) CloseableHttpResponse(org.apache.http.client.methods.CloseableHttpResponse) InvalidJsonException(io.kamax.matrix.json.InvalidJsonException) JsonProfileResult(io.kamax.mxisd.profile.JsonProfileResult)

Example 2 with JsonProfileRequest

use of io.kamax.mxisd.profile.JsonProfileRequest in project mxisd by kamax-io.

the class RestProfileProviderTest method forNameFound.

@Test
public void forNameFound() {
    String value = "This is my display name";
    JsonProfileResult r = new JsonProfileResult();
    r.setDisplayName(value);
    stubFor(post(urlEqualTo(displayNameEndpoint)).willReturn(aResponse().withHeader("Content-Type", ContentType.APPLICATION_JSON.getMimeType()).withBody(GsonUtil.get().toJson(GsonUtil.makeObj("profile", r)))));
    Optional<String> v = p.getDisplayName(userId);
    verify(postRequestedFor(urlMatching(displayNameEndpoint)).withHeader("Content-Type", containing(ContentType.APPLICATION_JSON.getMimeType())).withRequestBody(equalTo(GsonUtil.get().toJson(new JsonProfileRequest(userId)))));
    assertTrue(v.isPresent());
    assertEquals(value, v.get());
}
Also used : JsonProfileRequest(io.kamax.mxisd.profile.JsonProfileRequest) JsonProfileResult(io.kamax.mxisd.profile.JsonProfileResult) Test(org.junit.Test)

Example 3 with JsonProfileRequest

use of io.kamax.mxisd.profile.JsonProfileRequest in project mxisd by kamax-io.

the class ExecProfileStore method getFull.

private Optional<JsonProfileResult> getFull(_MatrixID userId, ExecConfig.Process cfg) {
    Processor<Optional<JsonProfileResult>> p = new Processor<>(cfg);
    p.addJsonInputTemplate(tokens -> new JsonProfileRequest(tokens.getLocalpart(), tokens.getDomain(), tokens.getMxid()));
    p.addInputTemplate(PlainType, tokens -> tokens.getLocalpart() + System.lineSeparator() + tokens.getDomain() + System.lineSeparator() + tokens.getMxid() + System.lineSeparator());
    p.addTokenMapper(cfg.getToken().getLocalpart(), userId::getLocalPart);
    p.addTokenMapper(cfg.getToken().getDomain(), userId::getDomain);
    p.addTokenMapper(cfg.getToken().getMxid(), userId::getId);
    p.withFailureDefault(v -> Optional.empty());
    p.addSuccessMapper(JsonType, output -> {
        if (StringUtils.isBlank(output)) {
            return Optional.empty();
        }
        return GsonUtil.findObj(GsonUtil.parseObj(output), "profile").map(obj -> GsonUtil.get().fromJson(obj, JsonProfileResult.class));
    });
    return p.execute();
}
Also used : Optional(java.util.Optional) JsonProfileRequest(io.kamax.mxisd.profile.JsonProfileRequest) JsonProfileResult(io.kamax.mxisd.profile.JsonProfileResult)

Aggregations

JsonProfileRequest (io.kamax.mxisd.profile.JsonProfileRequest)3 JsonProfileResult (io.kamax.mxisd.profile.JsonProfileResult)3 JsonObject (com.google.gson.JsonObject)1 JsonSyntaxException (com.google.gson.JsonSyntaxException)1 InvalidJsonException (io.kamax.matrix.json.InvalidJsonException)1 InternalServerError (io.kamax.mxisd.exception.InternalServerError)1 IOException (java.io.IOException)1 URISyntaxException (java.net.URISyntaxException)1 Optional (java.util.Optional)1 CloseableHttpResponse (org.apache.http.client.methods.CloseableHttpResponse)1 HttpPost (org.apache.http.client.methods.HttpPost)1 URIBuilder (org.apache.http.client.utils.URIBuilder)1 StringEntity (org.apache.http.entity.StringEntity)1 Test (org.junit.Test)1