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.core.model.type; 017 018import java.time.ZonedDateTime; 019import java.time.format.DateTimeFormatter; 020import java.time.format.DateTimeParseException; 021import java.util.ArrayList; 022import java.util.List; 023 024import org.apache.commons.lang3.StringUtils; 025 026import org.ametys.core.model.type.AbstractElementType; 027import org.ametys.runtime.model.exception.BadItemTypeException; 028 029/** 030 * Abstract class for date time element types 031 */ 032public abstract class AbstractDateTimeElementType extends AbstractElementType<ZonedDateTime> 033{ 034 public ZonedDateTime castValue(String value) throws BadItemTypeException 035 { 036 if (StringUtils.isEmpty(value)) 037 { 038 return null; 039 } 040 041 try 042 { 043 return ZonedDateTime.parse(value, DateTimeFormatter.ISO_OFFSET_DATE_TIME); 044 } 045 catch (DateTimeParseException e) 046 { 047 throw new BadItemTypeException("Unable to cast '" + value + "' to a date", e); 048 } 049 } 050 051 @Override 052 public String toString(ZonedDateTime value) 053 { 054 if (value == null) 055 { 056 return null; 057 } 058 return value.format(DateTimeFormatter.ISO_OFFSET_DATE_TIME); 059 } 060 061 @Override 062 protected Object _singleValueToJSON(ZonedDateTime value) 063 { 064 return toString(value); 065 } 066 067 public Object fromJSONForClient(Object json) 068 { 069 if (json == null) 070 { 071 return json; 072 } 073 else if (json instanceof String) 074 { 075 return castValue((String) json); 076 } 077 else if (json instanceof List) 078 { 079 @SuppressWarnings("unchecked") 080 List<String> jsonList = (List<String>) json; 081 List<ZonedDateTime> dateList = new ArrayList<>(); 082 for (String singleJSON : jsonList) 083 { 084 dateList.add(castValue(singleJSON)); 085 } 086 return dateList.toArray(new ZonedDateTime[dateList.size()]); 087 } 088 else 089 { 090 throw new IllegalArgumentException("Try to convert the non Date time JSON object '" + json + "' into a Date"); 091 } 092 } 093 094 public boolean isSimple() 095 { 096 return true; 097 } 098 099}