SingleValueFormField.java

  1. /**
  2.  *
  3.  * Copyright 2020-2021 Florian Schmaus.
  4.  *
  5.  * Licensed under the Apache License, Version 2.0 (the "License");
  6.  * you may not use this file except in compliance with the License.
  7.  * You may obtain a copy of the License at
  8.  *
  9.  *     http://www.apache.org/licenses/LICENSE-2.0
  10.  *
  11.  * Unless required by applicable law or agreed to in writing, software
  12.  * distributed under the License is distributed on an "AS IS" BASIS,
  13.  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14.  * See the License for the specific language governing permissions and
  15.  * limitations under the License.
  16.  */
  17. package org.jivesoftware.smackx.xdata;

  18. import java.util.Collections;
  19. import java.util.List;

  20. import org.jivesoftware.smack.util.CollectionUtil;

  21. public abstract class SingleValueFormField extends FormField {

  22.     private final Value rawValue;

  23.     protected SingleValueFormField(Builder<?, ?> builder) {
  24.         super(builder);
  25.         rawValue = builder.rawValue;
  26.     }

  27.     @Override
  28.     public final List<CharSequence> getValues() {
  29.         CharSequence value = getValue();
  30.         return CollectionUtil.emptyOrSingletonListFrom(value);
  31.     }

  32.     public abstract CharSequence getValue();

  33.     public final Value getRawValue() {
  34.         return rawValue;
  35.     }

  36.     @Override
  37.     public final List<Value> getRawValues() {
  38.         Value rawValue = getRawValue();
  39.         return CollectionUtil.emptyOrSingletonListFrom(rawValue);
  40.     }

  41.     @Override
  42.     protected void populateExtraXmlChildElements() {
  43.         if (rawValue == null) {
  44.             return;
  45.         }

  46.         extraXmlChildElements = Collections.singletonList(rawValue);
  47.     }

  48.     public abstract static class Builder<F extends SingleValueFormField, B extends Builder<F, B>>
  49.                     extends FormField.Builder<F, B> {

  50.         protected Builder(String fieldName, Type type) {
  51.             super(fieldName, type);
  52.         }

  53.         protected Builder(SingleValueFormField formField) {
  54.             super(formField);
  55.             rawValue = formField.getRawValue();
  56.         }

  57.         protected Value rawValue;

  58.         @Override
  59.         protected void resetInternal() {
  60.             rawValue = null;
  61.         };

  62.     }
  63. }