Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
  package org.apache.solr.util;
  /*
   * Licensed to the Apache Software Foundation (ASF) under one or more
   * contributor license agreements.  See the NOTICE file distributed with
   * this work for additional information regarding copyright ownership.
   * The ASF licenses this file to You under the Apache License, Version 2.0
   * (the "License"); you may not use this file except in compliance with
   * the License.  You may obtain a copy of the License at
   *
  *     http://www.apache.org/licenses/LICENSE-2.0
  *
  * Unless required by applicable law or agreed to in writing, software
  * distributed under the License is distributed on an "AS IS" BASIS,
  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  * See the License for the specific language governing permissions and
  * limitations under the License.
  */
 
 import java.util.Map;
 
 
 
 
 abstract public class RestTestBase extends SolrJettyTestBase {
   private static final Logger log = LoggerFactory.getLogger(RestTestBase.class);
   protected static RestTestHarness restTestHarness;
 
   public static void cleanUpHarness() {
      = null;
   }
 
   public static void createJettyAndHarness
       (String solrHomeString configFileString schemaFileString context,
        boolean stopAtShutdownSortedMap<ServletHolder,StringextraServletsthrows Exception {
 
     createJetty(solrHomeconfigFileschemaFilecontextstopAtShutdownextraServlets);
 
       @Override
       public String getBaseURL() {
         return .getBaseUrl().toString();
       }
     });
   }

  
Validates an update XML String is successful
 
   public static void assertU(String update) {
     assertU(nullupdate);
   }

  
Validates an update XML String is successful
 
   public static void assertU(String messageString update) {
     checkUpdateU(messageupdatetrue);
   }

  
Validates an update XML String failed
 
   public static void assertFailedU(String update) {
     assertFailedU(nullupdate);
   }

  
Validates an update XML String failed
 
   public static void assertFailedU(String messageString update) {
     checkUpdateU(messageupdatefalse);
   }

  
