code
stringlengths
1
2.01M
repo_name
stringlengths
3
62
path
stringlengths
1
267
language
stringclasses
231 values
license
stringclasses
13 values
size
int64
1
2.01M
package org.apache.lucene.util; /** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import org.apache.lucene.analysis.NumericTokenStream; // for javadocs import org.apache.lucene.document.NumericField; // for javadocs import org.apache.lucene.search.NumericRangeQuery; // for javadocs import org.apache.lucene.search.NumericRangeFilter; // for javadocs /** * This is a helper class to generate prefix-encoded representations for numerical values * and supplies converters to represent float/double values as sortable integers/longs. * * <p>To quickly execute range queries in Apache Lucene, a range is divided recursively * into multiple intervals for searching: The center of the range is searched only with * the lowest possible precision in the trie, while the boundaries are matched * more exactly. This reduces the number of terms dramatically. * * <p>This class generates terms to achieve this: First the numerical integer values need to * be converted to strings. For that integer values (32 bit or 64 bit) are made unsigned * and the bits are converted to ASCII chars with each 7 bit. The resulting string is * sortable like the original integer value. Each value is also prefixed * (in the first char) by the <code>shift</code> value (number of bits removed) used * during encoding. * * <p>To also index floating point numbers, this class supplies two methods to convert them * to integer values by changing their bit layout: {@link #doubleToSortableLong}, * {@link #floatToSortableInt}. You will have no precision loss by * converting floating point numbers to integers and back (only that the integer form * is not usable). Other data types like dates can easily converted to longs or ints (e.g. * date to long: {@link java.util.Date#getTime}). * * <p>For easy usage, the trie algorithm is implemented for indexing inside * {@link NumericTokenStream} that can index <code>int</code>, <code>long</code>, * <code>float</code>, and <code>double</code>. For querying, * {@link NumericRangeQuery} and {@link NumericRangeFilter} implement the query part * for the same data types. * * <p>This class can also be used, to generate lexicographically sortable (according * {@link String#compareTo(String)}) representations of numeric data types for other * usages (e.g. sorting). * * <p><font color="red"><b>NOTE:</b> This API is experimental and * might change in incompatible ways in the next release.</font> * * @since 2.9 */ public final class NumericUtils { private NumericUtils() {} // no instance! /** * The default precision step used by {@link NumericField}, {@link NumericTokenStream}, * {@link NumericRangeQuery}, and {@link NumericRangeFilter} as default */ public static final int PRECISION_STEP_DEFAULT = 4; /** * Expert: Longs are stored at lower precision by shifting off lower bits. The shift count is * stored as <code>SHIFT_START_LONG+shift</code> in the first character */ public static final char SHIFT_START_LONG = (char)0x20; /** * Expert: The maximum term length (used for <code>char[]</code> buffer size) * for encoding <code>long</code> values. * @see #longToPrefixCoded(long,int,char[]) */ public static final int BUF_SIZE_LONG = 63/7 + 2; /** * Expert: Integers are stored at lower precision by shifting off lower bits. The shift count is * stored as <code>SHIFT_START_INT+shift</code> in the first character */ public static final char SHIFT_START_INT = (char)0x60; /** * Expert: The maximum term length (used for <code>char[]</code> buffer size) * for encoding <code>int</code> values. * @see #intToPrefixCoded(int,int,char[]) */ public static final int BUF_SIZE_INT = 31/7 + 2; /** * Expert: Returns prefix coded bits after reducing the precision by <code>shift</code> bits. * This is method is used by {@link NumericTokenStream}. * @param val the numeric value * @param shift how many bits to strip from the right * @param buffer that will contain the encoded chars, must be at least of {@link #BUF_SIZE_LONG} * length * @return number of chars written to buffer */ public static int longToPrefixCoded(final long val, final int shift, final char[] buffer) { if (shift>63 || shift<0) throw new IllegalArgumentException("Illegal shift value, must be 0..63"); int nChars = (63-shift)/7 + 1, len = nChars+1; buffer[0] = (char)(SHIFT_START_LONG + shift); long sortableBits = val ^ 0x8000000000000000L; sortableBits >>>= shift; while (nChars>=1) { // Store 7 bits per character for good efficiency when UTF-8 encoding. // The whole number is right-justified so that lucene can prefix-encode // the terms more efficiently. buffer[nChars--] = (char)(sortableBits & 0x7f); sortableBits >>>= 7; } return len; } /** * Expert: Returns prefix coded bits after reducing the precision by <code>shift</code> bits. * This is method is used by {@link LongRangeBuilder}. * @param val the numeric value * @param shift how many bits to strip from the right */ public static String longToPrefixCoded(final long val, final int shift) { final char[] buffer = new char[BUF_SIZE_LONG]; final int len = longToPrefixCoded(val, shift, buffer); return new String(buffer, 0, len); } /** * This is a convenience method, that returns prefix coded bits of a long without * reducing the precision. It can be used to store the full precision value as a * stored field in index. * <p>To decode, use {@link #prefixCodedToLong}. */ public static String longToPrefixCoded(final long val) { return longToPrefixCoded(val, 0); } /** * Expert: Returns prefix coded bits after reducing the precision by <code>shift</code> bits. * This is method is used by {@link NumericTokenStream}. * @param val the numeric value * @param shift how many bits to strip from the right * @param buffer that will contain the encoded chars, must be at least of {@link #BUF_SIZE_INT} * length * @return number of chars written to buffer */ public static int intToPrefixCoded(final int val, final int shift, final char[] buffer) { if (shift>31 || shift<0) throw new IllegalArgumentException("Illegal shift value, must be 0..31"); int nChars = (31-shift)/7 + 1, len = nChars+1; buffer[0] = (char)(SHIFT_START_INT + shift); int sortableBits = val ^ 0x80000000; sortableBits >>>= shift; while (nChars>=1) { // Store 7 bits per character for good efficiency when UTF-8 encoding. // The whole number is right-justified so that lucene can prefix-encode // the terms more efficiently. buffer[nChars--] = (char)(sortableBits & 0x7f); sortableBits >>>= 7; } return len; } /** * Expert: Returns prefix coded bits after reducing the precision by <code>shift</code> bits. * This is method is used by {@link IntRangeBuilder}. * @param val the numeric value * @param shift how many bits to strip from the right */ public static String intToPrefixCoded(final int val, final int shift) { final char[] buffer = new char[BUF_SIZE_INT]; final int len = intToPrefixCoded(val, shift, buffer); return new String(buffer, 0, len); } /** * This is a convenience method, that returns prefix coded bits of an int without * reducing the precision. It can be used to store the full precision value as a * stored field in index. * <p>To decode, use {@link #prefixCodedToInt}. */ public static String intToPrefixCoded(final int val) { return intToPrefixCoded(val, 0); } /** * Returns a long from prefixCoded characters. * Rightmost bits will be zero for lower precision codes. * This method can be used to decode e.g. a stored field. * @throws NumberFormatException if the supplied string is * not correctly prefix encoded. * @see #longToPrefixCoded(long) */ public static long prefixCodedToLong(final String prefixCoded) { final int shift = prefixCoded.charAt(0)-SHIFT_START_LONG; if (shift>63 || shift<0) throw new NumberFormatException("Invalid shift value in prefixCoded string (is encoded value really a LONG?)"); long sortableBits = 0L; for (int i=1, len=prefixCoded.length(); i<len; i++) { sortableBits <<= 7; final char ch = prefixCoded.charAt(i); if (ch>0x7f) { throw new NumberFormatException( "Invalid prefixCoded numerical value representation (char "+ Integer.toHexString((int)ch)+" at position "+i+" is invalid)" ); } sortableBits |= (long)ch; } return (sortableBits << shift) ^ 0x8000000000000000L; } /** * Returns an int from prefixCoded characters. * Rightmost bits will be zero for lower precision codes. * This method can be used to decode e.g. a stored field. * @throws NumberFormatException if the supplied string is * not correctly prefix encoded. * @see #intToPrefixCoded(int) */ public static int prefixCodedToInt(final String prefixCoded) { final int shift = prefixCoded.charAt(0)-SHIFT_START_INT; if (shift>31 || shift<0) throw new NumberFormatException("Invalid shift value in prefixCoded string (is encoded value really an INT?)"); int sortableBits = 0; for (int i=1, len=prefixCoded.length(); i<len; i++) { sortableBits <<= 7; final char ch = prefixCoded.charAt(i); if (ch>0x7f) { throw new NumberFormatException( "Invalid prefixCoded numerical value representation (char "+ Integer.toHexString((int)ch)+" at position "+i+" is invalid)" ); } sortableBits |= (int)ch; } return (sortableBits << shift) ^ 0x80000000; } /** * Converts a <code>double</code> value to a sortable signed <code>long</code>. * The value is converted by getting their IEEE 754 floating-point &quot;double format&quot; * bit layout and then some bits are swapped, to be able to compare the result as long. * By this the precision is not reduced, but the value can easily used as a long. * @see #sortableLongToDouble */ public static long doubleToSortableLong(double val) { long f = Double.doubleToRawLongBits(val); if (f<0) f ^= 0x7fffffffffffffffL; return f; } /** * Convenience method: this just returns: * longToPrefixCoded(doubleToSortableLong(val)) */ public static String doubleToPrefixCoded(double val) { return longToPrefixCoded(doubleToSortableLong(val)); } /** * Converts a sortable <code>long</code> back to a <code>double</code>. * @see #doubleToSortableLong */ public static double sortableLongToDouble(long val) { if (val<0) val ^= 0x7fffffffffffffffL; return Double.longBitsToDouble(val); } /** * Convenience method: this just returns: * sortableLongToDouble(prefixCodedToLong(val)) */ public static double prefixCodedToDouble(String val) { return sortableLongToDouble(prefixCodedToLong(val)); } /** * Converts a <code>float</code> value to a sortable signed <code>int</code>. * The value is converted by getting their IEEE 754 floating-point &quot;float format&quot; * bit layout and then some bits are swapped, to be able to compare the result as int. * By this the precision is not reduced, but the value can easily used as an int. * @see #sortableIntToFloat */ public static int floatToSortableInt(float val) { int f = Float.floatToRawIntBits(val); if (f<0) f ^= 0x7fffffff; return f; } /** * Convenience method: this just returns: * intToPrefixCoded(floatToSortableInt(val)) */ public static String floatToPrefixCoded(float val) { return intToPrefixCoded(floatToSortableInt(val)); } /** * Converts a sortable <code>int</code> back to a <code>float</code>. * @see #floatToSortableInt */ public static float sortableIntToFloat(int val) { if (val<0) val ^= 0x7fffffff; return Float.intBitsToFloat(val); } /** * Convenience method: this just returns: * sortableIntToFloat(prefixCodedToInt(val)) */ public static float prefixCodedToFloat(String val) { return sortableIntToFloat(prefixCodedToInt(val)); } /** * Expert: Splits a long range recursively. * You may implement a builder that adds clauses to a * {@link org.apache.lucene.search.BooleanQuery} for each call to its * {@link LongRangeBuilder#addRange(String,String)} * method. * <p>This method is used by {@link NumericRangeQuery}. */ public static void splitLongRange(final LongRangeBuilder builder, final int precisionStep, final long minBound, final long maxBound ) { splitRange(builder, 64, precisionStep, minBound, maxBound); } /** * Expert: Splits an int range recursively. * You may implement a builder that adds clauses to a * {@link org.apache.lucene.search.BooleanQuery} for each call to its * {@link IntRangeBuilder#addRange(String,String)} * method. * <p>This method is used by {@link NumericRangeQuery}. */ public static void splitIntRange(final IntRangeBuilder builder, final int precisionStep, final int minBound, final int maxBound ) { splitRange(builder, 32, precisionStep, (long)minBound, (long)maxBound); } /** This helper does the splitting for both 32 and 64 bit. */ private static void splitRange( final Object builder, final int valSize, final int precisionStep, long minBound, long maxBound ) { if (precisionStep < 1) throw new IllegalArgumentException("precisionStep must be >=1"); if (minBound > maxBound) return; for (int shift=0; ; shift += precisionStep) { // calculate new bounds for inner precision final long diff = 1L << (shift+precisionStep), mask = ((1L<<precisionStep) - 1L) << shift; final boolean hasLower = (minBound & mask) != 0L, hasUpper = (maxBound & mask) != mask; final long nextMinBound = (hasLower ? (minBound + diff) : minBound) & ~mask, nextMaxBound = (hasUpper ? (maxBound - diff) : maxBound) & ~mask; if (shift+precisionStep>=valSize || nextMinBound>nextMaxBound) { // We are in the lowest precision or the next precision is not available. addRange(builder, valSize, minBound, maxBound, shift); // exit the split recursion loop break; } if (hasLower) addRange(builder, valSize, minBound, minBound | mask, shift); if (hasUpper) addRange(builder, valSize, maxBound & ~mask, maxBound, shift); // recurse to next precision minBound = nextMinBound; maxBound = nextMaxBound; } } /** Helper that delegates to correct range builder */ private static void addRange( final Object builder, final int valSize, long minBound, long maxBound, final int shift ) { // for the max bound set all lower bits (that were shifted away): // this is important for testing or other usages of the splitted range // (e.g. to reconstruct the full range). The prefixEncoding will remove // the bits anyway, so they do not hurt! maxBound |= (1L << shift) - 1L; // delegate to correct range builder switch(valSize) { case 64: ((LongRangeBuilder)builder).addRange(minBound, maxBound, shift); break; case 32: ((IntRangeBuilder)builder).addRange((int)minBound, (int)maxBound, shift); break; default: // Should not happen! throw new IllegalArgumentException("valSize must be 32 or 64."); } } /** * Expert: Callback for {@link #splitLongRange}. * You need to overwrite only one of the methods. * <p><font color="red"><b>NOTE:</b> This is a very low-level interface, * the method signatures may change in later versions.</font> */ public static abstract class LongRangeBuilder { /** * Overwrite this method, if you like to receive the already prefix encoded range bounds. * You can directly build classical (inclusive) range queries from them. */ public void addRange(String minPrefixCoded, String maxPrefixCoded) { throw new UnsupportedOperationException(); } /** * Overwrite this method, if you like to receive the raw long range bounds. * You can use this for e.g. debugging purposes (print out range bounds). */ public void addRange(final long min, final long max, final int shift) { addRange(longToPrefixCoded(min, shift), longToPrefixCoded(max, shift)); } } /** * Expert: Callback for {@link #splitIntRange}. * You need to overwrite only one of the methods. * <p><font color="red"><b>NOTE:</b> This is a very low-level interface, * the method signatures may change in later versions.</font> */ public static abstract class IntRangeBuilder { /** * Overwrite this method, if you like to receive the already prefix encoded range bounds. * You can directly build classical range (inclusive) queries from them. */ public void addRange(String minPrefixCoded, String maxPrefixCoded) { throw new UnsupportedOperationException(); } /** * Overwrite this method, if you like to receive the raw int range bounds. * You can use this for e.g. debugging purposes (print out range bounds). */ public void addRange(final int min, final int max, final int shift) { addRange(intToPrefixCoded(min, shift), intToPrefixCoded(max, shift)); } } }
zzh-simple-hr
Zlucene/src/java/org/apache/lucene/util/NumericUtils.java
Java
art
18,323
package org.apache.lucene.util; /** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * Use by certain classes to match version compatibility * across releases of Lucene. * * <p><b>WARNING</b>: When changing the version parameter * that you supply to components in Lucene, do not simply * change the version at search-time, but instead also adjust * your indexing code to match, and re-index. */ public enum Version { /** Match settings and bugs in Lucene's 2.0 release. */ LUCENE_20, /** Match settings and bugs in Lucene's 2.1 release. */ LUCENE_21, /** Match settings and bugs in Lucene's 2.2 release. */ LUCENE_22, /** Match settings and bugs in Lucene's 2.3 release. */ LUCENE_23, /** Match settings and bugs in Lucene's 2.4 release. */ LUCENE_24, /** Match settings and bugs in Lucene's 2.9 release. */ LUCENE_29, /** Match settings and bugs in Lucene's 3.0 release. * <p> * Use this to get the latest &amp; greatest settings, bug * fixes, etc, for Lucene. */ LUCENE_30, /* Add new constants for later versions **here** to respect order! */ /** * <p><b>WARNING</b>: if you use this setting, and then * upgrade to a newer release of Lucene, sizable changes * may happen. If backwards compatibility is important * then you should instead explicitly specify an actual * version. * <p> * If you use this constant then you may need to * <b>re-index all of your documents</b> when upgrading * Lucene, as the way text is indexed may have changed. * Additionally, you may need to <b>re-test your entire * application</b> to ensure it behaves as expected, as * some defaults may have changed and may break functionality * in your application. * @deprecated Use an actual version instead. */ @Deprecated LUCENE_CURRENT; public boolean onOrAfter(Version other) { return compareTo(other) >= 0; } }
zzh-simple-hr
Zlucene/src/java/org/apache/lucene/util/Version.java
Java
art
2,681
package org.apache.lucene.util; /** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * <p/> * http://www.apache.org/licenses/LICENSE-2.0 * <p/> * 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. */ /** * Thrown by lucene on detecting that Thread.interrupt() had * been called. Unlike Java's InterruptedException, this * exception is not checked.. */ public final class ThreadInterruptedException extends RuntimeException { public ThreadInterruptedException(InterruptedException ie) { super(ie); } }
zzh-simple-hr
Zlucene/src/java/org/apache/lucene/util/ThreadInterruptedException.java
Java
art
1,158
package org.apache.lucene.util; /** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import java.lang.ref.WeakReference; import java.util.Collections; import java.util.NoSuchElementException; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.WeakHashMap; import java.util.LinkedList; import java.util.Map; import java.util.Map.Entry; import org.apache.lucene.analysis.TokenStream; // for javadocs /** * An AttributeSource contains a list of different {@link AttributeImpl}s, * and methods to add and get them. There can only be a single instance * of an attribute in the same AttributeSource instance. This is ensured * by passing in the actual type of the Attribute (Class&lt;Attribute&gt;) to * the {@link #addAttribute(Class)}, which then checks if an instance of * that type is already present. If yes, it returns the instance, otherwise * it creates a new instance and returns it. */ public class AttributeSource { /** * An AttributeFactory creates instances of {@link AttributeImpl}s. */ public static abstract class AttributeFactory { /** * returns an {@link AttributeImpl} for the supplied {@link Attribute} interface class. */ public abstract AttributeImpl createAttributeInstance(Class<? extends Attribute> attClass); /** * This is the default factory that creates {@link AttributeImpl}s using the * class name of the supplied {@link Attribute} interface class by appending <code>Impl</code> to it. */ public static final AttributeFactory DEFAULT_ATTRIBUTE_FACTORY = new DefaultAttributeFactory(); private static final class DefaultAttributeFactory extends AttributeFactory { private static final WeakHashMap<Class<? extends Attribute>, WeakReference<Class<? extends AttributeImpl>>> attClassImplMap = new WeakHashMap<Class<? extends Attribute>, WeakReference<Class<? extends AttributeImpl>>>(); private DefaultAttributeFactory() {} @Override public AttributeImpl createAttributeInstance(Class<? extends Attribute> attClass) { try { return getClassForInterface(attClass).newInstance(); } catch (InstantiationException e) { throw new IllegalArgumentException("Could not instantiate implementing class for " + attClass.getName()); } catch (IllegalAccessException e) { throw new IllegalArgumentException("Could not instantiate implementing class for " + attClass.getName()); } } private static Class<? extends AttributeImpl> getClassForInterface(Class<? extends Attribute> attClass) { synchronized(attClassImplMap) { final WeakReference<Class<? extends AttributeImpl>> ref = attClassImplMap.get(attClass); Class<? extends AttributeImpl> clazz = (ref == null) ? null : ref.get(); if (clazz == null) { try { attClassImplMap.put(attClass, new WeakReference<Class<? extends AttributeImpl>>( clazz = Class.forName(attClass.getName() + "Impl", true, attClass.getClassLoader()) .asSubclass(AttributeImpl.class) ) ); } catch (ClassNotFoundException e) { throw new IllegalArgumentException("Could not find implementing class for " + attClass.getName()); } } return clazz; } } } } // These two maps must always be in sync!!! // So they are private, final and read-only from the outside (read-only iterators) private final Map<Class<? extends Attribute>, AttributeImpl> attributes; private final Map<Class<? extends AttributeImpl>, AttributeImpl> attributeImpls; private AttributeFactory factory; /** * An AttributeSource using the default attribute factory {@link AttributeSource.AttributeFactory#DEFAULT_ATTRIBUTE_FACTORY}. */ public AttributeSource() { this(AttributeFactory.DEFAULT_ATTRIBUTE_FACTORY); } /** * An AttributeSource that uses the same attributes as the supplied one. */ public AttributeSource(AttributeSource input) { if (input == null) { throw new IllegalArgumentException("input AttributeSource must not be null"); } this.attributes = input.attributes; this.attributeImpls = input.attributeImpls; this.factory = input.factory; } /** * An AttributeSource using the supplied {@link AttributeFactory} for creating new {@link Attribute} instances. */ public AttributeSource(AttributeFactory factory) { this.attributes = new LinkedHashMap<Class<? extends Attribute>, AttributeImpl>(); this.attributeImpls = new LinkedHashMap<Class<? extends AttributeImpl>, AttributeImpl>(); this.factory = factory; } /** * returns the used AttributeFactory. */ public AttributeFactory getAttributeFactory() { return this.factory; } /** Returns a new iterator that iterates the attribute classes * in the same order they were added in. */ public Iterator<Class<? extends Attribute>> getAttributeClassesIterator() { return Collections.unmodifiableSet(attributes.keySet()).iterator(); } /** Returns a new iterator that iterates all unique Attribute implementations. * This iterator may contain less entries that {@link #getAttributeClassesIterator}, * if one instance implements more than one Attribute interface. */ public Iterator<AttributeImpl> getAttributeImplsIterator() { if (hasAttributes()) { if (currentState == null) { computeCurrentState(); } final State initState = currentState; return new Iterator<AttributeImpl>() { private State state = initState; public void remove() { throw new UnsupportedOperationException(); } public AttributeImpl next() { if (state == null) throw new NoSuchElementException(); final AttributeImpl att = state.attribute; state = state.next; return att; } public boolean hasNext() { return state != null; } }; } else { return Collections.<AttributeImpl>emptySet().iterator(); } } /** a cache that stores all interfaces for known implementation classes for performance (slow reflection) */ private static final WeakHashMap<Class<? extends AttributeImpl>,LinkedList<WeakReference<Class<? extends Attribute>>>> knownImplClasses = new WeakHashMap<Class<? extends AttributeImpl>,LinkedList<WeakReference<Class<? extends Attribute>>>>(); /** <b>Expert:</b> Adds a custom AttributeImpl instance with one or more Attribute interfaces. * <p><font color="red"><b>Please note:</b> It is not guaranteed, that <code>att</code> is added to * the <code>AttributeSource</code>, because the provided attributes may already exist. * You should always retrieve the wanted attributes using {@link #getAttribute} after adding * with this method and cast to your class. * The recommended way to use custom implementations is using an {@link AttributeFactory}. * </font></p> */ public void addAttributeImpl(final AttributeImpl att) { final Class<? extends AttributeImpl> clazz = att.getClass(); if (attributeImpls.containsKey(clazz)) return; LinkedList<WeakReference<Class<? extends Attribute>>> foundInterfaces; synchronized(knownImplClasses) { foundInterfaces = knownImplClasses.get(clazz); if (foundInterfaces == null) { // we have a strong reference to the class instance holding all interfaces in the list (parameter "att"), // so all WeakReferences are never evicted by GC knownImplClasses.put(clazz, foundInterfaces = new LinkedList<WeakReference<Class<? extends Attribute>>>()); // find all interfaces that this attribute instance implements // and that extend the Attribute interface Class<?> actClazz = clazz; do { for (Class<?> curInterface : actClazz.getInterfaces()) { if (curInterface != Attribute.class && Attribute.class.isAssignableFrom(curInterface)) { foundInterfaces.add(new WeakReference<Class<? extends Attribute>>(curInterface.asSubclass(Attribute.class))); } } actClazz = actClazz.getSuperclass(); } while (actClazz != null); } } // add all interfaces of this AttributeImpl to the maps for (WeakReference<Class<? extends Attribute>> curInterfaceRef : foundInterfaces) { final Class<? extends Attribute> curInterface = curInterfaceRef.get(); assert (curInterface != null) : "We have a strong reference on the class holding the interfaces, so they should never get evicted"; // Attribute is a superclass of this interface if (!attributes.containsKey(curInterface)) { // invalidate state to force recomputation in captureState() this.currentState = null; attributes.put(curInterface, att); attributeImpls.put(clazz, att); } } } /** * The caller must pass in a Class&lt;? extends Attribute&gt; value. * This method first checks if an instance of that class is * already in this AttributeSource and returns it. Otherwise a * new instance is created, added to this AttributeSource and returned. */ public <A extends Attribute> A addAttribute(Class<A> attClass) { AttributeImpl attImpl = attributes.get(attClass); if (attImpl == null) { if (!(attClass.isInterface() && Attribute.class.isAssignableFrom(attClass))) { throw new IllegalArgumentException( "addAttribute() only accepts an interface that extends Attribute, but " + attClass.getName() + " does not fulfil this contract." ); } addAttributeImpl(attImpl = this.factory.createAttributeInstance(attClass)); } return attClass.cast(attImpl); } /** Returns true, iff this AttributeSource has any attributes */ public boolean hasAttributes() { return !this.attributes.isEmpty(); } /** * The caller must pass in a Class&lt;? extends Attribute&gt; value. * Returns true, iff this AttributeSource contains the passed-in Attribute. */ public boolean hasAttribute(Class<? extends Attribute> attClass) { return this.attributes.containsKey(attClass); } /** * The caller must pass in a Class&lt;? extends Attribute&gt; value. * Returns the instance of the passed in Attribute contained in this AttributeSource * * @throws IllegalArgumentException if this AttributeSource does not contain the * Attribute. It is recommended to always use {@link #addAttribute} even in consumers * of TokenStreams, because you cannot know if a specific TokenStream really uses * a specific Attribute. {@link #addAttribute} will automatically make the attribute * available. If you want to only use the attribute, if it is available (to optimize * consuming), use {@link #hasAttribute}. */ public <A extends Attribute> A getAttribute(Class<A> attClass) { AttributeImpl attImpl = attributes.get(attClass); if (attImpl == null) { throw new IllegalArgumentException("This AttributeSource does not have the attribute '" + attClass.getName() + "'."); } return attClass.cast(attImpl); } /** * This class holds the state of an AttributeSource. * @see #captureState * @see #restoreState */ public static final class State implements Cloneable { private AttributeImpl attribute; private State next; @Override public Object clone() { State clone = new State(); clone.attribute = (AttributeImpl) attribute.clone(); if (next != null) { clone.next = (State) next.clone(); } return clone; } } private State currentState = null; private void computeCurrentState() { currentState = new State(); State c = currentState; final Iterator<AttributeImpl> it = attributeImpls.values().iterator(); c.attribute = it.next(); while (it.hasNext()) { c.next = new State(); c = c.next; c.attribute = it.next(); } } /** * Resets all Attributes in this AttributeSource by calling * {@link AttributeImpl#clear()} on each Attribute implementation. */ public void clearAttributes() { if (hasAttributes()) { if (currentState == null) { computeCurrentState(); } for (State state = currentState; state != null; state = state.next) { state.attribute.clear(); } } } /** * Captures the state of all Attributes. The return value can be passed to * {@link #restoreState} to restore the state of this or another AttributeSource. */ public State captureState() { if (!hasAttributes()) { return null; } if (currentState == null) { computeCurrentState(); } return (State) this.currentState.clone(); } /** * Restores this state by copying the values of all attribute implementations * that this state contains into the attributes implementations of the targetStream. * The targetStream must contain a corresponding instance for each argument * contained in this state (e.g. it is not possible to restore the state of * an AttributeSource containing a TermAttribute into a AttributeSource using * a Token instance as implementation). * <p> * Note that this method does not affect attributes of the targetStream * that are not contained in this state. In other words, if for example * the targetStream contains an OffsetAttribute, but this state doesn't, then * the value of the OffsetAttribute remains unchanged. It might be desirable to * reset its value to the default, in which case the caller should first * call {@link TokenStream#clearAttributes()} on the targetStream. */ public void restoreState(State state) { if (state == null) return; do { AttributeImpl targetImpl = attributeImpls.get(state.attribute.getClass()); if (targetImpl == null) throw new IllegalArgumentException("State contains an AttributeImpl that is not in this AttributeSource"); state.attribute.copyTo(targetImpl); state = state.next; } while (state != null); } @Override public int hashCode() { int code = 0; if (hasAttributes()) { if (currentState == null) { computeCurrentState(); } for (State state = currentState; state != null; state = state.next) { code = code * 31 + state.attribute.hashCode(); } } return code; } @Override public boolean equals(Object obj) { if (obj == this) { return true; } if (obj instanceof AttributeSource) { AttributeSource other = (AttributeSource) obj; if (hasAttributes()) { if (!other.hasAttributes()) { return false; } if (this.attributeImpls.size() != other.attributeImpls.size()) { return false; } // it is only equal if all attribute impls are the same in the same order if (this.currentState == null) { this.computeCurrentState(); } State thisState = this.currentState; if (other.currentState == null) { other.computeCurrentState(); } State otherState = other.currentState; while (thisState != null && otherState != null) { if (otherState.attribute.getClass() != thisState.attribute.getClass() || !otherState.attribute.equals(thisState.attribute)) { return false; } thisState = thisState.next; otherState = otherState.next; } return true; } else { return !other.hasAttributes(); } } else return false; } @Override public String toString() { StringBuilder sb = new StringBuilder().append('('); if (hasAttributes()) { if (currentState == null) { computeCurrentState(); } for (State state = currentState; state != null; state = state.next) { if (state != currentState) sb.append(','); sb.append(state.attribute.toString()); } } return sb.append(')').toString(); } /** * Performs a clone of all {@link AttributeImpl} instances returned in a new * AttributeSource instance. This method can be used to e.g. create another TokenStream * with exactly the same attributes (using {@link #AttributeSource(AttributeSource)}) */ public AttributeSource cloneAttributes() { AttributeSource clone = new AttributeSource(this.factory); // first clone the impls if (hasAttributes()) { if (currentState == null) { computeCurrentState(); } for (State state = currentState; state != null; state = state.next) { clone.attributeImpls.put(state.attribute.getClass(), (AttributeImpl) state.attribute.clone()); } } // now the interfaces for (Entry<Class<? extends Attribute>, AttributeImpl> entry : this.attributes.entrySet()) { clone.attributes.put(entry.getKey(), clone.attributeImpls.get(entry.getValue().getClass())); } return clone; } }
zzh-simple-hr
Zlucene/src/java/org/apache/lucene/util/AttributeSource.java
Java
art
18,069
package org.apache.lucene.util; /** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * Simple lockless and memory barrier free String intern cache that is guaranteed * to return the same String instance as String.intern() does. */ public class SimpleStringInterner extends StringInterner { private static class Entry { final private String str; final private int hash; private Entry next; private Entry(String str, int hash, Entry next) { this.str = str; this.hash = hash; this.next = next; } } private final Entry[] cache; private final int maxChainLength; /** * @param tableSize Size of the hash table, should be a power of two. * @param maxChainLength Maximum length of each bucket, after which the oldest item inserted is dropped. */ public SimpleStringInterner(int tableSize, int maxChainLength) { cache = new Entry[Math.max(1,BitUtil.nextHighestPowerOfTwo(tableSize))]; this.maxChainLength = Math.max(2,maxChainLength); } @Override public String intern(String s) { int h = s.hashCode(); // In the future, it may be worth augmenting the string hash // if the lower bits need better distribution. int slot = h & (cache.length-1); Entry first = this.cache[slot]; Entry nextToLast = null; int chainLength = 0; for(Entry e=first; e!=null; e=e.next) { if (e.hash == h && (e.str == s || e.str.compareTo(s)==0)) { // if (e.str == s || (e.hash == h && e.str.compareTo(s)==0)) { return e.str; } chainLength++; if (e.next != null) { nextToLast = e; } } // insertion-order cache: add new entry at head s = s.intern(); this.cache[slot] = new Entry(s, h, first); if (chainLength >= maxChainLength) { // prune last entry nextToLast.next = null; } return s; } }
zzh-simple-hr
Zlucene/src/java/org/apache/lucene/util/SimpleStringInterner.java
Java
art
2,620
/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.lucene.util; // from org.apache.solr.util rev 555343 /** A variety of high efficiency bit twiddling routines. * * @version $Id$ */ public class BitUtil { /** Returns the number of bits set in the long */ public static int pop(long x) { /* Hacker's Delight 32 bit pop function: * http://www.hackersdelight.org/HDcode/newCode/pop_arrayHS.cc * int pop(unsigned x) { x = x - ((x >> 1) & 0x55555555); x = (x & 0x33333333) + ((x >> 2) & 0x33333333); x = (x + (x >> 4)) & 0x0F0F0F0F; x = x + (x >> 8); x = x + (x >> 16); return x & 0x0000003F; } ***/ // 64 bit java version of the C function from above x = x - ((x >>> 1) & 0x5555555555555555L); x = (x & 0x3333333333333333L) + ((x >>>2 ) & 0x3333333333333333L); x = (x + (x >>> 4)) & 0x0F0F0F0F0F0F0F0FL; x = x + (x >>> 8); x = x + (x >>> 16); x = x + (x >>> 32); return ((int)x) & 0x7F; } /*** Returns the number of set bits in an array of longs. */ public static long pop_array(long A[], int wordOffset, int numWords) { /* * Robert Harley and David Seal's bit counting algorithm, as documented * in the revisions of Hacker's Delight * http://www.hackersdelight.org/revisions.pdf * http://www.hackersdelight.org/HDcode/newCode/pop_arrayHS.cc * * This function was adapted to Java, and extended to use 64 bit words. * if only we had access to wider registers like SSE from java... * * This function can be transformed to compute the popcount of other functions * on bitsets via something like this: * sed 's/A\[\([^]]*\)\]/\(A[\1] \& B[\1]\)/g' * */ int n = wordOffset+numWords; long tot=0, tot8=0; long ones=0, twos=0, fours=0; int i; for (i = wordOffset; i <= n - 8; i+=8) { /*** C macro from Hacker's Delight #define CSA(h,l, a,b,c) \ {unsigned u = a ^ b; unsigned v = c; \ h = (a & b) | (u & v); l = u ^ v;} ***/ long twosA,twosB,foursA,foursB,eights; // CSA(twosA, ones, ones, A[i], A[i+1]) { long b=A[i], c=A[i+1]; long u=ones ^ b; twosA=(ones & b)|( u & c); ones=u^c; } // CSA(twosB, ones, ones, A[i+2], A[i+3]) { long b=A[i+2], c=A[i+3]; long u=ones^b; twosB =(ones&b)|(u&c); ones=u^c; } //CSA(foursA, twos, twos, twosA, twosB) { long u=twos^twosA; foursA=(twos&twosA)|(u&twosB); twos=u^twosB; } //CSA(twosA, ones, ones, A[i+4], A[i+5]) { long b=A[i+4], c=A[i+5]; long u=ones^b; twosA=(ones&b)|(u&c); ones=u^c; } // CSA(twosB, ones, ones, A[i+6], A[i+7]) { long b=A[i+6], c=A[i+7]; long u=ones^b; twosB=(ones&b)|(u&c); ones=u^c; } //CSA(foursB, twos, twos, twosA, twosB) { long u=twos^twosA; foursB=(twos&twosA)|(u&twosB); twos=u^twosB; } //CSA(eights, fours, fours, foursA, foursB) { long u=fours^foursA; eights=(fours&foursA)|(u&foursB); fours=u^foursB; } tot8 += pop(eights); } // handle trailing words in a binary-search manner... // derived from the loop above by setting specific elements to 0. // the original method in Hackers Delight used a simple for loop: // for (i = i; i < n; i++) // Add in the last elements // tot = tot + pop(A[i]); if (i<=n-4) { long twosA, twosB, foursA, eights; { long b=A[i], c=A[i+1]; long u=ones ^ b; twosA=(ones & b)|( u & c); ones=u^c; } { long b=A[i+2], c=A[i+3]; long u=ones^b; twosB =(ones&b)|(u&c); ones=u^c; } { long u=twos^twosA; foursA=(twos&twosA)|(u&twosB); twos=u^twosB; } eights=fours&foursA; fours=fours^foursA; tot8 += pop(eights); i+=4; } if (i<=n-2) { long b=A[i], c=A[i+1]; long u=ones ^ b; long twosA=(ones & b)|( u & c); ones=u^c; long foursA=twos&twosA; twos=twos^twosA; long eights=fours&foursA; fours=fours^foursA; tot8 += pop(eights); i+=2; } if (i<n) { tot += pop(A[i]); } tot += (pop(fours)<<2) + (pop(twos)<<1) + pop(ones) + (tot8<<3); return tot; } /** Returns the popcount or cardinality of the two sets after an intersection. * Neither array is modified. */ public static long pop_intersect(long A[], long B[], int wordOffset, int numWords) { // generated from pop_array via sed 's/A\[\([^]]*\)\]/\(A[\1] \& B[\1]\)/g' int n = wordOffset+numWords; long tot=0, tot8=0; long ones=0, twos=0, fours=0; int i; for (i = wordOffset; i <= n - 8; i+=8) { long twosA,twosB,foursA,foursB,eights; // CSA(twosA, ones, ones, (A[i] & B[i]), (A[i+1] & B[i+1])) { long b=(A[i] & B[i]), c=(A[i+1] & B[i+1]); long u=ones ^ b; twosA=(ones & b)|( u & c); ones=u^c; } // CSA(twosB, ones, ones, (A[i+2] & B[i+2]), (A[i+3] & B[i+3])) { long b=(A[i+2] & B[i+2]), c=(A[i+3] & B[i+3]); long u=ones^b; twosB =(ones&b)|(u&c); ones=u^c; } //CSA(foursA, twos, twos, twosA, twosB) { long u=twos^twosA; foursA=(twos&twosA)|(u&twosB); twos=u^twosB; } //CSA(twosA, ones, ones, (A[i+4] & B[i+4]), (A[i+5] & B[i+5])) { long b=(A[i+4] & B[i+4]), c=(A[i+5] & B[i+5]); long u=ones^b; twosA=(ones&b)|(u&c); ones=u^c; } // CSA(twosB, ones, ones, (A[i+6] & B[i+6]), (A[i+7] & B[i+7])) { long b=(A[i+6] & B[i+6]), c=(A[i+7] & B[i+7]); long u=ones^b; twosB=(ones&b)|(u&c); ones=u^c; } //CSA(foursB, twos, twos, twosA, twosB) { long u=twos^twosA; foursB=(twos&twosA)|(u&twosB); twos=u^twosB; } //CSA(eights, fours, fours, foursA, foursB) { long u=fours^foursA; eights=(fours&foursA)|(u&foursB); fours=u^foursB; } tot8 += pop(eights); } if (i<=n-4) { long twosA, twosB, foursA, eights; { long b=(A[i] & B[i]), c=(A[i+1] & B[i+1]); long u=ones ^ b; twosA=(ones & b)|( u & c); ones=u^c; } { long b=(A[i+2] & B[i+2]), c=(A[i+3] & B[i+3]); long u=ones^b; twosB =(ones&b)|(u&c); ones=u^c; } { long u=twos^twosA; foursA=(twos&twosA)|(u&twosB); twos=u^twosB; } eights=fours&foursA; fours=fours^foursA; tot8 += pop(eights); i+=4; } if (i<=n-2) { long b=(A[i] & B[i]), c=(A[i+1] & B[i+1]); long u=ones ^ b; long twosA=(ones & b)|( u & c); ones=u^c; long foursA=twos&twosA; twos=twos^twosA; long eights=fours&foursA; fours=fours^foursA; tot8 += pop(eights); i+=2; } if (i<n) { tot += pop((A[i] & B[i])); } tot += (pop(fours)<<2) + (pop(twos)<<1) + pop(ones) + (tot8<<3); return tot; } /** Returns the popcount or cardinality of the union of two sets. * Neither array is modified. */ public static long pop_union(long A[], long B[], int wordOffset, int numWords) { // generated from pop_array via sed 's/A\[\([^]]*\)\]/\(A[\1] \| B[\1]\)/g' int n = wordOffset+numWords; long tot=0, tot8=0; long ones=0, twos=0, fours=0; int i; for (i = wordOffset; i <= n - 8; i+=8) { /*** C macro from Hacker's Delight #define CSA(h,l, a,b,c) \ {unsigned u = a ^ b; unsigned v = c; \ h = (a & b) | (u & v); l = u ^ v;} ***/ long twosA,twosB,foursA,foursB,eights; // CSA(twosA, ones, ones, (A[i] | B[i]), (A[i+1] | B[i+1])) { long b=(A[i] | B[i]), c=(A[i+1] | B[i+1]); long u=ones ^ b; twosA=(ones & b)|( u & c); ones=u^c; } // CSA(twosB, ones, ones, (A[i+2] | B[i+2]), (A[i+3] | B[i+3])) { long b=(A[i+2] | B[i+2]), c=(A[i+3] | B[i+3]); long u=ones^b; twosB =(ones&b)|(u&c); ones=u^c; } //CSA(foursA, twos, twos, twosA, twosB) { long u=twos^twosA; foursA=(twos&twosA)|(u&twosB); twos=u^twosB; } //CSA(twosA, ones, ones, (A[i+4] | B[i+4]), (A[i+5] | B[i+5])) { long b=(A[i+4] | B[i+4]), c=(A[i+5] | B[i+5]); long u=ones^b; twosA=(ones&b)|(u&c); ones=u^c; } // CSA(twosB, ones, ones, (A[i+6] | B[i+6]), (A[i+7] | B[i+7])) { long b=(A[i+6] | B[i+6]), c=(A[i+7] | B[i+7]); long u=ones^b; twosB=(ones&b)|(u&c); ones=u^c; } //CSA(foursB, twos, twos, twosA, twosB) { long u=twos^twosA; foursB=(twos&twosA)|(u&twosB); twos=u^twosB; } //CSA(eights, fours, fours, foursA, foursB) { long u=fours^foursA; eights=(fours&foursA)|(u&foursB); fours=u^foursB; } tot8 += pop(eights); } if (i<=n-4) { long twosA, twosB, foursA, eights; { long b=(A[i] | B[i]), c=(A[i+1] | B[i+1]); long u=ones ^ b; twosA=(ones & b)|( u & c); ones=u^c; } { long b=(A[i+2] | B[i+2]), c=(A[i+3] | B[i+3]); long u=ones^b; twosB =(ones&b)|(u&c); ones=u^c; } { long u=twos^twosA; foursA=(twos&twosA)|(u&twosB); twos=u^twosB; } eights=fours&foursA; fours=fours^foursA; tot8 += pop(eights); i+=4; } if (i<=n-2) { long b=(A[i] | B[i]), c=(A[i+1] | B[i+1]); long u=ones ^ b; long twosA=(ones & b)|( u & c); ones=u^c; long foursA=twos&twosA; twos=twos^twosA; long eights=fours&foursA; fours=fours^foursA; tot8 += pop(eights); i+=2; } if (i<n) { tot += pop((A[i] | B[i])); } tot += (pop(fours)<<2) + (pop(twos)<<1) + pop(ones) + (tot8<<3); return tot; } /** Returns the popcount or cardinality of A & ~B * Neither array is modified. */ public static long pop_andnot(long A[], long B[], int wordOffset, int numWords) { // generated from pop_array via sed 's/A\[\([^]]*\)\]/\(A[\1] \& ~B[\1]\)/g' int n = wordOffset+numWords; long tot=0, tot8=0; long ones=0, twos=0, fours=0; int i; for (i = wordOffset; i <= n - 8; i+=8) { /*** C macro from Hacker's Delight #define CSA(h,l, a,b,c) \ {unsigned u = a ^ b; unsigned v = c; \ h = (a & b) | (u & v); l = u ^ v;} ***/ long twosA,twosB,foursA,foursB,eights; // CSA(twosA, ones, ones, (A[i] & ~B[i]), (A[i+1] & ~B[i+1])) { long b=(A[i] & ~B[i]), c=(A[i+1] & ~B[i+1]); long u=ones ^ b; twosA=(ones & b)|( u & c); ones=u^c; } // CSA(twosB, ones, ones, (A[i+2] & ~B[i+2]), (A[i+3] & ~B[i+3])) { long b=(A[i+2] & ~B[i+2]), c=(A[i+3] & ~B[i+3]); long u=ones^b; twosB =(ones&b)|(u&c); ones=u^c; } //CSA(foursA, twos, twos, twosA, twosB) { long u=twos^twosA; foursA=(twos&twosA)|(u&twosB); twos=u^twosB; } //CSA(twosA, ones, ones, (A[i+4] & ~B[i+4]), (A[i+5] & ~B[i+5])) { long b=(A[i+4] & ~B[i+4]), c=(A[i+5] & ~B[i+5]); long u=ones^b; twosA=(ones&b)|(u&c); ones=u^c; } // CSA(twosB, ones, ones, (A[i+6] & ~B[i+6]), (A[i+7] & ~B[i+7])) { long b=(A[i+6] & ~B[i+6]), c=(A[i+7] & ~B[i+7]); long u=ones^b; twosB=(ones&b)|(u&c); ones=u^c; } //CSA(foursB, twos, twos, twosA, twosB) { long u=twos^twosA; foursB=(twos&twosA)|(u&twosB); twos=u^twosB; } //CSA(eights, fours, fours, foursA, foursB) { long u=fours^foursA; eights=(fours&foursA)|(u&foursB); fours=u^foursB; } tot8 += pop(eights); } if (i<=n-4) { long twosA, twosB, foursA, eights; { long b=(A[i] & ~B[i]), c=(A[i+1] & ~B[i+1]); long u=ones ^ b; twosA=(ones & b)|( u & c); ones=u^c; } { long b=(A[i+2] & ~B[i+2]), c=(A[i+3] & ~B[i+3]); long u=ones^b; twosB =(ones&b)|(u&c); ones=u^c; } { long u=twos^twosA; foursA=(twos&twosA)|(u&twosB); twos=u^twosB; } eights=fours&foursA; fours=fours^foursA; tot8 += pop(eights); i+=4; } if (i<=n-2) { long b=(A[i] & ~B[i]), c=(A[i+1] & ~B[i+1]); long u=ones ^ b; long twosA=(ones & b)|( u & c); ones=u^c; long foursA=twos&twosA; twos=twos^twosA; long eights=fours&foursA; fours=fours^foursA; tot8 += pop(eights); i+=2; } if (i<n) { tot += pop((A[i] & ~B[i])); } tot += (pop(fours)<<2) + (pop(twos)<<1) + pop(ones) + (tot8<<3); return tot; } public static long pop_xor(long A[], long B[], int wordOffset, int numWords) { int n = wordOffset+numWords; long tot=0, tot8=0; long ones=0, twos=0, fours=0; int i; for (i = wordOffset; i <= n - 8; i+=8) { /*** C macro from Hacker's Delight #define CSA(h,l, a,b,c) \ {unsigned u = a ^ b; unsigned v = c; \ h = (a & b) | (u & v); l = u ^ v;} ***/ long twosA,twosB,foursA,foursB,eights; // CSA(twosA, ones, ones, (A[i] ^ B[i]), (A[i+1] ^ B[i+1])) { long b=(A[i] ^ B[i]), c=(A[i+1] ^ B[i+1]); long u=ones ^ b; twosA=(ones & b)|( u & c); ones=u^c; } // CSA(twosB, ones, ones, (A[i+2] ^ B[i+2]), (A[i+3] ^ B[i+3])) { long b=(A[i+2] ^ B[i+2]), c=(A[i+3] ^ B[i+3]); long u=ones^b; twosB =(ones&b)|(u&c); ones=u^c; } //CSA(foursA, twos, twos, twosA, twosB) { long u=twos^twosA; foursA=(twos&twosA)|(u&twosB); twos=u^twosB; } //CSA(twosA, ones, ones, (A[i+4] ^ B[i+4]), (A[i+5] ^ B[i+5])) { long b=(A[i+4] ^ B[i+4]), c=(A[i+5] ^ B[i+5]); long u=ones^b; twosA=(ones&b)|(u&c); ones=u^c; } // CSA(twosB, ones, ones, (A[i+6] ^ B[i+6]), (A[i+7] ^ B[i+7])) { long b=(A[i+6] ^ B[i+6]), c=(A[i+7] ^ B[i+7]); long u=ones^b; twosB=(ones&b)|(u&c); ones=u^c; } //CSA(foursB, twos, twos, twosA, twosB) { long u=twos^twosA; foursB=(twos&twosA)|(u&twosB); twos=u^twosB; } //CSA(eights, fours, fours, foursA, foursB) { long u=fours^foursA; eights=(fours&foursA)|(u&foursB); fours=u^foursB; } tot8 += pop(eights); } if (i<=n-4) { long twosA, twosB, foursA, eights; { long b=(A[i] ^ B[i]), c=(A[i+1] ^ B[i+1]); long u=ones ^ b; twosA=(ones & b)|( u & c); ones=u^c; } { long b=(A[i+2] ^ B[i+2]), c=(A[i+3] ^ B[i+3]); long u=ones^b; twosB =(ones&b)|(u&c); ones=u^c; } { long u=twos^twosA; foursA=(twos&twosA)|(u&twosB); twos=u^twosB; } eights=fours&foursA; fours=fours^foursA; tot8 += pop(eights); i+=4; } if (i<=n-2) { long b=(A[i] ^ B[i]), c=(A[i+1] ^ B[i+1]); long u=ones ^ b; long twosA=(ones & b)|( u & c); ones=u^c; long foursA=twos&twosA; twos=twos^twosA; long eights=fours&foursA; fours=fours^foursA; tot8 += pop(eights); i+=2; } if (i<n) { tot += pop((A[i] ^ B[i])); } tot += (pop(fours)<<2) + (pop(twos)<<1) + pop(ones) + (tot8<<3); return tot; } /* python code to generate ntzTable def ntz(val): if val==0: return 8 i=0 while (val&0x01)==0: i = i+1 val >>= 1 return i print ','.join([ str(ntz(i)) for i in range(256) ]) ***/ /** table of number of trailing zeros in a byte */ public static final byte[] ntzTable = {8,0,1,0,2,0,1,0,3,0,1,0,2,0,1,0,4,0,1,0,2,0,1,0,3,0,1,0,2,0,1,0,5,0,1,0,2,0,1,0,3,0,1,0,2,0,1,0,4,0,1,0,2,0,1,0,3,0,1,0,2,0,1,0,6,0,1,0,2,0,1,0,3,0,1,0,2,0,1,0,4,0,1,0,2,0,1,0,3,0,1,0,2,0,1,0,5,0,1,0,2,0,1,0,3,0,1,0,2,0,1,0,4,0,1,0,2,0,1,0,3,0,1,0,2,0,1,0,7,0,1,0,2,0,1,0,3,0,1,0,2,0,1,0,4,0,1,0,2,0,1,0,3,0,1,0,2,0,1,0,5,0,1,0,2,0,1,0,3,0,1,0,2,0,1,0,4,0,1,0,2,0,1,0,3,0,1,0,2,0,1,0,6,0,1,0,2,0,1,0,3,0,1,0,2,0,1,0,4,0,1,0,2,0,1,0,3,0,1,0,2,0,1,0,5,0,1,0,2,0,1,0,3,0,1,0,2,0,1,0,4,0,1,0,2,0,1,0,3,0,1,0,2,0,1,0}; /** Returns number of trailing zeros in a 64 bit long value. */ public static int ntz(long val) { // A full binary search to determine the low byte was slower than // a linear search for nextSetBit(). This is most likely because // the implementation of nextSetBit() shifts bits to the right, increasing // the probability that the first non-zero byte is in the rhs. // // This implementation does a single binary search at the top level only // so that all other bit shifting can be done on ints instead of longs to // remain friendly to 32 bit architectures. In addition, the case of a // non-zero first byte is checked for first because it is the most common // in dense bit arrays. int lower = (int)val; int lowByte = lower & 0xff; if (lowByte != 0) return ntzTable[lowByte]; if (lower!=0) { lowByte = (lower>>>8) & 0xff; if (lowByte != 0) return ntzTable[lowByte] + 8; lowByte = (lower>>>16) & 0xff; if (lowByte != 0) return ntzTable[lowByte] + 16; // no need to mask off low byte for the last byte in the 32 bit word // no need to check for zero on the last byte either. return ntzTable[lower>>>24] + 24; } else { // grab upper 32 bits int upper=(int)(val>>32); lowByte = upper & 0xff; if (lowByte != 0) return ntzTable[lowByte] + 32; lowByte = (upper>>>8) & 0xff; if (lowByte != 0) return ntzTable[lowByte] + 40; lowByte = (upper>>>16) & 0xff; if (lowByte != 0) return ntzTable[lowByte] + 48; // no need to mask off low byte for the last byte in the 32 bit word // no need to check for zero on the last byte either. return ntzTable[upper>>>24] + 56; } } /** Returns number of trailing zeros in a 32 bit int value. */ public static int ntz(int val) { // This implementation does a single binary search at the top level only. // In addition, the case of a non-zero first byte is checked for first // because it is the most common in dense bit arrays. int lowByte = val & 0xff; if (lowByte != 0) return ntzTable[lowByte]; lowByte = (val>>>8) & 0xff; if (lowByte != 0) return ntzTable[lowByte] + 8; lowByte = (val>>>16) & 0xff; if (lowByte != 0) return ntzTable[lowByte] + 16; // no need to mask off low byte for the last byte. // no need to check for zero on the last byte either. return ntzTable[val>>>24] + 24; } /** returns 0 based index of first set bit * (only works for x!=0) * <br/> This is an alternate implementation of ntz() */ public static int ntz2(long x) { int n = 0; int y = (int)x; if (y==0) {n+=32; y = (int)(x>>>32); } // the only 64 bit shift necessary if ((y & 0x0000FFFF) == 0) { n+=16; y>>>=16; } if ((y & 0x000000FF) == 0) { n+=8; y>>>=8; } return (ntzTable[ y & 0xff ]) + n; } /** returns 0 based index of first set bit * <br/> This is an alternate implementation of ntz() */ public static int ntz3(long x) { // another implementation taken from Hackers Delight, extended to 64 bits // and converted to Java. // Many 32 bit ntz algorithms are at http://www.hackersdelight.org/HDcode/ntz.cc int n = 1; // do the first step as a long, all others as ints. int y = (int)x; if (y==0) {n+=32; y = (int)(x>>>32); } if ((y & 0x0000FFFF) == 0) { n+=16; y>>>=16; } if ((y & 0x000000FF) == 0) { n+=8; y>>>=8; } if ((y & 0x0000000F) == 0) { n+=4; y>>>=4; } if ((y & 0x00000003) == 0) { n+=2; y>>>=2; } return n - (y & 1); } /** returns true if v is a power of two or zero*/ public static boolean isPowerOfTwo(int v) { return ((v & (v-1)) == 0); } /** returns true if v is a power of two or zero*/ public static boolean isPowerOfTwo(long v) { return ((v & (v-1)) == 0); } /** returns the next highest power of two, or the current value if it's already a power of two or zero*/ public static int nextHighestPowerOfTwo(int v) { v--; v |= v >> 1; v |= v >> 2; v |= v >> 4; v |= v >> 8; v |= v >> 16; v++; return v; } /** returns the next highest power of two, or the current value if it's already a power of two or zero*/ public static long nextHighestPowerOfTwo(long v) { v--; v |= v >> 1; v |= v >> 2; v |= v >> 4; v |= v >> 8; v |= v >> 16; v |= v >> 32; v++; return v; } }
zzh-simple-hr
Zlucene/src/java/org/apache/lucene/util/BitUtil.java
Java
art
22,367
<!doctype html public "-//w3c//dtd html 4.0 transitional//en"> <!-- Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. --> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1"> </head> <body> Some utility classes. </body> </html>
zzh-simple-hr
Zlucene/src/java/org/apache/lucene/util/package.html
HTML
art
982
package org.apache.lucene.util; /** * Copyright 2005 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** Floating point numbers smaller than 32 bits. * * @version $Id$ */ public class SmallFloat { /** Converts a 32 bit float to an 8 bit float. * <br>Values less than zero are all mapped to zero. * <br>Values are truncated (rounded down) to the nearest 8 bit value. * <br>Values between zero and the smallest representable value * are rounded up. * * @param f the 32 bit float to be converted to an 8 bit float (byte) * @param numMantissaBits the number of mantissa bits to use in the byte, with the remainder to be used in the exponent * @param zeroExp the zero-point in the range of exponent values * @return the 8 bit float representation */ public static byte floatToByte(float f, int numMantissaBits, int zeroExp) { // Adjustment from a float zero exponent to our zero exponent, // shifted over to our exponent position. int fzero = (63-zeroExp)<<numMantissaBits; int bits = Float.floatToRawIntBits(f); int smallfloat = bits >> (24-numMantissaBits); if (smallfloat < fzero) { return (bits<=0) ? (byte)0 // negative numbers and zero both map to 0 byte :(byte)1; // underflow is mapped to smallest non-zero number. } else if (smallfloat >= fzero + 0x100) { return -1; // overflow maps to largest number } else { return (byte)(smallfloat - fzero); } } /** Converts an 8 bit float to a 32 bit float. */ public static float byteToFloat(byte b, int numMantissaBits, int zeroExp) { // on Java1.5 & 1.6 JVMs, prebuilding a decoding array and doing a lookup // is only a little bit faster (anywhere from 0% to 7%) if (b == 0) return 0.0f; int bits = (b&0xff) << (24-numMantissaBits); bits += (63-zeroExp) << 24; return Float.intBitsToFloat(bits); } // // Some specializations of the generic functions follow. // The generic functions are just as fast with current (1.5) // -server JVMs, but still slower with client JVMs. // /** floatToByte(b, mantissaBits=3, zeroExponent=15) * <br>smallest non-zero value = 5.820766E-10 * <br>largest value = 7.5161928E9 * <br>epsilon = 0.125 */ public static byte floatToByte315(float f) { int bits = Float.floatToRawIntBits(f); int smallfloat = bits >> (24-3); if (smallfloat < (63-15)<<3) { return (bits<=0) ? (byte)0 : (byte)1; } if (smallfloat >= ((63-15)<<3) + 0x100) { return -1; } return (byte)(smallfloat - ((63-15)<<3)); } /** byteToFloat(b, mantissaBits=3, zeroExponent=15) */ public static float byte315ToFloat(byte b) { // on Java1.5 & 1.6 JVMs, prebuilding a decoding array and doing a lookup // is only a little bit faster (anywhere from 0% to 7%) if (b == 0) return 0.0f; int bits = (b&0xff) << (24-3); bits += (63-15) << 24; return Float.intBitsToFloat(bits); } /** floatToByte(b, mantissaBits=5, zeroExponent=2) * <br>smallest nonzero value = 0.033203125 * <br>largest value = 1984.0 * <br>epsilon = 0.03125 */ public static byte floatToByte52(float f) { int bits = Float.floatToRawIntBits(f); int smallfloat = bits >> (24-5); if (smallfloat < (63-2)<<5) { return (bits<=0) ? (byte)0 : (byte)1; } if (smallfloat >= ((63-2)<<5) + 0x100) { return -1; } return (byte)(smallfloat - ((63-2)<<5)); } /** byteToFloat(b, mantissaBits=5, zeroExponent=2) */ public static float byte52ToFloat(byte b) { // on Java1.5 & 1.6 JVMs, prebuilding a decoding array and doing a lookup // is only a little bit faster (anywhere from 0% to 7%) if (b == 0) return 0.0f; int bits = (b&0xff) << (24-5); bits += (63-2) << 24; return Float.intBitsToFloat(bits); } }
zzh-simple-hr
Zlucene/src/java/org/apache/lucene/util/SmallFloat.java
Java
art
4,373
package org.apache.lucene.util; /** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import java.util.concurrent.TimeUnit; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.Condition; import java.util.concurrent.locks.ReentrantLock; /** * A dummy lock as a replacement for {@link ReentrantLock} to disable locking */ public final class DummyConcurrentLock implements Lock { /** a default instance, can be always used, as this {@link Lock} is stateless. */ public static final DummyConcurrentLock INSTANCE = new DummyConcurrentLock(); public void lock() {} public void lockInterruptibly() {} public boolean tryLock() { return true; } public boolean tryLock(long time, TimeUnit unit) { return true; } public void unlock() {} public Condition newCondition() { throw new UnsupportedOperationException(); } }
zzh-simple-hr
Zlucene/src/java/org/apache/lucene/util/DummyConcurrentLock.java
Java
art
1,635
package org.apache.lucene.util; /** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * Helper methods to ease implementing {@link Object#toString()}. */ public class ToStringUtils { /** for printing boost only if not 1.0 */ public static String boost(float boost) { if (boost != 1.0f) { return "^" + Float.toString(boost); } else return ""; } }
zzh-simple-hr
Zlucene/src/java/org/apache/lucene/util/ToStringUtils.java
Java
art
1,125
package org.apache.lucene.util; /** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import java.io.ObjectStreamException; import java.io.Serializable; import java.io.StreamCorruptedException; import java.util.HashMap; import java.util.Map; /** * A serializable Enum class. * @deprecated Use Java 5 enum, will be removed in a later Lucene 3.x release. */ @SuppressWarnings("serial") public abstract class Parameter implements Serializable { static Map<String,Parameter> allParameters = new HashMap<String,Parameter>(); private String name; private Parameter() { // typesafe enum pattern, no public constructor } protected Parameter(String name) { // typesafe enum pattern, no public constructor this.name = name; String key = makeKey(name); if(allParameters.containsKey(key)) throw new IllegalArgumentException("Parameter name " + key + " already used!"); allParameters.put(key, this); } private String makeKey(String name){ return getClass() + " " + name; } @Override public String toString() { return name; } /** * Resolves the deserialized instance to the local reference for accurate * equals() and == comparisons. * * @return a reference to Parameter as resolved in the local VM * @throws ObjectStreamException */ protected Object readResolve() throws ObjectStreamException { Object par = allParameters.get(makeKey(name)); if(par == null) throw new StreamCorruptedException("Unknown parameter value: " + name); return par; } }
zzh-simple-hr
Zlucene/src/java/org/apache/lucene/util/Parameter.java
Java
art
2,335
package org.apache.lucene.util; /** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* * Some of this code came from the excellent Unicode * conversion examples from: * * http://www.unicode.org/Public/PROGRAMS/CVTUTF * * Full Copyright for that code follows: */ /* * Copyright 2001-2004 Unicode, Inc. * * Disclaimer * * This source code is provided as is by Unicode, Inc. No claims are * made as to fitness for any particular purpose. No warranties of any * kind are expressed or implied. The recipient agrees to determine * applicability of information provided. If this file has been * purchased on magnetic or optical media from Unicode, Inc., the * sole remedy for any claim will be exchange of defective media * within 90 days of receipt. * * Limitations on Rights to Redistribute This Code * * Unicode, Inc. hereby grants the right to freely use the information * supplied in this file in the creation of products supporting the * Unicode Standard, and to make copies of this file in any form * for internal or external distribution as long as this notice * remains attached. */ /** * Class to encode java's UTF16 char[] into UTF8 byte[] * without always allocating a new byte[] as * String.getBytes("UTF-8") does. * * <p><b>WARNING</b>: This API is a new and experimental and * may suddenly change. </p> */ final public class UnicodeUtil { public static final int UNI_SUR_HIGH_START = 0xD800; public static final int UNI_SUR_HIGH_END = 0xDBFF; public static final int UNI_SUR_LOW_START = 0xDC00; public static final int UNI_SUR_LOW_END = 0xDFFF; public static final int UNI_REPLACEMENT_CHAR = 0xFFFD; private static final long UNI_MAX_BMP = 0x0000FFFF; private static final int HALF_BASE = 0x0010000; private static final long HALF_SHIFT = 10; private static final long HALF_MASK = 0x3FFL; public static final class UTF8Result { public byte[] result = new byte[10]; public int length; public void setLength(int newLength) { if (result.length < newLength) { byte[] newArray = new byte[(int) (1.5*newLength)]; System.arraycopy(result, 0, newArray, 0, length); result = newArray; } length = newLength; } } public static final class UTF16Result { public char[] result = new char[10]; public int[] offsets = new int[10]; public int length; public void setLength(int newLength) { if (result.length < newLength) { char[] newArray = new char[(int) (1.5*newLength)]; System.arraycopy(result, 0, newArray, 0, length); result = newArray; } length = newLength; } public void copyText(UTF16Result other) { setLength(other.length); System.arraycopy(other.result, 0, result, 0, length); } } /** Encode characters from a char[] source, starting at * offset and stopping when the character 0xffff is seen. * Returns the number of bytes written to bytesOut. */ public static void UTF16toUTF8(final char[] source, final int offset, UTF8Result result) { int upto = 0; int i = offset; byte[] out = result.result; while(true) { final int code = (int) source[i++]; if (upto+4 > out.length) { byte[] newOut = new byte[2*out.length]; assert newOut.length >= upto+4; System.arraycopy(out, 0, newOut, 0, upto); result.result = out = newOut; } if (code < 0x80) out[upto++] = (byte) code; else if (code < 0x800) { out[upto++] = (byte) (0xC0 | (code >> 6)); out[upto++] = (byte)(0x80 | (code & 0x3F)); } else if (code < 0xD800 || code > 0xDFFF) { if (code == 0xffff) // END break; out[upto++] = (byte)(0xE0 | (code >> 12)); out[upto++] = (byte)(0x80 | ((code >> 6) & 0x3F)); out[upto++] = (byte)(0x80 | (code & 0x3F)); } else { // surrogate pair // confirm valid high surrogate if (code < 0xDC00 && source[i] != 0xffff) { int utf32 = (int) source[i]; // confirm valid low surrogate and write pair if (utf32 >= 0xDC00 && utf32 <= 0xDFFF) { utf32 = ((code - 0xD7C0) << 10) + (utf32 & 0x3FF); i++; out[upto++] = (byte)(0xF0 | (utf32 >> 18)); out[upto++] = (byte)(0x80 | ((utf32 >> 12) & 0x3F)); out[upto++] = (byte)(0x80 | ((utf32 >> 6) & 0x3F)); out[upto++] = (byte)(0x80 | (utf32 & 0x3F)); continue; } } // replace unpaired surrogate or out-of-order low surrogate // with substitution character out[upto++] = (byte) 0xEF; out[upto++] = (byte) 0xBF; out[upto++] = (byte) 0xBD; } } //assert matches(source, offset, i-offset-1, out, upto); result.length = upto; } /** Encode characters from a char[] source, starting at * offset for length chars. Returns the number of bytes * written to bytesOut. */ public static void UTF16toUTF8(final char[] source, final int offset, final int length, UTF8Result result) { int upto = 0; int i = offset; final int end = offset + length; byte[] out = result.result; while(i < end) { final int code = (int) source[i++]; if (upto+4 > out.length) { byte[] newOut = new byte[2*out.length]; assert newOut.length >= upto+4; System.arraycopy(out, 0, newOut, 0, upto); result.result = out = newOut; } if (code < 0x80) out[upto++] = (byte) code; else if (code < 0x800) { out[upto++] = (byte) (0xC0 | (code >> 6)); out[upto++] = (byte)(0x80 | (code & 0x3F)); } else if (code < 0xD800 || code > 0xDFFF) { out[upto++] = (byte)(0xE0 | (code >> 12)); out[upto++] = (byte)(0x80 | ((code >> 6) & 0x3F)); out[upto++] = (byte)(0x80 | (code & 0x3F)); } else { // surrogate pair // confirm valid high surrogate if (code < 0xDC00 && i < end && source[i] != 0xffff) { int utf32 = (int) source[i]; // confirm valid low surrogate and write pair if (utf32 >= 0xDC00 && utf32 <= 0xDFFF) { utf32 = ((code - 0xD7C0) << 10) + (utf32 & 0x3FF); i++; out[upto++] = (byte)(0xF0 | (utf32 >> 18)); out[upto++] = (byte)(0x80 | ((utf32 >> 12) & 0x3F)); out[upto++] = (byte)(0x80 | ((utf32 >> 6) & 0x3F)); out[upto++] = (byte)(0x80 | (utf32 & 0x3F)); continue; } } // replace unpaired surrogate or out-of-order low surrogate // with substitution character out[upto++] = (byte) 0xEF; out[upto++] = (byte) 0xBF; out[upto++] = (byte) 0xBD; } } //assert matches(source, offset, length, out, upto); result.length = upto; } /** Encode characters from this String, starting at offset * for length characters. Returns the number of bytes * written to bytesOut. */ public static void UTF16toUTF8(final String s, final int offset, final int length, UTF8Result result) { final int end = offset + length; byte[] out = result.result; int upto = 0; for(int i=offset;i<end;i++) { final int code = (int) s.charAt(i); if (upto+4 > out.length) { byte[] newOut = new byte[2*out.length]; assert newOut.length >= upto+4; System.arraycopy(out, 0, newOut, 0, upto); result.result = out = newOut; } if (code < 0x80) out[upto++] = (byte) code; else if (code < 0x800) { out[upto++] = (byte) (0xC0 | (code >> 6)); out[upto++] = (byte)(0x80 | (code & 0x3F)); } else if (code < 0xD800 || code > 0xDFFF) { out[upto++] = (byte)(0xE0 | (code >> 12)); out[upto++] = (byte)(0x80 | ((code >> 6) & 0x3F)); out[upto++] = (byte)(0x80 | (code & 0x3F)); } else { // surrogate pair // confirm valid high surrogate if (code < 0xDC00 && (i < end-1)) { int utf32 = (int) s.charAt(i+1); // confirm valid low surrogate and write pair if (utf32 >= 0xDC00 && utf32 <= 0xDFFF) { utf32 = ((code - 0xD7C0) << 10) + (utf32 & 0x3FF); i++; out[upto++] = (byte)(0xF0 | (utf32 >> 18)); out[upto++] = (byte)(0x80 | ((utf32 >> 12) & 0x3F)); out[upto++] = (byte)(0x80 | ((utf32 >> 6) & 0x3F)); out[upto++] = (byte)(0x80 | (utf32 & 0x3F)); continue; } } // replace unpaired surrogate or out-of-order low surrogate // with substitution character out[upto++] = (byte) 0xEF; out[upto++] = (byte) 0xBF; out[upto++] = (byte) 0xBD; } } //assert matches(s, offset, length, out, upto); result.length = upto; } /** Convert UTF8 bytes into UTF16 characters. If offset * is non-zero, conversion starts at that starting point * in utf8, re-using the results from the previous call * up until offset. */ public static void UTF8toUTF16(final byte[] utf8, final int offset, final int length, final UTF16Result result) { final int end = offset + length; char[] out = result.result; if (result.offsets.length <= end) { int[] newOffsets = new int[2*end]; System.arraycopy(result.offsets, 0, newOffsets, 0, result.offsets.length); result.offsets = newOffsets; } final int[] offsets = result.offsets; // If incremental decoding fell in the middle of a // single unicode character, rollback to its start: int upto = offset; while(offsets[upto] == -1) upto--; int outUpto = offsets[upto]; // Pre-allocate for worst case 1-for-1 if (outUpto+length >= out.length) { char[] newOut = new char[2*(outUpto+length)]; System.arraycopy(out, 0, newOut, 0, outUpto); result.result = out = newOut; } while (upto < end) { final int b = utf8[upto]&0xff; final int ch; offsets[upto++] = outUpto; if (b < 0xc0) { assert b < 0x80; ch = b; } else if (b < 0xe0) { ch = ((b&0x1f)<<6) + (utf8[upto]&0x3f); offsets[upto++] = -1; } else if (b < 0xf0) { ch = ((b&0xf)<<12) + ((utf8[upto]&0x3f)<<6) + (utf8[upto+1]&0x3f); offsets[upto++] = -1; offsets[upto++] = -1; } else { assert b < 0xf8; ch = ((b&0x7)<<18) + ((utf8[upto]&0x3f)<<12) + ((utf8[upto+1]&0x3f)<<6) + (utf8[upto+2]&0x3f); offsets[upto++] = -1; offsets[upto++] = -1; offsets[upto++] = -1; } if (ch <= UNI_MAX_BMP) { // target is a character <= 0xFFFF out[outUpto++] = (char) ch; } else { // target is a character in range 0xFFFF - 0x10FFFF final int chHalf = ch - HALF_BASE; out[outUpto++] = (char) ((chHalf >> HALF_SHIFT) + UNI_SUR_HIGH_START); out[outUpto++] = (char) ((chHalf & HALF_MASK) + UNI_SUR_LOW_START); } } offsets[upto] = outUpto; result.length = outUpto; } // Only called from assert /* private static boolean matches(char[] source, int offset, int length, byte[] result, int upto) { try { String s1 = new String(source, offset, length); String s2 = new String(result, 0, upto, "UTF-8"); if (!s1.equals(s2)) { //System.out.println("DIFF: s1 len=" + s1.length()); //for(int i=0;i<s1.length();i++) // System.out.println(" " + i + ": " + (int) s1.charAt(i)); //System.out.println("s2 len=" + s2.length()); //for(int i=0;i<s2.length();i++) // System.out.println(" " + i + ": " + (int) s2.charAt(i)); // If the input string was invalid, then the // difference is OK if (!validUTF16String(s1)) return true; return false; } return s1.equals(s2); } catch (UnsupportedEncodingException uee) { return false; } } // Only called from assert private static boolean matches(String source, int offset, int length, byte[] result, int upto) { try { String s1 = source.substring(offset, offset+length); String s2 = new String(result, 0, upto, "UTF-8"); if (!s1.equals(s2)) { // Allow a difference if s1 is not valid UTF-16 //System.out.println("DIFF: s1 len=" + s1.length()); //for(int i=0;i<s1.length();i++) // System.out.println(" " + i + ": " + (int) s1.charAt(i)); //System.out.println(" s2 len=" + s2.length()); //for(int i=0;i<s2.length();i++) // System.out.println(" " + i + ": " + (int) s2.charAt(i)); // If the input string was invalid, then the // difference is OK if (!validUTF16String(s1)) return true; return false; } return s1.equals(s2); } catch (UnsupportedEncodingException uee) { return false; } } public static final boolean validUTF16String(String s) { final int size = s.length(); for(int i=0;i<size;i++) { char ch = s.charAt(i); if (ch >= UNI_SUR_HIGH_START && ch <= UNI_SUR_HIGH_END) { if (i < size-1) { i++; char nextCH = s.charAt(i); if (nextCH >= UNI_SUR_LOW_START && nextCH <= UNI_SUR_LOW_END) { // Valid surrogate pair } else // Unmatched high surrogate return false; } else // Unmatched high surrogate return false; } else if (ch >= UNI_SUR_LOW_START && ch <= UNI_SUR_LOW_END) // Unmatched low surrogate return false; } return true; } public static final boolean validUTF16String(char[] s, int size) { for(int i=0;i<size;i++) { char ch = s[i]; if (ch >= UNI_SUR_HIGH_START && ch <= UNI_SUR_HIGH_END) { if (i < size-1) { i++; char nextCH = s[i]; if (nextCH >= UNI_SUR_LOW_START && nextCH <= UNI_SUR_LOW_END) { // Valid surrogate pair } else return false; } else return false; } else if (ch >= UNI_SUR_LOW_START && ch <= UNI_SUR_LOW_END) // Unmatched low surrogate return false; } return true; } */ }
zzh-simple-hr
Zlucene/src/java/org/apache/lucene/util/UnicodeUtil.java
Java
art
15,066
package org.apache.lucene.util; /** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import java.util.ArrayList; import java.util.List; import org.apache.lucene.index.IndexReader; /** * Common util methods for dealing with {@link IndexReader}s. * */ public class ReaderUtil { /** * Gathers sub-readers from reader into a List. * * @param allSubReaders * @param reader */ public static void gatherSubReaders(List<IndexReader> allSubReaders, IndexReader reader) { IndexReader[] subReaders = reader.getSequentialSubReaders(); if (subReaders == null) { // Add the reader itself, and do not recurse allSubReaders.add(reader); } else { for (int i = 0; i < subReaders.length; i++) { gatherSubReaders(allSubReaders, subReaders[i]); } } } /** * Returns sub IndexReader that contains the given document id. * * @param doc id of document * @param reader parent reader * @return sub reader of parent which contains the specified doc id */ public static IndexReader subReader(int doc, IndexReader reader) { List<IndexReader> subReadersList = new ArrayList<IndexReader>(); ReaderUtil.gatherSubReaders(subReadersList, reader); IndexReader[] subReaders = subReadersList .toArray(new IndexReader[subReadersList.size()]); int[] docStarts = new int[subReaders.length]; int maxDoc = 0; for (int i = 0; i < subReaders.length; i++) { docStarts[i] = maxDoc; maxDoc += subReaders[i].maxDoc(); } return subReaders[ReaderUtil.subIndex(doc, docStarts)]; } /** * Returns sub-reader subIndex from reader. * * @param reader parent reader * @param subIndex index of desired sub reader * @return the subreader at subIndex */ public static IndexReader subReader(IndexReader reader, int subIndex) { List<IndexReader> subReadersList = new ArrayList<IndexReader>(); ReaderUtil.gatherSubReaders(subReadersList, reader); IndexReader[] subReaders = subReadersList .toArray(new IndexReader[subReadersList.size()]); return subReaders[subIndex]; } /** * Returns index of the searcher/reader for document <code>n</code> in the * array used to construct this searcher/reader. */ public static int subIndex(int n, int[] docStarts) { // find // searcher/reader for doc n: int size = docStarts.length; int lo = 0; // search starts array int hi = size - 1; // for first element less than n, return its index while (hi >= lo) { int mid = (lo + hi) >>> 1; int midValue = docStarts[mid]; if (n < midValue) hi = mid - 1; else if (n > midValue) lo = mid + 1; else { // found a match while (mid + 1 < size && docStarts[mid + 1] == midValue) { mid++; // scan to last match } return mid; } } return hi; } }
zzh-simple-hr
Zlucene/src/java/org/apache/lucene/util/ReaderUtil.java
Java
art
3,643
package org.apache.lucene.util; /** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import java.util.BitSet; import org.apache.lucene.search.DocIdSet; import org.apache.lucene.search.DocIdSetIterator; /** Simple DocIdSet and DocIdSetIterator backed by a BitSet */ public class DocIdBitSet extends DocIdSet { private BitSet bitSet; public DocIdBitSet(BitSet bitSet) { this.bitSet = bitSet; } @Override public DocIdSetIterator iterator() { return new DocIdBitSetIterator(bitSet); } /** This DocIdSet implementation is cacheable. */ @Override public boolean isCacheable() { return true; } /** * Returns the underlying BitSet. */ public BitSet getBitSet() { return this.bitSet; } private static class DocIdBitSetIterator extends DocIdSetIterator { private int docId; private BitSet bitSet; DocIdBitSetIterator(BitSet bitSet) { this.bitSet = bitSet; this.docId = -1; } @Override public int docID() { return docId; } @Override public int nextDoc() { // (docId + 1) on next line requires -1 initial value for docNr: int d = bitSet.nextSetBit(docId + 1); // -1 returned by BitSet.nextSetBit() when exhausted docId = d == -1 ? NO_MORE_DOCS : d; return docId; } @Override public int advance(int target) { int d = bitSet.nextSetBit(target); // -1 returned by BitSet.nextSetBit() when exhausted docId = d == -1 ? NO_MORE_DOCS : d; return docId; } } }
zzh-simple-hr
Zlucene/src/java/org/apache/lucene/util/DocIdBitSet.java
Java
art
2,300
package org.apache.lucene.util; /** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** A PriorityQueue maintains a partial ordering of its elements such that the * least element can always be found in constant time. Put()'s and pop()'s * require log(size) time. * * <p><b>NOTE</b>: This class pre-allocates a full array of * length <code>maxSize+1</code>, in {@link #initialize}. * */ public abstract class PriorityQueue<T> { private int size; private int maxSize; protected T[] heap; /** Determines the ordering of objects in this priority queue. Subclasses must define this one method. */ protected abstract boolean lessThan(T a, T b); /** * This method can be overridden by extending classes to return a sentinel * object which will be used by {@link #initialize(int)} to fill the queue, so * that the code which uses that queue can always assume it's full and only * change the top without attempting to insert any new object.<br> * * Those sentinel values should always compare worse than any non-sentinel * value (i.e., {@link #lessThan} should always favor the * non-sentinel values).<br> * * By default, this method returns false, which means the queue will not be * filled with sentinel values. Otherwise, the value returned will be used to * pre-populate the queue. Adds sentinel values to the queue.<br> * * If this method is extended to return a non-null value, then the following * usage pattern is recommended: * * <pre> * // extends getSentinelObject() to return a non-null value. * PriorityQueue<MyObject> pq = new MyQueue<MyObject>(numHits); * // save the 'top' element, which is guaranteed to not be null. * MyObject pqTop = pq.top(); * &lt;...&gt; * // now in order to add a new element, which is 'better' than top (after * // you've verified it is better), it is as simple as: * pqTop.change(). * pqTop = pq.updateTop(); * </pre> * * <b>NOTE:</b> if this method returns a non-null value, it will be called by * {@link #initialize(int)} {@link #size()} times, relying on a new object to * be returned and will not check if it's null again. Therefore you should * ensure any call to this method creates a new instance and behaves * consistently, e.g., it cannot return null if it previously returned * non-null. * * @return the sentinel object to use to pre-populate the queue, or null if * sentinel objects are not supported. */ protected T getSentinelObject() { return null; } /** Subclass constructors must call this. */ @SuppressWarnings("unchecked") protected final void initialize(int maxSize) { size = 0; int heapSize; if (0 == maxSize) // We allocate 1 extra to avoid if statement in top() heapSize = 2; else { if (maxSize == Integer.MAX_VALUE) { // Don't wrap heapSize to -1, in this case, which // causes a confusing NegativeArraySizeException. // Note that very likely this will simply then hit // an OOME, but at least that's more indicative to // caller that this values is too big. We don't +1 // in this case, but it's very unlikely in practice // one will actually insert this many objects into // the PQ: heapSize = Integer.MAX_VALUE; } else { // NOTE: we add +1 because all access to heap is // 1-based not 0-based. heap[0] is unused. heapSize = maxSize + 1; } } heap = (T[]) new Object[heapSize]; // T is unbounded type, so this unchecked cast works always this.maxSize = maxSize; // If sentinel objects are supported, populate the queue with them T sentinel = getSentinelObject(); if (sentinel != null) { heap[1] = sentinel; for (int i = 2; i < heap.length; i++) { heap[i] = getSentinelObject(); } size = maxSize; } } /** * Adds an Object to a PriorityQueue in log(size) time. If one tries to add * more objects than maxSize from initialize an * {@link ArrayIndexOutOfBoundsException} is thrown. * * @return the new 'top' element in the queue. */ public final T add(T element) { size++; heap[size] = element; upHeap(); return heap[1]; } /** * Adds an Object to a PriorityQueue in log(size) time. * It returns the object (if any) that was * dropped off the heap because it was full. This can be * the given parameter (in case it is smaller than the * full heap's minimum, and couldn't be added), or another * object that was previously the smallest value in the * heap and now has been replaced by a larger one, or null * if the queue wasn't yet full with maxSize elements. */ public T insertWithOverflow(T element) { if (size < maxSize) { add(element); return null; } else if (size > 0 && !lessThan(element, heap[1])) { T ret = heap[1]; heap[1] = element; updateTop(); return ret; } else { return element; } } /** Returns the least element of the PriorityQueue in constant time. */ public final T top() { // We don't need to check size here: if maxSize is 0, // then heap is length 2 array with both entries null. // If size is 0 then heap[1] is already null. return heap[1]; } /** Removes and returns the least element of the PriorityQueue in log(size) time. */ public final T pop() { if (size > 0) { T result = heap[1]; // save first value heap[1] = heap[size]; // move last to first heap[size] = null; // permit GC of objects size--; downHeap(); // adjust heap return result; } else return null; } /** * Should be called when the Object at top changes values. Still log(n) worst * case, but it's at least twice as fast to * * <pre> * pq.top().change(); * pq.updateTop(); * </pre> * * instead of * * <pre> * o = pq.pop(); * o.change(); * pq.push(o); * </pre> * * @return the new 'top' element. */ public final T updateTop() { downHeap(); return heap[1]; } /** Returns the number of elements currently stored in the PriorityQueue. */ public final int size() { return size; } /** Removes all entries from the PriorityQueue. */ public final void clear() { for (int i = 0; i <= size; i++) { heap[i] = null; } size = 0; } private final void upHeap() { int i = size; T node = heap[i]; // save bottom node int j = i >>> 1; while (j > 0 && lessThan(node, heap[j])) { heap[i] = heap[j]; // shift parents down i = j; j = j >>> 1; } heap[i] = node; // install saved node } private final void downHeap() { int i = 1; T node = heap[i]; // save top node int j = i << 1; // find smaller child int k = j + 1; if (k <= size && lessThan(heap[k], heap[j])) { j = k; } while (j <= size && lessThan(heap[j], node)) { heap[i] = heap[j]; // shift up child i = j; j = i << 1; k = j + 1; if (k <= size && lessThan(heap[k], heap[j])) { j = k; } } heap[i] = node; // install saved node } }
zzh-simple-hr
Zlucene/src/java/org/apache/lucene/util/PriorityQueue.java
Java
art
8,055
package org.apache.lucene.util; /** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * Methods for manipulating strings. */ public abstract class StringHelper { /** * Expert: * The StringInterner implementation used by Lucene. * This shouldn't be changed to an incompatible implementation after other Lucene APIs have been used. */ public static StringInterner interner = new SimpleStringInterner(1024,8); /** Return the same string object for all equal strings */ public static String intern(String s) { return interner.intern(s); } /** * Compares two byte[] arrays, element by element, and returns the * number of elements common to both arrays. * * @param bytes1 The first byte[] to compare * @param bytes2 The second byte[] to compare * @return The number of common elements. */ public static final int bytesDifference(byte[] bytes1, int len1, byte[] bytes2, int len2) { int len = len1 < len2 ? len1 : len2; for (int i = 0; i < len; i++) if (bytes1[i] != bytes2[i]) return i; return len; } /** * Compares two strings, character by character, and returns the * first position where the two strings differ from one another. * * @param s1 The first string to compare * @param s2 The second string to compare * @return The first position where the two strings differ. */ public static final int stringDifference(String s1, String s2) { int len1 = s1.length(); int len2 = s2.length(); int len = len1 < len2 ? len1 : len2; for (int i = 0; i < len; i++) { if (s1.charAt(i) != s2.charAt(i)) { return i; } } return len; } private StringHelper() { } }
zzh-simple-hr
Zlucene/src/java/org/apache/lucene/util/StringHelper.java
Java
art
2,462
package org.apache.lucene.util; /** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import java.util.concurrent.Executors; import java.util.concurrent.ThreadFactory; import java.util.concurrent.atomic.AtomicInteger; /** * A default {@link ThreadFactory} implementation that accepts the name prefix * of the created threads as a constructor argument. Otherwise, this factory * yields the same semantics as the thread factory returned by * {@link Executors#defaultThreadFactory()}. */ public class NamedThreadFactory implements ThreadFactory { private static final AtomicInteger threadPoolNumber = new AtomicInteger(1); private final ThreadGroup group; private final AtomicInteger threadNumber = new AtomicInteger(1); private static final String NAME_PATTERN = "%s-%d-thread"; private final String threadNamePrefix; /** * Creates a new {@link NamedThreadFactory} instance * * @param threadNamePrefix the name prefix assigned to each thread created. */ public NamedThreadFactory(String threadNamePrefix) { final SecurityManager s = System.getSecurityManager(); group = (s != null) ? s.getThreadGroup() : Thread.currentThread() .getThreadGroup(); this.threadNamePrefix = String.format(NAME_PATTERN, checkPrefix(threadNamePrefix), threadPoolNumber.getAndIncrement()); } private static String checkPrefix(String prefix) { return prefix == null || prefix.length() == 0 ? "Lucene" : prefix; } /** * Creates a new {@link Thread} * * @see java.util.concurrent.ThreadFactory#newThread(java.lang.Runnable) */ public Thread newThread(Runnable r) { final Thread t = new Thread(group, r, String.format("%s-%d", this.threadNamePrefix, threadNumber.getAndIncrement()), 0); t.setDaemon(false); t.setPriority(Thread.NORM_PRIORITY); return t; } }
zzh-simple-hr
Zlucene/src/java/org/apache/lucene/util/NamedThreadFactory.java
Java
art
2,598
package org.apache.lucene.util; /** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import java.lang.reflect.*; import java.text.DecimalFormat; import java.util.*; /** * Estimates the size of a given Object using a given MemoryModel for primitive * size information. * * Resource Usage: * * Internally uses a Map to temporally hold a reference to every * object seen. * * If checkIntered, all Strings checked will be interned, but those * that were not already interned will be released for GC when the * estimate is complete. */ public final class RamUsageEstimator { private MemoryModel memoryModel; private final Map<Object,Object> seen; private int refSize; private int arraySize; private int classSize; private boolean checkInterned; /** * Constructs this object with an AverageGuessMemoryModel and * checkInterned = true. */ public RamUsageEstimator() { this(new AverageGuessMemoryModel()); } /** * @param checkInterned check if Strings are interned and don't add to size * if they are. Defaults to true but if you know the objects you are checking * won't likely contain many interned Strings, it will be faster to turn off * intern checking. */ public RamUsageEstimator(boolean checkInterned) { this(new AverageGuessMemoryModel(), checkInterned); } /** * @param memoryModel MemoryModel to use for primitive object sizes. */ public RamUsageEstimator(MemoryModel memoryModel) { this(memoryModel, true); } /** * @param memoryModel MemoryModel to use for primitive object sizes. * @param checkInterned check if Strings are interned and don't add to size * if they are. Defaults to true but if you know the objects you are checking * won't likely contain many interned Strings, it will be faster to turn off * intern checking. */ public RamUsageEstimator(MemoryModel memoryModel, boolean checkInterned) { this.memoryModel = memoryModel; this.checkInterned = checkInterned; // Use Map rather than Set so that we can use an IdentityHashMap - not // seeing an IdentityHashSet seen = new IdentityHashMap<Object,Object>(64); this.refSize = memoryModel.getReferenceSize(); this.arraySize = memoryModel.getArraySize(); this.classSize = memoryModel.getClassSize(); } public long estimateRamUsage(Object obj) { long size = size(obj); seen.clear(); return size; } private long size(Object obj) { if (obj == null) { return 0; } // interned not part of this object if (checkInterned && obj instanceof String && obj == ((String) obj).intern()) { // interned string will be eligible // for GC on // estimateRamUsage(Object) return return 0; } // skip if we have seen before if (seen.containsKey(obj)) { return 0; } // add to seen seen.put(obj, null); Class clazz = obj.getClass(); if (clazz.isArray()) { return sizeOfArray(obj); } long size = 0; // walk type hierarchy while (clazz != null) { Field[] fields = clazz.getDeclaredFields(); for (int i = 0; i < fields.length; i++) { if (Modifier.isStatic(fields[i].getModifiers())) { continue; } if (fields[i].getType().isPrimitive()) { size += memoryModel.getPrimitiveSize(fields[i].getType()); } else { size += refSize; fields[i].setAccessible(true); try { Object value = fields[i].get(obj); if (value != null) { size += size(value); } } catch (IllegalAccessException ex) { // ignore for now? } } } clazz = clazz.getSuperclass(); } size += classSize; return size; } private long sizeOfArray(Object obj) { int len = Array.getLength(obj); if (len == 0) { return 0; } long size = arraySize; Class arrayElementClazz = obj.getClass().getComponentType(); if (arrayElementClazz.isPrimitive()) { size += len * memoryModel.getPrimitiveSize(arrayElementClazz); } else { for (int i = 0; i < len; i++) { size += refSize + size(Array.get(obj, i)); } } return size; } private static final long ONE_KB = 1024; private static final long ONE_MB = ONE_KB * ONE_KB; private static final long ONE_GB = ONE_KB * ONE_MB; /** * Return good default units based on byte size. */ public static String humanReadableUnits(long bytes, DecimalFormat df) { String newSizeAndUnits; if (bytes / ONE_GB > 0) { newSizeAndUnits = String.valueOf(df.format((float) bytes / ONE_GB)) + " GB"; } else if (bytes / ONE_MB > 0) { newSizeAndUnits = String.valueOf(df.format((float) bytes / ONE_MB)) + " MB"; } else if (bytes / ONE_KB > 0) { newSizeAndUnits = String.valueOf(df.format((float) bytes / ONE_KB)) + " KB"; } else { newSizeAndUnits = String.valueOf(bytes) + " bytes"; } return newSizeAndUnits; } }
zzh-simple-hr
Zlucene/src/java/org/apache/lucene/util/RamUsageEstimator.java
Java
art
5,908
package org.apache.lucene.util; /** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import org.apache.lucene.LucenePackage; /** * Some useful constants. **/ public final class Constants { private Constants() {} // can't construct /** The value of <tt>System.getProperty("java.version")<tt>. **/ public static final String JAVA_VERSION = System.getProperty("java.version"); /** True iff this is Java version 1.1. */ public static final boolean JAVA_1_1 = JAVA_VERSION.startsWith("1.1."); /** True iff this is Java version 1.2. */ public static final boolean JAVA_1_2 = JAVA_VERSION.startsWith("1.2."); /** True iff this is Java version 1.3. */ public static final boolean JAVA_1_3 = JAVA_VERSION.startsWith("1.3."); /** The value of <tt>System.getProperty("os.name")<tt>. **/ public static final String OS_NAME = System.getProperty("os.name"); /** True iff running on Linux. */ public static final boolean LINUX = OS_NAME.startsWith("Linux"); /** True iff running on Windows. */ public static final boolean WINDOWS = OS_NAME.startsWith("Windows"); /** True iff running on SunOS. */ public static final boolean SUN_OS = OS_NAME.startsWith("SunOS"); public static final String OS_ARCH = System.getProperty("os.arch"); public static final String OS_VERSION = System.getProperty("os.version"); public static final String JAVA_VENDOR = System.getProperty("java.vendor"); // NOTE: this logic may not be correct; if you know of a // more reliable approach please raise it on java-dev! public static final boolean JRE_IS_64BIT; static { String x = System.getProperty("sun.arch.data.model"); if (x != null) { JRE_IS_64BIT = x.indexOf("64") != -1; } else { if (OS_ARCH != null && OS_ARCH.indexOf("64") != -1) { JRE_IS_64BIT = true; } else { JRE_IS_64BIT = false; } } } // this method prevents inlining the final version constant in compiled classes, // see: http://www.javaworld.com/community/node/3400 private static String ident(final String s) { return s.toString(); } public static final String LUCENE_MAIN_VERSION = ident("3.0.2"); public static final String LUCENE_VERSION; static { Package pkg = LucenePackage.get(); String v = (pkg == null) ? null : pkg.getImplementationVersion(); if (v == null) { v = LUCENE_MAIN_VERSION + "-dev"; } else if (!v.startsWith(LUCENE_MAIN_VERSION)) { v = LUCENE_MAIN_VERSION + "-dev " + v; } LUCENE_VERSION = ident(v); } }
zzh-simple-hr
Zlucene/src/java/org/apache/lucene/util/Constants.java
Java
art
3,284
package org.apache.lucene.util; /** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* Derived from org.apache.lucene.util.PriorityQueue of March 2005 */ import java.io.IOException; import org.apache.lucene.search.DocIdSetIterator; import org.apache.lucene.search.Scorer; /** A ScorerDocQueue maintains a partial ordering of its Scorers such that the least Scorer can always be found in constant time. Put()'s and pop()'s require log(size) time. The ordering is by Scorer.doc(). */ public class ScorerDocQueue { // later: SpansQueue for spans with doc and term positions private final HeapedScorerDoc[] heap; private final int maxSize; private int size; private class HeapedScorerDoc { Scorer scorer; int doc; HeapedScorerDoc(Scorer s) { this(s, s.docID()); } HeapedScorerDoc(Scorer scorer, int doc) { this.scorer = scorer; this.doc = doc; } void adjust() { doc = scorer.docID(); } } private HeapedScorerDoc topHSD; // same as heap[1], only for speed /** Create a ScorerDocQueue with a maximum size. */ public ScorerDocQueue(int maxSize) { // assert maxSize >= 0; size = 0; int heapSize = maxSize + 1; heap = new HeapedScorerDoc[heapSize]; this.maxSize = maxSize; topHSD = heap[1]; // initially null } /** * Adds a Scorer to a ScorerDocQueue in log(size) time. * If one tries to add more Scorers than maxSize * a RuntimeException (ArrayIndexOutOfBound) is thrown. */ public final void put(Scorer scorer) { size++; heap[size] = new HeapedScorerDoc(scorer); upHeap(); } /** * Adds a Scorer to the ScorerDocQueue in log(size) time if either * the ScorerDocQueue is not full, or not lessThan(scorer, top()). * @param scorer * @return true if scorer is added, false otherwise. */ public boolean insert(Scorer scorer){ if (size < maxSize) { put(scorer); return true; } else { int docNr = scorer.docID(); if ((size > 0) && (! (docNr < topHSD.doc))) { // heap[1] is top() heap[1] = new HeapedScorerDoc(scorer, docNr); downHeap(); return true; } else { return false; } } } /** Returns the least Scorer of the ScorerDocQueue in constant time. * Should not be used when the queue is empty. */ public final Scorer top() { // assert size > 0; return topHSD.scorer; } /** Returns document number of the least Scorer of the ScorerDocQueue * in constant time. * Should not be used when the queue is empty. */ public final int topDoc() { // assert size > 0; return topHSD.doc; } public final float topScore() throws IOException { // assert size > 0; return topHSD.scorer.score(); } public final boolean topNextAndAdjustElsePop() throws IOException { return checkAdjustElsePop(topHSD.scorer.nextDoc() != DocIdSetIterator.NO_MORE_DOCS); } public final boolean topSkipToAndAdjustElsePop(int target) throws IOException { return checkAdjustElsePop(topHSD.scorer.advance(target) != DocIdSetIterator.NO_MORE_DOCS); } private boolean checkAdjustElsePop(boolean cond) { if (cond) { // see also adjustTop topHSD.doc = topHSD.scorer.docID(); } else { // see also popNoResult heap[1] = heap[size]; // move last to first heap[size] = null; size--; } downHeap(); return cond; } /** Removes and returns the least scorer of the ScorerDocQueue in log(size) * time. * Should not be used when the queue is empty. */ public final Scorer pop() { // assert size > 0; Scorer result = topHSD.scorer; popNoResult(); return result; } /** Removes the least scorer of the ScorerDocQueue in log(size) time. * Should not be used when the queue is empty. */ private final void popNoResult() { heap[1] = heap[size]; // move last to first heap[size] = null; size--; downHeap(); // adjust heap } /** Should be called when the scorer at top changes doc() value. * Still log(n) worst case, but it's at least twice as fast to <pre> * { pq.top().change(); pq.adjustTop(); } * </pre> instead of <pre> * { o = pq.pop(); o.change(); pq.push(o); } * </pre> */ public final void adjustTop() { // assert size > 0; topHSD.adjust(); downHeap(); } /** Returns the number of scorers currently stored in the ScorerDocQueue. */ public final int size() { return size; } /** Removes all entries from the ScorerDocQueue. */ public final void clear() { for (int i = 0; i <= size; i++) { heap[i] = null; } size = 0; } private final void upHeap() { int i = size; HeapedScorerDoc node = heap[i]; // save bottom node int j = i >>> 1; while ((j > 0) && (node.doc < heap[j].doc)) { heap[i] = heap[j]; // shift parents down i = j; j = j >>> 1; } heap[i] = node; // install saved node topHSD = heap[1]; } private final void downHeap() { int i = 1; HeapedScorerDoc node = heap[i]; // save top node int j = i << 1; // find smaller child int k = j + 1; if ((k <= size) && (heap[k].doc < heap[j].doc)) { j = k; } while ((j <= size) && (heap[j].doc < node.doc)) { heap[i] = heap[j]; // shift up child i = j; j = i << 1; k = j + 1; if (k <= size && (heap[k].doc < heap[j].doc)) { j = k; } } heap[i] = node; // install saved node topHSD = heap[1]; } }
zzh-simple-hr
Zlucene/src/java/org/apache/lucene/util/ScorerDocQueue.java
Java
art
6,305
package org.apache.lucene.util; /** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import java.io.IOException; import java.util.BitSet; import org.apache.lucene.search.DocIdSet; import org.apache.lucene.search.DocIdSetIterator; /** * Stores and iterate on sorted integers in compressed form in RAM. <br> * The code for compressing the differences between ascending integers was * borrowed from {@link org.apache.lucene.store.IndexInput} and * {@link org.apache.lucene.store.IndexOutput}. * <p> * <b>NOTE:</b> this class assumes the stored integers are doc Ids (hence why it * extends {@link DocIdSet}). Therefore its {@link #iterator()} assumes {@link * DocIdSetIterator#NO_MORE_DOCS} can be used as sentinel. If you intent to use * this value, then make sure it's not used during search flow. */ public class SortedVIntList extends DocIdSet { /** When a BitSet has fewer than 1 in BITS2VINTLIST_SIZE bits set, * a SortedVIntList representing the index numbers of the set bits * will be smaller than that BitSet. */ final static int BITS2VINTLIST_SIZE = 8; private int size; private byte[] bytes; private int lastBytePos; /** * Create a SortedVIntList from all elements of an array of integers. * * @param sortedInts A sorted array of non negative integers. */ public SortedVIntList(int... sortedInts) { this(sortedInts, sortedInts.length); } /** * Create a SortedVIntList from an array of integers. * @param sortedInts An array of sorted non negative integers. * @param inputSize The number of integers to be used from the array. */ public SortedVIntList(int[] sortedInts, int inputSize) { SortedVIntListBuilder builder = new SortedVIntListBuilder(); for (int i = 0; i < inputSize; i++) { builder.addInt(sortedInts[i]); } builder.done(); } /** * Create a SortedVIntList from a BitSet. * @param bits A bit set representing a set of integers. */ public SortedVIntList(BitSet bits) { SortedVIntListBuilder builder = new SortedVIntListBuilder(); int nextInt = bits.nextSetBit(0); while (nextInt != -1) { builder.addInt(nextInt); nextInt = bits.nextSetBit(nextInt + 1); } builder.done(); } /** * Create a SortedVIntList from an OpenBitSet. * @param bits A bit set representing a set of integers. */ public SortedVIntList(OpenBitSet bits) { SortedVIntListBuilder builder = new SortedVIntListBuilder(); int nextInt = bits.nextSetBit(0); while (nextInt != -1) { builder.addInt(nextInt); nextInt = bits.nextSetBit(nextInt + 1); } builder.done(); } /** * Create a SortedVIntList. * @param docIdSetIterator An iterator providing document numbers as a set of integers. * This DocIdSetIterator is iterated completely when this constructor * is called and it must provide the integers in non * decreasing order. */ public SortedVIntList(DocIdSetIterator docIdSetIterator) throws IOException { SortedVIntListBuilder builder = new SortedVIntListBuilder(); int doc; while ((doc = docIdSetIterator.nextDoc()) != DocIdSetIterator.NO_MORE_DOCS) { builder.addInt(doc); } builder.done(); } private class SortedVIntListBuilder { private int lastInt = 0; SortedVIntListBuilder() { initBytes(); lastInt = 0; } void addInt(int nextInt) { int diff = nextInt - lastInt; if (diff < 0) { throw new IllegalArgumentException( "Input not sorted or first element negative."); } if ((lastBytePos + MAX_BYTES_PER_INT) > bytes.length) { // biggest possible int does not fit resizeBytes((bytes.length * 2) + MAX_BYTES_PER_INT); } // See org.apache.lucene.store.IndexOutput.writeVInt() while ((diff & ~VB1) != 0) { // The high bit of the next byte needs to be set. bytes[lastBytePos++] = (byte) ((diff & VB1) | ~VB1); diff >>>= BIT_SHIFT; } bytes[lastBytePos++] = (byte) diff; // Last byte, high bit not set. size++; lastInt = nextInt; } void done() { resizeBytes(lastBytePos); } } private void initBytes() { size = 0; bytes = new byte[128]; // initial byte size lastBytePos = 0; } private void resizeBytes(int newSize) { if (newSize != bytes.length) { byte[] newBytes = new byte[newSize]; System.arraycopy(bytes, 0, newBytes, 0, lastBytePos); bytes = newBytes; } } private static final int VB1 = 0x7F; private static final int BIT_SHIFT = 7; private final int MAX_BYTES_PER_INT = (31 / BIT_SHIFT) + 1; /** * @return The total number of sorted integers. */ public int size() { return size; } /** * @return The size of the byte array storing the compressed sorted integers. */ public int getByteSize() { return bytes.length; } /** This DocIdSet implementation is cacheable. */ @Override public boolean isCacheable() { return true; } /** * @return An iterator over the sorted integers. */ @Override public DocIdSetIterator iterator() { return new DocIdSetIterator() { int bytePos = 0; int lastInt = 0; int doc = -1; private void advance() { // See org.apache.lucene.store.IndexInput.readVInt() byte b = bytes[bytePos++]; lastInt += b & VB1; for (int s = BIT_SHIFT; (b & ~VB1) != 0; s += BIT_SHIFT) { b = bytes[bytePos++]; lastInt += (b & VB1) << s; } } @Override public int docID() { return doc; } @Override public int nextDoc() { if (bytePos >= lastBytePos) { doc = NO_MORE_DOCS; } else { advance(); doc = lastInt; } return doc; } @Override public int advance(int target) { while (bytePos < lastBytePos) { advance(); if (lastInt >= target) { return doc = lastInt; } } return doc = NO_MORE_DOCS; } }; } }
zzh-simple-hr
Zlucene/src/java/org/apache/lucene/util/SortedVIntList.java
Java
art
6,966
package org.apache.lucene.util; /** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import java.util.Set; import java.util.Collection; import java.util.HashSet; import java.util.Map; /** * Helper class for keeping Lists of Objects associated with keys. <b>WARNING: THIS CLASS IS NOT THREAD SAFE</b> */ public class MapOfSets<K, V> { private final Map<K, Set<V>> theMap; /** * @param m the backing store for this object */ public MapOfSets(Map<K, Set<V>> m) { theMap = m; } /** * @return direct access to the map backing this object. */ public Map<K, Set<V>> getMap() { return theMap; } /** * Adds val to the Set associated with key in the Map. If key is not * already in the map, a new Set will first be created. * @return the size of the Set associated with key once val is added to it. */ public int put(K key, V val) { final Set<V> theSet; if (theMap.containsKey(key)) { theSet = theMap.get(key); } else { theSet = new HashSet<V>(23); theMap.put(key, theSet); } theSet.add(val); return theSet.size(); } /** * Adds multiple vals to the Set associated with key in the Map. * If key is not * already in the map, a new Set will first be created. * @return the size of the Set associated with key once val is added to it. */ public int putAll(K key, Collection<? extends V> vals) { final Set<V> theSet; if (theMap.containsKey(key)) { theSet = theMap.get(key); } else { theSet = new HashSet<V>(23); theMap.put(key, theSet); } theSet.addAll(vals); return theSet.size(); } }
zzh-simple-hr
Zlucene/src/java/org/apache/lucene/util/MapOfSets.java
Java
art
2,396
package org.apache.lucene.util; /** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with this * work for additional information regarding copyright ownership. The ASF * licenses this file to You under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ /** * Returns primitive memory sizes for estimating RAM usage. * */ public abstract class MemoryModel { /** * @return size of array beyond contents */ public abstract int getArraySize(); /** * @return Class size overhead */ public abstract int getClassSize(); /** * @param clazz a primitive Class - bool, byte, char, short, long, float, * short, double, int * @return the size in bytes of given primitive Class */ public abstract int getPrimitiveSize(Class clazz); /** * @return size of reference */ public abstract int getReferenceSize(); }
zzh-simple-hr
Zlucene/src/java/org/apache/lucene/util/MemoryModel.java
Java
art
1,437
/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.lucene.util; import java.util.Arrays; import java.io.Serializable; import org.apache.lucene.search.DocIdSet; import org.apache.lucene.search.DocIdSetIterator; /** An "open" BitSet implementation that allows direct access to the array of words * storing the bits. * <p/> * Unlike java.util.bitset, the fact that bits are packed into an array of longs * is part of the interface. This allows efficient implementation of other algorithms * by someone other than the author. It also allows one to efficiently implement * alternate serialization or interchange formats. * <p/> * <code>OpenBitSet</code> is faster than <code>java.util.BitSet</code> in most operations * and *much* faster at calculating cardinality of sets and results of set operations. * It can also handle sets of larger cardinality (up to 64 * 2**32-1) * <p/> * The goals of <code>OpenBitSet</code> are the fastest implementation possible, and * maximum code reuse. Extra safety and encapsulation * may always be built on top, but if that's built in, the cost can never be removed (and * hence people re-implement their own version in order to get better performance). * If you want a "safe", totally encapsulated (and slower and limited) BitSet * class, use <code>java.util.BitSet</code>. * <p/> * <h3>Performance Results</h3> * Test system: Pentium 4, Sun Java 1.5_06 -server -Xbatch -Xmx64M <br/>BitSet size = 1,000,000 <br/>Results are java.util.BitSet time divided by OpenBitSet time. <table border="1"> <tr> <th></th> <th>cardinality</th> <th>intersect_count</th> <th>union</th> <th>nextSetBit</th> <th>get</th> <th>iterator</th> </tr> <tr> <th>50% full</th> <td>3.36</td> <td>3.96</td> <td>1.44</td> <td>1.46</td> <td>1.99</td> <td>1.58</td> </tr> <tr> <th>1% full</th> <td>3.31</td> <td>3.90</td> <td>&nbsp;</td> <td>1.04</td> <td>&nbsp;</td> <td>0.99</td> </tr> </table> <br/> Test system: AMD Opteron, 64 bit linux, Sun Java 1.5_06 -server -Xbatch -Xmx64M <br/>BitSet size = 1,000,000 <br/>Results are java.util.BitSet time divided by OpenBitSet time. <table border="1"> <tr> <th></th> <th>cardinality</th> <th>intersect_count</th> <th>union</th> <th>nextSetBit</th> <th>get</th> <th>iterator</th> </tr> <tr> <th>50% full</th> <td>2.50</td> <td>3.50</td> <td>1.00</td> <td>1.03</td> <td>1.12</td> <td>1.25</td> </tr> <tr> <th>1% full</th> <td>2.51</td> <td>3.49</td> <td>&nbsp;</td> <td>1.00</td> <td>&nbsp;</td> <td>1.02</td> </tr> </table> * @version $Id$ */ public class OpenBitSet extends DocIdSet implements Cloneable, Serializable { protected long[] bits; protected int wlen; // number of words (elements) used in the array /** Constructs an OpenBitSet large enough to hold numBits. * * @param numBits */ public OpenBitSet(long numBits) { bits = new long[bits2words(numBits)]; wlen = bits.length; } public OpenBitSet() { this(64); } /** Constructs an OpenBitSet from an existing long[]. * <br/> * The first 64 bits are in long[0], * with bit index 0 at the least significant bit, and bit index 63 at the most significant. * Given a bit index, * the word containing it is long[index/64], and it is at bit number index%64 within that word. * <p> * numWords are the number of elements in the array that contain * set bits (non-zero longs). * numWords should be &lt= bits.length, and * any existing words in the array at position &gt= numWords should be zero. * */ public OpenBitSet(long[] bits, int numWords) { this.bits = bits; this.wlen = numWords; } @Override public DocIdSetIterator iterator() { return new OpenBitSetIterator(bits, wlen); } /** This DocIdSet implementation is cacheable. */ @Override public boolean isCacheable() { return true; } /** Returns the current capacity in bits (1 greater than the index of the last bit) */ public long capacity() { return bits.length << 6; } /** * Returns the current capacity of this set. Included for * compatibility. This is *not* equal to {@link #cardinality} */ public long size() { return capacity(); } /** Returns true if there are no set bits */ public boolean isEmpty() { return cardinality()==0; } /** Expert: returns the long[] storing the bits */ public long[] getBits() { return bits; } /** Expert: sets a new long[] to use as the bit storage */ public void setBits(long[] bits) { this.bits = bits; } /** Expert: gets the number of longs in the array that are in use */ public int getNumWords() { return wlen; } /** Expert: sets the number of longs in the array that are in use */ public void setNumWords(int nWords) { this.wlen=nWords; } /** Returns true or false for the specified bit index. */ public boolean get(int index) { int i = index >> 6; // div 64 // signed shift will keep a negative index and force an // array-index-out-of-bounds-exception, removing the need for an explicit check. if (i>=bits.length) return false; int bit = index & 0x3f; // mod 64 long bitmask = 1L << bit; return (bits[i] & bitmask) != 0; } /** Returns true or false for the specified bit index. * The index should be less than the OpenBitSet size */ public boolean fastGet(int index) { int i = index >> 6; // div 64 // signed shift will keep a negative index and force an // array-index-out-of-bounds-exception, removing the need for an explicit check. int bit = index & 0x3f; // mod 64 long bitmask = 1L << bit; return (bits[i] & bitmask) != 0; } /** Returns true or false for the specified bit index */ public boolean get(long index) { int i = (int)(index >> 6); // div 64 if (i>=bits.length) return false; int bit = (int)index & 0x3f; // mod 64 long bitmask = 1L << bit; return (bits[i] & bitmask) != 0; } /** Returns true or false for the specified bit index. * The index should be less than the OpenBitSet size. */ public boolean fastGet(long index) { int i = (int)(index >> 6); // div 64 int bit = (int)index & 0x3f; // mod 64 long bitmask = 1L << bit; return (bits[i] & bitmask) != 0; } /* // alternate implementation of get() public boolean get1(int index) { int i = index >> 6; // div 64 int bit = index & 0x3f; // mod 64 return ((bits[i]>>>bit) & 0x01) != 0; // this does a long shift and a bittest (on x86) vs // a long shift, and a long AND, (the test for zero is prob a no-op) // testing on a P4 indicates this is slower than (bits[i] & bitmask) != 0; } */ /** returns 1 if the bit is set, 0 if not. * The index should be less than the OpenBitSet size */ public int getBit(int index) { int i = index >> 6; // div 64 int bit = index & 0x3f; // mod 64 return ((int)(bits[i]>>>bit)) & 0x01; } /* public boolean get2(int index) { int word = index >> 6; // div 64 int bit = index & 0x0000003f; // mod 64 return (bits[word] << bit) < 0; // hmmm, this would work if bit order were reversed // we could right shift and check for parity bit, if it was available to us. } */ /** sets a bit, expanding the set size if necessary */ public void set(long index) { int wordNum = expandingWordNum(index); int bit = (int)index & 0x3f; long bitmask = 1L << bit; bits[wordNum] |= bitmask; } /** Sets the bit at the specified index. * The index should be less than the OpenBitSet size. */ public void fastSet(int index) { int wordNum = index >> 6; // div 64 int bit = index & 0x3f; // mod 64 long bitmask = 1L << bit; bits[wordNum] |= bitmask; } /** Sets the bit at the specified index. * The index should be less than the OpenBitSet size. */ public void fastSet(long index) { int wordNum = (int)(index >> 6); int bit = (int)index & 0x3f; long bitmask = 1L << bit; bits[wordNum] |= bitmask; } /** Sets a range of bits, expanding the set size if necessary * * @param startIndex lower index * @param endIndex one-past the last bit to set */ public void set(long startIndex, long endIndex) { if (endIndex <= startIndex) return; int startWord = (int)(startIndex>>6); // since endIndex is one past the end, this is index of the last // word to be changed. int endWord = expandingWordNum(endIndex-1); long startmask = -1L << startIndex; long endmask = -1L >>> -endIndex; // 64-(endIndex&0x3f) is the same as -endIndex due to wrap if (startWord == endWord) { bits[startWord] |= (startmask & endmask); return; } bits[startWord] |= startmask; Arrays.fill(bits, startWord+1, endWord, -1L); bits[endWord] |= endmask; } protected int expandingWordNum(long index) { int wordNum = (int)(index >> 6); if (wordNum>=wlen) { ensureCapacity(index+1); wlen = wordNum+1; } return wordNum; } /** clears a bit. * The index should be less than the OpenBitSet size. */ public void fastClear(int index) { int wordNum = index >> 6; int bit = index & 0x03f; long bitmask = 1L << bit; bits[wordNum] &= ~bitmask; // hmmm, it takes one more instruction to clear than it does to set... any // way to work around this? If there were only 63 bits per word, we could // use a right shift of 10111111...111 in binary to position the 0 in the // correct place (using sign extension). // Could also use Long.rotateRight() or rotateLeft() *if* they were converted // by the JVM into a native instruction. // bits[word] &= Long.rotateLeft(0xfffffffe,bit); } /** clears a bit. * The index should be less than the OpenBitSet size. */ public void fastClear(long index) { int wordNum = (int)(index >> 6); // div 64 int bit = (int)index & 0x3f; // mod 64 long bitmask = 1L << bit; bits[wordNum] &= ~bitmask; } /** clears a bit, allowing access beyond the current set size without changing the size.*/ public void clear(long index) { int wordNum = (int)(index >> 6); // div 64 if (wordNum>=wlen) return; int bit = (int)index & 0x3f; // mod 64 long bitmask = 1L << bit; bits[wordNum] &= ~bitmask; } /** Clears a range of bits. Clearing past the end does not change the size of the set. * * @param startIndex lower index * @param endIndex one-past the last bit to clear */ public void clear(int startIndex, int endIndex) { if (endIndex <= startIndex) return; int startWord = (startIndex>>6); if (startWord >= wlen) return; // since endIndex is one past the end, this is index of the last // word to be changed. int endWord = ((endIndex-1)>>6); long startmask = -1L << startIndex; long endmask = -1L >>> -endIndex; // 64-(endIndex&0x3f) is the same as -endIndex due to wrap // invert masks since we are clearing startmask = ~startmask; endmask = ~endmask; if (startWord == endWord) { bits[startWord] &= (startmask | endmask); return; } bits[startWord] &= startmask; int middle = Math.min(wlen, endWord); Arrays.fill(bits, startWord+1, middle, 0L); if (endWord < wlen) { bits[endWord] &= endmask; } } /** Clears a range of bits. Clearing past the end does not change the size of the set. * * @param startIndex lower index * @param endIndex one-past the last bit to clear */ public void clear(long startIndex, long endIndex) { if (endIndex <= startIndex) return; int startWord = (int)(startIndex>>6); if (startWord >= wlen) return; // since endIndex is one past the end, this is index of the last // word to be changed. int endWord = (int)((endIndex-1)>>6); long startmask = -1L << startIndex; long endmask = -1L >>> -endIndex; // 64-(endIndex&0x3f) is the same as -endIndex due to wrap // invert masks since we are clearing startmask = ~startmask; endmask = ~endmask; if (startWord == endWord) { bits[startWord] &= (startmask | endmask); return; } bits[startWord] &= startmask; int middle = Math.min(wlen, endWord); Arrays.fill(bits, startWord+1, middle, 0L); if (endWord < wlen) { bits[endWord] &= endmask; } } /** Sets a bit and returns the previous value. * The index should be less than the OpenBitSet size. */ public boolean getAndSet(int index) { int wordNum = index >> 6; // div 64 int bit = index & 0x3f; // mod 64 long bitmask = 1L << bit; boolean val = (bits[wordNum] & bitmask) != 0; bits[wordNum] |= bitmask; return val; } /** Sets a bit and returns the previous value. * The index should be less than the OpenBitSet size. */ public boolean getAndSet(long index) { int wordNum = (int)(index >> 6); // div 64 int bit = (int)index & 0x3f; // mod 64 long bitmask = 1L << bit; boolean val = (bits[wordNum] & bitmask) != 0; bits[wordNum] |= bitmask; return val; } /** flips a bit. * The index should be less than the OpenBitSet size. */ public void fastFlip(int index) { int wordNum = index >> 6; // div 64 int bit = index & 0x3f; // mod 64 long bitmask = 1L << bit; bits[wordNum] ^= bitmask; } /** flips a bit. * The index should be less than the OpenBitSet size. */ public void fastFlip(long index) { int wordNum = (int)(index >> 6); // div 64 int bit = (int)index & 0x3f; // mod 64 long bitmask = 1L << bit; bits[wordNum] ^= bitmask; } /** flips a bit, expanding the set size if necessary */ public void flip(long index) { int wordNum = expandingWordNum(index); int bit = (int)index & 0x3f; // mod 64 long bitmask = 1L << bit; bits[wordNum] ^= bitmask; } /** flips a bit and returns the resulting bit value. * The index should be less than the OpenBitSet size. */ public boolean flipAndGet(int index) { int wordNum = index >> 6; // div 64 int bit = index & 0x3f; // mod 64 long bitmask = 1L << bit; bits[wordNum] ^= bitmask; return (bits[wordNum] & bitmask) != 0; } /** flips a bit and returns the resulting bit value. * The index should be less than the OpenBitSet size. */ public boolean flipAndGet(long index) { int wordNum = (int)(index >> 6); // div 64 int bit = (int)index & 0x3f; // mod 64 long bitmask = 1L << bit; bits[wordNum] ^= bitmask; return (bits[wordNum] & bitmask) != 0; } /** Flips a range of bits, expanding the set size if necessary * * @param startIndex lower index * @param endIndex one-past the last bit to flip */ public void flip(long startIndex, long endIndex) { if (endIndex <= startIndex) return; int startWord = (int)(startIndex>>6); // since endIndex is one past the end, this is index of the last // word to be changed. int endWord = expandingWordNum(endIndex-1); /*** Grrr, java shifting wraps around so -1L>>>64 == -1 * for that reason, make sure not to use endmask if the bits to flip will * be zero in the last word (redefine endWord to be the last changed...) long startmask = -1L << (startIndex & 0x3f); // example: 11111...111000 long endmask = -1L >>> (64-(endIndex & 0x3f)); // example: 00111...111111 ***/ long startmask = -1L << startIndex; long endmask = -1L >>> -endIndex; // 64-(endIndex&0x3f) is the same as -endIndex due to wrap if (startWord == endWord) { bits[startWord] ^= (startmask & endmask); return; } bits[startWord] ^= startmask; for (int i=startWord+1; i<endWord; i++) { bits[i] = ~bits[i]; } bits[endWord] ^= endmask; } /* public static int pop(long v0, long v1, long v2, long v3) { // derived from pop_array by setting last four elems to 0. // exchanges one pop() call for 10 elementary operations // saving about 7 instructions... is there a better way? long twosA=v0 & v1; long ones=v0^v1; long u2=ones^v2; long twosB =(ones&v2)|(u2&v3); ones=u2^v3; long fours=(twosA&twosB); long twos=twosA^twosB; return (pop(fours)<<2) + (pop(twos)<<1) + pop(ones); } */ /** @return the number of set bits */ public long cardinality() { return BitUtil.pop_array(bits,0,wlen); } /** Returns the popcount or cardinality of the intersection of the two sets. * Neither set is modified. */ public static long intersectionCount(OpenBitSet a, OpenBitSet b) { return BitUtil.pop_intersect(a.bits, b.bits, 0, Math.min(a.wlen, b.wlen)); } /** Returns the popcount or cardinality of the union of the two sets. * Neither set is modified. */ public static long unionCount(OpenBitSet a, OpenBitSet b) { long tot = BitUtil.pop_union(a.bits, b.bits, 0, Math.min(a.wlen, b.wlen)); if (a.wlen < b.wlen) { tot += BitUtil.pop_array(b.bits, a.wlen, b.wlen-a.wlen); } else if (a.wlen > b.wlen) { tot += BitUtil.pop_array(a.bits, b.wlen, a.wlen-b.wlen); } return tot; } /** Returns the popcount or cardinality of "a and not b" * or "intersection(a, not(b))". * Neither set is modified. */ public static long andNotCount(OpenBitSet a, OpenBitSet b) { long tot = BitUtil.pop_andnot(a.bits, b.bits, 0, Math.min(a.wlen, b.wlen)); if (a.wlen > b.wlen) { tot += BitUtil.pop_array(a.bits, b.wlen, a.wlen-b.wlen); } return tot; } /** Returns the popcount or cardinality of the exclusive-or of the two sets. * Neither set is modified. */ public static long xorCount(OpenBitSet a, OpenBitSet b) { long tot = BitUtil.pop_xor(a.bits, b.bits, 0, Math.min(a.wlen, b.wlen)); if (a.wlen < b.wlen) { tot += BitUtil.pop_array(b.bits, a.wlen, b.wlen-a.wlen); } else if (a.wlen > b.wlen) { tot += BitUtil.pop_array(a.bits, b.wlen, a.wlen-b.wlen); } return tot; } /** Returns the index of the first set bit starting at the index specified. * -1 is returned if there are no more set bits. */ public int nextSetBit(int index) { int i = index>>6; if (i>=wlen) return -1; int subIndex = index & 0x3f; // index within the word long word = bits[i] >> subIndex; // skip all the bits to the right of index if (word!=0) { return (i<<6) + subIndex + BitUtil.ntz(word); } while(++i < wlen) { word = bits[i]; if (word!=0) return (i<<6) + BitUtil.ntz(word); } return -1; } /** Returns the index of the first set bit starting at the index specified. * -1 is returned if there are no more set bits. */ public long nextSetBit(long index) { int i = (int)(index>>>6); if (i>=wlen) return -1; int subIndex = (int)index & 0x3f; // index within the word long word = bits[i] >>> subIndex; // skip all the bits to the right of index if (word!=0) { return (((long)i)<<6) + (subIndex + BitUtil.ntz(word)); } while(++i < wlen) { word = bits[i]; if (word!=0) return (((long)i)<<6) + BitUtil.ntz(word); } return -1; } @Override public Object clone() { try { OpenBitSet obs = (OpenBitSet)super.clone(); obs.bits = (long[]) obs.bits.clone(); // hopefully an array clone is as fast(er) than arraycopy return obs; } catch (CloneNotSupportedException e) { throw new RuntimeException(e); } } /** this = this AND other */ public void intersect(OpenBitSet other) { int newLen= Math.min(this.wlen,other.wlen); long[] thisArr = this.bits; long[] otherArr = other.bits; // testing against zero can be more efficient int pos=newLen; while(--pos>=0) { thisArr[pos] &= otherArr[pos]; } if (this.wlen > newLen) { // fill zeros from the new shorter length to the old length Arrays.fill(bits,newLen,this.wlen,0); } this.wlen = newLen; } /** this = this OR other */ public void union(OpenBitSet other) { int newLen = Math.max(wlen,other.wlen); ensureCapacityWords(newLen); long[] thisArr = this.bits; long[] otherArr = other.bits; int pos=Math.min(wlen,other.wlen); while(--pos>=0) { thisArr[pos] |= otherArr[pos]; } if (this.wlen < newLen) { System.arraycopy(otherArr, this.wlen, thisArr, this.wlen, newLen-this.wlen); } this.wlen = newLen; } /** Remove all elements set in other. this = this AND_NOT other */ public void remove(OpenBitSet other) { int idx = Math.min(wlen,other.wlen); long[] thisArr = this.bits; long[] otherArr = other.bits; while(--idx>=0) { thisArr[idx] &= ~otherArr[idx]; } } /** this = this XOR other */ public void xor(OpenBitSet other) { int newLen = Math.max(wlen,other.wlen); ensureCapacityWords(newLen); long[] thisArr = this.bits; long[] otherArr = other.bits; int pos=Math.min(wlen,other.wlen); while(--pos>=0) { thisArr[pos] ^= otherArr[pos]; } if (this.wlen < newLen) { System.arraycopy(otherArr, this.wlen, thisArr, this.wlen, newLen-this.wlen); } this.wlen = newLen; } // some BitSet compatability methods //** see {@link intersect} */ public void and(OpenBitSet other) { intersect(other); } //** see {@link union} */ public void or(OpenBitSet other) { union(other); } //** see {@link andNot} */ public void andNot(OpenBitSet other) { remove(other); } /** returns true if the sets have any elements in common */ public boolean intersects(OpenBitSet other) { int pos = Math.min(this.wlen, other.wlen); long[] thisArr = this.bits; long[] otherArr = other.bits; while (--pos>=0) { if ((thisArr[pos] & otherArr[pos])!=0) return true; } return false; } /** Expand the long[] with the size given as a number of words (64 bit longs). * getNumWords() is unchanged by this call. */ public void ensureCapacityWords(int numWords) { if (bits.length < numWords) { bits = ArrayUtil.grow(bits, numWords); } } /** Ensure that the long[] is big enough to hold numBits, expanding it if necessary. * getNumWords() is unchanged by this call. */ public void ensureCapacity(long numBits) { ensureCapacityWords(bits2words(numBits)); } /** Lowers numWords, the number of words in use, * by checking for trailing zero words. */ public void trimTrailingZeros() { int idx = wlen-1; while (idx>=0 && bits[idx]==0) idx--; wlen = idx+1; } /** returns the number of 64 bit words it would take to hold numBits */ public static int bits2words(long numBits) { return (int)(((numBits-1)>>>6)+1); } /** returns true if both sets have the same bits set */ @Override public boolean equals(Object o) { if (this == o) return true; if (!(o instanceof OpenBitSet)) return false; OpenBitSet a; OpenBitSet b = (OpenBitSet)o; // make a the larger set. if (b.wlen > this.wlen) { a = b; b=this; } else { a=this; } // check for any set bits out of the range of b for (int i=a.wlen-1; i>=b.wlen; i--) { if (a.bits[i]!=0) return false; } for (int i=b.wlen-1; i>=0; i--) { if (a.bits[i] != b.bits[i]) return false; } return true; } @Override public int hashCode() { long h = 0x98761234; // something non-zero for length==0 for (int i = bits.length; --i>=0;) { h ^= bits[i]; h = (h << 1) | (h >>> 63); // rotate left } return (int)((h>>32) ^ h); // fold leftmost bits into right } }
zzh-simple-hr
Zlucene/src/java/org/apache/lucene/util/OpenBitSet.java
Java
art
24,675
package org.apache.lucene.util; /** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * Subclasses of StringInterner are required to * return the same single String object for all equal strings. * Depending on the implementation, this may not be * the same object returned as String.intern(). * * This StringInterner base class simply delegates to String.intern(). */ public class StringInterner { /** Returns a single object instance for each equal string. */ public String intern(String s) { return s.intern(); } /** Returns a single object instance for each equal string. */ public String intern(char[] arr, int offset, int len) { return intern(new String(arr, offset, len)); } }
zzh-simple-hr
Zlucene/src/java/org/apache/lucene/util/StringInterner.java
Java
art
1,465
/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.lucene.util; import org.apache.lucene.search.DocIdSetIterator; /** An iterator to iterate over set bits in an OpenBitSet. * This is faster than nextSetBit() for iterating over the complete set of bits, * especially when the density of the bits set is high. * * @version $Id$ */ public class OpenBitSetIterator extends DocIdSetIterator { // The General Idea: instead of having an array per byte that has // the offsets of the next set bit, that array could be // packed inside a 32 bit integer (8 4 bit numbers). That // should be faster than accessing an array for each index, and // the total array size is kept smaller (256*sizeof(int))=1K protected final static int[] bitlist={ 0x0, 0x1, 0x2, 0x21, 0x3, 0x31, 0x32, 0x321, 0x4, 0x41, 0x42, 0x421, 0x43, 0x431, 0x432, 0x4321, 0x5, 0x51, 0x52, 0x521, 0x53, 0x531, 0x532, 0x5321, 0x54, 0x541, 0x542, 0x5421, 0x543, 0x5431, 0x5432, 0x54321, 0x6, 0x61, 0x62, 0x621, 0x63, 0x631, 0x632, 0x6321, 0x64, 0x641, 0x642, 0x6421, 0x643, 0x6431, 0x6432, 0x64321, 0x65, 0x651, 0x652, 0x6521, 0x653, 0x6531, 0x6532, 0x65321, 0x654, 0x6541, 0x6542, 0x65421, 0x6543, 0x65431, 0x65432, 0x654321, 0x7, 0x71, 0x72, 0x721, 0x73, 0x731, 0x732, 0x7321, 0x74, 0x741, 0x742, 0x7421, 0x743, 0x7431, 0x7432, 0x74321, 0x75, 0x751, 0x752, 0x7521, 0x753, 0x7531, 0x7532, 0x75321, 0x754, 0x7541, 0x7542, 0x75421, 0x7543, 0x75431, 0x75432, 0x754321, 0x76, 0x761, 0x762, 0x7621, 0x763, 0x7631, 0x7632, 0x76321, 0x764, 0x7641, 0x7642, 0x76421, 0x7643, 0x76431, 0x76432, 0x764321, 0x765, 0x7651, 0x7652, 0x76521, 0x7653, 0x76531, 0x76532, 0x765321, 0x7654, 0x76541, 0x76542, 0x765421, 0x76543, 0x765431, 0x765432, 0x7654321, 0x8, 0x81, 0x82, 0x821, 0x83, 0x831, 0x832, 0x8321, 0x84, 0x841, 0x842, 0x8421, 0x843, 0x8431, 0x8432, 0x84321, 0x85, 0x851, 0x852, 0x8521, 0x853, 0x8531, 0x8532, 0x85321, 0x854, 0x8541, 0x8542, 0x85421, 0x8543, 0x85431, 0x85432, 0x854321, 0x86, 0x861, 0x862, 0x8621, 0x863, 0x8631, 0x8632, 0x86321, 0x864, 0x8641, 0x8642, 0x86421, 0x8643, 0x86431, 0x86432, 0x864321, 0x865, 0x8651, 0x8652, 0x86521, 0x8653, 0x86531, 0x86532, 0x865321, 0x8654, 0x86541, 0x86542, 0x865421, 0x86543, 0x865431, 0x865432, 0x8654321, 0x87, 0x871, 0x872, 0x8721, 0x873, 0x8731, 0x8732, 0x87321, 0x874, 0x8741, 0x8742, 0x87421, 0x8743, 0x87431, 0x87432, 0x874321, 0x875, 0x8751, 0x8752, 0x87521, 0x8753, 0x87531, 0x87532, 0x875321, 0x8754, 0x87541, 0x87542, 0x875421, 0x87543, 0x875431, 0x875432, 0x8754321, 0x876, 0x8761, 0x8762, 0x87621, 0x8763, 0x87631, 0x87632, 0x876321, 0x8764, 0x87641, 0x87642, 0x876421, 0x87643, 0x876431, 0x876432, 0x8764321, 0x8765, 0x87651, 0x87652, 0x876521, 0x87653, 0x876531, 0x876532, 0x8765321, 0x87654, 0x876541, 0x876542, 0x8765421, 0x876543, 0x8765431, 0x8765432, 0x87654321 }; /***** the python code that generated bitlist def bits2int(val): arr=0 for shift in range(8,0,-1): if val & 0x80: arr = (arr << 4) | shift val = val << 1 return arr def int_table(): tbl = [ hex(bits2int(val)).strip('L') for val in range(256) ] return ','.join(tbl) ******/ // hmmm, what about an iterator that finds zeros though, // or a reverse iterator... should they be separate classes // for efficiency, or have a common root interface? (or // maybe both? could ask for a SetBitsIterator, etc... private final long[] arr; private final int words; private int i=-1; private long word; private int wordShift; private int indexArray; private int curDocId = -1; public OpenBitSetIterator(OpenBitSet obs) { this(obs.getBits(), obs.getNumWords()); } public OpenBitSetIterator(long[] bits, int numWords) { arr = bits; words = numWords; } // 64 bit shifts private void shift() { if ((int)word ==0) {wordShift +=32; word = word >>>32; } if ((word & 0x0000FFFF) == 0) { wordShift +=16; word >>>=16; } if ((word & 0x000000FF) == 0) { wordShift +=8; word >>>=8; } indexArray = bitlist[(int)word & 0xff]; } /***** alternate shift implementations // 32 bit shifts, but a long shift needed at the end private void shift2() { int y = (int)word; if (y==0) {wordShift +=32; y = (int)(word >>>32); } if ((y & 0x0000FFFF) == 0) { wordShift +=16; y>>>=16; } if ((y & 0x000000FF) == 0) { wordShift +=8; y>>>=8; } indexArray = bitlist[y & 0xff]; word >>>= (wordShift +1); } private void shift3() { int lower = (int)word; int lowByte = lower & 0xff; if (lowByte != 0) { indexArray=bitlist[lowByte]; return; } shift(); } ******/ @Override public int nextDoc() { if (indexArray == 0) { if (word != 0) { word >>>= 8; wordShift += 8; } while (word == 0) { if (++i >= words) { return curDocId = NO_MORE_DOCS; } word = arr[i]; wordShift = -1; // loop invariant code motion should move this } // after the first time, should I go with a linear search, or // stick with the binary search in shift? shift(); } int bitIndex = (indexArray & 0x0f) + wordShift; indexArray >>>= 4; // should i<<6 be cached as a separate variable? // it would only save one cycle in the best circumstances. return curDocId = (i<<6) + bitIndex; } @Override public int advance(int target) { indexArray = 0; i = target >> 6; if (i >= words) { word = 0; // setup so next() will also return -1 return curDocId = NO_MORE_DOCS; } wordShift = target & 0x3f; word = arr[i] >>> wordShift; if (word != 0) { wordShift--; // compensate for 1 based arrIndex } else { while (word == 0) { if (++i >= words) { return curDocId = NO_MORE_DOCS; } word = arr[i]; } wordShift = -1; } shift(); int bitIndex = (indexArray & 0x0f) + wordShift; indexArray >>>= 4; // should i<<6 be cached as a separate variable? // it would only save one cycle in the best circumstances. return curDocId = (i<<6) + bitIndex; } @Override public int docID() { return curDocId; } }
zzh-simple-hr
Zlucene/src/java/org/apache/lucene/util/OpenBitSetIterator.java
Java
art
7,076
package org.apache.lucene.util; /** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * Base interface for attributes. */ public interface Attribute { }
zzh-simple-hr
Zlucene/src/java/org/apache/lucene/util/Attribute.java
Java
art
910
package org.apache.lucene.util; /** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import java.util.IdentityHashMap; import java.util.Map; /** * An average, best guess, MemoryModel that should work okay on most systems. * */ public class AverageGuessMemoryModel extends MemoryModel { // best guess primitive sizes private final Map<Class,Integer> sizes = new IdentityHashMap<Class,Integer>() { { put(boolean.class, Integer.valueOf(1)); put(byte.class, Integer.valueOf(1)); put(char.class, Integer.valueOf(2)); put(short.class, Integer.valueOf(2)); put(int.class, Integer.valueOf(4)); put(float.class, Integer.valueOf(4)); put(double.class, Integer.valueOf(8)); put(long.class, Integer.valueOf(8)); } }; /* * (non-Javadoc) * * @see org.apache.lucene.util.MemoryModel#getArraySize() */ @Override public int getArraySize() { return 16; } /* * (non-Javadoc) * * @see org.apache.lucene.util.MemoryModel#getClassSize() */ @Override public int getClassSize() { return 8; } /* (non-Javadoc) * @see org.apache.lucene.util.MemoryModel#getPrimitiveSize(java.lang.Class) */ @Override public int getPrimitiveSize(Class clazz) { return sizes.get(clazz).intValue(); } /* (non-Javadoc) * @see org.apache.lucene.util.MemoryModel#getReferenceSize() */ @Override public int getReferenceSize() { return 4; } }
zzh-simple-hr
Zlucene/src/java/org/apache/lucene/util/AverageGuessMemoryModel.java
Java
art
2,202
package org.apache.lucene.util; /** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import java.nio.CharBuffer; import java.nio.ByteBuffer; /** * Provides support for converting byte sequences to Strings and back again. * The resulting Strings preserve the original byte sequences' sort order. * * The Strings are constructed using a Base 8000h encoding of the original * binary data - each char of an encoded String represents a 15-bit chunk * from the byte sequence. Base 8000h was chosen because it allows for all * lower 15 bits of char to be used without restriction; the surrogate range * [U+D8000-U+DFFF] does not represent valid chars, and would require * complicated handling to avoid them and allow use of char's high bit. * * Although unset bits are used as padding in the final char, the original * byte sequence could contain trailing bytes with no set bits (null bytes): * padding is indistinguishable from valid information. To overcome this * problem, a char is appended, indicating the number of encoded bytes in the * final content char. * * This class's operations are defined over CharBuffers and ByteBuffers, to * allow for wrapped arrays to be reused, reducing memory allocation costs for * repeated operations. Note that this class calls array() and arrayOffset() * on the CharBuffers and ByteBuffers it uses, so only wrapped arrays may be * used. This class interprets the arrayOffset() and limit() values returned by * its input buffers as beginning and end+1 positions on the wrapped array, * respectively; similarly, on the output buffer, arrayOffset() is the first * position written to, and limit() is set to one past the final output array * position. */ public class IndexableBinaryStringTools { private static final CodingCase[] CODING_CASES = { // CodingCase(int initialShift, int finalShift) new CodingCase( 7, 1 ), // CodingCase(int initialShift, int middleShift, int finalShift) new CodingCase(14, 6, 2), new CodingCase(13, 5, 3), new CodingCase(12, 4, 4), new CodingCase(11, 3, 5), new CodingCase(10, 2, 6), new CodingCase( 9, 1, 7), new CodingCase( 8, 0 ) }; // Export only static methods private IndexableBinaryStringTools() {} /** * Returns the number of chars required to encode the given byte sequence. * * @param original The byte sequence to be encoded. Must be backed by an array. * @return The number of chars required to encode the given byte sequence * @throws IllegalArgumentException If the given ByteBuffer is not backed by an array */ public static int getEncodedLength(ByteBuffer original) throws IllegalArgumentException { if (original.hasArray()) { // Use long for intermediaries to protect against overflow long length = (long)(original.limit() - original.arrayOffset()); return (int)((length * 8L + 14L) / 15L) + 1; } else { throw new IllegalArgumentException("original argument must have a backing array"); } } /** * Returns the number of bytes required to decode the given char sequence. * * @param encoded The char sequence to be encoded. Must be backed by an array. * @return The number of bytes required to decode the given char sequence * @throws IllegalArgumentException If the given CharBuffer is not backed by an array */ public static int getDecodedLength(CharBuffer encoded) throws IllegalArgumentException { if (encoded.hasArray()) { int numChars = encoded.limit() - encoded.arrayOffset() - 1; if (numChars <= 0) { return 0; } else { int numFullBytesInFinalChar = encoded.charAt(encoded.limit() - 1); int numEncodedChars = numChars - 1; return (numEncodedChars * 15 + 7) / 8 + numFullBytesInFinalChar; } } else { throw new IllegalArgumentException("encoded argument must have a backing array"); } } /** * Encodes the input byte sequence into the output char sequence. Before * calling this method, ensure that the output CharBuffer has sufficient * capacity by calling {@link #getEncodedLength(java.nio.ByteBuffer)}. * * @param input The byte sequence to encode * @param output Where the char sequence encoding result will go. The limit * is set to one past the position of the final char. * @throws IllegalArgumentException If either the input or the output buffer * is not backed by an array */ public static void encode(ByteBuffer input, CharBuffer output) { if (input.hasArray() && output.hasArray()) { byte[] inputArray = input.array(); int inputOffset = input.arrayOffset(); int inputLength = input.limit() - inputOffset; char[] outputArray = output.array(); int outputOffset = output.arrayOffset(); int outputLength = getEncodedLength(input); output.limit(outputOffset + outputLength); // Set output final pos + 1 output.position(0); if (inputLength > 0) { int inputByteNum = inputOffset; int caseNum = 0; int outputCharNum = outputOffset; CodingCase codingCase; for ( ; inputByteNum + CODING_CASES[caseNum].numBytes <= inputLength ; ++outputCharNum ) { codingCase = CODING_CASES[caseNum]; if (2 == codingCase.numBytes) { outputArray[outputCharNum] = (char)(((inputArray[inputByteNum] & 0xFF) << codingCase.initialShift) + (((inputArray[inputByteNum + 1] & 0xFF) >>> codingCase.finalShift) & codingCase.finalMask) & (short)0x7FFF); } else { // numBytes is 3 outputArray[outputCharNum] = (char)(((inputArray[inputByteNum] & 0xFF) << codingCase.initialShift) + ((inputArray[inputByteNum + 1] & 0xFF) << codingCase.middleShift) + (((inputArray[inputByteNum + 2] & 0xFF) >>> codingCase.finalShift) & codingCase.finalMask) & (short)0x7FFF); } inputByteNum += codingCase.advanceBytes; if (++caseNum == CODING_CASES.length) { caseNum = 0; } } // Produce final char (if any) and trailing count chars. codingCase = CODING_CASES[caseNum]; if (inputByteNum + 1 < inputLength) { // codingCase.numBytes must be 3 outputArray[outputCharNum++] = (char)((((inputArray[inputByteNum] & 0xFF) << codingCase.initialShift) + ((inputArray[inputByteNum + 1] & 0xFF) << codingCase.middleShift)) & (short)0x7FFF); // Add trailing char containing the number of full bytes in final char outputArray[outputCharNum++] = (char)1; } else if (inputByteNum < inputLength) { outputArray[outputCharNum++] = (char)(((inputArray[inputByteNum] & 0xFF) << codingCase.initialShift) & (short)0x7FFF); // Add trailing char containing the number of full bytes in final char outputArray[outputCharNum++] = caseNum == 0 ? (char)1 : (char)0; } else { // No left over bits - last char is completely filled. // Add trailing char containing the number of full bytes in final char outputArray[outputCharNum++] = (char)1; } } } else { throw new IllegalArgumentException("Arguments must have backing arrays"); } } /** * Decodes the input char sequence into the output byte sequence. Before * calling this method, ensure that the output ByteBuffer has sufficient * capacity by calling {@link #getDecodedLength(java.nio.CharBuffer)}. * * @param input The char sequence to decode * @param output Where the byte sequence decoding result will go. The limit * is set to one past the position of the final char. * @throws IllegalArgumentException If either the input or the output buffer * is not backed by an array */ public static void decode(CharBuffer input, ByteBuffer output) { if (input.hasArray() && output.hasArray()) { int numInputChars = input.limit() - input.arrayOffset() - 1; int numOutputBytes = getDecodedLength(input); output.limit(numOutputBytes + output.arrayOffset()); // Set output final pos + 1 output.position(0); byte[] outputArray = output.array(); char[] inputArray = input.array(); if (numOutputBytes > 0) { int caseNum = 0; int outputByteNum = output.arrayOffset(); int inputCharNum = input.arrayOffset(); short inputChar; CodingCase codingCase; for ( ; inputCharNum < numInputChars - 1 ; ++inputCharNum) { codingCase = CODING_CASES[caseNum]; inputChar = (short)inputArray[inputCharNum]; if (2 == codingCase.numBytes) { if (0 == caseNum) { outputArray[outputByteNum] = (byte)(inputChar >>> codingCase.initialShift); } else { outputArray[outputByteNum] += (byte)(inputChar >>> codingCase.initialShift); } outputArray[outputByteNum + 1] = (byte)((inputChar & codingCase.finalMask) << codingCase.finalShift); } else { // numBytes is 3 outputArray[outputByteNum] += (byte)(inputChar >>> codingCase.initialShift); outputArray[outputByteNum + 1] = (byte)((inputChar & codingCase.middleMask) >>> codingCase.middleShift); outputArray[outputByteNum + 2] = (byte)((inputChar & codingCase.finalMask) << codingCase.finalShift); } outputByteNum += codingCase.advanceBytes; if (++caseNum == CODING_CASES.length) { caseNum = 0; } } // Handle final char inputChar = (short)inputArray[inputCharNum]; codingCase = CODING_CASES[caseNum]; if (0 == caseNum) { outputArray[outputByteNum] = 0; } outputArray[outputByteNum] += (byte)(inputChar >>> codingCase.initialShift); int bytesLeft = numOutputBytes - outputByteNum; if (bytesLeft > 1) { if (2 == codingCase.numBytes) { outputArray[outputByteNum + 1] = (byte)((inputChar & codingCase.finalMask) >>> codingCase.finalShift); } else { // numBytes is 3 outputArray[outputByteNum + 1] = (byte)((inputChar & codingCase.middleMask) >>> codingCase.middleShift); if (bytesLeft > 2) { outputArray[outputByteNum + 2] = (byte)((inputChar & codingCase.finalMask) << codingCase.finalShift); } } } } } else { throw new IllegalArgumentException("Arguments must have backing arrays"); } } /** * Decodes the given char sequence, which must have been encoded by * {@link #encode(java.nio.ByteBuffer)} or * {@link #encode(java.nio.ByteBuffer, java.nio.CharBuffer)}. * * @param input The char sequence to decode * @return A byte sequence containing the decoding result. The limit * is set to one past the position of the final char. * @throws IllegalArgumentException If the input buffer is not backed by an * array */ public static ByteBuffer decode(CharBuffer input) { byte[] outputArray = new byte[getDecodedLength(input)]; ByteBuffer output = ByteBuffer.wrap(outputArray); decode(input, output); return output; } /** * Encodes the input byte sequence. * * @param input The byte sequence to encode * @return A char sequence containing the encoding result. The limit is set * to one past the position of the final char. * @throws IllegalArgumentException If the input buffer is not backed by an * array */ public static CharBuffer encode(ByteBuffer input) { char[] outputArray = new char[getEncodedLength(input)]; CharBuffer output = CharBuffer.wrap(outputArray); encode(input, output); return output; } static class CodingCase { int numBytes, initialShift, middleShift, finalShift, advanceBytes = 2; short middleMask, finalMask; CodingCase(int initialShift, int middleShift, int finalShift) { this.numBytes = 3; this.initialShift = initialShift; this.middleShift = middleShift; this.finalShift = finalShift; this.finalMask = (short)((short)0xFF >>> finalShift); this.middleMask = (short)((short)0xFF << middleShift); } CodingCase(int initialShift, int finalShift) { this.numBytes = 2; this.initialShift = initialShift; this.finalShift = finalShift; this.finalMask = (short)((short)0xFF >>> finalShift); if (finalShift != 0) { advanceBytes = 1; } } } }
zzh-simple-hr
Zlucene/src/java/org/apache/lucene/util/IndexableBinaryStringTools.java
Java
art
13,890
package org.apache.lucene.util; /** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import java.io.Closeable; import java.lang.ref.WeakReference; import java.util.HashMap; import java.util.Iterator; import java.util.Map; /** Java's builtin ThreadLocal has a serious flaw: * it can take an arbitrarily long amount of time to * dereference the things you had stored in it, even once the * ThreadLocal instance itself is no longer referenced. * This is because there is single, master map stored for * each thread, which all ThreadLocals share, and that * master map only periodically purges "stale" entries. * * While not technically a memory leak, because eventually * the memory will be reclaimed, it can take a long time * and you can easily hit OutOfMemoryError because from the * GC's standpoint the stale entries are not reclaimable. * * This class works around that, by only enrolling * WeakReference values into the ThreadLocal, and * separately holding a hard reference to each stored * value. When you call {@link #close}, these hard * references are cleared and then GC is freely able to * reclaim space by objects stored in it. * * We can not rely on {@link ThreadLocal#remove()} as it * only removes the value for the caller thread, whereas * {@link #close} takes care of all * threads. You should not call {@link #close} until all * threads are done using the instance. */ public class CloseableThreadLocal<T> implements Closeable { private ThreadLocal<WeakReference<T>> t = new ThreadLocal<WeakReference<T>>(); private Map<Thread,T> hardRefs = new HashMap<Thread,T>(); protected T initialValue() { return null; } public T get() { WeakReference<T> weakRef = t.get(); if (weakRef == null) { T iv = initialValue(); if (iv != null) { set(iv); return iv; } else return null; } else { return weakRef.get(); } } public void set(T object) { t.set(new WeakReference<T>(object)); synchronized(hardRefs) { hardRefs.put(Thread.currentThread(), object); // Purge dead threads for (Iterator<Thread> it = hardRefs.keySet().iterator(); it.hasNext();) { final Thread t = it.next(); if (!t.isAlive()) it.remove(); } } } public void close() { // Clear the hard refs; then, the only remaining refs to // all values we were storing are weak (unless somewhere // else is still using them) and so GC may reclaim them: hardRefs = null; // Take care of the current thread right now; others will be // taken care of via the WeakReferences. if (t != null) { t.remove(); } t = null; } }
zzh-simple-hr
Zlucene/src/java/org/apache/lucene/util/CloseableThreadLocal.java
Java
art
3,481
package org.apache.lucene.util; /** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import java.io.IOException; import org.apache.lucene.search.DocIdSetIterator; public class OpenBitSetDISI extends OpenBitSet { /** Construct an OpenBitSetDISI with its bits set * from the doc ids of the given DocIdSetIterator. * Also give a maximum size one larger than the largest doc id for which a * bit may ever be set on this OpenBitSetDISI. */ public OpenBitSetDISI(DocIdSetIterator disi, int maxSize) throws IOException { super(maxSize); inPlaceOr(disi); } /** Construct an OpenBitSetDISI with no bits set, and a given maximum size * one larger than the largest doc id for which a bit may ever be set * on this OpenBitSetDISI. */ public OpenBitSetDISI(int maxSize) { super(maxSize); } /** * Perform an inplace OR with the doc ids from a given DocIdSetIterator, * setting the bit for each such doc id. * These doc ids should be smaller than the maximum size passed to the * constructor. */ public void inPlaceOr(DocIdSetIterator disi) throws IOException { int doc; long size = size(); while ((doc = disi.nextDoc()) < size) { fastSet(doc); } } /** * Perform an inplace AND with the doc ids from a given DocIdSetIterator, * leaving only the bits set for which the doc ids are in common. * These doc ids should be smaller than the maximum size passed to the * constructor. */ public void inPlaceAnd(DocIdSetIterator disi) throws IOException { int bitSetDoc = nextSetBit(0); int disiDoc; while (bitSetDoc != -1 && (disiDoc = disi.advance(bitSetDoc)) != DocIdSetIterator.NO_MORE_DOCS) { clear(bitSetDoc, disiDoc); bitSetDoc = nextSetBit(disiDoc + 1); } if (bitSetDoc != -1) { clear(bitSetDoc, size()); } } /** * Perform an inplace NOT with the doc ids from a given DocIdSetIterator, * clearing all the bits for each such doc id. * These doc ids should be smaller than the maximum size passed to the * constructor. */ public void inPlaceNot(DocIdSetIterator disi) throws IOException { int doc; long size = size(); while ((doc = disi.nextDoc()) < size) { fastClear(doc); } } /** * Perform an inplace XOR with the doc ids from a given DocIdSetIterator, * flipping all the bits for each such doc id. * These doc ids should be smaller than the maximum size passed to the * constructor. */ public void inPlaceXor(DocIdSetIterator disi) throws IOException { int doc; long size = size(); while ((doc = disi.nextDoc()) < size) { fastFlip(doc); } } }
zzh-simple-hr
Zlucene/src/java/org/apache/lucene/util/OpenBitSetDISI.java
Java
art
3,436
package org.apache.lucene.util; /* * Copyright 2003 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. */ /** * Borrowed from Cglib. Allows custom swap so that two arrays can be sorted * at the same time. */ public abstract class SorterTemplate { private static final int MERGESORT_THRESHOLD = 12; private static final int QUICKSORT_THRESHOLD = 7; abstract protected void swap(int i, int j); abstract protected int compare(int i, int j); public void quickSort(int lo, int hi) { quickSortHelper(lo, hi); insertionSort(lo, hi); } private void quickSortHelper(int lo, int hi) { for (;;) { int diff = hi - lo; if (diff <= QUICKSORT_THRESHOLD) { break; } int i = (hi + lo) / 2; if (compare(lo, i) > 0) { swap(lo, i); } if (compare(lo, hi) > 0) { swap(lo, hi); } if (compare(i, hi) > 0) { swap(i, hi); } int j = hi - 1; swap(i, j); i = lo; int v = j; for (;;) { while (compare(++i, v) < 0) { /* nothing */; } while (compare(--j, v) > 0) { /* nothing */; } if (j < i) { break; } swap(i, j); } swap(i, hi - 1); if (j - lo <= hi - i + 1) { quickSortHelper(lo, j); lo = i + 1; } else { quickSortHelper(i + 1, hi); hi = j; } } } private void insertionSort(int lo, int hi) { for (int i = lo + 1 ; i <= hi; i++) { for (int j = i; j > lo; j--) { if (compare(j - 1, j) > 0) { swap(j - 1, j); } else { break; } } } } protected void mergeSort(int lo, int hi) { int diff = hi - lo; if (diff <= MERGESORT_THRESHOLD) { insertionSort(lo, hi); return; } int mid = lo + diff / 2; mergeSort(lo, mid); mergeSort(mid, hi); merge(lo, mid, hi, mid - lo, hi - mid); } private void merge(int lo, int pivot, int hi, int len1, int len2) { if (len1 == 0 || len2 == 0) { return; } if (len1 + len2 == 2) { if (compare(pivot, lo) < 0) { swap(pivot, lo); } return; } int first_cut, second_cut; int len11, len22; if (len1 > len2) { len11 = len1 / 2; first_cut = lo + len11; second_cut = lower(pivot, hi, first_cut); len22 = second_cut - pivot; } else { len22 = len2 / 2; second_cut = pivot + len22; first_cut = upper(lo, pivot, second_cut); len11 = first_cut - lo; } rotate(first_cut, pivot, second_cut); int new_mid = first_cut + len22; merge(lo, first_cut, new_mid, len11, len22); merge(new_mid, second_cut, hi, len1 - len11, len2 - len22); } private void rotate(int lo, int mid, int hi) { int lot = lo; int hit = mid - 1; while (lot < hit) { swap(lot++, hit--); } lot = mid; hit = hi - 1; while (lot < hit) { swap(lot++, hit--); } lot = lo; hit = hi - 1; while (lot < hit) { swap(lot++, hit--); } } private int lower(int lo, int hi, int val) { int len = hi - lo; while (len > 0) { int half = len / 2; int mid= lo + half; if (compare(mid, val) < 0) { lo = mid + 1; len = len - half -1; } else { len = half; } } return lo; } private int upper(int lo, int hi, int val) { int len = hi - lo; while (len > 0) { int half = len / 2; int mid = lo + half; if (compare(val, mid) < 0) { len = half; } else { lo = mid + 1; len = len - half -1; } } return lo; } }
zzh-simple-hr
Zlucene/src/java/org/apache/lucene/util/SorterTemplate.java
Java
art
4,994
<!-- Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. --> <html> <!-- Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. --> <head> <title>Apache Lucene API</title> </head> <body> <p>Apache Lucene is a high-performance, full-featured text search engine library. Here's a simple example how to use Lucene for indexing and searching (using JUnit to check if the results are what we expect):</p> <!-- code comes from org.apache.lucene.TestDemo: --> <!-- ======================================================== --> <!-- = Java Sourcecode to HTML automatically converted code = --> <!-- = Java2Html Converter 5.0 [2006-03-04] by Markus Gebhard markus@jave.de = --> <!-- = Further information: http://www.java2html.de = --> <div align="left" class="java"> <table border="0" cellpadding="3" cellspacing="0" bgcolor="#ffffff"> <tr> <!-- start source code --> <td nowrap="nowrap" valign="top" align="left"> <code> <font color="#ffffff">&nbsp;&nbsp;&nbsp;&nbsp;</font><font color="#000000">Analyzer&nbsp;analyzer&nbsp;=&nbsp;</font><font color="#7f0055"><b>new&nbsp;</b></font><font color="#000000">StandardAnalyzer</font><font color="#000000">(</font><font color="#000000">Version.LUCENE_CURRENT</font><font color="#000000">)</font><font color="#000000">;</font><br /> <font color="#ffffff"></font><br /> <font color="#ffffff">&nbsp;&nbsp;&nbsp;&nbsp;</font><font color="#3f7f5f">//&nbsp;Store&nbsp;the&nbsp;index&nbsp;in&nbsp;memory:</font><br /> <font color="#ffffff">&nbsp;&nbsp;&nbsp;&nbsp;</font><font color="#000000">Directory&nbsp;directory&nbsp;=&nbsp;</font><font color="#7f0055"><b>new&nbsp;</b></font><font color="#000000">RAMDirectory</font><font color="#000000">()</font><font color="#000000">;</font><br /> <font color="#ffffff">&nbsp;&nbsp;&nbsp;&nbsp;</font><font color="#3f7f5f">//&nbsp;To&nbsp;store&nbsp;an&nbsp;index&nbsp;on&nbsp;disk,&nbsp;use&nbsp;this&nbsp;instead:</font><br /> <font color="#ffffff">&nbsp;&nbsp;&nbsp;&nbsp;</font><font color="#3f7f5f">//Directory&nbsp;directory&nbsp;=&nbsp;FSDirectory.open(&#34;/tmp/testindex&#34;);</font><br /> <font color="#ffffff">&nbsp;&nbsp;&nbsp;&nbsp;</font><font color="#000000">IndexWriter&nbsp;iwriter&nbsp;=&nbsp;</font><font color="#7f0055"><b>new&nbsp;</b></font><font color="#000000">IndexWriter</font><font color="#000000">(</font><font color="#000000">directory,&nbsp;analyzer,&nbsp;true,</font><br /> <font color="#ffffff">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</font><font color="#7f0055"><b>new&nbsp;</b></font><font color="#000000">IndexWriter.MaxFieldLength</font><font color="#000000">(</font><font color="#990000">25000</font><font color="#000000">))</font><font color="#000000">;</font><br /> <font color="#ffffff">&nbsp;&nbsp;&nbsp;&nbsp;</font><font color="#000000">Document&nbsp;doc&nbsp;=&nbsp;</font><font color="#7f0055"><b>new&nbsp;</b></font><font color="#000000">Document</font><font color="#000000">()</font><font color="#000000">;</font><br /> <font color="#ffffff">&nbsp;&nbsp;&nbsp;&nbsp;</font><font color="#000000">String&nbsp;text&nbsp;=&nbsp;</font><font color="#2a00ff">&#34;This&nbsp;is&nbsp;the&nbsp;text&nbsp;to&nbsp;be&nbsp;indexed.&#34;</font><font color="#000000">;</font><br /> <font color="#ffffff">&nbsp;&nbsp;&nbsp;&nbsp;</font><font color="#000000">doc.add</font><font color="#000000">(</font><font color="#7f0055"><b>new&nbsp;</b></font><font color="#000000">Field</font><font color="#000000">(</font><font color="#2a00ff">&#34;fieldname&#34;</font><font color="#000000">,&nbsp;text,&nbsp;Field.Store.YES,</font><br /> <font color="#ffffff">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</font><font color="#000000">Field.Index.ANALYZED</font><font color="#000000">))</font><font color="#000000">;</font><br /> <font color="#ffffff">&nbsp;&nbsp;&nbsp;&nbsp;</font><font color="#000000">iwriter.addDocument</font><font color="#000000">(</font><font color="#000000">doc</font><font color="#000000">)</font><font color="#000000">;</font><br /> <font color="#ffffff">&nbsp;&nbsp;&nbsp;&nbsp;</font><font color="#000000">iwriter.close</font><font color="#000000">()</font><font color="#000000">;</font><br /> <font color="#ffffff">&nbsp;&nbsp;&nbsp;&nbsp;</font><br /> <font color="#ffffff">&nbsp;&nbsp;&nbsp;&nbsp;</font><font color="#3f7f5f">//&nbsp;Now&nbsp;search&nbsp;the&nbsp;index:</font><br /> <font color="#ffffff">&nbsp;&nbsp;&nbsp;&nbsp;</font><font color="#000000">IndexSearcher&nbsp;isearcher&nbsp;=&nbsp;</font><font color="#7f0055"><b>new&nbsp;</b></font><font color="#000000">IndexSearcher</font><font color="#000000">(</font><font color="#000000">directory,&nbsp;</font><font color="#7f0055"><b>true</b></font><font color="#000000">)</font><font color="#000000">;&nbsp;</font><font color="#3f7f5f">//&nbsp;read-only=true</font><br /> <font color="#ffffff">&nbsp;&nbsp;&nbsp;&nbsp;</font><font color="#3f7f5f">//&nbsp;Parse&nbsp;a&nbsp;simple&nbsp;query&nbsp;that&nbsp;searches&nbsp;for&nbsp;&#34;text&#34;:</font><br /> <font color="#ffffff">&nbsp;&nbsp;&nbsp;&nbsp;</font><font color="#000000">QueryParser&nbsp;parser&nbsp;=&nbsp;</font><font color="#7f0055"><b>new&nbsp;</b></font><font color="#000000">QueryParser</font><font color="#000000">(</font><font color="#2a00ff">&#34;fieldname&#34;</font><font color="#000000">,&nbsp;analyzer</font><font color="#000000">)</font><font color="#000000">;</font><br /> <font color="#ffffff">&nbsp;&nbsp;&nbsp;&nbsp;</font><font color="#000000">Query&nbsp;query&nbsp;=&nbsp;parser.parse</font><font color="#000000">(</font><font color="#2a00ff">&#34;text&#34;</font><font color="#000000">)</font><font color="#000000">;</font><br /> <font color="#ffffff">&nbsp;&nbsp;&nbsp;&nbsp;</font><font color="#000000">ScoreDoc</font><font color="#000000">[]&nbsp;</font><font color="#000000">hits&nbsp;=&nbsp;isearcher.search</font><font color="#000000">(</font><font color="#000000">query,&nbsp;null,&nbsp;</font><font color="#990000">1000</font><font color="#000000">)</font><font color="#000000">.scoreDocs;</font><br /> <font color="#ffffff">&nbsp;&nbsp;&nbsp;&nbsp;</font><font color="#000000">assertEquals</font><font color="#000000">(</font><font color="#990000">1</font><font color="#000000">,&nbsp;hits.length</font><font color="#000000">)</font><font color="#000000">;</font><br /> <font color="#ffffff">&nbsp;&nbsp;&nbsp;&nbsp;</font><font color="#3f7f5f">//&nbsp;Iterate&nbsp;through&nbsp;the&nbsp;results:</font><br /> <font color="#ffffff">&nbsp;&nbsp;&nbsp;&nbsp;</font><font color="#7f0055"><b>for&nbsp;</b></font><font color="#000000">(</font><font color="#7f0055"><b>int&nbsp;</b></font><font color="#000000">i&nbsp;=&nbsp;</font><font color="#990000">0</font><font color="#000000">;&nbsp;i&nbsp;&lt;&nbsp;hits.length;&nbsp;i++</font><font color="#000000">)&nbsp;{</font><br /> <font color="#ffffff">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</font><font color="#000000">Document&nbsp;hitDoc&nbsp;=&nbsp;isearcher.doc</font><font color="#000000">(</font><font color="#000000">hits</font><font color="#000000">[</font><font color="#000000">i</font><font color="#000000">]</font><font color="#000000">.doc</font><font color="#000000">)</font><font color="#000000">;</font><br /> <font color="#ffffff">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</font><font color="#000000">assertEquals</font><font color="#000000">(</font><font color="#2a00ff">&#34;This&nbsp;is&nbsp;the&nbsp;text&nbsp;to&nbsp;be&nbsp;indexed.&#34;</font><font color="#000000">,&nbsp;hitDoc.get</font><font color="#000000">(</font><font color="#2a00ff">&#34;fieldname&#34;</font><font color="#000000">))</font><font color="#000000">;</font><br /> <font color="#ffffff">&nbsp;&nbsp;&nbsp;&nbsp;</font><font color="#000000">}</font><br /> <font color="#ffffff">&nbsp;&nbsp;&nbsp;&nbsp;</font><font color="#000000">isearcher.close</font><font color="#000000">()</font><font color="#000000">;</font><br /> <font color="#ffffff">&nbsp;&nbsp;&nbsp;&nbsp;</font><font color="#000000">directory.close</font><font color="#000000">()</font><font color="#000000">;</font></code> </td> <!-- end source code --> </tr> </table> </div> <!-- = END of automatically generated HTML code = --> <!-- ======================================================== --> <p>The Lucene API is divided into several packages:</p> <ul> <li> <b><a href="org/apache/lucene/analysis/package-summary.html">org.apache.lucene.analysis</a></b> defines an abstract <a href="org/apache/lucene/analysis/Analyzer.html">Analyzer</a> API for converting text from a <a href="http://java.sun.com/products/jdk/1.2/docs/api/java/io/Reader.html">java.io.Reader</a> into a <a href="org/apache/lucene/analysis/TokenStream.html">TokenStream</a>, an enumeration of token <a href="org/apache/lucene/util/Attribute.html">Attribute</a>s.&nbsp; A TokenStream can be composed by applying <a href="org/apache/lucene/analysis/TokenFilter.html">TokenFilter</a>s to the output of a <a href="org/apache/lucene/analysis/Tokenizer.html">Tokenizer</a>.&nbsp; Tokenizers and TokenFilters are strung together and applied with an <a href="org/apache/lucene/analysis/Analyzer.html">Analyzer</a>.&nbsp; A handful of Analyzer implementations are provided, including <a href="org/apache/lucene/analysis/StopAnalyzer.html">StopAnalyzer</a> and the grammar-based <a href="org/apache/lucene/analysis/standard/StandardAnalyzer.html">StandardAnalyzer</a>.</li> <li> <b><a href="org/apache/lucene/document/package-summary.html">org.apache.lucene.document</a></b> provides a simple <a href="org/apache/lucene/document/Document.html">Document</a> class.&nbsp; A Document is simply a set of named <a href="org/apache/lucene/document/Field.html">Field</a>s, whose values may be strings or instances of <a href="http://java.sun.com/products/jdk/1.2/docs/api/java/io/Reader.html">java.io.Reader</a>.</li> <li> <b><a href="org/apache/lucene/index/package-summary.html">org.apache.lucene.index</a></b> provides two primary classes: <a href="org/apache/lucene/index/IndexWriter.html">IndexWriter</a>, which creates and adds documents to indices; and <a href="org/apache/lucene/index/IndexReader.html">IndexReader</a>, which accesses the data in the index.</li> <li> <b><a href="org/apache/lucene/search/package-summary.html">org.apache.lucene.search</a></b> provides data structures to represent queries (ie <a href="org/apache/lucene/search/TermQuery.html">TermQuery</a> for individual words, <a href="org/apache/lucene/search/PhraseQuery.html">PhraseQuery</a> for phrases, and <a href="org/apache/lucene/search/BooleanQuery.html">BooleanQuery</a> for boolean combinations of queries) and the abstract <a href="org/apache/lucene/search/Searcher.html">Searcher</a> which turns queries into <a href="org/apache/lucene/search/TopDocs.html">TopDocs</a>. <a href="org/apache/lucene/search/IndexSearcher.html">IndexSearcher</a> implements search over a single IndexReader.</li> <li> <b><a href="org/apache/lucene/queryParser/package-summary.html">org.apache.lucene.queryParser</a></b> uses <a href="http://javacc.dev.java.net">JavaCC</a> to implement a <a href="org/apache/lucene/queryParser/QueryParser.html">QueryParser</a>.</li> <li> <b><a href="org/apache/lucene/store/package-summary.html">org.apache.lucene.store</a></b> defines an abstract class for storing persistent data, the <a href="org/apache/lucene/store/Directory.html">Directory</a>, which is a collection of named files written by an <a href="org/apache/lucene/store/IndexOutput.html">IndexOutput</a> and read by an <a href="org/apache/lucene/store/IndexInput.html">IndexInput</a>.&nbsp; Multiple implementations are provided, including <a href="org/apache/lucene/store/FSDirectory.html">FSDirectory</a>, which uses a file system directory to store files, and <a href="org/apache/lucene/store/RAMDirectory.html">RAMDirectory</a> which implements files as memory-resident data structures.</li> <li> <b><a href="org/apache/lucene/util/package-summary.html">org.apache.lucene.util</a></b> contains a few handy data structures and util classes, ie <a href="org/apache/lucene/util/BitVector.html">BitVector</a> and <a href="org/apache/lucene/util/PriorityQueue.html">PriorityQueue</a>.</li> </ul> To use Lucene, an application should: <ol> <li> Create <a href="org/apache/lucene/document/Document.html">Document</a>s by adding <a href="org/apache/lucene/document/Field.html">Field</a>s;</li> <li> Create an <a href="org/apache/lucene/index/IndexWriter.html">IndexWriter</a> and add documents to it with <a href="org/apache/lucene/index/IndexWriter.html#addDocument(org.apache.lucene.document.Document)">addDocument()</a>;</li> <li> Call <a href="org/apache/lucene/queryParser/QueryParser.html#parse(java.lang.String)">QueryParser.parse()</a> to build a query from a string; and</li> <li> Create an <a href="org/apache/lucene/search/IndexSearcher.html">IndexSearcher</a> and pass the query to its <a href="org/apache/lucene/search/Searcher.html#search(org.apache.lucene.search.Query)">search()</a> method.</li> </ol> Some simple examples of code which does this are: <ul> <li> &nbsp;<a href="http://svn.apache.org/repos/asf/lucene/java/trunk/src/demo/org/apache/lucene/demo/FileDocument.java">FileDocument.java</a> contains code to create a Document for a file.</li> <li> &nbsp;<a href="http://svn.apache.org/repos/asf/lucene/java/trunk/src/demo/org/apache/lucene/demo/IndexFiles.java">IndexFiles.java</a> creates an index for all the files contained in a directory.</li> <li> &nbsp;<a href="http://svn.apache.org/repos/asf/lucene/java/trunk/src/demo/org/apache/lucene/demo/DeleteFiles.java">DeleteFiles.java</a> deletes some of these files from the index.</li> <li> &nbsp;<a href="http://svn.apache.org/repos/asf/lucene/java/trunk/src/demo/org/apache/lucene/demo/SearchFiles.java">SearchFiles.java</a> prompts for queries and searches an index.</li> </ul> To demonstrate these, try something like: <blockquote><tt>> <b>java -cp lucene.jar:lucene-demo.jar org.apache.lucene.demo.IndexFiles rec.food.recipes/soups</b></tt> <br><tt>adding rec.food.recipes/soups/abalone-chowder</tt> <br><tt>&nbsp; </tt>[ ... ] <p><tt>> <b>java -cp lucene.jar:lucene-demo.jar org.apache.lucene.demo.SearchFiles</b></tt> <br><tt>Query: <b>chowder</b></tt> <br><tt>Searching for: chowder</tt> <br><tt>34 total matching documents</tt> <br><tt>1. rec.food.recipes/soups/spam-chowder</tt> <br><tt>&nbsp; </tt>[ ... thirty-four documents contain the word "chowder" ... ] <p><tt>Query: <b>"clam chowder" AND Manhattan</b></tt> <br><tt>Searching for: +"clam chowder" +manhattan</tt> <br><tt>2 total matching documents</tt> <br><tt>1. rec.food.recipes/soups/clam-chowder</tt> <br><tt>&nbsp; </tt>[ ... two documents contain the phrase "clam chowder" and the word "manhattan" ... ] <br>&nbsp;&nbsp;&nbsp; [ Note: "+" and "-" are canonical, but "AND", "OR" and "NOT" may be used. ]</blockquote> The <a href="http://svn.apache.org/repos/asf/lucene/java/trunk/src/demo/org/apache/lucene/demo/IndexHTML.java">IndexHTML</a> demo is more sophisticated.&nbsp; It incrementally maintains an index of HTML files, adding new files as they appear, deleting old files as they disappear and re-indexing files as they change. <blockquote><tt>> <b>java -cp lucene.jar:lucene-demo.jar org.apache.lucene.demo.IndexHTML -create java/jdk1.1.6/docs/relnotes</b></tt> <br><tt>adding java/jdk1.1.6/docs/relnotes/SMICopyright.html</tt> <br><tt>&nbsp; </tt>[ ... create an index containing all the relnotes ] <p><tt>> <b>rm java/jdk1.1.6/docs/relnotes/smicopyright.html</b></tt> <p><tt>> <b>java -cp lucene.jar:lucene-demo.jar org.apache.lucene.demo.IndexHTML java/jdk1.1.6/docs/relnotes</b></tt> <br><tt>deleting java/jdk1.1.6/docs/relnotes/SMICopyright.html</tt></blockquote> </body> </html>
zzh-simple-hr
Zlucene/src/java/overview.html
HTML
art
17,353
package org.apache.lucene.demo.html; /** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import java.util.HashMap; import java.util.Map; public class Entities { static final Map<String,String> decoder = new HashMap<String,String>(300); static final String[] encoder = new String[0x100]; static final String decode(String entity) { if (entity.charAt(entity.length()-1) == ';') // remove trailing semicolon entity = entity.substring(0, entity.length()-1); if (entity.charAt(1) == '#') { int start = 2; int radix = 10; if (entity.charAt(2) == 'X' || entity.charAt(2) == 'x') { start++; radix = 16; } Character c = new Character((char)Integer.parseInt(entity.substring(start), radix)); return c.toString(); } else { String s = (String)decoder.get(entity); if (s != null) return s; else return ""; } } public static final String encode(String s) { int length = s.length(); StringBuffer buffer = new StringBuffer(length * 2); for (int i = 0; i < length; i++) { char c = s.charAt(i); int j = (int)c; if (j < 0x100 && encoder[j] != null) { buffer.append(encoder[j]); // have a named encoding buffer.append(';'); } else if (j < 0x80) { buffer.append(c); // use ASCII value } else { buffer.append("&#"); // use numeric encoding buffer.append((int)c); buffer.append(';'); } } return buffer.toString(); } static final void add(String entity, int value) { decoder.put(entity, (new Character((char)value)).toString()); if (value < 0x100) encoder[value] = entity; } static { add("&nbsp", 160); add("&iexcl", 161); add("&cent", 162); add("&pound", 163); add("&curren", 164); add("&yen", 165); add("&brvbar", 166); add("&sect", 167); add("&uml", 168); add("&copy", 169); add("&ordf", 170); add("&laquo", 171); add("&not", 172); add("&shy", 173); add("&reg", 174); add("&macr", 175); add("&deg", 176); add("&plusmn", 177); add("&sup2", 178); add("&sup3", 179); add("&acute", 180); add("&micro", 181); add("&para", 182); add("&middot", 183); add("&cedil", 184); add("&sup1", 185); add("&ordm", 186); add("&raquo", 187); add("&frac14", 188); add("&frac12", 189); add("&frac34", 190); add("&iquest", 191); add("&Agrave", 192); add("&Aacute", 193); add("&Acirc", 194); add("&Atilde", 195); add("&Auml", 196); add("&Aring", 197); add("&AElig", 198); add("&Ccedil", 199); add("&Egrave", 200); add("&Eacute", 201); add("&Ecirc", 202); add("&Euml", 203); add("&Igrave", 204); add("&Iacute", 205); add("&Icirc", 206); add("&Iuml", 207); add("&ETH", 208); add("&Ntilde", 209); add("&Ograve", 210); add("&Oacute", 211); add("&Ocirc", 212); add("&Otilde", 213); add("&Ouml", 214); add("&times", 215); add("&Oslash", 216); add("&Ugrave", 217); add("&Uacute", 218); add("&Ucirc", 219); add("&Uuml", 220); add("&Yacute", 221); add("&THORN", 222); add("&szlig", 223); add("&agrave", 224); add("&aacute", 225); add("&acirc", 226); add("&atilde", 227); add("&auml", 228); add("&aring", 229); add("&aelig", 230); add("&ccedil", 231); add("&egrave", 232); add("&eacute", 233); add("&ecirc", 234); add("&euml", 235); add("&igrave", 236); add("&iacute", 237); add("&icirc", 238); add("&iuml", 239); add("&eth", 240); add("&ntilde", 241); add("&ograve", 242); add("&oacute", 243); add("&ocirc", 244); add("&otilde", 245); add("&ouml", 246); add("&divide", 247); add("&oslash", 248); add("&ugrave", 249); add("&uacute", 250); add("&ucirc", 251); add("&uuml", 252); add("&yacute", 253); add("&thorn", 254); add("&yuml", 255); add("&fnof", 402); add("&Alpha", 913); add("&Beta", 914); add("&Gamma", 915); add("&Delta", 916); add("&Epsilon",917); add("&Zeta", 918); add("&Eta", 919); add("&Theta", 920); add("&Iota", 921); add("&Kappa", 922); add("&Lambda", 923); add("&Mu", 924); add("&Nu", 925); add("&Xi", 926); add("&Omicron",927); add("&Pi", 928); add("&Rho", 929); add("&Sigma", 931); add("&Tau", 932); add("&Upsilon",933); add("&Phi", 934); add("&Chi", 935); add("&Psi", 936); add("&Omega", 937); add("&alpha", 945); add("&beta", 946); add("&gamma", 947); add("&delta", 948); add("&epsilon",949); add("&zeta", 950); add("&eta", 951); add("&theta", 952); add("&iota", 953); add("&kappa", 954); add("&lambda", 955); add("&mu", 956); add("&nu", 957); add("&xi", 958); add("&omicron",959); add("&pi", 960); add("&rho", 961); add("&sigmaf", 962); add("&sigma", 963); add("&tau", 964); add("&upsilon",965); add("&phi", 966); add("&chi", 967); add("&psi", 968); add("&omega", 969); add("&thetasym",977); add("&upsih", 978); add("&piv", 982); add("&bull", 8226); add("&hellip", 8230); add("&prime", 8242); add("&Prime", 8243); add("&oline", 8254); add("&frasl", 8260); add("&weierp", 8472); add("&image", 8465); add("&real", 8476); add("&trade", 8482); add("&alefsym",8501); add("&larr", 8592); add("&uarr", 8593); add("&rarr", 8594); add("&darr", 8595); add("&harr", 8596); add("&crarr", 8629); add("&lArr", 8656); add("&uArr", 8657); add("&rArr", 8658); add("&dArr", 8659); add("&hArr", 8660); add("&forall", 8704); add("&part", 8706); add("&exist", 8707); add("&empty", 8709); add("&nabla", 8711); add("&isin", 8712); add("&notin", 8713); add("&ni", 8715); add("&prod", 8719); add("&sum", 8721); add("&minus", 8722); add("&lowast", 8727); add("&radic", 8730); add("&prop", 8733); add("&infin", 8734); add("&ang", 8736); add("&and", 8743); add("&or", 8744); add("&cap", 8745); add("&cup", 8746); add("&int", 8747); add("&there4", 8756); add("&sim", 8764); add("&cong", 8773); add("&asymp", 8776); add("&ne", 8800); add("&equiv", 8801); add("&le", 8804); add("&ge", 8805); add("&sub", 8834); add("&sup", 8835); add("&nsub", 8836); add("&sube", 8838); add("&supe", 8839); add("&oplus", 8853); add("&otimes", 8855); add("&perp", 8869); add("&sdot", 8901); add("&lceil", 8968); add("&rceil", 8969); add("&lfloor", 8970); add("&rfloor", 8971); add("&lang", 9001); add("&rang", 9002); add("&loz", 9674); add("&spades", 9824); add("&clubs", 9827); add("&hearts", 9829); add("&diams", 9830); add("&quot", 34); add("&amp", 38); add("&lt", 60); add("&gt", 62); add("&OElig", 338); add("&oelig", 339); add("&Scaron", 352); add("&scaron", 353); add("&Yuml", 376); add("&circ", 710); add("&tilde", 732); add("&ensp", 8194); add("&emsp", 8195); add("&thinsp", 8201); add("&zwnj", 8204); add("&zwj", 8205); add("&lrm", 8206); add("&rlm", 8207); add("&ndash", 8211); add("&mdash", 8212); add("&lsquo", 8216); add("&rsquo", 8217); add("&sbquo", 8218); add("&ldquo", 8220); add("&rdquo", 8221); add("&bdquo", 8222); add("&dagger", 8224); add("&Dagger", 8225); add("&permil", 8240); add("&lsaquo", 8249); add("&rsaquo", 8250); add("&euro", 8364); } }
zzh-simple-hr
Zlucene/src/demo/org/apache/lucene/demo/html/Entities.java
Java
art
8,801
package org.apache.lucene.demo.html; /** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import java.io.*; class ParserThread extends Thread { HTMLParser parser; ParserThread(HTMLParser p) { parser = p; } @Override public void run() { // convert pipeOut to pipeIn try { try { // parse document to pipeOut parser.HTMLDocument(); } catch (ParseException e) { System.out.println("Parse Aborted: " + e.getMessage()); } catch (TokenMgrError e) { System.out.println("Parse Aborted: " + e.getMessage()); } finally { parser.pipeOut.close(); synchronized (parser) { parser.summary.setLength(HTMLParser.SUMMARY_LENGTH); parser.titleComplete = true; parser.notifyAll(); } } } catch (IOException e) { e.printStackTrace(); } } }
zzh-simple-hr
Zlucene/src/demo/org/apache/lucene/demo/html/ParserThread.java
Java
art
1,610
package org.apache.lucene.demo.html; /** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import java.util.Collections; import java.util.HashSet; import java.util.Set; public final class Tags { /** * contains all tags for which whitespaces have to be inserted for proper tokenization */ public static final Set<String> WS_ELEMS = Collections.synchronizedSet(new HashSet<String>()); static{ WS_ELEMS.add("<hr"); WS_ELEMS.add("<hr/"); // note that "<hr />" does not need to be listed explicitly WS_ELEMS.add("<br"); WS_ELEMS.add("<br/"); WS_ELEMS.add("<p"); WS_ELEMS.add("</p"); WS_ELEMS.add("<div"); WS_ELEMS.add("</div"); WS_ELEMS.add("<td"); WS_ELEMS.add("</td"); WS_ELEMS.add("<li"); WS_ELEMS.add("</li"); WS_ELEMS.add("<q"); WS_ELEMS.add("</q"); WS_ELEMS.add("<blockquote"); WS_ELEMS.add("</blockquote"); WS_ELEMS.add("<dt"); WS_ELEMS.add("</dt"); WS_ELEMS.add("<h1"); WS_ELEMS.add("</h1"); WS_ELEMS.add("<h2"); WS_ELEMS.add("</h2"); WS_ELEMS.add("<h3"); WS_ELEMS.add("</h3"); WS_ELEMS.add("<h4"); WS_ELEMS.add("</h4"); WS_ELEMS.add("<h5"); WS_ELEMS.add("</h5"); WS_ELEMS.add("<h6"); WS_ELEMS.add("</h6"); } }
zzh-simple-hr
Zlucene/src/demo/org/apache/lucene/demo/html/Tags.java
Java
art
2,004
package org.apache.lucene.demo.html; /** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import java.io.*; class Test { public static void main(String[] argv) throws IOException, InterruptedException { if ("-dir".equals(argv[0])) { String[] files = new File(argv[1]).list(); java.util.Arrays.sort(files); for (int i = 0; i < files.length; i++) { System.err.println(files[i]); File file = new File(argv[1], files[i]); parse(file); } } else parse(new File(argv[0])); } public static void parse(File file) throws IOException, InterruptedException { FileInputStream fis = null; try { fis = new FileInputStream(file); HTMLParser parser = new HTMLParser(fis); System.out.println("Title: " + Entities.encode(parser.getTitle())); System.out.println("Summary: " + Entities.encode(parser.getSummary())); System.out.println("Content:"); LineNumberReader reader = new LineNumberReader(parser.getReader()); for (String l = reader.readLine(); l != null; l = reader.readLine()) System.out.println(l); } finally { if (fis != null) fis.close(); } } }
zzh-simple-hr
Zlucene/src/demo/org/apache/lucene/demo/html/Test.java
Java
art
1,910
package org.apache.lucene.demo; /** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import org.apache.lucene.analysis.standard.StandardAnalyzer; import org.apache.lucene.document.Document; import org.apache.lucene.index.IndexReader; import org.apache.lucene.index.IndexWriter; import org.apache.lucene.index.Term; import org.apache.lucene.index.TermEnum; import org.apache.lucene.store.FSDirectory; import org.apache.lucene.util.Version; import java.io.File; import java.util.Date; import java.util.Arrays; /** Indexer for HTML files. */ public class IndexHTML { private IndexHTML() {} private static boolean deleting = false; // true during deletion pass private static IndexReader reader; // existing index private static IndexWriter writer; // new index being built private static TermEnum uidIter; // document id iterator /** Indexer for HTML files.*/ public static void main(String[] argv) { try { File index = new File("index"); boolean create = false; File root = null; String usage = "IndexHTML [-create] [-index <index>] <root_directory>"; if (argv.length == 0) { System.err.println("Usage: " + usage); return; } for (int i = 0; i < argv.length; i++) { if (argv[i].equals("-index")) { // parse -index option index = new File(argv[++i]); } else if (argv[i].equals("-create")) { // parse -create option create = true; } else if (i != argv.length-1) { System.err.println("Usage: " + usage); return; } else root = new File(argv[i]); } if(root == null) { System.err.println("Specify directory to index"); System.err.println("Usage: " + usage); return; } Date start = new Date(); if (!create) { // delete stale docs deleting = true; indexDocs(root, index, create); } writer = new IndexWriter(FSDirectory.open(index), new StandardAnalyzer(Version.LUCENE_CURRENT), create, new IndexWriter.MaxFieldLength(1000000)); indexDocs(root, index, create); // add new docs System.out.println("Optimizing index..."); writer.optimize(); writer.close(); Date end = new Date(); System.out.print(end.getTime() - start.getTime()); System.out.println(" total milliseconds"); } catch (Exception e) { e.printStackTrace(); } } /* Walk directory hierarchy in uid order, while keeping uid iterator from /* existing index in sync. Mismatches indicate one of: (a) old documents to /* be deleted; (b) unchanged documents, to be left alone; or (c) new /* documents, to be indexed. */ private static void indexDocs(File file, File index, boolean create) throws Exception { if (!create) { // incrementally update reader = IndexReader.open(FSDirectory.open(index), false); // open existing index uidIter = reader.terms(new Term("uid", "")); // init uid iterator indexDocs(file); if (deleting) { // delete rest of stale docs while (uidIter.term() != null && uidIter.term().field() == "uid") { System.out.println("deleting " + HTMLDocument.uid2url(uidIter.term().text())); reader.deleteDocuments(uidIter.term()); uidIter.next(); } deleting = false; } uidIter.close(); // close uid iterator reader.close(); // close existing index } else // don't have exisiting indexDocs(file); } private static void indexDocs(File file) throws Exception { if (file.isDirectory()) { // if a directory String[] files = file.list(); // list its files Arrays.sort(files); // sort the files for (int i = 0; i < files.length; i++) // recursively index them indexDocs(new File(file, files[i])); } else if (file.getPath().endsWith(".html") || // index .html files file.getPath().endsWith(".htm") || // index .htm files file.getPath().endsWith(".txt")) { // index .txt files if (uidIter != null) { String uid = HTMLDocument.uid(file); // construct uid for doc while (uidIter.term() != null && uidIter.term().field() == "uid" && uidIter.term().text().compareTo(uid) < 0) { if (deleting) { // delete stale docs System.out.println("deleting " + HTMLDocument.uid2url(uidIter.term().text())); reader.deleteDocuments(uidIter.term()); } uidIter.next(); } if (uidIter.term() != null && uidIter.term().field() == "uid" && uidIter.term().text().compareTo(uid) == 0) { uidIter.next(); // keep matching docs } else if (!deleting) { // add new docs Document doc = HTMLDocument.Document(file); System.out.println("adding " + doc.get("path")); writer.addDocument(doc); } } else { // creating a new index Document doc = HTMLDocument.Document(file); System.out.println("adding " + doc.get("path")); writer.addDocument(doc); // add docs unconditionally } } } }
zzh-simple-hr
Zlucene/src/demo/org/apache/lucene/demo/IndexHTML.java
Java
art
6,016
package org.apache.lucene.demo; /** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import java.io.File; import java.io.FileReader; import org.apache.lucene.document.DateTools; import org.apache.lucene.document.Document; import org.apache.lucene.document.Field; /** A utility for making Lucene Documents from a File. */ public class FileDocument { /** Makes a document for a File. <p> The document has three fields: <ul> <li><code>path</code>--containing the pathname of the file, as a stored, untokenized field; <li><code>modified</code>--containing the last modified date of the file as a field as created by <a href="lucene.document.DateTools.html">DateTools</a>; and <li><code>contents</code>--containing the full contents of the file, as a Reader field; */ public static Document Document(File f) throws java.io.FileNotFoundException { // make a new, empty document Document doc = new Document(); // Add the path of the file as a field named "path". Use a field that is // indexed (i.e. searchable), but don't tokenize the field into words. doc.add(new Field("path", f.getPath(), Field.Store.YES, Field.Index.NOT_ANALYZED)); // Add the last modified date of the file a field named "modified". Use // a field that is indexed (i.e. searchable), but don't tokenize the field // into words. doc.add(new Field("modified", DateTools.timeToString(f.lastModified(), DateTools.Resolution.MINUTE), Field.Store.YES, Field.Index.NOT_ANALYZED)); // Add the contents of the file to a field named "contents". Specify a Reader, // so that the text of the file is tokenized and indexed, but not stored. // Note that FileReader expects the file to be in the system's default encoding. // If that's not the case searching for special characters will fail. doc.add(new Field("contents", new FileReader(f))); // return the document return doc; } private FileDocument() {} }
zzh-simple-hr
Zlucene/src/demo/org/apache/lucene/demo/FileDocument.java
Java
art
2,771
package org.apache.lucene.demo; /** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.Date; import org.apache.lucene.analysis.Analyzer; import org.apache.lucene.analysis.standard.StandardAnalyzer; import org.apache.lucene.document.Document; import org.apache.lucene.index.FilterIndexReader; import org.apache.lucene.index.IndexReader; import org.apache.lucene.queryParser.QueryParser; import org.apache.lucene.search.Collector; import org.apache.lucene.search.IndexSearcher; import org.apache.lucene.search.Query; import org.apache.lucene.search.ScoreDoc; import org.apache.lucene.search.Scorer; import org.apache.lucene.search.Searcher; import org.apache.lucene.search.TopScoreDocCollector; import org.apache.lucene.store.FSDirectory; import org.apache.lucene.util.Version; /** Simple command-line based search demo. */ public class SearchFiles { /** Use the norms from one field for all fields. Norms are read into memory, * using a byte of memory per document per searched field. This can cause * search of large collections with a large number of fields to run out of * memory. If all of the fields contain only a single token, then the norms * are all identical, then single norm vector may be shared. */ private static class OneNormsReader extends FilterIndexReader { private String field; public OneNormsReader(IndexReader in, String field) { super(in); this.field = field; } @Override public byte[] norms(String field) throws IOException { return in.norms(this.field); } } private SearchFiles() {} /** Simple command-line based search demo. */ public static void main(String[] args) throws Exception { String usage = "Usage:\tjava org.apache.lucene.demo.SearchFiles [-index dir] [-field f] [-repeat n] [-queries file] [-raw] [-norms field] [-paging hitsPerPage]"; usage += "\n\tSpecify 'false' for hitsPerPage to use streaming instead of paging search."; if (args.length > 0 && ("-h".equals(args[0]) || "-help".equals(args[0]))) { System.out.println(usage); System.exit(0); } String index = "index"; String field = "contents"; String queries = null; int repeat = 0; boolean raw = false; String normsField = null; boolean paging = true; int hitsPerPage = 10; for (int i = 0; i < args.length; i++) { if ("-index".equals(args[i])) { index = args[i+1]; i++; } else if ("-field".equals(args[i])) { field = args[i+1]; i++; } else if ("-queries".equals(args[i])) { queries = args[i+1]; i++; } else if ("-repeat".equals(args[i])) { repeat = Integer.parseInt(args[i+1]); i++; } else if ("-raw".equals(args[i])) { raw = true; } else if ("-norms".equals(args[i])) { normsField = args[i+1]; i++; } else if ("-paging".equals(args[i])) { if (args[i+1].equals("false")) { paging = false; } else { hitsPerPage = Integer.parseInt(args[i+1]); if (hitsPerPage == 0) { paging = false; } } i++; } } IndexReader reader = IndexReader.open(FSDirectory.open(new File(index)), true); // only searching, so read-only=true if (normsField != null) reader = new OneNormsReader(reader, normsField); Searcher searcher = new IndexSearcher(reader); Analyzer analyzer = new StandardAnalyzer(Version.LUCENE_CURRENT); BufferedReader in = null; if (queries != null) { in = new BufferedReader(new FileReader(queries)); } else { in = new BufferedReader(new InputStreamReader(System.in, "UTF-8")); } QueryParser parser = new QueryParser(Version.LUCENE_CURRENT, field, analyzer); while (true) { if (queries == null) // prompt the user System.out.println("Enter query: "); String line = in.readLine(); if (line == null || line.length() == -1) break; line = line.trim(); if (line.length() == 0) break; Query query = parser.parse(line); System.out.println("Searching for: " + query.toString(field)); if (repeat > 0) { // repeat & time as benchmark Date start = new Date(); for (int i = 0; i < repeat; i++) { searcher.search(query, null, 100); } Date end = new Date(); System.out.println("Time: "+(end.getTime()-start.getTime())+"ms"); } if (paging) { doPagingSearch(in, searcher, query, hitsPerPage, raw, queries == null); } else { doStreamingSearch(searcher, query); } } reader.close(); } /** * This method uses a custom HitCollector implementation which simply prints out * the docId and score of every matching document. * * This simulates the streaming search use case, where all hits are supposed to * be processed, regardless of their relevance. */ public static void doStreamingSearch(final Searcher searcher, Query query) throws IOException { Collector streamingHitCollector = new Collector() { private Scorer scorer; private int docBase; // simply print docId and score of every matching document @Override public void collect(int doc) throws IOException { System.out.println("doc=" + doc + docBase + " score=" + scorer.score()); } @Override public boolean acceptsDocsOutOfOrder() { return true; } @Override public void setNextReader(IndexReader reader, int docBase) throws IOException { this.docBase = docBase; } @Override public void setScorer(Scorer scorer) throws IOException { this.scorer = scorer; } }; searcher.search(query, streamingHitCollector); } /** * This demonstrates a typical paging search scenario, where the search engine presents * pages of size n to the user. The user can then go to the next page if interested in * the next hits. * * When the query is executed for the first time, then only enough results are collected * to fill 5 result pages. If the user wants to page beyond this limit, then the query * is executed another time and all hits are collected. * */ public static void doPagingSearch(BufferedReader in, Searcher searcher, Query query, int hitsPerPage, boolean raw, boolean interactive) throws IOException { // Collect enough docs to show 5 pages TopScoreDocCollector collector = TopScoreDocCollector.create( 5 * hitsPerPage, false); searcher.search(query, collector); ScoreDoc[] hits = collector.topDocs().scoreDocs; int numTotalHits = collector.getTotalHits(); System.out.println(numTotalHits + " total matching documents"); int start = 0; int end = Math.min(numTotalHits, hitsPerPage); while (true) { if (end > hits.length) { System.out.println("Only results 1 - " + hits.length +" of " + numTotalHits + " total matching documents collected."); System.out.println("Collect more (y/n) ?"); String line = in.readLine(); if (line.length() == 0 || line.charAt(0) == 'n') { break; } collector = TopScoreDocCollector.create(numTotalHits, false); searcher.search(query, collector); hits = collector.topDocs().scoreDocs; } end = Math.min(hits.length, start + hitsPerPage); for (int i = start; i < end; i++) { if (raw) { // output raw format System.out.println("doc="+hits[i].doc+" score="+hits[i].score); continue; } Document doc = searcher.doc(hits[i].doc); String path = doc.get("path"); if (path != null) { System.out.println((i+1) + ". " + path); String title = doc.get("title"); if (title != null) { System.out.println(" Title: " + doc.get("title")); } } else { System.out.println((i+1) + ". " + "No path for this document"); } } if (!interactive) { break; } if (numTotalHits >= end) { boolean quit = false; while (true) { System.out.print("Press "); if (start - hitsPerPage >= 0) { System.out.print("(p)revious page, "); } if (start + hitsPerPage < numTotalHits) { System.out.print("(n)ext page, "); } System.out.println("(q)uit or enter number to jump to a page."); String line = in.readLine(); if (line.length() == 0 || line.charAt(0)=='q') { quit = true; break; } if (line.charAt(0) == 'p') { start = Math.max(0, start - hitsPerPage); break; } else if (line.charAt(0) == 'n') { if (start + hitsPerPage < numTotalHits) { start+=hitsPerPage; } break; } else { int page = Integer.parseInt(line); if ((page - 1) * hitsPerPage < numTotalHits) { start = (page - 1) * hitsPerPage; break; } else { System.out.println("No such page"); } } } if (quit) break; end = Math.min(numTotalHits, start + hitsPerPage); } } } }
zzh-simple-hr
Zlucene/src/demo/org/apache/lucene/demo/SearchFiles.java
Java
art
10,500
package org.apache.lucene.demo; /** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import java.io.File; import org.apache.lucene.store.Directory; import org.apache.lucene.store.FSDirectory; import org.apache.lucene.index.IndexReader; import org.apache.lucene.index.Term; //import org.apache.lucene.index.Term; /** Deletes documents from an index that do not contain a term. */ public class DeleteFiles { private DeleteFiles() {} // singleton /** Deletes documents from an index that do not contain a term. */ public static void main(String[] args) { String usage = "java org.apache.lucene.demo.DeleteFiles <unique_term>"; if (args.length == 0) { System.err.println("Usage: " + usage); System.exit(1); } try { Directory directory = FSDirectory.open(new File("index")); IndexReader reader = IndexReader.open(directory, false); // we don't want read-only because we are about to delete Term term = new Term("path", args[0]); int deleted = reader.deleteDocuments(term); System.out.println("deleted " + deleted + " documents containing " + term); // one can also delete documents by their internal id: /* for (int i = 0; i < reader.maxDoc(); i++) { System.out.println("Deleting document with id " + i); reader.delete(i); }*/ reader.close(); directory.close(); } catch (Exception e) { System.out.println(" caught a " + e.getClass() + "\n with message: " + e.getMessage()); } } }
zzh-simple-hr
Zlucene/src/demo/org/apache/lucene/demo/DeleteFiles.java
Java
art
2,304
package org.apache.lucene.demo; /** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import java.io.*; import org.apache.lucene.document.*; import org.apache.lucene.demo.html.HTMLParser; /** A utility for making Lucene Documents for HTML documents. */ public class HTMLDocument { static char dirSep = System.getProperty("file.separator").charAt(0); public static String uid(File f) { // Append path and date into a string in such a way that lexicographic // sorting gives the same results as a walk of the file hierarchy. Thus // null (\u0000) is used both to separate directory components and to // separate the path from the date. return f.getPath().replace(dirSep, '\u0000') + "\u0000" + DateTools.timeToString(f.lastModified(), DateTools.Resolution.SECOND); } public static String uid2url(String uid) { String url = uid.replace('\u0000', '/'); // replace nulls with slashes return url.substring(0, url.lastIndexOf('/')); // remove date from end } public static Document Document(File f) throws IOException, InterruptedException { // make a new, empty document Document doc = new Document(); // Add the url as a field named "path". Use a field that is // indexed (i.e. searchable), but don't tokenize the field into words. doc.add(new Field("path", f.getPath().replace(dirSep, '/'), Field.Store.YES, Field.Index.NOT_ANALYZED)); // Add the last modified date of the file a field named "modified". // Use a field that is indexed (i.e. searchable), but don't tokenize // the field into words. doc.add(new Field("modified", DateTools.timeToString(f.lastModified(), DateTools.Resolution.MINUTE), Field.Store.YES, Field.Index.NOT_ANALYZED)); // Add the uid as a field, so that index can be incrementally maintained. // This field is not stored with document, it is indexed, but it is not // tokenized prior to indexing. doc.add(new Field("uid", uid(f), Field.Store.NO, Field.Index.NOT_ANALYZED)); FileInputStream fis = new FileInputStream(f); HTMLParser parser = new HTMLParser(fis); // Add the tag-stripped contents as a Reader-valued Text field so it will // get tokenized and indexed. doc.add(new Field("contents", parser.getReader())); // Add the summary as a field that is stored and returned with // hit documents for display. doc.add(new Field("summary", parser.getSummary(), Field.Store.YES, Field.Index.NO)); // Add the title as a field that it can be searched and that is stored. doc.add(new Field("title", parser.getTitle(), Field.Store.YES, Field.Index.ANALYZED)); // return the document return doc; } private HTMLDocument() {} }
zzh-simple-hr
Zlucene/src/demo/org/apache/lucene/demo/HTMLDocument.java
Java
art
3,511
package org.apache.lucene.analysis; /** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import java.util.Set; import java.io.StringReader; import java.io.IOException; import org.apache.lucene.analysis.tokenattributes.*; import org.apache.lucene.util.Attribute; import org.apache.lucene.util.AttributeImpl; import org.apache.lucene.util.LuceneTestCase; /** * Base class for all Lucene unit tests that use TokenStreams. */ public abstract class BaseTokenStreamTestCase extends LuceneTestCase { public BaseTokenStreamTestCase() { super(); } public BaseTokenStreamTestCase(String name) { super(name); } // some helpers to test Analyzers and TokenStreams: public static interface CheckClearAttributesAttribute extends Attribute { boolean getAndResetClearCalled(); } public static final class CheckClearAttributesAttributeImpl extends AttributeImpl implements CheckClearAttributesAttribute { private boolean clearCalled = false; public boolean getAndResetClearCalled() { try { return clearCalled; } finally { clearCalled = false; } } @Override public void clear() { clearCalled = true; } @Override public boolean equals(Object other) { return ( other instanceof CheckClearAttributesAttributeImpl && ((CheckClearAttributesAttributeImpl) other).clearCalled == this.clearCalled ); } @Override public int hashCode() { return 76137213 ^ Boolean.valueOf(clearCalled).hashCode(); } @Override public void copyTo(AttributeImpl target) { ((CheckClearAttributesAttributeImpl) target).clear(); } } public static void assertTokenStreamContents(TokenStream ts, String[] output, int startOffsets[], int endOffsets[], String types[], int posIncrements[], Integer finalOffset) throws IOException { assertNotNull(output); CheckClearAttributesAttribute checkClearAtt = ts.addAttribute(CheckClearAttributesAttribute.class); assertTrue("has no TermAttribute", ts.hasAttribute(TermAttribute.class)); TermAttribute termAtt = ts.getAttribute(TermAttribute.class); OffsetAttribute offsetAtt = null; if (startOffsets != null || endOffsets != null || finalOffset != null) { assertTrue("has no OffsetAttribute", ts.hasAttribute(OffsetAttribute.class)); offsetAtt = ts.getAttribute(OffsetAttribute.class); } TypeAttribute typeAtt = null; if (types != null) { assertTrue("has no TypeAttribute", ts.hasAttribute(TypeAttribute.class)); typeAtt = ts.getAttribute(TypeAttribute.class); } PositionIncrementAttribute posIncrAtt = null; if (posIncrements != null) { assertTrue("has no PositionIncrementAttribute", ts.hasAttribute(PositionIncrementAttribute.class)); posIncrAtt = ts.getAttribute(PositionIncrementAttribute.class); } ts.reset(); for (int i = 0; i < output.length; i++) { // extra safety to enforce, that the state is not preserved and also assign bogus values ts.clearAttributes(); termAtt.setTermBuffer("bogusTerm"); if (offsetAtt != null) offsetAtt.setOffset(14584724,24683243); if (typeAtt != null) typeAtt.setType("bogusType"); if (posIncrAtt != null) posIncrAtt.setPositionIncrement(45987657); checkClearAtt.getAndResetClearCalled(); // reset it, because we called clearAttribute() before assertTrue("token "+i+" does not exist", ts.incrementToken()); assertTrue("clearAttributes() was not called correctly in TokenStream chain", checkClearAtt.getAndResetClearCalled()); assertEquals("term "+i, output[i], termAtt.term()); if (startOffsets != null) assertEquals("startOffset "+i, startOffsets[i], offsetAtt.startOffset()); if (endOffsets != null) assertEquals("endOffset "+i, endOffsets[i], offsetAtt.endOffset()); if (types != null) assertEquals("type "+i, types[i], typeAtt.type()); if (posIncrements != null) assertEquals("posIncrement "+i, posIncrements[i], posIncrAtt.getPositionIncrement()); } assertFalse("end of stream", ts.incrementToken()); ts.end(); if (finalOffset != null) assertEquals("finalOffset ", finalOffset.intValue(), offsetAtt.endOffset()); ts.close(); } public static void assertTokenStreamContents(TokenStream ts, String[] output, int startOffsets[], int endOffsets[], String types[], int posIncrements[]) throws IOException { assertTokenStreamContents(ts, output, startOffsets, endOffsets, types, posIncrements, null); } public static void assertTokenStreamContents(TokenStream ts, String[] output) throws IOException { assertTokenStreamContents(ts, output, null, null, null, null, null); } public static void assertTokenStreamContents(TokenStream ts, String[] output, String[] types) throws IOException { assertTokenStreamContents(ts, output, null, null, types, null, null); } public static void assertTokenStreamContents(TokenStream ts, String[] output, int[] posIncrements) throws IOException { assertTokenStreamContents(ts, output, null, null, null, posIncrements, null); } public static void assertTokenStreamContents(TokenStream ts, String[] output, int startOffsets[], int endOffsets[]) throws IOException { assertTokenStreamContents(ts, output, startOffsets, endOffsets, null, null, null); } public static void assertTokenStreamContents(TokenStream ts, String[] output, int startOffsets[], int endOffsets[], Integer finalOffset) throws IOException { assertTokenStreamContents(ts, output, startOffsets, endOffsets, null, null, finalOffset); } public static void assertTokenStreamContents(TokenStream ts, String[] output, int startOffsets[], int endOffsets[], int[] posIncrements) throws IOException { assertTokenStreamContents(ts, output, startOffsets, endOffsets, null, posIncrements, null); } public static void assertTokenStreamContents(TokenStream ts, String[] output, int startOffsets[], int endOffsets[], int[] posIncrements, Integer finalOffset) throws IOException { assertTokenStreamContents(ts, output, startOffsets, endOffsets, null, posIncrements, finalOffset); } public static void assertAnalyzesTo(Analyzer a, String input, String[] output, int startOffsets[], int endOffsets[], String types[], int posIncrements[]) throws IOException { assertTokenStreamContents(a.tokenStream("dummy", new StringReader(input)), output, startOffsets, endOffsets, types, posIncrements, input.length()); } public static void assertAnalyzesTo(Analyzer a, String input, String[] output) throws IOException { assertAnalyzesTo(a, input, output, null, null, null, null); } public static void assertAnalyzesTo(Analyzer a, String input, String[] output, String[] types) throws IOException { assertAnalyzesTo(a, input, output, null, null, types, null); } public static void assertAnalyzesTo(Analyzer a, String input, String[] output, int[] posIncrements) throws IOException { assertAnalyzesTo(a, input, output, null, null, null, posIncrements); } public static void assertAnalyzesTo(Analyzer a, String input, String[] output, int startOffsets[], int endOffsets[]) throws IOException { assertAnalyzesTo(a, input, output, startOffsets, endOffsets, null, null); } public static void assertAnalyzesTo(Analyzer a, String input, String[] output, int startOffsets[], int endOffsets[], int[] posIncrements) throws IOException { assertAnalyzesTo(a, input, output, startOffsets, endOffsets, null, posIncrements); } public static void assertAnalyzesToReuse(Analyzer a, String input, String[] output, int startOffsets[], int endOffsets[], String types[], int posIncrements[]) throws IOException { assertTokenStreamContents(a.reusableTokenStream("dummy", new StringReader(input)), output, startOffsets, endOffsets, types, posIncrements, input.length()); } public static void assertAnalyzesToReuse(Analyzer a, String input, String[] output) throws IOException { assertAnalyzesToReuse(a, input, output, null, null, null, null); } public static void assertAnalyzesToReuse(Analyzer a, String input, String[] output, String[] types) throws IOException { assertAnalyzesToReuse(a, input, output, null, null, types, null); } public static void assertAnalyzesToReuse(Analyzer a, String input, String[] output, int[] posIncrements) throws IOException { assertAnalyzesToReuse(a, input, output, null, null, null, posIncrements); } public static void assertAnalyzesToReuse(Analyzer a, String input, String[] output, int startOffsets[], int endOffsets[]) throws IOException { assertAnalyzesToReuse(a, input, output, startOffsets, endOffsets, null, null); } public static void assertAnalyzesToReuse(Analyzer a, String input, String[] output, int startOffsets[], int endOffsets[], int[] posIncrements) throws IOException { assertAnalyzesToReuse(a, input, output, startOffsets, endOffsets, null, posIncrements); } // simple utility method for testing stemmers public static void checkOneTerm(Analyzer a, final String input, final String expected) throws IOException { assertAnalyzesTo(a, input, new String[]{expected}); } public static void checkOneTermReuse(Analyzer a, final String input, final String expected) throws IOException { assertAnalyzesToReuse(a, input, new String[]{expected}); } }
zzh-simple-hr
Zlucene/src/test/org/apache/lucene/analysis/BaseTokenStreamTestCase.java
Java
art
10,241
package org.apache.lucene.messages; /** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with this * work for additional information regarding copyright ownership. The ASF * licenses this file to You under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ public class MessagesTestBundle extends NLS { private static final String BUNDLE_NAME = MessagesTestBundle.class.getName(); private MessagesTestBundle() { // should never be instantiated } static { // register all string ids with NLS class and initialize static string // values NLS.initializeMessages(BUNDLE_NAME, MessagesTestBundle.class); } // static string must match the strings in the property files. public static String Q0001E_INVALID_SYNTAX; public static String Q0004E_INVALID_SYNTAX_ESCAPE_UNICODE_TRUNCATION; // this message is missing from the properties file public static String Q0005E_MESSAGE_NOT_IN_BUNDLE; }
zzh-simple-hr
Zlucene/src/test/org/apache/lucene/messages/MessagesTestBundle.java
Java
art
1,504
package org.apache.lucene.store; /** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import java.io.IOException; /** * Used by MockRAMDirectory to create an output stream that * will throw an IOException on fake disk full, track max * disk space actually used, and maybe throw random * IOExceptions. */ public class MockRAMOutputStream extends RAMOutputStream { private MockRAMDirectory dir; private boolean first=true; private final String name; byte[] singleByte = new byte[1]; /** Construct an empty output buffer. */ public MockRAMOutputStream(MockRAMDirectory dir, RAMFile f, String name) { super(f); this.dir = dir; this.name = name; } @Override public void close() throws IOException { super.close(); // Now compute actual disk usage & track the maxUsedSize // in the MockRAMDirectory: long size = dir.getRecomputedActualSizeInBytes(); if (size > dir.maxUsedSize) { dir.maxUsedSize = size; } } @Override public void flush() throws IOException { dir.maybeThrowDeterministicException(); super.flush(); } @Override public void writeByte(byte b) throws IOException { singleByte[0] = b; writeBytes(singleByte, 0, 1); } @Override public void writeBytes(byte[] b, int offset, int len) throws IOException { long freeSpace = dir.maxSize - dir.sizeInBytes(); long realUsage = 0; // If MockRAMDir crashed since we were opened, then // don't write anything: if (dir.crashed) throw new IOException("MockRAMDirectory was crashed; cannot write to " + name); // Enforce disk full: if (dir.maxSize != 0 && freeSpace <= len) { // Compute the real disk free. This will greatly slow // down our test but makes it more accurate: realUsage = dir.getRecomputedActualSizeInBytes(); freeSpace = dir.maxSize - realUsage; } if (dir.maxSize != 0 && freeSpace <= len) { if (freeSpace > 0 && freeSpace < len) { realUsage += freeSpace; super.writeBytes(b, offset, (int) freeSpace); } if (realUsage > dir.maxUsedSize) { dir.maxUsedSize = realUsage; } throw new IOException("fake disk full at " + dir.getRecomputedActualSizeInBytes() + " bytes when writing " + name); } else { super.writeBytes(b, offset, len); } dir.maybeThrowDeterministicException(); if (first) { // Maybe throw random exception; only do this on first // write to a new file: first = false; dir.maybeThrowIOException(); } } }
zzh-simple-hr
Zlucene/src/test/org/apache/lucene/store/MockRAMOutputStream.java
Java
art
3,312
package org.apache.lucene.store; import java.io.IOException; /** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * Used by MockRAMDirectory to create an input stream that * keeps track of when it's been closed. */ public class MockRAMInputStream extends RAMInputStream { private MockRAMDirectory dir; private String name; private boolean isClone; /** Construct an empty output buffer. * @throws IOException */ public MockRAMInputStream(MockRAMDirectory dir, String name, RAMFile f) throws IOException { super(f); this.name = name; this.dir = dir; } @Override public void close() { super.close(); // Pending resolution on LUCENE-686 we may want to // remove the conditional check so we also track that // all clones get closed: if (!isClone) { synchronized(dir) { Integer v = (Integer) dir.openFiles.get(name); // Could be null when MockRAMDirectory.crash() was called if (v != null) { if (v.intValue() == 1) { dir.openFiles.remove(name); } else { v = Integer.valueOf(v.intValue()-1); dir.openFiles.put(name, v); } } } } } @Override public Object clone() { MockRAMInputStream clone = (MockRAMInputStream) super.clone(); clone.isClone = true; // Pending resolution on LUCENE-686 we may want to // uncomment this code so that we also track that all // clones get closed: /* synchronized(dir.openFiles) { if (dir.openFiles.containsKey(name)) { Integer v = (Integer) dir.openFiles.get(name); v = Integer.valueOf(v.intValue()+1); dir.openFiles.put(name, v); } else { throw new RuntimeException("BUG: cloned file was not open?"); } } */ return clone; } }
zzh-simple-hr
Zlucene/src/test/org/apache/lucene/store/MockRAMInputStream.java
Java
art
2,577
package org.apache.lucene.store; /** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import java.io.IOException; import org.apache.lucene.store.SimpleFSDirectory.SimpleFSIndexInput; /** This class provides access to package-level features defined in the * store package. It is used for testing only. */ public class _TestHelper { /** Returns true if the instance of the provided input stream is actually * an SimpleFSIndexInput. */ public static boolean isSimpleFSIndexInput(IndexInput is) { return is instanceof SimpleFSIndexInput; } /** Returns true if the provided input stream is an SimpleFSIndexInput and * is a clone, that is it does not own its underlying file descriptor. */ public static boolean isSimpleFSIndexInputClone(IndexInput is) { if (isSimpleFSIndexInput(is)) { return ((SimpleFSIndexInput) is).isClone; } else { return false; } } /** Given an instance of SimpleFSDirectory.SimpleFSIndexInput, this method returns * true if the underlying file descriptor is valid, and false otherwise. * This can be used to determine if the OS file has been closed. * The descriptor becomes invalid when the non-clone instance of the * SimpleFSIndexInput that owns this descriptor is closed. However, the * descriptor may possibly become invalid in other ways as well. */ public static boolean isSimpleFSIndexInputOpen(IndexInput is) throws IOException { if (isSimpleFSIndexInput(is)) { SimpleFSIndexInput fis = (SimpleFSIndexInput) is; return fis.isFDValid(); } else { return false; } } }
zzh-simple-hr
Zlucene/src/test/org/apache/lucene/store/_TestHelper.java
Java
art
2,471
package org.apache.lucene.store; /** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import java.io.IOException; import java.io.FileNotFoundException; import java.util.Iterator; import java.util.Random; import java.util.Map; import java.util.HashMap; import java.util.HashSet; import java.util.Set; import java.util.ArrayList; import java.util.Arrays; /** * This is a subclass of RAMDirectory that adds methods * intended to be used only by unit tests. */ public class MockRAMDirectory extends RAMDirectory { long maxSize; // Max actual bytes used. This is set by MockRAMOutputStream: long maxUsedSize; double randomIOExceptionRate; Random randomState; boolean noDeleteOpenFile = true; boolean preventDoubleWrite = true; private Set<String> unSyncedFiles; private Set<String> createdFiles; volatile boolean crashed; // NOTE: we cannot initialize the Map here due to the // order in which our constructor actually does this // member initialization vs when it calls super. It seems // like super is called, then our members are initialized: Map<String,Integer> openFiles; private synchronized void init() { if (openFiles == null) openFiles = new HashMap<String,Integer>(); if (createdFiles == null) createdFiles = new HashSet(); if (unSyncedFiles == null) unSyncedFiles = new HashSet(); } public MockRAMDirectory() { super(); init(); } public MockRAMDirectory(Directory dir) throws IOException { super(dir); init(); } /** If set to true, we throw an IOException if the same * file is opened by createOutput, ever. */ public void setPreventDoubleWrite(boolean value) { preventDoubleWrite = value; } @Override public synchronized void sync(String name) throws IOException { maybeThrowDeterministicException(); if (crashed) throw new IOException("cannot sync after crash"); if (unSyncedFiles.contains(name)) unSyncedFiles.remove(name); } /** Simulates a crash of OS or machine by overwriting * unsynced files. */ public synchronized void crash() throws IOException { crashed = true; openFiles = new HashMap(); Iterator<String> it = unSyncedFiles.iterator(); unSyncedFiles = new HashSet(); int count = 0; while(it.hasNext()) { String name = it.next(); RAMFile file = fileMap.get(name); if (count % 3 == 0) { deleteFile(name, true); } else if (count % 3 == 1) { // Zero out file entirely final int numBuffers = file.numBuffers(); for(int i=0;i<numBuffers;i++) { byte[] buffer = file.getBuffer(i); Arrays.fill(buffer, (byte) 0); } } else if (count % 3 == 2) { // Truncate the file: file.setLength(file.getLength()/2); } count++; } } public synchronized void clearCrash() throws IOException { crashed = false; } public void setMaxSizeInBytes(long maxSize) { this.maxSize = maxSize; } public long getMaxSizeInBytes() { return this.maxSize; } /** * Returns the peek actual storage used (bytes) in this * directory. */ public long getMaxUsedSizeInBytes() { return this.maxUsedSize; } public void resetMaxUsedSizeInBytes() { this.maxUsedSize = getRecomputedActualSizeInBytes(); } /** * Emulate windows whereby deleting an open file is not * allowed (raise IOException). */ public void setNoDeleteOpenFile(boolean value) { this.noDeleteOpenFile = value; } public boolean getNoDeleteOpenFile() { return noDeleteOpenFile; } /** * If 0.0, no exceptions will be thrown. Else this should * be a double 0.0 - 1.0. We will randomly throw an * IOException on the first write to an OutputStream based * on this probability. */ public void setRandomIOExceptionRate(double rate, long seed) { randomIOExceptionRate = rate; // seed so we have deterministic behaviour: randomState = new Random(seed); } public double getRandomIOExceptionRate() { return randomIOExceptionRate; } void maybeThrowIOException() throws IOException { if (randomIOExceptionRate > 0.0) { int number = Math.abs(randomState.nextInt() % 1000); if (number < randomIOExceptionRate*1000) { throw new IOException("a random IOException"); } } } @Override public synchronized void deleteFile(String name) throws IOException { deleteFile(name, false); } private synchronized void deleteFile(String name, boolean forced) throws IOException { maybeThrowDeterministicException(); if (crashed && !forced) throw new IOException("cannot delete after crash"); if (unSyncedFiles.contains(name)) unSyncedFiles.remove(name); if (!forced) { if (noDeleteOpenFile && openFiles.containsKey(name)) { throw new IOException("MockRAMDirectory: file \"" + name + "\" is still open: cannot delete"); } } super.deleteFile(name); } @Override public synchronized IndexOutput createOutput(String name) throws IOException { if (crashed) throw new IOException("cannot createOutput after crash"); init(); if (preventDoubleWrite && createdFiles.contains(name) && !name.equals("segments.gen")) throw new IOException("file \"" + name + "\" was already written to"); if (noDeleteOpenFile && openFiles.containsKey(name)) throw new IOException("MockRAMDirectory: file \"" + name + "\" is still open: cannot overwrite"); RAMFile file = new RAMFile(this); if (crashed) throw new IOException("cannot createOutput after crash"); unSyncedFiles.add(name); createdFiles.add(name); RAMFile existing = fileMap.get(name); // Enforce write once: if (existing!=null && !name.equals("segments.gen") && preventDoubleWrite) throw new IOException("file " + name + " already exists"); else { if (existing!=null) { sizeInBytes -= existing.sizeInBytes; existing.directory = null; } fileMap.put(name, file); } return new MockRAMOutputStream(this, file, name); } @Override public synchronized IndexInput openInput(String name) throws IOException { RAMFile file = fileMap.get(name); if (file == null) throw new FileNotFoundException(name); else { if (openFiles.containsKey(name)) { Integer v = (Integer) openFiles.get(name); v = Integer.valueOf(v.intValue()+1); openFiles.put(name, v); } else { openFiles.put(name, Integer.valueOf(1)); } } return new MockRAMInputStream(this, name, file); } /** Provided for testing purposes. Use sizeInBytes() instead. */ public synchronized final long getRecomputedSizeInBytes() { long size = 0; for(final RAMFile file: fileMap.values()) { size += file.getSizeInBytes(); } return size; } /** Like getRecomputedSizeInBytes(), but, uses actual file * lengths rather than buffer allocations (which are * quantized up to nearest * RAMOutputStream.BUFFER_SIZE (now 1024) bytes. */ public final synchronized long getRecomputedActualSizeInBytes() { long size = 0; for (final RAMFile file : fileMap.values()) size += file.length; return size; } @Override public synchronized void close() { if (openFiles == null) { openFiles = new HashMap(); } if (noDeleteOpenFile && openFiles.size() > 0) { // RuntimeException instead of IOException because // super() does not throw IOException currently: throw new RuntimeException("MockRAMDirectory: cannot close: there are still open files: " + openFiles); } } /** * Objects that represent fail-able conditions. Objects of a derived * class are created and registered with the mock directory. After * register, each object will be invoked once for each first write * of a file, giving the object a chance to throw an IOException. */ public static class Failure { /** * eval is called on the first write of every new file. */ public void eval(MockRAMDirectory dir) throws IOException { } /** * reset should set the state of the failure to its default * (freshly constructed) state. Reset is convenient for tests * that want to create one failure object and then reuse it in * multiple cases. This, combined with the fact that Failure * subclasses are often anonymous classes makes reset difficult to * do otherwise. * * A typical example of use is * Failure failure = new Failure() { ... }; * ... * mock.failOn(failure.reset()) */ public Failure reset() { return this; } protected boolean doFail; public void setDoFail() { doFail = true; } public void clearDoFail() { doFail = false; } } ArrayList failures; /** * add a Failure object to the list of objects to be evaluated * at every potential failure point */ synchronized public void failOn(Failure fail) { if (failures == null) { failures = new ArrayList(); } failures.add(fail); } /** * Iterate through the failures list, giving each object a * chance to throw an IOE */ synchronized void maybeThrowDeterministicException() throws IOException { if (failures != null) { for(int i = 0; i < failures.size(); i++) { ((Failure)failures.get(i)).eval(this); } } } }
zzh-simple-hr
Zlucene/src/test/org/apache/lucene/store/MockRAMDirectory.java
Java
art
10,210
package org.apache.lucene.index; /** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import org.apache.lucene.store.BufferedIndexInput; public class MockIndexInput extends BufferedIndexInput { private byte[] buffer; private int pointer = 0; private long length; public MockIndexInput(byte[] bytes) { buffer = bytes; length = bytes.length; } @Override protected void readInternal(byte[] dest, int destOffset, int len) { int remainder = len; int start = pointer; while (remainder != 0) { // int bufferNumber = start / buffer.length; int bufferOffset = start % buffer.length; int bytesInBuffer = buffer.length - bufferOffset; int bytesToCopy = bytesInBuffer >= remainder ? remainder : bytesInBuffer; System.arraycopy(buffer, bufferOffset, dest, destOffset, bytesToCopy); destOffset += bytesToCopy; start += bytesToCopy; remainder -= bytesToCopy; } pointer += len; } @Override public void close() { // ignore } @Override protected void seekInternal(long pos) { pointer = (int) pos; } @Override public long length() { return length; } }
zzh-simple-hr
Zlucene/src/test/org/apache/lucene/index/MockIndexInput.java
Java
art
2,017
package org.apache.lucene.index; /** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import java.io.IOException; import java.io.UnsupportedEncodingException; import java.util.HashMap; import java.util.Map; import org.apache.lucene.analysis.Analyzer; import org.apache.lucene.analysis.WhitespaceAnalyzer; import org.apache.lucene.document.Document; import org.apache.lucene.document.Field; import org.apache.lucene.document.Fieldable; import org.apache.lucene.search.Similarity; import org.apache.lucene.store.Directory; class DocHelper { public static final String FIELD_1_TEXT = "field one text"; public static final String TEXT_FIELD_1_KEY = "textField1"; public static Field textField1 = new Field(TEXT_FIELD_1_KEY, FIELD_1_TEXT, Field.Store.YES, Field.Index.ANALYZED, Field.TermVector.NO); public static final String FIELD_2_TEXT = "field field field two text"; //Fields will be lexicographically sorted. So, the order is: field, text, two public static final int [] FIELD_2_FREQS = {3, 1, 1}; public static final String TEXT_FIELD_2_KEY = "textField2"; public static Field textField2 = new Field(TEXT_FIELD_2_KEY, FIELD_2_TEXT, Field.Store.YES, Field.Index.ANALYZED, Field.TermVector.WITH_POSITIONS_OFFSETS); public static final String FIELD_3_TEXT = "aaaNoNorms aaaNoNorms bbbNoNorms"; public static final String TEXT_FIELD_3_KEY = "textField3"; public static Field textField3 = new Field(TEXT_FIELD_3_KEY, FIELD_3_TEXT, Field.Store.YES, Field.Index.ANALYZED); static { textField3.setOmitNorms(true); } public static final String KEYWORD_TEXT = "Keyword"; public static final String KEYWORD_FIELD_KEY = "keyField"; public static Field keyField = new Field(KEYWORD_FIELD_KEY, KEYWORD_TEXT, Field.Store.YES, Field.Index.NOT_ANALYZED); public static final String NO_NORMS_TEXT = "omitNormsText"; public static final String NO_NORMS_KEY = "omitNorms"; public static Field noNormsField = new Field(NO_NORMS_KEY, NO_NORMS_TEXT, Field.Store.YES, Field.Index.NOT_ANALYZED_NO_NORMS); public static final String NO_TF_TEXT = "analyzed with no tf and positions"; public static final String NO_TF_KEY = "omitTermFreqAndPositions"; public static Field noTFField = new Field(NO_TF_KEY, NO_TF_TEXT, Field.Store.YES, Field.Index.ANALYZED); static { noTFField.setOmitTermFreqAndPositions(true); } public static final String UNINDEXED_FIELD_TEXT = "unindexed field text"; public static final String UNINDEXED_FIELD_KEY = "unIndField"; public static Field unIndField = new Field(UNINDEXED_FIELD_KEY, UNINDEXED_FIELD_TEXT, Field.Store.YES, Field.Index.NO); public static final String UNSTORED_1_FIELD_TEXT = "unstored field text"; public static final String UNSTORED_FIELD_1_KEY = "unStoredField1"; public static Field unStoredField1 = new Field(UNSTORED_FIELD_1_KEY, UNSTORED_1_FIELD_TEXT, Field.Store.NO, Field.Index.ANALYZED, Field.TermVector.NO); public static final String UNSTORED_2_FIELD_TEXT = "unstored field text"; public static final String UNSTORED_FIELD_2_KEY = "unStoredField2"; public static Field unStoredField2 = new Field(UNSTORED_FIELD_2_KEY, UNSTORED_2_FIELD_TEXT, Field.Store.NO, Field.Index.ANALYZED, Field.TermVector.YES); public static final String LAZY_FIELD_BINARY_KEY = "lazyFieldBinary"; public static byte [] LAZY_FIELD_BINARY_BYTES; public static Field lazyFieldBinary; public static final String LAZY_FIELD_KEY = "lazyField"; public static final String LAZY_FIELD_TEXT = "These are some field bytes"; public static Field lazyField = new Field(LAZY_FIELD_KEY, LAZY_FIELD_TEXT, Field.Store.YES, Field.Index.ANALYZED); public static final String LARGE_LAZY_FIELD_KEY = "largeLazyField"; public static String LARGE_LAZY_FIELD_TEXT; public static Field largeLazyField; //From Issue 509 public static final String FIELD_UTF1_TEXT = "field one \u4e00text"; public static final String TEXT_FIELD_UTF1_KEY = "textField1Utf8"; public static Field textUtfField1 = new Field(TEXT_FIELD_UTF1_KEY, FIELD_UTF1_TEXT, Field.Store.YES, Field.Index.ANALYZED, Field.TermVector.NO); public static final String FIELD_UTF2_TEXT = "field field field \u4e00two text"; //Fields will be lexicographically sorted. So, the order is: field, text, two public static final int [] FIELD_UTF2_FREQS = {3, 1, 1}; public static final String TEXT_FIELD_UTF2_KEY = "textField2Utf8"; public static Field textUtfField2 = new Field(TEXT_FIELD_UTF2_KEY, FIELD_UTF2_TEXT, Field.Store.YES, Field.Index.ANALYZED, Field.TermVector.WITH_POSITIONS_OFFSETS); public static Map nameValues = null; // ordered list of all the fields... // could use LinkedHashMap for this purpose if Java1.4 is OK public static Field[] fields = new Field[] { textField1, textField2, textField3, keyField, noNormsField, noTFField, unIndField, unStoredField1, unStoredField2, textUtfField1, textUtfField2, lazyField, lazyFieldBinary,//placeholder for binary field, since this is null. It must be second to last. largeLazyField//placeholder for large field, since this is null. It must always be last }; // Map<String fieldName, Fieldable field> public static Map all=new HashMap(); public static Map indexed=new HashMap(); public static Map stored=new HashMap(); public static Map unstored=new HashMap(); public static Map unindexed=new HashMap(); public static Map termvector=new HashMap(); public static Map notermvector=new HashMap(); public static Map lazy= new HashMap(); public static Map noNorms=new HashMap(); public static Map noTf=new HashMap(); static { //Initialize the large Lazy Field StringBuilder buffer = new StringBuilder(); for (int i = 0; i < 10000; i++) { buffer.append("Lazily loading lengths of language in lieu of laughing "); } try { LAZY_FIELD_BINARY_BYTES = "These are some binary field bytes".getBytes("UTF8"); } catch (UnsupportedEncodingException e) { } lazyFieldBinary = new Field(LAZY_FIELD_BINARY_KEY, LAZY_FIELD_BINARY_BYTES, Field.Store.YES); fields[fields.length - 2] = lazyFieldBinary; LARGE_LAZY_FIELD_TEXT = buffer.toString(); largeLazyField = new Field(LARGE_LAZY_FIELD_KEY, LARGE_LAZY_FIELD_TEXT, Field.Store.YES, Field.Index.ANALYZED); fields[fields.length - 1] = largeLazyField; for (int i=0; i<fields.length; i++) { Fieldable f = fields[i]; add(all,f); if (f.isIndexed()) add(indexed,f); else add(unindexed,f); if (f.isTermVectorStored()) add(termvector,f); if (f.isIndexed() && !f.isTermVectorStored()) add(notermvector,f); if (f.isStored()) add(stored,f); else add(unstored,f); if (f.getOmitNorms()) add(noNorms,f); if (f.getOmitTermFreqAndPositions()) add(noTf,f); if (f.isLazy()) add(lazy, f); } } private static void add(Map map, Fieldable field) { map.put(field.name(), field); } static { nameValues = new HashMap(); nameValues.put(TEXT_FIELD_1_KEY, FIELD_1_TEXT); nameValues.put(TEXT_FIELD_2_KEY, FIELD_2_TEXT); nameValues.put(TEXT_FIELD_3_KEY, FIELD_3_TEXT); nameValues.put(KEYWORD_FIELD_KEY, KEYWORD_TEXT); nameValues.put(NO_NORMS_KEY, NO_NORMS_TEXT); nameValues.put(NO_TF_KEY, NO_TF_TEXT); nameValues.put(UNINDEXED_FIELD_KEY, UNINDEXED_FIELD_TEXT); nameValues.put(UNSTORED_FIELD_1_KEY, UNSTORED_1_FIELD_TEXT); nameValues.put(UNSTORED_FIELD_2_KEY, UNSTORED_2_FIELD_TEXT); nameValues.put(LAZY_FIELD_KEY, LAZY_FIELD_TEXT); nameValues.put(LAZY_FIELD_BINARY_KEY, LAZY_FIELD_BINARY_BYTES); nameValues.put(LARGE_LAZY_FIELD_KEY, LARGE_LAZY_FIELD_TEXT); nameValues.put(TEXT_FIELD_UTF1_KEY, FIELD_UTF1_TEXT); nameValues.put(TEXT_FIELD_UTF2_KEY, FIELD_UTF2_TEXT); } /** * Adds the fields above to a document * @param doc The document to write */ public static void setupDoc(Document doc) { for (int i=0; i<fields.length; i++) { doc.add(fields[i]); } } /** * Writes the document to the directory using a segment * named "test"; returns the SegmentInfo describing the new * segment * @param dir * @param doc * @throws IOException */ public static SegmentInfo writeDoc(Directory dir, Document doc) throws IOException { return writeDoc(dir, new WhitespaceAnalyzer(), Similarity.getDefault(), doc); } /** * Writes the document to the directory using the analyzer * and the similarity score; returns the SegmentInfo * describing the new segment * @param dir * @param analyzer * @param similarity * @param doc * @throws IOException */ public static SegmentInfo writeDoc(Directory dir, Analyzer analyzer, Similarity similarity, Document doc) throws IOException { IndexWriter writer = new IndexWriter(dir, analyzer, IndexWriter.MaxFieldLength.LIMITED); writer.setSimilarity(similarity); //writer.setUseCompoundFile(false); writer.addDocument(doc); writer.commit(); SegmentInfo info = writer.newestSegment(); writer.close(); return info; } public static int numFields(Document doc) { return doc.getFields().size(); } }
zzh-simple-hr
Zlucene/src/test/org/apache/lucene/index/DocHelper.java
Java
art
10,048
package org.apache.lucene.search; /** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import java.util.Random; import org.apache.lucene.util.LuceneTestCase; import org.apache.lucene.analysis.SimpleAnalyzer; import org.apache.lucene.document.Document; import org.apache.lucene.document.Field; import org.apache.lucene.index.IndexWriter; import org.apache.lucene.store.RAMDirectory; public class BaseTestRangeFilter extends LuceneTestCase { public static final boolean F = false; public static final boolean T = true; protected Random rand; /** * Collation interacts badly with hyphens -- collation produces different * ordering than Unicode code-point ordering -- so two indexes are created: * one which can't have negative random integers, for testing collated * ranges, and the other which can have negative random integers, for all * other tests. */ class TestIndex { int maxR; int minR; boolean allowNegativeRandomInts; RAMDirectory index = new RAMDirectory(); TestIndex(int minR, int maxR, boolean allowNegativeRandomInts) { this.minR = minR; this.maxR = maxR; this.allowNegativeRandomInts = allowNegativeRandomInts; } } TestIndex signedIndex = new TestIndex(Integer.MAX_VALUE, Integer.MIN_VALUE, true); TestIndex unsignedIndex = new TestIndex(Integer.MAX_VALUE, 0, false); int minId = 0; int maxId = 10000; static final int intLength = Integer.toString(Integer.MAX_VALUE).length(); /** * a simple padding function that should work with any int */ public static String pad(int n) { StringBuilder b = new StringBuilder(40); String p = "0"; if (n < 0) { p = "-"; n = Integer.MAX_VALUE + n + 1; } b.append(p); String s = Integer.toString(n); for (int i = s.length(); i <= intLength; i++) { b.append("0"); } b.append(s); return b.toString(); } public BaseTestRangeFilter(String name) { super(name); rand = newRandom(); build(signedIndex); build(unsignedIndex); } public BaseTestRangeFilter() { rand = newRandom(); build(signedIndex); build(unsignedIndex); } private void build(TestIndex index) { try { /* build an index */ IndexWriter writer = new IndexWriter(index.index, new SimpleAnalyzer(), T, IndexWriter.MaxFieldLength.LIMITED); for (int d = minId; d <= maxId; d++) { Document doc = new Document(); doc.add(new Field("id",pad(d), Field.Store.YES, Field.Index.NOT_ANALYZED)); int r= index.allowNegativeRandomInts ? rand.nextInt() : rand.nextInt(Integer.MAX_VALUE); if (index.maxR < r) { index.maxR = r; } if (r < index.minR) { index.minR = r; } doc.add(new Field("rand",pad(r), Field.Store.YES, Field.Index.NOT_ANALYZED)); doc.add(new Field("body","body", Field.Store.YES, Field.Index.NOT_ANALYZED)); writer.addDocument(doc); } writer.optimize(); writer.close(); } catch (Exception e) { throw new RuntimeException("can't build index", e); } } public void testPad() { int[] tests = new int[] { -9999999, -99560, -100, -3, -1, 0, 3, 9, 10, 1000, 999999999 }; for (int i = 0; i < tests.length - 1; i++) { int a = tests[i]; int b = tests[i+1]; String aa = pad(a); String bb = pad(b); String label = a + ":" + aa + " vs " + b + ":" + bb; assertEquals("length of " + label, aa.length(), bb.length()); assertTrue("compare less than " + label, aa.compareTo(bb) < 0); } } }
zzh-simple-hr
Zlucene/src/test/org/apache/lucene/search/BaseTestRangeFilter.java
Java
art
4,884
package org.apache.lucene.search; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import junit.framework.Assert; import org.apache.lucene.analysis.WhitespaceAnalyzer; import org.apache.lucene.document.Document; import org.apache.lucene.index.IndexReader; import org.apache.lucene.index.IndexWriter; import org.apache.lucene.index.MultiReader; import org.apache.lucene.index.IndexWriter.MaxFieldLength; import org.apache.lucene.store.RAMDirectory; /** * Copyright 2005 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. */ public class QueryUtils { /** Check the types of things query objects should be able to do. */ public static void check(Query q) { checkHashEquals(q); } /** check very basic hashCode and equals */ public static void checkHashEquals(Query q) { Query q2 = (Query)q.clone(); checkEqual(q,q2); Query q3 = (Query)q.clone(); q3.setBoost(7.21792348f); checkUnequal(q,q3); // test that a class check is done so that no exception is thrown // in the implementation of equals() Query whacky = new Query() { @Override public String toString(String field) { return "My Whacky Query"; } }; whacky.setBoost(q.getBoost()); checkUnequal(q, whacky); } public static void checkEqual(Query q1, Query q2) { Assert.assertEquals(q1, q2); Assert.assertEquals(q1.hashCode(), q2.hashCode()); } public static void checkUnequal(Query q1, Query q2) { Assert.assertTrue(!q1.equals(q2)); Assert.assertTrue(!q2.equals(q1)); // possible this test can fail on a hash collision... if that // happens, please change test to use a different example. Assert.assertTrue(q1.hashCode() != q2.hashCode()); } /** deep check that explanations of a query 'score' correctly */ public static void checkExplanations (final Query q, final Searcher s) throws IOException { CheckHits.checkExplanations(q, null, s, true); } /** * Various query sanity checks on a searcher, some checks are only done for * instanceof IndexSearcher. * * @see #check(Query) * @see #checkFirstSkipTo * @see #checkSkipTo * @see #checkExplanations * @see #checkSerialization * @see #checkEqual */ public static void check(Query q1, Searcher s) { check(q1, s, true); } private static void check(Query q1, Searcher s, boolean wrap) { try { check(q1); if (s!=null) { if (s instanceof IndexSearcher) { IndexSearcher is = (IndexSearcher)s; checkFirstSkipTo(q1,is); checkSkipTo(q1,is); if (wrap) { check(q1, wrapUnderlyingReader(is, -1), false); check(q1, wrapUnderlyingReader(is, 0), false); check(q1, wrapUnderlyingReader(is, +1), false); } } if (wrap) { check(q1, wrapSearcher(s, -1), false); check(q1, wrapSearcher(s, 0), false); check(q1, wrapSearcher(s, +1), false); } checkExplanations(q1,s); checkSerialization(q1,s); Query q2 = (Query)q1.clone(); checkEqual(s.rewrite(q1), s.rewrite(q2)); } } catch (IOException e) { throw new RuntimeException(e); } } /** * Given an IndexSearcher, returns a new IndexSearcher whose IndexReader * is a MultiReader containing the Reader of the original IndexSearcher, * as well as several "empty" IndexReaders -- some of which will have * deleted documents in them. This new IndexSearcher should * behave exactly the same as the original IndexSearcher. * @param s the searcher to wrap * @param edge if negative, s will be the first sub; if 0, s will be in the middle, if positive s will be the last sub */ public static IndexSearcher wrapUnderlyingReader(final IndexSearcher s, final int edge) throws IOException { IndexReader r = s.getIndexReader(); // we can't put deleted docs before the nested reader, because // it will throw off the docIds IndexReader[] readers = new IndexReader[] { edge < 0 ? r : IndexReader.open(makeEmptyIndex(0), true), IndexReader.open(makeEmptyIndex(0), true), new MultiReader(new IndexReader[] { IndexReader.open(makeEmptyIndex(edge < 0 ? 4 : 0), true), IndexReader.open(makeEmptyIndex(0), true), 0 == edge ? r : IndexReader.open(makeEmptyIndex(0), true) }), IndexReader.open(makeEmptyIndex(0 < edge ? 0 : 7), true), IndexReader.open(makeEmptyIndex(0), true), new MultiReader(new IndexReader[] { IndexReader.open(makeEmptyIndex(0 < edge ? 0 : 5), true), IndexReader.open(makeEmptyIndex(0), true), 0 < edge ? r : IndexReader.open(makeEmptyIndex(0), true) }) }; IndexSearcher out = new IndexSearcher(new MultiReader(readers)); out.setSimilarity(s.getSimilarity()); return out; } /** * Given a Searcher, returns a new MultiSearcher wrapping the * the original Searcher, * as well as several "empty" IndexSearchers -- some of which will have * deleted documents in them. This new MultiSearcher * should behave exactly the same as the original Searcher. * @param s the Searcher to wrap * @param edge if negative, s will be the first sub; if 0, s will be in hte middle, if positive s will be the last sub */ public static MultiSearcher wrapSearcher(final Searcher s, final int edge) throws IOException { // we can't put deleted docs before the nested reader, because // it will through off the docIds Searcher[] searchers = new Searcher[] { edge < 0 ? s : new IndexSearcher(makeEmptyIndex(0), true), new MultiSearcher(new Searcher[] { new IndexSearcher(makeEmptyIndex(edge < 0 ? 65 : 0), true), new IndexSearcher(makeEmptyIndex(0), true), 0 == edge ? s : new IndexSearcher(makeEmptyIndex(0), true) }), new IndexSearcher(makeEmptyIndex(0 < edge ? 0 : 3), true), new IndexSearcher(makeEmptyIndex(0), true), new MultiSearcher(new Searcher[] { new IndexSearcher(makeEmptyIndex(0 < edge ? 0 : 5), true), new IndexSearcher(makeEmptyIndex(0), true), 0 < edge ? s : new IndexSearcher(makeEmptyIndex(0), true) }) }; MultiSearcher out = new MultiSearcher(searchers); out.setSimilarity(s.getSimilarity()); return out; } private static RAMDirectory makeEmptyIndex(final int numDeletedDocs) throws IOException { RAMDirectory d = new RAMDirectory(); IndexWriter w = new IndexWriter(d, new WhitespaceAnalyzer(), true, MaxFieldLength.LIMITED); for (int i = 0; i < numDeletedDocs; i++) { w.addDocument(new Document()); } w.commit(); w.deleteDocuments( new MatchAllDocsQuery() ); w.commit(); if (0 < numDeletedDocs) Assert.assertTrue("writer has no deletions", w.hasDeletions()); Assert.assertEquals("writer is missing some deleted docs", numDeletedDocs, w.maxDoc()); Assert.assertEquals("writer has non-deleted docs", 0, w.numDocs()); w.close(); IndexReader r = IndexReader.open(d, true); Assert.assertEquals("reader has wrong number of deleted docs", numDeletedDocs, r.numDeletedDocs()); r.close(); return d; } /** check that the query weight is serializable. * @throws IOException if serialization check fail. */ private static void checkSerialization(Query q, Searcher s) throws IOException { Weight w = q.weight(s); try { ByteArrayOutputStream bos = new ByteArrayOutputStream(); ObjectOutputStream oos = new ObjectOutputStream(bos); oos.writeObject(w); oos.close(); ObjectInputStream ois = new ObjectInputStream(new ByteArrayInputStream(bos.toByteArray())); ois.readObject(); ois.close(); //skip equals() test for now - most weights don't override equals() and we won't add this just for the tests. //TestCase.assertEquals("writeObject(w) != w. ("+w+")",w2,w); } catch (Exception e) { IOException e2 = new IOException("Serialization failed for "+w); e2.initCause(e); throw e2; } } /** alternate scorer skipTo(),skipTo(),next(),next(),skipTo(),skipTo(), etc * and ensure a hitcollector receives same docs and scores */ public static void checkSkipTo(final Query q, final IndexSearcher s) throws IOException { //System.out.println("Checking "+q); if (q.weight(s).scoresDocsOutOfOrder()) return; // in this case order of skipTo() might differ from that of next(). final int skip_op = 0; final int next_op = 1; final int orders [][] = { {next_op}, {skip_op}, {skip_op, next_op}, {next_op, skip_op}, {skip_op, skip_op, next_op, next_op}, {next_op, next_op, skip_op, skip_op}, {skip_op, skip_op, skip_op, next_op, next_op}, }; for (int k = 0; k < orders.length; k++) { final int order[] = orders[k]; // System.out.print("Order:");for (int i = 0; i < order.length; i++) // System.out.print(order[i]==skip_op ? " skip()":" next()"); // System.out.println(); final int opidx[] = { 0 }; final int lastDoc[] = {-1}; // FUTURE: ensure scorer.doc()==-1 final float maxDiff = 1e-5f; final IndexReader lastReader[] = {null}; s.search(q, new Collector() { private Scorer sc; private IndexReader reader; private Scorer scorer; @Override public void setScorer(Scorer scorer) throws IOException { this.sc = scorer; } @Override public void collect(int doc) throws IOException { float score = sc.score(); lastDoc[0] = doc; try { if (scorer == null) { Weight w = q.weight(s); scorer = w.scorer(reader, true, false); } int op = order[(opidx[0]++) % order.length]; // System.out.println(op==skip_op ? // "skip("+(sdoc[0]+1)+")":"next()"); boolean more = op == skip_op ? scorer.advance(scorer.docID() + 1) != DocIdSetIterator.NO_MORE_DOCS : scorer.nextDoc() != DocIdSetIterator.NO_MORE_DOCS; int scorerDoc = scorer.docID(); float scorerScore = scorer.score(); float scorerScore2 = scorer.score(); float scoreDiff = Math.abs(score - scorerScore); float scorerDiff = Math.abs(scorerScore2 - scorerScore); if (!more || doc != scorerDoc || scoreDiff > maxDiff || scorerDiff > maxDiff) { StringBuilder sbord = new StringBuilder(); for (int i = 0; i < order.length; i++) sbord.append(order[i] == skip_op ? " skip()" : " next()"); throw new RuntimeException("ERROR matching docs:" + "\n\t" + (doc != scorerDoc ? "--> " : "") + "doc=" + doc + ", scorerDoc=" + scorerDoc + "\n\t" + (!more ? "--> " : "") + "tscorer.more=" + more + "\n\t" + (scoreDiff > maxDiff ? "--> " : "") + "scorerScore=" + scorerScore + " scoreDiff=" + scoreDiff + " maxDiff=" + maxDiff + "\n\t" + (scorerDiff > maxDiff ? "--> " : "") + "scorerScore2=" + scorerScore2 + " scorerDiff=" + scorerDiff + "\n\thitCollector.doc=" + doc + " score=" + score + "\n\t Scorer=" + scorer + "\n\t Query=" + q + " " + q.getClass().getName() + "\n\t Searcher=" + s + "\n\t Order=" + sbord + "\n\t Op=" + (op == skip_op ? " skip()" : " next()")); } } catch (IOException e) { throw new RuntimeException(e); } } @Override public void setNextReader(IndexReader reader, int docBase) throws IOException { // confirm that skipping beyond the last doc, on the // previous reader, hits NO_MORE_DOCS if (lastReader[0] != null) { final IndexReader previousReader = lastReader[0]; Weight w = q.weight(new IndexSearcher(previousReader)); Scorer scorer = w.scorer(previousReader, true, false); if (scorer != null) { boolean more = scorer.advance(lastDoc[0] + 1) != DocIdSetIterator.NO_MORE_DOCS; Assert.assertFalse("query's last doc was "+ lastDoc[0] +" but skipTo("+(lastDoc[0]+1)+") got to "+scorer.docID(),more); } } this.reader = reader; this.scorer = null; lastDoc[0] = -1; } @Override public boolean acceptsDocsOutOfOrder() { return true; } }); if (lastReader[0] != null) { // confirm that skipping beyond the last doc, on the // previous reader, hits NO_MORE_DOCS final IndexReader previousReader = lastReader[0]; Weight w = q.weight(new IndexSearcher(previousReader)); Scorer scorer = w.scorer(previousReader, true, false); if (scorer != null) { boolean more = scorer.advance(lastDoc[0] + 1) != DocIdSetIterator.NO_MORE_DOCS; Assert.assertFalse("query's last doc was "+ lastDoc[0] +" but skipTo("+(lastDoc[0]+1)+") got to "+scorer.docID(),more); } } } } // check that first skip on just created scorers always goes to the right doc private static void checkFirstSkipTo(final Query q, final IndexSearcher s) throws IOException { //System.out.println("checkFirstSkipTo: "+q); final float maxDiff = 1e-5f; final int lastDoc[] = {-1}; final IndexReader lastReader[] = {null}; s.search(q,new Collector() { private Scorer scorer; private IndexReader reader; @Override public void setScorer(Scorer scorer) throws IOException { this.scorer = scorer; } @Override public void collect(int doc) throws IOException { //System.out.println("doc="+doc); float score = scorer.score(); try { for (int i=lastDoc[0]+1; i<=doc; i++) { Weight w = q.weight(s); Scorer scorer = w.scorer(reader, true, false); Assert.assertTrue("query collected "+doc+" but skipTo("+i+") says no more docs!",scorer.advance(i) != DocIdSetIterator.NO_MORE_DOCS); Assert.assertEquals("query collected "+doc+" but skipTo("+i+") got to "+scorer.docID(),doc,scorer.docID()); float skipToScore = scorer.score(); Assert.assertEquals("unstable skipTo("+i+") score!",skipToScore,scorer.score(),maxDiff); Assert.assertEquals("query assigned doc "+doc+" a score of <"+score+"> but skipTo("+i+") has <"+skipToScore+">!",score,skipToScore,maxDiff); } lastDoc[0] = doc; } catch (IOException e) { throw new RuntimeException(e); } } @Override public void setNextReader(IndexReader reader, int docBase) throws IOException { // confirm that skipping beyond the last doc, on the // previous reader, hits NO_MORE_DOCS if (lastReader[0] != null) { final IndexReader previousReader = lastReader[0]; Weight w = q.weight(new IndexSearcher(previousReader)); Scorer scorer = w.scorer(previousReader, true, false); if (scorer != null) { boolean more = scorer.advance(lastDoc[0] + 1) != DocIdSetIterator.NO_MORE_DOCS; Assert.assertFalse("query's last doc was "+ lastDoc[0] +" but skipTo("+(lastDoc[0]+1)+") got to "+scorer.docID(),more); } } this.reader = lastReader[0] = reader; lastDoc[0] = -1; } @Override public boolean acceptsDocsOutOfOrder() { return false; } }); if (lastReader[0] != null) { // confirm that skipping beyond the last doc, on the // previous reader, hits NO_MORE_DOCS final IndexReader previousReader = lastReader[0]; Weight w = q.weight(new IndexSearcher(previousReader)); Scorer scorer = w.scorer(previousReader, true, false); if (scorer != null) { boolean more = scorer.advance(lastDoc[0] + 1) != DocIdSetIterator.NO_MORE_DOCS; Assert.assertFalse("query's last doc was "+ lastDoc[0] +" but skipTo("+(lastDoc[0]+1)+") got to "+scorer.docID(),more); } } } }
zzh-simple-hr
Zlucene/src/test/org/apache/lucene/search/QueryUtils.java
Java
art
17,442
package org.apache.lucene.search; /** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import java.io.IOException; import junit.framework.Assert; import org.apache.lucene.index.IndexReader; /** * A unit test helper class to test when the filter is getting cached and when it is not. */ public class CachingWrapperFilterHelper extends CachingWrapperFilter { private boolean shouldHaveCache = false; /** * @param filter Filter to cache results of */ public CachingWrapperFilterHelper(Filter filter) { super(filter); } public void setShouldHaveCache(boolean shouldHaveCache) { this.shouldHaveCache = shouldHaveCache; } @Override public synchronized DocIdSet getDocIdSet(IndexReader reader) throws IOException { final int saveMissCount = missCount; DocIdSet docIdSet = super.getDocIdSet(reader); if (shouldHaveCache) { Assert.assertEquals("Cache should have data ", saveMissCount, missCount); } else { Assert.assertTrue("Cache should be null " + docIdSet, missCount > saveMissCount); } return docIdSet; } @Override public String toString() { return "CachingWrapperFilterHelper("+filter+")"; } @Override public boolean equals(Object o) { if (!(o instanceof CachingWrapperFilterHelper)) return false; return this.filter.equals((CachingWrapperFilterHelper)o); } @Override public int hashCode() { return this.filter.hashCode() ^ 0x5525aacb; } }
zzh-simple-hr
Zlucene/src/test/org/apache/lucene/search/CachingWrapperFilterHelper.java
Java
art
2,214
package org.apache.lucene.search; /** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import java.io.IOException; import java.util.Set; import java.util.TreeSet; import junit.framework.Assert; import org.apache.lucene.index.IndexReader; import org.apache.lucene.store.Directory; public class CheckHits { /** * Some explains methods calculate their values though a slightly * different order of operations from the actual scoring method ... * this allows for a small amount of variation */ public static float EXPLAIN_SCORE_TOLERANCE_DELTA = 0.00005f; /** * Tests that all documents up to maxDoc which are *not* in the * expected result set, have an explanation which indicates no match * (ie: Explanation value of 0.0f) */ public static void checkNoMatchExplanations(Query q, String defaultFieldName, Searcher searcher, int[] results) throws IOException { String d = q.toString(defaultFieldName); Set ignore = new TreeSet(); for (int i = 0; i < results.length; i++) { ignore.add(Integer.valueOf(results[i])); } int maxDoc = searcher.maxDoc(); for (int doc = 0; doc < maxDoc; doc++) { if (ignore.contains(Integer.valueOf(doc))) continue; Explanation exp = searcher.explain(q, doc); Assert.assertNotNull("Explanation of [["+d+"]] for #"+doc+" is null", exp); Assert.assertEquals("Explanation of [["+d+"]] for #"+doc+ " doesn't indicate non-match: " + exp.toString(), 0.0f, exp.getValue(), 0.0f); } } /** * Tests that a query matches the an expected set of documents using a * HitCollector. * * <p> * Note that when using the HitCollector API, documents will be collected * if they "match" regardless of what their score is. * </p> * @param query the query to test * @param searcher the searcher to test the query against * @param defaultFieldName used for displaying the query in assertion messages * @param results a list of documentIds that must match the query * @see Searcher#search(Query,HitCollector) * @see #checkHits */ public static void checkHitCollector(Query query, String defaultFieldName, Searcher searcher, int[] results) throws IOException { QueryUtils.check(query,searcher); Set correct = new TreeSet(); for (int i = 0; i < results.length; i++) { correct.add(Integer.valueOf(results[i])); } final Set actual = new TreeSet(); final Collector c = new SetCollector(actual); searcher.search(query, c); Assert.assertEquals("Simple: " + query.toString(defaultFieldName), correct, actual); for (int i = -1; i < 2; i++) { actual.clear(); QueryUtils.wrapSearcher(searcher, i).search(query, c); Assert.assertEquals("Wrap Searcher " + i + ": " + query.toString(defaultFieldName), correct, actual); } if ( ! ( searcher instanceof IndexSearcher ) ) return; for (int i = -1; i < 2; i++) { actual.clear(); QueryUtils.wrapUnderlyingReader ((IndexSearcher)searcher, i).search(query, c); Assert.assertEquals("Wrap Reader " + i + ": " + query.toString(defaultFieldName), correct, actual); } } public static class SetCollector extends Collector { final Set bag; public SetCollector(Set bag) { this.bag = bag; } private int base = 0; @Override public void setScorer(Scorer scorer) throws IOException {} @Override public void collect(int doc) { bag.add(Integer.valueOf(doc + base)); } @Override public void setNextReader(IndexReader reader, int docBase) { base = docBase; } @Override public boolean acceptsDocsOutOfOrder() { return true; } } /** * Tests that a query matches the an expected set of documents using Hits. * * <p> * Note that when using the Hits API, documents will only be returned * if they have a positive normalized score. * </p> * @param query the query to test * @param searcher the searcher to test the query against * @param defaultFieldName used for displaing the query in assertion messages * @param results a list of documentIds that must match the query * @see Searcher#search(Query) * @see #checkHitCollector */ public static void checkHits( Query query, String defaultFieldName, Searcher searcher, int[] results) throws IOException { if (searcher instanceof IndexSearcher) { QueryUtils.check(query,searcher); } ScoreDoc[] hits = searcher.search(query, null, 1000).scoreDocs; Set correct = new TreeSet(); for (int i = 0; i < results.length; i++) { correct.add(Integer.valueOf(results[i])); } Set actual = new TreeSet(); for (int i = 0; i < hits.length; i++) { actual.add(Integer.valueOf(hits[i].doc)); } Assert.assertEquals(query.toString(defaultFieldName), correct, actual); QueryUtils.check(query,searcher); } /** Tests that a Hits has an expected order of documents */ public static void checkDocIds(String mes, int[] results, ScoreDoc[] hits) throws IOException { Assert.assertEquals(mes + " nr of hits", hits.length, results.length); for (int i = 0; i < results.length; i++) { Assert.assertEquals(mes + " doc nrs for hit " + i, results[i], hits[i].doc); } } /** Tests that two queries have an expected order of documents, * and that the two queries have the same score values. */ public static void checkHitsQuery( Query query, ScoreDoc[] hits1, ScoreDoc[] hits2, int[] results) throws IOException { checkDocIds("hits1", results, hits1); checkDocIds("hits2", results, hits2); checkEqual(query, hits1, hits2); } public static void checkEqual(Query query, ScoreDoc[] hits1, ScoreDoc[] hits2) throws IOException { final float scoreTolerance = 1.0e-6f; if (hits1.length != hits2.length) { Assert.fail("Unequal lengths: hits1="+hits1.length+",hits2="+hits2.length); } for (int i = 0; i < hits1.length; i++) { if (hits1[i].doc != hits2[i].doc) { Assert.fail("Hit " + i + " docnumbers don't match\n" + hits2str(hits1, hits2,0,0) + "for query:" + query.toString()); } if ((hits1[i].doc != hits2[i].doc) || Math.abs(hits1[i].score - hits2[i].score) > scoreTolerance) { Assert.fail("Hit " + i + ", doc nrs " + hits1[i].doc + " and " + hits2[i].doc + "\nunequal : " + hits1[i].score + "\n and: " + hits2[i].score + "\nfor query:" + query.toString()); } } } public static String hits2str(ScoreDoc[] hits1, ScoreDoc[] hits2, int start, int end) throws IOException { StringBuilder sb = new StringBuilder(); int len1=hits1==null ? 0 : hits1.length; int len2=hits2==null ? 0 : hits2.length; if (end<=0) { end = Math.max(len1,len2); } sb.append("Hits length1=").append(len1).append("\tlength2=").append(len2); sb.append('\n'); for (int i=start; i<end; i++) { sb.append("hit=").append(i).append(':'); if (i<len1) { sb.append(" doc").append(hits1[i].doc).append('=').append(hits1[i].score); } else { sb.append(" "); } sb.append(",\t"); if (i<len2) { sb.append(" doc").append(hits2[i].doc).append('=').append(hits2[i].score); } sb.append('\n'); } return sb.toString(); } public static String topdocsString(TopDocs docs, int start, int end) { StringBuilder sb = new StringBuilder(); sb.append("TopDocs totalHits=").append(docs.totalHits).append(" top=").append(docs.scoreDocs.length).append('\n'); if (end<=0) end=docs.scoreDocs.length; else end=Math.min(end,docs.scoreDocs.length); for (int i=start; i<end; i++) { sb.append('\t'); sb.append(i); sb.append(") doc="); sb.append(docs.scoreDocs[i].doc); sb.append("\tscore="); sb.append(docs.scoreDocs[i].score); sb.append('\n'); } return sb.toString(); } /** * Asserts that the explanation value for every document matching a * query corresponds with the true score. * * @see ExplanationAsserter * @see #checkExplanations(Query, String, Searcher, boolean) for a * "deep" testing of the explanation details. * * @param query the query to test * @param searcher the searcher to test the query against * @param defaultFieldName used for displaing the query in assertion messages */ public static void checkExplanations(Query query, String defaultFieldName, Searcher searcher) throws IOException { checkExplanations(query, defaultFieldName, searcher, false); } /** * Asserts that the explanation value for every document matching a * query corresponds with the true score. Optionally does "deep" * testing of the explanation details. * * @see ExplanationAsserter * @param query the query to test * @param searcher the searcher to test the query against * @param defaultFieldName used for displaing the query in assertion messages * @param deep indicates whether a deep comparison of sub-Explanation details should be executed */ public static void checkExplanations(Query query, String defaultFieldName, Searcher searcher, boolean deep) throws IOException { searcher.search(query, new ExplanationAsserter (query, defaultFieldName, searcher, deep)); } /** * Assert that an explanation has the expected score, and optionally that its * sub-details max/sum/factor match to that score. * * @param q String representation of the query for assertion messages * @param doc Document ID for assertion messages * @param score Real score value of doc with query q * @param deep indicates whether a deep comparison of sub-Explanation details should be executed * @param expl The Explanation to match against score */ public static void verifyExplanation(String q, int doc, float score, boolean deep, Explanation expl) { float value = expl.getValue(); Assert.assertEquals(q+": score(doc="+doc+")="+score+ " != explanationScore="+value+" Explanation: "+expl, score,value,EXPLAIN_SCORE_TOLERANCE_DELTA); if (!deep) return; Explanation detail[] = expl.getDetails(); if (detail!=null) { if (detail.length==1) { // simple containment, no matter what the description says, // just verify contained expl has same score verifyExplanation(q,doc,score,deep,detail[0]); } else { // explanation must either: // - end with one of: "product of:", "sum of:", "max of:", or // - have "max plus <x> times others" (where <x> is float). float x = 0; String descr = expl.getDescription().toLowerCase(); boolean productOf = descr.endsWith("product of:"); boolean sumOf = descr.endsWith("sum of:"); boolean maxOf = descr.endsWith("max of:"); boolean maxTimesOthers = false; if (!(productOf || sumOf || maxOf)) { // maybe 'max plus x times others' int k1 = descr.indexOf("max plus "); if (k1>=0) { k1 += "max plus ".length(); int k2 = descr.indexOf(" ",k1); try { x = Float.parseFloat(descr.substring(k1,k2).trim()); if (descr.substring(k2).trim().equals("times others of:")) { maxTimesOthers = true; } } catch (NumberFormatException e) { } } } Assert.assertTrue( q+": multi valued explanation description=\""+descr +"\" must be 'max of plus x times others' or end with 'product of'" +" or 'sum of:' or 'max of:' - "+expl, productOf || sumOf || maxOf || maxTimesOthers); float sum = 0; float product = 1; float max = 0; for (int i=0; i<detail.length; i++) { float dval = detail[i].getValue(); verifyExplanation(q,doc,dval,deep,detail[i]); product *= dval; sum += dval; max = Math.max(max,dval); } float combined = 0; if (productOf) { combined = product; } else if (sumOf) { combined = sum; } else if (maxOf) { combined = max; } else if (maxTimesOthers) { combined = max + x * (sum - max); } else { Assert.assertTrue("should never get here!",false); } Assert.assertEquals(q+": actual subDetails combined=="+combined+ " != value="+value+" Explanation: "+expl, combined,value,EXPLAIN_SCORE_TOLERANCE_DELTA); } } } /** * an IndexSearcher that implicitly checks hte explanation of every match * whenever it executes a search. * * @see ExplanationAsserter */ public static class ExplanationAssertingSearcher extends IndexSearcher { public ExplanationAssertingSearcher(Directory d) throws IOException { super(d, true); } public ExplanationAssertingSearcher(IndexReader r) throws IOException { super(r); } protected void checkExplanations(Query q) throws IOException { super.search(q, null, new ExplanationAsserter (q, null, this)); } @Override public TopFieldDocs search(Query query, Filter filter, int n, Sort sort) throws IOException { checkExplanations(query); return super.search(query,filter,n,sort); } @Override public void search(Query query, Collector results) throws IOException { checkExplanations(query); super.search(query, results); } @Override public void search(Query query, Filter filter, Collector results) throws IOException { checkExplanations(query); super.search(query, filter, results); } @Override public TopDocs search(Query query, Filter filter, int n) throws IOException { checkExplanations(query); return super.search(query,filter, n); } } /** * Asserts that the score explanation for every document matching a * query corresponds with the true score. * * NOTE: this HitCollector should only be used with the Query and Searcher * specified at when it is constructed. * * @see CheckHits#verifyExplanation */ public static class ExplanationAsserter extends Collector { /** * @deprecated * @see CheckHits#EXPLAIN_SCORE_TOLERANCE_DELTA */ public static float SCORE_TOLERANCE_DELTA = 0.00005f; Query q; Searcher s; String d; boolean deep; Scorer scorer; private int base = 0; /** Constructs an instance which does shallow tests on the Explanation */ public ExplanationAsserter(Query q, String defaultFieldName, Searcher s) { this(q,defaultFieldName,s,false); } public ExplanationAsserter(Query q, String defaultFieldName, Searcher s, boolean deep) { this.q=q; this.s=s; this.d = q.toString(defaultFieldName); this.deep=deep; } @Override public void setScorer(Scorer scorer) throws IOException { this.scorer = scorer; } @Override public void collect(int doc) throws IOException { Explanation exp = null; doc = doc + base; try { exp = s.explain(q, doc); } catch (IOException e) { throw new RuntimeException ("exception in hitcollector of [["+d+"]] for #"+doc, e); } Assert.assertNotNull("Explanation of [["+d+"]] for #"+doc+" is null", exp); verifyExplanation(d,doc,scorer.score(),deep,exp); } @Override public void setNextReader(IndexReader reader, int docBase) { base = docBase; } @Override public boolean acceptsDocsOutOfOrder() { return true; } } }
zzh-simple-hr
Zlucene/src/test/org/apache/lucene/search/CheckHits.java
Java
art
17,585
package org.apache.lucene.search; /** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import org.apache.lucene.index.IndexReader; import org.apache.lucene.util.DocIdBitSet; import java.util.BitSet; public class MockFilter extends Filter { private boolean wasCalled; @Override public DocIdSet getDocIdSet(IndexReader reader) { wasCalled = true; return new DocIdBitSet(new BitSet()); } public void clear() { wasCalled = false; } public boolean wasCalled() { return wasCalled; } }
zzh-simple-hr
Zlucene/src/test/org/apache/lucene/search/MockFilter.java
Java
art
1,267
package org.apache.lucene.search; /** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import java.io.IOException; import org.apache.lucene.document.Document; import org.apache.lucene.document.FieldSelector; import org.apache.lucene.index.CorruptIndexException; import org.apache.lucene.index.IndexReader; import org.apache.lucene.index.Term; import org.apache.lucene.index.TermPositions; import org.apache.lucene.util.PriorityQueue; /** * Holds all implementations of classes in the o.a.l.search package as a * back-compatibility test. It does not run any tests per-se, however if * someone adds a method to an interface or abstract method to an abstract * class, one of the implementations here will fail to compile and so we know * back-compat policy was violated. */ final class JustCompileSearch { private static final String UNSUPPORTED_MSG = "unsupported: used for back-compat testing only !"; static final class JustCompileSearcher extends Searcher { @Override protected Weight createWeight(Query query) throws IOException { throw new UnsupportedOperationException(UNSUPPORTED_MSG); } @Override public void close() throws IOException { throw new UnsupportedOperationException(UNSUPPORTED_MSG); } @Override public Document doc(int i) throws CorruptIndexException, IOException { throw new UnsupportedOperationException(UNSUPPORTED_MSG); } @Override public int[] docFreqs(Term[] terms) throws IOException { throw new UnsupportedOperationException(UNSUPPORTED_MSG); } @Override public Explanation explain(Query query, int doc) throws IOException { throw new UnsupportedOperationException(UNSUPPORTED_MSG); } @Override public Similarity getSimilarity() { throw new UnsupportedOperationException(UNSUPPORTED_MSG); } @Override public void search(Query query, Collector results) throws IOException { throw new UnsupportedOperationException(UNSUPPORTED_MSG); } @Override public void search(Query query, Filter filter, Collector results) throws IOException { throw new UnsupportedOperationException(UNSUPPORTED_MSG); } @Override public TopDocs search(Query query, Filter filter, int n) throws IOException { throw new UnsupportedOperationException(UNSUPPORTED_MSG); } @Override public TopFieldDocs search(Query query, Filter filter, int n, Sort sort) throws IOException { throw new UnsupportedOperationException(UNSUPPORTED_MSG); } @Override public TopDocs search(Query query, int n) throws IOException { throw new UnsupportedOperationException(UNSUPPORTED_MSG); } @Override public void setSimilarity(Similarity similarity) { throw new UnsupportedOperationException(UNSUPPORTED_MSG); } @Override public int docFreq(Term term) throws IOException { throw new UnsupportedOperationException(UNSUPPORTED_MSG); } @Override public Explanation explain(Weight weight, int doc) throws IOException { throw new UnsupportedOperationException(UNSUPPORTED_MSG); } @Override public int maxDoc() throws IOException { throw new UnsupportedOperationException(UNSUPPORTED_MSG); } @Override public Query rewrite(Query query) throws IOException { throw new UnsupportedOperationException(UNSUPPORTED_MSG); } @Override public void search(Weight weight, Filter filter, Collector results) throws IOException { throw new UnsupportedOperationException(UNSUPPORTED_MSG); } @Override public TopDocs search(Weight weight, Filter filter, int n) throws IOException { throw new UnsupportedOperationException(UNSUPPORTED_MSG); } @Override public TopFieldDocs search(Weight weight, Filter filter, int n, Sort sort) throws IOException { throw new UnsupportedOperationException(UNSUPPORTED_MSG); } @Override public Document doc(int n, FieldSelector fieldSelector) throws CorruptIndexException, IOException { throw new UnsupportedOperationException(UNSUPPORTED_MSG); } } static final class JustCompileCollector extends Collector { @Override public void collect(int doc) throws IOException { throw new UnsupportedOperationException(UNSUPPORTED_MSG); } @Override public void setNextReader(IndexReader reader, int docBase) throws IOException { throw new UnsupportedOperationException(UNSUPPORTED_MSG); } @Override public void setScorer(Scorer scorer) throws IOException { throw new UnsupportedOperationException(UNSUPPORTED_MSG); } @Override public boolean acceptsDocsOutOfOrder() { throw new UnsupportedOperationException(UNSUPPORTED_MSG); } } static final class JustCompileDocIdSet extends DocIdSet { @Override public DocIdSetIterator iterator() throws IOException { throw new UnsupportedOperationException(UNSUPPORTED_MSG); } } static final class JustCompileDocIdSetIterator extends DocIdSetIterator { @Override public int docID() { throw new UnsupportedOperationException(UNSUPPORTED_MSG); } @Override public int nextDoc() throws IOException { throw new UnsupportedOperationException(UNSUPPORTED_MSG); } @Override public int advance(int target) throws IOException { throw new UnsupportedOperationException(UNSUPPORTED_MSG); } } static final class JustCompileExtendedFieldCacheLongParser implements FieldCache.LongParser { public long parseLong(String string) { throw new UnsupportedOperationException(UNSUPPORTED_MSG); } } static final class JustCompileExtendedFieldCacheDoubleParser implements FieldCache.DoubleParser { public double parseDouble(String string) { throw new UnsupportedOperationException(UNSUPPORTED_MSG); } } static final class JustCompileFieldComparator extends FieldComparator { @Override public int compare(int slot1, int slot2) { throw new UnsupportedOperationException(UNSUPPORTED_MSG); } @Override public int compareBottom(int doc) throws IOException { throw new UnsupportedOperationException(UNSUPPORTED_MSG); } @Override public void copy(int slot, int doc) throws IOException { throw new UnsupportedOperationException(UNSUPPORTED_MSG); } @Override public void setBottom(int slot) { throw new UnsupportedOperationException(UNSUPPORTED_MSG); } @Override public void setNextReader(IndexReader reader, int docBase) throws IOException { throw new UnsupportedOperationException(UNSUPPORTED_MSG); } @Override public Comparable value(int slot) { throw new UnsupportedOperationException(UNSUPPORTED_MSG); } } static final class JustCompileFieldComparatorSource extends FieldComparatorSource { @Override public FieldComparator newComparator(String fieldname, int numHits, int sortPos, boolean reversed) throws IOException { throw new UnsupportedOperationException(UNSUPPORTED_MSG); } } static final class JustCompileFilter extends Filter { // Filter is just an abstract class with no abstract methods. However it is // still added here in case someone will add abstract methods in the future. @Override public DocIdSet getDocIdSet(IndexReader reader) throws IOException { return null; } } static final class JustCompileFilteredDocIdSet extends FilteredDocIdSet { public JustCompileFilteredDocIdSet(DocIdSet innerSet) { super(innerSet); } @Override protected boolean match(int docid) { throw new UnsupportedOperationException(UNSUPPORTED_MSG); } } static final class JustCompileFilteredDocIdSetIterator extends FilteredDocIdSetIterator { public JustCompileFilteredDocIdSetIterator(DocIdSetIterator innerIter) { super(innerIter); } @Override protected boolean match(int doc) { throw new UnsupportedOperationException(UNSUPPORTED_MSG); } } static final class JustCompileFilteredTermEnum extends FilteredTermEnum { @Override public float difference() { throw new UnsupportedOperationException(UNSUPPORTED_MSG); } @Override protected boolean endEnum() { throw new UnsupportedOperationException(UNSUPPORTED_MSG); } @Override protected boolean termCompare(Term term) { throw new UnsupportedOperationException(UNSUPPORTED_MSG); } } static final class JustCompilePhraseScorer extends PhraseScorer { JustCompilePhraseScorer(Weight weight, TermPositions[] tps, int[] offsets, Similarity similarity, byte[] norms) { super(weight, tps, offsets, similarity, norms); } @Override protected float phraseFreq() throws IOException { throw new UnsupportedOperationException(UNSUPPORTED_MSG); } } static final class JustCompileQuery extends Query { @Override public String toString(String field) { throw new UnsupportedOperationException(UNSUPPORTED_MSG); } } static final class JustCompileScorer extends Scorer { protected JustCompileScorer(Similarity similarity) { super(similarity); } @Override protected boolean score(Collector collector, int max, int firstDocID) throws IOException { throw new UnsupportedOperationException(UNSUPPORTED_MSG); } @Override public float score() throws IOException { throw new UnsupportedOperationException(UNSUPPORTED_MSG); } @Override public int docID() { throw new UnsupportedOperationException(UNSUPPORTED_MSG); } @Override public int nextDoc() throws IOException { throw new UnsupportedOperationException(UNSUPPORTED_MSG); } @Override public int advance(int target) throws IOException { throw new UnsupportedOperationException(UNSUPPORTED_MSG); } } static final class JustCompileSimilarity extends Similarity { @Override public float coord(int overlap, int maxOverlap) { throw new UnsupportedOperationException(UNSUPPORTED_MSG); } @Override public float idf(int docFreq, int numDocs) { throw new UnsupportedOperationException(UNSUPPORTED_MSG); } @Override public float lengthNorm(String fieldName, int numTokens) { throw new UnsupportedOperationException(UNSUPPORTED_MSG); } @Override public float queryNorm(float sumOfSquaredWeights) { throw new UnsupportedOperationException(UNSUPPORTED_MSG); } @Override public float sloppyFreq(int distance) { throw new UnsupportedOperationException(UNSUPPORTED_MSG); } @Override public float tf(float freq) { throw new UnsupportedOperationException(UNSUPPORTED_MSG); } } static final class JustCompileSpanFilter extends SpanFilter { @Override public SpanFilterResult bitSpans(IndexReader reader) throws IOException { throw new UnsupportedOperationException(UNSUPPORTED_MSG); } @Override public DocIdSet getDocIdSet(IndexReader reader) throws IOException { return null; } } static final class JustCompileTopDocsCollector extends TopDocsCollector { protected JustCompileTopDocsCollector(PriorityQueue pq) { super(pq); } @Override public void collect(int doc) throws IOException { throw new UnsupportedOperationException(UNSUPPORTED_MSG); } @Override public void setNextReader(IndexReader reader, int docBase) throws IOException { throw new UnsupportedOperationException(UNSUPPORTED_MSG); } @Override public void setScorer(Scorer scorer) throws IOException { throw new UnsupportedOperationException(UNSUPPORTED_MSG); } @Override public boolean acceptsDocsOutOfOrder() { throw new UnsupportedOperationException(UNSUPPORTED_MSG); } } static final class JustCompileWeight extends Weight { @Override public Explanation explain(IndexReader reader, int doc) throws IOException { throw new UnsupportedOperationException(UNSUPPORTED_MSG); } @Override public Query getQuery() { throw new UnsupportedOperationException(UNSUPPORTED_MSG); } @Override public float getValue() { throw new UnsupportedOperationException(UNSUPPORTED_MSG); } @Override public void normalize(float norm) { throw new UnsupportedOperationException(UNSUPPORTED_MSG); } @Override public float sumOfSquaredWeights() throws IOException { throw new UnsupportedOperationException(UNSUPPORTED_MSG); } @Override public Scorer scorer(IndexReader reader, boolean scoreDocsInOrder, boolean topScorer) throws IOException { throw new UnsupportedOperationException(UNSUPPORTED_MSG); } } }
zzh-simple-hr
Zlucene/src/test/org/apache/lucene/search/JustCompileSearch.java
Java
art
13,833
package org.apache.lucene.search.function; /** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import java.io.IOException; import org.apache.lucene.index.IndexReader; import org.apache.lucene.search.FieldCache; /** * Holds all implementations of classes in the o.a.l.s.function package as a * back-compatibility test. It does not run any tests per-se, however if * someone adds a method to an interface or abstract method to an abstract * class, one of the implementations here will fail to compile and so we know * back-compat policy was violated. */ final class JustCompileSearchFunction { private static final String UNSUPPORTED_MSG = "unsupported: used for back-compat testing only !"; static final class JustCompileDocValues extends DocValues { @Override public float floatVal(int doc) { throw new UnsupportedOperationException(UNSUPPORTED_MSG); } @Override public String toString(int doc) { throw new UnsupportedOperationException(UNSUPPORTED_MSG); } } static final class JustCompileFieldCacheSource extends FieldCacheSource { public JustCompileFieldCacheSource(String field) { super(field); } @Override public boolean cachedFieldSourceEquals(FieldCacheSource other) { throw new UnsupportedOperationException(UNSUPPORTED_MSG); } @Override public int cachedFieldSourceHashCode() { throw new UnsupportedOperationException(UNSUPPORTED_MSG); } @Override public DocValues getCachedFieldValues(FieldCache cache, String field, IndexReader reader) throws IOException { throw new UnsupportedOperationException(UNSUPPORTED_MSG); } } static final class JustCompileValueSource extends ValueSource { @Override public String description() { throw new UnsupportedOperationException(UNSUPPORTED_MSG); } @Override public boolean equals(Object o) { throw new UnsupportedOperationException(UNSUPPORTED_MSG); } @Override public DocValues getValues(IndexReader reader) throws IOException { throw new UnsupportedOperationException(UNSUPPORTED_MSG); } @Override public int hashCode() { throw new UnsupportedOperationException(UNSUPPORTED_MSG); } } }
zzh-simple-hr
Zlucene/src/test/org/apache/lucene/search/function/JustCompileSearchSpans.java
Java
art
3,024
package org.apache.lucene.search.function; /** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import org.apache.lucene.analysis.Analyzer; import org.apache.lucene.analysis.standard.StandardAnalyzer; import org.apache.lucene.document.Document; import org.apache.lucene.document.Field; import org.apache.lucene.document.Fieldable; import org.apache.lucene.index.IndexWriter; import org.apache.lucene.store.Directory; import org.apache.lucene.store.RAMDirectory; import org.apache.lucene.util.LuceneTestCase; /** * Setup for function tests */ public abstract class FunctionTestSetup extends LuceneTestCase { /** * Actual score computation order is slightly different than assumptios * this allows for a small amount of variation */ public static float TEST_SCORE_TOLERANCE_DELTA = 0.001f; protected static final boolean DBG = false; // change to true for logging to print protected static final int N_DOCS = 17; // select a primary number > 2 protected static final String ID_FIELD = "id"; protected static final String TEXT_FIELD = "text"; protected static final String INT_FIELD = "iii"; protected static final String FLOAT_FIELD = "fff"; private static final String DOC_TEXT_LINES[] = { "Well, this is just some plain text we use for creating the ", "test documents. It used to be a text from an online collection ", "devoted to first aid, but if there was there an (online) lawyers ", "first aid collection with legal advices, \"it\" might have quite ", "probably advised one not to include \"it\"'s text or the text of ", "any other online collection in one's code, unless one has money ", "that one don't need and one is happy to donate for lawyers ", "charity. Anyhow at some point, rechecking the usage of this text, ", "it became uncertain that this text is free to use, because ", "the web site in the disclaimer of he eBook containing that text ", "was not responding anymore, and at the same time, in projGut, ", "searching for first aid no longer found that eBook as well. ", "So here we are, with a perhaps much less interesting ", "text for the test, but oh much much safer. ", }; protected Directory dir; protected Analyzer anlzr; /* @override constructor */ public FunctionTestSetup(String name) { this(name, false); } private final boolean doMultiSegment; public FunctionTestSetup(String name, boolean doMultiSegment) { super(name); this.doMultiSegment = doMultiSegment; } /* @override */ @Override protected void tearDown() throws Exception { super.tearDown(); dir = null; anlzr = null; } /* @override */ @Override protected void setUp() throws Exception { super.setUp(); // prepare a small index with just a few documents. super.setUp(); dir = new RAMDirectory(); anlzr = new StandardAnalyzer(org.apache.lucene.util.Version.LUCENE_CURRENT); IndexWriter iw = new IndexWriter(dir, anlzr, IndexWriter.MaxFieldLength.LIMITED); // add docs not exactly in natural ID order, to verify we do check the order of docs by scores int remaining = N_DOCS; boolean done[] = new boolean[N_DOCS]; int i = 0; while (remaining>0) { if (done[i]) { throw new Exception("to set this test correctly N_DOCS="+N_DOCS+" must be primary and greater than 2!"); } addDoc(iw,i); done[i] = true; i = (i+4)%N_DOCS; if (doMultiSegment && remaining % 3 == 0) { iw.commit(); } remaining --; } iw.close(); } private void addDoc(IndexWriter iw, int i) throws Exception { Document d = new Document(); Fieldable f; int scoreAndID = i+1; f = new Field(ID_FIELD,id2String(scoreAndID),Field.Store.YES,Field.Index.NOT_ANALYZED); // for debug purposes f.setOmitNorms(true); d.add(f); f = new Field(TEXT_FIELD,"text of doc"+scoreAndID+textLine(i),Field.Store.NO,Field.Index.ANALYZED); // for regular search f.setOmitNorms(true); d.add(f); f = new Field(INT_FIELD,""+scoreAndID,Field.Store.NO,Field.Index.NOT_ANALYZED); // for function scoring f.setOmitNorms(true); d.add(f); f = new Field(FLOAT_FIELD,scoreAndID+".000",Field.Store.NO,Field.Index.NOT_ANALYZED); // for function scoring f.setOmitNorms(true); d.add(f); iw.addDocument(d); log("added: "+d); } // 17 --> ID00017 protected String id2String(int scoreAndID) { String s = "000000000"+scoreAndID; int n = (""+N_DOCS).length() + 3; int k = s.length() - n; return "ID"+s.substring(k); } // some text line for regular search private String textLine(int docNum) { return DOC_TEXT_LINES[docNum % DOC_TEXT_LINES.length]; } // extract expected doc score from its ID Field: "ID7" --> 7.0 protected float expectedFieldScore(String docIDFieldVal) { return Float.parseFloat(docIDFieldVal.substring(2)); } // debug messages (change DBG to true for anything to print) protected void log (Object o) { if (DBG) { System.out.println(o.toString()); } } }
zzh-simple-hr
Zlucene/src/test/org/apache/lucene/search/function/FunctionTestSetup.java
Java
art
5,907
package org.apache.lucene.search; /** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import org.apache.lucene.index.IndexReader; import org.apache.lucene.util.DocIdBitSet; import java.util.BitSet; import java.io.IOException; public class SingleDocTestFilter extends Filter { private int doc; public SingleDocTestFilter(int doc) { this.doc = doc; } @Override public DocIdSet getDocIdSet(IndexReader reader) throws IOException { BitSet bits = new BitSet(reader.maxDoc()); bits.set(doc); return new DocIdBitSet(bits); } }
zzh-simple-hr
Zlucene/src/test/org/apache/lucene/search/SingleDocTestFilter.java
Java
art
1,305
package org.apache.lucene.search.spans; /** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import java.io.IOException; import java.util.Collection; import org.apache.lucene.index.IndexReader; import org.apache.lucene.search.Weight; import org.apache.lucene.search.Similarity; /** * Holds all implementations of classes in the o.a.l.s.spans package as a * back-compatibility test. It does not run any tests per-se, however if * someone adds a method to an interface or abstract method to an abstract * class, one of the implementations here will fail to compile and so we know * back-compat policy was violated. */ final class JustCompileSearchSpans { private static final String UNSUPPORTED_MSG = "unsupported: used for back-compat testing only !"; static final class JustCompileSpans extends Spans { @Override public int doc() { throw new UnsupportedOperationException(UNSUPPORTED_MSG); } @Override public int end() { throw new UnsupportedOperationException(UNSUPPORTED_MSG); } @Override public boolean next() throws IOException { throw new UnsupportedOperationException(UNSUPPORTED_MSG); } @Override public boolean skipTo(int target) throws IOException { throw new UnsupportedOperationException(UNSUPPORTED_MSG); } @Override public int start() { throw new UnsupportedOperationException(UNSUPPORTED_MSG); } @Override public Collection getPayload() throws IOException { throw new UnsupportedOperationException(UNSUPPORTED_MSG); } @Override public boolean isPayloadAvailable() { throw new UnsupportedOperationException(UNSUPPORTED_MSG); } } static final class JustCompileSpanQuery extends SpanQuery { @Override public String getField() { throw new UnsupportedOperationException(UNSUPPORTED_MSG); } @Override public Spans getSpans(IndexReader reader) throws IOException { throw new UnsupportedOperationException(UNSUPPORTED_MSG); } @Override public String toString(String field) { throw new UnsupportedOperationException(UNSUPPORTED_MSG); } } static final class JustCompilePayloadSpans extends Spans { @Override public Collection getPayload() throws IOException { throw new UnsupportedOperationException(UNSUPPORTED_MSG); } @Override public boolean isPayloadAvailable() { throw new UnsupportedOperationException(UNSUPPORTED_MSG); } @Override public int doc() { throw new UnsupportedOperationException(UNSUPPORTED_MSG); } @Override public int end() { throw new UnsupportedOperationException(UNSUPPORTED_MSG); } @Override public boolean next() throws IOException { throw new UnsupportedOperationException(UNSUPPORTED_MSG); } @Override public boolean skipTo(int target) throws IOException { throw new UnsupportedOperationException(UNSUPPORTED_MSG); } @Override public int start() { throw new UnsupportedOperationException(UNSUPPORTED_MSG); } } static final class JustCompileSpanScorer extends SpanScorer { protected JustCompileSpanScorer(Spans spans, Weight weight, Similarity similarity, byte[] norms) throws IOException { super(spans, weight, similarity, norms); } @Override protected boolean setFreqCurrentDoc() throws IOException { throw new UnsupportedOperationException(UNSUPPORTED_MSG); } } }
zzh-simple-hr
Zlucene/src/test/org/apache/lucene/search/spans/JustCompileSearchSpans.java
Java
art
4,262
package org.apache.lucene.search.payloads; /** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import org.apache.lucene.analysis.*; import org.apache.lucene.analysis.tokenattributes.PayloadAttribute; import org.apache.lucene.index.Payload; import org.apache.lucene.index.IndexWriter; import org.apache.lucene.store.RAMDirectory; import org.apache.lucene.document.Document; import org.apache.lucene.document.Field; import org.apache.lucene.util.English; import org.apache.lucene.search.IndexSearcher; import org.apache.lucene.search.Similarity; import java.io.Reader; import java.io.IOException; /** * * **/ public class PayloadHelper { private byte[] payloadField = new byte[]{1}; private byte[] payloadMultiField1 = new byte[]{2}; private byte[] payloadMultiField2 = new byte[]{4}; public static final String NO_PAYLOAD_FIELD = "noPayloadField"; public static final String MULTI_FIELD = "multiField"; public static final String FIELD = "field"; public class PayloadAnalyzer extends Analyzer { @Override public TokenStream tokenStream(String fieldName, Reader reader) { TokenStream result = new LowerCaseTokenizer(reader); result = new PayloadFilter(result, fieldName); return result; } } public class PayloadFilter extends TokenFilter { String fieldName; int numSeen = 0; PayloadAttribute payloadAtt; public PayloadFilter(TokenStream input, String fieldName) { super(input); this.fieldName = fieldName; payloadAtt = addAttribute(PayloadAttribute.class); } @Override public boolean incrementToken() throws IOException { if (input.incrementToken()) { if (fieldName.equals(FIELD)) { payloadAtt.setPayload(new Payload(payloadField)); } else if (fieldName.equals(MULTI_FIELD)) { if (numSeen % 2 == 0) { payloadAtt.setPayload(new Payload(payloadMultiField1)); } else { payloadAtt.setPayload(new Payload(payloadMultiField2)); } numSeen++; } return true; } return false; } } /** * Sets up a RAMDirectory, and adds documents (using English.intToEnglish()) with two fields: field and multiField * and analyzes them using the PayloadAnalyzer * @param similarity The Similarity class to use in the Searcher * @param numDocs The num docs to add * @return An IndexSearcher * @throws IOException */ public IndexSearcher setUp(Similarity similarity, int numDocs) throws IOException { RAMDirectory directory = new RAMDirectory(); PayloadAnalyzer analyzer = new PayloadAnalyzer(); IndexWriter writer = new IndexWriter(directory, analyzer, true, IndexWriter.MaxFieldLength.UNLIMITED); writer.setSimilarity(similarity); //writer.infoStream = System.out; for (int i = 0; i < numDocs; i++) { Document doc = new Document(); doc.add(new Field(FIELD, English.intToEnglish(i), Field.Store.YES, Field.Index.ANALYZED)); doc.add(new Field(MULTI_FIELD, English.intToEnglish(i) + " " + English.intToEnglish(i), Field.Store.YES, Field.Index.ANALYZED)); doc.add(new Field(NO_PAYLOAD_FIELD, English.intToEnglish(i), Field.Store.YES, Field.Index.ANALYZED)); writer.addDocument(doc); } //writer.optimize(); writer.close(); IndexSearcher searcher = new IndexSearcher(directory, true); searcher.setSimilarity(similarity); return searcher; } }
zzh-simple-hr
Zlucene/src/test/org/apache/lucene/search/payloads/PayloadHelper.java
Java
art
4,282
package org.apache.lucene.util; /** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import java.io.PrintStream; import java.io.File; import java.util.Arrays; import java.util.Iterator; import java.util.Random; import junit.framework.TestCase; import org.apache.lucene.index.ConcurrentMergeScheduler; import org.apache.lucene.search.FieldCache; import org.apache.lucene.search.FieldCache.CacheEntry; import org.apache.lucene.util.FieldCacheSanityChecker.Insanity; /** * Base class for all Lucene unit tests. * <p> * Currently the * only added functionality over JUnit's TestCase is * asserting that no unhandled exceptions occurred in * threads launched by ConcurrentMergeScheduler and asserting sane * FieldCache usage athe moment of tearDown. * </p> * <p> * If you * override either <code>setUp()</code> or * <code>tearDown()</code> in your unit test, make sure you * call <code>super.setUp()</code> and * <code>super.tearDown()</code> * </p> * @see #assertSaneFieldCaches */ public abstract class LuceneTestCase extends TestCase { public static final File TEMP_DIR; static { String s = System.getProperty("tempDir", System.getProperty("java.io.tmpdir")); if (s == null) throw new RuntimeException("To run tests, you need to define system property 'tempDir' or 'java.io.tmpdir'."); TEMP_DIR = new File(s); } public LuceneTestCase() { super(); } public LuceneTestCase(String name) { super(name); } @Override protected void setUp() throws Exception { super.setUp(); ConcurrentMergeScheduler.setTestMode(); } /** * Forcible purges all cache entries from the FieldCache. * <p> * This method will be called by tearDown to clean up FieldCache.DEFAULT. * If a (poorly written) test has some expectation that the FieldCache * will persist across test methods (ie: a static IndexReader) this * method can be overridden to do nothing. * </p> * @see FieldCache#purgeAllCaches() */ protected void purgeFieldCache(final FieldCache fc) { fc.purgeAllCaches(); } protected String getTestLabel() { return getClass().getName() + "." + getName(); } @Override protected void tearDown() throws Exception { try { // this isn't as useful as calling directly from the scope where the // index readers are used, because they could be gc'ed just before // tearDown is called. // But it's better then nothing. assertSaneFieldCaches(getTestLabel()); if (ConcurrentMergeScheduler.anyUnhandledExceptions()) { // Clear the failure so that we don't just keep // failing subsequent test cases ConcurrentMergeScheduler.clearUnhandledExceptions(); fail("ConcurrentMergeScheduler hit unhandled exceptions"); } } finally { purgeFieldCache(FieldCache.DEFAULT); } super.tearDown(); } /** * Asserts that FieldCacheSanityChecker does not detect any * problems with FieldCache.DEFAULT. * <p> * If any problems are found, they are logged to System.err * (allong with the msg) when the Assertion is thrown. * </p> * <p> * This method is called by tearDown after every test method, * however IndexReaders scoped inside test methods may be garbage * collected prior to this method being called, causing errors to * be overlooked. Tests are encouraged to keep their IndexReaders * scoped at the class level, or to explicitly call this method * directly in the same scope as the IndexReader. * </p> * @see FieldCacheSanityChecker */ protected void assertSaneFieldCaches(final String msg) { final CacheEntry[] entries = FieldCache.DEFAULT.getCacheEntries(); Insanity[] insanity = null; try { try { insanity = FieldCacheSanityChecker.checkSanity(entries); } catch (RuntimeException e) { dumpArray(msg+ ": FieldCache", entries, System.err); throw e; } assertEquals(msg + ": Insane FieldCache usage(s) found", 0, insanity.length); insanity = null; } finally { // report this in the event of any exception/failure // if no failure, then insanity will be null anyway if (null != insanity) { dumpArray(msg + ": Insane FieldCache usage(s)", insanity, System.err); } } } /** * Convinience method for logging an iterator. * @param label String logged before/after the items in the iterator * @param iter Each next() is toString()ed and logged on it's own line. If iter is null this is logged differnetly then an empty iterator. * @param stream Stream to log messages to. */ public static void dumpIterator(String label, Iterator iter, PrintStream stream) { stream.println("*** BEGIN "+label+" ***"); if (null == iter) { stream.println(" ... NULL ..."); } else { while (iter.hasNext()) { stream.println(iter.next().toString()); } } stream.println("*** END "+label+" ***"); } /** * Convinience method for logging an array. Wraps the array in an iterator and delegates * @see dumpIterator(String,Iterator,PrintStream) */ public static void dumpArray(String label, Object[] objs, PrintStream stream) { Iterator iter = (null == objs) ? null : Arrays.asList(objs).iterator(); dumpIterator(label, iter, stream); } /** * Returns a {@link Random} instance for generating random numbers during the test. * The random seed is logged during test execution and printed to System.out on any failure * for reproducing the test using {@link #newRandom(long)} with the recorded seed *. */ public Random newRandom() { if (seed != null) { throw new IllegalStateException("please call LuceneTestCase.newRandom only once per test"); } return newRandom(seedRnd.nextLong()); } /** * Returns a {@link Random} instance for generating random numbers during the test. * If an error occurs in the test that is not reproducible, you can use this method to * initialize the number generator with the seed that was printed out during the failing test. */ public Random newRandom(long seed) { if (this.seed != null) { throw new IllegalStateException("please call LuceneTestCase.newRandom only once per test"); } this.seed = Long.valueOf(seed); return new Random(seed); } @Override public void runBare() throws Throwable { try { seed = null; super.runBare(); } catch (Throwable e) { if (seed != null) { System.out.println("NOTE: random seed of testcase '" + getName() + "' was: " + seed); } throw e; } } // recorded seed protected Long seed = null; // static members private static final Random seedRnd = new Random(); }
zzh-simple-hr
Zlucene/src/test/org/apache/lucene/util/LuceneTestCase.java
Java
art
7,640
package org.apache.lucene.util; /** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import java.util.Locale; import java.util.Set; /** * Base test class for Lucene test classes that test Locale-sensitive behavior. * <p> * This class will run tests under the default Locale, but then will also run * tests under all available JVM locales. This is helpful to ensure tests will * not fail under a different environment. * </p> */ public abstract class LocalizedTestCase extends LuceneTestCase { /** * Before changing the default Locale, save the default Locale here so that it * can be restored. */ private final Locale defaultLocale = Locale.getDefault(); /** * The locale being used as the system default Locale */ private Locale locale; /** * An optional limited set of testcases that will run under different Locales. */ private final Set testWithDifferentLocales; public LocalizedTestCase() { super(); testWithDifferentLocales = null; } public LocalizedTestCase(String name) { super(name); testWithDifferentLocales = null; } public LocalizedTestCase(Set testWithDifferentLocales) { super(); this.testWithDifferentLocales = testWithDifferentLocales; } public LocalizedTestCase(String name, Set testWithDifferentLocales) { super(name); this.testWithDifferentLocales = testWithDifferentLocales; } @Override protected void setUp() throws Exception { super.setUp(); Locale.setDefault(locale); } @Override protected void tearDown() throws Exception { Locale.setDefault(defaultLocale); super.tearDown(); } @Override public void runBare() throws Throwable { // Do the test with the default Locale (default) try { locale = defaultLocale; super.runBare(); } catch (Throwable e) { System.out.println("Test failure of '" + getName() + "' occurred with the default Locale " + locale); throw e; } if (testWithDifferentLocales == null || testWithDifferentLocales.contains(getName())) { // Do the test again under different Locales Locale systemLocales[] = Locale.getAvailableLocales(); for (int i = 0; i < systemLocales.length; i++) { try { locale = systemLocales[i]; super.runBare(); } catch (Throwable e) { System.out.println("Test failure of '" + getName() + "' occurred under a different Locale " + locale); throw e; } } } } }
zzh-simple-hr
Zlucene/src/test/org/apache/lucene/util/LocalizedTestCase.java
Java
art
3,274
package org.apache.lucene.util; /** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import java.io.File; import java.io.IOException; import org.apache.lucene.index.IndexWriter; import org.apache.lucene.index.MergeScheduler; import org.apache.lucene.index.ConcurrentMergeScheduler; import org.apache.lucene.index.CheckIndex; import org.apache.lucene.store.Directory; import java.io.ByteArrayOutputStream; import java.io.PrintStream; import java.util.Random; public class _TestUtil { /** Returns temp dir, containing String arg in its name; * does not create the directory. */ public static File getTempDir(String desc) { String tempDir = System.getProperty("java.io.tmpdir"); if (tempDir == null) throw new RuntimeException("java.io.tmpdir undefined, cannot run test"); return new File(tempDir, desc + "." + new Random().nextLong()); } public static void rmDir(File dir) throws IOException { if (dir.exists()) { File[] files = dir.listFiles(); for (int i = 0; i < files.length; i++) { if (!files[i].delete()) { throw new IOException("could not delete " + files[i]); } } dir.delete(); } } public static void rmDir(String dir) throws IOException { rmDir(new File(dir)); } public static void syncConcurrentMerges(IndexWriter writer) { syncConcurrentMerges(writer.getMergeScheduler()); } public static void syncConcurrentMerges(MergeScheduler ms) { if (ms instanceof ConcurrentMergeScheduler) ((ConcurrentMergeScheduler) ms).sync(); } /** This runs the CheckIndex tool on the index in. If any * issues are hit, a RuntimeException is thrown; else, * true is returned. */ public static boolean checkIndex(Directory dir) throws IOException { ByteArrayOutputStream bos = new ByteArrayOutputStream(1024); CheckIndex checker = new CheckIndex(dir); checker.setInfoStream(new PrintStream(bos)); CheckIndex.Status indexStatus = checker.checkIndex(); if (indexStatus == null || indexStatus.clean == false) { System.out.println("CheckIndex failed"); System.out.println(bos.toString()); throw new RuntimeException("CheckIndex failed"); } else return true; } /** Use only for testing. * @deprecated -- in 3.0 we can use Arrays.toString * instead */ public static String arrayToString(int[] array) { StringBuilder buf = new StringBuilder(); buf.append("["); for(int i=0;i<array.length;i++) { if (i > 0) { buf.append(" "); } buf.append(array[i]); } buf.append("]"); return buf.toString(); } /** Use only for testing. * @deprecated -- in 3.0 we can use Arrays.toString * instead */ public static String arrayToString(Object[] array) { StringBuilder buf = new StringBuilder(); buf.append("["); for(int i=0;i<array.length;i++) { if (i > 0) { buf.append(" "); } buf.append(array[i]); } buf.append("]"); return buf.toString(); } public static int getRandomSocketPort() { return 1024 + new Random().nextInt(64512); } }
zzh-simple-hr
Zlucene/src/test/org/apache/lucene/util/_TestUtil.java
Java
art
3,877
package org.apache.lucene.util; /** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ public class English { public static String intToEnglish(int i) { StringBuilder result = new StringBuilder(); intToEnglish(i, result); return result.toString(); } public static void intToEnglish(int i, StringBuilder result) { if (i == 0) { result.append("zero"); return; } if (i < 0) { result.append("minus "); i = -i; } if (i >= 1000000000) { // billions intToEnglish(i/1000000000, result); result.append("billion, "); i = i%1000000000; } if (i >= 1000000) { // millions intToEnglish(i/1000000, result); result.append("million, "); i = i%1000000; } if (i >= 1000) { // thousands intToEnglish(i/1000, result); result.append("thousand, "); i = i%1000; } if (i >= 100) { // hundreds intToEnglish(i/100, result); result.append("hundred "); i = i%100; } if (i >= 20) { switch (i/10) { case 9 : result.append("ninety"); break; case 8 : result.append("eighty"); break; case 7 : result.append("seventy"); break; case 6 : result.append("sixty"); break; case 5 : result.append("fifty"); break; case 4 : result.append("forty"); break; case 3 : result.append("thirty"); break; case 2 : result.append("twenty"); break; } i = i%10; if (i == 0) result.append(" "); else result.append("-"); } switch (i) { case 19 : result.append("nineteen "); break; case 18 : result.append("eighteen "); break; case 17 : result.append("seventeen "); break; case 16 : result.append("sixteen "); break; case 15 : result.append("fifteen "); break; case 14 : result.append("fourteen "); break; case 13 : result.append("thirteen "); break; case 12 : result.append("twelve "); break; case 11 : result.append("eleven "); break; case 10 : result.append("ten "); break; case 9 : result.append("nine "); break; case 8 : result.append("eight "); break; case 7 : result.append("seven "); break; case 6 : result.append("six "); break; case 5 : result.append("five "); break; case 4 : result.append("four "); break; case 3 : result.append("three "); break; case 2 : result.append("two "); break; case 1 : result.append("one "); break; case 0 : result.append(""); break; } } public static void main(String[] args) { System.out.println(intToEnglish(Integer.parseInt(args[0]))); } }
zzh-simple-hr
Zlucene/src/test/org/apache/lucene/util/English.java
Java
art
3,360
<!-- Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to you under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE- 2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. --> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <HTML> <HEAD> <LINK type="text/css" rel="stylesheet" href="http://struts.apache.org/style/space.css"> <LINK type="text/css" rel="stylesheet" href="http://struts.apache.org/style/master.css"> <LINK type="text/css" rel="stylesheet" href="http://struts.apache.org/style/wiki-content.css"> <LINK type="text/css" rel="stylesheet" href="http://struts.apache.org/style/abs.css"> <LINK type="text/css" rel="stylesheet" href="http://struts.apache.org/style/menu.css"> <LINK type="text/css" rel="stylesheet" href="http://struts.apache.org/style/menu-ie.css"> <LINK type="text/css" rel="stylesheet" href="http://struts.apache.org/style/tables.css"> <LINK type="text/css" rel="stylesheet" href="http://struts.apache.org/style/panels.css"> <LINK type="text/css" rel="stylesheet" href="http://struts.apache.org/style/master-ie.css"> <LINK type="text/css" rel="stylesheet" href="http://struts.apache.org/style/renderer-macros.css"> <LINK type="text/css" rel="stylesheet" href="http://struts.apache.org/style/content-types.css"> <LINK type="text/css" rel="stylesheet" href="http://struts.apache.org/style/login.css"> <LINK type="text/css" rel="stylesheet" href="http://struts.apache.org/style/information-macros.css"> <LINK type="text/css" rel="stylesheet" href="http://struts.apache.org/style/layout-macros.css"> <LINK type="text/css" rel="stylesheet" href="http://struts.apache.org/style/default-theme.css"> <!-- currently inaccessible, would remove, but there is no version control on confluence or templates, so commenting out for now - WW <link type="text/css" rel="stylesheet" href="http://cwiki.apache.org/confluence/download/resources/confluence.ext.code:code/shStyles.css"> --> <STYLE type="text/css"> .dp-highlighter { width:95% !important; } </STYLE> <STYLE type="text/css"> .footer { background-image: url('https://cwiki.apache.org/confluence/images/border/border_bottom.gif'); background-repeat: repeat-x; background-position: left top; padding-top: 4px; color: #666; } </STYLE> <SCRIPT type="text/javascript" language="javascript"> var hide = null; var show = null; var children = null; function init() { /* Search form initialization */ var form = document.forms['search']; if (form != null) { form.elements['domains'].value = location.hostname; form.elements['sitesearch'].value = location.hostname; } /* Children initialization */ hide = document.getElementById('hide'); show = document.getElementById('show'); children = document.all != null ? document.all['children'] : document.getElementById('children'); if (children != null) { children.style.display = 'none'; show.style.display = 'inline'; hide.style.display = 'none'; } } function showChildren() { children.style.display = 'block'; show.style.display = 'none'; hide.style.display = 'inline'; } function hideChildren() { children.style.display = 'none'; show.style.display = 'inline'; hide.style.display = 'none'; } </SCRIPT> <TITLE>action</TITLE> <META http-equiv="Content-Type" content="text/html;charset=UTF-8"></HEAD> <BODY onload="init()"> <TABLE border="0" cellpadding="2" cellspacing="0" width="100%"> <TR class="topBar"> <TD align="left" valign="middle" class="topBarDiv" align="left" nowrap=""> &nbsp;<A href="home.html" title="Apache Struts 2 Documentation">Apache Struts 2 Documentation</A>&nbsp;&gt;&nbsp;<A href="home.html" title="Home">Home</A>&nbsp;&gt;&nbsp;<A href="guides.html" title="Guides">Guides</A>&nbsp;&gt;&nbsp;<A href="tag-developers-guide.html" title="Tag Developers Guide">Tag Developers Guide</A>&nbsp;&gt;&nbsp;<A href="struts-tags.html" title="Struts Tags">Struts Tags</A>&nbsp;&gt;&nbsp;<A href="tag-reference.html" title="Tag Reference">Tag Reference</A>&nbsp;&gt;&nbsp;<A href="generic-tag-reference.html" title="Generic Tag Reference">Generic Tag Reference</A>&nbsp;&gt;&nbsp;<A href="" title="action">action</A> </TD> <TD align="right" valign="middle" nowrap=""> <FORM name="search" action="http://www.google.com/search" method="get"> <INPUT type="hidden" name="ie" value="UTF-8"> <INPUT type="hidden" name="oe" value="UTF-8"> <INPUT type="hidden" name="domains" value=""> <INPUT type="hidden" name="sitesearch" value=""> <INPUT type="text" name="q" maxlength="255" value=""> <INPUT type="submit" name="btnG" value="Google Search"> </FORM> </TD> </TR> </TABLE> <DIV id="PageContent"> <DIV class="pageheader" style="padding: 6px 0px 0px 0px;"> <!-- We'll enable this once we figure out how to access (and save) the logo resource --> <!--img src="/wiki/images/confluence_logo.gif" style="float: left; margin: 4px 4px 4px 10px;" border="0"--> <DIV style="margin: 0px 10px 0px 10px" class="smalltext">Apache Struts 2 Documentation</DIV> <DIV style="margin: 0px 10px 8px 10px" class="pagetitle">action</DIV> <DIV class="greynavbar" align="right" style="padding: 2px 10px; margin: 0px;"> <A href="https://cwiki.apache.org/confluence/pages/editpage.action?pageId=14034"> <IMG src="https://cwiki.apache.org/confluence/images/icons/notep_16.gif" height="16" width="16" border="0" align="absmiddle" title="Edit Page"></A> <A href="https://cwiki.apache.org/confluence/pages/editpage.action?pageId=14034">Edit Page</A> &nbsp; <A href="https://cwiki.apache.org/confluence/pages/listpages.action?key=WW"> <IMG src="https://cwiki.apache.org/confluence/images/icons/browse_space.gif" height="16" width="16" border="0" align="absmiddle" title="Browse Space"></A> <A href="https://cwiki.apache.org/confluence/pages/listpages.action?key=WW">Browse Space</A> &nbsp; <A href="https://cwiki.apache.org/confluence/pages/createpage.action?spaceKey=WW&fromPageId=14034"> <IMG src="https://cwiki.apache.org/confluence/images/icons/add_page_16.gif" height="16" width="16" border="0" align="absmiddle" title="Add Page"></A> <A href="https://cwiki.apache.org/confluence/pages/createpage.action?spaceKey=WW&fromPageId=14034">Add Page</A> &nbsp; <A href="https://cwiki.apache.org/confluence/pages/createblogpost.action?spaceKey=WW&fromPageId=14034"> <IMG src="https://cwiki.apache.org/confluence/images/icons/add_blogentry_16.gif" height="16" width="16" border="0" align="absmiddle" title="Add News"></A> <A href="https://cwiki.apache.org/confluence/pages/createblogpost.action?spaceKey=WW&fromPageId=14034">Add News</A> </DIV> </DIV> <DIV class="pagesubheading" style="margin: 0px 10px 0px 10px;"> #editReport() </DIV> <DIV class="pagecontent"> <DIV class="wiki-content"> <DIV class="panelMacro"><TABLE class="noteMacro"><COLGROUP><COL width="24"><COL></COLGROUP><TR><TD valign="top"><IMG src="https://cwiki.apache.org/confluence/images/icons/emoticons/warning.gif" width="16" height="16" align="absmiddle" alt="" border="0"></TD><TD>Please make sure you have read the <A href="tag-syntax.html" title="Tag Syntax">Tag Syntax</A> document and understand how tag attribute syntax works.</TD></TR></TABLE></DIV> <H2><A name="action-Description"></A>Description</H2> <P><P>This tag enables developers to call actions directly from a JSP page by specifying the action name and an optional namespace. The body content of the tag is used to render the results from the Action. Any result processor defined for this action in struts.xml will be ignored, <I>unless</I> the executeResult parameter is specified.</P></P> <P>Parameters can be passed to the action using nested <A href="param.html" title="param">param</A> tags.</P> <H2><A name="action-Placementincontext"></A>Placement in context</H2> <P>The action will not be published to the context until the whole tag is evaluated, meaning that inside the body of the tag, the action cannot be accessed, For example:</P> <DIV class="code panel" style="border-width: 1px;"><DIV class="codeContent panelContent"> <PRE class="code-java"> &lt;s:action <SPAN class="code-keyword">var</SPAN>=<SPAN class="code-quote">&quot;myAction&quot;</SPAN> name=<SPAN class="code-quote">&quot;MyAction&quot;</SPAN> namespace=<SPAN class="code-quote">&quot;/&quot;</SPAN>&gt; Is <SPAN class="code-quote">&quot;myAction&quot;</SPAN> <SPAN class="code-keyword">null</SPAN> inside the tag? &lt;s:property value=<SPAN class="code-quote">&quot;#myAction == <SPAN class="code-keyword">null</SPAN>&quot;</SPAN> /&gt; &lt;/s:action&gt; Is <SPAN class="code-quote">&quot;myAction&quot;</SPAN> <SPAN class="code-keyword">null</SPAN> outside the tag? &lt;s:property value=<SPAN class="code-quote">&quot;#myAction == <SPAN class="code-keyword">null</SPAN>&quot;</SPAN> /&gt; </PRE> </DIV></DIV> <P>Will print:<BR> Is &quot;myAction&quot; null inside the tag? true<BR> Is &quot;myAction&quot; null outside the tag? false</P> <H2><A name="action-Parameters"></A>Parameters</H2> <P><TABLE width="100%"> <TR> <TD colspan="6"><H4>Dynamic Attributes Allowed:</H4> false</TD> </TR> <TR> <TD colspan="6">&nbsp;</TD> </TR> <TR> <TH align="left" valign="top"><H4>Name</H4></TH> <TH align="left" valign="top"><H4>Required</H4></TH> <TH align="left" valign="top"><H4>Default</H4></TH> <TH align="left" valign="top"><H4>Evaluated</H4></TH> <TH align="left" valign="top"><H4>Type</H4></TH> <TH align="left" valign="top"><H4>Description</H4></TH> </TR> <TR> <TD align="left" valign="top">executeResult</TD> <TD align="left" valign="top">false</TD> <TD align="left" valign="top">false</TD> <TD align="left" valign="top">false</TD> <TD align="left" valign="top">Boolean</TD> <TD align="left" valign="top">Whether the result of this action (probably a view) should be executed/rendered</TD> </TR> <TR> <TD align="left" valign="top">flush</TD> <TD align="left" valign="top">false</TD> <TD align="left" valign="top">true</TD> <TD align="left" valign="top">false</TD> <TD align="left" valign="top">Boolean</TD> <TD align="left" valign="top">Whether the writer should be flush upon end of action component tag, default to true</TD> </TR> <TR> <TD align="left" valign="top">id</TD> <TD align="left" valign="top">false</TD> <TD align="left" valign="top"></TD> <TD align="left" valign="top">false</TD> <TD align="left" valign="top">String</TD> <TD align="left" valign="top">Deprecated. Use 'var' instead</TD> </TR> <TR> <TD align="left" valign="top">ignoreContextParams</TD> <TD align="left" valign="top">false</TD> <TD align="left" valign="top">false</TD> <TD align="left" valign="top">false</TD> <TD align="left" valign="top">Boolean</TD> <TD align="left" valign="top">Whether the request parameters are to be included when the action is invoked</TD> </TR> <TR> <TD align="left" valign="top">name</TD> <TD align="left" valign="top"><STRONG>true</STRONG></TD> <TD align="left" valign="top"></TD> <TD align="left" valign="top">false</TD> <TD align="left" valign="top">String</TD> <TD align="left" valign="top">Name of the action to be executed (without the extension suffix eg. .action)</TD> </TR> <TR> <TD align="left" valign="top">namespace</TD> <TD align="left" valign="top">false</TD> <TD align="left" valign="top">namespace from where tag is used</TD> <TD align="left" valign="top">false</TD> <TD align="left" valign="top">String</TD> <TD align="left" valign="top">Namespace for action to call</TD> </TR> <TR> <TD align="left" valign="top">rethrowException</TD> <TD align="left" valign="top">false</TD> <TD align="left" valign="top">false</TD> <TD align="left" valign="top">false</TD> <TD align="left" valign="top">Boolean</TD> <TD align="left" valign="top">Whether an exception should be rethrown, if the target action throws an exception</TD> </TR> <TR> <TD align="left" valign="top">var</TD> <TD align="left" valign="top">false</TD> <TD align="left" valign="top"></TD> <TD align="left" valign="top">false</TD> <TD align="left" valign="top">String</TD> <TD align="left" valign="top">Name used to reference the value pushed into the Value Stack</TD> </TR> </TABLE></P> <H2><A name="action-Examples"></A>Examples</H2> <DIV class="code panel" style="border-width: 1px;"><DIV class="codeContent panelContent"> <PRE class="code-java"><SPAN class="code-keyword">public</SPAN> class ActionTagAction <SPAN class="code-keyword">extends</SPAN> ActionSupport { <SPAN class="code-keyword">public</SPAN> <SPAN class="code-object">String</SPAN> execute() <SPAN class="code-keyword">throws</SPAN> Exception { <SPAN class="code-keyword">return</SPAN> <SPAN class="code-quote">&quot;done&quot;</SPAN>; } <SPAN class="code-keyword">public</SPAN> <SPAN class="code-object">String</SPAN> doDefault() <SPAN class="code-keyword">throws</SPAN> Exception { ServletActionContext.getRequest().setAttribute(<SPAN class="code-quote">&quot;stringByAction&quot;</SPAN>, <SPAN class="code-quote">&quot;This is a <SPAN class="code-object">String</SPAN> put in by the action's doDefault()&quot;</SPAN>); <SPAN class="code-keyword">return</SPAN> <SPAN class="code-quote">&quot;done&quot;</SPAN>; } } </PRE> </DIV></DIV> <DIV class="code panel" style="border-width: 1px;"><DIV class="codeContent panelContent"> <PRE class="code-xml"><SPAN class="code-tag">&lt;xwork&gt;</SPAN> .... <SPAN class="code-tag">&lt;action name=<SPAN class="code-quote">&quot;actionTagAction1&quot;</SPAN> class=<SPAN class="code-quote">&quot;tmjee.testing.ActionTagAction&quot;</SPAN>&gt;</SPAN> <SPAN class="code-tag">&lt;result name=<SPAN class="code-quote">&quot;done&quot;</SPAN>&gt;</SPAN>success.jsp<SPAN class="code-tag">&lt;/result&gt;</SPAN> <SPAN class="code-tag">&lt;/action&gt;</SPAN> <SPAN class="code-tag">&lt;action name=<SPAN class="code-quote">&quot;actionTagAction2&quot;</SPAN> class=<SPAN class="code-quote">&quot;tmjee.testing.ActionTagAction&quot;</SPAN> method=<SPAN class="code-quote">&quot;default&quot;</SPAN>&gt;</SPAN> <SPAN class="code-tag">&lt;result name=<SPAN class="code-quote">&quot;done&quot;</SPAN>&gt;</SPAN>success.jsp<SPAN class="code-tag">&lt;/result&gt;</SPAN> <SPAN class="code-tag">&lt;/action&gt;</SPAN> .... <SPAN class="code-tag">&lt;/xwork&gt;</SPAN> </PRE> </DIV></DIV> <DIV class="code panel" style="border-width: 1px;"><DIV class="codeContent panelContent"> <PRE class="code-xml"><SPAN class="code-tag">&lt;div&gt;</SPAN>The following action tag will execute result and include it in this page<SPAN class="code-tag">&lt;/div&gt;</SPAN> <SPAN class="code-tag">&lt;br /&gt;</SPAN> <SPAN class="code-tag">&lt;s:action name=<SPAN class="code-quote">&quot;actionTagAction&quot;</SPAN> executeResult=<SPAN class="code-quote">&quot;true&quot;</SPAN> /&gt;</SPAN> <SPAN class="code-tag">&lt;br /&gt;</SPAN> <SPAN class="code-tag">&lt;div&gt;</SPAN>The following action tag will do the same as above, but invokes method specialMethod in action<SPAN class="code-tag">&lt;/div&gt;</SPAN> <SPAN class="code-tag">&lt;br /&gt;</SPAN> <SPAN class="code-tag">&lt;s:action name=<SPAN class="code-quote">&quot;actionTagAction!specialMethod&quot;</SPAN> executeResult=<SPAN class="code-quote">&quot;true&quot;</SPAN> /&gt;</SPAN> <SPAN class="code-tag">&lt;br /&gt;</SPAN> <SPAN class="code-tag">&lt;div&gt;</SPAN>The following action tag will not execute result, but put a String in request scope under an id <SPAN class="code-quote">&quot;stringByAction&quot;</SPAN> which will be retrieved using property tag<SPAN class="code-tag">&lt;/div&gt;</SPAN> <SPAN class="code-tag">&lt;s:action name=<SPAN class="code-quote">&quot;actionTagAction!default&quot;</SPAN> executeResult=<SPAN class="code-quote">&quot;false&quot;</SPAN> /&gt;</SPAN> <SPAN class="code-tag">&lt;s:property value=<SPAN class="code-quote">&quot;#attr.stringByAction&quot;</SPAN> /&gt;</SPAN> </PRE> </DIV></DIV> </DIV> </DIV> </DIV> <DIV class="footer"> Generated by <A href="http://www.atlassian.com/confluence/">Atlassian Confluence</A> (Version: 3.2 Build: 1810 Mar 16, 2010) <A href="http://could.it/autoexport/">Auto Export Plugin</A> (Version: 1.0.0-dkulp) </DIV> </BODY> </HTML>
zzh-simple-hr
Zlucene/doc/action.html
HTML
art
17,642
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <% String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; %> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <base href="<%=basePath%>"> <title>My JSP 'index.jsp' starting page</title> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="cache-control" content="no-cache"> <meta http-equiv="expires" content="0"> <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"> <meta http-equiv="description" content="This is my page"> <!-- <link rel="stylesheet" type="text/css" href="styles.css"> --> </head> <body> This is my JSP page. <br> </body> </html>
zzh-simple-hr
Zlucene/WebRoot/index.jsp
Java Server Pages
art
829
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <% String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; %> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <base href="<%=basePath%>"> <title>My JSP 'index.jsp' starting page</title> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="cache-control" content="no-cache"> <meta http-equiv="expires" content="0"> <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"> <meta http-equiv="description" content="This is my page"> <!-- <link rel="stylesheet" type="text/css" href="styles.css"> --> </head> <body> This is my JSP page. <br> </body> </html>
zzh-simple-hr
ZMybatis-generator/WebRoot/index.jsp
Java Server Pages
art
829
/* * Copyright (c) xlightweb.org, 2006 - 2010. All rights reserved. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * Please refer to the LGPL license at: http://www.gnu.org/copyleft/lesser.txt * The latest copy of this software may be found on http://www.xsocket.org/ */ package org.xsocket; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * The Resource annotation marks a resource that is required * by the application. * * E.g. * <pre> * class SmtpProtcolHandler implements IDataHandler, IConnectHandler { * * &#064Resource * private IServer srv; * * ... * * public boolean onConnect(INonBlockingConnection connection) throws IOException { * ... * } * * * * public boolean onData(INonBlockingConnection connection) throws IOException, BufferUnderflowException { * ... * * Executor workerpool = srv.getWorkerpool(); * ... * } * } * </pre> * * @author grro@xsocket.org */ @Target(ElementType.FIELD) @Retention(RetentionPolicy.RUNTIME) public @interface Resource { @SuppressWarnings("unchecked") Class type() default java.lang.Object.class; }
zzh-simple-hr
Zxsocket/src/org/xsocket/Resource.java
Java
art
2,063
/* * Copyright (c) xlightweb.org, 2006 - 2010. All rights reserved. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * Please refer to the LGPL license at: http://www.gnu.org/copyleft/lesser.txt * The latest copy of this software may be found on http://www.xlightweb.org/ */ package org.xsocket; /** * A destroyable resource * * @author grro@xlightweb.org */ public interface IDestroyable { /** * destroy this object */ void destroy(); }
zzh-simple-hr
Zxsocket/src/org/xsocket/IDestroyable.java
Java
art
1,212
/* * Copyright (c) xlightweb.org, 2006 - 2010. All rights reserved. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * Please refer to the LGPL license at: http://www.gnu.org/copyleft/lesser.txt * The latest copy of this software may be found on http://www.xsocket.org/ */ package org.xsocket; import java.io.ByteArrayOutputStream; import java.io.PrintWriter; import java.io.UnsupportedEncodingException; import java.nio.ByteBuffer; import java.nio.charset.CharacterCodingException; import java.nio.charset.Charset; import java.nio.charset.CharsetDecoder; import java.nio.charset.CharsetEncoder; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.TimeZone; /** * a data converter utilities class * * @author grro@xsocket.org */ public final class DataConverter { private static final Map<String, CharsetEncoder> encoders = new HashMap<String, CharsetEncoder>(); private static final Map<String, CharsetDecoder> decoders = new HashMap<String, CharsetDecoder>(); /** * converts the given byte size in a textual representation * * @param bytes the bytes to convert * @return the formated String representation of the bytes */ public static String toFormatedBytesSize(long bytes) { if (bytes > (5 * 1000 * 1000)) { return (bytes/1000000) + " MB"; } else if (bytes > (10 * 1000)) { return (bytes/1000) + " KB"; } else { return bytes + " bytes"; } } /** * converts the given time in a textual representation * * @param time the time to convert * @return the formated String representation of the date */ public static String toFormatedDate(long time) { return new SimpleDateFormat("MMM.dd HH:mm").format(new Date(time)); } /** * converts the given time in a RFC822 conform date representation * * @param time the time to convert * @return the formated String representation in a RFC822 conform date representation */ public static String toFormatedRFC822Date(long time) { return newRFC822DateFomat().format(time); } /** * converts a RFC822 date string into a date object * * @param rfc822DateString the rfc822 string * @return the date object */ public static Date toDate(String rfc822DateString) { try { return newRFC822DateFomat().parse(rfc822DateString); } catch (ParseException pe) { throw new RuntimeException(pe.toString()); } } private static SimpleDateFormat newRFC822DateFomat() { SimpleDateFormat df = new SimpleDateFormat("EEE', 'dd' 'MMM' 'yyyy' 'HH:mm:ss z", Locale.US); df.setCalendar(Calendar.getInstance(TimeZone.getTimeZone("GMT+0"))); df.setTimeZone(TimeZone.getTimeZone("GMT")); return df; } /** * converts the given duration in a textual representation * * @param duration the duration to convert * @return the formated String representation of the duration */ public static String toFormatedDuration(long duration) { if (duration < 5 * 1000) { return duration + " millis"; } else if (duration < (60 * 1000)) { return ((int) (duration / 1000)) + " sec"; } else if (duration < (60 * 60 * 1000)) { return ((int) (duration / (60* 1000))) + " min"; } else if (duration < (24 * 60 * 60 * 1000)) { return ((int) (duration / (60 * 60* 1000))) + " h"; } else { return ((long) (duration / (24 * 60 * 60* 1000))) + " d"; } } /** * converts the given String into a ByteBuffer * * @param s the String to convert * @param encoding the encoding to use * @return the String as ByteBuffer */ public static ByteBuffer toByteBuffer(String s, String encoding) { try { return ByteBuffer.wrap(s.getBytes(encoding)); } catch (UnsupportedEncodingException uee) { throw new RuntimeException(uee); } } /** * converts a stack into a String * * @param elements the stack trace elements * @return the stack as String */ public static String toString(StackTraceElement[] elements) { StringBuilder sb = new StringBuilder(); for (StackTraceElement element : elements) { sb.append(element.toString() + "\r\n"); } return sb.toString(); } /** * converts the given ByteBuffer into String by using * UTF-8 encoding * * @param buffer the ByteBuffer to convert * @return the ByteByuffer as String */ public static String toString(ByteBuffer buffer) throws UnsupportedEncodingException { return toString(buffer, "UTF-8"); } /** * converts the given ByteBuffer array into String by using * UTF-8 encoding * * @param buffer the ByteBuffer arrayto convert * @return the ByteByuffer as String */ public static String toString(ByteBuffer[] buffer) throws UnsupportedEncodingException { return toString(buffer, "UTF-8"); } /** * converts the given ByteBuffer into String repesentation * * @param buffer the ByteBuffer to convert * @param encoding the encoding to use * @return the ByteByuffer as String */ public static String toString(ByteBuffer buffer, String encoding) throws UnsupportedEncodingException { try { CharsetDecoder decoder = decoders.get(encoding); if (decoder == null) { Charset charset = Charset.forName(encoding); decoder = charset.newDecoder(); decoders.put(encoding, decoder); encoders.put(encoding, charset.newEncoder()); } return decoder.decode(buffer).toString(); } catch (CharacterCodingException cce) { RuntimeException re = new RuntimeException("coding exception for `" + encoding + "` occured: " + cce.toString(), cce); throw re; } } /** * converts the given ByteBuffer into a hex string * * @param buffer the ByteBuffer to convert * @return the hex string */ public static String toHexString(ByteBuffer buffer) { if (buffer == null) { return ""; } StringBuilder sb = new StringBuilder(); while (buffer.hasRemaining()) { String hex = Integer.toHexString(0x0100 + (buffer.get() & 0x00FF)).substring(1); sb.append((hex.length() < 2 ? "0" : "") + hex + " "); } return sb.toString(); } /** * converts the given list of ByteBuffers into a String by using UTF-8 encoding * * @param buffers the list of ByteBuffer to convert * @return the ByteByuffer as String */ public static String toString(List<ByteBuffer> buffers) throws UnsupportedEncodingException { return toString(buffers.toArray(new ByteBuffer[buffers.size()]), "UTF-8"); } /** * converts the given list of ByteBuffers into a String * * @param buffers the list of ByteBuffer to convert * @param encoding the encoding to use * @return the ByteByuffer as String */ public static String toString(List<ByteBuffer> buffers, String encoding) throws UnsupportedEncodingException { return toString(buffers.toArray(new ByteBuffer[buffers.size()]), encoding); } /** * converts the given array of ByteBuffers into String * * @param buffers the array of ByteBuffer to convert * @param encoding the encoding to use * @return the ByteByuffer as String */ public static String toString(ByteBuffer[] buffers, String encoding) throws UnsupportedEncodingException { return new String(toBytes(buffers), encoding); } /** * print the bytebuffer as limited string * * @param buffers the buffers to print * @param encoding the encoding to use * @param maxOutSize the max size to print * * @return the ByteBuffers as string representation */ public static String toString(ByteBuffer[] buffers, String encoding, int maxOutSize) throws UnsupportedEncodingException { String s = toString(buffers, encoding); if (s.length() > maxOutSize) { s = s.substring(0, maxOutSize) + " [output has been cut]"; } return s; } /** * merges a ByteBuffer array into a (direct) ByteBuffer * * @param buffers the ByteBuffer array to merge * @return the single ByteBuffer */ public static ByteBuffer toByteBuffer(ByteBuffer[] buffers) { if (buffers.length == 0) { return ByteBuffer.allocate(0); } if (buffers.length == 1) { return buffers[0]; } byte[] bytes = toBytes(buffers); return ByteBuffer.wrap(bytes); } /** * converts a single byte to a byte buffer * * @param b the byte * @return the ByteBuffer which contains the single byte */ public static ByteBuffer toByteBuffer(byte b) { ByteBuffer buffer = ByteBuffer.allocate(1).put(b); buffer.flip(); return buffer; } /** * converts a byte array to a byte buffer * * @param bytes the byte array * @return the ByteBuffer which contains the bytes */ public static ByteBuffer toByteBuffer(byte[] bytes) { return ByteBuffer.wrap(bytes); } /** * converts a byte array to a byte buffer * * @param bytes the bytes * @param offset the offset * @param length the length * @return the ByteBuffer which contains the single byte */ public static ByteBuffer toByteBuffer(byte[] bytes, int offset, int length) { return ByteBuffer.wrap(bytes, offset, length); } /** * converts a double to a byte buffer * * @param d the double * @return the ByteBuffer which contains the double */ public static ByteBuffer toByteBuffer(double d) { ByteBuffer buffer = ByteBuffer.allocate(8).putDouble(d); buffer.flip(); return buffer; } /** * converts a long to a byte buffer * * @param l the long * @return the ByteBuffer which contains the long */ public static ByteBuffer toByteBuffer(long l) { ByteBuffer buffer = ByteBuffer.allocate(8).putLong(l); buffer.flip(); return buffer; } /** * converts a short to a byte buffer * * @param s the short * @return the ByteBuffer which contains the short */ public static ByteBuffer toByteBuffer(short s) { ByteBuffer buffer = ByteBuffer.allocate(2).putShort(s); buffer.flip(); return buffer; } /** * converts a integer to a byte buffer * * @param i the int * @return the ByteBuffer which contains the int */ public static ByteBuffer toByteBuffer(int i) { ByteBuffer buffer = ByteBuffer.allocate(4).putInt(i); buffer.flip(); return buffer; } /** * copies a array of ByteBuffer based on offset length to a byte buffer array * * @param srcs the buffers * @param offset the offset * @param length the length * @return the ByteBuffer */ public static ByteBuffer[] toByteBuffers(ByteBuffer[] srcs, int offset, int length) { ByteBuffer[] bufs = new ByteBuffer[length]; System.arraycopy(srcs, offset, bufs, 0, length); return bufs; } /** * converts a list of ByteBuffer to a byte array * * @param buffers the ByteBuffer list to convert * @return the byte array */ public static byte[] toBytes(List<ByteBuffer> buffers) { return toBytes(buffers.toArray(new ByteBuffer[buffers.size()])); } /** * converts a ByteBuffer array to a byte array * * @param buffers the ByteBuffer array to convert * @return the byte array */ public static byte[] toBytes(ByteBuffer[] buffers) { if (buffers == null) { return new byte[0]; } if (buffers.length == 0) { return new byte[0]; } byte[][] bs = new byte[buffers.length][]; int size = 0; // transform ByteBuffer -> byte[] for (int i = 0; i < buffers.length; i++) { if (buffers[i] == null) { continue; } size += buffers[i].remaining(); bs[i] = toBytes(buffers[i]); } // merging byte arrays byte[] result = new byte[size]; int offset = 0; for (byte[] b : bs) { if (b != null) { System.arraycopy(b, 0, result, offset, b.length); offset += b.length; } } return result; } /** * converts a ByteBuffer into a byte array * * @param buffer the ByteBuffer to convert * @return the byte array */ public static byte[] toBytes(ByteBuffer buffer) { if (buffer == null) { return new byte[0]; } int savedPos = buffer.position(); int savedLimit = buffer.limit(); try { byte[] array = new byte[buffer.limit() - buffer.position()]; if (buffer.hasArray()) { int offset = buffer.arrayOffset() + savedPos; byte[] bufferArray = buffer.array(); System.arraycopy(bufferArray, offset, array, 0, array.length); return array; } else { buffer.get(array); return array; } } finally { buffer.position(savedPos); buffer.limit(savedLimit); } } /** * print the byte array as a hex string * * @param buffers the buffers to print * @param maxOutSize the max size to print * * @return the ByteBuffers as hex representation */ public static String toHexString(byte[] buffers, int maxOutSize) { return toHexString(new ByteBuffer[] { ByteBuffer.wrap(buffers) }, maxOutSize); } /** * print the byte buffer as a hex string * * @param buffers the buffers to print * @param maxOutSize the max size to print * * @return the ByteBuffers as hex representation */ public static String toHexString(List<ByteBuffer> buffers, int maxOutSize) { return toHexString(buffers.toArray(new ByteBuffer[buffers.size()]), maxOutSize); } /** * print the byte buffer as a hex string * * @param buffers the buffers to print * @param maxOutSize the max size to print * * @return the ByteBuffers as hex representation */ public static String toHexString(ByteBuffer[] buffers, int maxOutSize) { // first cut output if longer than max limit String postfix = ""; int size = 0; List<ByteBuffer> copies = new ArrayList<ByteBuffer>(); for (ByteBuffer buffer : buffers) { if (buffer != null) { ByteBuffer copy = buffer.duplicate(); if ((size + copy.limit()) > maxOutSize) { copy.limit(maxOutSize - size); copies.add(copy); postfix = " [...output has been cut]"; break; } else { copies.add(copy); } } } StringBuilder result = new StringBuilder(); for (ByteBuffer buffer : copies) { result.append(toHexString(buffer)); } result.append(postfix); return result.toString(); } /** * convert the ByteBuffer into a hex or text string (deping on content) * * @param buffer the buffers to print * @param maxOutSize the max size to print * @param encoding the encoding to use * @return the converted ByteBuffer */ public static String toTextOrHexString(ByteBuffer buffer, String encoding, int maxOutSize) { return toTextOrHexString(new ByteBuffer[] { buffer }, encoding, maxOutSize); } /** * convert the ByteBuffer array into a hex or text string (deping on content) * * @param buffers the buffers to print * @param maxOutSize the max size to print * @param encoding the encoding to use * @return the converted ByteBuffer */ public static String toTextOrHexString(ByteBuffer[] buffers, String encoding, int maxOutSize) { boolean hasNonPrintableChars = false; for (ByteBuffer buffer : buffers) { ByteBuffer copy = buffer.duplicate(); while (copy.hasRemaining()) { int i = copy.get(); if (i < 10) { hasNonPrintableChars = true; } } } if (hasNonPrintableChars) { return toHexString(buffers, maxOutSize); } else { try { return toString(buffers, encoding, maxOutSize); } catch (UnsupportedEncodingException use) { return toHexString(buffers, maxOutSize); } } } public static String toTextAndHexString(ByteBuffer[] buffers, String encoding, int maxOutSize) { StringBuilder sb = new StringBuilder(); sb.append(DataConverter.toHexString(buffers, 500)); sb.append("\n"); try { sb.append("[txt:] " + toString(buffers, "US-ASCII", 500)); } catch (UnsupportedEncodingException ue) { sb.append("[txt:] ... content not printable ..."); } return sb.toString(); } public static String toString(Throwable t) { if (t != null) { ByteArrayOutputStream bos = new ByteArrayOutputStream(); PrintWriter pw = new PrintWriter(bos); t.printStackTrace(pw); pw.flush(); return bos.toString(); } else { return null; } } }
zzh-simple-hr
Zxsocket/src/org/xsocket/DataConverter.java
Java
art
17,725
/* * Copyright (c) xlightweb.org, 2006 - 2010. All rights reserved. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * Please refer to the LGPL license at: http://www.gnu.org/copyleft/lesser.txt * The latest copy of this software may be found on http://www.xsocket.org/ */ package org.xsocket.connection; import java.io.IOException; import java.io.InputStreamReader; import java.io.LineNumberReader; import java.lang.management.ManagementFactory; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.net.SocketTimeoutException; import java.nio.BufferUnderflowException; import java.nio.ByteBuffer; import java.nio.channels.CancelledKeyException; import java.nio.channels.SelectionKey; import java.util.Collections; import java.util.LinkedHashMap; import java.util.Map; import java.util.Map.Entry; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import java.util.logging.Level; import java.util.logging.Logger; import javax.management.JMException; import javax.management.MBeanServer; import javax.management.ObjectName; import org.xsocket.DataConverter; import org.xsocket.Execution; import org.xsocket.ILifeCycle; import org.xsocket.Resource; /** * utility class * * @author grro@xsocket.org */ @SuppressWarnings("unchecked") public final class ConnectionUtils { private static final Logger LOG = Logger.getLogger(ConnectionUtils.class.getName()); public static final String DEFAULT_DOMAIN = "org.xsocket.connection"; public static final String SERVER_TRHREAD_PREFIX = "xServer"; private static final IoProvider IO_PROVIDER = new IoProvider(); private static final Map<Class, HandlerInfo> handlerInfoCache = newMapCache(25); private static final Map<Class, CompletionHandlerInfo> completionHandlerInfoCache = newMapCache(25); private static String implementationVersion; private static String implementationDate; private ConnectionUtils() { } static IoProvider getIoProvider() { return IO_PROVIDER; } /** * validate, based on a leading int length field. The length field will be removed * * @param connection the connection * @return the length * @throws IOException if an exception occurs * @throws BufferUnderflowException if not enough data is available */ public static int validateSufficientDatasizeByIntLengthField(INonBlockingConnection connection) throws IOException, BufferUnderflowException { connection.resetToReadMark(); connection.markReadPosition(); // check if enough data is available int length = connection.readInt(); if (connection.available() < length) { if (LOG.isLoggable(Level.FINE)) { LOG.fine("[" + connection.getId() + "]insufficient data. require " + length + " got " + connection.available()); } throw new BufferUnderflowException(); } else { // ...yes, remove mark connection.removeReadMark(); return length; } } /** * validate, based on a leading int length field, that enough data (getNumberOfAvailableBytes() >= length) is available. If not, * an BufferUnderflowException will been thrown. Example: * <pre> * //client * connection.setAutoflush(false); // avoid immediate write * ... * connection.markWritePosition(); // mark current position * connection.write((int) 0); // write "emtpy" length field * * // write and count written size * int written = connection.write(CMD_PUT); * written += ... * * connection.resetToWriteMark(); // return to length field position * connection.write(written); // and update it * connection.flush(); // flush (marker will be removed implicit) * ... * * * // server * class MyHandler implements IDataHandler { * ... * public boolean onData(INonBlockingConnection connection) throws IOException, BufferUnderflowException { * int length = ConnectionUtils.validateSufficientDatasizeByIntLengthField(connection); * * // enough data (BufferUnderflowException hasn`t been thrown) * byte cmd = connection.readByte(); * ... * } * } * </pre> * * @param connection the connection * @param removeLengthField true, if length field should be removed * @return the length * @throws IOException if an exception occurs * @throws BufferUnderflowException if not enough data is available */ public static int validateSufficientDatasizeByIntLengthField(INonBlockingConnection connection, boolean removeLengthField) throws IOException, BufferUnderflowException { connection.resetToReadMark(); connection.markReadPosition(); // check if enough data is available int length = connection.readInt(); if (connection.available() < length) { if (LOG.isLoggable(Level.FINE)) { LOG.fine("[" + connection.getId() + "]insufficient data. require " + length + " got " + connection.available()); } throw new BufferUnderflowException(); } else { // ...yes, remove mark if (!removeLengthField) { connection.resetToReadMark(); } connection.removeReadMark(); return length; } } /** * starts the given server within a dedicated thread. This method blocks * until the server is open. If the server hasn't been started within * 60 sec a timeout exception will been thrown. * * @param server the server to start * @throws SocketTimeoutException is the timeout has been reached */ public static void start(IServer server) throws SocketTimeoutException { start(server, 60); } /** * starts the given server within a dedicated thread. This method blocks * until the server is open. * * @param server the server to start * @param timeoutSec the maximum time to wait * * @throws SocketTimeoutException is the timeout has been reached */ public static void start(IServer server, int timeoutSec) throws SocketTimeoutException { final CountDownLatch startedSignal = new CountDownLatch(1); // create and add startup listener IServerListener startupListener = new IServerListener() { public void onInit() { startedSignal.countDown(); }; public void onDestroy() {}; }; server.addListener(startupListener); // start server within a dedicated thread Thread t = new Thread(server); t.setName("xServer"); t.start(); // wait until server has been started (onInit has been called) boolean isStarted = false; try { isStarted = startedSignal.await(timeoutSec, TimeUnit.SECONDS); } catch (InterruptedException ie) { // Restore the interrupted status Thread.currentThread().interrupt(); throw new RuntimeException("start signal doesn't occured. " + ie.toString()); } // timeout occurred? if (!isStarted) { throw new SocketTimeoutException("start timeout (" + DataConverter.toFormatedDuration((long) timeoutSec * 1000) + ")"); } // update thread name t.setName(SERVER_TRHREAD_PREFIX + ":" + server.getLocalPort()); // remove the startup listener server.removeListener(startupListener); } /** * (deep) copy of the byte buffer array * * @param buffers the byte buffer array * @return the copy */ public static ByteBuffer[] copy(ByteBuffer[] buffers) { if (buffers == null) { return null; } ByteBuffer[] copy = new ByteBuffer[buffers.length]; for (int i = 0; i < copy.length; i++) { copy[i] = copy(buffers[i]); } return copy; } /** * Returns a synchronized (thread-safe) connection backed by the specified connection. All methods * of the wapper are synchronized based on the underyling connection. * * @param con the connection to be "wrapped" in a synchronized connection * @return the synchronized (thread-safe) connection */ public static INonBlockingConnection synchronizedConnection(INonBlockingConnection con) { if (con instanceof SynchronizedNonBlockingConnection) { return con; } else { return new SynchronizedNonBlockingConnection(con); } } /** * Returns a synchronized (thread-safe) connection backed by the specified connection. All methods * of the wapper are synchronized based on the underyling connection. * * @param con the connection to be "wrapped" in a synchronized connection * @return the synchronized (thread-safe) connection */ public static IBlockingConnection synchronizedConnection(IBlockingConnection con) { if (con instanceof SynchronizedBlockingConnection) { return con; } else { return new SynchronizedBlockingConnection(con); } } /** * duplicates the byte buffer array * * @param buffers the byte buffer array * @return the copy */ static ByteBuffer[] duplicate(ByteBuffer[] buffers) { if (buffers == null) { return null; } ByteBuffer[] copy = new ByteBuffer[buffers.length]; for (int i = 0; i < copy.length; i++) { copy[i] = duplicate(buffers[i]); } return copy; } /** * duplicate the given buffer * * @param buffer the buffer to copy * @return the copy */ static ByteBuffer duplicate(ByteBuffer buffer) { if (buffer == null) { return null; } return buffer.duplicate(); } /** * copies the given buffer * * @param buffer the buffer to copy * @return the copy */ static ByteBuffer copy(ByteBuffer buffer) { if (buffer == null) { return null; } return ByteBuffer.wrap(DataConverter.toBytes(buffer)); } /** * creates and registers a mbean for the given server on the platform MBeanServer * * @param server the server to register * @return the objectName * @throws JMException if an jmx exception occurs */ public static ObjectName registerMBean(IServer server) throws JMException { return registerMBean(server, DEFAULT_DOMAIN); } /** * creates and registers a mbean for the given server on the platform MBeanServer * under the given domain name * * @param server the server to register * @param domain the domain name to use * @return the objectName * @throws JMException if an jmx exception occurs */ public static ObjectName registerMBean(IServer server, String domain) throws JMException { return registerMBean(server, domain, ManagementFactory.getPlatformMBeanServer()); } /** * creates and registers a mbean for the given server on the given MBeanServer * under the given domain name * * @param mbeanServer the mbean server to use * @param server the server to register * @param domain the domain name to use * @return the objectName * @throws JMException if an jmx exception occurs */ public static ObjectName registerMBean(IServer server, String domain, MBeanServer mbeanServer) { try { return ServerMBeanProxyFactory.createAndRegister(server, domain, mbeanServer); } catch (Exception e) { throw new RuntimeException(DataConverter.toString(e)); } } /** * creates and registers a mbean for the given connection pool on the platform MBeanServer * * @param pool the pool to register * @return the objectName * @throws JMException if an jmx exception occurs */ public static ObjectName registerMBean(IConnectionPool pool) throws JMException { return registerMBean(pool, DEFAULT_DOMAIN); } /** * creates and registers a mbean for the given connection pool on the platform MBeanServer * under the given domain name * * @param pool the pool to register * @param domain the domain name to use * @return the objectName * @throws JMException if an jmx exception occurs */ public static ObjectName registerMBean(IConnectionPool pool, String domain) throws JMException { return registerMBean(pool, domain, ManagementFactory.getPlatformMBeanServer()); } /** * creates and registers a mbean for the given pool on the given MBeanServer * under the given domain name * * @param mbeanServer the mbean server to use * @param pool the pool to register * @param domain the domain name to use * @return the objectName * @throws JMException if an jmx exception occurs */ public static ObjectName registerMBean(IConnectionPool pool, String domain, MBeanServer mbeanServer) throws JMException { return ConnectionPoolMBeanProxyFactory.createAndRegister(pool, domain, mbeanServer); } /** * * checks if the current version matchs with the required version by using the maven version style * * @param currentVersion the current version * @param requiredVersion the required version * @return true if the version matchs */ public static boolean matchVersion(String currentVersion, String requiredVersion) { try { requiredVersion = requiredVersion.trim(); currentVersion = currentVersion.split("-")[0].trim(); // remove qualifier // dedicated version notation? if (requiredVersion.indexOf(",") == -1) { requiredVersion = requiredVersion.split("-")[0].trim(); // remove qualifier return currentVersion.equalsIgnoreCase(requiredVersion); // .. no it is range notation } else { String[] range = requiredVersion.split(","); for (int i = 0; i < range.length; i++) { range[i] = range[i].trim(); } if (range.length < 2) { return false; } String requiredMinVersion = range[0].substring(1, range[0].length()).trim(); requiredMinVersion = requiredMinVersion.split("-")[0]; // remove qualifier String requiredMaxVersion = range[1].substring(0, range[1].length() - 1).trim(); requiredMaxVersion = requiredMaxVersion.split("-")[0]; // remove qualifier // check min version if (range[0].startsWith("[") && (!currentVersion.equalsIgnoreCase(requiredMinVersion) && !isGreater(currentVersion, requiredMinVersion))) { return false; } // check max version if (range[1].endsWith(")")) { return isSmaller(currentVersion, requiredMaxVersion); } else if (range[1].endsWith("]")) { return (currentVersion.equalsIgnoreCase(requiredMaxVersion)|| isSmaller(currentVersion, requiredMaxVersion)); } } return false; } catch (Throwable t) { return false; } } private static boolean isGreater(String version, String required) { String[] numsVersion = version.split("\\."); String[] numsRequired = required.split("\\."); for (int i = 0; i < numsVersion.length; i++) { int numVersion = Integer.parseInt(numsVersion[i]); if (numsRequired.length <= i) { return true; } int numRequired = Integer.parseInt(numsRequired[i]); if (numVersion > numRequired) { return true; } } return false; } private static boolean isSmaller(String version, String required) { String[] numsVersion = version.split("\\."); String[] numsRequired = required.split("\\."); for (int i = 0; i < numsVersion.length; i++) { int numVersion = Integer.parseInt(numsVersion[i]); if (numsRequired.length < i) { return true; } int numRequired = Integer.parseInt(numsRequired[i]); if (numVersion < numRequired) { return true; } } return false; } static IOException toIOException(Throwable t) { return toIOException(t.getMessage(), t); } static IOException toIOException(String text, Throwable t) { IOException ioe = new IOException(text); ioe.setStackTrace(t.getStackTrace()); return ioe; } /** * get the implementation version * * @return the implementation version */ public static String getImplementationVersion() { if (implementationVersion == null) { readVersionFile(); } return implementationVersion; } /** * get the implementation date * * @return the implementation date */ public static String getImplementationDate() { if (implementationDate== null) { readVersionFile(); } return implementationDate; } private static void readVersionFile() { implementationVersion = "<unknown>"; implementationDate = "<unknown>"; InputStreamReader isr = null; LineNumberReader lnr = null; try { isr = new InputStreamReader(ConnectionUtils.class.getResourceAsStream("/org/xsocket/version.txt")); if (isr != null) { lnr = new LineNumberReader(isr); String line = null; do { line = lnr.readLine(); if (line != null) { if (line.startsWith("Implementation-Version=")) { implementationVersion = line.substring("Implementation-Version=".length(), line.length()).trim(); } else if (line.startsWith("Implementation-Date=")) { implementationDate = line.substring("Implementation-Date=".length(), line.length()).trim(); } } } while (line != null); lnr.close(); } } catch (IOException ioe) { implementationVersion = "<unknown>"; implementationDate = "<unknown>"; if (LOG.isLoggable(Level.FINE)) { LOG.fine("could not read version file. reason: " + ioe.toString()); } } finally { try { if (lnr != null) { lnr.close(); } if (isr != null) { isr.close(); } } catch (IOException ioe) { if (LOG.isLoggable(Level.FINE)) { LOG.fine("exception occured by closing version.txt file stream " + ioe.toString()); } } } } static long computeSize(ByteBuffer[] buffers) { long size = 0; for (ByteBuffer byteBuffer : buffers) { size += byteBuffer.remaining(); } return size; } /** * creates a thread-safe new bound cache * * @param <T> the map value type * @param maxSize the max size of the cache * @return the new map cache */ public static <T> Map<Class, T> newMapCache(int maxSize) { return Collections.synchronizedMap(new MapCache<T>(maxSize)); } static void injectServerField(Server server, Object handler) { Field[] fields = handler.getClass().getDeclaredFields(); for (Field field : fields) { if (field.isAnnotationPresent(Resource.class)) { Resource res = field.getAnnotation(Resource.class); if ((field.getType() == IServer.class) || (res.type() == IServer.class) || (field.getType() == Server.class) || (res.type() == Server.class)) { try { field.setAccessible(true); field.set(handler, server); } catch (IllegalAccessException iae) { LOG.warning("could not inject server for attribute " + field.getName() + ". Reason " + DataConverter.toString(iae)); } } } } } /** * returns if current thread is dispatcher thread * * @return true, if current thread is a dispatcher thread */ public static boolean isDispatcherThread() { return Thread.currentThread().getName().startsWith(IoSocketDispatcher.DISPATCHER_PREFIX); } /** * returns if current thread is connector thread * @return true, if current thread is a connector thread */ static boolean isConnectorThread() { return Thread.currentThread().getName().startsWith(IoConnector.CONNECTOR_PREFIX); } static String printSelectionKey(SelectionKey key) { if (key != null) { try { int i = key.interestOps(); return printSelectionKeyValue(i) + " isValid=" + key.isValid(); } catch (CancelledKeyException cke) { return "canceled"; } } else { return "<null>"; } } static String printSelectionKeyValue(int ops) { StringBuilder sb = new StringBuilder(); if ((ops & SelectionKey.OP_ACCEPT) == SelectionKey.OP_ACCEPT) { sb.append("OP_ACCEPT, "); } if ((ops & SelectionKey.OP_CONNECT) == SelectionKey.OP_CONNECT) { sb.append("OP_CONNECT, "); } if ((ops & SelectionKey.OP_WRITE) == SelectionKey.OP_WRITE) { sb.append("OP_WRITE, "); } if ((ops & SelectionKey.OP_READ) == SelectionKey.OP_READ) { sb.append("OP_READ, "); } String txt = sb.toString(); txt = txt.trim(); if (txt.length() > 0) { txt = txt.substring(0, txt.length() - 1); } return txt + " (" + ops + ")"; } static IHandlerInfo getHandlerInfo(IHandler handler) { if (handler instanceof HandlerChain) { return ((HandlerChain) handler).getHandlerInfo(); } else { HandlerInfo handlerInfo = handlerInfoCache.get(handler.getClass()); if (handlerInfo == null) { handlerInfo = new HandlerInfo(handler); handlerInfoCache.put(handler.getClass(), handlerInfo); } return handlerInfo; } } static CompletionHandlerInfo getCompletionHandlerInfo(IWriteCompletionHandler handler) { CompletionHandlerInfo completionHandlerInfo = completionHandlerInfoCache.get(handler.getClass()); if (completionHandlerInfo == null) { completionHandlerInfo = new CompletionHandlerInfo(handler); completionHandlerInfoCache.put(handler.getClass(), completionHandlerInfo); } return completionHandlerInfo; } private static boolean isMethodThreaded(Class clazz, String methodname, boolean dflt, Class... paramClass) { try { Method meth = clazz.getMethod(methodname, paramClass); Execution execution = meth.getAnnotation(Execution.class); if (execution != null) { if(execution.value() == Execution.NONTHREADED) { return false; } else { return true; } } else { return dflt; } } catch (NoSuchMethodException nsme) { return dflt; } } private static boolean isHandlerMultithreaded(Object handler) { Execution execution = handler.getClass().getAnnotation(Execution.class); if (execution != null) { if(execution.value() == Execution.NONTHREADED) { return false; } else { return true; } } else { return true; } } private static final class MapCache<T> extends LinkedHashMap<Class , T> { private static final long serialVersionUID = 4513864504007457500L; private int maxSize = 0; MapCache(int maxSize) { this.maxSize = maxSize; } @Override protected boolean removeEldestEntry(Entry<Class, T> eldest) { return size() > maxSize; } } private static final class HandlerInfo implements IHandlerInfo { private boolean isConnectHandler = false; private boolean isDataHandler = false; private boolean isDisconnectHandler = false; private boolean isIdleTimeoutHandler = false; private boolean isConnectionTimeoutHandler = false; private boolean isConnectExceptionHandler = false; private boolean isLifeCycle = false; private boolean isConnectionScoped = false; private boolean isHandlerMultithreaded = false; private boolean isConnectHandlerMultithreaded = false; private boolean isDataHandlerMultithreaded = false; private boolean isDisconnectHandlerMultithreaded = false; private boolean isIdleTimeoutHandlerMultithreaded = false; private boolean isConnectionTimeoutHandlerMultithreaded = false; private boolean isConnectExceptionHandlerMultithreaded = false; private boolean isUnsynchronized = false; HandlerInfo(IHandler handler) { isConnectHandler = (handler instanceof IConnectHandler); isDataHandler = (handler instanceof IDataHandler); isDisconnectHandler = (handler instanceof IDisconnectHandler); isIdleTimeoutHandler = (handler instanceof IIdleTimeoutHandler); isConnectionTimeoutHandler = (handler instanceof IConnectionTimeoutHandler); isConnectExceptionHandler = (handler instanceof IConnectExceptionHandler); isLifeCycle = (handler instanceof ILifeCycle); isConnectionScoped = (handler instanceof IConnectionScoped); isUnsynchronized = (handler instanceof IUnsynchronized); isHandlerMultithreaded = ConnectionUtils.isHandlerMultithreaded(handler); if (isConnectHandler) { isConnectHandlerMultithreaded = isMethodThreaded(handler.getClass(), "onConnect", isHandlerMultithreaded, INonBlockingConnection.class); } if (isDataHandler) { isDataHandlerMultithreaded = isMethodThreaded(handler.getClass(), "onData", isHandlerMultithreaded, INonBlockingConnection.class); } if (isDisconnectHandler) { isDisconnectHandlerMultithreaded = isMethodThreaded(handler.getClass(), "onDisconnect", isHandlerMultithreaded, INonBlockingConnection.class); } if (isIdleTimeoutHandler) { isIdleTimeoutHandlerMultithreaded =isMethodThreaded(handler.getClass(), "onIdleTimeout", isHandlerMultithreaded, INonBlockingConnection.class); } if (isConnectionTimeoutHandler) { isConnectionTimeoutHandlerMultithreaded =isMethodThreaded(handler.getClass(), "onConnectionTimeout", isHandlerMultithreaded, INonBlockingConnection.class); } if (isConnectionTimeoutHandler) { isConnectHandlerMultithreaded = isMethodThreaded(handler.getClass(), "onConnectionTimeout", isHandlerMultithreaded, INonBlockingConnection.class); } if (isConnectExceptionHandler) { isConnectExceptionHandlerMultithreaded = isMethodThreaded(handler.getClass(), "onConnectException", isHandlerMultithreaded, INonBlockingConnection.class, IOException.class); } } public boolean isConnectHandler() { return isConnectHandler; } public boolean isDataHandler() { return isDataHandler; } public boolean isDisconnectHandler() { return isDisconnectHandler; } public boolean isIdleTimeoutHandler() { return isIdleTimeoutHandler; } public boolean isConnectionTimeoutHandler() { return isConnectionTimeoutHandler; } public boolean isLifeCycle() { return isLifeCycle; } public boolean isConnectionScoped() { return isConnectionScoped; } public boolean isConnectExceptionHandler() { return isConnectExceptionHandler; } public boolean isConnectExceptionHandlerMultithreaded() { return isConnectExceptionHandlerMultithreaded; } public boolean isUnsynchronized() { return isUnsynchronized; } public boolean isConnectHandlerMultithreaded() { return isConnectHandlerMultithreaded; } public boolean isDataHandlerMultithreaded() { return isDataHandlerMultithreaded; } public boolean isDisconnectHandlerMultithreaded() { return isDisconnectHandlerMultithreaded; } public boolean isIdleTimeoutHandlerMultithreaded() { return isIdleTimeoutHandlerMultithreaded; } public boolean isConnectionTimeoutHandlerMultithreaded() { return isConnectionTimeoutHandlerMultithreaded; } } static final class CompletionHandlerInfo { private boolean isOnWrittenMultithreaded = false; private boolean isOnExceptionMultithreaded = false; private boolean isUnsynchronized = false; public CompletionHandlerInfo(IWriteCompletionHandler handler) { isUnsynchronized = (handler instanceof IUnsynchronized); boolean isHandlerMultithreaded = ConnectionUtils.isHandlerMultithreaded(handler); isOnWrittenMultithreaded = isMethodThreaded(handler.getClass(), "onWritten", isHandlerMultithreaded, int.class); isOnExceptionMultithreaded = isMethodThreaded(handler.getClass(), "onException", isHandlerMultithreaded, IOException.class); } public boolean isUnsynchronized() { return isUnsynchronized; } public boolean isOnWrittenMultithreaded() { return isOnWrittenMultithreaded; } public boolean isOnExceptionMutlithreaded() { return isOnExceptionMultithreaded; } } }
zzh-simple-hr
Zxsocket/src/org/xsocket/connection/ConnectionUtils.java
Java
art
30,605
/* * Copyright (c) xlightweb.org, 2006 - 2010. All rights reserved. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * Please refer to the LGPL license at: http://www.gnu.org/copyleft/lesser.txt * The latest copy of this software may be found on http://www.xsocket.org/ */ package org.xsocket.connection; import java.io.IOException; /** * connector callback <br><br> * * @author grro@xsocket.org */ interface IIoConnectorCallback { /** * notifies that the connection has been established * * * @throws IOException if an exception occurs */ void onConnectionEstablished() throws IOException; /** * notfifies a connect error * * @param ioe the error */ void onConnectError(IOException ioe); /** * notifies that a connection timeout is occured * */ void onConnectTimeout(); }
zzh-simple-hr
Zxsocket/src/org/xsocket/connection/IIoConnectorCallback.java
Java
art
1,612
/* * Copyright (c) xlightweb.org, 2006 - 2010. All rights reserved. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * Please refer to the LGPL license at: http://www.gnu.org/copyleft/lesser.txt * The latest copy of this software may be found on http://www.xsocket.org/ */ package org.xsocket.connection; /** * marker interface * * @author grro@xlightweb.org */ interface IUnsynchronized { }
zzh-simple-hr
Zxsocket/src/org/xsocket/connection/IUnsynchronized.java
Java
art
1,143
/* * Copyright (c) xlightweb.org, 2006 - 2010. All rights reserved. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * Please refer to the LGPL license at: http://www.gnu.org/copyleft/lesser.txt * The latest copy of this software may be found on http://www.xsocket.org/ */ package org.xsocket.connection; import java.io.Closeable; import java.io.IOException; import java.net.InetSocketAddress; import java.nio.channels.SelectionKey; import java.nio.channels.Selector; import java.nio.channels.SocketChannel; import java.nio.channels.UnresolvedAddressException; import java.util.HashSet; import java.util.Iterator; import java.util.Set; import java.util.TimerTask; import java.util.concurrent.ConcurrentLinkedQueue; import java.util.concurrent.atomic.AtomicBoolean; import java.util.logging.Level; import java.util.logging.Logger; import org.xsocket.DataConverter; /** * The connector is responsible to connect a peer<br><br> * * @author grro@xsocket.org */ final class IoConnector extends MonitoredSelector implements Runnable, Closeable { private static final Logger LOG = Logger.getLogger(IoConnector.class.getName()); static final String CONNECTOR_PREFIX = "xConnector"; // is open flag private final AtomicBoolean isOpen = new AtomicBoolean(true); // timeout support private static final long DEFAULT_WATCHDOG_PERIOD_MILLIS = 1L * 60L * 1000L; private long watchDogPeriodMillis = DEFAULT_WATCHDOG_PERIOD_MILLIS; private final TimeoutCheckTask timeoutCheckTask = new TimeoutCheckTask(); private TimerTask watchDogTask; // selector private final Selector selector; private final String name; // queues private final ConcurrentLinkedQueue<Runnable> taskQueue = new ConcurrentLinkedQueue<Runnable>(); public IoConnector(String name) { this.name = CONNECTOR_PREFIX + "#" + name; try { selector = Selector.open(); } catch (IOException ioe) { String text = "exception occured while opening selector. Reason: " + ioe.toString(); LOG.severe(text); throw new RuntimeException(text, ioe); } } @Override void reinit() throws IOException { // reinit is not supported } /** * {@inheritDoc} */ public void run() { // set thread name and attach dispatcher id to thread Thread.currentThread().setName(name); if (LOG.isLoggable(Level.FINE)) { LOG.fine("selector " + name + " listening ..."); } int handledTasks = 0; while(isOpen.get()) { try { handledTasks = performTaskQueue(); int eventCount = selector.select(1000); if (eventCount > 0) { handleConnect(); } else { checkForLooping(handledTasks); } } catch (Exception e) { // eat and log exception LOG.warning("[" + Thread.currentThread().getName() + "] exception occured while processing. Reason " + DataConverter.toString(e)); } } try { selector.close(); } catch (Exception e) { // eat and log exception if (LOG.isLoggable(Level.FINE)) { LOG.fine("error occured by close selector within tearDown " + DataConverter.toString(e)); } } } @Override String printRegistered() { StringBuilder sb = new StringBuilder(); Set<SelectionKey> keys = new HashSet<SelectionKey>(); keys.addAll(selector.keys()); for (SelectionKey key : keys) { sb.append(ConnectionUtils.printSelectionKey(key) + "\r\n"); } return sb.toString(); } @Override int getNumRegisteredHandles() { return selector.keys().size(); } public void close() throws IOException { isOpen.set(false); } private int performTaskQueue() throws IOException { int handledTasks = 0; while (true) { Runnable task = taskQueue.poll(); if (task == null) { return handledTasks; } else { task.run(); handledTasks++; } } } private void handleConnect() { Set<SelectionKey> selectedEventKeys = selector.selectedKeys(); Iterator<SelectionKey> it = selectedEventKeys.iterator(); while (it.hasNext()) { SelectionKey eventKey = it.next(); it.remove(); RegisterTask registerTask = (RegisterTask) eventKey.attachment(); if (eventKey.isValid() && eventKey.isConnectable()) { try { boolean isConnected = ((SocketChannel) eventKey.channel()).finishConnect(); if (isConnected) { eventKey.cancel(); registerTask.callback.onConnectionEstablished(); } } catch (IOException ioe) { if (LOG.isLoggable(Level.FINE)) { LOG.fine("error occured by performing handling connect event " + ioe.toString()); } try { eventKey.channel().close(); } catch (IOException e) { if (LOG.isLoggable(Level.FINE)) { LOG.fine("error occured by closing channel " + e.toString()); } } registerTask.callback.onConnectError(ioe); } } } } public void connectAsync(SocketChannel channel, InetSocketAddress remoteAddress, long connectTimeoutMillis, IIoConnectorCallback callback) throws IOException { assert (channel.isOpen()); if (LOG.isLoggable(Level.FINE)) { LOG.fine("try to connect " + remoteAddress + " (connect timeout " + DataConverter.toFormatedDuration(connectTimeoutMillis) + ")"); } RegisterTask registerTask = new RegisterTask(channel, callback, remoteAddress, System.currentTimeMillis() + (long) connectTimeoutMillis); addToTaskQueue(registerTask); if (connectTimeoutMillis >= 1000) { updateTimeoutCheckPeriod(connectTimeoutMillis / 5); } else { updateTimeoutCheckPeriod(200); } } private void addToTaskQueue(Runnable task) { taskQueue.add(task); selector.wakeup(); } private final class RegisterTask implements Runnable { private final SocketChannel channel; private final IIoConnectorCallback callback; private final InetSocketAddress remoteAddress; private final long expireTime; private SelectionKey selectionKey; public RegisterTask(SocketChannel channel, IIoConnectorCallback callback, InetSocketAddress remoteAddress, long expireTime) throws IOException { this.channel = channel; this.callback = callback; this.remoteAddress = remoteAddress; this.expireTime = expireTime; channel.configureBlocking(false); } boolean isExpired(long currentTime) { return (currentTime > expireTime); } public void run() { selectionKey = null; try { selectionKey = channel.register(selector, SelectionKey.OP_CONNECT); selectionKey.attach(this); connect(channel, remoteAddress); } catch (IOException ioe) { if (LOG.isLoggable(Level.FINE)) { LOG.fine("error occured by registering channel " + channel + " reason " + ioe.toString()); } if (selectionKey != null) { selectionKey.cancel(); } try { channel.close(); } catch (IOException e) { if (LOG.isLoggable(Level.FINE)) { LOG.fine("error occured by closing channel " + e.toString()); } } callback.onConnectError(ioe); } } private void connect(SocketChannel channel, InetSocketAddress remoteAddress) throws IOException { try { channel.connect(remoteAddress); } catch (UnresolvedAddressException uae) { throw new IOException("connecting " + remoteAddress + " failed " + uae.toString()); } } } void updateTimeoutCheckPeriod(long requiredMinPeriod) { synchronized (this) { // if non watchdog task already exists and the required period is smaller than current one -> return if ((watchDogTask != null) && (watchDogPeriodMillis <= requiredMinPeriod)) { return; } // set watch dog period watchDogPeriodMillis = requiredMinPeriod; if (LOG.isLoggable(Level.FINE)) { LOG.fine("update watchdog period " + DataConverter.toFormatedDuration(watchDogPeriodMillis)); } // if watchdog task task already exits -> terminate it if (watchDogTask != null) { watchDogTask.cancel(); watchDogTask = null; } // create and run new watchdog task watchDogTask = new TimerTask() { public void run() { addToTaskQueue(timeoutCheckTask); } }; IoProvider.getTimer().schedule(watchDogTask, watchDogPeriodMillis, watchDogPeriodMillis); } } private final class TimeoutCheckTask implements Runnable { public void run() { try { long currentMillis = System.currentTimeMillis(); for (SelectionKey selectionKey : selector.keys()) { RegisterTask registerTask = (RegisterTask) selectionKey.attachment(); if (registerTask.isExpired(currentMillis)) { selectionKey.cancel(); registerTask.callback.onConnectTimeout(); } } } catch (Exception e) { // eat and log exception if (LOG.isLoggable(Level.FINE)) { LOG.fine("error occured by performing timeout check task " + e.toString()); } } } } }
zzh-simple-hr
Zxsocket/src/org/xsocket/connection/IoConnector.java
Java
art
12,207
/* * Copyright (c) xlightweb.org, 2006 - 2010. All rights reserved. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * Please refer to the LGPL license at: http://www.gnu.org/copyleft/lesser.txt * The latest copy of this software may be found on http://www.xsocket.org/ */ package org.xsocket.connection; /** * handler change listener * * @author grro@xsocket.org */ public interface IHandlerChangeListener { void onHanderReplaced(IHandler oldHandler, IHandler newHandler); }
zzh-simple-hr
Zxsocket/src/org/xsocket/connection/IHandlerChangeListener.java
Java
art
1,233
/* * Copyright (c) xlightweb.org, 2006 - 2010. All rights reserved. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * Please refer to the LGPL license at: http://www.gnu.org/copyleft/lesser.txt * The latest copy of this software may be found on http://www.xsocket.org/ */ package org.xsocket.connection; import java.io.IOException; /** * Handles the disconnecting of connections. <br> * The disconnecting of a connection occurs in three ways: * <ul> * <li> the client initiates the disconnect by closing the connection. In this case the * <code>onDisconnect</code> method will be called immediately * <li> the connection breaks or the client disconnects improperly and the underlying SocketChannel * detects the broken connection. In this case the <code>onDisconnect</code> method will be * called, when * the broken connection will be detected * <li> the connection breaks or the client disconnects improperly and the underlying SocketChannel * does not detect the broken connection. In this case the <code>onDisconnect</code> method * will only be called after a connection or idle timeout (see {@link IIdleTimeoutHandler}, {@link IConnectionTimeoutHandler}) * </ul> * * * @author grro@xsocket.org */ public interface IDisconnectHandler extends IHandler { /** * handles disconnecting of a connection * * * @param connection the <i>closed</i> connection * @return true for positive result of handling, false for negative result of handling * @throws IOException If some I/O error occurs. */ boolean onDisconnect(INonBlockingConnection connection) throws IOException; }
zzh-simple-hr
Zxsocket/src/org/xsocket/connection/IDisconnectHandler.java
Java
art
2,450
/* * Copyright (c) xlightweb.org, 2006 - 2010. All rights reserved. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * Please refer to the LGPL license at: http://www.gnu.org/copyleft/lesser.txt * The latest copy of this software may be found on http://www.xsocket.org/ */ package org.xsocket.connection; /** * marker interface * * @author grro@xsocket.org */ interface ISystemHandler extends IConnectHandler, IDataHandler, IDisconnectHandler, IConnectionTimeoutHandler, IIdleTimeoutHandler { }
zzh-simple-hr
Zxsocket/src/org/xsocket/connection/ISystemHandler.java
Java
art
1,247
/* * Copyright (c) xlightweb.org, 2006 - 2010. All rights reserved. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * Please refer to the LGPL license at: http://www.gnu.org/copyleft/lesser.txt * The latest copy of this software may be found on http://www.xsocket.org/ */ package org.xsocket.connection; import java.util.logging.Level; import java.util.logging.Logger; import javax.management.JMException; import javax.management.MBeanServer; import javax.management.ObjectName; import org.xsocket.ILifeCycle; import org.xsocket.IntrospectionBasedDynamicMBean; /** * A Mbean proxy factory, which creates and registers an appropriated mbean * for a given connction pool instance. * * <br><br><b>This class is for test purpose only, and will be modified or discarded in future versions</b> * * @author grro@xsocket.org */ final class ConnectionPoolMBeanProxyFactory { /** * creates and registers a mbean for the given pool on the given MBeanServer * under the given domain name * * @param pool the pool to register * @param domain the domain name to use * @param mbeanServer the mbean server to use * @throws JMException if an jmx exception occurs */ public static ObjectName createAndRegister(IConnectionPool pool, String domain, MBeanServer mbeanServer) throws JMException { ObjectName objectName = new ObjectName(domain + ".client:type=" + pool.getClass().getSimpleName() + ",name=" + pool.hashCode()); mbeanServer.registerMBean(new IntrospectionBasedDynamicMBean(pool), objectName); new ResourcePoolListener(pool, domain, mbeanServer); registerGlobalDispatcherPool(domain, mbeanServer); return objectName; } private static void registerGlobalDispatcherPool(String domain, MBeanServer mbeanServer) throws JMException { IoSocketDispatcherPool dispatcherPool = IoProvider.getGlobalClientDisptacherPool(); DispatcherPoolMBeanProxyFactory.createAndRegister(dispatcherPool, domain + ".client", mbeanServer); } private static void unregister(IConnectionPool pool, String domain, MBeanServer mbeanServer) throws JMException { ObjectName objectName = new ObjectName(domain + ".client:type=" + pool.getClass().getSimpleName() + ",name=" + pool.hashCode()); mbeanServer.unregisterMBean(objectName); } private static final class ResourcePoolListener implements ILifeCycle { private static final Logger LOG = Logger.getLogger(ResourcePoolListener.class.getName()); private final IConnectionPool pool; private final String domain; private final MBeanServer mbeanServer; ResourcePoolListener(IConnectionPool pool, String domain, MBeanServer mbeanServer) { this.pool = pool; this.domain = domain; this.mbeanServer = mbeanServer; pool.addListener(this); } public void onInit() { } public void onDestroy() { try { unregister(pool, domain, mbeanServer); } catch (Exception ex) { // eat and log exception if (LOG.isLoggable(Level.FINE)) { LOG.fine("error occured by deregistering the pool (domain=" + domain + "). reason: " + ex.toString()); } } } } }
zzh-simple-hr
Zxsocket/src/org/xsocket/connection/ConnectionPoolMBeanProxyFactory.java
Java
art
3,967
/* * Copyright (c) xlightweb.org, 2006 - 2010. All rights reserved. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * Please refer to the LGPL license at: http://www.gnu.org/copyleft/lesser.txt * The latest copy of this software may be found on http://www.xsocket.org/ */ package org.xsocket.connection; import java.io.IOException; /** * Handles connect exception. This handler is only supported on the client-side <br><br> * * E.g. * <pre> * Handler implements IConnectHandler, IConnectExceptionHandler, IDataHandler { * * public boolean onConnect(INonBlockingConnection connection) throws IOException, BufferUnderflowException, MaxReadSizeExceededException { * ... * } * * public boolean onConnectException(INonBlockingConnection connection, IOException ioe) throws IOException { * ... * } * * public boolean onData(INonBlockingConnection connection) throws IOException, BufferUnderflowException, ClosedChannelException, MaxReadSizeExceededException { * ... * } * * } * * * Handler hdl = new Handler(); * INonBlockingConnection con = new NonBlockingConnection(InetAddress.getByName(host), port, hdl, false, 500); * ... * <pre> * * * @author grro@xsocket.org */ public interface IConnectExceptionHandler extends IHandler { /** * handle a connect exception * * * @param connection the connection * @param ioe the exception * @return true for positive result of handling, false for negative result of handling * @throws IOException if some other I/O error occurs. Throwing this exception causes that the underlying connection will be closed. */ boolean onConnectException(INonBlockingConnection connection, IOException ioe) throws IOException; }
zzh-simple-hr
Zxsocket/src/org/xsocket/connection/IConnectExceptionHandler.java
Java
art
2,571
/* * Copyright (c) xlightweb.org, 2006 - 2010. All rights reserved. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * Please refer to the LGPL license at: http://www.gnu.org/copyleft/lesser.txt * The latest copy of this software may be found on http://www.xsocket.org/ */ package org.xsocket.connection; import java.io.IOException; import java.net.InetAddress; import java.nio.ByteBuffer; import java.nio.channels.ClosedChannelException; import java.util.ArrayList; import java.util.Arrays; import java.util.Map; /** * internal IoHandler * * * @author grro@xsocket.org */ abstract class IoChainableHandler { private IoChainableHandler successor; private IoChainableHandler previous; private IIoHandlerCallback callback; private final ArrayList<ByteBuffer> outQueue = new ArrayList<ByteBuffer>(); /** * constructor * * @param successor the sucessor */ public IoChainableHandler(IoChainableHandler successor) { setSuccessor(successor); } /** * "starts" the handler. Callback methods will not be called before * this method has been performed. * * * @param callbackHandler the callback handler */ public abstract void init(IIoHandlerCallback callbackHandler) throws IOException; /** * non-blocking close of the handler. <br><br> * * The implementation has to be threadsafe * * @param immediate if true, close the connection immediate. If false remaining * out buffers (collected by the writOutgoing methods) has * to written before closing * @throws IOException If some other I/O error occurs */ public abstract void close(boolean immediate) throws IOException; public void addToWriteQueue(ByteBuffer[] buffers) { synchronized (outQueue) { outQueue.addAll(Arrays.asList(buffers)); } } /** * {@inheritDoc} */ public void write() throws ClosedChannelException, IOException { synchronized (outQueue) { write(outQueue.toArray(new ByteBuffer[outQueue.size()])); outQueue.clear(); } } public abstract void write(ByteBuffer[] buffers) throws ClosedChannelException, IOException; public abstract void flush() throws IOException; /** * return the successor * * @return the successor */ public final IoChainableHandler getSuccessor() { return successor; } /** * set the successor * * @param successor the successor */ protected final void setSuccessor(IoChainableHandler successor) { this.successor = successor; if (successor != null) { successor.setPrevious(this); } } /** * set the previous IoHandler * @param previous the previous IoHandler */ protected final void setPrevious(IoChainableHandler previous) { this.previous = previous; } /** * get the previous IoHandler * @return the previous IoHandler */ protected final IoChainableHandler getPrevious() { return previous; } public boolean reset() { IoChainableHandler successor = getSuccessor(); if (successor != null) { return successor.reset(); } return true; } /** * {@inheritDoc} */ public boolean isSecure() { IoChainableHandler successor = getSuccessor(); if (successor != null) { return successor.isSecure(); } return false; } /** * get the local address of the underlying connection * * @return the local address of the underlying connection */ public InetAddress getLocalAddress() { return getSuccessor().getLocalAddress(); } public long getLastTimeReceivedMillis() { return getSuccessor().getLastTimeReceivedMillis(); } public long getLastTimeSendMillis() { return getSuccessor().getLastTimeSendMillis(); } public long getNumberOfReceivedBytes() { return getSuccessor().getNumberOfReceivedBytes(); } public long getNumberOfSendBytes() { return getSuccessor().getNumberOfSendBytes(); } public String getInfo() { return getSuccessor().getInfo(); } public String getRegisteredOpsInfo() { return getSuccessor().getRegisteredOpsInfo(); } /** * {@inheritDoc} */ public int getPendingWriteDataSize() { IoChainableHandler successor = getSuccessor(); if (successor != null) { return successor.getPendingWriteDataSize(); } else { return 0; } } /** * {@inheritDoc} */ public boolean hasDataToSend() { IoChainableHandler successor = getSuccessor(); if (successor != null) { return successor.hasDataToSend(); } else { return false; } } public void suspendRead() throws IOException { IoChainableHandler successor = getSuccessor(); if (successor != null) { successor.suspendRead(); } } public void resumeRead() throws IOException { IoChainableHandler successor = getSuccessor(); if (successor != null) { successor.resumeRead(); } } public boolean isReadSuspended() { IoChainableHandler successor = getSuccessor(); return successor.isReadSuspended() ; } public String getId() { return getSuccessor().getId(); } void setPreviousCallback(IIoHandlerCallback callback) { this.callback = callback; } IIoHandlerCallback getPreviousCallback() { return callback; } /** * get the local port of the underlying connection * * @return the local port of the underlying connection */ public int getLocalPort() { return getSuccessor().getLocalPort(); } /** * get the address of the remote host of the underlying connection * * @return the address of the remote host of the underlying connection */ public InetAddress getRemoteAddress() { return getSuccessor().getRemoteAddress(); } /** * get the port of the remote host of the underlying connection * * @return the port of the remote host of the underlying connection */ public int getRemotePort() { return getSuccessor().getRemotePort(); } /** * check, if handler is open * * @return true, if the handler is open */ public boolean isOpen() { return getSuccessor().isOpen(); } /** * {@inheritDoc} */ public void setIdleTimeoutMillis(long timeout) { getSuccessor().setIdleTimeoutMillis(timeout); } /** * sets the connection timout * * @param timeout the connection timeout */ public void setConnectionTimeoutMillis(long timeout) { getSuccessor().setConnectionTimeoutMillis(timeout); } /** * gets the connection timeout * * @return the connection timeout */ public long getConnectionTimeoutMillis() { return getSuccessor().getConnectionTimeoutMillis(); } /** * {@inheritDoc} */ public long getIdleTimeoutMillis() { return getSuccessor().getIdleTimeoutMillis(); } /** * {@inheritDoc} */ public long getRemainingMillisToConnectionTimeout() { return getSuccessor().getRemainingMillisToConnectionTimeout(); } /** * {@inheritDoc} */ public long getRemainingMillisToIdleTimeout() { return getSuccessor().getRemainingMillisToIdleTimeout(); } /** * {@inheritDoc} */ public Object getOption(String name) throws IOException { return getSuccessor().getOption(name); } /** * {@inheritDoc} */ @SuppressWarnings("unchecked") public Map<String, Class> getOptions() { return getSuccessor().getOptions(); } /** * {@inheritDoc} */ public void setOption(String name, Object value) throws IOException { getSuccessor().setOption(name, value); } /** * flush the outgoing buffers * * @throws IOException If some other I/O error occurs */ public abstract void hardFlush() throws IOException; @Override public String toString() { StringBuilder sb = new StringBuilder(this.getClass().getSimpleName() + "#" + hashCode()); IoChainableHandler ioHandler = this; while (ioHandler.getPrevious() != null) { ioHandler = ioHandler.getPrevious(); } StringBuilder forwardChain = new StringBuilder(""); while (ioHandler != null) { forwardChain.append(ioHandler.getClass().getSimpleName()); forwardChain.append(" > "); ioHandler = ioHandler.getSuccessor(); } forwardChain.trimToSize(); String fc = forwardChain.toString(); fc = fc.substring(0, fc.length() - 1); sb.append(" (forward chain: " + fc.trim() + ")"); return sb.toString(); } }
zzh-simple-hr
Zxsocket/src/org/xsocket/connection/IoChainableHandler.java
Java
art
9,236
/* * Copyright (c) xlightweb.org, 2006 - 2010. All rights reserved. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * Please refer to the LGPL license at: http://www.gnu.org/copyleft/lesser.txt * The latest copy of this software may be found on http://www.xsocket.org/ */ package org.xsocket.connection; /** * Dispatcher Pool Listener * * * @author grro@xsocket.org */ interface IIoDispatcherPoolListener { void onDispatcherAdded(IoSocketDispatcher dispatcher); void onDispatcherRemoved(IoSocketDispatcher dispatcher); }
zzh-simple-hr
Zxsocket/src/org/xsocket/connection/IIoDispatcherPoolListener.java
Java
art
1,287
/* * Copyright (c) xlightweb.org, 2006 - 2010. All rights reserved. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * Please refer to the LGPL license at: http://www.gnu.org/copyleft/lesser.txt * The latest copy of this software may be found on http://www.xsocket.org/ */ package org.xsocket.connection; import java.io.IOException; import java.net.InetAddress; import java.net.SocketTimeoutException; import java.nio.ByteBuffer; import java.nio.channels.ClosedChannelException; import java.nio.channels.SelectionKey; import java.nio.channels.SocketChannel; import java.text.SimpleDateFormat; import java.util.Collections; import java.util.Date; import java.util.HashMap; import java.util.Map; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicLong; import java.util.logging.Level; import java.util.logging.Logger; import org.xsocket.DataConverter; /** * Socket based io handler * * @author grro@xsocket.org */ final class IoSocketHandler extends IoChainableHandler { private static final Logger LOG = Logger.getLogger(IoSocketHandler.class.getName()); private static final int MAXSIZE_LOG_READ = 2000; @SuppressWarnings("unchecked") private static final Map<String, Class> SUPPORTED_OPTIONS = new HashMap<String, Class>(); static { SUPPORTED_OPTIONS.put(IoProvider.SO_RCVBUF, Integer.class); SUPPORTED_OPTIONS.put(IoProvider.SO_SNDBUF, Integer.class); SUPPORTED_OPTIONS.put(IoProvider.SO_REUSEADDR, Boolean.class); SUPPORTED_OPTIONS.put(IoProvider.SO_KEEPALIVE, Boolean.class); SUPPORTED_OPTIONS.put(IoProvider.TCP_NODELAY, Boolean.class); SUPPORTED_OPTIONS.put(IoProvider.SO_LINGER, Integer.class); } // flag private AtomicBoolean isConnected = new AtomicBoolean(false); private AtomicBoolean isLogicalClosed = new AtomicBoolean(false); private AtomicBoolean isDisconnect = new AtomicBoolean(false); // socket private final SocketChannel channel; // dispatcher handling private final SetWriteSelectionKeyTask setWriteSelectionKeyTask = new SetWriteSelectionKeyTask(); private IoSocketDispatcher dispatcher; // memory management private AbstractMemoryManager memoryManager; // receive & send queue private final IoQueue sendQueue = new IoQueue(); // write processor private final int soSendBufferSize; private IWriteTask pendingWriteTask = null; // id private final String id; // statistics private long openTime = -1; private long lastTimeReceivedMillis = System.currentTimeMillis(); private long lastTimeSentMillis = System.currentTimeMillis(); private final AtomicLong receivedBytes = new AtomicLong(0); private final AtomicLong sendBytes = new AtomicLong(0); private Exception lastException = null; /** * constructor * * @param channel the underlying channel * @param idLocalPrefix the id namespace prefix * @param dispatcher the dispatcher * @throws IOException If some other I/O error occurs */ IoSocketHandler(SocketChannel channel, IoSocketDispatcher dispatcher, String connectionId) throws IOException { super(null); assert (channel != null); this.channel = channel; openTime = System.currentTimeMillis(); channel.configureBlocking(false); this.dispatcher = dispatcher; this.id = connectionId; soSendBufferSize = channel.socket().getSendBufferSize(); } public void init(IIoHandlerCallback callbackHandler) throws IOException, SocketTimeoutException { setPreviousCallback(callbackHandler); dispatcher.register(this, SelectionKey.OP_READ); } /** * {@inheritDoc}b */ public boolean reset() { boolean reset = true; try { if (hasMoreDataToWrite()) { reset = false; } resumeRead(); return (reset && super.reset()); } catch (Exception e) { return false; } } void setMemoryManager(AbstractMemoryManager memoryManager) { this.memoryManager = memoryManager; } @Override public String getId() { return id; } /** * {@inheritDoc} */ @Override public int getPendingWriteDataSize() { return sendQueue.getSize() + super.getPendingWriteDataSize(); } /** * {@inheritDoc} */ @Override public boolean hasDataToSend() { return !sendQueue.isEmpty(); } /** * {@inheritDoc} */ public boolean isSecure() { return false; } /** * {@inheritDoc} */ public void setOption(String name, Object value) throws IOException { IoProvider.setOption(channel.socket(), name, value); } /** * {@inheritDoc} */ public Object getOption(String name) throws IOException { return IoProvider.getOption(channel.socket(), name); } /** * {@inheritDoc} */ @SuppressWarnings("unchecked") public Map<String, Class> getOptions() { return Collections.unmodifiableMap(SUPPORTED_OPTIONS); } /** * check if the underlying connection is timed out * * @param current the current time * @return true, if the connection has been timed out */ void checkConnection() { if (!channel.isOpen()) { getPreviousCallback().onConnectionAbnormalTerminated(); } } void onRegisteredEvent() throws IOException { boolean connected = isConnected.getAndSet(true); if(!connected) { try { getPreviousCallback().onConnect(); } catch (Exception e) { // eat and log exception if (LOG.isLoggable(Level.FINE)) { LOG.fine("error occured by performing onConnect " + id + " reason: " + e.toString()); } } } } void onRegisteredFailedEvent(IOException ioe) throws IOException { boolean connected = isConnected.getAndSet(true); if(!connected) { try { getPreviousCallback().onConnectException(ioe); } catch (Exception e) { // eat and log exception if (LOG.isLoggable(Level.FINE)) { LOG.fine("error occured by performing onConnectException " + id + " reason: " + e.toString()); } } } } long onReadableEvent() throws IOException { assert (Thread.currentThread().getName().startsWith(IoSocketDispatcher.DISPATCHER_PREFIX)) : "receiveQueue can only be accessed by the dispatcher thread"; long read = 0; // read data from socket ByteBuffer[] received = readSocket(); // handle the data if (received != null) { int size = 0; for (ByteBuffer byteBuffer : received) { size += byteBuffer.remaining(); } read += size; getPreviousCallback().onData(received, size); getPreviousCallback().onPostData(); } // increase preallocated read memory if not sufficient checkPreallocatedReadMemory(); return read; } void onWriteableEvent() throws IOException { assert (ConnectionUtils.isDispatcherThread()); try { // write data to socket writeSocket(); // more data to write? if (hasMoreDataToWrite()) { if (LOG.isLoggable(Level.FINE)) { LOG.fine("[" + id + "] remaining data to send. remaining (" + DataConverter.toFormatedBytesSize(sendQueue.getSize()) + ")"); } // .. no } else { // should channel be closed physically? if (isLogicalClosed.get()) { realClose(); // .. no, unset write selection key } else { boolean isKeyUpdated = dispatcher.unsetWriteSelectionKeyNow(this); if (isKeyUpdated) { dispatcher.flushKeyUpdate(); } } } } catch (Exception e) { e = ConnectionUtils.toIOException("erroroccurd by handling writeable event " + e.toString(), e); close(e); } } void onDeregisteredEvent() { try { channel.close(); } catch (Exception e) { if (LOG.isLoggable(Level.FINE)) { LOG.fine("error occured by closing socket handler " + e.toString()); } } if (!isDisconnect.getAndSet(true)) { try { getPreviousCallback().onDisconnect(); } catch (Exception e) { // eat and log exception if (LOG.isLoggable(Level.FINE)) { LOG.fine("[" + id + "] error occured by calling onDisconnect. reason: " + e.toString()); } } } } @Override public void write(ByteBuffer[] buffers) throws ClosedChannelException, IOException { addToWriteQueue(buffers); } void incSentBytes(int addSize) { lastTimeSentMillis = System.currentTimeMillis(); sendBytes.getAndAdd(addSize); } @Override public void flush() throws IOException { initializeWrite(true); } @Override public void addToWriteQueue(ByteBuffer[] buffers) { if (buffers != null) { sendQueue.append(buffers); } } private void initializeWrite(boolean isBypassingSelectorAllowed) throws IOException { // write within current thread if (isBypassingSelectorAllowed && dispatcher.isDispatcherInstanceThread()) { if (LOG.isLoggable(Level.FINE)) { LOG.fine("setWriteSelectionKeyNow (isDispatcherThread=true & bypassing=allowed)"); } boolean isKeyUpdated = dispatcher.setWriteSelectionKeyNow(this); if (isKeyUpdated) { dispatcher.flushKeyUpdate(); // required because it is running within dispatcher thread } // write with wake up } else { dispatcher.addKeyUpdateTask(setWriteSelectionKeyTask); } } private final class SetWriteSelectionKeyTask implements Runnable { public void run() { try { dispatcher.setWriteSelectionKeyNow(IoSocketHandler.this); } catch (Exception e) { e = ConnectionUtils.toIOException("Error by set write selection key now " + e.toString(), e); close(e); } } @Override public String toString() { return "setWriteSelectionKeyTask#" + super.toString(); } } void close(Exception e) { lastException = e; if (LOG.isLoggable(Level.FINE)) { LOG.fine("[" + getId() + "] performing close caused by exception " + DataConverter.toString(e)); } closeSilence(true); } /** * {@inheritDoc} */ public void close(boolean immediate) throws IOException { if (!hasMoreDataToWrite()) { immediate = true; } if (immediate || !isOpen()) { realClose(); } else { if (LOG.isLoggable(Level.FINE)) { LOG.fine("[" + getId() + "] postpone close until remaning data to write (" + sendQueue.getSize() + ") has been written"); } isLogicalClosed.set(true); initializeWrite(true); } } void closeSilence(boolean immediate) { try { close(immediate); } catch (IOException ioe) { if (LOG.isLoggable(Level.FINE)) { LOG.fine("error occured by closing " + getId() + " " + DataConverter.toString(ioe)); } } } private void realClose() { try { dispatcher.deregisterAndClose(this); } catch (Exception e) { // eat and log exception if (LOG.isLoggable(Level.FINE)) { LOG.fine("[" + id + "] error occured by deregistering/closing connection. reason: " + e.toString()); } } } /** * {@inheritDoc} */ public boolean isOpen() { return channel.isOpen(); } /** * return the underlying channel * * @return the underlying channel */ public SocketChannel getChannel() { return channel; } @Override public void suspendRead() throws IOException { dispatcher.suspendRead(this); } @Override public void resumeRead() throws IOException { dispatcher.resumeRead(this); } @Override public boolean isReadSuspended() { return !dispatcher.isReadable(this); } private ByteBuffer[] readSocket() throws IOException { assert (Thread.currentThread().getName().startsWith(IoSocketDispatcher.DISPATCHER_PREFIX)) : "receiveQueue can only be accessed by the dispatcher thread"; assert (memoryManager instanceof IoUnsynchronizedMemoryManager); if (isOpen()) { ByteBuffer[] received = null; int read = 0; lastTimeReceivedMillis = System.currentTimeMillis(); ByteBuffer readBuffer = memoryManager.acquireMemoryStandardSizeOrPreallocated(8192); int pos = readBuffer.position(); int limit = readBuffer.limit(); // read from channel try { read = channel.read(readBuffer); // exception occured while reading } catch (IOException ioe) { readBuffer.position(pos); readBuffer.limit(limit); memoryManager.recycleMemory(readBuffer); if (LOG.isLoggable(Level.FINE)) { LOG.fine("[" + id + "] error occured while reading channel: " + ioe.toString()); } throw ioe; } // handle read switch (read) { // end-of-stream has been reached -> throw an exception case -1: memoryManager.recycleMemory(readBuffer); try { channel.close(); // forces that isOpen() returns false } catch (IOException ignore) { } ExtendedClosedChannelException cce = new ExtendedClosedChannelException(getId() + " channel has reached end-of-stream (maybe closed by peer) (bytesReveived=" + receivedBytes + ", bytesSend=" + sendBytes + ", lastTimeReceived=" + lastTimeReceivedMillis + ", lastTimeSend=" + lastTimeSentMillis + ")"); if (LOG.isLoggable(Level.FINE)) { LOG.fine(cce.toString()); } throw cce; // no bytes read recycle read buffer and do nothing case 0: memoryManager.recycleMemory(readBuffer); return null; // bytes available (read < -1 is not handled) default: ByteBuffer dataBuffer = memoryManager.extractAndRecycleMemory(readBuffer, read); received = new ByteBuffer[1]; received[0] = dataBuffer; receivedBytes.addAndGet(read); if (LOG.isLoggable(Level.FINE)) { LOG.fine("[" + id + "] received (" + (dataBuffer.limit() - dataBuffer.position()) + " bytes, total " + receivedBytes.get() + " bytes): " + DataConverter.toTextOrHexString(new ByteBuffer[] {dataBuffer.duplicate() }, "UTF-8", MAXSIZE_LOG_READ)); } return received; } } else { return null; } } /** * check if preallocated read buffer size is sufficient. if not increase it */ private void checkPreallocatedReadMemory() throws IOException { assert (Thread.currentThread().getName().startsWith(IoSocketDispatcher.DISPATCHER_PREFIX)); memoryManager.preallocate(); } /** * writes the content of the send queue to the socket * * @return true, if more date is to send * * @throws IOException If some other I/O error occurs * @throws ClosedChannelException if the underlying channel is closed */ private void writeSocket() throws IOException { if (isOpen()) { IWriteTask writeTask = null; // does former task exists? if (pendingWriteTask != null) { writeTask = pendingWriteTask; pendingWriteTask = null; // no, create a new one } else { try { writeTask = TaskFactory.newTask(sendQueue, soSendBufferSize); } catch (Throwable t) { throw ConnectionUtils.toIOException(t); } } // perform write task IWriteResult result = writeTask.write(this); // is write task not complete? if (result.isAllWritten()) { sendQueue.removeLeased(); writeTask.release(); result.notifyWriteCallback(); } else { pendingWriteTask = writeTask; } } else { if (LOG.isLoggable(Level.FINEST)) { if (!isOpen()) { LOG.finest("[" + getId() + "] couldn't write send queue to socket because socket is already closed (sendQueuesize=" + DataConverter.toFormatedBytesSize(sendQueue.getSize()) + ")"); } if (sendQueue.isEmpty()) { LOG.finest("[" + getId() + "] nothing to write, because send queue is empty "); } } } } private boolean hasMoreDataToWrite() { return !sendQueue.isEmpty(); } /** * {@inheritDoc} */ @Override public InetAddress getLocalAddress() { return channel.socket().getLocalAddress(); } /** * {@inheritDoc} */ @Override public int getLocalPort() { return channel.socket().getLocalPort(); } /** * {@inheritDoc} */ @Override public InetAddress getRemoteAddress() { InetAddress addr = channel.socket().getInetAddress(); return addr; } /** * {@inheritDoc} */ @Override public int getRemotePort() { return channel.socket().getPort(); } public long getLastTimeReceivedMillis() { return lastTimeReceivedMillis; } public long getLastTimeSendMillis() { return lastTimeSentMillis; } public long getNumberOfReceivedBytes() { return receivedBytes.get(); } public long getNumberOfSendBytes() { return sendBytes.get(); } public String getInfo() { return "sendQueueSize=" + sendQueue.getSize() + ", countIncompleteWrites=" + " sendBytes=" + sendBytes+ ", reveivedBytes=" + receivedBytes + ", key=" + dispatcher.printSelectionKey(this) + ", isOpen=" + isOpen() + ", lastException=" + DataConverter.toString(lastException); } public String getRegisteredOpsInfo() { return dispatcher.getRegisteredOpsInfo(this); } /** * {@inheritDoc} */ public void hardFlush() throws IOException { flush(); } /** * {@inheritDoc} */ @Override public String toString() { try { SimpleDateFormat df = new SimpleDateFormat("HH:mm:ss,S"); StringBuilder sb = new StringBuilder(); sb.append("(" + channel.socket().getInetAddress().toString() + ":" + channel.socket().getPort() + " -> " + channel.socket().getLocalAddress().toString() + ":" + channel.socket().getLocalPort() + ")"); if (isReadSuspended()) { sb.append(" SUSPENDED"); } sb.append(" received=" + DataConverter.toFormatedBytesSize(receivedBytes.get()) + ", sent=" + DataConverter.toFormatedBytesSize(sendBytes.get()) + ", age=" + DataConverter.toFormatedDuration(System.currentTimeMillis() - openTime) + ", lastReceived=" + df.format(new Date(lastTimeReceivedMillis)) + ", sendQueueSize=" + DataConverter.toFormatedBytesSize(sendQueue.getSize()) + " [" + id + "]"); return sb.toString(); } catch (Throwable e) { return super.toString(); } } private static final class TaskFactory { private static final EmptyWriteTask EMPTY_WRITE_TASK = new EmptyWriteTask(); // performance optimization -> reuse write task private static ThreadLocal<MergingWriteTask> freeMergingWriteTaskThreadLocal = new ThreadLocal<MergingWriteTask>(); private static ThreadLocal<DirectWriteTask> freeDirectWriteTaskThreadLocal = new ThreadLocal<DirectWriteTask>(); static IWriteTask newTask(IoQueue sendQueue, int soSendBufferSize) { ByteBuffer[] buffersToWrite = sendQueue.lease(soSendBufferSize); // if no data to write? if (buffersToWrite == null) { return createEmptyWriteTask(); } // buffer array to write? if (buffersToWrite.length > 1) { MergingWriteTask mergingWriteTask = createMergingWriteTask(); boolean dataToWrite = mergingWriteTask.addData(buffersToWrite, soSendBufferSize); if (dataToWrite) { return mergingWriteTask; } else { return createEmptyWriteTask(); } // ... no, just a single byte buffer } else { DirectWriteTask directWriteTask = createDirectWriteTask(); boolean dataToWrite = directWriteTask.addData(buffersToWrite[0]); if (dataToWrite) { return directWriteTask; } else { return createEmptyWriteTask(); } } } static EmptyWriteTask createEmptyWriteTask() { return EMPTY_WRITE_TASK; } static MergingWriteTask createMergingWriteTask() { assert (ConnectionUtils.isDispatcherThread()); // does a free merging write task exists? MergingWriteTask meringWriteTask = freeMergingWriteTaskThreadLocal.get(); // ...yes, use it if (meringWriteTask != null) { freeMergingWriteTaskThreadLocal.remove(); // .. no creat a new one } else { meringWriteTask = new MergingWriteTask(); } return meringWriteTask; } static DirectWriteTask createDirectWriteTask() { assert (ConnectionUtils.isDispatcherThread()); // does a free direct write task exists? DirectWriteTask directWriteTask = freeDirectWriteTaskThreadLocal.get(); // ...yes, use it if (directWriteTask != null) { freeDirectWriteTaskThreadLocal.remove(); // .. no creat a new one } else { directWriteTask = new DirectWriteTask(); } return directWriteTask; } static void reuseWriteProcessor(MergingWriteTask meringWriteProcessor) { assert (ConnectionUtils.isDispatcherThread()); freeMergingWriteTaskThreadLocal.set(meringWriteProcessor); } static void reuseWriteProcessor(DirectWriteTask directWriteProcessor) { assert (ConnectionUtils.isDispatcherThread()); freeDirectWriteTaskThreadLocal.set(directWriteProcessor); } } private static interface IWriteTask { static final IncompleteWriteResult INCOMPLETE_WRITE_RESULT = new IncompleteWriteResult(); static final IWriteResult EMPTY_WRITE_RESULT = new EmptyWriteResult(); IWriteResult write(IoSocketHandler handler) throws IOException; void release(); } private static final class EmptyWriteTask implements IWriteTask { public IWriteResult write(IoSocketHandler handler) throws IOException { return EMPTY_WRITE_RESULT; } public void release() { } } private static final class MergingWriteTask implements IWriteTask { private boolean isReusable = true; private ByteBuffer writeBuffer; private int writeBufferSize = 8192; private ByteBuffer[] buffersToWrite = null; public MergingWriteTask() { allocateWriteBuffer(writeBufferSize); } private void allocateWriteBuffer(int size) { if (IoProvider.isUseDirectWriteBuffer()) { writeBuffer = ByteBuffer.allocateDirect(size); } else { writeBuffer = ByteBuffer.allocate(size); } } boolean addData(ByteBuffer[] buffers, int maxChunkSize) { buffersToWrite = buffers; if (writeBufferSize < maxChunkSize) { writeBufferSize = maxChunkSize; allocateWriteBuffer(writeBufferSize); } // copying data int countBuffers = buffersToWrite.length; for (int i = 0; i < countBuffers; i++) { writeBuffer.put(buffersToWrite[i]); } // nothing to write? if (writeBuffer.position() == 0) { return false; } writeBuffer.flip(); return true; } public IWriteResult write(IoSocketHandler handler) throws IOException { try { if (LOG.isLoggable(Level.FINE)) { LOG.fine("merging write task writing (" + (writeBuffer.limit() - writeBuffer.position()) + " bytes): " + DataConverter.toTextOrHexString(new ByteBuffer[] {writeBuffer.duplicate() }, "UTF-8", MAXSIZE_LOG_READ)); } int written = handler.channel.write(writeBuffer); handler.incSentBytes(written); if (LOG.isLoggable(Level.FINE)) { LOG.fine("[" + handler.getId() + "] written (" + written + " bytes)"); } if (!writeBuffer.hasRemaining()) { MultiBufferWriteResult writeResult = new MultiBufferWriteResult(handler, buffersToWrite); return writeResult; } else { return INCOMPLETE_WRITE_RESULT; } } catch(ClosedChannelException cce) { isReusable = false; return new ErrorWriteResult(handler, cce, buffersToWrite); } catch(final IOException ioe) { isReusable = false; return new ErrorWriteResult(handler, ioe, buffersToWrite); } catch(Throwable t) { isReusable = false; return new ErrorWriteResult(handler, ConnectionUtils.toIOException(t), buffersToWrite); } } public void release() { buffersToWrite = null; writeBuffer.clear(); if (isReusable) { TaskFactory.reuseWriteProcessor(this); } } } private static final class DirectWriteTask implements IWriteTask { private boolean isReusable = true; private ByteBuffer bufferToWrite = null; boolean addData(ByteBuffer bufferToWrite) { if (bufferToWrite.hasRemaining()) { this.bufferToWrite = bufferToWrite; return true; } else { return false; } } public IWriteResult write(IoSocketHandler handler) throws IOException { try { if (LOG.isLoggable(Level.FINE)) { LOG.fine("[" + handler.getId() + "] direct write task writing (" + (bufferToWrite.limit() - bufferToWrite.position()) + " bytes): " + DataConverter.toTextOrHexString(new ByteBuffer[] {bufferToWrite.duplicate() }, "UTF-8", MAXSIZE_LOG_READ)); } int written = handler.channel.write(bufferToWrite); handler.incSentBytes(written); if (LOG.isLoggable(Level.FINE)) { LOG.fine("[" + handler.getId() + "] written (" + written + " bytes)"); } if (!bufferToWrite.hasRemaining()) { SingleBufferWriteResult writeResult = new SingleBufferWriteResult(handler, bufferToWrite); return writeResult; } else { return INCOMPLETE_WRITE_RESULT; } } catch(ClosedChannelException cce) { isReusable = false; return new ErrorWriteResult(handler, cce, bufferToWrite); } catch(IOException ioe) { isReusable = false; return new ErrorWriteResult(handler, ioe, bufferToWrite); } catch(Throwable t) { isReusable = false; return new ErrorWriteResult(handler, ConnectionUtils.toIOException(t), bufferToWrite); } } public void release() { bufferToWrite = null; if (isReusable) { TaskFactory.reuseWriteProcessor(this); } } } private static interface IWriteResult { boolean isAllWritten(); void notifyWriteCallback(); } private static final class IncompleteWriteResult implements IWriteResult { public boolean isAllWritten() { return false; } public void notifyWriteCallback() { } } private static final class EmptyWriteResult implements IWriteResult { public boolean isAllWritten() { return true; } public void notifyWriteCallback() { } } private static final class ErrorWriteResult implements IWriteResult { private final IOException ioe; private final ByteBuffer[] buffers; private final IoSocketHandler handler; public ErrorWriteResult(IoSocketHandler handler, IOException ioe, ByteBuffer... buffers) { this.buffers = buffers; this.ioe = ioe; this.handler = handler; } public boolean isAllWritten() { return true; } public void notifyWriteCallback() { if (LOG.isLoggable(Level.FINE)) { LOG.fine("error " + ioe.toString() + " occured by writing " + ioe.toString()); } for (ByteBuffer buffer : buffers) { try { handler.getPreviousCallback().onWriteException(ioe, buffer); } catch (Exception e) { // eat and log exception if (LOG.isLoggable(Level.FINE)) { LOG.fine("error occured by notifying that write exception (" + e.toString() + ") has been occured " + e.toString()); } } } } } private static final class SingleBufferWriteResult implements IWriteResult { private final ByteBuffer buffer; private final IoSocketHandler handler; public SingleBufferWriteResult(IoSocketHandler handler, ByteBuffer buffer) { this.buffer = buffer; this.handler = handler; } public boolean isAllWritten() { return true; } public void notifyWriteCallback() { try { handler.getPreviousCallback().onWritten(buffer); } catch (Exception e) { // eat and log exception if (LOG.isLoggable(Level.FINE)) { LOG.fine("error occured by performing onWritten callback " + e.toString()); } } } } private static final class MultiBufferWriteResult implements IWriteResult { private final ByteBuffer[] buffers; private final IoSocketHandler handler; public MultiBufferWriteResult(IoSocketHandler handler, ByteBuffer... buffers) { this.buffers = buffers; this.handler = handler; } public boolean isAllWritten() { return true; } public void notifyWriteCallback() { for (ByteBuffer buffer : buffers) { try { handler.getPreviousCallback().onWritten(buffer); } catch (Exception e) { // eat and log exception if (LOG.isLoggable(Level.FINE)) { LOG.fine("error occured by performing onWritten callback " + e.toString()); } } } } } }
zzh-simple-hr
Zxsocket/src/org/xsocket/connection/IoSocketHandler.java
Java
art
32,888
/* * Copyright (c) xlightweb.org, 2006 - 2010. All rights reserved. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * Please refer to the LGPL license at: http://www.gnu.org/copyleft/lesser.txt * The latest copy of this software may be found on http://www.xsocket.org/ */ package org.xsocket.connection; import java.io.Closeable; import java.io.IOException; import java.util.ArrayList; import java.util.LinkedList; import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; /** * Dispacher pool * * * @author grro@xsocket.org */ final class IoSocketDispatcherPool implements Closeable { private static final Logger LOG = Logger.getLogger(IoSocketDispatcherPool.class.getName()); // open flag private volatile boolean isOpen = true; // name private final String name; // listeners private final ArrayList<IIoDispatcherPoolListener> listeners = new ArrayList<IIoDispatcherPoolListener>(); // memory management private int preallocationSize = IoProvider.DEFAULT_READ_BUFFER_PREALLOCATION_SIZE; private int bufferMinsize = IoProvider.DEFAULT_READ_BUFFER_MIN_SIZE; private boolean preallocation = true; private boolean useDirect = false; // dispatcher management private final LinkedList<IoSocketDispatcher> dispatchers = new LinkedList<IoSocketDispatcher>(); private int size; private int pointer; // statistics private long acceptedConnections; private long lastRequestAccpetedRate = System.currentTimeMillis(); public IoSocketDispatcherPool(String name, int size) { this.name = name; setDispatcherSize(size); } void addListener(IIoDispatcherPoolListener listener) { listeners.add(listener); } boolean removeListener(IIoDispatcherPoolListener listener) { return listeners.remove(listener); } IoSocketDispatcher nextDispatcher() throws IOException { return nextDispatcher(0); } private IoSocketDispatcher nextDispatcher(int currentTrial) throws IOException { IoSocketDispatcher dispatcher = null; if (!isOpen) { throw new IOException("dispatcher is already closed"); } try { // round-robin approach pointer++; if (pointer >= size) { // unsynchronized access of size is OK here (findbugs will criticize this) pointer = 0; } dispatcher = dispatchers.get(pointer); boolean peregistered = dispatcher.preRegister(); if (peregistered) { return dispatcher; } else { if (currentTrial < size) { return nextDispatcher(++currentTrial); } else { if (LOG.isLoggable(Level.FINE)) { LOG.fine("increasing dispatcher size because max handle size " + dispatcher.getMaxRegisterdHandles() + " of all " + size + " dispatcher reached"); } incDispatcherSize(); return nextDispatcher(0); } } } catch (Exception concurrentException) { if (isOpen) { if (currentTrial < 3) { dispatcher = nextDispatcher(++currentTrial); } else { throw new IOException(concurrentException.toString()); } } } return dispatcher; } private synchronized void updateDispatcher() { if (isOpen) { synchronized (dispatchers) { int currentRunning = dispatchers.size(); if (currentRunning != size) { if (currentRunning > size) { for (int i = size; i < currentRunning; i++) { IoSocketDispatcher dispatcher = dispatchers.getLast(); dispatchers.remove(dispatcher); try { dispatcher.close(); } catch (IOException ioe) { if (LOG.isLoggable(Level.FINE)) { LOG.fine("error occured by closing the dispatcher " + dispatcher + ". reason " + ioe.toString()); } } for (IIoDispatcherPoolListener listener : listeners) { listener.onDispatcherRemoved(dispatcher); } } } else if ( currentRunning < size) { for (int i = currentRunning; i < size; i++) { IoUnsynchronizedMemoryManager memoryManager = null; if (preallocation) { memoryManager = IoUnsynchronizedMemoryManager.createPreallocatedMemoryManager(preallocationSize, bufferMinsize, useDirect); } else { memoryManager = IoUnsynchronizedMemoryManager.createNonPreallocatedMemoryManager(useDirect); } IoSocketDispatcher dispatcher = new IoSocketDispatcher(memoryManager, name + "#" + i); dispatchers.addLast(dispatcher); Thread t = new Thread(dispatcher); t.setDaemon(true); t.start(); for (IIoDispatcherPoolListener listener : listeners) { listener.onDispatcherAdded(dispatcher); } } } } IoSocketDispatcher[] connectionDispatchers = new IoSocketDispatcher[dispatchers.size()]; for (int i = 0; i < connectionDispatchers.length; i++) { connectionDispatchers[i] = dispatchers.get(i); } } } } /** * {@inheritDoc} */ public void close() throws IOException { if (isOpen) { isOpen = false; shutdownDispatcher(); } } /** * shutdown the pool * */ private void shutdownDispatcher() { if (LOG.isLoggable(Level.FINER)) { LOG.fine("terminate dispatchers"); } synchronized (dispatchers) { for (IoSocketDispatcher dispatcher : dispatchers) { try { dispatcher.close(); for (IIoDispatcherPoolListener listener : listeners) { listener.onDispatcherRemoved(dispatcher); } } catch (IOException ioe) { if (LOG.isLoggable(Level.FINE)) { LOG.fine("error occured by closing the dispatcher " + dispatcher + ". reason " + ioe.toString()); } } } } dispatchers.clear(); } int getNumRegisteredHandles() { int num = 0; for (IoSocketDispatcher dispatcher : getDispatchers()) { num += dispatcher.getNumRegisteredHandles(); } return num; } int getRoughNumRegisteredHandles() { int num = 0; for (IoSocketDispatcher dispatcher : getDispatchers()) { num += dispatcher.getRoughNumRegisteredHandles(); } return num; } public List<String> getOpenConntionInfos() { List<String> result = new ArrayList<String>(); for (IoSocketDispatcher dispatcher : getDispatchers()) { for (IoSocketHandler handler : dispatcher.getRegistered()) { result.add(handler.toString()); } } return result; } @SuppressWarnings("unchecked") List<IoSocketDispatcher> getDispatchers() { List<IoSocketDispatcher> result = null; synchronized (dispatchers) { result = (List<IoSocketDispatcher>) dispatchers.clone(); } return result; } synchronized void setDispatcherSize(int size) { this.size = size; updateDispatcher(); } synchronized int getDispatcherSize() { return size; } synchronized void incDispatcherSize() { setDispatcherSize(getDispatcherSize() + 1); } boolean getReceiveBufferIsDirect() { return useDirect; } void setReceiveBufferIsDirect(boolean isDirect) { this.useDirect = isDirect; for (IoSocketDispatcher dispatcher: dispatchers) { dispatcher.setReceiveBufferIsDirect(isDirect); } } boolean isReceiveBufferPreallocationMode() { return preallocation; } void setReceiveBufferPreallocationMode(boolean mode) { this.preallocation = mode; synchronized (dispatchers) { for (IoSocketDispatcher dispatcher: dispatchers) { dispatcher.setReceiveBufferPreallocationMode(mode); } } } void setReceiveBufferPreallocatedMinSize(Integer minSize) { this.bufferMinsize = minSize; synchronized (dispatchers) { for (IoSocketDispatcher dispatcher: dispatchers) { dispatcher.setReceiveBufferPreallocatedMinSize(minSize); } } } Integer getReceiveBufferPreallocatedMinSize() { return bufferMinsize; } /** * get the size of the preallocation buffer, * for reading incoming data * * @return preallocation buffer size */ Integer getReceiveBufferPreallocationSize() { return preallocationSize; } /** * set the size of the preallocation buffer, * for reading incoming data * * @param size the preallocation buffer size */ void setReceiveBufferPreallocationSize(int size) { preallocationSize = size; for (IoSocketDispatcher dispatcher: dispatchers) { dispatcher.setReceiveBufferPreallocatedSize(size); } } double getAcceptedRateCountPerSec() { double rate = 0; long elapsed = System.currentTimeMillis() - lastRequestAccpetedRate; if (acceptedConnections == 0) { rate = 0; } else if (elapsed == 0) { rate = Integer.MAX_VALUE; } else { rate = (((double) (acceptedConnections * 1000)) / elapsed); } lastRequestAccpetedRate = System.currentTimeMillis(); acceptedConnections = 0; return rate; } long getSendRateBytesPerSec() { long rate = 0; for (IoSocketDispatcher dispatcher : dispatchers) { rate += dispatcher.getSendRateBytesPerSec(); } return rate; } long getReceiveRateBytesPerSec() { long rate = 0; for (IoSocketDispatcher dispatcher : dispatchers) { rate += dispatcher.getReceiveRateBytesPerSec(); } return rate; } @SuppressWarnings("unchecked") long getNumberOfConnectionTimeouts() { long timeouts = 0; LinkedList<IoSocketDispatcher> copy = null; synchronized (dispatchers) { copy = (LinkedList<IoSocketDispatcher>) dispatchers.clone(); } for (IoSocketDispatcher dispatcher : copy) { timeouts += dispatcher.getCountConnectionTimeout(); } return timeouts; } @SuppressWarnings("unchecked") public long getNumberOfIdleTimeouts() { long timeouts = 0; LinkedList<IoSocketDispatcher> copy = null; synchronized (dispatchers) { copy = (LinkedList<IoSocketDispatcher>) dispatchers.clone(); } for (IoSocketDispatcher dispatcher : copy) { timeouts += dispatcher.getCountIdleTimeout(); } return timeouts; } }
zzh-simple-hr
Zxsocket/src/org/xsocket/connection/IoSocketDispatcherPool.java
Java
art
11,247
/* * Copyright (c) xlightweb.org, 2006 - 2010. All rights reserved. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * Please refer to the LGPL license at: http://www.gnu.org/copyleft/lesser.txt * The latest copy of this software may be found on http://www.xsocket.org/ */ package org.xsocket.connection; import java.io.Closeable; import java.io.IOException; import java.nio.channels.ClosedChannelException; import java.nio.channels.SelectionKey; import java.nio.channels.Selector; import java.util.HashSet; import java.util.Iterator; import java.util.Set; import java.util.concurrent.ConcurrentLinkedQueue; import java.util.concurrent.atomic.AtomicBoolean; import java.util.logging.Level; import java.util.logging.Logger; import org.xsocket.DataConverter; /** * Implementation of the {@link IDispatcher} * * <br/><br/><b>This is a xSocket internal class and subject to change</b> * * @author grro@xsocket.org */ final class IoSocketDispatcher extends MonitoredSelector implements Runnable, Closeable { private static final Logger LOG = Logger.getLogger(IoSocketDispatcher.class.getName()); static final String DISPATCHER_PREFIX = "xDispatcher"; // queues private final ConcurrentLinkedQueue<Runnable> registerQueue = new ConcurrentLinkedQueue<Runnable>(); private final ConcurrentLinkedQueue<IoSocketHandler> deregisterQueue = new ConcurrentLinkedQueue<IoSocketHandler>(); private final ConcurrentLinkedQueue<Runnable> keyUpdateQueue = new ConcurrentLinkedQueue<Runnable>(); // id private static int nextId = 1; private final String name; private final int id; private final static ThreadLocal<Integer> THREADBOUND_ID = new ThreadLocal<Integer>(); private final static ThreadLocal<Integer> DIRECT_CALL_COUNTER = new ThreadLocal<Integer>(); // flags private final AtomicBoolean isOpen = new AtomicBoolean(true); // connection handling private static final Integer MAX_HANDLES = IoProvider.getMaxHandles(); private int roughNumOfRegisteredHandles; private Selector selector; // memory management private final AbstractMemoryManager memoryManager; // wakeup private long lastTimeWokeUp = System.currentTimeMillis(); // statistics private long statisticsStartTime = System.currentTimeMillis(); private long countIdleTimeouts = 0; private long countConnectionTimeouts = 0; private long handledRegistractions = 0; private long handledReads = 0; private long handledWrites = 0; private long lastRequestReceiveRate = System.currentTimeMillis(); private long lastRequestSendRate = System.currentTimeMillis(); private long receivedBytes = 0; private long sentBytes = 0; private long countUnregisteredWrite = 0; public IoSocketDispatcher(AbstractMemoryManager memoryManager, String name) { this.memoryManager = memoryManager; this.name = IoSocketDispatcher.DISPATCHER_PREFIX + name; synchronized (this) { id = nextId; nextId++; } try { selector = Selector.open(); } catch (IOException ioe) { String text = "exception occured while opening selector. Reason: " + ioe.toString(); LOG.severe(text); throw new RuntimeException(text, ioe); } if (LOG.isLoggable(Level.FINE)) { LOG.fine("dispatcher " + this.hashCode() + " has been closed"); } } String getName() { return name; } int getId() { return id; } private static Integer getThreadBoundId() { return THREADBOUND_ID.get(); } long getCountUnregisteredWrite() { return countUnregisteredWrite; } Integer getMaxRegisterdHandles() { return MAX_HANDLES; } @Override int getNumRegisteredHandles() { int hdls = selector.keys().size(); roughNumOfRegisteredHandles = hdls; return hdls; } int getRoughNumRegisteredHandles() { return roughNumOfRegisteredHandles; } @Override void reinit() throws IOException { // save old selector Selector oldSelector = selector; // retrieve all keys HashSet<SelectionKey> keys = new HashSet<SelectionKey>(); keys.addAll(oldSelector.keys()); // create new selector selector = Selector.open(); // "move" all sockets to the new selector for (SelectionKey key : keys) { // get info int ops = key.interestOps(); IoSocketHandler socketHandler = (IoSocketHandler) key.attachment(); // cancel old key key.cancel(); try { socketHandler.getChannel().register(selector, ops, socketHandler); } catch (IOException ioe) { LOG.warning("could not reinit " + socketHandler.toString() + " " + DataConverter.toString(ioe)); } } // close old selector oldSelector.close(); if (LOG.isLoggable(Level.FINE)) { LOG.fine("selector has been reinitialized"); } } /** * {@inheritDoc} */ public void run() { // set thread name and attach dispatcher id to thread Thread.currentThread().setName(name); THREADBOUND_ID.set(id); DIRECT_CALL_COUNTER.set(0); if (LOG.isLoggable(Level.FINE)) { LOG.fine("selector " + name + " listening ..."); } int handledTasks = 0; while(isOpen.get()) { try { int eventCount = selector.select(5000); handledTasks = performRegisterHandlerTasks(); handledTasks += performKeyUpdateTasks(); if (eventCount > 0) { handleReadWriteKeys(); } handledTasks += performDeregisterHandlerTasks(); checkForLooping(eventCount + handledTasks, lastTimeWokeUp); } catch (Throwable e) { // eat and log exception if (LOG.isLoggable(Level.FINE)) { LOG.fine("[" + Thread.currentThread().getName() + "] exception occured while processing. Reason " + DataConverter.toString(e)); } } } for (IoSocketHandler socketHandler : getRegistered()) { socketHandler.onDeregisteredEvent(); } try { selector.close(); } catch (Exception e) { // eat and log exception if (LOG.isLoggable(Level.FINE)) { LOG.fine("error occured by close selector within tearDown " + DataConverter.toString(e)); } } } private void handleReadWriteKeys() { Set<SelectionKey> selectedEventKeys = selector.selectedKeys(); Iterator<SelectionKey> it = selectedEventKeys.iterator(); // handle read & write while (it.hasNext()) { try { SelectionKey eventKey = it.next(); it.remove(); IoSocketHandler socketHandler = (IoSocketHandler) eventKey.attachment(); try { // read data if (eventKey.isValid() && eventKey.isReadable()) { onReadableEvent(socketHandler); } // write data if (eventKey.isValid() && eventKey.isWritable()) { onWriteableEvent(socketHandler); } } catch (Exception e) { socketHandler.close(e); } } catch (Exception e) { // eat and log exception if (LOG.isLoggable(Level.FINE)) { LOG.fine("error occured by handling selection keys + " + e.toString()); } } } } private void onReadableEvent(IoSocketHandler socketHandler) { try { long read = socketHandler.onReadableEvent(); receivedBytes += read; handledReads++; } catch (Exception t) { SelectionKey key = getSelectionKey(socketHandler); if ((key != null) && key.isValid()) { key.cancel(); } if (LOG.isLoggable(Level.FINE)) { LOG.fine("error occured by handling readable event " + DataConverter.toString(t)); } socketHandler.closeSilence(true); } } private void onWriteableEvent(IoSocketHandler socketHandler) { try { socketHandler.onWriteableEvent(); handledWrites++; } catch (ClosedChannelException ce) { IOException ioe = ConnectionUtils.toIOException("error occured by handling readable event. reason closed channel exception " + ce.toString(), ce); socketHandler.close(ioe); } catch (Exception e) { e = ConnectionUtils.toIOException("error occured by handling readable event. reason " + e.toString(), e); socketHandler.close(e); } } private void wakeUp() { lastTimeWokeUp = System.currentTimeMillis(); selector.wakeup(); } boolean preRegister() { // inc rough num of registered handles roughNumOfRegisteredHandles++; // check if max size reached if ((MAX_HANDLES != null) && (roughNumOfRegisteredHandles >= MAX_HANDLES) && // rough check (getNumRegisteredHandles() >= MAX_HANDLES)) { // accurate check return false; } else { return true; } } /** * {@inheritDoc} */ public boolean register(IoSocketHandler socketHandler, int ops) throws IOException { assert (!socketHandler.getChannel().isBlocking()); socketHandler.setMemoryManager(memoryManager); if (isDispatcherInstanceThread()) { registerHandlerNow(socketHandler, ops); } else { if (LOG.isLoggable(Level.FINE)) { LOG.fine("[" + socketHandler.getId() + "] add new connection to register task queue"); } registerQueue.add(new RegisterTask(socketHandler, ops)); wakeUp(); } return true; } private final class RegisterTask implements Runnable { private final IoSocketHandler socketHandler; private final int ops; public RegisterTask(IoSocketHandler socketHandler, int ops) { this.socketHandler = socketHandler; this.ops = ops; } public void run() { try { registerHandlerNow(socketHandler, ops); } catch (IOException ioe) { ioe = ConnectionUtils.toIOException("error occured by registering handler " + socketHandler.getId() + " " + ioe.toString(), ioe); socketHandler.close(ioe); } } } /** * {@inheritDoc} */ public void deregisterAndClose(IoSocketHandler handler) { if (isOpen.get()) { if (isDispatcherInstanceThread()) { deregisterAndCloseNow(handler); } else { deregisterQueue.add(handler); wakeUp(); } } else { handler.onDeregisteredEvent(); } } private int performDeregisterHandlerTasks() { int handledTasks = 0; while (true) { IoSocketHandler socketHandler = deregisterQueue.poll(); if (socketHandler == null) { return handledTasks; } else { deregisterAndCloseNow(socketHandler); handledTasks++; } } } private void deregisterAndCloseNow(IoSocketHandler socketHandler) { try { SelectionKey key = socketHandler.getChannel().keyFor(selector); if ((key != null) && key.isValid()) { key.cancel(); if (roughNumOfRegisteredHandles > 0) { roughNumOfRegisteredHandles--; } } } catch (Exception e) { if (LOG.isLoggable(Level.FINE)) { LOG.fine("error occured by deregistering socket handler " + e.toString()); } } socketHandler.onDeregisteredEvent(); } public void addKeyUpdateTask(Runnable task) { keyUpdateQueue.add(task); wakeUp(); } public void flushKeyUpdate() { wakeUp(); } public void suspendRead(final IoSocketHandler socketHandler) throws IOException { addKeyUpdateTask(new UpdateReadSelectionKeyTask(socketHandler, false)); } public void resumeRead(IoSocketHandler socketHandler) throws IOException { addKeyUpdateTask(new UpdateReadSelectionKeyTask(socketHandler, true)); } private final class UpdateReadSelectionKeyTask implements Runnable { private final IoSocketHandler socketHandler; private final boolean isSet; public UpdateReadSelectionKeyTask(IoSocketHandler socketHandler, boolean isSet) { this.socketHandler = socketHandler; this.isSet = isSet; } public void run() { assert (isDispatcherInstanceThread()); try { if (isSet) { setReadSelectionKeyNow(socketHandler); } else { unsetReadSelectionKeyNow(socketHandler); } } catch (Exception e) { e = ConnectionUtils.toIOException("Error by set read selection key now " + e.toString(), e); socketHandler.close(e); } } @Override public String toString() { return "setReadSelectionKeyTask#" + super.toString(); } } private int performKeyUpdateTasks() { int handledTasks = 0; while (true) { Runnable keyUpdateTask = keyUpdateQueue.poll(); if (keyUpdateTask == null) { return handledTasks; } else { keyUpdateTask.run(); handledTasks++; } } } public boolean isDispatcherInstanceThread() { Integer tbid = getThreadBoundId(); if ((tbid != null) && (tbid == id)) { return true; } return false; } private SelectionKey getSelectionKey(IoSocketHandler socketHandler) { SelectionKey key = socketHandler.getChannel().keyFor(selector); if (LOG.isLoggable(Level.FINE)) { if (key == null) { LOG.fine("[" + socketHandler.getId() + "] key is null"); } else if (!key.isValid()) { LOG.fine("[" + socketHandler.getId() + "] key is not valid"); } } return key; } public boolean setWriteSelectionKeyNow(final IoSocketHandler socketHandler) throws IOException { assert (isDispatcherInstanceThread()); SelectionKey key = getSelectionKey(socketHandler); if (key != null) { if (!isWriteable(key)) { key.interestOps(key.interestOps() | SelectionKey.OP_WRITE); return true; } } else { throw new IOException("[" + socketHandler.getId() + "] Error occured by setting write selection key. key is null"); } return false; } public boolean unsetWriteSelectionKeyNow(final IoSocketHandler socketHandler) throws IOException { assert (isDispatcherInstanceThread()); SelectionKey key = getSelectionKey(socketHandler); if (key != null) { if (isWriteable(key)) { key.interestOps(key.interestOps() & ~SelectionKey.OP_WRITE); return true; } } else { throw new IOException("[" + socketHandler.getId() + "] Error occured by unsetting write selection key. key is null"); } return false; } public boolean setReadSelectionKeyNow(final IoSocketHandler socketHandler) throws IOException { assert (isDispatcherInstanceThread()); SelectionKey key = getSelectionKey(socketHandler); if (key != null) { if (!isReadable(key)) { key.interestOps(key.interestOps() | SelectionKey.OP_READ); if (LOG.isLoggable(Level.FINE)) { LOG.fine("[" + socketHandler.getId() + "] key set to " + printSelectionKey(socketHandler)); } onReadableEvent(socketHandler); return true; } } else { throw new IOException("[" + socketHandler.getId() + "] Error occured by setting read selection key. key is null"); } return false; } private void unsetReadSelectionKeyNow(final IoSocketHandler socketHandler) throws IOException { assert (isDispatcherInstanceThread()); SelectionKey key = getSelectionKey(socketHandler); if (key != null) { if (isReadable(key)) { key.interestOps(key.interestOps() & ~SelectionKey.OP_READ); } } else { throw new IOException("[" + socketHandler.getId() + "] Error occured by unsetting read selection key. key is null"); } } String getRegisteredOpsInfo(IoSocketHandler socketHandler) { SelectionKey key = getSelectionKey(socketHandler); if (key == null) { return "<not registered>"; } else { return ConnectionUtils.printSelectionKeyValue(key.interestOps()); } } private int performRegisterHandlerTasks() throws IOException { int handledTasks = 0; while (true) { Runnable registerTask = registerQueue.poll(); if (registerTask == null) { return handledTasks; } else { registerTask.run(); handledTasks++; } } } private void registerHandlerNow(IoSocketHandler socketHandler, int ops) throws IOException { if (socketHandler.isOpen()) { if (LOG.isLoggable(Level.FINE)) { LOG.fine("[" + socketHandler.getId() + "] registering connection"); } try { socketHandler.getChannel().register(selector, ops, socketHandler); socketHandler.onRegisteredEvent(); handledRegistractions++; } catch (Exception e) { socketHandler.close(e); } } else { socketHandler.onRegisteredFailedEvent(new IOException("could not register handler " + socketHandler.getId() + " because the channel is closed")); } } /** * {@inheritDoc} */ public Set<IoSocketHandler> getRegistered() { Set<IoSocketHandler> registered = new HashSet<IoSocketHandler>(); Set<SelectionKey> keys = selector.keys(); for (SelectionKey key : keys) { IoSocketHandler socketHandler = (IoSocketHandler) key.attachment(); registered.add(socketHandler); } return registered; } /** * returns if the dispatcher is open * * @return true, if the dispatcher is open */ public boolean isOpen() { return isOpen.get(); } boolean isReadable(IoSocketHandler socketHandler) { SelectionKey key = getSelectionKey(socketHandler); if ((key != null) && ((key.interestOps() & SelectionKey.OP_READ) == SelectionKey.OP_READ)) { return true; } return false; } private boolean isReadable(SelectionKey key) { if ((key != null) && ((key.interestOps() & SelectionKey.OP_READ) == SelectionKey.OP_READ)) { return true; } return false; } private boolean isWriteable(SelectionKey key) { if ((key != null) && ((key.interestOps() & SelectionKey.OP_WRITE) == SelectionKey.OP_WRITE)) { return true; } return false; } /** * statistic method which returns the number handled registrations * @return the number handled registrations */ public long getNumberOfHandledRegistrations() { return handledRegistractions; } /** * statistic method which returns the number of handled reads * * @return the number of handled reads */ public long getNumberOfHandledReads() { return handledReads; } /** * statistic method which returns the number of handled writes * * @return the number of handled writes */ public long getNumberOfHandledWrites() { return handledWrites; } long getReceiveRateBytesPerSec() { long rate = 0; long elapsed = System.currentTimeMillis() - lastRequestReceiveRate; if (receivedBytes == 0) { rate = 0; } else if (elapsed == 0) { rate = Long.MAX_VALUE; } else { rate = ((receivedBytes * 1000) / elapsed); } lastRequestReceiveRate = System.currentTimeMillis(); receivedBytes = 0; return rate; } long getSendRateBytesPerSec() { long rate = 0; long elapsed = System.currentTimeMillis() - lastRequestSendRate; if (sentBytes == 0) { rate = 0; } else if (elapsed == 0) { rate = Long.MAX_VALUE; } else { rate = ((sentBytes * 1000) / elapsed); } lastRequestSendRate = System.currentTimeMillis(); sentBytes = 0; return rate; } long getCountIdleTimeout() { return countIdleTimeouts; } long getCountConnectionTimeout() { return countConnectionTimeouts; } public int getPreallocatedReadMemorySize() { return memoryManager.getCurrentSizePreallocatedBuffer(); } boolean getReceiveBufferPreallocationMode() { return memoryManager.isPreallocationMode(); } void setReceiveBufferPreallocationMode(boolean mode) { memoryManager.setPreallocationMode(mode); } void setReceiveBufferPreallocatedMinSize(Integer minSize) { memoryManager.setPreallocatedMinBufferSize(minSize); } Integer getReceiveBufferPreallocatedMinSize() { if (memoryManager.isPreallocationMode()) { return memoryManager.getPreallocatedMinBufferSize(); } else { return null; } } Integer getReceiveBufferPreallocatedSize() { if (memoryManager.isPreallocationMode()) { return memoryManager.getPreallocationBufferSize(); } else { return null; } } void setReceiveBufferPreallocatedSize(Integer size) { memoryManager.setPreallocationBufferSize(size); } boolean getReceiveBufferIsDirect() { return memoryManager.isDirect(); } void setReceiveBufferIsDirect(boolean isDirect) { memoryManager.setDirect(isDirect); } /** * reset the statistics (number of ...) */ public void resetStatistics() { statisticsStartTime = System.currentTimeMillis(); handledRegistractions = 0; handledReads = 0; handledWrites = 0; } @Override public String toString() { return "open channels " + getRegistered().size(); } /** * returns the statistics record start time (will be reset by the {@link IoSocketDispatcher#resetStatistics()} method) * @return */ protected long getStatisticsStartTime() { return statisticsStartTime; } @Override String printRegistered() { StringBuilder sb = new StringBuilder(); for (IoSocketHandler handler : getRegistered()) { sb.append(handler.toString() + " (key: " + printSelectionKey(handler) + ")\r\n"); } return sb.toString(); } String printSelectionKey(IoSocketHandler socketHandler) { return ConnectionUtils.printSelectionKey(socketHandler.getChannel().keyFor(selector)); } /** * {@inheritDoc} */ public void close() throws IOException { // wake up selector, so that isOpen loop can be terminated if (isOpen.getAndSet(false)&& (selector != null)) { selector.wakeup(); } } }
zzh-simple-hr
Zxsocket/src/org/xsocket/connection/IoSocketDispatcher.java
Java
art
23,347
/* * Copyright (c) xlightweb.org, 2006 - 2010. All rights reserved. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * Please refer to the LGPL license at: http://www.gnu.org/copyleft/lesser.txt * The latest copy of this software may be found on http://www.xsocket.org/ */ package org.xsocket.connection; import java.util.logging.Level; import java.util.logging.Logger; import javax.management.InstanceAlreadyExistsException; import javax.management.JMException; import javax.management.MBeanServer; import javax.management.ObjectName; import org.xsocket.DataConverter; import org.xsocket.IntrospectionBasedDynamicMBean; /** * A Mbean proxy factory, which creates and registers an appropriated mbean * for a given {@link IoSocketDispatcherPool} instance. * </pre> * * * @author grro@xsocket.org */ final class DispatcherPoolMBeanProxyFactory { private static final Logger LOG = Logger.getLogger(DispatcherPoolMBeanProxyFactory.class.getName()); public static ObjectName createAndRegister(IoSocketDispatcherPool dispatcherPool, String domain, MBeanServer mbeanServer) throws JMException { DispatcherPoolListener dispatcherPoolListener = new DispatcherPoolListener(domain, mbeanServer); dispatcherPool.addListener(dispatcherPoolListener); for (IoSocketDispatcher dispatcher : dispatcherPool.getDispatchers()) { dispatcherPoolListener.onDispatcherAdded(dispatcher); } return null; } private static final class DispatcherPoolListener implements IIoDispatcherPoolListener { private final String domain; private final MBeanServer mbeanServer; DispatcherPoolListener(String domain, MBeanServer mbeanServer) { this.domain = domain; this.mbeanServer = mbeanServer; } public void onDispatcherAdded(IoSocketDispatcher dispatcher) { try { ObjectName objectName = new ObjectName(domain + ":type=xDispatcher,name=" + dispatcher.getName()); mbeanServer.registerMBean(new IntrospectionBasedDynamicMBean(dispatcher), objectName); } catch (InstanceAlreadyExistsException ignore) { // ignore because global dispatcher pool could have been already registered } catch (Exception e) { // eat and log exception if (LOG.isLoggable(Level.FINE)) { LOG.warning("error occured by adding mbean for new dispatcher: " + DataConverter.toString(e)); } } } public void onDispatcherRemoved(IoSocketDispatcher dispatcher) { try { ObjectName objectName = new ObjectName(domain + ":type=xDispatcher,name=" + dispatcher.getName()); mbeanServer.unregisterMBean(objectName); } catch (Exception e) { // eat and log exception if (LOG.isLoggable(Level.FINE)) { LOG.warning("error occured by removing mbean of dispatcher: " + DataConverter.toString(e)); } } } } }
zzh-simple-hr
Zxsocket/src/org/xsocket/connection/DispatcherPoolMBeanProxyFactory.java
Java
art
3,931
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN"> <html> <head> </head> <body bgcolor="white"> Provides classes to handle a connection-oriented, sequenced flow of data in a blocking or non-blocking mode on the server and on the client side.<br> </body> </html>
zzh-simple-hr
Zxsocket/src/org/xsocket/connection/package.html
HTML
art
277
/* * Copyright (c) xlightweb.org, 2006 - 2010. All rights reserved. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * Please refer to the LGPL license at: http://www.gnu.org/copyleft/lesser.txt * The latest copy of this software may be found on http://www.xsocket.org/ */ package org.xsocket.connection; import java.util.logging.Level; import java.util.logging.Logger; import javax.management.InstanceNotFoundException; import javax.management.JMException; import javax.management.MBeanRegistration; import javax.management.MBeanServer; import javax.management.ObjectName; import org.xsocket.IntrospectionBasedDynamicMBean; /** * A Mbean proxy factory, which creates and registers an appropriated mbean * for a given {@link Server} instance. * * E.g. * <pre> * ... * IServer smtpServer = new Server(port, new SmtpProtcolHandler()); * ConnectionUtils.start(server); * * // create a mbean for the server and register it * ServerMBeanProxyFactory.createAndRegister(server); * * </pre> * * * @author grro@xsocket.org */ final class ServerMBeanProxyFactory { /** * creates and registers a mbean for the given server on the given MBeanServer * under the given domain name * * @param server the server to register * @param domain the domain name to use * @param mbeanServer the mbean server to use * @return the objectName * @throws JMException if an jmx exception occurs */ public static ObjectName createAndRegister(IServer server, String domain, MBeanServer mbeanServer) throws Exception { String address = server.getLocalAddress().getCanonicalHostName() + ":" + server.getLocalPort(); ObjectName serverObjectName = registerMBeans(server, domain, address, mbeanServer); server.addListener(new Listener(server, domain, address, mbeanServer)); return serverObjectName; } private static ObjectName registerMBeans(IServer server, String domain, String address, MBeanServer mbeanServer) throws Exception { address = address.replace(":", "_"); // create and register handler IHandler hdl = server.getHandler(); ObjectName hdlObjectName = new ObjectName(domain + ".server." + address + ":type=" + hdl.getClass().getSimpleName()); if (hdl instanceof MBeanRegistration) { ((MBeanRegistration) hdl).preRegister(mbeanServer, hdlObjectName); } else { mbeanServer.registerMBean(new IntrospectionBasedDynamicMBean(hdl), hdlObjectName); } // register the server ObjectName serverObjectName = null; if (server instanceof Server) { IoSocketDispatcherPool dispatcherPool = ((Server) server).getAcceptor().getDispatcherPool(); DispatcherPoolMBeanProxyFactory.createAndRegister(dispatcherPool, domain + ".server." + address, mbeanServer); } serverObjectName = new ObjectName(domain + ".server." + address + ":type=xServer,name=" + server.hashCode()); mbeanServer.registerMBean(new IntrospectionBasedDynamicMBean(server), serverObjectName); // create and register workerpool ObjectName workerpoolObjectName = new ObjectName(domain + ".server." + address + ":type=Workerpool"); mbeanServer.registerMBean(new IntrospectionBasedDynamicMBean(server.getWorkerpool()), workerpoolObjectName); if (hdl instanceof MBeanRegistration) { ((MBeanRegistration) hdl).postRegister(true); } return serverObjectName; } private static void unregisterMBeans(IServer server, String domain, String address, MBeanServer mbeanServer) throws Exception { address = address.replace(":", "_"); // create and register handler IHandler hdl = server.getHandler(); // unregister handler ObjectName hdlObjectName = new ObjectName(domain + ".server." + address + ":type=" + server.getHandler().getClass().getSimpleName()); if (hdl instanceof MBeanRegistration) { ((MBeanRegistration) hdl).preDeregister(); } mbeanServer.unregisterMBean(hdlObjectName); // unregister worker pool ObjectName workerpoolObjectName = new ObjectName(domain + ".server." + address + ":type=Workerpool"); mbeanServer.unregisterMBean(workerpoolObjectName); if (hdl instanceof MBeanRegistration) { ((MBeanRegistration) hdl).postDeregister(); } } private static final class Listener implements IServerListener { private static final Logger LOG = Logger.getLogger(Listener.class.getName()); private final IServer server; private final String domain; private final String address; private final MBeanServer mbeanServer; Listener(IServer server, String domain, String address, MBeanServer mbeanServer) { this.server = server; this.domain = domain; this.address = address; this.mbeanServer = mbeanServer; server.addListener(this); } public void onInit() { } public void onDestroy() { try { unregisterMBeans(server, domain, address, mbeanServer); } catch (InstanceNotFoundException ignore) { // eat exception } catch (Exception e) { if (LOG.isLoggable(Level.FINE)) { LOG.fine("error occured by deregistering the server (domain=" + domain + "). reason: " + e.toString()); } throw new RuntimeException(e); } } } }
zzh-simple-hr
Zxsocket/src/org/xsocket/connection/ServerMBeanProxyFactory.java
Java
art
6,086
/* * Copyright (c) xlightweb.org, 2006 - 2010. All rights reserved. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * Please refer to the LGPL license at: http://www.gnu.org/copyleft/lesser.txt * The latest copy of this software may be found on http://www.xsocket.org/ */ package org.xsocket.connection; import java.io.IOException; import java.nio.ByteBuffer; import java.nio.channels.ClosedChannelException; import java.util.LinkedList; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.ThreadFactory; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; import java.util.logging.Level; import java.util.logging.Logger; import javax.net.ssl.SSLContext; import javax.net.ssl.SSLEngine; import javax.net.ssl.SSLEngineResult; import javax.net.ssl.SSLException; import javax.net.ssl.SSLEngineResult.HandshakeStatus; import org.xsocket.DataConverter; /** * ssl processor * * @author grro@xsocket.org */ final class IoSSLProcessor { private static final Logger LOG = Logger.getLogger(IoSSLProcessor.class.getName()); private final static ByteBuffer NULL_BYTE_BUFFER = ByteBuffer.allocate(0); private final static ExecutorService WORKERPOOL = Executors.newCachedThreadPool(new DefaultThreadFactory()); private final SSLEngine sslEngine; private final boolean isClientMode; private final AbstractMemoryManager memoryManager; private final EventHandler eventHandler; // buffer size private int minNetBufferSize; private int minEncryptedBufferSize; private ByteBuffer unprocessedInNetData = NULL_BYTE_BUFFER; private final Object unprocessedInNetDataGuard = new Object(); private final LinkedList<ByteBuffer> outAppDataList = new LinkedList<ByteBuffer>(); private AtomicBoolean isOutboundClosed = new AtomicBoolean(); private AtomicBoolean isInboundClosed = new AtomicBoolean(); /** * constructor * * @param sslContext the ssl context * @param isClientMode true, is ssl processor runs in client mode */ IoSSLProcessor(SSLContext sslContext, boolean isClientMode, AbstractMemoryManager memoryManager, EventHandler eventHandler) { this.isClientMode = isClientMode; this.memoryManager = memoryManager; this.eventHandler = eventHandler; sslEngine = sslContext.createSSLEngine(); if (isClientMode) { if (IoProvider.getSSLEngineClientEnabledCipherSuites() != null) { sslEngine.setEnabledCipherSuites(IoProvider.getSSLEngineClientEnabledCipherSuites()); } if (IoProvider.getSSLEngineClientEnabledProtocols() != null) { sslEngine.setEnabledProtocols(IoProvider.getSSLEngineClientEnabledProtocols()); } } else { if (IoProvider.getSSLEngineServerEnabledCipherSuites() != null) { sslEngine.setEnabledCipherSuites(IoProvider.getSSLEngineServerEnabledCipherSuites()); } if (IoProvider.getSSLEngineServerEnabledProtocols() != null) { sslEngine.setEnabledProtocols(IoProvider.getSSLEngineServerEnabledProtocols()); } if (IoProvider.getSSLEngineServerWantClientAuth() != null) { sslEngine.setWantClientAuth(IoProvider.getSSLEngineServerWantClientAuth()); } if (IoProvider.getSSLEngineServerNeedClientAuth() != null) { sslEngine.setNeedClientAuth(IoProvider.getSSLEngineServerNeedClientAuth()); } } minEncryptedBufferSize = sslEngine.getSession().getApplicationBufferSize(); minNetBufferSize = sslEngine.getSession().getPacketBufferSize(); if (LOG.isLoggable(Level.FINE)) { if (isClientMode) { LOG.fine("initializing ssl processor (client mode)"); } else { LOG.fine("initializing ssl processor (server mode)"); } LOG.fine("app buffer size is " + minEncryptedBufferSize); LOG.fine("packet buffer size is " + minNetBufferSize); } sslEngine.setUseClientMode(isClientMode); } /** * start ssl processing * * @param inNetData already received net data * @throws IOException If some other I/O error occurs */ void start() throws IOException { if (LOG.isLoggable(Level.FINE)) { if (isClientMode) { LOG.fine("calling sslEngine beginHandshake and calling encncrypt to initiate handeshake (client mode)"); } else { LOG.fine("calling sslEngine beginHandshake (server mode)"); } } try { sslEngine.beginHandshake(); } catch (SSLException sslEx) { throw new RuntimeException(sslEx); } if (isClientMode) { encrypt(); } } void stop() throws IOException { sslEngine.closeOutbound(); wrap(); } /** * destroy this instance * */ void destroy() { try { eventHandler.onDestroy(); } catch (IOException ioe) { if (LOG.isLoggable(Level.FINE)) { LOG.fine("error occured by calling ssl processor closed caal back on " + eventHandler + " reason: " + DataConverter.toString(ioe)); } } } /** * decrypt data * * @param encryptedBufferList the encrypted data * @throws IOException if an io exction occurs * @throws ClosedChannelException if the connection is already closed */ void decrypt(ByteBuffer[] encryptedBufferList) throws IOException, ClosedChannelException { try { for (int i = 0; i < encryptedBufferList.length; i++) { synchronized (unprocessedInNetDataGuard) { unprocessedInNetData = mergeBuffer(unprocessedInNetData, encryptedBufferList[i]); } if (!isInboundClosed.get()) { unwrap(); } else { ByteBuffer data; synchronized (unprocessedInNetDataGuard) { data = unprocessedInNetData; unprocessedInNetData = NULL_BYTE_BUFFER; } eventHandler.onDataDecrypted(data); } } } catch (SSLException sslEx) { destroy(); throw sslEx; } } /** * return true, if the connection is handshaking * * @return true, if the connection is handshaking */ boolean isHandshaking() { synchronized (sslEngine) { HandshakeStatus handshakeStatus = sslEngine.getHandshakeStatus(); return !(handshakeStatus == SSLEngineResult.HandshakeStatus.NOT_HANDSHAKING) || (handshakeStatus == SSLEngineResult.HandshakeStatus.FINISHED); } } /** * add out app data * * @param plainBuffer the plain data to encrypt */ void addOutAppData(ByteBuffer[] plainBufferList) throws ClosedChannelException, IOException { if (plainBufferList != null) { for (ByteBuffer buffer : plainBufferList) { synchronized (outAppDataList) { outAppDataList.add(buffer); } } } } /** * encrypt data * * @throws IOException if an io exction occurs * @throws ClosedChannelException if the connection is already closed */ void encrypt() throws ClosedChannelException, IOException { try { wrap(); } catch (IOException sslEx) { destroy(); } } private void unwrap() throws SSLException, ClosedChannelException, IOException { synchronized (unprocessedInNetDataGuard) { if (unprocessedInNetData.remaining() == 0) { return; } } int minAppSize = minEncryptedBufferSize; boolean isDataDecrypted = false; boolean needUnwrap = true; boolean needWrap = false; boolean nodifyHandshakeFinished = false; while (needUnwrap) { needUnwrap = false; // perform unwrap ByteBuffer inAppData = memoryManager.acquireMemoryMinSize(minAppSize); synchronized (sslEngine) { SSLEngineResult engineResult = null; synchronized (unprocessedInNetDataGuard) { engineResult = sslEngine.unwrap(unprocessedInNetData, inAppData); } if (LOG.isLoggable(Level.FINE)) { if ((inAppData.position() == 0) && (engineResult.bytesConsumed() > 0)) { LOG.fine("incoming ssl system message (size " + engineResult.bytesConsumed() + ") encrypted by ssl engine"); } if (unprocessedInNetData.remaining() > 0) { LOG.fine("remaining not decrypted incoming net data (" + unprocessedInNetData.remaining() + ")"); } if (inAppData.position() > 0) { LOG.fine("incoming app data (size " + inAppData.position() + ") encrypted by ssl engine"); } } if ((unprocessedInNetData.remaining() > 0) && (engineResult.bytesConsumed() > 0)) { needUnwrap = true; } SSLEngineResult.Status status = engineResult.getStatus(); switch (status) { case BUFFER_UNDERFLOW: needUnwrap = false; memoryManager.recycleMemory(inAppData); /* * There is not enough data on the input buffer to perform the operation. The application should read * more data from the network. If the input buffer does not contain a full packet BufferUnderflow occurs * (unwrap() can only operate on full packets) */ if (LOG.isLoggable(Level.FINEST)) { LOG.finest("BufferUnderflow occured (not enough InNet data)"); } break; case CLOSED: needUnwrap = false; isInboundClosed.set(true); if (LOG.isLoggable(Level.FINE)) { LOG.fine("ssl engine inbound closed"); } memoryManager.recycleMemory(inAppData); ByteBuffer data; synchronized (unprocessedInNetDataGuard) { data = unprocessedInNetData; unprocessedInNetData = NULL_BYTE_BUFFER; } eventHandler.onInboundClosed(); if (data.remaining() > 0) { isDataDecrypted = true; eventHandler.onDataDecrypted(data); } break; case BUFFER_OVERFLOW: needUnwrap = true; memoryManager.recycleMemory(inAppData); // expanding the min buffer size minAppSize += minAppSize; break; case OK: // extract unwrapped app data inAppData = memoryManager.extractAndRecycleMemory(inAppData, engineResult.bytesProduced()); if (inAppData.hasRemaining()) { isDataDecrypted = true; eventHandler.onDataDecrypted(inAppData); } HandshakeStatus handshakeStatus = engineResult.getHandshakeStatus(); switch (handshakeStatus) { case NOT_HANDSHAKING: break; case NEED_UNWRAP: needUnwrap = true; break; case NEED_WRAP: needWrap = true; break; case NEED_TASK: needUnwrap = true; Runnable task = null; while ((task = sslEngine.getDelegatedTask()) != null) { task.run(); } break; case FINISHED: needUnwrap = true; nodifyHandshakeFinished = true; break; default: needUnwrap = false; break; } break; } } // synchronized(sslEngine) if (isDataDecrypted) { eventHandler.onPostDataDecrypted(); } boolean outAppDataListEmpty = false; synchronized (outAppDataList) { outAppDataListEmpty = outAppDataList.isEmpty(); } if (!outAppDataListEmpty) { needWrap = true; } if (needWrap) { wrap(); } if (nodifyHandshakeFinished) { notifyHandshakeFinished(); } } // while(needUnwrap) } private void wrap() throws SSLException, ClosedChannelException, IOException { int minNetSize = minNetBufferSize; boolean isDataEncrypted = false; boolean needWrap = true; boolean needUnwrap = false; boolean nodifyHandshakeFinished = false; while (needWrap) { needWrap = false; ByteBuffer outNetData = memoryManager.acquireMemoryMinSize(minNetSize); synchronized (sslEngine) { ByteBuffer outAppData = null; synchronized (outAppDataList) { if (outAppDataList.isEmpty()) { outAppData = ByteBuffer.allocate(0); } else { outAppData = outAppDataList.remove(0); } } int sizeToEncrypt = outAppData.remaining(); SSLEngineResult engineResult = sslEngine.wrap(outAppData, outNetData); if (LOG.isLoggable(Level.FINE)) { if ((sizeToEncrypt == 0) && (engineResult.bytesProduced() > 0)) { LOG.fine("outgoing ssl system message (size " + engineResult.bytesProduced() + ") created by ssl engine"); } else if ((sizeToEncrypt > 0)) { LOG.fine("outgoing app data (size " + sizeToEncrypt + ") encrypted (encrypted size " + outNetData.position() + ")"); } if (outAppData.remaining() > 0) { LOG.fine("remaining not encrypted outgoing app data (" + outAppData.remaining() + ")"); } } if ((outAppData.remaining() > 0) && (engineResult.bytesConsumed() > 0)) { needWrap = true; } if (outAppData.hasRemaining()) { synchronized (outAppDataList) { outAppDataList.addFirst(outAppData); } } if ((outAppDataList.size() > 0) && (engineResult.bytesConsumed() > 0)) { needWrap = true; } SSLEngineResult.Status status = engineResult.getStatus(); switch (status) { case BUFFER_UNDERFLOW: needWrap = false; outNetData = memoryManager.extractAndRecycleMemory(outNetData, engineResult.bytesProduced()); if (outNetData.hasRemaining()) { isDataEncrypted = true; eventHandler.onDataEncrypted(outAppData, outNetData); } break; case CLOSED: isOutboundClosed.set(true); if (LOG.isLoggable(Level.FINE)) { LOG.fine("ssl engine outbound closed"); } outNetData = memoryManager.extractAndRecycleMemory(outNetData, engineResult.bytesProduced()); if (outNetData.hasRemaining()) { isDataEncrypted = true; eventHandler.onDataEncrypted(outAppData, outNetData); } memoryManager.recycleMemory(outNetData); break; case BUFFER_OVERFLOW: needWrap = true; memoryManager.recycleMemory(outNetData); // expanding the min buffer size minNetSize += minNetSize; break; case OK: outNetData = memoryManager.extractAndRecycleMemory(outNetData, engineResult.bytesProduced()); if (outNetData.hasRemaining()) { isDataEncrypted = true; eventHandler.onDataEncrypted(outAppData, outNetData); } HandshakeStatus handshakeStatus = engineResult.getHandshakeStatus(); switch (handshakeStatus) { case NOT_HANDSHAKING: break; case NEED_UNWRAP: needUnwrap = true; break; case NEED_WRAP: needWrap = true; break; case NEED_TASK: needWrap = true; Runnable task = null; while ((task = sslEngine.getDelegatedTask()) != null) { task.run(); } break; case FINISHED: needWrap = true; nodifyHandshakeFinished = true; break; default: needWrap = false; break; } break; } } // synchronized(sslEngine) if (needUnwrap) { // call unwrap by a dedicated worker thread to prevent // unwrap -> wrap -> unwrap -> ... loops Runnable unwrapTask = new Runnable() { public void run() { try { unwrap(); } catch (IOException e) { destroy(); } } }; WORKERPOOL.execute(unwrapTask); } if (isDataEncrypted) { eventHandler.onPostDataEncrypted(); } if (nodifyHandshakeFinished) { notifyHandshakeFinished(); } } // while (needWrap) } private void notifyHandshakeFinished() throws IOException { if (LOG.isLoggable(Level.FINE)) { if (isClientMode) { LOG.fine("handshake has been finished (clientMode)"); } else { LOG.fine("handshake has been finished (serverMode)"); } } eventHandler.onHandshakeFinished(); } private ByteBuffer mergeBuffer(ByteBuffer first, ByteBuffer second) { if (first.remaining() == 0) { return second; } if (second.remaining() == 0) { return first; } ByteBuffer mergedBuffer = ByteBuffer.allocate(first.remaining() + second.remaining()); mergedBuffer.put(first); mergedBuffer.put(second); mergedBuffer.flip(); return mergedBuffer; } /** * SSLProcessor call back interface * * @author grro */ static interface EventHandler { /** * signals that the handshake has been finished * * @throws IOException if an io exception occurs */ public void onHandshakeFinished() throws IOException; /** * signals data has been decrypted * * @param decryptedBuffer the decrypted data */ public void onDataDecrypted(ByteBuffer decryptedBuffer); /** * signals the the decrypted task has been completed */ public void onPostDataDecrypted(); /** * signals that data has been encrypted * * @param plainData the plain data * @param encryptedData the encrypted data * @throws IOException if an io exception occurs */ public void onDataEncrypted(ByteBuffer plainData, ByteBuffer encryptedData) throws IOException ; /** * signals that data encrypt task has been completed * */ public void onPostDataEncrypted() throws IOException ; /** * signals, that the SSLProcessor has been closed * * @throws IOException if an io exception occurs */ public void onDestroy() throws IOException; /** * signals, that the inbound has been closed * * @throws IOException */ public void onInboundClosed() throws IOException; } private static class DefaultThreadFactory implements ThreadFactory { private static final AtomicInteger poolNumber = new AtomicInteger(1); private final AtomicInteger threadNumber = new AtomicInteger(1); private final String namePrefix; DefaultThreadFactory() { namePrefix = "xSSL-" + poolNumber.getAndIncrement() + "-thread-"; } public Thread newThread(Runnable r) { Thread t = new Thread(r, namePrefix + threadNumber.getAndIncrement()); if (t.isDaemon()) { t.setDaemon(false); } if (t.getPriority() != Thread.NORM_PRIORITY) { t.setPriority(Thread.NORM_PRIORITY); } return t; } } }
zzh-simple-hr
Zxsocket/src/org/xsocket/connection/IoSSLProcessor.java
Java
art
19,938
/* * Copyright (c) xlightweb.org, 2006 - 2010. All rights reserved. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * Please refer to the LGPL license at: http://www.gnu.org/copyleft/lesser.txt * The latest copy of this software may be found on http://www.xsocket.org/ */ package org.xsocket.connection; import java.io.IOException; /** * Checked exception thrown when a the max number of connections is exceeded * * @author grro */ public class MaxConnectionsExceededException extends IOException { private static final long serialVersionUID = 1281126091557474008L; public MaxConnectionsExceededException(String reason) { super(reason); } }
zzh-simple-hr
Zxsocket/src/org/xsocket/connection/MaxConnectionsExceededException.java
Java
art
1,421
/* * Copyright (c) xlightweb.org, 2006 - 2010. All rights reserved. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * Please refer to the LGPL license at: http://www.gnu.org/copyleft/lesser.txt * The latest copy of this software may be found on http://www.xsocket.org/ */ package org.xsocket.connection; import java.io.Closeable; import java.util.List; import org.xsocket.ILifeCycle; /** * A connection pool manages a pool of open connections. * Typically, a connection pool will be used on the client-side if connections for the * same server (address) will be created in a serial manner in a sort period of time. * By pooling such connections the overhead of establishing a connection will be avoided * For pool management reasons, timeouts can be defined. The * IdleTimeout defines the max idle time in the pool. After this time the * free connection will be closed. In the same way, the max living time * defines the timeout of the connection. If a free connection exceeds * this time, the connection will be closed. <br> * Additional the max size of the active connections can be defined. * If a connection is requested and the max limit of the active connection * is reached, an exception wiil be thrown. * * @author grro@xsocket.org */ public interface IConnectionPool extends Closeable { public static final int DEFAULT_MAX_ACTIVE = Integer.MAX_VALUE; public static final int DEFAULT_MAX_ACTIVE_PER_SERVER = Integer.MAX_VALUE; public static final int DEFAULT_MAX_IDLE = Integer.MAX_VALUE; public static final long DEFAULT_MAX_WAIT_MILLIS = 0; public static final int DEFAULT_MAX_WAITING = Integer.MAX_VALUE; public static final int DEFAULT_IDLE_TIMEOUT_MILLIS = Integer.MAX_VALUE; public static final int DEFAULT_LIFE_TIMEOUT_MILLIS = Integer.MAX_VALUE; public static final int DEFAULT_CREATION_TIMEOUT_MILLIS = 500; /** * returns true, is pool is open * * @return true, is pool is open */ boolean isOpen(); /** * adds a listener * * @param listener the listener to add */ void addListener(ILifeCycle listener); /** * removes a listener * * @param listener the listener to remove * @return true, is the listener has been removed */ boolean removeListener(ILifeCycle listener); /** * return the number of max active resources * * @return number of max active resources */ int getMaxActive(); /** * return the number of max active resources per server * * @return number of max active resources per server */ int getMaxActivePerServer(); /** * set the number of max active resources per server * * @return number of max active resources per server */ void setMaxActivePerServer(int maxActivePerServer); /** * set the number of max active resources * * @param maxActive the number of max active resources */ void setMaxActive(int maxActive); /** * get the number of max idling resources * * @return the number of max idling resources */ int getMaxIdle(); /** * set the number of max idling resources * * @param the number of max idling resources */ void setMaxIdle(int maxIdle); /** * get the current number of the active resources * * @return the current number of the active resources */ int getNumActive(); /** * get the number of the destroyed resources * * @return the number of the destroyed resources */ int getNumDestroyed(); /** * get the number of timeouts caused by the pool life timeout * @return the number of timeouts */ int getNumTimeoutPooledMaxLifeTime(); /** * get the number of timeouts caused by the pool idle timeout * @return the number of timeouts */ int getNumTimeoutPooledMaxIdleTime(); /** * get the number of the created resources * * @return the number of the created resources */ int getNumCreated(); /** * get a info list about the active connections * @return a info list about the active connection */ List<String> getActiveConnectionInfos(); /** * get a info list about the idle connections * @return a info list about the idle connections */ List<String> getIdleConnectionInfos(); /** * get the current number of idling resources * * @return the current number of idling resources */ int getNumIdle(); /** * get the idle time out * * @return the idle time out */ int getPooledMaxIdleTimeMillis(); /** * set the idle time out of a resource within the pool * * @param idleTimeoutMillis the idle time out */ void setPooledMaxIdleTimeMillis(int idleTimeoutMillis); /** * get the life timeout of a resource * * @return the life timeout of a resource */ int getPooledMaxLifeTimeMillis(); /** * set the life timeout of a resource * * @param lifeTimeoutSec the life timeout of a resource */ void setPooledMaxLifeTimeMillis(int lifeTimeoutMillis); }
zzh-simple-hr
Zxsocket/src/org/xsocket/connection/IConnectionPool.java
Java
art
6,007
/* * Copyright (c) xlightweb.org, 2006 - 2010. All rights reserved. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * Please refer to the LGPL license at: http://www.gnu.org/copyleft/lesser.txt * The latest copy of this software may be found on http://www.xsocket.org/ */ package org.xsocket.connection; import java.io.IOException; import java.nio.ByteBuffer; import java.util.logging.Level; import java.util.logging.Logger; import org.xsocket.DataConverter; /** * implementation base for a Memory Manager implementation * * @author grro@xsocket.org */ abstract class AbstractMemoryManager { private static final Logger LOG = Logger.getLogger(AbstractMemoryManager.class.getName()); // direct or non-direct buffer private boolean useDirectMemory = false; // preallocation support private int preallocationSize = 65536; private int minPreallocatedBufferSize = 1; private boolean preallocate = false; /** * constructor * * @param allocationSize the buffer to allocate * @param preallocate true, if buffer should be preallocated * @param minPreallocatedBufferSize the minimal buffer size * @param useDirectMemory true, if direct memory should be used */ protected AbstractMemoryManager(int preallocationSize, boolean preallocate, int minPreallocatedBufferSize, boolean useDirectMemory) { this.preallocationSize = preallocationSize; this.preallocate = preallocate; this.minPreallocatedBufferSize = minPreallocatedBufferSize; this.useDirectMemory = useDirectMemory; } /** * acquire ByteBuffer with free memory * * @param standardsize the standard size * @return the ByteBuffer with free memory * * @throws IOException if an exception occurs */ public abstract ByteBuffer acquireMemoryStandardSizeOrPreallocated(int standardsize) throws IOException; /** * recycle a ByteBuffer. * * @param buffer the ByteBuffer to recycle */ public abstract void recycleMemory(ByteBuffer buffer); /** * preallocate, if preallocated size is smaller the given minSize * * @throws IOException if an exception occurs */ public abstract void preallocate() throws IOException; /** * get the current free preallocated buffer size * @return the current free preallocated buffer size */ public abstract int getCurrentSizePreallocatedBuffer(); /** * {@inheritDoc} */ public final boolean isPreallocationMode() { return preallocate; } /** * {@inheritDoc} */ public final void setPreallocationMode(boolean mode) { this.preallocate = mode; } /** * {@inheritDoc} */ public final void setPreallocatedMinBufferSize(Integer minSize) { this.minPreallocatedBufferSize = minSize; } /** * {@inheritDoc} */ public final Integer getPreallocatedMinBufferSize() { return minPreallocatedBufferSize; } /** * {@inheritDoc} */ public final Integer getPreallocationBufferSize() { return preallocationSize; } /** * {@inheritDoc} */ public final void setPreallocationBufferSize(Integer minSize) { this.preallocationSize = minSize; } /** * {@inheritDoc} */ public final boolean isDirect() { return useDirectMemory; } /** * {@inheritDoc} */ public final void setDirect(boolean isDirect) { this.useDirectMemory = isDirect; } /** * {@inheritDoc} */ public final ByteBuffer extractAndRecycleMemory(ByteBuffer buffer, int read) { ByteBuffer readData = null; if (read > 0) { buffer.limit(buffer.position()); buffer.position(buffer.position() - read); // slice the read data readData = buffer.slice(); // preallocate mode? and does buffer contain remaining free data? -> recycle these if (preallocate && (buffer.limit() < buffer.capacity())) { buffer.position(buffer.limit()); buffer.limit(buffer.capacity()); recycleMemory(buffer); } } else { readData = ByteBuffer.allocate(0); if (preallocate) { recycleMemory(buffer); } } return readData; } /** * {@inheritDoc} */ public final ByteBuffer acquireMemoryMinSize(int minSize) throws IOException { // preallocation mode? if (preallocate) { // ... yes, but is required size larger than preallocation size? if (preallocationSize < minSize) { // ... yes. create a new buffer return newBuffer(minSize); // ... no, call method to get preallocated buffer first } else { ByteBuffer buffer = acquireMemoryStandardSizeOrPreallocated(minSize); // buffer to small? if (buffer.remaining() < minSize) { // yes, create a new one return newBuffer(minSize); } return buffer; } // .. no } else { return newBuffer(minSize); } } /** * creates a new buffer * @param size the size of the new buffer * @return the new buffer */ protected final ByteBuffer newBuffer(int size) throws IOException { return newBuffer(size, useDirectMemory); } private ByteBuffer newBuffer(int size, boolean isUseDirect) throws IOException { try { if (isUseDirect) { if (LOG.isLoggable(Level.FINE)) { LOG.fine("allocating " + DataConverter.toFormatedBytesSize(size) + " direct memory"); } return ByteBuffer.allocateDirect(size); } else { if (LOG.isLoggable(Level.FINE)) { LOG.fine("allocating " + DataConverter.toFormatedBytesSize(size) + " heap memory"); } return ByteBuffer.allocate(size); } } catch (OutOfMemoryError oome) { if (isUseDirect) { String msg = "out of memory exception occured by trying to allocated direct memory " + DataConverter.toString(oome); LOG.warning(msg); throw new IOException(msg); } else { String msg = "out of memory exception occured by trying to allocated non-direct memory " + DataConverter.toString(oome); LOG.warning(msg); throw new IOException(msg); } } } /** * {@inheritDoc} */ @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("useDirect=" + useDirectMemory + " preallocationOn=" + preallocate + " preallcoationSize=" + DataConverter.toFormatedBytesSize(preallocationSize) + " preallocatedMinSize=" + DataConverter.toFormatedBytesSize(minPreallocatedBufferSize)); return sb.toString(); } }
zzh-simple-hr
Zxsocket/src/org/xsocket/connection/AbstractMemoryManager.java
Java
art
7,647
/* * Copyright (c) xlightweb.org, 2006 - 2010. All rights reserved. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * Please refer to the LGPL license at: http://www.gnu.org/copyleft/lesser.txt * The latest copy of this software may be found on http://www.xsocket.org/ */ package org.xsocket.connection; import java.io.IOException; import java.net.InetAddress; import java.util.Map; /** * Base class of the synchronize wrapper * * @author grro@xsocket.org */ abstract class AbstractSynchronizedConnection implements IConnection { private final IConnection delegate; public AbstractSynchronizedConnection(IConnection delegate) { this.delegate = delegate; } public final Object getAttachment() { synchronized(delegate) { return delegate.getAttachment(); } } public final long getConnectionTimeoutMillis() { synchronized(delegate) { return delegate.getConnectionTimeoutMillis(); } } public final String getId() { synchronized(delegate) { return delegate.getId(); } } public final long getIdleTimeoutMillis() { synchronized(delegate) { return delegate.getIdleTimeoutMillis(); } } public final InetAddress getLocalAddress() { synchronized(delegate) { return delegate.getLocalAddress(); } } public final int getLocalPort() { synchronized(delegate) { return delegate.getLocalPort(); } } public final Object getOption(String name) throws IOException { synchronized(delegate) { return delegate.getOption(name); } } @SuppressWarnings("unchecked") public final Map<String, Class> getOptions() { synchronized(delegate) { return delegate.getOptions(); } } public final long getRemainingMillisToConnectionTimeout() { synchronized(delegate) { return delegate.getRemainingMillisToConnectionTimeout(); } } public final long getRemainingMillisToIdleTimeout() { synchronized(delegate) { return delegate.getRemainingMillisToIdleTimeout(); } } public final InetAddress getRemoteAddress() { synchronized(delegate) { return delegate.getRemoteAddress(); } } public final int getRemotePort() { synchronized(delegate) { return delegate.getRemotePort(); } } public final boolean isOpen() { synchronized(delegate) { return delegate.isOpen(); } } public final boolean isServerSide() { synchronized(delegate) { return delegate.isServerSide(); } } public final void setAttachment(Object obj) { synchronized(delegate) { delegate.setAttachment(obj); } } public final void setConnectionTimeoutMillis(long timeoutMillis) { synchronized(delegate) { delegate.setConnectionTimeoutMillis(timeoutMillis); } } public final void setIdleTimeoutMillis(long timeoutInMillis) { synchronized(delegate) { delegate.setIdleTimeoutMillis(timeoutInMillis); } } public final void setOption(String name, Object value) throws IOException { synchronized(delegate) { delegate.setOption(name, value); } } public final void close() throws IOException { synchronized(delegate) { delegate.close(); } } }
zzh-simple-hr
Zxsocket/src/org/xsocket/connection/AbstractSynchronizedConnection.java
Java
art
4,594
/* * Copyright (c) xlightweb.org, 2006 - 2010. All rights reserved. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * Please refer to the LGPL license at: http://www.gnu.org/copyleft/lesser.txt * The latest copy of this software may be found on http://www.xsocket.org/ */ package org.xsocket.connection; import java.io.IOException; import java.nio.ByteBuffer; import java.util.logging.Level; import java.util.logging.Logger; import org.xsocket.DataConverter; /** * Single thread memory manager * * * @author grro@xsocket.org */ final class IoUnsynchronizedMemoryManager extends AbstractMemoryManager { private static final Logger LOG = Logger.getLogger(IoUnsynchronizedMemoryManager.class.getName()); private ByteBuffer freeBuffer; /** * constructor * * @param allocationSize the buffer to allocate * @param preallocate true, if buffer should be preallocated * @param minPreallocatedBufferSize the minimal buffer size * @param useDirectMemory true, if direct memory should be used */ private IoUnsynchronizedMemoryManager(int preallocationSize, boolean preallocate, int minPreallocatedBufferSize, boolean useDirectMemory) { super(preallocationSize, preallocate, minPreallocatedBufferSize, useDirectMemory); } public static IoUnsynchronizedMemoryManager createPreallocatedMemoryManager(int preallocationSize, int minBufferSze, boolean useDirectMemory) { return new IoUnsynchronizedMemoryManager(preallocationSize, true, minBufferSze, useDirectMemory); } public static IoUnsynchronizedMemoryManager createNonPreallocatedMemoryManager(boolean useDirectMemory) { return new IoUnsynchronizedMemoryManager(0, false, 1, useDirectMemory); } /** * {@inheritDoc} */ public int getCurrentSizePreallocatedBuffer() { if (freeBuffer != null) { return freeBuffer.remaining(); } else { return 0; } } /** * {@inheritDoc} */ public void recycleMemory(ByteBuffer buffer) { // preallocate mode? if (isPreallocationMode() && (buffer.remaining() >= getPreallocatedMinBufferSize())) { if (LOG.isLoggable(Level.FINE)) { LOG.fine("recycling " + DataConverter.toFormatedBytesSize(buffer.remaining())); } freeBuffer = buffer; } } /** * {@inheritDoc} */ public ByteBuffer acquireMemoryStandardSizeOrPreallocated(int standardSize) throws IOException { if (isPreallocationMode()) { preallocate(); } else { freeBuffer = newBuffer(standardSize); } ByteBuffer buffer = freeBuffer; freeBuffer = null; return buffer; } /** * {@inheritDoc} */ public void preallocate() throws IOException { if (isPreallocationMode()) { // sufficient size? if ((freeBuffer != null) && (freeBuffer.remaining() >= getPreallocatedMinBufferSize())) { return; } // no, allocate new freeBuffer = newBuffer(getPreallocationBufferSize()); } } }
zzh-simple-hr
Zxsocket/src/org/xsocket/connection/IoUnsynchronizedMemoryManager.java
Java
art
3,766
/* * Copyright (c) xlightweb.org, 2006 - 2010. All rights reserved. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * Please refer to the LGPL license at: http://www.gnu.org/copyleft/lesser.txt * The latest copy of this software may be found on http://www.xsocket.org/ */ package org.xsocket.connection; import java.io.IOException; /** * Handles connection timeout. The timeouts will be defined by the server. To modify the timeouts * the proper server methods has to be called. E.g.<br> * <pre> * ... * IServer server = new Server(new MyHandler()); * server.setConnectionTimeoutMillis(60 * 1000); * ConnectionUtils.start(server); * ... * * * class MyHandler implements IConnectionTimeoutHandler { * * public boolean onConnectionTimeout(INonBlockingConnection connection) throws IOException { * ... * connection.close(); * return true; // true -> event has been handled (by returning false xSocket will close the connection) * } * } * </pre> * * @author grro@xsocket.org */ public interface IConnectionTimeoutHandler extends IHandler { /** * handles the connection timeout. * * @param connection the underlying connection * @return true if the timeout event has been handled (in case of false the connection will be closed by the server) * @throws IOException if an error occurs. Throwing this exception causes that the underlying connection will be closed. */ boolean onConnectionTimeout(INonBlockingConnection connection) throws IOException; }
zzh-simple-hr
Zxsocket/src/org/xsocket/connection/IConnectionTimeoutHandler.java
Java
art
2,339
/* * Copyright (c) xlightweb.org, 2006 - 2010. All rights reserved. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * Please refer to the LGPL license at: http://www.gnu.org/copyleft/lesser.txt * The latest copy of this software may be found on http://www.xsocket.org/ */ package org.xsocket.connection; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.net.InetAddress; import java.net.InetSocketAddress; import java.net.SocketTimeoutException; import java.nio.BufferOverflowException; import java.nio.BufferUnderflowException; import java.nio.ByteBuffer; import java.nio.channels.ClosedChannelException; import java.nio.channels.FileChannel; import java.nio.channels.ReadableByteChannel; import java.nio.channels.WritableByteChannel; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.atomic.AtomicBoolean; import java.util.logging.Level; import java.util.logging.Logger; import javax.net.ssl.SSLContext; import org.xsocket.DataConverter; import org.xsocket.MaxReadSizeExceededException; /** * Implementation of the <code>IBlockingConnection</code> interface. Internally a {@link INonBlockingConnection} * will be used. A <code>BlockingConnection</code> wraps a <code>INonBlockingConnection</code>. There are two ways to * create a <code>BlockingConnection</code>: * <ul> * <li>by passing over the remote address (e.g. host name & port), or</li> * <li>by passing over a <code>INonBlockingConnection</code>, which will be wrapped</li> * </ul> * <br><br> * * A newly created connection is in the open state. Write or read methods can be called immediately <br><br> * * <b>The methods of this class are not thread-safe.</b> * * @author grro@xsocket.org */ public class BlockingConnection implements IBlockingConnection { private static final Logger LOG = Logger.getLogger(BlockingConnection.class.getName()); public static final String READ_TIMEOUT_KEY = "org.xsocket.connection.readtimeoutMillis"; public static final int DEFAULT_TIMEOUT = Integer.parseInt(System.getProperty(READ_TIMEOUT_KEY, Integer.toString(DEFAULT_READ_TIMEOUT))); private final ReadNotificationHandler handler = new ReadNotificationHandler(); private final Object readGuard = new Object(); private final INonBlockingConnection delegate; private int readTimeout = DEFAULT_TIMEOUT; private AtomicBoolean disconnected = new AtomicBoolean(false); private AtomicBoolean idleTimeout = new AtomicBoolean(false); private AtomicBoolean connectionTimeout = new AtomicBoolean(false); private AtomicBoolean isClosed = new AtomicBoolean(false); /** * constructor. <br><br> * * @param hostname the remote host * @param port the port of the remote host to connect * @throws IOException If some other I/O error occurs */ public BlockingConnection(String hostname, int port) throws IOException { this(new InetSocketAddress(hostname, port), null, true, Integer.MAX_VALUE, new HashMap<String, Object>(), null, false); } /** * constructor. <br><br> * * @param hostname the remote host * @param port the port of the remote host to connect * @param options the socket options * @throws IOException If some other I/O error occurs */ public BlockingConnection(String hostname, int port, Map<String, Object> options) throws IOException { this(new InetSocketAddress(hostname, port), null, true, Integer.MAX_VALUE, options, null, false); } /** * constructor * * @param address the remote host address * @param port the remote host port * @throws IOException If some other I/O error occurs */ public BlockingConnection(InetAddress address, int port) throws IOException { this(address, port, Integer.MAX_VALUE, new HashMap<String, Object>(), null, false); } /** * constructor * * @param address the remote host address * @param port the remote host port * @param connectTimeoutMillis the timeout of the connect procedure * @throws IOException If some other I/O error occurs */ public BlockingConnection(InetAddress address, int port, int connectTimeoutMillis) throws IOException{ this(new InetSocketAddress(address, port), null, true, connectTimeoutMillis, new HashMap<String, Object>(), null, false); } /** * constructor * * @param address the remote host name * @param port the remote host port * @param sslContext the sslContext to use * @param sslOn true, activate SSL mode. false, ssl can be activated by user (see {@link IReadWriteableConnection#activateSecuredMode()}) * @throws IOException If some other I/O error occurs */ public BlockingConnection(InetAddress address, int port, SSLContext sslContext, boolean sslOn) throws IOException { this(new InetSocketAddress(address, port), null, true, Integer.MAX_VALUE, new HashMap<String, Object>(), sslContext, sslOn); } /** * constructor * * @param address the remote host name * @param port the remote host port * @param connectTimeoutMillis the timeout of the connect procedure * @param sslContext the sslContext to use * @param sslOn true, activate SSL mode. false, ssl can be activated by user (see {@link IReadWriteableConnection#activateSecuredMode()}) * @throws IOException If some other I/O error occurs */ public BlockingConnection(InetAddress address, int port, int connectTimeoutMillis, SSLContext sslContext, boolean sslOn) throws IOException { this(new InetSocketAddress(address, port), null, true, connectTimeoutMillis, new HashMap<String, Object>(), sslContext, sslOn); } /** * constructor * * @param address the remote host name * @param port the remote host port * @param options the socket options * @param sslContext the sslContext to use * @param sslOn true, activate SSL mode. false, ssl can be activated by user (see {@link IReadWriteableConnection#activateSecuredMode()}) * @throws IOException If some other I/O error occurs */ public BlockingConnection(InetAddress address, int port, Map<String, Object> options, SSLContext sslContext, boolean sslOn) throws IOException { this(new InetSocketAddress(address, port), null, true, Integer.MAX_VALUE, options, sslContext, sslOn); } /** * constructor * * @param address the remote host name * @param port the remote host port * @param connectTimeoutMillis the timeout of the connect procedure * @param options the socket options * @param sslContext the sslContext to use * @param sslOn true, activate SSL mode. false, ssl can be activated by user (see {@link IReadWriteableConnection#activateSecuredMode()}) * @throws IOException If some other I/O error occurs */ public BlockingConnection(InetAddress address, int port, int connectTimeoutMillis, Map<String, Object> options, SSLContext sslContext, boolean sslOn) throws IOException { this(new InetSocketAddress(address, port), null, true, connectTimeoutMillis, options, sslContext, sslOn); } /** * constructor * * @param hostname the remote host name * @param port the remote host port * @param sslContext the sslContext to use or <null> * @param sslOn true, activate SSL mode. false, ssl can be activated by user (see {@link IReadWriteableConnection#activateSecuredMode()}) * @throws IOException If some other I/O error occurs */ public BlockingConnection(String hostname, int port, SSLContext sslContext, boolean sslOn) throws IOException { this(new InetSocketAddress(hostname, port), null, true, Integer.MAX_VALUE, new HashMap<String, Object>(), sslContext, sslOn); } /** * constructor * * @param remoteAddress the remote address * @param localAddress the local address * @param waitForConnect true, if the constructor should block until the connection is established. * @param connectTimeoutMillis the connection timeout * @param options the socket options * @param sslContext the ssl context or <null> * @param sslOn true, if ssl mode * @throws IOException If some other I/O error occurs */ public BlockingConnection(InetSocketAddress remoteAddress, InetSocketAddress localAddress, boolean waitForConnect, int connectTimeoutMillis, Map<String, Object> options, SSLContext sslContext, boolean sslOn) throws IOException { this.delegate= new NonBlockingConnection(remoteAddress, localAddress, handler, waitForConnect, connectTimeoutMillis, options, sslContext, sslOn); } /** * Constructor. <br><br> * * By creating a BlokingConnection based on the given NonBlockingConnection the * assigned handler of the NonBlockingConnection will be removed (if exists). Take * care by using this on the server-side (see tutorial for more informations). * * @param delegate the underlying non blocking connection * @throws IOException If some other I/O error occurs */ public BlockingConnection(INonBlockingConnection delegate) throws IOException { this.delegate = delegate; delegate.setHandler(handler); } final INonBlockingConnection getDelegate() { return delegate; } /** * {@inheritDoc} */ public void setReadTimeoutMillis(int timeout) throws IOException { this.readTimeout = timeout; int soTimeout = (Integer) delegate.getOption(SO_TIMEOUT); if (timeout > soTimeout) { delegate.setOption(SO_TIMEOUT, timeout); } } /** * {@inheritDoc} */ public void setReceiveTimeoutMillis(int timeout) throws IOException { setReadTimeoutMillis(timeout); } /** * {@inheritDoc} */ public final int getReceiveTimeoutMillis() throws IOException { return getReadTimeoutMillis(); } /** * {@inheritDoc} */ public int getReadTimeoutMillis() throws IOException { return readTimeout; } /** * {@inheritDoc} */ public int getMaxReadBufferThreshold() { return delegate.getMaxReadBufferThreshold(); } /** * {@inheritDoc} */ public void setMaxReadBufferThreshold(int size) { delegate.setMaxReadBufferThreshold(size); } /** * {@inheritDoc} */ public final void setEncoding(String defaultEncoding) { delegate.setEncoding(defaultEncoding); } /** * {@inheritDoc} */ public final String getEncoding() { return delegate.getEncoding(); } /** * return if the data source is open. Default is true * @return true, if the data source is open */ public final boolean isOpen() { return !isClosed.get() && delegate.isOpen(); } /** * {@inheritDoc} */ public boolean isServerSide() { return delegate.isServerSide(); } /** * {@inheritDoc} */ public final void close() throws IOException { isClosed.set(true); delegate.close(); } /** * {@inheritDoc} */ public final void flush() throws ClosedChannelException, IOException, SocketTimeoutException { delegate.flush(); } /** * {@inheritDoc} */ public String getId() { return delegate.getId(); } /** * {@inheritDoc} */ public final InetAddress getRemoteAddress() { return delegate.getRemoteAddress(); } /** * {@inheritDoc} */ public final int getRemotePort() { return delegate.getRemotePort(); } /** * {@inheritDoc} */ public final InetAddress getLocalAddress() { return delegate.getLocalAddress(); } /** * {@inheritDoc} */ public final int getLocalPort() { return delegate.getLocalPort(); } /** * {@inheritDoc} */ public final int getPendingWriteDataSize() { return delegate.getPendingWriteDataSize(); } /** * {@inheritDoc} */ public final void suspendRead() throws IOException { delegate.suspendReceiving(); } /** * {@inheritDoc} */ public boolean isReadSuspended() { return delegate.isReceivingSuspended(); } /** * {@inheritDoc} */ public final void resumeRead() throws IOException { delegate.resumeReceiving(); } /** * {@inheritDoc} */ public boolean isReceivingSuspended() { return delegate.isReceivingSuspended(); } /** * {@inheritDoc} */ public void resumeReceiving() throws IOException { delegate.resumeReceiving(); } /** * {@inheritDoc} */ public void suspendReceiving() throws IOException { delegate.suspendReceiving(); } /** * {@inheritDoc} */ public void setFlushmode(FlushMode flushMode) { delegate.setFlushmode(flushMode); } /** * {@inheritDoc} */ public FlushMode getFlushmode() { return delegate.getFlushmode(); } /** * {@inheritDoc} */ public final void setOption(String name, Object value) throws IOException { delegate.setOption(name, value); } /** * {@inheritDoc} */ public final Object getOption(String name) throws IOException { return delegate.getOption(name); } /** * {@inheritDoc} */ @SuppressWarnings("unchecked") public final Map<String, Class> getOptions() { return delegate.getOptions(); } /** * {@inheritDoc} */ public final void setIdleTimeoutMillis(long timeoutInMillis) { delegate.setIdleTimeoutMillis(timeoutInMillis); } /** * {@inheritDoc} */ public final long getIdleTimeoutMillis() { return delegate.getIdleTimeoutMillis(); } /** * {@inheritDoc} */ public final void setConnectionTimeoutMillis(long timeoutMillis) { delegate.setConnectionTimeoutMillis(timeoutMillis); } /** * {@inheritDoc} */ public final long getConnectionTimeoutMillis() { return delegate.getConnectionTimeoutMillis(); } /** * {@inheritDoc} */ public long getRemainingMillisToConnectionTimeout() { return delegate.getRemainingMillisToConnectionTimeout(); } /** * {@inheritDoc} */ public long getRemainingMillisToIdleTimeout() { return delegate.getRemainingMillisToIdleTimeout(); } /** * {@inheritDoc} */ public final void setAttachment(Object obj) { delegate.setAttachment(obj); } /** * {@inheritDoc} */ public final Object getAttachment() { return delegate.getAttachment(); } /** * {@inheritDoc} */ public final void setAutoflush(boolean autoflush) { delegate.setAutoflush(autoflush); } /** * {@inheritDoc} */ public final boolean isAutoflush() { return delegate.isAutoflush(); } /** * {@inheritDoc} */ public final void activateSecuredMode() throws IOException { delegate.activateSecuredMode(); } /** * {@inheritDoc} */ public void deactivateSecuredMode() throws IOException { delegate.deactivateSecuredMode(); } /** * {@inheritDoc} */ public boolean isSecure() { return delegate.isSecure(); } /** * {@inheritDoc} */ public final void markReadPosition() { delegate.markReadPosition(); } /** * {@inheritDoc} */ public final void markWritePosition() { delegate.markWritePosition(); } /** * {@inheritDoc}. */ public void unread(ByteBuffer[] buffers) throws IOException { delegate.unread(buffers); } /** * {@inheritDoc}. */ public void unread(byte[] bytes) throws IOException { delegate.unread(bytes); } /** * {@inheritDoc}. */ public void unread(ByteBuffer buffer) throws IOException { delegate.unread(buffer); } /** * {@inheritDoc}. */ public void unread(String text) throws IOException { delegate.unread(text); } /** * {@inheritDoc}. */ public final int read(ByteBuffer buffer) throws IOException, ClosedChannelException { int size = buffer.remaining(); if (size < 1) { return 0; } return new ByteBufferReadTask(buffer).read(); } private final class ByteBufferReadTask extends ReadTask<Integer> { private final ByteBuffer buffer; public ByteBufferReadTask(ByteBuffer buffer) { this.buffer = buffer; } @Override Integer doRead() throws IOException, SocketTimeoutException, MaxReadSizeExceededException { try { available(1); // ensure that at minimum the required length is available return delegate.read(buffer); } catch (ClosedChannelException cce) { if (!isClosed.getAndSet(true)) { return -1; } else { throw cce; } } } } private Integer getSize() { try { return delegate.available(); } catch (IOException ioe) { return null; } } /** * {@inheritDoc} */ public final byte readByte() throws IOException, SocketTimeoutException { return new ByteReadTask().read(); } private final class ByteReadTask extends ReadTask<Byte> { @Override Byte doRead() throws IOException, SocketTimeoutException, MaxReadSizeExceededException { return delegate.readByte(); } } /** * {@inheritDoc} */ public final short readShort() throws IOException, SocketTimeoutException { return new ShortReadTask().read(); } private final class ShortReadTask extends ReadTask<Short> { @Override Short doRead() throws IOException, SocketTimeoutException, MaxReadSizeExceededException { return delegate.readShort(); } } /** * {@inheritDoc} */ public final int readInt() throws IOException, SocketTimeoutException { return new IntegerReadTask().read(); } private final class IntegerReadTask extends ReadTask<Integer> { @Override Integer doRead() throws IOException, SocketTimeoutException, MaxReadSizeExceededException { return delegate.readInt(); } } /** * {@inheritDoc} */ public final long readLong() throws IOException, SocketTimeoutException { return new LongReadTask().read(); } private final class LongReadTask extends ReadTask<Long> { @Override Long doRead() throws IOException, SocketTimeoutException, MaxReadSizeExceededException { return delegate.readLong(); } } /** * {@inheritDoc} */ public final double readDouble() throws IOException, SocketTimeoutException { return new DoubleReadTask().read(); } private final class DoubleReadTask extends ReadTask<Double> { @Override Double doRead() throws IOException, SocketTimeoutException, MaxReadSizeExceededException { return delegate.readDouble(); } } /** * {@inheritDoc} */ public final ByteBuffer[] readByteBufferByDelimiter(String delimiter) throws IOException, SocketTimeoutException { return readByteBufferByDelimiter(delimiter, getEncoding()); } /** * {@inheritDoc} */ public final ByteBuffer[] readByteBufferByDelimiter(String delimiter, int maxLength) throws IOException, MaxReadSizeExceededException, SocketTimeoutException { return readByteBufferByDelimiter(delimiter, getEncoding(), maxLength); } /** * {@inheritDoc} */ public final ByteBuffer[] readByteBufferByDelimiter(String delimiter, String encoding) throws IOException, SocketTimeoutException { return readByteBufferByDelimiter(delimiter, encoding, Integer.MAX_VALUE); } /** * {@inheritDoc} */ public final ByteBuffer[] readByteBufferByDelimiter(String delimiter, String encoding, int maxLength) throws IOException, MaxReadSizeExceededException, SocketTimeoutException { return new ByteBuffersByDelimiterReadTask(delimiter, encoding, maxLength).read(); } private final class ByteBuffersByDelimiterReadTask extends ReadTask<ByteBuffer[]> { private final String delimiter; private final String encoding; private final int maxLength; public ByteBuffersByDelimiterReadTask(String delimiter, String encoding, final int maxLength) { this.delimiter = delimiter; this.encoding = encoding; this.maxLength = maxLength; } @Override ByteBuffer[] doRead() throws IOException, SocketTimeoutException, MaxReadSizeExceededException { return delegate.readByteBufferByDelimiter(delimiter, encoding, maxLength); } } /** * {@inheritDoc} */ public final ByteBuffer[] readByteBufferByLength(int length) throws IOException, SocketTimeoutException { if (length <= 0) { return new ByteBuffer[0]; } return new ByteBuffersByLengthReadTask(length).read(); } private final class ByteBuffersByLengthReadTask extends ReadTask<ByteBuffer[]> { private final int length; public ByteBuffersByLengthReadTask(int length) { this.length = length; } @Override ByteBuffer[] doRead() throws IOException, SocketTimeoutException, MaxReadSizeExceededException { return delegate.readByteBufferByLength(length); } } /** * {@inheritDoc} */ public final byte[] readBytesByDelimiter(String delimiter) throws IOException, SocketTimeoutException { return readBytesByDelimiter(delimiter, getEncoding()); } /** * {@inheritDoc} */ public final byte[] readBytesByDelimiter(String delimiter, int maxLength) throws IOException, MaxReadSizeExceededException, SocketTimeoutException { return readBytesByDelimiter(delimiter, getEncoding(), maxLength); } /** * {@inheritDoc} */ public final byte[] readBytesByDelimiter(String delimiter, String encoding) throws IOException, SocketTimeoutException { return readBytesByDelimiter(delimiter, encoding, Integer.MAX_VALUE); } /** * {@inheritDoc} */ public final byte[] readBytesByDelimiter(String delimiter, String encoding, int maxLength) throws IOException, MaxReadSizeExceededException, SocketTimeoutException { return DataConverter.toBytes(readByteBufferByDelimiter(delimiter, encoding, maxLength)); } /** * {@inheritDoc} */ public final byte[] readBytesByLength(int length) throws IOException, SocketTimeoutException { return DataConverter.toBytes(readByteBufferByLength(length)); } /** * {@inheritDoc} */ public final String readStringByDelimiter(String delimiter) throws IOException, UnsupportedEncodingException, SocketTimeoutException { return readStringByDelimiter(delimiter, Integer.MAX_VALUE); } /** * {@inheritDoc} */ public final String readStringByDelimiter(String delimiter, int maxLength) throws IOException, UnsupportedEncodingException, MaxReadSizeExceededException, SocketTimeoutException { return readStringByDelimiter(delimiter, getEncoding(), maxLength); } /** * {@inheritDoc} */ public final String readStringByDelimiter(String delimiter, String encoding) throws IOException, UnsupportedEncodingException, MaxReadSizeExceededException, SocketTimeoutException { return readStringByDelimiter(delimiter, encoding, Integer.MAX_VALUE); } /** * {@inheritDoc} */ public final String readStringByDelimiter(String delimiter, String encoding, int maxLength) throws IOException, UnsupportedEncodingException, MaxReadSizeExceededException, SocketTimeoutException { return DataConverter.toString(readByteBufferByDelimiter(delimiter, encoding, maxLength), encoding); } /** * {@inheritDoc} */ public final String readStringByLength(int length) throws IOException, UnsupportedEncodingException, SocketTimeoutException { return readStringByLength(length, getEncoding()); } /** * {@inheritDoc} */ public final String readStringByLength(int length, String encoding) throws IOException, UnsupportedEncodingException, SocketTimeoutException { return DataConverter.toString(readByteBufferByLength(length), encoding); } /** * {@inheritDoc} */ public final long transferTo(WritableByteChannel target, int length) throws IOException, SocketTimeoutException { long written = 0; ByteBuffer[] buffers = readByteBufferByLength(length); for (ByteBuffer buffer : buffers) { written += target.write(buffer); } return written; } /** * {@inheritDoc} */ public final boolean resetToWriteMark() { return delegate.resetToWriteMark(); } /** * {@inheritDoc} */ public final boolean resetToReadMark() { return delegate.resetToReadMark(); } /** * {@inheritDoc} */ public final void removeReadMark() { delegate.removeReadMark(); } /** * {@inheritDoc} */ public final void removeWriteMark() { delegate.removeWriteMark(); } /** * {@inheritDoc} */ public final int write(byte b) throws IOException, BufferOverflowException { return delegate.write(b); } /** * {@inheritDoc} */ public final int write(byte... bytes) throws IOException { return delegate.write(bytes); } /** * {@inheritDoc} */ public void write(byte[] bytes, IWriteCompletionHandler writeCompletionHandler) throws IOException { delegate.write(bytes, writeCompletionHandler); } /** * {@inheritDoc} */ public final int write(byte[] bytes, int offset, int length) throws IOException { return delegate.write(bytes, offset, length); } /** * {@inheritDoc} */ public void write(byte[] bytes, int offset, int length, IWriteCompletionHandler writeCompletionHandler) throws IOException { delegate.write(bytes, offset, length, writeCompletionHandler); } /** * {@inheritDoc} */ public final int write(short s) throws IOException { return delegate.write(s); } /** * {@inheritDoc} */ public final int write(int i) throws IOException { return delegate.write(i); } /** * {@inheritDoc} */ public final int write(long l) throws IOException { return delegate.write(l); } /** * {@inheritDoc} */ public final int write(double d) throws IOException { return delegate.write(d); } /** * {@inheritDoc} */ public final int write(String message) throws IOException { return delegate.write(message); } /** * {@inheritDoc} */ public final int write(String message, String encoding) throws IOException { return delegate.write(message, encoding); } /** * {@inheritDoc} */ public void write(String message, String encoding, IWriteCompletionHandler writeCompletionHandler) throws IOException { delegate.write(message, encoding, writeCompletionHandler); } /** * {@inheritDoc} */ public final long write(ArrayList<ByteBuffer> buffers) throws IOException { return delegate.write(buffers); } /** * {@inheritDoc} */ public final long write(List<ByteBuffer> buffers) throws IOException { return delegate.write(buffers); } /** * {@inheritDoc} */ public final long write(ByteBuffer[] buffers) throws IOException { return delegate.write(buffers); } /** * {@inheritDoc} */ public long write(ByteBuffer[] srcs, int offset, int length) throws IOException { return delegate.write(srcs, offset, length); } /** * {@inheritDoc} */ public final int write(ByteBuffer buffer) throws IOException { return delegate.write(buffer); } /** * {@inheritDoc} */ public void write(ByteBuffer buffer, IWriteCompletionHandler writeCompletionHandler) throws IOException { delegate.write(buffer, writeCompletionHandler); } /** * {@inheritDoc} */ public void write(ByteBuffer[] buffers, IWriteCompletionHandler writeCompletionHandler) throws IOException { delegate.write(buffers, writeCompletionHandler); } /** * {@inheritDoc} */ public void write(ByteBuffer[] srcs, int offset, int length, IWriteCompletionHandler writeCompletionHandler) throws IOException { delegate.write(srcs, offset,length, writeCompletionHandler); } /** * {@inheritDoc} */ public final long transferFrom(ReadableByteChannel source) throws IOException { return delegate.transferFrom(source); } /** * {@inheritDoc} */ public void write(List<ByteBuffer> buffers, IWriteCompletionHandler writeCompletionHandler) throws IOException { delegate.write(buffers, writeCompletionHandler); } /** * {@inheritDoc} */ public final long transferFrom(ReadableByteChannel source, int chunkSize) throws IOException { return delegate.transferFrom(source, chunkSize); } public long transferFrom(FileChannel source) throws IOException { return delegate.transferFrom(source); } @Override public String toString() { return delegate.toString(); } private void onReadDataInserted() { synchronized (readGuard) { readGuard.notifyAll(); } } final class ReadNotificationHandler implements IDataHandler, IDisconnectHandler, IConnectionTimeoutHandler, IIdleTimeoutHandler, IUnsynchronized { public boolean onData(INonBlockingConnection connection) throws IOException, BufferUnderflowException, MaxReadSizeExceededException { onReadDataInserted(); return true; } public boolean onDisconnect(INonBlockingConnection connection) throws IOException { disconnected.set(true); onReadDataInserted(); return true; } public boolean onConnectionTimeout(INonBlockingConnection connection) throws IOException { connectionTimeout.set(true); onReadDataInserted(); connection.close(); return true; } public boolean onIdleTimeout(INonBlockingConnection connection) throws IOException { idleTimeout.set(true); onReadDataInserted(); connection.close(); return true; } } private abstract class ReadTask<T extends Object> { final T read() throws IOException, SocketTimeoutException, MaxReadSizeExceededException { long start = System.currentTimeMillis(); long remainingTime = readTimeout; do { int revision = delegate.getReadBufferVersion(); try { try { return doRead(); } catch (RevisionAwareBufferUnderflowException rbe) { synchronized (readGuard) { if (rbe.getRevision() != delegate.getReadBufferVersion()) { continue; } else { throw new BufferUnderflowException(); // "jump" into catch (BufferUnderflowException) } } } } catch (BufferUnderflowException bue) { synchronized (readGuard) { // no notification event is occurred meanwhile if (revision == delegate.getReadBufferVersion()) { // no more data expected? (connection is destroyed) if (disconnected.get()) { throw new ExtendedClosedChannelException("channel " + getId() + " is closed (read buffer size=" + getSize() + ")"); } else { if (LOG.isLoggable(Level.FINE)) { LOG.fine("waiting for more reveived data (guard: " + readGuard + ")"); } try { readGuard.wait(remainingTime); } catch (InterruptedException ie) { // Restore the interrupted status Thread.currentThread().interrupt(); } } } } } long elpased = System.currentTimeMillis() - start; remainingTime -= elpased; } while (remainingTime > 0); if (LOG.isLoggable(Level.FINE)) { LOG.fine("receive timeout " + readTimeout + " sec reached. throwing timeout exception"); } throw new SocketTimeoutException("timeout " + readTimeout + " millis reached"); } protected final int available(int required) throws IOException, BufferUnderflowException, ClosedChannelException { synchronized (readGuard) { int available = delegate.available(); if (available == -1) { throw new ClosedChannelException(); } else if (available < required) { throw new RevisionAwareBufferUnderflowException(delegate.getReadBufferVersion()); } else { return available; } } } abstract T doRead() throws IOException, SocketTimeoutException, MaxReadSizeExceededException; } private static final class RevisionAwareBufferUnderflowException extends BufferUnderflowException { private static final long serialVersionUID = -5623771436953505286L; private final int revision; public RevisionAwareBufferUnderflowException(int revision) { this.revision = revision; } public int getRevision() { return revision; } } }
zzh-simple-hr
Zxsocket/src/org/xsocket/connection/BlockingConnection.java
Java
art
35,689
/* * Copyright (c) xlightweb.org, 2006 - 2010. All rights reserved. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * Please refer to the LGPL license at: http://www.gnu.org/copyleft/lesser.txt * The latest copy of this software may be found on http://www.xsocket.org/ */ package org.xsocket.connection; import java.io.IOException; import java.net.BindException; import java.net.InetAddress; import java.net.InetSocketAddress; import java.nio.channels.ServerSocketChannel; import java.nio.channels.SocketChannel; import java.util.Collections; import java.util.HashMap; import java.util.Map; import java.util.concurrent.atomic.AtomicBoolean; import java.util.logging.Level; import java.util.logging.Logger; import javax.net.ssl.SSLContext; import org.xsocket.DataConverter; /** * The acceptor is responsible to accept new incoming connections, and * register these on the dispatcher.<br><br> * * @author grro@xsocket.org */ final class IoAcceptor { private static final Logger LOG = Logger.getLogger(IoAcceptor.class.getName()); private static final String SO_RCVBUF = IServer.SO_RCVBUF; private static final String SO_REUSEADDR = IServer.SO_REUSEADDR; @SuppressWarnings("unchecked") private static final Map<String, Class> SUPPORTED_OPTIONS = new HashMap<String, Class>(); static { SUPPORTED_OPTIONS.put(SO_RCVBUF, Integer.class); SUPPORTED_OPTIONS.put(SO_REUSEADDR, Boolean.class); } // io handler private IIoAcceptorCallback callback; // open flag private final AtomicBoolean isOpen = new AtomicBoolean(true); // Socket private final ServerSocketChannel serverChannel; // SSL private final boolean sslOn; private final SSLContext sslContext; // dispatcher pool private final IoSocketDispatcherPool dispatcherPool; // statistics private long acceptedConnections; private long lastRequestAccpetedRate = System.currentTimeMillis(); public IoAcceptor(IIoAcceptorCallback callback, InetSocketAddress address, int backlog, boolean isReuseAddress) throws IOException { this(callback, address, backlog, null, false, isReuseAddress); } public IoAcceptor(IIoAcceptorCallback callback, InetSocketAddress address, int backlog, SSLContext sslContext, boolean sslOn, boolean isReuseAddress) throws IOException { this.callback = callback; this.sslContext = sslContext; this.sslOn = sslOn; LOG.fine("try to bind server on " + address); // create a new server socket serverChannel = ServerSocketChannel.open(); assert (serverChannel != null); serverChannel.configureBlocking(true); serverChannel.socket().setSoTimeout(0); // accept method never times out serverChannel.socket().setReuseAddress(isReuseAddress); try { serverChannel.socket().bind(address, backlog); dispatcherPool = new IoSocketDispatcherPool("Srv" + getLocalPort(), IoProvider.getServerDispatcherInitialSize()); } catch (BindException be) { serverChannel.close(); LOG.warning("could not bind server to " + address + ". Reason: " + DataConverter.toString(be)); throw be; } } void setOption(String name, Object value) throws IOException { if (name.equals(SO_RCVBUF)) { serverChannel.socket().setReceiveBufferSize((Integer) value); } else if (name.equals(SO_REUSEADDR)) { serverChannel.socket().setReuseAddress((Boolean) value); } else { LOG.warning("option " + name + " is not supproted for " + this.getClass().getName()); } } boolean isSSLSupported() { return (sslContext != null); } boolean isSSLOn() { return sslOn; } /** * {@inheritDoc} */ public Object getOption(String name) throws IOException { if (name.equals(SO_RCVBUF)) { return serverChannel.socket().getReceiveBufferSize(); } else if (name.equals(SO_REUSEADDR)) { return serverChannel.socket().getReuseAddress(); } else { LOG.warning("option " + name + " is not supproted for " + this.getClass().getName()); return null; } } @SuppressWarnings("unchecked") public Map<String, Class> getOptions() { return Collections.unmodifiableMap(SUPPORTED_OPTIONS); } IoSocketDispatcherPool getDispatcherPool() { return dispatcherPool; } /** * {@inheritDoc} */ public InetAddress getLocalAddress() { return serverChannel.socket().getInetAddress(); } /** * {@inheritDoc} */ public int getLocalPort() { return serverChannel.socket().getLocalPort(); } /** * {@inheritDoc} */ public void listen() throws IOException { callback.onConnected(); accept(); } private void accept() { while (isOpen.get()) { try { // blocking accept call SocketChannel channel = serverChannel.accept(); // create IoSocketHandler IoSocketDispatcher dispatcher = dispatcherPool.nextDispatcher(); IoChainableHandler ioHandler = ConnectionUtils.getIoProvider().createIoHandler(false, dispatcher, channel, sslContext, sslOn); // notify call back callback.onConnectionAccepted(ioHandler); acceptedConnections++; } catch (Exception e) { // if acceptor is running (<socket>.close() causes that any // thread currently blocked in accept() will throw a SocketException) if (serverChannel.isOpen()) { LOG.warning("error occured while accepting connection: " + DataConverter.toString(e)); } } } } /** * {@inheritDoc} */ public void close() throws IOException { if (isOpen.get()) { isOpen.set(false); if (LOG.isLoggable(Level.FINE)) { LOG.fine("closing acceptor"); } try { // closes the server socket serverChannel.close(); } catch (Exception e) { // eat and log exception if (LOG.isLoggable(Level.FINE)) { LOG.fine("error occured by closing " + e.toString()); } } dispatcherPool.close(); callback.onDisconnected(); callback = null; // unset reference to server } } void setDispatcherSize(int size) { dispatcherPool.setDispatcherSize(size); } int getDispatcherSize() { return dispatcherPool.getDispatcherSize(); } boolean getReceiveBufferIsDirect() { return dispatcherPool.getReceiveBufferIsDirect(); } void setReceiveBufferIsDirect(boolean isDirect) { dispatcherPool.setReceiveBufferIsDirect(isDirect); } boolean isReceiveBufferPreallocationMode() { return dispatcherPool.isReceiveBufferPreallocationMode(); } void setReceiveBufferPreallocationMode(boolean mode) { dispatcherPool.setReceiveBufferPreallocationMode(mode); } void setReceiveBufferPreallocatedMinSize(Integer minSize) { dispatcherPool.setReceiveBufferPreallocatedMinSize(minSize); } Integer getReceiveBufferPreallocatedMinSize() { return dispatcherPool.getReceiveBufferPreallocatedMinSize(); } /** * get the size of the preallocation buffer, * for reading incoming data * * @return preallocation buffer size */ Integer getReceiveBufferPreallocationSize() { return dispatcherPool.getReceiveBufferPreallocationSize(); } /** * set the size of the preallocation buffer, * for reading incoming data * * @param size the preallocation buffer size */ void setReceiveBufferPreallocationSize(int size) { dispatcherPool.setReceiveBufferPreallocationSize(size); } double getAcceptedRateCountPerSec() { double rate = 0; long elapsed = System.currentTimeMillis() - lastRequestAccpetedRate; if (acceptedConnections == 0) { rate = 0; } else if (elapsed == 0) { rate = Integer.MAX_VALUE; } else { rate = (((double) (acceptedConnections * 1000)) / elapsed); } lastRequestAccpetedRate = System.currentTimeMillis(); acceptedConnections = 0; return rate; } long getSendRateBytesPerSec() { return dispatcherPool.getSendRateBytesPerSec(); } long getReceiveRateBytesPerSec() { return dispatcherPool.getReceiveRateBytesPerSec(); } }
zzh-simple-hr
Zxsocket/src/org/xsocket/connection/IoAcceptor.java
Java
art
9,846
/* * Copyright (c) xlightweb.org, 2006 - 2010. All rights reserved. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * Please refer to the LGPL license at: http://www.gnu.org/copyleft/lesser.txt * The latest copy of this software may be found on http://www.xsocket.org/ */ package org.xsocket.connection; import java.io.IOException; /** * acceptor callback <br><br> * * @author grro@xsocket.org */ interface IIoAcceptorCallback { /** * notifies that the acceptor has been bound to the socket, and * accepts incoming connections * */ void onConnected(); /** * notifies that the acceptor has been unbound * */ void onDisconnected(); /** * notifies a new incoming connection * * @param ioHandler the assigned io handler of the new connection * @throws IOException If some other I/O error occurs */ void onConnectionAccepted(IoChainableHandler ioHandler) throws IOException; }
zzh-simple-hr
Zxsocket/src/org/xsocket/connection/IIoAcceptorCallback.java
Java
art
1,697
/* * Copyright (c) xlightweb.org, 2006 - 2010. All rights reserved. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * Please refer to the LGPL license at: http://www.gnu.org/copyleft/lesser.txt * The latest copy of this software may be found on http://www.xsocket.org/ */ package org.xsocket.connection; import java.io.IOException; import java.net.InetAddress; import java.net.InetSocketAddress; import java.net.Socket; import java.nio.ByteBuffer; import java.nio.channels.SocketChannel; import java.util.Map; import java.util.Random; import java.util.Timer; import java.util.UUID; import java.util.Map.Entry; import java.util.concurrent.atomic.AtomicInteger; import java.util.logging.Level; import java.util.logging.Logger; import javax.net.ssl.SSLContext; import org.xsocket.DataConverter; /** * IoProvider * * * @author grro@xsocket.org */ final class IoProvider { private static final Logger LOG = Logger.getLogger(IoProvider.class.getName()); static final String SO_SNDBUF = IConnection.SO_SNDBUF; static final String SO_RCVBUF = IConnection.SO_RCVBUF; static final String SO_REUSEADDR = IConnection.SO_REUSEADDR; static final String SO_TIMEOUT = "SOL_SOCKET.SO_TIMEOUT"; static final String SO_KEEPALIVE = IConnection.SO_KEEPALIVE; static final String SO_LINGER = IConnection.SO_LINGER; static final String TCP_NODELAY = IConnection.TCP_NODELAY; static final int UNLIMITED = INonBlockingConnection.UNLIMITED; static final long DEFAULT_CONNECTION_TIMEOUT_MILLIS = IConnection.DEFAULT_CONNECTION_TIMEOUT_MILLIS; static final long DEFAULT_IDLE_TIMEOUT_MILLIS = IConnection.DEFAULT_IDLE_TIMEOUT_MILLIS; private static final Timer TIMER = new Timer("xIoTimer", true); private static IoSocketDispatcherPool globalClientDispatcherPool; // transfer props static final String TRANSFER_MAPPED_BYTE_BUFFER_MAX_MAP_SIZE_KEY = "org.xsocket.connection.transfer.mappedbytebuffer.maxsize"; static final int DEFAULT_TRANSFER_BYTE_BUFFER_MAX_MAP_SIZE = 16384; private static Integer transferByteBufferMaxSize; // connection props public static final String SUPPRESS_SYNC_FLUSH_WARNING_KEY = "org.xsocket.connection.suppressSyncFlushWarning"; public static final String DEFAULT_SUPPRESS_SYNC_FLUSH_WARNING = "false"; public static final String SUPPRESS_REUSE_BUFFER_WARNING_KEY = "org.xsocket.connection.suppressReuseBufferWarning"; public static final String DEFAULT_SUPPRESS_REUSE_BUFFER_WARNING = "false"; public static final String SUPPRESS_SYNC_FLUSH_COMPLETION_HANDLER_WARNING_KEY = "org.xsocket.connection.suppressSyncFlushCompletionHandlerWarning"; public static final String DEFAULT_SUPPRESS_SYNC_FLUSH_COMPLETION_HANDLER_WARNING = "false"; private static boolean IS_REUSE_ADDRESS = Boolean.parseBoolean(System.getProperty("org.xsocket.connection.server.reuseaddress", "true")); // dispatcher props public static final String COUNT_DISPATCHER_KEY = "org.xsocket.connection.dispatcher.initialCount"; private static final String COUNT_SERVER_DISPATCHER_KEY = "org.xsocket.connection.server.dispatcher.initialCount"; private static final String COUNT_CLIENT_DISPATCHER_KEY = "org.xsocket.connection.client.dispatcher.initialCount"; private static final String MAX_HANDLES = "org.xsocket.connection.dispatcher.maxHandles"; private static final String DETACH_HANDLE_ON_NO_OPS = "org.xsocket.connection.dispatcher.detachHandleOnNoOps"; private static final String DEFAULT_DETACH_HANDLE_ON_NO_OPS = "false"; private static final String IS_BYPASSING_WRITE_ALLOWED = "org.xsocket.connection.dispatcher.bypassingWriteAllowed"; private static final String DEFAULT_IS_BYPASSING_WRITE_ALLOWED = "true"; //////////////////////////////////////////////// // use direct buffer or non-direct buffer? // // current vm implementations (Juli/2007) seems to have // problems by gc direct buffers. // // links // * [Java bugdatabase] http://bugs.sun.com/bugdatabase/view_bug.do;jsessionid=94d5403110224b692e5354bd87a92:WuuT?bug_id=6210541 // * [forum thread] http://forums.java.net/jive/thread.jspa?messageID=223706&tstart=0 // * [mina] https://issues.apache.org/jira/browse/DIRMINA-391 // //////////////////////////////////////////////// // direct buffer? public static final String DEFAULT_USE_DIRECT_BUFFER = "false"; public static final String CLIENT_READBUFFER_USE_DIRECT_KEY = "org.xsocket.connection.client.readbuffer.usedirect"; public static final String SERVER_READBUFFER_USE_DIRECT_KEY = "org.xsocket.connection.server.readbuffer.usedirect"; private static final String WRITE_BUFFER_USE_DIRECT_KEY = "org.xsocket.connection.writebuffer.usedirect"; // preallocation params public static final String DEFAULT_READ_BUFFER_PREALLOCATION_ON = "true"; public static final int DEFAULT_READ_BUFFER_PREALLOCATION_SIZE = 16384; public static final int DEFAULT_READ_BUFFER_MIN_SIZE = 64; public static final String CLIENT_READBUFFER_PREALLOCATION_ON_KEY = "org.xsocket.connection.client.readbuffer.preallocation.on"; public static final String CLIENT_READBUFFER_PREALLOCATION_SIZE_KEY = "org.xsocket.connection.client.readbuffer.preallocation.size"; public static final String CLIENT_READBUFFER_PREALLOCATION_MIN_SIZE_KEY = "org.xsocket.connection.client.readbuffer.preallocated.minSize"; public static final String SERVER_READBUFFER_PREALLOCATION_ON_KEY = "org.xsocket.connection.server.readbuffer.preallocation.on"; public static final String SERVER_READBUFFER_PREALLOCATION_SIZE_KEY = "org.xsocket.connection.server.readbuffer.preallocation.size"; public static final String SERVER_READBUFFER_PREALLOCATION_MIN_SIZE_KEY = "org.xsocket.connection.server.readbuffer.preallocated.minSize"; public static final String DEFAULT_CLIENT_MAX_READBUFFER_SIZE_KEY = "org.xsocket.connection.client.readbuffer.defaultMaxReadBufferThreshold"; public static final String DEFAULT_SERVER_MAX_READBUFFER_SIZE_KEY = "org.xsocket.connection.server.readbuffer.defaultMaxReadBufferThreshold"; public static final String DEFAULT_CLIENT_MAX_WRITEBUFFER_SIZE_KEY = "org.xsocket.connection.client.readbuffer.defaultMaxWriteBufferThreshold"; public static final String DEFAULT_SERVER_MAX_WRITEBUFFER_SIZE_KEY = "org.xsocket.connection.server.readbuffer.defaultMaxWriteBufferThreshold"; private static Integer defaultClientMaxReadbufferSize; private static Integer defaultServerMaxReadbufferSize; private static Integer defaultClientMaxWritebufferSize; private static Integer defaultServerMaxWritebufferSize; private static final String SSLENGINE_CLIENT_ENABLED_CIPHER_SUITES_KEY = "org.xsocket.connection.client.ssl.sslengine.enabledCipherSuites"; private static final String SSLENGINE_SERVER_ENABLED_CIPHER_SUITES_KEY = "org.xsocket.connection.server.ssl.sslengine.enabledCipherSuites"; private static final String SSLENGINE_CLIENT_ENABLED_PROTOCOLS_KEY = "org.xsocket.connection.client.ssl.sslengine.enabledProtocols"; private static final String SSLENGINE_SERVER_ENABLED_PROTOCOLS_KEY = "org.xsocket.connection.server.ssl.sslengine.enabledProtocols"; private static final String SSLENGINE_SERVER_WANT_CLIENT_AUTH_KEY = "org.xsocket.connection.server.ssl.sslengine.wantClientAuth"; private static final String SSLENGINE_SERVER_NEED_CLIENT_AUTH_KEY = "org.xsocket.connection.server.ssl.sslengine.needClientAuth"; private static String[] sSLEngineClientEnabledCipherSuites; private static String[] sSLEngineServerEnabledCipherSuites; private static String[] sSLEngineClientEnabledProtocols; private static String[] sSLEngineServerEnabledProtocols; private static Boolean sSLEngineWantClientAuth; private static Boolean sSLEngineNeedClientAuth; private static Integer countDispatcher; private static Integer countClientDispatcher; private static Integer countServerDispatcher; private static Integer maxHandles; private static boolean detachHandleOnNoOps = true; private static boolean bypassingWriteAllowed = false; private static Boolean suppressSyncFlushWarning; private static boolean suppressSyncFlushCompletionHandlerWarning; private static Boolean suppressReuseBufferWarning; private static Boolean clientReadBufferUseDirect; private static Boolean serverReadBufferUseDirect; private static Boolean writeBufferUseDirect; private static Boolean clientReadBufferPreallocationOn; private static int clientReadBufferPreallocationsize = DEFAULT_READ_BUFFER_PREALLOCATION_SIZE; private static int clientReadBufferMinsize = DEFAULT_READ_BUFFER_MIN_SIZE; private static Boolean serverReadBufferPreallocationOn; private static int serverReadBufferPreallocationsize = DEFAULT_READ_BUFFER_PREALLOCATION_SIZE; private static int serverReadBufferMinsize = DEFAULT_READ_BUFFER_MIN_SIZE; private final static String idPrefix; static { countDispatcher = readIntProperty(COUNT_DISPATCHER_KEY); countClientDispatcher = readIntProperty(COUNT_CLIENT_DISPATCHER_KEY); countServerDispatcher = readIntProperty(COUNT_SERVER_DISPATCHER_KEY); maxHandles = readIntProperty(MAX_HANDLES); detachHandleOnNoOps = readBooleanProperty(DETACH_HANDLE_ON_NO_OPS, DEFAULT_DETACH_HANDLE_ON_NO_OPS); bypassingWriteAllowed = readBooleanProperty(IS_BYPASSING_WRITE_ALLOWED, DEFAULT_IS_BYPASSING_WRITE_ALLOWED); // transfer props transferByteBufferMaxSize = readIntProperty(TRANSFER_MAPPED_BYTE_BUFFER_MAX_MAP_SIZE_KEY, DEFAULT_TRANSFER_BYTE_BUFFER_MAX_MAP_SIZE); // coonection suppressSyncFlushWarning = readBooleanProperty(IoProvider.SUPPRESS_SYNC_FLUSH_WARNING_KEY, DEFAULT_SUPPRESS_SYNC_FLUSH_WARNING); suppressSyncFlushCompletionHandlerWarning = readBooleanProperty(IoProvider.SUPPRESS_SYNC_FLUSH_COMPLETION_HANDLER_WARNING_KEY, DEFAULT_SUPPRESS_SYNC_FLUSH_COMPLETION_HANDLER_WARNING); suppressReuseBufferWarning = readBooleanProperty(IoProvider.SUPPRESS_REUSE_BUFFER_WARNING_KEY, DEFAULT_SUPPRESS_REUSE_BUFFER_WARNING); // direct buffer? clientReadBufferUseDirect = readBooleanProperty(IoProvider.CLIENT_READBUFFER_USE_DIRECT_KEY, DEFAULT_USE_DIRECT_BUFFER); serverReadBufferUseDirect = readBooleanProperty(IoProvider.SERVER_READBUFFER_USE_DIRECT_KEY, DEFAULT_USE_DIRECT_BUFFER); writeBufferUseDirect = readBooleanProperty(IoProvider.WRITE_BUFFER_USE_DIRECT_KEY, DEFAULT_USE_DIRECT_BUFFER); // thresholds defaultClientMaxReadbufferSize = readIntProperty(IoProvider.DEFAULT_CLIENT_MAX_READBUFFER_SIZE_KEY); defaultServerMaxReadbufferSize = readIntProperty(IoProvider.DEFAULT_SERVER_MAX_READBUFFER_SIZE_KEY); defaultClientMaxWritebufferSize = readIntProperty(IoProvider.DEFAULT_CLIENT_MAX_WRITEBUFFER_SIZE_KEY); defaultServerMaxWritebufferSize = readIntProperty(IoProvider.DEFAULT_SERVER_MAX_WRITEBUFFER_SIZE_KEY); // ssl props sSLEngineServerEnabledProtocols = readStringArrayProperty(IoProvider.SSLENGINE_SERVER_ENABLED_PROTOCOLS_KEY, null); sSLEngineClientEnabledProtocols = readStringArrayProperty(IoProvider.SSLENGINE_CLIENT_ENABLED_PROTOCOLS_KEY, null); sSLEngineServerEnabledCipherSuites = readStringArrayProperty(IoProvider.SSLENGINE_SERVER_ENABLED_CIPHER_SUITES_KEY, null); sSLEngineClientEnabledCipherSuites = readStringArrayProperty(IoProvider.SSLENGINE_CLIENT_ENABLED_CIPHER_SUITES_KEY, null); sSLEngineWantClientAuth = readBooleanProperty(IoProvider.SSLENGINE_SERVER_WANT_CLIENT_AUTH_KEY, null); sSLEngineNeedClientAuth = readBooleanProperty(IoProvider.SSLENGINE_SERVER_NEED_CLIENT_AUTH_KEY, null); // preallocation clientReadBufferPreallocationOn = readBooleanProperty(IoProvider.CLIENT_READBUFFER_PREALLOCATION_ON_KEY, DEFAULT_READ_BUFFER_PREALLOCATION_ON); if (clientReadBufferPreallocationOn) { clientReadBufferPreallocationsize = readIntProperty(IoProvider.CLIENT_READBUFFER_PREALLOCATION_SIZE_KEY, DEFAULT_READ_BUFFER_PREALLOCATION_SIZE); clientReadBufferMinsize = readIntProperty(IoProvider.CLIENT_READBUFFER_PREALLOCATION_MIN_SIZE_KEY, DEFAULT_READ_BUFFER_MIN_SIZE); } serverReadBufferPreallocationOn = readBooleanProperty(IoProvider.SERVER_READBUFFER_PREALLOCATION_ON_KEY, DEFAULT_READ_BUFFER_PREALLOCATION_ON); if (serverReadBufferPreallocationOn) { serverReadBufferPreallocationsize = readIntProperty(IoProvider.SERVER_READBUFFER_PREALLOCATION_SIZE_KEY, DEFAULT_READ_BUFFER_PREALLOCATION_SIZE); serverReadBufferMinsize = readIntProperty(IoProvider.SERVER_READBUFFER_PREALLOCATION_MIN_SIZE_KEY, DEFAULT_READ_BUFFER_MIN_SIZE); } // prepare id prefix String base = null; try { base = InetAddress.getLocalHost().getHostAddress(); } catch (Exception e) { base = UUID.randomUUID().toString(); } int random = 0; Random rand = new Random(); do { random = rand.nextInt(); } while (random < 0); // ipaddress hash + currentTime + random idPrefix = Integer.toHexString(base.hashCode()) + Long.toHexString(System.currentTimeMillis()) + Integer.toHexString(random); if (LOG.isLoggable(Level.FINE)) { StringBuilder sb = new StringBuilder(); sb.append(IoProvider.class.getName() + " initialized ("); // disptacher params sb.append("countDispatcher=" + countDispatcher + " "); sb.append("maxHandles=" + maxHandles + " "); sb.append("detachHandleOnNoOps=" + detachHandleOnNoOps + " "); // client params sb.append("client: directMemory=" + clientReadBufferUseDirect); sb.append(" preallocation=" + clientReadBufferPreallocationOn); if (clientReadBufferPreallocationOn) { sb.append(" preallocationSize=" + DataConverter.toFormatedBytesSize(clientReadBufferPreallocationsize)); sb.append(" minBufferSize=" + DataConverter.toFormatedBytesSize(clientReadBufferMinsize)); } // server params sb.append(" & server: directMemory=" + serverReadBufferUseDirect); sb.append(" preallocation=" + serverReadBufferPreallocationOn); if (serverReadBufferPreallocationOn) { sb.append(" preallocationSize=" + DataConverter.toFormatedBytesSize(serverReadBufferPreallocationsize)); sb.append(" minBufferSize=" + DataConverter.toFormatedBytesSize(serverReadBufferMinsize)); } sb.append(")"); LOG.fine(sb.toString()); } } private AbstractMemoryManager sslMemoryManagerServer; private AbstractMemoryManager sslMemoryManagerClient; private final AtomicInteger nextId = new AtomicInteger(); IoProvider() { if (serverReadBufferPreallocationOn) { sslMemoryManagerServer = IoSynchronizedMemoryManager.createPreallocatedMemoryManager(serverReadBufferPreallocationsize, serverReadBufferMinsize, serverReadBufferUseDirect); } else { sslMemoryManagerServer = IoSynchronizedMemoryManager.createNonPreallocatedMemoryManager(serverReadBufferUseDirect); } if (clientReadBufferPreallocationOn) { sslMemoryManagerClient = IoSynchronizedMemoryManager.createPreallocatedMemoryManager(clientReadBufferPreallocationsize, clientReadBufferMinsize, clientReadBufferUseDirect); } else { sslMemoryManagerClient = IoSynchronizedMemoryManager.createNonPreallocatedMemoryManager(clientReadBufferUseDirect); } } static int getTransferByteBufferMaxSize() { return transferByteBufferMaxSize; } static String[] getSSLEngineServerEnabledCipherSuites() { return sSLEngineServerEnabledCipherSuites; } static String[] getSSLEngineClientEnabledCipherSuites() { return sSLEngineClientEnabledCipherSuites; } static String[] getSSLEngineClientEnabledProtocols() { return sSLEngineClientEnabledProtocols; } static String[] getSSLEngineServerEnabledProtocols() { return sSLEngineServerEnabledProtocols; } static Boolean getSSLEngineServerWantClientAuth() { return sSLEngineWantClientAuth; } static Boolean getSSLEngineServerNeedClientAuth() { return sSLEngineNeedClientAuth; } static Integer getDefaultClientMaxReadbufferSize() { return defaultClientMaxReadbufferSize; } static Integer getDefaultServerMaxReadbufferSize() { return defaultServerMaxReadbufferSize; } static Integer getDefaultClientMaxWritebufferSize() { return defaultClientMaxWritebufferSize; } static Integer getDefaultServerMaxWritebufferSize() { return defaultServerMaxWritebufferSize; } static boolean getSuppressSyncFlushWarning() { return suppressSyncFlushWarning; } static boolean getSuppressSyncFlushCompletionHandlerWarning() { return suppressSyncFlushCompletionHandlerWarning; } static boolean getSuppressReuseBufferWarning() { return suppressReuseBufferWarning; } static int getServerDispatcherInitialSize() { if (countServerDispatcher == null) { return getDispatcherInitialSize(); } else { return countServerDispatcher; } } static int getClientDispatcherInitialSize() { if (countClientDispatcher == null) { return getDispatcherInitialSize(); } else { return countClientDispatcher; } } private static int getDispatcherInitialSize() { if (countDispatcher == null) { return 2; } else { return countDispatcher; } } static Integer getMaxHandles() { return maxHandles; } static boolean getDetachHandleOnNoOps() { return detachHandleOnNoOps; } static boolean isBypassingWriteAllowed() { return bypassingWriteAllowed; } /** * Return the version of this implementation. It consists of any string assigned * by the vendor of this implementation and does not have any particular syntax * specified or expected by the Java runtime. It may be compared for equality * with other package version strings used for this implementation * by this vendor for this package. * * @return the version of the implementation */ public String getImplementationVersion() { return ""; } /** * {@inheritDoc} */ public IoAcceptor createAcceptor(IIoAcceptorCallback callback, InetSocketAddress address, int backlog, Map<String, Object> options) throws IOException { Boolean isReuseAddress = (Boolean) options.get(IConnection.SO_REUSEADDR); if (isReuseAddress == null) { isReuseAddress = IS_REUSE_ADDRESS; } IoAcceptor acceptor = new IoAcceptor(callback, address, backlog, isReuseAddress); for (Entry<String, Object> entry : options.entrySet()) { acceptor.setOption(entry.getKey(), entry.getValue()); } acceptor.setReceiveBufferIsDirect(serverReadBufferUseDirect); acceptor.setReceiveBufferPreallocationMode(serverReadBufferPreallocationOn); acceptor.setReceiveBufferPreallocatedMinSize(serverReadBufferMinsize); acceptor.setReceiveBufferPreallocationSize(serverReadBufferPreallocationsize); return acceptor; } /** * {@inheritDoc} */ public IoAcceptor createAcceptor(IIoAcceptorCallback callback, InetSocketAddress address, int backlog, Map<String, Object> options, SSLContext sslContext, boolean sslOn) throws IOException { Boolean isReuseAddress = (Boolean) options.get("SO_REUSEADDR"); if (isReuseAddress == null) { isReuseAddress = IS_REUSE_ADDRESS; } IoAcceptor acceptor = new IoAcceptor(callback, address, backlog, sslContext, sslOn, isReuseAddress); for (Entry<String, Object> entry : options.entrySet()) { acceptor.setOption(entry.getKey(), entry.getValue()); } acceptor.setReceiveBufferIsDirect(serverReadBufferUseDirect); acceptor.setReceiveBufferPreallocationMode(serverReadBufferPreallocationOn); acceptor.setReceiveBufferPreallocatedMinSize(serverReadBufferMinsize); acceptor.setReceiveBufferPreallocationSize(serverReadBufferPreallocationsize); return acceptor; } /** * {@inheritDoc} */ public IoChainableHandler createClientIoHandler(SocketChannel channel) throws IOException { return createIoHandler(true, getGlobalClientDisptacherPool().nextDispatcher(), channel, null, false); } /** * {@inheritDoc} */ public IoChainableHandler createSSLClientIoHandler(SocketChannel channel, SSLContext sslContext, boolean sslOn) throws IOException { return createIoHandler(true, getGlobalClientDisptacherPool().nextDispatcher(), channel, sslContext, sslOn); } /** * {@inheritDoc} */ IoChainableHandler createIoHandler(boolean isClient, IoSocketDispatcher dispatcher, SocketChannel channel, SSLContext sslContext, boolean sslOn) throws IOException { String connectionId = null; if (isClient) { connectionId = idPrefix + "C" + Integer.toHexString(nextId.incrementAndGet()); } else { connectionId = idPrefix + "S" + Integer.toHexString(nextId.incrementAndGet()); } IoChainableHandler ioHandler = new IoSocketHandler(channel, dispatcher, connectionId); // ssl connection? if (sslContext != null) { AbstractMemoryManager mm = null; if (isClient) { mm = sslMemoryManagerClient; } else { mm = sslMemoryManagerServer; } if (sslOn) { ioHandler = new IoSSLHandler(ioHandler, sslContext, isClient, mm); } else { ioHandler = new IoActivateableSSLHandler(ioHandler, sslContext, isClient, mm); } } return ioHandler; } /** * {@inheritDoc} */ public IoChainableHandler setWriteTransferRate(IoChainableHandler ioHandler, int bytesPerSecond) throws IOException { // unlimited? remove throttling handler if exists if (bytesPerSecond == UNLIMITED) { IoThrottledWriteHandler delayWriter = (IoThrottledWriteHandler) getHandler((IoChainableHandler) ioHandler, IoThrottledWriteHandler.class); if (delayWriter != null) { if (LOG.isLoggable(Level.FINE)) { LOG.fine("write transfer rate is set to unlimited. flushing throttle write handler"); } delayWriter.hardFlush(); IoChainableHandler successor = delayWriter.getSuccessor(); return successor; } else { return ioHandler; } // ...no -> add throttling handler if not exists and set rate } else { IoThrottledWriteHandler delayWriter = (IoThrottledWriteHandler) getHandler((IoChainableHandler) ioHandler, IoThrottledWriteHandler.class); if (delayWriter == null) { delayWriter = new IoThrottledWriteHandler((IoChainableHandler) ioHandler); } delayWriter.setWriteRateSec(bytesPerSecond); return delayWriter; } } public boolean isSecuredModeActivateable(IoChainableHandler ioHandler) { IoActivateableSSLHandler activateableHandler = (IoActivateableSSLHandler) getHandler(ioHandler, IoActivateableSSLHandler.class); if (activateableHandler != null) { return true; } else { return false; } } public boolean preActivateSecuredMode(IoChainableHandler ioHandler) throws IOException { IoActivateableSSLHandler activateableHandler = (IoActivateableSSLHandler) getHandler(ioHandler, IoActivateableSSLHandler.class); if (activateableHandler != null) { return activateableHandler.preActivateSecuredMode(); } else { throw new IOException("connection is not SSL activatable (non IoActivateableHandler in chain)"); } } public void activateSecuredMode(IoChainableHandler ioHandler, ByteBuffer[] buffers) throws IOException { ioHandler.hardFlush(); IoActivateableSSLHandler activateableHandler = (IoActivateableSSLHandler) getHandler((IoChainableHandler) ioHandler, IoActivateableSSLHandler.class); if (activateableHandler != null) { activateableHandler.activateSecuredMode(buffers); } else { LOG.warning("connection is not SSL activatable (non IoActivateableHandler in chain"); } } public void deactivateSecuredMode(IoChainableHandler ioHandler) throws IOException { ioHandler.hardFlush(); IoActivateableSSLHandler activateableHandler = (IoActivateableSSLHandler) getHandler((IoChainableHandler) ioHandler, IoActivateableSSLHandler.class); if (activateableHandler != null) { activateableHandler.deactivateSecuredMode(); } else { LOG.warning("connection is not SSL (de)activatable (non IoActivateableHandler in chain"); } } static Timer getTimer() { return TIMER; } static boolean isUseDirectWriteBuffer() { return writeBufferUseDirect; } static int getReadBufferPreallocationsizeServer() { return serverReadBufferPreallocationsize; } static int getReadBufferMinSizeServer() { return serverReadBufferMinsize; } static boolean isReadBufferPreallocationActivated() { return serverReadBufferPreallocationOn; } /** * set a option * * @param socket the socket * @param name the option name * @param value the option value * @throws IOException if an exception occurs */ static void setOption(Socket socket, String name, Object value) throws IOException { if (name.equals(SO_SNDBUF)) { socket.setSendBufferSize(asInt(value)); } else if (name.equals(SO_REUSEADDR)) { socket.setReuseAddress(asBoolean(value)); } else if (name.equals(SO_TIMEOUT)) { socket.setSoTimeout(asInt(value)); } else if (name.equals(SO_RCVBUF)) { socket.setReceiveBufferSize(asInt(value)); } else if (name.equals(SO_KEEPALIVE)) { socket.setKeepAlive(asBoolean(value)); } else if (name.equals(SO_LINGER)) { try { socket.setSoLinger(true, asInt(value)); } catch (ClassCastException cce) { socket.setSoLinger(Boolean.FALSE, 0); } } else if (name.equals(TCP_NODELAY)) { socket.setTcpNoDelay(asBoolean(value)); } else { LOG.warning("option " + name + " is not supported"); } } /** * get a option * * @param socket the socket * @param name the option name * @return the option value * @throws IOException if an exception occurs */ static Object getOption(Socket socket, String name) throws IOException { if (name.equals(SO_SNDBUF)) { return socket.getSendBufferSize(); } else if (name.equals(SO_REUSEADDR)) { return socket.getReuseAddress(); } else if (name.equals(SO_RCVBUF)) { return socket.getReceiveBufferSize(); } else if (name.equals(SO_KEEPALIVE)) { return socket.getKeepAlive(); } else if (name.equals(SO_TIMEOUT)) { return socket.getSoTimeout(); } else if (name.equals(TCP_NODELAY)) { return socket.getTcpNoDelay(); } else if (name.equals(SO_LINGER)) { return socket.getSoLinger(); } else { LOG.warning("option " + name + " is not supported"); return null; } } private static int asInt(Object obj) { if (obj instanceof Integer) { return (Integer) obj; } return Integer.parseInt(obj.toString()); } private static boolean asBoolean(Object obj) { if (obj instanceof Boolean) { return (Boolean) obj; } return Boolean.parseBoolean(obj.toString()); } @SuppressWarnings("unchecked") private IoChainableHandler getHandler(IoChainableHandler head, Class clazz) { IoChainableHandler handler = head; do { if (handler.getClass() == clazz) { return handler; } handler = handler.getSuccessor(); } while (handler != null); return null; } static synchronized IoSocketDispatcherPool getGlobalClientDisptacherPool() { if (globalClientDispatcherPool == null) { globalClientDispatcherPool = new IoSocketDispatcherPool("ClientGlb", getClientDispatcherInitialSize()); globalClientDispatcherPool.setReceiveBufferIsDirect(clientReadBufferUseDirect); globalClientDispatcherPool.setReceiveBufferPreallocationMode(clientReadBufferPreallocationOn); globalClientDispatcherPool.setReceiveBufferPreallocatedMinSize(clientReadBufferMinsize); globalClientDispatcherPool.setReceiveBufferPreallocationSize(clientReadBufferPreallocationsize); } return globalClientDispatcherPool; } private static Integer readIntProperty(String key) { try { String property = readProperty(key); if (property != null) { return Integer.parseInt(property); } else { return null; } } catch (Exception e) { LOG.warning("invalid value for system property " + key + ": " + System.getProperty(key) + " " + e.toString()); return null; } } private static Integer readIntProperty(String key, Integer dflt) { try { String property = readProperty(key); if (property != null) { return Integer.parseInt(property); } else { return dflt; } } catch (Exception e) { LOG.warning("invalid value for system property " + key + ": " + System.getProperty(key) + " (valid is int)" + " using " + dflt); return null; } } private static Boolean readBooleanProperty(String key, String dflt) { try { String property = readProperty(key); if (property != null) { return Boolean.parseBoolean(property); } else { if (dflt == null) { return null; } else { return Boolean.parseBoolean(dflt); } } } catch (Exception e) { LOG.warning("invalid value for system property " + key + ": " + System.getProperty(key) + " (valid is true|false)" + " using " + dflt); if (dflt != null) { return Boolean.parseBoolean(dflt); } else { return null; } } } private static String[] readStringArrayProperty(String key, String[] dflt) { String property = readProperty(key); if (property != null) { String[] props = property.split(","); String[] result = new String[props.length]; for (int i = 0; i < props.length; i++) { result[i] = props[i].trim(); } return result; } else { return dflt; } } private static String readProperty(String key) { try { return System.getProperty(key); } catch (Exception e) { LOG.warning("invalid value for system property " + key + " " + e.toString()); return null; } } }
zzh-simple-hr
Zxsocket/src/org/xsocket/connection/IoProvider.java
Java
art
31,411
/* * Copyright (c) xlightweb.org, 2006 - 2010. All rights reserved. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * Please refer to the LGPL license at: http://www.gnu.org/copyleft/lesser.txt * The latest copy of this software may be found on http://www.xsocket.org/ */ package org.xsocket.connection; /** * handler info * * @author grro@xsocket.org */ interface IHandlerInfo { boolean isConnectHandler(); boolean isDataHandler(); boolean isDisconnectHandler(); boolean isIdleTimeoutHandler(); boolean isConnectionTimeoutHandler(); boolean isLifeCycle(); boolean isConnectionScoped(); boolean isConnectExceptionHandler() ; boolean isUnsynchronized(); boolean isConnectExceptionHandlerMultithreaded(); boolean isConnectHandlerMultithreaded(); boolean isDataHandlerMultithreaded(); boolean isDisconnectHandlerMultithreaded(); boolean isIdleTimeoutHandlerMultithreaded(); boolean isConnectionTimeoutHandlerMultithreaded(); }
zzh-simple-hr
Zxsocket/src/org/xsocket/connection/IHandlerInfo.java
Java
art
1,791