Search in sources :

Example 6 with CommandException

use of org.jboss.aesh.console.command.CommandException in project keycloak by keycloak.

the class CreateCmd method execute.

@Override
public CommandResult execute(CommandInvocation commandInvocation) throws CommandException, InterruptedException {
    List<AttributeOperation> attrs = new LinkedList<>();
    try {
        if (printHelp()) {
            return help ? CommandResult.SUCCESS : CommandResult.FAILURE;
        }
        processGlobalOptions();
        if (args != null) {
            Iterator<String> it = args.iterator();
            while (it.hasNext()) {
                String option = it.next();
                switch(option) {
                    case "-s":
                    case "--set":
                        {
                            if (!it.hasNext()) {
                                throw new IllegalArgumentException("Option " + option + " requires a value");
                            }
                            String[] keyVal = parseKeyVal(it.next());
                            attrs.add(new AttributeOperation(SET, keyVal[0], keyVal[1]));
                            break;
                        }
                    default:
                        {
                            throw new IllegalArgumentException("Unsupported option: " + option);
                        }
                }
            }
        }
        if (file == null && attrs.size() == 0) {
            throw new IllegalArgumentException("No file nor attribute values specified");
        }
        if (outputClient && returnClientId) {
            throw new IllegalArgumentException("Options -o and -i are mutually exclusive");
        }
        // if --token is specified read it
        if ("-".equals(token)) {
            token = readSecret("Enter Initial Access Token: ", commandInvocation);
        }
        CmdStdinContext ctx = new CmdStdinContext();
        if (file != null) {
            ctx = parseFileOrStdin(file, regType);
        }
        if (ctx.getEndpointType() == null) {
            regType = regType != null ? regType : DEFAULT;
            ctx.setEndpointType(regType);
        } else if (regType != null && ctx.getEndpointType() != regType) {
            throw new RuntimeException("Requested endpoint type not compatible with detected configuration format: " + ctx.getEndpointType());
        }
        if (attrs.size() > 0) {
            ctx = mergeAttributes(ctx, attrs);
        }
        String contentType = getExpectedContentType(ctx.getEndpointType());
        ConfigData config = loadConfig();
        config = copyWithServerInfo(config);
        if (token == null) {
            // if initial token is not set, try use the one from configuration
            token = config.sessionRealmConfigData().getInitialToken();
        }
        setupTruststore(config, commandInvocation);
        String auth = token;
        if (auth == null) {
            config = ensureAuthInfo(config, commandInvocation);
            config = copyWithServerInfo(config);
            if (credentialsAvailable(config)) {
                auth = ensureToken(config);
            }
        }
        auth = auth != null ? "Bearer " + auth : null;
        final String server = config.getServerUrl();
        final String realm = config.getRealm();
        InputStream response = doPost(server + "/realms/" + realm + "/clients-registrations/" + ctx.getEndpointType().getEndpoint(), contentType, HttpUtil.APPLICATION_JSON, ctx.getContent(), auth);
        try {
            if (ctx.getEndpointType() == DEFAULT || ctx.getEndpointType() == SAML2) {
                ClientRepresentation client = JsonSerialization.readValue(response, ClientRepresentation.class);
                outputResult(client.getClientId(), client);
                saveMergeConfig(cfg -> {
                    setRegistrationToken(cfg.ensureRealmConfigData(server, realm), client.getClientId(), client.getRegistrationAccessToken());
                });
            } else if (ctx.getEndpointType() == OIDC) {
                OIDCClientRepresentation client = JsonSerialization.readValue(response, OIDCClientRepresentation.class);
                outputResult(client.getClientId(), client);
                saveMergeConfig(cfg -> {
                    setRegistrationToken(cfg.ensureRealmConfigData(server, realm), client.getClientId(), client.getRegistrationAccessToken());
                });
            } else {
                printOut("Response from server: " + readFully(response));
            }
        } catch (UnrecognizedPropertyException e) {
            throw new RuntimeException("Failed to process HTTP reponse - " + e.getMessage(), e);
        } catch (IOException e) {
            throw new RuntimeException("Failed to process HTTP response", e);
        }
        return CommandResult.SUCCESS;
    } catch (IllegalArgumentException e) {
        throw new IllegalArgumentException(e.getMessage() + suggestHelp(), e);
    } finally {
        commandInvocation.stop();
    }
}
Also used : UnrecognizedPropertyException(com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException) DEFAULT(org.keycloak.client.registration.cli.common.EndpointType.DEFAULT) CMD(org.keycloak.client.registration.cli.util.OsUtil.CMD) OIDC(org.keycloak.client.registration.cli.common.EndpointType.OIDC) ParseUtil.parseKeyVal(org.keycloak.client.registration.cli.util.ParseUtil.parseKeyVal) CommandResult(org.jboss.aesh.console.command.CommandResult) CommandDefinition(org.jboss.aesh.cl.CommandDefinition) AuthUtil.ensureToken(org.keycloak.client.registration.cli.util.AuthUtil.ensureToken) ConfigUtil.setRegistrationToken(org.keycloak.client.registration.cli.util.ConfigUtil.setRegistrationToken) IoUtil.printOut(org.keycloak.client.registration.cli.util.IoUtil.printOut) ConfigUtil.saveMergeConfig(org.keycloak.client.registration.cli.util.ConfigUtil.saveMergeConfig) CommandInvocation(org.jboss.aesh.console.command.invocation.CommandInvocation) EndpointType(org.keycloak.client.registration.cli.common.EndpointType) LinkedList(java.util.LinkedList) ParseUtil.parseFileOrStdin(org.keycloak.client.registration.cli.util.ParseUtil.parseFileOrStdin) CmdStdinContext(org.keycloak.client.registration.cli.common.CmdStdinContext) EOL(org.keycloak.client.registration.cli.util.OsUtil.EOL) OIDCClientRepresentation(org.keycloak.representations.oidc.OIDCClientRepresentation) PrintWriter(java.io.PrintWriter) IoUtil.readSecret(org.keycloak.client.registration.cli.util.IoUtil.readSecret) Iterator(java.util.Iterator) ParseUtil.mergeAttributes(org.keycloak.client.registration.cli.util.ParseUtil.mergeAttributes) Arguments(org.jboss.aesh.cl.Arguments) StringWriter(java.io.StringWriter) DEFAULT_CONFIG_FILE_STRING(org.keycloak.client.registration.cli.util.ConfigUtil.DEFAULT_CONFIG_FILE_STRING) SAML2(org.keycloak.client.registration.cli.common.EndpointType.SAML2) IOException(java.io.IOException) ConfigUtil.loadConfig(org.keycloak.client.registration.cli.util.ConfigUtil.loadConfig) HttpUtil(org.keycloak.client.registration.cli.util.HttpUtil) HttpUtil.getExpectedContentType(org.keycloak.client.registration.cli.util.HttpUtil.getExpectedContentType) ClientRepresentation(org.keycloak.representations.idm.ClientRepresentation) JsonSerialization(org.keycloak.util.JsonSerialization) ConfigUtil.credentialsAvailable(org.keycloak.client.registration.cli.util.ConfigUtil.credentialsAvailable) PROMPT(org.keycloak.client.registration.cli.util.OsUtil.PROMPT) Option(org.jboss.aesh.cl.Option) List(java.util.List) AttributeOperation(org.keycloak.client.registration.cli.common.AttributeOperation) CommandException(org.jboss.aesh.console.command.CommandException) EndpointTypeConverter(org.keycloak.client.registration.cli.aesh.EndpointTypeConverter) IoUtil.readFully(org.keycloak.client.registration.cli.util.IoUtil.readFully) SET(org.keycloak.client.registration.cli.common.AttributeOperation.Type.SET) OS_ARCH(org.keycloak.client.registration.cli.util.OsUtil.OS_ARCH) Command(org.jboss.aesh.console.command.Command) IoUtil.printErr(org.keycloak.client.registration.cli.util.IoUtil.printErr) ConfigData(org.keycloak.client.registration.cli.config.ConfigData) InputStream(java.io.InputStream) HttpUtil.doPost(org.keycloak.client.registration.cli.util.HttpUtil.doPost) AttributeOperation(org.keycloak.client.registration.cli.common.AttributeOperation) InputStream(java.io.InputStream) UnrecognizedPropertyException(com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException) IOException(java.io.IOException) LinkedList(java.util.LinkedList) OIDCClientRepresentation(org.keycloak.representations.oidc.OIDCClientRepresentation) ClientRepresentation(org.keycloak.representations.idm.ClientRepresentation) OIDCClientRepresentation(org.keycloak.representations.oidc.OIDCClientRepresentation) ConfigData(org.keycloak.client.registration.cli.config.ConfigData) CmdStdinContext(org.keycloak.client.registration.cli.common.CmdStdinContext)

Aggregations

CommandException (org.jboss.aesh.console.command.CommandException)6 InputStream (java.io.InputStream)4 IOException (java.io.IOException)3 JsonNode (com.fasterxml.jackson.databind.JsonNode)2 ByteArrayInputStream (java.io.ByteArrayInputStream)2 ByteArrayOutputStream (java.io.ByteArrayOutputStream)2 File (java.io.File)2 PrintWriter (java.io.PrintWriter)2 StringWriter (java.io.StringWriter)2 URL (java.net.URL)2 LinkedList (java.util.LinkedList)2 List (java.util.List)2 Arguments (org.jboss.aesh.cl.Arguments)2 CommandDefinition (org.jboss.aesh.cl.CommandDefinition)2 Option (org.jboss.aesh.cl.Option)2 CommandResult (org.jboss.aesh.console.command.CommandResult)2 CommandInvocation (org.jboss.aesh.console.command.invocation.CommandInvocation)2 CmdStdinContext (org.keycloak.client.admin.cli.common.CmdStdinContext)2 AccessibleBufferOutputStream (org.keycloak.client.admin.cli.util.AccessibleBufferOutputStream)2 EndpointType (org.keycloak.client.registration.cli.common.EndpointType)2