/*
** Module   : HttpResponsePathRegex.java
** Abstract : A test for a path in the HTTP response body.
**
** Copyright (c) 2021, Golden Code Development Corporation.
**
** -#- -I- --Date-- ---------------------------------------Description----------------------------------------
** 001 CA  20210827 Created initial version.
*/

/*
** This program is free software: you can redistribute it and/or modify
** it under the terms of the GNU Affero General Public License as
** published by the Free Software Foundation, either version 3 of the
** License, or (at your option) any later version.
**
** This program is distributed in the hope that it will be useful,
** but WITHOUT ANY WARRANTY; without even the implied warranty of
** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
** GNU Affero General Public License for more details.
**
** You should have received a copy of the GNU Affero General Public License
** along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/

package com.goldencode.harness.test;

import java.util.regex.*;

import com.goldencode.harness.*;

/**
 * A test applied to the response body, when the body is traversable (i.e. a XML or JSON structure).
 * <p>
 * This test checks that the path's value matches exactly the specified pattern.
 */
public class HttpResponsePathRegex
extends HttpResponsePath
{
   /** The regex. */
   private String value;
   
   /** The compiled pattern. */
   private Pattern pattern;

   /**
    * Configure a new body path test, for regex match.
    * 
    * @param    path
    *           The path to check.
    * @param    value
    *           The regex.
    * @param    variable
    *           The variable to save the path's value.
    * @param    service
    *           The associated web service.
    */
   public HttpResponsePathRegex(String path, String value, String variable, WebService service)
   {
      super(path, variable, service);
      
      this.value = value;
      this.pattern = Pattern.compile(this.value);
   }

   /**
    * Test the {@link #path}.
    * 
    * @return   The path's value or <code>null</code> if the test failed (path does not exist or it does not 
    *           match).
    */
   @Override
   protected Object testPath()
   {
      Object theVal = service.checkPathValueRegex(path, pattern);
      if (theVal == null)
      {
         setStatus(Status.FAILED, String.format("Path '%s' does not match regex %s", path, value));
         
         return null;
      }
      
      return theVal;
   }
}
