001/*
002 * (C) Copyright 2017 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 *     Gabriel Barata <gbarata@nuxeo.com>
018 */
019package org.nuxeo.ecm.platform.oauth2.tokens;
020
021import static org.nuxeo.ecm.core.io.registry.reflect.Instantiations.SINGLETON;
022import static org.nuxeo.ecm.core.io.registry.reflect.Priorities.REFERENCE;
023
024import java.io.IOException;
025import java.text.ParseException;
026import java.text.SimpleDateFormat;
027import java.util.Calendar;
028import java.util.List;
029
030import org.nuxeo.ecm.core.io.marshallers.json.EntityJsonReader;
031import org.nuxeo.ecm.core.io.registry.reflect.Setup;
032
033import com.fasterxml.jackson.databind.JsonNode;
034
035/**
036 * @since 9.2
037 */
038@Setup(mode = SINGLETON, priority = REFERENCE)
039public class NuxeoOAuth2TokenReader extends EntityJsonReader<NuxeoOAuth2Token> {
040
041    public NuxeoOAuth2TokenReader() {
042        super(NuxeoOAuth2TokenWriter.ENTITY_TYPE);
043    }
044
045    @Override
046    protected NuxeoOAuth2Token readEntity(JsonNode jn) throws IOException {
047        String cliendId = getStringField(jn, "clientId");
048        NuxeoOAuth2Token token = new NuxeoOAuth2Token(0, cliendId);
049        token.setServiceName(getStringField(jn, "serviceName"));
050        token.setNuxeoLogin(getStringField(jn, "nuxeoLogin"));
051        token.setServiceLogin(getStringField(jn, "serviceLogin"));
052        SimpleDateFormat dateFormat = new SimpleDateFormat(NuxeoOAuth2TokenWriter.DATE_FORMAT);
053        Calendar cal = Calendar.getInstance();
054        try {
055            cal.setTime(dateFormat.parse(getStringField(jn, "creationDate")));
056        } catch (ParseException e) {
057            cal = null;
058        }
059        token.setCreationDate(cal);
060        token.setIsShared(getBooleanField(jn, "isShared"));
061        List<String> sharedWith = getStringListField(jn, "sharedWith");
062        token.setSharedWith(sharedWith == null ? "" : String.join(",", sharedWith));
063        return token;
064    }
065
066}