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 *     Benjamin JALON <bjalon@nuxeo.com>
018 */
019package org.nuxeo.ecm.automation.core.operations.document;
020
021import org.nuxeo.ecm.automation.OperationException;
022import org.nuxeo.ecm.core.schema.types.ListType;
023import org.nuxeo.ecm.core.schema.types.Type;
024
025/**
026 * Abstract Class that exposes some useful method to manage list of values
027 *
028 * @author <a href="mailto:bjalon@nuxeo.com">Benjamin JALON</a>
029 * @since 5.7
030 */
031public class AbstractOperationMultiValuedProperty {
032
033    /**
034     * Check if the given field type store a list of values and if the given value is compatible with the given type. We
035     * assume the Type store a list of scalar values, not complex types.
036     */
037    protected void checkFieldType(Type type, Object value) throws OperationException {
038        if (!type.isListType()) {
039            throw new OperationException("Only multivalued String Types can be set using this operation");
040        }
041
042        ListType listType = (ListType) type;
043        Type itemType = listType.getFieldType();
044        if (itemType.isComplexType()) {
045            throw new UnsupportedOperationException("Manage only lists of scalar items");
046        }
047
048        if (!itemType.newInstance().getClass().equals(value.getClass())) {
049            throw new UnsupportedOperationException(String.format("Given type \"%s\" value is not a %s type", value,
050                    itemType.getName()));
051        }
052    }
053}