/*
 * Project: e-Dec Example Code
 * (C) 2017 Bundesamt fuer Informatik und Telekommunikation, CH
 */
package ch.admin.bit.edec.examples.ws;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import java.io.*;
import java.net.URLConnection;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;
import java.util.Iterator;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * This class provides common code for handling a webservice request.
 */
public abstract class AbstractRequest {
  public static final String SEP = System.getProperty("line.separator");
  private static final Log log = LogFactory.getLog(AbstractRequest.class);

  /**
   * Creates the response text out of the respnse reader.
   *
   * @param reader The connection reader.
   * @return Response.
   * @throws IOException Thrown if reading fails.
   */
  static protected StringBuilder createResponse(BufferedReader reader) throws IOException {
    StringBuilder response = new StringBuilder();
    String line = null;
    while ((line = reader.readLine()) != null) {
      response.append(line); // includes also binary parts!
      response.append(SEP);
    }

    return response;
  }

  /**
   * Creates an error response from the error stream by appending the error cause to the received response text.
   * @param response Received response text.
   * @param is Error input stream.
   * @return Response with appended error reason.
   * @throws IOException Thrown if reading is not possible for some reason.
   */
  static protected StringBuilder createError(StringBuilder response, InputStream is) throws IOException {
    if (is != null) {
      InputStreamReader isr = new InputStreamReader(is);
      BufferedReader br = new BufferedReader(isr);

      String line = null;
      response.append(SEP + "Detailed message:" + SEP);
      while ((line = br.readLine()) != null) {
        response.append(line);
      }
    }

    return response;
  }

}
