Java Code Examples for org.apache.uima.resource.metadata.TypeDescription#getFeatures()

The following examples show how to use org.apache.uima.resource.metadata.TypeDescription#getFeatures() . 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: TypeSystemAnalysis.java    From webanno with Apache License 2.0 6 votes vote down vote up
private void analyzeFeatures(AnnotationLayer aLayer, TypeSystem aTS, TypeDescription aTD,
        Optional<? extends LayerDetails> aDetails)
{
    Type type = aTS.getType(aTD.getName());
    for (FeatureDescription fd : aTD.getFeatures()) {
        Feature feat = type.getFeatureByBaseName(fd.getName());
        // We do not need to set up built-in features
        if (isBuiltInFeature(feat)) {
            continue;
        }
        
        if (aDetails.isPresent() && aDetails.get().isHiddenFeature(feat)) {
            continue;
        }
        
        AnnotationFeature f = analyzeFeature(aTS, fd, feat);
        features.put(aLayer.getName(), f);
    }
}
 
Example 2
Source File: TypeSection.java    From uima-uimaj with Apache License 2.0 6 votes vote down vote up
/**
 * Type requires type.
 *
 * @param upstreamType the upstream type
 * @param typeName the type name
 * @return true, if successful
 */
private boolean typeRequiresType(TypeDescription upstreamType, String typeName) {
  if (null == typeName)
    return false;
  if (typeName.equals(upstreamType.getSupertypeName())) {
    return true;
  }

  FeatureDescription[] features = upstreamType.getFeatures();
  if (features == null) {
    return false;
  }

  for (int i = 0; i < features.length; i++) {
    if (typeName.equals(features[i].getRangeTypeName())) {
      return true;
    }
  }
  return false;
}
 
Example 3
Source File: RecommendationServiceImpl.java    From inception with Apache License 2.0 5 votes vote down vote up
public CAS cloneAndMonkeyPatchCAS(Project aProject, CAS aSourceCas, CAS aTargetCas)
    throws UIMAException, IOException
{
    try (StopWatch watch = new StopWatch(log, "adding score features")) {
        TypeSystemDescription tsd = annoService.getFullProjectTypeSystem(aProject);

        for (AnnotationLayer layer : annoService.listAnnotationLayer(aProject)) {
            TypeDescription td = tsd.getType(layer.getName());

            if (td == null) {
                log.trace("Could not monkey patch type [{}]", layer.getName());
                continue;
            }

            for (FeatureDescription feature : td.getFeatures()) {
                String scoreFeatureName = feature.getName() + FEATURE_NAME_SCORE_SUFFIX;
                td.addFeature(scoreFeatureName, "Score feature", CAS.TYPE_NAME_DOUBLE);
                
                String scoreExplanationFeatureName = feature.getName() + 
                        FEATURE_NAME_SCORE_EXPLANATION_SUFFIX;
                td.addFeature(scoreExplanationFeatureName, "Score explanation feature", 
                        CAS.TYPE_NAME_STRING);
            }

            td.addFeature(FEATURE_NAME_IS_PREDICTION, "Is Prediction", CAS.TYPE_NAME_BOOLEAN);
        }

        annoService.upgradeCas(aSourceCas, aTargetCas, tsd);
    }

    return aTargetCas;
}
 
Example 4
Source File: AnnotationSchemaServiceImpl.java    From webanno with Apache License 2.0 5 votes vote down vote up
private void exportBuiltInTypeDescription(TypeSystemDescription aSource,
        TypeSystemDescription aTarget, String aType)
{
    TypeDescription builtInType = aSource.getType(aType);
    
    if (builtInType == null) {
        throw new IllegalArgumentException(
                "No type description found for type [" + aType + "]");
    }
    
    TypeDescription clonedType = aTarget.addType(builtInType.getName(),
            builtInType.getDescription(), builtInType.getSupertypeName());
    
    if (builtInType.getFeatures() != null) {
        for (FeatureDescription feature : builtInType.getFeatures()) {
            clonedType.addFeature(feature.getName(), feature.getDescription(),
                    feature.getRangeTypeName(), feature.getElementType(),
                    feature.getMultipleReferencesAllowed());
            
            // Export types referenced by built-in types also as built-in types. Note that
            // it is conceptually impossible for built-in types to refer to custom types, so
            // this is cannot lead to a custom type being exported as a built-in type.
            if (
                    feature.getElementType() != null && 
                    !isNativeUimaType(feature.getElementType()) &&
                    aTarget.getType(feature.getElementType()) == null
            ) {
                exportBuiltInTypeDescription(aSource, aTarget, feature.getElementType());
            }
            else if (
                    feature.getRangeTypeName() != null && 
                    !isNativeUimaType(feature.getRangeTypeName()) &&
                    aTarget.getType(feature.getRangeTypeName()) == null
            ) {
                exportBuiltInTypeDescription(aSource, aTarget, feature.getRangeTypeName());
            }
        }
    }
}
 
