Search in sources :

Example 16 with InternalServerError

use of io.kamax.mxisd.exception.InternalServerError in project mxisd by kamax-io.

the class ExecIdentityStore method populate.

@Override
public List<ThreePidMapping> populate(List<ThreePidMapping> mappings) {
    Processor<List<ThreePidMapping>> p = new Processor<>();
    p.withConfig(cfg.getLookup().getBulk());
    p.addInput(JsonType, () -> {
        JsonArray tpids = GsonUtil.asArray(mappings.stream().map(mapping -> GsonUtil.get().toJsonTree(new ThreePid(mapping.getMedium(), mapping.getValue()))).collect(Collectors.toList()));
        return GsonUtil.get().toJson(GsonUtil.makeObj("lookup", tpids));
    });
    p.addInput(PlainType, () -> {
        StringBuilder input = new StringBuilder();
        for (ThreePidMapping mapping : mappings) {
            input.append(mapping.getMedium()).append("\t").append(mapping.getValue()).append(System.lineSeparator());
        }
        return input.toString();
    });
    p.addSuccessMapper(JsonType, output -> {
        if (StringUtils.isBlank(output)) {
            return Collections.emptyList();
        }
        LookupBulkResponseJson response = GsonUtil.get().fromJson(output, LookupBulkResponseJson.class);
        return response.getLookup().stream().map(item -> {
            ThreePidMapping mapping = new ThreePidMapping();
            mapping.setMedium(item.getMedium());
            mapping.setValue(item.getAddress());
            if (UserIdType.Localpart.is(item.getId().getType())) {
                mapping.setValue(MatrixID.asAcceptable(item.getId().getValue(), mxCfg.getDomain()).getId());
                return mapping;
            }
            if (UserIdType.MatrixID.is(item.getId().getType())) {
                mapping.setValue(MatrixID.asAcceptable(item.getId().getValue()).getId());
                return mapping;
            }
            throw new InternalServerError("Invalid user type: " + item.getId().getType());
        }).collect(Collectors.toList());
    });
    p.withFailureDefault(output -> Collections.emptyList());
    return p.execute();
}
Also used : JsonArray(com.google.gson.JsonArray) ThreePidMapping(io.kamax.mxisd.lookup.ThreePidMapping) JsonParseException(com.google.gson.JsonParseException) GsonUtil(io.kamax.matrix.json.GsonUtil) LookupBulkResponseJson(io.kamax.mxisd.backend.rest.LookupBulkResponseJson) MatrixConfig(io.kamax.mxisd.config.MatrixConfig) LoggerFactory(org.slf4j.LoggerFactory) MatrixID(io.kamax.matrix.MatrixID) StringUtils(org.apache.commons.lang3.StringUtils) IThreePidProvider(io.kamax.mxisd.lookup.provider.IThreePidProvider) SingleLookupRequest(io.kamax.mxisd.lookup.SingleLookupRequest) UserIdType(io.kamax.mxisd.UserIdType) LookupSingleResponseJson(io.kamax.mxisd.backend.rest.LookupSingleResponseJson) SingleLookupReply(io.kamax.mxisd.lookup.SingleLookupReply) Logger(org.slf4j.Logger) ThreePidMapping(io.kamax.mxisd.lookup.ThreePidMapping) io.kamax.matrix._MatrixID(io.kamax.matrix._MatrixID) Collectors(java.util.stream.Collectors) ThreePid(io.kamax.matrix.ThreePid) Objects(java.util.Objects) JsonArray(com.google.gson.JsonArray) InternalServerError(io.kamax.mxisd.exception.InternalServerError) List(java.util.List) ExecConfig(io.kamax.mxisd.config.ExecConfig) UserID(io.kamax.mxisd.UserID) Optional(java.util.Optional) Collections(java.util.Collections) LookupBulkResponseJson(io.kamax.mxisd.backend.rest.LookupBulkResponseJson) List(java.util.List) ThreePid(io.kamax.matrix.ThreePid) InternalServerError(io.kamax.mxisd.exception.InternalServerError)

Example 17 with InternalServerError

use of io.kamax.mxisd.exception.InternalServerError in project mxisd by kamax-io.

the class DirectoryManager method search.

