001/* 002 * Copyright 2018 Anyware Services 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 */ 016package org.ametys.cms.data.type.impl; 017 018import org.ametys.core.model.type.AbstractLongElementType; 019import org.ametys.plugins.repository.data.UnknownDataException; 020import org.ametys.plugins.repository.data.repositorydata.ModifiableRepositoryData; 021import org.ametys.plugins.repository.data.repositorydata.RepositoryData; 022import org.ametys.plugins.repository.data.type.RepositoryElementType; 023import org.ametys.runtime.model.exception.BadItemTypeException; 024 025/** 026 * Class for long type of elements stored in the repository 027 */ 028public class LongRepositoryElementType extends AbstractLongElementType implements RepositoryElementType<Long> 029{ 030 031 public Object read(RepositoryData parentData, String name) throws BadItemTypeException 032 { 033 if (!parentData.hasValue(name)) 034 { 035 return null; 036 } 037 038 if (!isCompatible(parentData, name)) 039 { 040 throw new BadItemTypeException("Try to get long value from the non long data '" + name + "' on '" + parentData + "'"); 041 } 042 043 if (parentData.isMultiple(name)) 044 { 045 return parentData.getLongs(name); 046 } 047 048 return parentData.getLong(name); 049 } 050 051 public void write(ModifiableRepositoryData parentData, String name, Object value) throws BadItemTypeException 052 { 053 if (value == null) 054 { 055 if (parentData.hasValue(name)) 056 { 057 parentData.removeValue(name); 058 } 059 } 060 else if (value instanceof Number) 061 { 062 parentData.setValue(name, ((Number) value).longValue()); 063 } 064 else if (value instanceof Number[]) 065 { 066 Long[] valueAsLongArray = new Long[((Number[]) value).length]; 067 for (int i = 0; i < ((Number[]) value).length; i++) 068 { 069 valueAsLongArray[i] = ((Number[]) value)[i].longValue(); 070 } 071 parentData.setValues(name, valueAsLongArray); 072 } 073 else 074 { 075 throw new BadItemTypeException("Try to set the non long value '" + value + "' to the long data '" + name + "' on '" + parentData + "'"); 076 } 077 } 078 079 public boolean isCompatible(RepositoryData parentData, String name) throws UnknownDataException 080 { 081 return RepositoryData.LONG_REPOSITORY_DATA_TYPE.equals(parentData.getType(name)); 082 } 083}