Example 5
Source File: AbstractImportablePartSection.java    From uima-uimaj with Apache License 2.0 5 votes vote down vote up
/**
 * returns null if no feature by this name.
 *
 * @param name the name
 * @param td the td
 * @return the feature from type description
 */
public FeatureDescription getFeatureFromTypeDescription(String name, TypeDescription td) {
  FeatureDescription[] fds = td.getFeatures();
  if (fds == null)
    return null;
  for (int i = 0; i < fds.length; i++) {
    if (name.equals(fds[i].getName()))
      return fds[i];
  }
  return null;
}
 
Example 6
Source File: TypeSection.java    From uima-uimaj with Apache License 2.0 5 votes vote down vote up
/**
 * Adds the type to GUI.
 *
 * @param td the td
 */
private void addTypeToGUI(TypeDescription td) {
  TreeItem item = new TreeItem(tt, SWT.NONE);
  item.setText(NAME_COL, formatName(td.getName()));
  item.setText(SUPER_COL, formatName(td.getSupertypeName()));
  item.setData(td);
  setItemColor(item, isLocalType(td));

  FeatureDescription[] features = td.getFeatures();
  addFeaturesToGui(td, item, features);

  TypeDescription builtInTd = getBuiltInTypeDescription(td);
  if (null != builtInTd) {
    FeatureDescription[] additionalBuiltInFeatures = setDifference(builtInTd.getFeatures(), td
            .getFeatures());
    addFeaturesToGui(td, item, additionalBuiltInFeatures);
  }

  AllowedValue[] avs = td.getAllowedValues();
  if (null != avs) {
    for (int i = 0; i < avs.length; i++) {
      TreeItem avItem = new TreeItem(item, SWT.NONE);
      avItem.setText(NAME_COL, HEADER_ALLOWED_VALUE);
      avItem.setText(AV_COL, convertNull(avs[i].getString()));
      avItem.setData(avs[i]);
      setItemColor(avItem, null != getLocalAllowedValue(td, avs[i]));
    }
  }
  // No built-ins have "allowed values" so we don't have to add any
  item.setExpanded(true);
}
 
Example 7
Source File: Jg.java    From uima-uimaj with Apache License 2.0 5 votes vote down vote up
/**
 * Collect imports.
 *
 * @param td the td
 * @param _Type the type
 * @return the collection
 */
Collection<String> collectImports(TypeDescription td, boolean _Type) {
  if (_Type)
    _imports.clear();
  else
    imports.clear();
  collectImport(td.getName(), _Type);
  collectImport(td.getSupertypeName(), _Type);

  if (!_Type) {

    FeatureDescription[] fds = td.getFeatures();
    for (int i = 0; i < fds.length; i++) {
      FeatureDescription fd = fds[i];
      if (null != typeSystem) {
        String rangeTypeNameCAS = fd.getRangeTypeName();
        Type rangeCasType = typeSystem.getType(rangeTypeNameCAS);
        if (typeSystem.subsumes(casStringType, rangeCasType))
          continue;
      }
      collectImport(fd.getRangeTypeName(), false);
      if (isRangeTypeGeneric(fd)) {
        collectImport(getJavaRangeArrayElementType(fd), false);
      }
    }
  }
  return (_Type) ? _imports.values() : imports.values();
}
 
