001/*
002 * This file is part of the Keycloak Moodle authenticator
003 * Copyright (C) 2024 Michael N. Lipp
004 *
005 * This program is free software; you can redistribute it and/or modify it 
006 * under the terms of the GNU Lesser General Public License as published
007 * by the Free Software Foundation; either version 3 of the License, or 
008 * (at your option) any later version.
009 *
010 * This program is distributed in the hope that it will be useful, but 
011 * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
012 * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public 
013 * License for more details.
014 *
015 * You should have received a copy of the GNU Lesser General Public License along 
016 * with this program; if not, see <http://www.gnu.org/licenses/>.
017 */
018
019package org.jdrupes.keycloak.moodleauth.moodle.actions;
020
021import java.io.IOException;
022import java.util.List;
023import java.util.Map;
024import org.jdrupes.keycloak.moodleauth.moodle.RestAction;
025import org.jdrupes.keycloak.moodleauth.moodle.RestClient;
026import org.jdrupes.keycloak.moodleauth.moodle.model.MoodleErrorValues;
027import org.jdrupes.keycloak.moodleauth.moodle.model.MoodleUser;
028
029/**
030 * Find a user by his (login) name.
031 */
032public class MoodleUserByName extends RestAction {
033
034    /**
035     * Creates the action.
036     *
037     * @param client the client
038     */
039    public MoodleUserByName(RestClient client) {
040        super(client);
041    }
042
043    /**
044     * Must be public in order for the JSON decoder to work. For
045     * internal use only. 
046     */
047    public static class ResultWrapper extends MoodleErrorValues {
048        private MoodleUser[] users;
049
050        /**
051         * @param users the users to set
052         */
053        @SuppressWarnings({ "PMD.UseVarargs", "PMD.ArrayIsStoredDirectly" })
054        public void setUsers(MoodleUser[] users) {
055            this.users = users;
056        }
057
058        @SuppressWarnings("PMD.MethodReturnsInternalArray")
059        public MoodleUser[] getUsers() {
060            return users;
061        }
062    }
063
064    /**
065     * Invoke the action.
066     *
067     * @param userName the user name
068     * @return the moodle course
069     * @throws IOException Signals that an I/O exception has occurred.
070     */
071    @SuppressWarnings("PMD.AvoidLiteralsInIfCondition")
072    public MoodleUser invoke(String userName) throws IOException {
073        var users = client.invoke(MoodleUser[].class, Map.of(
074            "wsfunction", "core_user_get_users_by_field"),
075            Map.of("field", "username",
076                "values", List.of(userName)));
077        if (users.length != 1) {
078            throw new IllegalArgumentException(
079                "Course \"" + userName + "\"not found.");
080        }
081        return users[0];
082    }
083}