public UserDirectorySearchResult search(URI target, String accessToken, String query) {
    if (StringUtils.startsWith(query, "@")) {
        query = query.substring(1);
    }
    log.info("Performing search for '{}'", query);
    log.info("Original request URL: {}", target);
    UserDirectorySearchResult result = new UserDirectorySearchResult();
    if (cfg.getExclude().getHomeserver()) {
        log.info("Skipping HS directory data, disabled in config");
    } else {
        URIBuilder builder = dns.transform(target);
        log.info("Querying HS at {}", builder);
        builder.setParameter("access_token", accessToken);
        HttpPost req = RestClientUtils.post(builder.toString(), new UserDirectorySearchRequest(query));
        try (CloseableHttpResponse res = client.execute(req)) {
            int status = res.getStatusLine().getStatusCode();
            Charset charset = ContentType.getOrDefault(res.getEntity()).getCharset();
            String body = IOUtils.toString(res.getEntity().getContent(), charset);
            if (status != 200) {
                MatrixErrorInfo info = GsonUtil.get().fromJson(body, MatrixErrorInfo.class);
                if (StringUtils.equals("M_UNRECOGNIZED", info.getErrcode())) {
                    // FIXME no hardcoding, use Enum
                    log.warn("Homeserver does not support Directory feature, skipping");
                } else {
                    log.error("Homeserver returned an error while performing directory search");
                    throw new HttpMatrixException(status, info.getErrcode(), info.getError());
                }
            }
            UserDirectorySearchResult resultHs = GsonUtil.get().fromJson(body, UserDirectorySearchResult.class);
            log.info("Found {} match(es) in HS for '{}'", resultHs.getResults().size(), query);
            result.getResults().addAll(resultHs.getResults());
            if (resultHs.isLimited()) {
                result.setLimited(true);
            }
        } catch (JsonSyntaxException e) {
            throw new InternalServerError("Invalid JSON reply from the HS: " + e.getMessage());
        } catch (IOException e) {
            throw new InternalServerError("Unable to query the HS: I/O error: " + e.getMessage());
        }
    }
    for (DirectoryProvider provider : providers) {
        log.info("Using Directory provider {}", provider.getClass().getSimpleName());
        UserDirectorySearchResult resultProvider = provider.searchByDisplayName(query);
        log.info("Display name: found {} match(es) for '{}'", resultProvider.getResults().size(), query);
        result.getResults().addAll(resultProvider.getResults());
        if (resultProvider.isLimited()) {
            result.setLimited(true);
        }
        if (cfg.getExclude().getThreepid()) {
            log.info("Skipping 3PID data, disabled in config");
        } else {
            resultProvider = provider.searchBy3pid(query);
            log.info("Threepid: found {} match(es) for '{}'", resultProvider.getResults().size(), query);
            result.getResults().addAll(resultProvider.getResults());
            if (resultProvider.isLimited()) {
                result.setLimited(true);
            }
        }
    }
    log.info("Total matches: {} - limited? {}", result.getResults().size(), result.isLimited());
    return result;
}
Also used : HttpPost(org.apache.http.client.methods.HttpPost) UserDirectorySearchRequest(io.kamax.mxisd.http.io.UserDirectorySearchRequest) HttpMatrixException(io.kamax.mxisd.exception.HttpMatrixException) Charset(java.nio.charset.Charset) IOException(java.io.IOException) InternalServerError(io.kamax.mxisd.exception.InternalServerError) URIBuilder(org.apache.http.client.utils.URIBuilder) JsonSyntaxException(com.google.gson.JsonSyntaxException) CloseableHttpResponse(org.apache.http.client.methods.CloseableHttpResponse) MatrixErrorInfo(io.kamax.matrix.MatrixErrorInfo) UserDirectorySearchResult(io.kamax.mxisd.http.io.UserDirectorySearchResult)

Example 18 with InternalServerError

use of io.kamax.mxisd.exception.InternalServerError in project mxisd by kamax-io.

the class BasicHttpHandler method proxyPost.

protected void proxyPost(HttpServerExchange exchange, JsonObject body, CloseableHttpClient client, ClientDnsOverwrite dns) {
    String target = dns.transform(URI.create(exchange.getRequestURL())).toString();
    log.info("Requesting remote: {}", target);
    HttpPost req = RestClientUtils.post(target, GsonUtil.get(), body);
    exchange.getRequestHeaders().forEach(header -> {
        header.forEach(v -> {
            String name = header.getHeaderName().toString();
            if (!StringUtils.startsWithIgnoreCase(name, "content-")) {
                req.addHeader(name, v);
            }
        });
    });
    try (CloseableHttpResponse res = client.execute(req)) {
        exchange.setStatusCode(res.getStatusLine().getStatusCode());
        for (Header h : res.getAllHeaders()) {
            for (HeaderElement el : h.getElements()) {
                exchange.getResponseHeaders().add(HttpString.tryFromString(h.getName()), el.getValue());
            }
        }
        res.getEntity().writeTo(exchange.getOutputStream());
        exchange.endExchange();
    } catch (IOException e) {
        log.warn("Unable to make proxy call: {}", e.getMessage(), e);
        throw new InternalServerError(e);
    }
}
Also used : HttpPost(org.apache.http.client.methods.HttpPost) Header(org.apache.http.Header) HeaderElement(org.apache.http.HeaderElement) CloseableHttpResponse(org.apache.http.client.methods.CloseableHttpResponse) HttpString(io.undertow.util.HttpString) IOException(java.io.IOException) InternalServerError(io.kamax.mxisd.exception.InternalServerError)