Checks the success or failure of an update message
 
   private static void checkUpdateU(String messageString updateboolean shouldSucceed) {
     try {
       String m = (null == message) ? "" : message + " ";
       if (shouldSucceed) {
         String response = .validateUpdate(update);
         if (response != nullfail(m + "update was not successful: " + response);
       } else {
         String response = .validateErrorUpdate(update);
         if (response != nullfail(m + "update succeeded, but should have failed: " + response);
       }
     } catch (SAXException e) {
       throw new RuntimeException("Invalid XML"e);
     }
  }

  
Validates a query matches some XPath test expressions

Parameters:
request a URL path with optional query params, e.g. "/schema/fields?fl=id,_version_"
  public static void assertQ(String requestString... tests) {
    try {
      int queryStartPos = request.indexOf('?');
      String query;
      String path;
      if (-1 == queryStartPos) {
        query = "";
        path = request;
      } else {
        query = request.substring(queryStartPos + 1);
        path = request.substring(0, queryStartPos);
      }
      if ( ! query.matches(".*wt=schema\\.xml.*")) { // don't overwrite wt=schema.xml
        query = setParam(query"wt""xml");
      }
      request = path + '?' + setParam(query"indent""on");
      String response = .query(request);
      // TODO: should the facet handling below be converted to parse the URL?
      /*
      if (req.getParams().getBool("facet", false)) {
        // add a test to ensure that faceting did not throw an exception
        // internally, where it would be added to facet_counts/exception
        String[] allTests = new String[tests.length+1];
        System.arraycopy(tests,0,allTests,1,tests.length);
        allTests[0] = "*[count(//lst[@name='facet_counts']/*[@name='exception'])=0]";
        tests = allTests;
      }
      */
      String results = TestHarness.validateXPath(responsetests);
      if (null != results) {
        String msg = "REQUEST FAILED: xpath=" + results
            + "\n\txml response was: " + response
            + "\n\trequest was:" + request;
        .error(msg);
        throw new RuntimeException(msg);
      }
    } catch (XPathExpressionException e1) {
      throw new RuntimeException("XPath is invalid"e1);
    } catch (Exception e2) {
      SolrException.log("REQUEST FAILED: " + requeste2);
      throw new RuntimeException("Exception during query"e2);
    }
  }

  
Makes a query request and returns the JSON string response

Parameters:
request a URL path with optional query params, e.g. "/schema/fields?fl=id,_version_"
  public static String JQ(String requestthrows Exception {
    int queryStartPos = request.indexOf('?');
    String query;
    String path;
    if (-1 == queryStartPos) {
      query = "";
      path = request;
    } else {
      query = request.substring(queryStartPos + 1);
      path = request.substring(0, queryStartPos);
    }
    query = setParam(query"wt""json");
    request = path + '?' + setParam(query"indent""on"); 
    String response;
    boolean failed=true;
    try {
      response = .query(request);
      failed = false;
    } finally {
      if (failed) {
        .error("REQUEST FAILED: " + request);
      }
    }
    return response;
  }

  
Validates a query matches some JSON test expressions using the default double delta tolerance.

  public static void assertJQ(String requestString... teststhrows Exception {
    assertJQ(request.tests);
  }

  
Validates a query matches some JSON test expressions and closes the query. The text expression is of the form path:JSON. To facilitate easy embedding in Java strings, the JSON can have double quotes replaced with single quotes.

Please use this with care: this makes it easy to match complete structures, but doing so can result in fragile tests if you are matching more than what you want to test.

Parameters:
request a URL path with optional query params, e.g. "/schema/fields?fl=id,_version_"
delta tolerance allowed in comparing float/double values
tests JSON path expression + '==' + expected value
  public static void assertJQ(String requestdouble deltaString... teststhrows Exception {
    int queryStartPos = request.indexOf('?');
    String query;
    String path;
    if (-1 == queryStartPos) {
      query = "";
      path = request;
    } else {
      query = request.substring(queryStartPos + 1);
      path = request.substring(0, queryStartPos);
    }
    query = setParam(query"wt""json");
    request = path + '?' + setParam(query"indent""on");
    String response;
    boolean failed = true;
    try {
      response = .query(request);
      failed = false;
    } finally {
      if (failed) {
        .error("REQUEST FAILED: " + request);
      }
    }
    for (String test : tests) {
      if (null == test || 0 == test.length()) continue;
      String testJSON = json(test);
      try {
        failed = true;
        String err = JSONTestUtil.match(responsetestJSONdelta);
        failed = false;
        if (err != null) {
          .error("query failed JSON validation. error=" + err +
              "\n expected =" + testJSON +
              "\n response = " + response +
              "\n request = " + request + "\n"
          );
          throw new RuntimeException(err);
        }
      } finally {
        if (failed) {
          .error("JSON query validation threw an exception." +
              "\n expected =" + testJSON +
              "\n response = " + response +
              "\n request = " + request + "\n"
          );
        }
      }
    }
  }

  
  
  
Validates the response from a PUT request matches some JSON test expressions

  public static void assertJPut(String requestString contentString... teststhrows Exception {
    assertJPut(requestcontent.tests);
  }


  
Validates the response from a PUT request matches some JSON test expressions and closes the query. The text expression is of the form path==JSON. To facilitate easy embedding in Java strings, the JSON can have double quotes replaced with single quotes.

Please use this with care: this makes it easy to match complete structures, but doing so can result in fragile tests if you are matching more than what you want to test.

Parameters:
request a URL path with optional query params, e.g. "/schema/fields?fl=id,_version_"
content The content to include with the PUT request
delta tolerance allowed in comparing float/double values
tests JSON path expression + '==' + expected value
  public static void assertJPut(String requestString contentdouble deltaString... teststhrows Exception {
    int queryStartPos = request.indexOf('?');
    String query;
    String path;
    if (-1 == queryStartPos) {
      query = "";
      path = request;
    } else {
      query = request.substring(queryStartPos + 1);
      path = request.substring(0, queryStartPos);
    }
    query = setParam(query"wt""json");
    request = path + '?' + setParam(query"indent""on");
    String response;
    boolean failed = true;
    try {
      response = .put(requestcontent);
      failed = false;
    } finally {
      if (failed) {
        .error("REQUEST FAILED: " + request);
      }
    }
    for (String test : tests) {
      if (null == test || 0 == test.length()) continue;
      String testJSON = json(test);
      try {
        failed = true;
        String err = JSONTestUtil.match(responsetestJSONdelta);
        failed = false;
        if (err != null) {
          .error("query failed JSON validation. error=" + err +
              "\n expected =" + testJSON +
              "\n response = " + response +
              "\n request = " + request + "\n"
          );
          throw new RuntimeException(err);
        }
      } finally {
        if (failed) {
          .error("JSON query validation threw an exception." +
              "\n expected =" + testJSON +
              "\n response = " + response +
              "\n request = " + request + "\n"
          );
        }
      }
    }
  }

  
Validates the response from a POST request matches some JSON test expressions

  public static void assertJPost(String requestString contentString... teststhrows Exception {
    assertJPost(requestcontent.tests);
  }


  
Validates the response from a PUT request matches some JSON test expressions and closes the query. The text expression is of the form path==JSON. To facilitate easy embedding in Java strings, the JSON can have double quotes replaced with single quotes.

Please use this with care: this makes it easy to match complete structures, but doing so can result in fragile tests if you are matching more than what you want to test.

Parameters:
request a URL path with optional query params, e.g. "/schema/fields?fl=id,_version_"
content The content to include with the PUT request
delta tolerance allowed in comparing float/double values
tests JSON path expression + '==' + expected value
  public static void assertJPost(String requestString contentdouble deltaString... teststhrows Exception {
    int queryStartPos = request.indexOf('?');
    String query;
    String path;
    if (-1 == queryStartPos) {
      query = "";
      path = request;
    } else {
      query = request.substring(queryStartPos + 1);
      path = request.substring(0, queryStartPos);
    }
    query = setParam(query"wt""json");
    request = path + '?' + setParam(query"indent""on");
    String response;
    boolean failed = true;
    try {
      response = .post(requestcontent);
      failed = false;
    } finally {
      if (failed) {
        .error("REQUEST FAILED: " + request);
      }
    }
    for (String test : tests) {
      if (null == test || 0 == test.length()) continue;
      String testJSON = json(test);
      try {
        failed = true;
        String err = JSONTestUtil.match(responsetestJSONdelta);
        failed = false;
        if (err != null) {
          .error("query failed JSON validation. error=" + err +
              "\n expected =" + testJSON +
              "\n response = " + response +
              "\n request = " + request + "\n"
          );
          throw new RuntimeException(err);
        }
      } finally {
        if (failed) {
          .error("JSON query validation threw an exception." +
              "\n expected =" + testJSON +
              "\n response = " + response +
              "\n request = " + request + "\n"
          );
        }
      }
    }
  }
  
  
Deletes a resource and then matches some JSON test expressions against the response using the default double delta tolerance.

  public static void assertJDelete(String requestString... teststhrows Exception {
    assertJDelete(request.tests);
  }

  
Deletes a resource and then matches some JSON test expressions against the response using the specified double delta tolerance.
  public static void assertJDelete(String requestdouble deltaString... teststhrows Exception {
    int queryStartPos = request.indexOf('?');
    String query;
    String path;
    if (-1 == queryStartPos) {
      query = "";
      path = request;
    } else {
      query = request.substring(queryStartPos + 1);
      path = request.substring(0, queryStartPos);
    }
    query = setParam(query"wt""json");
    request = path + '?' + setParam(query"indent""on");
    String response;
    boolean failed = true;
    try {
      response = .delete(request);
      failed = false;
    } finally {
      if (failed) {
        .error("REQUEST FAILED: " + request);
      }
    }
    for (String test : tests) {
      if (null == test || 0 == test.length()) continue;
      String testJSON = json(test);
      try {
        failed = true;
        String err = JSONTestUtil.match(responsetestJSONdelta);
        failed = false;
        if (err != null) {
          .error("query failed JSON validation. error=" + err +
              "\n expected =" + testJSON +
              "\n response = " + response +
              "\n request = " + request + "\n"
          );
          throw new RuntimeException(err);
        }
      } finally {
        if (failed) {
          .error("JSON query validation threw an exception." +
              "\n expected =" + testJSON +
              "\n response = " + response +
              "\n request = " + request + "\n"
          );
        }
      }
    }
  }

  
Insures that the given param is included in the query with the given value.
  1. If the param is already included with the given value, the request is returned unchanged.
  2. If the param is not already included, it is added with the given value.
  3. If the param is already included, but with a different value, the value is replaced with the given value.
  4. If the param is already included multiple times, they are replaced with a single param with given value.
The passed-in valueToSet should NOT be URL encoded, as it will be URL encoded by this method.

Parameters:
query The query portion of a request URL, e.g. "wt=json&indent=on&fl=id,_version_"
paramToSet The parameter name to insure the presence of in the returned request
valueToSet The parameter value to insure in the returned request
Returns:
The query with the given param set to the given value
  private static String setParam(String queryString paramToSetString valueToSet) {
    if (null == valueToSet) {
      valueToSet = "";
    }
    try {
      StringBuilder builder = new StringBuilder();
      if (null == query || query.trim().isEmpty()) {
        // empty query -> return "paramToSet=valueToSet"
        builder.append(paramToSet);
        builder.append('=');
        StrUtils.partialURLEncodeVal(buildervalueToSet);
        return builder.toString();
      }
      MultiMapSolrParams requestParams = SolrRequestParsers.parseQueryString(query);
      String[] values = requestParams.getParams(paramToSet);
      if (null == values) {
        // paramToSet isn't present in the request -> append "&paramToSet=valueToSet"
        builder.append(query);
        builder.append('&');
        builder.append(paramToSet);
        builder.append('=');
        StrUtils.partialURLEncodeVal(buildervalueToSet);
        return builder.toString();
      }
      if (1 == values.length && valueToSet.equals(values[0])) {
        // paramToSet=valueToSet is already in the query - just return the query as-is.
        return query;
      }
      // More than one value for paramToSet on the request, or paramToSet's value is not valueToSet
      // -> rebuild the query
      boolean isFirst = true;
      for (Map.Entry<String,String[]> entry : requestParams.getMap().entrySet()) {
        String key = entry.getKey();
        String[] valarr = entry.getValue();
        if ( ! key.equals(paramToSet)) {
          for (String val : valarr) {
            builder.append(isFirst ? "" : '&');
            isFirst = false;
            builder.append(key);
            builder.append('=');
            StrUtils.partialURLEncodeVal(buildernull == val ? "" : val);
          }
        }
      }
      builder.append(isFirst ? "" : '&');
      builder.append(paramToSet);
      builder.append('=');
      StrUtils.partialURLEncodeVal(buildervalueToSet);
      return builder.toString();
    } catch (IOException e) {
      throw new RuntimeException(e);
    }
  }
}  
New to GrepCode? Check out our FAQ X