001/*
002 * (C) Copyright 2006-2013 Nuxeo SA (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 *     vpasquier <vpasquier@nuxeo.com>
018 */
019package org.nuxeo.ecm.automation.core.operations.business.adapter;
020
021import org.apache.commons.logging.Log;
022import org.apache.commons.logging.LogFactory;
023import org.nuxeo.ecm.core.api.CoreSession;
024import org.nuxeo.ecm.core.api.DocumentModel;
025import org.nuxeo.ecm.core.api.impl.SimpleDocumentModel;
026
027import com.fasterxml.jackson.annotation.JsonIgnore;
028import com.fasterxml.jackson.annotation.JsonProperty;
029import com.fasterxml.jackson.annotation.JsonPropertyOrder;
030
031/**
032 * Nuxeo document model abstract adapter to extend for mapping
033 *
034 * @since 5.7
035 */
036@JsonPropertyOrder({ "type", "id" })
037public abstract class BusinessAdapter {
038
039    private static final Log log = LogFactory.getLog(BusinessAdapter.class);
040
041    @JsonProperty("id")
042    protected String id;
043
044    @JsonProperty("type")
045    protected String type;
046
047    protected transient DocumentModel doc;
048
049    /**
050     * Default constructor called by jackson
051     */
052    public BusinessAdapter() {
053        doc = SimpleDocumentModel.empty();
054    }
055
056    public BusinessAdapter(DocumentModel document) {
057        type = document.getType();
058        doc = document;
059        id = doc.getId();
060    }
061
062    public void save(CoreSession session) {
063        session.saveDocument(doc);
064    }
065
066    @JsonIgnore
067    public DocumentModel getDocument() {
068        return doc;
069    }
070
071    public String getId() {
072        try {
073            return doc.getId();
074        } catch (UnsupportedOperationException e) {
075            return id;
076        }
077    }
078
079    public String getType() {
080        return doc.getType() == null ? type : doc.getType();
081    }
082
083}