Example 19 with InternalServerError

use of io.kamax.mxisd.exception.InternalServerError in project mxisd by kamax-io.

the class OrmLiteSqlStorage method getTransactionResult.

@Override
public Optional<ASTransactionDao> getTransactionResult(String localpart, String txnId) {
    return withCatcher(() -> {
        ASTransactionDao dao = new ASTransactionDao();
        dao.setLocalpart(localpart);
        dao.setTransactionId(txnId);
        List<ASTransactionDao> daoList = asTxnDao.queryForMatchingArgs(dao);
        if (daoList.size() > 1) {
            throw new InternalServerError("Lookup for Transaction " + txnId + " for localpart " + localpart + " returned more than one result");
        }
        if (daoList.isEmpty()) {
            return Optional.empty();
        }
        return Optional.of(daoList.get(0));
    });
}
Also used : ASTransactionDao(io.kamax.mxisd.storage.ormlite.dao.ASTransactionDao) InternalServerError(io.kamax.mxisd.exception.InternalServerError)

Example 20 with InternalServerError

use of io.kamax.mxisd.exception.InternalServerError in project mxisd by kamax-io.

the class RestDirectoryProvider method search.

private UserDirectorySearchResult search(String by, String query) {
    UserDirectorySearchRequest request = new UserDirectorySearchRequest(query);
    request.setBy(by);
    try (CloseableHttpResponse httpResponse = client.execute(RestClientUtils.post(cfg.getEndpoints().getDirectory(), request))) {
        int status = httpResponse.getStatusLine().getStatusCode();
        if (status < 200 || status >= 300) {
            throw new InternalServerError("REST backend: Error: " + IOUtils.toString(httpResponse.getEntity().getContent(), StandardCharsets.UTF_8));
        }
        UserDirectorySearchResult response = parser.parse(httpResponse, UserDirectorySearchResult.class);
        for (UserDirectorySearchResult.Result result : response.getResults()) {
            result.setUserId(MatrixID.asAcceptable(result.getUserId(), mxCfg.getDomain()).getId());
        }
        return response;
    } catch (IOException e) {
        throw new InternalServerError("REST backend: I/O error: " + e.getMessage());
    }
}
Also used : UserDirectorySearchRequest(io.kamax.mxisd.http.io.UserDirectorySearchRequest) CloseableHttpResponse(org.apache.http.client.methods.CloseableHttpResponse) IOException(java.io.IOException) InternalServerError(io.kamax.mxisd.exception.InternalServerError) UserDirectorySearchResult(io.kamax.mxisd.http.io.UserDirectorySearchResult)

Aggregations

InternalServerError (io.kamax.mxisd.exception.InternalServerError)24 IOException (java.io.IOException)13 LdapException (org.apache.directory.api.ldap.model.exception.LdapException)6 CloseableHttpResponse (org.apache.http.client.methods.CloseableHttpResponse)6 io.kamax.matrix._MatrixID (io.kamax.matrix._MatrixID)5 CursorException (org.apache.directory.api.ldap.model.cursor.CursorException)5 CursorLdapReferralException (org.apache.directory.api.ldap.model.cursor.CursorLdapReferralException)5 EntryCursor (org.apache.directory.api.ldap.model.cursor.EntryCursor)5 Entry (org.apache.directory.api.ldap.model.entry.Entry)5 JsonObject (com.google.gson.JsonObject)4 ThreePid (io.kamax.matrix.ThreePid)4 UserDirectorySearchResult (io.kamax.mxisd.http.io.UserDirectorySearchResult)4 Connection (java.sql.Connection)4 PreparedStatement (java.sql.PreparedStatement)4 ResultSet (java.sql.ResultSet)4 SQLException (java.sql.SQLException)4 ArrayList (java.util.ArrayList)4 LdapConnection (org.apache.directory.ldap.client.api.LdapConnection)4 MatrixID (io.kamax.matrix.MatrixID)3 GsonUtil (io.kamax.matrix.json.GsonUtil)3