PayloadFormDataImpl.java [src/csip] Revision: default  Date:
/*
 * $Id$
 *
 * This file is part of the Cloud Services Integration Platform (CSIP),
 * a Model-as-a-Service framework, API and application suite.
 *
 * 2012-2022, Olaf David and others, OMSLab, Colorado State University.
 *
 * OMSLab licenses this file to you under the MIT license.
 * See the LICENSE file in the project root for more information.
 */
package csip;

import csip.api.server.ServiceException;
import csip.api.server.PayloadFormData;
import csip.utils.Services.FormDataParameter;
import java.io.File;
import java.util.Collection;
import java.util.Collections;
import java.util.Map;

/**
 * PayloadFormData input
 *
 * @author od
 */
class PayloadFormDataImpl implements PayloadFormData {

  private final Map<String, FormDataParameter> formData;
  private final ModelDataService mds;


  PayloadFormDataImpl(Map<String, FormDataParameter> formData, ModelDataService mds) {
    this.formData = formData;
    this.mds = mds;
  }


  @Override
  public boolean hasKey(String key) {
    return formData != null && formData.containsKey(key);
  }


  @Override
  public boolean hasValue(String value) {
    return formData != null && formData.containsValue(value);
  }


  @Override
  public PayloadFormDataImpl require(String name) throws ServiceException {
    if (!hasKey(name))
      throw new ServiceException("Form data key not found :" + name);

    return this;
  }


  @Override
  public PayloadFormDataImpl requireValue(String name) throws ServiceException {
    if (!hasValue(name))
      throw new ServiceException("Form data value not found :" + name);

    return this;
  }


  @Override
  public File getFile(String key) throws ServiceException {
    if (hasKey(key)) {
      FormDataParameter p = formData.get(key);
      if (p.isFile()) {
        File f = new File(mds.getWorkspaceDir0(), p.getFilename());
        if (f.exists() && f.canRead())
          return f;

      }
    }
    throw new ServiceException("File not found or cannot access: " + key);
  }


  @Override
  public String getString(String key) throws ServiceException {
    if (formData != null && formData.containsKey(key)) {
      FormDataParameter p = formData.get(key);
      if (!p.isFile())
        return p.getValue();

    }
    throw new ServiceException("Form input not found: " + key);
  }


  @Override
  public Collection<String> getKeys() {
    return formData == null ? Collections.emptySet()
        : Collections.unmodifiableCollection(formData.keySet());
  }


  @Override
  public boolean hasFormData() {
    return formData != null;
  }

}