Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
  /*
   * 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.
  */
 
 package org.apache.solr.util;
 
 
 import java.io.File;
 import java.util.Map;


This class provides a simple harness that may be useful when writing testcases.

This class lives in the tests-framework source tree (and not in the test source tree), so that it will be included with even the most minimal solr distribution, in order to encourage plugin writers to create unit tests for their plugins.

 
 public class TestHarness extends BaseTestHarness {
   protected volatile CoreContainer container;
   public UpdateRequestHandler updater;
 
  
Creates a SolrConfig object for the specified coreName assuming it follows the basic conventions of being a relative path in the solrHome dir. (ie: ${solrHome}/${coreName}/conf/${confFile}
 
   public static SolrConfig createConfig(String solrHomeString coreNameString confFile) {
     // set some system properties for use by tests
     System.setProperty("solr.test.sys.prop1""propone");
     System.setProperty("solr.test.sys.prop2""proptwo");
     try {
       return new SolrConfig(solrHome + . + coreNameconfFilenull);
     } catch (Exception xany) {
       throw new RuntimeException(xany);
     }
   }
  
  
 
   public static SolrConfig createConfig(String solrHomeString confFile) {
     return createConfig(solrHome.confFile);
   }

  

Parameters:
coreName to initialize
dataDirectory path for index data, will not be cleaned up
solrConfig solronfig instance
schemaFile schema filename
 
      public TestHarnessString coreName,
                          String dataDirectory,
                          SolrConfig solrConfig,
                          String schemaFile) {
    thiscoreNamedataDirectorysolrConfig, IndexSchemaFactory.buildIndexSchema(schemaFilesolrConfig));
  }

   

Parameters:
dataDirectory path for index data, will not be cleaned up
solrConfig solronfig instance
schemaFile schema filename
      public TestHarnessString dataDirectory,
                          SolrConfig solrConfig,
                          String schemaFile) {
     thisdataDirectorysolrConfig, IndexSchemaFactory.buildIndexSchema(schemaFilesolrConfig));
   }
   

Parameters:
dataDirectory path for index data, will not be cleaned up
solrConfig solrconfig instance
indexSchema schema instance
  public TestHarnessString dataDirectory,
                      SolrConfig solrConfig,
                      IndexSchema indexSchema) {
      this(.dataDirectorysolrConfigindexSchema);
  }

  

Parameters:
coreName to initialize
dataDir path for index data, will not be cleaned up
solrConfig solrconfig resource name
indexSchema schema resource name
  public TestHarness(String coreNameString dataDirString solrConfigString indexSchema) {
    try {
      if (coreName == null)
        coreName = .;
      this. = coreName;
      SolrResourceLoader loader = new SolrResourceLoader(SolrResourceLoader.locateSolrHome());
      ConfigSolr config = getTestHarnessConfig(coreNamedataDirsolrConfigindexSchema);
       = new CoreContainer(loaderconfig);
      .load();
       = new UpdateRequestHandler();
      .initnull );
    } catch (Exception e) {
      throw new RuntimeException(e);
    }
  }
  public TestHarness(String coreNameString dataDirSolrConfig solrConfigIndexSchema indexSchema) {
    this(coreNamedataDirsolrConfig.getResourceName(), indexSchema.getResourceName());
  }

  
Create a TestHarness using a specific solr home directory and solr xml

Parameters:
solrHome the solr home directory
solrXml a File pointing to a solr.xml configuration
  public TestHarness(String solrHomeString solrXml) {
    this(new SolrResourceLoader(solrHome),
          ConfigSolr.fromInputStream(nullnew ByteArrayInputStream(solrXml.getBytes(.))));
  }

  
Create a TestHarness using a specific resource loader and config

