Apache Solr open-source search software
gdata 2006-08-10 checkin
Yonik Seeleyaa32350b33bd
diff --git a/contrib/gdata-server/build.xml b/contrib/gdata-server/build.xmlindex 205e947dcab..89ff816be96 100644--- a/contrib/gdata-server/build.xml+++ b/contrib/gdata-server/build.xml@@ -25,11 +25,14 @@<include name="commons-digester-1.7.jar" /><include name="commons-beanutils.jar" /><include name="commons-collections-3.2.jar" />+ <include name="nekohtml.jar" />+ <include name="xercesImpl.jar" /><include name="${db4o.jar}" if="db4o.jar.present" />- </fileset>+ </fileset></path>-- <!-- redefine compile-core and compile-test to exclude 3rd party dependend sources -->+++ <!-- redefine compile-core and compile-test to exclude 3rd party dependend sources --><target name="compile-core" depends="init"><echo>Use gdata - compile-core task </echo><compile srcdir="src/java" destdir="${build.dir}/classes/java">@@ -74,7 +77,10 @@<include name="commons-digester-1.7.jar" /><include name="commons-beanutils.jar" /><include name="commons-collections-3.2.jar" />+ <include name="nekohtml.jar" />+ <include name="xercesImpl.jar" /><include name="${db4o.jar}" if="db4o.jar.present" />+</lib><lib dir="${build.dir}" includes="${final.name}.jar" /><lib file="${lucene.jar}" />diff --git a/contrib/gdata-server/lib/nekohtml.jar b/contrib/gdata-server/lib/nekohtml.jarnew file mode 100644index 00000000000..5b0026f109a--- /dev/null+++ b/contrib/gdata-server/lib/nekohtml.jar@@ -0,0 +1,2 @@+AnyObjectId[ebd5b4b2a7a1d8b67c1717b364fb9affb35dca1e] was removed in git history.+Apache SVN contains full history.\ No newline at end of filediff --git a/contrib/gdata-server/lib/xercesImpl.jar b/contrib/gdata-server/lib/xercesImpl.jarnew file mode 100644index 00000000000..797b86a8d75--- /dev/null+++ b/contrib/gdata-server/lib/xercesImpl.jar@@ -0,0 +1,2 @@+AnyObjectId[33990e8a1fdf24e15701e4cf8d9f091038394ecd] was removed in git history.+Apache SVN contains full history.\ No newline at end of filediff --git a/contrib/gdata-server/src/java/org/apache/lucene/gdata/data/GDataAccount.java b/contrib/gdata-server/src/java/org/apache/lucene/gdata/data/GDataAccount.javaindex 2d4ec4b1c82..4674fd86238 100644--- a/contrib/gdata-server/src/java/org/apache/lucene/gdata/data/GDataAccount.java+++ b/contrib/gdata-server/src/java/org/apache/lucene/gdata/data/GDataAccount.java@@ -226,6 +226,8 @@ public class GDataAccount {* @see java.lang.Object#equals(java.lang.Object)*/public boolean equals(Object o) {+ if(this.name == null)+ return super.equals(o);if(o == null)return false;if (this == o)@@ -243,6 +245,8 @@ public class GDataAccount {* @see java.lang.Object#hashCode()*/public int hashCode() {+ if(this.name == null)+ return super.hashCode();int ret = 37;ret = 9 * ret + this.name.hashCode();return ret;@@ -269,14 +273,14 @@ public class GDataAccount {builder.append(" password: ").append((this.password!= null?" length: "+this.password.length():null));builder.append(" author: ").append(this.authorname);builder.append(" author email: ").append(this.authorMail);- builder.append(" author link: ").append(this.authorLink);+ builder.append(" author link: ").append(this.authorLink!=null?"":this.authorLink);return builder.toString();}/*** checks whether the given integer matches the account role.* @param intRole - integer representation of a role- * @param role - the accountrole to match+ * @param role - the account role to match* @return <code>true</code> if and only if the given roles match, otherwise <code>false</code>*/public static boolean isInRole(int intRole, AccountRole role){@@ -292,7 +296,7 @@ public class GDataAccount {}/**- * @return - a new Administartor accoutn+ * @return - a new Administrator account*/public static final GDataAccount createAdminAccount(){GDataAccount retVal = new GDataAccount();diff --git a/contrib/gdata-server/src/java/org/apache/lucene/gdata/search/GDataSearcher.java b/contrib/gdata-server/src/java/org/apache/lucene/gdata/search/GDataSearcher.javanew file mode 100755index 00000000000..b7f918b5215--- /dev/null+++ b/contrib/gdata-server/src/java/org/apache/lucene/gdata/search/GDataSearcher.java@@ -0,0 +1,44 @@+/**+ * Copyright 2004 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.+ */+package org.apache.lucene.gdata.search;++import java.io.IOException;+import java.util.List;++import org.apache.lucene.search.Query;++/**+ * @author Simon Willnauer+ * @param <T>+ *+ */+public interface GDataSearcher <T>{++ /**+ * executes an Query and returns a list of defined return values of type T+ * @param query - the query to apply to the searcher+ * @param hitcount - the amount of hits returned by this search+ * @param offset - the hit count offset+ * @param feedId+ * @return List of T+ * @throws IOException - if the underlying lucene searcher throws an IO Exception+ */+ public List<T> search(Query query,int hitcount, int offset, String feedId)throws IOException;+ /**+ * Destroys this Searcher+ */+ public abstract void close();+}diff --git a/contrib/gdata-server/src/java/org/apache/lucene/gdata/search/SearchComponent.java b/contrib/gdata-server/src/java/org/apache/lucene/gdata/search/SearchComponent.javanew file mode 100755index 00000000000..97373f74da8--- /dev/null+++ b/contrib/gdata-server/src/java/org/apache/lucene/gdata/search/SearchComponent.java@@ -0,0 +1,38 @@+/**+ * Copyright 2004 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.+ */++package org.apache.lucene.gdata.search;++import org.apache.lucene.gdata.server.registry.ProvidedService;+import org.apache.lucene.gdata.server.registry.ServerComponent;++/**+ * TODO document this when Search comes into play+ *+ * @author Simon Willnauer+ *+ */+public interface SearchComponent extends ServerComponent {+ /**+ * TODO document this when Search comes into play+ *+ * @param service+ *+ * @return a GDataSearcher+ */+ public abstract GDataSearcher<String> getServiceSearcher(ProvidedService service);++}diff --git a/contrib/gdata-server/src/java/org/apache/lucene/gdata/search/StandardGdataSearcher.java b/contrib/gdata-server/src/java/org/apache/lucene/gdata/search/StandardGdataSearcher.javanew file mode 100755index 00000000000..2e3fdf4ba25--- /dev/null+++ b/contrib/gdata-server/src/java/org/apache/lucene/gdata/search/StandardGdataSearcher.java@@ -0,0 +1,132 @@+/**+ * Copyright 2004 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.+ */++package org.apache.lucene.gdata.search;++import java.io.IOException;+import java.util.ArrayList;+import java.util.List;+import java.util.Map;+import java.util.WeakHashMap;+import java.util.concurrent.atomic.AtomicBoolean;++import org.apache.lucene.document.Document;+import org.apache.lucene.document.Field;+import org.apache.lucene.gdata.search.index.IndexDocument;+import org.apache.lucene.gdata.utils.ReferenceCounter;+import org.apache.lucene.index.Term;+import org.apache.lucene.search.Hits;+import org.apache.lucene.search.IndexSearcher;+import org.apache.lucene.search.Query;+import org.apache.lucene.search.QueryFilter;+import org.apache.lucene.search.TermQuery;++/**+ * Standard implementation of+ * {@link org.apache.lucene.gdata.search.GDataSearcher}+ *+ * @author Simon Willnauer+ *+ */+public class StandardGdataSearcher implements GDataSearcher<String> {+ private final AtomicBoolean isClosed = new AtomicBoolean(false);++ private final ReferenceCounter<IndexSearcher> searcher;++ private static final Map<String, QueryFilter> queryFilterCache = new WeakHashMap<String, QueryFilter>();++ /** constructs a new GdataSearcher+ * @param searcher - the current lucene searcher instance+ */+ public StandardGdataSearcher(ReferenceCounter<IndexSearcher> searcher) {+ if (searcher == null)+ throw new IllegalArgumentException("searcher must not be null");++ this.searcher = searcher;++ }++ /**+ * @see org.apache.lucene.gdata.search.GDataSearcher#search(org.apache.lucene.search.Query,+ * int, int, java.lang.String)+ */+ public List<String> search(Query query, int hitcount, int offset,+ String feedId) throws IOException {+ if (hitcount < 0 || offset < 0)+ throw new IllegalArgumentException(+ "hit count and offset must not be less than 0");+ if (this.isClosed.get())+ throw new IllegalStateException("Searcher is closed");+ if (query == null)+ throw new RuntimeException("query is null can not apply search");+ if (feedId == null)+ throw new IllegalArgumentException("feed id must not be null");+ QueryFilter filter = null;+ synchronized (queryFilterCache) {+ filter = queryFilterCache.get(feedId);+ }+ if (filter == null)+ filter = new QueryFilter(new TermQuery(new Term(+ IndexDocument.FIELD_FEED_ID, feedId)));+ IndexSearcher indexSearcher = this.searcher.get();+ Hits hits = indexSearcher.search(query, filter);+ synchronized (queryFilterCache) {+ queryFilterCache.put(feedId, filter);+ }+ return collectHits(hits, hitcount, offset);++ }++ protected List<String> collectHits(Hits hits, int hitcount, int offset)+ throws IOException {+ int hitLength = hits.length();+ if (hitLength < offset || hitLength == 0)+ return new ArrayList<String>(0);+ if (offset > 0)+ --offset;+ /*+ * include the offset+ */+ int remainingHits = hitLength - offset;+ int returnSize = remainingHits > hitcount ? hitcount : remainingHits;+ List<String> retVal = new ArrayList<String>(returnSize);+ for (int i = 0; i < returnSize; i++) {+ Document doc = hits.doc(offset++);+ /*+ * the entry id is sufficient to retrieve the entry from the+ * storage. the result will be ordered by score (default)+ */+ Field field = doc.getField(IndexDocument.FIELD_ENTRY_ID);+ retVal.add(i, field.stringValue());+ }+ return retVal;++ }++ /**+ * @see org.apache.lucene.gdata.search.GDataSearcher#close()+ */+ public void close() {+ this.isClosed.set(true);+ this.searcher.decrementRef();++ }++ static void flushFilterCache() {+ queryFilterCache.clear();+ }++}diff --git a/contrib/gdata-server/src/java/org/apache/lucene/gdata/search/analysis/ContentStrategy.java b/contrib/gdata-server/src/java/org/apache/lucene/gdata/search/analysis/ContentStrategy.javanew file mode 100755index 00000000000..9d56a6d4d2f--- /dev/null+++ b/contrib/gdata-server/src/java/org/apache/lucene/gdata/search/analysis/ContentStrategy.java@@ -0,0 +1,178 @@+/**+ * Copyright 2004 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.+ */+package org.apache.lucene.gdata.search.analysis;++import org.apache.lucene.document.Field;+import org.apache.lucene.document.Field.Index;+import org.apache.lucene.document.Field.Store;+import org.apache.lucene.gdata.data.ServerBaseEntry;+import org.apache.lucene.gdata.search.config.IndexSchemaField;+import org.apache.lucene.gdata.search.config.IndexSchemaField.ContentType;+import org.apache.lucene.gdata.search.index.GdataIndexerException;+import org.apache.lucene.gdata.utils.ReflectionUtils;+import org.w3c.dom.Node;++/**+ * Creating Indexable document requires processing of incoming entities as+ * GData Entries. Entries in the GData protocol might have very different+ * structures and content. They all have on thing in common as they are atom xml+ * format. To retrieve the configured elements of the atom format and process the+ * actual content might differ from element to element.+ * <p>+ * Each predefined ContentStrategy can be used to retrieve certain content from+ * the defined element. Which element to process is defined using a XPath+ * expression in the gdata-config.xml file.+ * </p>+ * <p>+ * <tt>ContentStrategy</tt> implementation should not be accessed directly. To+ * get a <tt>ContentStrategy</tt> for a specific+ * {@link org.apache.lucene.gdata.search.config.IndexSchemaField.ContentType}+ * use the {@link ContentStrategy#getFieldStrategy} factory method. This method+ * expects a IndexSchemaField instance with a set <tt>ContentType</tt>. The+ * return value is a new <tt>ContentStrategy</tt> instance for the defined+ * <tt>ContentType</tt>.+ * </p>+ *+ * @see org.apache.lucene.gdata.search.config.IndexSchemaField.ContentType+ * @see org.apache.lucene.gdata.search.index.IndexDocumentBuilder+ *+ * @author Simon Willnauer+ */+public abstract class ContentStrategy {+ protected final Store store;++ protected final Index index;++ protected final IndexSchemaField config;++ protected String content;++ protected String fieldName;++ protected ContentStrategy(IndexSchemaField fieldConfiguration) {+ this(null, null, fieldConfiguration);+ }++ protected ContentStrategy(Index index, Store store,+ IndexSchemaField fieldConfig) {+ if(fieldConfig == null)+ throw new IllegalArgumentException("IndexSchemaField must not be null");+ this.config = fieldConfig;+ this.fieldName = fieldConfig.getName();+ if (index != null) {+ this.index = index;+ } else {+ this.index = fieldConfig.getIndex() == null ? IndexSchemaField.DEFAULT_INDEX_STRATEGY+ : fieldConfig.getIndex();+ }+ if (store != null) {+ this.store = store;+ } else {+ this.store = fieldConfig.getStore() == null ? IndexSchemaField.DEFAULT_STORE_STRATEGY+ : fieldConfig.getStore();+ }++ }++ /**+ * @param indexable+ * @throws NotIndexableException+ */+ public abstract void processIndexable(+ Indexable<? extends Node, ? extends ServerBaseEntry> indexable)+ throws NotIndexableException;++ /**+ * This method creates a lucene field from the retrieved content of the+ * entity. Values for Field.Index, Field.Store, the field name and the boost+ * factor are configured in the <tt>IndexSchemaField</tt> passed by the+ * constructor e.g the factory method. This method might be overwritten by+ * subclasses.+ *+ * @return the Lucene {@link Field}+ */+ public Field[] createLuceneField() {+ /*+ * should I test the content for being empty?!+ * does that make any difference if empty fields are indexed?!+ */+ if(this.fieldName==null|| this.content == null)+ throw new GdataIndexerException("Required field not set fieldName: "+this.fieldName+" content: "+this.content);+ if(this.content.length()==0){+ return new Field[0];+ }+ Field retValue = new Field(this.fieldName, this.content, this.store,+ this.index);+ float boost = this.config.getBoost();+ if (boost != 1.0f)+ retValue.setBoost(boost);+ return new Field[]{retValue};++ }++ /**+ * This factory method creates the <tt>ContentStrategy</tt> corresponding+ * to the set <tt>ContentType</tt> value in the <tt>IndexSchemaField</tt>+ * passed to the method as the single parameter.+ * <p>+ * The ContentType must not be null+ * </p>+ *+ * @param fieldConfig -+ * the field config to use to identify the corresponding+ * <tt>ContentStrategy</tt>+ * @return - a new <tt>ContentStrategy</tt> instance+ */+ public static ContentStrategy getFieldStrategy(IndexSchemaField fieldConfig) {+ if (fieldConfig == null)+ throw new IllegalArgumentException(+ "field configuration must not be null");+ ContentType type = fieldConfig.getContentType();+ if (type == null)+ throw new IllegalArgumentException(+ "ContentType in IndexSchemaField must not be null");+ fieldConfig.getAnalyzerClass();++ switch (type) {+ case CATEGORY:+ return new GdataCategoryStrategy(fieldConfig);+ case HTML:+ return new HTMLStrategy(fieldConfig);+ case XHTML:+ return new XHtmlStrategy(fieldConfig);+ case GDATADATE:+ return new GdataDateStrategy(fieldConfig);+ case TEXT:+ return new PlainTextStrategy(fieldConfig);+ case KEYWORD:+ return new KeywordStrategy(fieldConfig);+ case CUSTOM:+ /*+ * check if this class can be created with default constructor is checked+ * in IndexSchemaField#setFieldClass and throws RuntimeEx if not. So+ * server can not start up.+ */+ return ReflectionUtils.getDefaultInstance(fieldConfig+ .getFieldClass());+ case MIXED:+ return new MixedContentStrategy(fieldConfig);+ default:+ throw new RuntimeException("No content strategy found for " + type);+ }++ }++}diff --git a/contrib/gdata-server/src/java/org/apache/lucene/gdata/search/analysis/DomIndexable.java b/contrib/gdata-server/src/java/org/apache/lucene/gdata/search/analysis/DomIndexable.javanew file mode 100755index 00000000000..32336486511--- /dev/null+++ b/contrib/gdata-server/src/java/org/apache/lucene/gdata/search/analysis/DomIndexable.java@@ -0,0 +1,109 @@+/**+ * Copyright 2004 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.+ */+package org.apache.lucene.gdata.search.analysis;++import java.io.IOException;+import java.io.StringReader;+import java.io.StringWriter;++import javax.xml.parsers.DocumentBuilder;+import javax.xml.parsers.DocumentBuilderFactory;+import javax.xml.parsers.ParserConfigurationException;+import javax.xml.xpath.XPath;+import javax.xml.xpath.XPathConstants;+import javax.xml.xpath.XPathExpressionException;+import javax.xml.xpath.XPathFactory;++import org.apache.lucene.gdata.data.ServerBaseEntry;+import org.w3c.dom.Document;+import org.w3c.dom.Node;+import org.xml.sax.InputSource;+import org.xml.sax.SAXException;++import com.google.gdata.data.ExtensionProfile;+import com.google.gdata.util.common.xml.XmlWriter;++/**+ * <tt>Indexable</tt> implementation using the W3C Dom API and JAXP XPath+ * engine+ *+ * @author Simon Willnauer+ * @param <R> -+ * a subtype of {@link org.w3c.dom.Node} returned by the applyPath+ * method+ * @param <I> -+ * a subtype of {@link org.apache.lucene.gdata.data.ServerBaseEntry}+ */+public class DomIndexable<R extends Node, I extends ServerBaseEntry> extends+ Indexable<R, I> {+ private final Document document;++ private final XPath xPath;++ /**+ * @param applyAble+ * @throws NotIndexableException+ */+ public DomIndexable(I applyAble) throws NotIndexableException {+ super(applyAble);+ if (this.applyAble.getServiceConfig() == null)+ throw new NotIndexableException("ServiceConfig is not set");+ try {+ this.document = buildDomDocument();+ } catch (ParserConfigurationException e) {+ throw new NotIndexableException("Can not create document builder",+ e);++ } catch (IOException e) {+ throw new NotIndexableException(+ "IO Exception occurred while building indexable", e);++ } catch (SAXException e) {+ throw new NotIndexableException("Can not parse entry", e);++ }+ this.xPath = XPathFactory.newInstance().newXPath();++ }++ private Document buildDomDocument() throws ParserConfigurationException,+ IOException, SAXException {+ StringWriter stringWriter = new StringWriter();+ ExtensionProfile profile = this.applyAble.getServiceConfig()+ .getExtensionProfile();+ if (profile == null)+ throw new IllegalStateException("ExtensionProfile is not set");+ XmlWriter writer = new XmlWriter(stringWriter);+ this.applyAble.generateAtom(writer, profile);+ DocumentBuilder builder = DocumentBuilderFactory.newInstance()+ .newDocumentBuilder();+ return builder.parse(new InputSource(new StringReader(stringWriter+ .toString())));++ }++ /**+ * @see org.apache.lucene.gdata.search.analysis.Indexable#applyPath(java.lang.String)+ */+ @SuppressWarnings("unchecked")+ @Override+ public R applyPath(String expression) throws XPathExpressionException {++ return (R) this.xPath.evaluate(expression, this.document,+ XPathConstants.NODE);+ }++}diff --git a/contrib/gdata-server/src/java/org/apache/lucene/gdata/search/analysis/GdataCategoryStrategy.java b/contrib/gdata-server/src/java/org/apache/lucene/gdata/search/analysis/GdataCategoryStrategy.javanew file mode 100755index 00000000000..89e8ceae015--- /dev/null+++ b/contrib/gdata-server/src/java/org/apache/lucene/gdata/search/analysis/GdataCategoryStrategy.java@@ -0,0 +1,163 @@+/**+ * Copyright 2004 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.+ */+package org.apache.lucene.gdata.search.analysis;++import java.util.ArrayList;+import java.util.List;++import javax.xml.xpath.XPathExpressionException;++import org.apache.lucene.document.Field;+import org.apache.lucene.gdata.data.ServerBaseEntry;+import org.apache.lucene.gdata.search.config.IndexSchemaField;+import org.apache.lucene.gdata.search.index.GdataIndexerException;+import org.w3c.dom.NamedNodeMap;+import org.w3c.dom.Node;++/**+ * This strategy retrieves the category term and and the scheme from a category+ * element. The content is represented by the term which can be configured via+ * the configuration file.+ * <p>+ * The category element has at least one attribute with the name "scheme" which+ * is not mandatory. The term can be the default attribute "term" or the text+ * content of the element, this is configured via the path of the field.+ * </p>+ * <p>+ * <tt><category scheme="http://www.example.com/type" term="blog.post"/><tt>+ * </p>+ * TODO extend javadoc for search info+ * @author Simon Willnauer+ *+ */+public class GdataCategoryStrategy extends ContentStrategy {+ protected String categoryScheme;++ protected String categorySchemeField;++ private static final String LABEL = "label";++ private static final String SCHEME = "scheme";++ private static final String TERM = "term";++ /**+ * the string to search a schema if no schema is specified+ */+ public static final String CATEGORY_SCHEMA_NULL_VALUE = "LUCISCHEMANULL";++ /**+ * Schema field suffix+ */+ public static final String CATEGORY_SCHEMA_FIELD_SUFFIX = "-schema";++ protected GdataCategoryStrategy(IndexSchemaField fieldConfiguration) {+ super(fieldConfiguration);+ this.categorySchemeField = new StringBuilder(this.fieldName).append(+ CATEGORY_SCHEMA_FIELD_SUFFIX).toString();++ }++ /**+ * @throws NotIndexableException+ * @see org.apache.lucene.gdata.search.analysis.ContentStrategy#processIndexable(org.apache.lucene.gdata.search.analysis.Indexable)+ */+ @Override+ public void processIndexable(+ Indexable<? extends Node, ? extends ServerBaseEntry> indexable)+ throws NotIndexableException {+ String contentPath = this.config.getPath();+ Node node = null;+ try {+ node = indexable.applyPath(contentPath);+ } catch (XPathExpressionException e) {++ throw new NotIndexableException("Can not apply path");+ }+ if (node == null)+ throw new NotIndexableException(+ "Could not retrieve content for schema field: "+ + this.config);++ StringBuilder contentBuilder = new StringBuilder();+ StringBuilder schemeBuilder = new StringBuilder();+ /*+ * enable more than one category element+ */+ while (node != null) {+ NamedNodeMap attributeMap = node.getAttributes();+ if (attributeMap == null)+ throw new NotIndexableException(+ "category term attribute not present");+ /*+ * the "term" is the internal string used by the software to+ * identify the category, while the "label" is the human-readable+ * string presented to a user in a user interface.+ */+ Node termNode = attributeMap.getNamedItem(TERM);+ if (termNode == null)+ throw new NotIndexableException(+ "category term attribute not present");+ contentBuilder.append(termNode.getTextContent()).append(" ");++ Node labelNode = attributeMap.getNamedItem(LABEL);+ if (labelNode != null)+ contentBuilder.append(labelNode.getTextContent()).append(" ");++ Node schemeNode = attributeMap.getNamedItem(SCHEME);+ if (schemeNode != null)+ schemeBuilder.append(schemeNode.getTextContent());+ node = node.getNextSibling();+ }++ this.content = contentBuilder.toString();+ this.categoryScheme = schemeBuilder.toString();+ }++ /**+ * @see org.apache.lucene.gdata.search.analysis.ContentStrategy#createLuceneField()+ */+ @Override+ public Field[] createLuceneField() {+ List<Field> retValue = new ArrayList<Field>(2);+ if (this.fieldName == null)+ throw new GdataIndexerException("Required field 'name' is null -- "+ + this.config);+ if (this.content == null)+ throw new GdataIndexerException(+ "Required field 'content' is null -- " + this.config);++ Field categoryTerm = new Field(this.fieldName, this.content,+ this.store, this.index);+ float boost = this.config.getBoost();+ if (boost != 1.0f)+ categoryTerm.setBoost(boost);+ retValue.add(categoryTerm);+ /*+ * if schema is not set index null value to enable search for categories+ * without a schema+ */+ if (this.categoryScheme == null || this.categoryScheme.length() == 0) {+ this.categoryScheme = CATEGORY_SCHEMA_NULL_VALUE;+ }+ Field categoryURN = new Field(this.categorySchemeField,+ this.categoryScheme, Field.Store.YES, Field.Index.UN_TOKENIZED);+ retValue.add(categoryURN);+ return retValue.toArray(new Field[0]);++ }++}diff --git a/contrib/gdata-server/src/java/org/apache/lucene/gdata/search/analysis/GdataDateStrategy.java b/contrib/gdata-server/src/java/org/apache/lucene/gdata/search/analysis/GdataDateStrategy.javanew file mode 100755index 00000000000..ffe236b87ac--- /dev/null+++ b/contrib/gdata-server/src/java/org/apache/lucene/gdata/search/analysis/GdataDateStrategy.java@@ -0,0 +1,98 @@+/**+ * Copyright 2004 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.+ */+package org.apache.lucene.gdata.search.analysis;++import javax.xml.xpath.XPathExpressionException;++import org.apache.lucene.document.Field;+import org.apache.lucene.gdata.data.ServerBaseEntry;+import org.apache.lucene.gdata.search.config.IndexSchemaField;+import org.apache.lucene.gdata.search.index.GdataIndexerException;+import org.w3c.dom.Node;++import com.google.gdata.data.DateTime;++/**+ * This content strategy retrieves a so called GData Date from a RFC 3339+ * timestamp format. The format will be parsed and indexed as a timestamp value.+ *+ * @author Simon Willnauer+ *+ */+public class GdataDateStrategy extends ContentStrategy {++ protected GdataDateStrategy(IndexSchemaField fieldConfiguration) {+ super(fieldConfiguration);++ }++ /**+ * @throws NotIndexableException+ * @see org.apache.lucene.gdata.search.analysis.ContentStrategy#processIndexable(org.apache.lucene.gdata.search.analysis.Indexable)+ */+ @Override+ public void processIndexable(+ Indexable<? extends Node, ? extends ServerBaseEntry> indexable)+ throws NotIndexableException {+ String path = this.config.getPath();+ Node node;+ try {+ node = indexable.applyPath(path);+ } catch (XPathExpressionException e1) {+ throw new NotIndexableException("Can not apply path -- " + path+ + " FieldConfig: " + this.config);+ }+ if (node == null)+ throw new NotIndexableException(+ "Could not retrieve content for schema field: "+ + this.config);+ String textContent = node.getTextContent();+ try {+ this.content = getTimeStamp(textContent);+ } catch (NumberFormatException e) {+ throw new NotIndexableException("Can not parse GData date -- "+ + textContent);+ }++ }++ /**+ * @see org.apache.lucene.gdata.search.analysis.ContentStrategy#createLuceneField()+ */+ @Override+ public Field[] createLuceneField() {+ if(this.fieldName == null)+ throw new GdataIndexerException(+ "Required field 'name' is null -- " +this.config);+ if(this.content == null)+ throw new GdataIndexerException(+ "Required field 'content' is null -- " +this.config);+ if(this.content.length()==0)+ return new Field[0];+ Field retValue = new Field(this.fieldName, this.content,+ Field.Store.YES, Field.Index.UN_TOKENIZED);+ float boost = this.config.getBoost();+ if (boost != 1.0f)+ retValue.setBoost(boost);+ return new Field[] { retValue };++ }++ private static String getTimeStamp(String dateString) {+ return Long.toString(DateTime.parseDateTimeChoice(dateString).getValue());+ }++}diff --git a/contrib/gdata-server/src/java/org/apache/lucene/gdata/search/analysis/HTMLStrategy.java b/contrib/gdata-server/src/java/org/apache/lucene/gdata/search/analysis/HTMLStrategy.javanew file mode 100755index 00000000000..dbfbee30083--- /dev/null+++ b/contrib/gdata-server/src/java/org/apache/lucene/gdata/search/analysis/HTMLStrategy.java@@ -0,0 +1,98 @@+/**+ * Copyright 2004 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.+ */+package org.apache.lucene.gdata.search.analysis;++import java.io.IOException;+import java.io.StringReader;+import java.io.StringWriter;++import javax.xml.xpath.XPathExpressionException;++import org.apache.lucene.gdata.data.ServerBaseEntry;+import org.apache.lucene.gdata.search.config.IndexSchemaField;+import org.apache.xerces.xni.XNIException;+import org.apache.xerces.xni.parser.XMLDocumentFilter;+import org.apache.xerces.xni.parser.XMLInputSource;+import org.apache.xerces.xni.parser.XMLParserConfiguration;+import org.cyberneko.html.HTMLConfiguration;+import org.cyberneko.html.filters.ElementRemover;+import org.cyberneko.html.filters.Writer;+import org.w3c.dom.Node;++/**+ * This ContentStrategy applies the path to the Indexable and retrieves the+ * plain string content from the returning node. All of the nodes text content+ * will cleaned from any html tags.+ *+ * @author Simon Willnauer+ *+ */+public class HTMLStrategy extends+ org.apache.lucene.gdata.search.analysis.ContentStrategy {+ private static final String REMOVE_SCRIPT = "script";++ private static final String CHAR_ENCODING = "UTF-8";++ protected HTMLStrategy(IndexSchemaField fieldConfiguration) {+ super(fieldConfiguration);++ }++ /**+ * @see org.apache.lucene.gdata.search.analysis.ContentStrategy#processIndexable(org.apache.lucene.gdata.search.analysis.Indexable)+ */+ @Override+ public void processIndexable(Indexable<? extends Node, ? extends ServerBaseEntry> indexable)+ throws NotIndexableException {+ String path = this.config.getPath();+ Node node = null;+ try {+ node = indexable.applyPath(path);+ } catch (XPathExpressionException e1) {+ throw new NotIndexableException("Can not apply path -- " + path);++ }+ if(node == null)+ throw new NotIndexableException("Could not retrieve content for schema field: "+this.config);+ StringReader contentReader = new StringReader(node.getTextContent());+ /*+ * remove all elements and script parts+ */+ ElementRemover remover = new ElementRemover();+ remover.removeElement(REMOVE_SCRIPT);+ StringWriter contentWriter = new StringWriter();+ Writer writer = new Writer(contentWriter, CHAR_ENCODING);+ XMLDocumentFilter[] filters = { remover, writer, };+ XMLParserConfiguration parser = new HTMLConfiguration();+ parser.setProperty("http://cyberneko.org/html/properties/filters",+ filters);+ XMLInputSource source = new XMLInputSource(null, null, null,+ contentReader, CHAR_ENCODING);+ try {+ parser.parse(source);+ } catch (XNIException e) {+ throw new NotIndexableException("Can not parse html -- ", e);++ } catch (IOException e) {+ throw new NotIndexableException("Can not parse html -- ", e);++ }+ this.content = contentWriter.toString();+ }++++}diff --git a/contrib/gdata-server/src/java/org/apache/lucene/gdata/search/analysis/Indexable.java b/contrib/gdata-server/src/java/org/apache/lucene/gdata/search/analysis/Indexable.javanew file mode 100755index 00000000000..1401d404f1b--- /dev/null+++ b/contrib/gdata-server/src/java/org/apache/lucene/gdata/search/analysis/Indexable.java@@ -0,0 +1,74 @@+/**+ * Copyright 2004 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.+ */+package org.apache.lucene.gdata.search.analysis;++import javax.xml.xpath.XPathExpressionException;++import org.apache.lucene.gdata.data.ServerBaseEntry;+import org.w3c.dom.Node;++/**+ * This class wraps the access to the GData entities to access them via xpath+ * expressions. An arbitrary valid Xpath expression can be passed to the+ * <tt>applyPath</tt> method to access an element, attribute etc. in the gdata+ * entity.+ *+ * @author Simon Willnauer+ * @param <R> -+ * a subtype of {@link org.w3c.dom.Node} returned by the applyPath+ * method+ * @param <I> -+ * a subtype of {@link org.apache.lucene.gdata.data.ServerBaseEntry}+ */+public abstract class Indexable<R extends Node, I extends ServerBaseEntry> {+ protected ServerBaseEntry applyAble;++ /**+ * @param applyAble+ */+ Indexable(I applyAble) {+ this.applyAble = applyAble;+ }++ /**+ * @param xPath -+ * a valid xpath expression+ * @return - the requested element <b>R</b>+ * @throws XPathExpressionException+ */+ public abstract R applyPath(String xPath) throws XPathExpressionException;++ /**+ * Factory method to create new <tt>Indexable</tt> instances.+ *+ * @param <R> -+ * a subtype of {@link org.w3c.dom.Node} returned by the+ * applyPath method+ * @param <I> -+ * a subtype of+ * {@link org.apache.lucene.gdata.data.ServerBaseEntry}+ * @param entry -+ * the entry to wrap in a <tt>Indexable</tt>+ * @return - a new instance of <tt>Indexable</tt> to access the entry via+ * Xpath+ * @throws NotIndexableException - if <b>I<b> can not be parsed.+ */+ public static <R extends Node, I extends ServerBaseEntry> Indexable<R, I> getIndexable(+ I entry) throws NotIndexableException {+ return new DomIndexable<R, I>(entry);+ }++}diff --git a/contrib/gdata-server/src/java/org/apache/lucene/gdata/search/analysis/KeywordStrategy.java b/contrib/gdata-server/src/java/org/apache/lucene/gdata/search/analysis/KeywordStrategy.javanew file mode 100755index 00000000000..26938b22105--- /dev/null+++ b/contrib/gdata-server/src/java/org/apache/lucene/gdata/search/analysis/KeywordStrategy.java@@ -0,0 +1,57 @@+/**+ * Copyright 2004 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.+ */+package org.apache.lucene.gdata.search.analysis;++import javax.xml.xpath.XPathExpressionException;++import org.apache.lucene.document.Field;+import org.apache.lucene.gdata.data.ServerBaseEntry;+import org.apache.lucene.gdata.search.config.IndexSchemaField;+import org.w3c.dom.Node;++/**+ * @author Simon Willnauer+ *+ */+public class KeywordStrategy extends ContentStrategy {++ /**+ * @param fieldConfig+ */+ public KeywordStrategy(IndexSchemaField fieldConfig) {+ super(Field.Index.UN_TOKENIZED,Field.Store.YES,fieldConfig);+ }++ /**+ * @see org.apache.lucene.gdata.search.analysis.ContentStrategy#processIndexable(org.apache.lucene.gdata.search.analysis.Indexable)+ */+ @Override+ public void processIndexable(Indexable<? extends Node, ? extends ServerBaseEntry> indexable) throws NotIndexableException {+ String path = this.config.getPath();+ try {+ Node node = indexable.applyPath(path);+ if(node == null)+ throw new NotIndexableException("Could not retrieve content for schema field: "+this.config);+ this.content = node.getTextContent();+ } catch (XPathExpressionException e) {+ throw new NotIndexableException("Can not apply Path", e);+ }++ }++++}diff --git a/contrib/gdata-server/src/java/org/apache/lucene/gdata/search/analysis/MixedContentStrategy.java b/contrib/gdata-server/src/java/org/apache/lucene/gdata/search/analysis/MixedContentStrategy.javanew file mode 100755index 00000000000..943102d247f--- /dev/null+++ b/contrib/gdata-server/src/java/org/apache/lucene/gdata/search/analysis/MixedContentStrategy.java@@ -0,0 +1,96 @@+/**+ * Copyright 2004 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.+ */++package org.apache.lucene.gdata.search.analysis;++import javax.xml.xpath.XPathExpressionException;++import org.apache.lucene.document.Field;+import org.apache.lucene.gdata.data.ServerBaseEntry;+import org.apache.lucene.gdata.search.config.IndexSchemaField;+import org.apache.lucene.gdata.search.config.IndexSchemaField.ContentType;+import org.w3c.dom.Node;++/**+ * @author Simon Willnauer+ *+ */+public class MixedContentStrategy extends ContentStrategy {+ protected ContentStrategy strategy;++ protected MixedContentStrategy(IndexSchemaField fieldConfiguration) {+ super(fieldConfiguration);++ }++ /**+ * @throws NotIndexableException+ * @see org.apache.lucene.gdata.search.analysis.ContentStrategy#processIndexable(org.apache.lucene.gdata.search.analysis.Indexable)+ */+ @Override+ public void processIndexable(+ Indexable<? extends Node, ? extends ServerBaseEntry> indexable)+ throws NotIndexableException {+ String path = this.config.getTypePath();++ try {+ Node node = indexable.applyPath(path);+ if (node == null)+ this.strategy = new PlainTextStrategy(this.config);+ else {+ String contentType = node.getTextContent();++ this.strategy = chooseStrategy(contentType, this.config);+ }+ this.strategy.processIndexable(indexable);+ } catch (XPathExpressionException e) {+ throw new NotIndexableException("Can not apply path -- " + path);++ }+ }++ /**+ * @see org.apache.lucene.gdata.search.analysis.ContentStrategy#createLuceneField()+ */+ @Override+ public Field[] createLuceneField() {++ return this.strategy.createLuceneField();+ }++ private static ContentStrategy chooseStrategy(final String contentType,+ final IndexSchemaField config) {+ ContentType type = null;+ try {+ type = ContentType.valueOf(contentType==null?"TEXT":contentType.toUpperCase());+ } catch (Throwable e) {+ type = ContentType.TEXT;+ }++ switch (type) {+ case HTML:+ return new HTMLStrategy(config);++ case XHTML:+ return new XHtmlStrategy(config);++ default:+ return new PlainTextStrategy(config);++ }+ }++}diff --git a/contrib/gdata-server/src/java/org/apache/lucene/gdata/search/analysis/NotIndexableException.java b/contrib/gdata-server/src/java/org/apache/lucene/gdata/search/analysis/NotIndexableException.javanew file mode 100755index 00000000000..9a8b8d4555c--- /dev/null+++ b/contrib/gdata-server/src/java/org/apache/lucene/gdata/search/analysis/NotIndexableException.java@@ -0,0 +1,78 @@+/**+ * Copyright 2004 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.+ */++package org.apache.lucene.gdata.search.analysis;++/**+ * This exception will be thrown by ContentStrategy instances if an exception+ * occurs while retrieving content from entries+ *+ * @author Simon Willnauer+ *+ */+public class NotIndexableException extends Exception {++ /**+ *+ */+ private static final long serialVersionUID = 1538388864181786380L;++ /**+ * Constructs a new NotIndexableException+ */+ public NotIndexableException() {+ super();++ }++ /**+ * Constructs a new NotIndexableException with the specified detail message.+ *+ * @param arg0 -+ * detail message+ */+ public NotIndexableException(String arg0) {+ super(arg0);++ }++ /**+ * Constructs a new NotIndexableException with the specified detail message+ * and nested exception.+ *+ * @param arg0 -+ * detail message+ * @param arg1 -+ * nested exception+ */+ public NotIndexableException(String arg0, Throwable arg1) {+ super(arg0, arg1);++ }++ /**+ * Constructs a new NotIndexableException with a nested exception caused+ * this exception.+ *+ * @param arg0 -+ * nested exception+ */+ public NotIndexableException(Throwable arg0) {+ super(arg0);++ }++}diff --git a/contrib/gdata-server/src/java/org/apache/lucene/gdata/search/analysis/PlainTextStrategy.java b/contrib/gdata-server/src/java/org/apache/lucene/gdata/search/analysis/PlainTextStrategy.javanew file mode 100755index 00000000000..b8603824d79--- /dev/null+++ b/contrib/gdata-server/src/java/org/apache/lucene/gdata/search/analysis/PlainTextStrategy.java@@ -0,0 +1,54 @@+/**+ * Copyright 2004 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.+ */++package org.apache.lucene.gdata.search.analysis;++import javax.xml.xpath.XPathExpressionException;++import org.apache.lucene.gdata.data.ServerBaseEntry;+import org.apache.lucene.gdata.search.config.IndexSchemaField;+import org.w3c.dom.Node;++/**+ * @author Simon Willnauer+ *+ */+public class PlainTextStrategy extends ContentStrategy {++ protected PlainTextStrategy(IndexSchemaField fieldConfiguration) {+ super(fieldConfiguration);++ }++ /**+ * @see org.apache.lucene.gdata.search.analysis.ContentStrategy#processIndexable(org.apache.lucene.gdata.search.analysis.Indexable)+ */+ @Override+ public void processIndexable(Indexable<? extends Node, ? extends ServerBaseEntry> indexable)+ throws NotIndexableException {+ String path = this.config.getPath();+ try {+ Node node = indexable.applyPath(path);+ if(node == null)+ throw new NotIndexableException("Could not retrieve content for schema field: "+this.config);+ this.content = node.getTextContent();++ } catch (XPathExpressionException e) {+ throw new NotIndexableException("Can not apply Path", e);+ }+ }++}diff --git a/contrib/gdata-server/src/java/org/apache/lucene/gdata/search/analysis/XHtmlStrategy.java b/contrib/gdata-server/src/java/org/apache/lucene/gdata/search/analysis/XHtmlStrategy.javanew file mode 100755index 00000000000..c4a4b440f19--- /dev/null+++ b/contrib/gdata-server/src/java/org/apache/lucene/gdata/search/analysis/XHtmlStrategy.java@@ -0,0 +1,36 @@+/**+ * Copyright 2004 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.+ */+package org.apache.lucene.gdata.search.analysis;++import org.apache.lucene.gdata.search.config.IndexSchemaField;+++/**+ * @author Simon Willnauer+ * @see org.apache.lucene.gdata.search.analysis.TestHTMLStrategy+ */+public class XHtmlStrategy extends HTMLStrategy {++++ /**+ * @param fieldConfig+ */+ public XHtmlStrategy(IndexSchemaField fieldConfig) {+ super(fieldConfig);+ }++}diff --git a/contrib/gdata-server/src/java/org/apache/lucene/gdata/search/analysis/package.html b/contrib/gdata-server/src/java/org/apache/lucene/gdata/search/analysis/package.htmlnew file mode 100755index 00000000000..8851e7792ac--- /dev/null+++ b/contrib/gdata-server/src/java/org/apache/lucene/gdata/search/analysis/package.html@@ -0,0 +1,10 @@+<!doctype html public "-//w3c//dtd html 4.0 transitional//en">+<html>+<head>+ <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">+ <meta name="Author" content="Simon Willnauer">+</head>+<body>+Classes used for extracting content from entries and building lucene documents.+</body>+</html>\ No newline at end of filediff --git a/contrib/gdata-server/src/java/org/apache/lucene/gdata/search/config/IndexSchema.java b/contrib/gdata-server/src/java/org/apache/lucene/gdata/search/config/IndexSchema.javanew file mode 100755index 00000000000..3dc7c9c7757--- /dev/null+++ b/contrib/gdata-server/src/java/org/apache/lucene/gdata/search/config/IndexSchema.java@@ -0,0 +1,524 @@+/**+ * Copyright 2004 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.+ */+package org.apache.lucene.gdata.search.config;++import java.util.ArrayList;+import java.util.Collection;+import java.util.HashSet;+import java.util.Set;++import org.apache.commons.logging.Log;+import org.apache.commons.logging.LogFactory;+import org.apache.lucene.analysis.Analyzer;+import org.apache.lucene.analysis.PerFieldAnalyzerWrapper;+import org.apache.lucene.analysis.standard.StandardAnalyzer;+import org.apache.lucene.gdata.search.index.IndexDocument;+import org.apache.lucene.gdata.utils.ReflectionUtils;++/**+ * This class is used to configure the indexing and search component. Each+ * service on the GData server will have an own search index. For this purpose+ * one single index schema will be configured in the gdata-config.xml file. This+ * file will be mapped on this class on startup.+ * <p>+ * This class breaks some encapsulation of general java classes to be+ * configurable via the xml configuration file. The will be very less type and+ * value checking of the properties inside this file. Mandatory values must be+ * set in the configuration file. The server won't start up if these values are+ * missing. See definition in the xml schema file. If this class is instantiated+ * manually the value for the name of the schema should be set before this is+ * passed to the IndexController.+ * </p>+ * <p>+ * One IndexSchema consists of multiple instances of+ * {@link org.apache.lucene.gdata.search.config.IndexSchemaField} each of this+ * instances describes a single field in the index and all schema informations+ * about the field.+ * <p>+ *+ *+ * @see org.apache.lucene.gdata.search.config.IndexSchemaField+ *+ *+ * @author Simon Willnauer+ */+public class IndexSchema {+ private final Set<String> searchableFieldNames = new HashSet<String>();++ private static final Log LOG = LogFactory.getLog(IndexSchema.class);++ /**+ * a static final value for properties are not set by the configuration file+ * this value will be set to all long and int properties by default+ */+ public static final int NOT_SET_VALUE = -1;+ private static final int DEFAULT_OPTIMIZE_COUNT = 1;+ private static final int DEFAULT_COMMIT_COUNT = 1;++ private String indexLocation;++ /*+ * this should be final change it if possible --> see commons digester /+ * RegistryBuilder+ */+ private String name;++ private boolean useTimedIndexer;++ private long indexerIdleTime = NOT_SET_VALUE;++ private Analyzer serviceAnalyzer;++ private String defaultSearchField;++ private PerFieldAnalyzerWrapper perFieldAnalyzer;++ private Collection<IndexSchemaField> schemaFields;++ private int maxBufferedDocs = NOT_SET_VALUE;++ private int maxMergeDocs = NOT_SET_VALUE;++ private int mergeFactor = NOT_SET_VALUE;++ private int maxFieldLength = NOT_SET_VALUE;++ private long writeLockTimeout = NOT_SET_VALUE;++ private long commitLockTimeout = NOT_SET_VALUE;++ private int commitAfterDocuments = DEFAULT_COMMIT_COUNT;++ private int optimizeAfterCommit = DEFAULT_OPTIMIZE_COUNT;++ private boolean useCompoundFile = false;++ /**+ * Creates a new IndexSchema and initialize the standard service analyzer to+ * {@link StandardAnalyzer}+ *+ */+ public IndexSchema() {+ this.schemaFields = new ArrayList<IndexSchemaField>();+ /*+ * keep as standard if omitted in the configuration+ */+ this.serviceAnalyzer = new StandardAnalyzer();++ }++ /**+ * Initialize the schema and checks all required values+ */+ public void initialize() {+ for (IndexSchemaField field : this.schemaFields) {+ if (!field.checkRequieredValues())+ throw new RuntimeException("Required Value for field: "+ + field.getName() + " is missing");+ }+ if (this.defaultSearchField == null)+ throw new RuntimeException("DefaulSearchField must not be null");+ if (this.name == null)+ throw new RuntimeException(+ "Schema field is not set -- must not be null");+ if (this.indexLocation == null)+ throw new RuntimeException("IndexLocation must not be null");+ if(!this.searchableFieldNames.contains(this.defaultSearchField)){+ throw new RuntimeException("the default search field: "+this.defaultSearchField+" is registered as a field");+ }++ }++ /**+ * @return Returns the useCompoundFile.+ */+ public boolean isUseCompoundFile() {+ return this.useCompoundFile;+ }++ /**+ * @param useCompoundFile+ * The useCompoundFile to set.+ */+ public void setUseCompoundFile(boolean useCompoundFile) {+ this.useCompoundFile = useCompoundFile;+ }++ /**+ * Adds a new {@link IndexSchemaField} to the schema. if the fields name+ * equals {@link IndexDocument#FIELD_ENTRY_ID} or the field is+ * <code>null</code> it will simply ignored+ *+ * @param field -+ * the index schema field to add as a field of this schema.+ */+ public void addSchemaField(final IndexSchemaField field) {+ if (field == null)+ return;+ /*+ * skip fields configured in the gdata-config.xml file if their names+ * match a primary key field id of the IndexDocument+ */+ if (field.getName().equals(IndexDocument.FIELD_ENTRY_ID)+ || field.getName().equals(IndexDocument.FIELD_FEED_ID))+ return;+ if (field.getAnalyzerClass() != null) {+ /*+ * enable per field analyzer if one is set.+ */+ Analyzer analyzer = getAnalyzerInstance(field.getAnalyzerClass());+ /*+ * null values will be omitted here+ */+ buildPerFieldAnalyzerWrapper(analyzer, field.getName());+ }+ this.schemaFields.add(field);+ this.searchableFieldNames.add(field.getName());+ }+++ /**+ * @return Returns the fieldConfiguration.+ */+ public Collection<IndexSchemaField> getFields() {+ return this.schemaFields;+ }++ /**+ * @return - the analyzer instance to be used for this schema+ */+ public Analyzer getSchemaAnalyzer() {+ if (this.perFieldAnalyzer == null)+ return this.serviceAnalyzer;+ return this.perFieldAnalyzer;+ }++ /**+ * @return Returns the serviceAnalyzer.+ */+ public Analyzer getServiceAnalyzer() {+ return this.serviceAnalyzer;+ }++ /**+ * @param serviceAnalyzer+ * The serviceAnalyzer to set.+ */+ public void setServiceAnalyzer(Analyzer serviceAnalyzer) {+ if (serviceAnalyzer == null)+ return;+ this.serviceAnalyzer = serviceAnalyzer;++ }++ /**+ * @return Returns the commitLockTimout.+ */+ public long getCommitLockTimeout() {+ return this.commitLockTimeout;+ }++ /**+ *+ * @param commitLockTimeout+ * The commitLockTimeout to set.+ */+ public void setCommitLockTimeout(long commitLockTimeout) {+ // TODO enable this in config+ this.commitLockTimeout = commitLockTimeout;+ }++ /**+ * @return Returns the maxBufferedDocs.+ */+ public int getMaxBufferedDocs() {++ return this.maxBufferedDocs;+ }++ /**+ * @param maxBufferedDocs+ * The maxBufferedDocs to set.+ */+ public void setMaxBufferedDocs(int maxBufferedDocs) {+ this.maxBufferedDocs = maxBufferedDocs;+ }++ /**+ * @return Returns the maxFieldLength.+ */+ public int getMaxFieldLength() {+ return this.maxFieldLength;+ }++ /**+ * @param maxFieldLength+ * The maxFieldLength to set.+ */+ public void setMaxFieldLength(int maxFieldLength) {+ this.maxFieldLength = maxFieldLength;+ }++ /**+ * @return Returns the maxMergeDocs.+ */+ public int getMaxMergeDocs() {+ return this.maxMergeDocs;+ }++ /**+ * @param maxMergeDocs+ * The maxMergeDocs to set.+ */+ public void setMaxMergeDocs(int maxMergeDocs) {+ this.maxMergeDocs = maxMergeDocs;+ }++ /**+ * @return Returns the mergeFactor.+ */+ public int getMergeFactor() {+ return this.mergeFactor;+ }++ /**+ * @param mergeFactor+ * The mergeFactor to set.+ */+ public void setMergeFactor(int mergeFactor) {+ this.mergeFactor = mergeFactor;+ }++ /**+ * @return Returns the writeLockTimeout.+ */+ public long getWriteLockTimeout() {+ return this.writeLockTimeout;+ }++ /**+ * @param writeLockTimeout+ * The writeLockTimeout to set.+ */+ public void setWriteLockTimeout(long writeLockTimeout) {+ this.writeLockTimeout = writeLockTimeout;+ }++ /**+ * @param fields+ * The fieldConfiguration to set.+ */+ public void setSchemaFields(Collection<IndexSchemaField> fields) {+ this.schemaFields = fields;+ }++ /**+ * @return Returns the name.+ */+ public String getName() {+ return this.name;+ }++ /**+ * @see java.lang.Object#equals(java.lang.Object)+ */+ @Override+ public boolean equals(Object object) {+ if (this == object)+ return true;+ if (object == null)+ return false;+ if (object instanceof IndexSchema) {+ if(this.name ==null)+ return super.equals(object);+ return this.name.equals(((IndexSchema) object).getName());+ }+ return false;+ }++ /**+ * @see java.lang.Object#hashCode()+ */+ @Override+ public int hashCode() {+ if (this.name == null)+ return super.hashCode();+ return this.name.hashCode();+ }++ private void buildPerFieldAnalyzerWrapper(Analyzer anazlyer, String field) {+ if (anazlyer == null || field == null || field.length() == 0)+ return;+ if (this.perFieldAnalyzer == null)+ this.perFieldAnalyzer = new PerFieldAnalyzerWrapper(+ this.serviceAnalyzer);+ this.perFieldAnalyzer.addAnalyzer(field, anazlyer);+ }++ private static Analyzer getAnalyzerInstance(Class<? extends Analyzer> clazz) {+ if (!ReflectionUtils.extendsType(clazz, Analyzer.class)) {+ LOG.warn("Can not create analyzer for class " + clazz.getName());+ return null;+ }+ try {+ return clazz.newInstance();+ } catch (Exception e) {+ LOG.warn("Can not create analyzer for class " + clazz.getName());+ }+ return null;+ }++ /**+ * @param name+ * The name to set.+ */+ public void setName(String name) {+ this.name = name;+ }++ /**+ * @return Returns the indexLocation.+ */+ public String getIndexLocation() {+ return this.indexLocation;+ }++ /**+ * @param indexLocation+ * The indexLocation to set.+ */+ public void setIndexLocation(String indexLocation) {+ this.indexLocation = indexLocation;+ }++ /**+ * @return Returns the defaultField.+ */+ public String getDefaultSearchField() {+ return this.defaultSearchField;+ }++ /**+ * @param defaultField+ * The defaultField to set.+ */+ public void setDefaultSearchField(String defaultField) {+ this.defaultSearchField = defaultField;+ }++ /**+ * @return Returns the indexerIdleTime.+ */+ public long getIndexerIdleTime() {+ return this.indexerIdleTime;+ }++ /**+ * @param indexerIdleTime+ * The indexerIdleTime to set.+ */+ public void setIndexerIdleTime(long indexerIdleTime) {+ this.indexerIdleTime = indexerIdleTime;+ }++ /**+ * @return Returns the useTimedIndexer.+ */+ public boolean isUseTimedIndexer() {+ return this.useTimedIndexer;+ }++ /**+ * @param useTimedIndexer+ * The useTimedIndexer to set.+ */+ public void setUseTimedIndexer(boolean useTimedIndexer) {+ this.useTimedIndexer = useTimedIndexer;+ }++ /**+ * @see java.lang.Object#toString()+ */+ @Override+ public String toString() {+ StringBuilder builder = new StringBuilder(this.getClass().getName())+ .append(" ");+ builder.append("Name: ").append(this.name).append(" ");+ builder.append("MaxBufferedDocs: ").append(this.maxBufferedDocs)+ .append(" ");+ builder.append("MaxFieldLength: ").append(this.maxFieldLength).append(+ " ");+ builder.append("MaxMergeDocs: ").append(this.maxMergeDocs).append(" ");+ builder.append("MergeFactor: ").append(this.mergeFactor).append(" ");+ builder.append("CommitLockTimeout: ").append(this.commitLockTimeout)+ .append(" ");+ builder.append("WriteLockTimeout: ").append(this.writeLockTimeout)+ .append(" ");+ builder.append("indexerIdleTime: ").append(this.indexerIdleTime)+ .append(" ");+ builder.append("useCompoundFile: ").append(this.useCompoundFile)+ .append(" ");+ builder.append("Added SchemaField instances: ").append(+ this.schemaFields.size()).append(" ");++ builder.append("IndexLocation: ").append(this.indexLocation)+ .append(" ");+ return builder.toString();++ }++ /**+ * @return Returns the searchableFieldNames.+ */+ public Set<String> getSearchableFieldNames() {+ return this.searchableFieldNames;+ }++ /**+ * Defines after how many added,removed or updated document the indexer should commit.+ * @return Returns the commitAfterDocuments.+ */+ public int getCommitAfterDocuments() {+ return this.commitAfterDocuments;+ }++ /**+ * @param commitAfterDocuments The commitAfterDocuments to set.+ */+ public void setCommitAfterDocuments(int commitAfterDocuments) {+ if(commitAfterDocuments < DEFAULT_COMMIT_COUNT)+ return;+ this.commitAfterDocuments = commitAfterDocuments;+ }++ /**+ * Defines after how many commits the indexer should optimize the index+ * @return Returns the optimizeAfterCommit.+ */+ public int getOptimizeAfterCommit() {++ return this.optimizeAfterCommit;+ }++ /**+ * @param optimizeAfterCommit The optimizeAfterCommit to set.+ */+ public void setOptimizeAfterCommit(int optimizeAfterCommit) {+ if(optimizeAfterCommit < DEFAULT_OPTIMIZE_COUNT )+ return;+ this.optimizeAfterCommit = optimizeAfterCommit;+ }+}diff --git a/contrib/gdata-server/src/java/org/apache/lucene/gdata/search/config/IndexSchemaField.java b/contrib/gdata-server/src/java/org/apache/lucene/gdata/search/config/IndexSchemaField.javanew file mode 100755index 00000000000..d292b9c7e3e--- /dev/null+++ b/contrib/gdata-server/src/java/org/apache/lucene/gdata/search/config/IndexSchemaField.java@@ -0,0 +1,379 @@+/**+ * Copyright 2004 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.+ */++package org.apache.lucene.gdata.search.config;++import org.apache.lucene.analysis.Analyzer;+import org.apache.lucene.document.Field;+import org.apache.lucene.document.Field.Index;+import org.apache.lucene.document.Field.Store;+import org.apache.lucene.gdata.search.analysis.ContentStrategy;+import org.apache.lucene.gdata.search.analysis.GdataCategoryStrategy;+import org.apache.lucene.gdata.search.analysis.GdataDateStrategy;+import org.apache.lucene.gdata.search.analysis.HTMLStrategy;+import org.apache.lucene.gdata.search.analysis.KeywordStrategy;+import org.apache.lucene.gdata.search.analysis.MixedContentStrategy;+import org.apache.lucene.gdata.search.analysis.PlainTextStrategy;+import org.apache.lucene.gdata.search.analysis.XHtmlStrategy;+import org.apache.lucene.gdata.utils.ReflectionUtils;++/**+ * Each field in the search index is defined by a instance of+ * {@link IndexSchemaField}. The schema definition will be loaded at startup+ * and the defined values will be set to instances of this class. Each+ * constructed field will be passed to an instance of+ * {@link org.apache.lucene.gdata.search.config.IndexSchema}.+ * <p>+ * IndexSchemaField contains all informations about how the content from+ * incoming entries has to be extracted and how the actual content has to be+ * index into the lucene index.+ * </p>+ * <p>+ * Each field will have a defined+ * {@link org.apache.lucene.gdata.search.analysis.ContentStrategy} which does+ * process the extraction of the field content from an incoming entry.+ * </p>+ * @see org.apache.lucene.gdata.search.analysis.ContentStrategy+ * @see org.apache.lucene.gdata.search.config.IndexSchema+ *+ * @author Simon Willnauer+ *+ */+public class IndexSchemaField {+ /**+ * Default value for Field.Store+ * @see org.apache.lucene.document.Field+ */+ public static final Store DEFAULT_STORE_STRATEGY = Field.Store.NO;+ /**+ * Default value for Field.Index+ * @see org.apache.lucene.document.Field+ */+ public static final Index DEFAULT_INDEX_STRATEGY = Field.Index.TOKENIZED;+ private static final float DEFAULT_BOOST = 1.0f;+ private static final float MINIMAL_BOOST = 0.1f;+ private float boost = DEFAULT_BOOST;++ private String name;++ private ContentType contentType;++ private Index index = DEFAULT_INDEX_STRATEGY;++ private Store store = DEFAULT_STORE_STRATEGY;++ private String path;++ private String typePath;++ private Class<? extends Analyzer> analyzerClass;++ private Class<? extends ContentStrategy> fieldClass;++ /**+ * Constructs a new SchemaField <br>+ * Default values:+ * <ol>+ * <li>boost: <i>1.0</i></li>+ * <li>index: <i>TOKENIZED</i></li>+ * <li>store: <i>NO</i></li>+ * </ol>+ */+ public IndexSchemaField() {+ super();+ }+ boolean checkRequieredValues(){+ /*+ * This class will be inst. by the reg builder.+ * Check all values to be set. otherwise return false.+ * false will cause a runtime exception in IndexSchema+ */+ boolean returnValue = (this.name != null&&this.path!=null&&this.contentType!=null&&this.index!=null&&this.store!=null&&this.boost>=MINIMAL_BOOST);+ if(this.contentType == ContentType.CUSTOM)+ returnValue &=this.fieldClass!=null;+ else if(this.contentType == ContentType.MIXED)+ returnValue &=this.typePath!=null;++ return returnValue;+ }+ /**+ * @return Returns the alanyzerClass.+ */+ public Class<? extends Analyzer> getAnalyzerClass() {+ return this.analyzerClass;+ }++ /**+ * @param alanyzerClass+ * The alanyzerClass to set.+ */+ public void setAnalyzerClass(Class<? extends Analyzer> alanyzerClass) {+ this.analyzerClass = alanyzerClass;+ }++ /**+ * @return Returns the fieldClass.+ */+ public Class<? extends ContentStrategy> getFieldClass() {+ return this.fieldClass;+ }++ /**+ * Sets the class or strategy is used to extract this field Attention: this+ * method set the contentTyp to {@link ContentType#CUSTOM}+ *+ * @param fieldClass+ * The fieldClass to set.+ */+ public void setFieldClass(Class<? extends ContentStrategy> fieldClass) {+ if(fieldClass == null)+ throw new IllegalArgumentException("ContentStrategy must not be null");+ if(!ReflectionUtils.extendsType(fieldClass,ContentStrategy.class))+ throw new RuntimeException("The configured ContentStrategy does not extend ContentStrategy, can not use as a custom strategy -- "+fieldClass.getName());+ if(!ReflectionUtils.hasDesiredConstructor(fieldClass,new Class[]{IndexSchemaField.class}))+ throw new RuntimeException("Can not create instance of "+fieldClass.getName());+ this.fieldClass = fieldClass;+ /*+ * set custom - field class is only needed by custom+ */+ this.contentType = ContentType.CUSTOM;+ }++ /**+ * @return Returns the index.+ */+ public Index getIndex() {+ return this.index;+ }++ /**+ * @param index+ * The index to set.+ */+ public void setIndex(Index index) {+ this.index = index;+ }++ /**+ * @return Returns the name.+ */+ public String getName() {+ return this.name;+ }++ /**+ * @param name+ * The name to set.+ */+ public void setName(String name) {+ this.name = name;+ }++ /**+ * @return Returns the path.+ */+ public String getPath() {+ return this.path;+ }++ /**+ * @param path+ * The path to set.+ */+ public void setPath(String path) {+ this.path = path;+ }++ /**+ * @return Returns the store.+ */+ public Store getStore() {+ return this.store;+ }++ /**+ * @param store+ * The store to set.+ */+ public void setStore(Store store) {+ this.store = store;+ }++ /**+ * @return Returns the type.+ */+ public ContentType getContentType() {+ return this.contentType;+ }++ /**+ * @param type+ * The type to set.+ */+ public void setContentType(ContentType type) {+ this.contentType = type;++ }++ /**+ * Sets the content type of this field by the name of the enum type. This+ * method is not case sensitive.+ *+ * @param type -+ * type name as string+ */+ public void setType(String type) {+ ContentType[] types = ContentType.class.getEnumConstants();+ for (int i = 0; i < types.length; i++) {+ if (types[i].name().toLowerCase().equals(type)) {+ this.contentType = types[i];+ break;+ }++ }+ }++ /**+ * Defines the {@link ContentStrategy} to use for a+ * <tt>IndexSchemaField</tt> to extract the content from the entry+ *+ * @author Simon Willnauer+ *+ */+ public enum ContentType {++ /**+ * HTML content strategy {@link HTMLStrategy }+ */+ HTML,+ /**+ * XHTML content strategy {@link XHtmlStrategy }+ */+ XHTML,+ /**+ * Text content strategy {@link PlainTextStrategy }+ */+ TEXT,+ /**+ * GDataDate content strategy {@link GdataDateStrategy }+ */+ GDATADATE,+ /**+ * KEYWORD content strategy {@link KeywordStrategy }+ */+ KEYWORD,+ /**+ * Category content strategy {@link GdataCategoryStrategy }+ */+ CATEGORY,+ /**+ * Custom content strategy (user defined)+ */+ CUSTOM,+ /**+ * Mixed content strategy {@link MixedContentStrategy }+ */+ MIXED++ }++ /**+ * @return Returns the boost.+ */+ public float getBoost() {+ return this.boost;+ }++ /**+ * @param boost+ * The boost to set.+ */+ public void setBoost(float boost) {+ if (boost <= 0)+ return;+ this.boost = boost;+ }++ /**+ * @see java.lang.Object#toString()+ */+ @Override+ public String toString() {+ StringBuilder builder = new StringBuilder(this.getClass()+ .getSimpleName()).append(" ");+ builder.append("field name: ").append(this.name).append(" ");+ builder.append("path: ").append(this.path).append(" ");+ builder.append("content type ").append(this.contentType).append(" ");+ builder.append("field class: ").append(this.fieldClass).append(" ");+ builder.append("analyzer: ").append(this.analyzerClass).append(" ");+ builder.append("boost: ").append(this.boost).append(" ");+ builder.append("INDEX: ").append(this.index).append(" ");+ builder.append("STORE: ").append(this.store);+ return builder.toString();+ }++ /**+ * Sets the Store class by simple name+ *+ * @param name -+ * one of yes, no, compress+ */+ public void setStoreByName(String name) {+ if (name.toLowerCase().equals("yes"))+ this.store = Field.Store.YES;+ else if (name.toLowerCase().equals("no"))+ this.store = Field.Store.NO;+ else if (name.toLowerCase().equals("compress"))+ this.store = Field.Store.COMPRESS;+ }++ /**+ * Sets the Index class by simple name+ *+ * @param name -+ * un_tokenized, tokenized, no, no_norms+ */+ public void setIndexByName(String name) {+ if (name.toLowerCase().equals("un_tokenized"))+ this.index = Field.Index.UN_TOKENIZED;+ else if (name.toLowerCase().equals("tokenized"))+ this.index = Field.Index.TOKENIZED;+ else if (name.toLowerCase().equals("no_norms"))+ this.index = Field.Index.NO_NORMS;+ else if (name.toLowerCase().equals("no"))+ this.index = Field.Index.NO;+ }++ /**+ * @return Returns the typePath.+ */+ public String getTypePath() {+ return this.typePath;+ }++ /**+ * @param typePath+ * The typePath to set.+ */+ public void setTypePath(String typePath) {+ this.typePath = typePath;+ /*+ * set Mixed - this property is only needed by mixed type+ */+ setContentType(ContentType.MIXED);+ }++}diff --git a/contrib/gdata-server/src/java/org/apache/lucene/gdata/search/config/package.html b/contrib/gdata-server/src/java/org/apache/lucene/gdata/search/config/package.htmlnew file mode 100755index 00000000000..2bb6076dd85--- /dev/null+++ b/contrib/gdata-server/src/java/org/apache/lucene/gdata/search/config/package.html@@ -0,0 +1,10 @@+<!doctype html public "-//w3c//dtd html 4.0 transitional//en">+<html>+<head>+ <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">+ <meta name="Author" content="Simon Willnauer">+</head>+<body>+All classes used for index and search configuration+</body>+</html>\ No newline at end of filediff --git a/contrib/gdata-server/src/java/org/apache/lucene/gdata/search/index/GDataIndexDocument.java b/contrib/gdata-server/src/java/org/apache/lucene/gdata/search/index/GDataIndexDocument.javanew file mode 100755index 00000000000..48cec995dc6--- /dev/null+++ b/contrib/gdata-server/src/java/org/apache/lucene/gdata/search/index/GDataIndexDocument.java@@ -0,0 +1,136 @@+/**+ * Copyright 2004 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.+ */+package org.apache.lucene.gdata.search.index;++import java.util.ArrayList;+import java.util.Collection;+import org.apache.lucene.document.Document;+import org.apache.lucene.document.Field;+import org.apache.lucene.gdata.search.analysis.ContentStrategy;+import org.apache.lucene.index.Term;++/**+ * Simple implementation+ *+ * @author Simon Willnauer+ * @see org.apache.lucene.gdata.search.index.IndexDocument+ */+class GDataIndexDocument implements IndexDocument {+ private final IndexAction action;++ private final boolean commitAfter;++ private final boolean optimizeAfter;++ private String id;++ protected Collection<ContentStrategy> fields;++ private final String feedId;++ GDataIndexDocument(final IndexAction action, final String entryId,final String feedId,final boolean commitAfter,final boolean optimizeAfter) {+ this.action = action;+ this.id = entryId;+ this.feedId = feedId;+ this.fields = new ArrayList<ContentStrategy>(10);+ this.commitAfter = commitAfter;+ this.optimizeAfter = optimizeAfter;+ }++ /**+ * Adds a new field e.g. <tt>ContentStrategy</tt> to the IndexDocument+ *+ * @param field -+ * the strategy to add+ */+ public void addField(ContentStrategy field) {+ if (field == null)+ return;+ this.fields.add(field);+ }++ /**+ * @see org.apache.lucene.gdata.search.index.IndexDocument#getWriteable()+ */+ public Document getWriteable() {+ Document retVal = new Document();+ retVal.add(new Field(FIELD_ENTRY_ID, this.id, Field.Store.YES,+ Field.Index.UN_TOKENIZED));+ retVal.add(new Field(FIELD_FEED_ID, this.feedId, Field.Store.YES,+ Field.Index.UN_TOKENIZED));+ for (ContentStrategy strategy : this.fields) {+ Field[] fieldArray = strategy.createLuceneField();+ for (int i = 0; i < fieldArray.length; i++) {+ retVal.add(fieldArray[i]);+ }++ }+ return retVal;+ }++ /**+ * @see org.apache.lucene.gdata.search.index.IndexDocument#getDeletealbe()+ */+ public Term getDeletealbe() {++ return new Term(IndexDocument.FIELD_ENTRY_ID, this.id);+ }++ /**+ * @see org.apache.lucene.gdata.search.index.IndexDocument#isUpdate()+ */+ public boolean isUpdate() {++ return isAction(IndexAction.UPDATE);+ }++ /**+ * @see org.apache.lucene.gdata.search.index.IndexDocument#isDelete()+ */+ public boolean isDelete() {++ return isAction(IndexAction.DELETE);+ }++ /**+ * @see org.apache.lucene.gdata.search.index.IndexDocument#isInsert()+ */+ public boolean isInsert() {++ return isAction(IndexAction.INSERT);+ }++ private boolean isAction(IndexAction indexAction) {+ return this.action == indexAction;+ }++ /**+ * @see org.apache.lucene.gdata.search.index.IndexDocument#commitAfter()+ */+ public boolean commitAfter() {++ return this.commitAfter;+ }++ /**+ * @see org.apache.lucene.gdata.search.index.IndexDocument#optimizeAfter()+ */+ public boolean optimizeAfter() {++ return this.optimizeAfter;+ }++}diff --git a/contrib/gdata-server/src/java/org/apache/lucene/gdata/search/index/GDataIndexWriter.java b/contrib/gdata-server/src/java/org/apache/lucene/gdata/search/index/GDataIndexWriter.javanew file mode 100755index 00000000000..038daf965e4--- /dev/null+++ b/contrib/gdata-server/src/java/org/apache/lucene/gdata/search/index/GDataIndexWriter.java@@ -0,0 +1,101 @@+/**+ * Copyright 2004 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.+ */++package org.apache.lucene.gdata.search.index;++import java.io.IOException;++import org.apache.commons.logging.Log;+import org.apache.commons.logging.LogFactory;+import org.apache.lucene.analysis.standard.StandardAnalyzer;+import org.apache.lucene.gdata.search.config.IndexSchema;+import org.apache.lucene.index.IndexWriter;+import org.apache.lucene.store.Directory;++/**+ * Configurable decorator for a lucene {@link IndexWriter}+ *+ * @author Simon Willnauer+ *+ */+public class GDataIndexWriter extends IndexWriter {+ private static final Log LOG = LogFactory.getLog(GDataIndexWriter.class);++ private String serviceName;++ private void initialize(IndexSchema config) {+ this.serviceName = config.getName();+ setUseCompoundFile(config.isUseCompoundFile());+ if (config.getMaxBufferedDocs() != IndexSchema.NOT_SET_VALUE)+ setMaxBufferedDocs(config.getMaxBufferedDocs());+ if (config.getMaxMergeDocs() != IndexSchema.NOT_SET_VALUE)+ setMaxMergeDocs(config.getMaxMergeDocs());+ if (config.getMergeFactor() != IndexSchema.NOT_SET_VALUE)+ setMergeFactor(config.getMergeFactor());+ if (config.getMaxFieldLength() != IndexSchema.NOT_SET_VALUE)+ setMaxFieldLength(config.getMaxFieldLength());+ if (config.getWriteLockTimeout() != IndexSchema.NOT_SET_VALUE)+ setWriteLockTimeout(config.getWriteLockTimeout());+ if (config.getCommitLockTimeout() != IndexSchema.NOT_SET_VALUE)+ setCommitLockTimeout(config.getCommitLockTimeout());+ }++ /**+ * Creates and configures a new GdataIndexWriter+ *+ * @param arg0 -+ * the index directory+ * @param arg1 -+ * create index+ * @param arg2 -+ * the index schema configuration including all parameter to set+ * up the index writer+ * @throws IOException+ * -if the directory cannot be read/written to, or if it does+ * not exist, and <code>create</code> is <code>false</code>+ */+ protected GDataIndexWriter(Directory arg0, boolean arg1, IndexSchema arg2)+ throws IOException {+ /*+ * Use Schema Analyzer rather than service analyzer.+ * Schema analyzer returns either the service analyzer or a per field analyzer if configured.+ */+ super(arg0, (arg2 == null ? new StandardAnalyzer() : arg2.getSchemaAnalyzer()), arg1);+ if (arg2 == null) {+ /*+ * if no schema throw exception - schema is mandatory for the index writer.+ */+ try {+ this.close();+ } catch (IOException e) {+ //+ }+ throw new IllegalArgumentException("configuration must not be null");++ }+ this.initialize(arg2);+ }++ /**+ * @see org.apache.lucene.index.IndexWriter#close()+ */+ @Override+ public void close() throws IOException {+ super.close();+ LOG.info("Closing GdataIndexWriter for service " + this.serviceName);+ }++}diff --git a/contrib/gdata-server/src/java/org/apache/lucene/gdata/search/index/GDataIndexer.java b/contrib/gdata-server/src/java/org/apache/lucene/gdata/search/index/GDataIndexer.javanew file mode 100755index 00000000000..299cd145e7e--- /dev/null+++ b/contrib/gdata-server/src/java/org/apache/lucene/gdata/search/index/GDataIndexer.java@@ -0,0 +1,509 @@+/**+ * Copyright 2004 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.+ */+package org.apache.lucene.gdata.search.index;++import java.io.IOException;+import java.util.ArrayList;+import java.util.HashMap;+import java.util.List;+import java.util.Map;+import java.util.concurrent.BlockingQueue;+import java.util.concurrent.ExecutionException;+import java.util.concurrent.ExecutorService;+import java.util.concurrent.Executors;+import java.util.concurrent.Future;+import java.util.concurrent.LinkedBlockingQueue;+import java.util.concurrent.TimeUnit;+import java.util.concurrent.TimeoutException;+import java.util.concurrent.atomic.AtomicBoolean;+import java.util.concurrent.atomic.AtomicInteger;++import org.apache.commons.logging.Log;+import org.apache.commons.logging.LogFactory;+import org.apache.lucene.gdata.search.config.IndexSchema;+import org.apache.lucene.index.IndexReader;+import org.apache.lucene.index.IndexWriter;+import org.apache.lucene.index.TermDocs;+import org.apache.lucene.search.IndexSearcher;+import org.apache.lucene.store.Directory;++/**+ * A GDataIndexer encapsulates every writing access to the search index.+ * <p>+ * Insert, updates and deletes to the index happens inside this class. All+ * modification will be base on an instance of+ * {@link org.apache.lucene.gdata.search.index.IndexDocument} which contains all+ * informations and command for the indexer.<br>+ * Although this class provides methods to add, remove and update document in+ * the index all <tt>IndexDocument</tt> instances should be added to the task+ * queue via the {@link GDataIndexer#addIndexableDocumentTask(Future)} method.+ * Inside this class runs an instance of+ * {@link org.apache.lucene.gdata.search.index.IndexTask} listening on this+ * queue. The analysis of the actual documents happens inside the+ * {@link com.sun.corba.se.impl.orbutil.closure.Future} object added to the+ * queue. This enables the indexer to do his actual work. Documents will be+ * build / analyzed concurrently while already finished tasks can be added to+ * the index.+ * </p>+ *+ *+ *+ * @author Simon Willnauer+ */+public class GDataIndexer {+ private static final Log LOG = LogFactory.getLog(GDataIndexer.class);++ protected IndexWriter writer;++ protected IndexSearcher searcher;++ protected AtomicInteger committed = new AtomicInteger(0);++ protected AtomicInteger optimized = new AtomicInteger(0);++ private AtomicBoolean isDestroyed = new AtomicBoolean(false);++ protected AtomicInteger docsAdded = new AtomicInteger();++ protected AtomicInteger docsUpdated = new AtomicInteger();++ protected AtomicInteger docsDeleted = new AtomicInteger();++ private final Directory dir;++ private final List<IndexEventListener> listeners = new ArrayList<IndexEventListener>();++ protected final BlockingQueue<Future<IndexDocument>> futurQueue = new LinkedBlockingQueue<Future<IndexDocument>>(+ 100);++ private final IndexSchema serviceConfiguration;++ private final ExecutorService indexTaskExecutor;++ protected IndexTask indexTask;++ private static final Integer ZERO = new Integer(0);++ private static final Integer ONE = new Integer(1);++ private final Map<IndexDocument, Integer> action;++ protected GDataIndexer(final IndexSchema schema, Directory dir,+ boolean create) throws IOException {+ if (schema == null)+ throw new IllegalArgumentException(+ "IndexServiceConfiguration must not be null");+ if (dir == null)+ throw new IllegalArgumentException(+ "IndexDirectory must not be null");++ this.serviceConfiguration = schema;+ this.dir = dir;+ openWriter(create);+ this.indexTaskExecutor = Executors.newSingleThreadExecutor();+ this.action = new HashMap<IndexDocument, Integer>(128);++ }++ protected void setIndexTask(final IndexTask task) {+ if (task != null && this.indexTask == null)+ this.indexTask = task;+ }++ protected void init() {+ if (this.indexTask == null)+ this.indexTask = new IndexTask(this, this.futurQueue);+ this.indexTaskExecutor.execute(this.indexTask);++ }++ /**+ * Adds the given future task to the queue, and waits if the queue is full.+ * The queue size is set to 100 by default.+ *+ * @param task -+ * the task to be scheduled+ * @throws InterruptedException -+ * if the queue is interrupted+ */+ public void addIndexableDocumentTask(final Future<IndexDocument> task)+ throws InterruptedException {+ if (this.isDestroyed.get())+ throw new IllegalStateException(+ "Indexer has already been destroyed");+ this.futurQueue.put(task);+ }++ /*+ * a added doc should not be in the index, be sure and delete possible+ * duplicates+ */+ protected synchronized void addDocument(IndexDocument indexable)+ throws IOException {+ if (!indexable.isInsert())+ throw new GdataIndexerException(+ "Index action must be set to insert");+ setAction(indexable);+ doWrite(indexable);+ this.docsAdded.incrementAndGet();++ }++ private void setAction(IndexDocument doc) {+ Integer docCountToKeep = this.action.get(doc);+ if (!doc.isDelete() && (docCountToKeep == null || docCountToKeep == 0)) {+ /*+ * add a ONE for ONE documents to keep for this IndexDocument when+ * doDelete. doDelete will keep the latest added document and+ * deletes all other documents for this IndexDocument e.g. all+ * duplicates+ */+ this.action.put(doc, ONE);+ } else if (doc.isDelete()+ && (docCountToKeep == null || docCountToKeep > 0)) {+ /*+ * add a zero for zero documents to keep for this IndexDocument when+ * doDelete+ */+ this.action.put(doc, ZERO);+ }+ }++ protected synchronized void updateDocument(IndexDocument indexable)+ throws IOException {+ if (!indexable.isUpdate())+ throw new GdataIndexerException(+ "Index action must be set to update");+ setAction(indexable);+ doWrite(indexable);+ this.docsUpdated.incrementAndGet();+ }++ protected synchronized void deleteDocument(IndexDocument indexable) {+ if (!indexable.isDelete())+ throw new GdataIndexerException(+ "Index action must be set to delete");++ setAction(indexable);+ this.docsDeleted.incrementAndGet();+ }++ /**+ * This method commits all changes to the index and closes all open+ * resources (e.g. IndexWriter and IndexReader). This method notifies all+ * registered Commit listeners if invoked.+ *+ * @param optimize -+ * <code>true</code> if the index should be optimized on this+ * commit+ * @throws IOException -+ * if an IOException occurs+ */+ protected synchronized void commit(boolean optimize) throws IOException {+ if (LOG.isInfoEnabled())+ LOG.info("Commit called with optimize = " + optimize);++ int changes = this.docsAdded.intValue() + this.docsDeleted.intValue()+ + this.docsUpdated.intValue();+ /*+ * don't call listeners to prevent unnecessary close / open of searchers+ */+ if (changes == 0)+ return;+ this.committed.incrementAndGet();+ if(optimize)+ this.optimized.incrementAndGet();+ doDeltete();+ if (optimize) {+ closeSearcher();+ openWriter();+ this.writer.optimize();+ }+ closeSearcher();+ closeWriter();+ this.docsAdded.set(0);+ this.docsDeleted.set(0);+ this.docsUpdated.set(0);+ notifyCommitListeners(this.serviceConfiguration.getName());++ }++ /**+ * Registers a new IndexEventListener. All registered listeners will be+ * notified if the index has been committed.+ *+ * @param listener -+ * the listener to register+ *+ */+ public void registerIndexEventListener(IndexEventListener listener) {+ if (listener == null || this.listeners.contains(listener))+ return;+ this.listeners.add(listener);+ }++ /**+ * Removes a registered IndexEventListener+ *+ * @param listener -+ * the listener to remove+ */+ public void removeIndexEventListener(IndexEventListener listener) {++ if (listener == null || !this.listeners.contains(listener))+ return;+ this.listeners.remove(listener);+ }++ protected void notifyCommitListeners(String serviceId) {+ if (LOG.isInfoEnabled())+ LOG.info("notify commit event listeners for service id: "+ + serviceId + " -- current size of registered listeners: "+ + this.listeners.size());+ for (IndexEventListener listener : this.listeners) {+ listener.commitCallBack(serviceId);+ }+ }++ protected void closeWriter() throws IOException {+ try {+ if (this.writer != null)+ this.writer.close();+ } finally {+ this.writer = null;+ }+ }++ protected void closeSearcher() throws IOException {+ try {+ if (this.searcher != null)+ this.searcher.close();+ } finally {+ this.searcher = null;+ }+ }++ protected void openSearcher() throws IOException {+ if (this.searcher == null)+ this.searcher = new IndexSearcher(this.dir);+ }++ protected void openWriter() throws IOException {+ openWriter(false);+ }++ private void openWriter(boolean create) throws IOException {+ if (this.writer == null)+ this.writer = new GDataIndexWriter(this.dir, create,+ this.serviceConfiguration);+ }++ /*+ * This should only be called in a synchronized block+ */+ protected void doWrite(IndexDocument document) throws IOException {+ closeSearcher();+ openWriter();+ this.writer.addDocument(document.getWriteable());++ }++ // only access synchronized+ int[] documentNumber;++ /*+ * This should only be called in a synchronized block+ */+ protected void doDeltete() throws IOException {+ if (this.action.size() == 0)+ return;+ if (LOG.isInfoEnabled())+ LOG+ .info("Deleting documents and duplicates from index, size of IndexDocuments "+ + this.action.size());+ closeWriter();+ openSearcher();++ IndexReader reader = this.searcher.getIndexReader();+ TermDocs termDocs = reader.termDocs();+ for (Map.Entry<IndexDocument, Integer> entry : this.action.entrySet()) {+ IndexDocument indexDocument = entry.getKey();+ Integer docToKeep = entry.getValue();+ // extend the array if needed+ if (this.documentNumber == null+ || docToKeep > this.documentNumber.length)+ this.documentNumber = new int[docToKeep];++ for (int i = 0; i < this.documentNumber.length; i++) {++ this.documentNumber[i] = -1;+ }+ /*+ * get the term to find the document from the document itself+ */+ termDocs.seek(indexDocument.getDeletealbe());++ int pos = 0;++ while (termDocs.next()) {+ /*+ * if this is a pure delete just delete it an continue+ */+ if (docToKeep == 0) {+ reader.deleteDocument(termDocs.doc());+ continue;+ }++ int prev = this.documentNumber[pos];+ this.documentNumber[pos] = termDocs.doc();+ if (prev != -1) {+ reader.deleteDocument(prev);+ }++ if (++pos >= docToKeep)+ pos = 0;++ }+ }+ /*+ * clear the map after all documents are processed+ */+ this.action.clear();+ closeSearcher();+ }++ protected synchronized void destroy() throws IOException {+ this.isDestroyed.set(true);+ if (!this.indexTask.isStopped())+ this.indexTask.stop();+ this.futurQueue.add(new FinishingFuture());+ this.indexTaskExecutor.shutdown();+ closeWriter();+ closeSearcher();+ if (LOG.isInfoEnabled())+ LOG.info("Destroying GdataIndexer for service -- "+ + this.serviceConfiguration.getName());++ }++ /**+ * This factory method creates a new GDataIndexer using a instance of+ * {@link IndexTask}+ *+ * @param config -+ * the config to be used to configure the indexer+ * @param dir -+ * the directory to index to+ * @param create -+ * <code>true</code> to create a new index, <code>false</code>+ * to use the existing one.+ * @return - a new GDataIndexer instance+ * @throws IOException -+ * if an IOException occurs while initializing the indexer+ */+ public static synchronized GDataIndexer createGdataIndexer(+ final IndexSchema config, Directory dir, boolean create)+ throws IOException {+ GDataIndexer retVal = new GDataIndexer(config, dir, create);+ retVal.setIndexTask(new IndexTask(retVal, retVal.futurQueue));+ retVal.init();+ return retVal;+ }++ /**+ * This factory method creates a new GDataIndexer using a instance of+ * {@link TimedIndexTask}. This indexer will automatically commit the index+ * if no modification to the index occur for the given time. The used time+ * unit is {@link TimeUnit#SECONDS}. Values less than the default value+ * will be ignored. For the default value see {@link TimedIndexTask}.+ *+ * @param config -+ * the config to be used to configure the indexer+ * @param dir -+ * the directory to index to+ * @param create -+ * <code>true</code> to create a new index, <code>false</code>+ * to use the existing one.+ * @param commitTimeout -+ * the amount of seconds to wait until a commit should be+ * scheduled+ * @return - a new GDataIndexer instance+ * @throws IOException -+ * if an IOException occurs while initializing the indexer+ */+ public static synchronized GDataIndexer createTimedGdataIndexer(+ final IndexSchema config, Directory dir, boolean create,+ long commitTimeout) throws IOException {++ GDataIndexer retVal = new GDataIndexer(config, dir, create);+ retVal.setIndexTask(new TimedIndexTask(retVal, retVal.futurQueue,+ commitTimeout));+ retVal.init();+ return retVal;+ }++ @SuppressWarnings("unused")+ static final class FinishingFuture implements Future<IndexDocument> {++ /**+ * @see java.util.concurrent.Future#cancel(boolean)+ */+ public boolean cancel(boolean arg0) {++ return false;+ }++ /**+ * @see java.util.concurrent.Future#isCancelled()+ */+ public boolean isCancelled() {++ return false;+ }++ /**+ * @see java.util.concurrent.Future#isDone()+ */+ public boolean isDone() {++ return true;+ }++ /**+ * @see java.util.concurrent.Future#get()+ */+ @SuppressWarnings("unused")+ public IndexDocument get() throws InterruptedException,+ ExecutionException {++ return null;+ }++ /**+ * @see java.util.concurrent.Future#get(long,+ * java.util.concurrent.TimeUnit)+ */+ @SuppressWarnings("unused")+ public IndexDocument get(long arg0, TimeUnit arg1)+ throws InterruptedException, ExecutionException,+ TimeoutException {++ return null;+ }++ }++}diff --git a/contrib/gdata-server/src/java/org/apache/lucene/gdata/search/index/GdataIndexerException.java b/contrib/gdata-server/src/java/org/apache/lucene/gdata/search/index/GdataIndexerException.javanew file mode 100755index 00000000000..b0c0d287590--- /dev/null+++ b/contrib/gdata-server/src/java/org/apache/lucene/gdata/search/index/GdataIndexerException.java@@ -0,0 +1,74 @@+/**+ * Copyright 2004 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.+ */++package org.apache.lucene.gdata.search.index;++/**+ * This exception will be thrown if an exception in the indexing component+ * occurs+ *+ * @author Simon Willnauer+ *+ */+public class GdataIndexerException extends RuntimeException {++ private static final long serialVersionUID = -8245420079471690182L;++ /**+ * Creates a new GdataIndexerException+ */+ public GdataIndexerException() {+ super();++ }++ /**+ * Creates a new GdataIndexerException with a new exception message+ *+ * @param arg0 -+ * exception message+ */+ public GdataIndexerException(String arg0) {+ super(arg0);++ }++ /**+ * Creates a new GdataIndexerException with a new exception message and a+ * root cause+ *+ * @param arg0 -+ * exception message+ * @param arg1 -+ * the root cause+ */+ public GdataIndexerException(String arg0, Throwable arg1) {+ super(arg0, arg1);++ }++ /**+ * Creates a new GdataIndexerException with a root cause+ *+ * @param arg0 -+ * the root cause+ */+ public GdataIndexerException(Throwable arg0) {+ super(arg0);++ }++}diff --git a/contrib/gdata-server/src/java/org/apache/lucene/gdata/search/index/IndexAction.java b/contrib/gdata-server/src/java/org/apache/lucene/gdata/search/index/IndexAction.javanew file mode 100755index 00000000000..827a2864f98--- /dev/null+++ b/contrib/gdata-server/src/java/org/apache/lucene/gdata/search/index/IndexAction.java@@ -0,0 +1,37 @@+/**+ * Copyright 2004 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.+ */+package org.apache.lucene.gdata.search.index;++/**+ * This enum defines all possible actions on a GData index.+ *+ * @see org.apache.lucene.gdata.search.index.IndexDocument+ * @see org.apache.lucene.gdata.search.index.IndexDocumentBuilderTask+ * @author Simon Willnauer+ *+ */+public enum IndexAction {+ /**+ * update action+ */+ UPDATE, /**+ * delete action+ */+ DELETE, /**+ * insert / add action+ */+ INSERT+}diff --git a/contrib/gdata-server/src/java/org/apache/lucene/gdata/search/index/IndexController.java b/contrib/gdata-server/src/java/org/apache/lucene/gdata/search/index/IndexController.javanew file mode 100755index 00000000000..1c552e4cd10--- /dev/null+++ b/contrib/gdata-server/src/java/org/apache/lucene/gdata/search/index/IndexController.java@@ -0,0 +1,511 @@+/**+ * Copyright 2004 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.+ */+package org.apache.lucene.gdata.search.index;++import java.io.File;+import java.io.IOException;+import java.util.Collection;+import java.util.Map;+import java.util.Set;+import java.util.Map.Entry;+import java.util.concurrent.ConcurrentHashMap;+import java.util.concurrent.ExecutorService;+import java.util.concurrent.Executors;+import java.util.concurrent.Future;+import java.util.concurrent.atomic.AtomicBoolean;+import java.util.concurrent.atomic.AtomicInteger;+import java.util.concurrent.locks.Lock;+import java.util.concurrent.locks.ReentrantLock;++import org.apache.commons.logging.Log;+import org.apache.commons.logging.LogFactory;+import org.apache.lucene.gdata.data.ServerBaseEntry;+import org.apache.lucene.gdata.search.GDataSearcher;+import org.apache.lucene.gdata.search.SearchComponent;+import org.apache.lucene.gdata.search.StandardGdataSearcher;+import org.apache.lucene.gdata.search.config.IndexSchema;+import org.apache.lucene.gdata.server.registry.Component;+import org.apache.lucene.gdata.server.registry.ComponentType;+import org.apache.lucene.gdata.server.registry.EntryEventListener;+import org.apache.lucene.gdata.server.registry.GDataServerRegistry;+import org.apache.lucene.gdata.server.registry.ProvidedService;+import org.apache.lucene.gdata.utils.ReferenceCounter;+import org.apache.lucene.index.IndexFileNameFilter;+import org.apache.lucene.search.Filter;+import org.apache.lucene.search.IndexSearcher;+import org.apache.lucene.store.Directory;+import org.apache.lucene.store.FSDirectory;++/**+ * Default implementation of the {@link SearchComponent} interface. All actions+ * on the index will be controlled from this class. Only this class grants read+ * or write actions access to the index.+ *+ * @author Simon Willnauer+ *+ */+@Component(componentType = ComponentType.SEARCHCONTROLLER)+public class IndexController implements SearchComponent, IndexEventListener,+ EntryEventListener {+ static final Log LOG = LogFactory.getLog(IndexController.class);++ private final AtomicBoolean isInitialized = new AtomicBoolean(false);++ private final AtomicBoolean destroyed = new AtomicBoolean(false);++ protected Map<String, ServiceIndex> indexerMap;++ private final ExecutorService taskExecutor;++ /**+ * Creates a new IndexController -- call+ * {@link IndexController#initialize()} to set up the controller.+ */+ public IndexController() {+ this.taskExecutor = Executors.newCachedThreadPool();+ }++ /**+ * @see org.apache.lucene.gdata.search.SearchComponent#initialize()+ */+ public synchronized void initialize() {+ if (this.isInitialized.get())+ throw new IllegalStateException(+ "IndexController is already initialized");+ this.destroyed.set(false);+ /*+ * if this fails the server must not startup --> throw runtime exception+ */+ GDataServerRegistry.getRegistry().registerEntryEventListener(this);++ GDataServerRegistry.getRegistry().registerEntryEventListener(this);+ Collection<ProvidedService> services = GDataServerRegistry+ .getRegistry().getServices();+ this.indexerMap = new ConcurrentHashMap<String, ServiceIndex>(services+ .size());++ for (ProvidedService service : services) {+ IndexSchema schema = service.getIndexSchema();+ /*+ * initialize will fail if mandatory values are not set. This is+ * just a+ */+ schema.initialize();+ addIndexSchema(schema);+ }+ this.isInitialized.set(true);+++ }++ /*+ * add a schema to the index controller and create the indexer. create+ * directories and check out existing indexes+ */+ protected void addIndexSchema(IndexSchema schema) {+ if (this.destroyed.get())+ throw new IllegalStateException(+ "IndexController has been destroyed");+ if (schema.getName() == null)+ throw new IllegalStateException(+ "schema has no name -- is not associated with any service");+ if (this.indexerMap.containsKey(schema.getName()))+ throw new IllegalStateException("schema for service "+ + schema.getName() + " is already registered");+ if (LOG.isInfoEnabled())+ LOG.info("add new IndexSchema for service " + schema.getName()+ + " -- " + schema);+ try {+ ServiceIndex bean = createIndexer(schema);+ ReferenceCounter<IndexSearcher> searcher = getNewServiceSearcher(bean.getDirectory());+ bean.setSearcher(searcher);+ this.indexerMap.put(schema.getName(), bean);+ } catch (IOException e) {+ LOG.error("Can not create indexer for service " + schema.getName(),+ e);+ throw new GdataIndexerException(+ "Can not create indexer for service " + schema.getName(), e);+ }++ }++ protected ServiceIndex createIndexer(IndexSchema schema) throws IOException {+ GDataIndexer indexer;+ File indexLocation = createIndexLocation(schema.getIndexLocation(),+ schema.getName());+ boolean create = createIndexDirectory(indexLocation);+ Directory dir = FSDirectory.getDirectory(indexLocation, create);+ if (LOG.isInfoEnabled())+ LOG.info("Create new Indexer for IndexSchema: " + schema);+ /*+ * timed or committed indexer?! keep the possibility to let users decide+ * to use scheduled commits+ */+ if (schema.isUseTimedIndexer())+ indexer = GDataIndexer.createTimedGdataIndexer(schema, dir, create,+ schema.getIndexerIdleTime());+ else+ indexer = GDataIndexer.createGdataIndexer(schema, dir, create);+ indexer.registerIndexEventListener(this);+ return new ServiceIndex(schema, indexer, dir);+ }++ /*+ * if this fails the server must not startup!!+ */+ protected File createIndexLocation(String path, String name) {+ if (path == null || name == null)+ throw new GdataIndexerException(+ "Path or Name of the index location is not set Path: "+ + path + " name: " + name);+ /*+ * check if parent e.g. the configured path is a directory+ */+ File parent = new File(path);+ if (!parent.isDirectory())+ throw new IllegalArgumentException(+ "the given path is not a directory -- " + path);+ /*+ * try to create and throw ex if fail+ */+ if (!parent.exists())+ if (!parent.mkdir())+ throw new RuntimeException("Can not create directory -- "+ + path);+ /*+ * try to create and throw ex if fail+ */+ File file = new File(parent, name);+ if (file.isFile())+ throw new IllegalArgumentException(+ "A file with the name"+ + name+ + " already exists in "+ + path+ + " -- a file of the name of the service must not exist in the index location");++ if (!file.exists()) {+ if (!file.mkdir())+ throw new RuntimeException("Can not create directory -- "+ + file.getAbsolutePath());+ }+ return file;+ }++ protected boolean createIndexDirectory(File file) {+ /*+ * use a lucene filename filter to figure out if there is an existing+ * index in the defined directory+ */+ String[] luceneFiles = file.list(new IndexFileNameFilter());+ return !(luceneFiles.length > 0);++ }++ /**+ * @see org.apache.lucene.gdata.search.index.IndexEventListener#commitCallBack(java.lang.String)+ */+ public synchronized void commitCallBack(String service) {+ if (this.destroyed.get())+ throw new IllegalStateException(+ "IndexController has been destroyed");+ if(LOG.isInfoEnabled())+ LOG.info("CommitCallback triggered - register new searcher for service: "+service);+ /*+ * get the old searcher and replace it if possible.+ */+ ServiceIndex index = this.indexerMap.get(service);+ ReferenceCounter<IndexSearcher> searcher = index.getSearcher();++ try {+ index.setSearcher(getNewServiceSearcher(index.getDirectory()));+ } catch (IOException e) {+ LOG.fatal("Can not create new Searcher -- keep the old one ", e);+ return;+ }+ /*+ * if new searcher if registered decrement old one to get it destroyed if unused+ */+ searcher.decrementRef();+ }+ /*+ * create a new ReferenceCounter for the indexSearcher.+ * The reference is already incremented before returned+ */+ private ReferenceCounter<IndexSearcher> getNewServiceSearcher(Directory dir)+ throws IOException {+ if(LOG.isInfoEnabled())+ LOG.info("Create new ServiceSearcher");+ IndexSearcher searcher = new IndexSearcher(dir);+ ReferenceCounter<IndexSearcher> holder = new ReferenceCounter<IndexSearcher>(+ searcher) {++ @Override+ protected void close() {+ try {+ LOG+ .info("Close IndexSearcher -- Zero references remaining");+ this.resource.close();+ } catch (IOException e) {+ LOG.warn("Can not close IndexSearcher -- ", e);+ }+ }++ };+ holder.increamentReference();+ return holder;+ }++ /**+ * @see org.apache.lucene.gdata.server.registry.EntryEventListener#fireUpdateEvent(org.apache.lucene.gdata.data.ServerBaseEntry)+ */+ public void fireUpdateEvent(ServerBaseEntry entry) {+ createNewIndexerTask(entry, IndexAction.UPDATE);+ }++ /**+ * @see org.apache.lucene.gdata.server.registry.EntryEventListener#fireInsertEvent(org.apache.lucene.gdata.data.ServerBaseEntry)+ */+ public void fireInsertEvent(ServerBaseEntry entry) {+ createNewIndexerTask(entry, IndexAction.INSERT);+ }++ /**+ * @see org.apache.lucene.gdata.server.registry.EntryEventListener#fireDeleteEvent(org.apache.lucene.gdata.data.ServerBaseEntry)+ */+ public void fireDeleteEvent(ServerBaseEntry entry) {+ createNewIndexerTask(entry, IndexAction.DELETE);++ }++ // TODO add test for this method!!+ private void createNewIndexerTask(ServerBaseEntry entry, IndexAction action) {+ if (this.destroyed.get())+ throw new IllegalStateException(+ "IndexController has been destroyed");+ if(!this.isInitialized.get())+ throw new IllegalStateException(+ "IndexController has not been initialized");++ String serviceName = entry.getServiceConfig().getName();+ if (LOG.isInfoEnabled())+ LOG.info("New Indexer Task submitted - Action: " + action+ + " for service: " + serviceName);+ ServiceIndex bean = this.indexerMap.get(serviceName);+ if (bean == null)+ throw new RuntimeException("no indexer for service " + serviceName+ + " registered");+ /*+ * lock on service to synchronize the event order. This lock has+ * fairness parameter set to true. Grant access to the longest waiting+ * thread. Using fairness is slower but is acceptable in this context+ */+ Lock lock = bean.getLock();+ lock.lock();+ try {+ IndexSchema schema = bean.getSchema();+ boolean commitAfter = bean.incrementActionAndReset(schema.getCommitAfterDocuments());+ IndexDocumentBuilder<IndexDocument> callable = new IndexDocumentBuilderTask<IndexDocument>(+ entry, bean.getSchema(), action, commitAfter,bean.getOptimize(schema.getOptimizeAfterCommit()));+ Future<IndexDocument> task = this.taskExecutor.submit(callable);+ GDataIndexer indexer = bean.getIndexer();+ try {+ indexer.addIndexableDocumentTask(task);+ } catch (InterruptedException e) {+ throw new GdataIndexerException(+ "Can not accept any index tasks -- interrupted. ", e);++ }+ } finally {+ /*+ * make sure to unlock+ */+ lock.unlock();+ }++ }++++ /**+ * @see org.apache.lucene.gdata.search.SearchComponent#getServiceSearcher(org.apache.lucene.gdata.server.registry.ProvidedService)+ */+ public GDataSearcher<String> getServiceSearcher(ProvidedService service) {+ if (this.destroyed.get())+ throw new IllegalStateException(+ "IndexController has been destroyed");+ /*+ * get and increment. searcher will be decremented if GdataSearcher is+ * closed+ */+ ReferenceCounter<IndexSearcher> searcher;+ synchronized (this) {+ ServiceIndex serviceIndex = this.indexerMap.get(service.getName());+ if(serviceIndex == null)+ throw new RuntimeException("no index for service "+service.getName());+ searcher = serviceIndex.getSearcher();+ searcher.increamentReference();+ }++ return new StandardGdataSearcher(searcher);+ }++ /**+ * @see org.apache.lucene.gdata.search.SearchComponent#destroy()+ */+ public synchronized void destroy() {+ if (this.destroyed.get())+ throw new IllegalStateException(+ "IndexController has been destroyed");+ if (!this.isInitialized.get())+ return;+ this.destroyed.set(true);+ this.isInitialized.set(false);+ LOG.info("Shutting down IndexController -- destroy has been called");+ Set<Entry<String, ServiceIndex>> entrySet = this.indexerMap.entrySet();+ for (Entry<String, ServiceIndex> entry : entrySet) {+ ServiceIndex bean = entry.getValue();+ bean.getSearcher().decrementRef();+ GDataIndexer indexer = bean.getIndexer();+ try {+ indexer.destroy();+ } catch (IOException e) {+ LOG.warn("Can not destroy indexer for service: "+ + bean.getSchema().getName(), e);+ }+ }+ this.taskExecutor.shutdown();+ this.indexerMap.clear();+ }++ static class ServiceIndex {+ private AtomicInteger actionCount = new AtomicInteger(0);++ private AtomicInteger commitCount = new AtomicInteger(0);++ private final Lock lock;++ private final IndexSchema schema;++ private final GDataIndexer indexer;++ private final Directory directory;++ private Filter addedDocumentFilter;++ private ReferenceCounter<IndexSearcher> searcher;++ // private final Map<String,IndexAction> actionMap;++++ ServiceIndex(final IndexSchema schema, GDataIndexer indexer,+ Directory directory) {+ this.schema = schema;+ this.indexer = indexer;+ this.lock = new ReentrantLock(true);+ this.directory = directory;+ // this.actionMap = new HashMap<String,IndexAction>(128);+ }++ Lock getLock() {+ return this.lock;+ }++ /**+ * @return Returns the indexer.+ */+ GDataIndexer getIndexer() {+ return this.indexer;+ }++ /**+ * @return Returns the schema.+ */+ IndexSchema getSchema() {+ return this.schema;+ }++ // public void addAction(IndexAction action,ServerBaseEntry entry){+ //+ // }+ /**+ * Counts how many actions have been executed on this index+ *+ * @param reset - count mod reset value equals 0 causes a commit+ *+ * @return <code>true</code> if the count mod reset value equals 0, otherwise+ * false;+ */+ boolean incrementActionAndReset(int reset) {+ if (this.actionCount.incrementAndGet()%reset == 0) {+ return true;+ }+ return false;+ }++ /**+ * @return Returns the directory.+ */+ public Directory getDirectory() {+ return this.directory;+ }+ /**+ * @return Returns the addedDocumentFilter.+ */+ public Filter getAddedDocumentFilter() {+ return this.addedDocumentFilter;+ }++ /**+ * @param addedDocumentFilter The addedDocumentFilter to set.+ */+ public void setAddedDocumentFilter(Filter addedDocumentFilter) {+ this.addedDocumentFilter = addedDocumentFilter;+ }++ /**+ * @return Returns the searcher.+ */+ public ReferenceCounter<IndexSearcher> getSearcher() {+ return this.searcher;+ }++ /**+ * @param searcher The searcher to set.+ */+ public void setSearcher(ReferenceCounter<IndexSearcher> searcher) {+ this.searcher = searcher;+ }++ /**+ * @return Returns the commitCount.+ */+ public int commitCountIncrement() {+ return this.commitCount.incrementAndGet();+ }+ /**+ * @param reset - the number after how many commits the index should be optimized+ * @return <code>true</code> if and only if the commit count mod reset equals 0, otherwise <code>false</code>.+ */+ public boolean getOptimize(int reset){+ if(this.commitCount.get()%reset == 0){+ return true;+ }+ return false;+ }+ }+}diff --git a/contrib/gdata-server/src/java/org/apache/lucene/gdata/search/index/IndexDocument.java b/contrib/gdata-server/src/java/org/apache/lucene/gdata/search/index/IndexDocument.javanew file mode 100755index 00000000000..feee6c5389d--- /dev/null+++ b/contrib/gdata-server/src/java/org/apache/lucene/gdata/search/index/IndexDocument.java@@ -0,0 +1,100 @@+/**+ * Copyright 2004 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.+ */+package org.apache.lucene.gdata.search.index;++import org.apache.lucene.document.Document;+import org.apache.lucene.index.Term;++/**+ * IndexDocument encapsulates the acual entity to store, update or delete. All+ * infomation to process the action on this document are provided via this+ * interface.+ * <p>+ * This enables the GDataIndexer to index every kind of document. All the+ * processing of the original document happens somewhere behind this facade.+ * {@link org.apache.lucene.gdata.search.index.IndexDocumentBuilderTask} passed+ * to the {@link org.apache.lucene.gdata.search.index.GDataIndexer} task queue+ * produce instances of this interface concurrently.+ * </p>+ *+ * @author Simon Willnauer+ *+ *+ */+public interface IndexDocument {+ /**+ * the index field to identify a document in the index. This acts as a+ * primary key to fetch the entire entry from the storage+ */+ public static final String FIELD_ENTRY_ID = "enryId";+ /**+ * the index field to associate a document with a specific feed+ */+ public static final String FIELD_FEED_ID = "feedId";+ public static final String GDATA_MANDATORY_FIELD_UPDATED = "updated";+ public static final String GDATA_MANDATORY_FIELD_CATEGORY = "category";++ /**+ * @return <code>true</code> if and only if this document is an update,+ * otherwise <code>false</code>+ */+ public abstract boolean isUpdate();++ /**+ * @return <code>true</code> if and only if this document is a delete,+ * otherwise <code>false</code>+ */+ public abstract boolean isDelete();++ /**+ * @return <code>true</code> if and only if this document is an insert,+ * otherwise <code>false</code>+ */+ public abstract boolean isInsert();++ /**+ *+ * @return - the lucene document to write to the index if the action is+ * insert or updated, otherwise it will return <code>null</code>;+ */+ public abstract Document getWriteable();++ /**+ * @return - a term that identifies this document in the index to delete+ * this document on a update or delete+ */+ public abstract Term getDeletealbe();++ /**+ * Indicates that the index should be commited after this document has been+ * processed+ *+ * @return <code>true</code> if the index should be commited after this+ * document, otherwise <code>false</code>+ */+ public abstract boolean commitAfter();++ /**+ * Indicates that the index should be optimized after this document has been+ * processed+ *+ *+ * @return <code>true</code> if the index should be optimized after this+ * document, otherwise <code>false</code>+ */+ public abstract boolean optimizeAfter();++}diff --git a/contrib/gdata-server/src/java/org/apache/lucene/gdata/search/index/IndexDocumentBuilder.java b/contrib/gdata-server/src/java/org/apache/lucene/gdata/search/index/IndexDocumentBuilder.javanew file mode 100755index 00000000000..a34d5cf3b54--- /dev/null+++ b/contrib/gdata-server/src/java/org/apache/lucene/gdata/search/index/IndexDocumentBuilder.java@@ -0,0 +1,32 @@+/**+ * Copyright 2004 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.+ */+package org.apache.lucene.gdata.search.index;++import java.util.concurrent.Callable;++/**+ * Interface for DocumentBuilders+ * @author Simon Willnauer+ * @param <T> IndexDocument implementation+ *+ */+public interface IndexDocumentBuilder<T extends IndexDocument> extends Callable<T>{+ /**+ * @see java.util.concurrent.Callable#call()+ */+ public T call() throws GdataIndexerException;++}diff --git a/contrib/gdata-server/src/java/org/apache/lucene/gdata/search/index/IndexDocumentBuilderTask.java b/contrib/gdata-server/src/java/org/apache/lucene/gdata/search/index/IndexDocumentBuilderTask.javanew file mode 100755index 00000000000..f16afaa8250--- /dev/null+++ b/contrib/gdata-server/src/java/org/apache/lucene/gdata/search/index/IndexDocumentBuilderTask.java@@ -0,0 +1,104 @@+/**+ * Copyright 2004 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.+ */++package org.apache.lucene.gdata.search.index;++import java.util.Collection;++import org.apache.commons.logging.Log;+import org.apache.commons.logging.LogFactory;+import org.apache.lucene.gdata.data.ServerBaseEntry;+import org.apache.lucene.gdata.search.analysis.ContentStrategy;+import org.apache.lucene.gdata.search.analysis.Indexable;+import org.apache.lucene.gdata.search.analysis.NotIndexableException;+import org.apache.lucene.gdata.search.config.IndexSchema;+import org.apache.lucene.gdata.search.config.IndexSchemaField;++/**+ * This callable does all of the entiti processing concurrently while added to+ * the {@link org.apache.lucene.gdata.search.index.GDataIndexer} task queue;+ *+ * @see org.apache.lucene.gdata.search.analysis.Indexable+ * @see org.apache.lucene.gdata.search.analysis.ContentStrategy+ * @author Simon Willnauer+ *+ */+class IndexDocumentBuilderTask<T extends IndexDocument> implements IndexDocumentBuilder<T> {+ private static final Log LOG = LogFactory+ .getLog(IndexDocumentBuilderTask.class);++ private final ServerBaseEntry entry;++ private final IndexSchema schema;++ private final IndexAction action;++ private final boolean commitAfter;+ private final boolean optimizeAfter;+ protected IndexDocumentBuilderTask(final ServerBaseEntry entry,+ final IndexSchema schema, IndexAction action, boolean commitAfter, boolean optimizeAfter) {+ /*+ * omit check for null parameter this happens in the controller.+ */+ this.schema = schema;+ this.entry = entry;+ this.action = action;+ this.commitAfter = commitAfter;+ this.optimizeAfter = optimizeAfter;+ }++ /**+ * @see java.util.concurrent.Callable#call()+ */+ @SuppressWarnings("unchecked")+ public T call() throws GdataIndexerException {++ Collection<IndexSchemaField> fields = this.schema.getFields();+ GDataIndexDocument document = new GDataIndexDocument(this.action,+ this.entry.getId(),this.entry.getFeedId(), this.commitAfter,this.optimizeAfter);+ if(this.action != IndexAction.DELETE){+ int addedFields = 0;+ for (IndexSchemaField field : fields) {+ /*+ * get the strategy to process the field+ */+ ContentStrategy strategy = ContentStrategy.getFieldStrategy(field);+ if (LOG.isInfoEnabled())+ LOG.info("Process indexable for " + field);+ try {+ /*+ * get the indexable via the factory method to enable new /+ * different implementation of the interface (this could be a+ * faster dom impl e.g. dom4j)+ */+ strategy.processIndexable(Indexable.getIndexable(this.entry));+ addedFields++;+ } catch (NotIndexableException e) {+ LOG.warn("Can not create field for " + field+" field will be skipped -- reason: ", e);+ continue;+ }++ document.addField(strategy);++ }+ if(addedFields == 0)+ throw new GdataIndexerException("No field added to document for Schema: "+this.schema);+ }+ return (T)document;+ }+++}diff --git a/contrib/gdata-server/src/java/org/apache/lucene/gdata/search/index/IndexEventListener.java b/contrib/gdata-server/src/java/org/apache/lucene/gdata/search/index/IndexEventListener.javanew file mode 100755index 00000000000..249ecaf382e--- /dev/null+++ b/contrib/gdata-server/src/java/org/apache/lucene/gdata/search/index/IndexEventListener.java@@ -0,0 +1,36 @@+/**+ * Copyright 2004 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.+ */+package org.apache.lucene.gdata.search.index;++/**+ * This interface should be implemented by classes need to be notified when an+ * index is commited+ *+ * @author Simon Willnauer+ *+ */+public interface IndexEventListener {++ /**+ * This method will be invoked by an instance of {@link GDataIndexer} if the+ * index is commited+ *+ * @param service -+ * the name of the service the invoking indexer runs for+ */+ public abstract void commitCallBack(String service);++}diff --git a/contrib/gdata-server/src/java/org/apache/lucene/gdata/search/index/IndexLogReader.java b/contrib/gdata-server/src/java/org/apache/lucene/gdata/search/index/IndexLogReader.javanew file mode 100755index 00000000000..b2fee1e9e88--- /dev/null+++ b/contrib/gdata-server/src/java/org/apache/lucene/gdata/search/index/IndexLogReader.java@@ -0,0 +1,168 @@+/**+ * Copyright 2004 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.+ */++package org.apache.lucene.gdata.search.index;++import java.io.File;+import java.io.FileInputStream;+import java.io.IOException;+import java.util.HashMap;+import java.util.Map;++import org.xml.sax.Attributes;+import org.xml.sax.ContentHandler;+import org.xml.sax.InputSource;+import org.xml.sax.Locator;+import org.xml.sax.SAXException;+import org.xml.sax.XMLReader;+import org.xml.sax.helpers.XMLReaderFactory;++/**+ * @author Simon Willnauer+ *+ */+class IndexLogReader {++ static Map<String,IndexAction> readIndexLog(File indexLogFile, Map<String,IndexAction> contentMap) throws SAXException,IOException{+ XMLReader reader = XMLReaderFactory.createXMLReader();++ Map<String, IndexAction> logContent = contentMap;+ if(logContent == null)+ logContent = new HashMap<String,IndexAction>(64);++ reader.setContentHandler(new IndexLogContentHandler(logContent));+ InputSource source = new InputSource(new FileInputStream(indexLogFile));+ try{+ reader.parse(source);+ }catch (SAXException e) {+ /*+ * try to append the Root element end+ * this happens if the server crashes.+ * If it dies while writing an entry the log file has to be fixed manually+ */+ IndexLogWriter.tryCloseRoot(indexLogFile);+ source = new InputSource(new FileInputStream(indexLogFile));+ reader.parse(source);+ }+ return logContent;+ }+++ private static class IndexLogContentHandler implements ContentHandler {+ private final Map<String, IndexAction> logContent;+ private String currentID;+ private String currentAction;+ private boolean isId;+ private boolean isAction;+ IndexLogContentHandler(final Map<String, IndexAction> content) {+ this.logContent = content;+ }++ /**+ * @see org.xml.sax.ContentHandler#setDocumentLocator(org.xml.sax.Locator)+ */+ public void setDocumentLocator(Locator locator) {+ }++ /**+ * @see org.xml.sax.ContentHandler#startDocument()+ */+ public void startDocument() throws SAXException {+ }++ /**+ * @see org.xml.sax.ContentHandler#endDocument()+ */+ public void endDocument() throws SAXException {+ }++ /**+ * @see org.xml.sax.ContentHandler#startPrefixMapping(java.lang.String, java.lang.String)+ */+ public void startPrefixMapping(String prefix, String uri)+ throws SAXException {+ }++ /**+ * @see org.xml.sax.ContentHandler#endPrefixMapping(java.lang.String)+ */+ public void endPrefixMapping(String prefix) throws SAXException {+ }++ /**+ * @see org.xml.sax.ContentHandler#startElement(java.lang.String, java.lang.String, java.lang.String, org.xml.sax.Attributes)+ */+ public void startElement(String uri, String localName, String qName,+ Attributes atts) throws SAXException {+ if(localName.equals("entryid")){+ this.isId = true;+ }else if(localName.equals("action")){+ this.isAction = true;+ }+ }++ /**+ * @see org.xml.sax.ContentHandler#endElement(java.lang.String, java.lang.String, java.lang.String)+ */+ public void endElement(String uri, String localName, String qName)+ throws SAXException {+ if(localName.equals("entryid")){+ this.isId = false;+ }else if(localName.equals("action")){+ this.isAction = false;+ }else if(localName.equals("indexentry")){+ this.logContent.put(this.currentID,IndexAction.valueOf(this.currentAction));+ }+ }++ /**+ * @see org.xml.sax.ContentHandler#characters(char[], int, int)+ */+ public void characters(char[] ch, int start, int length)+ throws SAXException {+ if(this.isId)+ this.currentID = new String(ch,start,length);+ if(this.isAction)+ this.currentAction = new String(ch,start,length);++ }++ /**+ * @see org.xml.sax.ContentHandler#ignorableWhitespace(char[], int, int)+ */+ public void ignorableWhitespace(char[] ch, int start, int length)+ throws SAXException {+ }++ /**+ * @see org.xml.sax.ContentHandler#processingInstruction(java.lang.String, java.lang.String)+ */+ public void processingInstruction(String target, String data)+ throws SAXException {+ }++ /**+ * @see org.xml.sax.ContentHandler#skippedEntity(java.lang.String)+ */+ public void skippedEntity(String name) throws SAXException {+ }++++ }+++}diff --git a/contrib/gdata-server/src/java/org/apache/lucene/gdata/search/index/IndexLogWriter.java b/contrib/gdata-server/src/java/org/apache/lucene/gdata/search/index/IndexLogWriter.javanew file mode 100755index 00000000000..2e6fcc947fb--- /dev/null+++ b/contrib/gdata-server/src/java/org/apache/lucene/gdata/search/index/IndexLogWriter.java@@ -0,0 +1,112 @@+/**+ * Copyright 2004 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.+ */++package org.apache.lucene.gdata.search.index;++import java.io.BufferedWriter;+import java.io.File;+import java.io.FileOutputStream;+import java.io.IOException;+import java.io.OutputStreamWriter;+import java.io.RandomAccessFile;+import java.util.concurrent.atomic.AtomicBoolean;++/**+ * @author Simon Willnauer+ *+ */+class IndexLogWriter {+ private static final String LINE_BREAK = System+ .getProperty("line.separator");++ private static final String XMLHEADER = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>"+ + LINE_BREAK;+ private static final String CHARSET = "UTF-8";+ private static final String ROOT_BEGIN = "<indexlog>" + LINE_BREAK;++ private static final String ROOT_END = "</indexlog>";++++ private final BufferedWriter writer;++ private final AtomicBoolean isClosed;++ /**+ * @param file+ * @throws IOException+ *+ */+ public IndexLogWriter(File file) throws IOException {++ this.writer = new BufferedWriter(new OutputStreamWriter(+ new FileOutputStream(file), CHARSET));+ this.writer.write(XMLHEADER);+ this.writer.write(ROOT_BEGIN);+ this.writer.flush();+ this.isClosed = new AtomicBoolean(false);++ }++ synchronized void writeAction(String id, IndexAction action)+ throws IOException {+ if (this.isClosed.get())+ throw new IllegalStateException("Writer is already closed");+ this.writer.write(buildElement(id, action.name()));+ this.writer.flush();+ }++ static synchronized void tryCloseRoot(File file) throws IOException {+ /*+ * try to append the Root element end+ * this happens if the server crashes.+ * If it dies while writing an entry the log file has to be fixed manually+ */+ RandomAccessFile raFile = new RandomAccessFile(file, "rw");+ raFile.seek(raFile.length());+ raFile.write(IndexLogWriter.ROOT_END.getBytes(CHARSET));+ raFile.close();+++ }++ private static String buildElement(String id, String action) {+ StringBuilder builder = new StringBuilder("\t<indexentry>")+ .append(LINE_BREAK);+ builder.append("\t\t<entryid>");+ builder.append(id);+ builder.append("</entryid>").append(LINE_BREAK);+ builder.append("\t\t<action>");+ builder.append(action);+ builder.append("</action>").append(LINE_BREAK);+ builder.append("\t</indexentry>").append(LINE_BREAK);+ return builder.toString();++ }++ synchronized void close() throws IOException {+ if (!this.isClosed.compareAndSet(false,true))+ throw new IllegalStateException("Writer is already closed");+ try {+ this.writer.write(ROOT_END);+ this.writer.flush();+ } finally {+ this.writer.close();+ }++ }++}diff --git a/contrib/gdata-server/src/java/org/apache/lucene/gdata/search/index/IndexTask.java b/contrib/gdata-server/src/java/org/apache/lucene/gdata/search/index/IndexTask.javanew file mode 100755index 00000000000..658bad76e10--- /dev/null+++ b/contrib/gdata-server/src/java/org/apache/lucene/gdata/search/index/IndexTask.java@@ -0,0 +1,174 @@+/**+ * Copyright 2004 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.+ */++package org.apache.lucene.gdata.search.index;++import java.io.IOException;+import java.util.concurrent.BlockingQueue;+import java.util.concurrent.ExecutionException;+import java.util.concurrent.Future;+import java.util.concurrent.atomic.AtomicBoolean;++import org.apache.commons.logging.Log;+import org.apache.commons.logging.LogFactory;++/**+ *+ * Class to be used inside a+ * {@link org.apache.lucene.gdata.search.index.GDataIndexer} to process the task+ * queue. This class calls the commit method of the indexer if commit is+ * scheduled.+ *+ * @author Simon Willnauer+ *+ */+class IndexTask implements Runnable {+ private static final Log INNERLOG = LogFactory.getLog(IndexTask.class);++ private AtomicBoolean stopped = new AtomicBoolean(false);++ private final GDataIndexer indexer;++ protected AtomicBoolean commit = new AtomicBoolean(false);++ protected AtomicBoolean optimize = new AtomicBoolean(false);++ /*+ * keep protected for subclassing+ */+ protected final BlockingQueue<Future<IndexDocument>> taskQueue;++ IndexTask(final GDataIndexer indexer,+ final BlockingQueue<Future<IndexDocument>> taskQueue) {+ this.indexer = indexer;+ this.taskQueue = taskQueue;+ }++ /**+ * @see java.lang.Runnable#run()+ */+ public void run() {++ while (!this.stopped.get() || this.taskQueue.size() != 0) {++ try {+ /*+ * get the future from the queue and wait until processing has+ * been done+ */+ Future<IndexDocument> future = getTask();+ if (future != null) {+ IndexDocument document = future.get();+ setOptimize(document);+ processDocument(document);+ /*+ * the document contains the info for commit or optimize -->+ * this comes from the controller+ */+ if (document == null || document.commitAfter())+ this.indexer.commit(document == null ? false : this.optimize.getAndSet(false));+ }+ if (this.commit.getAndSet(false))+ this.indexer.commit(this.optimize.getAndSet(false));++ } catch (InterruptedException e) {+ INNERLOG.warn("Queue is interrupted exiting IndexTask -- ", e);++ } catch (GdataIndexerException e) {+ /*+ *+ * TODO fire callback here as well+ */+ INNERLOG.error("can not retrieve Field from IndexDocument ", e);+ } catch (ExecutionException e) {+ /*+ * TODO callback for fail this exception is caused by an+ * exception while processing the document. call back for failed+ * docs should be placed here+ */+ INNERLOG.error("Future throws execution exception ", e);++ } catch (IOException e) {+ INNERLOG.error("IOException thrown while processing document ",+ e);++ } catch (Throwable e) {+ /*+ * catch all to prevent the thread from dieing+ */+ INNERLOG.error(+ "Unexpected exception while processing document -- "+ + e.getMessage(), e);+ }+ }+ try {+ this.indexer.commit(this.optimize.getAndSet(false));+ } catch (IOException e) {+ INNERLOG.warn("commit on going down failed - "+e.getMessage(),e);++ }+ this.stop();+ }+ protected void setOptimize(IndexDocument document){+ if(document == null)+ return;+ this.optimize.set(document.optimizeAfter());+ }++ /*+ * keep this protected for subclassing see TimedIndexTask!+ */+ protected Future<IndexDocument> getTask() throws InterruptedException {+ return this.taskQueue.take();+ }++ private void processDocument(IndexDocument document) throws IOException {+ /*+ * a null document is used for waking up the task if the indexer has+ * been destroyed to finish up and commit. should I change this?! -->+ * see TimedIndexTask#getTask() also!!+ */+ if (document == null) {+ INNERLOG.warn("Can not process document -- is null -- run commit");+ return;+ }+ if (document.isDelete()) {+ this.indexer.deleteDocument(document);+ return;+ } else if (document.isInsert()) {+ this.indexer.addDocument(document);+ return;+ } else if (document.isUpdate()) {+ this.indexer.updateDocument(document);+ return;+ }+ /*+ * that should not happen -- anyway skip the document and write it to+ * the log+ */+ INNERLOG.warn("IndexDocument has no Action " + document);++ }++ protected boolean isStopped() {+ return this.stopped.get();+ }++ protected void stop() {+ this.stopped.set(true);+ }++}\ No newline at end of filediff --git a/contrib/gdata-server/src/java/org/apache/lucene/gdata/search/index/TimedIndexTask.java b/contrib/gdata-server/src/java/org/apache/lucene/gdata/search/index/TimedIndexTask.javanew file mode 100755index 00000000000..d6e05febe9a--- /dev/null+++ b/contrib/gdata-server/src/java/org/apache/lucene/gdata/search/index/TimedIndexTask.java@@ -0,0 +1,67 @@+/**+ * Copyright 2004 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.+ */++package org.apache.lucene.gdata.search.index;++import java.util.concurrent.BlockingQueue;+import java.util.concurrent.Future;+import java.util.concurrent.TimeUnit;++/**+ * This {@link IndexTask} will idle the given time if no task is on the queue.+ * If the idle time exceeds the task will force a commit on the index. The timer+ * will be reset if a task is on the queue.+ *+ * @author Simon Willnauer+ *+ */+class TimedIndexTask extends IndexTask {+ protected final static TimeUnit TIME_UNIT = TimeUnit.SECONDS;++ protected final static long DEFAULT_IDLE_TIME = 30;++ private final long idleTime;++ TimedIndexTask(final GDataIndexer indexer,+ final BlockingQueue<Future<IndexDocument>> taskQueue,+ final long idleTime) {+ super(indexer, taskQueue);+ this.idleTime = idleTime < DEFAULT_IDLE_TIME ? DEFAULT_IDLE_TIME+ : idleTime;++ }++ /**+ * @see org.apache.lucene.gdata.search.index.IndexTask#getTask()+ */+ @Override+ protected Future<IndexDocument> getTask() throws InterruptedException {+ /*+ * wait for a certain time and return null if no task is on the queue.+ * If return null --> commit will be called+ */+ Future<IndexDocument> retVal = this.taskQueue.poll(this.idleTime, TIME_UNIT);+ if(retVal== null)+ this.commit.set(true);+ return retVal;++ }++ protected long getIdleTime(){+ return this.idleTime;+ }++}diff --git a/contrib/gdata-server/src/java/org/apache/lucene/gdata/search/index/package.html b/contrib/gdata-server/src/java/org/apache/lucene/gdata/search/index/package.htmlnew file mode 100755index 00000000000..7257463a2bd--- /dev/null+++ b/contrib/gdata-server/src/java/org/apache/lucene/gdata/search/index/package.html@@ -0,0 +1,10 @@+<!doctype html public "-//w3c//dtd html 4.0 transitional//en">+<html>+<head>+ <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">+ <meta name="Author" content="Simon Willnauer">+</head>+<body>+Contains classes processing of documents and accessing the search index of the server+</body>+</html>\ No newline at end of filediff --git a/contrib/gdata-server/src/java/org/apache/lucene/gdata/search/package.html b/contrib/gdata-server/src/java/org/apache/lucene/gdata/search/package.htmlnew file mode 100755index 00000000000..44809524a84--- /dev/null+++ b/contrib/gdata-server/src/java/org/apache/lucene/gdata/search/package.html@@ -0,0 +1,10 @@+<!doctype html public "-//w3c//dtd html 4.0 transitional//en">+<html>+<head>+ <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">+ <meta name="Author" content="Simon Willnauer">+</head>+<body>+Classes used for query the lucene index for a specific feed instance+</body>+</html>\ No newline at end of filediff --git a/contrib/gdata-server/src/java/org/apache/lucene/gdata/search/query/GDataQueryParser.java b/contrib/gdata-server/src/java/org/apache/lucene/gdata/search/query/GDataQueryParser.javanew file mode 100755index 00000000000..a92e8bca176--- /dev/null+++ b/contrib/gdata-server/src/java/org/apache/lucene/gdata/search/query/GDataQueryParser.java@@ -0,0 +1,57 @@+/**+ * Copyright 2004 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.+ */++package org.apache.lucene.gdata.search.query;++import org.apache.lucene.analysis.Analyzer;+import org.apache.lucene.gdata.search.config.IndexSchema;+import org.apache.lucene.queryParser.QueryParser;++/**+ * @author Simon Willnauer+ *+ */+public class GDataQueryParser extends QueryParser {++ /**+ * Creates a new QueryParser instance and sets the default operator to+ * {@link Operator#AND}+ *+ * @param field -+ * the parser field+ * @param analyzer -+ * the parser analyzer+ */+ public GDataQueryParser(String field, Analyzer analyzer) {+ super(field, analyzer);+ this.setDefaultOperator(Operator.AND);+ }++ /**+ * Creates a new QueryParser instance and sets the default operator to+ * {@link Operator#AND}. The parser will use+ * {@link IndexSchema#getDefaultSearchField} as the field and+ * {@link IndexSchema#getSchemaAnalyzer()} as the analyzer.+ *+ * @param schema -+ * the schema to set the default fields+ */+ public GDataQueryParser(IndexSchema schema) {+ this(schema.getDefaultSearchField(), schema.getSchemaAnalyzer());++ }++}diff --git a/contrib/gdata-server/src/java/org/apache/lucene/gdata/search/query/QueryTranslator.java b/contrib/gdata-server/src/java/org/apache/lucene/gdata/search/query/QueryTranslator.javanew file mode 100755index 00000000000..df29c72785e--- /dev/null+++ b/contrib/gdata-server/src/java/org/apache/lucene/gdata/search/query/QueryTranslator.java@@ -0,0 +1,134 @@+/**+ * Copyright 2004 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.+ */++package org.apache.lucene.gdata.search.query;++import java.util.HashSet;+import java.util.Map;+import java.util.Set;++import org.apache.lucene.gdata.search.config.IndexSchema;++import com.google.gdata.data.DateTime;++/**+ * Simple static methods to translate the http query to a lucene query string.+ * @author Simon Willnauer+ *+ */+public class QueryTranslator {+ private static final Set<String> STANDARD_REQUEST_PARAMETER = new HashSet<String>(3);+ private static final String GDATA_DEFAULT_SEARCH_PARAMETER = "q";+ private static final String UPDATED_MIN = Long.toString(0);+ private static final String UPDATED_MAX = Long.toString(Long.MAX_VALUE);+// private static final String GDATA_CATEGORY_FIEL =++++ static{+ STANDARD_REQUEST_PARAMETER.add("max-results");+ STANDARD_REQUEST_PARAMETER.add("start-index");+ STANDARD_REQUEST_PARAMETER.add("alt");+ }+ /**+ * This method does a little preprocessing of the query. Basically it will map the given request parameters to a lucene syntax. Each+ * parameter matching a index field in the given schema will be translated into a grouped query string according to the lucene query syntax.+ * <p>+ * <ol>+ * <li>title=foo bar AND "FooBar" will be title:(foo bar AND "FooBar)</i>+ * <li>updated-min=2005-08-09T10:57:00-08:00 will be translated to updated:[1123613820000 TO 9223372036854775807] according to the gdata protocol</i>+ * </ol>+ * </p>+ * @param schema the index schema for the queried service+ * @param parameterMap - the http parameter map returning String[] instances as values+ * @param categoryQuery - the parsed category query from the request+ * @return - a lucene syntax query string+ */+ public static String translateHttpSearchRequest(IndexSchema schema,+ Map<String, String[]> parameterMap, String categoryQuery) {+ Set<String> searchableFieldNames = schema.getSearchableFieldNames();+ Set<String> parameterSet = parameterMap.keySet();+ StringBuilder translatedQuery = new StringBuilder();+ if(categoryQuery != null){+ translatedQuery.append(translateCategory(translatedQuery,categoryQuery));+ }+ String updateMin = null;+ String updateMax = null;+ for (String parameterName : parameterSet) {+ if (STANDARD_REQUEST_PARAMETER.contains(parameterName))+ continue;+ if (searchableFieldNames.contains(parameterName)) {+ translatedQuery.append(parameterName).append(":(");+ translatedQuery.append(parameterMap.get(parameterName)[0]);+ translatedQuery.append(") ");+ continue;+ }+ if(parameterName.equals(GDATA_DEFAULT_SEARCH_PARAMETER)){+ translatedQuery.append(schema.getDefaultSearchField());+ translatedQuery.append(":(");+ translatedQuery.append(parameterMap.get(parameterName)[0]);+ translatedQuery.append(") ");+ continue;++ }+ if(parameterName.endsWith("updated-min")){+ updateMin = parameterMap.get(parameterName)[0];+ continue;+ }+ if(parameterName.endsWith("updated-max")){+ updateMax = parameterMap.get(parameterName)[0];+ continue;+ }+ throw new RuntimeException("Can not apply parameter -- invalid -- "+ + parameterName);+ }+ if(updateMax!=null || updateMin!= null)+ translatedQuery.append(translateUpdate(updateMin,updateMax));++ return translatedQuery.length() == 0?null:translatedQuery.toString();+ }+++ static String translateUpdate(String updateMin, String updateMax){+ StringBuilder builder = new StringBuilder("updated:[");+ if(updateMin != null)+ builder.append(Long.toString(DateTime.parseDateTime(updateMin).getValue()));+ else+ builder.append(UPDATED_MIN);+ builder.append(" TO ");+ if(updateMax != null)+ builder.append(Long.toString(DateTime.parseDateTime(updateMax).getValue()-1));+ else+ builder.append(UPDATED_MAX);+ builder.append("]");+ return builder.toString();+++ }++ static String translateCategory(StringBuilder builder, String categoryQuery){+ return categoryQuery;+ //TODO Implement this+// GDataCategoryQueryParser parser = new GDataCategoryQueryParser()+++ }++++++}diff --git a/contrib/gdata-server/src/java/org/apache/lucene/gdata/server/FeedNotFoundException.java b/contrib/gdata-server/src/java/org/apache/lucene/gdata/server/FeedNotFoundException.javaindex cec74f759de..5ebe60dcaf9 100644--- a/contrib/gdata-server/src/java/org/apache/lucene/gdata/server/FeedNotFoundException.java+++ b/contrib/gdata-server/src/java/org/apache/lucene/gdata/server/FeedNotFoundException.java@@ -12,41 +12,46 @@ public class FeedNotFoundException extends ServiceException {private static final long serialVersionUID = 1L;- /**- * Constructs a FeedNotFoundException- */- public FeedNotFoundException() {- super();-- }-- /**- * @param arg0 -- * message- * @param arg1 -- * cause- */- public FeedNotFoundException(String arg0, Throwable arg1) {- super(arg0, arg1);-- }-- /**- * @param arg0 -- * message- */- public FeedNotFoundException(String arg0) {- super(arg0);-- }-- /**- * @param arg0 -- * cause- */- public FeedNotFoundException(Throwable arg0) {- super(arg0);-- }+ /**+ * Constructs a new FeedNotFoundException+ * @param errorCode - gdata request errorcode+ */+ public FeedNotFoundException(int errorCode) {+ super(errorCode);+++ }++ /**+ * Constructs a new FeedNotFoundException+ * @param arg0 - the exception message+ * @param errorCode - gdata request errorcode+ */+ public FeedNotFoundException(String arg0,int errorCode) {+ super(arg0, errorCode);++ }++ /**+ * Constructs a new FeedNotFoundException+ * @param arg0 - the exceptin message+ * @param arg1 - the exception cause+ * @param errorCode - gdata request errorcode+ */+ public FeedNotFoundException(String arg0, Throwable arg1,int errorCode) {+ super(arg0, arg1, errorCode);+++ }++ /**+ * Constructs a new FeedNotFoundException+ * @param arg0 - the exception cause+ * @param errorCode - gdata request errorcode+ */+ public FeedNotFoundException(Throwable arg0,int errorCode) {+ super(arg0, errorCode);++ }}\ No newline at end of filediff --git a/contrib/gdata-server/src/java/org/apache/lucene/gdata/server/GDataRequest.java b/contrib/gdata-server/src/java/org/apache/lucene/gdata/server/GDataRequest.javaindex 7068b144cb1..e8d1d50860e 100644--- a/contrib/gdata-server/src/java/org/apache/lucene/gdata/server/GDataRequest.java+++ b/contrib/gdata-server/src/java/org/apache/lucene/gdata/server/GDataRequest.java@@ -27,23 +27,22 @@ import javax.servlet.http.HttpServletRequest;import org.apache.commons.logging.Log;import org.apache.commons.logging.LogFactory;+import org.apache.lucene.gdata.search.config.IndexSchema;+import org.apache.lucene.gdata.search.query.QueryTranslator;import org.apache.lucene.gdata.server.authentication.AuthenticationController;-import org.apache.lucene.gdata.server.registry.ComponentType;import org.apache.lucene.gdata.server.registry.GDataServerRegistry;import org.apache.lucene.gdata.server.registry.ProvidedService;-import org.apache.lucene.gdata.storage.Storage;-import org.apache.lucene.gdata.storage.StorageController;/*** The GDataRequest Class wraps the incoming HttpServletRequest. Needed* information coming with the HttpServletRequest can be accessed directly. It* represents an abstraction on the plain HttpServletRequest. Every GData- * specific data coming from the client will be availiable and can be accessed+ * specific data coming from the client will be available and can be accessed* via the GDataRequest.* <p>* GDataRequest instances will be passed to any action requested by the client.* This class also holds the logic to retrieve important information like- * response format, the reqeusted feed instance and query parameters.+ * response format, the requested feed instance and query parameters.** </p>*@@ -52,7 +51,8 @@ import org.apache.lucene.gdata.storage.StorageController;*//* this class might be extracted as an interface in later development */public class GDataRequest {-++private static final Log LOG = LogFactory.getLog(GDataRequest.class);private static final String RESPONSE_FORMAT_PARAMETER = "alt";@@ -76,7 +76,9 @@ public class GDataRequest {private static final String HTTP_HEADER_AUTH = "Authorization";- // Atom is the default resopnse format+ private static final Object CATEGORY_QUERY_INDICATOR = "-";++ // Atom is the default response formatprivate OutputFormat responseFormat = OutputFormat.ATOM;private final HttpServletRequest request;@@ -85,12 +87,22 @@ public class GDataRequest {private String entryId = null;+ private String service = null;+private ProvidedService configurator = null;+ private boolean isSearchRequest = false;+private String entryVersion = null;private GDataRequestType type;+ private String categoryQuery;++ private String translatedSearchQuery;++ private boolean isFeedRequest = false;+/*** Creates a new FeedRequest*@@ -120,35 +132,40 @@ public class GDataRequest {public void initializeRequest() throws GDataRequestException {generateIdentificationProperties();setOutputFormat();- // TODO remove this dependency- StorageController controller = GDataServerRegistry.getRegistry()- .lookup(StorageController.class,- ComponentType.STORAGECONTROLLER);+try {-- Storage storage = controller.getStorage();-- String service = storage.getServiceForFeed(this.feedId);- storage.close();/** ExtensionProfile and the type is used for building the Entry /- * Feed Instances from an inputstream or reader+ * Feed Instances from an input stream or reader**/this.configurator = GDataServerRegistry.getRegistry()- .getProvidedService(service);+ .getProvidedService(this.service);+if (this.configurator == null)throw new GDataRequestException(- "feed is not registered or extension profile could not be created");-+ "no Provided Service found for service id: "+this.service,GDataResponse.NOT_FOUND);+ applyRequestParameter();+ if(this.translatedSearchQuery != null)+ this.isSearchRequest = true;+ } catch(GDataRequestException ex){+ throw ex;} catch (Exception e) {- e.printStackTrace();-throw new GDataRequestException(- "feed is not registered or extension profile could not be created -- "- + e.getMessage(), e);+ "failed to initialize GDataRequest -- "+ + e.getMessage(), e,GDataResponse.SERVER_ERROR);+ }++ }++ @SuppressWarnings("unchecked")+ private void applyRequestParameter() throws GDataRequestException{+ IndexSchema schema = this.configurator.getIndexSchema();+ try{+ this.translatedSearchQuery = QueryTranslator.translateHttpSearchRequest(schema,this.request.getParameterMap(),this.categoryQuery);+ }catch (Exception e) {+ throw new GDataRequestException("Can not translate user query to search query",e,GDataResponse.BAD_REQUEST);}-}/**@@ -181,15 +198,15 @@ public class GDataRequest {** @return - the HttpServletRequest {@link Reader}* @throws IOException -- * if an I/O Exception occures+ * if an I/O Exception occurs*/public Reader getReader() throws IOException {return this.request.getReader();}/**- * Returns the {@link HttpServletRequest} parameter map containig all <i>GET</i>- * request parameters.+ * Returns the {@link HttpServletRequest} parameter map containing all+ * <i>GET</i> request parameters.** @return the parameter map*/@@ -222,19 +239,34 @@ public class GDataRequest {throws GDataRequestException {/* generate all needed data to identify the requested feed/entry */String pathInfo = this.request.getPathInfo();- /*- * TODO this has to be changed to support the category queries. Category- * queries could also be rewrited in the Servlet.- */- if (pathInfo.length() <= 1)+ if (pathInfo.length() <= 1)throw new GDataRequestException(- "No feed or entry specified for this request");+ "No feed or entry specified for this request",GDataResponse.BAD_REQUEST);StringTokenizer tokenizer = new StringTokenizer(pathInfo, "/");+ this.service = tokenizer.nextToken();+ if (!tokenizer.hasMoreTokens())+ throw new GDataRequestException(+ "Can not find feed id in requested path " + pathInfo,GDataResponse.BAD_REQUEST);this.feedId = tokenizer.nextToken();- this.entryId = tokenizer.hasMoreTokens() ? tokenizer.nextToken() : "";- this.entryVersion = tokenizer.hasMoreTokens() ? tokenizer.nextToken()- : "";+ String appendix = tokenizer.hasMoreTokens() ? tokenizer.nextToken()+ : null;+ if (appendix == null){+ this.isFeedRequest = true;+ return;+ }+ if (appendix.equals(CATEGORY_QUERY_INDICATOR)) {+ StringBuilder builder = new StringBuilder();+ while (tokenizer.hasMoreTokens())+ builder.append("/").append(tokenizer.nextToken());+ this.categoryQuery = builder.toString();+ } else {+ this.entryId = appendix;+ this.entryVersion = tokenizer.hasMoreTokens() ? tokenizer+ .nextToken() : "";+ }+ this.isFeedRequest = (this.type == GDataRequestType.GET && (this.entryId == null+ || this.entryId.length() == 0 || (this.entryId.equals('/'))));}private void setOutputFormat() {@@ -259,7 +291,7 @@ public class GDataRequest {retval = new Integer(this.request.getParameter(ITEMS_PER_PAGE_PARAMETER)).intValue();} catch (Exception e) {- LOG.warn("Intems per page could not be parsed - " + e.getMessage(),+ LOG.warn("Items per page could not be parsed - " + e.getMessage(),e);}@@ -269,26 +301,26 @@ public class GDataRequest {/*** Start index represents the number of the first entry of the query -* result. The order depends on the query. Is the query a search query the- * this value will be assinged to the score in a common feed query the value+ * this value will be assigned to the score in a common feed query the value* will be assigned to the update time of the entries.** @return - the requested start index*/public int getStartIndex() {- if (this.request.getParameter(START_INDEX_NEXT_PAGE_PARAMETER) == null)+ String startIndex = this.request.getParameter(START_INDEX_NEXT_PAGE_PARAMETER);+ if (startIndex == null)return DEFAULT_START_INDEX;int retval = -1;try {- retval = new Integer(this.request- .getParameter(START_INDEX_NEXT_PAGE_PARAMETER)).intValue();+ retval = new Integer(startIndex).intValue();} catch (Exception e) {- LOG.warn("Start-index could not be parsed - " + e.getMessage(), e);+ LOG.warn("Start-index could not be parsed - not an integer - " + e.getMessage());}return retval < 0 ? DEFAULT_START_INDEX : retval;}/**- * The selfid is <i>href</i> pointing to the requested resource+ * The self id is the feeds <i>href</i> pointing to the requested resource** @return - the self id*/@@ -300,55 +332,59 @@ public class GDataRequest {return builder.toString();}-+/**- * The <i>href</i> id of the next page of the requested resource.+ * The previous id is the feeds <i>href</i> pointing to the previous result of the requested resource*- * @return the id of the next page+ * @return - the self id*/- public String getNextId() {+ public String getPreviousId(){++ int startIndex = getStartIndex();+ if(startIndex == DEFAULT_START_INDEX )+ return null;StringBuilder builder = new StringBuilder();builder.append(buildRequestIDString(false));- builder.append("?");-- if (builder.charAt(builder.length() - 1) != '?')- builder.append('&');- Enumeration parameters = this.request.getParameterNames();- while (parameters.hasMoreElements()) {- String element = (String) parameters.nextElement();- String values = this.request.getParameter(element);-- builder.append(element).append("=");- if (element.equals(START_INDEX_NEXT_PAGE_PARAMETER)) {- int tempVal = DEFAULT_START_INDEX;- try {- tempVal = Integer.parseInt(values);- } catch (Exception e) {- LOG.info("Can not parse StartIndex -- use defaut");- }- builder.append(tempVal + getItemsPerPage());- continue;- }-- builder.append(values);-- if (parameters.hasMoreElements())- builder.append("&");-- }- if (this.request.getParameter(ITEMS_PER_PAGE_PARAMETER) == null) {- if (builder.charAt(builder.length() - 1) != '?')- builder.append('&');- builder.append(ITEMS_PER_PAGE_PARAMETER).append("=").append(- DEFAULT_ITEMS_PER_PAGE);+ startIndex = startIndex-getItemsPerPage();+ builder.append(getPreparedQueryString(startIndex<1?DEFAULT_START_INDEX:startIndex));+ return builder.toString();+ }++++ private String getPreparedQueryString(int startIndex){+ String queryString = this.request.getQueryString();+ String startIndexValue = this.request.getParameter(START_INDEX_NEXT_PAGE_PARAMETER);+ String maxResultsValue = this.request.getParameter(ITEMS_PER_PAGE_PARAMETER);++ StringBuilder builder = new StringBuilder("?");+ if(maxResultsValue == null){+ builder.append(ITEMS_PER_PAGE_PARAMETER).append("=").append(DEFAULT_ITEMS_PER_PAGE);+ builder.append("&");}- if (this.request.getParameter(START_INDEX_NEXT_PAGE_PARAMETER) == null) {- if (builder.charAt(builder.length() - 1) != '?')- builder.append('&');+ if(startIndexValue== null){builder.append(START_INDEX_NEXT_PAGE_PARAMETER).append("=");- builder.append(getItemsPerPage() + 1);+ builder.append(Integer.toString(startIndex));+ if(queryString!=null){+ builder.append("&");+ builder.append(queryString);+ }+ }else{+ builder.append(queryString.replaceAll("start-index=[\\d]*",START_INDEX_NEXT_PAGE_PARAMETER+"="+Integer.toString(startIndex)));}-+ return builder.toString();+ }+ /**+ * The <i>href</i> id of the next page of the requested resource.+ *+ * @return the id of the next page+ */+ public String getNextId() {+ int startIndex = getStartIndex();+ StringBuilder builder = new StringBuilder();+ builder.append(buildRequestIDString(false));+ startIndex = startIndex+getItemsPerPage();+ builder.append(getPreparedQueryString(startIndex));return builder.toString();}@@ -367,14 +403,14 @@ public class GDataRequest {/*** This will return the current query string including all parameters.- * Additionaly the <code>max-resul</code> parameter will be added if not+ * Additionally the <code>max-resul</code> parameter will be added if not* specified.* <p>* <code>max-resul</code> indicates the number of results returned to the* client. The default value is 25.* </p>*- * @return - the query string incluing all parameters+ * @return - the query string including all parameters*/public String getQueryString() {String retVal = this.request.getQueryString();@@ -453,7 +489,7 @@ public class GDataRequest {}/**- * If the reuquest is a {@link GDataRequestType#GET} request and there is no+ * If the request is a {@link GDataRequestType#GET} request and there is no* entry id specified, the requested resource is a feed.** @return - <code>true</code> if an only if the requested resource is a@@ -461,12 +497,11 @@ public class GDataRequest {*/public boolean isFeedRequested() {- return (this.type == GDataRequestType.GET && (this.entryId == null- || this.entryId.length() == 0 || (this.entryId.equals('/'))));+ return this.isFeedRequest ;}/**- * * If the reuquest is a {@link GDataRequestType#GET} request and there is+ * * If the request is a {@link GDataRequestType#GET} request and there is* an entry id specified, the requested resource is an entry.** @return - <code>true</code> if an only if the requested resource is an@@ -475,6 +510,12 @@ public class GDataRequest {public boolean isEntryRequested() {return !this.isFeedRequested();}+ /**+ * @return - <code>true</code> if an only if the user request is a search request, otherwise <code>false</code>+ */+ public boolean isSearchRequested(){+ return this.isSearchRequest;+ }/*** @return the configuration for this request@@ -505,7 +546,7 @@ public class GDataRequest {/*** @return - Returns an array containing all of the Cookie objects the- * client sent with underlaying HttpServletRequest.+ * client sent with underlying HttpServletRequest.*/public Cookie[] getCookies() {return this.request.getCookies();@@ -513,7 +554,7 @@ public class GDataRequest {/*** @return - the cookie set instead of the authentication token or- * <code>null</code> if not auth cookie is set+ * <code>null</code> if no auth cookie is set*/public Cookie getAuthCookie() {Cookie[] cookies = this.request.getCookies();@@ -535,10 +576,16 @@ public class GDataRequest {}/**- * @return - the underlaying HttpServletRequest+ * @return - the underlying HttpServletRequest*/public HttpServletRequest getHttpServletRequest() {return this.request;}++ protected String getTranslatedQuery(){+ return this.translatedSearchQuery;+ }++}diff --git a/contrib/gdata-server/src/java/org/apache/lucene/gdata/server/GDataRequestException.java b/contrib/gdata-server/src/java/org/apache/lucene/gdata/server/GDataRequestException.javaindex f89eaed931d..8f783f3f8c0 100644--- a/contrib/gdata-server/src/java/org/apache/lucene/gdata/server/GDataRequestException.java+++ b/contrib/gdata-server/src/java/org/apache/lucene/gdata/server/GDataRequestException.java@@ -17,51 +17,64 @@package org.apache.lucene.gdata.server;/**- * This exception wraps all exceptions occure inside the {@link org.apache.lucene.gdata.server.GDataRequest}+ * This exception wraps all exceptions occur inside the {@link org.apache.lucene.gdata.server.GDataRequest}* @author Simon Willnauer**/public class GDataRequestException extends Exception {-+ private final int errorCode;/*** Serial version ID. -> Implements Serializable*/private static final long serialVersionUID = -4440777051466950723L;/**- * Constructs a new GDataException- */- public GDataRequestException() {- super();-- }-- /**- * Constructs a new GDataException with a given message string- * @param arg0 - the excpetion message- */- public GDataRequestException(String arg0) {- super(arg0);-- }-- /**- * Constructs a new GDataException with a given message string and cause- * @param arg0 - the exception message- * @param arg1 - the exception who caused this exception- */- public GDataRequestException(String arg0, Throwable arg1) {- super(arg0, arg1);-- }-- /**- * Constructs a new GDataException with a given cause- * @param arg0 - exception cause- */- public GDataRequestException(Throwable arg0) {- super(arg0);-- }-+ /**+ * Constructs a new GDataRequestException+ * @param errorCode - gdata request error code+ */+ public GDataRequestException(int errorCode) {+ super();+ this.errorCode = errorCode;++ }++ /**+ * Constructs a new GDataRequestException+ * @param arg0 - the exception message+ * @param errorCode - gdata request error code+ */+ public GDataRequestException(String arg0,int errorCode) {+ super(arg0);+ this.errorCode = errorCode;+ }++ /**+ * Constructs a new GDataRequestException+ * @param arg0 - the exception message+ * @param arg1 - the exception cause+ * @param errorCode - gdata request error code+ */+ public GDataRequestException(String arg0, Throwable arg1,int errorCode) {+ super(arg0, arg1);+ this.errorCode = errorCode;++ }++ /**+ * Constructs a new GDataRequestException+ * @param arg0 - the exception cause+ * @param errorCode - gdata request error code+ */+ public GDataRequestException(Throwable arg0,int errorCode) {+ super(arg0);+ this.errorCode = errorCode;+ }++ /**+ * @return Returns the errorCode.+ */+ public int getErrorCode() {+ return this.errorCode;+ }}diff --git a/contrib/gdata-server/src/java/org/apache/lucene/gdata/server/GDataResponse.java b/contrib/gdata-server/src/java/org/apache/lucene/gdata/server/GDataResponse.javaindex 073822e783e..8d6c422baf7 100644--- a/contrib/gdata-server/src/java/org/apache/lucene/gdata/server/GDataResponse.java+++ b/contrib/gdata-server/src/java/org/apache/lucene/gdata/server/GDataResponse.java@@ -35,18 +35,18 @@ import com.google.gdata.util.common.xml.XmlWriter;import com.google.gdata.util.common.xml.XmlWriter.Namespace;/**- * The FeedRequest Class wraps the curren HttpServletResponse. Any action on the+ * The FeedRequest Class wraps the current HttpServletResponse. Any action on the* HttpServletRequest will be executed via this class. This represents an* abstraction on the plain {@link HttpServletResponse}. Any action which has- * to be performed on the underlaying {@link HttpServletResponse} will be+ * to be performed on the underlying {@link HttpServletResponse} will be* executed within this class.* <p>- * The GData basicly writes two different kinds ouf reponse to the output+ * The GData basically writes two different kinds of response to the output* stream.* <ol>- * <li>update, delete or insert requests will respond with a statuscode and if+ * <li>update, delete or insert requests will respond with a status code and if* successful the feed entry modified or created</li>- * <li>get requests will respond with a statuscode and if successful the+ * <li>get requests will respond with a status code and if successful the* requested feed</li>* </ol>*@@ -70,6 +70,40 @@ import com.google.gdata.util.common.xml.XmlWriter.Namespace;**/public class GDataResponse {+ /**+ * Response code bad request+ */+ public static final int BAD_REQUEST = HttpServletResponse.SC_BAD_REQUEST;+ /**+ * Response code version conflict+ */+ public static final int CONFLICT = HttpServletResponse.SC_CONFLICT;+ /**+ * Response code forbidden access+ */+ public static final int FORBIDDEN = HttpServletResponse.SC_FORBIDDEN;+ /**+ * Response code internal server error+ */+ public static final int SERVER_ERROR = HttpServletResponse.SC_INTERNAL_SERVER_ERROR;+ /**+ * Response code not found+ */+ public static final int NOT_FOUND = HttpServletResponse.SC_NOT_FOUND;+ /**+ * Response code not modified since+ */+ public static final int NOT_MODIFIED = HttpServletResponse.SC_NOT_MODIFIED;+ /**+ * Response code created+ */+ public static final int CREATED = HttpServletResponse.SC_CREATED;+ /**+ * Response code unauthorized access+ */+ public static final int UNAUTHORIZED = HttpServletResponse.SC_UNAUTHORIZED;++private static final Log LOG = LogFactory.getLog(GDataResponse.class);private int error;@@ -96,7 +130,7 @@ public class GDataResponse {* Creates a new GDataResponse** @param response -- * The underlaying {@link HttpServletResponse}+ * The underlying {@link HttpServletResponse}*/public GDataResponse(HttpServletResponse response) {if (response == null)@@ -117,7 +151,7 @@ public class GDataResponse {}/**- * Sets the status of the underlaying response+ * Sets the status of the underlying response** @see HttpServletResponse* @param responseCode -@@ -131,7 +165,7 @@ public class GDataResponse {* This method sends the specified error to the user if set** @throws IOException -- * if an I/O Exception occures+ * if an I/O Exception occurs*/public void sendError() throws IOException {if (this.isError)@@ -142,7 +176,7 @@ public class GDataResponse {/*** @return - the {@link HttpServletResponse} writer* @throws IOException -- * If an I/O exception occures+ * If an I/O exception occurs*/public Writer getWriter() throws IOException {return this.response.getWriter();@@ -150,14 +184,14 @@ public class GDataResponse {/*** Sends a response for a get e.g. query request. This method must not- * invoked in a case of an error performing the requeste action.+ * invoked in a case of an error performing the requested action.** @param feed -* the feed to respond to the client* @param profile -- * the extension profil for the feed to write+ * the extension profile for the feed to write* @throws IOException -- * if an I/O exception accures, often caused by an already+ * if an I/O exception occurs, often caused by an already* closed Writer or OutputStream**/@@ -167,7 +201,7 @@ public class GDataResponse {throw new IllegalArgumentException("feed must not be null");if (profile == null)throw new IllegalArgumentException(- "extension profil must not be null");+ "extension profile must not be null");DateTime time = feed.getUpdated();if (time != null)setLastModifiedHeader(time.getValue());@@ -186,7 +220,7 @@ public class GDataResponse {/**** Sends a response for an update, insert or delete request. This method- * must not invoked in a case of an error performing the requeste action. If+ * must not invoked in a case of an error performing the requested action. If* the specified response format is ATOM the default namespace will be set* to ATOM.*@@ -195,7 +229,7 @@ public class GDataResponse {* @param profile -* the entries extension profile* @throws IOException -- * if an I/O exception accures, often caused by an already+ * if an I/O exception occurs, often caused by an already* closed Writer or OutputStream*/public void sendResponse(BaseEntry entry, ExtensionProfile profile)@@ -204,7 +238,7 @@ public class GDataResponse {throw new IllegalArgumentException("entry must not be null");if (profile == null)throw new IllegalArgumentException(- "extension profil must not be null");+ "extension profile must not be null");DateTime time = entry.getUpdated();if (time != null)setLastModifiedHeader(time.getValue());diff --git a/contrib/gdata-server/src/java/org/apache/lucene/gdata/server/GDataSearchService.java b/contrib/gdata-server/src/java/org/apache/lucene/gdata/server/GDataSearchService.javanew file mode 100755index 00000000000..d3c60f8f7a8--- /dev/null+++ b/contrib/gdata-server/src/java/org/apache/lucene/gdata/server/GDataSearchService.java@@ -0,0 +1,108 @@+/**+ * Copyright 2004 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.+ */++package org.apache.lucene.gdata.server;++import java.io.IOException;+import java.util.List;++import org.apache.commons.logging.Log;+import org.apache.commons.logging.LogFactory;+import org.apache.lucene.gdata.data.ServerBaseEntry;+import org.apache.lucene.gdata.data.ServerBaseFeed;+import org.apache.lucene.gdata.search.GDataSearcher;+import org.apache.lucene.gdata.search.SearchComponent;+import org.apache.lucene.gdata.search.query.GDataQueryParser;+import org.apache.lucene.gdata.server.registry.ComponentType;+import org.apache.lucene.gdata.server.registry.GDataServerRegistry;+import org.apache.lucene.gdata.server.registry.ProvidedService;+import org.apache.lucene.gdata.storage.StorageException;+import org.apache.lucene.queryParser.ParseException;+import org.apache.lucene.queryParser.QueryParser;+import org.apache.lucene.search.Query;++import com.google.gdata.data.BaseEntry;+import com.google.gdata.data.BaseFeed;++/**+ * @author Simon Willnauer+ *+ */+public class GDataSearchService extends GDataService {+ private static final Log LOG = LogFactory.getLog(GDataSearchService.class);+ private static SearchComponent SEARCHCOMPONENT;+ private GDataSearcher<String> searcher;+ protected GDataSearchService() throws ServiceException {+ if(SEARCHCOMPONENT == null)+ SEARCHCOMPONENT = GDataServerRegistry.getRegistry().lookup(SearchComponent.class,ComponentType.SEARCHCONTROLLER);+++ }++ /**+ * @see org.apache.lucene.gdata.server.GDataService#getFeed(org.apache.lucene.gdata.server.GDataRequest, org.apache.lucene.gdata.server.GDataResponse)+ */+ @Override+ public BaseFeed getFeed(GDataRequest request, GDataResponse response) throws ServiceException {+ String translatedQuery = request.getTranslatedQuery();+ ProvidedService service = request.getConfigurator();++ QueryParser parser = new GDataQueryParser(service.getIndexSchema());+ Query query;+ try {+ query = parser.parse(translatedQuery);++ } catch (ParseException e1) {+ throw new ServiceException("Search Failed -- Can not parse query",e1,GDataResponse.BAD_REQUEST);+ }+ if(LOG.isInfoEnabled())+ LOG.info("Fire search for user query query: "+query.toString());+ this.searcher = SEARCHCOMPONENT.getServiceSearcher(service);+ List<String> result;+ try {+ result = this.searcher.search(query,request.getItemsPerPage(),request.getStartIndex(),request.getFeedId());+ } catch (IOException e) {+ throw new ServiceException("Search Failed -- Searcher throws IOException",e,GDataResponse.SERVER_ERROR);++ }+ if(LOG.isInfoEnabled())+ LOG.info("Fetching results for user query result size: "+result.size());+ ServerBaseFeed requestFeed = new ServerBaseFeed();+ requestFeed.setServiceConfig(service);+ requestFeed.setStartIndex(0);+ requestFeed.setItemsPerPage(0);+ requestFeed.setId(request.getFeedId());++ BaseFeed feed = this.storage.getFeed(requestFeed);+ for (String entryId : result) {+ ServerBaseEntry requestEntry = new ServerBaseEntry();+ requestEntry.setId(entryId);+ requestEntry.setServiceConfig(service);+ try{+ BaseEntry entry = this.storage.getEntry(requestEntry);+ feed.getEntries().add(entry);+ }catch (StorageException e) {++ LOG.error("StorageException caught while fetching query results -- skip entry -- "+e.getMessage(),e);+ }+ }+ dynamicElementFeedStragey(feed,request);+ return feed;+ }++++}diff --git a/contrib/gdata-server/src/java/org/apache/lucene/gdata/server/GDataService.java b/contrib/gdata-server/src/java/org/apache/lucene/gdata/server/GDataService.javaindex edbfd0665a4..a7ab52db95e 100644--- a/contrib/gdata-server/src/java/org/apache/lucene/gdata/server/GDataService.java+++ b/contrib/gdata-server/src/java/org/apache/lucene/gdata/server/GDataService.java@@ -19,13 +19,12 @@ import java.io.IOException;import java.util.Date;import java.util.List;-import javax.servlet.http.HttpServletResponse;-import org.apache.commons.logging.Log;import org.apache.commons.logging.LogFactory;import org.apache.lucene.gdata.data.ServerBaseEntry;import org.apache.lucene.gdata.data.ServerBaseFeed;import org.apache.lucene.gdata.server.registry.ComponentType;+import org.apache.lucene.gdata.server.registry.EntryEventMediator;import org.apache.lucene.gdata.server.registry.GDataServerRegistry;import org.apache.lucene.gdata.storage.ModificationConflictException;import org.apache.lucene.gdata.storage.ResourceNotFoundException;@@ -48,7 +47,7 @@ import com.google.gdata.util.ParseException;**/public class GDataService implements Service {- private static final Log LOGGER = LogFactory.getLog(GDataService.class);+ private static final Log LOG = LogFactory.getLog(GDataService.class);protected Storage storage;@@ -61,6 +60,8 @@ public class GDataService implements Service {private static final String generatorURI = "http://lucene.apache.org";private static final String XMLMIME = "application/atom+xml";++ private final EntryEventMediator entryEventMediator;static {generator = new Generator();generator.setName(generatorName);@@ -77,14 +78,14 @@ public class GDataService implements Service {throw new StorageException("StorageController is not registered");this.storage = controller.getStorage();-+ this.entryEventMediator = GDataServerRegistry.getRegistry().getEntryEventMediator();} catch (StorageException e) {- LOGGER+ LOG.fatal("Can't get Storage Instance -- can't serve any requests",e);ServiceException ex = new ServiceException(- "Can't get Storage instance" + e.getMessage(), e);+ "Can't get Storage instance" + e.getMessage(), e,GDataResponse.SERVER_ERROR);ex.setStackTrace(e.getStackTrace());throw ex;}@@ -98,8 +99,8 @@ public class GDataService implements Service {public BaseEntry createEntry(GDataRequest request, GDataResponse response)throws ServiceException {- if (LOGGER.isInfoEnabled())- LOGGER.info("create Entry for feedId: " + request.getFeedId());+ if (LOG.isInfoEnabled())+ LOG.info("create Entry for feedId: " + request.getFeedId());ServerBaseEntry entry = buildEntry(request, response);entry.setFeedId(request.getFeedId());@@ -108,15 +109,17 @@ public class GDataService implements Service {tempEntry.setPublished(getCurrentDateTime());tempEntry.setUpdated(getCurrentDateTime());BaseEntry retVal = null;+ removeDynamicElements(entry.getEntry());try {retVal = this.storage.storeEntry(entry);} catch (Exception e) {- response.setError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);+ServiceException ex = new ServiceException("Could not store entry",- e);+ e,GDataResponse.SERVER_ERROR);ex.setStackTrace(e.getStackTrace());throw ex;}+ this.entryEventMediator.entryAdded(entry);return retVal;}@@ -135,28 +138,31 @@ public class GDataService implements Service {setVersionId(entry,request,response);if (entry.getId() == null)throw new ServiceException(- "entry id is null -- can not delete null entry");+ "entry id is null -- can not delete null entry",GDataResponse.SERVER_ERROR);try {this.storage.deleteEntry(entry);+} catch (ResourceNotFoundException e) {- response.setError(HttpServletResponse.SC_BAD_REQUEST);+ServiceException ex = new ServiceException(- "Could not delete entry", e);+ "Could not delete entry", e,GDataResponse.BAD_REQUEST);ex.setStackTrace(e.getStackTrace());throw ex;}catch (ModificationConflictException e) {- response.setError(HttpServletResponse.SC_CONFLICT);+ServiceException ex = new ServiceException(- "Could not delete entry - version confilict", e);+ "Could not delete entry - version conflict",e, GDataResponse.CONFLICT);ex.setStackTrace(e.getStackTrace());throw ex;}catch (StorageException e) {- response.setError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);+ServiceException ex = new ServiceException(- "Could not delete entry", e);+ "Could not delete entry", e,GDataResponse.SERVER_ERROR);ex.setStackTrace(e.getStackTrace());throw ex;}+ this.entryEventMediator.entryDeleted(entry);+ //TODO change ret valuereturn null;}@@ -172,51 +178,50 @@ public class GDataService implements Service {entry.setFeedId(request.getFeedId());setVersionId(entry,request,response);entry.setServiceConfig(request.getConfigurator());- if (LOGGER.isInfoEnabled())- LOGGER.info("update Entry" + entry.getId() + " for feedId: "+ if (LOG.isInfoEnabled())+ LOG.info("update Entry" + entry.getId() + " for feedId: "+ request.getFeedId());if (entry.getId() == null) {- response.setError(HttpServletResponse.SC_BAD_REQUEST);- throw new ServiceException("Entry id is null can not update entry");+ throw new ServiceException("Entry id is null can not update entry",GDataResponse.BAD_REQUEST);}if (!entry.getId().equals(request.getEntryId())) {- if (LOGGER.isInfoEnabled())- LOGGER+ if (LOG.isInfoEnabled())+ LOG.info("Entry id in the entry xml does not match the requested resource -- XML-ID:"+ entry.getId()+ "; Requested resource: "+ request.getEntryId());- response.setError(HttpServletResponse.SC_BAD_REQUEST);+throw new ServiceException(- "Entry id in the entry xml does not match the requested resource");+ "Entry id in the entry xml does not match the requested resource",GDataResponse.BAD_REQUEST);}BaseEntry tempEntry = entry.getEntry();tempEntry.setUpdated(getCurrentDateTime());- Link selfLink = entry.getSelfLink();- if(selfLink != null)- entry.getLinks().remove(selfLink);+ removeDynamicElements(entry.getEntry());+BaseEntry retVal = null;+try {retVal = this.storage.updateEntry(entry);} catch (ResourceNotFoundException e) {- response.setError(HttpServletResponse.SC_BAD_REQUEST);+ServiceException ex = new ServiceException(- "Could not update entry", e);+ "Could not update entry", e,GDataResponse.BAD_REQUEST);ex.setStackTrace(e.getStackTrace());throw ex;}catch (ModificationConflictException e) {- response.setError(HttpServletResponse.SC_CONFLICT);ServiceException ex = new ServiceException(- "Could not update entry - version confilict", e);+ "Could not update entry - version conflict", e,GDataResponse.CONFLICT);ex.setStackTrace(e.getStackTrace());throw ex;}catch (StorageException e) {- response.setError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);+ServiceException ex = new ServiceException(- "Could not update entry", e);+ "Could not update entry", e,GDataResponse.SERVER_ERROR);ex.setStackTrace(e.getStackTrace());throw ex;}+ this.entryEventMediator.entryUpdated(entry);return retVal;}@@ -234,17 +239,19 @@ public class GDataService implements Service {feed.setItemsPerPage(request.getItemsPerPage());feed.setServiceConfig(request.getConfigurator());try {+ /*+ * the strategy executes either a search or a direct access.+ */BaseFeed retVal = this.storage.getFeed(feed);dynamicElementFeedStragey(retVal, request);return retVal;/*- * resouce not found will be detected in Gdata request.- * the request queries the storage for the feed to get the serivce for the feed+ * Resource not found will be detected in Gdata request.+ * the request queries the storage for the feed to get the service for the feed*/} catch (StorageException e) {- response.setError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);- ServiceException ex = new ServiceException("Could not get feed", e);+ ServiceException ex = new ServiceException("Could not get feed", e,GDataResponse.NOT_FOUND);ex.setStackTrace(e.getStackTrace());throw ex;}@@ -267,15 +274,13 @@ public class GDataService implements Service {return entry;} catch (ParseException e) {- response.setError(HttpServletResponse.SC_BAD_REQUEST);ServiceException ex = new ServiceException(- "Could not parse entry from incoming request", e);+ "Could not parse entry from incoming request", e, GDataResponse.BAD_REQUEST);ex.setStackTrace(e.getStackTrace());throw ex;} catch (IOException e) {- response.setError(HttpServletResponse.SC_BAD_REQUEST);ServiceException ex = new ServiceException(- "Could not read or open input stream", e);+ "Could not read or open input stream", e, GDataResponse.BAD_REQUEST);ex.setStackTrace(e.getStackTrace());throw ex;}@@ -298,8 +303,7 @@ public class GDataService implements Service {if(entry.getId() == null){- response.setError(HttpServletResponse.SC_BAD_REQUEST);- throw new ServiceException("entry is null can't get entry");+ throw new ServiceException("entry is null can't get entry", GDataResponse.BAD_REQUEST);}BaseEntry retVal = null;@@ -307,13 +311,12 @@ public class GDataService implements Service {dynamicElementEntryStragey(retVal, request);return retVal;} catch (ResourceNotFoundException e) {- response.setError(HttpServletResponse.SC_BAD_REQUEST);ServiceException ex = new ServiceException(- "Could not get entry", e);+ "Could not get entry", e, GDataResponse.BAD_REQUEST);ex.setStackTrace(e.getStackTrace());throw ex;} catch (StorageException e) {- ServiceException ex = new ServiceException("Could not get feed", e);+ ServiceException ex = new ServiceException("Could not get entry", e, GDataResponse.SERVER_ERROR);ex.setStackTrace(e.getStackTrace());throw ex;}@@ -331,7 +334,7 @@ public class GDataService implements Service {* adds all dynamic element to the feed entries*/@SuppressWarnings("unchecked")- private void dynamicElementFeedStragey(final BaseFeed feed,+ protected void dynamicElementFeedStragey(final BaseFeed feed,final GDataRequest request) {buildDynamicFeedElements(request, feed);List<BaseEntry> entryList = feed.getEntries();@@ -372,6 +375,9 @@ public class GDataService implements Service {buildLink(Link.Rel.SELF, Link.Type.ATOM, request.getSelfId()));links.add(buildLink(Link.Rel.NEXT, XMLMIME, request.getNextId()));+ String prevLink = request.getPreviousId();+ if(prevLink != null)+ links.add(buildLink(Link.Rel.PREVIOUS,XMLMIME,prevLink));}@@ -392,7 +398,7 @@ public class GDataService implements Service {} catch (StorageException e) {ServiceException ex = new ServiceException(- "Could not get Last update for feed -- "+feedId, e);+ "Could not get Last update for feed -- "+feedId, e, GDataResponse.SERVER_ERROR);ex.setStackTrace(e.getStackTrace());throw ex;}@@ -405,12 +411,9 @@ public class GDataService implements Service {public Date getEntryLastModified(final String entryId,final String feedId) throws ServiceException {try {return new Date(this.storage.getEntryLastModified(entryId, feedId));---} catch (StorageException e) {ServiceException ex = new ServiceException(- "Could not get Last update for entry -- "+entryId, e);+ "Could not get Last update for entry -- "+entryId, e, GDataResponse.SERVER_ERROR);ex.setStackTrace(e.getStackTrace());throw ex;}@@ -421,9 +424,8 @@ public class GDataService implements Service {entry.setVersion(Integer.parseInt(request.getEntryVersion()));return entry;}catch (Exception e) {- LOGGER.error("Can not parse entry version -- version is not an integer -- versionid: "+request.getEntryVersion(),e);- response.setError(HttpServletResponse.SC_BAD_REQUEST);- throw new ServiceException("Can not parse entry version -- version is not an integer -- versionid: "+request.getEntryVersion(),e);+ LOG.error("Can not parse entry version -- version is not an integer -- versionid: "+request.getEntryVersion(),e);+ throw new ServiceException("Can not parse entry version -- version is not an integer -- versionid: "+request.getEntryVersion(),e, GDataResponse.BAD_REQUEST);}}@@ -435,4 +437,13 @@ public class GDataService implements Service {protected DateTime getCurrentDateTime(){return new DateTime(System.currentTimeMillis(),0);}++ private void removeDynamicElements(BaseEntry entry){+ Link selfLink = entry.getSelfLink();+ if(selfLink != null)+ entry.getLinks().remove(selfLink);+ Link editLink = entry.getEditLink();+ if(editLink != null)+ entry.getLinks().remove(editLink);+ }}diff --git a/contrib/gdata-server/src/java/org/apache/lucene/gdata/server/ServiceException.java b/contrib/gdata-server/src/java/org/apache/lucene/gdata/server/ServiceException.javaindex c7acbe40a0b..9643e2bca60 100644--- a/contrib/gdata-server/src/java/org/apache/lucene/gdata/server/ServiceException.java+++ b/contrib/gdata-server/src/java/org/apache/lucene/gdata/server/ServiceException.java@@ -16,16 +16,18 @@package org.apache.lucene.gdata.server;+/*** The ServiceException is used to encapsulate all {@link java.lang.Exception}- * throw by underlaying layers of the+ * throw by underlying layers of the* {@link org.apache.lucene.gdata.server.Service} layer.** @author Simon Willnauer**/public class ServiceException extends Exception {-++ private int errorCode;/****/@@ -33,38 +35,51 @@ public class ServiceException extends Exception {/*** Constructs a new ServiceException+ * @param errorCode - gdata request error code*/- public ServiceException() {+ public ServiceException(int errorCode) {super();+ this.errorCode = errorCode;}/*** Constructs a new ServiceException* @param arg0 - the exception message+ * @param errorCode - gdata request error code*/- public ServiceException(String arg0) {+ public ServiceException(String arg0,int errorCode) {super(arg0);-+ this.errorCode = errorCode;}/*** Constructs a new ServiceException- * @param arg0 - the exceptin message+ * @param arg0 - the exception message* @param arg1 - the exception cause+ * @param errorCode - gdata request error code*/- public ServiceException(String arg0, Throwable arg1) {+ public ServiceException(String arg0, Throwable arg1,int errorCode) {super(arg0, arg1);-+ this.errorCode = errorCode;+}/*** Constructs a new ServiceException* @param arg0 - the exception cause+ * @param errorCode - gdata request error code*/- public ServiceException(Throwable arg0) {+ public ServiceException(Throwable arg0,int errorCode) {super(arg0);+ this.errorCode = errorCode;+ }+ /**+ * @return Returns the errorCode.+ */+ public int getErrorCode() {+ return this.errorCode;}}diff --git a/contrib/gdata-server/src/java/org/apache/lucene/gdata/server/ServiceFactory.java b/contrib/gdata-server/src/java/org/apache/lucene/gdata/server/ServiceFactory.javaindex 08c2b2ceab4..94b15d70419 100644--- a/contrib/gdata-server/src/java/org/apache/lucene/gdata/server/ServiceFactory.java+++ b/contrib/gdata-server/src/java/org/apache/lucene/gdata/server/ServiceFactory.java@@ -51,11 +51,14 @@ public class ServiceFactory implements ServerComponent {/*** Creates a {@link Service} instance.+ * @param request - the request for this service** @return a Service instance*/- public Service getService() {+ public Service getService(GDataRequest request) {try{+ if(request.isSearchRequested())+ return new GDataSearchService();return new GDataService();}catch (Exception e) {//diff --git a/contrib/gdata-server/src/java/org/apache/lucene/gdata/server/administration/AccountBuilder.java b/contrib/gdata-server/src/java/org/apache/lucene/gdata/server/administration/AccountBuilder.javaindex f313b518cc0..af823f2a5dc 100644--- a/contrib/gdata-server/src/java/org/apache/lucene/gdata/server/administration/AccountBuilder.java+++ b/contrib/gdata-server/src/java/org/apache/lucene/gdata/server/administration/AccountBuilder.java@@ -17,14 +17,18 @@ package org.apache.lucene.gdata.server.administration;import java.io.IOException;import java.io.Reader;+import java.net.URL;++import org.apache.commons.digester.Digester;import org.apache.lucene.gdata.data.GDataAccount;import org.apache.lucene.gdata.utils.SimpleSaxErrorHandler;+import org.apache.xerces.parsers.SAXParser;import org.xml.sax.SAXException;/**- * Helperclass to create {@link org.apache.lucene.gdata.data.GDataAccount}+ * Helper class to create {@link org.apache.lucene.gdata.data.GDataAccount}* instances from a xml stream provided via a {@link Reader} instance.** @author Simon Willnauer@@ -36,16 +40,27 @@ public class AccountBuilder {* Reads the xml from the provided reader and binds the values to the* @param reader - the reader to read the xml from* @return - the GDataAccount- * @throws IOException - if an IOException occures+ * @throws IOException - if an IOException occurs* @throws SAXException - if the xml can not be parsed by the sax reader*/public static GDataAccount buildAccount(final Reader reader) throws IOException,SAXException {if (reader == null)throw new IllegalArgumentException("Reader must not be null");- String schemaFile = AccountBuilder.class.getResource("/gdata-account.xsd").getFile();+ URL resource = AccountBuilder.class.getResource("/gdata-account.xsd");+ if(resource == null)+ throw new RuntimeException("can not find xml schema file 'gdata-account.xsd' -- file must be present on the classpath");+ String schemaFile = resource.getFile();GDataAccount account = null;- Digester digester = new Digester();+ /*+ * Force using apache xerces parser for digester+ */+ SAXParser parser = new SAXParser();+ parser.setFeature("http://apache.org/xml/features/validation/schema-full-checking",true);+ parser.setFeature("http://apache.org/xml/features/validation/schema",true);+ parser.setFeature("http://xml.org/sax/features/validation",true);+ parser.setProperty("http://apache.org/xml/properties/schema/external-noNamespaceSchemaLocation",schemaFile);+ Digester digester = new Digester(parser);digester.setValidating(true);digester.setErrorHandler(new SimpleSaxErrorHandler());digester.setSchema(schemaFile);@@ -61,7 +76,6 @@ public class AccountBuilder {"authorLink");account = (GDataAccount) digester.parse(reader);-return account;}diff --git a/contrib/gdata-server/src/java/org/apache/lucene/gdata/server/administration/GDataAdminService.java b/contrib/gdata-server/src/java/org/apache/lucene/gdata/server/administration/GDataAdminService.javaindex 3192d4a66fa..684084cf9ae 100644--- a/contrib/gdata-server/src/java/org/apache/lucene/gdata/server/administration/GDataAdminService.java+++ b/contrib/gdata-server/src/java/org/apache/lucene/gdata/server/administration/GDataAdminService.java@@ -19,6 +19,7 @@ import org.apache.commons.logging.Log;import org.apache.commons.logging.LogFactory;import org.apache.lucene.gdata.data.GDataAccount;import org.apache.lucene.gdata.data.ServerBaseFeed;+import org.apache.lucene.gdata.server.GDataResponse;import org.apache.lucene.gdata.server.GDataService;import org.apache.lucene.gdata.server.ServiceException;import org.apache.lucene.gdata.storage.StorageException;@@ -47,13 +48,13 @@ public class GDataAdminService extends GDataService implements AdminService {*/public void createFeed(final ServerBaseFeed feed,final GDataAccount account) throws ServiceException {if(feed == null)- throw new ServiceException("Can not create feed -- feed is null");+ throw new ServiceException("Can not create feed -- feed is null", GDataResponse.BAD_REQUEST);if(account == null)- throw new ServiceException("Can not create feed -- account is null");+ throw new ServiceException("Can not create feed -- account is null", GDataResponse.UNAUTHORIZED);if(feed.getId() == null)- throw new ServiceException("Feed ID is null can not create feed");+ throw new ServiceException("Feed ID is null can not create feed", GDataResponse.BAD_REQUEST);if(account.getName() == null)- throw new ServiceException("Account name is null -- can't create feed");+ throw new ServiceException("Account name is null -- can't create feed", GDataResponse.UNAUTHORIZED);try {feed.setUpdated(getCurrentDateTime());feed.setAccount(account);@@ -61,7 +62,7 @@ public class GDataAdminService extends GDataService implements AdminService {} catch (StorageException e) {if(LOG.isInfoEnabled())LOG.info("Can not save feed -- "+e.getMessage(),e);- throw new ServiceException("Can not save feed",e);+ throw new ServiceException("Can not save feed",e, GDataResponse.SERVER_ERROR);}}@@ -73,13 +74,13 @@ public class GDataAdminService extends GDataService implements AdminService {*/public void updateFeed(ServerBaseFeed feed, GDataAccount account) throws ServiceException {if(feed == null)- throw new ServiceException("Can not update null feed");+ throw new ServiceException("Can not update null feed", GDataResponse.BAD_REQUEST);if(account == null)- throw new ServiceException("Can not update feed -- account is null");+ throw new ServiceException("Can not update feed -- account is null", GDataResponse.UNAUTHORIZED);if(feed.getId() == null)- throw new ServiceException("Feed ID is null can not update feed");+ throw new ServiceException("Feed ID is null can not update feed", GDataResponse.BAD_REQUEST);if(account.getName() == null)- throw new ServiceException("Account name is null -- can't update feed");+ throw new ServiceException("Account name is null -- can't update feed", GDataResponse.UNAUTHORIZED);try {feed.setAccount(account);feed.setUpdated(getCurrentDateTime());@@ -87,7 +88,7 @@ public class GDataAdminService extends GDataService implements AdminService {} catch (StorageException e) {if(LOG.isInfoEnabled())LOG.info("Can not update feed -- "+e.getMessage(),e);- throw new ServiceException("Can not update feed",e);+ throw new ServiceException("Can not update feed",e, GDataResponse.SERVER_ERROR);}}@@ -99,15 +100,15 @@ public class GDataAdminService extends GDataService implements AdminService {*/public void deleteFeed(ServerBaseFeed feed) throws ServiceException {if(feed == null)- throw new ServiceException("Can not delete null feed");+ throw new ServiceException("Can not delete null feed", GDataResponse.BAD_REQUEST);if(feed.getId() == null)- throw new ServiceException("Feed ID is null can not delete feed");+ throw new ServiceException("Feed ID is null can not delete feed", GDataResponse.BAD_REQUEST);try {this.storage.deleteFeed(feed.getId());} catch (StorageException e) {if(LOG.isInfoEnabled())LOG.info("Can not delete feed -- "+e.getMessage(),e);- throw new ServiceException("Can not delete feed",e);+ throw new ServiceException("Can not delete feed",e, GDataResponse.SERVER_ERROR);}}@@ -117,13 +118,13 @@ public class GDataAdminService extends GDataService implements AdminService {*/public void createAccount(GDataAccount account) throws ServiceException {if(account == null)- throw new ServiceException("Can not save null account");+ throw new ServiceException("Can not save null account", GDataResponse.BAD_REQUEST);try {this.storage.storeAccount(account);} catch (StorageException e) {if(LOG.isInfoEnabled())LOG.info("Can not save account -- "+e.getMessage(),e);- throw new ServiceException("Can not save account",e);+ throw new ServiceException("Can not save account",e, GDataResponse.SERVER_ERROR);}}@@ -132,13 +133,13 @@ public class GDataAdminService extends GDataService implements AdminService {*/public void deleteAccount(GDataAccount account) throws ServiceException {if(account == null)- throw new ServiceException("Can not delete null account");+ throw new ServiceException("Can not delete null account", GDataResponse.BAD_REQUEST);try {this.storage.deleteAccount(account.getName());} catch (StorageException e) {if(LOG.isInfoEnabled())LOG.info("Can not save account -- "+e.getMessage(),e);- throw new ServiceException("Can not save account",e);+ throw new ServiceException("Can not save account",e, GDataResponse.SERVER_ERROR);}}@@ -147,13 +148,13 @@ public class GDataAdminService extends GDataService implements AdminService {*/public void updateAccount(GDataAccount account) throws ServiceException {if(account == null)- throw new ServiceException("Can not update null account");+ throw new ServiceException("Can not update null account", GDataResponse.BAD_REQUEST);try {this.storage.updateAccount(account);} catch (StorageException e) {if(LOG.isInfoEnabled())LOG.info("Can not save account -- "+e.getMessage(),e);- throw new ServiceException("Can not save account",e);+ throw new ServiceException("Can not save account",e, GDataResponse.SERVER_ERROR);}}@@ -162,13 +163,13 @@ public class GDataAdminService extends GDataService implements AdminService {*/public GDataAccount getAccount(String accountName)throws ServiceException{if(accountName == null)- throw new ServiceException("Can not get null account");+ throw new ServiceException("Can not get null account", GDataResponse.BAD_REQUEST);try {return this.storage.getAccount(accountName);} catch (StorageException e) {if(LOG.isInfoEnabled())LOG.info("Can not get account -- "+e.getMessage(),e);- throw new ServiceException("Can not get account",e);+ throw new ServiceException("Can not get account",e, GDataResponse.SERVER_ERROR);}}@@ -180,7 +181,7 @@ public class GDataAdminService extends GDataService implements AdminService {*/public GDataAccount getFeedOwningAccount(String feedId) throws ServiceException {if(feedId == null)- throw new ServiceException("Can not get account - feed id must not be null");+ throw new ServiceException("Can not get account - feed id must not be null", GDataResponse.BAD_REQUEST);try {String accountName = this.storage.getAccountNameForFeedId(feedId);return this.storage.getAccount(accountName);@@ -188,7 +189,7 @@ public class GDataAdminService extends GDataService implements AdminService {} catch (StorageException e) {if(LOG.isInfoEnabled())LOG.info("Can not get account for feed Id -- "+e.getMessage(),e);- throw new ServiceException("Can not get account for the given feed id",e);+ throw new ServiceException("Can not get account for the given feed id",e, GDataResponse.SERVER_ERROR);}}diff --git a/contrib/gdata-server/src/java/org/apache/lucene/gdata/server/registry/ComponentType.java b/contrib/gdata-server/src/java/org/apache/lucene/gdata/server/registry/ComponentType.javaindex d28c4d0f28c..29d36988050 100644--- a/contrib/gdata-server/src/java/org/apache/lucene/gdata/server/registry/ComponentType.java+++ b/contrib/gdata-server/src/java/org/apache/lucene/gdata/server/registry/ComponentType.java@@ -1,12 +1,13 @@package org.apache.lucene.gdata.server.registry;+import org.apache.lucene.gdata.search.SearchComponent;import org.apache.lucene.gdata.server.ServiceFactory;import org.apache.lucene.gdata.server.authentication.AuthenticationController;import org.apache.lucene.gdata.servlet.handler.RequestHandlerFactory;import org.apache.lucene.gdata.storage.StorageController;/**- * The enmueration {@link ComponentType} defines the GDATA-Server Components+ * The enumeration {@link ComponentType} defines the GDATA-Server Components* available via {@link org.apache.lucene.gdata.server.registry.GDataServerRegistry#lookup(Class, ComponentType)}* method.* @see org.apache.lucene.gdata.server.registry.Component@@ -30,12 +31,11 @@ public enum ComponentType {@SuperType(superType = RequestHandlerFactory.class)REQUESTHANDLERFACTORY,/**- * INDEXER TYPE- *+ * SearchComponent Type+ * @see SearchComponent*/- // TODO not available yet- @SuperType(superType = Object.class)- INDEXER,+ @SuperType(superType = SearchComponent.class)+ SEARCHCONTROLLER,/*** ServiceFactory Type*@@ -44,7 +44,7 @@ public enum ComponentType {@SuperType(superType = ServiceFactory.class)SERVICEFACTORY,/**- * Supertype for AuthenticationController implementations+ * Super type for AuthenticationController implementations* @see AuthenticationController*/@SuperType(superType = AuthenticationController.class)diff --git a/contrib/gdata-server/src/java/org/apache/lucene/gdata/server/registry/EntryEventListener.java b/contrib/gdata-server/src/java/org/apache/lucene/gdata/server/registry/EntryEventListener.javanew file mode 100755index 00000000000..bc58d631359--- /dev/null+++ b/contrib/gdata-server/src/java/org/apache/lucene/gdata/server/registry/EntryEventListener.java@@ -0,0 +1,48 @@+/**+ * Copyright 2004 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.+ */++package org.apache.lucene.gdata.server.registry;++import org.apache.lucene.gdata.data.ServerBaseEntry;++/**+ * The EntryEventListener interface should be implemented by any class needs to be informed about any changes on entries.+ * To register a class as a EntryEventListener use:+ * <p>+ * <tt>+ * GdataServerRegistry.registerEntryEventListener(EntryEventListener);+ * <tt>+ * </p>+ * @author Simon Willnauer+ *+ */+public interface EntryEventListener {+ /**+ * will be invoked on every successful update on every entry+ * @param entry the updated entry+ */+ public abstract void fireUpdateEvent(ServerBaseEntry entry);+ /**+ * will be invoked on every successful entry insert+ * @param entry+ */+ public abstract void fireInsertEvent(ServerBaseEntry entry);+ /**+ * will be invoked on every successful entry delete+ * @param entry+ */+ public abstract void fireDeleteEvent(ServerBaseEntry entry);+}diff --git a/contrib/gdata-server/src/java/org/apache/lucene/gdata/server/registry/EntryEventMediator.java b/contrib/gdata-server/src/java/org/apache/lucene/gdata/server/registry/EntryEventMediator.javanew file mode 100755index 00000000000..baf1d0262c4--- /dev/null+++ b/contrib/gdata-server/src/java/org/apache/lucene/gdata/server/registry/EntryEventMediator.java@@ -0,0 +1,89 @@+/**+ * Copyright 2004 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.+ */++package org.apache.lucene.gdata.server.registry;++import java.util.ArrayList;+import java.util.List;++import org.apache.lucene.gdata.data.ServerBaseEntry;++/**+ * This class will be informed about every successful entry event and+ * distributes all event to all registered+ * {@link org.apache.lucene.gdata.server.registry.EntryEventListener}+ *+ * @author Simon Willnauer+ *+ */+public abstract class EntryEventMediator {++ private final List<EntryEventListener> entryEventListener = new ArrayList<EntryEventListener>(+ 5);++ /**+ * @return - a entry event mediator instance+ */+ public abstract EntryEventMediator getEntryEventMediator();++ /**+ * Registers a {@link EntryEventListener}. This listner will be fired if an+ * entry update, insert or delete occures+ *+ * @param listener -+ * listener to register+ */+ public void registerEntryEventListener(final EntryEventListener listener) {+ if (listener == null || this.entryEventListener.contains(listener))+ return;+ this.entryEventListener.add(listener);+ }++ /**+ * @param entry -+ * the updated entry+ */+ public void entryUpdated(final ServerBaseEntry entry) {+ for (EntryEventListener listener : this.entryEventListener) {+ listener.fireUpdateEvent(entry);+ }+ }++ /**+ * @param entry -+ * the added entry+ */+ public void entryAdded(final ServerBaseEntry entry) {+ for (EntryEventListener listener : this.entryEventListener) {+ listener.fireInsertEvent(entry);+ }+ }++ /**+ * @param entry -+ * the deleted entry+ */+ public void entryDeleted(final ServerBaseEntry entry) {+ for (EntryEventListener listener : this.entryEventListener) {+ listener.fireDeleteEvent(entry);+ }+ }++ public boolean isListenerRegistered(final EntryEventListener listner){+ return listner!=null&&this.entryEventListener.contains(listner);+ }++}diff --git a/contrib/gdata-server/src/java/org/apache/lucene/gdata/server/registry/GDataServerRegistry.java b/contrib/gdata-server/src/java/org/apache/lucene/gdata/server/registry/GDataServerRegistry.javaindex af5bf4f95ae..78038a3e715 100644--- a/contrib/gdata-server/src/java/org/apache/lucene/gdata/server/registry/GDataServerRegistry.java+++ b/contrib/gdata-server/src/java/org/apache/lucene/gdata/server/registry/GDataServerRegistry.java@@ -25,12 +25,13 @@ import org.apache.commons.logging.Log;import org.apache.commons.logging.LogFactory;import org.apache.lucene.gdata.server.registry.configuration.ComponentConfiguration;import org.apache.lucene.gdata.server.registry.configuration.PropertyInjector;+import org.apache.lucene.gdata.utils.ReflectionUtils;/**** The GDataServerRegistry represents the registry component of the GData* Server. All provided services and server components will be registered here.- * The Gdata Server serves RSS / ATOM feeds for defined services. Each service+ * The GData Server serves RSS / ATOM feeds for defined services. Each service* provides <i>n</i> feeds of a defined subclass of* {@link com.google.gdata.data.BaseFeed}. Each feed contains <i>m</i> entries* of a defined subclass of {@link com.google.gdata.data.BaseEntry}. To@@ -42,9 +43,9 @@ import org.apache.lucene.gdata.server.registry.configuration.PropertyInjector;* </p>* <p>* The components defined in the gdata-config.xml will also be loaded and- * instanciated at startup. If a component can not be loaded or an Exception- * occures the server will not start up. To cause of the exception or error will- * be logged to the standart server output.+ * instantiated at startup. If a component can not be loaded or an Exception+ * occurs the server will not start up. To cause of the exception or error will+ * be logged to the standard server output.* </p>* <p>* The GDataServerRegistry is a Singleton@@ -54,16 +55,17 @@ import org.apache.lucene.gdata.server.registry.configuration.PropertyInjector;* @author Simon Willnauer**/-public class GDataServerRegistry {+public class GDataServerRegistry extends EntryEventMediator{private static GDataServerRegistry INSTANCE;- private static final Log LOGGER = LogFactory+ private static final Log LOG = LogFactory.getLog(GDataServerRegistry.class);private ScopeVisitable requestVisitable;private ScopeVisitable sessionVisitable;- //not available yet++ // not available yetprivate ScopeVisitable contextVisitable;private List<ScopeVisitor> visitorBuffer = new ArrayList<ScopeVisitor>(5);@@ -78,7 +80,7 @@ public class GDataServerRegistry {}/**- * @return a Sinleton registry instance+ * @return a Singleton registry instance*/public static synchronized GDataServerRegistry getRegistry() {if (INSTANCE == null)@@ -94,7 +96,7 @@ public class GDataServerRegistry {*/public void registerService(ProvidedService configurator) {if (configurator == null) {- LOGGER.warn("Feedconfigurator is null -- skip registration");+ LOG.warn("Feed configurator is null -- skip registration");return;}this.serviceTypeMap.put(configurator.getName(), configurator);@@ -112,8 +114,8 @@ public class GDataServerRegistry {Scope scope = visitor.getClass().getAnnotation(Scope.class);if (scope == null)throw new RegistryException("Visitor has not Scope");- if (LOGGER.isInfoEnabled())- LOGGER.info("Register scope visitor -- " + visitor.getClass());+ if (LOG.isInfoEnabled())+ LOG.info("Register scope visitor -- " + visitor.getClass());if (scope.scope().equals(Scope.ScopeType.REQUEST)&& this.requestVisitable != null)this.requestVisitable.accept(visitor);@@ -141,8 +143,8 @@ public class GDataServerRegistry {Scope scope = visitable.getClass().getAnnotation(Scope.class);if (scope == null)throw new RegistryException("Visitable has not Scope");- if (LOGGER.isInfoEnabled())- LOGGER.info("Register scope visitable -- " + visitable.getClass());+ if (LOG.isInfoEnabled())+ LOG.info("Register scope visitable -- " + visitable.getClass());if (scope.scope() == Scope.ScopeType.REQUEST&& this.requestVisitable == null)this.requestVisitable = visitable;@@ -176,7 +178,7 @@ public class GDataServerRegistry {public ProvidedService getProvidedService(String service) {if (service == null)throw new IllegalArgumentException(- "Service is null - must not be null to get registered feedtype");+ "Service is null - must not be null to get registered feed type");return this.serviceTypeMap.get(service);}@@ -267,7 +269,7 @@ public class GDataServerRegistry {* annotations not visible at runtime or not set, if the super* type provided by the {@link ComponentType} for the class to* register is not a super type of the class or if the- * invokation of the {@link ServerComponent#initialize()} method+ * invocation of the {@link ServerComponent#initialize()} method* throws an exception.*/@SuppressWarnings("unchecked")@@ -280,7 +282,8 @@ public class GDataServerRegistry {throw new IllegalArgumentException("component class must not be null");- if (!checkSuperType(componentClass, ServerComponent.class))+ if (!ReflectionUtils.implementsType(componentClass,+ ServerComponent.class))throw new RegistryException("can not register component. the given class does not implement ServerComponent interface -- "+ componentClass.getName());@@ -298,14 +301,14 @@ public class GDataServerRegistry {+ type.name());Class superType = type.getClass().getField(type.name()).getAnnotation(SuperType.class).superType();- if (!checkSuperType(componentClass, superType))- throw new RegistryException("Considered Supertype <"+ if (!ReflectionUtils.isTypeOf(componentClass, superType))+ throw new RegistryException("Considered super type <"+ superType.getName() + "> is not a super type of <"+ componentClass + ">");ServerComponent comp = componentClass.newInstance();if (configuration == null) {- if (LOGGER.isInfoEnabled())- LOGGER.info("no configuration for ComponentType: "+ if (LOG.isInfoEnabled())+ LOG.info("no configuration for ComponentType: "+ type.name());} elseconfigureComponent(comp, type, configuration);@@ -313,7 +316,8 @@ public class GDataServerRegistry {ComponentBean bean = new ComponentBean(comp, superType);this.componentMap.put(type, bean);- if (checkSuperType(componentClass, ScopeVisitor.class))+ if (ReflectionUtils.implementsType(componentClass,+ ScopeVisitor.class))this.registerScopeVisitor((ScopeVisitor) comp);} catch (Exception e) {e.printStackTrace();@@ -334,21 +338,6 @@ public class GDataServerRegistry {injector.injectProperties(configuration);}- private static boolean checkSuperType(Class type, Class consideredSuperType) {- if (type == null)- return false;- if (type.equals(Object.class))- return false;- if (type.equals(consideredSuperType))- return true;- Class[] interfaces = type.getInterfaces();- for (int i = 0; i < interfaces.length; i++) {- if (checkSuperType(interfaces[i], consideredSuperType))- return true;- }- return checkSuperType(type.getSuperclass(), consideredSuperType);- }-private static class ComponentBean {private final Class superType;@@ -369,4 +358,21 @@ public class GDataServerRegistry {}+ /**+ * @see org.apache.lucene.gdata.server.registry.EntryEventMediator#getEntryEventMediator()+ */+ @Override+ public EntryEventMediator getEntryEventMediator() {++ return this;+ }++ /**+ * @return - all registered services+ */+ public Collection<ProvidedService> getServices() {++ return this.serviceTypeMap.values();+ }+}diff --git a/contrib/gdata-server/src/java/org/apache/lucene/gdata/server/registry/ProvidedService.java b/contrib/gdata-server/src/java/org/apache/lucene/gdata/server/registry/ProvidedService.javaindex 069557f2146..61ab86b7381 100644--- a/contrib/gdata-server/src/java/org/apache/lucene/gdata/server/registry/ProvidedService.java+++ b/contrib/gdata-server/src/java/org/apache/lucene/gdata/server/registry/ProvidedService.java@@ -15,6 +15,8 @@*/package org.apache.lucene.gdata.server.registry;+import org.apache.lucene.gdata.search.config.IndexSchema;+import com.google.gdata.data.ExtensionProfile;/**@@ -41,7 +43,7 @@ public interface ProvidedService {public abstract Class getEntryType();/**- * @return - the servicename+ * @return - the service name*/public abstract String getName();@@ -49,5 +51,8 @@ public interface ProvidedService {* releases all dependencies and resources*/public abstract void destroy();-+ /**+ * @return the index schema configuration for this service+ */+ public abstract IndexSchema getIndexSchema();}\ No newline at end of filediff --git a/contrib/gdata-server/src/java/org/apache/lucene/gdata/server/registry/ProvidedServiceConfig.java b/contrib/gdata-server/src/java/org/apache/lucene/gdata/server/registry/ProvidedServiceConfig.javaindex cc6f18f2204..11e7ae800e0 100644--- a/contrib/gdata-server/src/java/org/apache/lucene/gdata/server/registry/ProvidedServiceConfig.java+++ b/contrib/gdata-server/src/java/org/apache/lucene/gdata/server/registry/ProvidedServiceConfig.java@@ -19,20 +19,25 @@ import java.lang.reflect.Constructor;import org.apache.commons.logging.Log;import org.apache.commons.logging.LogFactory;+import org.apache.lucene.gdata.search.config.IndexSchema;import org.apache.lucene.gdata.utils.Pool;import org.apache.lucene.gdata.utils.PoolObjectFactory;import org.apache.lucene.gdata.utils.SimpleObjectPool;+import com.google.gdata.data.BaseEntry;+import com.google.gdata.data.BaseFeed;+import com.google.gdata.data.Entry;import com.google.gdata.data.ExtensionProfile;+import com.google.gdata.data.Feed;/**- * Standart implementation of+ * Standard implementation of* {@link org.apache.lucene.gdata.server.registry.ProvidedService} to be used* inside the* {@link org.apache.lucene.gdata.server.registry.GDataServerRegistry}* <p>* ExtensionProfiles are used to generate and parse xml by the gdata api. For- * that case all methodes are synchronized. This will slow down the application+ * that case all methods are synchronized. This will slow down the application* when performing lots of xml generation concurrently. For that case the* extensionProfile for a specific service will be pooled and reused.* </p>@@ -47,13 +52,13 @@ public class ProvidedServiceConfig implements ProvidedService, ScopeVisitor {.getLog(ProvidedServiceConfig.class);private static final int DEFAULT_POOL_SIZE = 5;-+ private IndexSchema indexSchema;/*- * To ensure a extensionprofile instance will not be shared within multiple+ * To ensure a extension profile instance will not be shared within multiple* threads each thread requesting a config will have one instance for the* entire request.*/- private final ThreadLocal<ExtensionProfile> extProfThreadLocal = new ThreadLocal<ExtensionProfile>();+ protected final ThreadLocal<ExtensionProfile> extProfThreadLocal = new ThreadLocal<ExtensionProfile>();/** ExtensionProfiles are used to generate and parse xml by the gdata api.@@ -66,9 +71,9 @@ public class ProvidedServiceConfig implements ProvidedService, ScopeVisitor {private String serviceName;- private Class entryType;+ private Class<? extends BaseEntry> entryType;- private Class feedType;+ private Class<? extends BaseFeed> feedType;private ExtensionProfile extensionProfile;@@ -92,7 +97,7 @@ public class ProvidedServiceConfig implements ProvidedService, ScopeVisitor {}/**- * Default constructor to instanciate via reflection+ * Default constructor to instantiate via reflection*/public ProvidedServiceConfig() {try {@@ -126,6 +131,8 @@ public class ProvidedServiceConfig implements ProvidedService, ScopeVisitor {if (ext != null) {return ext;}+ if(this.extensionProfile == null)+ return null;if (this.profilPool == null)createProfilePool();ext = this.profilPool.aquire();@@ -135,7 +142,7 @@ public class ProvidedServiceConfig implements ProvidedService, ScopeVisitor {/*** @param extensionProfil -- * the extensionprofile for this feed configuration+ * the extension profile for this feed configuration*/@SuppressWarnings("unchecked")public void setExtensionProfile(ExtensionProfile extensionProfil) {@@ -150,11 +157,11 @@ public class ProvidedServiceConfig implements ProvidedService, ScopeVisitor {private void createProfilePool() {if (LOG.isInfoEnabled())- LOG.info("Create ExtensionProfile pool with poolsize:"+ LOG.info("Create ExtensionProfile pool with pool size:"+ this.poolSize + " for service " + this.serviceName);this.profilPool = new SimpleObjectPool<ExtensionProfile>(this.poolSize,new ExtensionProfileFactory<ExtensionProfile>(- this.extensionProfile.getClass()));+ this.extensionProfile.getClass(),this.entryType,this.feedType));}/**@@ -225,14 +232,19 @@ public class ProvidedServiceConfig implements ProvidedService, ScopeVisitor {private final Constructor<? extends ExtensionProfile> constructor;private static final Object[] constArray = new Object[0];++ private BaseEntry entry;+ private BaseFeed feed;- ExtensionProfileFactory(Class<? extends ExtensionProfile> clazz) {+ ExtensionProfileFactory(Class<? extends ExtensionProfile> clazz, Class<? extends BaseEntry> entryClass, Class<? extends BaseFeed> feedClass) {this.clazz = clazz;try {this.constructor = clazz.getConstructor(new Class[0]);+ this.entry = entryClass.newInstance();+ this.feed = feedClass.newInstance();} catch (Exception e) {throw new IllegalArgumentException(- "The given class has no defaul constructor -- can not use as a ExtensionProfile -- "+ "The given class has no default constructor -- can not use as a ExtensionProfile -- "+ this.clazz.getName(), e);}}@@ -244,10 +256,13 @@ public class ProvidedServiceConfig implements ProvidedService, ScopeVisitor {public Type getInstance() {try {- return (Type) this.constructor.newInstance(constArray);+ Type retValue = (Type) this.constructor.newInstance(constArray);+ this.entry.declareExtensions(retValue);+ this.feed.declareExtensions(retValue);+ return retValue;} catch (Exception e) {throw new RuntimeException(- "Can not instanciate new ExtensionProfile -- ", e);+ "Can not instantiate new ExtensionProfile -- ", e);}}@@ -271,7 +286,7 @@ public class ProvidedServiceConfig implements ProvidedService, ScopeVisitor {createProfilePool();/** don't set a extension profile for each thread. The current thread- * might use another service and does not need the extensionprofile of+ * might use another service and does not need the extension profile of* this service*/}@@ -295,4 +310,20 @@ public class ProvidedServiceConfig implements ProvidedService, ScopeVisitor {this.profilPool.release(ext);}+ /**+ * @return Returns the indexSchema.+ */+ public IndexSchema getIndexSchema() {+ return this.indexSchema;+ }++ /**+ * @param indexSchema The indexSchema to set.+ */+ public void setIndexSchema(IndexSchema indexSchema) {+ this.indexSchema = indexSchema;+ if(this.indexSchema != null)+ this.indexSchema.setName(this.serviceName);+ }+}diff --git a/contrib/gdata-server/src/java/org/apache/lucene/gdata/server/registry/RegistryBuilder.java b/contrib/gdata-server/src/java/org/apache/lucene/gdata/server/registry/RegistryBuilder.javaindex 7475003a58d..3a1e695c53c 100644--- a/contrib/gdata-server/src/java/org/apache/lucene/gdata/server/registry/RegistryBuilder.java+++ b/contrib/gdata-server/src/java/org/apache/lucene/gdata/server/registry/RegistryBuilder.java@@ -18,14 +18,17 @@ package org.apache.lucene.gdata.server.registry;import java.io.IOException;import org.apache.commons.digester.Digester;+import org.apache.lucene.gdata.search.config.IndexSchema;+import org.apache.lucene.gdata.search.config.IndexSchemaField;import org.apache.lucene.gdata.server.registry.configuration.ComponentConfiguration;import org.apache.lucene.gdata.utils.SimpleSaxErrorHandler;+import org.apache.xerces.parsers.SAXParser;import org.xml.sax.SAXException;/*** Reads the configuration file and creates the* {@link org.apache.lucene.gdata.server.registry.GDataServerRegistry} singleton- * instance. All services and components will be instanciated and registered in+ * instance. All services and components will be instantiated and registered in* the registry.** @author Simon Willnauer@@ -38,22 +41,30 @@ class RegistryBuilder {* {@link GDataServerRegistry#getRegistry()} method** @throws IOException -- * if an IOException occures while reading the config file+ * if an IOException occurs while reading the config file* @throws SAXException -* if the config file can not be parsed*/static void buildRegistry() throws IOException, SAXException {-- buildFromConfiguration(new Digester(), GDataServerRegistry- .getRegistry());+ String schemaFile = RegistryBuilder.class.getResource("/gdata-config.xsd").getFile();+ /*+ * Force using apache xerces parser for digester+ */+ SAXParser parser = new SAXParser();+ parser.setFeature("http://apache.org/xml/features/validation/schema-full-checking",true);+ parser.setFeature("http://apache.org/xml/features/validation/schema",true);+ parser.setFeature("http://xml.org/sax/features/validation",true);+ parser.setProperty("http://apache.org/xml/properties/schema/external-noNamespaceSchemaLocation",schemaFile);+ Digester digester = new Digester(parser);+ buildFromConfiguration(digester, GDataServerRegistry+ .getRegistry(),schemaFile);}private static void buildFromConfiguration(Digester digester,- GDataServerRegistry registry) throws IOException, SAXException {- String schemaFile = RegistryBuilder.class.getResource("/gdata-config.xsd").getFile();+ GDataServerRegistry registry, String schemaURL) throws IOException, SAXException {digester.setValidating(true);- digester.setSchema(schemaFile);+ digester.setSchema(schemaURL);digester.setErrorHandler(new SimpleSaxErrorHandler());digester.push(registry);/*@@ -66,7 +77,7 @@ class RegistryBuilder {digester.addBeanPropertySetter("gdata/service/entry-class", "entryType");digester.addBeanPropertySetter("gdata/service/extension-profile","extensionProfileClass");-+ addIndexRule(digester);/** load components and configurations*/@@ -77,11 +88,66 @@ class RegistryBuilder {digester.addCallMethod("gdata/server-components/component/configuration/property","set",2,new Class[]{String.class,String.class});digester.addCallParam("gdata/server-components/component/configuration/property",0,"name");digester.addCallParam("gdata/server-components/component/configuration/property",1);+ //second parameter on registerComponent -- top of the stack (Component configuration)digester.addCallParam("gdata/server-components/component/configuration",1,0);digester.parse(RegistryBuilder.class.getResourceAsStream("/gdata-config.xml"));}+++ private static void addIndexRule(Digester digester){+ digester.addObjectCreate("gdata/service/index-schema", IndexSchema.class);+ digester.addSetNext("gdata/service/index-schema", "setIndexSchema");+ digester.addSetProperties("gdata/service/index-schema");+ digester.addSetProperties("gdata/service/index-schema/index");+ digester.addBeanPropertySetter("gdata/service/index-schema/index/maxMergeDocs");+ digester.addBeanPropertySetter("gdata/service/index-schema/index/maxBufferedDocs");+ digester.addBeanPropertySetter("gdata/service/index-schema/index/maxFieldLength");+ digester.addBeanPropertySetter("gdata/service/index-schema/index/mergeFactor");+ digester.addBeanPropertySetter("gdata/service/index-schema/index/indexLocation");+ digester.addBeanPropertySetter("gdata/service/index-schema/index/useCompoundFile");+ digester.addCallMethod("gdata/service/index-schema/index/defaultAnalyzer", "serviceAnalyzer",1,new Class[]{Class.class});++ //call method on top of the stack addSchemaField+ digester.addCallMethod("gdata/service/index-schema/field","addSchemaField",1,new Class[]{IndexSchemaField.class});+ digester.addObjectCreate("gdata/service/index-schema/field",IndexSchemaField.class);+ //set parameter for method call -- parameter is IndexSchemaField+ digester.addCallParam("gdata/service/index-schema/field",0,0);+ digester.addSetProperties("gdata/service/index-schema/field");+ digester.addBeanPropertySetter("gdata/service/index-schema/field/path");+ digester.addBeanPropertySetter("gdata/service/index-schema/field/store","storeByName");+ digester.addBeanPropertySetter("gdata/service/index-schema/field/index","indexByName");+ digester.addBeanPropertySetter("gdata/service/index-schema/field/analyzer","analyzerClass");++// call method on top of the stack addSchemaField+ digester.addCallMethod("gdata/service/index-schema/custom","addSchemaField",1,new Class[]{IndexSchemaField.class});+ digester.addObjectCreate("gdata/service/index-schema/custom",IndexSchemaField.class);+ //set parameter for method call -- parameter is IndexSchemaField+ digester.addCallParam("gdata/service/index-schema/custom",0,0);+ digester.addSetProperties("gdata/service/index-schema/custom");+ digester.addBeanPropertySetter("gdata/service/index-schema/custom/path");+ digester.addBeanPropertySetter("gdata/service/index-schema/custom/store","storeByName");+ digester.addBeanPropertySetter("gdata/service/index-schema/custom/index","indexByName");+ digester.addBeanPropertySetter("gdata/service/index-schema/custom/analyzer","analyzerClass");+ digester.addBeanPropertySetter("gdata/service/index-schema/custom/field-class","fieldClass");+// digester.addCallMethod("gdata/service/index-schema/custom/field-class","fieldClass",1,new Class[]{Class.class});+++// call method on top of the stack addSchemaField+ digester.addCallMethod("gdata/service/index-schema/mixed","addSchemaField",1,new Class[]{IndexSchemaField.class});+ digester.addObjectCreate("gdata/service/index-schema/mixed",IndexSchemaField.class);+ //set parameter for method call -- parameter is IndexSchemaField+ digester.addCallParam("gdata/service/index-schema/mixed",0,0);+ digester.addSetProperties("gdata/service/index-schema/mixed");+ digester.addBeanPropertySetter("gdata/service/index-schema/mixed","type");+ digester.addBeanPropertySetter("gdata/service/index-schema/mixed/path");+ digester.addBeanPropertySetter("gdata/service/index-schema/mixed/store","storeByName");+ digester.addBeanPropertySetter("gdata/service/index-schema/mixed/index","indexByName");+ digester.addBeanPropertySetter("gdata/service/index-schema/mixed/contenttype","typePath");+ digester.addBeanPropertySetter("gdata/service/index-schema/mixed/analyzer","analyzerClass");++ }}diff --git a/contrib/gdata-server/src/java/org/apache/lucene/gdata/server/registry/RegistryContextListener.java b/contrib/gdata-server/src/java/org/apache/lucene/gdata/server/registry/RegistryContextListener.javaindex ffbed0b22e8..b4a4d59b45a 100644--- a/contrib/gdata-server/src/java/org/apache/lucene/gdata/server/registry/RegistryContextListener.java+++ b/contrib/gdata-server/src/java/org/apache/lucene/gdata/server/registry/RegistryContextListener.java@@ -27,7 +27,7 @@ import org.apache.commons.logging.LogFactory;* {@link org.apache.lucene.gdata.server.registry.GDataServerRegistry} when the* context is loaded. The registry will be loaded before the* {@link org.apache.lucene.gdata.servlet.RequestControllerServlet} is loaded.- * The Registry will be loaded and set up befor the REST interface is available.+ * The Registry will be loaded and set up before the REST interface is available.* <p>* This ContextListener has to be configured in the <code>web.xml</code>* deployment descriptor.@@ -58,9 +58,13 @@ public class RegistryContextListener implements ServletContextListener {try {RegistryBuilder.buildRegistry();this.serverRegistry = GDataServerRegistry.getRegistry();- } catch (Exception e) {- this.serverRegistry.destroy();- LOG.error("can not register requiered components", e);+ /*+ * catch all exceptions and destroy the registry to release all resources.+ * some components start lots of threads, the will remain running if the registry is not destroyed+ */+ } catch (Throwable e) {+ GDataServerRegistry.getRegistry().destroy();+ LOG.error("can not register required components", e);throw new RuntimeException("Can not register required components",e);}@@ -73,7 +77,12 @@ public class RegistryContextListener implements ServletContextListener {*/public void contextDestroyed(ServletContextEvent arg0) {LOG.info("Destroying context");- this.serverRegistry.destroy();+ /*+ * this might be null if startup fails+ * --> prevent null pointer exception+ */+ if(this.serverRegistry != null)+ this.serverRegistry.destroy();}diff --git a/contrib/gdata-server/src/java/org/apache/lucene/gdata/server/registry/ServerComponent.java b/contrib/gdata-server/src/java/org/apache/lucene/gdata/server/registry/ServerComponent.javaindex e21115861bd..369067b0c79 100644--- a/contrib/gdata-server/src/java/org/apache/lucene/gdata/server/registry/ServerComponent.java+++ b/contrib/gdata-server/src/java/org/apache/lucene/gdata/server/registry/ServerComponent.java@@ -32,6 +32,7 @@ package org.apache.lucene.gdata.server.registry;public interface ServerComponent {/*** will be call when the component is registered.+ * if this fails the server must not startup.*/public abstract void initialize();diff --git a/contrib/gdata-server/src/java/org/apache/lucene/gdata/server/registry/configuration/ComponentConfiguration.java b/contrib/gdata-server/src/java/org/apache/lucene/gdata/server/registry/configuration/ComponentConfiguration.javaindex a46b0c5ebd1..d3522a2bfe1 100755--- a/contrib/gdata-server/src/java/org/apache/lucene/gdata/server/registry/configuration/ComponentConfiguration.java+++ b/contrib/gdata-server/src/java/org/apache/lucene/gdata/server/registry/configuration/ComponentConfiguration.java@@ -21,7 +21,7 @@ import java.util.Map;/*** Simple configuration class storing properties as key with defined property- * values as values in a <code>Map<String,String></code>. As amap cannot+ * values as values in a <code>Map<String,String></code>. As a map cannot* contain duplicate keys the first use of a key can not be replaced. If a key* is used twice a {@link java.lang.IllegalArgumentException} will be thrown.* @see Mapdiff --git a/contrib/gdata-server/src/java/org/apache/lucene/gdata/server/registry/configuration/PropertyInjector.java b/contrib/gdata-server/src/java/org/apache/lucene/gdata/server/registry/configuration/PropertyInjector.javaindex 14d83c98ba9..1f8e7eed8b7 100755--- a/contrib/gdata-server/src/java/org/apache/lucene/gdata/server/registry/configuration/PropertyInjector.java+++ b/contrib/gdata-server/src/java/org/apache/lucene/gdata/server/registry/configuration/PropertyInjector.java@@ -19,14 +19,15 @@ package org.apache.lucene.gdata.server.registry.configuration;import java.lang.reflect.Constructor;import java.lang.reflect.Method;import java.util.HashMap;-import java.util.Locale;import java.util.Map;import java.util.Set;import java.util.Map.Entry;+import org.apache.lucene.gdata.utils.ReflectionUtils;+/*** PropertyInjector is used to set member variables / properties of classes via- * <i>setter</i> methodes using the+ * <i>setter</i> methods using the* {@link org.apache.lucene.gdata.server.registry.configuration.ComponentConfiguration}* class.* <p>@@ -34,8 +35,8 @@ import java.util.Map.Entry;* the class or a superclass of the object to populate has to provide at least* one setter method with a single parameter. The object to populate is set via* the {@link PropertyInjector#setTargetObject} method. The class of the object- * will be analyzed for setter methodes having a "set" prefix in their method- * name. If one of the found setter methodes is annotated with+ * will be analyzed for setter methods having a "set" prefix in their method+ * name. If one of the found setter methods is annotated with* {@link org.apache.lucene.gdata.server.registry.configuration.Requiered} this* property is interpreted as a mandatory property. Mandatory properties must be* available in the provided ComponentConfiguration, if not the injection will@@ -46,14 +47,14 @@ import java.util.Map.Entry;* setter method without the 'set' prefix and must begin with a lower case* character. <span>Key<code>bufferSize</code> does match a method signature* of <code>setBufferSize</code></span> The type of the parameter will be- * reflected via the Reflection API and instanciated with the given value if+ * reflected via the Reflection API and instantiated with the given value if* possible.* </p>* <p>- * Setter methodes without a <code>Requiered</code> anntoation will be set if+ * Setter methods without a <code>Required</code> annotation will be set if* the property is present in the ComponentConfiguration* </p>- * <p>This class does not support overloaded setter methodes.</p>+ * <p>This class does not support overloaded setter methods.</p>* @author Simon Willnauer* @see org.apache.lucene.gdata.server.registry.configuration.Requiered* @see org.apache.lucene.gdata.server.registry.configuration.ComponentConfiguration@@ -88,7 +89,7 @@ public class PropertyInjector {if (this.requieredProperties.isEmpty()&& this.optionalProperties.isEmpty())throw new InjectionException(- "Given type has no public setter methodes -- "+ "Given type has no public setter methods -- "+ o.getClass().getName());}@@ -132,7 +133,7 @@ public class PropertyInjector {/*** Injects the properties stored in the <code>ComponentConfiguration</code>- * to the corresponding methodes of the target object+ * to the corresponding methods of the target object* @param bean - configuration bean containing all properties to set.**/@@ -143,11 +144,11 @@ public class PropertyInjector {throw new IllegalStateException("target is not set -- null");Set<Entry<String, Method>> requiered = this.requieredProperties.entrySet();- // set requiered properties+ // set required propertiesfor (Entry<String, Method> entry : requiered) {if (!bean.contains(entry.getKey()))throw new InjectionException(- "requiered property can not be set -- value not in configuration bean; Property: "+ "Required property can not be set -- value not in configuration bean; Property: "+ entry.getKey()+ "for class "+ this.targetClass.getName());@@ -196,12 +197,12 @@ public class PropertyInjector {private Object createObject(String s, Class<?> clazz) {try {- // if class is requested use s as fully qualified classname+ // if class is requested use s as fully qualified class nameif (clazz == Class.class)return Class.forName(s);// check for primitive typeif (clazz.isPrimitive())- clazz = getPrimitiveWrapper(clazz);+ clazz = ReflectionUtils.getPrimitiveWrapper(clazz);boolean defaultConst = false;boolean stringConst = false;Constructor[] constructors = clazz.getConstructors();@@ -226,8 +227,8 @@ public class PropertyInjector {return constructor.newInstance(new Object[] { s });}/*- * if no string const. but a default const -- use the string as a- * classname+ * if no string const. but a default const. -- use the string as a+ * class name*/if (defaultConst)return Class.forName(s).newInstance();@@ -255,28 +256,6 @@ public class PropertyInjector {this.requieredProperties.clear();}- /*- * return the wrappertype for the given primitive type. Wrappers can be- * easily instanciated via reflection and will be boxed by the vm- */- private static final Class getPrimitiveWrapper(Class primitive) {-- if (primitive == Integer.TYPE)- return Integer.class;- if (primitive == Float.TYPE)- return Float.class;- if (primitive == Long.TYPE)- return Long.class;- if (primitive == Short.TYPE)- return Short.class;- if (primitive == Byte.TYPE)- return Byte.class;- if (primitive == Double.TYPE)- return Double.class;- if (primitive == Boolean.TYPE)- return Boolean.class;-- return primitive;- }+}diff --git a/contrib/gdata-server/src/java/org/apache/lucene/gdata/servlet/handler/AbstractAccountHandler.java b/contrib/gdata-server/src/java/org/apache/lucene/gdata/servlet/handler/AbstractAccountHandler.javaindex 5b8a296c9eb..d64a14b604a 100644--- a/contrib/gdata-server/src/java/org/apache/lucene/gdata/servlet/handler/AbstractAccountHandler.java+++ b/contrib/gdata-server/src/java/org/apache/lucene/gdata/servlet/handler/AbstractAccountHandler.java@@ -26,6 +26,7 @@ import org.apache.commons.logging.Log;import org.apache.commons.logging.LogFactory;import org.apache.lucene.gdata.data.GDataAccount;import org.apache.lucene.gdata.data.GDataAccount.AccountRole;+import org.apache.lucene.gdata.server.GDataResponse;import org.apache.lucene.gdata.server.ServiceException;import org.apache.lucene.gdata.server.ServiceFactory;import org.apache.lucene.gdata.server.administration.AccountBuilder;@@ -72,10 +73,10 @@ public abstract class AbstractAccountHandler extends RequestAuthenticatorGDataAccount account = getAccountFromRequest(request);if (!account.requiredValuesSet()) {- setError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,- "requiered server component not available");+ setError(GDataResponse.SERVER_ERROR,+ "Required server component not available");throw new AccountHandlerException(- "requiered values are not set -- account can not be saved -- "+ "Required values are not set -- account can not be saved -- "+ account);}this.service = factory.getAdminService();@@ -83,13 +84,14 @@ public abstract class AbstractAccountHandler extends RequestAuthenticator} catch (ServiceException e) {LOG.error("Can't process account action -- " + e.getMessage(),e);- setError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "");- } catch (Exception e) {+ setError(e.getErrorCode(), "");+ }+ catch (AccountHandlerException e) {LOG.error("Can't process account action -- " + e.getMessage(),e);}}else{- setError(HttpServletResponse.SC_UNAUTHORIZED,"Authorization failed");+ setError(GDataResponse.UNAUTHORIZED,"Authorization failed");}sendResponse(response);}finally{diff --git a/contrib/gdata-server/src/java/org/apache/lucene/gdata/servlet/handler/AbstractFeedHandler.java b/contrib/gdata-server/src/java/org/apache/lucene/gdata/servlet/handler/AbstractFeedHandler.javaindex b3dc56415f7..160b2677f66 100644--- a/contrib/gdata-server/src/java/org/apache/lucene/gdata/servlet/handler/AbstractFeedHandler.java+++ b/contrib/gdata-server/src/java/org/apache/lucene/gdata/servlet/handler/AbstractFeedHandler.java@@ -28,6 +28,7 @@ import org.apache.lucene.gdata.data.GDataAccount;import org.apache.lucene.gdata.data.ServerBaseFeed;import org.apache.lucene.gdata.data.GDataAccount.AccountRole;import org.apache.lucene.gdata.server.GDataEntityBuilder;+import org.apache.lucene.gdata.server.GDataResponse;import org.apache.lucene.gdata.server.ServiceException;import org.apache.lucene.gdata.server.ServiceFactory;import org.apache.lucene.gdata.server.administration.AdminService;@@ -62,7 +63,7 @@ public abstract class AbstractFeedHandler extends RequestAuthenticator implementHttpServletResponse response) throws ServletException, IOException {this.authenticated = authenticateAccount(request,AccountRole.FEEDAMINISTRATOR);if(!this.authenticated)- setError(HttpServletResponse.SC_UNAUTHORIZED,"Authorization failed");+ setError(GDataResponse.UNAUTHORIZED,"Authorization failed");}@@ -70,12 +71,12 @@ public abstract class AbstractFeedHandler extends RequestAuthenticator implementGDataServerRegistry registry = GDataServerRegistry.getRegistry();String providedService = request.getParameter(PARAMETER_SERVICE);if(!registry.isServiceRegistered(providedService)){- setError(HttpServletResponse.SC_NOT_FOUND,"no such service");+ setError(GDataResponse.NOT_FOUND,"no such service");throw new FeedHandlerException("ProvicdedService is not registered -- Name: "+providedService);}ProvidedService provServiceInstance = registry.getProvidedService(providedService);if(providedService == null){- setError(HttpServletResponse.SC_BAD_REQUEST,"no such service");+ setError(GDataResponse.BAD_REQUEST,"no such service");throw new FeedHandlerException("no such service registered -- "+providedService);}try{@@ -85,12 +86,12 @@ public abstract class AbstractFeedHandler extends RequestAuthenticator implement}catch (IOException e) {if(LOG.isInfoEnabled())LOG.info("Can not read from input stream - ",e);- setError(HttpServletResponse.SC_BAD_REQUEST,"Can not read from input stream");+ setError(GDataResponse.BAD_REQUEST,"Can not read from input stream");throw e;}catch (ParseException e) {if(LOG.isInfoEnabled())LOG.info("feed can not be parsed - ",e);- setError(HttpServletResponse.SC_BAD_REQUEST,"incoming feed can not be parsed");+ setError(GDataResponse.BAD_REQUEST,"incoming feed can not be parsed");throw e;}@@ -102,7 +103,7 @@ public abstract class AbstractFeedHandler extends RequestAuthenticator implementServiceFactory serviceFactory = registry.lookup(ServiceFactory.class,ComponentType.SERVICEFACTORY);if(serviceFactory == null){- setError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Required server component not available");+ setError(GDataResponse.SERVER_ERROR, "Required server component not available");throw new FeedHandlerException("Required server component not available -- "+ServiceFactory.class.getName());}AdminService service = serviceFactory.getAdminService();diff --git a/contrib/gdata-server/src/java/org/apache/lucene/gdata/servlet/handler/AbstractGdataRequestHandler.java b/contrib/gdata-server/src/java/org/apache/lucene/gdata/servlet/handler/AbstractGdataRequestHandler.javaindex 240bd140de7..8dcf0a698d3 100644--- a/contrib/gdata-server/src/java/org/apache/lucene/gdata/servlet/handler/AbstractGdataRequestHandler.java+++ b/contrib/gdata-server/src/java/org/apache/lucene/gdata/servlet/handler/AbstractGdataRequestHandler.java@@ -61,14 +61,15 @@ public abstract class AbstractGdataRequestHandler extends RequestAuthenticator ithis.feedRequest = new GDataRequest(request, type);this.feedResponse = new GDataResponse(response);this.feedResponse.setEncoding(ENCODING);- getService();+try {this.feedRequest.initializeRequest();} catch (GDataRequestException e) {- this.feedResponse.setError(HttpServletResponse.SC_NOT_FOUND);+ setError(e.getErrorCode());LOG.warn("Couldn't initialize FeedRequest - " + e.getMessage(), e);throw e;}+ getService(this.feedRequest);}@@ -90,10 +91,10 @@ public abstract class AbstractGdataRequestHandler extends RequestAuthenticator ithis.feedResponse.setError(error);}- private void getService() throws ServletException {+ private void getService(GDataRequest request) throws ServletException {GDataServerRegistry registry = GDataServerRegistry.getRegistry();ServiceFactory serviceFactory = registry.lookup(ServiceFactory.class,ComponentType.SERVICEFACTORY);- this.service = serviceFactory.getService();+ this.service = serviceFactory.getService(request);if(this.service == null)throw new ServletException("Service not available");diff --git a/contrib/gdata-server/src/java/org/apache/lucene/gdata/servlet/handler/AuthenticationHandler.java b/contrib/gdata-server/src/java/org/apache/lucene/gdata/servlet/handler/AuthenticationHandler.javaindex 5dcd20ac6c7..5612114de8f 100644--- a/contrib/gdata-server/src/java/org/apache/lucene/gdata/servlet/handler/AuthenticationHandler.java+++ b/contrib/gdata-server/src/java/org/apache/lucene/gdata/servlet/handler/AuthenticationHandler.java@@ -27,6 +27,7 @@ import javax.servlet.http.HttpServletResponse;import org.apache.commons.logging.Log;import org.apache.commons.logging.LogFactory;import org.apache.lucene.gdata.data.GDataAccount;+import org.apache.lucene.gdata.server.GDataResponse;import org.apache.lucene.gdata.server.ServiceException;import org.apache.lucene.gdata.server.ServiceFactory;import org.apache.lucene.gdata.server.administration.AdminService;@@ -91,10 +92,10 @@ public class AuthenticationHandler implements GDataRequestHandler {}} catch (AuthenticationException e){LOG.error("BadAuthentication -- "+e.getMessage(),e);- sendError(response, HttpServletResponse.SC_FORBIDDEN,"BadAuthentication");+ sendError(response, GDataResponse.FORBIDDEN,"BadAuthentication");}catch (Exception e) {LOG.error("Unexpected Exception -- SERVERERROR -- "+e.getMessage(),e);- sendError(response,HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Service not available");+ sendError(response,GDataResponse.SERVER_ERROR, "Service not available");}}diff --git a/contrib/gdata-server/src/java/org/apache/lucene/gdata/servlet/handler/DefaultDeleteHandler.java b/contrib/gdata-server/src/java/org/apache/lucene/gdata/servlet/handler/DefaultDeleteHandler.javaindex f14642a131e..e354341a094 100644--- a/contrib/gdata-server/src/java/org/apache/lucene/gdata/servlet/handler/DefaultDeleteHandler.java+++ b/contrib/gdata-server/src/java/org/apache/lucene/gdata/servlet/handler/DefaultDeleteHandler.java@@ -25,6 +25,7 @@ import org.apache.commons.logging.Log;import org.apache.commons.logging.LogFactory;import org.apache.lucene.gdata.data.GDataAccount.AccountRole;import org.apache.lucene.gdata.server.GDataRequestException;+import org.apache.lucene.gdata.server.GDataResponse;import org.apache.lucene.gdata.server.ServiceException;import org.apache.lucene.gdata.server.GDataRequest.GDataRequestType;@@ -37,7 +38,7 @@ import org.apache.lucene.gdata.server.GDataRequest.GDataRequestType;* </p>* <ol>* <li>if the entry could be deleted - HTTP status code <i>200 OK</i></li>- * <li>if an error occures - HTTP status code <i>500 INTERNAL SERVER ERROR</i></li>+ * <li>if an error occurs - HTTP status code <i>500 INTERNAL SERVER ERROR</i></li>* <li>if the resource could not found - HTTP status code <i>404 NOT FOUND</i></li>* </ol>*@@ -63,7 +64,7 @@ public class DefaultDeleteHandler extends AbstractGdataRequestHandler {return;}if(!authenticateAccount(request,AccountRole.ENTRYAMINISTRATOR)){- setError(HttpServletResponse.SC_UNAUTHORIZED);+ setError(GDataResponse.UNAUTHORIZED);sendError();return;}@@ -74,6 +75,7 @@ public class DefaultDeleteHandler extends AbstractGdataRequestHandler {} catch (ServiceException e) {LOG.error("Could not process DeleteFeed request - "+ e.getMessage(), e);+ setError(e.getErrorCode());sendError();}finally{closeService();diff --git a/contrib/gdata-server/src/java/org/apache/lucene/gdata/servlet/handler/DefaultGetHandler.java b/contrib/gdata-server/src/java/org/apache/lucene/gdata/servlet/handler/DefaultGetHandler.javaindex f4ab604879c..0bbd74e8688 100644--- a/contrib/gdata-server/src/java/org/apache/lucene/gdata/servlet/handler/DefaultGetHandler.java+++ b/contrib/gdata-server/src/java/org/apache/lucene/gdata/servlet/handler/DefaultGetHandler.java@@ -37,10 +37,10 @@ import com.google.gdata.data.BaseFeed;/*** Default Handler implementation. This handler processes the incoming* {@link org.apache.lucene.gdata.server.GDataRequest} and retrieves the- * requested feed from the underlaying storage.+ * requested feed from the underlying storage.* <p>- * This hander also processes search queries and retrives the search hits from- * the underlaying search component. The user query will be accessed via the+ * This hander also processes search queries and retrieves the search hits from+ * the underlying search component. The user query will be accessed via the* {@link org.apache.lucene.gdata.server.GDataRequest} instance passed to the* {@link Service} class.* </p>@@ -101,6 +101,7 @@ public class DefaultGetHandler extends AbstractGdataRequestHandler {} catch (ServiceException e) {LOG.error("Could not process GetFeed request - " + e.getMessage(),e);+ setError(e.getErrorCode());sendError();}finally{closeService();@@ -110,9 +111,9 @@ public class DefaultGetHandler extends AbstractGdataRequestHandler {/**** returns true if the resource has been modified since the specified- * reqeust header value+ * request header value*/- private boolean checkIsModified(String lastModified)+ protected boolean checkIsModified(String lastModified)throws ServiceException {if (lastModified == null)return true;@@ -126,7 +127,7 @@ public class DefaultGetHandler extends AbstractGdataRequestHandler {entityDate = this.service.getEntryLastModified(this.feedRequest.getEntryId(),this.feedRequest.getFeedId());if(LOG.isInfoEnabled())- LOG.info("comparing date clientDate: "+clientDate+"; lastmodified: "+entityDate);+ LOG.info("comparing date clientDate: "+clientDate+"; last modified: "+entityDate);return (entityDate.getTime()-clientDate.getTime() > 1000);} catch (java.text.ParseException e) {LOG.info("Couldn't parse Last-Modified header -- "+lastModified,e);diff --git a/contrib/gdata-server/src/java/org/apache/lucene/gdata/servlet/handler/DefaultInsertHandler.java b/contrib/gdata-server/src/java/org/apache/lucene/gdata/servlet/handler/DefaultInsertHandler.javaindex e85fb6592df..21d4eb9daf9 100644--- a/contrib/gdata-server/src/java/org/apache/lucene/gdata/servlet/handler/DefaultInsertHandler.java+++ b/contrib/gdata-server/src/java/org/apache/lucene/gdata/servlet/handler/DefaultInsertHandler.java@@ -26,6 +26,7 @@ import org.apache.commons.logging.Log;import org.apache.commons.logging.LogFactory;import org.apache.lucene.gdata.data.GDataAccount.AccountRole;import org.apache.lucene.gdata.server.GDataRequestException;+import org.apache.lucene.gdata.server.GDataResponse;import org.apache.lucene.gdata.server.ServiceException;import org.apache.lucene.gdata.server.GDataRequest.GDataRequestType;@@ -40,7 +41,7 @@ import com.google.gdata.data.BaseEntry;* </p>* <ol>* <li>if the entry was added - HTTP status code <i>200 OK</i></li>- * <li>if an error occures - HTTP status code <i>500 INTERNAL SERVER ERROR</i></li>+ * <li>if an error occurs - HTTP status code <i>500 INTERNAL SERVER ERROR</i></li>* <li>if the resource could not found - HTTP status code <i>404 NOT FOUND</i></li>* </ol>* <p>The added entry will be send back to the client if the insert request was successful.</p>@@ -64,7 +65,7 @@ public class DefaultInsertHandler extends AbstractGdataRequestHandler {return;}if(!authenticateAccount(this.feedRequest,AccountRole.ENTRYAMINISTRATOR)){- setError(HttpServletResponse.SC_UNAUTHORIZED);+ setError(GDataResponse.UNAUTHORIZED);sendError();return;}@@ -72,12 +73,13 @@ public class DefaultInsertHandler extends AbstractGdataRequestHandler {try{BaseEntry entry = this.service.createEntry(this.feedRequest,this.feedResponse);setFeedResponseFormat();- setFeedResponseStatus(HttpServletResponse.SC_CREATED);+ setFeedResponseStatus(GDataResponse.CREATED);this.feedResponse.sendResponse(entry, this.feedRequest.getConfigurator().getExtensionProfile());}catch (ServiceException e) {LOG.error("Could not process GetFeed request - "+e.getMessage(),e);- this.feedResponse.sendError();+ setError(e.getErrorCode());+ sendError();}finally{closeService();}diff --git a/contrib/gdata-server/src/java/org/apache/lucene/gdata/servlet/handler/DefaultUpdateHandler.java b/contrib/gdata-server/src/java/org/apache/lucene/gdata/servlet/handler/DefaultUpdateHandler.javaindex 1f4ad4b09a4..33d980544a2 100644--- a/contrib/gdata-server/src/java/org/apache/lucene/gdata/servlet/handler/DefaultUpdateHandler.java+++ b/contrib/gdata-server/src/java/org/apache/lucene/gdata/servlet/handler/DefaultUpdateHandler.java@@ -25,6 +25,7 @@ import org.apache.commons.logging.Log;import org.apache.commons.logging.LogFactory;import org.apache.lucene.gdata.data.GDataAccount.AccountRole;import org.apache.lucene.gdata.server.GDataRequestException;+import org.apache.lucene.gdata.server.GDataResponse;import org.apache.lucene.gdata.server.ServiceException;import org.apache.lucene.gdata.server.GDataRequest.GDataRequestType;@@ -39,7 +40,7 @@ import com.google.gdata.data.BaseEntry;* </p>* <ol>* <li>if the entry was successfully updated - HTTP status code <i>200 OK</i></li>- * <li>if an error occures - HTTP status code <i>500 INTERNAL SERVER ERROR</i></li>+ * <li>if an error occurs - HTTP status code <i>500 INTERNAL SERVER ERROR</i></li>* <li>if the resource could not found - HTTP status code <i>404 NOT FOUND</i></li>* </ol>*@@ -61,7 +62,7 @@ public class DefaultUpdateHandler extends AbstractGdataRequestHandler {try {initializeRequestHandler(request, response,GDataRequestType.UPDATE);} catch (GDataRequestException e) {- setError(HttpServletResponse.SC_UNAUTHORIZED);+ setError(GDataResponse.UNAUTHORIZED);sendError();return;}@@ -74,13 +75,13 @@ public class DefaultUpdateHandler extends AbstractGdataRequestHandler {BaseEntry entry = this.service.updateEntry(this.feedRequest,this.feedResponse);setFeedResponseFormat();- setFeedResponseStatus(HttpServletResponse.SC_OK);this.feedResponse.sendResponse(entry, this.feedRequest.getConfigurator().getExtensionProfile());}catch (ServiceException e) {LOG.error("Could not process UpdateFeed request - "+ e.getMessage(), e);+ setError(e.getErrorCode());sendError();}finally{closeService();diff --git a/contrib/gdata-server/src/java/org/apache/lucene/gdata/servlet/handler/DeleteFeedHandler.java b/contrib/gdata-server/src/java/org/apache/lucene/gdata/servlet/handler/DeleteFeedHandler.javaindex 7a24fac9959..a7a8f75e5ab 100644--- a/contrib/gdata-server/src/java/org/apache/lucene/gdata/servlet/handler/DeleteFeedHandler.java+++ b/contrib/gdata-server/src/java/org/apache/lucene/gdata/servlet/handler/DeleteFeedHandler.java@@ -25,6 +25,8 @@ import javax.servlet.http.HttpServletResponse;import org.apache.commons.logging.Log;import org.apache.commons.logging.LogFactory;import org.apache.lucene.gdata.data.ServerBaseFeed;+import org.apache.lucene.gdata.server.GDataResponse;+import org.apache.lucene.gdata.server.ServiceException;import org.apache.lucene.gdata.server.ServiceFactory;import org.apache.lucene.gdata.server.administration.AdminService;import org.apache.lucene.gdata.server.registry.ComponentType;@@ -52,16 +54,16 @@ public class DeleteFeedHandler extends AbstractFeedHandler{GDataServerRegistry registry = GDataServerRegistry.getRegistry();ServiceFactory serviceFactory = registry.lookup(ServiceFactory.class,ComponentType.SERVICEFACTORY);if(serviceFactory == null){- setError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,"required component is not available");+ setError(GDataResponse.SERVER_ERROR,"required component is not available");throw new FeedHandlerException("Can't save feed - ServiceFactory is null");}service = serviceFactory.getAdminService();service.deleteFeed(feed);} catch (FeedHandlerException e) {LOG.error("Can not delete feed -- "+e.getMessage(),e);- }catch (Exception e) {+ }catch (ServiceException e) {LOG.error("Can not delete feed -- "+e.getMessage(),e);- setError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,"can not create feed");+ setError(e.getErrorCode(),"can not create feed");}finally{if(service != null)service.close();@@ -76,7 +78,7 @@ public class DeleteFeedHandler extends AbstractFeedHandler{private ServerBaseFeed createDeleteFeed(final HttpServletRequest request) throws FeedHandlerException {String feedId = request.getParameter("feedid");if(feedId == null){- setError(HttpServletResponse.SC_BAD_REQUEST,"No feed id specified");+ setError(GDataResponse.BAD_REQUEST,"No feed id specified");throw new FeedHandlerException("no feed Id specified");}ServerBaseFeed retVal = new ServerBaseFeed();diff --git a/contrib/gdata-server/src/java/org/apache/lucene/gdata/servlet/handler/InsertFeedHandler.java b/contrib/gdata-server/src/java/org/apache/lucene/gdata/servlet/handler/InsertFeedHandler.javaindex 9d060f99106..eb678772f24 100644--- a/contrib/gdata-server/src/java/org/apache/lucene/gdata/servlet/handler/InsertFeedHandler.java+++ b/contrib/gdata-server/src/java/org/apache/lucene/gdata/servlet/handler/InsertFeedHandler.java@@ -26,12 +26,15 @@ import org.apache.commons.logging.Log;import org.apache.commons.logging.LogFactory;import org.apache.lucene.gdata.data.GDataAccount;import org.apache.lucene.gdata.data.ServerBaseFeed;+import org.apache.lucene.gdata.server.GDataResponse;import org.apache.lucene.gdata.server.ServiceException;import org.apache.lucene.gdata.server.ServiceFactory;import org.apache.lucene.gdata.server.administration.AdminService;import org.apache.lucene.gdata.server.registry.ComponentType;import org.apache.lucene.gdata.server.registry.GDataServerRegistry;+import com.google.gdata.util.ParseException;+/*** @author Simon Willnauer*@@ -66,12 +69,14 @@ public class InsertFeedHandler extends AbstractFeedHandler {service = serviceFactory.getAdminService();service.createFeed(feed, account);} catch (ServiceException e) {- setError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,+ setError(GDataResponse.SERVER_ERROR,"can not create feed");LOG.error("Can not create feed -- " + e.getMessage(), e);- } catch (Exception e) {+ } catch (FeedHandlerException e) {LOG.error("Can not create feed -- " + e.getMessage(), e);+ }catch (ParseException e) {+ LOG.error("Can not create feed -- " + e.getMessage(), e);}finally{if(service != null)service.close();diff --git a/contrib/gdata-server/src/java/org/apache/lucene/gdata/servlet/handler/UpdateFeedHandler.java b/contrib/gdata-server/src/java/org/apache/lucene/gdata/servlet/handler/UpdateFeedHandler.javaindex eafb7d535d3..6166e552f81 100644--- a/contrib/gdata-server/src/java/org/apache/lucene/gdata/servlet/handler/UpdateFeedHandler.java+++ b/contrib/gdata-server/src/java/org/apache/lucene/gdata/servlet/handler/UpdateFeedHandler.java@@ -26,6 +26,7 @@ import org.apache.commons.logging.Log;import org.apache.commons.logging.LogFactory;import org.apache.lucene.gdata.data.GDataAccount;import org.apache.lucene.gdata.data.ServerBaseFeed;+import org.apache.lucene.gdata.server.GDataResponse;import org.apache.lucene.gdata.server.ServiceException;import org.apache.lucene.gdata.server.ServiceFactory;import org.apache.lucene.gdata.server.administration.AdminService;@@ -59,7 +60,7 @@ public class UpdateFeedHandler extends AbstractFeedHandler {ServiceFactory serviceFactory = registry.lookup(ServiceFactory.class, ComponentType.SERVICEFACTORY);if (serviceFactory == null) {- setError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,+ setError(GDataResponse.SERVER_ERROR,"required component is not available");throw new FeedHandlerException("Can't update feed - ServiceFactory is null");@@ -67,7 +68,7 @@ public class UpdateFeedHandler extends AbstractFeedHandler {service = serviceFactory.getAdminService();service.updateFeed(feed, account);} catch (ServiceException e) {- setError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,+ setError(e.getErrorCode(),"can not update feed");LOG.error("Can not update feed -- " + e.getMessage(), e);} catch (Exception e) {diff --git a/contrib/gdata-server/src/java/org/apache/lucene/gdata/storage/db4o/DB4oController.java b/contrib/gdata-server/src/java/org/apache/lucene/gdata/storage/db4o/DB4oController.javaindex 19430874104..39c35ff70ab 100755--- a/contrib/gdata-server/src/java/org/apache/lucene/gdata/storage/db4o/DB4oController.java+++ b/contrib/gdata-server/src/java/org/apache/lucene/gdata/storage/db4o/DB4oController.java@@ -156,13 +156,14 @@ public class DB4oController implements StorageController, ScopeVisitor {false);Db4o.configure().objectClass(ServerBaseFeed.class).maximumActivationDepth(0);- Db4o.configure().objectClass(BaseFeed.class).minimumActivationDepth(10);+ Db4o.configure().objectClass(BaseFeed.class).minimumActivationDepth(1);Db4o.configure().objectClass(BaseEntry.class)- .minimumActivationDepth(10);+ .minimumActivationDepth(1);Db4o.configure().objectClass(BaseFeed.class).cascadeOnDelete(true);Db4o.configure().objectClass(DB4oEntry.class).cascadeOnDelete(true);Db4o.configure().objectClass(GDataAccount.class).cascadeOnDelete(true);Db4o.configure().weakReferences(this.weakReferences);+ Db4o.configure().optimizeNativeQueries(false);if (this.runAsServer) {this.server = Db4o.openServer(this.filePath, this.port);this.server.grantAccess(this.user, this.password);@@ -181,8 +182,7 @@ public class DB4oController implements StorageController, ScopeVisitor {try {createAdminAccount();} catch (StorageException e) {-- e.printStackTrace();+ LOG.error("Can not create admin account -- ",e);}}diff --git a/contrib/gdata-server/src/java/org/apache/lucene/gdata/storage/db4o/DB4oStorage.java b/contrib/gdata-server/src/java/org/apache/lucene/gdata/storage/db4o/DB4oStorage.javaindex 72a9bb8100e..8a2da4149c6 100755--- a/contrib/gdata-server/src/java/org/apache/lucene/gdata/storage/db4o/DB4oStorage.java+++ b/contrib/gdata-server/src/java/org/apache/lucene/gdata/storage/db4o/DB4oStorage.java@@ -25,6 +25,7 @@ import org.apache.lucene.gdata.data.GDataAccount;import org.apache.lucene.gdata.data.ServerBaseEntry;import org.apache.lucene.gdata.data.ServerBaseFeed;import org.apache.lucene.gdata.storage.ModificationConflictException;+import org.apache.lucene.gdata.storage.ResourceNotFoundException;import org.apache.lucene.gdata.storage.Storage;import org.apache.lucene.gdata.storage.StorageController;import org.apache.lucene.gdata.storage.StorageException;@@ -38,7 +39,7 @@ import com.google.gdata.data.DateTime;/***- * Storage implementaion for the DB4o storage component+ * Storage implementation for the DB4o storage component* @author Simon Willnauer**/@@ -92,7 +93,7 @@ public class DB4oStorage implements Storage {throw new StorageException("can not store entry -- feed id is null");if (LOG.isDebugEnabled())LOG.debug("Storing entry for feed: " + entry.getFeedId());- BaseFeed<BaseFeed, BaseEntry> feed = getFeedOnly(entry.getFeedId());+ BaseFeed<BaseFeed, BaseEntry> feed = getFeedOnly(entry.getFeedId(),entry.getServiceType());refreshPersistentObject(feed);try {StringBuilder idBuilder = new StringBuilder(entry.getFeedId());@@ -181,7 +182,7 @@ public class DB4oStorage implements Storage {if(persistentEntry.getVersion() != entry.getVersion())throw new ModificationConflictException("Current version does not match given version -- currentVersion: "+persistentEntry.getVersion()+"; given Version: "+entry.getVersion() );- BaseFeed<BaseFeed, BaseEntry> feed = getFeedOnly(entry.getFeedId());+ BaseFeed<BaseFeed, BaseEntry> feed = getFeedOnly(entry.getFeedId(),entry.getServiceType());refreshPersistentObject(feed);DateTime time = DateTime.now();if (persistentEntry.getEntry().getUpdated() != null)@@ -226,7 +227,7 @@ public class DB4oStorage implements Storage {"Current version does not match given version -- currentVersion: "+persistentEntry.getVersion()+"; given Version: "+entry.getVersion() );setUpdated(entry, persistentEntry);- BaseFeed<BaseFeed, BaseEntry> feed = getFeedOnly(entry.getFeedId());+ BaseFeed<BaseFeed, BaseEntry> feed = getFeedOnly(entry.getFeedId(),entry.getServiceType());refreshPersistentObject(feed);BaseEntry retVal = entry.getEntry();DB4oEntry newEntry = new DB4oEntry();@@ -255,6 +256,8 @@ public class DB4oStorage implements Storage {return retVal;}++/*** @see org.apache.lucene.gdata.storage.Storage#getFeed(org.apache.lucene.gdata.data.ServerBaseFeed)@@ -270,10 +273,10 @@ public class DB4oStorage implements Storage {if (LOG.isInfoEnabled())LOG.info("Fetching feed for feedID: " + feed.getId()- + "; startindex: " + feed.getStartIndex()+ + "; start-index: " + feed.getStartIndex()+ "; items per page: " + feed.getItemsPerPage());- BaseFeed<BaseFeed, BaseEntry> persistentFeed = getFeedOnly(feed.getId());+ BaseFeed<BaseFeed, BaseEntry> persistentFeed = getFeedOnly(feed.getId(),feed.getServiceType());/** prevent previously added entries in long running storage instances*/@@ -290,7 +293,7 @@ public class DB4oStorage implements Storage {if (size < feed.getStartIndex()) {if (LOG.isDebugEnabled())LOG.debug("no entries found for feed constrain -- feedID: "- + feed.getId() + "; startindex: "+ + feed.getId() + "; start-index: "+ feed.getStartIndex() + "; items per page: "+ feed.getItemsPerPage());return persistentFeed;@@ -311,22 +314,34 @@ public class DB4oStorage implements Storage {}@SuppressWarnings("unchecked")- private BaseFeed<BaseFeed, BaseEntry> getFeedOnly(String feedId)+ private BaseFeed<BaseFeed, BaseEntry> getFeedOnly(final String feedId, final String serviceId)throws StorageException {+ if(!checkService(feedId,serviceId))+ throw new StorageException();Query query = this.container.query();+ query.constrain(ServerBaseFeed.class);+query.constrain(BaseFeed.class);+query.descend("id").constrain(feedId).equal();+ObjectSet set = query.execute();if (set.size() > 1)throw new StorageException("Query for feed id " + feedId+ " returns more than one result");if (set.hasNext())- return (BaseFeed<BaseFeed, BaseEntry>) set.next();- throw new StorageException("can not find feed for given feed id -- "+ return (BaseFeed<BaseFeed, BaseEntry>) set.next();+ throw new ResourceNotFoundException("can not find feed for given feed id -- "+ feedId);}-+ private boolean checkService(String feedId,String serviceId){+ Query query = this.container.query();+ query.constrain(ServerBaseFeed.class);+ query.descend("feed").descend("id").constrain(feedId).equal();+ query.descend("serviceType").constrain(serviceId).equal();+ return query.execute().size() == 1;+ }private ObjectSet getEnriesForFeedID(String feedId) {Query query = this.container.query();query.constrain(DB4oEntry.class);@@ -360,7 +375,7 @@ public class DB4oStorage implements Storage {"Entry query returned not a unique result");if (resultSet.hasNext())return resultSet.next();- throw new StorageException("no entry with entryID: " + id+ throw new ResourceNotFoundException("no entry with entryID: " + id+ " stored -- query returned no result");}@@ -432,7 +447,7 @@ public class DB4oStorage implements Storage {public void deleteAccount(String accountname) throws StorageException {if (accountname == null)throw new StorageException(- "can not delete account -- accountname is null");+ "can not delete account -- account name is null");GDataAccount account = this.getAccount(accountname);refreshPersistentObject(account);if (LOG.isInfoEnabled())@@ -474,7 +489,7 @@ public class DB4oStorage implements Storage {refreshPersistentObject(account);feed.setAccount(account);/*- * service config not requiered in db4o storage.+ * service config not required in db4o storage.* Entries/Feeds don't have to be build from xml*/feed.setServiceConfig(null);@@ -566,7 +581,7 @@ public class DB4oStorage implements Storage {this.container.commit();} catch (Exception e) {LOG- .error("Error occured on persisting changes -- rollback changes");+ .error("Error occurred on persisting changes -- rollback changes");this.container.rollback();throw new StorageException("Can not persist changes -- "+ e.getMessage(), e);@@ -582,7 +597,7 @@ public class DB4oStorage implements Storage {if(feedId == null)throw new StorageException("can not get Service for feed -- feed id is null");if(LOG.isInfoEnabled())- LOG.info("retriving Service for feed -- feed id: "+feedId);+ LOG.info("Retrieving Service for feed -- feed id: "+feedId);Query query = this.container.query();query.constrain(ServerBaseFeed.class);query.descend("feed").descend("id").constrain(feedId);@@ -593,9 +608,10 @@ public class DB4oStorage implements Storage {if (feed.size() < 1)throw new StorageException("can not find feed for given feed id -- "+ feedId);+ServerBaseFeed result = feed.next();if(LOG.isInfoEnabled())- LOG.info("retrived Service for feed -- serviceType: "+result.getServiceType());+ LOG.info("Retrieved Service for feed -- serviceType: "+result.getServiceType());return result.getServiceType();}@@ -605,7 +621,7 @@ public class DB4oStorage implements Storage {public GDataAccount getAccount(String accountName) throws StorageException {if (accountName == null)throw new StorageException(- "Can not get account -- accountname is null");+ "Can not get account -- account name is null");if (LOG.isInfoEnabled())LOG.info("Retrieving account for account name: " + accountName);Query query = this.container.query();@@ -617,7 +633,7 @@ public class DB4oStorage implements Storage {"Account query returned not a unique result -- account name: "+ accountName);if (!set.hasNext())- throw new StorageException(+ throw new ResourceNotFoundException("No such account stored -- query returned not result for account name: "+ accountName);@@ -676,8 +692,8 @@ public class DB4oStorage implements Storage {}/*- * !Caution! -- could instanciate a lot of objects if used with certain classes!!- * refreshs a persistend object with a depth of 100+ * !Caution! -- could instantiate a lot of objects if used with certain classes!!+ * Refresh a persisted object with a depth of 100**/private void refreshPersistentObject(Object o){diff --git a/contrib/gdata-server/src/java/org/apache/lucene/gdata/storage/lucenestorage/ModifiedEntryFilter.java b/contrib/gdata-server/src/java/org/apache/lucene/gdata/storage/lucenestorage/ModifiedEntryFilter.javaindex 0e06120738d..e69de29bb2d 100644--- a/contrib/gdata-server/src/java/org/apache/lucene/gdata/storage/lucenestorage/ModifiedEntryFilter.java+++ b/contrib/gdata-server/src/java/org/apache/lucene/gdata/storage/lucenestorage/ModifiedEntryFilter.java@@ -1,79 +0,0 @@-/**- * Copyright 2004 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.- */--package org.apache.lucene.gdata.storage.lucenestorage;--import java.io.IOException;-import java.util.BitSet;--import org.apache.lucene.index.IndexReader;-import org.apache.lucene.index.Term;-import org.apache.lucene.index.TermDocs;-import org.apache.lucene.search.Filter;--/**- * The {@link ModifiedEntryFilter} filters the given entryIds from the lucene- * {@link org.apache.lucene.search.Hits} set. This filter is used to prevent the- * storage from retrieving already deleted or updated entries still remainig in- * the {@link org.apache.lucene.gdata.storage.lucenestorage.StorageBuffer}.- *- * @see org.apache.lucene.search.Filter- *- * @author Simon Willnauer- *- */-public class ModifiedEntryFilter extends Filter {- /**- * impl Serializable- */- private static final long serialVersionUID = -1551686287704213591L;-- private final String[] entyIds;-- /**- * Creates a new {@link ModifiedEntryFilter}- * @param entryIds the entry id's to filter- *- */- public ModifiedEntryFilter(final String[] entryIds) {- super();- this.entyIds = entryIds;- }-- /**- * @see org.apache.lucene.search.Filter#bits(org.apache.lucene.index.IndexReader)- */- @Override- public BitSet bits(IndexReader reader) throws IOException {- BitSet bitSet = new BitSet(reader.maxDoc());- bitSet.flip(0, reader.maxDoc()); // set all docs- int[] docs = new int[1];- int[] freq = new int[1];- for (String id : this.entyIds) {- if (id != null) {- TermDocs termDocs = reader.termDocs(new Term(- StorageEntryWrapper.FIELD_ENTRY_ID, id));- int count = termDocs.read(docs, freq);- if (count == 1)- bitSet.flip(docs[0]);-- }- }-- return bitSet;- }--}diff --git a/contrib/gdata-server/src/java/org/apache/lucene/gdata/storage/lucenestorage/StorageBuffer.java b/contrib/gdata-server/src/java/org/apache/lucene/gdata/storage/lucenestorage/StorageBuffer.javaindex cacb2297aa3..ceaf4def3ca 100644--- a/contrib/gdata-server/src/java/org/apache/lucene/gdata/storage/lucenestorage/StorageBuffer.java+++ b/contrib/gdata-server/src/java/org/apache/lucene/gdata/storage/lucenestorage/StorageBuffer.java@@ -32,6 +32,7 @@ import java.util.concurrent.locks.ReentrantReadWriteLock;import org.apache.commons.logging.Log;import org.apache.commons.logging.LogFactory;import org.apache.lucene.gdata.storage.lucenestorage.StorageEntryWrapper.StorageOperation;+import org.apache.lucene.gdata.utils.ModifiedEntryFilter;import com.google.gdata.data.BaseEntry;import com.google.gdata.data.ExtensionProfile;diff --git a/contrib/gdata-server/src/java/org/apache/lucene/gdata/storage/lucenestorage/StorageCoreController.java b/contrib/gdata-server/src/java/org/apache/lucene/gdata/storage/lucenestorage/StorageCoreController.javaindex bcddf0fe2a2..da695f697a7 100644--- a/contrib/gdata-server/src/java/org/apache/lucene/gdata/storage/lucenestorage/StorageCoreController.java+++ b/contrib/gdata-server/src/java/org/apache/lucene/gdata/storage/lucenestorage/StorageCoreController.java@@ -1,3 +1,18 @@+/**+ * Copyright 2004 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.+ */package org.apache.lucene.gdata.storage.lucenestorage;import java.io.File;@@ -19,7 +34,7 @@ import org.apache.lucene.gdata.storage.StorageController;import org.apache.lucene.gdata.storage.StorageException;import org.apache.lucene.gdata.storage.lucenestorage.recover.RecoverController;import org.apache.lucene.gdata.storage.lucenestorage.recover.RecoverException;-import org.apache.lucene.gdata.storage.lucenestorage.util.ReferenceCounter;+import org.apache.lucene.gdata.utils.ReferenceCounter;import org.apache.lucene.index.IndexModifier;import org.apache.lucene.search.IndexSearcher;import org.apache.lucene.store.Directory;@@ -212,7 +227,7 @@ public class StorageCoreController implements StorageController {* <p>* if the reference counter has no remaining references the resource e.g.* the <tt>StorageQuery</tt> will be closed. This ensures that a- * <tt>StorageQuery</tt> instance will be arround as long as needed and+ * <tt>StorageQuery</tt> instance will be around as long as needed and* the resources will be released. The reference counter should be* decremented by clients after finished using the query instance.* </p>@@ -232,7 +247,7 @@ public class StorageCoreController implements StorageController {this.storageQuery = getNewStorageQueryHolder(new StorageQuery(this.currentBuffer, this.searcher));if (LOG.isInfoEnabled())- LOG.info("Relese new StorageQuery");+ LOG.info("Release new StorageQuery");}this.storageQuery.increamentReference();return this.storageQuery;@@ -271,7 +286,7 @@ public class StorageCoreController implements StorageController {* changes available for searching.** @throws IOException -- * if an IO exception occures+ * if an IO exception occurs*/protected void registerNewStorageQuery() throws IOException {if(this.isClosed.get())@@ -324,7 +339,7 @@ public class StorageCoreController implements StorageController {** @return - a new modifier* @throws IOException -- * if an IO exception occures+ * if an IO exception occurs*/protected IndexModifier createIndexModifier() throws IOException {if(this.isClosed.get())@@ -380,7 +395,7 @@ public class StorageCoreController implements StorageController {* Forces the StorageModifier to write all buffered changes.** @throws IOException -- * if an IO exception occures+ * if an IO exception occurs**/public void forceWrite() throws IOException {@@ -492,7 +507,7 @@ public class StorageCoreController implements StorageController {/*** An integer value after how many changes to the StorageModifier the- * buffered changes will be persisted / wirtten to the index+ * buffered changes will be persisted / written to the index** @return - the persist factor*/diff --git a/contrib/gdata-server/src/java/org/apache/lucene/gdata/storage/lucenestorage/StorageImplementation.java b/contrib/gdata-server/src/java/org/apache/lucene/gdata/storage/lucenestorage/StorageImplementation.javaindex 4d2b4cc3da8..36e216520aa 100644--- a/contrib/gdata-server/src/java/org/apache/lucene/gdata/storage/lucenestorage/StorageImplementation.java+++ b/contrib/gdata-server/src/java/org/apache/lucene/gdata/storage/lucenestorage/StorageImplementation.java@@ -31,7 +31,7 @@ import org.apache.lucene.gdata.storage.Storage;import org.apache.lucene.gdata.storage.StorageController;import org.apache.lucene.gdata.storage.StorageException;import org.apache.lucene.gdata.storage.lucenestorage.StorageEntryWrapper.StorageOperation;-import org.apache.lucene.gdata.storage.lucenestorage.util.ReferenceCounter;+import org.apache.lucene.gdata.utils.ReferenceCounter;import com.google.gdata.data.BaseEntry;import com.google.gdata.data.BaseFeed;@@ -42,7 +42,7 @@ import com.google.gdata.data.BaseFeed;* StorageImplementation provides access to the* {@link org.apache.lucene.gdata.storage.lucenestorage.StorageQuery} and the* {@link org.apache.lucene.gdata.storage.lucenestorage.StorageModifier}. This- * class will be instanciated per client request.+ * class will be instantiated per client request.***@@ -80,7 +80,7 @@ public class StorageImplementation implements Storage {if (entry == null)throw new StorageException("entry is null");if(entry.getFeedId() == null)- throw new StorageException("feedid is null");+ throw new StorageException("feed-id is null");if(entry.getVersion() != 1)throw new StorageException("entry version must be 1");if(entry.getServiceConfig() == null)@@ -223,7 +223,7 @@ public class StorageImplementation implements Storage {if (feed == null)throw new StorageException("feed is null");if (LOG.isInfoEnabled())- LOG.info("get feed: " + feed.getId() + " startindex: "+ LOG.info("get feed: " + feed.getId() + " start-index: "+ feed.getStartIndex() + " resultCount: "+ feed.getItemsPerPage());ReferenceCounter<StorageQuery> query = null;@@ -514,7 +514,7 @@ public class StorageImplementation implements Storage {public String getAccountNameForFeedId(String feedId)throws StorageException {if (feedId == null)- throw new StorageException("feedid must not be null");+ throw new StorageException("feed-id must not be null");ReferenceCounter<StorageQuery> query = null;try {query = this.controller.getStorageQuery();diff --git a/contrib/gdata-server/src/java/org/apache/lucene/gdata/storage/lucenestorage/StorageQuery.java b/contrib/gdata-server/src/java/org/apache/lucene/gdata/storage/lucenestorage/StorageQuery.javaindex 651e3a8ce00..00b327e9f22 100644--- a/contrib/gdata-server/src/java/org/apache/lucene/gdata/storage/lucenestorage/StorageQuery.java+++ b/contrib/gdata-server/src/java/org/apache/lucene/gdata/storage/lucenestorage/StorageQuery.java@@ -26,11 +26,11 @@ import java.util.List;import org.apache.commons.logging.Log;import org.apache.commons.logging.LogFactory;import org.apache.lucene.document.Document;-import org.apache.lucene.document.Field;import org.apache.lucene.gdata.data.GDataAccount;import org.apache.lucene.gdata.server.GDataEntityBuilder;import org.apache.lucene.gdata.server.registry.ProvidedService;import org.apache.lucene.gdata.storage.StorageException;+import org.apache.lucene.gdata.utils.ModifiedEntryFilter;import org.apache.lucene.index.Term;import org.apache.lucene.search.BooleanClause;import org.apache.lucene.search.BooleanQuery;@@ -48,7 +48,7 @@ import com.google.gdata.data.DateTime;import com.google.gdata.util.ParseException;/**- * StorageQuery wrapps a Lucene {@link org.apache.lucene.search.IndexSearcher}+ * StorageQuery wraps a Lucene {@link org.apache.lucene.search.IndexSearcher}* and a {@link org.apache.lucene.gdata.storage.lucenestorage.StorageBuffer} to* perform all request on the lucene storage. The wrapped components are thread -* safe.@@ -109,7 +109,7 @@ public class StorageQuery {}return this.searcher.search(query, new ModifiedEntryFilter(this.buffer- .getExculdList()));+ .getExculdList(),StorageEntryWrapper.FIELD_ENTRY_ID));}/*@@ -120,7 +120,7 @@ public class StorageQuery {TermQuery query = new TermQuery(new Term(StorageEntryWrapper.FIELD_FEED_REFERENCE, feedId));return this.searcher.search(query, new ModifiedEntryFilter(this.buffer- .getExculdList()), sort);+ .getExculdList(),StorageEntryWrapper.FIELD_ENTRY_ID), sort);}@@ -135,21 +135,21 @@ public class StorageQuery {* deleted entries. These entries must be found!!*/return this.searcher.search(termQuery, new ModifiedEntryFilter(- this.buffer.getExculdList()));+ this.buffer.getExculdList(),StorageEntryWrapper.FIELD_ENTRY_ID));}/*** This method fetches the latest feed entries from the storage. Feed- * ususaly requested via a search query or as a simple query to the REST+ * usually requested via a search query or as a simple query to the REST* interface.* <p>- * The REST interface requestes all the entries from a Storage. The Storage+ * The REST interface requests all the entries from a Storage. The Storage* retrieves the entries corresponding to the parameters specified. This* method first requests the latest entries or updated entries from the- * {@link StorageBuffer}. If the buffer already contains enought entries- * for the the specified result count the entires will be returned. If not,- * the underlaying lucene index will be searcher for all documents of the+ * {@link StorageBuffer}. If the buffer already contains enough entries+ * for the the specified result count the entries will be returned. If not,+ * the underlying lucene index will be searcher for all documents of the* specified feed sorted by storing timestamp desc.* </p>* <p>@@ -164,10 +164,10 @@ public class StorageQuery {* @param resultCount -* how many entries are requested* @param startIndex -- * the offset of the entriy to start from.+ * the offset of the entry to start from.* @param config -- * the FeedInstanceConfiguration contaning extension profile used- * to create the entriy instances+ * the FeedInstanceConfiguration containing extension profile used+ * to create the entry instances* @return - an ordered list of {@link BaseEntry} objects, or an empty list* if no entries could be found* @throws IOException -@@ -214,7 +214,7 @@ public class StorageQuery {}} else {/*- * if the buffersize is less than the startindex the buffersize must+ * if the buffer size is less than the start index the buffer size must* be considered. Sublists would not be a repeatable read part of* the whole list*/@@ -251,7 +251,7 @@ public class StorageQuery {/*** This method retrieves a single entry from the storage. If the* {@link StorageBuffer} does not contain the requested entry the- * underlaying storage index will be searched.+ * underlying storage index will be searched.* <p>* The Entry will be searched in a feed context specified by the given feed* ID@@ -260,10 +260,10 @@ public class StorageQuery {* @param entryId -* the entry to fetch* @param feedId -- * the feedid eg. feed context+ * the feed id e.g. feed context* @param config -- * the FeedInstanceConfiguration contaning extension profile used- * to create the entriy instances+ * the FeedInstanceConfiguration containing extension profile used+ * to create the entry instances* @return - the requested {@link BaseEntry} or <code>null</code> if the* entry can not be found* @throws IOException -@@ -297,9 +297,9 @@ public class StorageQuery {/*** Fetches the requested entries from the storage. The given list contains- * entry ids to be looked up in the storage. First the {@link StorageBuffer}- * will be queried for the entry ids. If not all of the entries remain in- * the buffer the underlaying lucene index will be searched. The entries are+ * entry id's to be looked up in the storage. First the {@link StorageBuffer}+ * will be queried for the entry id's. If not all of the entries remain in+ * the buffer the underlying lucene index will be searched. The entries are* not guaranteed to be in the same order as they are in the given id list.* Entry ID's not found in the index or the buffer will be omitted.* <p>@@ -308,12 +308,12 @@ public class StorageQuery {* </p>** @param entryIds -- * the entriy ids to fetch.+ * the entry id's to fetch.* @param feedId -- * the feed id eg. feed context.+ * the feed id e.g. feed context.* @param config -- * the FeedInstanceConfiguration contaning extension profile used- * to create the entriy instances+ * the FeedInstanceConfiguration containing extension profile used+ * to create the entry instances** @return - the list of entries corresponding to the given entry id list.* @throws IOException -@@ -395,7 +395,7 @@ public class StorageQuery {* not be reused after invoking this method.** @throws IOException -- * if the resouces can not be closed+ * if the resources can not be closed*/public void close() throws IOException {this.searcher.close();@@ -419,7 +419,7 @@ public class StorageQuery {}/**- * Looks up the feedtype for the given feed ID+ * Looks up the feed type for the given feed ID** @param feedID -* the feed IDdiff --git a/contrib/gdata-server/src/java/org/apache/lucene/gdata/storage/lucenestorage/util/ReferenceCounter.java b/contrib/gdata-server/src/java/org/apache/lucene/gdata/storage/lucenestorage/util/ReferenceCounter.javaindex 676e000110a..e69de29bb2d 100644--- a/contrib/gdata-server/src/java/org/apache/lucene/gdata/storage/lucenestorage/util/ReferenceCounter.java+++ b/contrib/gdata-server/src/java/org/apache/lucene/gdata/storage/lucenestorage/util/ReferenceCounter.java@@ -1,77 +0,0 @@-/**- * Copyright 2004 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.- */--package org.apache.lucene.gdata.storage.lucenestorage.util;--import java.util.concurrent.atomic.AtomicInteger;--/**- * A reference counting utility. This is use to keep track of released objects- * of <code>Type</code>.- *- * @author Simon Willnauer- * @param <Type> -- * the type of the object- *- */-public abstract class ReferenceCounter<Type> {- protected final Type resource;-- private AtomicInteger refcounter = new AtomicInteger();-- /**- * @param resource -- * the resouce to track- *- */- public ReferenceCounter(Type resource) {- this.resource = resource;- }-- /**- *- * Decrements the reference. If no references remain the- * {@link ReferenceCounter#close()} method will be inoked;- */- public final void decrementRef() {- if (this.refcounter.decrementAndGet() == 0)- close();- }-- /**- * A custom implementation. Performs an action if no reference remaining- *- */- protected abstract void close();-- /**- * Increments the reference- *- * @return the refernece object- */- public final ReferenceCounter<Type> increamentReference() {- this.refcounter.incrementAndGet();- return this;- }-- /**- * @return - the resource to keep track of- */- public final Type get() {- return this.resource;- }--}diff --git a/contrib/gdata-server/src/java/org/apache/lucene/gdata/utils/ModifiedEntryFilter.java b/contrib/gdata-server/src/java/org/apache/lucene/gdata/utils/ModifiedEntryFilter.javanew file mode 100755index 00000000000..b6b2b1a75d3--- /dev/null+++ b/contrib/gdata-server/src/java/org/apache/lucene/gdata/utils/ModifiedEntryFilter.java@@ -0,0 +1,81 @@+/**+ * Copyright 2004 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.+ */++package org.apache.lucene.gdata.utils;++import java.io.IOException;+import java.util.BitSet;++import org.apache.lucene.index.IndexReader;+import org.apache.lucene.index.Term;+import org.apache.lucene.index.TermDocs;+import org.apache.lucene.search.Filter;++/**+ * The {@link ModifiedEntryFilter} filters the given entryIds from the lucene+ * {@link org.apache.lucene.search.Hits} set. This filter is used to prevent the+ * storage from retrieving already deleted or updated entries still remaining in+ * the {@link org.apache.lucene.gdata.storage.lucenestorage.StorageBuffer}.+ *+ * @see org.apache.lucene.search.Filter+ *+ * @author Simon Willnauer+ *+ */+public class ModifiedEntryFilter extends Filter {+ /*+ * implements Serializable+ */+ private static final long serialVersionUID = -1551686287704213591L;++ private final String[] entyIds;+ private final String searchField;+ /**+ * Creates a new {@link ModifiedEntryFilter}+ * @param entryIds the entry id's to filter+ * @param field - the field, the id is stored+ *+ */+ public ModifiedEntryFilter(final String[] entryIds,String field) {+ super();+ this.searchField = field;+ this.entyIds = entryIds;+ }++ /**+ * @see org.apache.lucene.search.Filter#bits(org.apache.lucene.index.IndexReader)+ */+ @Override+ public BitSet bits(IndexReader reader) throws IOException {+ BitSet bitSet = new BitSet(reader.maxDoc());+ bitSet.flip(0, reader.maxDoc()); // set all documents+ int[] docs = new int[1];+ int[] freq = new int[1];+ for (String id : this.entyIds) {+ if (id != null) {+ TermDocs termDocs = reader.termDocs(new Term(+ this.searchField, id));+ int count = termDocs.read(docs, freq);+ if (count == 1)+ bitSet.flip(docs[0]);++ }+ }++ return bitSet;+ }++}diff --git a/contrib/gdata-server/src/java/org/apache/lucene/gdata/utils/ReferenceCounter.java b/contrib/gdata-server/src/java/org/apache/lucene/gdata/utils/ReferenceCounter.javanew file mode 100755index 00000000000..7f56b4597aa--- /dev/null+++ b/contrib/gdata-server/src/java/org/apache/lucene/gdata/utils/ReferenceCounter.java@@ -0,0 +1,80 @@+/**+ * Copyright 2004 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.+ */++package org.apache.lucene.gdata.utils;++import java.util.concurrent.atomic.AtomicInteger;++/**+ * A reference counting utility. This is use to keep track of released objects+ * of <code>Type</code>.+ *+ * @author Simon Willnauer+ * @param <Type> -+ * the type of the object+ *+ */+public abstract class ReferenceCounter<Type> {+ protected final Type resource;++ private AtomicInteger refcounter = new AtomicInteger();++ /**+ * @param resource -+ * the resource to track+ *+ */+ public ReferenceCounter(Type resource) {+ this.resource = resource;+ }++ /**+ *+ * Decrements the reference. If no references remain the+ * {@link ReferenceCounter#close()} method will be invoked;+ */+ public final void decrementRef() {+ /*+ * close if less or equals 0+ */+ if (this.refcounter.decrementAndGet() <= 0)+ close();+ }++ /**+ * A custom implementation. Performs an action if no reference remaining+ *+ */+ protected abstract void close();++ /**+ * Increments the reference+ *+ * @return the reference object+ */+ public final ReferenceCounter<Type> increamentReference() {+ this.refcounter.incrementAndGet();+ return this;+ }++ /**+ * @return - the resource to keep track of+ */+ public final Type get() {+ return this.resource;+ }++}diff --git a/contrib/gdata-server/src/java/org/apache/lucene/gdata/utils/ReflectionUtils.java b/contrib/gdata-server/src/java/org/apache/lucene/gdata/utils/ReflectionUtils.javanew file mode 100755index 00000000000..6a645faa2a5--- /dev/null+++ b/contrib/gdata-server/src/java/org/apache/lucene/gdata/utils/ReflectionUtils.java@@ -0,0 +1,193 @@+/**+ * Copyright 2004 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.+ */++package org.apache.lucene.gdata.utils;++import java.lang.reflect.Constructor;++/**+ * A collection of static helper methods solve common reflection problems+ *+ * @author Simon Willnauer+ *+ */+public class ReflectionUtils {++ /**+ * Check if the given type implements a given super type+ * @param typeToCheck - type supposed to implement an interface+ * @param superType - the interface to be implemented by the type to check+ * @return <code>true</code> if and only if the super type is above in the type hierarchy of the given type, otherwise <code>false</code>+ */+ public static boolean implementsType(Class typeToCheck, Class superType) {+ if(superType == null)+ return false;+ if(!superType.isInterface())+ return false;+ if (typeToCheck == null)+ return false;+ if (typeToCheck.equals(Object.class))+ return false;+ if (typeToCheck.equals(superType))+ return true;+ Class[] interfaces = typeToCheck.getInterfaces();+ for (int i = 0; i < interfaces.length; i++) {+ if (implementsType(interfaces[i], superType))+ return true;+ }+ return implementsType(typeToCheck.getSuperclass(),superType);++ }+ /**+ * Check if the given type extends a given super type+ * @param typeToCheck - type supposed to extend an specific type+ * @param superType - the type to be extended by the type to check+ * @return <code>true</code> if and only if the super type is above in the type hierarchy of the given type, otherwise <code>false</code>+ */+ public static boolean extendsType(Class typeToCheck, Class superType) {+ if (typeToCheck == null)+ return false;+ if (typeToCheck.equals(Object.class))+ return false;+ if (typeToCheck.equals(superType))+ return true;++ return extendsType(typeToCheck.getSuperclass(),superType);+ }+ /**+ * This method combines the extendsType and implementsType and checks interfaces and classes+ * @param typeToCheck - type supposed to extend / implement an specific type+ * @param superType - the type to be extended / implemented by the type to check+ * @return <code>true</code> if and only if the super type is above in the type hierarchy of the given type, otherwise <code>false</code>+ */+ public static boolean isTypeOf(Class typeToCheck, Class superType){+ return extendsType(typeToCheck,superType)||implementsType(typeToCheck,superType);+ }++ /**+ * @param type - the type to check+ * @param parameter - the constructor parameter+ * @return <code>true</code> if and only if the type has a visible constructor with the desired parameters+ */+ public static boolean hasDesiredConstructor(Class type, Class[] parameter){+ try{+ return type.getConstructor(parameter) != null;++ }catch (Exception e) {+ return false;+ }+ }+++/**+ * @param <T> the type of the class to instantiate+ * @param clazz - class object of the type+ * @return a new instance of T++ */+@SuppressWarnings("unchecked")+public static <T> T getDefaultInstance(Class<T> clazz) {+ if(clazz == null)+ throw new ReflectionException("class must not be null");++ try{+ Constructor constructor = clazz.getConstructor(new Class[]{});+ return (T) constructor.newInstance(new Object[]{});+ }catch (Exception e) {+ throw new ReflectionException("can not instantiate type of class "+clazz.getName(),e);+ }+}+++/**+ * This method calls {@link Class#newInstance()} to get a new instance. Use with care!+ * @param clazz - the class to instantiate+ * @return <code>true</code> if an instance could be created, otherwise false;+ */+public static boolean canCreateInstance(Class clazz){+ if(clazz == null)+ return false;+ if(clazz.isPrimitive())+ clazz = getPrimitiveWrapper(clazz);+ try{+ Object o = clazz.newInstance();+ return o != null;+ }catch (Throwable e) {+ return false;+ }+}+/**+ * Returns the wrapper type for the given primitive type. Wrappers can be+ * easily instantiated via reflection and will be boxed by the VM+ * @param primitive - the primitive type+ * @return - the corresponding wrapper type+ */+public static final Class getPrimitiveWrapper(Class primitive) {+ if(primitive == null )+ throw new ReflectionException("primitive must not be null");+ if(!primitive.isPrimitive())+ throw new ReflectionException("given class is not a primitive");++ if (primitive == Integer.TYPE)+ return Integer.class;+ if (primitive == Float.TYPE)+ return Float.class;+ if (primitive == Long.TYPE)+ return Long.class;+ if (primitive == Short.TYPE)+ return Short.class;+ if (primitive == Byte.TYPE)+ return Byte.class;+ if (primitive == Double.TYPE)+ return Double.class;+ if (primitive == Boolean.TYPE)+ return Boolean.class;++ return primitive;+}++/**+ * Exception wrapper for all thrown exception in the ReflectionUtils methods+ * @author Simon Willnauer+ *+ */+public static class ReflectionException extends RuntimeException{++ /**+ *+ */+ private static final long serialVersionUID = -4855060602565614280L;++ /**+ * @param message - the exception message+ * @param cause - the exception root cause+ */+ public ReflectionException(String message, Throwable cause) {+ super(message, cause);+ // TODO Auto-generated constructor stub+ }++ /**+ * @param message - the exception message+ */+ public ReflectionException(String message) {+ super(message);+ // TODO Auto-generated constructor stub+ }++}++}diff --git a/contrib/gdata-server/src/test/org/apache/lucene/gdata/data/TestGDataUser.java b/contrib/gdata-server/src/test/org/apache/lucene/gdata/data/TestGDataUser.javaindex bed8956d52a..ec2a877746a 100644--- a/contrib/gdata-server/src/test/org/apache/lucene/gdata/data/TestGDataUser.java+++ b/contrib/gdata-server/src/test/org/apache/lucene/gdata/data/TestGDataUser.java@@ -1,18 +1,34 @@+/**+ * Copyright 2004 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.+ */package org.apache.lucene.gdata.data;-import java.net.MalformedURLException;-import java.net.URL;+import junit.framework.TestCase;import org.apache.lucene.gdata.data.GDataAccount.AccountRole;-import junit.framework.TestCase;-+/**+ * @author Simon Willnauer+ *+ */public class TestGDataUser extends TestCase {private GDataAccount user;@Overrideprotected void setUp() throws Exception {this.user = new GDataAccount();- this.user.setName("simon");+ this.user.setName("simonW");super.setUp();}@@ -26,6 +42,7 @@ public class TestGDataUser extends TestCase {* Test method for 'org.apache.lucene.gdata.data.GDataUser.isUserInRole(UserRole)'*/public void testIsUserInRole() {+ assertFalse(this.user.isUserInRole(null));assertTrue(this.user.isUserInRole(AccountRole.USER));assertFalse(this.user.isUserInRole(AccountRole.ENTRYAMINISTRATOR));this.user.setRole(AccountRole.ENTRYAMINISTRATOR);@@ -44,6 +61,19 @@ public class TestGDataUser extends TestCase {this.user.setRole(AccountRole.USERADMINISTRATOR);assertEquals(15,this.user.getRolesAsInt());+++ }++ public void testIsUserInRoleInt(){+ assertFalse(GDataAccount.isInRole(1,AccountRole.ENTRYAMINISTRATOR));+ assertFalse(GDataAccount.isInRole(1,AccountRole.FEEDAMINISTRATOR));+ assertTrue(GDataAccount.isInRole(3,AccountRole.ENTRYAMINISTRATOR));+ assertTrue(GDataAccount.isInRole(15,AccountRole.ENTRYAMINISTRATOR));+ assertTrue(GDataAccount.isInRole(3,AccountRole.USER));+ assertTrue(GDataAccount.isInRole(15,AccountRole.USERADMINISTRATOR));+ assertFalse(GDataAccount.isInRole(7,AccountRole.USERADMINISTRATOR));+ assertFalse(GDataAccount.isInRole(7,null));}/*@@ -62,7 +92,40 @@ public class TestGDataUser extends TestCase {assertEquals(4,this.user.getRoles().size());}-++ public void testEquals(){+ assertTrue(this.user.equals(this.user));+ GDataAccount a = new GDataAccount();+ a.setName(this.user.getName());+ assertTrue(this.user.equals(a));+ a.setName("someOtheraccount");+ assertFalse(this.user.equals(a));+ assertFalse(this.user.equals(null));+ assertFalse(this.user.equals(new String()));+ assertFalse(new GDataAccount().equals(new GDataAccount()));+ }+ public void testHashCode(){+ assertEquals(this.user.hashCode(),this.user.hashCode());+ assertFalse(this.user.hashCode()== this.user.getName().hashCode());+ GDataAccount a = new GDataAccount();+ a.setName(this.user.getName());+ assertEquals(this.user.hashCode(),a.hashCode());+ a.setName(null);+ assertFalse(a.hashCode()== this.user.hashCode());+ }++ public void testReqValuesSet(){+ assertFalse(this.user.requiredValuesSet());+ this.user.setPassword("hello");+ assertFalse(this.user.requiredValuesSet());+ this.user.setPassword("helloworld");+ assertTrue(this.user.requiredValuesSet());+ assertFalse(new GDataAccount().requiredValuesSet());+ }++ public void testToStringPrevNulPEx(){+ assertNotNull(this.user.toString());+ }diff --git a/contrib/gdata-server/src/test/org/apache/lucene/gdata/search/TestStandardGdataSearcher.java b/contrib/gdata-server/src/test/org/apache/lucene/gdata/search/TestStandardGdataSearcher.javanew file mode 100755index 00000000000..26ee9df89fb--- /dev/null+++ b/contrib/gdata-server/src/test/org/apache/lucene/gdata/search/TestStandardGdataSearcher.java@@ -0,0 +1,222 @@+/**+ * Copyright 2004 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.+ */+package org.apache.lucene.gdata.search;++import java.io.IOException;+import java.util.ArrayList;+import java.util.List;++import junit.framework.TestCase;++import org.apache.lucene.analysis.standard.StandardAnalyzer;+import org.apache.lucene.document.Document;+import org.apache.lucene.document.Field;+import org.apache.lucene.gdata.search.StandardGdataSearcher;+import org.apache.lucene.gdata.search.index.IndexDocument;+import org.apache.lucene.gdata.utils.ReferenceCounter;+import org.apache.lucene.index.IndexWriter;+import org.apache.lucene.index.Term;+import org.apache.lucene.search.Hits;+import org.apache.lucene.search.IndexSearcher;+import org.apache.lucene.search.Query;+import org.apache.lucene.search.TermQuery;+import org.apache.lucene.store.Directory;+import org.apache.lucene.store.RAMDirectory;++/**+ * @author Simon Willnauer+ *+ */+public class TestStandardGdataSearcher extends TestCase {+ private Directory dir;++ private int amountDocuments = 30;++ private static final String FIELDNAME = "fname";++ private static final String FIELDVALUE = "foobar";++ private ReferenceCounter<IndexSearcher> searcher;++ private StandardGdataSearcher gdataSearcher;++ private List<String> idlist;++ private String feedId = "myFeed";++ protected void setUp() throws Exception {+ this.dir = new RAMDirectory();+ IndexWriter writer = new IndexWriter(dir, new StandardAnalyzer(), true);+ this.idlist = new ArrayList<String>();+ for (int i = 0; i < this.amountDocuments; i++) {+ Document doc = new Document();+ doc.add(new Field(IndexDocument.FIELD_FEED_ID, this.feedId,+ Field.Store.YES, Field.Index.UN_TOKENIZED));+ doc.add(new Field(IndexDocument.FIELD_ENTRY_ID, "" + i,+ Field.Store.YES, Field.Index.UN_TOKENIZED));+ doc.add(new Field(FIELDNAME, FIELDVALUE, Field.Store.YES,+ Field.Index.UN_TOKENIZED));+ writer.addDocument(doc);+ this.idlist.add("" + i);+ }+ writer.close();+ this.searcher = new TestRefcounter(new IndexSearcher(this.dir));+ this.searcher.increamentReference();+ this.gdataSearcher = new StandardGdataSearcher(this.searcher);+ }++ protected void tearDown() throws Exception {+ this.searcher.decrementRef();+ StandardGdataSearcher.flushFilterCache();+ }++ /*+ * Test method for+ * 'org.apache.lucene.gdata.search.StandardGdataSearcher.StandardGdataSearcher(ReferenceCounter<IndexSearcher>)'+ */+ public void testStandardGdataSearcher() {+ try {+ new StandardGdataSearcher(null);+ fail("searcher ref is null");+ } catch (IllegalArgumentException e) {++ }+ new StandardGdataSearcher(this.searcher);+ }++ /*+ * Test method for+ * 'org.apache.lucene.gdata.search.StandardGdataSearcher.search(Query, int,+ * int)'+ */+ public void testSearch() throws IOException {+ Query q = new TermQuery(new Term(FIELDNAME, FIELDVALUE));+ Hits hits = this.searcher.get().search(q);+ assertEquals(amountDocuments, hits.length());+ List<String> returnValue = this.gdataSearcher.search(q,+ this.amountDocuments, 0,this.feedId);+ assertEquals(amountDocuments, returnValue.size());+ assertTrue(returnValue.containsAll(this.idlist));+ try {+ this.gdataSearcher.search(null, 1, 0,this.feedId);+ fail("searcher is null");+ } catch (RuntimeException e) {+ }++ try {+ this.gdataSearcher.search(q, -1, 5,this.feedId);+ fail("hitcount is less than 0");+ } catch (IllegalArgumentException e) {}+ try {+ this.gdataSearcher.search(q, 4, -1,this.feedId);+ fail("offset is less than 0");+ } catch (IllegalArgumentException e) {}+ try {+ this.gdataSearcher.search(q, 4, 5,null);+ fail("feed id is null");+ } catch (IllegalArgumentException e) {}++ returnValue = this.gdataSearcher.search(q,this.amountDocuments, 0,"SomeOtherFeed");+ assertEquals(0,returnValue.size());+++ }++ /*+ * Test method for+ * 'org.apache.lucene.gdata.search.StandardGdataSearcher.collectHits(Hits,+ * int, int)'+ */+ public void testCollectHits() throws IOException {+ Query q = new TermQuery(new Term(FIELDNAME, FIELDVALUE));+ Hits hits = this.searcher.get().search(q);+ assertEquals(amountDocuments, hits.length());+ List<String> returnValue = this.gdataSearcher.collectHits(hits, 1, 0);+ assertEquals(hits.doc(0).getField(IndexDocument.FIELD_ENTRY_ID)+ .stringValue(), returnValue.get(0));++ returnValue = this.gdataSearcher.collectHits(hits, 1, 1);+ assertEquals(hits.doc(0).getField(IndexDocument.FIELD_ENTRY_ID)+ .stringValue(), returnValue.get(0));++ returnValue = this.gdataSearcher.collectHits(hits, 1,+ this.amountDocuments);+ assertEquals(1, returnValue.size());+ assertEquals(hits.doc(this.amountDocuments - 1).getField(+ IndexDocument.FIELD_ENTRY_ID).stringValue(), returnValue.get(0));++ returnValue = this.gdataSearcher.collectHits(hits, 10,+ this.amountDocuments);+ assertEquals(1, returnValue.size());+ assertEquals(hits.doc(this.amountDocuments - 1).getField(+ IndexDocument.FIELD_ENTRY_ID).stringValue(), returnValue.get(0));++ returnValue = this.gdataSearcher.collectHits(hits, 50, 0);+ assertEquals(this.amountDocuments, returnValue.size());+ assertTrue(returnValue.containsAll(this.idlist));++ returnValue = this.gdataSearcher.collectHits(hits, 1, 5);+ assertEquals(1, returnValue.size());+ assertEquals(hits.doc(4).getField(IndexDocument.FIELD_ENTRY_ID)+ .stringValue(), returnValue.get(0));++ returnValue = this.gdataSearcher.collectHits(hits, 50,+ this.amountDocuments);+ assertEquals(1, returnValue.size());+ assertEquals(hits.doc(this.amountDocuments - 1).getField(+ IndexDocument.FIELD_ENTRY_ID).stringValue(), returnValue.get(0));++ returnValue = this.gdataSearcher.collectHits(hits, 1,+ this.amountDocuments + 1);+ assertEquals(0, returnValue.size());++ }++ /*+ * Test method for+ * 'org.apache.lucene.gdata.search.StandardGdataSearcher.close()'+ */+ public void testClose() throws IOException {+ StandardGdataSearcher s = new StandardGdataSearcher(new TestRefcounter(+ new IndexSearcher(this.dir)));+ s.close();+ try {+ s.search(null, 0, 0,this.feedId);+ fail("searcher is closed");+ } catch (IllegalStateException e) {+ }++ }++ private static class TestRefcounter extends ReferenceCounter<IndexSearcher> {++ public TestRefcounter(IndexSearcher resource) {+ super(resource);+ // TODO Auto-generated constructor stub+ }++ @Override+ protected void close() {+ try {+ this.resource.close();+ } catch (Exception e) {+ // TODO: handle exception+ }+ }++ }++}diff --git a/contrib/gdata-server/src/test/org/apache/lucene/gdata/search/analysis/IndexableStub.java b/contrib/gdata-server/src/test/org/apache/lucene/gdata/search/analysis/IndexableStub.javanew file mode 100755index 00000000000..c1c526af4cb--- /dev/null+++ b/contrib/gdata-server/src/test/org/apache/lucene/gdata/search/analysis/IndexableStub.java@@ -0,0 +1,88 @@+/**+ * Copyright 2004 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.+ */+package org.apache.lucene.gdata.search.analysis;++import java.lang.reflect.InvocationHandler;+import java.lang.reflect.Method;+import java.lang.reflect.Proxy;++import javax.xml.xpath.XPathExpressionException;++import org.w3c.dom.NamedNodeMap;+import org.w3c.dom.Node;++/**+ * @author Simon Willnauer+ *+ */+public class IndexableStub extends Indexable {++ private String content;+ private boolean retNull;+ int times = 1;+ int count = 0;+ IndexableStub() {+ super(null);++ }+ public void returnProxyTimes(int times){+ this.times = times;+ }+ public void setReturnNull(boolean returnNull){+ this.retNull = returnNull;+ }+ public void setReturnValueTextContent(String content){+ this.content = content;+ }+ @Override+ public Node applyPath(String xPath) throws XPathExpressionException {+ if(xPath == null)+ throw new XPathExpressionException("path is null");+ if(this.retNull)+ return null;+ if(times == count)+ return null;+ times++;+ return (Node)Proxy.newProxyInstance(this.getClass().getClassLoader(),new Class[] {Node.class,NamedNodeMap.class},new Handler(this.content));++ }++ private static class Handler implements InvocationHandler{+ String returnValue;+ public Handler(String toReturn){+ this.returnValue = toReturn;+ }+ public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {+ if(method.getName().equals("getNextSibling")){+ return null;+ }+ if(method.getReturnType() == String.class)+ return this.returnValue;+ if(method.getReturnType() == Node.class)++ return (Node)Proxy.newProxyInstance(this.getClass().getClassLoader(),new Class[] {Node.class,NamedNodeMap.class},new Handler(this.returnValue));+ if(method.getReturnType() == NamedNodeMap.class)+ return (NamedNodeMap)Proxy.newProxyInstance(this.getClass().getClassLoader(),new Class[] {Node.class,NamedNodeMap.class},new Handler(this.returnValue));+ return null;++ }++ }++++}+diff --git a/contrib/gdata-server/src/test/org/apache/lucene/gdata/search/analysis/TestContentStrategy.java b/contrib/gdata-server/src/test/org/apache/lucene/gdata/search/analysis/TestContentStrategy.javanew file mode 100755index 00000000000..59f4e70b937--- /dev/null+++ b/contrib/gdata-server/src/test/org/apache/lucene/gdata/search/analysis/TestContentStrategy.java@@ -0,0 +1,130 @@+/**+ * Copyright 2004 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.+ */+package org.apache.lucene.gdata.search.analysis;++import org.apache.lucene.document.Field;+import org.apache.lucene.document.Field.Index;+import org.apache.lucene.document.Field.Store;+import org.apache.lucene.gdata.data.ServerBaseEntry;+import org.apache.lucene.gdata.search.config.IndexSchemaField;+import org.apache.lucene.gdata.search.index.GdataIndexerException;+import org.w3c.dom.Node;++import junit.framework.TestCase;++public class TestContentStrategy extends TestCase {+ private static final String FIELD = "foo";+ private static final float BOOST = 2.0f;+ ContentStrategy strategy;++ protected void setUp() throws Exception {+ IndexSchemaField field = new IndexSchemaField();+ field.setName(FIELD);+ field.setStore(Field.Store.YES);+ field.setIndex(Field.Index.UN_TOKENIZED);+ field.setBoost(BOOST);+ this.strategy = new TestStrategy(field);+ }++ protected void tearDown() throws Exception {+ super.tearDown();+ }+ public void testContentStrategyIndexStoreField() throws NotIndexableException{+ IndexSchemaField field = new IndexSchemaField();+ field.setName(FIELD);+++ this.strategy = new TestStrategy(Field.Index.UN_TOKENIZED,Field.Store.YES,field);+ this.strategy.processIndexable(null);+ Field f = this.strategy.createLuceneField()[0];+ assertEquals(FIELD,f.name());+ assertEquals(TestStrategy.CONTENT,f.stringValue());+ assertEquals(1.0f,f.getBoost());+ assertTrue(f.isIndexed());+ assertTrue(f.isStored());+ assertFalse(f.isTokenized());+ assertFalse(f.isCompressed());+ }++ /*+ * Test method for 'org.apache.lucene.gdata.search.analysis.ContentStrategy.ContentStrategy(Index, Store, IndexSchemaField)'+ */+ public void testContentStrategyIndexSchemaField() throws NotIndexableException {+ IndexSchemaField field = new IndexSchemaField();+ field.setName(FIELD);+++ this.strategy = new TestStrategy(field);+ this.strategy.processIndexable(null);+ Field f = this.strategy.createLuceneField()[0];++ assertEquals(FIELD,f.name());+ assertEquals(TestStrategy.CONTENT,f.stringValue());+ assertEquals(1.0f,f.getBoost());+ assertTrue(f.isIndexed());+ assertFalse(f.isStored());+ assertTrue(f.isTokenized());+ assertFalse(f.isCompressed());+ }++ /*+ * Test method for 'org.apache.lucene.gdata.search.analysis.ContentStrategy.createLuceneField()'+ */+ public void testCreateLuceneField() throws NotIndexableException {+ try{+ this.strategy.createLuceneField();+ fail("processIndexable is not called");+ }catch (GdataIndexerException e) {+ //+ }+ this.strategy.processIndexable(null);+ Field f = this.strategy.createLuceneField()[0];++ assertEquals(FIELD,f.name());+ assertEquals(TestStrategy.CONTENT,f.stringValue());+ assertEquals(BOOST,f.getBoost());+ assertTrue(f.isIndexed());+ assertTrue(f.isStored());+ assertFalse(f.isTokenized());+ assertFalse(f.isCompressed());++++ }++ private static class TestStrategy extends ContentStrategy{++ private static final String CONTENT = "someString";+++ protected TestStrategy(Index index, Store store, IndexSchemaField fieldConfig) {+ super(index, store, fieldConfig);++ }++ protected TestStrategy(IndexSchemaField fieldConfiguration) {+ super(fieldConfiguration);++ }++ @Override+ public void processIndexable(Indexable<? extends Node, ? extends ServerBaseEntry> indexable) throws NotIndexableException {+ this.content = CONTENT;+ }++ }++}diff --git a/contrib/gdata-server/src/test/org/apache/lucene/gdata/search/analysis/TestDomIndexable.java b/contrib/gdata-server/src/test/org/apache/lucene/gdata/search/analysis/TestDomIndexable.javanew file mode 100755index 00000000000..5d4cd0cea32--- /dev/null+++ b/contrib/gdata-server/src/test/org/apache/lucene/gdata/search/analysis/TestDomIndexable.java@@ -0,0 +1,84 @@+/**+ * Copyright 2004 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.+ */+package org.apache.lucene.gdata.search.analysis;++import javax.xml.xpath.XPathExpressionException;++import junit.framework.TestCase;++import org.apache.lucene.gdata.data.ServerBaseEntry;+import org.apache.lucene.gdata.server.registry.ProvidedServiceConfig;+import org.apache.lucene.gdata.utils.ProvidedServiceStub;+import org.w3c.dom.Attr;+import org.w3c.dom.Node;++import com.google.gdata.data.Category;+import com.google.gdata.data.ExtensionProfile;+import com.google.gdata.data.HtmlTextConstruct;+import com.google.gdata.data.extensions.EventEntry;++public class TestDomIndexable extends TestCase {+++ public void testConstructor(){+ try {+ new DomIndexable(new ServerBaseEntry());+ fail("no service config");+ } catch (NotIndexableException e) {+++ }+ ServerBaseEntry e = new ServerBaseEntry();+ e.setServiceConfig(new ProvidedServiceConfig());+ try {+ new DomIndexable(e);+ fail("no extension profile");+ } catch (IllegalStateException e1) {+++ } catch (NotIndexableException e2) {++ fail("unexp. exception");+ }+ e.setServiceConfig(new ProvidedServiceStub());+ try {+ new DomIndexable(e);+ } catch (NotIndexableException e1) {+ fail("unexp. exception");++ }+ }+ /*+ * Test method for 'org.apache.lucene.gdata.search.analysis.DomIndexable.applyPath(String)'+ */+ public void testApplyPath() throws NotIndexableException, XPathExpressionException {+ String content = "fooo bar<br>";+ ServerBaseEntry entry = new ServerBaseEntry();+ entry.setContent(new HtmlTextConstruct(content));+ entry.setServiceConfig(new ProvidedServiceStub());++ Indexable ind = new DomIndexable(entry);+ Node n = ind.applyPath("/entry/content");+ assertNotNull(n);+ assertEquals(content,n.getTextContent());+ Node attr = ind.applyPath("/entry/content/@type");+ assertNotNull(attr);+ assertEquals("html",attr.getTextContent());+ assertTrue(attr instanceof Attr);++ }++}diff --git a/contrib/gdata-server/src/test/org/apache/lucene/gdata/search/analysis/TestGdataCategoryStrategy.java b/contrib/gdata-server/src/test/org/apache/lucene/gdata/search/analysis/TestGdataCategoryStrategy.javanew file mode 100755index 00000000000..18ee9a0a176--- /dev/null+++ b/contrib/gdata-server/src/test/org/apache/lucene/gdata/search/analysis/TestGdataCategoryStrategy.java@@ -0,0 +1,105 @@+/**+ * Copyright 2004 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.+ */+package org.apache.lucene.gdata.search.analysis;++import junit.framework.TestCase;++import org.apache.lucene.document.Field;+import org.apache.lucene.gdata.search.config.IndexSchemaField;+import org.apache.lucene.gdata.search.index.GdataIndexerException;++/**+ * @author Simon Willnauer+ *+ */+public class TestGdataCategoryStrategy extends TestCase {+ private static final String FIELD = "foo";++ private static final float BOOST = 2.0f;++ GdataCategoryStrategy strategy;++ private IndexSchemaField field;++ protected void setUp() throws Exception {+ this.field = new IndexSchemaField();+ field.setName(FIELD);+ //store and index will be ignored+ field.setStore(Field.Store.NO);+ field.setIndex(Field.Index.TOKENIZED);+ field.setBoost(BOOST);+ field.setPath("/path");+ this.strategy = new GdataCategoryStrategy(field);+ }++ protected void tearDown() throws Exception {+ super.tearDown();+ }++ /*+ * Test method for+ * 'org.apache.lucene.gdata.search.analysis.PlainTextStrategy.processIndexable(Indexable<?+ * extends Node, ? extends ServerBaseEntry>)'+ */+ public void testProcessIndexable() throws NotIndexableException {+ IndexableStub stub = new IndexableStub();+ stub.setReturnNull(true);+ try {+ this.strategy.processIndexable(stub);+ fail("retun value is null must fail");+ } catch (NotIndexableException e) {+ }+ assertNull(this.strategy.content);+ try {+ this.strategy.createLuceneField();+ fail("content is not set");+ } catch (GdataIndexerException e) {+ }++ String content = "fooBar";+ stub.setReturnNull(false);+ stub.setReturnValueTextContent(content);+ this.strategy.processIndexable(stub);+ assertNotNull(this.strategy.content);+ assertNotNull(this.strategy.categoryScheme);+ assertEquals(content+" "+content, this.strategy.content.trim());+ assertEquals(content, this.strategy.categoryScheme);++ Field[] fields = this.strategy.createLuceneField();+ assertEquals(2, fields.length);+ assertEquals(this.field.getName(), fields[0].name());+ assertEquals(content+" "+content, fields[0].stringValue().trim());+ assertEquals(this.strategy.categorySchemeField, fields[1].name());+ assertEquals(content, fields[1].stringValue());+ // this is also stored an untok.+ assertFalse(fields[0].isStored());+ assertTrue(fields[0].isTokenized());+ // test for xpath exc.+ this.field.setPath(null);+ this.strategy = new GdataCategoryStrategy(field);+ try {+ this.strategy.processIndexable(stub);+ fail("path is null must fail");+ } catch (NotIndexableException e) {+ }+ try {+ this.strategy.createLuceneField();+ fail("content is not set");+ } catch (GdataIndexerException e) {+ }+ }++}diff --git a/contrib/gdata-server/src/test/org/apache/lucene/gdata/search/analysis/TestGdataDateStrategy.java b/contrib/gdata-server/src/test/org/apache/lucene/gdata/search/analysis/TestGdataDateStrategy.javanew file mode 100755index 00000000000..b39d2b4aafe--- /dev/null+++ b/contrib/gdata-server/src/test/org/apache/lucene/gdata/search/analysis/TestGdataDateStrategy.java@@ -0,0 +1,115 @@+/**+ * Copyright 2004 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.+ */+package org.apache.lucene.gdata.search.analysis;++import junit.framework.TestCase;++import org.apache.lucene.document.Field;+import org.apache.lucene.gdata.search.config.IndexSchemaField;+import org.apache.lucene.gdata.search.index.GdataIndexerException;++import com.google.gdata.data.DateTime;++/**+ * @author Simon Willnauer+ *+ */+public class TestGdataDateStrategy extends TestCase {+ private static final String FIELD = "foo";++ private static final float BOOST = 2.0f;++ ContentStrategy strategy;++ private IndexSchemaField field;++ protected void setUp() throws Exception {+ this.field = new IndexSchemaField();+ field.setName(FIELD);+ field.setStore(Field.Store.NO);+ field.setIndex(Field.Index.TOKENIZED);+ field.setBoost(BOOST);+ field.setPath("/path");+ this.strategy = new GdataDateStrategy(field);+ }++ protected void tearDown() throws Exception {+ super.tearDown();+ }++ /*+ * Test method for+ * 'org.apache.lucene.gdata.search.analysis.PlainTextStrategy.processIndexable(Indexable<?+ * extends Node, ? extends ServerBaseEntry>)'+ */+ public void testProcessIndexable() throws NotIndexableException {+ IndexableStub stub = new IndexableStub();+ stub.setReturnNull(true);+ try {+ this.strategy.processIndexable(stub);+ fail("retun value is null must fail");+ } catch (NotIndexableException e) {+ }+ assertNull(this.strategy.content);+ try {+ this.strategy.createLuceneField();+ fail("content is not set");+ } catch (GdataIndexerException e) {+ }+ // test with proper date+ String content = "2005-01-09T08:00:00Z";+ String parsedConent = Long.toString(DateTime.parseDateTime(content)+ .getValue());+ stub.setReturnNull(false);+ stub.setReturnValueTextContent(content);+ this.strategy.processIndexable(stub);+ assertNotNull(this.strategy.content);+ assertEquals(parsedConent, this.strategy.content);++ Field[] fields = this.strategy.createLuceneField();+ assertEquals(1, fields.length);+ assertEquals(this.field.getName(), fields[0].name());+ assertEquals(parsedConent, fields[0].stringValue());+ // timestamp is stored and untok.+ assertTrue(fields[0].isStored());+ assertFalse(fields[0].isTokenized());++ this.strategy = new GdataDateStrategy(this.field);+ content = "2005-01-09T##08:00:00Z";+ stub.setReturnValueTextContent(content);+ try {+ this.strategy.processIndexable(stub);+ fail("unparsable date must fail");+ } catch (NotIndexableException e) {+ }+++ // test for xpath exc.+ this.field.setPath(null);+ this.strategy = new GdataDateStrategy(this.field);+ try {+ this.strategy.processIndexable(stub);+ fail("path is null must fail");+ } catch (NotIndexableException e) {+ }+ try {+ this.strategy.createLuceneField();+ fail("content is not set");+ } catch (GdataIndexerException e) {+ }++ }+}diff --git a/contrib/gdata-server/src/test/org/apache/lucene/gdata/search/analysis/TestHTMLStrategy.java b/contrib/gdata-server/src/test/org/apache/lucene/gdata/search/analysis/TestHTMLStrategy.javanew file mode 100755index 00000000000..fd2dbde1bdb--- /dev/null+++ b/contrib/gdata-server/src/test/org/apache/lucene/gdata/search/analysis/TestHTMLStrategy.java@@ -0,0 +1,75 @@+/**+ * Copyright 2004 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.+ */+package org.apache.lucene.gdata.search.analysis;++import junit.framework.TestCase;++import org.apache.lucene.document.Field;+import org.apache.lucene.gdata.search.config.IndexSchemaField;++/**+ * @author Simon Willnauer+ *+ */+public class TestHTMLStrategy extends TestCase {+ private static final String FIELD = "foo";+ private static final float BOOST = 2.0f;+ ContentStrategy strategy;+ private IndexSchemaField field;+ protected void setUp() throws Exception {+ this.field = new IndexSchemaField();+ field.setName(FIELD);+ field.setStore(Field.Store.YES);+ field.setIndex(Field.Index.UN_TOKENIZED);+ field.setBoost(BOOST);+ field.setPath("/path");+ this.strategy = new HTMLStrategy(field);+ }++ protected void tearDown() throws Exception {+ super.tearDown();+ }++ /*+ * Test method for 'org.apache.lucene.gdata.search.analysis.PlainTextStrategy.processIndexable(Indexable<? extends Node, ? extends ServerBaseEntry>)'+ */+ public void testProcessIndexable() throws NotIndexableException {+ IndexableStub stub = new IndexableStub();+ stub.setReturnNull(true);+ try{+ this.strategy.processIndexable(stub);+ fail("retun value is null must fail");+ }catch (NotIndexableException e) {}+ assertNull(this.strategy.content);+ String content = "fooBar";+ //just to make sure the filter is applied.+ String htmlContent = "<b>"+content+"</b>";+ stub.setReturnNull(false);+ stub.setReturnValueTextContent(htmlContent);+ this.strategy.processIndexable(stub);+ assertNotNull(this.strategy.content);+ assertEquals(content,this.strategy.content);+++ // test for xpath exc.+ this.field.setPath(null);+ try{+ this.strategy.processIndexable(stub);+ fail("path is null must fail");+ }catch (NotIndexableException e) {}+ }++}diff --git a/contrib/gdata-server/src/test/org/apache/lucene/gdata/search/analysis/TestKeywordStrategy.java b/contrib/gdata-server/src/test/org/apache/lucene/gdata/search/analysis/TestKeywordStrategy.javanew file mode 100755index 00000000000..633dc7a2eed--- /dev/null+++ b/contrib/gdata-server/src/test/org/apache/lucene/gdata/search/analysis/TestKeywordStrategy.java@@ -0,0 +1,104 @@+/**+ * Copyright 2004 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.+ */+package org.apache.lucene.gdata.search.analysis;++import junit.framework.TestCase;++import org.apache.lucene.document.Field;+import org.apache.lucene.gdata.search.config.IndexSchemaField;+import org.apache.lucene.gdata.search.index.GdataIndexerException;++/**+ * @author Simon Willnauer+ *+ */+public class TestKeywordStrategy extends TestCase {+ private static final String FIELD = "foo";++ private static final float BOOST = 2.0f;++ ContentStrategy strategy;++ private IndexSchemaField field;++ protected void setUp() throws Exception {+ this.field = new IndexSchemaField();+ field.setName(FIELD);+ field.setStore(Field.Store.NO);+ field.setIndex(Field.Index.TOKENIZED);+ field.setBoost(BOOST);+ field.setPath("/path");++ this.strategy = new KeywordStrategy(field);+ }++ protected void tearDown() throws Exception {+ super.tearDown();+ }++ /*+ * Test method for+ * 'org.apache.lucene.gdata.search.analysis.PlainTextStrategy.processIndexable(Indexable<?+ * extends Node, ? extends ServerBaseEntry>)'+ */+ public void testProcessIndexable() throws NotIndexableException {+ IndexableStub stub = new IndexableStub();+ stub.setReturnNull(true);+ try {+ this.strategy.processIndexable(stub);+ fail("retun value is null must fail");+ } catch (NotIndexableException e) {+ }+ assertNull(this.strategy.content);+ try {+ this.strategy.createLuceneField();+ fail("content is not set");+ } catch (GdataIndexerException e) {+ }++ String content = "fooBar";+ stub.setReturnNull(false);+ stub.setReturnValueTextContent(content);+ this.strategy.processIndexable(stub);+ assertNotNull(this.strategy.content);+ assertEquals(content, this.strategy.content);++ Field[] fields = this.strategy.createLuceneField();+ assertEquals(1, fields.length);+ assertEquals(this.field.getName(), fields[0].name());+ assertEquals(content, fields[0].stringValue());+ // this is also stored an untok.+ assertTrue(fields[0].isStored());+ assertFalse(fields[0].isTokenized());+++ // test for xpath exc.+ this.field.setPath(null);+ this.strategy = new KeywordStrategy(field);+ try {+ this.strategy.processIndexable(stub);+ fail("path is null must fail");+ } catch (NotIndexableException e) {+ }+ try {+ this.strategy.createLuceneField();+ fail("content is not set");+ } catch (GdataIndexerException e) {+ }++ }++}diff --git a/contrib/gdata-server/src/test/org/apache/lucene/gdata/search/analysis/TestMixedStrategy.java b/contrib/gdata-server/src/test/org/apache/lucene/gdata/search/analysis/TestMixedStrategy.javanew file mode 100755index 00000000000..d913955815f--- /dev/null+++ b/contrib/gdata-server/src/test/org/apache/lucene/gdata/search/analysis/TestMixedStrategy.java@@ -0,0 +1,102 @@+/**+ * Copyright 2004 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.+ */+package org.apache.lucene.gdata.search.analysis;++import junit.framework.TestCase;++import org.apache.lucene.document.Field;+import org.apache.lucene.gdata.search.config.IndexSchemaField;++/**+ * @author Simon Willnauer+ *+ */+public class TestMixedStrategy extends TestCase {+ private static final String FIELD = "foo";++ private static final float BOOST = 2.0f;++ MixedContentStrategy strategy;++ private IndexSchemaField field;++ protected void setUp() throws Exception {+ this.field = new IndexSchemaField();+ field.setName(FIELD);++ field.setStore(Field.Store.YES);+ field.setIndex(Field.Index.UN_TOKENIZED);+ field.setBoost(BOOST);+ field.setPath("/path");+ field.setTypePath("/path");+ this.strategy = new MixedContentStrategy(field);+ }++ protected void tearDown() throws Exception {+ super.tearDown();+ }++ /*+ * Test method for+ * 'org.apache.lucene.gdata.search.analysis.PlainTextStrategy.processIndexable(Indexable<?+ * extends Node, ? extends ServerBaseEntry>)'+ */+ public void testProcessIndexable() throws NotIndexableException {+ IndexableStub stub = new IndexableStub();+ stub.setReturnNull(true);+ try {+ this.strategy.processIndexable(stub);+ fail("retun value is null must fail");+ } catch (NotIndexableException e) {+ }+ assertNull(this.strategy.content);+ String content = "fooBar";+ stub.setReturnNull(false);+ stub.setReturnValueTextContent(content);+ this.strategy.processIndexable(stub);+ assertNotNull(this.strategy.strategy.content);+ assertEquals(content, this.strategy.strategy.content);+ assertEquals(this.strategy.strategy.getClass(), PlainTextStrategy.class);++++ content = "html";+ stub.setReturnNull(false);+ stub.setReturnValueTextContent(content);+ this.strategy.processIndexable(stub);+ assertNotNull(this.strategy.strategy.content);+ assertEquals(content, this.strategy.strategy.content);+ assertEquals(this.strategy.strategy.getClass(), HTMLStrategy.class);++ content = "xhtml";+ stub.setReturnNull(false);+ stub.setReturnValueTextContent(content);+ this.strategy.processIndexable(stub);+ assertNotNull(this.strategy.strategy.content);+ assertEquals(content, this.strategy.strategy.content);+ assertEquals(this.strategy.strategy.getClass(), XHtmlStrategy.class);+++ // test for xpath exc.+ this.field.setPath(null);+ try {+ this.strategy.processIndexable(stub);+ fail("path is null must fail");+ } catch (NotIndexableException e) {+ }+ }++}diff --git a/contrib/gdata-server/src/test/org/apache/lucene/gdata/search/analysis/TestPlainTextStrategy.java b/contrib/gdata-server/src/test/org/apache/lucene/gdata/search/analysis/TestPlainTextStrategy.javanew file mode 100755index 00000000000..f3c83f37f79--- /dev/null+++ b/contrib/gdata-server/src/test/org/apache/lucene/gdata/search/analysis/TestPlainTextStrategy.java@@ -0,0 +1,73 @@+/**+ * Copyright 2004 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.+ */+package org.apache.lucene.gdata.search.analysis;++import junit.framework.TestCase;++import org.apache.lucene.document.Field;+import org.apache.lucene.gdata.search.config.IndexSchemaField;++/**+ * @author Simon Willnauer+ *+ */+public class TestPlainTextStrategy extends TestCase {+ private static final String FIELD = "foo";+ private static final float BOOST = 2.0f;+ ContentStrategy strategy;+ private IndexSchemaField field;+ protected void setUp() throws Exception {+ this.field = new IndexSchemaField();+ field.setName(FIELD);+ field.setStore(Field.Store.YES);+ field.setIndex(Field.Index.UN_TOKENIZED);+ field.setBoost(BOOST);+ field.setPath("/path");+ this.strategy = new PlainTextStrategy(field);+ }++ protected void tearDown() throws Exception {+ super.tearDown();+ }++ /*+ * Test method for 'org.apache.lucene.gdata.search.analysis.PlainTextStrategy.processIndexable(Indexable<? extends Node, ? extends ServerBaseEntry>)'+ */+ public void testProcessIndexable() throws NotIndexableException {+ IndexableStub stub = new IndexableStub();+ stub.setReturnNull(true);+ try{+ this.strategy.processIndexable(stub);+ fail("retun value is null must fail");+ }catch (NotIndexableException e) {}+ assertNull(this.strategy.content);+ String content = "fooBar";+ stub.setReturnNull(false);+ stub.setReturnValueTextContent(content);+ this.strategy.processIndexable(stub);+ assertNotNull(this.strategy.content);+ assertEquals(content,this.strategy.content);+++ // test for xpath exc.+ this.field.setPath(null);+ try{+ this.strategy.processIndexable(stub);+ fail("path is null must fail");+ }catch (NotIndexableException e) {}+ }++}diff --git a/contrib/gdata-server/src/test/org/apache/lucene/gdata/search/config/TestIndexSchema.java b/contrib/gdata-server/src/test/org/apache/lucene/gdata/search/config/TestIndexSchema.javanew file mode 100755index 00000000000..45113a92cd4--- /dev/null+++ b/contrib/gdata-server/src/test/org/apache/lucene/gdata/search/config/TestIndexSchema.java@@ -0,0 +1,159 @@+/**+ * Copyright 2004 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.+ */+package org.apache.lucene.gdata.search.config;++import org.apache.lucene.analysis.PerFieldAnalyzerWrapper;+import org.apache.lucene.analysis.StopAnalyzer;+import org.apache.lucene.analysis.standard.StandardAnalyzer;+import org.apache.lucene.gdata.search.config.IndexSchemaField.ContentType;+import org.apache.lucene.gdata.search.index.IndexDocument;++import junit.framework.TestCase;++/**+ * @author Simon Willnauer+ *+ */+public class TestIndexSchema extends TestCase {+ IndexSchema schema;++ protected void setUp() throws Exception {+ schema = new IndexSchema();+ }++ protected void tearDown() throws Exception {+ super.tearDown();+ }++ /*+ * Test method for+ * 'org.apache.lucene.gdata.search.config.IndexSchema.initialize()'+ */+ public void testInitialize() {+ try {+ schema.initialize();+ fail("def search field is null");+ } catch (RuntimeException e) {+ // TODO: handle exception+ }+ schema.setDefaultSearchField("someField");+ try {+ schema.initialize();+ fail("name is null");+ } catch (RuntimeException e) {+ // TODO: handle exception+ }+ schema.setName("someName");+ try {+ schema.initialize();+ fail("indexLocation is null");+ } catch (RuntimeException e) {+ // TODO: handle exception+ }+ schema.setIndexLocation("/loc/loc");+ try {+ schema.initialize();+ fail("default search field is not set as a field");+ } catch (RuntimeException e) {+ // TODO: handle exception+ }+ IndexSchemaField f = new IndexSchemaField();+ f.setName(schema.getDefaultSearchField());+ f.setContentType(ContentType.TEXT);+ schema.addSchemaField(f);+ try {+ schema.initialize();+ fail("field check failed");+ } catch (RuntimeException e) {+ // TODO: handle exception+ }+ f.setPath("path");+ schema.initialize();+ }++ /*+ * Test method for+ * 'org.apache.lucene.gdata.search.config.IndexSchema.addSchemaField(IndexSchemaField)'+ */+ public void testAddSchemaField() {+ schema.addSchemaField(null);+ assertEquals(0, schema.getFields().size());++ IndexSchemaField f = new IndexSchemaField();+ f.setName(IndexDocument.FIELD_ENTRY_ID);+ schema.addSchemaField(f);+ assertEquals(0, schema.getFields().size());++ f.setName(IndexDocument.FIELD_FEED_ID);+ schema.addSchemaField(f);+ assertEquals(0, schema.getFields().size());++ f.setName("some");+ schema.addSchemaField(f);+ assertEquals(1, schema.getFields().size());+ assertEquals(StandardAnalyzer.class, schema.getServiceAnalyzer()+ .getClass());+ assertEquals(StandardAnalyzer.class, schema.getSchemaAnalyzer()+ .getClass());+ f.setName("someOther");+ f.setAnalyzerClass(StopAnalyzer.class);+ schema.addSchemaField(f);+ assertEquals(2, schema.getFields().size());+ assertEquals(PerFieldAnalyzerWrapper.class, schema.getSchemaAnalyzer()+ .getClass());+ schema.addSchemaField(f);+ assertEquals(3, schema.getFields().size());++ }++ /*+ * Test method for+ * 'org.apache.lucene.gdata.search.config.IndexSchema.getSearchableFieldNames()'+ */+ public void testGetSearchableFieldNames() {+ IndexSchemaField f = new IndexSchemaField();+ f.setName("some");+ schema.addSchemaField(f);+ assertEquals(1, schema.getSearchableFieldNames().size());+ assertTrue(schema.getSearchableFieldNames().contains("some"));+ }++ public void testEquals() {+ assertFalse(schema.equals(null));+ assertFalse(schema.equals(new String()));+ assertTrue(schema.equals(schema));+ assertFalse(schema.equals(new IndexSchema()));+ IndexSchema s1 = new IndexSchema();+ s1.setName("someName");+ assertFalse(schema.equals(s1));+ schema.setName(s1.getName());+ assertTrue(schema.equals(s1));+ }++ public void testHashCode() {+ assertEquals(schema.hashCode(), schema.hashCode());+ assertNotNull(schema.hashCode());+ IndexSchema s1 = new IndexSchema();+ s1.setName("someName");+ assertTrue(schema.hashCode() != s1.hashCode());+ schema.setName(s1.getName());+ assertTrue(schema.hashCode() == s1.hashCode());+ }++ public void testToSTringNoNullPEx() {+ assertNotNull(schema.toString());+ }+}diff --git a/contrib/gdata-server/src/test/org/apache/lucene/gdata/search/config/TestIndexSchemaField.java b/contrib/gdata-server/src/test/org/apache/lucene/gdata/search/config/TestIndexSchemaField.javanew file mode 100755index 00000000000..c4f4c5eeb75--- /dev/null+++ b/contrib/gdata-server/src/test/org/apache/lucene/gdata/search/config/TestIndexSchemaField.java@@ -0,0 +1,154 @@+/**+ * Copyright 2004 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.+ */+package org.apache.lucene.gdata.search.config;++import junit.framework.TestCase;++import org.apache.lucene.document.Field;+import org.apache.lucene.gdata.data.ServerBaseEntry;+import org.apache.lucene.gdata.search.analysis.ContentStrategy;+import org.apache.lucene.gdata.search.analysis.Indexable;+import org.apache.lucene.gdata.search.analysis.NotIndexableException;+import org.apache.lucene.gdata.search.analysis.PlainTextStrategy;+import org.apache.lucene.gdata.search.config.IndexSchemaField.ContentType;+import org.w3c.dom.Node;++/**+ * @author Simon Willnauer+ *+ */+public class TestIndexSchemaField extends TestCase {++ protected void setUp() throws Exception {+ super.setUp();+ }++ protected void tearDown() throws Exception {+ super.tearDown();+ }++ /*+ * Test method for 'org.apache.lucene.gdata.search.config.IndexSchemaField.checkRequieredValues()'+ */+ public void testCheckRequieredValues() {+ IndexSchemaField f = new IndexSchemaField();+ assertFalse(f.checkRequieredValues());+ f.setName("someName");+ assertFalse(f.checkRequieredValues());+ f.setPath("somePath");+ assertFalse(f.checkRequieredValues());+ f.setType("text");+ assertTrue(f.checkRequieredValues());+ f.setType("mixed");+ assertFalse(f.checkRequieredValues());+ f.setTypePath("sometypepath");+ assertTrue(f.checkRequieredValues());++ f.setType("custom");+ assertFalse(f.checkRequieredValues());+ f.setFieldClass(TestContentStragtegy.class);+ assertTrue(f.checkRequieredValues());+ }+ public void testSetFieldType(){+ IndexSchemaField f = new IndexSchemaField();+ f.setFieldClass(TestContentStragtegy.class);+ try{+ f.setFieldClass(PlainTextStrategy.class);+ fail("no pub const.");+ }catch (RuntimeException e) {++ }+ try{+ f.setFieldClass(null);+ fail("is null");+ }catch (RuntimeException e) {++ }++ }+ /*+ * Test method for 'org.apache.lucene.gdata.search.config.IndexSchemaField.setAnalyzerClass(Class<? extends Analyzer>)'+ */+ public void testSetType() {+ IndexSchemaField f = new IndexSchemaField();+ f.setType("notatype");+ assertNull(f.getContentType());+ f.setType("custom");+ assertEquals(ContentType.CUSTOM,f.getContentType());+ f.setType("text");+ assertEquals(ContentType.TEXT,f.getContentType());+ }++ /*+ * Test method for 'org.apache.lucene.gdata.search.config.IndexSchemaField.setStoreByName(String)'+ */+ public void testSetStoreByName() {+ IndexSchemaField f = new IndexSchemaField();+ f.setStoreByName("someother");+ assertEquals(Field.Store.NO,f.getStore());+ f.setStoreByName("COMPRESS");+ assertEquals(Field.Store.COMPRESS,f.getStore());+ f.setStoreByName("YeS");+ assertEquals(Field.Store.YES,f.getStore());+ f.setStoreByName("No");+ assertEquals(Field.Store.NO,f.getStore());+++ }++ /*+ * Test method for 'org.apache.lucene.gdata.search.config.IndexSchemaField.setIndexByName(String)'+ */+ public void testSetIndexByName() {+ IndexSchemaField f = new IndexSchemaField();+ f.setIndexByName("UN_done");+ assertEquals(Field.Index.TOKENIZED,f.getIndex());+ f.setIndexByName("UN_tokenized");+ assertEquals(Field.Index.UN_TOKENIZED,f.getIndex());+ f.setIndexByName("tokenized");+ assertEquals(Field.Index.TOKENIZED,f.getIndex());+ f.setIndexByName("no");+ assertEquals(Field.Index.NO,f.getIndex());+ f.setIndexByName("no_norms");+ assertEquals(Field.Index.NO_NORMS,f.getIndex());+++ }++ public void testSetboost(){+ IndexSchemaField f = new IndexSchemaField();+ f.setBoost(-0.1f);+ assertEquals(1.0f,f.getBoost());+ f.setBoost(2.50f);+ assertEquals(2.50f,f.getBoost());+ }++ public void testToSTringNoNullPEx(){+ assertNotNull(new IndexSchemaField().toString());+ }+ static class TestContentStragtegy extends ContentStrategy{++ public TestContentStragtegy(IndexSchemaField fieldConfiguration) {+ super(fieldConfiguration);+ // TODO Auto-generated constructor stub+ }++ @Override+ public void processIndexable(Indexable<? extends Node, ? extends ServerBaseEntry> indexable) throws NotIndexableException {+ }++ }+}diff --git a/contrib/gdata-server/src/test/org/apache/lucene/gdata/search/index/FutureStub.java b/contrib/gdata-server/src/test/org/apache/lucene/gdata/search/index/FutureStub.javanew file mode 100755index 00000000000..5dff5a33486--- /dev/null+++ b/contrib/gdata-server/src/test/org/apache/lucene/gdata/search/index/FutureStub.java@@ -0,0 +1,103 @@+/**+ * Copyright 2004 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.+ */++package org.apache.lucene.gdata.search.index;++import java.util.concurrent.CountDownLatch;+import java.util.concurrent.ExecutionException;+import java.util.concurrent.Future;+import java.util.concurrent.TimeUnit;+import java.util.concurrent.TimeoutException;++/**+ * @author Simon Willnauer+ *+ */+public class FutureStub<T> implements Future<T>{+ T object;+ CountDownLatch latch;+ boolean wait;++ /**+ *+ */+ public FutureStub(T returnObject, CountDownLatch latch) {+ this(returnObject,latch,false);+ }+ /**+ *+ */+ public FutureStub(T returnObject, CountDownLatch latch, boolean wait) {+ super();+ this.object = returnObject;+ this.latch =latch;+ this.wait =wait;+ }+ public FutureStub(T returnObject) {+ this(returnObject,null);+ }++ /**+ * @see java.util.concurrent.Future#cancel(boolean)+ */+ public boolean cancel(boolean arg0) {++ return false;+ }++ /**+ * @see java.util.concurrent.Future#isCancelled()+ */+ public boolean isCancelled() {++ return false;+ }++ /**+ * @see java.util.concurrent.Future#isDone()+ */+ public boolean isDone() {++ return true;+ }++ /**+ * @see java.util.concurrent.Future#get()+ */+ public T get() throws InterruptedException, ExecutionException {+ doLatch();+ return this.object;+ }++ /**+ * @see java.util.concurrent.Future#get(long, java.util.concurrent.TimeUnit)+ */+ public T get(long arg0, TimeUnit arg1) throws InterruptedException,+ ExecutionException, TimeoutException {+ doLatch();+ return this.object;+ }++ private void doLatch() throws InterruptedException{+ if(latch != null){+ if(!wait)+ this.latch.countDown();+ else+ this.latch.await(5000,TimeUnit.MILLISECONDS);+ }+ }++}diff --git a/contrib/gdata-server/src/test/org/apache/lucene/gdata/search/index/IndexDocumentStub.java b/contrib/gdata-server/src/test/org/apache/lucene/gdata/search/index/IndexDocumentStub.javanew file mode 100755index 00000000000..bb246908230--- /dev/null+++ b/contrib/gdata-server/src/test/org/apache/lucene/gdata/search/index/IndexDocumentStub.java@@ -0,0 +1,112 @@+/**+ * Copyright 2004 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.+ */++package org.apache.lucene.gdata.search.index;++import java.util.concurrent.CountDownLatch;++import org.apache.lucene.document.Document;+import org.apache.lucene.index.Term;++/**+ * @author Simon Willnauer+ *+ */+public class IndexDocumentStub implements IndexDocument {+ Document document;+ Term deleteTerm;+ IndexAction action;+ CountDownLatch latch;+ boolean commitAfter;+ boolean optimizeAfter;+ /**+ *+ */+ public IndexDocumentStub(Document doc, Term deleteTerm, IndexAction action, CountDownLatch latch) {+ this.document = doc;+ this.deleteTerm = deleteTerm;+ this.action = action;+ this.latch = latch;+ }+ public IndexDocumentStub(Document doc, Term deleteTerm, IndexAction action) {+ this(doc,deleteTerm,action,null);+ }++ /**+ * @see org.apache.lucene.gdata.search.index.IndexDocument#isUpdate()+ */+ public boolean isUpdate() {++ return isAction(IndexAction.UPDATE);+ }++ /**+ * @see org.apache.lucene.gdata.search.index.IndexDocument#isDelete()+ */+ public boolean isDelete() {++ return isAction(IndexAction.DELETE);+ }++ /**+ * @see org.apache.lucene.gdata.search.index.IndexDocument#isInsert()+ */+ public boolean isInsert() {++ return isAction(IndexAction.INSERT);+ }+ private boolean isAction(IndexAction currentAction){+ return this.action == currentAction;+ }+ /**+ * @see org.apache.lucene.gdata.search.index.IndexDocument#getWriteable()+ */+ public Document getWriteable() {+ if(latch != null)+ latch.countDown();+ return this.document;+ }++ /**+ * @see org.apache.lucene.gdata.search.index.IndexDocument#getDeletealbe()+ */+ public Term getDeletealbe() {+ if(latch != null)+ latch.countDown();+ return this.deleteTerm;+ }+ public boolean commitAfter() {++ return this.commitAfter;+ }+ public boolean optimizeAfter() {++ return this.optimizeAfter;+ }+ /**+ * @param commitAfter The commitAfter to set.+ */+ public void setCommitAfter(boolean commitAfter) {+ this.commitAfter = commitAfter;+ }+ /**+ * @param optimizeAfter The optimizeAfter to set.+ */+ public void setOptimizeAfter(boolean optimizeAfter) {+ this.optimizeAfter = optimizeAfter;+ }++}diff --git a/contrib/gdata-server/src/test/org/apache/lucene/gdata/search/index/IndexEventListenerStub.java b/contrib/gdata-server/src/test/org/apache/lucene/gdata/search/index/IndexEventListenerStub.javanew file mode 100755index 00000000000..929ec4626ed--- /dev/null+++ b/contrib/gdata-server/src/test/org/apache/lucene/gdata/search/index/IndexEventListenerStub.java@@ -0,0 +1,46 @@+/**+ * Copyright 2004 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.+ */++package org.apache.lucene.gdata.search.index;++import java.util.concurrent.atomic.AtomicInteger;++/**+ * @author Simon Willnauer+ *+ */+public class IndexEventListenerStub implements IndexEventListener {+ AtomicInteger count;+ /**+ *+ */+ public IndexEventListenerStub() {+ super();+ this.count = new AtomicInteger(0);+ }++ /**+ * @see org.apache.lucene.gdata.search.index.IndexEventListener#commitCallBack(java.lang.String)+ */+ public void commitCallBack(String service) {+ this.count.incrementAndGet();+ }++ public int getCalledCount(){+ return this.count.get();+ }++}diff --git a/contrib/gdata-server/src/test/org/apache/lucene/gdata/search/index/TestGdataIndexDocument.java b/contrib/gdata-server/src/test/org/apache/lucene/gdata/search/index/TestGdataIndexDocument.javanew file mode 100755index 00000000000..6182a50f760--- /dev/null+++ b/contrib/gdata-server/src/test/org/apache/lucene/gdata/search/index/TestGdataIndexDocument.java@@ -0,0 +1,123 @@+/**+ * Copyright 2004 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.+ */+package org.apache.lucene.gdata.search.index;++import junit.framework.TestCase;++import org.apache.lucene.document.Document;+import org.apache.lucene.gdata.search.analysis.ContentStrategy;+import org.apache.lucene.gdata.search.config.IndexSchemaField;+import org.apache.lucene.gdata.search.config.IndexSchemaField.ContentType;+import org.apache.lucene.index.Term;++public class TestGdataIndexDocument extends TestCase {+ static String ENTRYID = "someEId";+ static String FEEDID = "someFId";+ GDataIndexDocument delDocument;+ GDataIndexDocument updDocument;+ GDataIndexDocument insDocument;+ protected void setUp() throws Exception {+ this.delDocument = new GDataIndexDocument(IndexAction.DELETE,ENTRYID,FEEDID,false,true);+ this.insDocument = new GDataIndexDocument(IndexAction.INSERT,ENTRYID,FEEDID,true,false);+ this.updDocument = new GDataIndexDocument(IndexAction.UPDATE,ENTRYID,FEEDID,false,true);+ }++ protected void tearDown() throws Exception {+ super.tearDown();+ }++ /*+ * Test method for 'org.apache.lucene.gdata.search.index.GDataIndexDocument.addField(ContentStrategy)'+ */+ public void testAddField() {+ assertEquals(0,this.delDocument.fields.size());+ this.delDocument.addField(null);+ assertEquals(0,this.delDocument.fields.size());+ IndexSchemaField ifield = new IndexSchemaField();+ ifield.setContentType(ContentType.TEXT);+ this.delDocument.addField(ContentStrategy.getFieldStrategy(ifield));+ assertEquals(1,this.delDocument.fields.size());+ }++ /*+ * Test method for 'org.apache.lucene.gdata.search.index.GDataIndexDocument.getWriteable()'+ */+ public void testGetWriteable() {+ assertNotNull(this.insDocument.getWriteable());+ Document doc = this.insDocument.getWriteable();+ assertEquals(2,doc.getFields().size());+ assertEquals(ENTRYID,doc.getField(GDataIndexDocument.FIELD_ENTRY_ID).stringValue());+ assertEquals(FEEDID,doc.getField(GDataIndexDocument.FIELD_FEED_ID).stringValue());+++ }++ /*+ * Test method for 'org.apache.lucene.gdata.search.index.GDataIndexDocument.getDeletealbe()'+ */+ public void testGetDeletealbe() {+ assertNotNull(this.insDocument.getDeletealbe());+ Term t = this.insDocument.getDeletealbe();+ assertEquals(IndexDocument.FIELD_ENTRY_ID,t.field());+ assertEquals(ENTRYID,t.text());+ }++ /*+ * Test method for 'org.apache.lucene.gdata.search.index.GDataIndexDocument.isUpdate()'+ */+ public void testIsUpdate() {+ assertFalse(this.insDocument.isUpdate());+ assertTrue(this.updDocument.isUpdate());+ assertFalse(this.delDocument.isUpdate());+ }++ /*+ * Test method for 'org.apache.lucene.gdata.search.index.GDataIndexDocument.isDelete()'+ */+ public void testIsDelete() {+ assertFalse(this.insDocument.isDelete());+ assertFalse(this.updDocument.isDelete());+ assertTrue(this.delDocument.isDelete());+ }++ /*+ * Test method for 'org.apache.lucene.gdata.search.index.GDataIndexDocument.isInsert()'+ */+ public void testIsInsert() {+ assertTrue(this.insDocument.isInsert());+ assertFalse(this.updDocument.isInsert());+ assertFalse(this.delDocument.isInsert());+ }++ /*+ * Test method for 'org.apache.lucene.gdata.search.index.GDataIndexDocument.commitAfter()'+ */+ public void testCommitAfter() {+ assertTrue(this.insDocument.commitAfter());+ assertFalse(this.updDocument.commitAfter());+ assertFalse(this.delDocument.commitAfter());+ }++ /*+ * Test method for 'org.apache.lucene.gdata.search.index.GDataIndexDocument.optimizeAfter()'+ */+ public void testOptimizeAfter() {+ assertFalse(this.insDocument.optimizeAfter());+ assertTrue(this.updDocument.optimizeAfter());+ assertTrue(this.delDocument.optimizeAfter());+ }++}diff --git a/contrib/gdata-server/src/test/org/apache/lucene/gdata/search/index/TestGdataIndexWriter.java b/contrib/gdata-server/src/test/org/apache/lucene/gdata/search/index/TestGdataIndexWriter.javanew file mode 100755index 00000000000..79b49ba2152--- /dev/null+++ b/contrib/gdata-server/src/test/org/apache/lucene/gdata/search/index/TestGdataIndexWriter.java@@ -0,0 +1,79 @@+/**+ * Copyright 2004 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.+ */+package org.apache.lucene.gdata.search.index;++import java.io.IOException;++import junit.framework.TestCase;++import org.apache.lucene.analysis.PerFieldAnalyzerWrapper;+import org.apache.lucene.analysis.StopAnalyzer;+import org.apache.lucene.analysis.standard.StandardAnalyzer;+import org.apache.lucene.gdata.search.config.IndexSchema;+import org.apache.lucene.gdata.search.config.IndexSchemaField;+import org.apache.lucene.store.RAMDirectory;++/**+ * @author Simon Willnauer+ *+ */+public class TestGdataIndexWriter extends TestCase {+ IndexSchema schemaNoPerFielAnalyzer;+ IndexSchema schemaPerFielAnalyzer;+ long VALUE_GT_DEFAULT_LONG = 15000;+ int VALUE_GT_DEFAULT_INT = 10000;++ protected void setUp() throws Exception {+ this.schemaNoPerFielAnalyzer = new IndexSchema();+ this.schemaPerFielAnalyzer = new IndexSchema();+ IndexSchemaField field = new IndexSchemaField();+ field.setName("someField");+ field.setAnalyzerClass(StopAnalyzer.class);+ this.schemaPerFielAnalyzer.addSchemaField(field);+ this.schemaPerFielAnalyzer.setCommitLockTimeout(VALUE_GT_DEFAULT_LONG);+ this.schemaPerFielAnalyzer.setMaxBufferedDocs(VALUE_GT_DEFAULT_INT);+ this.schemaPerFielAnalyzer.setMaxFieldLength(VALUE_GT_DEFAULT_INT);+ this.schemaPerFielAnalyzer.setMaxMergeDocs(VALUE_GT_DEFAULT_INT);+ this.schemaPerFielAnalyzer.setMergeFactor(VALUE_GT_DEFAULT_INT);+ this.schemaPerFielAnalyzer.setWriteLockTimeout(VALUE_GT_DEFAULT_LONG);+ this.schemaPerFielAnalyzer.setUseCompoundFile(true);+ }+++ /**+ * Test method for 'org.apache.lucene.gdata.search.index.GDataIndexWriter.GDataIndexWriter(Directory, boolean, IndexSchema)'+ * @throws IOException+ */+ public void testGDataIndexWriter() throws IOException {+ try{+ new GDataIndexWriter(new RAMDirectory(),true,null);+ fail("no index schema");+ }catch (IllegalArgumentException e) {}+ GDataIndexWriter writer = new GDataIndexWriter(new RAMDirectory(),true,this.schemaNoPerFielAnalyzer);+ assertTrue(writer.getAnalyzer().getClass() == StandardAnalyzer.class);++ writer = new GDataIndexWriter(new RAMDirectory(),true,this.schemaPerFielAnalyzer);+ assertTrue(writer.getAnalyzer().getClass() == PerFieldAnalyzerWrapper.class);+ assertEquals(VALUE_GT_DEFAULT_LONG,writer.getCommitLockTimeout());+ assertEquals(VALUE_GT_DEFAULT_LONG,writer.getWriteLockTimeout());+ assertEquals(VALUE_GT_DEFAULT_INT,writer.getMaxBufferedDocs());+ assertEquals(VALUE_GT_DEFAULT_INT,writer.getMaxMergeDocs());+ assertEquals(VALUE_GT_DEFAULT_INT,writer.getMaxFieldLength());+ assertEquals(VALUE_GT_DEFAULT_INT,writer.getMergeFactor());+ assertTrue(writer.getUseCompoundFile());+ }++}diff --git a/contrib/gdata-server/src/test/org/apache/lucene/gdata/search/index/TestGdataIndexer.java b/contrib/gdata-server/src/test/org/apache/lucene/gdata/search/index/TestGdataIndexer.javanew file mode 100755index 00000000000..2f982f4f582--- /dev/null+++ b/contrib/gdata-server/src/test/org/apache/lucene/gdata/search/index/TestGdataIndexer.java@@ -0,0 +1,549 @@+/**+ * Copyright 2004 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.+ */+package org.apache.lucene.gdata.search.index;++import java.io.IOException;+import java.util.concurrent.CountDownLatch;+import java.util.concurrent.ExecutionException;+import java.util.concurrent.Future;+import java.util.concurrent.TimeUnit;+import java.util.concurrent.TimeoutException;++import junit.framework.TestCase;++import org.apache.lucene.analysis.standard.StandardAnalyzer;+import org.apache.lucene.document.Document;+import org.apache.lucene.document.Field;+import org.apache.lucene.gdata.search.config.IndexSchema;+import org.apache.lucene.index.Term;+import org.apache.lucene.search.Hits;+import org.apache.lucene.search.IndexSearcher;+import org.apache.lucene.search.TermQuery;+import org.apache.lucene.store.Directory;+import org.apache.lucene.store.RAMDirectory;++/**+ * @author Simon Willnauer+ *+ */+public class TestGdataIndexer extends TestCase {+ private GDataIndexer indexer;++ private Directory dir;++ private static IndexSchema config;++ private static String FIELD_ID = "id";++ static {+ config = new IndexSchema();+ config.setName("testService");+ config.setCommitLockTimeout(-1);+ config.setServiceAnalyzer(new StandardAnalyzer());+ config.setMaxBufferedDocs(-1);+ config.setMaxFieldLength(-1);+ config.setMaxMergeDocs(-1);+ config.setWriteLockTimeout(-1);+ config.setMergeFactor(-1);+ }++ /**+ * @see junit.framework.TestCase#setUp()+ */+ @Override+ protected void setUp() throws Exception {+ this.dir = new RAMDirectory();+ this.indexer = GDataIndexer.createGdataIndexer(config, this.dir, true);+ super.setUp();+ }++ /**+ * @see junit.framework.TestCase#tearDown()+ */+ @Override+ protected void tearDown() throws Exception {+ this.indexer.destroy();+ }+ public void testStaticFactoryMethodes() throws IOException{+ GDataIndexer i =GDataIndexer.createGdataIndexer(config, new RAMDirectory(), true);+ assertNotNull(i);+ assertEquals(IndexTask.class,i.indexTask.getClass());++ i =GDataIndexer.createTimedGdataIndexer(config, new RAMDirectory(), true,60);+ assertNotNull(i);+ assertEquals(TimedIndexTask.class,i.indexTask.getClass());+ assertEquals(60,((TimedIndexTask)i.indexTask).getIdleTime());++ i.destroy();+ }+ /*+ * Test method for+ * 'org.apache.lucene.gdata.search.index.GDataIndexer.GDataIndexer(IndexServiceConfiguration,+ * Directory, boolean)'+ */+ public void testGDataIndexer() throws InterruptedException, IOException {+ try {+ new GDataIndexer(null, dir, true);+ fail("config is null");+ } catch (IllegalArgumentException e) {+ //+ }++ try {+ new GDataIndexer(config, null, true);+ fail("dir is null");+ } catch (IllegalArgumentException e) {+ //+ }++ GDataIndexer in = new GDataIndexer(config,new RAMDirectory(),true);+ in.setIndexTask(null);+ in.init();+ assertNotNull(in.indexTask);+ assertEquals(IndexTask.class,in.indexTask.getClass());+ }++ /*+ * Test method for+ * 'org.apache.lucene.gdata.search.index.GDataIndexer.addIndexableDocumentTask(Future<IndexDocument>)'+ */+ public void testAddIndexableDocumentTask() throws InterruptedException,+ IOException {+ String id = "myID";+ Field f = new Field(FIELD_ID, id, Field.Store.YES,+ Field.Index.UN_TOKENIZED);+ Document doc = new Document();+ doc.add(f);+ Term delTerm = new Term(FIELD_ID, id);+ /*+ * Latch will be decremented in FutureStub#get() and+ * IndexDocumentStub#getIndexable+ */+ CountDownLatch l = new CountDownLatch(2);+ IndexDocument iDoc = new IndexDocumentStub(doc, delTerm,+ IndexAction.INSERT, l);+ Future<IndexDocument> future = new FutureStub<IndexDocument>(iDoc, l);++ this.indexer.addIndexableDocumentTask(future);+ // wait for the latch do decrement+ l.await(5000, TimeUnit.MILLISECONDS);++ this.indexer.commit(false);+ IndexSearcher s = new IndexSearcher(this.dir);+ Hits h = s.search(new TermQuery(delTerm));+ assertEquals(1, h.length());+ s.close();+ // test for update+ /*+ * Latch will be decremented in FutureStub#get() and+ * IndexDocumentStub#getIndexable+ */+ l = new CountDownLatch(2);+ iDoc = new IndexDocumentStub(doc, delTerm, IndexAction.UPDATE, l);+ future = new FutureStub<IndexDocument>(iDoc, l);+ this.indexer.addIndexableDocumentTask(future);+ l.await(5000, TimeUnit.MILLISECONDS);+ this.indexer.commit(false);+ s = new IndexSearcher(this.dir);+ h = s.search(new TermQuery(delTerm));+ assertEquals(1, h.length());+ s.close();++ // test for delete+ /*+ * Latch will be decremented in FutureStub#get()+ */+ l = new CountDownLatch(1);+ iDoc = new IndexDocumentStub(doc, delTerm, IndexAction.DELETE, l);+ future = new FutureStub<IndexDocument>(iDoc, l);++ this.indexer.addIndexableDocumentTask(future);+ /*+ * wait for the indexer task to add the deleted+ */+ while (this.indexer.docsDeleted.get() == 0)+ l.await(5000, TimeUnit.MILLISECONDS);++ this.indexer.commit(false);+ s = new IndexSearcher(this.dir);+ h = s.search(new TermQuery(delTerm));+ assertEquals(0, h.length());+ s.close();+ }++ /*+ * Test method for+ * 'org.apache.lucene.gdata.search.index.GDataIndexer.addDocument(IndexDocument)'+ */+public void testAddDocument() throws IOException {+ String id = "myID";+ Field f = new Field(FIELD_ID, id, Field.Store.YES,+ Field.Index.UN_TOKENIZED);+ Document doc = new Document();+ doc.add(f);+ Term delTerm = new Term(FIELD_ID, id);+ IndexDocument iDoc = new IndexDocumentStub(doc,delTerm,+ IndexAction.INSERT);++ this.indexer.addDocument(iDoc);+ assertEquals(1,this.indexer.docsAdded.get());+ assertEquals(0,this.indexer.docsDeleted.get());+ assertEquals(0,this.indexer.docsUpdated.get());+ this.indexer.addDocument(iDoc);+ this.indexer.commit(false);+++ IndexSearcher s = new IndexSearcher(this.dir);+ Hits h = s.search(new TermQuery(delTerm));+ assertEquals(1, h.length());+ s.close();++ iDoc = new IndexDocumentStub(doc,delTerm,+ IndexAction.UPDATE);+ try{+ this.indexer.addDocument(iDoc);+ fail("document has not insert action ");+ }catch (GdataIndexerException e) {++ }++ }+ /*+ * Test method for+ * 'org.apache.lucene.gdata.search.index.GDataIndexer.updateDocument(IndexDocument)'+ */+ public void testUpdateDocument() throws IOException {++ String id = "myID";+ Field f = new Field(FIELD_ID, id, Field.Store.YES,+ Field.Index.UN_TOKENIZED);+ Document doc = new Document();+ doc.add(f);+ Term delTerm = new Term(FIELD_ID, id);+ IndexDocument iDoc = new IndexDocumentStub(doc,delTerm,+ IndexAction.INSERT);+ /*+ * write doc to index+ */+ this.indexer.writer.addDocument(doc);+ this.indexer.closeWriter();+ IndexSearcher s = new IndexSearcher(this.dir);+ Hits h = s.search(new TermQuery(delTerm));+ assertEquals(1, h.length());+ s.close();++ iDoc = new IndexDocumentStub(doc,delTerm,+ IndexAction.UPDATE);+ /*+ * updateDoc via indexer+ */+ this.indexer.updateDocument(iDoc);+ assertEquals(0,this.indexer.docsAdded.get());+ assertEquals(0,this.indexer.docsDeleted.get());+ assertEquals(1,this.indexer.docsUpdated.get());++ this.indexer.commit(false);+++ s = new IndexSearcher(this.dir);+ h = s.search(new TermQuery(delTerm));+ assertEquals(1, h.length());+ s.close();++ iDoc = new IndexDocumentStub(doc,delTerm,+ IndexAction.DELETE);+ try{+ this.indexer.updateDocument(iDoc);+ fail("document has not update action ");+ }catch (GdataIndexerException e) {++ }+ }++ /*+ * Test method for+ * 'org.apache.lucene.gdata.search.index.GDataIndexer.deleteDocument(IndexDocument)'+ */+ public void testDeleteDocument() throws IOException {+ String id = "myID";+ Field f = new Field(FIELD_ID, id, Field.Store.YES,+ Field.Index.UN_TOKENIZED);+ Document doc = new Document();+ doc.add(f);+ Term delTerm = new Term(FIELD_ID, id);+ IndexDocument iDoc = new IndexDocumentStub(doc,delTerm,+ IndexAction.INSERT);+ /*+ * write doc to index+ */+ this.indexer.writer.addDocument(doc);++ this.indexer.closeWriter();+ IndexSearcher s = new IndexSearcher(this.dir);+ Hits h = s.search(new TermQuery(delTerm));+ assertEquals(1, h.length());+ s.close();++ /*+ * del doc via indexer+ */+ iDoc = new IndexDocumentStub(doc,delTerm,+ IndexAction.DELETE);+ this.indexer.deleteDocument(iDoc);+ assertEquals(0,this.indexer.docsAdded.get());+ assertEquals(1,this.indexer.docsDeleted.get());+ assertEquals(0,this.indexer.docsUpdated.get());+ this.indexer.commit(false);+ s = new IndexSearcher(this.dir);+ h = s.search(new TermQuery(delTerm));+ assertEquals(0, h.length());+ s.close();++ /*+ * test insert / del without commit+ */+ iDoc = new IndexDocumentStub(doc,delTerm,+ IndexAction.INSERT);+ this.indexer.addDocument(iDoc);+ iDoc = new IndexDocumentStub(doc,delTerm,+ IndexAction.DELETE);+ this.indexer.deleteDocument(iDoc);+ this.indexer.commit(false);+ s = new IndexSearcher(this.dir);+ h = s.search(new TermQuery(delTerm));+ assertEquals(0, h.length());+ s.close();++ /*+ * test insert / update / del without commit+ */+ iDoc = new IndexDocumentStub(doc,delTerm,+ IndexAction.INSERT);+ this.indexer.addDocument(iDoc);+ iDoc = new IndexDocumentStub(doc,delTerm,+ IndexAction.UPDATE);+ this.indexer.updateDocument(iDoc);+ iDoc = new IndexDocumentStub(doc,delTerm,+ IndexAction.DELETE);+ this.indexer.deleteDocument(iDoc);+ this.indexer.commit(false);+ s = new IndexSearcher(this.dir);+ h = s.search(new TermQuery(delTerm));+ assertEquals(0, h.length());+ s.close();++ iDoc = new IndexDocumentStub(doc,delTerm,+ IndexAction.UPDATE);+ try{+ this.indexer.deleteDocument(iDoc);+ fail("document has not delete action ");+ }catch (GdataIndexerException e) {++ }++ }++ /*+ * Test method for+ * 'org.apache.lucene.gdata.search.index.GDataIndexer.commit(boolean)'+ */+ public void testCommit() throws IOException {+ String id = "myID";+ Field f = new Field(FIELD_ID, id, Field.Store.YES,+ Field.Index.UN_TOKENIZED);+ Document doc = new Document();+ doc.add(f);+ Term delTerm = new Term(FIELD_ID, id);+ IndexDocument iDoc = new IndexDocumentStub(doc,delTerm,+ IndexAction.INSERT);+ this.indexer.addDocument(iDoc);+ iDoc = new IndexDocumentStub(doc,delTerm,+ IndexAction.UPDATE);+ this.indexer.updateDocument(iDoc);+ this.indexer.updateDocument(iDoc);+ iDoc = new IndexDocumentStub(doc,delTerm,+ IndexAction.DELETE);+ this.indexer.deleteDocument(iDoc);+ IndexEventListenerStub evListener = new IndexEventListenerStub();+ this.indexer.registerIndexEventListener(evListener);+ assertEquals(1,this.indexer.docsAdded.get());+ assertEquals(1,this.indexer.docsDeleted.get());+ assertEquals(2,this.indexer.docsUpdated.get());+ assertEquals(0,evListener.getCalledCount());+ this.indexer.commit(true);+ this.indexer.commit(false);+ assertEquals(1,evListener.getCalledCount());+ assertEquals(0,this.indexer.docsAdded.get());+ assertEquals(0,this.indexer.docsDeleted.get());+ assertEquals(0,this.indexer.docsUpdated.get());+ IndexSearcher s = new IndexSearcher(this.dir);+ Hits h = s.search(new TermQuery(delTerm));+ assertEquals(0, h.length());+ s.close();+ }++ /*+ * Test method for+ * 'org.apache.lucene.gdata.search.index.GDataIndexer.registerIndexEventListener(IndexEventListener)'+ */+ public void testRegisterIndexEventListener() {+ IndexEventListenerStub evListener = new IndexEventListenerStub();+ this.indexer.registerIndexEventListener(evListener);+ this.indexer.registerIndexEventListener(evListener);+ assertEquals(0,evListener.getCalledCount());+ this.indexer.notifyCommitListeners("someId");+ this.indexer.notifyCommitListeners("someId");+ assertEquals(2,evListener.getCalledCount());+ }++ /*+ * Test method for+ * 'org.apache.lucene.gdata.search.index.GDataIndexer.removeIndexEventListener(IndexEventListener)'+ */+ public void testRemoveIndexEventListener() {+ IndexEventListenerStub evListener = new IndexEventListenerStub();+ this.indexer.registerIndexEventListener(evListener);+ assertEquals(0,evListener.getCalledCount());+ this.indexer.notifyCommitListeners("someId");+ assertEquals(1,evListener.getCalledCount());+ this.indexer.removeIndexEventListener(evListener);+ this.indexer.removeIndexEventListener(evListener);+ this.indexer.notifyCommitListeners("someId");+ assertEquals(1,evListener.getCalledCount());++ }++ /*+ * Test method for+ * 'org.apache.lucene.gdata.search.index.GDataIndexer.notifyCommitListeners(String)'+ */+ public void testNotifyCommitListeners() {+ IndexEventListenerStub evListener = new IndexEventListenerStub();+ IndexEventListenerStub evListener1 = new IndexEventListenerStub();+ IndexEventListenerStub evListener2 = new IndexEventListenerStub();+ this.indexer.registerIndexEventListener(evListener);+ this.indexer.registerIndexEventListener(evListener1);+ this.indexer.registerIndexEventListener(evListener2);+ assertEquals(0,evListener.getCalledCount());+ this.indexer.notifyCommitListeners("someId");+ assertEquals(1,evListener.getCalledCount());+ assertEquals(1,evListener1.getCalledCount());+ assertEquals(1,evListener2.getCalledCount());+ this.indexer.removeIndexEventListener(evListener);+ this.indexer.notifyCommitListeners("someId");+ assertEquals(1,evListener.getCalledCount());+ assertEquals(2,evListener1.getCalledCount());+ assertEquals(2,evListener2.getCalledCount());+ }++ /*+ * Test method for+ * 'org.apache.lucene.gdata.search.index.GDataIndexer.closeWriter()'+ */+ public void testCloseWriter() throws IOException{+ assertNotNull(this.indexer.writer);+ this.indexer.closeWriter();+ assertNull(this.indexer.writer);++ }++ /*+ * Test method for+ * 'org.apache.lucene.gdata.search.index.GDataIndexer.closeSearcher()'+ */+ public void testCloseSearcher() throws IOException {+ this.indexer.openSearcher();+ assertNotNull(this.indexer.searcher);+ this.indexer.closeSearcher();+ assertNull(this.indexer.searcher);+ }++ /*+ * Test method for+ * 'org.apache.lucene.gdata.search.index.GDataIndexer.openSearcher()'+ */+ public void testOpenSearcher() throws IOException {+ this.indexer.searcher = null;+ this.indexer.openSearcher();+ assertNotNull(this.indexer.searcher);+ }++ /*+ * Test method for+ * 'org.apache.lucene.gdata.search.index.GDataIndexer.openWriter()'+ */+ public void testOpenWriter() throws IOException {+ this.indexer.closeWriter();+ assertNull(this.indexer.writer);+ this.indexer.openWriter();+ assertNotNull(this.indexer.writer);+ }+++ /*+ * Test method for+ * 'org.apache.lucene.gdata.search.index.GDataIndexer.destroy()'+ */+ public void testDestroy() throws InterruptedException, IOException {+ this.indexer.destroy();+ String id = "myID";+ Field f = new Field(FIELD_ID, id, Field.Store.YES,+ Field.Index.UN_TOKENIZED);+ Document doc = new Document();+ doc.add(f);+ Term delTerm = new Term(FIELD_ID, id);+ IndexDocument iDoc = new IndexDocumentStub(doc, delTerm,+ IndexAction.INSERT);+ Future<IndexDocument> future = new FutureStub<IndexDocument>(iDoc);+ try{+ this.indexer.addIndexableDocumentTask(future);+ fail("indexer already closed exc. expected");+ }catch (IllegalStateException e) {}+ this.indexer = GDataIndexer.createGdataIndexer(config, dir, true);+ CountDownLatch documentLatch = new CountDownLatch(1);+ iDoc = new IndexDocumentStub(doc, delTerm,+ IndexAction.INSERT,documentLatch);++ CountDownLatch latch = new CountDownLatch(1);+ future = new FutureStub<IndexDocument>(iDoc,latch,true);+ this.indexer.addIndexableDocumentTask(future);+ this.indexer.destroy();+ latch.countDown();+ documentLatch.await(5000,TimeUnit.MILLISECONDS);+ // wait active for the commit+ while(this.indexer.writer != null){}++ IndexSearcher s = new IndexSearcher(this.dir);+ Hits h = s.search(new TermQuery(delTerm));+ assertEquals(1, h.length());+ s.close();+++ }++ public void testInnerClassFuture() throws InterruptedException, ExecutionException, TimeoutException{+ Future f = new GDataIndexer.FinishingFuture();+ assertNull(f.get());+ assertNull(f.get(0,TimeUnit.MICROSECONDS));+ assertTrue(f.isDone());+ assertFalse(f.isCancelled());+ assertFalse(f.cancel(true));++ }++++}diff --git a/contrib/gdata-server/src/test/org/apache/lucene/gdata/search/index/TestIndexController.java b/contrib/gdata-server/src/test/org/apache/lucene/gdata/search/index/TestIndexController.javanew file mode 100755index 00000000000..f775af87cc5--- /dev/null+++ b/contrib/gdata-server/src/test/org/apache/lucene/gdata/search/index/TestIndexController.java@@ -0,0 +1,381 @@+/**+ * Copyright 2004 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.+ */+package org.apache.lucene.gdata.search.index;++import java.io.File;+import java.io.IOException;+import java.util.List;+import java.util.concurrent.CountDownLatch;++import junit.framework.TestCase;++import org.apache.lucene.analysis.standard.StandardAnalyzer;+import org.apache.lucene.document.Document;+import org.apache.lucene.document.Field;+import org.apache.lucene.gdata.data.ServerBaseEntry;+import org.apache.lucene.gdata.search.GDataSearcher;+import org.apache.lucene.gdata.search.config.IndexSchema;+import org.apache.lucene.gdata.search.config.IndexSchemaField;+import org.apache.lucene.gdata.search.config.IndexSchemaField.ContentType;+import org.apache.lucene.gdata.search.index.IndexController.ServiceIndex;+import org.apache.lucene.gdata.server.registry.GDataServerRegistry;+import org.apache.lucene.gdata.utils.ProvidedServiceStub;+import org.apache.lucene.gdata.utils.ReferenceCounter;+import org.apache.lucene.index.IndexWriter;+import org.apache.lucene.index.Term;+import org.apache.lucene.search.IndexSearcher;+import org.apache.lucene.search.TermQuery;+++/**+ * @author Simon Willnauer+ *+ */+public class TestIndexController extends TestCase {+ IndexController controller;++ IndexSchema schema;++ File indexLocation;++ protected void setUp() throws Exception {+ this.controller = new IndexController();+ GDataServerRegistry reg = GDataServerRegistry.getRegistry();++ this.indexLocation = new File(System.getProperty("java.io.tmpdir"));+++ ProvidedServiceStub stub = new ProvidedServiceStub();+ this.schema = new IndexSchema();+ // must be set+ this.schema.setDefaultSearchField("content");+ this.schema.setName(ProvidedServiceStub.SERVICE_NAME);+ this.schema.setIndexLocation(this.indexLocation.getAbsolutePath());+ IndexSchemaField field = new IndexSchemaField();+ field.setName("content");+ field.setPath("/somePath");+ field.setContentType(ContentType.TEXT);+ this.schema.addSchemaField(field);+ stub.setIndexSchema(this.schema);++ reg.registerService(stub);+ }++ protected void tearDown() throws Exception {+ super.tearDown();+ GDataServerRegistry.getRegistry().destroy();+ this.controller.destroy();+ /*+ * this file will be created by the controller+ */+ File toDel = new File(this.indexLocation,+ ProvidedServiceStub.SERVICE_NAME);+ delAllFiles(toDel);+ }++ /*+ * del all created files+ */+ private void delAllFiles(File dir) {+ if (dir == null || !dir.exists())+ return;+ File[] files = dir.listFiles();+ for (int i = 0; i < files.length; i++) {+ while (!files[i].canWrite()) {+ }+ ;+ files[i].delete();+ }+ dir.delete();+ }++ /*+ * Test method for+ * 'org.apache.lucene.gdata.search.index.IndexController.initialize()'+ */+ public void testInitialize() {+ this.controller.initialize();+ assertTrue(this.controller.indexerMap+ .containsKey(ProvidedServiceStub.SERVICE_NAME));+ ServiceIndex bean = this.controller.indexerMap+ .get(ProvidedServiceStub.SERVICE_NAME);+ assertNotNull(bean);+ assertNotNull(bean.getIndexer());+ assertSame(this.schema, bean.getSchema());+ assertTrue(GDataServerRegistry.getRegistry().getEntryEventMediator()+ .isListenerRegistered(this.controller));++ }++ /*+ * Test method for+ * 'org.apache.lucene.gdata.search.index.IndexController.initialize()'+ */+ public void testInitializeValueMissing() {+ this.schema.setIndexLocation(null);+ try {++ this.controller.initialize();+ fail("missing index location");+ } catch (RuntimeException e) {+ }+ }++ /*+ * Test method for+ * 'org.apache.lucene.gdata.search.index.IndexController.addIndexSchema(IndexSchema)'+ */+ public void testAddIndexSchema() {+ this.controller.initialize();+ assertEquals(1, this.controller.indexerMap.size());+ try {+ this.controller.addIndexSchema(this.schema);+ fail("schema already added");+ } catch (IllegalStateException e) {++ }+ this.schema.setName(null);+ try {+ this.controller.addIndexSchema(this.schema);+ fail("schema name is null");+ } catch (IllegalStateException e) {++ }++ this.schema.setName("someOthername");+ this.controller.addIndexSchema(this.schema);+ assertEquals(2, this.controller.indexerMap.size());++ }++ /*+ * Test method for+ * 'org.apache.lucene.gdata.search.index.IndexController.createIndexer(IndexSchema)'+ */+ public void testCreateIndexDirectory() throws IOException {+ File f = new File(System.getProperty("java.io.tmpdir"), "gdataindexdir"+ + System.currentTimeMillis());+ f.mkdir();+ f.deleteOnExit();+ IndexWriter w = new IndexWriter(f, new StandardAnalyzer(), true);+ Document d = new Document();+ d.add(new Field("test", "test", Field.Store.NO, Field.Index.TOKENIZED));+ w.addDocument(d);+ w.close();+ assertFalse(this.controller.createIndexDirectory(f));+ // throw away files in the directory+ delAllFiles(f);+ File f1 = new File(System.getProperty("java.io.tmpdir"), "newIndexDir"+ + System.currentTimeMillis());+ f1.mkdir();+ f1.deleteOnExit();+ assertTrue(this.controller.createIndexDirectory(f1));+ }++ /*+ * Test method for+ * 'org.apache.lucene.gdata.search.index.IndexController.createIndexLocation(String,+ * String)'+ */+ public void testCreateIndexLocation() throws IOException {+ File f = new File(System.getProperty("java.io.tmpdir"), "gdatadir"+ + System.currentTimeMillis());+ f.mkdir();+ f.deleteOnExit();++ assertEquals(f.getAbsolutePath(), this.controller.createIndexLocation(+ f.getParent(), f.getName()).getAbsolutePath());+ ;+ File pFile = new File(System.getProperty("java.io.tmpdir"), "gdatafile"+ + System.currentTimeMillis());+ pFile.deleteOnExit();+ try{+ this.controller.createIndexLocation(pFile.getParent(),pFile.getAbsolutePath());+ fail("can not create dir");+ }catch (RuntimeException e) {++ }+ assertTrue(pFile.createNewFile());+ try {+ this.controller.createIndexLocation(pFile.getParent(), pFile+ .getName());+ fail("file is not a directory");+ } catch (IllegalArgumentException e) {++ }+ try {+ this.controller.createIndexLocation(pFile.getName(), pFile+ .getName());+ fail("parent is not a directory");+ } catch (IllegalArgumentException e) {++ }+ try{+ this.controller.createIndexLocation(null,null);+ fail("null");+ }catch (GdataIndexerException e) {++ }+ }++ /*+ * Test method for+ * 'org.apache.lucene.gdata.search.index.IndexController.getServiceSearcher(ProvidedService)'+ */+ public void testGetServiceSearcher() {++ this.controller.initialize();+ ReferenceCounter<IndexSearcher> refCounter = this.controller.indexerMap+ .get(ProvidedServiceStub.SERVICE_NAME).getSearcher();+ GDataSearcher searcher = this.controller+ .getServiceSearcher(new ProvidedServiceStub());+ assertNotNull(searcher);+ GDataSearcher sameSearcher = this.controller+ .getServiceSearcher(new ProvidedServiceStub());+ assertSame(refCounter, this.controller.indexerMap.get(+ ProvidedServiceStub.SERVICE_NAME).getSearcher());++ this.controller.commitCallBack(ProvidedServiceStub.SERVICE_NAME);+ GDataSearcher newSearcher = this.controller+ .getServiceSearcher(new ProvidedServiceStub());+ assertNotSame(refCounter, this.controller.indexerMap.get(+ ProvidedServiceStub.SERVICE_NAME).getSearcher());++ sameSearcher.close();+ searcher.close();+ newSearcher.close();++ }++ public void testDestroy() {+ this.controller.initialize();+ try {+ this.controller.initialize();+ fail("controller is initialized");+ } catch (IllegalStateException e) {+ }+ this.controller.destroy();+ try {+ this.controller.getServiceSearcher(null);+ fail("controller is closed");+ } catch (IllegalStateException e) {+ }+ try {+ this.controller.commitCallBack("null");+ fail("controller is closed");+ } catch (IllegalStateException e) {+ }++ try {+ this.controller.destroy();+ fail("controller is closed");+ } catch (IllegalStateException e) {+ }+ try {+ this.controller.addIndexSchema(null);+ fail("controller is closed");+ } catch (IllegalStateException e) {+ }+ /*+ * init again to destroy in teardown+ */+ this.controller.initialize();+ }+++ public void testfireInsertEvent(){+ try{+ this.controller.fireInsertEvent(null);+ fail("not initialized");+ }catch (IllegalStateException e) {+ // TODO: handle exception+ }+ this.controller.initialize();+ ServerBaseEntry e = new ServerBaseEntry();+ e.setId("someId");+ e.setFeedId("someId");+ e.setServiceConfig(new ProvidedServiceStub());+ this.controller.fireInsertEvent(e);+ }++ public void testCreateNewIndexTask() throws InterruptedException, IOException{+ this.schema.setCommitAfterDocuments(1);+ this.schema.setOptimizeAfterCommit(1);+ IndexSchemaField f = new IndexSchemaField();+ f.setName("myField");+ f.setContentType(ContentType.KEYWORD);+ f.setPath("entry/id");+ this.schema.addSchemaField(f);+ this.controller.initialize();+ ServerBaseEntry e = new ServerBaseEntry();+ e.setId("someId");+ e.setFeedId("someId");+ e.setServiceConfig(new ProvidedServiceStub());+ CommitListener l = new CommitListener();+ l.createLatch(1);+ ServiceIndex sIndex = this.controller.indexerMap.get(this.schema.getName());+ sIndex.getIndexer().registerIndexEventListener(l);+ this.controller.fireInsertEvent(e);+ l.waitOnLatch();++ assertEquals(1,sIndex.getIndexer().optimized.get());+ assertEquals(1,sIndex.getIndexer().committed.get());++ sIndex.getIndexer().removeIndexEventListener(l);+++ e = new ServerBaseEntry();+ e.setId("someId");+ e.setFeedId("someId");+ e.setServiceConfig(new ProvidedServiceStub());+ l = new CommitListener();+ l.createLatch(1);+ sIndex = this.controller.indexerMap.get(this.schema.getName());+ sIndex.getIndexer().registerIndexEventListener(l);+ this.controller.fireUpdateEvent(e);+ l.waitOnLatch();++ assertEquals(2,sIndex.getIndexer().optimized.get());+ assertEquals(2,sIndex.getIndexer().committed.get());++ GDataSearcher<String> searcher = this.controller.getServiceSearcher(e.getServiceConfig());+ List<String> results = searcher.search(new TermQuery(new Term(IndexDocument.FIELD_ENTRY_ID,"someId")),10,0,"someId");+ assertEquals(1,results.size());+ searcher.close();++++ }++ static class CommitListener implements IndexEventListener{+ public CountDownLatch latch;++ public void createLatch(int count){+ this.latch = new CountDownLatch(count);+ }+ public void waitOnLatch() throws InterruptedException{+ if(latch != null)+ latch.await();+ }++ public void commitCallBack(String service) {+ if(this.latch != null)+ this.latch.countDown();+ }++ }++}diff --git a/contrib/gdata-server/src/test/org/apache/lucene/gdata/search/index/TestIndexLogReader.java b/contrib/gdata-server/src/test/org/apache/lucene/gdata/search/index/TestIndexLogReader.javanew file mode 100755index 00000000000..2de309f2fb2--- /dev/null+++ b/contrib/gdata-server/src/test/org/apache/lucene/gdata/search/index/TestIndexLogReader.java@@ -0,0 +1,139 @@+/**+ * Copyright 2004 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.+ */+package org.apache.lucene.gdata.search.index;++import java.io.File;+import java.io.IOException;+import java.util.HashMap;+import java.util.Map;+import java.util.Set;++import org.xml.sax.SAXException;++import junit.framework.TestCase;++/**+ * @author Simon Willnauer+ *+ */+public class TestIndexLogReader extends TestCase {+ File logFile;+ Map<String, IndexAction> actions;+ protected void setUp() throws Exception {+ this.logFile = new File(System.getProperty("java.io.tmpdir"),"log");+ this.logFile.deleteOnExit();+ this.logFile.createNewFile();+ this.actions = new HashMap<String,IndexAction>();+++ }+ private IndexLogWriter writeLog() throws IOException{+ this.actions = new HashMap<String,IndexAction>();+ IndexLogWriter writer = new IndexLogWriter(this.logFile);+ boolean totwice = true;+ for (int i = 0; i < 10; i++) {+ IndexAction a = null;+ if(i%3 ==0)+ a= IndexAction.INSERT;+ if(i%3 ==1)+ a= IndexAction.UPDATE;+ if(i%3 ==2)+ a= IndexAction.DELETE;+ this.actions.put(""+i,a);+ writer.writeAction(""+i,a);+ /*+ * double action+ */+ if(i == 9 && totwice){+ i = 0;+ totwice = false;+ }+ }+ return writer;+ }+ protected void tearDown() throws Exception {+ super.tearDown();+ this.logFile.delete();+ }++ /*+ * Test method for 'org.apache.lucene.gdata.search.index.IndexLogReader.readIndexLog(File, Map<String, IndexAction>)'+ */+ public void testReadIndexLog() throws SAXException, IOException {+ writeLog().close();++ Map<String,IndexAction> readActionMap = new HashMap<String,IndexAction>();+ IndexLogReader.readIndexLog(this.logFile,readActionMap);+ Set<String> keySet = this.actions.keySet();+ assertEquals(10,keySet.size());+ for (String string : keySet) {+ assertTrue(readActionMap.get(string).equals(actions.get(string)));+ }++++ }++ /*+ * Test method for 'org.apache.lucene.gdata.search.index.IndexLogReader.readIndexLog(File, Map<String, IndexAction>)'+ */+ public void testReadIndexLogNoInputMap() throws SAXException, IOException {+ writeLog().close();++ Map<String,IndexAction> readActionMap = IndexLogReader.readIndexLog(this.logFile,null);+ Set<String> keySet = this.actions.keySet();+ assertEquals(10,keySet.size());+ for (String string : keySet) {+ assertTrue(readActionMap.get(string).equals(actions.get(string)));+ }++ }++ /*+ * Test method for 'org.apache.lucene.gdata.search.index.IndexLogReader.readIndexLog(File, Map<String, IndexAction>)'+ */+ public void testReadIndexLogFixLogFile() throws SAXException, IOException {+ writeLog();++ Map<String,IndexAction> readActionMap = IndexLogReader.readIndexLog(this.logFile,null);+ Set<String> keySet = this.actions.keySet();+ assertEquals(10,keySet.size());+ for (String string : keySet) {+ assertTrue(readActionMap.get(string).equals(actions.get(string)));+ }++ }++ public void testWriterClosed()throws SAXException, IOException{+ IndexLogWriter writer = writeLog();+ writer.close();+ try{+ writer.writeAction(null,null);+ fail("writer is closed");+ }catch (IllegalStateException e) {++ }+ try{+ writer.close();+ fail("writer is closed");+ }catch (IllegalStateException e) {++ }+++ }++}diff --git a/contrib/gdata-server/src/test/org/apache/lucene/gdata/search/index/TestindexDocumentBuilderTask.java b/contrib/gdata-server/src/test/org/apache/lucene/gdata/search/index/TestindexDocumentBuilderTask.javanew file mode 100755index 00000000000..0d7f13078ba--- /dev/null+++ b/contrib/gdata-server/src/test/org/apache/lucene/gdata/search/index/TestindexDocumentBuilderTask.java@@ -0,0 +1,163 @@+/**+ * Copyright 2004 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.+ */+package org.apache.lucene.gdata.search.index;++import java.util.concurrent.ExecutionException;+import java.util.concurrent.ExecutorService;+import java.util.concurrent.Executors;+import java.util.concurrent.Future;++import junit.framework.TestCase;++import org.apache.lucene.gdata.data.ServerBaseEntry;+import org.apache.lucene.gdata.search.config.IndexSchema;+import org.apache.lucene.gdata.search.config.IndexSchemaField;+import org.apache.lucene.gdata.search.config.IndexSchemaField.ContentType;+import org.apache.lucene.gdata.utils.ProvidedServiceStub;++import com.google.gdata.data.PlainTextConstruct;++/**+ * @author Simon Willnauer+ *+ */+public class TestindexDocumentBuilderTask extends TestCase {+ IndexDocumentBuilder fineBuilder;+ IndexDocumentBuilder failInStrategyBuilder;+ IndexDocumentBuilder builder;+ IndexDocumentBuilderTask zeroFields;+ static String ID = "someId";+ static String CONTENT_FIELD = "someId";+ static String CONTENT = "foo bar";+ protected void setUp() throws Exception {+ ServerBaseEntry entry = new ServerBaseEntry();+ entry.setVersionId("1");+ entry.setFeedId("myFeed");+ entry.setId(ID);+ entry.setContent(new PlainTextConstruct(CONTENT));+ entry.setServiceConfig(new ProvidedServiceStub());+ IndexSchema schema = new IndexSchema();+ schema.setName("mySchema");+ IndexSchemaField field = new IndexSchemaField();+ field.setName(CONTENT_FIELD);+ field.setPath("/entry/content");+ field.setContentType(ContentType.TEXT);+ schema.addSchemaField(field);+ this.fineBuilder = new IndexDocumentBuilderTask(entry,schema,IndexAction.INSERT,true,true);++ /*+ * two fields, one will fail due to broken xpath.+ * One will remain.+ */+ schema = new IndexSchema();+ schema.setName("mySchema");+ field = new IndexSchemaField();+ field.setName("someContent");+ //broken xpath+ field.setPath("/entry///wrongXPath");+ field.setContentType(ContentType.TEXT);+ schema.addSchemaField(field);+ field = new IndexSchemaField();+ field.setName(CONTENT_FIELD);+ field.setPath("/entry/content");+ field.setContentType(ContentType.TEXT);+ schema.addSchemaField(field);+ this.failInStrategyBuilder = new IndexDocumentBuilderTask(entry,schema,IndexAction.INSERT,false,false);+ //fail with no fields+ schema = new IndexSchema();+ schema.setName("mySchema");+ this.zeroFields = new IndexDocumentBuilderTask(entry,schema,IndexAction.INSERT,false,false);+++ }++ protected void tearDown() throws Exception {+ super.tearDown();+ }++ /*+ * Test method for 'org.apache.lucene.gdata.search.index.IndexDocumentBuilderTask.IndexDocumentBuilderTask(ServerBaseEntry, IndexSchema, IndexAction, boolean)'+ */+ public void testIndexDocumentBuilderTask() {+ IndexDocument doc = this.fineBuilder.call();+ assertNotNull(doc.getDeletealbe());+ assertNotNull(doc.getWriteable());+ assertEquals(IndexDocument.FIELD_ENTRY_ID,doc.getDeletealbe().field());+ assertEquals(ID,doc.getDeletealbe().text());+ assertEquals(ID,doc.getWriteable().getField(IndexDocument.FIELD_ENTRY_ID).stringValue());+ assertNotNull(doc.getWriteable().getField(CONTENT_FIELD).stringValue());++ /*+ * the broken xpath fails but the other fields will be indexed+ */+ doc = this.failInStrategyBuilder.call();+ assertNotNull(doc.getDeletealbe());+ assertNotNull(doc.getWriteable());+ assertEquals(IndexDocument.FIELD_ENTRY_ID,doc.getDeletealbe().field());+ assertEquals(ID,doc.getDeletealbe().text());+ assertEquals(ID,doc.getWriteable().getField(IndexDocument.FIELD_ENTRY_ID).stringValue());+ assertNotNull(doc.getWriteable().getField(CONTENT_FIELD).stringValue());++ try{+ this.zeroFields.call();+ fail("zero fields in document");+ }catch (GdataIndexerException e) {}+ }++ /*+ * Test method for 'org.apache.lucene.gdata.search.index.IndexDocumentBuilderTask.call()'+ */+ public void testCall() throws InterruptedException, ExecutionException {+ ExecutorService service = Executors.newSingleThreadExecutor();+ Future<IndexDocument> future = service.submit(this.fineBuilder);+ IndexDocument doc = future.get();+ assertNotNull(doc.getDeletealbe());+ assertNotNull(doc.getWriteable());+ assertEquals(IndexDocument.FIELD_ENTRY_ID,doc.getDeletealbe().field());+ assertEquals(ID,doc.getDeletealbe().text());+ assertEquals(ID,doc.getWriteable().getField(IndexDocument.FIELD_ENTRY_ID).stringValue());+ assertNotNull(doc.getWriteable().getField(CONTENT_FIELD).stringValue());+ assertTrue(doc.commitAfter());+ assertTrue(doc.optimizeAfter());++ /*+ * the broken xpath fails but the other fields will be indexed+ */+ future = service.submit(this.failInStrategyBuilder);+ doc = future.get();++ assertNotNull(doc.getDeletealbe());+ assertNotNull(doc.getWriteable());+ assertEquals(IndexDocument.FIELD_ENTRY_ID,doc.getDeletealbe().field());+ assertEquals(ID,doc.getDeletealbe().text());+ assertEquals(ID,doc.getWriteable().getField(IndexDocument.FIELD_ENTRY_ID).stringValue());+ assertNotNull(doc.getWriteable().getField(CONTENT_FIELD).stringValue());+ future = service.submit(this.zeroFields);++ try{+ future.get();+ fail("zero fields in document");+ }catch (ExecutionException e) {+ assertTrue(e.getCause().getClass() == GdataIndexerException.class);++ }+ service.shutdownNow();+ }+++++}diff --git a/contrib/gdata-server/src/test/org/apache/lucene/gdata/search/query/TestGdataQueryParser.java b/contrib/gdata-server/src/test/org/apache/lucene/gdata/search/query/TestGdataQueryParser.javanew file mode 100755index 00000000000..09a1927f2f1--- /dev/null+++ b/contrib/gdata-server/src/test/org/apache/lucene/gdata/search/query/TestGdataQueryParser.java@@ -0,0 +1,36 @@+/**+ * Copyright 2004 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.+ */+package org.apache.lucene.gdata.search.query;++import org.apache.lucene.analysis.standard.StandardAnalyzer;+import org.apache.lucene.gdata.search.config.IndexSchema;+import org.apache.lucene.queryParser.QueryParser.Operator;++import junit.framework.TestCase;++public class TestGdataQueryParser extends TestCase {+++ public void testConstructor(){+ String field = "someField";+ IndexSchema s = new IndexSchema();+ s.setDefaultSearchField(field);+ GDataQueryParser p = new GDataQueryParser(s);+ assertEquals(field,p.getField());+ assertEquals(Operator.AND,p.getDefaultOperator());+ assertEquals(StandardAnalyzer.class,p.getAnalyzer().getClass());+ }+}diff --git a/contrib/gdata-server/src/test/org/apache/lucene/gdata/search/query/TestQueryTranslator.java b/contrib/gdata-server/src/test/org/apache/lucene/gdata/search/query/TestQueryTranslator.javanew file mode 100755index 00000000000..bdfe3e78852--- /dev/null+++ b/contrib/gdata-server/src/test/org/apache/lucene/gdata/search/query/TestQueryTranslator.java@@ -0,0 +1,106 @@+/**+ * Copyright 2004 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.+ */+package org.apache.lucene.gdata.search.query;++import java.util.HashMap;+import java.util.Map;++import org.apache.lucene.gdata.search.config.IndexSchema;+import org.apache.lucene.gdata.search.config.IndexSchemaField;+import org.apache.lucene.gdata.search.config.IndexSchemaField.ContentType;+import org.apache.lucene.gdata.utils.ProvidedServiceStub;+import org.apache.lucene.index.Term;+import org.apache.lucene.search.RangeQuery;++import junit.framework.TestCase;++/**+ * @author Simon Willnauer+ *+ */+public class TestQueryTranslator extends TestCase {+ private static final String CONTENT_FIELD = "content";+ private static final String UPDATED_FIELD = "updated";+ private IndexSchema schema;+ Map<String,String[]> parameterMap;+ /*+ * @see junit.framework.TestCase#setUp()+ */+ @Override+ protected void setUp() throws Exception {+ this.schema = new IndexSchema();+ //must be set+ this.schema.setDefaultSearchField(CONTENT_FIELD);+ this.schema.setIndexLocation("/tmp/");+ this.schema.setName(ProvidedServiceStub.SERVICE_NAME);+ IndexSchemaField field = new IndexSchemaField();++ field.setName(CONTENT_FIELD);+ field.setContentType(ContentType.TEXT);++ IndexSchemaField field1 = new IndexSchemaField();+ field1.setName(UPDATED_FIELD);+ field1.setContentType(ContentType.GDATADATE);+ this.schema.addSchemaField(field);+ this.schema.addSchemaField(field1);+ parameterMap = new HashMap<String,String[]>();+++ }++ /*+ * Test method for 'org.apache.lucene.gdata.search.query.QueryTranslator.translateHttpSearchRequest(IndexSchema, Map<String, String>, String, String)'+ */+ public void testTranslateHttpSearchRequest() {+ assertNull(QueryTranslator.translateHttpSearchRequest(this.schema,this.parameterMap,null));+ String contentQuery = "content1 -content2 \"exact Content\"";+ parameterMap.put("q", new String[]{contentQuery});+ String expected = CONTENT_FIELD+":("+contentQuery+") ";++ assertEquals(expected,QueryTranslator.translateHttpSearchRequest(this.schema,this.parameterMap,null));+ parameterMap.put("updated-min", new String[]{"2005-08-09T10:57:00-08:00"});+ parameterMap.put("updated-max", new String[]{"2005-10-09T10:57:00-08:00"});+ parameterMap.put("max-results", new String[]{"3"});+ parameterMap.remove("q");+ parameterMap.put(CONTENT_FIELD, new String[]{"apache"});++ String tranlatedQuery = QueryTranslator.translateHttpSearchRequest(this.schema,this.parameterMap,"test |{urn:google.com} {urn:apache.org}");+ assertTrue(tranlatedQuery.contains("updated:[1123613820000 TO 1128884219999]"));+ assertTrue(tranlatedQuery.contains(CONTENT_FIELD+":(apache)"));++ parameterMap.remove("updated-max");+ tranlatedQuery = QueryTranslator.translateHttpSearchRequest(this.schema,this.parameterMap,"test |{urn:google.com} {urn:apache.org}");+ assertTrue(tranlatedQuery.contains("updated:[1123613820000 TO "+Long.MAX_VALUE+"]"));+ assertTrue(tranlatedQuery.contains(CONTENT_FIELD+":(apache)"));+ parameterMap.put("updated-max", new String[]{"2005-10-09T10:57:00-08:00"});+ parameterMap.remove("updated-min");+ tranlatedQuery = QueryTranslator.translateHttpSearchRequest(this.schema,this.parameterMap,"test |{urn:google.com} {urn:apache.org}");+ assertTrue(tranlatedQuery.contains("updated:["+0+" TO 1128884219999]"));+ assertTrue(tranlatedQuery.contains(CONTENT_FIELD+":(apache)"));++++ parameterMap.put("wrong-parameter", new String[]{"3"});+ try{+ QueryTranslator.translateHttpSearchRequest(this.schema,this.parameterMap,"test |{urn:google.com} {urn:apache.org}");+ fail("illegal parameter");+ }catch (RuntimeException e) {++ }++ }++}diff --git a/contrib/gdata-server/src/test/org/apache/lucene/gdata/server/TestGDataRequest.java b/contrib/gdata-server/src/test/org/apache/lucene/gdata/server/TestGDataRequest.javaindex 229b1f4b806..f635a8e851f 100644--- a/contrib/gdata-server/src/test/org/apache/lucene/gdata/server/TestGDataRequest.java+++ b/contrib/gdata-server/src/test/org/apache/lucene/gdata/server/TestGDataRequest.java@@ -16,17 +16,21 @@package org.apache.lucene.gdata.server;import java.util.Enumeration;+import java.util.HashMap;+import java.util.Map;import java.util.StringTokenizer;import javax.servlet.http.HttpServletRequest;import junit.framework.TestCase;+import org.apache.lucene.gdata.search.config.IndexSchema;+import org.apache.lucene.gdata.search.config.IndexSchemaField;+import org.apache.lucene.gdata.search.config.IndexSchemaField.ContentType;import org.apache.lucene.gdata.server.GDataRequest.GDataRequestType;import org.apache.lucene.gdata.server.GDataRequest.OutputFormat;import org.apache.lucene.gdata.server.registry.GDataServerRegistry;import org.apache.lucene.gdata.server.registry.ProvidedService;-import org.apache.lucene.gdata.server.registry.RegistryException;import org.apache.lucene.gdata.utils.ProvidedServiceStub;import org.apache.lucene.gdata.utils.StorageStub;import org.easymock.MockControl;@@ -43,6 +47,7 @@ public class TestGDataRequest extends TestCase {private GDataRequest feedRequest;+ private Map parametermap = new HashMap();@Overrideprotected void setUp() throws Exception {@@ -52,8 +57,14 @@ public class TestGDataRequest extends TestCase {}ProvidedService configurator = new ProvidedServiceStub();- GDataServerRegistry.getRegistry().registerService(configurator);+ GDataServerRegistry.getRegistry().registerService(configurator);+ IndexSchema schema = new IndexSchema();+ //must be set+ schema.setDefaultSearchField("field");+ schema.setIndexLocation("/tmp/");+ schema.setName(ProvidedServiceStub.SERVICE_NAME);+ ((ProvidedServiceStub)configurator).setIndexSchema(schema);this.control = MockControl.createControl(HttpServletRequest.class);this.request = (HttpServletRequest) this.control.getMock();@@ -64,6 +75,7 @@ public class TestGDataRequest extends TestCase {protected void tearDown() throws Exception {super.tearDown();this.control.reset();+ GDataServerRegistry.getRegistry().destroy();}public void testConstructor() {@@ -88,9 +100,9 @@ public class TestGDataRequest extends TestCase {}public void testGetFeedId() throws GDataRequestException {-+ this.control.expectAndDefaultReturn(this.request.getParameterMap(),this.parametermap);this.control.expectAndDefaultReturn(this.request.getPathInfo(),- "/feed/1/1");+ "/"+ProvidedServiceStub.SERVICE_NAME+"/feed/1/1");this.control.expectAndDefaultReturn(this.request.getParameter("alt"),null);this.control.replay();@@ -118,8 +130,9 @@ public class TestGDataRequest extends TestCase {}public void testGetFeedIdWithoutEntry() throws GDataRequestException {+ this.control.expectAndDefaultReturn(this.request.getParameterMap(),this.parametermap);this.control- .expectAndDefaultReturn(this.request.getPathInfo(), "/feed");+ .expectAndDefaultReturn(this.request.getPathInfo(), "/"+ProvidedServiceStub.SERVICE_NAME+"/feed");this.control.expectAndDefaultReturn(this.request.getParameter("alt"),null);this.control.replay();@@ -128,9 +141,9 @@ public class TestGDataRequest extends TestCase {}public void testGetEntyId() throws GDataRequestException {-+ this.control.expectAndDefaultReturn(this.request.getParameterMap(),this.parametermap);this.control.expectAndDefaultReturn(this.request.getPathInfo(),- "/feed/1/15");+ "/"+ProvidedServiceStub.SERVICE_NAME+"/feed/1/15");this.control.expectAndDefaultReturn(this.request.getParameter("alt"),null);this.control.replay();@@ -143,10 +156,11 @@ public class TestGDataRequest extends TestCase {}public void testSetResponseFormatAtom() throws GDataRequestException {+ this.control.expectAndDefaultReturn(this.request.getParameterMap(),this.parametermap);this.control.expectAndDefaultReturn(this.request.getParameter("alt"),"atom");this.control- .expectAndDefaultReturn(this.request.getPathInfo(), "/feed");+ .expectAndDefaultReturn(this.request.getPathInfo(),"/"+ProvidedServiceStub.SERVICE_NAME+ "/feed");this.control.replay();this.feedRequest.initializeRequest();assertEquals("ResponseFromat Atom", this.feedRequest@@ -155,10 +169,11 @@ public class TestGDataRequest extends TestCase {}public void testSetResponseFormatRSS() throws GDataRequestException {+ this.control.expectAndDefaultReturn(this.request.getParameterMap(),this.parametermap);this.control.expectAndDefaultReturn(this.request.getParameter("alt"),"rss");this.control- .expectAndDefaultReturn(this.request.getPathInfo(), "/feed");+ .expectAndDefaultReturn(this.request.getPathInfo(), "/"+ProvidedServiceStub.SERVICE_NAME+"/feed");this.control.replay();this.feedRequest.initializeRequest();assertEquals("ResponseFromat RSS", this.feedRequest@@ -167,10 +182,11 @@ public class TestGDataRequest extends TestCase {}public void testSetResponseFormatKeepAtom() throws GDataRequestException {+ this.control.expectAndDefaultReturn(this.request.getParameterMap(),this.parametermap);this.control.expectAndDefaultReturn(this.request.getParameter("alt"),"fooBar");this.control- .expectAndDefaultReturn(this.request.getPathInfo(), "/feed");+ .expectAndDefaultReturn(this.request.getPathInfo(), "/"+ProvidedServiceStub.SERVICE_NAME+"/feed");this.control.replay();this.feedRequest.initializeRequest();assertEquals("ResponseFromat Atom", this.feedRequest@@ -179,11 +195,12 @@ public class TestGDataRequest extends TestCase {}public void testSetResponseFormatNull() throws GDataRequestException {+ this.control.expectAndDefaultReturn(this.request.getParameterMap(),this.parametermap);this.control.expectAndDefaultReturn(this.request.getParameter("alt"),null);this.control- .expectAndDefaultReturn(this.request.getPathInfo(), "/feed");+ .expectAndDefaultReturn(this.request.getPathInfo(), "/"+ProvidedServiceStub.SERVICE_NAME+"/feed");this.control.replay();this.feedRequest.initializeRequest();assertEquals("ResponseFromat Atom", this.feedRequest@@ -223,11 +240,12 @@ public class TestGDataRequest extends TestCase {public void testGetSelfId() throws GDataRequestException{String host = "www.apache.org";- String feedAndEntryID = "/feed/entryid";+ String feedAndEntryID = "/"+ProvidedServiceStub.SERVICE_NAME+"/feed/entryid";String queryString = "max-results=25";+ this.control.expectAndDefaultReturn(this.request.getParameterMap(),this.parametermap);this.control.expectAndDefaultReturn(this.request.getHeader("Host"),host);- this.control.expectAndDefaultReturn(this.request.getRequestURI(),"/host/feed/entryId/15/");- this.control.expectAndDefaultReturn(this.request.getPathInfo(),"/feed/entryId/15");+ this.control.expectAndDefaultReturn(this.request.getRequestURI(),"/host"+"/"+ProvidedServiceStub.SERVICE_NAME+"/feed/entryId/15/");+ this.control.expectAndDefaultReturn(this.request.getPathInfo(),"/"+ProvidedServiceStub.SERVICE_NAME+"/feed/entryId/15");this.control.expectAndReturn(this.request.getParameter("max-results"),"25",2);this.control.expectAndDefaultReturn(this.request.getParameter("alt"),null);@@ -235,15 +253,16 @@ public class TestGDataRequest extends TestCase {queryString);this.control.replay();this.feedRequest.initializeRequest();- String selfID = "http://"+host+"/host/feed/entryId/15?"+queryString;+ String selfID = "http://"+host+"/host"+"/"+ProvidedServiceStub.SERVICE_NAME+"/feed/entryId/15?"+queryString;assertEquals("Self ID",selfID,this.feedRequest.getSelfId());this.control.reset();- queryString = "alt=rss&max-results=25";+ queryString = "alt=rss&max-results=25";+ this.control.expectAndDefaultReturn(this.request.getParameterMap(),this.parametermap);this.control.expectAndDefaultReturn(this.request.getHeader("Host"),host);- this.control.expectAndDefaultReturn(this.request.getRequestURI(),"/host/feed/entryId/15");- this.control.expectAndDefaultReturn(this.request.getPathInfo(),"/feed/entryId/15");+ this.control.expectAndDefaultReturn(this.request.getRequestURI(),"/host"+"/"+ProvidedServiceStub.SERVICE_NAME+"/feed/entryId/15/");+ this.control.expectAndDefaultReturn(this.request.getPathInfo(),"/"+ProvidedServiceStub.SERVICE_NAME+"/feed/entryId/15");this.control.expectAndReturn(this.request.getParameter("max-results"),"25",2);this.control.expectAndDefaultReturn(this.request.getParameter("alt"),null);@@ -251,15 +270,16 @@ public class TestGDataRequest extends TestCase {queryString);this.control.replay();this.feedRequest.initializeRequest();- selfID = "http://"+host+"/host/feed/entryId/15?"+queryString;+ selfID = "http://"+host+"/host"+"/"+ProvidedServiceStub.SERVICE_NAME+"/feed/entryId/15?"+queryString;assertEquals("Self ID",selfID,this.feedRequest.getSelfId());this.control.reset();queryString = "";+ this.control.expectAndDefaultReturn(this.request.getParameterMap(),this.parametermap);this.control.expectAndDefaultReturn(this.request.getHeader("Host"),host);- this.control.expectAndDefaultReturn(this.request.getRequestURI(),"/host/feed/entryId/15");- this.control.expectAndDefaultReturn(this.request.getPathInfo(),"/feed/entryId/15");+ this.control.expectAndDefaultReturn(this.request.getRequestURI(),"/host"+"/"+ProvidedServiceStub.SERVICE_NAME+"/feed/entryId/15/");+ this.control.expectAndDefaultReturn(this.request.getPathInfo(),"/"+ProvidedServiceStub.SERVICE_NAME+"/feed/entryId/15");this.control.expectAndDefaultReturn(this.request.getParameter("max-results"),null);this.control.expectAndDefaultReturn(this.request.getParameter("alt"),null);@@ -267,7 +287,7 @@ public class TestGDataRequest extends TestCase {null);this.control.replay();this.feedRequest.initializeRequest();- selfID = "http://"+host+"/host/feed/entryId/15"+"?max-results=25";+ selfID = "http://"+host+"/host"+"/"+ProvidedServiceStub.SERVICE_NAME+"/feed/entryId/15"+"?max-results=25";assertEquals("Self ID",selfID,this.feedRequest.getSelfId());this.control.reset();@@ -311,10 +331,10 @@ public class TestGDataRequest extends TestCase {public void testIsFeedRequest() throws GDataRequestException{String host = "www.apache.org";String feedAndEntryID = "/feed";-+ this.control.expectAndDefaultReturn(this.request.getParameterMap(),this.parametermap);this.control.expectAndDefaultReturn(this.request.getHeader("Host"),host);- this.control.expectAndDefaultReturn(this.request.getRequestURI(),"/host/feed");- this.control.expectAndDefaultReturn(this.request.getPathInfo(),"/feed");+ this.control.expectAndDefaultReturn(this.request.getRequestURI(),"/host"+"/"+ProvidedServiceStub.SERVICE_NAME+"/feed");+ this.control.expectAndDefaultReturn(this.request.getPathInfo(),"/"+ProvidedServiceStub.SERVICE_NAME+"/feed");this.control.expectAndDefaultReturn(this.request.getParameter("alt"),null);@@ -329,10 +349,10 @@ public class TestGDataRequest extends TestCase {this.control.reset();host = "www.apache.org";- feedAndEntryID = "/feed/1";-+ feedAndEntryID = "/"+ProvidedServiceStub.SERVICE_NAME+"/feed/1";+ this.control.expectAndDefaultReturn(this.request.getParameterMap(),this.parametermap);this.control.expectAndDefaultReturn(this.request.getHeader("Host"),host);- this.control.expectAndDefaultReturn(this.request.getRequestURI(),"/host/feed/1");+ this.control.expectAndDefaultReturn(this.request.getRequestURI(),"/host"+"/"+ProvidedServiceStub.SERVICE_NAME+"/feed/1");this.control.expectAndDefaultReturn(this.request.getPathInfo(),feedAndEntryID);this.control.expectAndDefaultReturn(this.request.getParameter("alt"),@@ -346,6 +366,46 @@ public class TestGDataRequest extends TestCase {assertFalse(this.feedRequest.isFeedRequested());assertTrue(this.feedRequest.isEntryRequested());this.control.reset();++ host = "www.apache.org";+ feedAndEntryID = "/"+ProvidedServiceStub.SERVICE_NAME+"/feed/1";+ this.control.expectAndDefaultReturn(this.request.getParameterMap(),this.parametermap);+ this.control.expectAndDefaultReturn(this.request.getHeader("Host"),host);+ this.control.expectAndDefaultReturn(this.request.getRequestURI(),"/host"+"/"+"NOTREGISTERED"+"/feed/1");+ this.control.expectAndDefaultReturn(this.request.getPathInfo(),"/"+"NOTREGISTERED"+"/feed/1");++ this.control.expectAndDefaultReturn(this.request.getParameter("alt"),+ null);+ this.control.expectAndDefaultReturn(this.request.getQueryString(),+ null);+ this.control.replay();+ try{+ this.feedRequest.initializeRequest();+ fail("service not registered");+ }catch (GDataRequestException e) {+ //+ }+ this.control.reset();++ host = "www.apache.org";+ feedAndEntryID = "/"+ProvidedServiceStub.SERVICE_NAME+"/feed/1";+ this.control.expectAndDefaultReturn(this.request.getParameterMap(),this.parametermap);+ this.control.expectAndDefaultReturn(this.request.getHeader("Host"),host);+ this.control.expectAndDefaultReturn(this.request.getRequestURI(),"/host"+"/"+ProvidedServiceStub.SERVICE_NAME+"/");+ this.control.expectAndDefaultReturn(this.request.getPathInfo(),"/"+ProvidedServiceStub.SERVICE_NAME+"/");++ this.control.expectAndDefaultReturn(this.request.getParameter("alt"),+ null);+ this.control.expectAndDefaultReturn(this.request.getQueryString(),+ null);+ this.control.replay();+ try{+ this.feedRequest.initializeRequest();+ fail("service not registered");+ }catch (GDataRequestException e) {+//+ }+ this.control.reset();}@@ -356,21 +416,45 @@ public class TestGDataRequest extends TestCase {this.control.verify();this.control.reset();+ this.control.expectAndDefaultReturn(this.request.getHeader("Authentication"),null);+ this.control.replay();+ assertNull(this.feedRequest.getAuthToken());+ this.control.verify();+ this.control.reset();+}++ public void testGetStartIndex(){+ this.control.expectAndDefaultReturn(this.request.getParameter("start-index"),"5");+ this.control.replay();+ assertEquals(5,this.feedRequest.getStartIndex());+ this.control.verify();+ this.control.reset();+ this.control.expectAndDefaultReturn(this.request.getParameter("start-index"),"-5");+ this.control.replay();+ assertEquals(1,this.feedRequest.getStartIndex());+ this.control.verify();+ this.control.reset();+ this.control.expectAndDefaultReturn(this.request.getParameter("start-index"),"unparsable");+ this.control.replay();+ assertEquals(1,this.feedRequest.getStartIndex());+ this.control.verify();+ this.control.reset();+ }public void testGetNextId() throws GDataRequestException{String host = "www.apache.org";- String feedAndEntryID = "/feed/entryid";- String queryString = "?max-results=25";- String startIndex = "&start-index=26";+ String feedAndEntryID = "/"+ProvidedServiceStub.SERVICE_NAME+"/feed/entryid";+ String queryString = "max-results=25";+ String startIndex = "start-index=26";Enumeration enu = new StringTokenizer("max-results",",");-+ this.control.expectAndDefaultReturn(this.request.getParameterMap(),this.parametermap);this.control.expectAndDefaultReturn(this.request.getParameterNames(),enu);this.control.expectAndDefaultReturn(this.request.getHeader("Host"),host);- this.control.expectAndDefaultReturn(this.request.getRequestURI(),"/feed/");- this.control.expectAndDefaultReturn(this.request.getPathInfo(),"/feed/");- this.control.expectAndReturn(this.request.getParameter("max-results"),"25",4);+ this.control.expectAndDefaultReturn(this.request.getRequestURI(),"/"+ProvidedServiceStub.SERVICE_NAME+"/feed/");+ this.control.expectAndDefaultReturn(this.request.getPathInfo(),"/"+ProvidedServiceStub.SERVICE_NAME+"/feed/");+ this.control.expectAndReturn(this.request.getParameter("max-results"),"25",3);this.control.expectAndReturn(this.request.getParameter("start-index"),null);this.control.expectAndDefaultReturn(this.request.getParameter("alt"),null);@@ -379,24 +463,24 @@ public class TestGDataRequest extends TestCase {this.control.replay();this.feedRequest.initializeRequest();- String nextID = "http://"+host+"/feed"+queryString+startIndex;+ String nextID = "http://"+host+"/"+ProvidedServiceStub.SERVICE_NAME+"/feed?"+startIndex+"&"+queryString;assertEquals("Next ID",nextID,this.feedRequest.getNextId());this.control.verify();this.control.reset();enu = new StringTokenizer("alt,max-results,start-index",",");- queryString = "?alt=rss&max-results=25";-+ queryString = "alt=rss&max-results=25";+ this.control.expectAndDefaultReturn(this.request.getParameterMap(),this.parametermap);this.control.expectAndDefaultReturn(this.request.getHeader("Host"),host);- this.control.expectAndDefaultReturn(this.request.getRequestURI(),"/feed/");- this.control.expectAndDefaultReturn(this.request.getPathInfo(),"/feed/");+ this.control.expectAndDefaultReturn(this.request.getRequestURI(),"/"+ProvidedServiceStub.SERVICE_NAME+"/feed/");+ this.control.expectAndDefaultReturn(this.request.getPathInfo(),"/"+ProvidedServiceStub.SERVICE_NAME+"/feed/");this.control.expectAndReturn(this.request.getParameter("max-results"),"25",4);this.control.expectAndReturn(this.request.getParameter("start-index"),"26",4);this.control.expectAndDefaultReturn(this.request.getParameter("alt"),"rss");this.control.expectAndDefaultReturn(this.request.getQueryString(),- queryString+startIndex);+ queryString+"&"+startIndex);this.control.expectAndDefaultReturn(this.request.getParameterNames(),enu);@@ -404,15 +488,16 @@ public class TestGDataRequest extends TestCase {this.control.replay();this.feedRequest.initializeRequest();startIndex = "&start-index=51";- nextID = "http://"+host+"/feed"+queryString+startIndex;+ nextID = "http://"+host+"/"+ProvidedServiceStub.SERVICE_NAME+"/feed?"+queryString+startIndex;assertEquals("Next ID 51",nextID,this.feedRequest.getNextId());this.control.reset();queryString = "";+ this.control.expectAndDefaultReturn(this.request.getParameterMap(),this.parametermap);this.control.expectAndDefaultReturn(this.request.getHeader("Host"),host);- this.control.expectAndDefaultReturn(this.request.getRequestURI(),"/feed/");- this.control.expectAndDefaultReturn(this.request.getPathInfo(),"/feed/entryId/15");+ this.control.expectAndDefaultReturn(this.request.getRequestURI(),"/"+ProvidedServiceStub.SERVICE_NAME+"/feed/");+ this.control.expectAndDefaultReturn(this.request.getPathInfo(),"/"+ProvidedServiceStub.SERVICE_NAME+"/feed/entryId/15");this.control.expectAndDefaultReturn(this.request.getParameter("max-results"),null);this.control.expectAndDefaultReturn(this.request.getParameter("alt"),null);@@ -420,29 +505,177 @@ public class TestGDataRequest extends TestCase {null);this.control.replay();this.feedRequest.initializeRequest();- String selfID = "http://"+host+"/feed"+"?max-results=25";+ String nextId = "http://"+host+"/"+ProvidedServiceStub.SERVICE_NAME+"/feed"+"?max-results=25&start-index=26";- assertEquals("Self ID",selfID,this.feedRequest.getSelfId());+ assertEquals("next ID",nextId,this.feedRequest.getNextId());+ this.control.reset();+++ this.control.expectAndDefaultReturn(this.request.getParameterMap(),this.parametermap);+ this.control.expectAndDefaultReturn(this.request.getHeader("Host"),host);+ this.control.expectAndDefaultReturn(this.request.getRequestURI(),"/"+ProvidedServiceStub.SERVICE_NAME+"/feed/");+ this.control.expectAndDefaultReturn(this.request.getPathInfo(),"/"+ProvidedServiceStub.SERVICE_NAME+"/feed/entryId/15");+ this.control.expectAndReturn(this.request.getParameter("max-results"),null,3);+ this.control.expectAndReturn(this.request.getParameter("start-index"),null,3);+ this.control.expectAndDefaultReturn(this.request.getParameter("alt"),+ null);+ this.control.expectAndDefaultReturn(this.request.getQueryString(),+ null);+ this.control.replay();+ this.feedRequest.initializeRequest();+ nextId = "http://"+host+"/"+ProvidedServiceStub.SERVICE_NAME+"/feed"+"?max-results=25&start-index=26";+ assertEquals("nextID",nextId,this.feedRequest.getNextId());+ }++ public void testGetpreviousId() throws GDataRequestException{+ String host = "www.apache.org";+ String feedAndEntryID = "/"+ProvidedServiceStub.SERVICE_NAME+"/feed/entryid";+ String queryString = "max-results=25";++ Enumeration enu = new StringTokenizer("max-results",",");++ this.control.expectAndDefaultReturn(this.request.getParameterMap(),this.parametermap);+ this.control.expectAndDefaultReturn(this.request.getParameterNames(),enu);+ this.control.expectAndDefaultReturn(this.request.getHeader("Host"),host);+ this.control.expectAndDefaultReturn(this.request.getRequestURI(),"/"+ProvidedServiceStub.SERVICE_NAME+"/feed/");+ this.control.expectAndDefaultReturn(this.request.getPathInfo(),"/"+ProvidedServiceStub.SERVICE_NAME+"/feed/");+ this.control.expectAndReturn(this.request.getParameter("start-index"),null);+ this.control.expectAndDefaultReturn(this.request.getParameter("alt"),+ null);+ this.control.expectAndDefaultReturn(this.request.getQueryString(),+ queryString);+ this.control.replay();++ this.feedRequest.initializeRequest();+++ assertNull(this.feedRequest.getPreviousId());+ this.control.verify();+ this.control.reset();+ String startIndex = "start-index=";+ enu = new StringTokenizer("alt,max-results,start-index",",");+ queryString = "alt=rss&max-results=25&start-index=26";+ this.control.expectAndDefaultReturn(this.request.getParameterMap(),this.parametermap);+ this.control.expectAndDefaultReturn(this.request.getHeader("Host"),host);+ this.control.expectAndDefaultReturn(this.request.getRequestURI(),"/"+ProvidedServiceStub.SERVICE_NAME+"/feed/");+ this.control.expectAndDefaultReturn(this.request.getPathInfo(),"/"+ProvidedServiceStub.SERVICE_NAME+"/feed/");+ this.control.expectAndReturn(this.request.getParameter("max-results"),"25",4);+ this.control.expectAndReturn(this.request.getParameter("start-index"),"26",4);+ this.control.expectAndDefaultReturn(this.request.getParameter("alt"),+ "rss");+ this.control.expectAndDefaultReturn(this.request.getQueryString(),+ queryString);++ this.control.expectAndDefaultReturn(this.request.getParameterNames(),enu);+++ this.control.replay();+ this.feedRequest.initializeRequest();++ String prevId = "http://"+host+"/"+ProvidedServiceStub.SERVICE_NAME+"/feed"+"?alt=rss&max-results=25&start-index=1";+ assertEquals("prevID",prevId,this.feedRequest.getPreviousId());+this.control.reset();++ queryString = "";+ this.control.expectAndDefaultReturn(this.request.getParameterMap(),this.parametermap);+ this.control.expectAndDefaultReturn(this.request.getHeader("Host"),host);+ this.control.expectAndDefaultReturn(this.request.getRequestURI(),"/"+ProvidedServiceStub.SERVICE_NAME+"/feed/");+ this.control.expectAndDefaultReturn(this.request.getPathInfo(),"/"+ProvidedServiceStub.SERVICE_NAME+"/feed/entryId/15");+ this.control.expectAndDefaultReturn(this.request.getParameter("max-results"),null);+ this.control.expectAndDefaultReturn(this.request.getParameter("alt"),+ null);+ this.control.expectAndDefaultReturn(this.request.getQueryString(),+ null);+ this.control.replay();+ this.feedRequest.initializeRequest();+ assertNull(this.feedRequest.getPreviousId());+++ this.control.reset();++ this.control.expectAndDefaultReturn(this.request.getParameterMap(),this.parametermap);+ this.control.expectAndDefaultReturn(this.request.getHeader("Host"),host);+ this.control.expectAndDefaultReturn(this.request.getRequestURI(),"/"+ProvidedServiceStub.SERVICE_NAME+"/feed/");+ this.control.expectAndDefaultReturn(this.request.getPathInfo(),"/"+ProvidedServiceStub.SERVICE_NAME+"/feed/entryId/15");+ this.control.expectAndReturn(this.request.getParameter("max-results"),"35",3);+ this.control.expectAndReturn(this.request.getParameter("start-index"),"5",3);+ this.control.expectAndDefaultReturn(this.request.getParameter("alt"),+ null);+ this.control.expectAndDefaultReturn(this.request.getQueryString(),+ "max-results=35&start-index=5");+ this.control.replay();+ this.feedRequest.initializeRequest();+ prevId = "http://"+host+"/"+ProvidedServiceStub.SERVICE_NAME+"/feed"+"?max-results=35&start-index=1";+ assertEquals("prevID",prevId,this.feedRequest.getPreviousId());++++}public void testGetContextPath(){String host = "www.apache.org";this.control.expectAndDefaultReturn(this.request.getHeader("Host"),host);- this.control.expectAndDefaultReturn(this.request.getRequestURI(),"/feed/id/");- this.control.expectAndDefaultReturn(this.request.getPathInfo(),"/feed/id/");+ this.control.expectAndDefaultReturn(this.request.getRequestURI(),"/"+ProvidedServiceStub.SERVICE_NAME+"/feed/id/");+ this.control.expectAndDefaultReturn(this.request.getPathInfo(),"/"+ProvidedServiceStub.SERVICE_NAME+"/feed/id/");this.control.replay();- String result = "http://"+host+"/feed/id/";+ String result = "http://"+host+"/"+ProvidedServiceStub.SERVICE_NAME+"/feed/id/";assertEquals(result,this.feedRequest.getContextPath());this.control.verify();this.control.reset();this.control.expectAndDefaultReturn(this.request.getHeader("Host"),host);- this.control.expectAndDefaultReturn(this.request.getRequestURI(),"/feed/id");- this.control.expectAndDefaultReturn(this.request.getPathInfo(),"/feed/id");+ this.control.expectAndDefaultReturn(this.request.getRequestURI(),"/"+ProvidedServiceStub.SERVICE_NAME+"/feed/id");+ this.control.expectAndDefaultReturn(this.request.getPathInfo(),"/"+ProvidedServiceStub.SERVICE_NAME+"/feed/id");this.control.replay();assertEquals(result,this.feedRequest.getContextPath());this.control.verify();}++ public void testCategoryQuery() throws GDataRequestException{+ String host = "www.apache.org";+ String feedAndEntryID = "/feed";+ this.control.expectAndDefaultReturn(this.request.getParameterMap(),this.parametermap);+ this.control.expectAndDefaultReturn(this.request.getHeader("Host"),host);+ this.control.expectAndDefaultReturn(this.request.getRequestURI(),"/host"+"/"+ProvidedServiceStub.SERVICE_NAME+"/feed/-/test");+ this.control.expectAndDefaultReturn(this.request.getPathInfo(),"/"+ProvidedServiceStub.SERVICE_NAME+"/feed/-/test");++ this.control.expectAndDefaultReturn(this.request.getParameter("alt"),+ null);+ this.control.expectAndDefaultReturn(this.request.getQueryString(),+ null);+ this.control.replay();+ this.feedRequest.initializeRequest();+++ assertTrue(this.feedRequest.isFeedRequested());+ assertFalse(this.feedRequest.isEntryRequested());+ assertNotNull(this.feedRequest.getTranslatedQuery());+ this.control.verify();+ this.control.reset();+ this.feedRequest = new GDataRequest(this.request,GDataRequestType.GET);+ this.control.expectAndDefaultReturn(this.request.getParameterMap(),this.parametermap);+ this.control.expectAndDefaultReturn(this.request.getHeader("Host"),host);+ this.control.expectAndDefaultReturn(this.request.getRequestURI(),"/host"+"/"+ProvidedServiceStub.SERVICE_NAME+"/feed/");+ this.control.expectAndDefaultReturn(this.request.getPathInfo(),"/"+ProvidedServiceStub.SERVICE_NAME+"/feed/");++ this.control.expectAndDefaultReturn(this.request.getParameter("alt"),+ null);+ this.control.expectAndDefaultReturn(this.request.getQueryString(),+ null);+ this.control.replay();+ this.feedRequest.initializeRequest();+++ assertTrue(this.feedRequest.isFeedRequested());+ assertFalse(this.feedRequest.isEntryRequested());+ assertNull(this.feedRequest.getTranslatedQuery());+ this.control.verify();+ this.control.reset();+ }+++}diff --git a/contrib/gdata-server/src/test/org/apache/lucene/gdata/server/TestGDataResponse.java b/contrib/gdata-server/src/test/org/apache/lucene/gdata/server/TestGDataResponse.javaindex e2450eed305..59750181c28 100644--- a/contrib/gdata-server/src/test/org/apache/lucene/gdata/server/TestGDataResponse.java+++ b/contrib/gdata-server/src/test/org/apache/lucene/gdata/server/TestGDataResponse.java@@ -1,3 +1,18 @@+/**+ * Copyright 2004 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.+ */package org.apache.lucene.gdata.server;import java.io.IOException;diff --git a/contrib/gdata-server/src/test/org/apache/lucene/gdata/server/administration/TestAccountBuilder.java b/contrib/gdata-server/src/test/org/apache/lucene/gdata/server/administration/TestAccountBuilder.javaindex 57bb300ab84..7ed8586f158 100644--- a/contrib/gdata-server/src/test/org/apache/lucene/gdata/server/administration/TestAccountBuilder.java+++ b/contrib/gdata-server/src/test/org/apache/lucene/gdata/server/administration/TestAccountBuilder.java@@ -1,3 +1,18 @@+/**+ * Copyright 2004 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.+ */package org.apache.lucene.gdata.server.administration;import java.io.IOException;diff --git a/contrib/gdata-server/src/test/org/apache/lucene/gdata/server/registry/TestProvidedServiceConfig.java b/contrib/gdata-server/src/test/org/apache/lucene/gdata/server/registry/TestProvidedServiceConfig.javanew file mode 100755index 00000000000..cc8402a092f--- /dev/null+++ b/contrib/gdata-server/src/test/org/apache/lucene/gdata/server/registry/TestProvidedServiceConfig.java@@ -0,0 +1,105 @@+/**+ * Copyright 2004 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.+ */+package org.apache.lucene.gdata.server.registry;++import junit.framework.TestCase;++import com.google.gdata.data.Entry;+import com.google.gdata.data.ExtensionProfile;+import com.google.gdata.data.Feed;++public class TestProvidedServiceConfig extends TestCase {+ ProvidedServiceConfig instance;+ protected void setUp() throws Exception {+ instance = new ProvidedServiceConfig();+ instance.setExtensionProfileClass(ExtensionProfile.class);+ instance.setFeedType(Feed.class);+ instance.setEntryType(Entry.class);+ }++ protected void tearDown() throws Exception {+ super.tearDown();+ instance.destroy();+ }++ /*+ * Test method for 'org.apache.lucene.gdata.server.registry.ProvidedServiceConfig.getExtensionProfile()'+ */+ public void testGetExtensionProfile() {+ try{+ this.instance.setExtensionProfile(null);+ fail("value must not be null");+ }catch (IllegalArgumentException e) {++ }+ ExtensionProfile profile = this.instance.getExtensionProfile();+ assertNotNull(profile);+ assertSame(profile,this.instance.getExtensionProfile());+ this.instance.visiteInitialize();+ assertSame(profile,this.instance.getExtensionProfile());+ assertNull(new ProvidedServiceConfig().getExtensionProfile());+ }++ /*+ * Test method for 'org.apache.lucene.gdata.server.registry.ProvidedServiceConfig.setExtensionProfile(ExtensionProfile)'+ */+ public void testSetPoolSize() throws InstantiationException, IllegalAccessException {+ assertEquals(5,instance.getPoolSize());+ instance.destroy();+ instance = new ProvidedServiceConfig();+ instance.setExtensionProfileClass(ExtensionProfile.class);+ instance.setFeedType(Feed.class);+ instance.setEntryType(Entry.class);+ instance.setPoolSize(30);+ instance.visiteInitialize();+ assertEquals(30,instance.getPoolSize());+ instance.destroy();+ instance = new ProvidedServiceConfig();+ instance.setExtensionProfileClass(ExtensionProfile.class);+ instance.setFeedType(Feed.class);+ instance.setEntryType(Entry.class);+ instance.setPoolSize(-5);+ instance.visiteInitialize();+ assertEquals(5,instance.getPoolSize());+ }+++++ /*+ * Test method for 'org.apache.lucene.gdata.server.registry.ProvidedServiceConfig.visiteInitialize()'+ */+ public void testVisiteInitialize() {+ instance.visiteInitialize();+ assertNull(instance.extProfThreadLocal.get());+ instance.getExtensionProfile();+ assertNotNull(instance.extProfThreadLocal.get());+ }++ /*+ * Test method for 'org.apache.lucene.gdata.server.registry.ProvidedServiceConfig.visiteDestroy()'+ */+ public void testVisiteDestroy() {+ ExtensionProfile profile = this.instance.getExtensionProfile();+ assertNotNull(profile);+ assertNotNull(instance.extProfThreadLocal.get());+ instance.visiteDestroy();+ assertNull(instance.extProfThreadLocal.get());+ instance.visiteDestroy();+ assertNull(instance.extProfThreadLocal.get());+ }++}diff --git a/contrib/gdata-server/src/test/org/apache/lucene/gdata/server/registry/configuration/TestConfigurationBean.java b/contrib/gdata-server/src/test/org/apache/lucene/gdata/server/registry/configuration/TestConfigurationBean.javaindex 4e1a25670df..f66d2a9edb5 100755--- a/contrib/gdata-server/src/test/org/apache/lucene/gdata/server/registry/configuration/TestConfigurationBean.java+++ b/contrib/gdata-server/src/test/org/apache/lucene/gdata/server/registry/configuration/TestConfigurationBean.java@@ -1,3 +1,18 @@+/**+ * Copyright 2004 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.+ */package org.apache.lucene.gdata.server.registry.configuration;import junit.framework.TestCase;diff --git a/contrib/gdata-server/src/test/org/apache/lucene/gdata/server/registry/configuration/TestPropertyInjector.java b/contrib/gdata-server/src/test/org/apache/lucene/gdata/server/registry/configuration/TestPropertyInjector.javaindex fa8346ac360..54b706a9d77 100755--- a/contrib/gdata-server/src/test/org/apache/lucene/gdata/server/registry/configuration/TestPropertyInjector.java+++ b/contrib/gdata-server/src/test/org/apache/lucene/gdata/server/registry/configuration/TestPropertyInjector.java@@ -1,3 +1,18 @@+/**+ * Copyright 2004 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.+ */package org.apache.lucene.gdata.server.registry.configuration;import junit.framework.TestCase;diff --git a/contrib/gdata-server/src/test/org/apache/lucene/gdata/servlet/TestAbstractGdataServlet.java b/contrib/gdata-server/src/test/org/apache/lucene/gdata/servlet/TestAbstractGdataServlet.javaindex 477e738ac8d..3a19426fffb 100644--- a/contrib/gdata-server/src/test/org/apache/lucene/gdata/servlet/TestAbstractGdataServlet.java+++ b/contrib/gdata-server/src/test/org/apache/lucene/gdata/servlet/TestAbstractGdataServlet.java@@ -1,3 +1,18 @@+/**+ * Copyright 2004 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.+ */package org.apache.lucene.gdata.servlet;import java.io.IOException;diff --git a/contrib/gdata-server/src/test/org/apache/lucene/gdata/servlet/handler/TestAbstractFeedHandler.java b/contrib/gdata-server/src/test/org/apache/lucene/gdata/servlet/handler/TestAbstractFeedHandler.javaindex e53cd970750..f9a0f71f9b0 100644--- a/contrib/gdata-server/src/test/org/apache/lucene/gdata/servlet/handler/TestAbstractFeedHandler.java+++ b/contrib/gdata-server/src/test/org/apache/lucene/gdata/servlet/handler/TestAbstractFeedHandler.java@@ -27,6 +27,7 @@ import junit.framework.TestCase;import org.apache.lucene.gdata.data.GDataAccount;import org.apache.lucene.gdata.data.ServerBaseFeed;+import org.apache.lucene.gdata.server.GDataResponse;import org.apache.lucene.gdata.server.ServiceException;import org.apache.lucene.gdata.server.ServiceFactory;import org.apache.lucene.gdata.server.administration.AdminService;@@ -184,7 +185,7 @@ public class TestAbstractFeedHandler extends TestCase {.getParameter(AbstractFeedHandler.PARAMETER_ACCOUNT), this.accountName);a.setName("helloworld");- this.adminServiceMockControl.expectAndDefaultThrow(this.adminService.getAccount(this.accountName),new ServiceException() );+ this.adminServiceMockControl.expectAndDefaultThrow(this.adminService.getAccount(this.accountName),new ServiceException(GDataResponse.BAD_REQUEST) );this.requestMockControl.replay();this.adminServiceMockControl.replay();handler = new InsertFeedHandler();diff --git a/contrib/gdata-server/src/test/org/apache/lucene/gdata/servlet/handler/TestRequestAuthenticator.java b/contrib/gdata-server/src/test/org/apache/lucene/gdata/servlet/handler/TestRequestAuthenticator.javaindex 1a780ea9a9b..ace688a48d8 100644--- a/contrib/gdata-server/src/test/org/apache/lucene/gdata/servlet/handler/TestRequestAuthenticator.java+++ b/contrib/gdata-server/src/test/org/apache/lucene/gdata/servlet/handler/TestRequestAuthenticator.java@@ -1,3 +1,18 @@+/**+ * Copyright 2004 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.+ */package org.apache.lucene.gdata.servlet.handler;import javax.servlet.http.Cookie;diff --git a/contrib/gdata-server/src/test/org/apache/lucene/gdata/storage/TestIDGenerator.java b/contrib/gdata-server/src/test/org/apache/lucene/gdata/storage/TestIDGenerator.javaindex a03c4ca215d..f320d162a1b 100644--- a/contrib/gdata-server/src/test/org/apache/lucene/gdata/storage/TestIDGenerator.java+++ b/contrib/gdata-server/src/test/org/apache/lucene/gdata/storage/TestIDGenerator.java@@ -1,3 +1,18 @@+/**+ * Copyright 2004 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.+ */package org.apache.lucene.gdata.storage;import java.util.ArrayList;diff --git a/contrib/gdata-server/src/test/org/apache/lucene/gdata/storage/db4o/TestDb4oStorage.java b/contrib/gdata-server/src/test/org/apache/lucene/gdata/storage/db4o/TestDb4oStorage.javaindex b1c519f74d8..ff2d09458d1 100755--- a/contrib/gdata-server/src/test/org/apache/lucene/gdata/storage/db4o/TestDb4oStorage.java+++ b/contrib/gdata-server/src/test/org/apache/lucene/gdata/storage/db4o/TestDb4oStorage.java@@ -1,7 +1,21 @@+/**+ * Copyright 2004 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.+ */package org.apache.lucene.gdata.storage.db4o;-import java.io.IOException;-import java.io.StringWriter;+import java.io.File;import java.util.ArrayList;import java.util.List;import java.util.concurrent.atomic.AtomicBoolean;@@ -26,9 +40,7 @@ import com.db4o.query.Query;import com.google.gdata.data.BaseEntry;import com.google.gdata.data.BaseFeed;import com.google.gdata.data.DateTime;-import com.google.gdata.data.ExtensionProfile;import com.google.gdata.data.PlainTextConstruct;-import com.google.gdata.util.common.xml.XmlWriter;public class TestDb4oStorage extends TestCase {private static final String FEEDID = "myFeed";@@ -61,6 +73,8 @@ public class TestDb4oStorage extends TestCase {this.controller.getStorage().close();this.controller.visiteDestroy();this.controller.destroy();+ File dbFile = new File("test.yap");+ assertTrue(dbFile.delete());}private void clearDB() {@@ -78,8 +92,7 @@ public class TestDb4oStorage extends TestCase {return this.controller.releaseContainer();}--+/** Test method for* 'org.apache.lucene.gdata.storage.db4o.DB4oStorage.storeEntry(ServerBaseEntry)'@@ -94,6 +107,33 @@ public class TestDb4oStorage extends TestCase {} catch (StorageException e) {//}++ try {++ storage.storeEntry(null);+ fail("entry is null");+ } catch (StorageException e) {+ //+ }+ ServerBaseEntry exEntry = new ServerBaseEntry();+ exEntry.setFeedId("some");+ try {++ storage.storeEntry(exEntry);+ fail("entry id is null");+ } catch (StorageException e) {+ //+ }+ exEntry.setId("someID");+ exEntry.setFeedId(null);+ try {++ storage.storeEntry(exEntry);+ fail("feed id is null");+ } catch (StorageException e) {+ //+ }+storeServerBaseFeed();ServerBaseEntry e = createServerBaseEntry();storage.storeEntry(e);@@ -106,13 +146,14 @@ public class TestDb4oStorage extends TestCase {query.descend("id").constrain(e.getId());ObjectSet resultSet = query.execute();assertEquals(1, resultSet.size());- BaseEntry storedEntry = (BaseEntry)resultSet.next();- assertEquals("1",storedEntry.getVersionId());+ BaseEntry storedEntry = (BaseEntry) resultSet.next();+ assertEquals("1", storedEntry.getVersionId());ServerBaseFeed bFeed = new ServerBaseFeed();bFeed.setItemsPerPage(25);bFeed.setId(FEEDID);bFeed.setStartIndex(1);+ bFeed.setServiceType(SERVICENAME);BaseFeed<BaseFeed, BaseEntry> feed = storage.getFeed(bFeed);assertEquals(2, feed.getEntries().size());assertEquals(e.getId(), feed.getEntries().get(1).getId()); // last post@@ -133,13 +174,41 @@ public class TestDb4oStorage extends TestCase {ObjectContainer container = getContainer();storeServerBaseFeed();Storage storage = this.controller.getStorage();++ try {++ storage.deleteEntry(null);+ fail("entry is null");+ } catch (StorageException e) {+ //+ }+ ServerBaseEntry exEntry = new ServerBaseEntry();+ exEntry.setFeedId("some");+ try {++ storage.deleteEntry(exEntry);+ fail("entry id is null");+ } catch (StorageException e) {+ //+ }+ exEntry.setId("someID");+ exEntry.setFeedId(null);+ try {++ storage.storeEntry(exEntry);+ fail("feed id is null");+ } catch (StorageException e) {+ //+ }++ServerBaseEntry e = createServerBaseEntry();storage.storeEntry(e);ServerBaseEntry e1 = createServerBaseEntry();storage.storeEntry(e1);storage.deleteEntry(e);-+container.close();container = getContainer();Query query = container.query();@@ -158,7 +227,12 @@ public class TestDb4oStorage extends TestCase {} catch (Exception ex) {// TODO: handle exception}-+ try {+ storage.deleteEntry(null);+ fail("entry id is null");+ } catch (Exception ex) {+ // TODO: handle exception+ }storage = this.controller.getStorage();storage.deleteEntry(e1);container.close();@@ -186,16 +260,14 @@ public class TestDb4oStorage extends TestCase {storage.storeEntry(concuEntry);storage.close();- concuEntry.acceptGetVersionVisitor(getMonitorVisitor(monitor,reached));-+ concuEntry.acceptGetVersionVisitor(getMonitorVisitor(monitor, reached));Thread t1 = getDelThread(controller, concuEntry, false);Thread t2 = getDelThread(controller, concuEntry, true);t1.start();/*- * Wait active -- not nice but works fine here- * wait until thread parked+ * Wait active -- not nice but works fine here wait until thread parked*/while (true) {@@ -208,8 +280,8 @@ public class TestDb4oStorage extends TestCase {t2.start();t2.join(800);/*- * Wait active -- not nice but works fine here- * wake up the waiting thread+ * Wait active -- not nice but works fine here wake up the waiting+ * thread*/while (true) {synchronized (monitor) {@@ -221,28 +293,30 @@ public class TestDb4oStorage extends TestCase {t1.join(300);if (fail)fail("thread failed -- see stacktrace");-+container.close();}-- private Visitor getMonitorVisitor(final Object monitor, final AtomicBoolean reached){++ private Visitor getMonitorVisitor(final Object monitor,+ final AtomicBoolean reached) {/*- * The executing thread stops at a defined position while holding the semaphore inside the storageImpl+ * The executing thread stops at a defined position while holding the+ * semaphore inside the storageImpl*/- return new Visitor(){- public void execute(Object[] o){- synchronized (monitor) {- try {- reached.set(true);- monitor.wait();- reached.set(false);-- } catch (InterruptedException e) {- //- }+ return new Visitor() {+ public void execute(Object[] o) {+ synchronized (monitor) {+ try {+ reached.set(true);+ monitor.wait();+ reached.set(false);++ } catch (InterruptedException e) {+ //+ }+ }}- }};}@@ -269,6 +343,35 @@ public class TestDb4oStorage extends TestCase {public void testUpdateEntry() throws StorageException, InterruptedException {storeServerBaseFeed();Storage storage = this.controller.getStorage();+ ServerBaseEntry exEntry = new ServerBaseEntry();+++ try {++ storage.updateEntry(null);+ fail("entry is null");+ } catch (StorageException e) {+ //+ }++ try {++ storage.updateEntry(exEntry);+ fail("entry id is null");+ } catch (StorageException e) {+ //+ }+ exEntry.setId("someID");+ try {++ storage.updateEntry(exEntry);+ fail("feed id is null");+ } catch (StorageException e) {+ //+ }+++ServerBaseEntry e = createServerBaseEntry();ServerBaseEntry e1 = createServerBaseEntry();try {@@ -296,12 +399,12 @@ public class TestDb4oStorage extends TestCase {BaseEntry result = (BaseEntry) resultSet.next();assertEquals("new", result.getTitle().getPlainText());assertEquals("2", result.getVersionId());--+ServerBaseFeed bFeed = new ServerBaseFeed();bFeed.setItemsPerPage(25);bFeed.setId(FEEDID);bFeed.setStartIndex(1);+ bFeed.setServiceType(SERVICENAME);storage = this.controller.getStorage();BaseFeed<BaseFeed, BaseEntry> feed = storage.getFeed(bFeed);@@ -336,16 +439,14 @@ public class TestDb4oStorage extends TestCase {storage.storeEntry(concuEntry);storage.close();- concuEntry.acceptGetEntryVisitor(getMonitorVisitor(monitor,reached));-+ concuEntry.acceptGetEntryVisitor(getMonitorVisitor(monitor, reached));Thread t1 = getUpdThread(controller, concuEntry, false);Thread t2 = getUpdThread(controller, concuEntry, true);t1.start();/*- * Wait active -- not nice but works fine here- * wait until thread parked+ * Wait active -- not nice but works fine here wait until thread parked*/while (true) {@@ -358,8 +459,8 @@ public class TestDb4oStorage extends TestCase {t2.start();t2.join(800);/*- * Wait active -- not nice but works fine here- * wake up the waiting thread+ * Wait active -- not nice but works fine here wake up the waiting+ * thread*/while (true) {synchronized (monitor) {@@ -384,6 +485,14 @@ public class TestDb4oStorage extends TestCase {ServerBaseFeed feed = new ServerBaseFeed();feed.setItemsPerPage(25);feed.setStartIndex(1);+ feed.setServiceType(SERVICENAME);+ try{+ storage.getFeed(feed);+ fail("feedid is null");+ }catch (StorageException e) {+ //+ }+feed.setId(FEEDID);BaseFeed result = storage.getFeed(feed);assertNotNull(result);@@ -460,11 +569,19 @@ public class TestDb4oStorage extends TestCase {public void testGetEntry() throws StorageException {storeServerBaseFeed();Storage storage = this.controller.getStorage();+ ServerBaseEntry exEntry = createServerBaseEntry();+ exEntry.setId(null);+ try{+ storage.getEntry(exEntry);+ fail("id is null");+ }catch (StorageException e) {++ }ServerBaseEntry e = createServerBaseEntry();storage.storeEntry(e);ServerBaseEntry e1 = createServerBaseEntry();storage.storeEntry(e1);-+storage = this.controller.getStorage();BaseEntry result = storage.getEntry(e);assertNotNull(result);@@ -541,7 +658,8 @@ public class TestDb4oStorage extends TestCase {account.setName("simon");account.setPassword("newPass");storage.updateAccount(account);-+ container.close();+ container = getContainer();q = container.query();q.constrain(GDataAccount.class);q.descend("name").constrain(account.getName());@@ -570,7 +688,8 @@ public class TestDb4oStorage extends TestCase {assertEquals(1, set.size());storage.deleteAccount(account.getName());-+ container.close();+ container = getContainer();q = container.query();q.constrain(GDataAccount.class);q.descend("name").constrain(account.getName());@@ -636,9 +755,7 @@ public class TestDb4oStorage extends TestCase {* 'org.apache.lucene.gdata.storage.db4o.DB4oStorage.deleteFeed(String)'*/public void testDeleteFeed() throws StorageException {--ServerBaseFeed feed = new ServerBaseFeed();feed.setId(FEEDID);GDataAccount account = new GDataAccount();@@ -653,7 +770,7 @@ public class TestDb4oStorage extends TestCase {conf.setName(SERVICENAME);feed.setServiceConfig(conf);storage.storeFeed(feed, ACCOUNTNAME);-+storage.deleteFeed(FEEDID);container = getContainer();Query query = container.query();@@ -719,7 +836,7 @@ public class TestDb4oStorage extends TestCase {container.set(account);container.commit();container.close();-+Storage storage = this.controller.getStorage();assertNotNull(storage.getAccount(ACCOUNTNAME));assertEquals(account.getPassword(), storage.getAccount(ACCOUNTNAME)@@ -763,9 +880,12 @@ public class TestDb4oStorage extends TestCase {feedU.setServiceConfig(conf);feedU.setId(FEEDID);feedU.setTitle(new PlainTextConstruct("someText"));+ feedU.setServiceType(SERVICENAME);+storage.updateFeed(feedU, ACCOUNTNAME);ServerBaseFeed requestFeed = new ServerBaseFeed();requestFeed.setId(FEEDID);+ requestFeed.setServiceType(SERVICENAME);assertNotNull(storage.getFeed(requestFeed));assertEquals(feedU.getTitle(), storage.getFeed(requestFeed).getTitle());try {@@ -807,7 +927,7 @@ public class TestDb4oStorage extends TestCase {return e;}- private void storeServerBaseFeed() {+ private ServerBaseFeed storeServerBaseFeed() {ServerBaseFeed f = new ServerBaseFeed();ProvidedServiceConfig conf = new ProvidedServiceConfig();conf.setName(SERVICENAME);@@ -820,7 +940,7 @@ public class TestDb4oStorage extends TestCase {con.commit();con.close();-+ return f;}static class Runner implements Runnable {@@ -874,4 +994,47 @@ public class TestDb4oStorage extends TestCase {}}++ public void testFeedLastModified() {+ ServerBaseFeed feed = storeServerBaseFeed();+ Storage s = this.controller.getStorage();+ assertEquals(feed.getUpdated().getValue(), s+ .getFeedLastModified(FEEDID).longValue());+ try {+ s.getFeedLastModified(null);+ fail("id is null");+ } catch (StorageException e) {++ }+ try {+ s.getFeedLastModified("someOtherid");+ fail("no such feed");+ } catch (StorageException e) {++ }++ }++ public void testEntryLastModified() {+ ServerBaseFeed feed = storeServerBaseFeed();+ Storage s = this.controller.getStorage();+ ServerBaseEntry en = createServerBaseEntry();+ s.storeEntry(en);+ assertEquals(en.getUpdated().getValue(), s.getEntryLastModified(+ en.getId(), FEEDID).longValue());+ try {+ s.getEntryLastModified(null, null);+ fail("id is null");+ } catch (StorageException e) {++ }+ try {+ s.getEntryLastModified("someOtherid", "notinstorage");+ fail("no such Entry");+ } catch (StorageException e) {++ }++ }+}diff --git a/contrib/gdata-server/src/test/org/apache/lucene/gdata/storage/db4o/TestObjectServerDecorator.java b/contrib/gdata-server/src/test/org/apache/lucene/gdata/storage/db4o/TestObjectServerDecorator.javanew file mode 100755index 00000000000..4004fa982ce--- /dev/null+++ b/contrib/gdata-server/src/test/org/apache/lucene/gdata/storage/db4o/TestObjectServerDecorator.java@@ -0,0 +1,59 @@+/**+ * Copyright 2004 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.+ */+package org.apache.lucene.gdata.storage.db4o;++import java.io.File;+import java.lang.reflect.Proxy;++import com.db4o.Db4o;+import com.db4o.ObjectContainer;+import com.db4o.ObjectServer;++import junit.framework.TestCase;++public class TestObjectServerDecorator extends TestCase {+ ObjectServer decorator;+ ObjectServer actualServer;+ String dbFile = "test.yap";+ protected void setUp() throws Exception {+ decorator = (ObjectServer) Proxy.newProxyInstance(this.getClass().getClassLoader(),new Class[]{ObjectServer.class},new ObjectServerDecorator("u","p","127.0.0.1",10101));+ actualServer= Db4o.openServer(dbFile,10101);+ actualServer.grantAccess("u","p");++ }++ protected void tearDown() throws Exception {+ actualServer.close();+ File dbF = new File(dbFile);+ assertTrue(dbF.delete());++ }++ /*+ * Test method for 'org.apache.lucene.gdata.storage.db4o.ObjectServerDecorator.invoke(Object, Method, Object[])'+ */+ public void testInvoke() {+ assertFalse(this.decorator.close());+ assertNull(this.decorator.ext());+ assertEquals(0,this.decorator.hashCode());+ ObjectContainer container = this.decorator.openClient();+ assertNotNull(container);+ assertTrue(this.decorator.openClient()instanceof ObjectContainer);+ container.close();++ }++}diff --git a/contrib/gdata-server/src/test/org/apache/lucene/gdata/storage/lucenestorage/StorageCoreControllerStub.java b/contrib/gdata-server/src/test/org/apache/lucene/gdata/storage/lucenestorage/StorageCoreControllerStub.javaindex f38ed36bd56..0aec6b50f61 100755--- a/contrib/gdata-server/src/test/org/apache/lucene/gdata/storage/lucenestorage/StorageCoreControllerStub.java+++ b/contrib/gdata-server/src/test/org/apache/lucene/gdata/storage/lucenestorage/StorageCoreControllerStub.java@@ -23,12 +23,10 @@ import org.apache.lucene.gdata.server.registry.Component;import org.apache.lucene.gdata.server.registry.ComponentType;import org.apache.lucene.gdata.storage.IDGenerator;import org.apache.lucene.gdata.storage.Storage;-import org.apache.lucene.gdata.storage.StorageController;import org.apache.lucene.gdata.storage.StorageException;-import org.apache.lucene.gdata.storage.lucenestorage.util.ReferenceCounter;+import org.apache.lucene.gdata.utils.ReferenceCounter;import org.apache.lucene.index.IndexModifier;import org.apache.lucene.store.Directory;-import org.apache.lucene.store.RAMDirectory;/*** @author Simon Willnauerdiff --git a/contrib/gdata-server/src/test/org/apache/lucene/gdata/storage/lucenestorage/TestModifiedEntryFilter.java b/contrib/gdata-server/src/test/org/apache/lucene/gdata/storage/lucenestorage/TestModifiedEntryFilter.javaindex 1bcc9235f45..2d942095313 100644--- a/contrib/gdata-server/src/test/org/apache/lucene/gdata/storage/lucenestorage/TestModifiedEntryFilter.java+++ b/contrib/gdata-server/src/test/org/apache/lucene/gdata/storage/lucenestorage/TestModifiedEntryFilter.java@@ -9,8 +9,8 @@ import junit.framework.TestCase;import org.apache.lucene.analysis.standard.StandardAnalyzer;import org.apache.lucene.document.Document;import org.apache.lucene.document.Field;-import org.apache.lucene.gdata.storage.lucenestorage.ModifiedEntryFilter;import org.apache.lucene.gdata.storage.lucenestorage.StorageEntryWrapper;+import org.apache.lucene.gdata.utils.ModifiedEntryFilter;import org.apache.lucene.index.IndexReader;import org.apache.lucene.index.IndexWriter;import org.apache.lucene.index.Term;@@ -55,11 +55,15 @@ public class TestModifiedEntryFilter extends TestCase {Hits hits = s.search(q);assertEquals(2,hits.length());- hits = s.search(q,new ModifiedEntryFilter(this.excludeList.toArray(new String[0])));+ hits = s.search(q,new ModifiedEntryFilter(this.excludeList.toArray(new String[0]),StorageEntryWrapper.FIELD_ENTRY_ID));assertEquals(1,hits.length());this.excludeList.add("2");- hits = s.search(q,new ModifiedEntryFilter(this.excludeList.toArray(new String[0])));+ hits = s.search(q,new ModifiedEntryFilter(this.excludeList.toArray(new String[0]),StorageEntryWrapper.FIELD_ENTRY_ID));+ assertEquals(0,hits.length());+ this.excludeList.add(null);+ this.excludeList.add("5");+ hits = s.search(q,new ModifiedEntryFilter(this.excludeList.toArray(new String[0]),StorageEntryWrapper.FIELD_ENTRY_ID));assertEquals(0,hits.length());}diff --git a/contrib/gdata-server/src/test/org/apache/lucene/gdata/storage/lucenestorage/TestSingelHostConcurrencyLock.java b/contrib/gdata-server/src/test/org/apache/lucene/gdata/storage/lucenestorage/TestSingelHostConcurrencyLock.javaindex 93da718783e..c1257686ee3 100755--- a/contrib/gdata-server/src/test/org/apache/lucene/gdata/storage/lucenestorage/TestSingelHostConcurrencyLock.java+++ b/contrib/gdata-server/src/test/org/apache/lucene/gdata/storage/lucenestorage/TestSingelHostConcurrencyLock.java@@ -1,3 +1,18 @@+/**+ * Copyright 2004 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.+ */package org.apache.lucene.gdata.storage.lucenestorage;import org.apache.lucene.gdata.storage.lucenestorage.SingleHostConcurrentStorageLock.ConcurrencyException;diff --git a/contrib/gdata-server/src/test/org/apache/lucene/gdata/storage/lucenestorage/TestStorageBuffer.java b/contrib/gdata-server/src/test/org/apache/lucene/gdata/storage/lucenestorage/TestStorageBuffer.javaindex ad5cc583cef..d43154fe9bf 100755--- a/contrib/gdata-server/src/test/org/apache/lucene/gdata/storage/lucenestorage/TestStorageBuffer.java+++ b/contrib/gdata-server/src/test/org/apache/lucene/gdata/storage/lucenestorage/TestStorageBuffer.java@@ -1,3 +1,18 @@+/**+ * Copyright 2004 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.+ */package org.apache.lucene.gdata.storage.lucenestorage;import java.io.IOException;diff --git a/contrib/gdata-server/src/test/org/apache/lucene/gdata/storage/lucenestorage/TestStorageImplementation.java b/contrib/gdata-server/src/test/org/apache/lucene/gdata/storage/lucenestorage/TestStorageImplementation.javaindex 9ad11fd61ac..8f76d7e9652 100755--- a/contrib/gdata-server/src/test/org/apache/lucene/gdata/storage/lucenestorage/TestStorageImplementation.java+++ b/contrib/gdata-server/src/test/org/apache/lucene/gdata/storage/lucenestorage/TestStorageImplementation.java@@ -1,3 +1,18 @@+/**+ * Copyright 2004 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.+ */package org.apache.lucene.gdata.storage.lucenestorage;import java.util.concurrent.atomic.AtomicBoolean;diff --git a/contrib/gdata-server/src/test/org/apache/lucene/gdata/storage/lucenestorage/TestStorageModifier.java b/contrib/gdata-server/src/test/org/apache/lucene/gdata/storage/lucenestorage/TestStorageModifier.javaindex 445b78149c7..91da27c93d3 100644--- a/contrib/gdata-server/src/test/org/apache/lucene/gdata/storage/lucenestorage/TestStorageModifier.java+++ b/contrib/gdata-server/src/test/org/apache/lucene/gdata/storage/lucenestorage/TestStorageModifier.java@@ -1,3 +1,18 @@+/**+ * Copyright 2004 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.+ */package org.apache.lucene.gdata.storage.lucenestorage;import java.io.IOException;@@ -10,8 +25,8 @@ import org.apache.lucene.gdata.data.ServerBaseFeed;import org.apache.lucene.gdata.server.registry.ProvidedService;import org.apache.lucene.gdata.storage.StorageException;import org.apache.lucene.gdata.storage.lucenestorage.StorageEntryWrapper.StorageOperation;-import org.apache.lucene.gdata.storage.lucenestorage.util.ReferenceCounter;import org.apache.lucene.gdata.utils.ProvidedServiceStub;+import org.apache.lucene.gdata.utils.ReferenceCounter;import org.apache.lucene.index.Term;import org.apache.lucene.search.BooleanClause;import org.apache.lucene.search.BooleanQuery;diff --git a/contrib/gdata-server/src/test/org/apache/lucene/gdata/storage/lucenestorage/TestStorageQuery.java b/contrib/gdata-server/src/test/org/apache/lucene/gdata/storage/lucenestorage/TestStorageQuery.javaindex 68d539537fd..32fae22d19b 100644--- a/contrib/gdata-server/src/test/org/apache/lucene/gdata/storage/lucenestorage/TestStorageQuery.java+++ b/contrib/gdata-server/src/test/org/apache/lucene/gdata/storage/lucenestorage/TestStorageQuery.java@@ -1,3 +1,18 @@+/**+ * Copyright 2004 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.+ */package org.apache.lucene.gdata.storage.lucenestorage;import java.io.IOException;@@ -13,8 +28,8 @@ import org.apache.lucene.gdata.data.ServerBaseFeed;import org.apache.lucene.gdata.server.registry.ProvidedService;import org.apache.lucene.gdata.storage.StorageException;import org.apache.lucene.gdata.storage.lucenestorage.StorageEntryWrapper.StorageOperation;-import org.apache.lucene.gdata.storage.lucenestorage.util.ReferenceCounter;import org.apache.lucene.gdata.utils.ProvidedServiceStub;+import org.apache.lucene.gdata.utils.ReferenceCounter;import org.apache.lucene.store.Directory;import org.apache.lucene.store.RAMDirectory;diff --git a/contrib/gdata-server/src/test/org/apache/lucene/gdata/storage/lucenestorage/recover/TestRecoverController.java b/contrib/gdata-server/src/test/org/apache/lucene/gdata/storage/lucenestorage/recover/TestRecoverController.javaindex c250dc58f37..2c58f75e0e6 100644--- a/contrib/gdata-server/src/test/org/apache/lucene/gdata/storage/lucenestorage/recover/TestRecoverController.java+++ b/contrib/gdata-server/src/test/org/apache/lucene/gdata/storage/lucenestorage/recover/TestRecoverController.java@@ -1,3 +1,18 @@+/**+ * Copyright 2004 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.+ */package org.apache.lucene.gdata.storage.lucenestorage.recover;import java.io.File;@@ -96,7 +111,9 @@ public class TestRecoverController extends TestCase {private void createCorruptedFile() throws IOException{- FileWriter writer = new FileWriter(new File(this.recDir,"somefile.rec"));+ File file = new File(this.recDir,"somefile.rec");+ file.deleteOnExit();+ FileWriter writer = new FileWriter(file);writer.write("someString\nSomeOtherString");writer.close();}diff --git a/contrib/gdata-server/src/test/org/apache/lucene/gdata/storage/lucenestorage/recover/TestRecoverWriter.java b/contrib/gdata-server/src/test/org/apache/lucene/gdata/storage/lucenestorage/recover/TestRecoverWriter.javaindex 26053f2a4b8..58d53ebfb49 100644--- a/contrib/gdata-server/src/test/org/apache/lucene/gdata/storage/lucenestorage/recover/TestRecoverWriter.java+++ b/contrib/gdata-server/src/test/org/apache/lucene/gdata/storage/lucenestorage/recover/TestRecoverWriter.java@@ -1,3 +1,18 @@+/**+ * Copyright 2004 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.+ */package org.apache.lucene.gdata.storage.lucenestorage.recover;import java.io.IOException;diff --git a/contrib/gdata-server/src/test/org/apache/lucene/gdata/storage/lucenestorage/recover/TestRevocerReader.java b/contrib/gdata-server/src/test/org/apache/lucene/gdata/storage/lucenestorage/recover/TestRevocerReader.javaindex 9b87d1795ca..c4a7b1264d8 100644--- a/contrib/gdata-server/src/test/org/apache/lucene/gdata/storage/lucenestorage/recover/TestRevocerReader.java+++ b/contrib/gdata-server/src/test/org/apache/lucene/gdata/storage/lucenestorage/recover/TestRevocerReader.java@@ -1,3 +1,18 @@+/**+ * Copyright 2004 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.+ */package org.apache.lucene.gdata.storage.lucenestorage.recover;import java.io.BufferedReader;diff --git a/contrib/gdata-server/src/test/org/apache/lucene/gdata/utils/ProvidedServiceStub.java b/contrib/gdata-server/src/test/org/apache/lucene/gdata/utils/ProvidedServiceStub.javaindex afa9c05c30d..126df36ad1c 100644--- a/contrib/gdata-server/src/test/org/apache/lucene/gdata/utils/ProvidedServiceStub.java+++ b/contrib/gdata-server/src/test/org/apache/lucene/gdata/utils/ProvidedServiceStub.java@@ -1,5 +1,21 @@+/**+ * Copyright 2004 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.+ */package org.apache.lucene.gdata.utils;+import org.apache.lucene.gdata.search.config.IndexSchema;import org.apache.lucene.gdata.server.registry.ProvidedService;import com.google.gdata.data.Entry;@@ -9,6 +25,7 @@ import com.google.gdata.data.Feed;public class ProvidedServiceStub implements ProvidedService {public static final String SERVICE_NAME = "service";+ private IndexSchema indexSchema;public ProvidedServiceStub() {super();@@ -37,5 +54,13 @@ public class ProvidedServiceStub implements ProvidedService {public void destroy() {}+ public void setIndexSchema(IndexSchema schema){+ this.indexSchema = schema;+ this.indexSchema.setName(SERVICE_NAME);+ }+ public IndexSchema getIndexSchema() {++ return this.indexSchema;+ }}diff --git a/contrib/gdata-server/src/test/org/apache/lucene/gdata/utils/ServiceFactoryStub.java b/contrib/gdata-server/src/test/org/apache/lucene/gdata/utils/ServiceFactoryStub.javaindex aa5517f2c8f..ccfefe3ee33 100644--- a/contrib/gdata-server/src/test/org/apache/lucene/gdata/utils/ServiceFactoryStub.java+++ b/contrib/gdata-server/src/test/org/apache/lucene/gdata/utils/ServiceFactoryStub.java@@ -16,12 +16,15 @@package org.apache.lucene.gdata.utils;+import org.apache.lucene.gdata.server.GDataRequest;import org.apache.lucene.gdata.server.Service;import org.apache.lucene.gdata.server.ServiceFactory;import org.apache.lucene.gdata.server.administration.AdminService;import org.apache.lucene.gdata.server.registry.Component;import org.apache.lucene.gdata.server.registry.ComponentType;++/*** @author Simon Willnauer*@@ -44,7 +47,7 @@ public class ServiceFactoryStub extends ServiceFactory {* @see org.apache.lucene.gdata.server.ServiceFactory#getService()*/@Override- public Service getService() {+ public Service getService(GDataRequest request) {return service;}diff --git a/contrib/gdata-server/src/test/org/apache/lucene/gdata/utils/TestDateFormater.java b/contrib/gdata-server/src/test/org/apache/lucene/gdata/utils/TestDateFormater.javaindex 134c158b584..9c586b92abd 100644--- a/contrib/gdata-server/src/test/org/apache/lucene/gdata/utils/TestDateFormater.java+++ b/contrib/gdata-server/src/test/org/apache/lucene/gdata/utils/TestDateFormater.java@@ -1,3 +1,18 @@+/**+ * Copyright 2004 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.+ */package org.apache.lucene.gdata.utils;import java.text.ParseException;diff --git a/contrib/gdata-server/src/test/org/apache/lucene/gdata/utils/TestReflectionUtils.java b/contrib/gdata-server/src/test/org/apache/lucene/gdata/utils/TestReflectionUtils.javanew file mode 100755index 00000000000..127b3b0c010--- /dev/null+++ b/contrib/gdata-server/src/test/org/apache/lucene/gdata/utils/TestReflectionUtils.java@@ -0,0 +1,119 @@+/**+ * Copyright 2004 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.+ */+package org.apache.lucene.gdata.utils;++import org.apache.lucene.gdata.search.analysis.PlainTextStrategy;+import org.apache.lucene.gdata.search.config.IndexSchemaField;+import org.apache.lucene.gdata.utils.ReflectionUtils.ReflectionException;+import org.apache.lucene.search.RangeQuery;++import junit.framework.TestCase;++public class TestReflectionUtils extends TestCase {++ /*+ * Test method for 'org.apache.lucene.gdata.utils.ReflectionUtils.implementsType(Class, Class)'+ */+ public void testImplementsType() {++ }++ /*+ * Test method for 'org.apache.lucene.gdata.utils.ReflectionUtils.extendsType(Class, Class)'+ */+ public void testExtendsType() {+ assertTrue(ReflectionUtils.isTypeOf(Integer.class,Number.class));+ assertFalse(ReflectionUtils.isTypeOf(null,CharSequence.class));+ }++ /*+ * Test method for 'org.apache.lucene.gdata.utils.ReflectionUtils.isTypeOf(Class, Class)'+ */+ public void testIsTypeOf() {+ assertTrue(ReflectionUtils.isTypeOf(String.class,CharSequence.class));+ assertTrue(ReflectionUtils.isTypeOf(Integer.class,Number.class));+ assertFalse(ReflectionUtils.isTypeOf(Integer.class,CharSequence.class));+ assertFalse(ReflectionUtils.isTypeOf(null,CharSequence.class));+ assertFalse(ReflectionUtils.isTypeOf(Integer.class,null));++ }++ /*+ * Test method for 'org.apache.lucene.gdata.utils.ReflectionUtils.getDefaultInstance(Class<T>) <T>'+ */+ public void testGetDefaultInstance() {+ assertEquals(new String(),ReflectionUtils.getDefaultInstance(String.class));+ try{+ ReflectionUtils.getDefaultInstance(Integer.class);+ fail("can not create instance");+ }catch (ReflectionException e) {++ }+ try{+ ReflectionUtils.getDefaultInstance(null);+ fail("can not create instance");+ }catch (ReflectionException e) {++ }+ }++ /*+ * Test method for 'org.apache.lucene.gdata.utils.ReflectionUtils.canCreateInstance(Class)'+ */+ public void testCanCreateInstance() {+ assertTrue(ReflectionUtils.canCreateInstance(String.class));+ assertFalse(ReflectionUtils.canCreateInstance(Integer.class));+ assertFalse(ReflectionUtils.canCreateInstance(Integer.TYPE));+ assertFalse(ReflectionUtils.canCreateInstance(null));++++ }++ /*+ * Test method for 'org.apache.lucene.gdata.utils.ReflectionUtils.getPrimitiveWrapper(Class)'+ */+ public void testGetPrimitiveWrapper() {++ assertEquals(Integer.class,ReflectionUtils.getPrimitiveWrapper(Integer.TYPE));+ assertEquals(Long.class,ReflectionUtils.getPrimitiveWrapper(Long.TYPE));+ assertEquals(Float.class,ReflectionUtils.getPrimitiveWrapper(Float.TYPE));+ assertEquals(Byte.class,ReflectionUtils.getPrimitiveWrapper(Byte.TYPE));+ assertEquals(Double.class,ReflectionUtils.getPrimitiveWrapper(Double.TYPE));+ assertEquals(Short.class,ReflectionUtils.getPrimitiveWrapper(Short.TYPE));+ assertEquals(Boolean.class,ReflectionUtils.getPrimitiveWrapper(Boolean.TYPE));+ try {+ ReflectionUtils.getPrimitiveWrapper(null);+ fail("type is null");+ }catch (ReflectionException e) {++ }+ try {+ ReflectionUtils.getPrimitiveWrapper(String.class);+ fail("type is not a primitive");+ }catch (ReflectionException e) {++ }++ }++ public void testHasdesiredconstructor(){+ assertFalse(ReflectionUtils.hasDesiredConstructor(PlainTextStrategy.class, new Class[]{IndexSchemaField.class}));+ assertFalse(ReflectionUtils.hasDesiredConstructor(PlainTextStrategy.class, new Class[]{}));+ assertTrue(ReflectionUtils.hasDesiredConstructor(String.class, new Class[]{String.class}));+ }++}diff --git a/contrib/gdata-server/src/test/org/apache/lucene/gdata/utils/TestSimpleObjectPool.java b/contrib/gdata-server/src/test/org/apache/lucene/gdata/utils/TestSimpleObjectPool.javaindex 273a5520d74..0920c488965 100755--- a/contrib/gdata-server/src/test/org/apache/lucene/gdata/utils/TestSimpleObjectPool.java+++ b/contrib/gdata-server/src/test/org/apache/lucene/gdata/utils/TestSimpleObjectPool.java@@ -1,3 +1,19 @@+/**+ * Copyright 2004 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 permissi/**+ *+ */+package org.apache.lucene.gdata.utils;import java.util.ArrayList;diff --git a/contrib/gdata-server/src/test/org/apache/lucene/gdata/utils/Visitor.java b/contrib/gdata-server/src/test/org/apache/lucene/gdata/utils/Visitor.javaindex 12d99773476..9824f6aa20a 100755--- a/contrib/gdata-server/src/test/org/apache/lucene/gdata/utils/Visitor.java+++ b/contrib/gdata-server/src/test/org/apache/lucene/gdata/utils/Visitor.java@@ -1,5 +1,24 @@+/**+ * Copyright 2004 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.+ */package org.apache.lucene.gdata.utils;+/**+ * @author Simon Willnauer+ *+ */public interface Visitor {public void execute(Object[] objects);}diff --git a/contrib/gdata-server/webroot/WEB-INF/classes/gdata-config.xml b/contrib/gdata-server/webroot/WEB-INF/classes/gdata-config.xmlindex 037a619ae95..4991ea00e96 100644--- a/contrib/gdata-server/webroot/WEB-INF/classes/gdata-config.xml+++ b/contrib/gdata-server/webroot/WEB-INF/classes/gdata-config.xml@@ -6,8 +6,78 @@<extension-profile>com.google.gdata.data.ExtensionProfile</extension-profile>+ <index-schema defaultSearchField="content">+ <index useTimedIndexer="true" indexerIdleTime="120" optimizeAfterCommit="5" commitAfterDocuments="10">+ <defaultAnalyzer>+ org.apache.lucene.analysis.standard.StandardAnalyzer+ </defaultAnalyzer>+ <indexLocation>/tmp</indexLocation>+ <useCompoundFile>true</useCompoundFile>+ <mergeFactor>10</mergeFactor>+ <maxBufferedDocs>1000</maxBufferedDocs>+ <maxMergeDocs>2147483647</maxMergeDocs>+ <maxFieldLength>10000</maxFieldLength>+ </index>++ <field name="title" boost="2.0" type="text">+ <path>/entry/title</path>+ <analyzer>+ org.apache.lucene.analysis.standard.StandardAnalyzer+ </analyzer>+ </field>+ <field name="summary" boost="2.0" type="text">+ <path>/entry/summary</path>+ <analyzer>+ org.apache.lucene.analysis.standard.StandardAnalyzer+ </analyzer>+ </field>+ <field name="content" boost="2.0" type="text">+ <path>/entry/summary</path>+ <analyzer>+ org.apache.lucene.analysis.StopAnalyzer+ </analyzer>+ </field>+ <mixed name="content" boost="1.0">+ <path>/entry/content</path>+ <contenttype>/entry/content/@type</contenttype>+ <analyzer>+ org.apache.lucene.analysis.StopAnalyzer+ </analyzer>+ <store>YES</store>+ <index>TOKENIZED</index>+ </mixed>+ <field name="author" boost="1.0" type="text">+ <path>/entry/author/name</path>+ <analyzer>+ org.apache.lucene.analysis.standard.StandardAnalyzer+ </analyzer>+ </field>+ <field name="author" boost="1.0" type="text">+ <path>/entry/author/email</path>+ <analyzer>+ org.apache.lucene.analysis.standard.StandardAnalyzer+ </analyzer>+ </field>+ <field name="updated" boost="1.0" type="gdatadate">+ <path>/entry/updated</path>+ </field>+ <field name="category" boost="1.0" type="category">+ <path>/entry/category/</path>+ </field>+ <!-- custom field configuration -->+ <!-- <custom name="custom">+ <path>/path</path>+ <field-class>+ org.apache.lucene.gdata.search.analysis.ExtendContentStrategy+ </field-class>+ <analyzer>+ org.apache.lucene.analysis.SimpleAnalyzer+ </analyzer>+ </custom>+ -->+ </index-schema></service>- <service name="calendar" poolSize="20" public="true">+ <service name="eventfeed" poolSize="20" public="true"><feed-class>com.google.gdata.data.extensions.EventFeed</feed-class>@@ -17,19 +87,77 @@<extension-profile>com.google.gdata.data.ExtensionProfile</extension-profile>+ <index-schema defaultSearchField="content">++ <index useTimedIndexer="true" indexerIdleTime="120" optimizeAfterCommit="5" commitAfterDocuments="10">+ <defaultAnalyzer>+ org.apache.lucene.analysis.StandardAnalyzer+ </defaultAnalyzer>+ <indexLocation>/tmp/</indexLocation>+ <useCompoundFile>false</useCompoundFile>+ <mergeFactor>10</mergeFactor>+ <maxBufferedDocs>1000</maxBufferedDocs>+ <maxMergeDocs>10000</maxMergeDocs>+ <maxFieldLength>10000</maxFieldLength>+ </index>+ <field name="title" boost="2.0" type="text">+ <path>/entry/title</path>+ <analyzer>+ org.apache.lucene.analysis.SimpleAnalyzer+ </analyzer>+ </field>+ <field name="summary" boost="2.0" type="text">+ <path>/entry/summary</path>+ <analyzer>+ org.apache.lucene.analysis.SimpleAnalyzer+ </analyzer>+ </field>+ <mixed name="content" boost="1.0">+ <path>/entry/content</path>+ <contenttype>/entry/content/@type</contenttype>+ <analyzer>+ org.apache.lucene.analysis.StopAnalyzer+ </analyzer>+ <store>YES</store>+ <index>TOKENIZED</index>+ </mixed>+ <field name="author" boost="1.0" type="text">+ <path>/entry/author/name</path>+ <analyzer>+ org.apache.lucene.analysis.StopAnalyzer+ </analyzer>+ </field>+ <field name="author" boost="1.0" type="text">+ <path>/entry/author/email</path>+ <analyzer>+ org.apache.lucene.analysis.KeywordAnalyzer+ </analyzer>+ </field>+ <field name="updated" boost="1.0" type="gdatadate">+ <path>/entry/updated</path>+ </field>+ <field name="category" boost="1.0" type="category">+ <path>/entry/category</path>+ </field>+ </index-schema></service>+<server-components><component><class>- org.apache.lucene.gdata.storage.lucenestorage.StorageCoreController+ org.apache.lucene.gdata.storage.db4o.DB4oController</class><configuration>- <property name="bufferSize">20</property>- <property name="optimizeInterval">20</property>- <property name="persistFactor">20</property>- <property name="directory">/tmp/storage</property>- <property name="recover">true</property>- <property name="keepRecoveredFiles">false</property>+ <property name="runAsServer">true</property>+ <property name="port">0</property>+ <property name="host">localhost</property>+ <property name="filePath">+ /tmp/+ </property>+ <property name="containerPoolSize">10</property>+ <property name="user">entw_apache</property>+ <property name="password">Eh2aSZ</property>+ <property name="useWeakReferences">true</property></configuration></component><component>@@ -37,6 +165,11 @@org.apache.lucene.gdata.servlet.handler.DefaultRequestHandlerFactory</class></component>+ <component>+ <class>+ org.apache.lucene.gdata.search.index.IndexController+ </class>+ </component><component><class>org.apache.lucene.gdata.server.ServiceFactory</class></component>diff --git a/contrib/gdata-server/webroot/WEB-INF/classes/gdata-config.xsd b/contrib/gdata-server/webroot/WEB-INF/classes/gdata-config.xsdindex 978afed3778..5fb08c05de4 100755--- a/contrib/gdata-server/webroot/WEB-INF/classes/gdata-config.xsd+++ b/contrib/gdata-server/webroot/WEB-INF/classes/gdata-config.xsd@@ -1,10 +1,16 @@<?xml version="1.0" encoding="UTF-8"?><xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">-<xs:element name="feed-class" type="xs:string" /><xs:element name="entry-class" type="xs:string" /><xs:element name="extension-profile" type="xs:string" /><xs:element name="class" type="xs:string" />+ <xs:annotation>+ <xs:documentation xml:lang="en">+ This Schema defines the configuration for the+ gdata-config.xml file.+ </xs:documentation>+ </xs:annotation>+<xs:element name="property"><xs:complexType mixed="true">@@ -12,15 +18,6 @@</xs:complexType></xs:element>- <xs:element name="configuration">- <xs:complexType>- <xs:sequence>- <xs:element ref="property" minOccurs="1"- maxOccurs="unbounded" />- </xs:sequence>- </xs:complexType>- </xs:element>-<xs:element name="service"><xs:complexType><xs:sequence>@@ -30,6 +27,8 @@minOccurs="1" /><xs:element ref="extension-profile" maxOccurs="1"minOccurs="1" />+ <xs:element ref="index-schema" maxOccurs="1"+ minOccurs="1" /></xs:sequence><xs:attribute name="name" type="xs:string" use="required" /><xs:attribute name="public" type="xs:boolean" />@@ -37,6 +36,17 @@use="required" /></xs:complexType></xs:element>+ <xs:element name="configuration">+ <xs:complexType>+ <xs:sequence>+ <xs:element ref="property" minOccurs="1"+ maxOccurs="unbounded" />+ </xs:sequence>+ </xs:complexType>++ </xs:element>++<xs:element name="component"><xs:complexType>@@ -55,6 +65,10 @@maxOccurs="unbounded" /></xs:sequence></xs:complexType>+ <xs:unique name="component-class">+ <xs:selector xpath="component" />+ <xs:field xpath="class" />+ </xs:unique></xs:element><xs:element name="gdata">@@ -66,5 +80,164 @@minOccurs="1" /></xs:sequence></xs:complexType>+ <xs:unique name="service-name">+ <xs:selector xpath="service" />+ <xs:field xpath="@name" />+ </xs:unique>+</xs:element>+++ <!-- Index / Search -->+ <!-- field boost -->+ <xs:simpleType name="boostType">+ <xs:restriction base="xs:decimal">+ <xs:minExclusive value="0.0" />+ <xs:fractionDigits value="3" />+ </xs:restriction>+ </xs:simpleType>++ <!-- all possible Field.Store constants -->+ <xs:simpleType name="storeType">+ <xs:restriction base="xs:string">+ <xs:enumeration value="YES" />+ <xs:enumeration value="NO" />+ <xs:enumeration value="COMPRESS" />+ </xs:restriction>+ </xs:simpleType>+ <!-- all possible Field.Index constants -->+ <xs:simpleType name="indexType">+ <xs:restriction base="xs:string">+ <xs:enumeration value="TOKENIZED" />+ <xs:enumeration value="UN_TOKENIZED" />+ <xs:enumeration value="NO" />+ <xs:enumeration value="NO_NORMS" />+ </xs:restriction>+ </xs:simpleType>++ <!--+ This type correspond to+ org.apache.lucene.gdata.search.config.IndexSchemaField$ContentType+ -->+ <xs:simpleType name="fieldType">+ <xs:restriction base="xs:string">+ <xs:enumeration value="html" />+ <xs:enumeration value="xhtml" />+ <xs:enumeration value="gdatadate" />+ <xs:enumeration value="category" />+ <xs:enumeration value="keyword" />+ <xs:enumeration value="text" />+ </xs:restriction>+ </xs:simpleType>+<!-- type of fields see: org.apache.lucene.gdata.search.config.IndexSchemaField -->+ <xs:group name="fields">+ <xs:choice>+ <xs:element ref="field" />+ <xs:element ref="custom" />+ <xs:element ref="mixed" />++ </xs:choice>+ </xs:group>+ <!-- index configuration see: org.apache.lucene.gdata.search.config.IndexSchema -->+ <xs:element name="index">+ <xs:complexType>+ <xs:sequence>+ <xs:element name="defaultAnalyzer" type="xs:string"+ maxOccurs="1" minOccurs="1" />+ <xs:element name="indexLocation" type="xs:string"+ maxOccurs="1" minOccurs="1" />+ <xs:element name="useCompoundFile" type="xs:boolean"+ maxOccurs="1" />+ <xs:element name="mergeFactor" type="xs:unsignedInt"+ maxOccurs="1" />+ <xs:element name="maxBufferedDocs" type="xs:unsignedInt"+ maxOccurs="1" />+ <xs:element name="maxMergeDocs" type="xs:unsignedInt"+ maxOccurs="1" />+ <xs:element name="maxFieldLength" type="xs:unsignedInt"+ maxOccurs="1" />+ </xs:sequence>+ <xs:attribute name="useTimedIndexer" type="xs:boolean"+ use="required" />+ <xs:attribute name="indexerIdleTime" type="xs:unsignedLong" />+ <xs:attribute name="optimizeAfterCommit" type="xs:unsignedInt" use="required"/>+ <xs:attribute name="commitAfterDocuments" type="xs:unsignedInt" use="required"/>+ </xs:complexType>+ </xs:element>++<!-- index configuration see: org.apache.lucene.gdata.search.config.IndexSchema -->+ <xs:element name="index-schema">+ <xs:complexType>+ <xs:sequence>+ <xs:element ref="index" maxOccurs="1" minOccurs="1" />+ <xs:group ref="fields" maxOccurs="unbounded"+ minOccurs="1" />+ </xs:sequence>++ <xs:attribute name="defaultSearchField" type="xs:string"+ use="required" />++ </xs:complexType>+ </xs:element>++ <xs:element name="field">+ <xs:complexType>+ <xs:all>+ <xs:element name="path" type="xs:string" maxOccurs="1"+ minOccurs="1" />+ <xs:element name="analyzer" type="xs:string"+ maxOccurs="1" minOccurs="0" />+ <xs:element name="index" type="indexType" maxOccurs="1"+ minOccurs="0" />+ <xs:element name="store" type="storeType" maxOccurs="1"+ minOccurs="0" />+ </xs:all>+ <xs:attribute name="name" type="xs:string" use="required" />+ <xs:attribute name="boost" type="boostType" />+ <xs:attribute name="type" type="fieldType" use="required" />+ </xs:complexType>++ </xs:element>++ <xs:element name="custom">+ <xs:complexType>+ <xs:all>+ <xs:element name="path" type="xs:string" maxOccurs="1"+ minOccurs="1" />+ <xs:element name="field-class" type="xs:string"+ maxOccurs="1" minOccurs="1" />+ <xs:element name="analyzer" type="xs:string"+ maxOccurs="1" minOccurs="0" />+ <xs:element name="index" type="indexType" maxOccurs="1"+ minOccurs="0" />+ <xs:element name="store" type="storeType" maxOccurs="1"+ minOccurs="0" />+ </xs:all>+ <xs:attribute name="name" type="xs:string" use="required" />+ <xs:attribute name="boost" type="boostType" />+ </xs:complexType>++ </xs:element>++ <xs:element name="mixed">+ <xs:complexType>+ <xs:all>+ <xs:element name="path" type="xs:string" maxOccurs="1"+ minOccurs="1" />+ <xs:element name="contenttype" type="xs:string"+ maxOccurs="1" minOccurs="1" />+ <xs:element name="analyzer" type="xs:string"+ maxOccurs="1" minOccurs="0" />+ <xs:element name="index" type="indexType" maxOccurs="1"+ minOccurs="0" />+ <xs:element name="store" type="storeType" maxOccurs="1"+ minOccurs="0" />+ </xs:all>+ <xs:attribute name="name" type="xs:string" use="required" />+ <xs:attribute name="boost" type="boostType" />+ </xs:complexType>++ </xs:element>++</xs:schema>