Java Code Examples for org.apache.uima.cas.Type#getName()

The following examples show how to use org.apache.uima.cas.Type#getName() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: TsvDocument.java    From webanno with Apache License 2.0 6 votes vote down vote up
public AnnotationFS resolveReference(Type aType, String aId,
        int aDisambiguationId)
{
    AnnotationFS annotation;
    // If there is a disambiguation ID then we can easily look up the annotation via the ID.
    // A disambiguation ID of 0 used when a relation refers to a non-ambiguous target and
    // it is handled in the second case.
    if (aDisambiguationId > 0) {
        annotation = getDisambiguatedAnnotation(aDisambiguationId);
        if (annotation == null) {
            throw new IllegalStateException("Unable to resolve reference to disambiguation ID ["
                    + aDisambiguationId + "]");
        }
    }
    // Otherwise, we'll have to go through the source unit.
    else {
        annotation = getUnit(aId).getUimaAnnotation(aType, 0);
        if (annotation == null) {
            throw new IllegalStateException(
                    "Unable to resolve reference to unambiguous annotation of type ["
                            + aType.getName() + "] in unit [" + aId + "]");
        }
    }
    
    return annotation;
}
 
Example 2
Source File: CasUtil.java    From uima-uimafit with Apache License 2.0 6 votes vote down vote up
/**
 * Get the single instance of the specified type from the CAS at the given offsets.
 * 
 * @param aCas
 *          the CAS containing the annotations.
 * @param aType
 *          the type of annotations to fetch.
 * @param aBegin
 *          the begin offset.
 * @param aEnd
 *          the end offset.
 * @return the single annotation at the specified offsets.
 */
public static AnnotationFS selectSingleAt(final CAS aCas, final Type aType, int aBegin, int aEnd) {
  List<AnnotationFS> list = selectAt(aCas, aType, aBegin, aEnd);

  if (list.isEmpty()) {
    throw new IllegalArgumentException("CAS does not contain any [" + aType.getName() + "] at ["
            + aBegin + "," + aEnd + "]");
  }
  
  if (list.size() > 1) {
    throw new IllegalArgumentException("CAS contains more than one [" + aType.getName()
            + "] at [" + aBegin + "," + aEnd + "]");
  }

  return list.get(0);
}
 
Example 3
Source File: TypeImpl.java    From uima-uimaj with Apache License 2.0 6 votes vote down vote up
void checkExistingFeatureCompatible(FeatureImpl existingFi, Type range) {
  if (existingFi != null) {
    if (existingFi.getRange() != range) {
      /**
       * Trying to define feature "{0}" on type "{1}" with range "{2}", but feature has already been
       * defined on (super)type "{3}" with range "{4}".
       */
      throw new CASAdminException(CASAdminException.DUPLICATE_FEATURE, 
          existingFi            .getShortName(), 
          this                  .getName(), 
          range                 .getName(), 
          existingFi.getDomain().getName(), 
          existingFi.getRange() .getName());
    }
  }
}
 
Example 4
Source File: CasUtil.java    From uima-uimafit with Apache License 2.0 6 votes vote down vote up
/**
 * Get the single instance of the specified type from the CAS.
 * 
 * @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 AnnotationFS selectSingle(CAS cas, Type type) {
  FSIterator<AnnotationFS> iterator = cas.getAnnotationIndex(type).iterator();

  if (!iterator.hasNext()) {
    throw new IllegalArgumentException("CAS does not contain any [" + type.getName() + "]");
  }

  AnnotationFS result = iterator.next();

  if (iterator.hasNext()) {
    throw new IllegalArgumentException("CAS contains more than one [" + type.getName() + "]");
  }

  return result;
}
 
Example 5
Source File: CasUtil.java    From uima-uimafit with Apache License 2.0 6 votes vote down vote up
/**
 * Get the single instance of the specified type from the CAS.
 * 
 * @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 selectSingleFS(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;
}
 
Example 6
Source File: AllTypes.java    From uima-uimaj with Apache License 2.0 6 votes vote down vote up
/**
 * Update.
 */
// create a hash table of all types
private void update() {
  cachedResult.clear();

  CAS tcas = modelRoot.getCurrentView();
  if (null == tcas)
    return;
  TypeSystem typeSystem = tcas.getTypeSystem();

  if (typeSystem == null)
    return;

  Iterator typeIterator = typeSystem.getTypeIterator();

  while (typeIterator.hasNext()) {
    Type type = (Type) typeIterator.next();
    String typeName = type.getName();
    if (null != typeName && !typeName.endsWith("[]")) {
      cachedResult.put(type.getName(), type);
    }
  }
}
 