Parameters:
loader the SolrResourceLoader to use
config the ConfigSolr to use
  public TestHarness(SolrResourceLoader loaderConfigSolr config) {
     = new CoreContainer(loaderconfig);
    .load();
     = new UpdateRequestHandler();
    .init(null);
  }
  private static ConfigSolr getTestHarnessConfig(String coreNameString dataDir,
                                                 String solrConfigString schema) {
    String solrxml = "<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\n"
        + "<solr persistent=\"false\">\n"
        + "  <logging enabled=\"true\"/>\n"
        + "  <cores adminPath=\"/admin/cores\" defaultCoreName=\""
        + "\""
        + " host=\"${host:}\" hostPort=\"${hostPort:}\" hostContext=\"${hostContext:}\""
        + " distribUpdateSoTimeout=\"30000\""
        + " zkClientTimeout=\"${zkClientTimeout:30000}\" distribUpdateConnTimeout=\"30000\""
        + ">\n"
        + "    <core name=\"" + coreName + "\" config=\"" + solrConfig
        + "\" schema=\"" + schema + "\" dataDir=\"" + dataDir
        + "\" transient=\"false\" loadOnStartup=\"true\""
        + " shard=\"${shard:shard1}\" collection=\"${collection:collection1}\" instanceDir=\"" + coreName + "/\" />\n"
        + "  </cores>\n" + "</solr>";
    return ConfigSolr.fromString(new SolrResourceLoader(dataDir), solrxml);
  }
  
    return ;
  }

  
Gets a core that does not have it's refcount incremented (i.e. there is no need to close when done). This is not MT safe in conjunction with reloads!
  public SolrCore getCore() {
    // get the core & decrease its refcount:
    // the container holds the core for the harness lifetime
    if (core != null)
      core.close();
    return core;
  }

  
Gets the core with it's reference count incremented. You must call core.close() when done!
  public SolrCore getCoreInc() {
    return .getCore();
  }
  public void reload() throws Exception {
  }

  
Processes an "update" (add, commit or optimize) and returns the response as a String.

Parameters:
xml The XML of the update
Returns:
The XML response to the update
  public String update(String xml) {
    SolrCore core = getCoreInc();
    DirectSolrConnection connection = new DirectSolrConnection(core);
    SolrRequestHandler handler = core.getRequestHandler("/update");
    // prefer the handler mapped to /update, but use our generic backup handler
    // if that lookup fails
    if (handler == null) {
      handler = ;
    }
    try {
      return connection.request(handlernullxml);
    } catch (SolrException e) {
      throw (SolrException)e;
    } catch (Exception e) {
      throw new SolrException(..e);
    } finally {
      core.close();
    }
  }
  
        
  
Validates a "query" response against an array of XPath test strings

Parameters:
req the Query to process
Returns:
null if all good, otherwise the first test that fails.
Throws:
java.lang.Exception any exception in the response.
java.io.IOException if there is a problem writing the XML
See also:
org.apache.solr.request.LocalSolrQueryRequest
  public String validateQuery(SolrQueryRequest reqString... tests)
    throws Exception {
                
    String res = query(req);
    return validateXPath(restests);
  }
            
  
Processes a "query" using a user constructed SolrQueryRequest