Example 8
Source File: TypeSystemDescription_implTest.java    From uima-uimaj with Apache License 2.0 5 votes vote down vote up
public void testBuildFromXmlElement() throws Exception {
  try {
    File descriptor = JUnitExtension.getFile("TypeSystemDescriptionImplTest/TestTypeSystem.xml");
    TypeSystemDescription ts = UIMAFramework.getXMLParser().parseTypeSystemDescription(
            new XMLInputSource(descriptor));

    assertEquals("TestTypeSystem", ts.getName());
    assertEquals("This is a test.", ts.getDescription());
    assertEquals("The Apache Software Foundation", ts.getVendor());
    assertEquals("0.1", ts.getVersion());
    Import[] imports = ts.getImports();
    assertEquals(3, imports.length);
    assertEquals("org.apache.uima.resource.metadata.impl.TypeSystemImportedByName", imports[0]
            .getName());
    assertNull(imports[0].getLocation());
    assertNull(imports[1].getName());
    assertEquals("TypeSystemImportedByLocation.xml", imports[1].getLocation());

    TypeDescription[] types = ts.getTypes();
    assertEquals(6, types.length);
    TypeDescription paragraphType = types[4];
    assertEquals("Paragraph", paragraphType.getName());
    assertEquals("A paragraph.", paragraphType.getDescription());
    assertEquals("DocumentStructure", paragraphType.getSupertypeName());
    FeatureDescription[] features = paragraphType.getFeatures();
    assertEquals(2, features.length);
    assertEquals("sentences", features[0].getName());
    assertEquals("Direct references to sentences in this paragraph", features[0].getDescription());
    assertEquals("uima.cas.FSArray", features[0].getRangeTypeName());
    assertEquals("Sentence", features[0].getElementType());
    assertFalse(features[0].getMultipleReferencesAllowed());

    // ts.toXML(System.out);
  } catch (Exception e) {
    JUnitExtension.handleException(e);
  }
}
 
Example 9
Source File: AnnotationSchemaServiceImpl.java    From webanno with Apache License 2.0 4 votes vote down vote up
/**
 * Check if the current CAS already contains the required type system.
 */
private boolean isUpgradeRequired(CAS aCas, TypeSystemDescription aTargetTypeSystem)
{
    TypeSystem ts = aCas.getTypeSystem();
    boolean upgradeRequired = false;
    nextType: for (TypeDescription tdesc : aTargetTypeSystem.getTypes()) {
        Type t = ts.getType(tdesc.getName());
        
        // Type does not exist
        if (t == null) {
            log.debug("CAS update required: type {} does not exist", tdesc.getName());
            upgradeRequired = true;
            break nextType;
        }
        
        // Super-type does not match
        if (!Objects.equals(tdesc.getSupertypeName(), ts.getParent(t).getName())) {
            log.debug("CAS update required: supertypes of {} do not match: {} <-> {}",
                    tdesc.getName(), tdesc.getSupertypeName(), ts.getParent(t).getName());
            upgradeRequired = true;
            break nextType;
        }
        
        // Check features
        for (FeatureDescription fdesc : tdesc.getFeatures()) {
            Feature f = t.getFeatureByBaseName(fdesc.getName());
            
            // Feature does not exist
            if (f == null) {
                log.debug("CAS update required: feature {} on type {} does not exist",
                        fdesc.getName(), tdesc.getName());
                upgradeRequired = true;
                break nextType;
            }
            
            // Range does not match
            if (CAS.TYPE_NAME_FS_ARRAY.equals(fdesc.getRangeTypeName())) {
                if (!Objects.equals(fdesc.getElementType(),
                        f.getRange().getComponentType().getName())) {
                    log.debug(
                            "CAS update required: ranges of feature {} on type {} do not match: {} <-> {}",
                            fdesc.getName(), tdesc.getName(), fdesc.getRangeTypeName(),
                            f.getRange().getName());
                    upgradeRequired = true;
                    break nextType;
                }
            }
            else {
                if (!Objects.equals(fdesc.getRangeTypeName(), f.getRange().getName())) {
                    log.debug(
                            "CAS update required: ranges of feature {} on type {} do not match: {} <-> {}",
                            fdesc.getName(), tdesc.getName(), fdesc.getRangeTypeName(),
                            f.getRange().getName());
                    upgradeRequired = true;
                    break nextType;
                }
            }
        }
    }
    
    return upgradeRequired;
}
 
