Ivelin Iliev
Ivelin Iliev

Reputation: 53

Cannot add element to Map - Unsupported Operation Exception

I am having trouble inserting element to this mutable Map and i cannot figure out why? I can see it returns Map so it should not an issue to put element in. Can you help me with that?

myClient.authentications.put("basicAuthentication", httpBasicAuth)

Authentications look like this:

public Map<String, Authentication> getAuthentications() {
        return authentications;
}
private Map<String, Authentication> authentications;

Is there something that i am missing here?

Edit 1: Adding some more code for clearance

HttpBasicAuth is just a basic class that implements Authentication

public class HttpBasicAuth implements Authentication {
    private String username;
    private String password;

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    @Override
    public void applyToParams(List<Pair> queryParams, Map<String, String> headerParams) {
        if (username == null && password == null) {
            return;
        }
        headerParams.put("Authorization", Credentials.basic(
            username == null ? "" : username,
            password == null ? "" : password));
    }

 val httpBasicAuth = HttpBasicAuth()
                httpBasicAuth.username = "user"
                httpBasicAuth.password = "pass"
                myClient.authentications.put("basicAuthentication", httpBasicAuth)

Upvotes: 0

Views: 5866

Answers (1)

Boken
Boken

Reputation: 5445

Currently, by default this field has null value so you CAN NOT call any method on it. So when you call:

myClient.authentications.put("basicAuthentication", httpBasicAuth)

you are trying call method put() on null.

To solve it, you can change your initialization from:

private Map<String, Authentication> authentications;

To (in Java):

private Map<String, String> authentications = new HashMap<>();

or in to (in Kotlin):

private val authentications: Map<String, Authentication> = mapOf();

After those changes this field will be initialized with empty array instead of null. Remember that this change it's very important when you have some logic based on it (e.g. you are checking authentications == null).

Upvotes: 0

Related Questions