Example 7
Source File: NewFeatureUtils.java    From baleen with Apache License 2.0 5 votes vote down vote up
private static CommonArrayFS getCommonArrayFS(JCas jCas, Type componentType, Collection<?> list) {
  CommonArrayFS fs = null;

  switch (componentType.getName()) {
    case CAS.TYPE_NAME_STRING:
      fs = getStringArray(jCas, list);
      break;
    case CAS.TYPE_NAME_INTEGER:
      fs = getIntegerArray(jCas, list);
      break;
    case CAS.TYPE_NAME_FLOAT:
      fs = getFloatArray(jCas, list);
      break;
    case CAS.TYPE_NAME_BOOLEAN:
      fs = getBooleanArray(jCas, list);
      break;
    case CAS.TYPE_NAME_BYTE:
      fs = getByteArray(jCas, list);
      break;
    case CAS.TYPE_NAME_SHORT:
      fs = getShortArray(jCas, list);
      break;
    case CAS.TYPE_NAME_LONG:
      fs = getLongArray(jCas, list);
      break;
    case CAS.TYPE_NAME_DOUBLE:
      fs = getDoubleArray(jCas, list);
      break;
    default:
      break;
  }
  return fs;
}
 
Example 8
Source File: Primitives.java    From uima-uimaj with Apache License 2.0 5 votes vote down vote up
/**
 * Gets the restricted values.
 *
 * @param ts the ts
 * @param type the type
 * @return the restricted values
 */
public static String[] getRestrictedValues(TypeSystem ts, Type type) {
  if (isRestrictedByAllowedValues(ts, type)) {
    throw new IllegalArgumentException("Type " + type.getName() + " does not defines allowed values!");
  }
  
  LowLevelTypeSystem lts = ts.getLowLevelTypeSystem();
  final int typeCode = lts.ll_getCodeForType(type);
  
  return lts.ll_getStringSet(typeCode);
}
 
Example 9
Source File: CASImpl.java    From uima-uimaj with Apache License 2.0 5 votes vote down vote up
/**
 * Create the appropriate Feature Structure Java instance
 *   - from whatever the generator for this type specifies.
 *   
 * @param type the type to create
 * @return a Java object representing the FeatureStructure impl in Java.
 */
@Override
public <T extends FeatureStructure> T createFS(Type type) {
  final TypeImpl ti = (TypeImpl) type;
  if (!ti.isCreatableAndNotBuiltinArray()) {
    throw new CASRuntimeException(CASRuntimeException.NON_CREATABLE_TYPE, type.getName(), "CAS.createFS()");
  }
  return (T) createFSAnnotCheck(ti);
}
 
Example 10
Source File: WebAnnoCasUtil.java    From webanno with Apache License 2.0 5 votes vote down vote up
public static boolean isPrimitiveType(Type aType)
{
    switch (aType.getName()) {
    case CAS.TYPE_NAME_STRING: // fallthrough
    case CAS.TYPE_NAME_BOOLEAN: // fallthrough
    case CAS.TYPE_NAME_FLOAT: // fallthrough
    case CAS.TYPE_NAME_INTEGER:
        return true;
    default:
        return false;
    }
}
 
Example 11
Source File: CasMerge.java    From webanno with Apache License 2.0 5 votes vote down vote up
private void copyFeatures(SourceDocument aDocument, String aUsername, TypeAdapter aAdapter,
        FeatureStructure aTargetFS, FeatureStructure aSourceFs)
    throws AnnotationException
{
    // Cache the feature list instead of hammering the database
    List<AnnotationFeature> features = featureCache.computeIfAbsent(aAdapter.getLayer(),
        key -> schemaService.listSupportedFeatures(key));
    for (AnnotationFeature feature : features) {
        Type sourceFsType = aAdapter.getAnnotationType(aSourceFs.getCAS());
        Feature sourceFeature = sourceFsType.getFeatureByBaseName(feature.getName());

        if (sourceFeature == null) {
            throw new IllegalStateException("Target CAS type [" + sourceFsType.getName()
                    + "] does not define a feature named [" + feature.getName() + "]");
        }

        if (shouldIgnoreFeatureOnMerge(aSourceFs, sourceFeature)) {
            continue;
        }

        Object value = aAdapter.getFeatureValue(feature, aSourceFs);
        
        try {
            aAdapter.setFeatureValue(aDocument, aUsername, aTargetFS.getCAS(),
                    getAddr(aTargetFS), feature, value);
        }
        catch (IllegalArgumentException e) {
            // This happens e.g. if the value we try to set is not in the tagset and the tagset
            // cannot be extended.
            throw new IllegalFeatureValueException("Cannot set value of feature ["
                    + feature.getUiName() + "] to [" + value + "]: " + e.getMessage(), e);
        }
    }
}
 
