PayloadAttachmentsImpl.java [src/csip] Revision:   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.PayloadAttachments;
import java.io.File;
import java.util.Arrays;
import java.util.Collection;
import java.util.Set;
import java.util.TreeSet;

/**
 * FormDataInput attachments
 *
 * @author od
 */
class PayloadAttachmentsImpl implements PayloadAttachments {

  private final String[] inputs;
  private final ModelDataService mds;


  PayloadAttachmentsImpl(String[] inputs, ModelDataService mds) {
    this.inputs = inputs;
    this.mds = mds;
  }


  @Override
  public Collection<File> getFiles() {
    Set<File> f = new TreeSet<>();
    for (String att : inputs) {
      File file = new File(mds.getWorkspaceDir0(), att);
      if (file.exists())
        f.add(file);

    }
    return f;
  }


  @Override
  public int getFilesCount() {
    return inputs.length;
  }


  @Override
  public boolean hasFile(String name) throws ServiceException {
    return getFile(name) != null;
  }


  @Override
  public PayloadAttachmentsImpl require(String name) throws ServiceException {
    if (!hasFile(name))
      throw new ServiceException("File attachment not found :" + name);

    return this;
  }


  @Override
  public File getFile(String name) throws ServiceException {
    if (!Arrays.asList(inputs).contains(name)) 
      return null;
    
    File f = new File(mds.getWorkspaceDir0(), name);
    if (f.exists())
      return f;

    throw new ServiceException("Missing Input File: " + name);
  }
}