Parameters:
req the Query to process, will be closed.
Returns:
The XML response to the query
Throws:
java.lang.Exception any exception in the response.
java.io.IOException if there is a problem writing the XML
See also:
org.apache.solr.request.LocalSolrQueryRequest
  public String query(SolrQueryRequest reqthrows Exception {
    return query(req.getParams().get(.), req);
  }

  
Processes a "query" using a user constructed SolrQueryRequest, and closes the request at the end.

Parameters:
handler the name of the request handler to process the request
req the Query to process, will be closed.
Returns:
The XML response to the query
Throws:
java.lang.Exception any exception in the response.
java.io.IOException if there is a problem writing the XML
See also:
org.apache.solr.request.LocalSolrQueryRequest
  public String query(String handlerSolrQueryRequest reqthrows Exception {
    SolrCore core = getCoreInc();
    try {
      SolrQueryResponse rsp = new SolrQueryResponse();
      SolrRequestInfo.setRequestInfo(new SolrRequestInfo(reqrsp));
      core.execute(core.getRequestHandler(handler),req,rsp);
      if (rsp.getException() != null) {
        throw rsp.getException();
      }
      StringWriter sw = new StringWriter(32000);
      QueryResponseWriter responseWriter = core.getQueryResponseWriter(req);
      responseWriter.write(sw,req,rsp);
      req.close();
      return sw.toString();
    } finally {
      req.close();
      SolrRequestInfo.clearRequestInfo();
      core.close();
    }
  }

  
It is the users responsibility to close the request object when done with it. This method does not set/clear SolrRequestInfo
  public SolrQueryResponse queryAndResponse(String handlerSolrQueryRequest reqthrows Exception {
    SolrCore core = getCoreInc();
    try {
      SolrQueryResponse rsp = new SolrQueryResponse();
      core.execute(core.getRequestHandler(handler),req,rsp);
      if (rsp.getException() != null) {
        throw rsp.getException();
      }
      return rsp;
    } finally {
      core.close();
    }
  }

  
Shuts down and frees any resources
  public void close() {
    if ( != null) {
      for (SolrCore c : .getCores()) {
        if (c.getOpenCount() > 1)
          throw new RuntimeException("SolrCore.getOpenCount()=="+c.getOpenCount());
      }      
    }
    if ( != null) {
      .shutdown();
       = null;
    }
  }
                                               int start,
                                               int limit) {
    f.qtype = qtype;
    f.start = start;
    f.limit = limit;
    return f;
  }
    
  
0 and Even numbered args are keys, Odd numbered args are values.
                                               int startint limit,
                                               String... args) {
    LocalRequestFactory f = getRequestFactory(qtypestartlimit);
    for (int i = 0; i < args.lengthi+=2) {
      f.args.put(args[i], args[i+1]);
    }
    return f;
        
  }
    
                                               int startint limit,
                                               Map<String,Stringargs) {
    LocalRequestFactory f = getRequestFactory(qtypestartlimit);
    f.args.putAll(args);
    return f;
  }
    
  
A Factory that generates LocalSolrQueryRequest objects using a specified set of default options.
  public class LocalRequestFactory {
    public String qtype = null;
    public int start = 0;
    public int limit = 1000;
    public Map<String,Stringargs = new HashMap<String,String>();
    public LocalRequestFactory() {
    }
    
Creates a LocalSolrQueryRequest based on variable args; for historical reasons, this method has some peculiar behavior:
  • If there is a single arg, then it is treated as the "q" param, and the LocalSolrQueryRequest consists of that query string along with "qt", "start", and "rows" params (based on the qtype, start, and limit properties of this factory) along with any other default "args" set on this factory.
  • If there are multiple args, then there must be an even number of them, and each pair of args is used as a key=value param in the LocalSolrQueryRequest. NOTE: In this usage, the "qtype", "start", "limit", and "args" properties of this factory are ignored.
TODO: this isn't really safe in the presense of core reloads! Perhaps the best we could do is increment the core reference count and decrement it in the request close() method?
    public LocalSolrQueryRequest makeRequest(String ... q) {
      if (q.length==1) {
        return new LocalSolrQueryRequest(TestHarness.this.getCore(),
                                       q[0], );
      }
      if (q.length%2 != 0) { 
        throw new RuntimeException("The length of the string array (query arguments) needs to be even");
      }
      Map.Entry<StringString> [] entries = new NamedListEntry[q.length / 2];
      for (int i = 0; i < q.lengthi += 2) {
        entries[i/2] = new NamedListEntry<String>(q[i], q[i+1]);
      }
      return new LocalSolrQueryRequest(TestHarness.this.getCore(), new NamedList(entries));
    }
  }
New to GrepCode? Check out our FAQ X