Example 12
Source File: Primitives.java    From uima-uimaj with Apache License 2.0 5 votes vote down vote up
/**
 * Retrieve the primitive java class for a primitive type.
 *
 * @param ts the ts
 * @param type the type
 * @return the primitive java class
 */
public static Class<?> getPrimitiveClass(TypeSystem ts, Type type) {
  if (!type.isPrimitive())
    throw new IllegalArgumentException("Type " + type.getName() + " is not primitive!");
  
  // Note:
  // In a UIMA type system *only* the primitive string type can be 
  // sub-typed.
  
  if (ts.getType(CAS.TYPE_NAME_BOOLEAN).equals(type)) {
    return Boolean.class;
  }
  else if (ts.getType(CAS.TYPE_NAME_BYTE).equals(type)) {
    return Byte.class;
  }
  else if (ts.getType(CAS.TYPE_NAME_SHORT).equals(type)) {
    return Short.class;
  }
  else if (ts.getType(CAS.TYPE_NAME_INTEGER).equals(type)) {
    return Integer.class;
  }
  else if (ts.getType(CAS.TYPE_NAME_LONG).equals(type)) {
    return Long.class;
  }
  else if (ts.getType(CAS.TYPE_NAME_FLOAT).equals(type)) {
    return Float.class;
  }
  else if (ts.getType(CAS.TYPE_NAME_DOUBLE).equals(type)) {
    return Double.class;
  }
  else if (ts.getType(CAS.TYPE_NAME_STRING).equals(type) || 
          ts.subsumes(ts.getType(CAS.TYPE_NAME_STRING), type)) {
    return String.class;
  }
  else {
    throw new IllegalStateException("Unexpected primitive type: " + type.getName());
  }
}
 
Example 13
Source File: AnnotationPropertyPage.java    From uima-uimaj with Apache License 2.0 5 votes vote down vote up
/**
 * Item selected.
 */
private void itemSelected() {
  IStructuredSelection selection = (IStructuredSelection) mTypeList.getSelection();

  Type selectedType = (Type) selection.getFirstElement();

  if( selectedType != null) {
    
    AnnotationStyle style = getWorkingCopyAnnotationStyle(selectedType);

    if (style == null) {
      style = new AnnotationStyle(selectedType.getName(), AnnotationStyle.DEFAULT_STYLE,
              AnnotationStyle.DEFAULT_COLOR, 0);
    }

    mStyleCombo.setText(style.getStyle().name());
    mStyleCombo.setEnabled(true);

    Color color = style.getColor();
    mColorSelector.setColorValue(new RGB(color.getRed(), color.getGreen(), color.getBlue()));
    mColorSelector.setEnabled(true);

    moveLayerUpButton.setEnabled(true);
    moveLayerDownButton.setEnabled(true);
    
    updateCustomStyleControl(style, selectedType);
  }
  else {
    // no type selected
    mStyleCombo.setEnabled(false);
    mColorSelector.setEnabled(false);
    
    moveLayerUpButton.setEnabled(false);
    moveLayerDownButton.setEnabled(false);
    styleConfigurationWidget.setVisible(false);
  }
}
 
Example 14
Source File: JCasImpl.java    From uima-uimaj with Apache License 2.0 5 votes vote down vote up
public Feature getRequiredFeature(Type t, String s) throws CASException {
  Feature f = t.getFeatureByBaseName(s);
  if (null == f) {
    throw new CASException(CASException.JCAS_FEATURENOTFOUND_ERROR, t.getName(), s);
  }
  return f;
}
 
