Apache Solr open-source search software
- find . -name \*java -type f | xargs perl -pi -e 's/(\r\n|\n|\r)/\n/g' \ && find . -name \*java -type f | xargs svn propset svn:eol-style native
Otis Gospodnetic5650a7bf92df
diff --git a/contrib/benchmark/src/java/org/apache/lucene/benchmark/byTask/Benchmark.java b/contrib/benchmark/src/java/org/apache/lucene/benchmark/byTask/Benchmark.javaindex 9c4e3c02140..5e4d8043a23 100644--- a/contrib/benchmark/src/java/org/apache/lucene/benchmark/byTask/Benchmark.java+++ b/contrib/benchmark/src/java/org/apache/lucene/benchmark/byTask/Benchmark.java@@ -1,134 +1,134 @@-package org.apache.lucene.benchmark.byTask;--/**- * 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.io.File;-import java.io.FileReader;-import java.io.Reader;--import org.apache.lucene.benchmark.byTask.utils.Algorithm;-import org.apache.lucene.benchmark.byTask.utils.Config;---/**- * Run the benchmark algorithm.- * <p>Usage: java Benchmark algorithm-file- * <ol>- * <li>Read algorithm.</li>- * <li> Run the algorithm.</li>- * </ol>- * Things to be added/fixed in "Benchmarking by tasks":- * <ol>- * <li>TODO - report into Excel and/or graphed view.</li>- * <li>TODO - perf comparison between Lucene releases over the years.</li>- * <li>TODO - perf report adequate to include in Lucene nightly build site? (so we can easily track performance changes.)</li>- * <li>TODO - add overall time control for repeated execution (vs. current by-count only).</li>- * <li>TODO - query maker that is based on index statistics.</li>- * </ol>- */-public class Benchmark {-- private PerfRunData runData;- private Algorithm algorithm;- private boolean executed;-- public Benchmark (Reader algReader) throws Exception {- // prepare run data- try {- runData = new PerfRunData(new Config(algReader));- } catch (Exception e) {- e.printStackTrace();- throw new Exception("Error: cannot init PerfRunData!",e);- }-- // parse algorithm- try {- algorithm = new Algorithm(runData);- } catch (Exception e) {- throw new Exception("Error: cannot understand algorithm!",e);- }- }-- public synchronized void execute() throws Exception {- if (executed) {- throw new IllegalStateException("Benchmark was already executed");- }- executed = true;- algorithm.execute();- }-- /**- * Run the benchmark algorithm.- * @param args benchmark config and algorithm files- */- public static void main(String[] args) {- // verify command line args- if (args.length < 1) {- System.err.println("Usage: java Benchmark <algorithm file>");- System.exit(1);- }-- // verify input files- File algFile = new File(args[0]);- if (!algFile.exists() || !algFile.isFile() || !algFile.canRead()) {- System.err.println("cannot find/read algorithm file: "+algFile.getAbsolutePath());- System.exit(1);- }-- System.out.println("Running algorithm from: "+algFile.getAbsolutePath());-- Benchmark benchmark = null;- try {- benchmark = new Benchmark(new FileReader(algFile));- } catch (Exception e) {- e.printStackTrace();- System.exit(1);- }-- System.out.println("------------> algorithm:");- System.out.println(benchmark.getAlgorithm().toString());-- // execute- try {- benchmark.execute();- } catch (Exception e) {- System.err.println("Error: cannot execute the algorithm! "+e.getMessage());- e.printStackTrace();- }-- System.out.println("####################");- System.out.println("### D O N E !!! ###");- System.out.println("####################");-- }-- /**- * @return Returns the algorithm.- */- public Algorithm getAlgorithm() {- return algorithm;- }-- /**- * @return Returns the runData.- */- public PerfRunData getRunData() {- return runData;- }--}+package org.apache.lucene.benchmark.byTask;++/**+ * 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.io.File;+import java.io.FileReader;+import java.io.Reader;++import org.apache.lucene.benchmark.byTask.utils.Algorithm;+import org.apache.lucene.benchmark.byTask.utils.Config;+++/**+ * Run the benchmark algorithm.+ * <p>Usage: java Benchmark algorithm-file+ * <ol>+ * <li>Read algorithm.</li>+ * <li> Run the algorithm.</li>+ * </ol>+ * Things to be added/fixed in "Benchmarking by tasks":+ * <ol>+ * <li>TODO - report into Excel and/or graphed view.</li>+ * <li>TODO - perf comparison between Lucene releases over the years.</li>+ * <li>TODO - perf report adequate to include in Lucene nightly build site? (so we can easily track performance changes.)</li>+ * <li>TODO - add overall time control for repeated execution (vs. current by-count only).</li>+ * <li>TODO - query maker that is based on index statistics.</li>+ * </ol>+ */+public class Benchmark {++ private PerfRunData runData;+ private Algorithm algorithm;+ private boolean executed;++ public Benchmark (Reader algReader) throws Exception {+ // prepare run data+ try {+ runData = new PerfRunData(new Config(algReader));+ } catch (Exception e) {+ e.printStackTrace();+ throw new Exception("Error: cannot init PerfRunData!",e);+ }++ // parse algorithm+ try {+ algorithm = new Algorithm(runData);+ } catch (Exception e) {+ throw new Exception("Error: cannot understand algorithm!",e);+ }+ }++ public synchronized void execute() throws Exception {+ if (executed) {+ throw new IllegalStateException("Benchmark was already executed");+ }+ executed = true;+ algorithm.execute();+ }++ /**+ * Run the benchmark algorithm.+ * @param args benchmark config and algorithm files+ */+ public static void main(String[] args) {+ // verify command line args+ if (args.length < 1) {+ System.err.println("Usage: java Benchmark <algorithm file>");+ System.exit(1);+ }++ // verify input files+ File algFile = new File(args[0]);+ if (!algFile.exists() || !algFile.isFile() || !algFile.canRead()) {+ System.err.println("cannot find/read algorithm file: "+algFile.getAbsolutePath());+ System.exit(1);+ }++ System.out.println("Running algorithm from: "+algFile.getAbsolutePath());++ Benchmark benchmark = null;+ try {+ benchmark = new Benchmark(new FileReader(algFile));+ } catch (Exception e) {+ e.printStackTrace();+ System.exit(1);+ }++ System.out.println("------------> algorithm:");+ System.out.println(benchmark.getAlgorithm().toString());++ // execute+ try {+ benchmark.execute();+ } catch (Exception e) {+ System.err.println("Error: cannot execute the algorithm! "+e.getMessage());+ e.printStackTrace();+ }++ System.out.println("####################");+ System.out.println("### D O N E !!! ###");+ System.out.println("####################");++ }++ /**+ * @return Returns the algorithm.+ */+ public Algorithm getAlgorithm() {+ return algorithm;+ }++ /**+ * @return Returns the runData.+ */+ public PerfRunData getRunData() {+ return runData;+ }++}diff --git a/contrib/benchmark/src/java/org/apache/lucene/benchmark/byTask/PerfRunData.java b/contrib/benchmark/src/java/org/apache/lucene/benchmark/byTask/PerfRunData.javaindex 8dc60298101..696a61514a3 100644--- a/contrib/benchmark/src/java/org/apache/lucene/benchmark/byTask/PerfRunData.java+++ b/contrib/benchmark/src/java/org/apache/lucene/benchmark/byTask/PerfRunData.java@@ -1,222 +1,222 @@-package org.apache.lucene.benchmark.byTask;--/**- * 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.io.File;+package org.apache.lucene.benchmark.byTask;++/**+ * 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.io.File;import java.util.HashMap;import java.util.Iterator;-import org.apache.lucene.analysis.Analyzer;-import org.apache.lucene.benchmark.byTask.feeds.DocMaker;-import org.apache.lucene.benchmark.byTask.feeds.HTMLParser;-import org.apache.lucene.benchmark.byTask.feeds.QueryMaker;-import org.apache.lucene.benchmark.byTask.stats.Points;+import org.apache.lucene.analysis.Analyzer;+import org.apache.lucene.benchmark.byTask.feeds.DocMaker;+import org.apache.lucene.benchmark.byTask.feeds.HTMLParser;+import org.apache.lucene.benchmark.byTask.feeds.QueryMaker;+import org.apache.lucene.benchmark.byTask.stats.Points;import org.apache.lucene.benchmark.byTask.tasks.ReadTask;import org.apache.lucene.benchmark.byTask.tasks.SearchTask;-import org.apache.lucene.index.IndexReader;-import org.apache.lucene.index.IndexWriter;-import org.apache.lucene.store.Directory;-import org.apache.lucene.store.FSDirectory;-import org.apache.lucene.store.RAMDirectory;-import org.apache.lucene.benchmark.byTask.utils.Config;-import org.apache.lucene.benchmark.byTask.utils.FileUtils;---/**- * Data maintained by a performance test run.- * <p>- * Data includes:- * <ul>- * <li>Configuration.- * <li>Directory, Writer, Reader.- * <li>Docmaker and a few instances of QueryMaker.- * <li>Analyzer.- * <li>Statistics data which updated during the run.- * </ul>- */-public class PerfRunData {-- private Points points;-- // objects used during performance test run- // directory, analyzer, docMaker - created at startup.- // reader, writer, searcher - maintained by basic tasks.- private Directory directory;- private Analyzer analyzer;- private DocMaker docMaker;- private HTMLParser htmlParser;+import org.apache.lucene.index.IndexReader;+import org.apache.lucene.index.IndexWriter;+import org.apache.lucene.store.Directory;+import org.apache.lucene.store.FSDirectory;+import org.apache.lucene.store.RAMDirectory;+import org.apache.lucene.benchmark.byTask.utils.Config;+import org.apache.lucene.benchmark.byTask.utils.FileUtils;+++/**+ * Data maintained by a performance test run.+ * <p>+ * Data includes:+ * <ul>+ * <li>Configuration.+ * <li>Directory, Writer, Reader.+ * <li>Docmaker and a few instances of QueryMaker.+ * <li>Analyzer.+ * <li>Statistics data which updated during the run.+ * </ul>+ */+public class PerfRunData {++ private Points points;++ // objects used during performance test run+ // directory, analyzer, docMaker - created at startup.+ // reader, writer, searcher - maintained by basic tasks.+ private Directory directory;+ private Analyzer analyzer;+ private DocMaker docMaker;+ private HTMLParser htmlParser;// we use separate (identical) instances for each "read" task type, so each can iterate the quries separately.private HashMap readTaskQueryMaker;private Class qmkrClass;-- private IndexReader indexReader;- private IndexWriter indexWriter;- private Config config;-- // constructor- public PerfRunData (Config config) throws Exception {- this.config = config;- // analyzer (default is standard analyzer)- analyzer = (Analyzer) Class.forName(config.get("analyzer",- "org.apache.lucene.analysis.standard.StandardAnalyzer")).newInstance();- // doc maker- docMaker = (DocMaker) Class.forName(config.get("doc.maker",- "org.apache.lucene.benchmark.byTask.feeds.SimpleDocMaker")).newInstance();- docMaker.setConfig(config);- // query makers++ private IndexReader indexReader;+ private IndexWriter indexWriter;+ private Config config;++ // constructor+ public PerfRunData (Config config) throws Exception {+ this.config = config;+ // analyzer (default is standard analyzer)+ analyzer = (Analyzer) Class.forName(config.get("analyzer",+ "org.apache.lucene.analysis.standard.StandardAnalyzer")).newInstance();+ // doc maker+ docMaker = (DocMaker) Class.forName(config.get("doc.maker",+ "org.apache.lucene.benchmark.byTask.feeds.SimpleDocMaker")).newInstance();+ docMaker.setConfig(config);+ // query makersreadTaskQueryMaker = new HashMap();- qmkrClass = Class.forName(config.get("query.maker","org.apache.lucene.benchmark.byTask.feeds.SimpleQueryMaker"));- // html parser, used for some doc makers- htmlParser = (HTMLParser) Class.forName(config.get("html.parser","org.apache.lucene.benchmark.byTask.feeds.DemoHTMLParser")).newInstance();+ qmkrClass = Class.forName(config.get("query.maker","org.apache.lucene.benchmark.byTask.feeds.SimpleQueryMaker"));+ // html parser, used for some doc makers+ htmlParser = (HTMLParser) Class.forName(config.get("html.parser","org.apache.lucene.benchmark.byTask.feeds.DemoHTMLParser")).newInstance();docMaker.setHTMLParser(htmlParser);- // index stuff- reinit(false);-- // statistic points- points = new Points(config);-- if (Boolean.valueOf(config.get("log.queries","false")).booleanValue()) {- System.out.println("------------> queries:");+ // index stuff+ reinit(false);++ // statistic points+ points = new Points(config);++ if (Boolean.valueOf(config.get("log.queries","false")).booleanValue()) {+ System.out.println("------------> queries:");System.out.println(getQueryMaker(new SearchTask(this)).printQueries());- }-- }-- // clean old stuff, reopen- public void reinit(boolean eraseIndex) throws Exception {-- // cleanup index- if (indexWriter!=null) {- indexWriter.close();- indexWriter = null;- }- if (indexReader!=null) {- indexReader.close();- indexReader = null;- }- if (directory!=null) {- directory.close();- }-- // directory (default is ram-dir).- if ("FSDirectory".equals(config.get("directory","RAMDirectory"))) {- File workDir = new File("work");- File indexDir = new File(workDir,"index");- if (eraseIndex && indexDir.exists()) {- FileUtils.fullyDelete(indexDir);- }- indexDir.mkdirs();+ }++ }++ // clean old stuff, reopen+ public void reinit(boolean eraseIndex) throws Exception {++ // cleanup index+ if (indexWriter!=null) {+ indexWriter.close();+ indexWriter = null;+ }+ if (indexReader!=null) {+ indexReader.close();+ indexReader = null;+ }+ if (directory!=null) {+ directory.close();+ }++ // directory (default is ram-dir).+ if ("FSDirectory".equals(config.get("directory","RAMDirectory"))) {+ File workDir = new File("work");+ File indexDir = new File(workDir,"index");+ if (eraseIndex && indexDir.exists()) {+ FileUtils.fullyDelete(indexDir);+ }+ indexDir.mkdirs();directory = FSDirectory.getDirectory(indexDir);- } else {- directory = new RAMDirectory();- }-- // inputs- resetInputs();-- // release unused stuff- System.runFinalization();- System.gc();- }-- /**- * @return Returns the points.- */- public Points getPoints() {- return points;- }-- /**- * @return Returns the directory.- */- public Directory getDirectory() {- return directory;- }-- /**- * @param directory The directory to set.- */- public void setDirectory(Directory directory) {- this.directory = directory;- }-- /**- * @return Returns the indexReader.- */- public IndexReader getIndexReader() {- return indexReader;- }-- /**- * @param indexReader The indexReader to set.- */- public void setIndexReader(IndexReader indexReader) {- this.indexReader = indexReader;- }-- /**- * @return Returns the indexWriter.- */- public IndexWriter getIndexWriter() {- return indexWriter;- }-- /**- * @param indexWriter The indexWriter to set.- */- public void setIndexWriter(IndexWriter indexWriter) {- this.indexWriter = indexWriter;- }-- /**- * @return Returns the anlyzer.- */- public Analyzer getAnalyzer() {- return analyzer;- }-- /**- * @return Returns the docMaker.- */- public DocMaker getDocMaker() {- return docMaker;- }-- /**- * @return Returns the config.- */- public Config getConfig() {- return config;- }-- public void resetInputs() {- docMaker.resetInputs();+ } else {+ directory = new RAMDirectory();+ }++ // inputs+ resetInputs();++ // release unused stuff+ System.runFinalization();+ System.gc();+ }++ /**+ * @return Returns the points.+ */+ public Points getPoints() {+ return points;+ }++ /**+ * @return Returns the directory.+ */+ public Directory getDirectory() {+ return directory;+ }++ /**+ * @param directory The directory to set.+ */+ public void setDirectory(Directory directory) {+ this.directory = directory;+ }++ /**+ * @return Returns the indexReader.+ */+ public IndexReader getIndexReader() {+ return indexReader;+ }++ /**+ * @param indexReader The indexReader to set.+ */+ public void setIndexReader(IndexReader indexReader) {+ this.indexReader = indexReader;+ }++ /**+ * @return Returns the indexWriter.+ */+ public IndexWriter getIndexWriter() {+ return indexWriter;+ }++ /**+ * @param indexWriter The indexWriter to set.+ */+ public void setIndexWriter(IndexWriter indexWriter) {+ this.indexWriter = indexWriter;+ }++ /**+ * @return Returns the anlyzer.+ */+ public Analyzer getAnalyzer() {+ return analyzer;+ }++ /**+ * @return Returns the docMaker.+ */+ public DocMaker getDocMaker() {+ return docMaker;+ }++ /**+ * @return Returns the config.+ */+ public Config getConfig() {+ return config;+ }++ public void resetInputs() {+ docMaker.resetInputs();Iterator it = readTaskQueryMaker.values().iterator();while (it.hasNext()) {((QueryMaker) it.next()).resetInputs();}- }-- /**+ }++ /*** @return Returns the queryMaker by read task type (class)- */+ */public QueryMaker getQueryMaker(ReadTask readTask) {// mapping the query maker by task class allows extending/adding new search/read tasks// without needing to modify this class.@@ -232,13 +232,13 @@ public class PerfRunData {readTaskQueryMaker.put(readTaskClass,qm);}return qm;- }-- /**- * @return Returns the htmlParser.- */- public HTMLParser getHtmlParser() {- return htmlParser;- }--}+ }++ /**+ * @return Returns the htmlParser.+ */+ public HTMLParser getHtmlParser() {+ return htmlParser;+ }++}diff --git a/contrib/benchmark/src/java/org/apache/lucene/benchmark/byTask/feeds/BasicDocMaker.java b/contrib/benchmark/src/java/org/apache/lucene/benchmark/byTask/feeds/BasicDocMaker.javaindex fccc4eb85c8..6e16f33b152 100644--- a/contrib/benchmark/src/java/org/apache/lucene/benchmark/byTask/feeds/BasicDocMaker.java+++ b/contrib/benchmark/src/java/org/apache/lucene/benchmark/byTask/feeds/BasicDocMaker.java@@ -1,309 +1,309 @@-package org.apache.lucene.benchmark.byTask.feeds;--/**- * 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 org.apache.lucene.benchmark.byTask.utils.Config;-import org.apache.lucene.benchmark.byTask.utils.Format;-import org.apache.lucene.document.DateTools;-import org.apache.lucene.document.Document;-import org.apache.lucene.document.Field;--import java.io.File;-import java.io.UnsupportedEncodingException;-import java.util.ArrayList;-import java.util.Iterator;---/**- * Create documents for the test.- * Maintains counters of chars etc. so that sub-classes just need to- * provide textual content, and the create-by-size is handled here.- *- * <p/>- * Config Params (default is in caps):- * doc.stored=true|FALSE<br/>- * doc.tokenized=TRUE|false<br/>- * doc.term.vector=true|FALSE<br/>- * doc.store.body.bytes=true|FALSE //Store the body contents raw UTF-8 bytes as a field<br/>- */-public abstract class BasicDocMaker implements DocMaker {-- private int numDocsCreated = 0;- private boolean storeBytes = false;- protected boolean forever;-- private static class LeftOver {- private DocData docdata;- private int cnt;- }-- // leftovers are thread local, because it is unsafe to share residues between threads- private ThreadLocal leftovr = new ThreadLocal();-- static final String BODY_FIELD = "body";- private long numBytes = 0;- private long numUniqueBytes = 0;-- protected Config config;-- protected Field.Store storeVal = Field.Store.NO;- protected Field.Index indexVal = Field.Index.TOKENIZED;- protected Field.TermVector termVecVal = Field.TermVector.NO;-- private synchronized int incrNumDocsCreated() {- return numDocsCreated++;- }-- /**- * Return the data of the next document.- * All current implementations can create docs forever.- * When the input data is exhausted, input files are iterated.- * This re-iteration can be avoided by setting doc.maker.forever to false (default is true).- * @return data of the next document.- * @exception if cannot create the next doc data- * @exception NoMoreDataException if data is exhausted (and 'forever' set to false).- */- protected abstract DocData getNextDocData() throws NoMoreDataException, Exception;-- /*- * (non-Javadoc)- * @see org.apache.lucene.benchmark.byTask.feeds.DocMaker#makeDocument()- */- public Document makeDocument () throws Exception {- resetLeftovers();- DocData docData = getNextDocData();- Document doc = createDocument(docData,0,-1);- return doc;- }-- // create a doc- // use only part of the body, modify it to keep the rest (or use all if size==0).- // reset the docdata properties so they are not added more than once.- private Document createDocument(DocData docData, int size, int cnt) throws UnsupportedEncodingException {- int docid = incrNumDocsCreated();- Document doc = new Document();- doc.add(new Field("docid", "doc"+docid, storeVal, indexVal, termVecVal));- if (docData.getName()!=null) {- String name = (cnt<0 ? docData.getName() : docData.getName()+"_"+cnt);- doc.add(new Field("docname", name, storeVal, indexVal, termVecVal));- }- if (docData.getDate()!=null) {- String dateStr = DateTools.dateToString(docData.getDate(), DateTools.Resolution.SECOND);- doc.add(new Field("docdate", dateStr, storeVal, indexVal, termVecVal));- }- if (docData.getTitle()!=null) {- doc.add(new Field("doctitle", docData.getTitle(), storeVal, indexVal, termVecVal));- }- if (docData.getBody()!=null && docData.getBody().length()>0) {- String bdy;- if (size<=0 || size>=docData.getBody().length()) {- bdy = docData.getBody(); // use all- docData.setBody(""); // nothing left- } else {- // attempt not to break words - if whitespace found within next 20 chars...- for (int n=size-1; n<size+20 && n<docData.getBody().length(); n++) {- if (Character.isWhitespace(docData.getBody().charAt(n))) {- size = n;- break;- }- }- bdy = docData.getBody().substring(0,size); // use part- docData.setBody(docData.getBody().substring(size)); // some left- }- doc.add(new Field(BODY_FIELD, bdy, storeVal, indexVal, termVecVal));- if (storeBytes == true) {- doc.add(new Field("bytes", bdy.getBytes("UTF-8"), Field.Store.YES));- }- }-- if (docData.getProps()!=null) {- for (Iterator it = docData.getProps().keySet().iterator(); it.hasNext(); ) {- String key = (String) it.next();- String val = (String) docData.getProps().get(key);- doc.add(new Field(key, val, storeVal, indexVal, termVecVal));- }- docData.setProps(null);- }- //System.out.println("============== Created doc "+numDocsCreated+" :\n"+doc+"\n==========");- return doc;- }-- /*- * (non-Javadoc)- * @see org.apache.lucene.benchmark.byTask.feeds.DocMaker#makeDocument(int)- */- public Document makeDocument(int size) throws Exception {- LeftOver lvr = (LeftOver) leftovr.get();- if (lvr==null || lvr.docdata==null || lvr.docdata.getBody()==null || lvr.docdata.getBody().length()==0) {- resetLeftovers();- }- DocData dd = (lvr==null ? getNextDocData() : lvr.docdata);- int cnt = (lvr==null ? 0 : lvr.cnt);- while (dd.getBody()==null || dd.getBody().length()<size) {- DocData dd2 = dd;- dd = getNextDocData();- cnt = 0;- dd.setBody(dd2.getBody() + dd.getBody());- }- Document doc = createDocument(dd,size,cnt);- if (dd.getBody()==null || dd.getBody().length()==0) {- resetLeftovers();- } else {- if (lvr == null) {- lvr = new LeftOver();- leftovr.set(lvr);- }- lvr.docdata = dd;- lvr.cnt = ++cnt;- }- return doc;- }-- private void resetLeftovers() {- leftovr.set(null);- }-- /* (non-Javadoc)- * @see DocMaker#setConfig(java.util.Properties)- */- public void setConfig(Config config) {- this.config = config;- boolean stored = config.get("doc.stored",false);- boolean tokenized = config.get("doc.tokenized",true);- boolean termVec = config.get("doc.term.vector",false);- storeVal = (stored ? Field.Store.YES : Field.Store.NO);- indexVal = (tokenized ? Field.Index.TOKENIZED : Field.Index.UN_TOKENIZED);- termVecVal = (termVec ? Field.TermVector.YES : Field.TermVector.NO);- storeBytes = config.get("doc.store.body.bytes", false);- forever = config.get("doc.maker.forever",true);- }-- /*- * (non-Javadoc)- * @see DocMaker#resetIinputs()- */- public synchronized void resetInputs() {- printDocStatistics();- numBytes = 0;- numDocsCreated = 0;- resetLeftovers();- }-- /*- * (non-Javadoc)- * @see org.apache.lucene.benchmark.byTask.feeds.DocMaker#numUniqueBytes()- */- public long numUniqueBytes() {- return numUniqueBytes;- }-- /*- * (non-Javadoc)- * @see DocMaker#getCount()- */- public synchronized int getCount() {- return numDocsCreated;- }-- /*- * (non-Javadoc)- * @see DocMaker#getByteCount()- */- public synchronized long getByteCount() {- return numBytes;- }-- protected void addUniqueBytes (long n) {- numUniqueBytes += n;- }-- protected synchronized void addBytes (long n) {- numBytes += n;- }-- /*- * (non-Javadoc)- * @see org.apache.lucene.benchmark.byTask.feeds.DocMaker#printDocStatistics()- */- private int lastPrintedNumUniqueTexts = 0;- private long lastPrintedNumUniqueBytes = 0;- private int printNum = 0;- private HTMLParser htmlParser;-- public void printDocStatistics() {- boolean print = false;- String col = " ";- StringBuffer sb = new StringBuffer();- String newline = System.getProperty("line.separator");- sb.append("------------> ").append(Format.simpleName(getClass())).append(" statistics (").append(printNum).append("): ").append(newline);- int nut = numUniqueTexts();- if (nut > lastPrintedNumUniqueTexts) {- print = true;- sb.append("total count of unique texts: ").append(Format.format(0,nut,col)).append(newline);- lastPrintedNumUniqueTexts = nut;- }- long nub = numUniqueBytes();- if (nub > lastPrintedNumUniqueBytes) {- print = true;- sb.append("total bytes of unique texts: ").append(Format.format(0,nub,col)).append(newline);- lastPrintedNumUniqueBytes = nub;- }- if (getCount()>0) {- print = true;- sb.append("num docs added since last inputs reset: ").append(Format.format(0,getCount(),col)).append(newline);- sb.append("total bytes added since last inputs reset: ").append(Format.format(0,getByteCount(),col)).append(newline);- }- if (print) {- System.out.println(sb.append(newline).toString());- printNum++;- }- }-- protected void collectFiles(File f, ArrayList inputFiles) {- //System.out.println("Collect: "+f.getAbsolutePath());- if (!f.canRead()) {- return;- }- if (f.isDirectory()) {- File files[] = f.listFiles();- for (int i = 0; i < files.length; i++) {- collectFiles(files[i],inputFiles);- }- return;- }- inputFiles.add(f);- addUniqueBytes(f.length());- }-- /* (non-Javadoc)- * @see org.apache.lucene.benchmark.byTask.feeds.DocMaker#setHTMLParser(org.apache.lucene.benchmark.byTask.feeds.HTMLParser)- */- public void setHTMLParser(HTMLParser htmlParser) {- this.htmlParser = htmlParser;- }-- /*- * (non-Javadoc)- * @see org.apache.lucene.benchmark.byTask.feeds.DocMaker#getHtmlParser()- */- public HTMLParser getHtmlParser() {- return htmlParser;- }---}+package org.apache.lucene.benchmark.byTask.feeds;++/**+ * 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 org.apache.lucene.benchmark.byTask.utils.Config;+import org.apache.lucene.benchmark.byTask.utils.Format;+import org.apache.lucene.document.DateTools;+import org.apache.lucene.document.Document;+import org.apache.lucene.document.Field;++import java.io.File;+import java.io.UnsupportedEncodingException;+import java.util.ArrayList;+import java.util.Iterator;+++/**+ * Create documents for the test.+ * Maintains counters of chars etc. so that sub-classes just need to+ * provide textual content, and the create-by-size is handled here.+ *+ * <p/>+ * Config Params (default is in caps):+ * doc.stored=true|FALSE<br/>+ * doc.tokenized=TRUE|false<br/>+ * doc.term.vector=true|FALSE<br/>+ * doc.store.body.bytes=true|FALSE //Store the body contents raw UTF-8 bytes as a field<br/>+ */+public abstract class BasicDocMaker implements DocMaker {++ private int numDocsCreated = 0;+ private boolean storeBytes = false;+ protected boolean forever;++ private static class LeftOver {+ private DocData docdata;+ private int cnt;+ }++ // leftovers are thread local, because it is unsafe to share residues between threads+ private ThreadLocal leftovr = new ThreadLocal();++ static final String BODY_FIELD = "body";+ private long numBytes = 0;+ private long numUniqueBytes = 0;++ protected Config config;++ protected Field.Store storeVal = Field.Store.NO;+ protected Field.Index indexVal = Field.Index.TOKENIZED;+ protected Field.TermVector termVecVal = Field.TermVector.NO;++ private synchronized int incrNumDocsCreated() {+ return numDocsCreated++;+ }++ /**+ * Return the data of the next document.+ * All current implementations can create docs forever.+ * When the input data is exhausted, input files are iterated.+ * This re-iteration can be avoided by setting doc.maker.forever to false (default is true).+ * @return data of the next document.+ * @exception if cannot create the next doc data+ * @exception NoMoreDataException if data is exhausted (and 'forever' set to false).+ */+ protected abstract DocData getNextDocData() throws NoMoreDataException, Exception;++ /*+ * (non-Javadoc)+ * @see org.apache.lucene.benchmark.byTask.feeds.DocMaker#makeDocument()+ */+ public Document makeDocument () throws Exception {+ resetLeftovers();+ DocData docData = getNextDocData();+ Document doc = createDocument(docData,0,-1);+ return doc;+ }++ // create a doc+ // use only part of the body, modify it to keep the rest (or use all if size==0).+ // reset the docdata properties so they are not added more than once.+ private Document createDocument(DocData docData, int size, int cnt) throws UnsupportedEncodingException {+ int docid = incrNumDocsCreated();+ Document doc = new Document();+ doc.add(new Field("docid", "doc"+docid, storeVal, indexVal, termVecVal));+ if (docData.getName()!=null) {+ String name = (cnt<0 ? docData.getName() : docData.getName()+"_"+cnt);+ doc.add(new Field("docname", name, storeVal, indexVal, termVecVal));+ }+ if (docData.getDate()!=null) {+ String dateStr = DateTools.dateToString(docData.getDate(), DateTools.Resolution.SECOND);+ doc.add(new Field("docdate", dateStr, storeVal, indexVal, termVecVal));+ }+ if (docData.getTitle()!=null) {+ doc.add(new Field("doctitle", docData.getTitle(), storeVal, indexVal, termVecVal));+ }+ if (docData.getBody()!=null && docData.getBody().length()>0) {+ String bdy;+ if (size<=0 || size>=docData.getBody().length()) {+ bdy = docData.getBody(); // use all+ docData.setBody(""); // nothing left+ } else {+ // attempt not to break words - if whitespace found within next 20 chars...+ for (int n=size-1; n<size+20 && n<docData.getBody().length(); n++) {+ if (Character.isWhitespace(docData.getBody().charAt(n))) {+ size = n;+ break;+ }+ }+ bdy = docData.getBody().substring(0,size); // use part+ docData.setBody(docData.getBody().substring(size)); // some left+ }+ doc.add(new Field(BODY_FIELD, bdy, storeVal, indexVal, termVecVal));+ if (storeBytes == true) {+ doc.add(new Field("bytes", bdy.getBytes("UTF-8"), Field.Store.YES));+ }+ }++ if (docData.getProps()!=null) {+ for (Iterator it = docData.getProps().keySet().iterator(); it.hasNext(); ) {+ String key = (String) it.next();+ String val = (String) docData.getProps().get(key);+ doc.add(new Field(key, val, storeVal, indexVal, termVecVal));+ }+ docData.setProps(null);+ }+ //System.out.println("============== Created doc "+numDocsCreated+" :\n"+doc+"\n==========");+ return doc;+ }++ /*+ * (non-Javadoc)+ * @see org.apache.lucene.benchmark.byTask.feeds.DocMaker#makeDocument(int)+ */+ public Document makeDocument(int size) throws Exception {+ LeftOver lvr = (LeftOver) leftovr.get();+ if (lvr==null || lvr.docdata==null || lvr.docdata.getBody()==null || lvr.docdata.getBody().length()==0) {+ resetLeftovers();+ }+ DocData dd = (lvr==null ? getNextDocData() : lvr.docdata);+ int cnt = (lvr==null ? 0 : lvr.cnt);+ while (dd.getBody()==null || dd.getBody().length()<size) {+ DocData dd2 = dd;+ dd = getNextDocData();+ cnt = 0;+ dd.setBody(dd2.getBody() + dd.getBody());+ }+ Document doc = createDocument(dd,size,cnt);+ if (dd.getBody()==null || dd.getBody().length()==0) {+ resetLeftovers();+ } else {+ if (lvr == null) {+ lvr = new LeftOver();+ leftovr.set(lvr);+ }+ lvr.docdata = dd;+ lvr.cnt = ++cnt;+ }+ return doc;+ }++ private void resetLeftovers() {+ leftovr.set(null);+ }++ /* (non-Javadoc)+ * @see DocMaker#setConfig(java.util.Properties)+ */+ public void setConfig(Config config) {+ this.config = config;+ boolean stored = config.get("doc.stored",false);+ boolean tokenized = config.get("doc.tokenized",true);+ boolean termVec = config.get("doc.term.vector",false);+ storeVal = (stored ? Field.Store.YES : Field.Store.NO);+ indexVal = (tokenized ? Field.Index.TOKENIZED : Field.Index.UN_TOKENIZED);+ termVecVal = (termVec ? Field.TermVector.YES : Field.TermVector.NO);+ storeBytes = config.get("doc.store.body.bytes", false);+ forever = config.get("doc.maker.forever",true);+ }++ /*+ * (non-Javadoc)+ * @see DocMaker#resetIinputs()+ */+ public synchronized void resetInputs() {+ printDocStatistics();+ numBytes = 0;+ numDocsCreated = 0;+ resetLeftovers();+ }++ /*+ * (non-Javadoc)+ * @see org.apache.lucene.benchmark.byTask.feeds.DocMaker#numUniqueBytes()+ */+ public long numUniqueBytes() {+ return numUniqueBytes;+ }++ /*+ * (non-Javadoc)+ * @see DocMaker#getCount()+ */+ public synchronized int getCount() {+ return numDocsCreated;+ }++ /*+ * (non-Javadoc)+ * @see DocMaker#getByteCount()+ */+ public synchronized long getByteCount() {+ return numBytes;+ }++ protected void addUniqueBytes (long n) {+ numUniqueBytes += n;+ }++ protected synchronized void addBytes (long n) {+ numBytes += n;+ }++ /*+ * (non-Javadoc)+ * @see org.apache.lucene.benchmark.byTask.feeds.DocMaker#printDocStatistics()+ */+ private int lastPrintedNumUniqueTexts = 0;+ private long lastPrintedNumUniqueBytes = 0;+ private int printNum = 0;+ private HTMLParser htmlParser;++ public void printDocStatistics() {+ boolean print = false;+ String col = " ";+ StringBuffer sb = new StringBuffer();+ String newline = System.getProperty("line.separator");+ sb.append("------------> ").append(Format.simpleName(getClass())).append(" statistics (").append(printNum).append("): ").append(newline);+ int nut = numUniqueTexts();+ if (nut > lastPrintedNumUniqueTexts) {+ print = true;+ sb.append("total count of unique texts: ").append(Format.format(0,nut,col)).append(newline);+ lastPrintedNumUniqueTexts = nut;+ }+ long nub = numUniqueBytes();+ if (nub > lastPrintedNumUniqueBytes) {+ print = true;+ sb.append("total bytes of unique texts: ").append(Format.format(0,nub,col)).append(newline);+ lastPrintedNumUniqueBytes = nub;+ }+ if (getCount()>0) {+ print = true;+ sb.append("num docs added since last inputs reset: ").append(Format.format(0,getCount(),col)).append(newline);+ sb.append("total bytes added since last inputs reset: ").append(Format.format(0,getByteCount(),col)).append(newline);+ }+ if (print) {+ System.out.println(sb.append(newline).toString());+ printNum++;+ }+ }++ protected void collectFiles(File f, ArrayList inputFiles) {+ //System.out.println("Collect: "+f.getAbsolutePath());+ if (!f.canRead()) {+ return;+ }+ if (f.isDirectory()) {+ File files[] = f.listFiles();+ for (int i = 0; i < files.length; i++) {+ collectFiles(files[i],inputFiles);+ }+ return;+ }+ inputFiles.add(f);+ addUniqueBytes(f.length());+ }++ /* (non-Javadoc)+ * @see org.apache.lucene.benchmark.byTask.feeds.DocMaker#setHTMLParser(org.apache.lucene.benchmark.byTask.feeds.HTMLParser)+ */+ public void setHTMLParser(HTMLParser htmlParser) {+ this.htmlParser = htmlParser;+ }++ /*+ * (non-Javadoc)+ * @see org.apache.lucene.benchmark.byTask.feeds.DocMaker#getHtmlParser()+ */+ public HTMLParser getHtmlParser() {+ return htmlParser;+ }+++}diff --git a/contrib/benchmark/src/java/org/apache/lucene/benchmark/byTask/feeds/DocMaker.java b/contrib/benchmark/src/java/org/apache/lucene/benchmark/byTask/feeds/DocMaker.javaindex b698d1efe6a..62589f550c5 100644--- a/contrib/benchmark/src/java/org/apache/lucene/benchmark/byTask/feeds/DocMaker.java+++ b/contrib/benchmark/src/java/org/apache/lucene/benchmark/byTask/feeds/DocMaker.java@@ -1,71 +1,71 @@-package org.apache.lucene.benchmark.byTask.feeds;--/**- * 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 org.apache.lucene.document.Document;-import org.apache.lucene.benchmark.byTask.utils.Config;---/**- * Create documents for the test.- * <br>Each call to makeDocument would create the next document.- * When input is exhausted, the DocMaker iterates over the input again,- * does provifing a source for unlimited number of documents,- * though not all of them are unique.- */-public interface DocMaker {-- /**- * Create the next document, of the given size by input bytes.- * If the implementation does not support control over size, an exception is thrown.- * @param size size of document, or 0 if there is no size requirement.- * @exception if cannot make the document, or if size>0 was specified but this feature is not supported.- */- public Document makeDocument (int size) throws Exception;-- /** Create the next document. */- public Document makeDocument () throws Exception;-- /** Set the properties */- public void setConfig (Config config);-- /** Reset inputs so that the test run would behave, input wise, as if it just started. */- public void resetInputs();-- /** Return how many real unique texts are available, 0 if not applicable. */- public int numUniqueTexts();-- /** Return total bytes of all available unique texts, 0 if not applicable */- public long numUniqueBytes();-- /** Return number of docs made since last reset. */- public int getCount();-- /** Return total byte size of docs made since last reset. */- public long getByteCount();-- /** Print some statistics on docs available/added/etc. */- public void printDocStatistics();-- /** Set the html parser to use, when appropriate */- public void setHTMLParser(HTMLParser htmlParser);-- /** Returns the htmlParser. */- public HTMLParser getHtmlParser();-+package org.apache.lucene.benchmark.byTask.feeds;++/**+ * 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 org.apache.lucene.document.Document;+import org.apache.lucene.benchmark.byTask.utils.Config;+++/**+ * Create documents for the test.+ * <br>Each call to makeDocument would create the next document.+ * When input is exhausted, the DocMaker iterates over the input again,+ * does provifing a source for unlimited number of documents,+ * though not all of them are unique.+ */+public interface DocMaker {++ /**+ * Create the next document, of the given size by input bytes.+ * If the implementation does not support control over size, an exception is thrown.+ * @param size size of document, or 0 if there is no size requirement.+ * @exception if cannot make the document, or if size>0 was specified but this feature is not supported.+ */+ public Document makeDocument (int size) throws Exception;++ /** Create the next document. */+ public Document makeDocument () throws Exception;++ /** Set the properties */+ public void setConfig (Config config);++ /** Reset inputs so that the test run would behave, input wise, as if it just started. */+ public void resetInputs();++ /** Return how many real unique texts are available, 0 if not applicable. */+ public int numUniqueTexts();++ /** Return total bytes of all available unique texts, 0 if not applicable */+ public long numUniqueBytes();++ /** Return number of docs made since last reset. */+ public int getCount();++ /** Return total byte size of docs made since last reset. */+ public long getByteCount();++ /** Print some statistics on docs available/added/etc. */+ public void printDocStatistics();++ /** Set the html parser to use, when appropriate */+ public void setHTMLParser(HTMLParser htmlParser);++ /** Returns the htmlParser. */+ public HTMLParser getHtmlParser();+}\ No newline at end of filediff --git a/contrib/benchmark/src/java/org/apache/lucene/benchmark/byTask/feeds/QueryMaker.java b/contrib/benchmark/src/java/org/apache/lucene/benchmark/byTask/feeds/QueryMaker.javaindex ed8d101a8ae..af6ec5bf6b6 100644--- a/contrib/benchmark/src/java/org/apache/lucene/benchmark/byTask/feeds/QueryMaker.java+++ b/contrib/benchmark/src/java/org/apache/lucene/benchmark/byTask/feeds/QueryMaker.java@@ -1,49 +1,49 @@-package org.apache.lucene.benchmark.byTask.feeds;--/**- * 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 org.apache.lucene.search.Query;-import org.apache.lucene.benchmark.byTask.utils.Config;---/**- * Create queries for the test.- */-public interface QueryMaker {-- /**- * Create the next query, of the given size.- * @param size the size of the query - number of terms, etc.- * @exception if cannot make the query, or if size>0 was specified but this feature is not supported.- */- public Query makeQuery (int size) throws Exception;-- /** Create the next query */- public Query makeQuery () throws Exception;-- /** Set the properties- * @throws Exception */- public void setConfig (Config config) throws Exception;-- /** Reset inputs so that the test run would behave, input wise, as if it just started. */- public void resetInputs();-- /** Print the queries */- public String printQueries();-}+package org.apache.lucene.benchmark.byTask.feeds;++/**+ * 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 org.apache.lucene.search.Query;+import org.apache.lucene.benchmark.byTask.utils.Config;+++/**+ * Create queries for the test.+ */+public interface QueryMaker {++ /**+ * Create the next query, of the given size.+ * @param size the size of the query - number of terms, etc.+ * @exception if cannot make the query, or if size>0 was specified but this feature is not supported.+ */+ public Query makeQuery (int size) throws Exception;++ /** Create the next query */+ public Query makeQuery () throws Exception;++ /** Set the properties+ * @throws Exception */+ public void setConfig (Config config) throws Exception;++ /** Reset inputs so that the test run would behave, input wise, as if it just started. */+ public void resetInputs();++ /** Print the queries */+ public String printQueries();+}diff --git a/contrib/benchmark/src/java/org/apache/lucene/benchmark/byTask/feeds/ReutersDocMaker.java b/contrib/benchmark/src/java/org/apache/lucene/benchmark/byTask/feeds/ReutersDocMaker.javaindex 3826de126f9..c665383b0dc 100644--- a/contrib/benchmark/src/java/org/apache/lucene/benchmark/byTask/feeds/ReutersDocMaker.java+++ b/contrib/benchmark/src/java/org/apache/lucene/benchmark/byTask/feeds/ReutersDocMaker.java@@ -1,121 +1,121 @@-package org.apache.lucene.benchmark.byTask.feeds;--/**- * 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 org.apache.lucene.benchmark.byTask.utils.Config;--import java.io.BufferedReader;-import java.io.File;-import java.io.FileReader;-import java.text.DateFormat;-import java.text.SimpleDateFormat;-import java.util.ArrayList;-import java.util.Date;-import java.util.Locale;---/**- * A DocMaker using the Reuters collection for its input.- *- * Config properties:- * docs.dir=<path to the docs dir| Default: reuters-out>-- *- */-public class ReutersDocMaker extends BasicDocMaker {-- private DateFormat dateFormat;- private File dataDir = null;- private ArrayList inputFiles = new ArrayList();- private int nextFile = 0;- private int iteration=0;-- /* (non-Javadoc)- * @see SimpleDocMaker#setConfig(java.util.Properties)- */- public void setConfig(Config config) {- super.setConfig(config);- String d = config.get("docs.dir","reuters-out");- dataDir = new File(new File("work"),d);--- collectFiles(dataDir,inputFiles);- if (inputFiles.size()==0) {- throw new RuntimeException("No txt files in dataDir: "+dataDir.getAbsolutePath());- }- // date format: 30-MAR-1987 14:22:36.87- dateFormat = new SimpleDateFormat("dd-MMM-yyyy kk:mm:ss.SSS",Locale.US);- dateFormat.setLenient(true);- }-- protected DocData getNextDocData() throws Exception {- File f = null;- String name = null;- synchronized (this) {- if (nextFile >= inputFiles.size()) {- // exhausted files, start a new round, unless forever set to false.- if (!forever) {- throw new NoMoreDataException();- }- nextFile = 0;- iteration++;- }- f = (File) inputFiles.get(nextFile++);- name = f.getCanonicalPath()+"_"+iteration;- }-- BufferedReader reader = new BufferedReader(new FileReader(f));- String line = null;- //First line is the date, 3rd is the title, rest is body- String dateStr = reader.readLine();- reader.readLine();//skip an empty line- String title = reader.readLine();- reader.readLine();//skip an empty line- StringBuffer bodyBuf = new StringBuffer(1024);- while ((line = reader.readLine()) != null) {- bodyBuf.append(line).append(' ');- }- reader.close();-- addBytes(f.length());--- Date date = dateFormat.parse(dateStr.trim());- return new DocData(name, bodyBuf.toString(), title, null, date);- }--- /*- * (non-Javadoc)- * @see DocMaker#resetIinputs()- */- public synchronized void resetInputs() {- super.resetInputs();- nextFile = 0;- iteration = 0;- }-- /*- * (non-Javadoc)- * @see DocMaker#numUniqueTexts()- */- public int numUniqueTexts() {- return inputFiles.size();- }--}+package org.apache.lucene.benchmark.byTask.feeds;++/**+ * 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 org.apache.lucene.benchmark.byTask.utils.Config;++import java.io.BufferedReader;+import java.io.File;+import java.io.FileReader;+import java.text.DateFormat;+import java.text.SimpleDateFormat;+import java.util.ArrayList;+import java.util.Date;+import java.util.Locale;+++/**+ * A DocMaker using the Reuters collection for its input.+ *+ * Config properties:+ * docs.dir=<path to the docs dir| Default: reuters-out>++ *+ */+public class ReutersDocMaker extends BasicDocMaker {++ private DateFormat dateFormat;+ private File dataDir = null;+ private ArrayList inputFiles = new ArrayList();+ private int nextFile = 0;+ private int iteration=0;++ /* (non-Javadoc)+ * @see SimpleDocMaker#setConfig(java.util.Properties)+ */+ public void setConfig(Config config) {+ super.setConfig(config);+ String d = config.get("docs.dir","reuters-out");+ dataDir = new File(new File("work"),d);+++ collectFiles(dataDir,inputFiles);+ if (inputFiles.size()==0) {+ throw new RuntimeException("No txt files in dataDir: "+dataDir.getAbsolutePath());+ }+ // date format: 30-MAR-1987 14:22:36.87+ dateFormat = new SimpleDateFormat("dd-MMM-yyyy kk:mm:ss.SSS",Locale.US);+ dateFormat.setLenient(true);+ }++ protected DocData getNextDocData() throws Exception {+ File f = null;+ String name = null;+ synchronized (this) {+ if (nextFile >= inputFiles.size()) {+ // exhausted files, start a new round, unless forever set to false.+ if (!forever) {+ throw new NoMoreDataException();+ }+ nextFile = 0;+ iteration++;+ }+ f = (File) inputFiles.get(nextFile++);+ name = f.getCanonicalPath()+"_"+iteration;+ }++ BufferedReader reader = new BufferedReader(new FileReader(f));+ String line = null;+ //First line is the date, 3rd is the title, rest is body+ String dateStr = reader.readLine();+ reader.readLine();//skip an empty line+ String title = reader.readLine();+ reader.readLine();//skip an empty line+ StringBuffer bodyBuf = new StringBuffer(1024);+ while ((line = reader.readLine()) != null) {+ bodyBuf.append(line).append(' ');+ }+ reader.close();++ addBytes(f.length());+++ Date date = dateFormat.parse(dateStr.trim());+ return new DocData(name, bodyBuf.toString(), title, null, date);+ }+++ /*+ * (non-Javadoc)+ * @see DocMaker#resetIinputs()+ */+ public synchronized void resetInputs() {+ super.resetInputs();+ nextFile = 0;+ iteration = 0;+ }++ /*+ * (non-Javadoc)+ * @see DocMaker#numUniqueTexts()+ */+ public int numUniqueTexts() {+ return inputFiles.size();+ }++}diff --git a/contrib/benchmark/src/java/org/apache/lucene/benchmark/byTask/feeds/ReutersQueryMaker.java b/contrib/benchmark/src/java/org/apache/lucene/benchmark/byTask/feeds/ReutersQueryMaker.javaindex 63e3afdeadf..5c2d940e5b2 100644--- a/contrib/benchmark/src/java/org/apache/lucene/benchmark/byTask/feeds/ReutersQueryMaker.java+++ b/contrib/benchmark/src/java/org/apache/lucene/benchmark/byTask/feeds/ReutersQueryMaker.java@@ -1,117 +1,117 @@-package org.apache.lucene.benchmark.byTask.feeds;--/**- * 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 org.apache.lucene.analysis.Analyzer;-import org.apache.lucene.index.Term;-import org.apache.lucene.queryParser.QueryParser;-import org.apache.lucene.search.Query;-import org.apache.lucene.search.WildcardQuery;-import org.apache.lucene.search.spans.SpanFirstQuery;-import org.apache.lucene.search.spans.SpanNearQuery;-import org.apache.lucene.search.spans.SpanQuery;-import org.apache.lucene.search.spans.SpanTermQuery;-+package org.apache.lucene.benchmark.byTask.feeds;++/**+ * 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 org.apache.lucene.analysis.Analyzer;+import org.apache.lucene.index.Term;+import org.apache.lucene.queryParser.QueryParser;+import org.apache.lucene.search.Query;+import org.apache.lucene.search.WildcardQuery;+import org.apache.lucene.search.spans.SpanFirstQuery;+import org.apache.lucene.search.spans.SpanNearQuery;+import org.apache.lucene.search.spans.SpanQuery;+import org.apache.lucene.search.spans.SpanTermQuery;+import java.util.ArrayList;import java.util.Arrays;import java.util.List;--/**- * A QueryMaker that makes queries devised manually (by Grant Ingersoll) for- * searching in the Reuters collection.- */++/**+ * A QueryMaker that makes queries devised manually (by Grant Ingersoll) for+ * searching in the Reuters collection.+ */public class ReutersQueryMaker extends AbstractQueryMaker implements QueryMaker {- private static String [] STANDARD_QUERIES = {- //Start with some short queries- "Salomon", "Comex", "night trading", "Japan Sony",- //Try some Phrase Queries- "\"Sony Japan\"", "\"food needs\"~3",- "\"World Bank\"^2 AND Nigeria", "\"World Bank\" -Nigeria",- "\"Ford Credit\"~5",- //Try some longer queries- "airline Europe Canada destination",- "Long term pressure by trade " +- "ministers is necessary if the current Uruguay round of talks on " +- "the General Agreement on Trade and Tariffs (GATT) is to " +- "succeed"- };-- private static Query[] getPrebuiltQueries(String field) {- // be wary of unanalyzed text- return new Query[] {- new SpanFirstQuery(new SpanTermQuery(new Term(field, "ford")), 5),- new SpanNearQuery(new SpanQuery[]{new SpanTermQuery(new Term(field, "night")), new SpanTermQuery(new Term(field, "trading"))}, 4, false),- new SpanNearQuery(new SpanQuery[]{new SpanFirstQuery(new SpanTermQuery(new Term(field, "ford")), 10), new SpanTermQuery(new Term(field, "credit"))}, 10, false),- new WildcardQuery(new Term(field, "fo*")),- };- }-- /**- * Parse the strings containing Lucene queries.- *- * @param qs array of strings containing query expressions- * @param a analyzer to use when parsing queries- * @return array of Lucene queries- */- private static Query[] createQueries(List qs, Analyzer a) {- QueryParser qp = new QueryParser("body", a);- List queries = new ArrayList();- for (int i = 0; i < qs.size(); i++) {- try {-- Object query = qs.get(i);- Query q = null;- if (query instanceof String) {- q = qp.parse((String) query);-- } else if (query instanceof Query) {- q = (Query) query;-- } else {- System.err.println("Unsupported Query Type: " + query);- }-- if (q != null) {- queries.add(q);- }-- } catch (Exception e) {- e.printStackTrace();- }- }-- return (Query[]) queries.toArray(new Query[0]);- }-+ private static String [] STANDARD_QUERIES = {+ //Start with some short queries+ "Salomon", "Comex", "night trading", "Japan Sony",+ //Try some Phrase Queries+ "\"Sony Japan\"", "\"food needs\"~3",+ "\"World Bank\"^2 AND Nigeria", "\"World Bank\" -Nigeria",+ "\"Ford Credit\"~5",+ //Try some longer queries+ "airline Europe Canada destination",+ "Long term pressure by trade " ++ "ministers is necessary if the current Uruguay round of talks on " ++ "the General Agreement on Trade and Tariffs (GATT) is to " ++ "succeed"+ };++ private static Query[] getPrebuiltQueries(String field) {+ // be wary of unanalyzed text+ return new Query[] {+ new SpanFirstQuery(new SpanTermQuery(new Term(field, "ford")), 5),+ new SpanNearQuery(new SpanQuery[]{new SpanTermQuery(new Term(field, "night")), new SpanTermQuery(new Term(field, "trading"))}, 4, false),+ new SpanNearQuery(new SpanQuery[]{new SpanFirstQuery(new SpanTermQuery(new Term(field, "ford")), 10), new SpanTermQuery(new Term(field, "credit"))}, 10, false),+ new WildcardQuery(new Term(field, "fo*")),+ };+ }++ /**+ * Parse the strings containing Lucene queries.+ *+ * @param qs array of strings containing query expressions+ * @param a analyzer to use when parsing queries+ * @return array of Lucene queries+ */+ private static Query[] createQueries(List qs, Analyzer a) {+ QueryParser qp = new QueryParser("body", a);+ List queries = new ArrayList();+ for (int i = 0; i < qs.size(); i++) {+ try {++ Object query = qs.get(i);+ Query q = null;+ if (query instanceof String) {+ q = qp.parse((String) query);++ } else if (query instanceof Query) {+ q = (Query) query;++ } else {+ System.err.println("Unsupported Query Type: " + query);+ }++ if (q != null) {+ queries.add(q);+ }++ } catch (Exception e) {+ e.printStackTrace();+ }+ }++ return (Query[]) queries.toArray(new Query[0]);+ }+protected Query[] prepareQueries() throws Exception {- // analyzer (default is standard analyzer)- Analyzer anlzr= (Analyzer) Class.forName(config.get("analyzer",- "org.apache.lucene.analysis.standard.StandardAnalyzer")).newInstance();-- List queryList = new ArrayList(20);- queryList.addAll(Arrays.asList(STANDARD_QUERIES));- queryList.addAll(Arrays.asList(getPrebuiltQueries("body")));+ // analyzer (default is standard analyzer)+ Analyzer anlzr= (Analyzer) Class.forName(config.get("analyzer",+ "org.apache.lucene.analysis.standard.StandardAnalyzer")).newInstance();++ List queryList = new ArrayList(20);+ queryList.addAll(Arrays.asList(STANDARD_QUERIES));+ queryList.addAll(Arrays.asList(getPrebuiltQueries("body")));return createQueries(queryList, anlzr);- }+ }++---}+}diff --git a/contrib/benchmark/src/java/org/apache/lucene/benchmark/byTask/feeds/SimpleDocMaker.java b/contrib/benchmark/src/java/org/apache/lucene/benchmark/byTask/feeds/SimpleDocMaker.javaindex f3ef936293c..0891491d6a1 100644--- a/contrib/benchmark/src/java/org/apache/lucene/benchmark/byTask/feeds/SimpleDocMaker.java+++ b/contrib/benchmark/src/java/org/apache/lucene/benchmark/byTask/feeds/SimpleDocMaker.java@@ -1,69 +1,69 @@-package org.apache.lucene.benchmark.byTask.feeds;--/**- * 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.- */--/**- * Create documents for the test.- */-public class SimpleDocMaker extends BasicDocMaker {-- private int docID = 0;-- static final String DOC_TEXT = // from a public first aid info at http://firstaid.ie.eu.org- "Well it may be a little dramatic but sometimes it true. " +- "If you call the emergency medical services to an incident, " +- "your actions have started the chain of survival. " +- "You have acted to help someone you may not even know. " +- "First aid is helping, first aid is making that call, " +- "putting a Band-Aid on a small wound, controlling bleeding in large " +- "wounds or providing CPR for a collapsed person whose not breathing " +- "and heart has stopped beating. You can help yourself, your loved " +- "ones and the stranger whose life may depend on you being in the " +- "right place at the right time with the right knowledge.";-- // return a new docid- private synchronized int newdocid() {- return docID++;- }-- /*- * (non-Javadoc)- * @see DocMaker#resetIinputs()- */- public synchronized void resetInputs() {- super.resetInputs();- docID = 0;- }-- /*- * (non-Javadoc)- * @see DocMaker#numUniqueTexts()- */- public int numUniqueTexts() {- return 0; // not applicable- }-- protected DocData getNextDocData() throws NoMoreDataException {- if (docID>0 && !forever) {- throw new NoMoreDataException();- }- addBytes(DOC_TEXT.length());- return new DocData("doc"+newdocid(),DOC_TEXT, null, null, null);- }--}+package org.apache.lucene.benchmark.byTask.feeds;++/**+ * 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.+ */++/**+ * Create documents for the test.+ */+public class SimpleDocMaker extends BasicDocMaker {++ private int docID = 0;++ static final String DOC_TEXT = // from a public first aid info at http://firstaid.ie.eu.org+ "Well it may be a little dramatic but sometimes it true. " ++ "If you call the emergency medical services to an incident, " ++ "your actions have started the chain of survival. " ++ "You have acted to help someone you may not even know. " ++ "First aid is helping, first aid is making that call, " ++ "putting a Band-Aid on a small wound, controlling bleeding in large " ++ "wounds or providing CPR for a collapsed person whose not breathing " ++ "and heart has stopped beating. You can help yourself, your loved " ++ "ones and the stranger whose life may depend on you being in the " ++ "right place at the right time with the right knowledge.";++ // return a new docid+ private synchronized int newdocid() {+ return docID++;+ }++ /*+ * (non-Javadoc)+ * @see DocMaker#resetIinputs()+ */+ public synchronized void resetInputs() {+ super.resetInputs();+ docID = 0;+ }++ /*+ * (non-Javadoc)+ * @see DocMaker#numUniqueTexts()+ */+ public int numUniqueTexts() {+ return 0; // not applicable+ }++ protected DocData getNextDocData() throws NoMoreDataException {+ if (docID>0 && !forever) {+ throw new NoMoreDataException();+ }+ addBytes(DOC_TEXT.length());+ return new DocData("doc"+newdocid(),DOC_TEXT, null, null, null);+ }++}diff --git a/contrib/benchmark/src/java/org/apache/lucene/benchmark/byTask/feeds/SimpleQueryMaker.java b/contrib/benchmark/src/java/org/apache/lucene/benchmark/byTask/feeds/SimpleQueryMaker.javaindex ec4811f8331..6468e2e0708 100644--- a/contrib/benchmark/src/java/org/apache/lucene/benchmark/byTask/feeds/SimpleQueryMaker.java+++ b/contrib/benchmark/src/java/org/apache/lucene/benchmark/byTask/feeds/SimpleQueryMaker.java@@ -1,68 +1,68 @@-package org.apache.lucene.benchmark.byTask.feeds;--/**- * 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 org.apache.lucene.analysis.Analyzer;-import org.apache.lucene.index.Term;-import org.apache.lucene.queryParser.QueryParser;+package org.apache.lucene.benchmark.byTask.feeds;++/**+ * 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 org.apache.lucene.analysis.Analyzer;+import org.apache.lucene.index.Term;+import org.apache.lucene.queryParser.QueryParser;import org.apache.lucene.search.BooleanClause.Occur;-import org.apache.lucene.search.BooleanQuery;-import org.apache.lucene.search.Query;-import org.apache.lucene.search.TermQuery;-+import org.apache.lucene.search.BooleanQuery;+import org.apache.lucene.search.Query;+import org.apache.lucene.search.TermQuery;+import java.util.ArrayList;-/**- * A QueryMaker that makes queries for a collection created- * using {@link org.apache.lucene.benchmark.byTask.feeds.SimpleDocMaker}.- */+/**+ * A QueryMaker that makes queries for a collection created+ * using {@link org.apache.lucene.benchmark.byTask.feeds.SimpleDocMaker}.+ */public class SimpleQueryMaker extends AbstractQueryMaker implements QueryMaker {-- /**- * Prepare the queries for this test.- * Extending classes can overide this method for preparing different queries.- * @return prepared queries.- * @throws Exception if canot prepare the queries.- */- protected Query[] prepareQueries() throws Exception {- // analyzer (default is standard analyzer)- Analyzer anlzr= (Analyzer) Class.forName(config.get("analyzer",- "org.apache.lucene.analysis.standard.StandardAnalyzer")).newInstance();-- QueryParser qp = new QueryParser("body",anlzr);- ArrayList qq = new ArrayList();- Query q1 = new TermQuery(new Term("docid","doc2"));- qq.add(q1);- Query q2 = new TermQuery(new Term("body","simple"));- qq.add(q2);- BooleanQuery bq = new BooleanQuery();- bq.add(q1,Occur.MUST);- bq.add(q2,Occur.MUST);- qq.add(bq);- qq.add(qp.parse("synthetic body"));- qq.add(qp.parse("\"synthetic body\""));- qq.add(qp.parse("synthetic text"));- qq.add(qp.parse("\"synthetic text\""));- qq.add(qp.parse("\"synthetic text\"~3"));- qq.add(qp.parse("zoom*"));- qq.add(qp.parse("synth*"));- return (Query []) qq.toArray(new Query[0]);- }--}++ /**+ * Prepare the queries for this test.+ * Extending classes can overide this method for preparing different queries.+ * @return prepared queries.+ * @throws Exception if canot prepare the queries.+ */+ protected Query[] prepareQueries() throws Exception {+ // analyzer (default is standard analyzer)+ Analyzer anlzr= (Analyzer) Class.forName(config.get("analyzer",+ "org.apache.lucene.analysis.standard.StandardAnalyzer")).newInstance();++ QueryParser qp = new QueryParser("body",anlzr);+ ArrayList qq = new ArrayList();+ Query q1 = new TermQuery(new Term("docid","doc2"));+ qq.add(q1);+ Query q2 = new TermQuery(new Term("body","simple"));+ qq.add(q2);+ BooleanQuery bq = new BooleanQuery();+ bq.add(q1,Occur.MUST);+ bq.add(q2,Occur.MUST);+ qq.add(bq);+ qq.add(qp.parse("synthetic body"));+ qq.add(qp.parse("\"synthetic body\""));+ qq.add(qp.parse("synthetic text"));+ qq.add(qp.parse("\"synthetic text\""));+ qq.add(qp.parse("\"synthetic text\"~3"));+ qq.add(qp.parse("zoom*"));+ qq.add(qp.parse("synth*"));+ return (Query []) qq.toArray(new Query[0]);+ }++}diff --git a/contrib/benchmark/src/java/org/apache/lucene/benchmark/byTask/feeds/SimpleSloppyPhraseQueryMaker.java b/contrib/benchmark/src/java/org/apache/lucene/benchmark/byTask/feeds/SimpleSloppyPhraseQueryMaker.javaindex e5b24055b71..7e4f97558e2 100644--- a/contrib/benchmark/src/java/org/apache/lucene/benchmark/byTask/feeds/SimpleSloppyPhraseQueryMaker.java+++ b/contrib/benchmark/src/java/org/apache/lucene/benchmark/byTask/feeds/SimpleSloppyPhraseQueryMaker.java@@ -1,65 +1,65 @@-package org.apache.lucene.benchmark.byTask.feeds;--import java.util.ArrayList;-import java.util.StringTokenizer;--import org.apache.lucene.index.Term;-import org.apache.lucene.search.PhraseQuery;-import org.apache.lucene.search.Query;--/**- * Create sloppy phrase queries for performance test, in an index created using simple doc maker.- */-public class SimpleSloppyPhraseQueryMaker extends SimpleQueryMaker {-- /* (non-Javadoc)- * @see org.apache.lucene.benchmark.byTask.feeds.SimpleQueryMaker#prepareQueries()- */- protected Query[] prepareQueries() throws Exception {- // exatract some 100 words from doc text to an array- String words[];- ArrayList w = new ArrayList();- StringTokenizer st = new StringTokenizer(SimpleDocMaker.DOC_TEXT);- while (st.hasMoreTokens() && w.size()<100) {- w.add(st.nextToken());- }- words = (String[]) w.toArray(new String[0]);-- // create queries (that would find stuff) with varying slops- ArrayList queries = new ArrayList();- for (int slop=0; slop<8; slop++) {- for (int qlen=2; qlen<6; qlen++) {- for (int wd=0; wd<words.length-qlen-slop; wd++) {- // ordered- int remainedSlop = slop;- PhraseQuery q = new PhraseQuery();- q.setSlop(slop);- int wind = wd;- for (int i=0; i<qlen; i++) {+package org.apache.lucene.benchmark.byTask.feeds;++import java.util.ArrayList;+import java.util.StringTokenizer;++import org.apache.lucene.index.Term;+import org.apache.lucene.search.PhraseQuery;+import org.apache.lucene.search.Query;++/**+ * Create sloppy phrase queries for performance test, in an index created using simple doc maker.+ */+public class SimpleSloppyPhraseQueryMaker extends SimpleQueryMaker {++ /* (non-Javadoc)+ * @see org.apache.lucene.benchmark.byTask.feeds.SimpleQueryMaker#prepareQueries()+ */+ protected Query[] prepareQueries() throws Exception {+ // exatract some 100 words from doc text to an array+ String words[];+ ArrayList w = new ArrayList();+ StringTokenizer st = new StringTokenizer(SimpleDocMaker.DOC_TEXT);+ while (st.hasMoreTokens() && w.size()<100) {+ w.add(st.nextToken());+ }+ words = (String[]) w.toArray(new String[0]);++ // create queries (that would find stuff) with varying slops+ ArrayList queries = new ArrayList();+ for (int slop=0; slop<8; slop++) {+ for (int qlen=2; qlen<6; qlen++) {+ for (int wd=0; wd<words.length-qlen-slop; wd++) {+ // ordered+ int remainedSlop = slop;+ PhraseQuery q = new PhraseQuery();+ q.setSlop(slop);+ int wind = wd;+ for (int i=0; i<qlen; i++) {q.add(new Term(BasicDocMaker.BODY_FIELD,words[wind++]));- if (remainedSlop>0) {- remainedSlop--;- wind++;- }- }- queries.add(q);- // reveresed- remainedSlop = slop;- q = new PhraseQuery();- q.setSlop(slop+2*qlen);- wind = wd+qlen+remainedSlop-1;- for (int i=0; i<qlen; i++) {+ if (remainedSlop>0) {+ remainedSlop--;+ wind++;+ }+ }+ queries.add(q);+ // reveresed+ remainedSlop = slop;+ q = new PhraseQuery();+ q.setSlop(slop+2*qlen);+ wind = wd+qlen+remainedSlop-1;+ for (int i=0; i<qlen; i++) {q.add(new Term(BasicDocMaker.BODY_FIELD,words[wind--]));- if (remainedSlop>0) {- remainedSlop--;- wind--;- }- }- queries.add(q);- }- }- }- return (Query[]) queries.toArray(new Query[0]);- }--}+ if (remainedSlop>0) {+ remainedSlop--;+ wind--;+ }+ }+ queries.add(q);+ }+ }+ }+ return (Query[]) queries.toArray(new Query[0]);+ }++}diff --git a/contrib/benchmark/src/java/org/apache/lucene/benchmark/byTask/feeds/TrecDocMaker.java b/contrib/benchmark/src/java/org/apache/lucene/benchmark/byTask/feeds/TrecDocMaker.javaindex 402c93a1e62..3113991565d 100644--- a/contrib/benchmark/src/java/org/apache/lucene/benchmark/byTask/feeds/TrecDocMaker.java+++ b/contrib/benchmark/src/java/org/apache/lucene/benchmark/byTask/feeds/TrecDocMaker.java@@ -1,221 +1,221 @@-package org.apache.lucene.benchmark.byTask.feeds;--/**- * 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.io.BufferedInputStream;-import java.io.BufferedReader;-import java.io.File;-import java.io.FileInputStream;-import java.io.IOException;-import java.io.InputStreamReader;-import java.text.DateFormat;-import java.text.ParseException;-import java.text.SimpleDateFormat;-import java.util.ArrayList;-import java.util.Date;-import java.util.Locale;-import java.util.zip.GZIPInputStream;--import org.apache.lucene.benchmark.byTask.utils.Config;---/**- * A DocMaker using the (compressed) Trec collection for its input.- */-public class TrecDocMaker extends BasicDocMaker {-- private static final String newline = System.getProperty("line.separator");-- private DateFormat dateFormat [];- private File dataDir = null;- private ArrayList inputFiles = new ArrayList();- private int nextFile = 0;- private int iteration=0;- private BufferedReader reader;- private GZIPInputStream zis;-- private static final String DATE_FORMATS [] = {- "EEE, dd MMM yyyy kk:mm:ss z", //Tue, 09 Dec 2003 22:39:08 GMT- "EEE MMM dd kk:mm:ss yyyy z", //Tue Dec 09 16:45:08 2003 EST- "EEE, dd-MMM-':'y kk:mm:ss z", //Tue, 09 Dec 2003 22:39:08 GMT- "EEE, dd-MMM-yyy kk:mm:ss z", //Tue, 09 Dec 2003 22:39:08 GMT- };-- /* (non-Javadoc)- * @see SimpleDocMaker#setConfig(java.util.Properties)- */- public void setConfig(Config config) {- super.setConfig(config);- String d = config.get("docs.dir","trec");- dataDir = new File(new File("work"),d);- collectFiles(dataDir,inputFiles);- if (inputFiles.size()==0) {- throw new RuntimeException("No txt files in dataDir: "+dataDir.getAbsolutePath());- }- // date format: 30-MAR-1987 14:22:36.87- dateFormat = new SimpleDateFormat[DATE_FORMATS.length];- for (int i = 0; i < dateFormat.length; i++) {- dateFormat[i] = new SimpleDateFormat(DATE_FORMATS[i],Locale.US);- dateFormat[i].setLenient(true);- }- }-- private void openNextFile() throws NoMoreDataException, Exception {- closeInputs();- int retries = 0;- while (true) {- File f = null;- synchronized (this) {- if (nextFile >= inputFiles.size()) {- // exhausted files, start a new round, unless forever set to false.- if (!forever) {- throw new NoMoreDataException();- }- nextFile = 0;- iteration++;- }- f = (File) inputFiles.get(nextFile++);- }- System.out.println("opening: "+f+" length: "+f.length());- try {- zis = new GZIPInputStream(new BufferedInputStream(new FileInputStream(f)));- reader = new BufferedReader(new InputStreamReader(zis));- return;- } catch (Exception e) {- retries++;- if (retries<20) {- System.out.println("Skipping 'bad' file "+f.getAbsolutePath()+" #retries="+retries);- continue;- } else {- throw new NoMoreDataException();- }- }- }- }-- private void closeInputs() {- if (zis!=null) {- try {- zis.close();- } catch (IOException e) {- System.out.println("closeInputs(): Ingnoring error: "+e);- e.printStackTrace();- }- zis = null;- }- if (reader!=null) {- try {- reader.close();- } catch (IOException e) {- System.out.println("closeInputs(): Ingnoring error: "+e);- e.printStackTrace();- }- reader = null;- }- }-- // read until finding a line that starts with the specified prefix- private StringBuffer read (String prefix, StringBuffer sb, boolean collectMatchLine, boolean collectAll) throws Exception {- sb = (sb==null ? new StringBuffer() : sb);- String sep = "";- while (true) {- String line = reader.readLine();- if (line==null) {- openNextFile();- continue;- }- if (line.startsWith(prefix)) {- if (collectMatchLine) {- sb.append(sep+line);- sep = newline;- }- break;- }- if (collectAll) {- sb.append(sep+line);- sep = newline;- }- }- //System.out.println("read: "+sb);- return sb;- }-- protected DocData getNextDocData() throws NoMoreDataException, Exception {- if (reader==null) {- openNextFile();- }- // 1. skip until doc start- read("<DOC>",null,false,false);- // 2. name- StringBuffer sb = read("<DOCNO>",null,true,false);- String name = sb.substring("<DOCNO>".length());- name = name.substring(0,name.indexOf("</DOCNO>"))+"_"+iteration;- // 3. skip until doc header- read("<DOCHDR>",null,false,false);- // 4. date- sb = read("Date: ",null,true,false);- String dateStr = sb.substring("Date: ".length());- // 5. skip until end of doc header- read("</DOCHDR>",null,false,false);- // 6. collect until end of doc- sb = read("</DOC>",null,false,true);- // this is the next document, so parse it- Date date = parseDate(dateStr);- HTMLParser p = getHtmlParser();- DocData docData = p.parse(name, date, sb, dateFormat[0]);- addBytes(sb.length()); // count char length of parsed html text (larger than the plain doc body text).-- return docData;- }-- private Date parseDate(String dateStr) {- Date date = null;- for (int i=0; i<dateFormat.length; i++) {- try {- date = dateFormat[i].parse(dateStr.trim());- return date;- } catch (ParseException e) {- }- }- // do not fail test just because a date could not be parsed- System.out.println("ignoring date parse exception (assigning 'now') for: "+dateStr);- date = new Date(); // now- return date;- }--- /*- * (non-Javadoc)- * @see DocMaker#resetIinputs()- */- public synchronized void resetInputs() {- super.resetInputs();- closeInputs();- nextFile = 0;- iteration = 0;- }-- /*- * (non-Javadoc)- * @see DocMaker#numUniqueTexts()- */- public int numUniqueTexts() {- return inputFiles.size();- }--}+package org.apache.lucene.benchmark.byTask.feeds;++/**+ * 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.io.BufferedInputStream;+import java.io.BufferedReader;+import java.io.File;+import java.io.FileInputStream;+import java.io.IOException;+import java.io.InputStreamReader;+import java.text.DateFormat;+import java.text.ParseException;+import java.text.SimpleDateFormat;+import java.util.ArrayList;+import java.util.Date;+import java.util.Locale;+import java.util.zip.GZIPInputStream;++import org.apache.lucene.benchmark.byTask.utils.Config;+++/**+ * A DocMaker using the (compressed) Trec collection for its input.+ */+public class TrecDocMaker extends BasicDocMaker {++ private static final String newline = System.getProperty("line.separator");++ private DateFormat dateFormat [];+ private File dataDir = null;+ private ArrayList inputFiles = new ArrayList();+ private int nextFile = 0;+ private int iteration=0;+ private BufferedReader reader;+ private GZIPInputStream zis;++ private static final String DATE_FORMATS [] = {+ "EEE, dd MMM yyyy kk:mm:ss z", //Tue, 09 Dec 2003 22:39:08 GMT+ "EEE MMM dd kk:mm:ss yyyy z", //Tue Dec 09 16:45:08 2003 EST+ "EEE, dd-MMM-':'y kk:mm:ss z", //Tue, 09 Dec 2003 22:39:08 GMT+ "EEE, dd-MMM-yyy kk:mm:ss z", //Tue, 09 Dec 2003 22:39:08 GMT+ };++ /* (non-Javadoc)+ * @see SimpleDocMaker#setConfig(java.util.Properties)+ */+ public void setConfig(Config config) {+ super.setConfig(config);+ String d = config.get("docs.dir","trec");+ dataDir = new File(new File("work"),d);+ collectFiles(dataDir,inputFiles);+ if (inputFiles.size()==0) {+ throw new RuntimeException("No txt files in dataDir: "+dataDir.getAbsolutePath());+ }+ // date format: 30-MAR-1987 14:22:36.87+ dateFormat = new SimpleDateFormat[DATE_FORMATS.length];+ for (int i = 0; i < dateFormat.length; i++) {+ dateFormat[i] = new SimpleDateFormat(DATE_FORMATS[i],Locale.US);+ dateFormat[i].setLenient(true);+ }+ }++ private void openNextFile() throws NoMoreDataException, Exception {+ closeInputs();+ int retries = 0;+ while (true) {+ File f = null;+ synchronized (this) {+ if (nextFile >= inputFiles.size()) {+ // exhausted files, start a new round, unless forever set to false.+ if (!forever) {+ throw new NoMoreDataException();+ }+ nextFile = 0;+ iteration++;+ }+ f = (File) inputFiles.get(nextFile++);+ }+ System.out.println("opening: "+f+" length: "+f.length());+ try {+ zis = new GZIPInputStream(new BufferedInputStream(new FileInputStream(f)));+ reader = new BufferedReader(new InputStreamReader(zis));+ return;+ } catch (Exception e) {+ retries++;+ if (retries<20) {+ System.out.println("Skipping 'bad' file "+f.getAbsolutePath()+" #retries="+retries);+ continue;+ } else {+ throw new NoMoreDataException();+ }+ }+ }+ }++ private void closeInputs() {+ if (zis!=null) {+ try {+ zis.close();+ } catch (IOException e) {+ System.out.println("closeInputs(): Ingnoring error: "+e);+ e.printStackTrace();+ }+ zis = null;+ }+ if (reader!=null) {+ try {+ reader.close();+ } catch (IOException e) {+ System.out.println("closeInputs(): Ingnoring error: "+e);+ e.printStackTrace();+ }+ reader = null;+ }+ }++ // read until finding a line that starts with the specified prefix+ private StringBuffer read (String prefix, StringBuffer sb, boolean collectMatchLine, boolean collectAll) throws Exception {+ sb = (sb==null ? new StringBuffer() : sb);+ String sep = "";+ while (true) {+ String line = reader.readLine();+ if (line==null) {+ openNextFile();+ continue;+ }+ if (line.startsWith(prefix)) {+ if (collectMatchLine) {+ sb.append(sep+line);+ sep = newline;+ }+ break;+ }+ if (collectAll) {+ sb.append(sep+line);+ sep = newline;+ }+ }+ //System.out.println("read: "+sb);+ return sb;+ }++ protected DocData getNextDocData() throws NoMoreDataException, Exception {+ if (reader==null) {+ openNextFile();+ }+ // 1. skip until doc start+ read("<DOC>",null,false,false);+ // 2. name+ StringBuffer sb = read("<DOCNO>",null,true,false);+ String name = sb.substring("<DOCNO>".length());+ name = name.substring(0,name.indexOf("</DOCNO>"))+"_"+iteration;+ // 3. skip until doc header+ read("<DOCHDR>",null,false,false);+ // 4. date+ sb = read("Date: ",null,true,false);+ String dateStr = sb.substring("Date: ".length());+ // 5. skip until end of doc header+ read("</DOCHDR>",null,false,false);+ // 6. collect until end of doc+ sb = read("</DOC>",null,false,true);+ // this is the next document, so parse it+ Date date = parseDate(dateStr);+ HTMLParser p = getHtmlParser();+ DocData docData = p.parse(name, date, sb, dateFormat[0]);+ addBytes(sb.length()); // count char length of parsed html text (larger than the plain doc body text).++ return docData;+ }++ private Date parseDate(String dateStr) {+ Date date = null;+ for (int i=0; i<dateFormat.length; i++) {+ try {+ date = dateFormat[i].parse(dateStr.trim());+ return date;+ } catch (ParseException e) {+ }+ }+ // do not fail test just because a date could not be parsed+ System.out.println("ignoring date parse exception (assigning 'now') for: "+dateStr);+ date = new Date(); // now+ return date;+ }+++ /*+ * (non-Javadoc)+ * @see DocMaker#resetIinputs()+ */+ public synchronized void resetInputs() {+ super.resetInputs();+ closeInputs();+ nextFile = 0;+ iteration = 0;+ }++ /*+ * (non-Javadoc)+ * @see DocMaker#numUniqueTexts()+ */+ public int numUniqueTexts() {+ return inputFiles.size();+ }++}diff --git a/contrib/benchmark/src/java/org/apache/lucene/benchmark/byTask/programmatic/Sample.java b/contrib/benchmark/src/java/org/apache/lucene/benchmark/byTask/programmatic/Sample.javaindex 54a4d616ffe..482ef5b1de2 100644--- a/contrib/benchmark/src/java/org/apache/lucene/benchmark/byTask/programmatic/Sample.java+++ b/contrib/benchmark/src/java/org/apache/lucene/benchmark/byTask/programmatic/Sample.java@@ -1,101 +1,101 @@-package org.apache.lucene.benchmark.byTask.programmatic;--/**- * Copyright 2005 The Apache Software Foundation- *- * Licensed 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.io.IOException;-import java.util.Properties;--import org.apache.lucene.benchmark.byTask.PerfRunData;-import org.apache.lucene.benchmark.byTask.tasks.AddDocTask;-import org.apache.lucene.benchmark.byTask.tasks.CloseIndexTask;-import org.apache.lucene.benchmark.byTask.tasks.CreateIndexTask;-import org.apache.lucene.benchmark.byTask.tasks.RepSumByNameTask;-import org.apache.lucene.benchmark.byTask.tasks.TaskSequence;-import org.apache.lucene.benchmark.byTask.utils.Config;--/**- * Sample performance test written programatically - no algorithm file is needed here.- */-public class Sample {-- /**- * @param args- * @throws Exception- * @throws IOException- */- public static void main(String[] args) throws Exception {- Properties p = initProps();- Config conf = new Config(p);- PerfRunData runData = new PerfRunData(conf);-- // 1. top sequence- TaskSequence top = new TaskSequence(runData,null,null,false); // top level, not parralel-- // 2. task to create the index- CreateIndexTask create = new CreateIndexTask(runData);- top.addTask(create);-- // 3. task seq to add 500 docs (order matters - top to bottom - add seq to top, only then add to seq)- TaskSequence seq1 = new TaskSequence(runData,"AddDocs",top,false);- seq1.setRepetitions(500);- seq1.setNoChildReport();- top.addTask(seq1);-- // 4. task to add the doc- AddDocTask addDoc = new AddDocTask(runData);- //addDoc.setParams("1200"); // doc size limit if supported- seq1.addTask(addDoc); // order matters 9see comment above)-- // 5. task to close the index- CloseIndexTask close = new CloseIndexTask(runData);- top.addTask(close);-- // task to report- RepSumByNameTask rep = new RepSumByNameTask(runData);- top.addTask(rep);-- // print algorithm- System.out.println(top.toString());-- // execute- top.doLogic();- }-- // Sample programmatic settings. Could also read from file.- private static Properties initProps() {- Properties p = new Properties();- p.setProperty ( "task.max.depth.log" , "3" );- p.setProperty ( "max.buffered" , "buf:10:10:100:100:10:10:100:100" );- p.setProperty ( "doc.maker" , "org.apache.lucene.benchmark.byTask.feeds.ReutersDocMaker" );- p.setProperty ( "doc.add.log.step" , "2000" );- p.setProperty ( "doc.delete.log.step" , "2000" );- p.setProperty ( "doc.delete.step" , "8" );- p.setProperty ( "analyzer" , "org.apache.lucene.analysis.standard.StandardAnalyzer" );- p.setProperty ( "doc.term.vector" , "false" );- p.setProperty ( "directory" , "FSDirectory" );- p.setProperty ( "query.maker" , "org.apache.lucene.benchmark.byTask.feeds.ReutersQueryMaker" );- p.setProperty ( "doc.stored" , "true" );- p.setProperty ( "docs.dir" , "reuters-out" );- p.setProperty ( "compound" , "cmpnd:true:true:true:true:false:false:false:false" );- p.setProperty ( "doc.tokenized" , "true" );- p.setProperty ( "merge.factor" , "mrg:10:100:10:100:10:100:10:100" );- return p;- }----}+package org.apache.lucene.benchmark.byTask.programmatic;++/**+ * Copyright 2005 The Apache Software Foundation+ *+ * Licensed 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.io.IOException;+import java.util.Properties;++import org.apache.lucene.benchmark.byTask.PerfRunData;+import org.apache.lucene.benchmark.byTask.tasks.AddDocTask;+import org.apache.lucene.benchmark.byTask.tasks.CloseIndexTask;+import org.apache.lucene.benchmark.byTask.tasks.CreateIndexTask;+import org.apache.lucene.benchmark.byTask.tasks.RepSumByNameTask;+import org.apache.lucene.benchmark.byTask.tasks.TaskSequence;+import org.apache.lucene.benchmark.byTask.utils.Config;++/**+ * Sample performance test written programatically - no algorithm file is needed here.+ */+public class Sample {++ /**+ * @param args+ * @throws Exception+ * @throws IOException+ */+ public static void main(String[] args) throws Exception {+ Properties p = initProps();+ Config conf = new Config(p);+ PerfRunData runData = new PerfRunData(conf);++ // 1. top sequence+ TaskSequence top = new TaskSequence(runData,null,null,false); // top level, not parralel++ // 2. task to create the index+ CreateIndexTask create = new CreateIndexTask(runData);+ top.addTask(create);++ // 3. task seq to add 500 docs (order matters - top to bottom - add seq to top, only then add to seq)+ TaskSequence seq1 = new TaskSequence(runData,"AddDocs",top,false);+ seq1.setRepetitions(500);+ seq1.setNoChildReport();+ top.addTask(seq1);++ // 4. task to add the doc+ AddDocTask addDoc = new AddDocTask(runData);+ //addDoc.setParams("1200"); // doc size limit if supported+ seq1.addTask(addDoc); // order matters 9see comment above)++ // 5. task to close the index+ CloseIndexTask close = new CloseIndexTask(runData);+ top.addTask(close);++ // task to report+ RepSumByNameTask rep = new RepSumByNameTask(runData);+ top.addTask(rep);++ // print algorithm+ System.out.println(top.toString());++ // execute+ top.doLogic();+ }++ // Sample programmatic settings. Could also read from file.+ private static Properties initProps() {+ Properties p = new Properties();+ p.setProperty ( "task.max.depth.log" , "3" );+ p.setProperty ( "max.buffered" , "buf:10:10:100:100:10:10:100:100" );+ p.setProperty ( "doc.maker" , "org.apache.lucene.benchmark.byTask.feeds.ReutersDocMaker" );+ p.setProperty ( "doc.add.log.step" , "2000" );+ p.setProperty ( "doc.delete.log.step" , "2000" );+ p.setProperty ( "doc.delete.step" , "8" );+ p.setProperty ( "analyzer" , "org.apache.lucene.analysis.standard.StandardAnalyzer" );+ p.setProperty ( "doc.term.vector" , "false" );+ p.setProperty ( "directory" , "FSDirectory" );+ p.setProperty ( "query.maker" , "org.apache.lucene.benchmark.byTask.feeds.ReutersQueryMaker" );+ p.setProperty ( "doc.stored" , "true" );+ p.setProperty ( "docs.dir" , "reuters-out" );+ p.setProperty ( "compound" , "cmpnd:true:true:true:true:false:false:false:false" );+ p.setProperty ( "doc.tokenized" , "true" );+ p.setProperty ( "merge.factor" , "mrg:10:100:10:100:10:100:10:100" );+ return p;+ }++++}diff --git a/contrib/benchmark/src/java/org/apache/lucene/benchmark/byTask/stats/Points.java b/contrib/benchmark/src/java/org/apache/lucene/benchmark/byTask/stats/Points.javaindex 3ad69dd1fb4..31b7428d35c 100644--- a/contrib/benchmark/src/java/org/apache/lucene/benchmark/byTask/stats/Points.java+++ b/contrib/benchmark/src/java/org/apache/lucene/benchmark/byTask/stats/Points.java@@ -1,91 +1,91 @@-package org.apache.lucene.benchmark.byTask.stats;--/**- * 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.ArrayList;+package org.apache.lucene.benchmark.byTask.stats;++/**+ * 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.ArrayList;import java.util.List;--import org.apache.lucene.benchmark.byTask.tasks.PerfTask;-import org.apache.lucene.benchmark.byTask.utils.Config;---/**- * Test run data points collected as the test proceeds.- */-public class Points {-- private Config config;-- // stat points ordered by their start time.- // for now we collect points as TaskStats objects.- // later might optimize to collect only native data.- private ArrayList points = new ArrayList();-- private int nextTaskRunNum = 0;-- /**- * Create a Points statistics object.- */- public Points (Config config) {- this.config = config;- }-- /**++import org.apache.lucene.benchmark.byTask.tasks.PerfTask;+import org.apache.lucene.benchmark.byTask.utils.Config;+++/**+ * Test run data points collected as the test proceeds.+ */+public class Points {++ private Config config;++ // stat points ordered by their start time.+ // for now we collect points as TaskStats objects.+ // later might optimize to collect only native data.+ private ArrayList points = new ArrayList();++ private int nextTaskRunNum = 0;++ /**+ * Create a Points statistics object.+ */+ public Points (Config config) {+ this.config = config;+ }++ /*** Return the current task stats.* the actual task stats are returned, so caller should not modify this task stats.* @return current {@link TaskStats}.- */+ */public List taskStats () {return points;- }-- /**- * Mark that a task is starting.- * Create a task stats for it and store it as a point.- * @param task the starting task.- * @return the new task stats created for the starting task.- */- public synchronized TaskStats markTaskStart (PerfTask task, int round) {- TaskStats stats = new TaskStats(task, nextTaskRunNum(), round);- points.add(stats);- return stats;- }-- // return next task num- private synchronized int nextTaskRunNum() {- return nextTaskRunNum++;- }-- /**- * mark the end of a task- */- public synchronized void markTaskEnd (TaskStats stats, int count) {- int numParallelTasks = nextTaskRunNum - 1 - stats.getTaskRunNum();- // note: if the stats were cleared, might be that this stats object is- // no longer in points, but this is just ok.- stats.markEnd(numParallelTasks, count);- }-- /**- * Clear all data, prepare for more tests.- */- public void clearData() {- points.clear();- }--}+ }++ /**+ * Mark that a task is starting.+ * Create a task stats for it and store it as a point.+ * @param task the starting task.+ * @return the new task stats created for the starting task.+ */+ public synchronized TaskStats markTaskStart (PerfTask task, int round) {+ TaskStats stats = new TaskStats(task, nextTaskRunNum(), round);+ points.add(stats);+ return stats;+ }++ // return next task num+ private synchronized int nextTaskRunNum() {+ return nextTaskRunNum++;+ }++ /**+ * mark the end of a task+ */+ public synchronized void markTaskEnd (TaskStats stats, int count) {+ int numParallelTasks = nextTaskRunNum - 1 - stats.getTaskRunNum();+ // note: if the stats were cleared, might be that this stats object is+ // no longer in points, but this is just ok.+ stats.markEnd(numParallelTasks, count);+ }++ /**+ * Clear all data, prepare for more tests.+ */+ public void clearData() {+ points.clear();+ }++}diff --git a/contrib/benchmark/src/java/org/apache/lucene/benchmark/byTask/stats/Report.java b/contrib/benchmark/src/java/org/apache/lucene/benchmark/byTask/stats/Report.javaindex 71897320fb8..05cff5320a1 100644--- a/contrib/benchmark/src/java/org/apache/lucene/benchmark/byTask/stats/Report.java+++ b/contrib/benchmark/src/java/org/apache/lucene/benchmark/byTask/stats/Report.java@@ -1,64 +1,64 @@-package org.apache.lucene.benchmark.byTask.stats;--/**- * 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.- */--/**- * Textual report of current statistics.- */-public class Report {-- private String text;- private int size;- private int outOf;- private int reported;-+package org.apache.lucene.benchmark.byTask.stats;++/**+ * 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.+ */++/**+ * Textual report of current statistics.+ */+public class Report {++ private String text;+ private int size;+ private int outOf;+ private int reported;+public Report (String text, int size, int reported, int outOf) {- this.text = text;- this.size = size;- this.reported = reported;- this.outOf = outOf;- }-- /**- * Returns total number of stats points when this report was created.- */- public int getOutOf() {- return outOf;- }-- /**- * Returns number of lines in the reoprt.- */- public int getSize() {- return size;- }-- /**- * Returns the report text.- */- public String getText() {- return text;- }-- /**- * Returns number of stats points represented in this report.- */- public int getReported() {- return reported;- }-}+ this.text = text;+ this.size = size;+ this.reported = reported;+ this.outOf = outOf;+ }++ /**+ * Returns total number of stats points when this report was created.+ */+ public int getOutOf() {+ return outOf;+ }++ /**+ * Returns number of lines in the reoprt.+ */+ public int getSize() {+ return size;+ }++ /**+ * Returns the report text.+ */+ public String getText() {+ return text;+ }++ /**+ * Returns number of stats points represented in this report.+ */+ public int getReported() {+ return reported;+ }+}diff --git a/contrib/benchmark/src/java/org/apache/lucene/benchmark/byTask/stats/TaskStats.java b/contrib/benchmark/src/java/org/apache/lucene/benchmark/byTask/stats/TaskStats.javaindex e97db786888..7138b9a5f73 100644--- a/contrib/benchmark/src/java/org/apache/lucene/benchmark/byTask/stats/TaskStats.java+++ b/contrib/benchmark/src/java/org/apache/lucene/benchmark/byTask/stats/TaskStats.java@@ -1,192 +1,192 @@-package org.apache.lucene.benchmark.byTask.stats;--/**- * 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 org.apache.lucene.benchmark.byTask.tasks.PerfTask;--/**- * Statistics for a task run.- * <br>The same task can run more than once, but, if that task records statistics,- * each run would create its own TaskStats.- */-public class TaskStats implements Cloneable {-- /** task for which data was collected */- private PerfTask task;-- /** round in which task run started */- private int round;-- /** task start time */- private long start;-- /** task elapsed time. elapsed >= 0 indicates run completion! */- private long elapsed = -1;-- /** max tot mem during task */- private long maxTotMem;-- /** max used mem during task */- private long maxUsedMem;-- /** serial run number of this task run in the perf run */- private int taskRunNum;-- /** number of other tasks that started to run while this task was still running */- private int numParallelTasks;-- /** number of work items done by this task.- * For indexing that can be number of docs added.- * For warming that can be number of scanned items, etc.- * For repeating tasks, this is a sum over repetitions.- */- private int count;-- /** Number of similar tasks aggregated into this record.- * Used when summing up on few runs/instances of similar tasks.- */- private int numRuns = 1;-- /**- * Create a run data for a task that is starting now.- * To be called from Points.- */- TaskStats (PerfTask task, int taskRunNum, int round) {- this.task = task;- this.taskRunNum = taskRunNum;- this.round = round;- maxTotMem = Runtime.getRuntime().totalMemory();- maxUsedMem = maxTotMem - Runtime.getRuntime().freeMemory();- start = System.currentTimeMillis();- }-- /**- * mark the end of a task- */- void markEnd (int numParallelTasks, int count) {- elapsed = System.currentTimeMillis() - start;- long totMem = Runtime.getRuntime().totalMemory();- if (totMem > maxTotMem) {- maxTotMem = totMem;- }- long usedMem = totMem - Runtime.getRuntime().freeMemory();- if (usedMem > maxUsedMem) {- maxUsedMem = usedMem;- }- this.numParallelTasks = numParallelTasks;- this.count = count;- }-- /**- * @return the taskRunNum.- */- public int getTaskRunNum() {- return taskRunNum;- }-- /* (non-Javadoc)- * @see java.lang.Object#toString()- */- public String toString() {- StringBuffer res = new StringBuffer(task.getName());- res.append(" ");- res.append(count);- res.append(" ");- res.append(elapsed);- return res.toString();- }-- /**- * @return Returns the count.- */- public int getCount() {- return count;- }-- /**- * @return elapsed time.- */- public long getElapsed() {- return elapsed;- }-- /**- * @return Returns the maxTotMem.- */- public long getMaxTotMem() {- return maxTotMem;- }-- /**- * @return Returns the maxUsedMem.- */- public long getMaxUsedMem() {- return maxUsedMem;- }-- /**- * @return Returns the numParallelTasks.- */- public int getNumParallelTasks() {- return numParallelTasks;- }-- /**- * @return Returns the task.- */- public PerfTask getTask() {- return task;- }-- /**- * @return Returns the numRuns.- */- public int getNumRuns() {- return numRuns;- }-- /**- * Add data from another stat, for aggregation- * @param stat2 the added stat data.- */- public void add(TaskStats stat2) {- numRuns += stat2.getNumRuns();- elapsed += stat2.getElapsed();- maxTotMem += stat2.getMaxTotMem();- maxUsedMem += stat2.getMaxUsedMem();- count += stat2.getCount();- if (round != stat2.round) {- round = -1; // no meaning if agregating tasks of different ruond.- }- }-- /* (non-Javadoc)- * @see java.lang.Object#clone()- */+package org.apache.lucene.benchmark.byTask.stats;++/**+ * 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 org.apache.lucene.benchmark.byTask.tasks.PerfTask;++/**+ * Statistics for a task run.+ * <br>The same task can run more than once, but, if that task records statistics,+ * each run would create its own TaskStats.+ */+public class TaskStats implements Cloneable {++ /** task for which data was collected */+ private PerfTask task;++ /** round in which task run started */+ private int round;++ /** task start time */+ private long start;++ /** task elapsed time. elapsed >= 0 indicates run completion! */+ private long elapsed = -1;++ /** max tot mem during task */+ private long maxTotMem;++ /** max used mem during task */+ private long maxUsedMem;++ /** serial run number of this task run in the perf run */+ private int taskRunNum;++ /** number of other tasks that started to run while this task was still running */+ private int numParallelTasks;++ /** number of work items done by this task.+ * For indexing that can be number of docs added.+ * For warming that can be number of scanned items, etc.+ * For repeating tasks, this is a sum over repetitions.+ */+ private int count;++ /** Number of similar tasks aggregated into this record.+ * Used when summing up on few runs/instances of similar tasks.+ */+ private int numRuns = 1;++ /**+ * Create a run data for a task that is starting now.+ * To be called from Points.+ */+ TaskStats (PerfTask task, int taskRunNum, int round) {+ this.task = task;+ this.taskRunNum = taskRunNum;+ this.round = round;+ maxTotMem = Runtime.getRuntime().totalMemory();+ maxUsedMem = maxTotMem - Runtime.getRuntime().freeMemory();+ start = System.currentTimeMillis();+ }++ /**+ * mark the end of a task+ */+ void markEnd (int numParallelTasks, int count) {+ elapsed = System.currentTimeMillis() - start;+ long totMem = Runtime.getRuntime().totalMemory();+ if (totMem > maxTotMem) {+ maxTotMem = totMem;+ }+ long usedMem = totMem - Runtime.getRuntime().freeMemory();+ if (usedMem > maxUsedMem) {+ maxUsedMem = usedMem;+ }+ this.numParallelTasks = numParallelTasks;+ this.count = count;+ }++ /**+ * @return the taskRunNum.+ */+ public int getTaskRunNum() {+ return taskRunNum;+ }++ /* (non-Javadoc)+ * @see java.lang.Object#toString()+ */+ public String toString() {+ StringBuffer res = new StringBuffer(task.getName());+ res.append(" ");+ res.append(count);+ res.append(" ");+ res.append(elapsed);+ return res.toString();+ }++ /**+ * @return Returns the count.+ */+ public int getCount() {+ return count;+ }++ /**+ * @return elapsed time.+ */+ public long getElapsed() {+ return elapsed;+ }++ /**+ * @return Returns the maxTotMem.+ */+ public long getMaxTotMem() {+ return maxTotMem;+ }++ /**+ * @return Returns the maxUsedMem.+ */+ public long getMaxUsedMem() {+ return maxUsedMem;+ }++ /**+ * @return Returns the numParallelTasks.+ */+ public int getNumParallelTasks() {+ return numParallelTasks;+ }++ /**+ * @return Returns the task.+ */+ public PerfTask getTask() {+ return task;+ }++ /**+ * @return Returns the numRuns.+ */+ public int getNumRuns() {+ return numRuns;+ }++ /**+ * Add data from another stat, for aggregation+ * @param stat2 the added stat data.+ */+ public void add(TaskStats stat2) {+ numRuns += stat2.getNumRuns();+ elapsed += stat2.getElapsed();+ maxTotMem += stat2.getMaxTotMem();+ maxUsedMem += stat2.getMaxUsedMem();+ count += stat2.getCount();+ if (round != stat2.round) {+ round = -1; // no meaning if agregating tasks of different ruond.+ }+ }++ /* (non-Javadoc)+ * @see java.lang.Object#clone()+ */public Object clone() throws CloneNotSupportedException {- return super.clone();- }-- /**- * @return the round number.- */+ return super.clone();+ }++ /**+ * @return the round number.+ */public int getRound() {- return round;- }--}+ return round;+ }++}diff --git a/contrib/benchmark/src/java/org/apache/lucene/benchmark/byTask/tasks/AddDocTask.java b/contrib/benchmark/src/java/org/apache/lucene/benchmark/byTask/tasks/AddDocTask.javaindex c0275c1ed28..89817e02ecc 100644--- a/contrib/benchmark/src/java/org/apache/lucene/benchmark/byTask/tasks/AddDocTask.java+++ b/contrib/benchmark/src/java/org/apache/lucene/benchmark/byTask/tasks/AddDocTask.java@@ -1,98 +1,98 @@-package org.apache.lucene.benchmark.byTask.tasks;--/**- * 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 org.apache.lucene.benchmark.byTask.PerfRunData;-import org.apache.lucene.benchmark.byTask.feeds.DocMaker;-import org.apache.lucene.document.Document;---/**+package org.apache.lucene.benchmark.byTask.tasks;++/**+ * 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 org.apache.lucene.benchmark.byTask.PerfRunData;+import org.apache.lucene.benchmark.byTask.feeds.DocMaker;+import org.apache.lucene.document.Document;+++/*** Add a document, optionally with of a certain size.* <br>Other side effects: none.* <br>Relevant properties: <code>doc.add.log.step</code>.* <br>Takes optional param: document size.- */-public class AddDocTask extends PerfTask {-+ */+public class AddDocTask extends PerfTask {+/*** Default value for property <code>doc.add.log.step<code> - indicating how often* an "added N docs" message should be logged.*/public static final int DEFAULT_ADD_DOC_LOG_STEP = 500;- public AddDocTask(PerfRunData runData) {- super(runData);- }-- private static int logStep = -1;- private int docSize = 0;-- // volatile data passed between setup(), doLogic(), tearDown().- private Document doc = null;-- /*- * (non-Javadoc)- * @see PerfTask#setup()- */- public void setup() throws Exception {- super.setup();- DocMaker docMaker = getRunData().getDocMaker();- if (docSize > 0) {- doc = docMaker.makeDocument(docSize);- } else {- doc = docMaker.makeDocument();- }- }-- /* (non-Javadoc)- * @see PerfTask#tearDown()- */- public void tearDown() throws Exception {- DocMaker docMaker = getRunData().getDocMaker();- log(docMaker.getCount());- doc = null;- super.tearDown();- }-- public int doLogic() throws Exception {- getRunData().getIndexWriter().addDocument(doc);- return 1;- }-- private void log (int count) {- if (logStep<0) {- // avoid sync although race possible here+ public AddDocTask(PerfRunData runData) {+ super(runData);+ }++ private static int logStep = -1;+ private int docSize = 0;++ // volatile data passed between setup(), doLogic(), tearDown().+ private Document doc = null;++ /*+ * (non-Javadoc)+ * @see PerfTask#setup()+ */+ public void setup() throws Exception {+ super.setup();+ DocMaker docMaker = getRunData().getDocMaker();+ if (docSize > 0) {+ doc = docMaker.makeDocument(docSize);+ } else {+ doc = docMaker.makeDocument();+ }+ }++ /* (non-Javadoc)+ * @see PerfTask#tearDown()+ */+ public void tearDown() throws Exception {+ DocMaker docMaker = getRunData().getDocMaker();+ log(docMaker.getCount());+ doc = null;+ super.tearDown();+ }++ public int doLogic() throws Exception {+ getRunData().getIndexWriter().addDocument(doc);+ return 1;+ }++ private void log (int count) {+ if (logStep<0) {+ // avoid sync although race possible herelogStep = getRunData().getConfig().get("doc.add.log.step",DEFAULT_ADD_DOC_LOG_STEP);- }- if (logStep>0 && (count%logStep)==0) {+ }+ if (logStep>0 && (count%logStep)==0) {System.out.println("--> processed (add) "+count+" docs");- }- }-- /**- * Set the params (docSize only)- * @param params docSize, or 0 for no limit.- */- public void setParams(String params) {- super.setParams(params);- docSize = (int) Float.parseFloat(params);- }+ }+ }++ /**+ * Set the params (docSize only)+ * @param params docSize, or 0 for no limit.+ */+ public void setParams(String params) {+ super.setParams(params);+ docSize = (int) Float.parseFloat(params);+ }/* (non-Javadoc)* @see org.apache.lucene.benchmark.byTask.tasks.PerfTask#supportsParams()@@ -101,4 +101,4 @@ public class AddDocTask extends PerfTask {return true;}-}+}diff --git a/contrib/benchmark/src/java/org/apache/lucene/benchmark/byTask/tasks/ClearStatsTask.java b/contrib/benchmark/src/java/org/apache/lucene/benchmark/byTask/tasks/ClearStatsTask.javaindex f53d6433aad..b7d23169d84 100644--- a/contrib/benchmark/src/java/org/apache/lucene/benchmark/byTask/tasks/ClearStatsTask.java+++ b/contrib/benchmark/src/java/org/apache/lucene/benchmark/byTask/tasks/ClearStatsTask.java@@ -1,44 +1,44 @@-package org.apache.lucene.benchmark.byTask.tasks;--import org.apache.lucene.benchmark.byTask.PerfRunData;--/**- * 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.- */--/**- * Clear statistics data.+package org.apache.lucene.benchmark.byTask.tasks;++import org.apache.lucene.benchmark.byTask.PerfRunData;++/**+ * 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.+ */++/**+ * Clear statistics data.* <br>Other side effects: None.- */-public class ClearStatsTask extends PerfTask {-- public ClearStatsTask(PerfRunData runData) {- super(runData);- }-- public int doLogic() throws Exception {- getRunData().getPoints().clearData();- return 0;- }-- /* (non-Javadoc)- * @see PerfTask#shouldNotRecordStats()- */- protected boolean shouldNotRecordStats() {- return true;- }--}+ */+public class ClearStatsTask extends PerfTask {++ public ClearStatsTask(PerfRunData runData) {+ super(runData);+ }++ public int doLogic() throws Exception {+ getRunData().getPoints().clearData();+ return 0;+ }++ /* (non-Javadoc)+ * @see PerfTask#shouldNotRecordStats()+ */+ protected boolean shouldNotRecordStats() {+ return true;+ }++}diff --git a/contrib/benchmark/src/java/org/apache/lucene/benchmark/byTask/tasks/CloseIndexTask.java b/contrib/benchmark/src/java/org/apache/lucene/benchmark/byTask/tasks/CloseIndexTask.javaindex c661e99a171..ba378bdb811 100644--- a/contrib/benchmark/src/java/org/apache/lucene/benchmark/byTask/tasks/CloseIndexTask.java+++ b/contrib/benchmark/src/java/org/apache/lucene/benchmark/byTask/tasks/CloseIndexTask.java@@ -1,44 +1,44 @@-package org.apache.lucene.benchmark.byTask.tasks;--/**- * 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.io.IOException;--import org.apache.lucene.benchmark.byTask.PerfRunData;-import org.apache.lucene.index.IndexWriter;--/**- * Close index writer.+package org.apache.lucene.benchmark.byTask.tasks;++/**+ * 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.io.IOException;++import org.apache.lucene.benchmark.byTask.PerfRunData;+import org.apache.lucene.index.IndexWriter;++/**+ * Close index writer.* <br>Other side effects: index writer object in perfRunData is nullified.- */-public class CloseIndexTask extends PerfTask {-- public CloseIndexTask(PerfRunData runData) {- super(runData);- }-- public int doLogic() throws IOException {- IndexWriter iw = getRunData().getIndexWriter();- if (iw!=null) {- iw.close();- }- getRunData().setIndexWriter(null);- return 1;- }--}+ */+public class CloseIndexTask extends PerfTask {++ public CloseIndexTask(PerfRunData runData) {+ super(runData);+ }++ public int doLogic() throws IOException {+ IndexWriter iw = getRunData().getIndexWriter();+ if (iw!=null) {+ iw.close();+ }+ getRunData().setIndexWriter(null);+ return 1;+ }++}diff --git a/contrib/benchmark/src/java/org/apache/lucene/benchmark/byTask/tasks/CloseReaderTask.java b/contrib/benchmark/src/java/org/apache/lucene/benchmark/byTask/tasks/CloseReaderTask.javaindex ff48b85b941..7b827c8cbb2 100644--- a/contrib/benchmark/src/java/org/apache/lucene/benchmark/byTask/tasks/CloseReaderTask.java+++ b/contrib/benchmark/src/java/org/apache/lucene/benchmark/byTask/tasks/CloseReaderTask.java@@ -1,45 +1,45 @@-package org.apache.lucene.benchmark.byTask.tasks;--/**- * 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.io.IOException;--import org.apache.lucene.benchmark.byTask.PerfRunData;-import org.apache.lucene.index.IndexReader;--/**- * Close index reader.+package org.apache.lucene.benchmark.byTask.tasks;++/**+ * 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.io.IOException;++import org.apache.lucene.benchmark.byTask.PerfRunData;+import org.apache.lucene.index.IndexReader;++/**+ * Close index reader.* <br>Other side effects: index reader in perfRunData is nullified.* <br>This would cause read related tasks to reopen their own reader.- */-public class CloseReaderTask extends PerfTask {-- public CloseReaderTask(PerfRunData runData) {- super(runData);- }-- public int doLogic() throws IOException {- IndexReader reader= getRunData().getIndexReader();- if (reader!=null) {- reader.close();- }- getRunData().setIndexReader(null);- return 1;- }--}+ */+public class CloseReaderTask extends PerfTask {++ public CloseReaderTask(PerfRunData runData) {+ super(runData);+ }++ public int doLogic() throws IOException {+ IndexReader reader= getRunData().getIndexReader();+ if (reader!=null) {+ reader.close();+ }+ getRunData().setIndexReader(null);+ return 1;+ }++}diff --git a/contrib/benchmark/src/java/org/apache/lucene/benchmark/byTask/tasks/CreateIndexTask.java b/contrib/benchmark/src/java/org/apache/lucene/benchmark/byTask/tasks/CreateIndexTask.javaindex d74dc3c4d07..4a7b1b72b83 100644--- a/contrib/benchmark/src/java/org/apache/lucene/benchmark/byTask/tasks/CreateIndexTask.java+++ b/contrib/benchmark/src/java/org/apache/lucene/benchmark/byTask/tasks/CreateIndexTask.java@@ -1,60 +1,60 @@-package org.apache.lucene.benchmark.byTask.tasks;--/**- * 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.io.IOException;--import org.apache.lucene.analysis.Analyzer;-import org.apache.lucene.index.IndexWriter;-import org.apache.lucene.store.Directory;-import org.apache.lucene.benchmark.byTask.PerfRunData;-import org.apache.lucene.benchmark.byTask.utils.Config;---/**- * Create an index.+package org.apache.lucene.benchmark.byTask.tasks;++/**+ * 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.io.IOException;++import org.apache.lucene.analysis.Analyzer;+import org.apache.lucene.index.IndexWriter;+import org.apache.lucene.store.Directory;+import org.apache.lucene.benchmark.byTask.PerfRunData;+import org.apache.lucene.benchmark.byTask.utils.Config;+++/**+ * Create an index.* <br>Other side effects: index writer object in perfRunData is set.* <br>Relevant properties: <code>merge.factor , max.buffered</code>.- */-public class CreateIndexTask extends PerfTask {-- public CreateIndexTask(PerfRunData runData) {- super(runData);- }-- public int doLogic() throws IOException {- Directory dir = getRunData().getDirectory();- Analyzer analyzer = getRunData().getAnalyzer();-- IndexWriter iw = new IndexWriter(dir, analyzer, true);-- Config config = getRunData().getConfig();-- boolean cmpnd = config.get("compound",true);+ */+public class CreateIndexTask extends PerfTask {++ public CreateIndexTask(PerfRunData runData) {+ super(runData);+ }++ public int doLogic() throws IOException {+ Directory dir = getRunData().getDirectory();+ Analyzer analyzer = getRunData().getAnalyzer();++ IndexWriter iw = new IndexWriter(dir, analyzer, true);++ Config config = getRunData().getConfig();++ boolean cmpnd = config.get("compound",true);int mrgf = config.get("merge.factor",OpenIndexTask.DEFAULT_MERGE_PFACTOR);int mxbf = config.get("max.buffered",OpenIndexTask.DEFAULT_MAX_BUFFERED);-- iw.setUseCompoundFile(cmpnd);- iw.setMergeFactor(mrgf);- iw.setMaxBufferedDocs(mxbf);-- getRunData().setIndexWriter(iw);- return 1;- }--}++ iw.setUseCompoundFile(cmpnd);+ iw.setMergeFactor(mrgf);+ iw.setMaxBufferedDocs(mxbf);++ getRunData().setIndexWriter(iw);+ return 1;+ }++}diff --git a/contrib/benchmark/src/java/org/apache/lucene/benchmark/byTask/tasks/DeleteDocTask.java b/contrib/benchmark/src/java/org/apache/lucene/benchmark/byTask/tasks/DeleteDocTask.javaindex 9311ed0260d..a601dc2b0f7 100644--- a/contrib/benchmark/src/java/org/apache/lucene/benchmark/byTask/tasks/DeleteDocTask.java+++ b/contrib/benchmark/src/java/org/apache/lucene/benchmark/byTask/tasks/DeleteDocTask.java@@ -1,33 +1,33 @@-package org.apache.lucene.benchmark.byTask.tasks;--import org.apache.lucene.benchmark.byTask.PerfRunData;--/**- * 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.- */--/**- * Delete a document by docid.+package org.apache.lucene.benchmark.byTask.tasks;++import org.apache.lucene.benchmark.byTask.PerfRunData;++/**+ * 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.+ */++/**+ * Delete a document by docid.* <br>Other side effects: none.* <br>Relevant properties: <code>doc.delete.log.step , doc.delete.step</code>.* <br>If no docid param is supplied, deletes doc with <code>id = last-deleted-doc + doc.delete.step</code>.* <br>Takes optional param: document id.- */-public class DeleteDocTask extends PerfTask {-+ */+public class DeleteDocTask extends PerfTask {+/*** Gap between ids of deleted docs, applies when no docid param is provided.*/@@ -39,63 +39,63 @@ public class DeleteDocTask extends PerfTask {*/public static final int DEFAULT_DELETE_DOC_LOG_STEP = 500;- public DeleteDocTask(PerfRunData runData) {- super(runData);- }-- private static int logStep = -1;- private static int deleteStep = -1;- private static int numDeleted = 0;- private static int lastDeleted = -1;-- private int docid = -1;- private boolean byStep = true;-- public int doLogic() throws Exception {- getRunData().getIndexReader().deleteDocument(docid);- lastDeleted = docid;- return 1; // one work item done here- }-- /* (non-Javadoc)- * @see org.apache.lucene.benchmark.byTask.tasks.PerfTask#setup()- */- public void setup() throws Exception {- super.setup();- // one time static initializations- if (logStep<0) {+ public DeleteDocTask(PerfRunData runData) {+ super(runData);+ }++ private static int logStep = -1;+ private static int deleteStep = -1;+ private static int numDeleted = 0;+ private static int lastDeleted = -1;++ private int docid = -1;+ private boolean byStep = true;++ public int doLogic() throws Exception {+ getRunData().getIndexReader().deleteDocument(docid);+ lastDeleted = docid;+ return 1; // one work item done here+ }++ /* (non-Javadoc)+ * @see org.apache.lucene.benchmark.byTask.tasks.PerfTask#setup()+ */+ public void setup() throws Exception {+ super.setup();+ // one time static initializations+ if (logStep<0) {logStep = getRunData().getConfig().get("doc.delete.log.step",DEFAULT_DELETE_DOC_LOG_STEP);- }- if (deleteStep<0) {+ }+ if (deleteStep<0) {deleteStep = getRunData().getConfig().get("doc.delete.step",DEFAULT_DOC_DELETE_STEP);- }- // set the docid to be deleted- docid = (byStep ? lastDeleted + deleteStep : docid);- }-- /* (non-Javadoc)- * @see PerfTask#tearDown()- */- public void tearDown() throws Exception {- log(++numDeleted);- super.tearDown();- }-- private void log (int count) {- if (logStep>0 && (count%logStep)==0) {+ }+ // set the docid to be deleted+ docid = (byStep ? lastDeleted + deleteStep : docid);+ }++ /* (non-Javadoc)+ * @see PerfTask#tearDown()+ */+ public void tearDown() throws Exception {+ log(++numDeleted);+ super.tearDown();+ }++ private void log (int count) {+ if (logStep>0 && (count%logStep)==0) {System.out.println("--> processed (delete) "+count+" docs, last deleted: "+lastDeleted);- }- }-- /**- * Set the params (docid only)- * @param params docid to delete, or -1 for deleting by delete gap settings.- */- public void setParams(String params) {- super.setParams(params);- docid = (int) Float.parseFloat(params);- byStep = (docid < 0);- }+ }+ }++ /**+ * Set the params (docid only)+ * @param params docid to delete, or -1 for deleting by delete gap settings.+ */+ public void setParams(String params) {+ super.setParams(params);+ docid = (int) Float.parseFloat(params);+ byStep = (docid < 0);+ }/* (non-Javadoc)* @see org.apache.lucene.benchmark.byTask.tasks.PerfTask#supportsParams()@@ -103,5 +103,5 @@ public class DeleteDocTask extends PerfTask {public boolean supportsParams() {return true;}--}++}diff --git a/contrib/benchmark/src/java/org/apache/lucene/benchmark/byTask/tasks/NewRoundTask.java b/contrib/benchmark/src/java/org/apache/lucene/benchmark/byTask/tasks/NewRoundTask.javaindex 8d50d8ef4c2..826d3471689 100644--- a/contrib/benchmark/src/java/org/apache/lucene/benchmark/byTask/tasks/NewRoundTask.java+++ b/contrib/benchmark/src/java/org/apache/lucene/benchmark/byTask/tasks/NewRoundTask.java@@ -1,44 +1,44 @@-package org.apache.lucene.benchmark.byTask.tasks;--import org.apache.lucene.benchmark.byTask.PerfRunData;--/**- * 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.- */---/**- * Increment the counter for properties maintained by Round Number.+package org.apache.lucene.benchmark.byTask.tasks;++import org.apache.lucene.benchmark.byTask.PerfRunData;++/**+ * 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.+ */+++/**+ * Increment the counter for properties maintained by Round Number.* <br>Other side effects: if there are props by round number, log value change.- */-public class NewRoundTask extends PerfTask {-- public NewRoundTask(PerfRunData runData) {- super(runData);- }-- public int doLogic() throws Exception {- getRunData().getConfig().newRound();- return 0;- }-- /* (non-Javadoc)- * @see PerfTask#shouldNotRecordStats()- */- protected boolean shouldNotRecordStats() {- return true;- }-}+ */+public class NewRoundTask extends PerfTask {++ public NewRoundTask(PerfRunData runData) {+ super(runData);+ }++ public int doLogic() throws Exception {+ getRunData().getConfig().newRound();+ return 0;+ }++ /* (non-Javadoc)+ * @see PerfTask#shouldNotRecordStats()+ */+ protected boolean shouldNotRecordStats() {+ return true;+ }+}diff --git a/contrib/benchmark/src/java/org/apache/lucene/benchmark/byTask/tasks/OpenIndexTask.java b/contrib/benchmark/src/java/org/apache/lucene/benchmark/byTask/tasks/OpenIndexTask.javaindex 6422e39a06d..a224e685f13 100644--- a/contrib/benchmark/src/java/org/apache/lucene/benchmark/byTask/tasks/OpenIndexTask.java+++ b/contrib/benchmark/src/java/org/apache/lucene/benchmark/byTask/tasks/OpenIndexTask.java@@ -1,63 +1,63 @@-package org.apache.lucene.benchmark.byTask.tasks;--/**- * 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.io.IOException;--import org.apache.lucene.analysis.Analyzer;-import org.apache.lucene.index.IndexWriter;-import org.apache.lucene.store.Directory;-import org.apache.lucene.benchmark.byTask.PerfRunData;-import org.apache.lucene.benchmark.byTask.utils.Config;---/**- * Open an index writer.+package org.apache.lucene.benchmark.byTask.tasks;++/**+ * 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.io.IOException;++import org.apache.lucene.analysis.Analyzer;+import org.apache.lucene.index.IndexWriter;+import org.apache.lucene.store.Directory;+import org.apache.lucene.benchmark.byTask.PerfRunData;+import org.apache.lucene.benchmark.byTask.utils.Config;+++/**+ * Open an index writer.* <br>Other side effects: index writer object in perfRunData is set.* <br>Relevant properties: <code>merge.factor , max.buffered</code>.- */-public class OpenIndexTask extends PerfTask {-+ */+public class OpenIndexTask extends PerfTask {+public static final int DEFAULT_MAX_BUFFERED = 10;public static final int DEFAULT_MERGE_PFACTOR = 10;- public OpenIndexTask(PerfRunData runData) {- super(runData);- }-- public int doLogic() throws IOException {- Directory dir = getRunData().getDirectory();- Analyzer analyzer = getRunData().getAnalyzer();- IndexWriter writer = new IndexWriter(dir, analyzer, false);-- Config config = getRunData().getConfig();-- boolean cmpnd = config.get("compound",true);+ public OpenIndexTask(PerfRunData runData) {+ super(runData);+ }++ public int doLogic() throws IOException {+ Directory dir = getRunData().getDirectory();+ Analyzer analyzer = getRunData().getAnalyzer();+ IndexWriter writer = new IndexWriter(dir, analyzer, false);++ Config config = getRunData().getConfig();++ boolean cmpnd = config.get("compound",true);int mrgf = config.get("merge.factor",DEFAULT_MERGE_PFACTOR);int mxbf = config.get("max.buffered",DEFAULT_MAX_BUFFERED);-- // must update params for newly opened writer- writer.setMaxBufferedDocs(mxbf);- writer.setMergeFactor(mrgf);- writer.setUseCompoundFile(cmpnd); // this one redundant?-- getRunData().setIndexWriter(writer);- return 1;- }--}++ // must update params for newly opened writer+ writer.setMaxBufferedDocs(mxbf);+ writer.setMergeFactor(mrgf);+ writer.setUseCompoundFile(cmpnd); // this one redundant?++ getRunData().setIndexWriter(writer);+ return 1;+ }++}diff --git a/contrib/benchmark/src/java/org/apache/lucene/benchmark/byTask/tasks/OpenReaderTask.java b/contrib/benchmark/src/java/org/apache/lucene/benchmark/byTask/tasks/OpenReaderTask.javaindex a11358f9d3f..fcef25ea91c 100644--- a/contrib/benchmark/src/java/org/apache/lucene/benchmark/byTask/tasks/OpenReaderTask.java+++ b/contrib/benchmark/src/java/org/apache/lucene/benchmark/byTask/tasks/OpenReaderTask.java@@ -1,43 +1,43 @@-package org.apache.lucene.benchmark.byTask.tasks;--/**- * 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.io.IOException;--import org.apache.lucene.benchmark.byTask.PerfRunData;-import org.apache.lucene.index.IndexReader;-import org.apache.lucene.store.Directory;--/**- * Open an index reader.+package org.apache.lucene.benchmark.byTask.tasks;++/**+ * 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.io.IOException;++import org.apache.lucene.benchmark.byTask.PerfRunData;+import org.apache.lucene.index.IndexReader;+import org.apache.lucene.store.Directory;++/**+ * Open an index reader.* <br>Other side effects: index redaer object in perfRunData is set.- */-public class OpenReaderTask extends PerfTask {-- public OpenReaderTask(PerfRunData runData) {- super(runData);- }-- public int doLogic() throws IOException {- Directory dir = getRunData().getDirectory();- IndexReader reader = IndexReader.open(dir);- getRunData().setIndexReader(reader);- return 1;- }--}+ */+public class OpenReaderTask extends PerfTask {++ public OpenReaderTask(PerfRunData runData) {+ super(runData);+ }++ public int doLogic() throws IOException {+ Directory dir = getRunData().getDirectory();+ IndexReader reader = IndexReader.open(dir);+ getRunData().setIndexReader(reader);+ return 1;+ }++}diff --git a/contrib/benchmark/src/java/org/apache/lucene/benchmark/byTask/tasks/OptimizeTask.java b/contrib/benchmark/src/java/org/apache/lucene/benchmark/byTask/tasks/OptimizeTask.javaindex 704765b712b..c6a459d23bb 100644--- a/contrib/benchmark/src/java/org/apache/lucene/benchmark/byTask/tasks/OptimizeTask.java+++ b/contrib/benchmark/src/java/org/apache/lucene/benchmark/byTask/tasks/OptimizeTask.java@@ -1,40 +1,40 @@-package org.apache.lucene.benchmark.byTask.tasks;--/**- * 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 org.apache.lucene.benchmark.byTask.PerfRunData;-import org.apache.lucene.index.IndexWriter;--/**- * Optimize the index.+package org.apache.lucene.benchmark.byTask.tasks;++/**+ * 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 org.apache.lucene.benchmark.byTask.PerfRunData;+import org.apache.lucene.index.IndexWriter;++/**+ * Optimize the index.* <br>Other side effects: none.- */-public class OptimizeTask extends PerfTask {-- public OptimizeTask(PerfRunData runData) {- super(runData);- }-- public int doLogic() throws Exception {- IndexWriter iw = getRunData().getIndexWriter();- iw.optimize();- //System.out.println("optimize called");- return 1;- }--}+ */+public class OptimizeTask extends PerfTask {++ public OptimizeTask(PerfRunData runData) {+ super(runData);+ }++ public int doLogic() throws Exception {+ IndexWriter iw = getRunData().getIndexWriter();+ iw.optimize();+ //System.out.println("optimize called");+ return 1;+ }++}diff --git a/contrib/benchmark/src/java/org/apache/lucene/benchmark/byTask/tasks/PerfTask.java b/contrib/benchmark/src/java/org/apache/lucene/benchmark/byTask/tasks/PerfTask.javaindex 0a17fb18fda..685cee6ef5c 100644--- a/contrib/benchmark/src/java/org/apache/lucene/benchmark/byTask/tasks/PerfTask.java+++ b/contrib/benchmark/src/java/org/apache/lucene/benchmark/byTask/tasks/PerfTask.java@@ -1,230 +1,230 @@-package org.apache.lucene.benchmark.byTask.tasks;--/**- * 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 org.apache.lucene.benchmark.byTask.PerfRunData;-import org.apache.lucene.benchmark.byTask.stats.Points;-import org.apache.lucene.benchmark.byTask.stats.TaskStats;-import org.apache.lucene.benchmark.byTask.utils.Format;--/**- * A (abstract) task to be tested for performance.- * <br>- * Every performance task extends this class, and provides its own doLogic() method,- * which performss the actual task.- * <br>- * Tasks performing some work that should be measured for the task, can overide setup() and/or tearDown() and- * placed that work there.- * <br>- * Relevant properties: <code>task.max.depth.log</code>.- */-public abstract class PerfTask implements Cloneable {-- private PerfRunData runData;-- // propeties that all tasks have- private String name;- private int depth = 0;- private int maxDepthLogStart = 0;- protected String params = null;-- protected static final String NEW_LINE = System.getProperty("line.separator");-- /**- * Should not be used externally- */- private PerfTask() {- name = Format.simpleName(getClass());- if (name.endsWith("Task")) {- name = name.substring(0,name.length()-4);- }- }-- public PerfTask(PerfRunData runData) {- this();- this.runData = runData;- this.maxDepthLogStart = runData.getConfig().get("task.max.depth.log",0);- }-- /* (non-Javadoc)- * @see java.lang.Object#clone()- */- protected Object clone() throws CloneNotSupportedException {- // tasks having non primitive data structures should overide this.- // otherwise parallel running of a task sequence might not run crrectly.- return super.clone();- }-- /**- * Run the task, record statistics.- * @return number of work items done by this task.- */- public final int runAndMaybeStats(boolean reportStats) throws Exception {- if (reportStats && depth <= maxDepthLogStart && !shouldNeverLogAtStart()) {- System.out.println("------------> starting task: " + getName());- }- if (shouldNotRecordStats() || !reportStats) {- setup();- int count = doLogic();- tearDown();- return count;- }- setup();- Points pnts = runData.getPoints();- TaskStats ts = pnts.markTaskStart(this,runData.getConfig().getRoundNumber());- int count = doLogic();- pnts.markTaskEnd(ts, count);- tearDown();- return count;- }-- /**- * Perform the task once (ignoring repetions specification)- * Return number of work items done by this task.- * For indexing that can be number of docs added.- * For warming that can be number of scanned items, etc.- * @return number of work items done by this task.- */- public abstract int doLogic() throws Exception;-- /**- * @return Returns the name.- */- public String getName() {- if (params==null) {- return name;- }- return new StringBuffer(name).append('(').append(params).append(')').toString();- }-- /**- * @param name The name to set.- */- protected void setName(String name) {- this.name = name;- }-- /**- * @return Returns the run data.- */- public PerfRunData getRunData() {- return runData;- }-- /**- * @return Returns the depth.- */- public int getDepth() {- return depth;- }-- /**- * @param depth The depth to set.- */- public void setDepth(int depth) {- this.depth = depth;- }-- // compute a blank string padding for printing this task indented by its depth- String getPadding () {- char c[] = new char[4*getDepth()];- for (int i = 0; i < c.length; i++) c[i] = ' ';- return new String(c);- }-- /* (non-Javadoc)- * @see java.lang.Object#toString()- */- public String toString() {- String padd = getPadding();- StringBuffer sb = new StringBuffer(padd);- sb.append(getName());- return sb.toString();- }-- /**- * @return Returns the maxDepthLogStart.- */- int getMaxDepthLogStart() {- return maxDepthLogStart;- }-- /**- * Tasks that should never log at start can overide this.- * @return true if this task should never log when it start.- */- protected boolean shouldNeverLogAtStart () {- return false;- }-- /**- * Tasks that should not record statistics can overide this.- * @return true if this task should never record its statistics.- */- protected boolean shouldNotRecordStats () {- return false;- }-- /**- * Task setup work that should not be measured for that specific task.- * By default it does nothing, but tasks can implement this, moving work from- * doLogic() to this method. Only the work done in doLogicis measured for this task.- * Notice that higher level (sequence) tasks containing this task would then- * measure larger time than the sum of their contained tasks.- * @throws Exception- */- public void setup () throws Exception {- }-- /**- * Task tearDown work that should not be measured for that specific task.- * By default it does nothing, but tasks can implement this, moving work from- * doLogic() to this method. Only the work done in doLogicis measured for this task.- * Notice that higher level (sequence) tasks containing this task would then- * measure larger time than the sum of their contained tasks.- */- public void tearDown () throws Exception {- }-- /**- * Sub classes that supports parameters must overide this method to return true.- * @return true iff this task supports command line params.- */- public boolean supportsParams () {- return false;- }-- /**- * Set the params of this task.- * @exception UnsupportedOperationException for tasks supporting command line parameters.- */- public void setParams(String params) {- if (!supportsParams()) {- throw new UnsupportedOperationException(getName()+" does not support command line parameters.");- }- this.params = params;- }-- /**- * @return Returns the Params.- */- public String getParams() {- return params;- }--}+package org.apache.lucene.benchmark.byTask.tasks;++/**+ * 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 org.apache.lucene.benchmark.byTask.PerfRunData;+import org.apache.lucene.benchmark.byTask.stats.Points;+import org.apache.lucene.benchmark.byTask.stats.TaskStats;+import org.apache.lucene.benchmark.byTask.utils.Format;++/**+ * A (abstract) task to be tested for performance.+ * <br>+ * Every performance task extends this class, and provides its own doLogic() method,+ * which performss the actual task.+ * <br>+ * Tasks performing some work that should be measured for the task, can overide setup() and/or tearDown() and+ * placed that work there.+ * <br>+ * Relevant properties: <code>task.max.depth.log</code>.+ */+public abstract class PerfTask implements Cloneable {++ private PerfRunData runData;++ // propeties that all tasks have+ private String name;+ private int depth = 0;+ private int maxDepthLogStart = 0;+ protected String params = null;++ protected static final String NEW_LINE = System.getProperty("line.separator");++ /**+ * Should not be used externally+ */+ private PerfTask() {+ name = Format.simpleName(getClass());+ if (name.endsWith("Task")) {+ name = name.substring(0,name.length()-4);+ }+ }++ public PerfTask(PerfRunData runData) {+ this();+ this.runData = runData;+ this.maxDepthLogStart = runData.getConfig().get("task.max.depth.log",0);+ }++ /* (non-Javadoc)+ * @see java.lang.Object#clone()+ */+ protected Object clone() throws CloneNotSupportedException {+ // tasks having non primitive data structures should overide this.+ // otherwise parallel running of a task sequence might not run crrectly.+ return super.clone();+ }++ /**+ * Run the task, record statistics.+ * @return number of work items done by this task.+ */+ public final int runAndMaybeStats(boolean reportStats) throws Exception {+ if (reportStats && depth <= maxDepthLogStart && !shouldNeverLogAtStart()) {+ System.out.println("------------> starting task: " + getName());+ }+ if (shouldNotRecordStats() || !reportStats) {+ setup();+ int count = doLogic();+ tearDown();+ return count;+ }+ setup();+ Points pnts = runData.getPoints();+ TaskStats ts = pnts.markTaskStart(this,runData.getConfig().getRoundNumber());+ int count = doLogic();+ pnts.markTaskEnd(ts, count);+ tearDown();+ return count;+ }++ /**+ * Perform the task once (ignoring repetions specification)+ * Return number of work items done by this task.+ * For indexing that can be number of docs added.+ * For warming that can be number of scanned items, etc.+ * @return number of work items done by this task.+ */+ public abstract int doLogic() throws Exception;++ /**+ * @return Returns the name.+ */+ public String getName() {+ if (params==null) {+ return name;+ }+ return new StringBuffer(name).append('(').append(params).append(')').toString();+ }++ /**+ * @param name The name to set.+ */+ protected void setName(String name) {+ this.name = name;+ }++ /**+ * @return Returns the run data.+ */+ public PerfRunData getRunData() {+ return runData;+ }++ /**+ * @return Returns the depth.+ */+ public int getDepth() {+ return depth;+ }++ /**+ * @param depth The depth to set.+ */+ public void setDepth(int depth) {+ this.depth = depth;+ }++ // compute a blank string padding for printing this task indented by its depth+ String getPadding () {+ char c[] = new char[4*getDepth()];+ for (int i = 0; i < c.length; i++) c[i] = ' ';+ return new String(c);+ }++ /* (non-Javadoc)+ * @see java.lang.Object#toString()+ */+ public String toString() {+ String padd = getPadding();+ StringBuffer sb = new StringBuffer(padd);+ sb.append(getName());+ return sb.toString();+ }++ /**+ * @return Returns the maxDepthLogStart.+ */+ int getMaxDepthLogStart() {+ return maxDepthLogStart;+ }++ /**+ * Tasks that should never log at start can overide this.+ * @return true if this task should never log when it start.+ */+ protected boolean shouldNeverLogAtStart () {+ return false;+ }++ /**+ * Tasks that should not record statistics can overide this.+ * @return true if this task should never record its statistics.+ */+ protected boolean shouldNotRecordStats () {+ return false;+ }++ /**+ * Task setup work that should not be measured for that specific task.+ * By default it does nothing, but tasks can implement this, moving work from+ * doLogic() to this method. Only the work done in doLogicis measured for this task.+ * Notice that higher level (sequence) tasks containing this task would then+ * measure larger time than the sum of their contained tasks.+ * @throws Exception+ */+ public void setup () throws Exception {+ }++ /**+ * Task tearDown work that should not be measured for that specific task.+ * By default it does nothing, but tasks can implement this, moving work from+ * doLogic() to this method. Only the work done in doLogicis measured for this task.+ * Notice that higher level (sequence) tasks containing this task would then+ * measure larger time than the sum of their contained tasks.+ */+ public void tearDown () throws Exception {+ }++ /**+ * Sub classes that supports parameters must overide this method to return true.+ * @return true iff this task supports command line params.+ */+ public boolean supportsParams () {+ return false;+ }++ /**+ * Set the params of this task.+ * @exception UnsupportedOperationException for tasks supporting command line parameters.+ */+ public void setParams(String params) {+ if (!supportsParams()) {+ throw new UnsupportedOperationException(getName()+" does not support command line parameters.");+ }+ this.params = params;+ }++ /**+ * @return Returns the Params.+ */+ public String getParams() {+ return params;+ }++}diff --git a/contrib/benchmark/src/java/org/apache/lucene/benchmark/byTask/tasks/ReadTask.java b/contrib/benchmark/src/java/org/apache/lucene/benchmark/byTask/tasks/ReadTask.javaindex 653c51b6283..71ec5af64d3 100644--- a/contrib/benchmark/src/java/org/apache/lucene/benchmark/byTask/tasks/ReadTask.java+++ b/contrib/benchmark/src/java/org/apache/lucene/benchmark/byTask/tasks/ReadTask.java@@ -1,144 +1,144 @@-package org.apache.lucene.benchmark.byTask.tasks;--/**- * 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 org.apache.lucene.benchmark.byTask.PerfRunData;-import org.apache.lucene.benchmark.byTask.feeds.QueryMaker;-import org.apache.lucene.document.Document;-import org.apache.lucene.index.IndexReader;-import org.apache.lucene.search.Hits;-import org.apache.lucene.search.IndexSearcher;-import org.apache.lucene.search.Query;-import org.apache.lucene.store.Directory;--import java.io.IOException;---/**- * Read index (abstract) task.- * Sub classes implement withSearch(), withWarm(), withTraverse() and withRetrieve()- * methods to configure the actual action.- *- * <p>Note: All ReadTasks reuse the reader if it is already open.- * Otherwise a reader is opened at start and closed at the end.- *- * <p>Other side effects: none.- */-public abstract class ReadTask extends PerfTask {-- public ReadTask(PerfRunData runData) {- super(runData);- }-- public int doLogic() throws Exception {- int res = 0;- boolean closeReader = false;-- // open reader or use existing one- IndexReader ir = getRunData().getIndexReader();- if (ir == null) {- Directory dir = getRunData().getDirectory();- ir = IndexReader.open(dir);- closeReader = true;- //res++; //this is confusing, comment it out- }-- // optionally warm and add num docs traversed to count- if (withWarm()) {- Document doc = null;- for (int m = 0; m < ir.maxDoc(); m++) {- if (!ir.isDeleted(m)) {- doc = ir.document(m);- res += (doc==null ? 0 : 1);- }- }- }-- if (withSearch()) {- res++;- IndexSearcher searcher = new IndexSearcher(ir);- QueryMaker queryMaker = getQueryMaker();- Query q = queryMaker.makeQuery();- Hits hits = searcher.search(q);- //System.out.println("searched: "+q);-- if (withTraverse() && hits!=null) {- int traversalSize = Math.min(hits.length(), traversalSize());- if (traversalSize > 0) {- boolean retrieve = withRetrieve();- for (int m = 0; m < hits.length(); m++) {- int id = hits.id(m);- res++;- if (retrieve) {- res += retrieveDoc(ir, id);- }- }- }- }-- searcher.close();- }-- if (closeReader) {- ir.close();- }- return res;- }-- protected int retrieveDoc(IndexReader ir, int id) throws IOException {- return (ir.document(id) == null ? 0 : 1);- }-- /**- * Return query maker used for this task.- */- public abstract QueryMaker getQueryMaker();-- /**- * Return true if search should be performed.- */- public abstract boolean withSearch ();-- /**- * Return true if warming should be performed.- */- public abstract boolean withWarm ();-- /**- * Return true if, with search, results should be traversed.- */- public abstract boolean withTraverse ();-- /**- * Specify the number of hits to traverse. Tasks should override this if they want to restrict the number- * of hits that are traversed when {@link #withTraverse()} is true. Must be greater than 0.- *- * Read task calculates the traversal as: Math.min(hits.length(), traversalSize())- * @return Integer.MAX_VALUE- */- public int traversalSize()- {- return Integer.MAX_VALUE;- }-- /**- * Return true if, with search & results traversing, docs should be retrieved.- */- public abstract boolean withRetrieve ();--}+package org.apache.lucene.benchmark.byTask.tasks;++/**+ * 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 org.apache.lucene.benchmark.byTask.PerfRunData;+import org.apache.lucene.benchmark.byTask.feeds.QueryMaker;+import org.apache.lucene.document.Document;+import org.apache.lucene.index.IndexReader;+import org.apache.lucene.search.Hits;+import org.apache.lucene.search.IndexSearcher;+import org.apache.lucene.search.Query;+import org.apache.lucene.store.Directory;++import java.io.IOException;+++/**+ * Read index (abstract) task.+ * Sub classes implement withSearch(), withWarm(), withTraverse() and withRetrieve()+ * methods to configure the actual action.+ *+ * <p>Note: All ReadTasks reuse the reader if it is already open.+ * Otherwise a reader is opened at start and closed at the end.+ *+ * <p>Other side effects: none.+ */+public abstract class ReadTask extends PerfTask {++ public ReadTask(PerfRunData runData) {+ super(runData);+ }++ public int doLogic() throws Exception {+ int res = 0;+ boolean closeReader = false;++ // open reader or use existing one+ IndexReader ir = getRunData().getIndexReader();+ if (ir == null) {+ Directory dir = getRunData().getDirectory();+ ir = IndexReader.open(dir);+ closeReader = true;+ //res++; //this is confusing, comment it out+ }++ // optionally warm and add num docs traversed to count+ if (withWarm()) {+ Document doc = null;+ for (int m = 0; m < ir.maxDoc(); m++) {+ if (!ir.isDeleted(m)) {+ doc = ir.document(m);+ res += (doc==null ? 0 : 1);+ }+ }+ }++ if (withSearch()) {+ res++;+ IndexSearcher searcher = new IndexSearcher(ir);+ QueryMaker queryMaker = getQueryMaker();+ Query q = queryMaker.makeQuery();+ Hits hits = searcher.search(q);+ //System.out.println("searched: "+q);++ if (withTraverse() && hits!=null) {+ int traversalSize = Math.min(hits.length(), traversalSize());+ if (traversalSize > 0) {+ boolean retrieve = withRetrieve();+ for (int m = 0; m < hits.length(); m++) {+ int id = hits.id(m);+ res++;+ if (retrieve) {+ res += retrieveDoc(ir, id);+ }+ }+ }+ }++ searcher.close();+ }++ if (closeReader) {+ ir.close();+ }+ return res;+ }++ protected int retrieveDoc(IndexReader ir, int id) throws IOException {+ return (ir.document(id) == null ? 0 : 1);+ }++ /**+ * Return query maker used for this task.+ */+ public abstract QueryMaker getQueryMaker();++ /**+ * Return true if search should be performed.+ */+ public abstract boolean withSearch ();++ /**+ * Return true if warming should be performed.+ */+ public abstract boolean withWarm ();++ /**+ * Return true if, with search, results should be traversed.+ */+ public abstract boolean withTraverse ();++ /**+ * Specify the number of hits to traverse. Tasks should override this if they want to restrict the number+ * of hits that are traversed when {@link #withTraverse()} is true. Must be greater than 0.+ *+ * Read task calculates the traversal as: Math.min(hits.length(), traversalSize())+ * @return Integer.MAX_VALUE+ */+ public int traversalSize()+ {+ return Integer.MAX_VALUE;+ }++ /**+ * Return true if, with search & results traversing, docs should be retrieved.+ */+ public abstract boolean withRetrieve ();++}diff --git a/contrib/benchmark/src/java/org/apache/lucene/benchmark/byTask/tasks/RepAllTask.java b/contrib/benchmark/src/java/org/apache/lucene/benchmark/byTask/tasks/RepAllTask.javaindex 0eb7b89bda0..a1e923979a0 100644--- a/contrib/benchmark/src/java/org/apache/lucene/benchmark/byTask/tasks/RepAllTask.java+++ b/contrib/benchmark/src/java/org/apache/lucene/benchmark/byTask/tasks/RepAllTask.java@@ -1,48 +1,48 @@-package org.apache.lucene.benchmark.byTask.tasks;--/**- * 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.lucene.benchmark.byTask.tasks;++/**+ * 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.Iterator;import java.util.List;-import org.apache.lucene.benchmark.byTask.PerfRunData;-import org.apache.lucene.benchmark.byTask.stats.Report;+import org.apache.lucene.benchmark.byTask.PerfRunData;+import org.apache.lucene.benchmark.byTask.stats.Report;import org.apache.lucene.benchmark.byTask.stats.TaskStats;--/**- * Report all statistics with no aggregations.++/**+ * Report all statistics with no aggregations.* <br>Other side effects: None.- */-public class RepAllTask extends ReportTask {-- public RepAllTask(PerfRunData runData) {- super(runData);- }-- public int doLogic() throws Exception {+ */+public class RepAllTask extends ReportTask {++ public RepAllTask(PerfRunData runData) {+ super(runData);+ }++ public int doLogic() throws Exception {Report rp = reportAll(getRunData().getPoints().taskStats());-- System.out.println();- System.out.println("------------> Report All ("+rp.getSize()+" out of "+rp.getOutOf()+")");- System.out.println(rp.getText());- System.out.println();- return 0;- }++ System.out.println();+ System.out.println("------------> Report All ("+rp.getSize()+" out of "+rp.getOutOf()+")");+ System.out.println(rp.getText());+ System.out.println();+ return 0;+ }/*** Report detailed statistics as a string@@ -74,5 +74,5 @@ public class RepAllTask extends ReportTask {String reptxt = (reported==0 ? "No Matching Entries Were Found!" : sb.toString());return new Report(reptxt,reported,reported,taskStats.size());}--}++}diff --git a/contrib/benchmark/src/java/org/apache/lucene/benchmark/byTask/tasks/RepSelectByPrefTask.java b/contrib/benchmark/src/java/org/apache/lucene/benchmark/byTask/tasks/RepSelectByPrefTask.javaindex 2e6f4ffd96b..9dc5a6d4595 100644--- a/contrib/benchmark/src/java/org/apache/lucene/benchmark/byTask/tasks/RepSelectByPrefTask.java+++ b/contrib/benchmark/src/java/org/apache/lucene/benchmark/byTask/tasks/RepSelectByPrefTask.java@@ -1,50 +1,50 @@-package org.apache.lucene.benchmark.byTask.tasks;--/**- * 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.lucene.benchmark.byTask.tasks;++/**+ * 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.Iterator;import java.util.List;-import org.apache.lucene.benchmark.byTask.PerfRunData;-import org.apache.lucene.benchmark.byTask.stats.Report;+import org.apache.lucene.benchmark.byTask.PerfRunData;+import org.apache.lucene.benchmark.byTask.stats.Report;import org.apache.lucene.benchmark.byTask.stats.TaskStats;--/**- * Report by-name-prefix statistics with no aggregations.++/**+ * Report by-name-prefix statistics with no aggregations.* <br>Other side effects: None.- */-public class RepSelectByPrefTask extends RepSumByPrefTask {-- public RepSelectByPrefTask(PerfRunData runData) {- super(runData);- }-- public int doLogic() throws Exception {+ */+public class RepSelectByPrefTask extends RepSumByPrefTask {++ public RepSelectByPrefTask(PerfRunData runData) {+ super(runData);+ }++ public int doLogic() throws Exception {Report rp = reportSelectByPrefix(getRunData().getPoints().taskStats());-- System.out.println();- System.out.println("------------> Report Select By Prefix ("+prefix+") ("+- rp.getSize()+" about "+rp.getReported()+" out of "+rp.getOutOf()+")");- System.out.println(rp.getText());- System.out.println();-- return 0;- }++ System.out.println();+ System.out.println("------------> Report Select By Prefix ("+prefix+") ("++ rp.getSize()+" about "+rp.getReported()+" out of "+rp.getOutOf()+")");+ System.out.println(rp.getText());+ System.out.println();++ return 0;+ }protected Report reportSelectByPrefix(List taskStats) {String longestOp = longestOp(taskStats.iterator());@@ -72,4 +72,4 @@ public class RepSelectByPrefTask extends RepSumByPrefTask {return new Report(reptxt,reported,reported, taskStats.size());}-}+}diff --git a/contrib/benchmark/src/java/org/apache/lucene/benchmark/byTask/tasks/RepSumByNameRoundTask.java b/contrib/benchmark/src/java/org/apache/lucene/benchmark/byTask/tasks/RepSumByNameRoundTask.javaindex 159056f2444..6491c0305c0 100644--- a/contrib/benchmark/src/java/org/apache/lucene/benchmark/byTask/tasks/RepSumByNameRoundTask.java+++ b/contrib/benchmark/src/java/org/apache/lucene/benchmark/byTask/tasks/RepSumByNameRoundTask.java@@ -1,52 +1,52 @@-package org.apache.lucene.benchmark.byTask.tasks;--/**- * 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.lucene.benchmark.byTask.tasks;++/**+ * 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.Iterator;import java.util.LinkedHashMap;import java.util.List;-import org.apache.lucene.benchmark.byTask.PerfRunData;-import org.apache.lucene.benchmark.byTask.stats.Report;+import org.apache.lucene.benchmark.byTask.PerfRunData;+import org.apache.lucene.benchmark.byTask.stats.Report;import org.apache.lucene.benchmark.byTask.stats.TaskStats;--/**- * Report all statistics grouped/aggregated by name and round.++/**+ * Report all statistics grouped/aggregated by name and round.* <br>Other side effects: None.- */-public class RepSumByNameRoundTask extends ReportTask {-- public RepSumByNameRoundTask(PerfRunData runData) {- super(runData);- }-- public int doLogic() throws Exception {+ */+public class RepSumByNameRoundTask extends ReportTask {++ public RepSumByNameRoundTask(PerfRunData runData) {+ super(runData);+ }++ public int doLogic() throws Exception {Report rp = reportSumByNameRound(getRunData().getPoints().taskStats());-- System.out.println();- System.out.println("------------> Report Sum By (any) Name and Round ("+- rp.getSize()+" about "+rp.getReported()+" out of "+rp.getOutOf()+")");- System.out.println(rp.getText());- System.out.println();-- return 0;- }-++ System.out.println();+ System.out.println("------------> Report Sum By (any) Name and Round ("++ rp.getSize()+" about "+rp.getReported()+" out of "+rp.getOutOf()+")");+ System.out.println(rp.getText());+ System.out.println();++ return 0;+ }+/*** Report statistics as a string, aggregate for tasks named the same, and from the same round.* @return the report@@ -78,4 +78,4 @@ public class RepSumByNameRoundTask extends ReportTask {return genPartialReport(reported, p2, taskStats.size());}-}+}diff --git a/contrib/benchmark/src/java/org/apache/lucene/benchmark/byTask/tasks/RepSumByNameTask.java b/contrib/benchmark/src/java/org/apache/lucene/benchmark/byTask/tasks/RepSumByNameTask.javaindex a8f4441a1a1..101ed4cc457 100644--- a/contrib/benchmark/src/java/org/apache/lucene/benchmark/byTask/tasks/RepSumByNameTask.java+++ b/contrib/benchmark/src/java/org/apache/lucene/benchmark/byTask/tasks/RepSumByNameTask.java@@ -1,52 +1,52 @@-package org.apache.lucene.benchmark.byTask.tasks;--/**- * 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.lucene.benchmark.byTask.tasks;++/**+ * 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.Iterator;import java.util.LinkedHashMap;import java.util.List;-import org.apache.lucene.benchmark.byTask.PerfRunData;-import org.apache.lucene.benchmark.byTask.stats.Report;+import org.apache.lucene.benchmark.byTask.PerfRunData;+import org.apache.lucene.benchmark.byTask.stats.Report;import org.apache.lucene.benchmark.byTask.stats.TaskStats;--/**- * Report all statistics aggregated by name.++/**+ * Report all statistics aggregated by name.* <br>Other side effects: None.- */-public class RepSumByNameTask extends ReportTask {-- public RepSumByNameTask(PerfRunData runData) {- super(runData);- }-- public int doLogic() throws Exception {+ */+public class RepSumByNameTask extends ReportTask {++ public RepSumByNameTask(PerfRunData runData) {+ super(runData);+ }++ public int doLogic() throws Exception {Report rp = reportSumByName(getRunData().getPoints().taskStats());-- System.out.println();- System.out.println("------------> Report Sum By (any) Name ("+- rp.getSize()+" about "+rp.getReported()+" out of "+rp.getOutOf()+")");- System.out.println(rp.getText());- System.out.println();-- return 0;- }-++ System.out.println();+ System.out.println("------------> Report Sum By (any) Name ("++ rp.getSize()+" about "+rp.getReported()+" out of "+rp.getOutOf()+")");+ System.out.println(rp.getText());+ System.out.println();++ return 0;+ }+/*** Report statistics as a string, aggregate for tasks named the same.* @return the report@@ -78,4 +78,4 @@ public class RepSumByNameTask extends ReportTask {}-}+}diff --git a/contrib/benchmark/src/java/org/apache/lucene/benchmark/byTask/tasks/RepSumByPrefRoundTask.java b/contrib/benchmark/src/java/org/apache/lucene/benchmark/byTask/tasks/RepSumByPrefRoundTask.javaindex 24c43c1f44e..72f954e5b6a 100644--- a/contrib/benchmark/src/java/org/apache/lucene/benchmark/byTask/tasks/RepSumByPrefRoundTask.java+++ b/contrib/benchmark/src/java/org/apache/lucene/benchmark/byTask/tasks/RepSumByPrefRoundTask.java@@ -1,52 +1,52 @@-package org.apache.lucene.benchmark.byTask.tasks;--/**- * 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.lucene.benchmark.byTask.tasks;++/**+ * 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.Iterator;import java.util.LinkedHashMap;import java.util.List;-import org.apache.lucene.benchmark.byTask.PerfRunData;-import org.apache.lucene.benchmark.byTask.stats.Report;+import org.apache.lucene.benchmark.byTask.PerfRunData;+import org.apache.lucene.benchmark.byTask.stats.Report;import org.apache.lucene.benchmark.byTask.stats.TaskStats;--/**- * Report all prefix matching statistics grouped/aggregated by name and round.++/**+ * Report all prefix matching statistics grouped/aggregated by name and round.* <br>Other side effects: None.- */-public class RepSumByPrefRoundTask extends RepSumByPrefTask {-- public RepSumByPrefRoundTask(PerfRunData runData) {- super(runData);- }-- public int doLogic() throws Exception {+ */+public class RepSumByPrefRoundTask extends RepSumByPrefTask {++ public RepSumByPrefRoundTask(PerfRunData runData) {+ super(runData);+ }++ public int doLogic() throws Exception {Report rp = reportSumByPrefixRound(getRunData().getPoints().taskStats());-- System.out.println();- System.out.println("------------> Report sum by Prefix ("+prefix+") and Round ("+- rp.getSize()+" about "+rp.getReported()+" out of "+rp.getOutOf()+")");- System.out.println(rp.getText());- System.out.println();-- return 0;- }-++ System.out.println();+ System.out.println("------------> Report sum by Prefix ("+prefix+") and Round ("++ rp.getSize()+" about "+rp.getReported()+" out of "+rp.getOutOf()+")");+ System.out.println(rp.getText());+ System.out.println();++ return 0;+ }+protected Report reportSumByPrefixRound(List taskStats) {// aggregate by task name and by roundint reported = 0;@@ -75,4 +75,4 @@ public class RepSumByPrefRoundTask extends RepSumByPrefTask {}-}+}diff --git a/contrib/benchmark/src/java/org/apache/lucene/benchmark/byTask/tasks/RepSumByPrefTask.java b/contrib/benchmark/src/java/org/apache/lucene/benchmark/byTask/tasks/RepSumByPrefTask.javaindex 50cc8556652..e55f688e100 100644--- a/contrib/benchmark/src/java/org/apache/lucene/benchmark/byTask/tasks/RepSumByPrefTask.java+++ b/contrib/benchmark/src/java/org/apache/lucene/benchmark/byTask/tasks/RepSumByPrefTask.java@@ -1,90 +1,90 @@-package org.apache.lucene.benchmark.byTask.tasks;--/**- * 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 org.apache.lucene.benchmark.byTask.PerfRunData;-import org.apache.lucene.benchmark.byTask.stats.Report;-import org.apache.lucene.benchmark.byTask.stats.TaskStats;--import java.util.Iterator;-import java.util.LinkedHashMap;-import java.util.List;--/**- * Report by-name-prefix statistics aggregated by name.- * <br>Other side effects: None.- */-public class RepSumByPrefTask extends ReportTask {-- public RepSumByPrefTask(PerfRunData runData) {- super(runData);- }-- protected String prefix;-- public int doLogic() throws Exception {- Report rp = reportSumByPrefix(getRunData().getPoints().taskStats());-- System.out.println();- System.out.println("------------> Report Sum By Prefix ("+prefix+") ("+- rp.getSize()+" about "+rp.getReported()+" out of "+rp.getOutOf()+")");- System.out.println(rp.getText());- System.out.println();-- return 0;- }-- protected Report reportSumByPrefix (List taskStats) {- // aggregate by task name- int reported = 0;- LinkedHashMap p2 = new LinkedHashMap();- for (Iterator it = taskStats.iterator(); it.hasNext();) {- TaskStats stat1 = (TaskStats) it.next();- if (stat1.getElapsed()>=0 && stat1.getTask().getName().startsWith(prefix)) { // only ended tasks with proper name- reported++;- String name = stat1.getTask().getName();- TaskStats stat2 = (TaskStats) p2.get(name);- if (stat2 == null) {- try {- stat2 = (TaskStats) stat1.clone();- } catch (CloneNotSupportedException e) {- throw new RuntimeException(e);- }- p2.put(name,stat2);- } else {- stat2.add(stat1);- }- }- }- // now generate report from secondary list p2- return genPartialReport(reported, p2, taskStats.size());- }--- public void setPrefix(String prefix) {- this.prefix = prefix;- }-- /* (non-Javadoc)- * @see PerfTask#toString()- */- public String toString() {- return super.toString()+" "+prefix;- }--}+package org.apache.lucene.benchmark.byTask.tasks;++/**+ * 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 org.apache.lucene.benchmark.byTask.PerfRunData;+import org.apache.lucene.benchmark.byTask.stats.Report;+import org.apache.lucene.benchmark.byTask.stats.TaskStats;++import java.util.Iterator;+import java.util.LinkedHashMap;+import java.util.List;++/**+ * Report by-name-prefix statistics aggregated by name.+ * <br>Other side effects: None.+ */+public class RepSumByPrefTask extends ReportTask {++ public RepSumByPrefTask(PerfRunData runData) {+ super(runData);+ }++ protected String prefix;++ public int doLogic() throws Exception {+ Report rp = reportSumByPrefix(getRunData().getPoints().taskStats());++ System.out.println();+ System.out.println("------------> Report Sum By Prefix ("+prefix+") ("++ rp.getSize()+" about "+rp.getReported()+" out of "+rp.getOutOf()+")");+ System.out.println(rp.getText());+ System.out.println();++ return 0;+ }++ protected Report reportSumByPrefix (List taskStats) {+ // aggregate by task name+ int reported = 0;+ LinkedHashMap p2 = new LinkedHashMap();+ for (Iterator it = taskStats.iterator(); it.hasNext();) {+ TaskStats stat1 = (TaskStats) it.next();+ if (stat1.getElapsed()>=0 && stat1.getTask().getName().startsWith(prefix)) { // only ended tasks with proper name+ reported++;+ String name = stat1.getTask().getName();+ TaskStats stat2 = (TaskStats) p2.get(name);+ if (stat2 == null) {+ try {+ stat2 = (TaskStats) stat1.clone();+ } catch (CloneNotSupportedException e) {+ throw new RuntimeException(e);+ }+ p2.put(name,stat2);+ } else {+ stat2.add(stat1);+ }+ }+ }+ // now generate report from secondary list p2+ return genPartialReport(reported, p2, taskStats.size());+ }+++ public void setPrefix(String prefix) {+ this.prefix = prefix;+ }++ /* (non-Javadoc)+ * @see PerfTask#toString()+ */+ public String toString() {+ return super.toString()+" "+prefix;+ }++}diff --git a/contrib/benchmark/src/java/org/apache/lucene/benchmark/byTask/tasks/ReportTask.java b/contrib/benchmark/src/java/org/apache/lucene/benchmark/byTask/tasks/ReportTask.javaindex 274c962858f..9b5a68c38be 100644--- a/contrib/benchmark/src/java/org/apache/lucene/benchmark/byTask/tasks/ReportTask.java+++ b/contrib/benchmark/src/java/org/apache/lucene/benchmark/byTask/tasks/ReportTask.java@@ -1,52 +1,52 @@-package org.apache.lucene.benchmark.byTask.tasks;-+package org.apache.lucene.benchmark.byTask.tasks;+import java.util.Iterator;import java.util.LinkedHashMap;-import org.apache.lucene.benchmark.byTask.PerfRunData;+import org.apache.lucene.benchmark.byTask.PerfRunData;import org.apache.lucene.benchmark.byTask.stats.Report;import org.apache.lucene.benchmark.byTask.stats.TaskStats;import org.apache.lucene.benchmark.byTask.utils.Format;--/**- * 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.- */--/**- * Report (abstract) task - all report tasks extend this task.- */-public abstract class ReportTask extends PerfTask {-- public ReportTask(PerfRunData runData) {- super(runData);- }-- /* (non-Javadoc)- * @see PerfTask#shouldNeverLogAtStart()- */- protected boolean shouldNeverLogAtStart() {- return true;- }-- /* (non-Javadoc)- * @see PerfTask#shouldNotRecordStats()- */- protected boolean shouldNotRecordStats() {- return true;- }++/**+ * 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.+ */++/**+ * Report (abstract) task - all report tasks extend this task.+ */+public abstract class ReportTask extends PerfTask {++ public ReportTask(PerfRunData runData) {+ super(runData);+ }++ /* (non-Javadoc)+ * @see PerfTask#shouldNeverLogAtStart()+ */+ protected boolean shouldNeverLogAtStart() {+ return true;+ }++ /* (non-Javadoc)+ * @see PerfTask#shouldNotRecordStats()+ */+ protected boolean shouldNotRecordStats() {+ return true;+ }/** From here start the code used to generate the reports.@@ -159,4 +159,4 @@ public abstract class ReportTask extends PerfTask {-}+}diff --git a/contrib/benchmark/src/java/org/apache/lucene/benchmark/byTask/tasks/ResetInputsTask.java b/contrib/benchmark/src/java/org/apache/lucene/benchmark/byTask/tasks/ResetInputsTask.javaindex 76e01484bb3..4bbc1153a01 100644--- a/contrib/benchmark/src/java/org/apache/lucene/benchmark/byTask/tasks/ResetInputsTask.java+++ b/contrib/benchmark/src/java/org/apache/lucene/benchmark/byTask/tasks/ResetInputsTask.java@@ -1,48 +1,48 @@-package org.apache.lucene.benchmark.byTask.tasks;--import org.apache.lucene.benchmark.byTask.PerfRunData;--/**- * 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.- */----/**- * Reset inputs so that the test run would behave, input wise,- * as if it just started. This affects e.g. the generation of docs and queries.- */-public class ResetInputsTask extends PerfTask {-- public ResetInputsTask(PerfRunData runData) {- super(runData);- }-- public int doLogic() throws Exception {- getRunData().resetInputs();- return 0;- }-- /*- * (non-Javadoc)- * @see org.apache.lucene.benchmark.byTask.tasks.PerfTask#shouldNotRecordStats()- */- protected boolean shouldNotRecordStats() {- return true;- }---}+package org.apache.lucene.benchmark.byTask.tasks;++import org.apache.lucene.benchmark.byTask.PerfRunData;++/**+ * 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.+ */++++/**+ * Reset inputs so that the test run would behave, input wise,+ * as if it just started. This affects e.g. the generation of docs and queries.+ */+public class ResetInputsTask extends PerfTask {++ public ResetInputsTask(PerfRunData runData) {+ super(runData);+ }++ public int doLogic() throws Exception {+ getRunData().resetInputs();+ return 0;+ }++ /*+ * (non-Javadoc)+ * @see org.apache.lucene.benchmark.byTask.tasks.PerfTask#shouldNotRecordStats()+ */+ protected boolean shouldNotRecordStats() {+ return true;+ }+++}diff --git a/contrib/benchmark/src/java/org/apache/lucene/benchmark/byTask/tasks/ResetSystemEraseTask.java b/contrib/benchmark/src/java/org/apache/lucene/benchmark/byTask/tasks/ResetSystemEraseTask.javaindex 5b1d989813c..48111e6072c 100644--- a/contrib/benchmark/src/java/org/apache/lucene/benchmark/byTask/tasks/ResetSystemEraseTask.java+++ b/contrib/benchmark/src/java/org/apache/lucene/benchmark/byTask/tasks/ResetSystemEraseTask.java@@ -1,50 +1,50 @@-package org.apache.lucene.benchmark.byTask.tasks;--import org.apache.lucene.benchmark.byTask.PerfRunData;--/**- * 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.- */----/**- * Reset all index and input data and call gc, erase index and dir, does NOT clear statistics.+package org.apache.lucene.benchmark.byTask.tasks;++import org.apache.lucene.benchmark.byTask.PerfRunData;++/**+ * 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.+ */++++/**+ * Reset all index and input data and call gc, erase index and dir, does NOT clear statistics.* <br>This contains ResetInputs.* <br>Other side effects: writers/readers nulified, deleted, closed.- * Index is erased.- * Directory is erased.- */-public class ResetSystemEraseTask extends PerfTask {-- public ResetSystemEraseTask(PerfRunData runData) {- super(runData);- }-- public int doLogic() throws Exception {- getRunData().reinit(true);- return 0;- }-- /*- * (non-Javadoc)- * @see org.apache.lucene.benchmark.byTask.tasks.PerfTask#shouldNotRecordStats()- */- protected boolean shouldNotRecordStats() {- return true;- }--}+ * Index is erased.+ * Directory is erased.+ */+public class ResetSystemEraseTask extends PerfTask {++ public ResetSystemEraseTask(PerfRunData runData) {+ super(runData);+ }++ public int doLogic() throws Exception {+ getRunData().reinit(true);+ return 0;+ }++ /*+ * (non-Javadoc)+ * @see org.apache.lucene.benchmark.byTask.tasks.PerfTask#shouldNotRecordStats()+ */+ protected boolean shouldNotRecordStats() {+ return true;+ }++}diff --git a/contrib/benchmark/src/java/org/apache/lucene/benchmark/byTask/tasks/ResetSystemSoftTask.java b/contrib/benchmark/src/java/org/apache/lucene/benchmark/byTask/tasks/ResetSystemSoftTask.javaindex 2c27862362c..456cce49092 100644--- a/contrib/benchmark/src/java/org/apache/lucene/benchmark/byTask/tasks/ResetSystemSoftTask.java+++ b/contrib/benchmark/src/java/org/apache/lucene/benchmark/byTask/tasks/ResetSystemSoftTask.java@@ -1,50 +1,50 @@-package org.apache.lucene.benchmark.byTask.tasks;--import org.apache.lucene.benchmark.byTask.PerfRunData;--/**- * 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.- */----/**- * Reset all index and input data and call gc, does NOT erase index/dir, does NOT clear statistics.- * This contains ResetInputs.+package org.apache.lucene.benchmark.byTask.tasks;++import org.apache.lucene.benchmark.byTask.PerfRunData;++/**+ * 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.+ */++++/**+ * Reset all index and input data and call gc, does NOT erase index/dir, does NOT clear statistics.+ * This contains ResetInputs.* <br>Other side effects: writers/readers nulified, closed.- * Index is NOT erased.- * Directory is NOT erased.- */-public class ResetSystemSoftTask extends PerfTask {-- public ResetSystemSoftTask(PerfRunData runData) {- super(runData);- }-- public int doLogic() throws Exception {- getRunData().reinit(false);- return 0;- }-- /*- * (non-Javadoc)- * @see org.apache.lucene.benchmark.byTask.tasks.PerfTask#shouldNotRecordStats()- */- protected boolean shouldNotRecordStats() {- return true;- }--}+ * Index is NOT erased.+ * Directory is NOT erased.+ */+public class ResetSystemSoftTask extends PerfTask {++ public ResetSystemSoftTask(PerfRunData runData) {+ super(runData);+ }++ public int doLogic() throws Exception {+ getRunData().reinit(false);+ return 0;+ }++ /*+ * (non-Javadoc)+ * @see org.apache.lucene.benchmark.byTask.tasks.PerfTask#shouldNotRecordStats()+ */+ protected boolean shouldNotRecordStats() {+ return true;+ }++}diff --git a/contrib/benchmark/src/java/org/apache/lucene/benchmark/byTask/tasks/SearchTask.java b/contrib/benchmark/src/java/org/apache/lucene/benchmark/byTask/tasks/SearchTask.javaindex 8c0e9cd146e..8234e190ad5 100644--- a/contrib/benchmark/src/java/org/apache/lucene/benchmark/byTask/tasks/SearchTask.java+++ b/contrib/benchmark/src/java/org/apache/lucene/benchmark/byTask/tasks/SearchTask.java@@ -1,56 +1,56 @@-package org.apache.lucene.benchmark.byTask.tasks;--/**- * 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 org.apache.lucene.benchmark.byTask.PerfRunData;-import org.apache.lucene.benchmark.byTask.feeds.QueryMaker;--/**- * Search task.- *- * <p>Note: This task reuses the reader if it is already open.- * Otherwise a reader is opened at start and closed at the end.- */-public class SearchTask extends ReadTask {-- public SearchTask(PerfRunData runData) {- super(runData);- }-- public boolean withRetrieve() {- return false;- }-- public boolean withSearch() {- return true;- }-- public boolean withTraverse() {- return false;- }-- public boolean withWarm() {- return false;- }-- public QueryMaker getQueryMaker() {+package org.apache.lucene.benchmark.byTask.tasks;++/**+ * 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 org.apache.lucene.benchmark.byTask.PerfRunData;+import org.apache.lucene.benchmark.byTask.feeds.QueryMaker;++/**+ * Search task.+ *+ * <p>Note: This task reuses the reader if it is already open.+ * Otherwise a reader is opened at start and closed at the end.+ */+public class SearchTask extends ReadTask {++ public SearchTask(PerfRunData runData) {+ super(runData);+ }++ public boolean withRetrieve() {+ return false;+ }++ public boolean withSearch() {+ return true;+ }++ public boolean withTraverse() {+ return false;+ }++ public boolean withWarm() {+ return false;+ }++ public QueryMaker getQueryMaker() {return getRunData().getQueryMaker(this);- }---}+ }+++}diff --git a/contrib/benchmark/src/java/org/apache/lucene/benchmark/byTask/tasks/SearchTravRetTask.java b/contrib/benchmark/src/java/org/apache/lucene/benchmark/byTask/tasks/SearchTravRetTask.javaindex d6ef6feb6d2..1ebdc1c3c75 100644--- a/contrib/benchmark/src/java/org/apache/lucene/benchmark/byTask/tasks/SearchTravRetTask.java+++ b/contrib/benchmark/src/java/org/apache/lucene/benchmark/byTask/tasks/SearchTravRetTask.java@@ -1,44 +1,44 @@-package org.apache.lucene.benchmark.byTask.tasks;--/**- * 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 org.apache.lucene.benchmark.byTask.PerfRunData;--/**- * Search and Traverse and Retrieve docs task.- *- * <p>Note: This task reuses the reader if it is already open.- * Otherwise a reader is opened at start and closed at the end.- * </p>+package org.apache.lucene.benchmark.byTask.tasks;++/**+ * 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 org.apache.lucene.benchmark.byTask.PerfRunData;++/**+ * Search and Traverse and Retrieve docs task.*- * <p>Takes optional param: traversal size (otherwise all results are traversed).</p>+ * <p>Note: This task reuses the reader if it is already open.+ * Otherwise a reader is opened at start and closed at the end.+ * </p>*- * <p>Other side effects: counts additional 1 (record) for each traversed hit,- * and 1 more for each retrieved (non null) document.</p>- */+ * <p>Takes optional param: traversal size (otherwise all results are traversed).</p>+ *+ * <p>Other side effects: counts additional 1 (record) for each traversed hit,+ * and 1 more for each retrieved (non null) document.</p>+ */public class SearchTravRetTask extends SearchTravTask {-- public SearchTravRetTask(PerfRunData runData) {- super(runData);- }-- public boolean withRetrieve() {- return true;- }--}++ public SearchTravRetTask(PerfRunData runData) {+ super(runData);+ }++ public boolean withRetrieve() {+ return true;+ }++}diff --git a/contrib/benchmark/src/java/org/apache/lucene/benchmark/byTask/tasks/SearchTravTask.java b/contrib/benchmark/src/java/org/apache/lucene/benchmark/byTask/tasks/SearchTravTask.javaindex 74a910b3f34..393bd393009 100644--- a/contrib/benchmark/src/java/org/apache/lucene/benchmark/byTask/tasks/SearchTravTask.java+++ b/contrib/benchmark/src/java/org/apache/lucene/benchmark/byTask/tasks/SearchTravTask.java@@ -1,65 +1,65 @@-package org.apache.lucene.benchmark.byTask.tasks;--/**- * 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 org.apache.lucene.benchmark.byTask.PerfRunData;-import org.apache.lucene.benchmark.byTask.feeds.QueryMaker;--/**- * Search and Traverse task.- *- * <p>Note: This task reuses the reader if it is already open.- * Otherwise a reader is opened at start and closed at the end.+package org.apache.lucene.benchmark.byTask.tasks;++/**+ * 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 org.apache.lucene.benchmark.byTask.PerfRunData;+import org.apache.lucene.benchmark.byTask.feeds.QueryMaker;++/**+ * Search and Traverse task.+ *+ * <p>Note: This task reuses the reader if it is already open.+ * Otherwise a reader is opened at start and closed at the end.* <p/>*- * <p>Takes optional param: traversal size (otherwise all results are traversed).</p>- *- * <p>Other side effects: counts additional 1 (record) for each traversed hit.</p>- */-public class SearchTravTask extends ReadTask {+ * <p>Takes optional param: traversal size (otherwise all results are traversed).</p>+ *+ * <p>Other side effects: counts additional 1 (record) for each traversed hit.</p>+ */+public class SearchTravTask extends ReadTask {protected int traversalSize = Integer.MAX_VALUE;-- public SearchTravTask(PerfRunData runData) {- super(runData);- }-- public boolean withRetrieve() {- return false;- }-- public boolean withSearch() {- return true;- }-- public boolean withTraverse() {- return true;- }-- public boolean withWarm() {- return false;- }-++ public SearchTravTask(PerfRunData runData) {+ super(runData);+ }++ public boolean withRetrieve() {+ return false;+ }++ public boolean withSearch() {+ return true;+ }++ public boolean withTraverse() {+ return true;+ }++ public boolean withWarm() {+ return false;+ }+- public QueryMaker getQueryMaker() {+ public QueryMaker getQueryMaker() {return getRunData().getQueryMaker(this);- }-+ }+public int traversalSize() {return traversalSize;}@@ -75,4 +75,4 @@ public class SearchTravTask extends ReadTask {public boolean supportsParams() {return true;}-}+}diff --git a/contrib/benchmark/src/java/org/apache/lucene/benchmark/byTask/tasks/SetPropTask.java b/contrib/benchmark/src/java/org/apache/lucene/benchmark/byTask/tasks/SetPropTask.javaindex e56396056b7..6a5ad083d3e 100644--- a/contrib/benchmark/src/java/org/apache/lucene/benchmark/byTask/tasks/SetPropTask.java+++ b/contrib/benchmark/src/java/org/apache/lucene/benchmark/byTask/tasks/SetPropTask.java@@ -1,61 +1,61 @@-package org.apache.lucene.benchmark.byTask.tasks;--import org.apache.lucene.benchmark.byTask.PerfRunData;--/**- * 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.- */--/**- * Set a performance test configuration property.- * A property may have a single value, or a sequence of values, seprated by ":".- * If a sequence of values is specified, each time a new round starts,- * the next (cyclic) value is taken.+package org.apache.lucene.benchmark.byTask.tasks;++import org.apache.lucene.benchmark.byTask.PerfRunData;++/**+ * 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.+ */++/**+ * Set a performance test configuration property.+ * A property may have a single value, or a sequence of values, seprated by ":".+ * If a sequence of values is specified, each time a new round starts,+ * the next (cyclic) value is taken.* <br>Other side effects: none.* <br>Takes mandatory param: "name,value" pair.- * @see org.apache.lucene.benchmark.byTask.tasks.NewRoundTask- */-public class SetPropTask extends PerfTask {-- public SetPropTask(PerfRunData runData) {- super(runData);- }-- private String name;- private String value;-- public int doLogic() throws Exception {- if (name==null || value==null) {- throw new Exception(getName()+" - undefined name or value: name="+name+" value="+value);- }- getRunData().getConfig().set(name,value);- return 0;- }-- /**- * Set the params (property name and value).- * @param params property name and value separated by ','.- */- public void setParams(String params) {- super.setParams(params);- int k = params.indexOf(",");- name = params.substring(0,k).trim();- value = params.substring(k+1).trim();- }-+ * @see org.apache.lucene.benchmark.byTask.tasks.NewRoundTask+ */+public class SetPropTask extends PerfTask {++ public SetPropTask(PerfRunData runData) {+ super(runData);+ }++ private String name;+ private String value;++ public int doLogic() throws Exception {+ if (name==null || value==null) {+ throw new Exception(getName()+" - undefined name or value: name="+name+" value="+value);+ }+ getRunData().getConfig().set(name,value);+ return 0;+ }++ /**+ * Set the params (property name and value).+ * @param params property name and value separated by ','.+ */+ public void setParams(String params) {+ super.setParams(params);+ int k = params.indexOf(",");+ name = params.substring(0,k).trim();+ value = params.substring(k+1).trim();+ }+/* (non-Javadoc)* @see org.apache.lucene.benchmark.byTask.tasks.PerfTask#supportsParams()*/@@ -63,4 +63,4 @@ public class SetPropTask extends PerfTask {return true;}-}+}diff --git a/contrib/benchmark/src/java/org/apache/lucene/benchmark/byTask/tasks/TaskSequence.java b/contrib/benchmark/src/java/org/apache/lucene/benchmark/byTask/tasks/TaskSequence.javaindex e110dc69858..0da5705bb21 100644--- a/contrib/benchmark/src/java/org/apache/lucene/benchmark/byTask/tasks/TaskSequence.java+++ b/contrib/benchmark/src/java/org/apache/lucene/benchmark/byTask/tasks/TaskSequence.java@@ -1,295 +1,295 @@-package org.apache.lucene.benchmark.byTask.tasks;--/**- * 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.ArrayList;-import java.util.Iterator;--import org.apache.lucene.benchmark.byTask.PerfRunData;-import org.apache.lucene.benchmark.byTask.feeds.NoMoreDataException;--/**- * Sequence of parallel or sequential tasks.- */-public class TaskSequence extends PerfTask {- public static int REPEAT_EXHAUST = -2;- private ArrayList tasks;- private int repetitions = 1;- private boolean parallel;- private TaskSequence parent;- private boolean letChildReport = true;- private int rate = 0;- private boolean perMin = false; // rate, if set, is, by default, be sec.- private String seqName;-- public TaskSequence (PerfRunData runData, String name, TaskSequence parent, boolean parallel) {- super(runData);- name = (name!=null ? name : (parallel ? "Par" : "Seq"));- setName(name);- setSequenceName();- this.parent = parent;- this.parallel = parallel;- tasks = new ArrayList();- }-- /**- * @return Returns the parallel.- */- public boolean isParallel() {- return parallel;- }-- /**- * @return Returns the repetitions.- */- public int getRepetitions() {- return repetitions;- }-- /**- * @param repetitions The repetitions to set.- * @throws Exception- */- public void setRepetitions(int repetitions) throws Exception {- this.repetitions = repetitions;- if (repetitions==REPEAT_EXHAUST && isParallel()) {- throw new Exception("REPEAT_EXHAUST is not allowed for parallel tasks");- }- setSequenceName();- }-- /**- * @return Returns the parent.- */- public TaskSequence getParent() {- return parent;- }-- /*- * (non-Javadoc)- * @see org.apache.lucene.benchmark.byTask.tasks.PerfTask#doLogic()- */- public int doLogic() throws Exception {- return ( parallel ? doParallelTasks() : doSerialTasks());- }-- private int doSerialTasks() throws Exception {- if (rate > 0) {- return doSerialTasksWithRate();- }-- int count = 0;- boolean exhausted = false;- for (int k=0; (repetitions==REPEAT_EXHAUST && !exhausted) || k<repetitions; k++) {- for (Iterator it = tasks.iterator(); it.hasNext();) {- PerfTask task = (PerfTask) it.next();- try {- count += task.runAndMaybeStats(letChildReport);- } catch (NoMoreDataException e) {- exhausted = true;- }- }- }- return count;- }-- private int doSerialTasksWithRate() throws Exception {- long delayStep = (perMin ? 60000 : 1000) /rate;- long nextStartTime = System.currentTimeMillis();- int count = 0;- boolean exhausted = false;- for (int k=0; (repetitions==REPEAT_EXHAUST && !exhausted) || k<repetitions; k++) {- for (Iterator it = tasks.iterator(); it.hasNext();) {- PerfTask task = (PerfTask) it.next();- long waitMore = nextStartTime - System.currentTimeMillis();- if (waitMore > 0) {- //System.out.println("wait: "+waitMore+" for rate: "+ratePerMin+" (delayStep="+delayStep+")");- Thread.sleep(waitMore);- }- nextStartTime += delayStep; // this aims at avarage rate.- try {- count += task.runAndMaybeStats(letChildReport);- } catch (NoMoreDataException e) {- exhausted = true;- }- }- }- return count;- }-- private int doParallelTasks() throws Exception {- final int count [] = {0};- Thread t[] = new Thread [repetitions * tasks.size()];- // prepare threads- int indx = 0;- for (int k=0; k<repetitions; k++) {- for (int i = 0; i < tasks.size(); i++) {- final PerfTask task = (PerfTask) ((PerfTask) tasks.get(i)).clone();- t[indx++] = new Thread() {- public void run() {- int n;- try {- n = task.runAndMaybeStats(letChildReport);- } catch (Exception e) {- throw new RuntimeException(e);- }- synchronized (count) {- count[0] += n;- }- }- };- }- }- // run threads- startThreads(t);- // wait for all threads to complete- for (int i = 0; i < t.length; i++) {- t[i].join();- }- // return total count- return count[0];- }-- // run threads- private void startThreads(Thread[] t) throws InterruptedException {- if (rate > 0) {- startlThreadsWithRate(t);- return;- }- for (int i = 0; i < t.length; i++) {- t[i].start();- }- }-- // run threadsm with rate- private void startlThreadsWithRate(Thread[] t) throws InterruptedException {- long delayStep = (perMin ? 60000 : 1000) /rate;- long nextStartTime = System.currentTimeMillis();- for (int i = 0; i < t.length; i++) {- long waitMore = nextStartTime - System.currentTimeMillis();- if (waitMore > 0) {- //System.out.println("thread wait: "+waitMore+" for rate: "+ratePerMin+" (delayStep="+delayStep+")");- Thread.sleep(waitMore);- }- nextStartTime += delayStep; // this aims at avarage rate of starting threads.- t[i].start();- }- }-- public void addTask(PerfTask task) {- tasks.add(task);- task.setDepth(getDepth()+1);- }-- /* (non-Javadoc)- * @see java.lang.Object#toString()- */- public String toString() {- String padd = getPadding();- StringBuffer sb = new StringBuffer(super.toString());- sb.append(parallel ? " [" : " {");- sb.append(NEW_LINE);- for (Iterator it = tasks.iterator(); it.hasNext();) {- PerfTask task = (PerfTask) it.next();- sb.append(task.toString());- sb.append(NEW_LINE);- }- sb.append(padd);- sb.append(!letChildReport ? ">" : (parallel ? "]" : "}"));- if (repetitions>1) {- sb.append(" * " + repetitions);- }- if (repetitions==REPEAT_EXHAUST) {- sb.append(" * EXHAUST");- }- if (rate>0) {- sb.append(", rate: " + rate+"/"+(perMin?"min":"sec"));- }- return sb.toString();- }-- /**- * Execute child tasks in a way that they do not report their time separately.- */- public void setNoChildReport() {- letChildReport = false;- for (Iterator it = tasks.iterator(); it.hasNext();) {- PerfTask task = (PerfTask) it.next();- if (task instanceof TaskSequence) {- ((TaskSequence)task).setNoChildReport();- }- }- }-- /**- * Returns the rate per minute: how many operations should be performed in a minute.- * If 0 this has no effect.- * @return the rate per min: how many operations should be performed in a minute.- */- public int getRate() {- return (perMin ? rate : 60*rate);- }-- /**- * @param rate The rate to set.- */- public void setRate(int rate, boolean perMin) {- this.rate = rate;- this.perMin = perMin;- setSequenceName();- }-- private void setSequenceName() {- seqName = super.getName();- if (repetitions==REPEAT_EXHAUST) {- seqName += "_Exhaust";- } else if (repetitions>1) {- seqName += "_"+repetitions;- }- if (rate>0) {- seqName += "_" + rate + (perMin?"/min":"/sec");- }- if (parallel && seqName.toLowerCase().indexOf("par")<0) {- seqName += "_Par";- }- }-- public String getName() {- return seqName; // overide to include more info- }-- /**- * @return Returns the tasks.- */- public ArrayList getTasks() {- return tasks;- }-- /* (non-Javadoc)- * @see java.lang.Object#clone()- */- protected Object clone() throws CloneNotSupportedException {- TaskSequence res = (TaskSequence) super.clone();- res.tasks = new ArrayList();- for (int i = 0; i < tasks.size(); i++) {- res.tasks.add(((PerfTask)tasks.get(i)).clone());- }- return res;- }--}+package org.apache.lucene.benchmark.byTask.tasks;++/**+ * 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.ArrayList;+import java.util.Iterator;++import org.apache.lucene.benchmark.byTask.PerfRunData;+import org.apache.lucene.benchmark.byTask.feeds.NoMoreDataException;++/**+ * Sequence of parallel or sequential tasks.+ */+public class TaskSequence extends PerfTask {+ public static int REPEAT_EXHAUST = -2;+ private ArrayList tasks;+ private int repetitions = 1;+ private boolean parallel;+ private TaskSequence parent;+ private boolean letChildReport = true;+ private int rate = 0;+ private boolean perMin = false; // rate, if set, is, by default, be sec.+ private String seqName;++ public TaskSequence (PerfRunData runData, String name, TaskSequence parent, boolean parallel) {+ super(runData);+ name = (name!=null ? name : (parallel ? "Par" : "Seq"));+ setName(name);+ setSequenceName();+ this.parent = parent;+ this.parallel = parallel;+ tasks = new ArrayList();+ }++ /**+ * @return Returns the parallel.+ */+ public boolean isParallel() {+ return parallel;+ }++ /**+ * @return Returns the repetitions.+ */+ public int getRepetitions() {+ return repetitions;+ }++ /**+ * @param repetitions The repetitions to set.+ * @throws Exception+ */+ public void setRepetitions(int repetitions) throws Exception {+ this.repetitions = repetitions;+ if (repetitions==REPEAT_EXHAUST && isParallel()) {+ throw new Exception("REPEAT_EXHAUST is not allowed for parallel tasks");+ }+ setSequenceName();+ }++ /**+ * @return Returns the parent.+ */+ public TaskSequence getParent() {+ return parent;+ }++ /*+ * (non-Javadoc)+ * @see org.apache.lucene.benchmark.byTask.tasks.PerfTask#doLogic()+ */+ public int doLogic() throws Exception {+ return ( parallel ? doParallelTasks() : doSerialTasks());+ }++ private int doSerialTasks() throws Exception {+ if (rate > 0) {+ return doSerialTasksWithRate();+ }++ int count = 0;+ boolean exhausted = false;+ for (int k=0; (repetitions==REPEAT_EXHAUST && !exhausted) || k<repetitions; k++) {+ for (Iterator it = tasks.iterator(); it.hasNext();) {+ PerfTask task = (PerfTask) it.next();+ try {+ count += task.runAndMaybeStats(letChildReport);+ } catch (NoMoreDataException e) {+ exhausted = true;+ }+ }+ }+ return count;+ }++ private int doSerialTasksWithRate() throws Exception {+ long delayStep = (perMin ? 60000 : 1000) /rate;+ long nextStartTime = System.currentTimeMillis();+ int count = 0;+ boolean exhausted = false;+ for (int k=0; (repetitions==REPEAT_EXHAUST && !exhausted) || k<repetitions; k++) {+ for (Iterator it = tasks.iterator(); it.hasNext();) {+ PerfTask task = (PerfTask) it.next();+ long waitMore = nextStartTime - System.currentTimeMillis();+ if (waitMore > 0) {+ //System.out.println("wait: "+waitMore+" for rate: "+ratePerMin+" (delayStep="+delayStep+")");+ Thread.sleep(waitMore);+ }+ nextStartTime += delayStep; // this aims at avarage rate.+ try {+ count += task.runAndMaybeStats(letChildReport);+ } catch (NoMoreDataException e) {+ exhausted = true;+ }+ }+ }+ return count;+ }++ private int doParallelTasks() throws Exception {+ final int count [] = {0};+ Thread t[] = new Thread [repetitions * tasks.size()];+ // prepare threads+ int indx = 0;+ for (int k=0; k<repetitions; k++) {+ for (int i = 0; i < tasks.size(); i++) {+ final PerfTask task = (PerfTask) ((PerfTask) tasks.get(i)).clone();+ t[indx++] = new Thread() {+ public void run() {+ int n;+ try {+ n = task.runAndMaybeStats(letChildReport);+ } catch (Exception e) {+ throw new RuntimeException(e);+ }+ synchronized (count) {+ count[0] += n;+ }+ }+ };+ }+ }+ // run threads+ startThreads(t);+ // wait for all threads to complete+ for (int i = 0; i < t.length; i++) {+ t[i].join();+ }+ // return total count+ return count[0];+ }++ // run threads+ private void startThreads(Thread[] t) throws InterruptedException {+ if (rate > 0) {+ startlThreadsWithRate(t);+ return;+ }+ for (int i = 0; i < t.length; i++) {+ t[i].start();+ }+ }++ // run threadsm with rate+ private void startlThreadsWithRate(Thread[] t) throws InterruptedException {+ long delayStep = (perMin ? 60000 : 1000) /rate;+ long nextStartTime = System.currentTimeMillis();+ for (int i = 0; i < t.length; i++) {+ long waitMore = nextStartTime - System.currentTimeMillis();+ if (waitMore > 0) {+ //System.out.println("thread wait: "+waitMore+" for rate: "+ratePerMin+" (delayStep="+delayStep+")");+ Thread.sleep(waitMore);+ }+ nextStartTime += delayStep; // this aims at avarage rate of starting threads.+ t[i].start();+ }+ }++ public void addTask(PerfTask task) {+ tasks.add(task);+ task.setDepth(getDepth()+1);+ }++ /* (non-Javadoc)+ * @see java.lang.Object#toString()+ */+ public String toString() {+ String padd = getPadding();+ StringBuffer sb = new StringBuffer(super.toString());+ sb.append(parallel ? " [" : " {");+ sb.append(NEW_LINE);+ for (Iterator it = tasks.iterator(); it.hasNext();) {+ PerfTask task = (PerfTask) it.next();+ sb.append(task.toString());+ sb.append(NEW_LINE);+ }+ sb.append(padd);+ sb.append(!letChildReport ? ">" : (parallel ? "]" : "}"));+ if (repetitions>1) {+ sb.append(" * " + repetitions);+ }+ if (repetitions==REPEAT_EXHAUST) {+ sb.append(" * EXHAUST");+ }+ if (rate>0) {+ sb.append(", rate: " + rate+"/"+(perMin?"min":"sec"));+ }+ return sb.toString();+ }++ /**+ * Execute child tasks in a way that they do not report their time separately.+ */+ public void setNoChildReport() {+ letChildReport = false;+ for (Iterator it = tasks.iterator(); it.hasNext();) {+ PerfTask task = (PerfTask) it.next();+ if (task instanceof TaskSequence) {+ ((TaskSequence)task).setNoChildReport();+ }+ }+ }++ /**+ * Returns the rate per minute: how many operations should be performed in a minute.+ * If 0 this has no effect.+ * @return the rate per min: how many operations should be performed in a minute.+ */+ public int getRate() {+ return (perMin ? rate : 60*rate);+ }++ /**+ * @param rate The rate to set.+ */+ public void setRate(int rate, boolean perMin) {+ this.rate = rate;+ this.perMin = perMin;+ setSequenceName();+ }++ private void setSequenceName() {+ seqName = super.getName();+ if (repetitions==REPEAT_EXHAUST) {+ seqName += "_Exhaust";+ } else if (repetitions>1) {+ seqName += "_"+repetitions;+ }+ if (rate>0) {+ seqName += "_" + rate + (perMin?"/min":"/sec");+ }+ if (parallel && seqName.toLowerCase().indexOf("par")<0) {+ seqName += "_Par";+ }+ }++ public String getName() {+ return seqName; // overide to include more info+ }++ /**+ * @return Returns the tasks.+ */+ public ArrayList getTasks() {+ return tasks;+ }++ /* (non-Javadoc)+ * @see java.lang.Object#clone()+ */+ protected Object clone() throws CloneNotSupportedException {+ TaskSequence res = (TaskSequence) super.clone();+ res.tasks = new ArrayList();+ for (int i = 0; i < tasks.size(); i++) {+ res.tasks.add(((PerfTask)tasks.get(i)).clone());+ }+ return res;+ }++}diff --git a/contrib/benchmark/src/java/org/apache/lucene/benchmark/byTask/tasks/WarmTask.java b/contrib/benchmark/src/java/org/apache/lucene/benchmark/byTask/tasks/WarmTask.javaindex 271ca1ed49b..e0e1c75c042 100644--- a/contrib/benchmark/src/java/org/apache/lucene/benchmark/byTask/tasks/WarmTask.java+++ b/contrib/benchmark/src/java/org/apache/lucene/benchmark/byTask/tasks/WarmTask.java@@ -1,60 +1,60 @@-package org.apache.lucene.benchmark.byTask.tasks;--/**- * 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 org.apache.lucene.benchmark.byTask.PerfRunData;-import org.apache.lucene.benchmark.byTask.feeds.QueryMaker;--/**- * Warm reader task: retrieve all reader documents.- *- * <p>Note: This task reuses the reader if it is already open.- * Otherwise a reader is opened at start and closed at the end.- * </p>- *- * <p>Other side effects: counts additional 1 (record) for each- * retrieved (non null) document.</p>- */-public class WarmTask extends ReadTask {-- public WarmTask(PerfRunData runData) {- super(runData);- }-- public boolean withRetrieve() {- return false;- }-- public boolean withSearch() {- return false;- }-- public boolean withTraverse() {- return false;- }-- public boolean withWarm() {- return true;- }-- public QueryMaker getQueryMaker() {- return null; // not required for this task.- }---}+package org.apache.lucene.benchmark.byTask.tasks;++/**+ * 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 org.apache.lucene.benchmark.byTask.PerfRunData;+import org.apache.lucene.benchmark.byTask.feeds.QueryMaker;++/**+ * Warm reader task: retrieve all reader documents.+ *+ * <p>Note: This task reuses the reader if it is already open.+ * Otherwise a reader is opened at start and closed at the end.+ * </p>+ *+ * <p>Other side effects: counts additional 1 (record) for each+ * retrieved (non null) document.</p>+ */+public class WarmTask extends ReadTask {++ public WarmTask(PerfRunData runData) {+ super(runData);+ }++ public boolean withRetrieve() {+ return false;+ }++ public boolean withSearch() {+ return false;+ }++ public boolean withTraverse() {+ return false;+ }++ public boolean withWarm() {+ return true;+ }++ public QueryMaker getQueryMaker() {+ return null; // not required for this task.+ }+++}diff --git a/contrib/benchmark/src/java/org/apache/lucene/benchmark/byTask/utils/Algorithm.java b/contrib/benchmark/src/java/org/apache/lucene/benchmark/byTask/utils/Algorithm.javaindex ff688a87125..a8f6e3a2933 100644--- a/contrib/benchmark/src/java/org/apache/lucene/benchmark/byTask/utils/Algorithm.java+++ b/contrib/benchmark/src/java/org/apache/lucene/benchmark/byTask/utils/Algorithm.java@@ -1,258 +1,258 @@-package org.apache.lucene.benchmark.byTask.utils;--/**- * 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.io.StreamTokenizer;-import java.io.StringReader;-import java.lang.reflect.Constructor;-import java.util.ArrayList;--import org.apache.lucene.benchmark.byTask.PerfRunData;-import org.apache.lucene.benchmark.byTask.tasks.PerfTask;-import org.apache.lucene.benchmark.byTask.tasks.RepSumByPrefTask;-import org.apache.lucene.benchmark.byTask.tasks.TaskSequence;--/**- * Test algorithm, as read from file- */-public class Algorithm {-- private TaskSequence sequence;-- /**- * Read algorithm from file- * @param runData perf-run-data used at running the tasks.- * @throws Exception if errors while parsing the algorithm- */- public Algorithm (PerfRunData runData) throws Exception {- String algTxt = runData.getConfig().getAlgorithmText();- sequence = new TaskSequence(runData,null,null,false);- TaskSequence currSequence = sequence;- PerfTask prevTask = null;- StreamTokenizer stok = new StreamTokenizer(new StringReader(algTxt));- stok.commentChar('#');- stok.eolIsSignificant(false);- stok.ordinaryChar('"');- stok.ordinaryChar('/');- stok.ordinaryChar('(');- stok.ordinaryChar(')');- boolean colonOk = false;- currSequence.setDepth(0);- String taskPackage = PerfTask.class.getPackage().getName() + ".";-- Class paramClass[] = {PerfRunData.class};- PerfRunData paramObj[] = {runData};-- while (stok.nextToken() != StreamTokenizer.TT_EOF) {- switch(stok.ttype) {-- case StreamTokenizer.TT_WORD:- String s = stok.sval;- Constructor cnstr = Class.forName(taskPackage+s+"Task").getConstructor(paramClass);- PerfTask task = (PerfTask) cnstr.newInstance(paramObj);- currSequence.addTask(task);- if (task instanceof RepSumByPrefTask) {- stok.nextToken();- String prefix = stok.sval;- if (prefix==null || prefix.length()==0) {- throw new Exception("named report prefix problem - "+stok.toString());- }- ((RepSumByPrefTask) task).setPrefix(prefix);- }- // check for task param: '(' someParam ')'- stok.nextToken();- if (stok.ttype!='(') {- stok.pushBack();- } else {- // get params, for tasks that supports them, - anything until next ')'- StringBuffer params = new StringBuffer();- stok.nextToken();- while (stok.ttype!=')') {- switch (stok.ttype) {- case StreamTokenizer.TT_NUMBER:- params.append(stok.nval);- break;- case StreamTokenizer.TT_WORD:- params.append(stok.sval);- break;- case StreamTokenizer.TT_EOF:- throw new Exception("unexpexted EOF: - "+stok.toString());- default:- params.append((char)stok.ttype);- }- stok.nextToken();- }- String prm = params.toString().trim();- if (prm.length()>0) {- task.setParams(prm);- }- }-- // ---------------------------------------- colonOk = false; prevTask = task;- break;-- default:- char c = (char)stok.ttype;-- switch(c) {-- case ':' :- if (!colonOk) throw new Exception("colon unexpexted: - "+stok.toString());- colonOk = false;- // get repetitions number- stok.nextToken();- if ((char)stok.ttype == '*') {- ((TaskSequence)prevTask).setRepetitions(TaskSequence.REPEAT_EXHAUST);- } else {- if (stok.ttype!=StreamTokenizer.TT_NUMBER) throw new Exception("expexted repetitions number: - "+stok.toString());- ((TaskSequence)prevTask).setRepetitions((int)stok.nval);- }- // check for rate specification (ops/min)- stok.nextToken();- if (stok.ttype!=':') {- stok.pushBack();- } else {- // get rate number- stok.nextToken();- if (stok.ttype!=StreamTokenizer.TT_NUMBER) throw new Exception("expexted rate number: - "+stok.toString());- // check for unit - min or sec, sec is default- stok.nextToken();- if (stok.ttype!='/') {- stok.pushBack();- ((TaskSequence)prevTask).setRate((int)stok.nval,false); // set rate per sec- } else {- stok.nextToken();- if (stok.ttype!=StreamTokenizer.TT_WORD) throw new Exception("expexted rate unit: 'min' or 'sec' - "+stok.toString());- String unit = stok.sval.toLowerCase();- if ("min".equals(unit)) {- ((TaskSequence)prevTask).setRate((int)stok.nval,true); // set rate per min- } else if ("sec".equals(unit)) {- ((TaskSequence)prevTask).setRate((int)stok.nval,false); // set rate per sec- } else {- throw new Exception("expexted rate unit: 'min' or 'sec' - "+stok.toString());- }- }- }- colonOk = false;- break;-- case '{' :- case '[' :- // a sequence- // check for sequence name- String name = null;- stok.nextToken();- if (stok.ttype!='"') {- stok.pushBack();- } else {- stok.nextToken();- name = stok.sval;- stok.nextToken();- if (stok.ttype!='"' || name==null || name.length()==0) {- throw new Exception("sequence name problem - "+stok.toString());- }- }- // start the sequence- TaskSequence seq2 = new TaskSequence(runData, name, currSequence, c=='[');- currSequence.addTask(seq2);- currSequence = seq2;- colonOk = false;- break;-- case '>' :- currSequence.setNoChildReport();- case '}' :- case ']' :- // end sequence- colonOk = true; prevTask = currSequence;- currSequence = currSequence.getParent();- break;-- } //switch(c)- break;-- } //switch(stok.ttype)-- }-- if (sequence != currSequence) {- throw new Exception("Unmatched sequences");- }-- // remove redundant top level enclosing sequences- while (sequence.getRepetitions()==1 && sequence.getRate()==0) {- ArrayList t = sequence.getTasks();- if (t!=null && t.size()==1) {- PerfTask p = (PerfTask) t.get(0);- if (p instanceof TaskSequence) {- sequence = (TaskSequence) p;- continue;- }- }- break;- }- }-- /* (non-Javadoc)- * @see java.lang.Object#toString()- */- public String toString() {- String newline = System.getProperty("line.separator");- StringBuffer sb = new StringBuffer();- sb.append(sequence.toString());- sb.append(newline);- return sb.toString();- }-- /**- * Execute this algorithm- * @throws Exception- */- public void execute() throws Exception {- sequence.doLogic();- }-- /**- * Expert: for test purposes, return all tasks participating in this algorithm.- * @return all tasks participating in this algorithm.- */- public ArrayList extractTasks() {- ArrayList res = new ArrayList();- extractTasks(res, sequence);- return res;- }- private void extractTasks (ArrayList extrct, TaskSequence seq) {- if (seq==null)- return;- extrct.add(seq);- ArrayList t = sequence.getTasks();- if (t==null)- return;- for (int i = 0; i < t.size(); i++) {- PerfTask p = (PerfTask) t.get(0);- if (p instanceof TaskSequence) {- extractTasks(extrct, (TaskSequence)p);- } else {- extrct.add(p);- }- }- }--}-+package org.apache.lucene.benchmark.byTask.utils;++/**+ * 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.io.StreamTokenizer;+import java.io.StringReader;+import java.lang.reflect.Constructor;+import java.util.ArrayList;++import org.apache.lucene.benchmark.byTask.PerfRunData;+import org.apache.lucene.benchmark.byTask.tasks.PerfTask;+import org.apache.lucene.benchmark.byTask.tasks.RepSumByPrefTask;+import org.apache.lucene.benchmark.byTask.tasks.TaskSequence;++/**+ * Test algorithm, as read from file+ */+public class Algorithm {++ private TaskSequence sequence;++ /**+ * Read algorithm from file+ * @param runData perf-run-data used at running the tasks.+ * @throws Exception if errors while parsing the algorithm+ */+ public Algorithm (PerfRunData runData) throws Exception {+ String algTxt = runData.getConfig().getAlgorithmText();+ sequence = new TaskSequence(runData,null,null,false);+ TaskSequence currSequence = sequence;+ PerfTask prevTask = null;+ StreamTokenizer stok = new StreamTokenizer(new StringReader(algTxt));+ stok.commentChar('#');+ stok.eolIsSignificant(false);+ stok.ordinaryChar('"');+ stok.ordinaryChar('/');+ stok.ordinaryChar('(');+ stok.ordinaryChar(')');+ boolean colonOk = false;+ currSequence.setDepth(0);+ String taskPackage = PerfTask.class.getPackage().getName() + ".";++ Class paramClass[] = {PerfRunData.class};+ PerfRunData paramObj[] = {runData};++ while (stok.nextToken() != StreamTokenizer.TT_EOF) {+ switch(stok.ttype) {++ case StreamTokenizer.TT_WORD:+ String s = stok.sval;+ Constructor cnstr = Class.forName(taskPackage+s+"Task").getConstructor(paramClass);+ PerfTask task = (PerfTask) cnstr.newInstance(paramObj);+ currSequence.addTask(task);+ if (task instanceof RepSumByPrefTask) {+ stok.nextToken();+ String prefix = stok.sval;+ if (prefix==null || prefix.length()==0) {+ throw new Exception("named report prefix problem - "+stok.toString());+ }+ ((RepSumByPrefTask) task).setPrefix(prefix);+ }+ // check for task param: '(' someParam ')'+ stok.nextToken();+ if (stok.ttype!='(') {+ stok.pushBack();+ } else {+ // get params, for tasks that supports them, - anything until next ')'+ StringBuffer params = new StringBuffer();+ stok.nextToken();+ while (stok.ttype!=')') {+ switch (stok.ttype) {+ case StreamTokenizer.TT_NUMBER:+ params.append(stok.nval);+ break;+ case StreamTokenizer.TT_WORD:+ params.append(stok.sval);+ break;+ case StreamTokenizer.TT_EOF:+ throw new Exception("unexpexted EOF: - "+stok.toString());+ default:+ params.append((char)stok.ttype);+ }+ stok.nextToken();+ }+ String prm = params.toString().trim();+ if (prm.length()>0) {+ task.setParams(prm);+ }+ }++ // ---------------------------------------+ colonOk = false; prevTask = task;+ break;++ default:+ char c = (char)stok.ttype;++ switch(c) {++ case ':' :+ if (!colonOk) throw new Exception("colon unexpexted: - "+stok.toString());+ colonOk = false;+ // get repetitions number+ stok.nextToken();+ if ((char)stok.ttype == '*') {+ ((TaskSequence)prevTask).setRepetitions(TaskSequence.REPEAT_EXHAUST);+ } else {+ if (stok.ttype!=StreamTokenizer.TT_NUMBER) throw new Exception("expexted repetitions number: - "+stok.toString());+ ((TaskSequence)prevTask).setRepetitions((int)stok.nval);+ }+ // check for rate specification (ops/min)+ stok.nextToken();+ if (stok.ttype!=':') {+ stok.pushBack();+ } else {+ // get rate number+ stok.nextToken();+ if (stok.ttype!=StreamTokenizer.TT_NUMBER) throw new Exception("expexted rate number: - "+stok.toString());+ // check for unit - min or sec, sec is default+ stok.nextToken();+ if (stok.ttype!='/') {+ stok.pushBack();+ ((TaskSequence)prevTask).setRate((int)stok.nval,false); // set rate per sec+ } else {+ stok.nextToken();+ if (stok.ttype!=StreamTokenizer.TT_WORD) throw new Exception("expexted rate unit: 'min' or 'sec' - "+stok.toString());+ String unit = stok.sval.toLowerCase();+ if ("min".equals(unit)) {+ ((TaskSequence)prevTask).setRate((int)stok.nval,true); // set rate per min+ } else if ("sec".equals(unit)) {+ ((TaskSequence)prevTask).setRate((int)stok.nval,false); // set rate per sec+ } else {+ throw new Exception("expexted rate unit: 'min' or 'sec' - "+stok.toString());+ }+ }+ }+ colonOk = false;+ break;++ case '{' :+ case '[' :+ // a sequence+ // check for sequence name+ String name = null;+ stok.nextToken();+ if (stok.ttype!='"') {+ stok.pushBack();+ } else {+ stok.nextToken();+ name = stok.sval;+ stok.nextToken();+ if (stok.ttype!='"' || name==null || name.length()==0) {+ throw new Exception("sequence name problem - "+stok.toString());+ }+ }+ // start the sequence+ TaskSequence seq2 = new TaskSequence(runData, name, currSequence, c=='[');+ currSequence.addTask(seq2);+ currSequence = seq2;+ colonOk = false;+ break;++ case '>' :+ currSequence.setNoChildReport();+ case '}' :+ case ']' :+ // end sequence+ colonOk = true; prevTask = currSequence;+ currSequence = currSequence.getParent();+ break;++ } //switch(c)+ break;++ } //switch(stok.ttype)++ }++ if (sequence != currSequence) {+ throw new Exception("Unmatched sequences");+ }++ // remove redundant top level enclosing sequences+ while (sequence.getRepetitions()==1 && sequence.getRate()==0) {+ ArrayList t = sequence.getTasks();+ if (t!=null && t.size()==1) {+ PerfTask p = (PerfTask) t.get(0);+ if (p instanceof TaskSequence) {+ sequence = (TaskSequence) p;+ continue;+ }+ }+ break;+ }+ }++ /* (non-Javadoc)+ * @see java.lang.Object#toString()+ */+ public String toString() {+ String newline = System.getProperty("line.separator");+ StringBuffer sb = new StringBuffer();+ sb.append(sequence.toString());+ sb.append(newline);+ return sb.toString();+ }++ /**+ * Execute this algorithm+ * @throws Exception+ */+ public void execute() throws Exception {+ sequence.doLogic();+ }++ /**+ * Expert: for test purposes, return all tasks participating in this algorithm.+ * @return all tasks participating in this algorithm.+ */+ public ArrayList extractTasks() {+ ArrayList res = new ArrayList();+ extractTasks(res, sequence);+ return res;+ }+ private void extractTasks (ArrayList extrct, TaskSequence seq) {+ if (seq==null)+ return;+ extrct.add(seq);+ ArrayList t = sequence.getTasks();+ if (t==null)+ return;+ for (int i = 0; i < t.size(); i++) {+ PerfTask p = (PerfTask) t.get(0);+ if (p instanceof TaskSequence) {+ extractTasks(extrct, (TaskSequence)p);+ } else {+ extrct.add(p);+ }+ }+ }++}+diff --git a/contrib/benchmark/src/java/org/apache/lucene/benchmark/byTask/utils/Config.java b/contrib/benchmark/src/java/org/apache/lucene/benchmark/byTask/utils/Config.javaindex 3f55d58be96..150e8392d9f 100644--- a/contrib/benchmark/src/java/org/apache/lucene/benchmark/byTask/utils/Config.java+++ b/contrib/benchmark/src/java/org/apache/lucene/benchmark/byTask/utils/Config.java@@ -1,324 +1,324 @@-package org.apache.lucene.benchmark.byTask.utils;--/**- * 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.io.BufferedReader;-import java.io.ByteArrayInputStream;-import java.io.IOException;-import java.io.Reader;-import java.util.ArrayList;-import java.util.HashMap;-import java.util.Iterator;-import java.util.Properties;-import java.util.StringTokenizer;--/**- * Perf run configuration properties.- * Numeric peroperty containing ":", e.g. "10:100:5" is interpreted- * as array of numeric values. It is extracted once, on first use, and- * maintain an round number to return the appropriate value.- */-public class Config {-- private static final String NEW_LINE = System.getProperty("line.separator");-- private int roundNumber = 0;- private Properties props;- private HashMap valByRound = new HashMap();- private HashMap colForValByRound = new HashMap();- private String algorithmText;-- /**- * Read both algorithm and config properties.- * @param algReader from where to read algorithm and config properties.- * @throws IOException- */- public Config (Reader algReader) throws IOException {- // read alg file to array of lines- ArrayList lines = new ArrayList();- BufferedReader r = new BufferedReader(algReader);- int lastConfigLine=0;- for (String line = r.readLine(); line!=null; line=r.readLine()) {- lines.add(line);- if (line.indexOf('=')>0) {- lastConfigLine = lines.size();- }- }- r.close();- // copy props lines to string- StringBuffer sb = new StringBuffer();- for (int i=0; i<lastConfigLine; i++) {- sb.append(lines.get(i));- sb.append(NEW_LINE);- }- // read props from string- this.props = new Properties();- props.load(new ByteArrayInputStream(sb.toString().getBytes()));-- if (Boolean.valueOf(props.getProperty("print.props","true")).booleanValue()) {- printProps();- }-- // copy algorithm lines- sb = new StringBuffer();- for (int i=lastConfigLine; i<lines.size(); i++) {- sb.append(lines.get(i));- sb.append(NEW_LINE);- }- algorithmText = sb.toString();- }-- /**- * Create config without algorithm - usefull for a programmatic perf test.- * @param props - configuration properties.- * @throws IOException- */- public Config (Properties props) {- this.props = props;- if (Boolean.valueOf(props.getProperty("print.props","true")).booleanValue()) {- printProps();- }- }-- private void printProps() {- System.out.println("------------> config properties:");- for (Iterator it = props.keySet().iterator(); it.hasNext();) {- String propName = (String) it.next();- System.out.println(propName + " = " + props.getProperty(propName));- }- System.out.println("-------------------------------");- }-- /**- * Return a string property.- * @param name name of property.- * @param dflt default value.- * @return a string property.- */- public String get (String name, String dflt) {- return props.getProperty(name,dflt);- }-- /**- * Set a property.- * Note: once a multiple values property is set, it can no longer be modified.- * @param name name of property.- * @param value either single or multiple propery value (multple values are separated by ":")- * @throws Exception- */- public void set (String name, String value) throws Exception {- if (valByRound.get(name) != null) {- throw new Exception("Cannot modify a multi value property!");- }- props.setProperty(name,value);- }-- /**- * Return an int property.- * If the property contain ":", e.g. "10:100:5", it is interpreted- * as array of ints. It is extracted once, on first call- * to get() it, and a by-round-value is returned.- * @param name name of property- * @param dflt default value- * @return a int property.- */- public int get (String name, int dflt) {- // use value by round if already parsed- int vals[] = (int[]) valByRound.get(name);- if (vals != null) {- return vals[roundNumber % vals.length];- }- // done if not by round- String sval = props.getProperty(name,""+dflt);- if (sval.indexOf(":")<0) {- return Integer.parseInt(sval);- }- // first time this prop is extracted by round- int k = sval.indexOf(":");- String colName = sval.substring(0,k);- sval = sval.substring(k+1);- colForValByRound.put(name,colName);- vals = propToIntArray(sval);- valByRound.put(name,vals);- return vals[roundNumber % vals.length];- }-- /**- * Return a boolean property.- * If the property contain ":", e.g. "true.true.false", it is interpreted- * as array of boleans. It is extracted once, on first call- * to get() it, and a by-round-value is returned.- * @param name name of property- * @param dflt default value- * @return a int property.- */- public boolean get (String name, boolean dflt) {- // use value by round if already parsed- boolean vals[] = (boolean[]) valByRound.get(name);- if (vals != null) {- return vals[roundNumber % vals.length];- }- // done if not by round- String sval = props.getProperty(name,""+dflt);- if (sval.indexOf(":")<0) {- return Boolean.valueOf(sval).booleanValue();- }- // first time this prop is extracted by round- int k = sval.indexOf(":");- String colName = sval.substring(0,k);- sval = sval.substring(k+1);- colForValByRound.put(name,colName);- vals = propToBooleanArray(sval);- valByRound.put(name,vals);- return vals[roundNumber % vals.length];- }-- /**- * Increment the round number, for config values that are extracted by round number.- * @return the new round number.- */- public int newRound () {- roundNumber++;-- // log changes in values- if (valByRound.size()>0) {- StringBuffer sb = new StringBuffer("--> Round ").append(roundNumber-1).append("-->").append(roundNumber).append(": ");- for (Iterator iter = valByRound.keySet().iterator(); iter.hasNext();) {- String name = (String) iter.next();- Object a = valByRound.get(name);- if (a instanceof int[]) {- int ai[] = (int[]) a;- int n1 = (roundNumber-1)%ai.length;- int n2 = roundNumber%ai.length;- sb.append(" ").append(name).append(":").append(ai[n1]).append("-->").append(ai[n2]);- } else {- boolean ab[] = (boolean[]) a;- int n1 = (roundNumber-1)%ab.length;- int n2 = roundNumber%ab.length;- sb.append(" ").append(name).append(":").append(ab[n1]).append("-->").append(ab[n2]);- }- }- System.out.println();- System.out.println(sb.toString());- System.out.println();- }-- return roundNumber;- }-- // extract properties to array, e.g. for "10.100.5" return int[]{10,100,5}.- private int[] propToIntArray (String s) {- if (s.indexOf(":")<0) {- return new int [] { Integer.parseInt(s) };- }-- ArrayList a = new ArrayList();- StringTokenizer st = new StringTokenizer(s,":");- while (st.hasMoreTokens()) {- String t = st.nextToken();- a.add(new Integer(t));- }- int res[] = new int[a.size()];- for (int i=0; i<a.size(); i++) {- res[i] = ((Integer) a.get(i)).intValue();- }- return res;- }-- // extract properties to array, e.g. for "true.true.false" return booleab[]{true,false,false}.- private boolean[] propToBooleanArray (String s) {- if (s.indexOf(":")<0) {- return new boolean [] { Boolean.valueOf(s).booleanValue() };- }-- ArrayList a = new ArrayList();- StringTokenizer st = new StringTokenizer(s,":");- while (st.hasMoreTokens()) {- String t = st.nextToken();- a.add(new Boolean(t));- }- boolean res[] = new boolean[a.size()];- for (int i=0; i<a.size(); i++) {- res[i] = ((Boolean) a.get(i)).booleanValue();- }- return res;- }-- /**- * @return names of params set by round, for reports title- */- public String getColsNamesForValsByRound() {- if (colForValByRound.size()==0) {- return "";- }- StringBuffer sb = new StringBuffer();- for (Iterator it = colForValByRound.keySet().iterator(); it.hasNext();) {- String name = (String) it.next();- String colName = (String) colForValByRound.get(name);- sb.append(" ").append(colName);- }- return sb.toString();- }-- /**- * @return values of params set by round, for reports lines.- */- public String getColsValuesForValsByRound(int roundNum) {- if (colForValByRound.size()==0) {- return "";- }- StringBuffer sb = new StringBuffer();- for (Iterator it = colForValByRound.keySet().iterator(); it.hasNext();) {- String name = (String) it.next();- String colName = (String) colForValByRound.get(name);- String template = " "+colName;- if (roundNum<0) {- // just append blanks- sb.append(Format.formatPaddLeft("-",template));- } else {- // append actual values, for that round- Object a = valByRound.get(name);- if (a instanceof int[]) {- int ai[] = (int[]) a;- int n = roundNum % ai.length;- sb.append(Format.format(ai[n],template));- } else {- boolean ab[] = (boolean[]) a;- int n = roundNum % ab.length;- sb.append(Format.formatPaddLeft(""+ab[n],template));- }- }- }- return sb.toString();- }-- /**- * @return the round number.- */- public int getRoundNumber() {- return roundNumber;- }-- /**- * @return Returns the algorithmText.- */- public String getAlgorithmText() {- return algorithmText;- }--}+package org.apache.lucene.benchmark.byTask.utils;++/**+ * 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.io.BufferedReader;+import java.io.ByteArrayInputStream;+import java.io.IOException;+import java.io.Reader;+import java.util.ArrayList;+import java.util.HashMap;+import java.util.Iterator;+import java.util.Properties;+import java.util.StringTokenizer;++/**+ * Perf run configuration properties.+ * Numeric peroperty containing ":", e.g. "10:100:5" is interpreted+ * as array of numeric values. It is extracted once, on first use, and+ * maintain an round number to return the appropriate value.+ */+public class Config {++ private static final String NEW_LINE = System.getProperty("line.separator");++ private int roundNumber = 0;+ private Properties props;+ private HashMap valByRound = new HashMap();+ private HashMap colForValByRound = new HashMap();+ private String algorithmText;++ /**+ * Read both algorithm and config properties.+ * @param algReader from where to read algorithm and config properties.+ * @throws IOException+ */+ public Config (Reader algReader) throws IOException {+ // read alg file to array of lines+ ArrayList lines = new ArrayList();+ BufferedReader r = new BufferedReader(algReader);+ int lastConfigLine=0;+ for (String line = r.readLine(); line!=null; line=r.readLine()) {+ lines.add(line);+ if (line.indexOf('=')>0) {+ lastConfigLine = lines.size();+ }+ }+ r.close();+ // copy props lines to string+ StringBuffer sb = new StringBuffer();+ for (int i=0; i<lastConfigLine; i++) {+ sb.append(lines.get(i));+ sb.append(NEW_LINE);+ }+ // read props from string+ this.props = new Properties();+ props.load(new ByteArrayInputStream(sb.toString().getBytes()));++ if (Boolean.valueOf(props.getProperty("print.props","true")).booleanValue()) {+ printProps();+ }++ // copy algorithm lines+ sb = new StringBuffer();+ for (int i=lastConfigLine; i<lines.size(); i++) {+ sb.append(lines.get(i));+ sb.append(NEW_LINE);+ }+ algorithmText = sb.toString();+ }++ /**+ * Create config without algorithm - usefull for a programmatic perf test.+ * @param props - configuration properties.+ * @throws IOException+ */+ public Config (Properties props) {+ this.props = props;+ if (Boolean.valueOf(props.getProperty("print.props","true")).booleanValue()) {+ printProps();+ }+ }++ private void printProps() {+ System.out.println("------------> config properties:");+ for (Iterator it = props.keySet().iterator(); it.hasNext();) {+ String propName = (String) it.next();+ System.out.println(propName + " = " + props.getProperty(propName));+ }+ System.out.println("-------------------------------");+ }++ /**+ * Return a string property.+ * @param name name of property.+ * @param dflt default value.+ * @return a string property.+ */+ public String get (String name, String dflt) {+ return props.getProperty(name,dflt);+ }++ /**+ * Set a property.+ * Note: once a multiple values property is set, it can no longer be modified.+ * @param name name of property.+ * @param value either single or multiple propery value (multple values are separated by ":")+ * @throws Exception+ */+ public void set (String name, String value) throws Exception {+ if (valByRound.get(name) != null) {+ throw new Exception("Cannot modify a multi value property!");+ }+ props.setProperty(name,value);+ }++ /**+ * Return an int property.+ * If the property contain ":", e.g. "10:100:5", it is interpreted+ * as array of ints. It is extracted once, on first call+ * to get() it, and a by-round-value is returned.+ * @param name name of property+ * @param dflt default value+ * @return a int property.+ */+ public int get (String name, int dflt) {+ // use value by round if already parsed+ int vals[] = (int[]) valByRound.get(name);+ if (vals != null) {+ return vals[roundNumber % vals.length];+ }+ // done if not by round+ String sval = props.getProperty(name,""+dflt);+ if (sval.indexOf(":")<0) {+ return Integer.parseInt(sval);+ }+ // first time this prop is extracted by round+ int k = sval.indexOf(":");+ String colName = sval.substring(0,k);+ sval = sval.substring(k+1);+ colForValByRound.put(name,colName);+ vals = propToIntArray(sval);+ valByRound.put(name,vals);+ return vals[roundNumber % vals.length];+ }++ /**+ * Return a boolean property.+ * If the property contain ":", e.g. "true.true.false", it is interpreted+ * as array of boleans. It is extracted once, on first call+ * to get() it, and a by-round-value is returned.+ * @param name name of property+ * @param dflt default value+ * @return a int property.+ */+ public boolean get (String name, boolean dflt) {+ // use value by round if already parsed+ boolean vals[] = (boolean[]) valByRound.get(name);+ if (vals != null) {+ return vals[roundNumber % vals.length];+ }+ // done if not by round+ String sval = props.getProperty(name,""+dflt);+ if (sval.indexOf(":")<0) {+ return Boolean.valueOf(sval).booleanValue();+ }+ // first time this prop is extracted by round+ int k = sval.indexOf(":");+ String colName = sval.substring(0,k);+ sval = sval.substring(k+1);+ colForValByRound.put(name,colName);+ vals = propToBooleanArray(sval);+ valByRound.put(name,vals);+ return vals[roundNumber % vals.length];+ }++ /**+ * Increment the round number, for config values that are extracted by round number.+ * @return the new round number.+ */+ public int newRound () {+ roundNumber++;++ // log changes in values+ if (valByRound.size()>0) {+ StringBuffer sb = new StringBuffer("--> Round ").append(roundNumber-1).append("-->").append(roundNumber).append(": ");+ for (Iterator iter = valByRound.keySet().iterator(); iter.hasNext();) {+ String name = (String) iter.next();+ Object a = valByRound.get(name);+ if (a instanceof int[]) {+ int ai[] = (int[]) a;+ int n1 = (roundNumber-1)%ai.length;+ int n2 = roundNumber%ai.length;+ sb.append(" ").append(name).append(":").append(ai[n1]).append("-->").append(ai[n2]);+ } else {+ boolean ab[] = (boolean[]) a;+ int n1 = (roundNumber-1)%ab.length;+ int n2 = roundNumber%ab.length;+ sb.append(" ").append(name).append(":").append(ab[n1]).append("-->").append(ab[n2]);+ }+ }+ System.out.println();+ System.out.println(sb.toString());+ System.out.println();+ }++ return roundNumber;+ }++ // extract properties to array, e.g. for "10.100.5" return int[]{10,100,5}.+ private int[] propToIntArray (String s) {+ if (s.indexOf(":")<0) {+ return new int [] { Integer.parseInt(s) };+ }++ ArrayList a = new ArrayList();+ StringTokenizer st = new StringTokenizer(s,":");+ while (st.hasMoreTokens()) {+ String t = st.nextToken();+ a.add(new Integer(t));+ }+ int res[] = new int[a.size()];+ for (int i=0; i<a.size(); i++) {+ res[i] = ((Integer) a.get(i)).intValue();+ }+ return res;+ }++ // extract properties to array, e.g. for "true.true.false" return booleab[]{true,false,false}.+ private boolean[] propToBooleanArray (String s) {+ if (s.indexOf(":")<0) {+ return new boolean [] { Boolean.valueOf(s).booleanValue() };+ }++ ArrayList a = new ArrayList();+ StringTokenizer st = new StringTokenizer(s,":");+ while (st.hasMoreTokens()) {+ String t = st.nextToken();+ a.add(new Boolean(t));+ }+ boolean res[] = new boolean[a.size()];+ for (int i=0; i<a.size(); i++) {+ res[i] = ((Boolean) a.get(i)).booleanValue();+ }+ return res;+ }++ /**+ * @return names of params set by round, for reports title+ */+ public String getColsNamesForValsByRound() {+ if (colForValByRound.size()==0) {+ return "";+ }+ StringBuffer sb = new StringBuffer();+ for (Iterator it = colForValByRound.keySet().iterator(); it.hasNext();) {+ String name = (String) it.next();+ String colName = (String) colForValByRound.get(name);+ sb.append(" ").append(colName);+ }+ return sb.toString();+ }++ /**+ * @return values of params set by round, for reports lines.+ */+ public String getColsValuesForValsByRound(int roundNum) {+ if (colForValByRound.size()==0) {+ return "";+ }+ StringBuffer sb = new StringBuffer();+ for (Iterator it = colForValByRound.keySet().iterator(); it.hasNext();) {+ String name = (String) it.next();+ String colName = (String) colForValByRound.get(name);+ String template = " "+colName;+ if (roundNum<0) {+ // just append blanks+ sb.append(Format.formatPaddLeft("-",template));+ } else {+ // append actual values, for that round+ Object a = valByRound.get(name);+ if (a instanceof int[]) {+ int ai[] = (int[]) a;+ int n = roundNum % ai.length;+ sb.append(Format.format(ai[n],template));+ } else {+ boolean ab[] = (boolean[]) a;+ int n = roundNum % ab.length;+ sb.append(Format.formatPaddLeft(""+ab[n],template));+ }+ }+ }+ return sb.toString();+ }++ /**+ * @return the round number.+ */+ public int getRoundNumber() {+ return roundNumber;+ }++ /**+ * @return Returns the algorithmText.+ */+ public String getAlgorithmText() {+ return algorithmText;+ }++}diff --git a/contrib/benchmark/src/java/org/apache/lucene/benchmark/byTask/utils/FileUtils.java b/contrib/benchmark/src/java/org/apache/lucene/benchmark/byTask/utils/FileUtils.javaindex aa93b151bac..17120385f44 100644--- a/contrib/benchmark/src/java/org/apache/lucene/benchmark/byTask/utils/FileUtils.java+++ b/contrib/benchmark/src/java/org/apache/lucene/benchmark/byTask/utils/FileUtils.java@@ -1,54 +1,54 @@-package org.apache.lucene.benchmark.byTask.utils;--/**- * 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.io.File;-import java.io.IOException;--/**- * File utilities.- */-public class FileUtils {-- /**- * Delete files and directories, even if non-empty.- *- * @param dir file or directory- * @return true on success, false if no or part of files have been deleted- * @throws java.io.IOException- */- public static boolean fullyDelete(File dir) throws IOException {- if (dir == null || !dir.exists()) return false;- File contents[] = dir.listFiles();- if (contents != null) {- for (int i = 0; i < contents.length; i++) {- if (contents[i].isFile()) {- if (!contents[i].delete()) {- return false;- }- } else {- if (!fullyDelete(contents[i])) {- return false;- }- }- }- }- return dir.delete();- }--}+package org.apache.lucene.benchmark.byTask.utils;++/**+ * 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.io.File;+import java.io.IOException;++/**+ * File utilities.+ */+public class FileUtils {++ /**+ * Delete files and directories, even if non-empty.+ *+ * @param dir file or directory+ * @return true on success, false if no or part of files have been deleted+ * @throws java.io.IOException+ */+ public static boolean fullyDelete(File dir) throws IOException {+ if (dir == null || !dir.exists()) return false;+ File contents[] = dir.listFiles();+ if (contents != null) {+ for (int i = 0; i < contents.length; i++) {+ if (contents[i].isFile()) {+ if (!contents[i].delete()) {+ return false;+ }+ } else {+ if (!fullyDelete(contents[i])) {+ return false;+ }+ }+ }+ }+ return dir.delete();+ }++}diff --git a/contrib/benchmark/src/java/org/apache/lucene/benchmark/byTask/utils/Format.java b/contrib/benchmark/src/java/org/apache/lucene/benchmark/byTask/utils/Format.javaindex 432a0331fe2..5013383d398 100644--- a/contrib/benchmark/src/java/org/apache/lucene/benchmark/byTask/utils/Format.java+++ b/contrib/benchmark/src/java/org/apache/lucene/benchmark/byTask/utils/Format.java@@ -1,114 +1,114 @@-package org.apache.lucene.benchmark.byTask.utils;--/**- * 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.text.NumberFormat;--/**- * Formatting utilities (for reports).- */-public class Format {-- private static NumberFormat numFormat [] = {- NumberFormat.getInstance(),- NumberFormat.getInstance(),- NumberFormat.getInstance(),- };- private static final String padd = " ";-- static {- numFormat[0].setMaximumFractionDigits(0);- numFormat[0].setMinimumFractionDigits(0);- numFormat[1].setMaximumFractionDigits(1);- numFormat[1].setMinimumFractionDigits(1);- numFormat[2].setMaximumFractionDigits(2);- numFormat[2].setMinimumFractionDigits(2);- }-- /**- * Padd a number from left.- * @param numFracDigits number of digits in fraction part - must be 0 or 1 or 2.- * @param f number to be formatted.- * @param col column name (used for deciding on length).- * @return formatted string.- */- public static String format(int numFracDigits, float f, String col) {- String res = padd + numFormat[numFracDigits].format(f);- return res.substring(res.length() - col.length());- }-- /**- * Padd a number from right.- * @param numFracDigits number of digits in fraction part - must be 0 or 1 or 2.- * @param f number to be formatted.- * @param col column name (used for deciding on length).- * @return formatted string.- */- public static String formatPaddRight(int numFracDigits, float f, String col) {- String res = numFormat[numFracDigits].format(f) + padd;- return res.substring(0, col.length());- }-- /**- * Padd a number from left.- * @param n number to be formatted.- * @param col column name (used for deciding on length).- * @return formatted string.- */- public static String format(int n, String col) {- String res = padd + n;- return res.substring(res.length() - col.length());- }-- /**- * Padd a string from right.- * @param s string to be formatted.- * @param col column name (used for deciding on length).- * @return formatted string.- */- public static String format(String s, String col) {- return (s + padd).substring(0, col.length());- }-- /**- * Padd a string from left.- * @param s string to be formatted.- * @param col column name (used for deciding on length).- * @return formatted string.- */- public static String formatPaddLeft(String s, String col) {- String res = padd + s;- return res.substring(res.length() - col.length());- }-- /**- * Extract simple class name- * @param cls class whose simple name is required- * @return simple class name- */- public static String simpleName (Class cls) {- String c = cls.getName();- String p = cls.getPackage().getName();- int k = c.lastIndexOf(p+".");- if (k<0) {- return c;- }- return c.substring(k+1+p.length());- }--}+package org.apache.lucene.benchmark.byTask.utils;++/**+ * 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.text.NumberFormat;++/**+ * Formatting utilities (for reports).+ */+public class Format {++ private static NumberFormat numFormat [] = {+ NumberFormat.getInstance(),+ NumberFormat.getInstance(),+ NumberFormat.getInstance(),+ };+ private static final String padd = " ";++ static {+ numFormat[0].setMaximumFractionDigits(0);+ numFormat[0].setMinimumFractionDigits(0);+ numFormat[1].setMaximumFractionDigits(1);+ numFormat[1].setMinimumFractionDigits(1);+ numFormat[2].setMaximumFractionDigits(2);+ numFormat[2].setMinimumFractionDigits(2);+ }++ /**+ * Padd a number from left.+ * @param numFracDigits number of digits in fraction part - must be 0 or 1 or 2.+ * @param f number to be formatted.+ * @param col column name (used for deciding on length).+ * @return formatted string.+ */+ public static String format(int numFracDigits, float f, String col) {+ String res = padd + numFormat[numFracDigits].format(f);+ return res.substring(res.length() - col.length());+ }++ /**+ * Padd a number from right.+ * @param numFracDigits number of digits in fraction part - must be 0 or 1 or 2.+ * @param f number to be formatted.+ * @param col column name (used for deciding on length).+ * @return formatted string.+ */+ public static String formatPaddRight(int numFracDigits, float f, String col) {+ String res = numFormat[numFracDigits].format(f) + padd;+ return res.substring(0, col.length());+ }++ /**+ * Padd a number from left.+ * @param n number to be formatted.+ * @param col column name (used for deciding on length).+ * @return formatted string.+ */+ public static String format(int n, String col) {+ String res = padd + n;+ return res.substring(res.length() - col.length());+ }++ /**+ * Padd a string from right.+ * @param s string to be formatted.+ * @param col column name (used for deciding on length).+ * @return formatted string.+ */+ public static String format(String s, String col) {+ return (s + padd).substring(0, col.length());+ }++ /**+ * Padd a string from left.+ * @param s string to be formatted.+ * @param col column name (used for deciding on length).+ * @return formatted string.+ */+ public static String formatPaddLeft(String s, String col) {+ String res = padd + s;+ return res.substring(res.length() - col.length());+ }++ /**+ * Extract simple class name+ * @param cls class whose simple name is required+ * @return simple class name+ */+ public static String simpleName (Class cls) {+ String c = cls.getName();+ String p = cls.getPackage().getName();+ int k = c.lastIndexOf(p+".");+ if (k<0) {+ return c;+ }+ return c.substring(k+1+p.length());+ }++}diff --git a/contrib/benchmark/src/java/org/apache/lucene/benchmark/stats/TestData.java b/contrib/benchmark/src/java/org/apache/lucene/benchmark/stats/TestData.javaindex 628aa39a875..8e1505fb2ad 100644--- a/contrib/benchmark/src/java/org/apache/lucene/benchmark/stats/TestData.java+++ b/contrib/benchmark/src/java/org/apache/lucene/benchmark/stats/TestData.java@@ -1,576 +1,576 @@-package org.apache.lucene.benchmark.stats;-/**- * Copyright 2005 The Apache Software Foundation- *- * Licensed 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.io.File;-import java.text.NumberFormat;-import java.util.ArrayList;-import java.util.Collection;-import java.util.Date;-import java.util.HashMap;-import java.util.Iterator;-import java.util.LinkedHashMap;-import java.util.List;-import java.util.Vector;--import org.apache.lucene.analysis.Analyzer;-import org.apache.lucene.benchmark.Constants;-import org.apache.lucene.store.Directory;---/**- * This class holds together all parameters related to a test. Single test is- * performed several times, and all results are averaged.- *- * @author Andrzej Bialecki <[email protected]>- */-public class TestData-{- public static int[] MAX_BUFFERED_DOCS_COUNTS = new int[]{10, 20, 50, 100, 200, 500};- public static int[] MERGEFACTOR_COUNTS = new int[]{10, 20, 50, 100, 200, 500};-- /**- * ID of this test data.- */- private String id;- /**- * Heap size.- */- private long heap;- /**- * List of results for each test run with these parameters.- */- private Vector runData = new Vector();- private int maxBufferedDocs, mergeFactor;- /**- * Directory containing source files.- */- private File source;- /**- * Lucene Directory implementation for creating an index.- */- private Directory directory;- /**- * Analyzer to use when adding documents.- */- private Analyzer analyzer;- /**- * If true, use compound file format.- */- private boolean compound;- /**- * If true, optimize index when finished adding documents.- */- private boolean optimize;- /**- * Data for search benchmarks.- */- private QueryData[] queries;-- public TestData()- {- heap = Runtime.getRuntime().maxMemory();- }-- private static class DCounter- {- double total;- int count, recordCount;- }-- private static class LCounter- {- long total;- int count;- }-- private static class LDCounter- {- double Dtotal;- int Dcount, DrecordCount;- long Ltotal0;- int Lcount0;- long Ltotal1;- int Lcount1;- }-- /**- * Get a textual summary of the benchmark results, average from all test runs.- */- static final String ID = "# testData id ";- static final String OP = "operation ";- static final String RUNCNT = " runCnt";- static final String RECCNT = " recCnt";- static final String RECSEC = " rec/s";- static final String FREEMEM = " avgFreeMem";- static final String TOTMEM = " avgTotalMem";- static final String COLS[] = {- ID,- OP,- RUNCNT,- RECCNT,- RECSEC,- FREEMEM,- TOTMEM- };- public String showRunData(String prefix)- {- if (runData.size() == 0)- {- return "# [NO RUN DATA]";- }- HashMap resByTask = new HashMap();- StringBuffer sb = new StringBuffer();- String lineSep = System.getProperty("line.separator");- sb.append("warm = Warm Index Reader").append(lineSep).append("srch = Search Index").append(lineSep).append("trav = Traverse Hits list, optionally retrieving document").append(lineSep).append(lineSep);- for (int i = 0; i < COLS.length; i++) {- sb.append(COLS[i]);- }- sb.append("\n");- LinkedHashMap mapMem = new LinkedHashMap();- LinkedHashMap mapSpeed = new LinkedHashMap();- for (int i = 0; i < runData.size(); i++)- {- TestRunData trd = (TestRunData) runData.get(i);- Collection labels = trd.getLabels();- Iterator it = labels.iterator();- while (it.hasNext())- {- String label = (String) it.next();- MemUsage mem = trd.getMemUsage(label);- if (mem != null)- {- TestData.LCounter[] tm = (TestData.LCounter[]) mapMem.get(label);- if (tm == null)- {- tm = new TestData.LCounter[2];- tm[0] = new TestData.LCounter();- tm[1] = new TestData.LCounter();- mapMem.put(label, tm);- }- tm[0].total += mem.avgFree;- tm[0].count++;- tm[1].total += mem.avgTotal;- tm[1].count++;- }- TimeData td = trd.getTotals(label);- if (td != null)- {- TestData.DCounter dc = (TestData.DCounter) mapSpeed.get(label);- if (dc == null)- {- dc = new TestData.DCounter();- mapSpeed.put(label, dc);- }- dc.count++;- //dc.total += td.getRate();- dc.total += (td.count>0 && td.elapsed<=0 ? 1 : td.elapsed); // assume atleast 1ms for any countable op- dc.recordCount += td.count;- }- }- }- LinkedHashMap res = new LinkedHashMap();- Iterator it = mapSpeed.keySet().iterator();- while (it.hasNext())- {- String label = (String) it.next();- TestData.DCounter dc = (TestData.DCounter) mapSpeed.get(label);- res.put(label,- format(dc.count, RUNCNT) +- format(dc.recordCount / dc.count, RECCNT) +- format(1,(float) (dc.recordCount * 1000.0 / (dc.total>0 ? dc.total : 1.0)), RECSEC)- //format((float) (dc.total / (double) dc.count), RECSEC)- );-- // also sum by task- String task = label.substring(label.lastIndexOf("-")+1);- LDCounter ldc = (LDCounter) resByTask.get(task);- if (ldc==null) {- ldc = new LDCounter();- resByTask.put(task,ldc);- }- ldc.Dcount += dc.count;- ldc.DrecordCount += dc.recordCount;- ldc.Dtotal += (dc.count>0 && dc.total<=0 ? 1 : dc.total); // assume atleast 1ms for any countable op- }- it = mapMem.keySet().iterator();- while (it.hasNext())- {- String label = (String) it.next();- TestData.LCounter[] lc = (TestData.LCounter[]) mapMem.get(label);- String speed = (String) res.get(label);- boolean makeSpeed = false;- if (speed == null)- {- makeSpeed = true;- speed =- format(lc[0].count, RUNCNT) +- format(0, RECCNT) +- format(0,(float)0.0, RECSEC);- }- res.put(label, speed +- format(0, lc[0].total / lc[0].count, FREEMEM) +- format(0, lc[1].total / lc[1].count, TOTMEM));-- // also sum by task- String task = label.substring(label.lastIndexOf("-")+1);- LDCounter ldc = (LDCounter) resByTask.get(task);- if (ldc==null) {- ldc = new LDCounter();- resByTask.put(task,ldc);- makeSpeed = true;- }- if (makeSpeed) {- ldc.Dcount += lc[0].count;- }- ldc.Lcount0 += lc[0].count;- ldc.Lcount1 += lc[1].count;- ldc.Ltotal0 += lc[0].total;- ldc.Ltotal1 += lc[1].total;- }- it = res.keySet().iterator();- while (it.hasNext())- {- String label = (String) it.next();- sb.append(format(prefix, ID));- sb.append(format(label, OP));- sb.append(res.get(label)).append("\n");- }- // show results by task (srch, optimize, etc.)- sb.append("\n");- for (int i = 0; i < COLS.length; i++) {- sb.append(COLS[i]);- }- sb.append("\n");- it = resByTask.keySet().iterator();- while (it.hasNext())- {- String task = (String) it.next();- LDCounter ldc = (LDCounter) resByTask.get(task);- sb.append(format(" ", ID));- sb.append(format(task, OP));- sb.append(format(ldc.Dcount, RUNCNT));- sb.append(format(ldc.DrecordCount / ldc.Dcount, RECCNT));- sb.append(format(1,(float) (ldc.DrecordCount * 1000.0 / (ldc.Dtotal>0 ? ldc.Dtotal : 1.0)), RECSEC));- sb.append(format(0, ldc.Ltotal0 / ldc.Lcount0, FREEMEM));- sb.append(format(0, ldc.Ltotal1 / ldc.Lcount1, TOTMEM));- sb.append("\n");- }- return sb.toString();- }-- private static NumberFormat numFormat [] = { NumberFormat.getInstance(), NumberFormat.getInstance()};- private static final String padd = " ";- static {- numFormat[0].setMaximumFractionDigits(0);- numFormat[0].setMinimumFractionDigits(0);- numFormat[1].setMaximumFractionDigits(1);- numFormat[1].setMinimumFractionDigits(1);- }-- // padd number from left- // numFracDigits must be 0 or 1.- static String format(int numFracDigits, float f, String col) {- String res = padd + numFormat[numFracDigits].format(f);- return res.substring(res.length() - col.length());- }-- // padd number from left- static String format(int n, String col) {- String res = padd + n;- return res.substring(res.length() - col.length());- }-- // padd string from right- static String format(String s, String col) {- return (s + padd).substring(0,col.length());- }-- /**- * Prepare a list of benchmark data, using all possible combinations of- * benchmark parameters.- *- * @param sources list of directories containing different source document- * collections- * @param analyzers of analyzers to use.- */- public static TestData[] getAll(File[] sources, Analyzer[] analyzers)- {- List res = new ArrayList(50);- TestData ref = new TestData();- for (int q = 0; q < analyzers.length; q++)- {- for (int m = 0; m < sources.length; m++)- {- for (int i = 0; i < MAX_BUFFERED_DOCS_COUNTS.length; i++)- {- for (int k = 0; k < MERGEFACTOR_COUNTS.length; k++)- {- for (int n = 0; n < Constants.BOOLEANS.length; n++)- {- for (int p = 0; p < Constants.BOOLEANS.length; p++)- {- ref.id = "td-" + q + m + i + k + n + p;- ref.source = sources[m];- ref.analyzer = analyzers[q];- ref.maxBufferedDocs = MAX_BUFFERED_DOCS_COUNTS[i];- ref.mergeFactor = MERGEFACTOR_COUNTS[k];- ref.compound = Constants.BOOLEANS[n].booleanValue();- ref.optimize = Constants.BOOLEANS[p].booleanValue();- try- {- res.add(ref.clone());- }- catch (Exception e)- {- e.printStackTrace();- }- }- }- }- }- }- }- return (TestData[]) res.toArray(new TestData[0]);- }-- /**- * Similar to {@link #getAll(java.io.File[], org.apache.lucene.analysis.Analyzer[])} but only uses- * maxBufferedDocs of 10 and 100 and same for mergeFactor, thus reducing the number of permutations significantly.- * It also only uses compund file and optimize is always true.- *- * @param sources- * @param analyzers- * @return An Array of {@link TestData}- */- public static TestData[] getTestDataMinMaxMergeAndMaxBuffered(File[] sources, Analyzer[] analyzers)- {- List res = new ArrayList(50);- TestData ref = new TestData();- for (int q = 0; q < analyzers.length; q++)- {- for (int m = 0; m < sources.length; m++)- {- ref.id = "td-" + q + m + "_" + 10 + "_" + 10;- ref.source = sources[m];- ref.analyzer = analyzers[q];- ref.maxBufferedDocs = 10;- ref.mergeFactor = 10;//MERGEFACTOR_COUNTS[k];- ref.compound = true;- ref.optimize = true;- try- {- res.add(ref.clone());- }- catch (Exception e)- {- e.printStackTrace();- }- ref.id = "td-" + q + m + "_" + 10 + "_" + 100;- ref.source = sources[m];- ref.analyzer = analyzers[q];- ref.maxBufferedDocs = 10;- ref.mergeFactor = 100;//MERGEFACTOR_COUNTS[k];- ref.compound = true;- ref.optimize = true;- try- {- res.add(ref.clone());- }- catch (Exception e)- {- e.printStackTrace();- }- ref.id = "td-" + q + m + "_" + 100 + "_" + 10;- ref.source = sources[m];- ref.analyzer = analyzers[q];- ref.maxBufferedDocs = 100;- ref.mergeFactor = 10;//MERGEFACTOR_COUNTS[k];- ref.compound = true;- ref.optimize = true;- try- {- res.add(ref.clone());- }- catch (Exception e)- {- e.printStackTrace();- }- ref.id = "td-" + q + m + "_" + 100 + "_" + 100;- ref.source = sources[m];- ref.analyzer = analyzers[q];- ref.maxBufferedDocs = 100;- ref.mergeFactor = 100;//MERGEFACTOR_COUNTS[k];- ref.compound = true;- ref.optimize = true;- try- {- res.add(ref.clone());- }- catch (Exception e)- {- e.printStackTrace();- }- }- }- return (TestData[]) res.toArray(new TestData[0]);- }-- protected Object clone()- {- TestData cl = new TestData();- cl.id = id;- cl.compound = compound;- cl.heap = heap;- cl.mergeFactor = mergeFactor;- cl.maxBufferedDocs = maxBufferedDocs;- cl.optimize = optimize;- cl.source = source;- cl.directory = directory;- cl.analyzer = analyzer;- // don't clone runData- return cl;- }-- public String toString()- {- StringBuffer res = new StringBuffer();- res.append("#-- ID: ").append(id).append(", ").append(new Date()).append(", heap=").append(heap).append(" --\n");- res.append("# source=").append(source).append(", directory=").append(directory).append("\n");- res.append("# maxBufferedDocs=").append(maxBufferedDocs).append(", mergeFactor=").append(mergeFactor);- res.append(", compound=").append(compound).append(", optimize=").append(optimize).append("\n");- if (queries != null)- {- res.append(QueryData.getLabels()).append("\n");- for (int i = 0; i < queries.length; i++)- {- res.append("# ").append(queries[i].toString()).append("\n");- }- }- return res.toString();- }-- public Analyzer getAnalyzer()- {- return analyzer;- }-- public void setAnalyzer(Analyzer analyzer)- {- this.analyzer = analyzer;- }-- public boolean isCompound()- {- return compound;- }-- public void setCompound(boolean compound)- {- this.compound = compound;- }-- public Directory getDirectory()- {- return directory;- }-- public void setDirectory(Directory directory)- {- this.directory = directory;- }-- public long getHeap()- {- return heap;- }-- public void setHeap(long heap)- {- this.heap = heap;- }-- public String getId()- {- return id;- }-- public void setId(String id)- {- this.id = id;- }-- public int getMaxBufferedDocs()- {- return maxBufferedDocs;- }-- public void setMaxBufferedDocs(int maxBufferedDocs)- {- this.maxBufferedDocs = maxBufferedDocs;- }-- public int getMergeFactor()- {- return mergeFactor;- }-- public void setMergeFactor(int mergeFactor)- {- this.mergeFactor = mergeFactor;- }-- public boolean isOptimize()- {- return optimize;- }-- public void setOptimize(boolean optimize)- {- this.optimize = optimize;- }-- public QueryData[] getQueries()- {- return queries;- }-- public void setQueries(QueryData[] queries)- {- this.queries = queries;- }-- public Vector getRunData()- {- return runData;- }-- public void setRunData(Vector runData)- {- this.runData = runData;- }-- public File getSource()- {- return source;- }-- public void setSource(File source)- {- this.source = source;- }-}+package org.apache.lucene.benchmark.stats;+/**+ * Copyright 2005 The Apache Software Foundation+ *+ * Licensed 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.io.File;+import java.text.NumberFormat;+import java.util.ArrayList;+import java.util.Collection;+import java.util.Date;+import java.util.HashMap;+import java.util.Iterator;+import java.util.LinkedHashMap;+import java.util.List;+import java.util.Vector;++import org.apache.lucene.analysis.Analyzer;+import org.apache.lucene.benchmark.Constants;+import org.apache.lucene.store.Directory;+++/**+ * This class holds together all parameters related to a test. Single test is+ * performed several times, and all results are averaged.+ *+ * @author Andrzej Bialecki <[email protected]>+ */+public class TestData+{+ public static int[] MAX_BUFFERED_DOCS_COUNTS = new int[]{10, 20, 50, 100, 200, 500};+ public static int[] MERGEFACTOR_COUNTS = new int[]{10, 20, 50, 100, 200, 500};++ /**+ * ID of this test data.+ */+ private String id;+ /**+ * Heap size.+ */+ private long heap;+ /**+ * List of results for each test run with these parameters.+ */+ private Vector runData = new Vector();+ private int maxBufferedDocs, mergeFactor;+ /**+ * Directory containing source files.+ */+ private File source;+ /**+ * Lucene Directory implementation for creating an index.+ */+ private Directory directory;+ /**+ * Analyzer to use when adding documents.+ */+ private Analyzer analyzer;+ /**+ * If true, use compound file format.+ */+ private boolean compound;+ /**+ * If true, optimize index when finished adding documents.+ */+ private boolean optimize;+ /**+ * Data for search benchmarks.+ */+ private QueryData[] queries;++ public TestData()+ {+ heap = Runtime.getRuntime().maxMemory();+ }++ private static class DCounter+ {+ double total;+ int count, recordCount;+ }++ private static class LCounter+ {+ long total;+ int count;+ }++ private static class LDCounter+ {+ double Dtotal;+ int Dcount, DrecordCount;+ long Ltotal0;+ int Lcount0;+ long Ltotal1;+ int Lcount1;+ }++ /**+ * Get a textual summary of the benchmark results, average from all test runs.+ */+ static final String ID = "# testData id ";+ static final String OP = "operation ";+ static final String RUNCNT = " runCnt";+ static final String RECCNT = " recCnt";+ static final String RECSEC = " rec/s";+ static final String FREEMEM = " avgFreeMem";+ static final String TOTMEM = " avgTotalMem";+ static final String COLS[] = {+ ID,+ OP,+ RUNCNT,+ RECCNT,+ RECSEC,+ FREEMEM,+ TOTMEM+ };+ public String showRunData(String prefix)+ {+ if (runData.size() == 0)+ {+ return "# [NO RUN DATA]";+ }+ HashMap resByTask = new HashMap();+ StringBuffer sb = new StringBuffer();+ String lineSep = System.getProperty("line.separator");+ sb.append("warm = Warm Index Reader").append(lineSep).append("srch = Search Index").append(lineSep).append("trav = Traverse Hits list, optionally retrieving document").append(lineSep).append(lineSep);+ for (int i = 0; i < COLS.length; i++) {+ sb.append(COLS[i]);+ }+ sb.append("\n");+ LinkedHashMap mapMem = new LinkedHashMap();+ LinkedHashMap mapSpeed = new LinkedHashMap();+ for (int i = 0; i < runData.size(); i++)+ {+ TestRunData trd = (TestRunData) runData.get(i);+ Collection labels = trd.getLabels();+ Iterator it = labels.iterator();+ while (it.hasNext())+ {+ String label = (String) it.next();+ MemUsage mem = trd.getMemUsage(label);+ if (mem != null)+ {+ TestData.LCounter[] tm = (TestData.LCounter[]) mapMem.get(label);+ if (tm == null)+ {+ tm = new TestData.LCounter[2];+ tm[0] = new TestData.LCounter();+ tm[1] = new TestData.LCounter();+ mapMem.put(label, tm);+ }+ tm[0].total += mem.avgFree;+ tm[0].count++;+ tm[1].total += mem.avgTotal;+ tm[1].count++;+ }+ TimeData td = trd.getTotals(label);+ if (td != null)+ {+ TestData.DCounter dc = (TestData.DCounter) mapSpeed.get(label);+ if (dc == null)+ {+ dc = new TestData.DCounter();+ mapSpeed.put(label, dc);+ }+ dc.count++;+ //dc.total += td.getRate();+ dc.total += (td.count>0 && td.elapsed<=0 ? 1 : td.elapsed); // assume atleast 1ms for any countable op+ dc.recordCount += td.count;+ }+ }+ }+ LinkedHashMap res = new LinkedHashMap();+ Iterator it = mapSpeed.keySet().iterator();+ while (it.hasNext())+ {+ String label = (String) it.next();+ TestData.DCounter dc = (TestData.DCounter) mapSpeed.get(label);+ res.put(label,+ format(dc.count, RUNCNT) ++ format(dc.recordCount / dc.count, RECCNT) ++ format(1,(float) (dc.recordCount * 1000.0 / (dc.total>0 ? dc.total : 1.0)), RECSEC)+ //format((float) (dc.total / (double) dc.count), RECSEC)+ );++ // also sum by task+ String task = label.substring(label.lastIndexOf("-")+1);+ LDCounter ldc = (LDCounter) resByTask.get(task);+ if (ldc==null) {+ ldc = new LDCounter();+ resByTask.put(task,ldc);+ }+ ldc.Dcount += dc.count;+ ldc.DrecordCount += dc.recordCount;+ ldc.Dtotal += (dc.count>0 && dc.total<=0 ? 1 : dc.total); // assume atleast 1ms for any countable op+ }+ it = mapMem.keySet().iterator();+ while (it.hasNext())+ {+ String label = (String) it.next();+ TestData.LCounter[] lc = (TestData.LCounter[]) mapMem.get(label);+ String speed = (String) res.get(label);+ boolean makeSpeed = false;+ if (speed == null)+ {+ makeSpeed = true;+ speed =+ format(lc[0].count, RUNCNT) ++ format(0, RECCNT) ++ format(0,(float)0.0, RECSEC);+ }+ res.put(label, speed ++ format(0, lc[0].total / lc[0].count, FREEMEM) ++ format(0, lc[1].total / lc[1].count, TOTMEM));++ // also sum by task+ String task = label.substring(label.lastIndexOf("-")+1);+ LDCounter ldc = (LDCounter) resByTask.get(task);+ if (ldc==null) {+ ldc = new LDCounter();+ resByTask.put(task,ldc);+ makeSpeed = true;+ }+ if (makeSpeed) {+ ldc.Dcount += lc[0].count;+ }+ ldc.Lcount0 += lc[0].count;+ ldc.Lcount1 += lc[1].count;+ ldc.Ltotal0 += lc[0].total;+ ldc.Ltotal1 += lc[1].total;+ }+ it = res.keySet().iterator();+ while (it.hasNext())+ {+ String label = (String) it.next();+ sb.append(format(prefix, ID));+ sb.append(format(label, OP));+ sb.append(res.get(label)).append("\n");+ }+ // show results by task (srch, optimize, etc.)+ sb.append("\n");+ for (int i = 0; i < COLS.length; i++) {+ sb.append(COLS[i]);+ }+ sb.append("\n");+ it = resByTask.keySet().iterator();+ while (it.hasNext())+ {+ String task = (String) it.next();+ LDCounter ldc = (LDCounter) resByTask.get(task);+ sb.append(format(" ", ID));+ sb.append(format(task, OP));+ sb.append(format(ldc.Dcount, RUNCNT));+ sb.append(format(ldc.DrecordCount / ldc.Dcount, RECCNT));+ sb.append(format(1,(float) (ldc.DrecordCount * 1000.0 / (ldc.Dtotal>0 ? ldc.Dtotal : 1.0)), RECSEC));+ sb.append(format(0, ldc.Ltotal0 / ldc.Lcount0, FREEMEM));+ sb.append(format(0, ldc.Ltotal1 / ldc.Lcount1, TOTMEM));+ sb.append("\n");+ }+ return sb.toString();+ }++ private static NumberFormat numFormat [] = { NumberFormat.getInstance(), NumberFormat.getInstance()};+ private static final String padd = " ";+ static {+ numFormat[0].setMaximumFractionDigits(0);+ numFormat[0].setMinimumFractionDigits(0);+ numFormat[1].setMaximumFractionDigits(1);+ numFormat[1].setMinimumFractionDigits(1);+ }++ // padd number from left+ // numFracDigits must be 0 or 1.+ static String format(int numFracDigits, float f, String col) {+ String res = padd + numFormat[numFracDigits].format(f);+ return res.substring(res.length() - col.length());+ }++ // padd number from left+ static String format(int n, String col) {+ String res = padd + n;+ return res.substring(res.length() - col.length());+ }++ // padd string from right+ static String format(String s, String col) {+ return (s + padd).substring(0,col.length());+ }++ /**+ * Prepare a list of benchmark data, using all possible combinations of+ * benchmark parameters.+ *+ * @param sources list of directories containing different source document+ * collections+ * @param analyzers of analyzers to use.+ */+ public static TestData[] getAll(File[] sources, Analyzer[] analyzers)+ {+ List res = new ArrayList(50);+ TestData ref = new TestData();+ for (int q = 0; q < analyzers.length; q++)+ {+ for (int m = 0; m < sources.length; m++)+ {+ for (int i = 0; i < MAX_BUFFERED_DOCS_COUNTS.length; i++)+ {+ for (int k = 0; k < MERGEFACTOR_COUNTS.length; k++)+ {+ for (int n = 0; n < Constants.BOOLEANS.length; n++)+ {+ for (int p = 0; p < Constants.BOOLEANS.length; p++)+ {+ ref.id = "td-" + q + m + i + k + n + p;+ ref.source = sources[m];+ ref.analyzer = analyzers[q];+ ref.maxBufferedDocs = MAX_BUFFERED_DOCS_COUNTS[i];+ ref.mergeFactor = MERGEFACTOR_COUNTS[k];+ ref.compound = Constants.BOOLEANS[n].booleanValue();+ ref.optimize = Constants.BOOLEANS[p].booleanValue();+ try+ {+ res.add(ref.clone());+ }+ catch (Exception e)+ {+ e.printStackTrace();+ }+ }+ }+ }+ }+ }+ }+ return (TestData[]) res.toArray(new TestData[0]);+ }++ /**+ * Similar to {@link #getAll(java.io.File[], org.apache.lucene.analysis.Analyzer[])} but only uses+ * maxBufferedDocs of 10 and 100 and same for mergeFactor, thus reducing the number of permutations significantly.+ * It also only uses compund file and optimize is always true.+ *+ * @param sources+ * @param analyzers+ * @return An Array of {@link TestData}+ */+ public static TestData[] getTestDataMinMaxMergeAndMaxBuffered(File[] sources, Analyzer[] analyzers)+ {+ List res = new ArrayList(50);+ TestData ref = new TestData();+ for (int q = 0; q < analyzers.length; q++)+ {+ for (int m = 0; m < sources.length; m++)+ {+ ref.id = "td-" + q + m + "_" + 10 + "_" + 10;+ ref.source = sources[m];+ ref.analyzer = analyzers[q];+ ref.maxBufferedDocs = 10;+ ref.mergeFactor = 10;//MERGEFACTOR_COUNTS[k];+ ref.compound = true;+ ref.optimize = true;+ try+ {+ res.add(ref.clone());+ }+ catch (Exception e)+ {+ e.printStackTrace();+ }+ ref.id = "td-" + q + m + "_" + 10 + "_" + 100;+ ref.source = sources[m];+ ref.analyzer = analyzers[q];+ ref.maxBufferedDocs = 10;+ ref.mergeFactor = 100;//MERGEFACTOR_COUNTS[k];+ ref.compound = true;+ ref.optimize = true;+ try+ {+ res.add(ref.clone());+ }+ catch (Exception e)+ {+ e.printStackTrace();+ }+ ref.id = "td-" + q + m + "_" + 100 + "_" + 10;+ ref.source = sources[m];+ ref.analyzer = analyzers[q];+ ref.maxBufferedDocs = 100;+ ref.mergeFactor = 10;//MERGEFACTOR_COUNTS[k];+ ref.compound = true;+ ref.optimize = true;+ try+ {+ res.add(ref.clone());+ }+ catch (Exception e)+ {+ e.printStackTrace();+ }+ ref.id = "td-" + q + m + "_" + 100 + "_" + 100;+ ref.source = sources[m];+ ref.analyzer = analyzers[q];+ ref.maxBufferedDocs = 100;+ ref.mergeFactor = 100;//MERGEFACTOR_COUNTS[k];+ ref.compound = true;+ ref.optimize = true;+ try+ {+ res.add(ref.clone());+ }+ catch (Exception e)+ {+ e.printStackTrace();+ }+ }+ }+ return (TestData[]) res.toArray(new TestData[0]);+ }++ protected Object clone()+ {+ TestData cl = new TestData();+ cl.id = id;+ cl.compound = compound;+ cl.heap = heap;+ cl.mergeFactor = mergeFactor;+ cl.maxBufferedDocs = maxBufferedDocs;+ cl.optimize = optimize;+ cl.source = source;+ cl.directory = directory;+ cl.analyzer = analyzer;+ // don't clone runData+ return cl;+ }++ public String toString()+ {+ StringBuffer res = new StringBuffer();+ res.append("#-- ID: ").append(id).append(", ").append(new Date()).append(", heap=").append(heap).append(" --\n");+ res.append("# source=").append(source).append(", directory=").append(directory).append("\n");+ res.append("# maxBufferedDocs=").append(maxBufferedDocs).append(", mergeFactor=").append(mergeFactor);+ res.append(", compound=").append(compound).append(", optimize=").append(optimize).append("\n");+ if (queries != null)+ {+ res.append(QueryData.getLabels()).append("\n");+ for (int i = 0; i < queries.length; i++)+ {+ res.append("# ").append(queries[i].toString()).append("\n");+ }+ }+ return res.toString();+ }++ public Analyzer getAnalyzer()+ {+ return analyzer;+ }++ public void setAnalyzer(Analyzer analyzer)+ {+ this.analyzer = analyzer;+ }++ public boolean isCompound()+ {+ return compound;+ }++ public void setCompound(boolean compound)+ {+ this.compound = compound;+ }++ public Directory getDirectory()+ {+ return directory;+ }++ public void setDirectory(Directory directory)+ {+ this.directory = directory;+ }++ public long getHeap()+ {+ return heap;+ }++ public void setHeap(long heap)+ {+ this.heap = heap;+ }++ public String getId()+ {+ return id;+ }++ public void setId(String id)+ {+ this.id = id;+ }++ public int getMaxBufferedDocs()+ {+ return maxBufferedDocs;+ }++ public void setMaxBufferedDocs(int maxBufferedDocs)+ {+ this.maxBufferedDocs = maxBufferedDocs;+ }++ public int getMergeFactor()+ {+ return mergeFactor;+ }++ public void setMergeFactor(int mergeFactor)+ {+ this.mergeFactor = mergeFactor;+ }++ public boolean isOptimize()+ {+ return optimize;+ }++ public void setOptimize(boolean optimize)+ {+ this.optimize = optimize;+ }++ public QueryData[] getQueries()+ {+ return queries;+ }++ public void setQueries(QueryData[] queries)+ {+ this.queries = queries;+ }++ public Vector getRunData()+ {+ return runData;+ }++ public void setRunData(Vector runData)+ {+ this.runData = runData;+ }++ public File getSource()+ {+ return source;+ }++ public void setSource(File source)+ {+ this.source = source;+ }+}diff --git a/contrib/benchmark/src/java/org/apache/lucene/benchmark/stats/TimeData.java b/contrib/benchmark/src/java/org/apache/lucene/benchmark/stats/TimeData.javaindex 91252fffb70..c2c76210c8f 100644--- a/contrib/benchmark/src/java/org/apache/lucene/benchmark/stats/TimeData.java+++ b/contrib/benchmark/src/java/org/apache/lucene/benchmark/stats/TimeData.java@@ -1,102 +1,102 @@-package org.apache.lucene.benchmark.stats;-/**- * Copyright 2005 The Apache Software Foundation- *- * Licensed 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.- */---/**- * This class holds a data point measuring speed of processing.- *- * @author Andrzej Bialecki <[email protected]>- */-public class TimeData {- /** Name of the data point - usually one of a data series with the same name */- public String name;- /** Number of records processed. */- public long count = 0;- /** Elapsed time in milliseconds. */- public long elapsed = 0L;-- private long delta = 0L;- /** Free memory at the end of measurement interval. */- public long freeMem = 0L;- /** Total memory at the end of measurement interval. */- public long totalMem = 0L;-- public TimeData() {};-- public TimeData(String name) {- this.name = name;- }-- /** Start counting elapsed time. */- public void start() {- delta = System.currentTimeMillis();- }-- /** Stop counting elapsed time. */- public void stop() {- count++;- elapsed += (System.currentTimeMillis() - delta);- }-- /** Record memory usage. */- public void recordMemUsage() {- freeMem = Runtime.getRuntime().freeMemory();- totalMem = Runtime.getRuntime().totalMemory();- }-- /** Reset counters. */- public void reset() {- count = 0;- elapsed = 0L;- delta = elapsed;- }-- protected Object clone() {- TimeData td = new TimeData(name);- td.name = name;- td.elapsed = elapsed;- td.count = count;- td.delta = delta;- td.freeMem = freeMem;- td.totalMem = totalMem;- return td;- }-- /** Get rate of processing, defined as number of processed records per second. */- public double getRate() {- double rps = (double) count * 1000.0 / (double) (elapsed>0 ? elapsed : 1); // assume atleast 1ms for any countable op- return rps;- }-- /** Get a short legend for toString() output. */- public static String getLabels() {- return "# count\telapsed\trec/s\tfreeMem\ttotalMem";- }-- public String toString() { return toString(true); }- /**- * Return a tab-seprated string containing this data.- * @param withMem if true, append also memory information- * @return The String- */- public String toString(boolean withMem) {- StringBuffer sb = new StringBuffer();- sb.append(count + "\t" + elapsed + "\t" + getRate());- if (withMem) sb.append("\t" + freeMem + "\t" + totalMem);- return sb.toString();- }-}+package org.apache.lucene.benchmark.stats;+/**+ * Copyright 2005 The Apache Software Foundation+ *+ * Licensed 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.+ */+++/**+ * This class holds a data point measuring speed of processing.+ *+ * @author Andrzej Bialecki <[email protected]>+ */+public class TimeData {+ /** Name of the data point - usually one of a data series with the same name */+ public String name;+ /** Number of records processed. */+ public long count = 0;+ /** Elapsed time in milliseconds. */+ public long elapsed = 0L;++ private long delta = 0L;+ /** Free memory at the end of measurement interval. */+ public long freeMem = 0L;+ /** Total memory at the end of measurement interval. */+ public long totalMem = 0L;++ public TimeData() {};++ public TimeData(String name) {+ this.name = name;+ }++ /** Start counting elapsed time. */+ public void start() {+ delta = System.currentTimeMillis();+ }++ /** Stop counting elapsed time. */+ public void stop() {+ count++;+ elapsed += (System.currentTimeMillis() - delta);+ }++ /** Record memory usage. */+ public void recordMemUsage() {+ freeMem = Runtime.getRuntime().freeMemory();+ totalMem = Runtime.getRuntime().totalMemory();+ }++ /** Reset counters. */+ public void reset() {+ count = 0;+ elapsed = 0L;+ delta = elapsed;+ }++ protected Object clone() {+ TimeData td = new TimeData(name);+ td.name = name;+ td.elapsed = elapsed;+ td.count = count;+ td.delta = delta;+ td.freeMem = freeMem;+ td.totalMem = totalMem;+ return td;+ }++ /** Get rate of processing, defined as number of processed records per second. */+ public double getRate() {+ double rps = (double) count * 1000.0 / (double) (elapsed>0 ? elapsed : 1); // assume atleast 1ms for any countable op+ return rps;+ }++ /** Get a short legend for toString() output. */+ public static String getLabels() {+ return "# count\telapsed\trec/s\tfreeMem\ttotalMem";+ }++ public String toString() { return toString(true); }+ /**+ * Return a tab-seprated string containing this data.+ * @param withMem if true, append also memory information+ * @return The String+ */+ public String toString(boolean withMem) {+ StringBuffer sb = new StringBuffer();+ sb.append(count + "\t" + elapsed + "\t" + getRate());+ if (withMem) sb.append("\t" + freeMem + "\t" + totalMem);+ return sb.toString();+ }+}