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.SimpleDateFormat;
026import java.util.Calendar;
027
028import org.nuxeo.ecm.core.io.marshallers.json.ExtensibleEntityJsonWriter;
029import org.nuxeo.ecm.core.io.registry.reflect.Setup;
030
031import com.fasterxml.jackson.core.JsonGenerator;
032
033/**
034 * @since 9.2
035 */
036@Setup(mode = SINGLETON, priority = REFERENCE)
037public class NuxeoOAuth2TokenWriter extends ExtensibleEntityJsonWriter<NuxeoOAuth2Token> {
038
039    public static final String ENTITY_TYPE = "nuxeoOAuth2Token";
040
041    public static final String DATE_FORMAT = "yyyy-MM-dd HH:mm:ss";
042
043    public NuxeoOAuth2TokenWriter() {
044        super(ENTITY_TYPE, NuxeoOAuth2Token.class);
045    }
046
047    @Override
048    protected void writeEntityBody(NuxeoOAuth2Token token, JsonGenerator jg) throws IOException {
049        jg.writeStringField("serviceName", token.getServiceName());
050        jg.writeStringField("nuxeoLogin", token.getNuxeoLogin());
051        jg.writeStringField("serviceLogin", token.getServiceLogin());
052        jg.writeStringField("clientId", token.getClientId());
053        jg.writeBooleanField("isShared", token.isShared());
054        jg.writeArrayFieldStart("sharedWith");
055        String sharedWithStr = token.getSharedWith();
056        String[] sharedWith = sharedWithStr == null ? new String[0] : token.getSharedWith().split(",");
057        for (String user : sharedWith) {
058            jg.writeString(user.trim());
059        }
060        jg.writeEndArray();
061        SimpleDateFormat dateFormat = new SimpleDateFormat(DATE_FORMAT);
062        Calendar cal = token.getCreationDate();
063        jg.writeStringField("creationDate", dateFormat.format(cal == null ? null : cal.getTime()));
064    }
065}