All Downloads are FREE. Search and download functionalities are using the official Maven repository.

au.com.dius.pact.model.HttpPart.groovy Maven / Gradle / Ivy

package au.com.dius.pact.model

/**
 * Base trait for an object that represents part of an http message
 */
trait HttpPart {

  private static String CONTENT_TYPE = 'Content-Type'

  abstract OptionalBody getBody()
  abstract Map getHeaders()
  abstract void setHeaders(Map headers)
  abstract Map> getMatchingRules()

  String mimeType() {
    def contentTypeKey = headers?.keySet()?.find { CONTENT_TYPE.equalsIgnoreCase(it) }
    if (contentTypeKey) {
      headers[contentTypeKey].split('\\s*;\\s*').first()
    } else {
      detectContentType()
    }
  }

  boolean jsonBody() {
    mimeType().matches('application\\/.*json')
  }

  static XMLREGEXP = /^\s*<\?xml\s*version.*/
  static HTMLREGEXP = /^\s*().*/
  static JSONREGEXP = /^\s*("(\.|[^"\\u000A\u000D])*?"|[,:{}\[\]0-9.\-+Eaeflnr-u \u000A\u000D\u0009])+/
  static XMLREGEXP2 = /^\s*<\w+\s*(:\w+=[\"”][^\"”]+[\"”])?.*/

  String detectContentType() {
    if (body.present) {
      def s = body.value.substring(0, Math.min(body.value.size(), 32)).replaceAll('\n', '')
      if (s ==~ XMLREGEXP) {
        "application/xml"
      } else if (s.toUpperCase() ==~ HTMLREGEXP) {
        "text/html"
      } else if (s ==~ JSONREGEXP) {
        "application/json"
      } else if (s ==~ XMLREGEXP2) {
        "application/xml"
      } else {
        "text/plain"
      }
    } else {
      'text/plain'
    }
  }

  void setDefaultMimeType(String mimetype) {
    if (headers == null) {
      headers = [:]
    }
    if (!headers.containsKey(CONTENT_TYPE)) {
      headers[CONTENT_TYPE] = mimetype
    }
  }
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy