You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@uima.apache.org by sc...@apache.org on 2012/12/13 15:54:18 UTC
svn commit: r1421324 [6/9] - in /uima/sandbox/trunk/uimaFIT:
uimaFIT-examples/src/main/java/org/uimafit/examples/experiment/pos/
uimaFIT-examples/src/main/java/org/uimafit/examples/getstarted/
uimaFIT-examples/src/main/java/org/uimafit/examples/resourc...
Added: uima/sandbox/trunk/uimaFIT/uimaFIT/src/main/java/org/apache/uima/fit/util/CasUtil.java
URL: http://svn.apache.org/viewvc/uima/sandbox/trunk/uimaFIT/uimaFIT/src/main/java/org/apache/uima/fit/util/CasUtil.java?rev=1421324&view=auto
==============================================================================
--- uima/sandbox/trunk/uimaFIT/uimaFIT/src/main/java/org/apache/uima/fit/util/CasUtil.java (added)
+++ uima/sandbox/trunk/uimaFIT/uimaFIT/src/main/java/org/apache/uima/fit/util/CasUtil.java Thu Dec 13 14:53:52 2012
@@ -0,0 +1,1022 @@
+/*
+ Copyright 2009-2010
+ Ubiquitous Knowledge Processing (UKP) Lab
+ Technische Universitaet Darmstadt
+ All rights reserved.
+
+ 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.
+
+ getCoveredAnnotations() contains code adapted from the UIMA Subiterator class.
+ */
+package org.apache.uima.fit.util;
+
+import static java.util.Collections.EMPTY_LIST;
+import static java.util.Collections.emptyList;
+import static java.util.Collections.unmodifiableList;
+import static java.util.Collections.unmodifiableMap;
+
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.LinkedList;
+import java.util.List;
+import java.util.Map;
+
+import org.apache.uima.cas.ArrayFS;
+import org.apache.uima.cas.CAS;
+import org.apache.uima.cas.CASRuntimeException;
+import org.apache.uima.cas.FSIterator;
+import org.apache.uima.cas.FeatureStructure;
+import org.apache.uima.cas.Type;
+import org.apache.uima.cas.TypeSystem;
+import org.apache.uima.cas.impl.Subiterator;
+import org.apache.uima.cas.text.AnnotationFS;
+import org.apache.uima.cas.text.AnnotationIndex;
+import org.apache.uima.jcas.tcas.Annotation;
+
+/**
+ * Utility methods for convenient access to the {@link CAS}.
+ *
+ * @author Richard Eckart de Castilho
+ * @author Niklas Jakob
+ */
+public class CasUtil {
+ /**
+ * Package name of JCas wrapper classes built into UIMA.
+ */
+ public static final String UIMA_BUILTIN_JCAS_PREFIX = "org.apache.uima.jcas.";
+
+ /**
+ * Convenience method to iterator over all feature structures of a given type.
+ *
+ * @param cas
+ * a CAS.
+ * @param type
+ * the type.
+ * @return An iterable.
+ * @see AnnotationIndex#iterator()
+ * @deprecated use {@link #selectFS}
+ */
+ @Deprecated
+ public static Iterable<FeatureStructure> iterateFS(final CAS cas, final Type type) {
+ return selectFS(cas, type);
+ }
+
+ /**
+ * Convenience method to iterator over all annotations of a given type.
+ *
+ * @param cas
+ * a CAS.
+ * @param type
+ * the type.
+ * @return An iterable.
+ * @see AnnotationIndex#iterator()
+ * @deprecated use {@link #select}
+ */
+ @Deprecated
+ public static Iterable<AnnotationFS> iterate(final CAS cas, final Type type) {
+ return select(cas, type);
+ }
+
+ /**
+ * Get an iterator over the given feature structures type.
+ *
+ * @param <T>
+ * the JCas type.
+ * @param cas
+ * a CAS.
+ * @param type
+ * a type.
+ * @return a return value.
+ */
+ @SuppressWarnings("unchecked")
+ public static <T extends FeatureStructure> Iterator<T> iteratorFS(CAS cas, Type type) {
+ return ((FSIterator<T>) cas.getIndexRepository().getAllIndexedFS(type));
+ }
+
+ /**
+ * Get an iterator over the given annotation type.
+ *
+ * @param <T>
+ * the JCas type.
+ * @param cas
+ * a CAS.
+ * @param type
+ * a type.
+ * @return a return value.
+ */
+ @SuppressWarnings("unchecked")
+ public static <T extends AnnotationFS> Iterator<T> iterator(CAS cas, Type type) {
+ return ((AnnotationIndex<T>) cas.getAnnotationIndex(type)).iterator();
+ }
+
+ /**
+ * Get the CAS type for the given JCas wrapper class.
+ *
+ * @param cas
+ * the CAS hosting the type system.
+ * @param type
+ * the JCas wrapper class.
+ * @return the CAS type.
+ */
+ public static Type getType(CAS cas, Class<?> type) {
+ return getType(cas, type.getName());
+ }
+
+ /**
+ * Get the CAS type for the given name.
+ *
+ * @param aCas
+ * the CAS hosting the type system.
+ * @param aTypename
+ * the fully qualified type name.
+ * @return the CAS type.
+ */
+ public static Type getType(CAS aCas, String aTypename) {
+ String typeName = aTypename;
+ if (typeName.startsWith(UIMA_BUILTIN_JCAS_PREFIX)) {
+ typeName = "uima." + typeName.substring(UIMA_BUILTIN_JCAS_PREFIX.length());
+ }
+ final Type type = aCas.getTypeSystem().getType(typeName);
+ if (type == null) {
+ throw new IllegalArgumentException("Undeclared type [" + aTypename + "]");
+ }
+ return type;
+ }
+
+ /**
+ * Get the CAS type for the given JCas wrapper class making sure it is or inherits from
+ * {@link Annotation}.
+ *
+ * @param aCas
+ * the CAS hosting the type system.
+ * @param aJCasClass
+ * the JCas wrapper class.
+ * @return the CAS type.
+ */
+ public static Type getAnnotationType(CAS aCas, Class<?> aJCasClass) {
+ final Type type = getType(aCas, aJCasClass);
+ if (!aCas.getTypeSystem().subsumes(aCas.getAnnotationType(), type)) {
+ throw new IllegalArgumentException("Type [" + aJCasClass.getName()
+ + "] is not an annotation type");
+ }
+ return type;
+ }
+
+ /**
+ * Get the CAS type for the given name making sure it is or inherits from Annotation.
+ *
+ * @param aCas
+ * the CAS hosting the type system.
+ * @param aTypeName
+ * the fully qualified type name.
+ * @return the CAS type.
+ */
+ public static Type getAnnotationType(CAS aCas, String aTypeName) {
+ Type type = getType(aCas, aTypeName);
+ if (!aCas.getTypeSystem().subsumes(aCas.getAnnotationType(), type)) {
+ throw new IllegalArgumentException("Type [" + aTypeName + "] is not an annotation type");
+ }
+ return type;
+ }
+
+ /**
+ * Convenience method to iterator over all feature structures of a given type.
+ *
+ * @param array
+ * features structure array.
+ * @param type
+ * the type.
+ * @return A collection of the selected type.
+ */
+ public static Collection<FeatureStructure> selectFS(ArrayFS array, Type type) {
+ return FSCollectionFactory.create(array, type);
+ }
+
+ /**
+ * Convenience method to iterator over all annotations of a given type.
+ *
+ * @param array
+ * features structure array.
+ * @param type
+ * the type.
+ * @return A collection of the selected type.
+ */
+ @SuppressWarnings({ "unchecked", "rawtypes" })
+ public static Collection<AnnotationFS> select(ArrayFS array, Type type) {
+ final CAS cas = array.getCAS();
+ if (!cas.getTypeSystem().subsumes(cas.getAnnotationType(), type)) {
+ throw new IllegalArgumentException("Type [" + type.getName()
+ + "] is not an annotation type");
+ }
+ return (Collection) FSCollectionFactory.create(cas, type);
+ }
+
+ /**
+ * Convenience method to iterator over all features structures.
+ *
+ * @param aCas
+ * the CAS hosting the type system.
+ * @return A collection of the selected type.
+ */
+ public static Collection<FeatureStructure> selectAllFS(final CAS aCas) {
+ return selectFS(aCas, getType(aCas, CAS.TYPE_NAME_TOP));
+ }
+
+ /**
+ * Convenience method to iterator over all feature structures of a given type.
+ *
+ * @param cas
+ * the CAS containing the type system.
+ * @param type
+ * the type.
+ * @return A collection of the selected type.
+ */
+ public static Collection<FeatureStructure> selectFS(final CAS cas, final Type type) {
+ return FSCollectionFactory.create(cas, type);
+ }
+
+ /**
+ * Convenience method to iterator over all annotations.
+ *
+ * @param aCas
+ * the CAS hosting the type system.
+ * @return A collection of the selected type.
+ */
+ public static Collection<AnnotationFS> selectAll(final CAS aCas) {
+ return select(aCas, getType(aCas, CAS.TYPE_NAME_ANNOTATION));
+ }
+
+ /**
+ * Convenience method to iterator over all annotations of a given type.
+ *
+ * @param cas
+ * the CAS containing the type system.
+ * @param type
+ * the type.
+ * @return A collection of the selected type.
+ */
+ @SuppressWarnings({ "unchecked", "rawtypes" })
+ public static Collection<AnnotationFS> select(final CAS cas, final Type type) {
+ if (!cas.getTypeSystem().subsumes(cas.getAnnotationType(), type)) {
+ throw new IllegalArgumentException("Type [" + type.getName()
+ + "] is not an annotation type");
+ }
+ return (Collection) FSCollectionFactory.create(cas, type);
+ }
+
+ /**
+ * 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 List<AnnotationFS> selectBetween(
+ final Type type, final AnnotationFS ann1, final AnnotationFS ann2) {
+ return selectBetween(ann1.getView(), 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 cas
+ * a CAS.
+ * @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 List<AnnotationFS> selectBetween(final CAS cas, final Type type,
+ final AnnotationFS ann1, final AnnotationFS ann2) {
+ AnnotationFS left;
+ AnnotationFS right;
+ if (ann1.getEnd() > ann2.getBegin()) {
+ left = ann2;
+ right = ann1;
+ }
+ else {
+ left = ann1;
+ right = ann2;
+ }
+
+ int begin = left.getEnd();
+ int end = right.getBegin();
+
+ List<AnnotationFS> list = new ArrayList<AnnotationFS>();
+ FSIterator<AnnotationFS> it = cas.getAnnotationIndex(type).iterator();
+
+ // Try to seek the insertion point.
+ it.moveTo(left);
+
+ // If the insertion point is beyond the index, move back to the last.
+ if (!it.isValid()) {
+ it.moveToLast();
+ if (!it.isValid()) {
+ return list;
+ }
+ }
+
+ // Ignore type priorities by seeking to the first that has the same begin
+ boolean moved = false;
+ while (it.isValid() && (it.get()).getBegin() >= begin) {
+ it.moveToPrevious();
+ moved = true;
+ }
+
+ // If we moved, then we are now on one starting before the requested begin, so we have to
+ // move one ahead.
+ if (moved) {
+ it.moveToNext();
+ }
+
+ // If we managed to move outside the index, start at first.
+ if (!it.isValid()) {
+ it.moveToFirst();
+ }
+
+ // Skip annotations whose start is before the start parameter.
+ while (it.isValid() && (it.get()).getBegin() < begin) {
+ it.moveToNext();
+ }
+
+ boolean strict = true;
+ while (it.isValid()) {
+ AnnotationFS a = it.get();
+ // If the start of the current annotation is past the end parameter, we're done.
+ if (a.getBegin() > end) {
+ break;
+ }
+ it.moveToNext();
+ if (strict && a.getEnd() > end) {
+ continue;
+ }
+
+ assert (a.getBegin() >= left.getEnd()) : "Illegal begin "
+ + a.getBegin() + " in [" + begin + ".." + end + "]";
+
+ assert (a.getEnd() <= right.getBegin()) : "Illegal end "
+ + a.getBegin() + " in [" + begin + ".." + end + "]";
+
+
+ if (!a.equals(left) && !a.equals(right)) {
+ list.add(a);
+ }
+ }
+
+ return unmodifiableList(list); }
+
+ /**
+ * Get a list of annotations of the given annotation type constraint by a certain annotation.
+ * Iterates over all annotations of the given type to find the covered annotations. Does not use
+ * subiterators and does not respect type prioritites. Was adapted from {@link Subiterator}.
+ * Uses the same approach except that type priorities are ignored.
+ *
+ * @param type
+ * a UIMA type.
+ * @param coveringAnnotation
+ * the covering annotation.
+ * @return a return value.
+ * @see Subiterator
+ */
+ public static List<AnnotationFS> selectCovered(Type type, AnnotationFS coveringAnnotation) {
+ return selectCovered(coveringAnnotation.getView(), type, coveringAnnotation);
+ }
+
+ /**
+ * Get a list of annotations of the given annotation type constraint by a certain annotation.
+ * Iterates over all annotations of the given type to find the covered annotations. Does not use
+ * subiterators and does not respect type prioritites. Was adapted from {@link Subiterator}.
+ * Uses the same approach except that type priorities are ignored.
+ *
+ * @param cas
+ * a CAS.
+ * @param type
+ * a UIMA type.
+ * @param coveringAnnotation
+ * the covering annotation.
+ * @return a return value.
+ * @see Subiterator
+ */
+ public static List<AnnotationFS> selectCovered(CAS cas, Type type,
+ AnnotationFS coveringAnnotation) {
+ int begin = coveringAnnotation.getBegin();
+ int end = coveringAnnotation.getEnd();
+
+ List<AnnotationFS> list = new ArrayList<AnnotationFS>();
+ FSIterator<AnnotationFS> it = cas.getAnnotationIndex(type).iterator();
+
+ // Try to seek the insertion point.
+ it.moveTo(coveringAnnotation);
+
+ // If the insertion point is beyond the index, move back to the last.
+ if (!it.isValid()) {
+ it.moveToLast();
+ if (!it.isValid()) {
+ return list;
+ }
+ }
+
+ // Ignore type priorities by seeking to the first that has the same begin
+ boolean moved = false;
+ while (it.isValid() && (it.get()).getBegin() >= begin) {
+ it.moveToPrevious();
+ moved = true;
+ }
+
+ // If we moved, then we are now on one starting before the requested begin, so we have to
+ // move one ahead.
+ if (moved) {
+ it.moveToNext();
+ }
+
+ // If we managed to move outside the index, start at first.
+ if (!it.isValid()) {
+ it.moveToFirst();
+ }
+
+ // Skip annotations whose start is before the start parameter.
+ while (it.isValid() && (it.get()).getBegin() < begin) {
+ it.moveToNext();
+ }
+
+ boolean strict = true;
+ while (it.isValid()) {
+ AnnotationFS a = it.get();
+ // If the start of the current annotation is past the end parameter, we're done.
+ if (a.getBegin() > end) {
+ break;
+ }
+ it.moveToNext();
+ if (strict && a.getEnd() > end) {
+ continue;
+ }
+
+ assert (a.getBegin() >= coveringAnnotation.getBegin()) : "Illegal begin "
+ + a.getBegin() + " in [" + coveringAnnotation.getBegin() + ".."
+ + coveringAnnotation.getEnd() + "]";
+
+ assert (a.getEnd() <= coveringAnnotation.getEnd()) : "Illegal end " + a.getEnd()
+ + " in [" + coveringAnnotation.getBegin() + ".." + coveringAnnotation.getEnd()
+ + "]";
+
+ if (!a.equals(coveringAnnotation)) {
+ list.add(a);
+ }
+ }
+
+ return unmodifiableList(list);
+ }
+
+ /**
+ * Get a list of annotations of the given annotation type constraint by a certain annotation.
+ * Iterates over all annotations of the given type to find the covered annotations. Does not use
+ * subiterators and does not respect type prioritites. Was adapted from {@link Subiterator}.
+ * Uses the same approach except that type priorities are ignored.
+ * <p>
+ * <b>Note:</b> this is significantly slower than using
+ * {@link #selectCovered(CAS, Type, AnnotationFS)}. It is possible to use {@code
+ * selectCovered(cas, type, 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 cas
+ * a CAS.
+ * @param type
+ * a UIMA type.
+ * @param begin
+ * begin offset.
+ * @param end
+ * end offset.
+ * @return a return value.
+ * @see Subiterator
+ */
+ public static List<AnnotationFS> selectCovered(CAS cas, Type type, int begin, int end) {
+
+ List<AnnotationFS> list = new ArrayList<AnnotationFS>();
+ FSIterator<AnnotationFS> it = cas.getAnnotationIndex(type).iterator();
+
+ // Skip annotations whose start is before the start parameter.
+ while (it.isValid() && (it.get()).getBegin() < begin) {
+ it.moveToNext();
+ }
+
+ boolean strict = true;
+ while (it.isValid()) {
+ AnnotationFS a = it.get();
+ // If the start of the current annotation is past the end parameter, we're done.
+ if (a.getBegin() > end) {
+ break;
+ }
+ it.moveToNext();
+ if (strict && a.getEnd() > end) {
+ continue;
+ }
+
+ assert (a.getBegin() >= begin) : "Illegal begin " + a.getBegin() + " in [" + begin
+ + ".." + end + "]";
+
+ assert (a.getEnd() <= end) : "Illegal end " + a.getEnd() + " in [" + begin + ".."
+ + end + "]";
+
+ list.add(a);
+ }
+
+ return list;
+ }
+
+ /**
+ * 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(CAS, Type, Type)} or a {@link ContainmentIndex}.
+ *
+ * @param cas
+ * a CAS.
+ * @param type
+ * a UIMA type.
+ * @param begin
+ * begin offset.
+ * @param end
+ * end offset.
+ * @return a return value.
+ */
+ public static List<AnnotationFS> selectCovering(CAS cas, Type type, int begin, int end) {
+
+ TypeSystem ts = cas.getTypeSystem();
+ List<AnnotationFS> list = new ArrayList<AnnotationFS>();
+ FSIterator<AnnotationFS> iter = cas.getAnnotationIndex().iterator();
+ while (iter.hasNext()) {
+ AnnotationFS a = iter.next();
+ if ((a.getBegin() <= begin) && (a.getEnd() >= end)
+ && ((type == null) || (ts.subsumes(type, a.getType())))) {
+ list.add(a);
+ }
+ }
+ return list;
+ }
+
+ /**
+ * Create an index for quickly lookup up the annotations covering a particular annotation. This
+ * is preferable to using {@link #selectCovering(CAS, Type, int, int)} because the overhead of
+ * scanning the CAS occurs only when the index is build. Subsequent lookups to the index are
+ * fast.
+ *
+ * @param cas
+ * a CAS.
+ * @param type
+ * type to create the index for - this is used in lookups.
+ * @param coveringType
+ * type of covering annotations.
+ * @return the index.
+ */
+ public static Map<AnnotationFS, Collection<AnnotationFS>> indexCovering(CAS cas, Type type,
+ Type coveringType) {
+ Map<AnnotationFS, Collection<AnnotationFS>> index = new HashMap<AnnotationFS, Collection<AnnotationFS>>() {
+ private static final long serialVersionUID = 1L;
+
+ @Override
+ public Collection<AnnotationFS> get(Object paramObject) {
+ Collection<AnnotationFS> res = super.get(paramObject);
+ if (res == null) {
+ return emptyList();
+ }
+ else {
+ return res;
+ }
+ }
+ };
+ for (AnnotationFS s : select(cas, coveringType)) {
+ for (AnnotationFS u : selectCovered(cas, type, s)) {
+ Collection<AnnotationFS> c = index.get(u);
+ if (c == EMPTY_LIST) {
+ c = new LinkedList<AnnotationFS>();
+ index.put(u, c);
+ }
+ c.add(s);
+ }
+ }
+ return unmodifiableMap(index);
+ }
+
+ /**
+ * Create an index for quickly lookup up the annotations covered by a particular annotation. This
+ * is preferable to using {@link #selectCovered(CAS, Type, int, int)} because the overhead of
+ * scanning the CAS occurs only when the index is build. Subsequent lookups to the index are
+ * fast.
+ *
+ * @param cas
+ * a CAS.
+ * @param type
+ * type to create the index for - this is used in lookups.
+ * @param coveredType
+ * type of covering annotations.
+ * @return the index.
+ */
+ public static Map<AnnotationFS, Collection<AnnotationFS>> indexCovered(CAS cas, Type type,
+ Type coveredType) {
+ Map<AnnotationFS, Collection<AnnotationFS>> index = new HashMap<AnnotationFS, Collection<AnnotationFS>>() {
+ private static final long serialVersionUID = 1L;
+
+ @Override
+ public Collection<AnnotationFS> get(Object paramObject) {
+ Collection<AnnotationFS> res = super.get(paramObject);
+ if (res == null) {
+ return emptyList();
+ }
+ else {
+ return res;
+ }
+ }
+ };
+ for (AnnotationFS s : select(cas, type)) {
+ for (AnnotationFS u : selectCovered(cas, coveredType, s)) {
+ Collection<AnnotationFS> c = index.get(s);
+ if (c == EMPTY_LIST) {
+ c = new LinkedList<AnnotationFS>();
+ index.put(s, c);
+ }
+ c.add(u);
+ }
+ }
+ return unmodifiableMap(index);
+ }
+ /**
+ * 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 cas
+ * a CAS containing the feature structure.
+ * @param type
+ * 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
+ */
+ public static FeatureStructure selectFSByIndex(CAS cas, Type type, int index) {
+ FSIterator<FeatureStructure> i = cas.getIndexRepository().getAllIndexedFS(type);
+ int n = index;
+ i.moveToFirst();
+ if (n > 0) {
+ while (n > 0 && i.isValid()) {
+ i.moveToNext();
+ n--;
+ }
+ }
+ if (n < 0) {
+ i.moveToLast();
+ while (n < -1 && i.isValid()) {
+ i.moveToPrevious();
+ n++;
+ }
+ }
+
+ return i.isValid() ? i.get() : null;
+ }
+
+ /**
+ * 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 cas
+ * a CAS containing the annotation.
+ * @param type
+ * 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
+ */
+ public static AnnotationFS selectByIndex(CAS cas, Type type, int index) {
+ if (!cas.getTypeSystem().subsumes(cas.getAnnotationType(), type)) {
+ throw new IllegalArgumentException("Type [" + type.getName()
+ + "] is not an annotation type");
+ }
+ FSIterator<AnnotationFS> i = cas.getAnnotationIndex(type).iterator();
+ int n = index;
+ i.moveToFirst();
+ if (n > 0) {
+ while (n > 0 && i.isValid()) {
+ i.moveToNext();
+ n--;
+ }
+ }
+ if (n < 0) {
+ i.moveToLast();
+ while (n < -1 && i.isValid()) {
+ i.moveToPrevious();
+ n++;
+ }
+ }
+
+ return i.isValid() ? i.get() : null;
+ }
+
+ /**
+ * Get the single instance of the specified type from the JCas.
+ *
+ * @param cas
+ * a CAS 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.
+ */
+ public static FeatureStructure selectSingle(CAS cas, Type type) {
+ FSIterator<FeatureStructure> iterator = cas.getIndexRepository().getAllIndexedFS(type);
+
+ if (!iterator.hasNext()) {
+ throw new IllegalArgumentException("CAS does not contain any [" + type.getName() + "]");
+ }
+
+ FeatureStructure result = iterator.next();
+
+ if (iterator.hasNext()) {
+ throw new IllegalArgumentException("CAS contains more than one [" + type.getName()
+ + "]");
+ }
+
+ return result;
+ }
+
+ /**
+ * Return an annotation preceding or following of a given reference annotation.
+ *
+ * @param type
+ * 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.
+ */
+ public static AnnotationFS selectSingleRelative(Type type,
+ AnnotationFS annotation, int index) {
+ return selectSingleRelative(annotation.getView(), type, annotation, index);
+ }
+
+ /**
+ * Return an annotation preceding or following of a given reference annotation.
+ *
+ * @param cas
+ * a CAS containing the annotation.
+ * @param type
+ * 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.
+ */
+ public static AnnotationFS selectSingleRelative(CAS cas, Type type,
+ AnnotationFS annotation, int index) {
+ if (!cas.getTypeSystem().subsumes(cas.getAnnotationType(), type)) {
+ throw new IllegalArgumentException("Type [" + type.getName()
+ + "] is not an annotation type");
+ }
+
+ // move to first previous annotation
+ FSIterator<AnnotationFS> itr = cas.getAnnotationIndex(type).iterator();
+ itr.moveTo(annotation);
+
+ if (index < 0) {
+ // make sure we're past the beginning of the reference annotation
+ while (itr.isValid() && itr.get().getEnd() > annotation.getBegin()) {
+ itr.moveToPrevious();
+ }
+
+ for (int i = 0; i < (-index - 1) && itr.isValid(); ++i, itr.moveToPrevious()) {
+ // Seeking
+ }
+
+ if (!itr.isValid()) {
+ throw new IndexOutOfBoundsException("Reached end of index while seeking.");
+ }
+ else {
+ return itr.get();
+ }
+ }
+ else if (index > 0) {
+ // make sure we're past the end of the reference annotation
+ while (itr.isValid() && itr.get().getBegin() < annotation.getEnd()) {
+ itr.moveToNext();
+ }
+
+ for (int i = 0; i < (index - 1) && itr.isValid(); ++i, itr.moveToPrevious()) {
+ // Seeking
+ }
+
+ if (!itr.isValid()) {
+ throw new IndexOutOfBoundsException("Reached end of index while seeking.");
+ }
+ else {
+ return itr.get();
+ }
+ }
+ else {
+ return annotation;
+ }
+ }
+
+ /**
+ * Returns the n annotations preceding the given annotation
+ *
+ * @param cas
+ * a CAS.
+ * @param type
+ * a UIMA type.
+ * @param annotation
+ * anchor annotation
+ * @param count
+ * number of annotations to collect
+ * @return List of aType annotations preceding anchor annotation
+ */
+ public static List<AnnotationFS> selectPreceding(CAS cas, Type type, AnnotationFS annotation,
+ int count) {
+ if (!cas.getTypeSystem().subsumes(cas.getAnnotationType(), type)) {
+ throw new IllegalArgumentException("Type [" + type.getName()
+ + "] is not an annotation type");
+ }
+
+ // move to first previous annotation
+ FSIterator<AnnotationFS> itr = cas.getAnnotationIndex(type).iterator();
+ itr.moveTo(annotation);
+
+ // make sure we're past the beginning of the reference annotation
+ while (itr.isValid() && itr.get().getEnd() > annotation.getBegin()) {
+ itr.moveToPrevious();
+ }
+
+ // add annotations from the iterator into the result list
+ List<AnnotationFS> precedingAnnotations = new LinkedList<AnnotationFS>();
+ for (int i = 0; i < count && itr.isValid(); ++i, itr.moveToPrevious()) {
+ precedingAnnotations.add(itr.get());
+ }
+
+ // return in correct order
+ Collections.reverse(precedingAnnotations);
+ return precedingAnnotations;
+ }
+
+ /**
+ * Returns the n annotations following the given annotation
+ *
+ * @param cas
+ * a CAS.
+ * @param type
+ * a UIMA type.
+ * @param annotation
+ * anchor annotation
+ * @param count
+ * number of annotations to collect
+ * @return List of aType annotations following anchor annotation
+ */
+ public static List<AnnotationFS> selectFollowing(CAS cas, Type type, AnnotationFS annotation,
+ int count) {
+ if (!cas.getTypeSystem().subsumes(cas.getAnnotationType(), type)) {
+ throw new IllegalArgumentException("Type [" + type.getName()
+ + "] is not an annotation type");
+ }
+
+ // move to first previous annotation
+ FSIterator<AnnotationFS> itr = cas.getAnnotationIndex(type).iterator();
+ itr.moveTo(annotation);
+
+ // make sure we're past the end of the reference annotation
+ while (itr.isValid() && itr.get().getBegin() < annotation.getEnd()) {
+ itr.moveToNext();
+ }
+
+ // add annotations from the iterator into the result list
+ List<AnnotationFS> followingAnnotations = new LinkedList<AnnotationFS>();
+ for (int i = 0; i < count && itr.isValid(); ++i, itr.moveToNext()) {
+ followingAnnotations.add(itr.get());
+ }
+ return followingAnnotations;
+ }
+
+ /**
+ * 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 cas
+ * a CAS
+ * @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.
+ */
+ public static CAS getView(CAS cas, String viewName, CAS fallback) {
+ CAS view;
+ try {
+ view = cas.getView(viewName);
+ }
+ catch (CASRuntimeException e) {
+ // use fall-back view instead
+ view = fallback;
+ }
+ return view;
+ }
+
+ /**
+ * Convenience method to get the specified view or create a new view if the requested view does
+ * not exist.
+ *
+ * @param cas
+ * a CAS
+ * @param viewName
+ * the requested view.
+ * @param create
+ * the view is created if it does not exist.
+ * @return the requested view
+ * @throws IllegalArgumentException
+ * if the view does not exist and is not to be created.
+ */
+ public static CAS getView(CAS cas, String viewName, boolean create) {
+ CAS view;
+ try {
+ view = cas.getView(viewName);
+ }
+ catch (CASRuntimeException e) {
+ // View does not exist
+ if (create) {
+ view = cas.createView(viewName);
+ }
+ else {
+ throw new IllegalArgumentException("No view with name [" + viewName + "]");
+ }
+ }
+
+ return view;
+ }
+
+ /**
+ * 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 toText(iterable.iterator());
+ }
+
+ /**
+ * Fetch the text covered by the specified annotations and return it as a list of strings.
+ *
+ * @param <T>
+ * UIMA JCas type.
+ * @param iterator
+ * annotation iterator.
+ * @return list of covered strings.
+ */
+ public static <T extends AnnotationFS> List<String> toText(Iterator<T> iterator) {
+ List<String> text = new ArrayList<String>();
+ while (iterator.hasNext()) {
+ AnnotationFS a = iterator.next();
+ text.add(a.getCoveredText());
+ }
+ return text;
+ }
+}
Propchange: uima/sandbox/trunk/uimaFIT/uimaFIT/src/main/java/org/apache/uima/fit/util/CasUtil.java
------------------------------------------------------------------------------
svn:eol-style = native
Added: uima/sandbox/trunk/uimaFIT/uimaFIT/src/main/java/org/apache/uima/fit/util/ContainmentIndex.java
URL: http://svn.apache.org/viewvc/uima/sandbox/trunk/uimaFIT/uimaFIT/src/main/java/org/apache/uima/fit/util/ContainmentIndex.java?rev=1421324&view=auto
==============================================================================
--- uima/sandbox/trunk/uimaFIT/uimaFIT/src/main/java/org/apache/uima/fit/util/ContainmentIndex.java (added)
+++ uima/sandbox/trunk/uimaFIT/uimaFIT/src/main/java/org/apache/uima/fit/util/ContainmentIndex.java Thu Dec 13 14:53:52 2012
@@ -0,0 +1,205 @@
+/*
+ Copyright 2009-2010
+ Ubiquitous Knowledge Processing (UKP) Lab
+ Technische Universitaet Darmstadt
+ All rights reserved.
+
+ Licensed under the Apache License, Version 2.0 (the "License");
+ you may not use this file except in compliance with the License.
+ You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
+ */
+
+package org.apache.uima.fit.util;
+
+import static org.apache.uima.fit.util.CasUtil.select;
+import static org.apache.uima.fit.util.CasUtil.selectCovered;
+
+import java.util.Collection;
+import java.util.Collections;
+import java.util.LinkedHashMap;
+import java.util.LinkedList;
+import java.util.Map;
+
+import org.apache.uima.cas.CAS;
+import org.apache.uima.cas.text.AnnotationFS;
+import org.apache.uima.jcas.JCas;
+
+/**
+ * Create a fast way of repeatedly checking whether instances of one type are contained within the
+ * boundaries on another type.
+ *
+ * @author Richard Eckart de Castilho
+ *
+ * @param <S>
+ * covering type.
+ * @param <U>
+ * covered type.
+ */
+public class ContainmentIndex<S extends AnnotationFS, U extends AnnotationFS> {
+ public static enum Type {
+ DIRECT, REVERSE, BOTH
+ }
+
+ private Map<AnnotationFS, Collection<AnnotationFS>> data =
+ new LinkedHashMap<AnnotationFS, Collection<AnnotationFS>>();
+ private Map<AnnotationFS, Collection<AnnotationFS>> dataRev =
+ new LinkedHashMap<AnnotationFS, Collection<AnnotationFS>>();
+
+ /**
+ * Create a new index on the given JCas using the specified two types. The last argument
+ * indicates in which directions lookups to the index will be made.
+ *
+ * @param cas
+ * the working JCas.
+ * @param aSuper
+ * the covering type.
+ * @param aUnder
+ * the covered type.
+ * @param aType
+ * the indexing strategy.
+ */
+ public ContainmentIndex(CAS cas, org.apache.uima.cas.Type aSuper, org.apache.uima.cas.Type aUnder,
+ Type aType) {
+ Collection<AnnotationFS> over = select(cas, aSuper);
+ for (AnnotationFS s : over) {
+ Collection<AnnotationFS> under = selectCovered(cas, aUnder, s);
+ for (AnnotationFS u : under) {
+ switch (aType) {
+ case DIRECT: {
+ put(data, s, u);
+ break;
+ }
+ case REVERSE:
+ put(dataRev, u, s);
+ break;
+ case BOTH:
+ put(data, s, u);
+ put(dataRev, u, s);
+ break;
+ }
+ }
+ }
+ }
+
+ private <X, Y> void put(Map<X, Collection<Y>> map, X key, Y value) {
+ Collection<Y> c = map.get(key);
+ if (c == null) {
+ c = new LinkedList<Y>();
+ map.put(key, c);
+ }
+ c.add(value);
+ }
+
+ /**
+ * Get all instances of the covered type contained within the boundaries of the specified
+ * instance of the covering type.
+ *
+ * @param aSuper
+ * a covering type instance.
+ * @return a collection of covered type instances.
+ */
+ @SuppressWarnings("unchecked")
+ public Collection<U> containedIn(S aSuper) {
+ @SuppressWarnings("rawtypes")
+ Collection c = data.get(aSuper);
+ if (c == null) {
+ return Collections.emptySet();
+ }
+ return c;
+ }
+
+ /**
+ * Get all instances of the covering type containing the the specified instance of the covered
+ * type.
+ *
+ * @param aUnder
+ * a covered type instance.
+ * @return a collection of covering type instances.
+ */
+ @SuppressWarnings("unchecked")
+ public Collection<S> containing(U aUnder) {
+ @SuppressWarnings("rawtypes")
+ Collection c = dataRev.get(aUnder);
+ if (c == null) {
+ return Collections.emptySet();
+ }
+ return c;
+ }
+
+ /**
+ * Checks if the given covered type is contained in the specified covering type.
+ *
+ * @param aSuper
+ * the covering type instance.
+ * @param aUnder
+ * the covered type instance.
+ * @return whether the covered instance is contained in the covering instance.
+ */
+ public boolean isContainedIn(S aSuper, U aUnder) {
+ return containedIn(aSuper).contains(aUnder);
+ }
+
+ /**
+ * Checks if the given covered type is contained in any instance of the covering type.
+ *
+ * @param aUnder
+ * the covered type instance.
+ * @return whether the covered instance is contained in any instance of the covering type.
+ */
+ public boolean isContainedInAny(U aUnder) {
+ Collection<S> containers = containing(aUnder);
+ return containers != null && !containers.isEmpty();
+ }
+
+ /**
+ * Factory method to create an index instead of using the constructor. This makes used of Java's
+ * type inference capabilities and results in less verbose code.
+ *
+ * @param <A>
+ * covering type.
+ * @param <B>
+ * covered type.
+ * @param aJcas
+ * the working JCas.
+ * @param aSuper
+ * the covering type.
+ * @param aUnder
+ * the covered type.
+ * @param aType
+ * the indexing strategy.
+ * @return the index instance.
+ */
+ @SuppressWarnings("unchecked")
+ public static <A extends AnnotationFS, B extends AnnotationFS> ContainmentIndex<A, B> create(
+ JCas aJcas, Class<A> aSuper, Class<B> aUnder, Type aType) {
+ return (ContainmentIndex<A, B>) create(aJcas.getCas(), JCasUtil.getType(aJcas, aSuper),
+ JCasUtil.getType(aJcas, aUnder), aType);
+ }
+
+ /**
+ * Factory method to create an index instead of using the constructor. This makes used of Java's
+ * type inference capabilities and results in less verbose code.
+ *
+ * @param cas
+ * the working JCas.
+ * @param aSuper
+ * the covering type.
+ * @param aUnder
+ * the covered type.
+ * @param aType
+ * the indexing strategy.
+ * @return the index instance.
+ */
+ public static ContainmentIndex<AnnotationFS, AnnotationFS> create(
+ CAS cas, org.apache.uima.cas.Type aSuper, org.apache.uima.cas.Type aUnder, Type aType) {
+ return new ContainmentIndex<AnnotationFS, AnnotationFS>(cas, aSuper, aUnder, aType);
+ }
+}
Propchange: uima/sandbox/trunk/uimaFIT/uimaFIT/src/main/java/org/apache/uima/fit/util/ContainmentIndex.java
------------------------------------------------------------------------------
svn:eol-style = native
Added: uima/sandbox/trunk/uimaFIT/uimaFIT/src/main/java/org/apache/uima/fit/util/ExtendedExternalResourceDescription_impl.java
URL: http://svn.apache.org/viewvc/uima/sandbox/trunk/uimaFIT/uimaFIT/src/main/java/org/apache/uima/fit/util/ExtendedExternalResourceDescription_impl.java?rev=1421324&view=auto
==============================================================================
--- uima/sandbox/trunk/uimaFIT/uimaFIT/src/main/java/org/apache/uima/fit/util/ExtendedExternalResourceDescription_impl.java (added)
+++ uima/sandbox/trunk/uimaFIT/uimaFIT/src/main/java/org/apache/uima/fit/util/ExtendedExternalResourceDescription_impl.java Thu Dec 13 14:53:52 2012
@@ -0,0 +1,63 @@
+/*
+ Copyright 2009-2010
+ Ubiquitous Knowledge Processing (UKP) Lab
+ Technische Universitaet Darmstadt
+ All rights reserved.
+
+ Licensed under the Apache License, Version 2.0 (the "License");
+ you may not use this file except in compliance with the License.
+ You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
+ */
+package org.apache.uima.fit.util;
+
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.List;
+
+import org.apache.uima.resource.ExternalResourceDescription;
+import org.apache.uima.resource.impl.ExternalResourceDescription_impl;
+import org.apache.uima.resource.metadata.ExternalResourceBinding;
+
+/**
+ * Extended {@link ExternalResourceDescription_impl} which can carry
+ * {@link ExternalResourceDescription}s.
+ *
+ * @author Richard Eckart de Castilho
+ */
+public class ExtendedExternalResourceDescription_impl extends ExternalResourceDescription_impl {
+ private static final long serialVersionUID = 4901306350609836452L;
+ private List<ExternalResourceBinding> externalResourceBindings = new ArrayList<ExternalResourceBinding>();
+ private List<ExternalResourceDescription> externalResources = new ArrayList<ExternalResourceDescription>();
+
+ public List<ExternalResourceBinding> getExternalResourceBindings() {
+ return externalResourceBindings;
+ }
+
+ public void setExternalResourceBindings(
+ Collection<ExternalResourceBinding> aExternalResourceBindings) {
+ externalResourceBindings = new ArrayList<ExternalResourceBinding>();
+ if (aExternalResourceBindings != null) {
+ externalResourceBindings.addAll(aExternalResourceBindings);
+ }
+ }
+
+ public List<ExternalResourceDescription> getExternalResources() {
+ return externalResources;
+ }
+
+ public void setExternalResources(
+ Collection<ExternalResourceDescription> aExternalResourceDescriptions) {
+ externalResources = new ArrayList<ExternalResourceDescription>();
+ if (externalResources != null) {
+ externalResources.addAll(aExternalResourceDescriptions);
+ }
+ }
+}
Propchange: uima/sandbox/trunk/uimaFIT/uimaFIT/src/main/java/org/apache/uima/fit/util/ExtendedExternalResourceDescription_impl.java
------------------------------------------------------------------------------
svn:eol-style = native
Added: uima/sandbox/trunk/uimaFIT/uimaFIT/src/main/java/org/apache/uima/fit/util/ExtendedLogger.java
URL: http://svn.apache.org/viewvc/uima/sandbox/trunk/uimaFIT/uimaFIT/src/main/java/org/apache/uima/fit/util/ExtendedLogger.java?rev=1421324&view=auto
==============================================================================
--- uima/sandbox/trunk/uimaFIT/uimaFIT/src/main/java/org/apache/uima/fit/util/ExtendedLogger.java (added)
+++ uima/sandbox/trunk/uimaFIT/uimaFIT/src/main/java/org/apache/uima/fit/util/ExtendedLogger.java Thu Dec 13 14:53:52 2012
@@ -0,0 +1,382 @@
+/*
+ Copyright 2010 Regents of the University of Colorado.
+ All rights reserved.
+
+ Licensed under the Apache License, Version 2.0 (the "License");
+ you may not use this file except in compliance with the License.
+ You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
+*/
+package org.apache.uima.fit.util;
+
+import java.io.OutputStream;
+import java.io.PrintStream;
+
+import org.apache.uima.UimaContext;
+import org.apache.uima.resource.ResourceManager;
+import org.apache.uima.util.Level;
+import org.apache.uima.util.Logger;
+
+
+/**
+ * Wrapper for the UIMA {@link Logger} offering a more convenient API similar to that of the
+ * Apache Commons Logging interface {@link org.apache.commons.logging.Log Log} or to that of
+ * Log4J's {@code Category} and SLF4J's {@code Logger}, using the names {@code error}, {@code warn},
+ * {@code info}, {@code debug} and {@code trace} and mapping these to UIMA logging levels.
+ *
+ * @author Richard Eckart de Castilho
+ */
+public class ExtendedLogger implements Logger {
+
+ private final UimaContext context;
+
+ public ExtendedLogger(final UimaContext aContext) {
+ context = aContext;
+ }
+
+ @Deprecated
+ public void log(String aMessage) {
+ if (context != null) {
+ Logger logger = context.getLogger();
+ if (logger != null) {
+ logger.log(aMessage);
+ }
+ }
+ }
+
+ @Deprecated
+ public void log(String aResourceBundleName, String aMessageKey, Object[] aArguments) {
+ if (context != null) {
+ Logger logger = context.getLogger();
+ if (logger != null) {
+ context.getLogger().log(aResourceBundleName, aMessageKey, aArguments);
+ }
+ }
+ }
+
+ @Deprecated
+ public void logException(Exception aException) {
+ if (context != null) {
+ Logger logger = context.getLogger();
+ if (logger != null) {
+ context.getLogger().logException(aException);
+ }
+ }
+ }
+
+ @Deprecated
+ public void setOutputStream(PrintStream aStream) {
+ if (context != null) {
+ Logger logger = context.getLogger();
+ if (logger != null) {
+ context.getLogger().setOutputStream(aStream);
+ }
+ }
+ }
+
+ @Deprecated
+ public void setOutputStream(OutputStream aStream) {
+ if (context != null) {
+ Logger logger = context.getLogger();
+ if (logger != null) {
+ context.getLogger().setOutputStream(aStream);
+ }
+ }
+ }
+
+ public void log(Level level, String aMessage) {
+ if (context != null) {
+ Logger logger = context.getLogger();
+ if (logger != null) {
+ context.getLogger().log(level, aMessage);
+ }
+ }
+ }
+
+ public void log(Level level, String aMessage, Object param1) {
+ if (context != null) {
+ Logger logger = context.getLogger();
+ if (logger != null) {
+ context.getLogger().log(level, aMessage, param1);
+ }
+ }
+ }
+
+ public void log(Level level, String aMessage, Object[] params) {
+ if (context != null) {
+ Logger logger = context.getLogger();
+ if (logger != null) {
+ context.getLogger().log(level, aMessage, params);
+ }
+ }
+ }
+
+ public void log(Level level, String aMessage, Throwable thrown) {
+ if (context != null) {
+ Logger logger = context.getLogger();
+ if (logger != null) {
+ context.getLogger().log(level, aMessage, thrown);
+ }
+ }
+ }
+
+ public void logrb(Level level, String sourceClass, String sourceMethod, String bundleName,
+ String msgKey) {
+ if (context != null) {
+ Logger logger = context.getLogger();
+ if (logger != null) {
+ context.getLogger().logrb(level, sourceClass, sourceMethod, bundleName, msgKey);
+ }
+ }
+ }
+
+ public void logrb(Level level, String sourceClass, String sourceMethod, String bundleName,
+ String msgKey, Object param1) {
+ if (context != null) {
+ Logger logger = context.getLogger();
+ if (logger != null) {
+ context.getLogger().logrb(level, sourceClass, sourceMethod, bundleName, msgKey, param1);
+ }
+ }
+ }
+
+ public void logrb(Level level, String sourceClass, String sourceMethod, String bundleName,
+ String msgKey, Object[] params) {
+ if (context != null) {
+ Logger logger = context.getLogger();
+ if (logger != null) {
+ context.getLogger().logrb(level, sourceClass, sourceMethod, bundleName, msgKey, params);
+ }
+ }
+ }
+
+ public void logrb(Level level, String sourceClass, String sourceMethod, String bundleName,
+ String msgKey, Throwable thrown) {
+ if (context != null) {
+ Logger logger = context.getLogger();
+ if (logger != null) {
+ context.getLogger().logrb(level, sourceClass, sourceMethod, bundleName, msgKey, thrown);
+ }
+ }
+ }
+
+ public boolean isLoggable(Level level) {
+ if (context != null) {
+ Logger logger = context.getLogger();
+ if (logger != null) {
+ return context.getLogger().isLoggable(level);
+ }
+ }
+ return false;
+ }
+
+ public void setLevel(Level level) {
+ context.getLogger().setLevel(level);
+ }
+
+ public void setResourceManager(ResourceManager resourceManager) {
+ context.getLogger().setResourceManager(resourceManager);
+ }
+
+ /**
+ * Logs a message at {@link Level#FINE}.
+ *
+ * @param paramObject a message.
+ */
+ public void debug(Object paramObject) {
+ if (context != null) {
+ Logger logger = context.getLogger();
+ if (logger != null) {
+ context.getLogger().log(Level.FINE, String.valueOf(paramObject));
+ }
+ }
+ }
+
+ /**
+ * Logs a message at {@link Level#FINE}.
+ *
+ * @param paramObject a message.
+ * @param paramThrowable a cause.
+ */
+ public void debug(Object paramObject, Throwable paramThrowable) {
+ if (context != null) {
+ Logger logger = context.getLogger();
+ if (logger != null) {
+ context.getLogger().log(Level.FINE, String.valueOf(paramObject), paramThrowable);
+ }
+ }
+ }
+
+ /**
+ * Logs a message at {@link Level#SEVERE}.
+ *
+ * @param paramObject a message.
+ */
+ public void error(Object paramObject) {
+ if (context != null) {
+ Logger logger = context.getLogger();
+ if (logger != null) {
+ context.getLogger().log(Level.SEVERE, String.valueOf(paramObject));
+ }
+ }
+ }
+
+ /**
+ * Logs a message at {@link Level#SEVERE}.
+ *
+ * @param paramObject a message.
+ * @param paramThrowable a cause.
+ */
+ public void error(Object paramObject, Throwable paramThrowable) {
+ if (context != null) {
+ Logger logger = context.getLogger();
+ if (logger != null) {
+ context.getLogger().log(Level.SEVERE, String.valueOf(paramObject), paramThrowable);
+ }
+ }
+ }
+
+ /**
+ * Logs a message at {@link Level#INFO}.
+ *
+ * @param paramObject a message.
+ */
+ public void info(Object paramObject) {
+ if (context != null) {
+ Logger logger = context.getLogger();
+ if (logger != null) {
+ context.getLogger().log(Level.INFO, String.valueOf(paramObject));
+ }
+ }
+ }
+
+ /**
+ * Logs a message at {@link Level#INFO}.
+ *
+ * @param paramObject a message.
+ * @param paramThrowable a cause.
+ */
+ public void info(Object paramObject, Throwable paramThrowable) {
+ if (context != null) {
+ Logger logger = context.getLogger();
+ if (logger != null) {
+ context.getLogger().log(Level.INFO, String.valueOf(paramObject), paramThrowable);
+ }
+ }
+ }
+
+ public boolean isDebugEnabled() {
+ if (context != null) {
+ Logger logger = context.getLogger();
+ if (logger != null) {
+ return context.getLogger().isLoggable(Level.FINE);
+ }
+ }
+ return false;
+ }
+
+ public boolean isErrorEnabled() {
+ if (context != null) {
+ Logger logger = context.getLogger();
+ if (logger != null) {
+ return context.getLogger().isLoggable(Level.SEVERE);
+ }
+ }
+ return false;
+ }
+
+ public boolean isInfoEnabled() {
+ if (context != null) {
+ Logger logger = context.getLogger();
+ if (logger != null) {
+ return context.getLogger().isLoggable(Level.INFO);
+ }
+ }
+ return false;
+ }
+
+ public boolean isTraceEnabled() {
+ if (context != null) {
+ Logger logger = context.getLogger();
+ if (logger != null) {
+ return context.getLogger().isLoggable(Level.FINER);
+ }
+ }
+ return false;
+ }
+
+ public boolean isWarnEnabled() {
+ if (context != null) {
+ Logger logger = context.getLogger();
+ if (logger != null) {
+ return context.getLogger().isLoggable(Level.WARNING);
+ }
+ }
+ return false;
+ }
+
+ /**
+ * Logs a message at {@link Level#FINER}.
+ *
+ * @param paramObject a message.
+ */
+ public void trace(Object paramObject) {
+ if (context != null) {
+ Logger logger = context.getLogger();
+ if (logger != null) {
+ context.getLogger().log(Level.FINER, String.valueOf(paramObject));
+ }
+ }
+ }
+
+ /**
+ * Logs a message at {@link Level#FINER}.
+ *
+ * @param paramObject a message.
+ * @param paramThrowable a cause.
+ */
+ public void trace(Object paramObject, Throwable paramThrowable) {
+ if (context != null) {
+ Logger logger = context.getLogger();
+ if (logger != null) {
+ context.getLogger().log(Level.FINER, String.valueOf(paramObject), paramThrowable);
+ }
+ }
+ }
+
+ /**
+ * Logs a message at {@link Level#WARNING}.
+ *
+ * @param paramObject a message.
+ */
+ public void warn(Object paramObject) {
+ if (context != null) {
+ Logger logger = context.getLogger();
+ if (logger != null) {
+ context.getLogger().log(Level.WARNING, String.valueOf(paramObject));
+ }
+ }
+ }
+
+ /**
+ * Logs a message at {@link Level#WARNING}.
+ *
+ * @param paramObject a message.
+ * @param paramThrowable a cause.
+ */
+ public void warn(Object paramObject, Throwable paramThrowable) {
+ if (context != null) {
+ Logger logger = context.getLogger();
+ if (logger != null) {
+ context.getLogger().log(Level.WARNING, String.valueOf(paramObject), paramThrowable);
+ }
+ }
+ }
+}
Propchange: uima/sandbox/trunk/uimaFIT/uimaFIT/src/main/java/org/apache/uima/fit/util/ExtendedLogger.java
------------------------------------------------------------------------------
svn:eol-style = native
Added: uima/sandbox/trunk/uimaFIT/uimaFIT/src/main/java/org/apache/uima/fit/util/FSCollectionFactory.java
URL: http://svn.apache.org/viewvc/uima/sandbox/trunk/uimaFIT/uimaFIT/src/main/java/org/apache/uima/fit/util/FSCollectionFactory.java?rev=1421324&view=auto
==============================================================================
--- uima/sandbox/trunk/uimaFIT/uimaFIT/src/main/java/org/apache/uima/fit/util/FSCollectionFactory.java (added)
+++ uima/sandbox/trunk/uimaFIT/uimaFIT/src/main/java/org/apache/uima/fit/util/FSCollectionFactory.java Thu Dec 13 14:53:52 2012
@@ -0,0 +1,704 @@
+/*
+ Copyright 2011
+ Ubiquitous Knowledge Processing (UKP) Lab
+ Technische Universitaet Darmstadt
+ All rights reserved.
+
+ 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.
+
+ getCoveredAnnotations() contains code adapted from the UIMA Subiterator class.
+ */
+package org.apache.uima.fit.util;
+
+import static java.util.Arrays.asList;
+
+import java.util.AbstractCollection;
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.Iterator;
+import java.util.List;
+
+import org.apache.uima.cas.ArrayFS;
+import org.apache.uima.cas.BooleanArrayFS;
+import org.apache.uima.cas.ByteArrayFS;
+import org.apache.uima.cas.CAS;
+import org.apache.uima.cas.DoubleArrayFS;
+import org.apache.uima.cas.FSIterator;
+import org.apache.uima.cas.FeatureStructure;
+import org.apache.uima.cas.FloatArrayFS;
+import org.apache.uima.cas.IntArrayFS;
+import org.apache.uima.cas.LongArrayFS;
+import org.apache.uima.cas.ShortArrayFS;
+import org.apache.uima.cas.StringArrayFS;
+import org.apache.uima.cas.Type;
+import org.apache.uima.cas.TypeSystem;
+import org.apache.uima.cas.text.AnnotationFS;
+import org.apache.uima.cas.text.AnnotationIndex;
+import org.apache.uima.jcas.JCas;
+import org.apache.uima.jcas.cas.BooleanArray;
+import org.apache.uima.jcas.cas.ByteArray;
+import org.apache.uima.jcas.cas.DoubleArray;
+import org.apache.uima.jcas.cas.EmptyFSList;
+import org.apache.uima.jcas.cas.EmptyFloatList;
+import org.apache.uima.jcas.cas.EmptyIntegerList;
+import org.apache.uima.jcas.cas.EmptyStringList;
+import org.apache.uima.jcas.cas.FSArray;
+import org.apache.uima.jcas.cas.FSList;
+import org.apache.uima.jcas.cas.FloatArray;
+import org.apache.uima.jcas.cas.FloatList;
+import org.apache.uima.jcas.cas.IntegerArray;
+import org.apache.uima.jcas.cas.IntegerList;
+import org.apache.uima.jcas.cas.LongArray;
+import org.apache.uima.jcas.cas.NonEmptyFSList;
+import org.apache.uima.jcas.cas.NonEmptyFloatList;
+import org.apache.uima.jcas.cas.NonEmptyIntegerList;
+import org.apache.uima.jcas.cas.NonEmptyStringList;
+import org.apache.uima.jcas.cas.ShortArray;
+import org.apache.uima.jcas.cas.StringArray;
+import org.apache.uima.jcas.cas.StringList;
+import org.apache.uima.jcas.cas.TOP;
+
+/**
+ * Bridge between Java {@link Collection Collections} from different representations of collections
+ * of UIMA {@link FeatureStructure FeatureStructures}.
+ *
+ * @author Richard Eckart de Castilho
+ *
+ * @param <T> data type.
+ */
+public abstract class FSCollectionFactory<T extends FeatureStructure> extends AbstractCollection<T> {
+
+ @SuppressWarnings({ "unchecked", "rawtypes" })
+ public static Collection<FeatureStructure> create(CAS cas, Type type)
+ {
+ // If the type is an annotation type, we can use the annotation index, which directly
+ // provides us with its size. If not, we have to use getAllIndexedFS() which we have to
+ // scan from beginning to end in order to determine its size.
+ TypeSystem ts = cas.getTypeSystem();
+ if (ts.subsumes(cas.getAnnotationType(), type)) {
+ return (Collection) create(cas.getAnnotationIndex(type));
+ }
+ else {
+ return create(cas.getIndexRepository().getAllIndexedFS(type));
+ }
+ }
+
+ public static <T extends FeatureStructure> Collection<T> create(FSIterator<T> aIterator)
+ {
+ return new FSIteratorAdapter<T>(aIterator);
+ }
+
+ public static <T extends AnnotationFS> Collection<T> create(AnnotationIndex<T> aIndex)
+ {
+ return new AnnotationIndexAdapter<T>(aIndex);
+ }
+
+ public static Collection<FeatureStructure> create(ArrayFS aArray)
+ {
+ return create(aArray, (Type) null);
+ }
+
+ /**
+ * Fetch all annotations of the given type or its sub-types from the given FS array.
+ *
+ * @param <T>
+ * the JCas type.
+ * @param aArray
+ * the FS array
+ * @param aType
+ * the JCas wrapper class.
+ * @return a collection of all annotations of the given type.
+ */
+ @SuppressWarnings({ "unchecked", "rawtypes" })
+ public static <T extends TOP> Collection<T> create(ArrayFS aArray, Class<T> aType)
+ {
+ return (Collection) create(aArray, CasUtil.getType(aArray.getCAS(), aType));
+ }
+
+ /**
+ * Fetch all annotations of the given type or its sub-types from the given FS array.
+ *
+ * @param aArray
+ * the FS array
+ * @param aType
+ * the CAS type.
+ * @return a collection of all annotations of the given type.
+ */
+ public static Collection<FeatureStructure> create(ArrayFS aArray, Type aType)
+ {
+ TypeSystem ts = aArray.getCAS().getTypeSystem();
+ List<FeatureStructure> data = new ArrayList<FeatureStructure>(aArray.size());
+ for (int i = 0; i < aArray.size(); i++) {
+ FeatureStructure value = aArray.get(i);
+ if (value != null && (aType == null || ts.subsumes(aType, value.getType()))) {
+ data.add(value);
+ }
+ }
+ return asList(data.toArray(new FeatureStructure[data.size()]));
+ }
+
+ public static ArrayFS createFSArray(CAS aCas, Collection<? extends FeatureStructure> aCollection)
+ {
+ return fillArrayFS(aCas.createArrayFS(aCollection.size()), aCollection);
+ }
+
+ public static ArrayFS createFSArray(CAS aCas, FeatureStructure[] aArray)
+ {
+ return fillArrayFS(aCas.createArrayFS(aArray.length), asList(aArray));
+ }
+
+ public static ArrayFS createFSArray(JCas aJCas, Collection<? extends FeatureStructure> aCollection)
+ {
+ return fillArrayFS(new FSArray(aJCas, aCollection.size()), aCollection);
+ }
+
+ public static ArrayFS createFSArray(JCas aJCas, FeatureStructure[] aArray)
+ {
+ return fillArrayFS(new FSArray(aJCas, aArray.length), asList(aArray));
+ }
+
+ public static BooleanArrayFS createBooleanArray(CAS aCas, Collection<Boolean> aCollection)
+ {
+ return fillArrayFS(aCas.createBooleanArrayFS(aCollection.size()), aCollection);
+ }
+
+ public static BooleanArrayFS createBooleanArray(CAS aCas, boolean[] aArray)
+ {
+ return fillArrayFS(aCas.createBooleanArrayFS(aArray.length), aArray);
+ }
+
+ public static BooleanArrayFS createBooleanArray(JCas aJCas, Collection<Boolean> aCollection)
+ {
+ return fillArrayFS(new BooleanArray(aJCas, aCollection.size()), aCollection);
+ }
+
+ public static BooleanArrayFS createBooleanArray(JCas aJCas, boolean[] aArray)
+ {
+ return fillArrayFS(new BooleanArray(aJCas, aArray.length), aArray);
+ }
+
+ public static ByteArrayFS createByteArray(CAS aCas, Collection<Byte> aCollection)
+ {
+ return fillArrayFS(aCas.createByteArrayFS(aCollection.size()), aCollection);
+ }
+
+ public static ByteArrayFS createByteArray(CAS aCas, byte[] aArray)
+ {
+ return fillArrayFS(aCas.createByteArrayFS(aArray.length), aArray);
+ }
+
+ public static ByteArrayFS createByteArray(JCas aJCas, Collection<Byte> aCollection)
+ {
+ return fillArrayFS(new ByteArray(aJCas, aCollection.size()), aCollection);
+ }
+
+ public static ByteArrayFS createByteArray(JCas aJCas, byte[] aArray)
+ {
+ return fillArrayFS(new ByteArray(aJCas, aArray.length), aArray);
+ }
+
+ public static DoubleArrayFS createDoubleArray(CAS aCas, Collection<Double> aCollection)
+ {
+ return fillArrayFS(aCas.createDoubleArrayFS(aCollection.size()), aCollection);
+ }
+
+ public static DoubleArrayFS createDoubleArray(CAS aCas, double[] aArray)
+ {
+ return fillArrayFS(aCas.createDoubleArrayFS(aArray.length), aArray);
+ }
+
+ public static DoubleArrayFS createDoubleArray(JCas aJCas, Collection<Double> aCollection)
+ {
+ return fillArrayFS(new DoubleArray(aJCas, aCollection.size()), aCollection);
+ }
+
+ public static DoubleArrayFS createDoubleArray(JCas aJCas, double[] aArray)
+ {
+ return fillArrayFS(new DoubleArray(aJCas, aArray.length), aArray);
+ }
+
+ public static FloatArrayFS createFloatArray(CAS aCas, Collection<Float> aCollection)
+ {
+ return fillArrayFS(aCas.createFloatArrayFS(aCollection.size()), aCollection);
+ }
+
+ public static FloatArrayFS createFloatArray(CAS aCas, float[] aArray)
+ {
+ return fillArrayFS(aCas.createFloatArrayFS(aArray.length), aArray);
+ }
+
+ public static FloatArrayFS createFloatArray(JCas aJCas, Collection<Float> aCollection)
+ {
+ return fillArrayFS(new FloatArray(aJCas, aCollection.size()), aCollection);
+ }
+
+ public static FloatArrayFS createFloatArray(JCas aJCas, float[] aArray)
+ {
+ return fillArrayFS(new FloatArray(aJCas, aArray.length), aArray);
+ }
+
+ public static IntArrayFS createIntArray(CAS aCas, Collection<Integer> aCollection)
+ {
+ return fillArrayFS(aCas.createIntArrayFS(aCollection.size()), aCollection);
+ }
+
+ public static IntArrayFS createIntArray(CAS aCas, int[] aArray)
+ {
+ return fillArrayFS(aCas.createIntArrayFS(aArray.length), aArray);
+ }
+
+ public static IntArrayFS createIntArray(JCas aJCas, Collection<Integer> aCollection)
+ {
+ return fillArrayFS(new IntegerArray(aJCas, aCollection.size()), aCollection);
+ }
+
+ public static IntArrayFS createIntArray(JCas aJCas, int[] aArray)
+ {
+ return fillArrayFS(new IntegerArray(aJCas, aArray.length), aArray);
+ }
+
+ public static LongArrayFS createLongArray(CAS aCas, Collection<Long> aCollection)
+ {
+ return fillArrayFS(aCas.createLongArrayFS(aCollection.size()), aCollection);
+ }
+
+ public static LongArrayFS createLongArray(CAS aCas, long[] aArray)
+ {
+ return fillArrayFS(aCas.createLongArrayFS(aArray.length), aArray);
+ }
+
+ public static LongArrayFS createLongArray(JCas aJCas, Collection<Long> aCollection)
+ {
+ return fillArrayFS(new LongArray(aJCas, aCollection.size()), aCollection);
+ }
+
+ public static LongArrayFS createLongArray(JCas aJCas, long[] aArray)
+ {
+ return fillArrayFS(new LongArray(aJCas, aArray.length), aArray);
+ }
+
+ public static ShortArrayFS createShortArray(CAS aCas, Collection<Short> aCollection)
+ {
+ return fillArrayFS(aCas.createShortArrayFS(aCollection.size()), aCollection);
+ }
+
+ public static ShortArrayFS createShortArray(CAS aCas, short[] aArray)
+ {
+ return fillArrayFS(aCas.createShortArrayFS(aArray.length), aArray);
+ }
+
+ public static ShortArrayFS createShortArray(JCas aJCas, Collection<Short> aCollection)
+ {
+ return fillArrayFS(new ShortArray(aJCas, aCollection.size()), aCollection);
+ }
+
+ public static ShortArrayFS createShortArray(JCas aJCas, short[] aArray)
+ {
+ return fillArrayFS(new ShortArray(aJCas, aArray.length), aArray);
+ }
+
+ public static StringArrayFS createStringArray(CAS aCas, Collection<String> aCollection)
+ {
+ return fillArrayFS(aCas.createStringArrayFS(aCollection.size()), aCollection);
+ }
+
+ public static StringArrayFS createStringArray(CAS aCas, String[] aArray)
+ {
+ return fillArrayFS(aCas.createStringArrayFS(aArray.length), aArray);
+ }
+
+ public static StringArrayFS createStringArray(JCas aJCas, Collection<String> aCollection)
+ {
+ return fillArrayFS(new StringArray(aJCas, aCollection.size()), aCollection);
+ }
+
+ public static StringArrayFS createStringArray(JCas aJCas, String[] aArray)
+ {
+ return fillArrayFS(new StringArray(aJCas, aArray.length), aArray);
+ }
+
+ public static ArrayFS fillArrayFS(ArrayFS aArrayFs, Iterable<? extends FeatureStructure> aCollection)
+ {
+ int i = 0;
+ for (FeatureStructure fs : aCollection) {
+ aArrayFs.set(i, fs);
+ i++;
+ }
+ return aArrayFs;
+ }
+
+ public static ArrayFS fillArrayFS(ArrayFS aArrayFs, FeatureStructure[] aArray)
+ {
+ aArrayFs.copyFromArray(aArray, 0, 0, aArrayFs.size());
+ return aArrayFs;
+ }
+
+ public static BooleanArrayFS fillArrayFS(BooleanArrayFS aArrayFs, Iterable<Boolean> aCollection)
+ {
+ int i = 0;
+ for (Boolean fs : aCollection) {
+ aArrayFs.set(i, fs);
+ i++;
+ }
+ return aArrayFs;
+ }
+
+ public static BooleanArrayFS fillArrayFS(BooleanArrayFS aArrayFs, boolean[] aArray)
+ {
+ aArrayFs.copyFromArray(aArray, 0, 0, aArrayFs.size());
+ return aArrayFs;
+ }
+
+ public static ByteArrayFS fillArrayFS(ByteArrayFS aArrayFs, Iterable<Byte> aCollection)
+ {
+ int i = 0;
+ for (Byte fs : aCollection) {
+ aArrayFs.set(i, fs);
+ i++;
+ }
+ return aArrayFs;
+ }
+
+ public static ByteArrayFS fillArrayFS(ByteArrayFS aArrayFs, byte[] aArray)
+ {
+ aArrayFs.copyFromArray(aArray, 0, 0, aArrayFs.size());
+ return aArrayFs;
+ }
+
+ public static DoubleArrayFS fillArrayFS(DoubleArrayFS aArrayFs, Iterable<Double> aCollection)
+ {
+ int i = 0;
+ for (Double fs : aCollection) {
+ aArrayFs.set(i, fs);
+ i++;
+ }
+ return aArrayFs;
+ }
+
+ public static DoubleArrayFS fillArrayFS(DoubleArrayFS aArrayFs, double[] aArray)
+ {
+ aArrayFs.copyFromArray(aArray, 0, 0, aArrayFs.size());
+ return aArrayFs;
+ }
+
+ public static FloatArrayFS fillArrayFS(FloatArrayFS aArrayFs, Iterable<Float> aCollection)
+ {
+ int i = 0;
+ for (Float fs : aCollection) {
+ aArrayFs.set(i, fs);
+ i++;
+ }
+ return aArrayFs;
+ }
+
+ public static FloatArrayFS fillArrayFS(FloatArrayFS aArrayFs, float[] aArray)
+ {
+ aArrayFs.copyFromArray(aArray, 0, 0, aArrayFs.size());
+ return aArrayFs;
+ }
+
+ public static IntArrayFS fillArrayFS(IntArrayFS aArrayFs, Iterable<Integer> aCollection)
+ {
+ int i = 0;
+ for (Integer fs : aCollection) {
+ aArrayFs.set(i, fs);
+ i++;
+ }
+ return aArrayFs;
+ }
+
+ public static IntArrayFS fillArrayFS(IntArrayFS aArrayFs, int[] aArray)
+ {
+ aArrayFs.copyFromArray(aArray, 0, 0, aArrayFs.size());
+ return aArrayFs;
+ }
+
+ public static LongArrayFS fillArrayFS(LongArrayFS aArrayFs, Iterable<Long> aCollection)
+ {
+ int i = 0;
+ for (Long fs : aCollection) {
+ aArrayFs.set(i, fs);
+ i++;
+ }
+ return aArrayFs;
+ }
+
+ public static LongArrayFS fillArrayFS(LongArrayFS aArrayFs, long[] aArray)
+ {
+ aArrayFs.copyFromArray(aArray, 0, 0, aArrayFs.size());
+ return aArrayFs;
+ }
+
+ public static ShortArrayFS fillArrayFS(ShortArrayFS aArrayFs, Iterable<Short> aCollection)
+ {
+ int i = 0;
+ for (Short fs : aCollection) {
+ aArrayFs.set(i, fs);
+ i++;
+ }
+ return aArrayFs;
+ }
+
+ public static ShortArrayFS fillArrayFS(ShortArrayFS aArrayFs, short[] aArray)
+ {
+ aArrayFs.copyFromArray(aArray, 0, 0, aArrayFs.size());
+ return aArrayFs;
+ }
+
+ public static StringArrayFS fillArrayFS(StringArrayFS aArrayFs, Iterable<String> aCollection)
+ {
+ int i = 0;
+ for (String fs : aCollection) {
+ aArrayFs.set(i, fs);
+ i++;
+ }
+ return aArrayFs;
+ }
+
+ public static StringArrayFS fillArrayFS(StringArrayFS aArrayFs, String[] aArray)
+ {
+ aArrayFs.copyFromArray(aArray, 0, 0, aArrayFs.size());
+ return aArrayFs;
+ }
+
+ // Using TOP here because FSList is only available in the JCas.
+ public static Collection<TOP> create(FSList aList)
+ {
+ return create(aList, (Type) null);
+ }
+
+ /**
+ * Fetch all annotations of the given type or its sub-types from the given FS list.
+ *
+ * @param <T>
+ * the JCas type.
+ * @param aList
+ * the FS list
+ * @param aType
+ * the JCas wrapper class.
+ * @return a collection of all annotations of the given type.
+ */
+ @SuppressWarnings("unchecked")
+ public static <T extends TOP> Collection<T> create(FSList aList, Class<T> aType)
+ {
+ return (Collection<T>) create(aList, CasUtil.getType(aList.getCAS(), aType));
+ }
+
+ // Using TOP here because FSList is only available in the JCas.
+ public static Collection<TOP> create(FSList aList, Type type)
+ {
+ TypeSystem ts = aList.getCAS().getTypeSystem();
+ List<FeatureStructure> data = new ArrayList<FeatureStructure>();
+ FSList i = aList;
+ while (i instanceof NonEmptyFSList) {
+ NonEmptyFSList l = (NonEmptyFSList) i;
+ TOP value = l.getHead();
+ if (value != null && (type == null || ts.subsumes(type, value.getType()))) {
+ data.add(l.getHead());
+ }
+ i = l.getTail();
+ }
+
+ return asList(data.toArray(new TOP[data.size()]));
+ }
+
+ public static Collection<String> create(StringList aList)
+ {
+ List<String> data = new ArrayList<String>();
+ StringList i = aList;
+ while (i instanceof NonEmptyStringList) {
+ NonEmptyStringList l = (NonEmptyStringList) i;
+ data.add(l.getHead());
+ i = l.getTail();
+ }
+
+ return asList(data.toArray(new String[data.size()]));
+ }
+
+ public static Collection<Integer> create(IntegerList aList)
+ {
+ List<Integer> data = new ArrayList<Integer>();
+ IntegerList i = aList;
+ while (i instanceof NonEmptyIntegerList) {
+ NonEmptyIntegerList l = (NonEmptyIntegerList) i;
+ data.add(l.getHead());
+ i = l.getTail();
+ }
+
+ return asList(data.toArray(new Integer[data.size()]));
+ }
+
+ public static Collection<Float> create(FloatList aList)
+ {
+ List<Float> data = new ArrayList<Float>();
+ FloatList i = aList;
+ while (i instanceof NonEmptyFloatList) {
+ NonEmptyFloatList l = (NonEmptyFloatList) i;
+ data.add(l.getHead());
+ i = l.getTail();
+ }
+
+ return asList(data.toArray(new Float[data.size()]));
+ }
+
+ public static FSList createFSList(JCas aJCas, Collection<? extends TOP> aCollection)
+ {
+ if (aCollection.size() == 0) {
+ return new EmptyFSList(aJCas);
+ }
+
+ NonEmptyFSList head = new NonEmptyFSList(aJCas);
+ NonEmptyFSList list = head;
+ Iterator<? extends TOP> i = aCollection.iterator();
+ while (i.hasNext()) {
+ head.setHead(i.next());
+ if (i.hasNext()) {
+ head.setTail(new NonEmptyFSList(aJCas));
+ head = (NonEmptyFSList) head.getTail();
+ }
+ else {
+ head.setTail(new EmptyFSList(aJCas));
+ }
+ }
+
+ return list;
+ }
+
+ public static FloatList createFloatList(JCas aJCas, Collection<Float> aCollection)
+ {
+ if (aCollection.size() == 0) {
+ return new EmptyFloatList(aJCas);
+ }
+
+ NonEmptyFloatList head = new NonEmptyFloatList(aJCas);
+ NonEmptyFloatList list = head;
+ Iterator<Float> i = aCollection.iterator();
+ while (i.hasNext()) {
+ head.setHead(i.next());
+ if (i.hasNext()) {
+ head.setTail(new NonEmptyFloatList(aJCas));
+ head = (NonEmptyFloatList) head.getTail();
+ }
+ else {
+ head.setTail(new EmptyFloatList(aJCas));
+ }
+ }
+
+ return list;
+ }
+
+ public static IntegerList createIntegerList(JCas aJCas, Collection<Integer> aCollection)
+ {
+ if (aCollection.size() == 0) {
+ return new EmptyIntegerList(aJCas);
+ }
+
+ NonEmptyIntegerList head = new NonEmptyIntegerList(aJCas);
+ NonEmptyIntegerList list = head;
+ Iterator<Integer> i = aCollection.iterator();
+ while (i.hasNext()) {
+ head.setHead(i.next());
+ if (i.hasNext()) {
+ head.setTail(new NonEmptyIntegerList(aJCas));
+ head = (NonEmptyIntegerList) head.getTail();
+ }
+ else {
+ head.setTail(new EmptyIntegerList(aJCas));
+ }
+ }
+
+ return list;
+ }
+
+ public static StringList createStringList(JCas aJCas, Collection<String> aCollection)
+ {
+ if (aCollection.size() == 0) {
+ return new EmptyStringList(aJCas);
+ }
+
+ NonEmptyStringList head = new NonEmptyStringList(aJCas);
+ NonEmptyStringList list = head;
+ Iterator<String> i = aCollection.iterator();
+ while (i.hasNext()) {
+ head.setHead(i.next());
+ if (i.hasNext()) {
+ head.setTail(new NonEmptyStringList(aJCas));
+ head = (NonEmptyStringList) head.getTail();
+ }
+ else {
+ head.setTail(new EmptyStringList(aJCas));
+ }
+ }
+
+ return list;
+ }
+
+ private static class FSIteratorAdapter<T extends FeatureStructure> extends FSCollectionFactory<T>
+ {
+ private int sizeCache = -1;
+ private final FSIterator<T> index;
+
+ public FSIteratorAdapter(final FSIterator<T> aIterator)
+ {
+ index = aIterator.copy();
+ index.moveToFirst();
+ }
+
+ @Override
+ public Iterator<T> iterator() {
+ return index.copy();
+ }
+
+ @Override
+ public int size() {
+ // Unfortunately FSIterator does not expose the sizes of its internal collection,
+ // neither the current position although FSIteratorAggregate has a private field
+ // with that information.
+ if (sizeCache == -1) {
+ synchronized (this) {
+ if (sizeCache == -1) {
+ FSIterator<T> clone = index.copy();
+ clone.moveToFirst();
+ sizeCache = 0;
+ while (clone.isValid()) {
+ sizeCache++;
+ clone.moveToNext();
+ }
+ }
+ }
+ }
+
+ return sizeCache;
+ }
+ }
+
+ private static class AnnotationIndexAdapter<T extends AnnotationFS> extends FSCollectionFactory<T>
+ {
+ private final AnnotationIndex<T> index;
+
+ public AnnotationIndexAdapter(AnnotationIndex<T> aIndex)
+ {
+ index = aIndex;
+ }
+
+ @Override
+ public Iterator<T> iterator() {
+ return index.iterator();
+ }
+
+ @Override
+ public int size() {
+ return index.size();
+ }
+ }
+}
Propchange: uima/sandbox/trunk/uimaFIT/uimaFIT/src/main/java/org/apache/uima/fit/util/FSCollectionFactory.java
------------------------------------------------------------------------------
svn:eol-style = native
Added: uima/sandbox/trunk/uimaFIT/uimaFIT/src/main/java/org/apache/uima/fit/util/JCasGenPomFriendly.java
URL: http://svn.apache.org/viewvc/uima/sandbox/trunk/uimaFIT/uimaFIT/src/main/java/org/apache/uima/fit/util/JCasGenPomFriendly.java?rev=1421324&view=auto
==============================================================================
--- uima/sandbox/trunk/uimaFIT/uimaFIT/src/main/java/org/apache/uima/fit/util/JCasGenPomFriendly.java (added)
+++ uima/sandbox/trunk/uimaFIT/uimaFIT/src/main/java/org/apache/uima/fit/util/JCasGenPomFriendly.java Thu Dec 13 14:53:52 2012
@@ -0,0 +1,92 @@
+/*
+ Copyright 2010 Regents of the University of Colorado.
+ All rights reserved.
+
+ Licensed under the Apache License, Version 2.0 (the "License");
+ you may not use this file except in compliance with the License.
+ You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
+ */
+
+package org.apache.uima.fit.util;
+
+import static org.apache.uima.UIMAFramework.getXMLParser;
+
+import java.io.IOException;
+
+import org.apache.uima.cas.CAS;
+import org.apache.uima.cas.impl.CASImpl;
+import org.apache.uima.fit.factory.TypeSystemDescriptionFactory;
+import org.apache.uima.resource.ResourceInitializationException;
+import org.apache.uima.resource.metadata.TypeSystemDescription;
+import org.apache.uima.tools.jcasgen.Jg;
+import org.apache.uima.tools.jcasgen.LogThrowErrorImpl;
+import org.apache.uima.tools.jcasgen.UimaLoggerProgressMonitor;
+import org.apache.uima.util.CasCreationUtils;
+import org.apache.uima.util.InvalidXMLException;
+import org.apache.uima.util.XMLInputSource;
+
+/**
+ * This class provides an advanced version of the UIMA JCas wrapper generator. It's main method
+ * takes two arguments. The first is a list of ANT-like URL patterns (';'-separated )which indicate
+ * where to look for type descriptors. The second is the output directory. Being able to process
+ * multiple type system descriptors at the same time removes the need of having a single master type
+ * system file importing all others. Example section for a pom.xml:
+ *
+ * <pre>
+ * <plugin>
+ * <groupId>org.codehaus.mojo</groupId>
+ * <artifactId>exec-maven-plugin</artifactId>
+ * <executions>
+ * <execution>
+ * <phase>process-test-resources</phase>
+ * <goals>
+ * <goal>java</goal>
+ * </goals>
+ * </execution>
+ * </executions>
+ * <configuration>
+ * <classpathScope>test</classpathScope>
+ * <mainClass>org.uimafit.util.JCasGenPomFriendly</mainClass>
+ * <arguments>
+ * <argument>file:src/test/resources/META-INF/org.uimafit/type/**/*.xml</argument>
+ * <argument>${basedir}/src/test/java</argument>
+ * </arguments>
+ * </configuration>
+ * </plugin>
+ * </pre>
+ *
+ * @author Philip Ogren
+ * @author Richard Eckart de Castilho
+ */
+public class JCasGenPomFriendly {
+ /**
+ * See class-level javadoc for instructions on running this program.
+ */
+ public static void main(String[] args) throws Exception {
+ Jg jg = new Jg();
+ for (String file : TypeSystemDescriptionFactory.resolve(args[0].split(";"))) {
+ generate(jg, file, args[1], load(file));
+ }
+ }
+
+ private static TypeSystemDescription load(String location) throws IOException,
+ InvalidXMLException {
+ XMLInputSource xmlInputType1 = new XMLInputSource(location);
+ return getXMLParser().parseTypeSystemDescription(xmlInputType1);
+ }
+
+ private static void generate(Jg jg, String inputFile, String outputDirectory,
+ TypeSystemDescription tsd) throws IOException, ResourceInitializationException {
+ CAS cas = CasCreationUtils.createCas(tsd, null, null);
+ jg.mainForCde(null, new UimaLoggerProgressMonitor(), new LogThrowErrorImpl(), inputFile,
+ outputDirectory, tsd.getTypes(), (CASImpl) cas);
+ }
+}
Propchange: uima/sandbox/trunk/uimaFIT/uimaFIT/src/main/java/org/apache/uima/fit/util/JCasGenPomFriendly.java
------------------------------------------------------------------------------
svn:eol-style = native