001/*
002 * (C) Copyright 2006-2011 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 *     Florent Guillaume
018 */
019
020package org.nuxeo.ecm.core.storage.sql;
021
022import java.io.Serializable;
023import java.util.Arrays;
024
025/**
026 * A type of fragment corresponding to several rows with the same id.
027 */
028public class CollectionFragment extends Fragment {
029
030    private static final long serialVersionUID = 1L;
031
032    /**
033     * Constructs a {@link CollectionFragment} from a {@link Row}.
034     *
035     * @param row the row
036     * @param state the initial state for the fragment
037     * @param context the persistence context to which the fragment is tied, or {@code null}
038     */
039    public CollectionFragment(Row row, State state, PersistenceContext context) {
040        super(row, state, context);
041    }
042
043    /**
044     * Sets a collection value.
045     *
046     * @param value the value
047     */
048    public void set(Serializable[] value) {
049        // unless invalidated (in which case don't try to refetch the value just
050        // to compare state), don't mark modified or dirty if there is no change
051        if (getState() != State.INVALIDATED_MODIFIED) {
052            // not invalidated, so no need to call accessed()
053            if (Arrays.equals(row.values, value)) {
054                return;
055            }
056        }
057        row.values = value.clone();
058        markModified();
059    }
060
061    /**
062     * Gets the collection value.
063     *
064     * @return the value
065     */
066    public Serializable[] get() {
067        accessed();
068        return row.values.clone();
069    }
070
071    /**
072     * Checks if the array is dirty (values changed since last clear).
073     *
074     * @return {@code true} if the array changed
075     */
076    public boolean isDirty() {
077        return !Arrays.equals(row.values, oldvalues);
078    }
079
080    @Override
081    protected State refetch() {
082        row.values = context.mapper.readCollectionRowArray(row);
083        clearDirty();
084        return State.PRISTINE;
085    }
086
087    @Override
088    protected State refetchDeleted() {
089        row.values = context.model.getCollectionFragmentType(row.tableName).getEmptyArray();
090        clearDirty();
091        return State.PRISTINE;
092    }
093
094}