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