001/*
002 * (C) Copyright 2019 Nuxeo (http://nuxeo.com/) and others.
003 *
004 * Licensed under the Apache License, Version 2.0 (the "License");
005 * you may not use this file except in compliance with the License.
006 * You may obtain a copy of the License at
007 *
008 *     http://www.apache.org/licenses/LICENSE-2.0
009 *
010 * Unless required by applicable law or agreed to in writing, software
011 * distributed under the License is distributed on an "AS IS" BASIS,
012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013 * See the License for the specific language governing permissions and
014 * limitations under the License.
015 *
016 * Contributors:
017 *     Salem Aouana
018 */
019
020package org.nuxeo.ecm.platform.oauth2.clients;
021
022import static java.util.Objects.requireNonNullElse;
023import static java.util.Objects.requireNonNullElseGet;
024import static org.nuxeo.ecm.core.io.registry.reflect.Instantiations.SINGLETON;
025import static org.nuxeo.ecm.core.io.registry.reflect.Priorities.REFERENCE;
026import static org.nuxeo.ecm.platform.oauth2.clients.OAuth2Client.NAME_FIELD;
027import static org.nuxeo.ecm.platform.oauth2.clients.OAuth2Client.REDIRECT_URI_FIELD;
028import static org.nuxeo.ecm.platform.oauth2.clients.OAuth2ClientWriter.AUTO_GRANT_FIELD;
029import static org.nuxeo.ecm.platform.oauth2.clients.OAuth2ClientWriter.ENABLED_FIELD;
030import static org.nuxeo.ecm.platform.oauth2.clients.OAuth2ClientWriter.ID_FIELD;
031import static org.nuxeo.ecm.platform.oauth2.clients.OAuth2ClientWriter.SECRET_FIELD;
032
033import java.util.Collections;
034import java.util.List;
035
036import org.nuxeo.ecm.core.io.marshallers.json.EntityJsonReader;
037import org.nuxeo.ecm.core.io.registry.reflect.Setup;
038
039import com.fasterxml.jackson.databind.JsonNode;
040
041/**
042 * @since 11.1
043 */
044@Setup(mode = SINGLETON, priority = REFERENCE)
045public class OAuth2ClientReader extends EntityJsonReader<OAuth2Client> {
046
047    public OAuth2ClientReader() {
048        super(OAuth2ClientWriter.ENTITY_TYPE);
049    }
050
051    @Override
052    protected OAuth2Client readEntity(JsonNode jn) {
053        String name = getStringField(jn, NAME_FIELD);
054        List<String> redirectURIs = requireNonNullElseGet(getStringListField(jn, REDIRECT_URI_FIELD),
055                Collections::emptyList);
056        String clientId = getStringField(jn, ID_FIELD);
057        String secret = getStringField(jn, SECRET_FIELD);
058
059        boolean autoGrant = requireNonNullElse(getBooleanField(jn, AUTO_GRANT_FIELD), false);
060        boolean enabled = requireNonNullElse(getBooleanField(jn, ENABLED_FIELD), false);
061
062        return new OAuth2Client(name, clientId, secret, redirectURIs, autoGrant, enabled);
063    }
064}