Example 10
Source File: TypeSection.java    From uima-uimaj with Apache License 2.0 4 votes vote down vote up
/**
 * CALL THIS FN after removing and remerging. Assuming the localTd is removed, it may result in
 * the mergedTd having fewer features. Compute the features that would be removed. Do it not just
 * for this type, but for all subtypes of this type. NOTE: if mergeTd is null, it means the type
 * is removed completely (no shadowing of built-in or imported types), so no special feature
 * removal is needed.
 *
 * @param localTd the local td
 * @param mergedTd          The "remerged" value of the type.
 * @return array of string names of features to be removed
 */

private TypeFeature[] computeFeaturesToRemove(TypeDescription localTd, TypeDescription mergedTd) {
  if (null == mergedTd)
    return typeFeature0;
  FeatureDescription[] locallyDefinedFeatures = localTd.getFeatures();
  if (null == locallyDefinedFeatures || locallyDefinedFeatures.length == 0)
    return typeFeature0;

  FeatureDescription[] remainingFeatures = mergedTd.getFeatures();
  ArrayList deletedFeatures = new ArrayList();

  outer: for (int i = 0; i < locallyDefinedFeatures.length; i++) {
    String fname = locallyDefinedFeatures[i].getName();
    if (null != remainingFeatures)
      for (int j = 0; j < remainingFeatures.length; j++) {
        if (fname.equals(remainingFeatures[j].getName()))
          continue outer;
      }
    deletedFeatures.add(fname);
  }

  // have list of features really disappearing (not kept present by imports or built-ins)
  // return all types/features of these for types which are subtypes of the passed-in type

  CAS tcas = editor.getCurrentView();
  TypeSystem typeSystem = tcas.getTypeSystem();
  Type thisType = typeSystem.getType(localTd.getName());
  List subsumedTypesList = typeSystem.getProperlySubsumedTypes(thisType);
  subsumedTypesList.add(thisType);
  Type[] subsumedTypes = (Type[]) subsumedTypesList.toArray(new Type[0]);

  String[] featNameArray = (String[]) deletedFeatures.toArray(new String[deletedFeatures.size()]);
  ArrayList result = new ArrayList();
  for (int i = 0; i < subsumedTypes.length; i++) {
    Type t = subsumedTypes[i];
    for (int j = 0; j < featNameArray.length; j++) {
      if (null != t.getFeatureByBaseName(featNameArray[j]))
        result.add(new TypeFeature(t.getName(), featNameArray[j]));
    }
  }
  return (TypeFeature[]) result.toArray(typeFeature0);
}
 
Example 11
Source File: TypeSection.java    From uima-uimaj with Apache License 2.0 4 votes vote down vote up
/**
 * return true if refresh is needed.
 *
 * @param oldTypeName the old type name
 * @param newTypeName the new type name
 * @return true if refresh is needed
 */
private boolean alterTypeMentionsInOtherTypes(String oldTypeName, String newTypeName) {
  // only modify locally modifiable types, but scan all types to give appropriate error msgs
  TypeSystemDescription typeSystem = getMergedTypeSystemDescription();
  boolean refreshNeeded = false;
  boolean remergeNeeded = false;
  TypeDescription[] types = typeSystem.getTypes();
  for (int i = 0; i < types.length; i++) {
    TypeDescription td = types[i];
    TypeDescription localTd = getLocalTypeDefinition(td);
    String typeName = td.getName();
    if (td.getSupertypeName().equals(oldTypeName)) {
      if (null != localTd) { // is a local type
        if (isImportedType(typeName)) {
          Utility
                  .popMessage(
                          "Imported type won't be changed",
                          "There is both a local and imported version of type, '"
                                  + typeName
                                  + "', which has a supertype which is the item being renamed.  Although the local version will be updated, but the imported one won't."
                                  + "This may cause an error when you save.",
                          MessageDialog.WARNING);
        }
        if (isBuiltInType(typeName)) {
          // invalid: changed some type name which was a supertype of a built in - but
          // all the supertypes of built-ins are unchangable.
          throw new InternalErrorCDE("invalid state");
        }
      } else { // is not a local type
        // can't be a built-in type because all the supertypes of built-ins are unchangeable
        Utility
                .popMessage(
                        "Imported type not changed",
                        "There is an imported type, '"
                                + typeName
                                + "', which has a supertype which is the item being renamed.  It won't be updated - this may cause an error when you save this descriptor."
                                + "  If it does, you will need to edit the imported type to change it.",
                        MessageDialog.WARNING);
        continue;
      }
      // guaranteed to have local type def here
      localTd.setSupertypeName(newTypeName);

      if (isImportedType(typeName)) {
        remergeNeeded = true;
        refreshNeeded = true;
      } else {
        td.setSupertypeName(newTypeName);
        updateGuiType(tt.getItems()[i], td);
      }
    }
    FeatureDescription fds[] = td.getFeatures();
    FeatureDescription localFds[] = (null == localTd) ? null : localTd.getFeatures();
    if (null != fds) {
      for (int j = 0; j < fds.length; j++) {
        FeatureDescription fd = fds[j];
        if (oldTypeName.equals(fd.getRangeTypeName())) {
          if (warnAndSkipIfImported(typeName))
            continue; // skipped if feature not present in local td, or no local td.

          setNamedFeatureDescriptionRange(localFds, fd.getName(), newTypeName);
          if (isImportedType(typeName)) {
            remergeNeeded = true;
            refreshNeeded = true;
          } else {
            fd.setRangeTypeName(newTypeName);
            updateGuiFeature(tt.getItems()[i].getItems()[j], fd, td);
          }
        }
      }
    }
  }
  if (remergeNeeded)
    rebuildMergedTypeSystem();
  return refreshNeeded;
}
 
