Search in sources :

Example 1 with HeadersBodyStatus

use of org.keycloak.client.admin.cli.util.HeadersBodyStatus in project keycloak by keycloak.

the class UserOperations method resetUserPassword.

public static void resetUserPassword(String rootUrl, String realm, String auth, String userid, String password, boolean temporary) {
    String resourceUrl = composeResourceUrl(rootUrl, realm, "users/" + userid + "/reset-password");
    Headers headers = new Headers();
    if (auth != null) {
        headers.add("Authorization", auth);
    }
    headers.add("Content-Type", "application/json");
    CredentialRepresentation credentials = new CredentialRepresentation();
    credentials.setType("password");
    credentials.setTemporary(temporary);
    credentials.setValue(password);
    HeadersBodyStatus response;
    byte[] body;
    try {
        body = JsonSerialization.writeValueAsBytes(credentials);
    } catch (IOException e) {
        throw new RuntimeException("Failed to serialize JSON", e);
    }
    try {
        response = HttpUtil.doRequest("put", resourceUrl, new HeadersBody(headers, new ByteArrayInputStream(body)));
    } catch (IOException e) {
        throw new RuntimeException("HTTP request failed: PUT " + resourceUrl + "\n" + new String(body), e);
    }
    response.checkSuccess();
}
Also used : CredentialRepresentation(org.keycloak.representations.idm.CredentialRepresentation) HeadersBodyStatus(org.keycloak.client.admin.cli.util.HeadersBodyStatus) ByteArrayInputStream(java.io.ByteArrayInputStream) Headers(org.keycloak.client.admin.cli.util.Headers) HeadersBody(org.keycloak.client.admin.cli.util.HeadersBody) IOException(java.io.IOException)

Example 2 with HeadersBodyStatus

use of org.keycloak.client.admin.cli.util.HeadersBodyStatus in project keycloak by keycloak.

the class AbstractRequestCmd method process.