Example 15
Source File: EditViewPage.java    From uima-uimaj with Apache License 2.0 4 votes vote down vote up
/**
 * Creates the FS.
 *
 * @param type the type
 * @param arraySize the array size
 * @return the feature structure
 */
FeatureStructure createFS(Type type, int arraySize) {

  if (type.isPrimitive()) {
    throw new IllegalArgumentException("Cannot create FS for primitive type!");
  }

  FeatureStructure fs;

  TypeSystem ts = document.getCAS().getTypeSystem();

  if (type.isArray()) {
    switch (type.getName()) {
      case CAS.TYPE_NAME_BOOLEAN_ARRAY:
        fs = document.getCAS().createBooleanArrayFS(arraySize);
        break;
      case CAS.TYPE_NAME_BYTE_ARRAY:
        fs = document.getCAS().createByteArrayFS(arraySize);
        break;
      case CAS.TYPE_NAME_SHORT_ARRAY:
        fs = document.getCAS().createShortArrayFS(arraySize);
        break;
      case CAS.TYPE_NAME_INTEGER_ARRAY:
        fs = document.getCAS().createIntArrayFS(arraySize);
        break;
      case CAS.TYPE_NAME_LONG_ARRAY:
        fs = document.getCAS().createLongArrayFS(arraySize);
        break;
      case CAS.TYPE_NAME_FLOAT_ARRAY:
        fs = document.getCAS().createFloatArrayFS(arraySize);
        break;
      case CAS.TYPE_NAME_DOUBLE_ARRAY:
        fs = document.getCAS().createDoubleArrayFS(arraySize);
        break;
      case CAS.TYPE_NAME_STRING_ARRAY:
        fs = document.getCAS().createStringArrayFS(arraySize);
        break;
      case CAS.TYPE_NAME_FS_ARRAY:
        fs = document.getCAS().createArrayFS(arraySize);
        break;
      default:
        throw new CasEditorError("Unkown array type: " + type.getName() + "!");
    }
  }
  else if (ts.subsumes(ts.getType(CAS.TYPE_NAME_ANNOTATION), type)) {

	// get begin of selection from editor, if any
	// TODO: Add an interface to retrieve the span from the editor

	int begin = 0;
	int end = 0;

	if (editor instanceof AnnotationEditor) {
	  Point selection = ((AnnotationEditor) editor).getSelection();

	  begin = selection.x;
	  end = selection.y;
	}

	fs = document.getCAS().createAnnotation(type, begin, end);
  }
  else if (!type.isArray()) {
    fs = document.getCAS().createFS(type);
  }
  else {
    throw new TaeError("Unexpected error!");
  }

  return fs;
}
 
Example 16
Source File: CasUtil.java    From uima-uimafit with Apache License 2.0 4 votes vote down vote up
/**
 * 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
 * @see <a href="package-summary.html#SortOrder">Order of selected feature structures</a>
 */
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");
  }

  List<AnnotationFS> precedingAnnotations = new ArrayList<AnnotationFS>();

  // Seek annotation in index
  // withSnapshotIterators() not needed here since we copy the FSes to a list anyway    
  FSIterator<AnnotationFS> itr = cas.getAnnotationIndex(type).iterator();
  itr.moveTo(annotation);
  
  // If the insertion point is beyond the index, move back to the last.
  if (!itr.isValid()) {
    itr.moveToLast();
    if (!itr.isValid()) {
      return precedingAnnotations;
    }
  }

  // No need to do additional seeks here (as done in selectCovered) because the current method
  // does not have to worry about type priorities - it never returns annotations that have
  // the same offset as the reference 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
  for (int i = 0; i < count && itr.isValid(); itr.moveToPrevious()) {
    AnnotationFS cur = itr.get();
    if (cur.getEnd() <= annotation.getBegin()) {
      precedingAnnotations.add(itr.get());
      i++;
    }
  }

  // return in correct order
  Collections.reverse(precedingAnnotations);
  return precedingAnnotations;
}
 