Example 12
Source File: CasCreationUtils.java    From uima-uimaj with Apache License 2.0 4 votes vote down vote up
/**
 * Merges features into a TypeDescription.
 * 
 * @param aType
 *                TypeDescription into which to merge the features
 * @param aFeatures
 *                array of features to merge
 * 
 * @throws ResourceInitializationException
 *                 if an incompatibility exists
 */
protected static void mergeFeatures(TypeDescription aType, FeatureDescription[] aFeatures)
    throws ResourceInitializationException {
  FeatureDescription[] existingFeatures = aType.getFeatures();
  if (existingFeatures == null) {
    existingFeatures = EMPTY_FEAT_DESC_ARRAY;
  }

  for (int i = 0; i < aFeatures.length; i++) {
    String featName = aFeatures[i].getName();
    String rangeTypeName = aFeatures[i].getRangeTypeName();
    String elementTypeName = aFeatures[i].getElementType();
    Boolean multiRefsAllowed = aFeatures[i].getMultipleReferencesAllowed();

    // see if a feature already exists with this name
    FeatureDescription feat = null;
    for (int j = 0; j < existingFeatures.length; j++) {
      if (existingFeatures[j].getName().equals(featName)) {
        feat = existingFeatures[j];
        break;
      }
    }

    if (feat == null) {
      // doesn't exist; add it
      FeatureDescription featDesc = aType.addFeature(featName, aFeatures[i].getDescription(),
          rangeTypeName, elementTypeName, multiRefsAllowed);
      featDesc.setSourceUrl(aFeatures[i].getSourceUrl());
    } else {// feature does exist
      // check that the range types match
      if (!feat.getRangeTypeName().equals(rangeTypeName)) {
        throw new ResourceInitializationException(
            ResourceInitializationException.INCOMPATIBLE_RANGE_TYPES, new Object[] {
                aType.getName() + ":" + feat.getName(), rangeTypeName, feat.getRangeTypeName(),
                aType.getSourceUrlString() });
      }
      Boolean mra1 = feat.getMultipleReferencesAllowed();
      Boolean mra2 = multiRefsAllowed;

      // the logic here:
      // OK if both null
      // OK if both not-null, and are equals()
      // OK if one is null, the other has boolean-value of false (false is the default)
      // not ok otherwise

      if (!(((mra1 == null) && (mra2 == null)) || ((mra1 != null) && mra1.equals(mra2))
          || ((mra1 == null) && !mra2) || ((mra2 == null) && !mra1))) {
        throw new ResourceInitializationException(
            ResourceInitializationException.INCOMPATIBLE_MULTI_REFS, new Object[] {
                aType.getName() + ":" + feat.getName(), aType.getSourceUrlString() });
      }

      if (!elementTypesCompatible(feat.getElementType(), elementTypeName)) {
        throw new ResourceInitializationException(
            ResourceInitializationException.INCOMPATIBLE_ELEMENT_RANGE_TYPES, new Object[] {
                aType.getName() + TypeSystem.FEATURE_SEPARATOR + feat.getName(), elementTypeName,
                feat.getElementType(), aType.getSourceUrlString() });
      }
    }
  }
}