001/** 002 * 003 * Copyright 2020-2021 Florian Schmaus 004 * 005 * Licensed under the Apache License, Version 2.0 (the "License"); 006 * you may not use this file except in compliance with the License. 007 * You may obtain a copy of the License at 008 * 009 * http://www.apache.org/licenses/LICENSE-2.0 010 * 011 * Unless required by applicable law or agreed to in writing, software 012 * distributed under the License is distributed on an "AS IS" BASIS, 013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 014 * See the License for the specific language governing permissions and 015 * limitations under the License. 016 */ 017package org.jivesoftware.smackx.xdata; 018 019import java.util.ArrayList; 020import java.util.Collection; 021import java.util.Date; 022import java.util.List; 023 024import org.jivesoftware.smack.util.CollectionUtil; 025 026import org.jxmpp.util.XmppDateTime; 027 028public class AbstractMultiFormField extends FormField { 029 030 private final List<Value> values; 031 032 protected AbstractMultiFormField(Builder<?, ?> builder) { 033 super(builder); 034 values = CollectionUtil.cloneAndSeal(builder.values); 035 } 036 037 @Override 038 public final List<Value> getRawValues() { 039 return values; 040 } 041 042 public abstract static class Builder<F extends AbstractMultiFormField, B extends FormField.Builder<F, B>> 043 extends FormField.Builder<F, B> { 044 045 private List<Value> values; 046 047 protected Builder(AbstractMultiFormField formField) { 048 super(formField); 049 values = CollectionUtil.newListWith(formField.getRawValues()); 050 } 051 052 protected Builder(String fieldName, FormField.Type type) { 053 super(fieldName, type); 054 } 055 056 private void ensureValuesAreInitialized() { 057 if (values == null) { 058 values = new ArrayList<>(); 059 } 060 } 061 062 @Override 063 protected void resetInternal() { 064 values = null; 065 } 066 067 public abstract B addValue(CharSequence value); 068 069 public B addValueVerbatim(CharSequence value) { 070 return addValueVerbatim(new Value(value)); 071 } 072 073 public B addValueVerbatim(Value value) { 074 ensureValuesAreInitialized(); 075 076 values.add(value); 077 return getThis(); 078 } 079 080 public final B addValue(Date date) { 081 String dateString = XmppDateTime.formatXEP0082Date(date); 082 return addValueVerbatim(dateString); 083 } 084 085 public final B addValues(Collection<? extends CharSequence> values) { 086 ensureValuesAreInitialized(); 087 088 for (CharSequence value : values) { 089 addValueVerbatim(value); 090 } 091 092 return getThis(); 093 } 094 } 095}