Example 17
Source File: WebannoTsv2Writer.java    From webanno with Apache License 2.0 4 votes vote down vote up
private void setTokenAnnos(CAS aCas, Map<Integer, String> aTokenAnnoMap, Type aType,
        Feature aFeature)
{
    LowLevelCAS llCas = aCas.getLowLevelCAS();
    for (AnnotationFS annoFs : CasUtil.select(aCas, aType)) {
        boolean first = true;
        boolean previous = false; // exists previous annotation, place-holed O-_ should be kept
        for (Token token : selectCovered(Token.class, annoFs)) {
            if (annoFs.getBegin() <= token.getBegin() && annoFs.getEnd() >= token.getEnd()) {
                String annotation = annoFs.getFeatureValueAsString(aFeature);
                if (annotation == null) {
                    annotation = aType.getName() + "_";
                }
                if (aTokenAnnoMap.get(llCas.ll_getFSRef(token)) == null) {
                    if (previous) {
                        if (!multipleSpans.contains(aType.getName())) {
                            aTokenAnnoMap.put(llCas.ll_getFSRef(token), annotation);
                        }
                        else {
                            aTokenAnnoMap.put(llCas.ll_getFSRef(token), "O-_|"
                                    + (first ? "B-" : "I-") + annotation);
                            first = false;
                        }
                    }
                    else {
                        if (!multipleSpans.contains(aType.getName())) {
                            aTokenAnnoMap.put(llCas.ll_getFSRef(token), annotation);
                        }
                        else {
                            aTokenAnnoMap.put(llCas.ll_getFSRef(token), (first ? "B-" : "I-")
                                    + annotation);
                            first = false;
                        }
                    }
                }
                else {
                    if (!multipleSpans.contains(aType.getName())) {
                        aTokenAnnoMap.put(llCas.ll_getFSRef(token),
                                aTokenAnnoMap.get(llCas.ll_getFSRef(token)) + "|"
                                        + annotation);
                        previous = true;
                    }
                    else {
                        aTokenAnnoMap.put(llCas.ll_getFSRef(token),
                                aTokenAnnoMap.get(llCas.ll_getFSRef(token)) + "|"
                                        + (first ? "B-" : "I-") + annotation);
                        first = false;
                        previous = true;
                    }
                }

            }
        }
    }
}
 
Example 18
Source File: TypeUtils.java    From baleen with Apache License 2.0 4 votes vote down vote up
/**
 * For a given type name, look through the type system and return the matching class. If two types
 * of the same name (but different packages) exist, then null will be returned and the package
 * will need to be included in the typeName.
 *
 * @param typeName The name of the type, optionally including the package
 * @param typeSystem The type system to search
 * @return The class associated with that type
 */
@SuppressWarnings("unchecked")
public static Class<AnnotationBase> getType(String typeName, TypeSystem typeSystem) {
  SuffixTree<Class<AnnotationBase>> types =
      new ConcurrentSuffixTree<>(new DefaultByteArrayNodeFactory());

  Iterator<Type> itTypes = typeSystem.getTypeIterator();
  while (itTypes.hasNext()) {
    Type t = itTypes.next();

    Class<AnnotationBase> c;
    try {
      String clazz = t.getName();
      if (clazz.startsWith("uima.")) {
        continue;
      } else if (clazz.endsWith("[]")) {
        clazz = clazz.substring(0, clazz.length() - 2);
      }

      Class<?> unchecked = Class.forName(clazz);

      if (AnnotationBase.class.isAssignableFrom(unchecked)) {
        c = (Class<AnnotationBase>) unchecked;
        types.put(t.getName(), c);
      } else {
        LOGGER.debug("Skipping class {} that doesn't inherit from AnnotationBase", clazz);
      }
    } catch (ClassNotFoundException e) {
      LOGGER.warn("Unable to load class {} from type system", t.getName(), e);
    }
  }

  Class<AnnotationBase> ret = getClassFromType("." + typeName, types);
  if (ret == null) {
    ret = getClassFromType(typeName, types);
  }

  if (ret == null) {
    LOGGER.warn("No uniquely matching class found for type {}", typeName);
  }

  return ret;
}
 
Example 19
Source File: CasUtil.java    From uima-uimafit with Apache License 2.0 3 votes vote down vote up
/**
 * 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.
 * @see <a href="package-summary.html#SortOrder">Order of selected feature structures</a>
 */
@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.getAnnotationIndex(type));
}
 
Example 20
Source File: CasUtil.java    From uima-uimafit with Apache License 2.0 3 votes vote down vote up
/**
 * 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.
 * @see <a href="package-summary.html#SortOrder">Order of selected feature structures</a>
 */
@SuppressWarnings({ "unchecked", "rawtypes" })
public static List<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 (List) FSCollectionFactory.create(array, type);
}