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.codehaus.jackson.JsonNode;
031import org.nuxeo.ecm.core.io.marshallers.json.EntityJsonReader;
032import org.nuxeo.ecm.core.io.registry.reflect.Setup;
033
034/**
035 * @since 9.2
036 */
037@Setup(mode = SINGLETON, priority = REFERENCE)
038public class NuxeoOAuth2TokenReader extends EntityJsonReader<NuxeoOAuth2Token> {
039
040    public NuxeoOAuth2TokenReader() {
041        super(NuxeoOAuth2TokenWriter.ENTITY_TYPE);
042    }
043
044    @Override
045    protected NuxeoOAuth2Token readEntity(JsonNode jn) throws IOException {
046        String cliendId = getStringField(jn, "clientId");
047        NuxeoOAuth2Token token = new NuxeoOAuth2Token(0, cliendId);
048        token.setServiceName(getStringField(jn, "serviceName"));
049        token.setNuxeoLogin(getStringField(jn, "nuxeoLogin"));
050        token.setServiceLogin(getStringField(jn, "serviceLogin"));
051        SimpleDateFormat dateFormat = new SimpleDateFormat(NuxeoOAuth2TokenWriter.DATE_FORMAT);
052        Calendar cal = Calendar.getInstance();
053        try {
054            cal.setTime(dateFormat.parse(getStringField(jn, "creationDate")));
055        } catch (ParseException e) {
056            cal = null;
057        }
058        token.setCreationDate(cal);
059        token.setIsShared(getBooleanField(jn, "isShared"));
060        List<String> sharedWith = getStringListField(jn, "sharedWith");
061        token.setSharedWith(sharedWith == null ? "" : String.join(",", sharedWith));
062        return token;
063    }
064
065}