public CommandResult process(CommandInvocation commandInvocation) throws CommandException, InterruptedException {
    // see if Content-Type header is explicitly set to non-json value
    Header ctype = headers.get("content-type");
    InputStream content = null;
    CmdStdinContext<JsonNode> ctx = new CmdStdinContext<>();
    if (file != null) {
        if (ctype != null && !"application/json".equals(ctype.getValue())) {
            if ("-".equals(file)) {
                content = System.in;
            } else {
                try {
                    content = new BufferedInputStream(new FileInputStream(file));
                } catch (FileNotFoundException e) {
                    throw new RuntimeException("File not found: " + file);
                }
            }
        } else {
            ctx = parseFileOrStdin(file);
        }
    } else if (body != null) {
        content = new ByteArrayInputStream(body.getBytes(StandardCharsets.UTF_8));
    }
    ConfigData config = loadConfig();
    config = copyWithServerInfo(config);
    setupTruststore(config, commandInvocation);
    String auth = null;
    config = ensureAuthInfo(config, commandInvocation);
    config = copyWithServerInfo(config);
    if (credentialsAvailable(config)) {
        auth = ensureToken(config);
    }
    auth = auth != null ? "Bearer " + auth : null;
    if (auth != null) {
        headers.addIfMissing("Authorization", auth);
    }
    final String server = config.getServerUrl();
    final String realm = getTargetRealm(config);
    final String adminRoot = adminRestRoot != null ? adminRestRoot : composeAdminRoot(server);
    String resourceUrl = composeResourceUrl(adminRoot, realm, url);
    String typeName = extractTypeNameFromUri(resourceUrl);
    if (filter.size() > 0) {
        resourceUrl = HttpUtil.addQueryParamsToUri(resourceUrl, filter);
    }
    headers.addIfMissing("Accept", "application/json");
    if (isUpdate() && mergeMode) {
        ObjectNode result;
        HeadersBodyStatus response;
        try {
            response = HttpUtil.doGet(resourceUrl, new HeadersBody(headers));
            checkSuccess(resourceUrl, response);
            ByteArrayOutputStream buffer = new ByteArrayOutputStream();
            copyStream(response.getBody(), buffer);
            result = MAPPER.readValue(buffer.toByteArray(), ObjectNode.class);
        } catch (IOException e) {
            throw new RuntimeException("HTTP request error: " + e.getMessage(), e);
        }
        CmdStdinContext<JsonNode> ctxremote = new CmdStdinContext<>();
        ctxremote.setResult(result);
        // merge local representation over remote one
        if (ctx.getResult() != null) {
            ReflectionUtil.merge(ctx.getResult(), (ObjectNode) ctxremote.getResult());
        }
        ctx = ctxremote;
    }
    if (attrs.size() > 0) {
        if (content != null) {
            throw new RuntimeException("Can't set attributes on content of type other than application/json");
        }
        ctx = mergeAttributes(ctx, MAPPER.createObjectNode(), attrs);
    }
    if (content == null && ctx.getContent() != null) {
        content = new ByteArrayInputStream(ctx.getContent().getBytes(StandardCharsets.UTF_8));
    }
    ReturnFields returnFields = null;
    if (fields != null) {
        returnFields = new ReturnFields(fields);
    }
    // make sure content type is set
    if (content != null) {
        headers.addIfMissing("Content-Type", "application/json");
    }
    LinkedHashMap<String, String> queryParams = new LinkedHashMap<>();
    if (offset != null) {
        queryParams.put("first", String.valueOf(offset));
    }
    if (limit != null) {
        queryParams.put("max", String.valueOf(limit));
    }
    if (queryParams.size() > 0) {
        resourceUrl = HttpUtil.addQueryParamsToUri(resourceUrl, queryParams);
    }
    HeadersBodyStatus response;
    try {
        response = HttpUtil.doRequest(httpVerb, resourceUrl, new HeadersBody(headers, content));
    } catch (IOException e) {
        throw new RuntimeException("HTTP request error: " + e.getMessage(), e);
    }
    // output response
    if (printHeaders) {
        printOut(response.getStatus());
        for (Header header : response.getHeaders()) {
            printOut(header.getName() + ": " + header.getValue());
        }
    }
    checkSuccess(resourceUrl, response);
    AccessibleBufferOutputStream abos = new AccessibleBufferOutputStream(System.out);
    if (response.getBody() == null) {
        throw new RuntimeException("Internal error - response body should never be null");
    }
    if (printHeaders) {
        printOut("");
    }
    Header location = response.getHeaders().get("Location");
    String id = location != null ? extractLastComponentOfUri(location.getValue()) : null;
    if (id != null) {
        if (returnId) {
            printOut(id);
        } else if (!outputResult) {
            printErr("Created new " + typeName + " with id '" + id + "'");
        }
    }
    if (outputResult) {
        if (isCreateOrUpdate() && (response.getStatusCode() == 204 || id != null)) {
            // get object for id
            headers = new Headers();
            if (auth != null) {
                headers.add("Authorization", auth);
            }
            try {
                String fetchUrl = id != null ? (resourceUrl + "/" + id) : resourceUrl;
                response = doGet(fetchUrl, new HeadersBody(headers));
            } catch (IOException e) {
                throw new RuntimeException("HTTP request error: " + e.getMessage(), e);
            }
        }
        Header contentType = response.getHeaders().get("content-type");
        boolean canPrettyPrint = contentType != null && contentType.getValue().equals("application/json");
        boolean pretty = !compressed;
        if (canPrettyPrint && (pretty || returnFields != null)) {
            ByteArrayOutputStream buffer = new ByteArrayOutputStream();
            copyStream(response.getBody(), buffer);
            try {
                JsonNode rootNode = MAPPER.readValue(buffer.toByteArray(), JsonNode.class);
                if (returnFields != null) {
                    rootNode = applyFieldFilter(MAPPER, rootNode, returnFields);
                }
                if (outputFormat == OutputFormat.JSON) {
                    // now pretty print it to output
                    MAPPER.writeValue(abos, rootNode);
                } else {
                    printAsCsv(rootNode, returnFields, unquoted);
                }
            } catch (Exception ignored) {
                copyStream(new ByteArrayInputStream(buffer.toByteArray()), abos);
            }
        } else {
            copyStream(response.getBody(), abos);
        }
    }
    int lastByte = abos.getLastByte();
    if (lastByte != -1 && lastByte != 13 && lastByte != 10) {
        printErr("");
    }
    return CommandResult.SUCCESS;
}
Also used : HeadersBodyStatus(org.keycloak.client.admin.cli.util.HeadersBodyStatus) Headers(org.keycloak.client.admin.cli.util.Headers) FileNotFoundException(java.io.FileNotFoundException) JsonNode(com.fasterxml.jackson.databind.JsonNode) LinkedHashMap(java.util.LinkedHashMap) BufferedInputStream(java.io.BufferedInputStream) ObjectNode(com.fasterxml.jackson.databind.node.ObjectNode) ReturnFields(org.keycloak.client.admin.cli.util.ReturnFields) BufferedInputStream(java.io.BufferedInputStream) ByteArrayInputStream(java.io.ByteArrayInputStream) FileInputStream(java.io.FileInputStream) InputStream(java.io.InputStream) AccessibleBufferOutputStream(org.keycloak.client.admin.cli.util.AccessibleBufferOutputStream) HeadersBody(org.keycloak.client.admin.cli.util.HeadersBody) ByteArrayOutputStream(java.io.ByteArrayOutputStream) IOException(java.io.IOException) FileInputStream(java.io.FileInputStream) IOException(java.io.IOException) FileNotFoundException(java.io.FileNotFoundException) CommandException(org.jboss.aesh.console.command.CommandException) Header(org.keycloak.client.admin.cli.util.Header) ByteArrayInputStream(java.io.ByteArrayInputStream) ConfigData(org.keycloak.client.admin.cli.config.ConfigData) CmdStdinContext(org.keycloak.client.admin.cli.common.CmdStdinContext)

Aggregations

ByteArrayInputStream (java.io.ByteArrayInputStream)2 IOException (java.io.IOException)2 Headers (org.keycloak.client.admin.cli.util.Headers)2 HeadersBody (org.keycloak.client.admin.cli.util.HeadersBody)2 HeadersBodyStatus (org.keycloak.client.admin.cli.util.HeadersBodyStatus)2 JsonNode (com.fasterxml.jackson.databind.JsonNode)1 ObjectNode (com.fasterxml.jackson.databind.node.ObjectNode)1 BufferedInputStream (java.io.BufferedInputStream)1 ByteArrayOutputStream (java.io.ByteArrayOutputStream)1 FileInputStream (java.io.FileInputStream)1 FileNotFoundException (java.io.FileNotFoundException)1 InputStream (java.io.InputStream)1 LinkedHashMap (java.util.LinkedHashMap)1 CommandException (org.jboss.aesh.console.command.CommandException)1 CmdStdinContext (org.keycloak.client.admin.cli.common.CmdStdinContext)1 ConfigData (org.keycloak.client.admin.cli.config.ConfigData)1 AccessibleBufferOutputStream (org.keycloak.client.admin.cli.util.AccessibleBufferOutputStream)1 Header (org.keycloak.client.admin.cli.util.Header)1 ReturnFields (org.keycloak.client.admin.cli.util.ReturnFields)1 CredentialRepresentation (org.keycloak.representations.idm.CredentialRepresentation)1