You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@uima.apache.org by re...@apache.org on 2013/01/11 00:12:37 UTC
svn commit: r1431721 [13/19] - in /uima/sandbox/uimafit/trunk:
uimafit-examples/src/main/java/org/apache/uima/fit/examples/experiment/pos/
uimafit-examples/src/main/java/org/apache/uima/fit/examples/getstarted/
uimafit-examples/src/main/java/org/apache...
Modified: uima/sandbox/uimafit/trunk/uimafit/src/main/java/org/apache/uima/fit/util/JCasUtil.java
URL: http://svn.apache.org/viewvc/uima/sandbox/uimafit/trunk/uimafit/src/main/java/org/apache/uima/fit/util/JCasUtil.java?rev=1431721&r1=1431720&r2=1431721&view=diff
==============================================================================
--- uima/sandbox/uimafit/trunk/uimafit/src/main/java/org/apache/uima/fit/util/JCasUtil.java (original)
+++ uima/sandbox/uimafit/trunk/uimafit/src/main/java/org/apache/uima/fit/util/JCasUtil.java Thu Jan 10 23:12:33 2013
@@ -38,658 +38,651 @@ import org.apache.uima.jcas.tcas.Annotat
/**
* Utility methods for convenient access to the {@link JCas}.
- *
+ *
*/
public class JCasUtil {
- /**
- * Convenience method to iterator over all features structures of a given type.
- *
- * @param <T>
- * the iteration type.
- * @param jCas
- * a JCas.
- * @param type
- * the type.
- * @return An iterable.
- * @see AnnotationIndex#iterator()
- * @deprecated use {@link #select}
- */
- @Deprecated
- public static <T extends TOP> Iterable<T> iterate(final JCas jCas, final Class<T> type) {
- return select(jCas, type);
- }
-
- /**
- * Convenience method to iterator over all annotations of a given type occurring within the
- * scope of a provided annotation.
- *
- * @param <T>
- * the iteration type.
- * @param container
- * the containing annotation.
- * @param type
- * the type.
- * @return A iterable.
- * @see #selectCovered(Class, AnnotationFS)
- * @deprecated use {@link #selectCovered}
- */
- @Deprecated
- public static <T extends Annotation> Iterable<T> iterate(final Class<T> type,
- final AnnotationFS container) {
- return selectCovered(type, container);
- }
-
- /**
- * Convenience method to iterator over all annotations of a given type occurring within the
- * scope of a provided annotation.
- *
- * @param <T>
- * the iteration type.
- * @param jCas
- * a JCas.
- * @param container
- * the containing annotation.
- * @param type
- * the type.
- * @return A iterable.
- * @deprecated use {@link #selectCovered}
- */
- @Deprecated
- public static <T extends Annotation> Iterable<T> iterate(final JCas jCas, final Class<T> type,
- final AnnotationFS container) {
- return selectCovered(jCas, type, container);
- }
-
- /**
- * Convenience method to iterator over all annotations of a given type occurring within the
- * scope of a provided annotation (sub-iteration).
- *
- * @param <T>
- * the iteration type.
- * @param jCas
- * a JCas.
- * @param container
- * the containing annotation.
- * @param type
- * the type.
- * @param ambiguous
- * If set to <code>false</code>, resulting iterator will be unambiguous.
- * @param strict
- * Controls if annotations that overlap to the right are considered in or out.
- * @return A sub-iterator iterable.
- * @see AnnotationIndex#subiterator(AnnotationFS, boolean, boolean)
- */
- public static <T extends Annotation> Iterable<T> subiterate(final JCas jCas,
- final Class<T> type, final AnnotationFS container, final boolean ambiguous,
- final boolean strict) {
- return new Iterable<T>() {
- public Iterator<T> iterator() {
- return JCasUtil.iterator(container, type, ambiguous, strict);
- }
- };
- }
-
- /**
- * Get an iterator over the given feature structure type.
- *
- * @param <T>
- * the JCas type.
- * @param jCas
- * a JCas.
- * @param type
- * a type.
- * @return a return value.
- */
- @SuppressWarnings({ "unchecked", "rawtypes" })
- public static <T extends TOP> Iterator<T> iterator(JCas jCas, Class<T> type) {
- return (FSIterator) jCas.getIndexRepository().getAllIndexedFS(getType(jCas, type));
- }
-
- /**
- * Convenience method to get a sub-iterator for the specified type.
- *
- * @param <T>
- * the iteration type.
- * @param container
- * the containing annotation.
- * @param type
- * the type.
- * @param ambiguous
- * If set to <code>false</code>, resulting iterator will be unambiguous.
- * @param strict
- * Controls if annotations that overlap to the right are considered in or out.
- * @return A sub-iterator.
- */
- @SuppressWarnings("unchecked")
- public static <T extends AnnotationFS> Iterator<T> iterator(AnnotationFS container,
- Class<T> type, boolean ambiguous, boolean strict) {
- CAS cas = container.getCAS();
- return ((AnnotationIndex<T>) cas.getAnnotationIndex(CasUtil.getType(cas, type)))
- .subiterator(container, ambiguous, strict);
- }
-
- /**
- * Get the CAS type for the given JCas wrapper class type.
- *
- * @param jCas
- * the JCas containing the type system.
- * @param type
- * the JCas wrapper class type.
- * @return the CAS type.
- */
- public static Type getType(JCas jCas, Class<?> type) {
- return CasUtil.getType(jCas.getCas(), type);
- }
-
- /**
- * Get the CAS type for the given JCas wrapper class type making sure it inherits from
- * {@link Annotation}.
- *
- * @param jCas
- * the JCas containing the type system.
- * @param type
- * the JCas wrapper class type.
- * @return the CAS type.
- */
- public static Type getAnnotationType(JCas jCas, Class<?> type) {
- return CasUtil.getAnnotationType(jCas.getCas(), type);
- }
-
- /**
- * Convenience method select all feature structure from the given type from an array.
- *
- * @param <T>
- * the JCas type.
- * @param array
- * a feature structure array.
- * @param type
- * the type.
- * @return A collection of the selected type.
- * @see #selectCovered(Class, AnnotationFS)
- */
- public static <T extends TOP> Collection<T> select(final FSArray array, final Class<T> type) {
- return cast(CasUtil.selectFS(array, CasUtil.getType(array.getCAS(), type.getName())));
- }
-
- /**
- * Convenience method select all feature structure from the given type from a list.
- *
- * @param <T>
- * the JCas type.
- * @param list
- * a feature structure list.
- * @param type
- * the type.
- * @return A collection of the selected type.
- * @see #selectCovered(Class, AnnotationFS)
- */
- public static <T extends TOP> Collection<T> select(final FSList list, final Class<T> type) {
- return cast(FSCollectionFactory
- .create(list, CasUtil.getType(list.getCAS(), type.getName())));
- }
-
- /**
- * Convenience method to iterator over all features structures of a given type.
- *
- * @param <T>
- * the iteration type.
- * @param jCas
- * the JCas containing the type system.
- * @param type
- * the type.
- * @return A collection of the selected type.
- */
- public static <T extends TOP> Collection<T> select(final JCas jCas, final Class<T> type) {
- return cast(CasUtil.selectFS(jCas.getCas(), getType(jCas, type)));
- }
-
- /**
- * Convenience method to iterator over all features structures.
- *
- * @param jCas
- * the JCas containing the type system.
- * the type.
- * @return A collection of the selected type.
- */
- public static Collection<TOP> selectAll(final JCas jCas) {
- return select(jCas, TOP.class);
- }
-
- /**
- * Get a list of annotations of the given annotation type located between two annotations.
- * Does not use subiterators and does not respect type priorities. Zero-width annotations
- * what lie on the borders are included in the result, e.g. if the boundary annotations are
- * [1..2] and [2..3] then an annotation [2..2] is returned. If there is a non-zero overlap
- * between the boundary annotations, the result is empty. The method properly handles cases
- * where the second boundary annotations occurs before the first boundary annotation by
- * switching their roles.
- *
- * @param type
- * a UIMA type.
- * @param ann1
- * the first boundary annotation.
- * @param ann2
- * the second boundary annotation.
- * @return a return value.
- * @see Subiterator
- */
- public static <T extends Annotation> List<T> selectBetween(final Class<T> type,
- AnnotationFS ann1, AnnotationFS ann2) {
- return cast(CasUtil.selectBetween(CasUtil.getType(ann1.getCAS(), type), ann1, ann2));
- }
-
- /**
- * Get a list of annotations of the given annotation type located between two annotations.
- * Does not use subiterators and does not respect type priorities. Zero-width annotations
- * what lie on the borders are included in the result, e.g. if the boundary annotations are
- * [1..2] and [2..3] then an annotation [2..2] is returned. If there is a non-zero overlap
- * between the boundary annotations, the result is empty. The method properly handles cases
- * where the second boundary annotations occurs before the first boundary annotation by
- * switching their roles.
- *
- * @param jCas
- * a JCas containing the annotation.
- * @param type
- * a UIMA type.
- * @param ann1
- * the first boundary annotation.
- * @param ann2
- * the second boundary annotation.
- * @return a return value.
- * @see Subiterator
- */
- public static <T extends Annotation> List<T> selectBetween(JCas jCas, final Class<T> type,
- AnnotationFS ann1, AnnotationFS ann2) {
- return cast(CasUtil.selectBetween(jCas.getCas(), getType(jCas, type), ann1, ann2));
- }
-
- /**
- * Get a list of annotations of the given annotation type constrained by a 'covering'
- * annotation. Iterates over all annotations of the given type to find the covered annotations.
- * Does not use subiterators.
- *
- * @param <T>
- * the JCas type.
- * @param type
- * a UIMA type.
- * @param coveringAnnotation
- * the covering annotation.
- * @return a return value.
- * @see Subiterator
- */
- public static <T extends AnnotationFS> List<T> selectCovered(Class<T> type,
- AnnotationFS coveringAnnotation) {
- CAS cas = coveringAnnotation.getCAS();
- return cast(CasUtil.selectCovered(cas, CasUtil.getType(cas, type), coveringAnnotation));
- }
-
- /**
- * Get a list of annotations of the given annotation type constrained by a 'covering'
- * annotation. Iterates over all annotations of the given type to find the covered annotations.
- * Does not use subiterators.
- *
- * @param <T>
- * the JCas type.
- * @param jCas
- * a JCas containing the annotation.
- * @param type
- * a UIMA type.
- * @param coveringAnnotation
- * the covering annotation.
- * @return a return value.
- * @see Subiterator
- */
- public static <T extends Annotation> List<T> selectCovered(JCas jCas, final Class<T> type,
- AnnotationFS coveringAnnotation) {
- return cast(CasUtil.selectCovered(jCas.getCas(), getType(jCas, type), coveringAnnotation));
- }
-
- /**
- * Get a list of annotations of the given annotation type constrained by a 'covering'
- * annotation. Iterates over all annotations of the given type to find the covered annotations.
- * Does not use subiterators.
- * <p>
- * <b>Note:</b> this is significantly slower than using
- * {@link #selectCovered(JCas, Class, AnnotationFS)}. It is possible to use {@code
- * selectCovered(jCas, cls, new Annotation(jCas, int, int))}, but that will allocate memory
- * in the jCas for the new annotation. If you do that repeatedly many times, memory may fill up.
- *
- * @param <T>
- * the JCas type.
- * @param jCas
- * a JCas containing the annotation.
- * @param type
- * a UIMA type.
- * @param begin
- * begin offset.
- * @param end
- * end offset.
- * @return a return value.
- */
- public static <T extends Annotation> List<T> selectCovered(JCas jCas, final Class<T> type,
- int begin, int end) {
- return cast(CasUtil.selectCovered(jCas.getCas(), getType(jCas, type), begin, end));
- }
-
- /**
- * Get a list of annotations of the given annotation type constraint by a certain annotation.
- * Iterates over all annotations to find the covering annotations.
- *
- * <p>
- * <b>Note:</b> this is <b>REALLY SLOW!</b> You don't want to use this. Instead, consider
- * using {@link #indexCovering(JCas, Class, Class)} or a {@link ContainmentIndex}.
- *
- * @param <T>
- * the JCas type.
- * @param jCas
- * a CAS.
- * @param type
- * a UIMA type.
- * @param begin
- * begin offset.
- * @param end
- * end offset.
- * @return a return value.
- */
- public static <T extends Annotation> List<T> selectCovering(JCas jCas, Class<T> type,
- int begin, int end) {
-
- return cast(CasUtil.selectCovering(jCas.getCas(), getType(jCas, type), begin, end));
- }
-
- /**
- * Create an index for quickly lookup up the annotations covering a particular annotation. This
- * is preferable to using {@link #selectCovering(JCas, Class, int, int)} because the overhead of
- * scanning the CAS occurs only when the index is build. Subsequent lookups to the index are
- * fast.
- *
- * @param <T>
- * the JCas type.
- * @param jCas
- * a JCas.
- * @param type
- * type to create the index for - this is used in lookups.
- * @param coveringType
- * type of covering annotations.
- * @return the index.
- */
- public static <T extends Annotation, S extends Annotation> Map<T, Collection<S>> indexCovering(
- JCas jCas, Class<T> type, Class<S> coveringType) {
- return cast(CasUtil.indexCovering(jCas.getCas(), getType(jCas, type),
- getType(jCas, coveringType)));
- }
-
- /**
- * Create an index for quickly lookup up the annotations covered by a particular annotation. This
- * is preferable to using {@link #selectCovered(JCas, Class, int, int)} because the overhead of
- * scanning the CAS occurs only when the index is build. Subsequent lookups to the index are
- * fast.
- *
- * @param <T>
- * the JCas type.
- * @param jCas
- * a JCas.
- * @param type
- * type to create the index for - this is used in lookups.
- * @param coveredType
- * type of covered annotations.
- * @return the index.
- */
- public static <T extends Annotation, S extends Annotation> Map<T, Collection<S>> indexCovered(
- JCas jCas, Class<T> type, Class<S> coveredType) {
- return cast(CasUtil.indexCovered(jCas.getCas(), getType(jCas, type),
- getType(jCas, coveredType)));
- }
-
- /**
- * Check if the given annotation contains any annotation of the given type.
- *
- * @param jCas
- * a JCas containing the annotation.
- * @param coveringAnnotation
- * the covering annotation.
- * @param type
- * a UIMA type.
- * @return if an annotation of the given type is present.
- * @deprecated use {@link #contains}
- */
- @Deprecated
- public static boolean isCovered(JCas jCas, AnnotationFS coveringAnnotation,
- Class<? extends Annotation> type) {
- return contains(jCas, coveringAnnotation, type);
- }
-
- /**
- * Check if the given annotation contains any annotation of the given type.
- *
- * @param jCas
- * a JCas containing the annotation.
- * @param coveringAnnotation
- * the covering annotation.
- * @param type
- * a UIMA type.
- * @return if an annotation of the given type is present.
- */
- public static boolean contains(JCas jCas, AnnotationFS coveringAnnotation,
- Class<? extends Annotation> type) {
- return selectCovered(jCas, type, coveringAnnotation).size() > 0;
- }
-
- /**
- * This method exists simply as a convenience method for unit testing. It is not very efficient
- * and should not, in general be used outside the context of unit testing.
- *
- * @param <T>
- * JCas wrapper type.
- * @param jCas
- * a JCas containing the annotation.
- * @param cls
- * a UIMA type.
- * @param index
- * this can be either positive (0 corresponds to the first annotation of a type) or
- * negative (-1 corresponds to the last annotation of a type.)
- * @return an annotation of the given type
- */
- @SuppressWarnings("unchecked")
- public static <T extends TOP> T selectByIndex(JCas jCas, Class<T> cls, int index) {
- return (T) CasUtil.selectFSByIndex(jCas.getCas(), getType(jCas, cls), index);
- }
-
- /**
- * Get the single instance of the specified type from the JCas.
- *
- * @param <T>
- * JCas wrapper type.
- * @param jCas
- * a JCas containing the annotation.
- * @param type
- * a UIMA type.
- * @return the single instance of the given type. throws IllegalArgumentException if not exactly
- * one instance if the given type is present.
- */
- @SuppressWarnings("unchecked")
- public static <T extends TOP> T selectSingle(JCas jCas, Class<T> type) {
- return (T) CasUtil.selectSingle(jCas.getCas(), getType(jCas, type));
- }
-
- /**
- * Return an annotation preceding or following of a given reference annotation.
- *
- * @param <T>
- * the JCas type.
- * @param aType
- * a type.
- * @param annotation
- * anchor annotation
- * @param index
- * relative position to access. A negative value selects a preceding annotation
- * while a positive number selects a following annotation.
- * @return the addressed annotation.
- * @throws IndexOutOfBoundsException if the relative index points beyond the type index bounds.
- */
- @SuppressWarnings("unchecked")
- public static <T extends Annotation> T selectSingleRelative(Class<T> aType,
- AnnotationFS annotation, int index) {
- CAS cas = annotation.getCAS();
- Type t = CasUtil.getType(cas, aType);
- return (T) CasUtil.selectSingleRelative(cas, t, annotation, index);
- }
-
- /**
- * Return an annotation preceding or following of a given reference annotation.
- *
- * @param <T>
- * the JCas type.
- * @param aJCas
- * a JCas.
- * @param aType
- * a type.
- * @param annotation
- * anchor annotation
- * @param index
- * relative position to access. A negative value selects a preceding annotation
- * while a positive number selects a following annotation.
- * @return the addressed annotation.
- * @throws IndexOutOfBoundsException if the relative index points beyond the type index bounds.
- */
- @SuppressWarnings("unchecked")
- public static <T extends Annotation> T selectSingleRelative(JCas aJCas, Class<T> aType,
- AnnotationFS annotation, int index) {
- Type t = getType(aJCas, aType);
- return (T) CasUtil.selectSingleRelative(aJCas.getCas(), t, annotation, index);
- }
-
- /**
- * Returns the n annotations preceding the given annotation
- *
- * @param <T>
- * the JCas type.
- * @param aJCas
- * a JCas.
- * @param aType
- * a type.
- * @param annotation
- * anchor annotation
- * @param count
- * number of annotations to collect
- * @return List of aType annotations preceding anchor annotation
- */
- public static <T extends Annotation> List<T> selectPreceding(JCas aJCas, Class<T> aType,
- AnnotationFS annotation, int count) {
- Type t = getType(aJCas, aType);
- return cast(CasUtil.selectPreceding(aJCas.getCas(), t, annotation, count));
- }
-
- /**
- * Returns the n annotations following the given annotation
- *
- * @param <T>
- * the JCas type.
- * @param aJCas
- * a JCas.
- * @param aType
- * a type.
- * @param annotation
- * anchor annotation
- * @param count
- * number of annotations to collect
- * @return List of aType annotations following anchor annotation
- */
- public static <T extends Annotation> List<T> selectFollowing(JCas aJCas, Class<T> aType,
- AnnotationFS annotation, int count) {
- Type t = getType(aJCas, aType);
- return cast(CasUtil.selectFollowing(aJCas.getCas(), t, annotation, count));
- }
-
- /**
- * Test if a JCas contains an annotation of the given type.
- *
- * @param <T>
- * the annotation type.
- * @param aJCas
- * a JCas.
- * @param aType
- * a annotation class.
- * @return {@code true} if there is at least one annotation of the given type in the JCas.
- */
- public static <T extends TOP> boolean exists(JCas aJCas, Class<T> aType) {
- return JCasUtil.iterator(aJCas, aType).hasNext();
- }
-
- /**
- * Convenience method to get the specified view or a default view if the requested view does not
- * exist. The default can also be {@code null}.
- *
- * @param jcas
- * a JCas
- * @param viewName
- * the requested view.
- * @param fallback
- * the default view if the requested view does not exist.
- * @return the requested view or the default if the requested view does not exist.
- * @throws IllegalStateException
- * if the JCas wrapper cannot be obtained.
- */
- public static JCas getView(JCas jcas, String viewName, JCas fallback) {
- try {
- CAS fallbackCas = fallback != null ? fallback.getCas() : null;
- CAS view = CasUtil.getView(jcas.getCas(), viewName, fallbackCas);
- return view != null ? view.getJCas() : null;
- }
- catch (CASException e) {
- throw new IllegalStateException(e);
- }
- }
-
- /**
- * Convenience method to get the specified view or create a new view if the requested view does
- * not exist.
- *
- * @param jcas
- * a JCas
- * @param viewName
- * the requested view.
- * @param create
- * the view is created if it does not exist.
- * @return the requested view
- * @throws IllegalStateException
- * if the JCas wrapper cannot be obtained.
- */
- public static JCas getView(JCas jcas, String viewName, boolean create) {
- try {
- CAS view = CasUtil.getView(jcas.getCas(), viewName, create);
- return view != null ? view.getJCas() : null;
- }
- catch (CASException e) {
- throw new IllegalStateException(e);
- }
- }
-
- /**
- * Fetch the text covered by the specified annotations and return it as a list of strings.
- *
- * @param <T>
- * UIMA JCas type.
- * @param iterable
- * annotation container.
- * @return list of covered strings.
- */
- public static <T extends AnnotationFS> List<String> toText(Iterable<T> iterable) {
- return CasUtil.toText(iterable);
- }
-
- @SuppressWarnings({ "cast", "unchecked", "rawtypes" })
- private static <T> Collection<T> cast(Collection aCollection) {
- return (Collection<T>) aCollection;
- }
-
- @SuppressWarnings({ "cast", "unchecked", "rawtypes" })
- private static <T> List<T> cast(List aCollection) {
- return (List<T>) aCollection;
- }
-
- @SuppressWarnings({ "cast", "unchecked", "rawtypes" })
- private static <K, V> Map<K, V> cast(Map aCollection) {
- return (Map<K, V>) aCollection;
- }
+ /**
+ * Convenience method to iterator over all features structures of a given type.
+ *
+ * @param <T>
+ * the iteration type.
+ * @param jCas
+ * a JCas.
+ * @param type
+ * the type.
+ * @return An iterable.
+ * @see AnnotationIndex#iterator()
+ * @deprecated use {@link #select}
+ */
+ @Deprecated
+ public static <T extends TOP> Iterable<T> iterate(final JCas jCas, final Class<T> type) {
+ return select(jCas, type);
+ }
+
+ /**
+ * Convenience method to iterator over all annotations of a given type occurring within the scope
+ * of a provided annotation.
+ *
+ * @param <T>
+ * the iteration type.
+ * @param container
+ * the containing annotation.
+ * @param type
+ * the type.
+ * @return A iterable.
+ * @see #selectCovered(Class, AnnotationFS)
+ * @deprecated use {@link #selectCovered}
+ */
+ @Deprecated
+ public static <T extends Annotation> Iterable<T> iterate(final Class<T> type,
+ final AnnotationFS container) {
+ return selectCovered(type, container);
+ }
+
+ /**
+ * Convenience method to iterator over all annotations of a given type occurring within the scope
+ * of a provided annotation.
+ *
+ * @param <T>
+ * the iteration type.
+ * @param jCas
+ * a JCas.
+ * @param container
+ * the containing annotation.
+ * @param type
+ * the type.
+ * @return A iterable.
+ * @deprecated use {@link #selectCovered}
+ */
+ @Deprecated
+ public static <T extends Annotation> Iterable<T> iterate(final JCas jCas, final Class<T> type,
+ final AnnotationFS container) {
+ return selectCovered(jCas, type, container);
+ }
+
+ /**
+ * Convenience method to iterator over all annotations of a given type occurring within the scope
+ * of a provided annotation (sub-iteration).
+ *
+ * @param <T>
+ * the iteration type.
+ * @param jCas
+ * a JCas.
+ * @param container
+ * the containing annotation.
+ * @param type
+ * the type.
+ * @param ambiguous
+ * If set to <code>false</code>, resulting iterator will be unambiguous.
+ * @param strict
+ * Controls if annotations that overlap to the right are considered in or out.
+ * @return A sub-iterator iterable.
+ * @see AnnotationIndex#subiterator(AnnotationFS, boolean, boolean)
+ */
+ public static <T extends Annotation> Iterable<T> subiterate(final JCas jCas, final Class<T> type,
+ final AnnotationFS container, final boolean ambiguous, final boolean strict) {
+ return new Iterable<T>() {
+ public Iterator<T> iterator() {
+ return JCasUtil.iterator(container, type, ambiguous, strict);
+ }
+ };
+ }
+
+ /**
+ * Get an iterator over the given feature structure type.
+ *
+ * @param <T>
+ * the JCas type.
+ * @param jCas
+ * a JCas.
+ * @param type
+ * a type.
+ * @return a return value.
+ */
+ @SuppressWarnings({ "unchecked", "rawtypes" })
+ public static <T extends TOP> Iterator<T> iterator(JCas jCas, Class<T> type) {
+ return (FSIterator) jCas.getIndexRepository().getAllIndexedFS(getType(jCas, type));
+ }
+
+ /**
+ * Convenience method to get a sub-iterator for the specified type.
+ *
+ * @param <T>
+ * the iteration type.
+ * @param container
+ * the containing annotation.
+ * @param type
+ * the type.
+ * @param ambiguous
+ * If set to <code>false</code>, resulting iterator will be unambiguous.
+ * @param strict
+ * Controls if annotations that overlap to the right are considered in or out.
+ * @return A sub-iterator.
+ */
+ @SuppressWarnings("unchecked")
+ public static <T extends AnnotationFS> Iterator<T> iterator(AnnotationFS container,
+ Class<T> type, boolean ambiguous, boolean strict) {
+ CAS cas = container.getCAS();
+ return ((AnnotationIndex<T>) cas.getAnnotationIndex(CasUtil.getType(cas, type))).subiterator(
+ container, ambiguous, strict);
+ }
+
+ /**
+ * Get the CAS type for the given JCas wrapper class type.
+ *
+ * @param jCas
+ * the JCas containing the type system.
+ * @param type
+ * the JCas wrapper class type.
+ * @return the CAS type.
+ */
+ public static Type getType(JCas jCas, Class<?> type) {
+ return CasUtil.getType(jCas.getCas(), type);
+ }
+
+ /**
+ * Get the CAS type for the given JCas wrapper class type making sure it inherits from
+ * {@link Annotation}.
+ *
+ * @param jCas
+ * the JCas containing the type system.
+ * @param type
+ * the JCas wrapper class type.
+ * @return the CAS type.
+ */
+ public static Type getAnnotationType(JCas jCas, Class<?> type) {
+ return CasUtil.getAnnotationType(jCas.getCas(), type);
+ }
+
+ /**
+ * Convenience method select all feature structure from the given type from an array.
+ *
+ * @param <T>
+ * the JCas type.
+ * @param array
+ * a feature structure array.
+ * @param type
+ * the type.
+ * @return A collection of the selected type.
+ * @see #selectCovered(Class, AnnotationFS)
+ */
+ public static <T extends TOP> Collection<T> select(final FSArray array, final Class<T> type) {
+ return cast(CasUtil.selectFS(array, CasUtil.getType(array.getCAS(), type.getName())));
+ }
+
+ /**
+ * Convenience method select all feature structure from the given type from a list.
+ *
+ * @param <T>
+ * the JCas type.
+ * @param list
+ * a feature structure list.
+ * @param type
+ * the type.
+ * @return A collection of the selected type.
+ * @see #selectCovered(Class, AnnotationFS)
+ */
+ public static <T extends TOP> Collection<T> select(final FSList list, final Class<T> type) {
+ return cast(FSCollectionFactory.create(list, CasUtil.getType(list.getCAS(), type.getName())));
+ }
+
+ /**
+ * Convenience method to iterator over all features structures of a given type.
+ *
+ * @param <T>
+ * the iteration type.
+ * @param jCas
+ * the JCas containing the type system.
+ * @param type
+ * the type.
+ * @return A collection of the selected type.
+ */
+ public static <T extends TOP> Collection<T> select(final JCas jCas, final Class<T> type) {
+ return cast(CasUtil.selectFS(jCas.getCas(), getType(jCas, type)));
+ }
+
+ /**
+ * Convenience method to iterator over all features structures.
+ *
+ * @param jCas
+ * the JCas containing the type system. the type.
+ * @return A collection of the selected type.
+ */
+ public static Collection<TOP> selectAll(final JCas jCas) {
+ return select(jCas, TOP.class);
+ }
+
+ /**
+ * Get a list of annotations of the given annotation type located between two annotations. Does
+ * not use subiterators and does not respect type priorities. Zero-width annotations what lie on
+ * the borders are included in the result, e.g. if the boundary annotations are [1..2] and [2..3]
+ * then an annotation [2..2] is returned. If there is a non-zero overlap between the boundary
+ * annotations, the result is empty. The method properly handles cases where the second boundary
+ * annotations occurs before the first boundary annotation by switching their roles.
+ *
+ * @param type
+ * a UIMA type.
+ * @param ann1
+ * the first boundary annotation.
+ * @param ann2
+ * the second boundary annotation.
+ * @return a return value.
+ * @see Subiterator
+ */
+ public static <T extends Annotation> List<T> selectBetween(final Class<T> type,
+ AnnotationFS ann1, AnnotationFS ann2) {
+ return cast(CasUtil.selectBetween(CasUtil.getType(ann1.getCAS(), type), ann1, ann2));
+ }
+
+ /**
+ * Get a list of annotations of the given annotation type located between two annotations. Does
+ * not use subiterators and does not respect type priorities. Zero-width annotations what lie on
+ * the borders are included in the result, e.g. if the boundary annotations are [1..2] and [2..3]
+ * then an annotation [2..2] is returned. If there is a non-zero overlap between the boundary
+ * annotations, the result is empty. The method properly handles cases where the second boundary
+ * annotations occurs before the first boundary annotation by switching their roles.
+ *
+ * @param jCas
+ * a JCas containing the annotation.
+ * @param type
+ * a UIMA type.
+ * @param ann1
+ * the first boundary annotation.
+ * @param ann2
+ * the second boundary annotation.
+ * @return a return value.
+ * @see Subiterator
+ */
+ public static <T extends Annotation> List<T> selectBetween(JCas jCas, final Class<T> type,
+ AnnotationFS ann1, AnnotationFS ann2) {
+ return cast(CasUtil.selectBetween(jCas.getCas(), getType(jCas, type), ann1, ann2));
+ }
+
+ /**
+ * Get a list of annotations of the given annotation type constrained by a 'covering' annotation.
+ * Iterates over all annotations of the given type to find the covered annotations. Does not use
+ * subiterators.
+ *
+ * @param <T>
+ * the JCas type.
+ * @param type
+ * a UIMA type.
+ * @param coveringAnnotation
+ * the covering annotation.
+ * @return a return value.
+ * @see Subiterator
+ */
+ public static <T extends AnnotationFS> List<T> selectCovered(Class<T> type,
+ AnnotationFS coveringAnnotation) {
+ CAS cas = coveringAnnotation.getCAS();
+ return cast(CasUtil.selectCovered(cas, CasUtil.getType(cas, type), coveringAnnotation));
+ }
+
+ /**
+ * Get a list of annotations of the given annotation type constrained by a 'covering' annotation.
+ * Iterates over all annotations of the given type to find the covered annotations. Does not use
+ * subiterators.
+ *
+ * @param <T>
+ * the JCas type.
+ * @param jCas
+ * a JCas containing the annotation.
+ * @param type
+ * a UIMA type.
+ * @param coveringAnnotation
+ * the covering annotation.
+ * @return a return value.
+ * @see Subiterator
+ */
+ public static <T extends Annotation> List<T> selectCovered(JCas jCas, final Class<T> type,
+ AnnotationFS coveringAnnotation) {
+ return cast(CasUtil.selectCovered(jCas.getCas(), getType(jCas, type), coveringAnnotation));
+ }
+
+ /**
+ * Get a list of annotations of the given annotation type constrained by a 'covering' annotation.
+ * Iterates over all annotations of the given type to find the covered annotations. Does not use
+ * subiterators.
+ * <p>
+ * <b>Note:</b> this is significantly slower than using
+ * {@link #selectCovered(JCas, Class, AnnotationFS)}. It is possible to use
+ * {@code selectCovered(jCas, cls, new Annotation(jCas, int, int))}, but that will allocate memory
+ * in the jCas for the new annotation. If you do that repeatedly many times, memory may fill up.
+ *
+ * @param <T>
+ * the JCas type.
+ * @param jCas
+ * a JCas containing the annotation.
+ * @param type
+ * a UIMA type.
+ * @param begin
+ * begin offset.
+ * @param end
+ * end offset.
+ * @return a return value.
+ */
+ public static <T extends Annotation> List<T> selectCovered(JCas jCas, final Class<T> type,
+ int begin, int end) {
+ return cast(CasUtil.selectCovered(jCas.getCas(), getType(jCas, type), begin, end));
+ }
+
+ /**
+ * Get a list of annotations of the given annotation type constraint by a certain annotation.
+ * Iterates over all annotations to find the covering annotations.
+ *
+ * <p>
+ * <b>Note:</b> this is <b>REALLY SLOW!</b> You don't want to use this. Instead, consider using
+ * {@link #indexCovering(JCas, Class, Class)} or a {@link ContainmentIndex}.
+ *
+ * @param <T>
+ * the JCas type.
+ * @param jCas
+ * a CAS.
+ * @param type
+ * a UIMA type.
+ * @param begin
+ * begin offset.
+ * @param end
+ * end offset.
+ * @return a return value.
+ */
+ public static <T extends Annotation> List<T> selectCovering(JCas jCas, Class<T> type, int begin,
+ int end) {
+
+ return cast(CasUtil.selectCovering(jCas.getCas(), getType(jCas, type), begin, end));
+ }
+
+ /**
+ * Create an index for quickly lookup up the annotations covering a particular annotation. This is
+ * preferable to using {@link #selectCovering(JCas, Class, int, int)} because the overhead of
+ * scanning the CAS occurs only when the index is build. Subsequent lookups to the index are fast.
+ *
+ * @param <T>
+ * the JCas type.
+ * @param jCas
+ * a JCas.
+ * @param type
+ * type to create the index for - this is used in lookups.
+ * @param coveringType
+ * type of covering annotations.
+ * @return the index.
+ */
+ public static <T extends Annotation, S extends Annotation> Map<T, Collection<S>> indexCovering(
+ JCas jCas, Class<T> type, Class<S> coveringType) {
+ return cast(CasUtil.indexCovering(jCas.getCas(), getType(jCas, type),
+ getType(jCas, coveringType)));
+ }
+
+ /**
+ * Create an index for quickly lookup up the annotations covered by a particular annotation. This
+ * is preferable to using {@link #selectCovered(JCas, Class, int, int)} because the overhead of
+ * scanning the CAS occurs only when the index is build. Subsequent lookups to the index are fast.
+ *
+ * @param <T>
+ * the JCas type.
+ * @param jCas
+ * a JCas.
+ * @param type
+ * type to create the index for - this is used in lookups.
+ * @param coveredType
+ * type of covered annotations.
+ * @return the index.
+ */
+ public static <T extends Annotation, S extends Annotation> Map<T, Collection<S>> indexCovered(
+ JCas jCas, Class<T> type, Class<S> coveredType) {
+ return cast(CasUtil
+ .indexCovered(jCas.getCas(), getType(jCas, type), getType(jCas, coveredType)));
+ }
+
+ /**
+ * Check if the given annotation contains any annotation of the given type.
+ *
+ * @param jCas
+ * a JCas containing the annotation.
+ * @param coveringAnnotation
+ * the covering annotation.
+ * @param type
+ * a UIMA type.
+ * @return if an annotation of the given type is present.
+ * @deprecated use {@link #contains}
+ */
+ @Deprecated
+ public static boolean isCovered(JCas jCas, AnnotationFS coveringAnnotation,
+ Class<? extends Annotation> type) {
+ return contains(jCas, coveringAnnotation, type);
+ }
+
+ /**
+ * Check if the given annotation contains any annotation of the given type.
+ *
+ * @param jCas
+ * a JCas containing the annotation.
+ * @param coveringAnnotation
+ * the covering annotation.
+ * @param type
+ * a UIMA type.
+ * @return if an annotation of the given type is present.
+ */
+ public static boolean contains(JCas jCas, AnnotationFS coveringAnnotation,
+ Class<? extends Annotation> type) {
+ return selectCovered(jCas, type, coveringAnnotation).size() > 0;
+ }
+
+ /**
+ * This method exists simply as a convenience method for unit testing. It is not very efficient
+ * and should not, in general be used outside the context of unit testing.
+ *
+ * @param <T>
+ * JCas wrapper type.
+ * @param jCas
+ * a JCas containing the annotation.
+ * @param cls
+ * a UIMA type.
+ * @param index
+ * this can be either positive (0 corresponds to the first annotation of a type) or
+ * negative (-1 corresponds to the last annotation of a type.)
+ * @return an annotation of the given type
+ */
+ @SuppressWarnings("unchecked")
+ public static <T extends TOP> T selectByIndex(JCas jCas, Class<T> cls, int index) {
+ return (T) CasUtil.selectFSByIndex(jCas.getCas(), getType(jCas, cls), index);
+ }
+
+ /**
+ * Get the single instance of the specified type from the JCas.
+ *
+ * @param <T>
+ * JCas wrapper type.
+ * @param jCas
+ * a JCas containing the annotation.
+ * @param type
+ * a UIMA type.
+ * @return the single instance of the given type. throws IllegalArgumentException if not exactly
+ * one instance if the given type is present.
+ */
+ @SuppressWarnings("unchecked")
+ public static <T extends TOP> T selectSingle(JCas jCas, Class<T> type) {
+ return (T) CasUtil.selectSingle(jCas.getCas(), getType(jCas, type));
+ }
+
+ /**
+ * Return an annotation preceding or following of a given reference annotation.
+ *
+ * @param <T>
+ * the JCas type.
+ * @param aType
+ * a type.
+ * @param annotation
+ * anchor annotation
+ * @param index
+ * relative position to access. A negative value selects a preceding annotation while a
+ * positive number selects a following annotation.
+ * @return the addressed annotation.
+ * @throws IndexOutOfBoundsException
+ * if the relative index points beyond the type index bounds.
+ */
+ @SuppressWarnings("unchecked")
+ public static <T extends Annotation> T selectSingleRelative(Class<T> aType,
+ AnnotationFS annotation, int index) {
+ CAS cas = annotation.getCAS();
+ Type t = CasUtil.getType(cas, aType);
+ return (T) CasUtil.selectSingleRelative(cas, t, annotation, index);
+ }
+
+ /**
+ * Return an annotation preceding or following of a given reference annotation.
+ *
+ * @param <T>
+ * the JCas type.
+ * @param aJCas
+ * a JCas.
+ * @param aType
+ * a type.
+ * @param annotation
+ * anchor annotation
+ * @param index
+ * relative position to access. A negative value selects a preceding annotation while a
+ * positive number selects a following annotation.
+ * @return the addressed annotation.
+ * @throws IndexOutOfBoundsException
+ * if the relative index points beyond the type index bounds.
+ */
+ @SuppressWarnings("unchecked")
+ public static <T extends Annotation> T selectSingleRelative(JCas aJCas, Class<T> aType,
+ AnnotationFS annotation, int index) {
+ Type t = getType(aJCas, aType);
+ return (T) CasUtil.selectSingleRelative(aJCas.getCas(), t, annotation, index);
+ }
+
+ /**
+ * Returns the n annotations preceding the given annotation
+ *
+ * @param <T>
+ * the JCas type.
+ * @param aJCas
+ * a JCas.
+ * @param aType
+ * a type.
+ * @param annotation
+ * anchor annotation
+ * @param count
+ * number of annotations to collect
+ * @return List of aType annotations preceding anchor annotation
+ */
+ public static <T extends Annotation> List<T> selectPreceding(JCas aJCas, Class<T> aType,
+ AnnotationFS annotation, int count) {
+ Type t = getType(aJCas, aType);
+ return cast(CasUtil.selectPreceding(aJCas.getCas(), t, annotation, count));
+ }
+
+ /**
+ * Returns the n annotations following the given annotation
+ *
+ * @param <T>
+ * the JCas type.
+ * @param aJCas
+ * a JCas.
+ * @param aType
+ * a type.
+ * @param annotation
+ * anchor annotation
+ * @param count
+ * number of annotations to collect
+ * @return List of aType annotations following anchor annotation
+ */
+ public static <T extends Annotation> List<T> selectFollowing(JCas aJCas, Class<T> aType,
+ AnnotationFS annotation, int count) {
+ Type t = getType(aJCas, aType);
+ return cast(CasUtil.selectFollowing(aJCas.getCas(), t, annotation, count));
+ }
+
+ /**
+ * Test if a JCas contains an annotation of the given type.
+ *
+ * @param <T>
+ * the annotation type.
+ * @param aJCas
+ * a JCas.
+ * @param aType
+ * a annotation class.
+ * @return {@code true} if there is at least one annotation of the given type in the JCas.
+ */
+ public static <T extends TOP> boolean exists(JCas aJCas, Class<T> aType) {
+ return JCasUtil.iterator(aJCas, aType).hasNext();
+ }
+
+ /**
+ * Convenience method to get the specified view or a default view if the requested view does not
+ * exist. The default can also be {@code null}.
+ *
+ * @param jcas
+ * a JCas
+ * @param viewName
+ * the requested view.
+ * @param fallback
+ * the default view if the requested view does not exist.
+ * @return the requested view or the default if the requested view does not exist.
+ * @throws IllegalStateException
+ * if the JCas wrapper cannot be obtained.
+ */
+ public static JCas getView(JCas jcas, String viewName, JCas fallback) {
+ try {
+ CAS fallbackCas = fallback != null ? fallback.getCas() : null;
+ CAS view = CasUtil.getView(jcas.getCas(), viewName, fallbackCas);
+ return view != null ? view.getJCas() : null;
+ } catch (CASException e) {
+ throw new IllegalStateException(e);
+ }
+ }
+
+ /**
+ * Convenience method to get the specified view or create a new view if the requested view does
+ * not exist.
+ *
+ * @param jcas
+ * a JCas
+ * @param viewName
+ * the requested view.
+ * @param create
+ * the view is created if it does not exist.
+ * @return the requested view
+ * @throws IllegalStateException
+ * if the JCas wrapper cannot be obtained.
+ */
+ public static JCas getView(JCas jcas, String viewName, boolean create) {
+ try {
+ CAS view = CasUtil.getView(jcas.getCas(), viewName, create);
+ return view != null ? view.getJCas() : null;
+ } catch (CASException e) {
+ throw new IllegalStateException(e);
+ }
+ }
+
+ /**
+ * Fetch the text covered by the specified annotations and return it as a list of strings.
+ *
+ * @param <T>
+ * UIMA JCas type.
+ * @param iterable
+ * annotation container.
+ * @return list of covered strings.
+ */
+ public static <T extends AnnotationFS> List<String> toText(Iterable<T> iterable) {
+ return CasUtil.toText(iterable);
+ }
+
+ @SuppressWarnings({ "cast", "unchecked", "rawtypes" })
+ private static <T> Collection<T> cast(Collection aCollection) {
+ return (Collection<T>) aCollection;
+ }
+
+ @SuppressWarnings({ "cast", "unchecked", "rawtypes" })
+ private static <T> List<T> cast(List aCollection) {
+ return (List<T>) aCollection;
+ }
+
+ @SuppressWarnings({ "cast", "unchecked", "rawtypes" })
+ private static <K, V> Map<K, V> cast(Map aCollection) {
+ return (Map<K, V>) aCollection;
+ }
}
Modified: uima/sandbox/uimafit/trunk/uimafit/src/main/java/org/apache/uima/fit/util/LocaleUtil.java
URL: http://svn.apache.org/viewvc/uima/sandbox/uimafit/trunk/uimafit/src/main/java/org/apache/uima/fit/util/LocaleUtil.java?rev=1431721&r1=1431720&r2=1431721&view=diff
==============================================================================
--- uima/sandbox/uimafit/trunk/uimafit/src/main/java/org/apache/uima/fit/util/LocaleUtil.java (original)
+++ uima/sandbox/uimafit/trunk/uimafit/src/main/java/org/apache/uima/fit/util/LocaleUtil.java Thu Jan 10 23:12:33 2013
@@ -25,63 +25,61 @@ import java.util.Locale;
*/
public final class LocaleUtil {
- private LocaleUtil() {
- // Utility method class.
- }
-
- /**
- * This method returns the locale constant for the given string. For example, see
- * {@link Locale#US} as an example locale constant. To retrieve that locale using this method,
- * pass in the string value "US". If there is no locale constant for the passed in string, then
- * null is returned
- *
- * @param localeConstant
- * a string value that names a locale constant.
- * @return the corresponding locale or null if there is no locale for the provided string.
- */
- public static Locale getLocaleConstant(String localeConstant) {
- try {
- Field field = Locale.class.getField(localeConstant);
- if (field != null && field.getType().equals(Locale.class)) {
- return (Locale) field.get(null);
- }
- }
- catch (Exception e) {
- return null;
- }
- return null;
- }
+ private LocaleUtil() {
+ // Utility method class.
+ }
- /**
- * This method passes through to {@link Locale#Locale(String)} unless the provided string
- * contains a hyphen. If it does, then the string is split on the hyphen and the resulting
- * strings are passed into the multi-parameter constructors of Locale. The passed in string
- * should not contain more than two hyphens as the Locale constructor with the most params is
- * three.
- */
- public static Locale createLocale(String localeString) {
- String[] parts = localeString.split("[_-]", 3);
- switch (parts.length) {
- case 3:
- return new Locale(parts[0], parts[1], parts[2]);
- case 2:
- return new Locale(parts[0], parts[1]);
- case 1:
- return new Locale(parts[0]);
- default:
- throw new IllegalArgumentException("Invalid locale: " + localeString);
- }
- }
+ /**
+ * This method returns the locale constant for the given string. For example, see
+ * {@link Locale#US} as an example locale constant. To retrieve that locale using this method,
+ * pass in the string value "US". If there is no locale constant for the passed in string, then
+ * null is returned
+ *
+ * @param localeConstant
+ * a string value that names a locale constant.
+ * @return the corresponding locale or null if there is no locale for the provided string.
+ */
+ public static Locale getLocaleConstant(String localeConstant) {
+ try {
+ Field field = Locale.class.getField(localeConstant);
+ if (field != null && field.getType().equals(Locale.class)) {
+ return (Locale) field.get(null);
+ }
+ } catch (Exception e) {
+ return null;
+ }
+ return null;
+ }
- /**
- * passes through to getLocaleConstant. If this returns null, then this method passes through to
- * createLocale.
- */
- public static Locale getLocale(String localeString) {
- Locale locale = getLocaleConstant(localeString);
- if (locale != null) {
- return locale;
- }
- return createLocale(localeString);
- }
+ /**
+ * This method passes through to {@link Locale#Locale(String)} unless the provided string contains
+ * a hyphen. If it does, then the string is split on the hyphen and the resulting strings are
+ * passed into the multi-parameter constructors of Locale. The passed in string should not contain
+ * more than two hyphens as the Locale constructor with the most params is three.
+ */
+ public static Locale createLocale(String localeString) {
+ String[] parts = localeString.split("[_-]", 3);
+ switch (parts.length) {
+ case 3:
+ return new Locale(parts[0], parts[1], parts[2]);
+ case 2:
+ return new Locale(parts[0], parts[1]);
+ case 1:
+ return new Locale(parts[0]);
+ default:
+ throw new IllegalArgumentException("Invalid locale: " + localeString);
+ }
+ }
+
+ /**
+ * passes through to getLocaleConstant. If this returns null, then this method passes through to
+ * createLocale.
+ */
+ public static Locale getLocale(String localeString) {
+ Locale locale = getLocaleConstant(localeString);
+ if (locale != null) {
+ return locale;
+ }
+ return createLocale(localeString);
+ }
}
Modified: uima/sandbox/uimafit/trunk/uimafit/src/main/java/org/apache/uima/fit/util/ReflectionUtil.java
URL: http://svn.apache.org/viewvc/uima/sandbox/uimafit/trunk/uimafit/src/main/java/org/apache/uima/fit/util/ReflectionUtil.java?rev=1431721&r1=1431720&r2=1431721&view=diff
==============================================================================
--- uima/sandbox/uimafit/trunk/uimafit/src/main/java/org/apache/uima/fit/util/ReflectionUtil.java (original)
+++ uima/sandbox/uimafit/trunk/uimafit/src/main/java/org/apache/uima/fit/util/ReflectionUtil.java Thu Jan 10 23:12:33 2013
@@ -27,96 +27,95 @@ import java.util.List;
/**
*/
public final class ReflectionUtil {
-
- private ReflectionUtil() {
- // Library class
- }
-
- /**
- * Get all the fields for the class (and superclasses) of the passed in object
- *
- * @param aObject
- * any object will do
- * @return the fields for the class of the object
- */
- public static List<Field> getFields(final Object aObject) {
- return getFields(aObject.getClass());
- }
-
- /**
- * Get all the fields for this class and all of its superclasses
- *
- * @param aClass
- * any class will do
- * @return the fields for the class and all of its superclasses
- */
- public static List<Field> getFields(final Class<?> aClass) {
- Class<?> cls = aClass;
- final List<Field> fields = new ArrayList<Field>();
- while (!cls.equals(Object.class)) {
- final Field[] flds = cls.getDeclaredFields();
- fields.addAll(Arrays.asList(flds));
- cls = cls.getSuperclass();
- }
- return fields;
- }
-
- /**
- * Get the given field of the passed in object from its class or the first superclass that
- * declares it.
- *
- * @param aObject
- * any object will do
- * @return the fields for the class of the object
- */
- public static Field getField(final Object aObject, final String aName)
- throws NoSuchFieldException {
- return getField(aObject.getClass(), aName);
- }
-
- /**
- * Get the given field from the class or the first superclass that declares it.
- *
- * @param aClass
- * any class will do
- * @return the fields for the class of the object
- */
- public static Field getField(final Class<?> aClass, final String aName)
- throws NoSuchFieldException {
- try {
- return aClass.getDeclaredField(aName);
- }
- catch (NoSuchFieldException e) {
- if (aClass.getSuperclass() == null) {
- throw e;
- }
-
- return getField(aClass.getSuperclass(), aName);
- }
- }
-
- /**
- * Search for an annotation of the specified type starting on the given class and tracking back
- * the inheritance hierarchy. Only parent classes are tracked back, no implemented interfaces.
- *
- * @param <T>
- * the annotation type
- * @param aAnnotation
- * the annotation class
- * @param aClass
- * the class to start searching on
- * @return the annotation or {@code null} if it could not be found
- */
- public static <T extends Annotation> T getInheritableAnnotation(final Class<T> aAnnotation,
- final Class<?> aClass) {
- if (aClass.isAnnotationPresent(aAnnotation)) {
- return aClass.getAnnotation(aAnnotation);
- }
-
- if (aClass.getSuperclass() != null) {
- return getInheritableAnnotation(aAnnotation, aClass.getSuperclass());
- }
- return null;
- }
+ private ReflectionUtil() {
+ // Library class
+ }
+
+ /**
+ * Get all the fields for the class (and superclasses) of the passed in object
+ *
+ * @param aObject
+ * any object will do
+ * @return the fields for the class of the object
+ */
+ public static List<Field> getFields(final Object aObject) {
+ return getFields(aObject.getClass());
+ }
+
+ /**
+ * Get all the fields for this class and all of its superclasses
+ *
+ * @param aClass
+ * any class will do
+ * @return the fields for the class and all of its superclasses
+ */
+ public static List<Field> getFields(final Class<?> aClass) {
+ Class<?> cls = aClass;
+ final List<Field> fields = new ArrayList<Field>();
+ while (!cls.equals(Object.class)) {
+ final Field[] flds = cls.getDeclaredFields();
+ fields.addAll(Arrays.asList(flds));
+ cls = cls.getSuperclass();
+ }
+ return fields;
+ }
+
+ /**
+ * Get the given field of the passed in object from its class or the first superclass that
+ * declares it.
+ *
+ * @param aObject
+ * any object will do
+ * @return the fields for the class of the object
+ */
+ public static Field getField(final Object aObject, final String aName)
+ throws NoSuchFieldException {
+ return getField(aObject.getClass(), aName);
+ }
+
+ /**
+ * Get the given field from the class or the first superclass that declares it.
+ *
+ * @param aClass
+ * any class will do
+ * @return the fields for the class of the object
+ */
+ public static Field getField(final Class<?> aClass, final String aName)
+ throws NoSuchFieldException {
+ try {
+ return aClass.getDeclaredField(aName);
+ } catch (NoSuchFieldException e) {
+ if (aClass.getSuperclass() == null) {
+ throw e;
+ }
+
+ return getField(aClass.getSuperclass(), aName);
+ }
+ }
+
+ /**
+ * Search for an annotation of the specified type starting on the given class and tracking back
+ * the inheritance hierarchy. Only parent classes are tracked back, no implemented interfaces.
+ *
+ * @param <T>
+ * the annotation type
+ * @param aAnnotation
+ * the annotation class
+ * @param aClass
+ * the class to start searching on
+ * @return the annotation or {@code null} if it could not be found
+ */
+ public static <T extends Annotation> T getInheritableAnnotation(final Class<T> aAnnotation,
+ final Class<?> aClass) {
+ if (aClass.isAnnotationPresent(aAnnotation)) {
+ return aClass.getAnnotation(aAnnotation);
+ }
+
+ if (aClass.getSuperclass() != null) {
+ return getInheritableAnnotation(aAnnotation, aClass.getSuperclass());
+ }
+
+ return null;
+ }
}
Modified: uima/sandbox/uimafit/trunk/uimafit/src/main/java/org/apache/uima/fit/util/SimpleNamedResourceManager.java
URL: http://svn.apache.org/viewvc/uima/sandbox/uimafit/trunk/uimafit/src/main/java/org/apache/uima/fit/util/SimpleNamedResourceManager.java?rev=1431721&r1=1431720&r2=1431721&view=diff
==============================================================================
--- uima/sandbox/uimafit/trunk/uimafit/src/main/java/org/apache/uima/fit/util/SimpleNamedResourceManager.java (original)
+++ uima/sandbox/uimafit/trunk/uimafit/src/main/java/org/apache/uima/fit/util/SimpleNamedResourceManager.java Thu Jan 10 23:12:33 2013
@@ -17,7 +17,6 @@
* under the License.
*/
-
package org.apache.uima.fit.util;
import java.lang.reflect.Constructor;
@@ -26,6 +25,7 @@ import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
+
import org.apache.uima.UIMAFramework;
import org.apache.uima.resource.ExternalResourceDescription;
import org.apache.uima.resource.ResourceInitializationException;
@@ -37,188 +37,182 @@ import org.apache.uima.util.Level;
/**
* <b>EXPERIMENTAL CODE</b>
* <p>
- * Simple {@link ResourceManager} allowing for direct injection of Java objects into UIMA
- * components as external resources.
+ * Simple {@link ResourceManager} allowing for direct injection of Java objects into UIMA components
+ * as external resources.
* <p>
- * This implementation uses a simple map to look up an Java object by key. If any component
- * using this resource manager declares an external resource by the given key, the Java object
- * will be bound to that external resource.
+ * This implementation uses a simple map to look up an Java object by key. If any component using
+ * this resource manager declares an external resource by the given key, the Java object will be
+ * bound to that external resource.
* <p>
* Example:
* <p>
- * <blockquote><pre>
+ * <blockquote>
+ *
+ * <pre>
* class MyComponent extends JCasAnnotator_ImplBase {
* static final String RES_INJECTED_POJO = "InjectedPojo";
* {@code @ExternalResource(key = RES_INJECTED_POJO)}
* private String injectedString;
- *
+ *
* public void process(JCas aJCas) throws AnalysisEngineProcessException {
* ...
* }
* }
- * </pre></blockquote>
- *
+ * </pre>
+ *
+ * </blockquote>
+ *
* Per default it is necessary to explicitly bind a objects from the external context to external
- * resource keys used by the UIMA component:
- * <blockquote><pre>
- * Map<String, Object> context = new HashMap<String, Object>();
- * context("myString", "Just an injected POJO");
- *
+ * resource keys used by the UIMA component: <blockquote>
+ *
+ * <pre>
+ * Map<String, Object> context = new HashMap<String, Object>();
+ * context("myString", "Just an injected POJO");
+ *
* SimpleNamedResourceManager resMgr = new SimpleNamedResourceManager();
* resMgr.setExternalContext(externalContext);
- *
+ *
* AnalysisEngineDescription desc = createPrimitiveDescription(MyComponent.class);
- * bindExternalResource(desc, MyComponent.RES_INJECTED_POJO, "myString");
+ * bindExternalResource(desc, MyComponent.RES_INJECTED_POJO, "myString");
* AnalysisEngine ae = UIMAFramework.produceAnalysisEngine(desc, resMgr, null);
- * </pre></blockquote>
- *
- * With autowireing enabled, an explicit binding is not necessary:
- * <blockquote><pre>
- * Map<String, Object> context = new HashMap<String, Object>();
- * context(MyComponent.RES_INJECTED_POJO, "Just an injected POJO");
- *
+ * </pre>
+ *
+ * </blockquote>
+ *
+ * With autowireing enabled, an explicit binding is not necessary: <blockquote>
+ *
+ * <pre>
+ * Map<String, Object> context = new HashMap<String, Object>();
+ * context(MyComponent.RES_INJECTED_POJO, "Just an injected POJO");
+ *
* SimpleNamedResourceManager resMgr = new SimpleNamedResourceManager();
* resMgr.setAutoWireEnabled(true);
* resMgr.setExternalContext(externalContext);
- *
+ *
* AnalysisEngineDescription desc = createPrimitiveDescription(MyComponent.class);
* AnalysisEngine ae = UIMAFramework.produceAnalysisEngine(desc, resMgr, null);
- * </pre></blockquote>
- *
+ * </pre>
+ *
+ * </blockquote>
+ *
*/
public class SimpleNamedResourceManager extends ResourceManager_impl {
- private Map<String, Object> externalContext;
+ private Map<String, Object> externalContext;
- private boolean autoWireEnabled = false;
+ private boolean autoWireEnabled = false;
- @SuppressWarnings({ "rawtypes", "unchecked" })
- @Override
- public void initializeExternalResources(ResourceManagerConfiguration aConfiguration,
- String aQualifiedContextName, java.util.Map<String, Object> aAdditionalParams)
- throws ResourceInitializationException {
-
- for (Entry<String, Object> e : externalContext.entrySet()) {
- Object registration = mInternalResourceRegistrationMap.get(e.getKey());
-
- if (registration == null) {
- try {
- // Register resource
- // ResourceRegistration unfortunately is package private
- Object reg = newInstance(
- "org.apache.uima.resource.impl.ResourceManager_impl$ResourceRegistration",
- Object.class, e.getValue(),
- ExternalResourceDescription.class, null,
- String.class, aQualifiedContextName);
- ((Map) mInternalResourceRegistrationMap).put(e.getKey(), reg);
-
- // Perform binding
- if (isAutoWireEnabled()) {
- mResourceMap.put(aQualifiedContextName + e.getKey(), e.getValue());
- }
- }
- catch (Exception e1) {
- throw new ResourceInitializationException(e1);
- }
- }
- else {
- try {
- Object desc = getFieldValue(registration, "description");
-
- if (desc != null) {
- String definingContext = getFieldValue(registration, "definingContext");
-
- if (aQualifiedContextName.startsWith(definingContext)) {
- UIMAFramework.getLogger().logrb(
- Level.CONFIG,
- ResourceManager_impl.class.getName(),
- "initializeExternalResources",
- LOG_RESOURCE_BUNDLE,
- "UIMA_overridden_resource__CONFIG",
- new Object[] { e.getKey(), aQualifiedContextName,
- definingContext });
- }
- else {
- UIMAFramework.getLogger().logrb(
- Level.WARNING,
- ResourceManager_impl.class.getName(),
- "initializeExternalResources",
- LOG_RESOURCE_BUNDLE,
- "UIMA_duplicate_resource_name__WARNING",
- new Object[] { e.getKey(), definingContext,
- aQualifiedContextName });
- }
- }
- }
- catch (Exception e1) {
- throw new ResourceInitializationException(e1);
- }
- }
- }
-
- super.initializeExternalResources(aConfiguration, aQualifiedContextName, aAdditionalParams);
- }
-
- public void setExternalContext(Map<String, Object> aExternalContext) {
- externalContext = aExternalContext;
- }
-
- public void setAutoWireEnabled(boolean aAutoWireEnabled) {
- autoWireEnabled = aAutoWireEnabled;
- }
-
- public boolean isAutoWireEnabled() {
- return autoWireEnabled;
- }
-
- /**
- * Instantiate a non-visible class.
- */
- @SuppressWarnings({ "unchecked", "rawtypes" })
- private static <T> T newInstance(String aClassName, Object... aArgs) throws ResourceInitializationException {
- Constructor constr = null;
- try {
- Class<?> cl = Class.forName(aClassName);
-
- List<Class> types = new ArrayList<Class>();
- List<Object> values = new ArrayList<Object>();
- for (int i = 0; i < aArgs.length; i += 2) {
- types.add((Class) aArgs[i]);
- values.add(aArgs[i+1]);
- }
-
- constr = cl.getDeclaredConstructor(types.toArray(new Class[types.size()]));
- constr.setAccessible(true);
- return (T) constr.newInstance(values.toArray(new Object[values.size()]));
- }
- catch (Exception e) {
- throw new ResourceInitializationException(e);
- }
- finally {
- if (constr != null) {
- constr.setAccessible(false);
- }
- }
- }
-
- /**
- * Get a field value from a non-visible field.
- */
- @SuppressWarnings("unchecked")
- private static <T> T getFieldValue(Object aObject, String aFieldName) throws ResourceInitializationException
- {
- Field f = null;
- try {
- f = aObject.getClass().getField(aFieldName);
- f.setAccessible(true);
- return (T) f.get(aObject);
- }
- catch (Exception e) {
- throw new ResourceInitializationException(e);
- }
- finally {
- if (f != null) {
- f.setAccessible(false);
- }
- }
- }
+ @SuppressWarnings({ "rawtypes", "unchecked" })
+ @Override
+ public void initializeExternalResources(ResourceManagerConfiguration aConfiguration,
+ String aQualifiedContextName, java.util.Map<String, Object> aAdditionalParams)
+ throws ResourceInitializationException {
+
+ for (Entry<String, Object> e : externalContext.entrySet()) {
+ Object registration = mInternalResourceRegistrationMap.get(e.getKey());
+
+ if (registration == null) {
+ try {
+ // Register resource
+ // ResourceRegistration unfortunately is package private
+ Object reg = newInstance(
+ "org.apache.uima.resource.impl.ResourceManager_impl$ResourceRegistration",
+ Object.class, e.getValue(), ExternalResourceDescription.class, null,
+ String.class, aQualifiedContextName);
+ ((Map) mInternalResourceRegistrationMap).put(e.getKey(), reg);
+
+ // Perform binding
+ if (isAutoWireEnabled()) {
+ mResourceMap.put(aQualifiedContextName + e.getKey(), e.getValue());
+ }
+ } catch (Exception e1) {
+ throw new ResourceInitializationException(e1);
+ }
+ } else {
+ try {
+ Object desc = getFieldValue(registration, "description");
+
+ if (desc != null) {
+ String definingContext = getFieldValue(registration, "definingContext");
+
+ if (aQualifiedContextName.startsWith(definingContext)) {
+ UIMAFramework.getLogger().logrb(Level.CONFIG, ResourceManager_impl.class.getName(),
+ "initializeExternalResources", LOG_RESOURCE_BUNDLE,
+ "UIMA_overridden_resource__CONFIG",
+ new Object[] { e.getKey(), aQualifiedContextName, definingContext });
+ } else {
+ UIMAFramework.getLogger().logrb(Level.WARNING, ResourceManager_impl.class.getName(),
+ "initializeExternalResources", LOG_RESOURCE_BUNDLE,
+ "UIMA_duplicate_resource_name__WARNING",
+ new Object[] { e.getKey(), definingContext, aQualifiedContextName });
+ }
+ }
+ } catch (Exception e1) {
+ throw new ResourceInitializationException(e1);
+ }
+ }
+ }
+
+ super.initializeExternalResources(aConfiguration, aQualifiedContextName, aAdditionalParams);
+ }
+
+ public void setExternalContext(Map<String, Object> aExternalContext) {
+ externalContext = aExternalContext;
+ }
+
+ public void setAutoWireEnabled(boolean aAutoWireEnabled) {
+ autoWireEnabled = aAutoWireEnabled;
+ }
+
+ public boolean isAutoWireEnabled() {
+ return autoWireEnabled;
+ }
+
+ /**
+ * Instantiate a non-visible class.
+ */
+ @SuppressWarnings({ "unchecked", "rawtypes" })
+ private static <T> T newInstance(String aClassName, Object... aArgs)
+ throws ResourceInitializationException {
+ Constructor constr = null;
+ try {
+ Class<?> cl = Class.forName(aClassName);
+
+ List<Class> types = new ArrayList<Class>();
+ List<Object> values = new ArrayList<Object>();
+ for (int i = 0; i < aArgs.length; i += 2) {
+ types.add((Class) aArgs[i]);
+ values.add(aArgs[i + 1]);
+ }
+
+ constr = cl.getDeclaredConstructor(types.toArray(new Class[types.size()]));
+ constr.setAccessible(true);
+ return (T) constr.newInstance(values.toArray(new Object[values.size()]));
+ } catch (Exception e) {
+ throw new ResourceInitializationException(e);
+ } finally {
+ if (constr != null) {
+ constr.setAccessible(false);
+ }
+ }
+ }
+
+ /**
+ * Get a field value from a non-visible field.
+ */
+ @SuppressWarnings("unchecked")
+ private static <T> T getFieldValue(Object aObject, String aFieldName)
+ throws ResourceInitializationException {
+ Field f = null;
+ try {
+ f = aObject.getClass().getField(aFieldName);
+ f.setAccessible(true);
+ return (T) f.get(aObject);
+ } catch (Exception e) {
+ throw new ResourceInitializationException(e);
+ } finally {
+ if (f != null) {
+ f.setAccessible(false);
+ }
+ }
+ }
}
Modified: uima/sandbox/uimafit/trunk/uimafit/src/main/java/org/apache/uima/fit/util/package-info.java
URL: http://svn.apache.org/viewvc/uima/sandbox/uimafit/trunk/uimafit/src/main/java/org/apache/uima/fit/util/package-info.java?rev=1431721&r1=1431720&r2=1431721&view=diff
==============================================================================
--- uima/sandbox/uimafit/trunk/uimafit/src/main/java/org/apache/uima/fit/util/package-info.java (original)
+++ uima/sandbox/uimafit/trunk/uimafit/src/main/java/org/apache/uima/fit/util/package-info.java Thu Jan 10 23:12:33 2013
@@ -20,3 +20,4 @@
* Utility classes like {@link org.apache.uima.fit.util.CasUtil} and {@link org.apache.uima.fit.util.JCasUtil}.
*/
package org.apache.uima.fit.util;
+
Modified: uima/sandbox/uimafit/trunk/uimafit/src/test/java/DefaultPackageAE.java
URL: http://svn.apache.org/viewvc/uima/sandbox/uimafit/trunk/uimafit/src/test/java/DefaultPackageAE.java?rev=1431721&r1=1431720&r2=1431721&view=diff
==============================================================================
--- uima/sandbox/uimafit/trunk/uimafit/src/test/java/DefaultPackageAE.java (original)
+++ uima/sandbox/uimafit/trunk/uimafit/src/test/java/DefaultPackageAE.java Thu Jan 10 23:12:33 2013
@@ -21,13 +21,12 @@ import org.apache.uima.analysis_engine.A
import org.apache.uima.fit.component.JCasAnnotator_ImplBase;
import org.apache.uima.jcas.JCas;
-
/**
*/
public class DefaultPackageAE extends JCasAnnotator_ImplBase {
- @Override
- public void process(JCas aJCas) throws AnalysisEngineProcessException {
- // does nothing
- }
+ @Override
+ public void process(JCas aJCas) throws AnalysisEngineProcessException {
+ // does nothing
+ }
}
Modified: uima/sandbox/uimafit/trunk/uimafit/src/test/java/DefaultPackageAETest.java
URL: http://svn.apache.org/viewvc/uima/sandbox/uimafit/trunk/uimafit/src/test/java/DefaultPackageAETest.java?rev=1431721&r1=1431720&r2=1431721&view=diff
==============================================================================
--- uima/sandbox/uimafit/trunk/uimafit/src/test/java/DefaultPackageAETest.java (original)
+++ uima/sandbox/uimafit/trunk/uimafit/src/test/java/DefaultPackageAETest.java Thu Jan 10 23:12:33 2013
@@ -31,26 +31,26 @@ import org.junit.Test;
public class DefaultPackageAETest extends ComponentTestBase {
- @Test
- public void testPackageLessAE() throws Exception {
- AnalysisEngineDescription aed = AnalysisEngineFactory.createPrimitiveDescription(
- DefaultPackageAE.class, (Object[]) null);
- jCas.setDocumentText("some text");
- SimplePipeline.runPipeline(jCas, aed);
-
- aed = AnalysisEngineFactory.createPrimitiveDescription(DefaultPackageAE2.class,
- (Object[]) null);
- jCas.reset();
- jCas.setDocumentText("some text");
- SimplePipeline.runPipeline(jCas, aed);
-
- }
-
- public static class DefaultPackageAE2 extends JCasAnnotator_ImplBase {
- @Override
- public void process(JCas aJCas) throws AnalysisEngineProcessException {
- // does nothing
- }
- }
+ @Test
+ public void testPackageLessAE() throws Exception {
+ AnalysisEngineDescription aed = AnalysisEngineFactory.createPrimitiveDescription(
+ DefaultPackageAE.class, (Object[]) null);
+ jCas.setDocumentText("some text");
+ SimplePipeline.runPipeline(jCas, aed);
+
+ aed = AnalysisEngineFactory
+ .createPrimitiveDescription(DefaultPackageAE2.class, (Object[]) null);
+ jCas.reset();
+ jCas.setDocumentText("some text");
+ SimplePipeline.runPipeline(jCas, aed);
+
+ }
+
+ public static class DefaultPackageAE2 extends JCasAnnotator_ImplBase {
+ @Override
+ public void process(JCas aJCas) throws AnalysisEngineProcessException {
+ // does nothing
+ }
+ }
}
Modified: uima/sandbox/uimafit/trunk/uimafit/src/test/java/org/apache/uima/fit/ComponentTestBase.java
URL: http://svn.apache.org/viewvc/uima/sandbox/uimafit/trunk/uimafit/src/test/java/org/apache/uima/fit/ComponentTestBase.java?rev=1431721&r1=1431720&r2=1431721&view=diff
==============================================================================
--- uima/sandbox/uimafit/trunk/uimafit/src/test/java/org/apache/uima/fit/ComponentTestBase.java (original)
+++ uima/sandbox/uimafit/trunk/uimafit/src/test/java/org/apache/uima/fit/ComponentTestBase.java Thu Jan 10 23:12:33 2013
@@ -35,51 +35,55 @@ import org.junit.Before;
*/
public class ComponentTestBase {
- private static ThreadLocal<JCas> JCAS = new ThreadLocal<JCas>();
- private static ThreadLocal<TypeSystemDescription> TYPE_SYSTEM_DESCRIPTION = new ThreadLocal<TypeSystemDescription>();
- private static ThreadLocal<TypePriorities> TYPE_PRIORITIES = new ThreadLocal<TypePriorities>();
- private static ThreadLocal<TokenBuilder<Token, Sentence>> TOKEN_BUILDER = new ThreadLocal<TokenBuilder<Token, Sentence>>();
-
- static {
- try {
- TYPE_SYSTEM_DESCRIPTION.set(TypeSystemDescriptionFactory.createTypeSystemDescription());
-
- TypePriorities tp = TypePrioritiesFactory.createTypePriorities(new String[] {
- "org.apache.uima.fit.type.Sentence", "org.apache.uima.fit.type.AnalyzedText",
- "org.apache.uima.fit.type.Token" });
- TYPE_PRIORITIES.set(tp);
-
- JCas jCas = CasCreationUtils.createCas(TYPE_SYSTEM_DESCRIPTION.get(), tp, null)
- .getJCas();
- JCAS.set(jCas);
-
- TokenBuilder<Token, Sentence> tb = new TokenBuilder<Token, Sentence>(Token.class,
- Sentence.class, "pos", "stem");
- TOKEN_BUILDER.set(tb);
- }
- catch (Exception e) {
- e.printStackTrace();
- System.exit(1);
- }
- }
-
- protected JCas jCas;
- protected TypeSystemDescription typeSystemDescription;
- protected TypePriorities typePriorities;
- protected TokenBuilder<Token, Sentence> tokenBuilder;
-
- /**
- * we do not want to create a new JCas object every time we run a test because it is expensive
- * (~100ms on my laptop). Instead, we will have one JCas per thread sitting around that we will
- * reset everytime a new test is called.
- */
- @Before
- public void setUp() {
- jCas = JCAS.get();
- jCas.reset();
- typeSystemDescription = TYPE_SYSTEM_DESCRIPTION.get();
- typePriorities = TYPE_PRIORITIES.get();
- tokenBuilder = TOKEN_BUILDER.get();
- }
+ private static ThreadLocal<JCas> JCAS = new ThreadLocal<JCas>();
+
+ private static ThreadLocal<TypeSystemDescription> TYPE_SYSTEM_DESCRIPTION = new ThreadLocal<TypeSystemDescription>();
+
+ private static ThreadLocal<TypePriorities> TYPE_PRIORITIES = new ThreadLocal<TypePriorities>();
+
+ private static ThreadLocal<TokenBuilder<Token, Sentence>> TOKEN_BUILDER = new ThreadLocal<TokenBuilder<Token, Sentence>>();
+
+ static {
+ try {
+ TYPE_SYSTEM_DESCRIPTION.set(TypeSystemDescriptionFactory.createTypeSystemDescription());
+
+ TypePriorities tp = TypePrioritiesFactory.createTypePriorities(new String[] {
+ "org.apache.uima.fit.type.Sentence", "org.apache.uima.fit.type.AnalyzedText",
+ "org.apache.uima.fit.type.Token" });
+ TYPE_PRIORITIES.set(tp);
+
+ JCas jCas = CasCreationUtils.createCas(TYPE_SYSTEM_DESCRIPTION.get(), tp, null).getJCas();
+ JCAS.set(jCas);
+
+ TokenBuilder<Token, Sentence> tb = new TokenBuilder<Token, Sentence>(Token.class,
+ Sentence.class, "pos", "stem");
+ TOKEN_BUILDER.set(tb);
+ } catch (Exception e) {
+ e.printStackTrace();
+ System.exit(1);
+ }
+ }
+
+ protected JCas jCas;
+
+ protected TypeSystemDescription typeSystemDescription;
+
+ protected TypePriorities typePriorities;
+
+ protected TokenBuilder<Token, Sentence> tokenBuilder;
+
+ /**
+ * we do not want to create a new JCas object every time we run a test because it is expensive
+ * (~100ms on my laptop). Instead, we will have one JCas per thread sitting around that we will
+ * reset everytime a new test is called.
+ */
+ @Before
+ public void setUp() {
+ jCas = JCAS.get();
+ jCas.reset();
+ typeSystemDescription = TYPE_SYSTEM_DESCRIPTION.get();
+ typePriorities = TYPE_PRIORITIES.get();
+ tokenBuilder = TOKEN_BUILDER.get();
+ }
}
Modified: uima/sandbox/uimafit/trunk/uimafit/src/test/java/org/apache/uima/fit/component/JCasCollectionReader_ImplBaseTest.java
URL: http://svn.apache.org/viewvc/uima/sandbox/uimafit/trunk/uimafit/src/test/java/org/apache/uima/fit/component/JCasCollectionReader_ImplBaseTest.java?rev=1431721&r1=1431720&r2=1431721&view=diff
==============================================================================
--- uima/sandbox/uimafit/trunk/uimafit/src/test/java/org/apache/uima/fit/component/JCasCollectionReader_ImplBaseTest.java (original)
+++ uima/sandbox/uimafit/trunk/uimafit/src/test/java/org/apache/uima/fit/component/JCasCollectionReader_ImplBaseTest.java Thu Jan 10 23:12:33 2013
@@ -39,42 +39,43 @@ import org.junit.Test;
*
*/
public class JCasCollectionReader_ImplBaseTest {
- /**
- * Test using a simple reader reading one text file.
- *
- * @throws Exception
- * if an error occurs.
- */
- @Test
- public void test() throws Exception {
- File file = new File("src/test/resources/data/docs/A.txt");
-
- CollectionReader reader = createCollectionReader(SingleTextReader.class,
- SingleTextReader.PARAM_FILE, file.getPath());
-
- CAS cas = CasCreationUtils.createCas(reader.getProcessingResourceMetaData());
- reader.getNext(cas);
- reader.close();
-
- assertEquals(FileUtils.readFileToString(file, "UTF-8"), cas.getDocumentText());
- }
-
- public static class SingleTextReader extends JCasCollectionReader_ImplBase {
- public static final String PARAM_FILE = "File";
- @ConfigurationParameter(name = PARAM_FILE, mandatory = true)
- private File file;
-
- public boolean hasNext() throws IOException, CollectionException {
- return file != null;
- }
-
- public Progress[] getProgress() {
- return new Progress[0];
- }
-
- @Override
- public void getNext(JCas jCas) throws IOException, CollectionException {
- jCas.setDocumentText(FileUtils.readFileToString(file, "UTF-8"));
- }
- }
+ /**
+ * Test using a simple reader reading one text file.
+ *
+ * @throws Exception
+ * if an error occurs.
+ */
+ @Test
+ public void test() throws Exception {
+ File file = new File("src/test/resources/data/docs/A.txt");
+
+ CollectionReader reader = createCollectionReader(SingleTextReader.class,
+ SingleTextReader.PARAM_FILE, file.getPath());
+
+ CAS cas = CasCreationUtils.createCas(reader.getProcessingResourceMetaData());
+ reader.getNext(cas);
+ reader.close();
+
+ assertEquals(FileUtils.readFileToString(file, "UTF-8"), cas.getDocumentText());
+ }
+
+ public static class SingleTextReader extends JCasCollectionReader_ImplBase {
+ public static final String PARAM_FILE = "File";
+
+ @ConfigurationParameter(name = PARAM_FILE, mandatory = true)
+ private File file;
+
+ public boolean hasNext() throws IOException, CollectionException {
+ return file != null;
+ }
+
+ public Progress[] getProgress() {
+ return new Progress[0];
+ }
+
+ @Override
+ public void getNext(JCas jCas) throws IOException, CollectionException {
+ jCas.setDocumentText(FileUtils.readFileToString(file, "UTF-8"));
+ }
+ }
}