Java Code Examples for org.apache.uima.cas.CAS#TYPE_NAME_STRING

The following examples show how to use org.apache.uima.cas.CAS#TYPE_NAME_STRING . 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: TypeSystemImpl.java    From uima-uimaj with Apache License 2.0 6 votes vote down vote up
/**
   * The range type of features may include 
   *   special uima types that are not creatable, such as the primitive ones
   *   like integer, or string, or subtypes of string.
   * Other types are reference types
   */
  boolean classifyAsRefType(String name, TypeImpl superType) {
    switch(name) {
    case CAS.TYPE_NAME_BOOLEAN:
    case CAS.TYPE_NAME_BYTE:
    case CAS.TYPE_NAME_SHORT:
    case CAS.TYPE_NAME_INTEGER:
    case CAS.TYPE_NAME_LONG:
    case CAS.TYPE_NAME_FLOAT:
    case CAS.TYPE_NAME_DOUBLE:
    case CAS.TYPE_NAME_STRING:
//    case CAS.TYPE_NAME_JAVA_OBJECT:
//    case CAS.TYPE_NAME_MAP:
//    case CAS.TYPE_NAME_LIST:
      return false;
    }
    // superType is null for TOP, which is a Ref type
    if (superType != null && superType.getName().equals(CAS.TYPE_NAME_STRING)) { // can't compare to stringType - may not be set yet
      return false;
    }
    return true;
  }
 
Example 2
Source File: PrimitiveUimaIndexingSupport.java    From inception with Apache License 2.0 6 votes vote down vote up
@Override
public boolean accepts(AnnotationFeature aFeature)
{
    switch (aFeature.getMultiValueMode()) {
    case NONE:
        switch (aFeature.getType()) {
        case CAS.TYPE_NAME_INTEGER: // fallthrough
        case CAS.TYPE_NAME_FLOAT: // fallthrough
        case CAS.TYPE_NAME_BOOLEAN: // fallthrough
        case CAS.TYPE_NAME_STRING: 
            return true;
        default:
            return false;
        }
    case ARRAY: // fallthrough
    default:
        return false;
    }
}
 
Example 3
Source File: StringFeatureSupportTest.java    From webanno with Apache License 2.0 6 votes vote down vote up
@Before
public void setUp() throws Exception
{
    initMocks(this);
    
    sut = new StringFeatureSupport(new PrimitiveUimaFeatureSupportProperties(),
            schemaService);
    
    valueFeature = new AnnotationFeature("value", CAS.TYPE_NAME_STRING);
    
    valueTagset = new TagSet();
    
    jcas = createJCasFromPath("src/test/resources/desc/type/webannoTestTypes.xml");
    jcas.setDocumentText("label");
    
    Type spanType = jcas.getCas().getTypeSystem().getType("webanno.custom.Span");
    spanFS = jcas.getCas().createAnnotation(spanType, 0, jcas.getDocumentText().length());
}
 
Example 4
Source File: WebAnnoCasUtil.java    From webanno with Apache License 2.0 6 votes vote down vote up
/**
 * Get the feature value of this {@code Feature} on this annotation
 */
private static Object getFeatureValue(FeatureStructure aFS, Feature aFeature)
{
    switch (aFeature.getRange().getName()) {
    case CAS.TYPE_NAME_STRING:
        return aFS.getFeatureValueAsString(aFeature);
    case CAS.TYPE_NAME_BOOLEAN:
        return aFS.getBooleanValue(aFeature);
    case CAS.TYPE_NAME_FLOAT:
        return aFS.getFloatValue(aFeature);
    case CAS.TYPE_NAME_INTEGER:
        return aFS.getIntValue(aFeature);
    case CAS.TYPE_NAME_BYTE:
        return aFS.getByteValue(aFeature);
    case CAS.TYPE_NAME_DOUBLE:
        return aFS.getDoubleValue(aFeature);
    case CAS.TYPE_NAME_LONG:
        aFS.getLongValue(aFeature);
    case CAS.TYPE_NAME_SHORT:
        aFS.getShortValue(aFeature);
    default:
        return null;
    // return aFS.getFeatureValue(aFeature);
    }
}
 
Example 5
Source File: WebAnnoCasUtil.java    From webanno with Apache License 2.0 6 votes vote down vote up
public static <T> T getFeature(FeatureStructure aFS, String aFeatureName)
{
    Feature feature = aFS.getType().getFeatureByBaseName(aFeatureName);

    if (feature == null) {
        throw new IllegalArgumentException("Type [" + aFS.getType().getName()
                + "] has no feature called [" + aFeatureName + "]");
    }

    switch (feature.getRange().getName()) {
    case CAS.TYPE_NAME_STRING:
        return (T) aFS.getStringValue(feature);
    case CAS.TYPE_NAME_BOOLEAN:
        return (T) (Boolean) aFS.getBooleanValue(feature);
    case CAS.TYPE_NAME_FLOAT:
        return (T) (Float) aFS.getFloatValue(feature);
    case CAS.TYPE_NAME_INTEGER:
        return (T) (Integer) aFS.getIntValue(feature);
    default:
        throw new IllegalArgumentException("Cannot get value of feature [" + feature.getName()
                + "] with type [" + feature.getRange().getName() + "]");
    }
}
 
Example 6
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 7
Source File: AgreementMeasureTestSuite_ImplBase.java    From webanno with Apache License 2.0 5 votes vote down vote up
public <R extends Serializable, T extends DefaultAgreementTraits> R twoWithoutLabelTest(
        AggreementMeasureSupport<T, R, ICodingAnnotationStudy> aSupport, T aTraits)
    throws Exception
{
    AnnotationLayer layer = new AnnotationLayer(POS.class.getName(),
            POS.class.getSimpleName(), SPAN_TYPE, project, false, SINGLE_TOKEN, NO_OVERLAP);
    layer.setId(1l);
    layers.add(layer);

    AnnotationFeature feature = new AnnotationFeature(project, layer, "PosValue", "PosValue",
            CAS.TYPE_NAME_STRING);
    feature.setId(1l);
    features.add(feature);
    
    JCas user1 = JCasFactory.createJCas();
    user1.setDocumentText("test");
    new POS(user1, 0, 1).addToIndexes();
    new POS(user1, 1, 2).addToIndexes();
    POS p1 = new POS(user1, 3, 4);
    p1.setPosValue("A");
    p1.addToIndexes();

    JCas user2 = JCasFactory.createJCas();
    user2.setDocumentText("test");
    new POS(user2, 0, 1).addToIndexes();
    new POS(user2, 2, 3).addToIndexes();
    POS p2 = new POS(user2, 3, 4);
    p2.setPosValue("B");
    p2.addToIndexes();
    
    Map<String, List<CAS>> casByUser = new LinkedHashMap<>();
    casByUser.put("user1", asList(user1.getCas()));
    casByUser.put("user2", asList(user2.getCas()));
    
    AggreementMeasure<R> measure = aSupport.createMeasure(feature, aTraits);
    
    return measure.getAgreement(casByUser);
}
 
Example 8
Source File: AgreementMeasureTestSuite_ImplBase.java    From webanno with Apache License 2.0 5 votes vote down vote up
public <R extends Serializable, T extends DefaultAgreementTraits> R 
        singleNoDifferencesWithAdditionalCasTest(
                AggreementMeasureSupport<T, R, ICodingAnnotationStudy> aSupport)
    throws Exception
{
    AnnotationLayer layer = new AnnotationLayer(POS.class.getName(),
            POS.class.getSimpleName(), SPAN_TYPE, project, false, SINGLE_TOKEN, NO_OVERLAP);
    layer.setId(1l);
    layers.add(layer);

    AnnotationFeature feature = new AnnotationFeature(project, layer, "PosValue", "PosValue",
            CAS.TYPE_NAME_STRING);
    feature.setId(1l);
    features.add(feature);
    
    T traits = aSupport.createTraits();
    
    JCas user1 = JCasFactory.createJCas();
    user1.setDocumentText("test");

    JCas user2 = JCasFactory.createJCas();
    user2.setDocumentText("test");
    
    JCas user3 = JCasFactory.createJCas();
    user3.setDocumentText("test");
    POS pos3 = new POS(user3, 0, 4);
    pos3.setPosValue("test");
    pos3.addToIndexes();
    
    Map<String, List<CAS>> casByUser = new LinkedHashMap<>();
    casByUser.put("user1", asList(user1.getCas()));
    casByUser.put("user2", asList(user2.getCas()));
    casByUser.put("user3", asList(user3.getCas()));
    
    AggreementMeasure<R> measure = aSupport.createMeasure(feature, traits);
    
    return measure.getAgreement(casByUser);
}
 
Example 9
Source File: TypeSystemAnalysisTest.java    From webanno with Apache License 2.0 5 votes vote down vote up
@Test
public void testChain() throws Exception
{
    TypeSystemDescription tsd = createTypeSystemDescription(
            "tsd/chain");
    TypeSystemAnalysis analysis = TypeSystemAnalysis.of(tsd);
    
    AnnotationLayer chainLayer = new AnnotationLayer();
    chainLayer.setName("webanno.custom.Chain");
    chainLayer.setUiName("Chain");
    chainLayer.setType(WebAnnoConst.CHAIN_TYPE);
    chainLayer.setAnchoringMode(AnchoringMode.CHARACTERS);
    chainLayer.setOverlapMode(OverlapMode.ANY_OVERLAP);
    chainLayer.setCrossSentence(true);

    AnnotationFeature referenceRelationFeature = new AnnotationFeature(
            "referenceRelation", CAS.TYPE_NAME_STRING);
    AnnotationFeature referenceTypeFeature = new AnnotationFeature(
            "referenceType", CAS.TYPE_NAME_STRING);

    SoftAssertions softly = new SoftAssertions();
    softly.assertThat(analysis.getLayers())
        .containsExactlyInAnyOrder(chainLayer)
        .usingFieldByFieldElementComparator();
    softly.assertThat(analysis.getFeatures(chainLayer.getName()))
        .containsExactlyInAnyOrder(referenceRelationFeature, referenceTypeFeature)
        .usingFieldByFieldElementComparator();
    softly.assertAll();
}
 
Example 10
Source File: TypeSystemAnalysisTest.java    From webanno with Apache License 2.0 5 votes vote down vote up
@Test
public void testSpanWithPrimitiveFeatures() throws Exception
{
    TypeSystemDescription tsd = createTypeSystemDescription("tsd/spanWithPrimitiveFeatures");
    TypeSystemAnalysis analysis = TypeSystemAnalysis.of(tsd);
    
    AnnotationLayer spanLayer = new AnnotationLayer();
    spanLayer.setName("webanno.custom.Span");
    spanLayer.setUiName("Span");
    spanLayer.setType(WebAnnoConst.SPAN_TYPE);
    spanLayer.setAnchoringMode(AnchoringMode.CHARACTERS);
    spanLayer.setOverlapMode(OverlapMode.ANY_OVERLAP);
    spanLayer.setCrossSentence(true);
    
    AnnotationFeature stringFeature = new AnnotationFeature(
            "stringFeature", CAS.TYPE_NAME_STRING);
    AnnotationFeature intFeature = new AnnotationFeature(
            "intFeature", CAS.TYPE_NAME_INTEGER);
    AnnotationFeature booleanFeature = new AnnotationFeature(
            "booleanFeature", CAS.TYPE_NAME_BOOLEAN);
    AnnotationFeature floatFeature = new AnnotationFeature(
            "floatFeature", CAS.TYPE_NAME_FLOAT);

    SoftAssertions softly = new SoftAssertions();
    softly.assertThat(analysis.getLayers())
        .containsExactly(spanLayer)
        .usingFieldByFieldElementComparator();
    softly.assertThat(analysis.getFeatures(spanLayer.getName()))
        .containsExactlyInAnyOrder(stringFeature, intFeature, booleanFeature, floatFeature)
        .usingFieldByFieldElementComparator();
    softly.assertAll();
}
 
Example 11
Source File: PartOfSpeechLayerInitializer.java    From webanno with Apache License 2.0 5 votes vote down vote up
@Override
public void configure(Project aProject) throws IOException
{
    TagSet posTagSet = JsonImportUtil.importTagSetFromJson(aProject,
            new ClassPathResource("/tagsets/mul-pos-ud2.json").getInputStream(),
            annotationSchemaService);

    AnnotationLayer tokenLayer = annotationSchemaService.findLayer(aProject,
            Token.class.getName());

    AnnotationLayer posLayer = new AnnotationLayer(POS.class.getName(), "Part of speech",
            SPAN_TYPE, aProject, true, SINGLE_TOKEN, NO_OVERLAP);

    AnnotationFeature tokenPosFeature = new AnnotationFeature(aProject, tokenLayer, "pos",
            "pos", POS.class.getName());
    annotationSchemaService.createFeature(tokenPosFeature);

    posLayer.setAttachType(tokenLayer);
    posLayer.setAttachFeature(tokenPosFeature);
    annotationSchemaService.createLayer(posLayer);

    AnnotationFeature xpos = new AnnotationFeature(aProject, posLayer, "PosValue",
            "XPOS", CAS.TYPE_NAME_STRING, "XPOS", null);
    xpos.setDescription("Language-specific part-of-speech tag");
    annotationSchemaService.createFeature(xpos);

    AnnotationFeature upos = new AnnotationFeature(aProject, posLayer, "coarseValue",
            "UPOS", CAS.TYPE_NAME_STRING, "UPOS", posTagSet);
    upos.setDescription("Universal part-of-speech tag");
    annotationSchemaService.createFeature(upos);

            
}
 
Example 12
Source File: AbstractJsonConsumer.java    From baleen with Apache License 2.0 5 votes vote down vote up
/**
 * Write primitive value.
 *
 * @param generator the generator
 * @param annotation the annotation
 * @param feature the feature
 * @throws IOException Signals that an I/O exception has occurred.
 */
private void writePrimitiveValue(
    JsonGenerator generator, FeatureStructure annotation, Feature feature) throws IOException {
  String range = feature.getRange().getName();
  switch (range) {
    case CAS.TYPE_NAME_INTEGER:
      generator.writeNumber(annotation.getIntValue(feature));
      break;
    case CAS.TYPE_NAME_FLOAT:
      generator.writeNumber(annotation.getFloatValue(feature));
      break;
    case CAS.TYPE_NAME_STRING:
      generator.writeString(annotation.getStringValue(feature));
      break;
    case CAS.TYPE_NAME_BOOLEAN:
      generator.writeBoolean(annotation.getBooleanValue(feature));
      break;
    case CAS.TYPE_NAME_BYTE:
      generator.writeNumber(annotation.getByteValue(feature));
      break;
    case CAS.TYPE_NAME_SHORT:
      generator.writeNumber(annotation.getShortValue(feature));
      break;
    case CAS.TYPE_NAME_LONG:
      generator.writeNumber(annotation.getLongValue(feature));
      break;
    case CAS.TYPE_NAME_DOUBLE:
      generator.writeNumber(annotation.getDoubleValue(feature));
      break;
    default:
      getMonitor().warn("Unexpected primitive type: " + range);
      break;
  }
}
 
Example 13
Source File: FeatureUtils.java    From baleen with Apache License 2.0 5 votes vote down vote up
/**
 * Convert a UIMA feature to a Java object of the correct type
 *
 * @param f UIMA CAS Feature
 * @param a UIMA CAS Annotation
 * @return Java object, or null if unable to convert
 */
public static Object featureToObject(Feature f, Annotation a) {
  Object ret = null;

  switch (f.getRange().getName()) {
    case CAS.TYPE_NAME_STRING:
      ret = StringToObject.convertStringToObject(a.getStringValue(f));
      break;
    case CAS.TYPE_NAME_INTEGER:
      ret = a.getIntValue(f);
      break;
    case CAS.TYPE_NAME_FLOAT:
      ret = a.getFloatValue(f);
      break;
    case CAS.TYPE_NAME_BOOLEAN:
      ret = a.getBooleanValue(f);
      break;
    case CAS.TYPE_NAME_BYTE:
      ret = a.getByteValue(f);
      break;
    case CAS.TYPE_NAME_SHORT:
      ret = a.getShortValue(f);
      break;
    case CAS.TYPE_NAME_LONG:
      ret = a.getLongValue(f);
      break;
    case CAS.TYPE_NAME_DOUBLE:
      ret = a.getDoubleValue(f);
      break;
    default:
      ret = null;
  }

  return ret;
}
 
Example 14
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 15
Source File: MtasUimaParserTest.java    From inception with Apache License 2.0 4 votes vote down vote up
@Test
public void testDependencyRelation() throws Exception
{
    // Set up document with a dummy dependency relation
    jcas.setDocumentText("a b");
    Token t1 = new Token(jcas, 0, 1);
    t1.addToIndexes();
    
    POS p1 = new POS(jcas, t1.getBegin(), t1.getEnd());
    p1.setPosValue("A");
    t1.setPos(p1);
    p1.addToIndexes();

    Token t2 = new Token(jcas, 2, 3);
    t2.addToIndexes();

    POS p2 = new POS(jcas, t2.getBegin(), t2.getEnd());
    p2.setPosValue("B");
    t2.setPos(p2);
    p2.addToIndexes();
    
    Dependency d1 = new Dependency(jcas, t2.getBegin(), t2.getEnd());
    d1.setDependent(t2);
    d1.setGovernor(t1);
    d1.addToIndexes();
    
    // Set up annotation schema with POS and Dependency
    AnnotationLayer tokenLayer = new AnnotationLayer(Token.class.getName(), "Token",
            SPAN_TYPE, project, true, SINGLE_TOKEN, NO_OVERLAP);
    tokenLayer.setId(1l);
    AnnotationFeature tokenLayerPos = new AnnotationFeature(1l, tokenLayer, "pos",
            POS.class.getName());
    
    AnnotationLayer posLayer = new AnnotationLayer(POS.class.getName(), "POS",
            SPAN_TYPE, project, true, SINGLE_TOKEN, NO_OVERLAP);
    posLayer.setId(2l);
    AnnotationFeature posLayerValue = new AnnotationFeature(1l, posLayer, "PosValue",
            CAS.TYPE_NAME_STRING);
    
    AnnotationLayer depLayer = new AnnotationLayer(Dependency.class.getName(),
            "Dependency", RELATION_TYPE, project, true, SINGLE_TOKEN, NO_OVERLAP);
    depLayer.setId(3l);
    depLayer.setAttachType(tokenLayer);
    depLayer.setAttachFeature(tokenLayerPos);
    AnnotationFeature dependencyLayerGovernor = new AnnotationFeature(2l, depLayer,
            "Governor", Token.class.getName());
    AnnotationFeature dependencyLayerDependent = new AnnotationFeature(3l, depLayer,
            "Dependent", Token.class.getName());
        
    when(annotationSchemaService.listAnnotationLayer(any(Project.class)))
            .thenReturn(asList(tokenLayer, posLayer, depLayer));

    when(annotationSchemaService.getAdapter(posLayer)).thenReturn(new SpanAdapter(
        layerSupportRegistry, featureSupportRegistry, null, posLayer, 
        () -> asList(posLayerValue), null));

    when(annotationSchemaService.getAdapter(depLayer))
            .thenReturn(new RelationAdapter(
                layerSupportRegistry, featureSupportRegistry, null, depLayer,
                FEAT_REL_TARGET, FEAT_REL_SOURCE,
                () -> asList(dependencyLayerGovernor, dependencyLayerDependent),
                emptyList()));

    MtasUimaParser sut = new MtasUimaParser(
            asList(tokenLayerPos, posLayerValue, dependencyLayerGovernor,
                    dependencyLayerDependent),
            annotationSchemaService, featureIndexingSupportRegistry);
    MtasTokenCollection tc = sut.createTokenCollection(jcas.getCas());
    
    MtasUtils.print(tc);
    
    List<MtasToken> tokens = new ArrayList<>();
    tc.iterator().forEachRemaining(tokens::add);

    assertThat(tokens)
        .filteredOn(t -> t.getPrefix().startsWith("Dependency"))
        .extracting(t -> t.getPrefix() + "=" + t.getPostfix())
        .containsExactly(
                "Dependency=b", 
                "Dependency-source=a", 
                "Dependency-source.PosValue=A",
                "Dependency-target=b", 
                "Dependency-target.PosValue=B");
}
 
Example 16
Source File: WebAnnoCasUtil.java    From webanno with Apache License 2.0 4 votes vote down vote up
public static boolean isNativeUimaType(String aType)
{
    Validate.notNull(aType, "Type must not be null");
    
    switch (aType) {
    case CAS.TYPE_NAME_ANNOTATION:
    case CAS.TYPE_NAME_ANNOTATION_BASE:
    case CAS.TYPE_NAME_ARRAY_BASE:
    case CAS.TYPE_NAME_BOOLEAN:
    case CAS.TYPE_NAME_BOOLEAN_ARRAY:
    case CAS.TYPE_NAME_BYTE:
    case CAS.TYPE_NAME_BYTE_ARRAY:
    case CAS.TYPE_NAME_DOCUMENT_ANNOTATION:
    case CAS.TYPE_NAME_DOUBLE:
    case CAS.TYPE_NAME_DOUBLE_ARRAY:
    case CAS.TYPE_NAME_EMPTY_FLOAT_LIST:
    case CAS.TYPE_NAME_EMPTY_FS_LIST:
    case CAS.TYPE_NAME_EMPTY_INTEGER_LIST:
    case CAS.TYPE_NAME_EMPTY_STRING_LIST:
    case CAS.TYPE_NAME_FLOAT:
    case CAS.TYPE_NAME_FLOAT_ARRAY:
    case CAS.TYPE_NAME_FLOAT_LIST:
    case CAS.TYPE_NAME_FS_ARRAY:
    case CAS.TYPE_NAME_FS_LIST:
    case CAS.TYPE_NAME_INTEGER:
    case CAS.TYPE_NAME_INTEGER_ARRAY:
    case CAS.TYPE_NAME_INTEGER_LIST:
    case CAS.TYPE_NAME_LIST_BASE:
    case CAS.TYPE_NAME_LONG:
    case CAS.TYPE_NAME_LONG_ARRAY:
    case CAS.TYPE_NAME_NON_EMPTY_FLOAT_LIST:
    case CAS.TYPE_NAME_NON_EMPTY_FS_LIST:
    case CAS.TYPE_NAME_NON_EMPTY_INTEGER_LIST:
    case CAS.TYPE_NAME_NON_EMPTY_STRING_LIST:
    case CAS.TYPE_NAME_SHORT:
    case CAS.TYPE_NAME_SHORT_ARRAY:
    case CAS.TYPE_NAME_SOFA:
    case CAS.TYPE_NAME_STRING:
    case CAS.TYPE_NAME_STRING_ARRAY:
    case CAS.TYPE_NAME_STRING_LIST:
    case CAS.TYPE_NAME_TOP:
        return true;
    }
    
    return false;
}
 
Example 17
Source File: WebAnnoCasUtil.java    From webanno with Apache License 2.0 4 votes vote down vote up
/**
 * Set a feature value.
 *
 * @param aFS
 *            the feature structure.
 * @param aFeature
 *            the feature within the annotation whose value to set. If this parameter is
 *            {@code null} then nothing happens.
 * @param aValue
 *            the feature value.
 */
public static void setFeature(FeatureStructure aFS, AnnotationFeature aFeature, Object aValue)
{
    if (aFeature == null) {
        return;
    }

    Feature feature = aFS.getType().getFeatureByBaseName(aFeature.getName());

    switch (aFeature.getMultiValueMode()) {
    case NONE: {
        String effectiveType = aFeature.getType();
        if (effectiveType.contains(":")) {
            effectiveType = CAS.TYPE_NAME_STRING;
        }
        
        // Sanity check
        if (!Objects.equals(effectiveType, feature.getRange().getName())) {
            throw new IllegalArgumentException("On [" + aFS.getType().getName() + "] feature ["
                    + aFeature.getName() + "] actual type [" + feature.getRange().getName()
                    + "] does not match expected feature type [" + effectiveType + "].");
        }

        switch (effectiveType) {
        case CAS.TYPE_NAME_STRING:
            aFS.setStringValue(feature, (String) aValue);
            break;
        case CAS.TYPE_NAME_BOOLEAN:
            aFS.setBooleanValue(feature, aValue != null ? (boolean) aValue : false);
            break;
        case CAS.TYPE_NAME_FLOAT:
            aFS.setFloatValue(feature, aValue != null ? (float) aValue : 0.0f);
            break;
        case CAS.TYPE_NAME_INTEGER:
            aFS.setIntValue(feature, aValue != null ? (int) aValue : 0);
            break;
        default:
            throw new IllegalArgumentException("Cannot set value of feature ["
                    + aFeature.getName() + "] with type [" + feature.getRange().getName()
                    + "] to [" + aValue + "]");
        }
        break;
    }
    case ARRAY: {
        switch (aFeature.getLinkMode()) {
        case WITH_ROLE: {
            // Get type and features - we need them later in the loop
            setLinkFeature(aFS, aFeature, (List<LinkWithRoleModel>) aValue, feature);
            break;
        }
        default:
            throw new IllegalArgumentException("Unsupported link mode ["
                    + aFeature.getLinkMode() + "] on feature [" + aFeature.getName() + "]");
        }
        break;
    }
    default:
        throw new IllegalArgumentException("Unsupported multi-value mode ["
                + aFeature.getMultiValueMode() + "] on feature [" + aFeature.getName() + "]");
    }
}
 
Example 18
Source File: TypeSystemAnalysisTest.java    From webanno with Apache License 2.0 4 votes vote down vote up
@Test
public void testRelationWithPrimitiveFeatures() throws Exception
{
    TypeSystemDescription tsd = createTypeSystemDescription(
            "tsd/relationWithPrimitiveFeatures");
    TypeSystemAnalysis analysis = TypeSystemAnalysis.of(tsd);
    
    AnnotationLayer relationLayer = new AnnotationLayer();
    relationLayer.setName("webanno.custom.Relation");
    relationLayer.setUiName("Relation");
    relationLayer.setType(WebAnnoConst.RELATION_TYPE);
    relationLayer.setAnchoringMode(AnchoringMode.CHARACTERS);
    relationLayer.setOverlapMode(OverlapMode.ANY_OVERLAP);
    relationLayer.setCrossSentence(true);

    AnnotationLayer relationTargetLayer = new AnnotationLayer();
    relationTargetLayer.setName("webanno.custom.RelationTarget");
    relationTargetLayer.setUiName("RelationTarget");
    relationTargetLayer.setType(WebAnnoConst.SPAN_TYPE);
    relationTargetLayer.setAnchoringMode(AnchoringMode.CHARACTERS);
    relationTargetLayer.setOverlapMode(OverlapMode.ANY_OVERLAP);
    relationTargetLayer.setCrossSentence(true);

    AnnotationFeature stringFeature = new AnnotationFeature(
            "stringFeature", CAS.TYPE_NAME_STRING);
    AnnotationFeature intFeature = new AnnotationFeature(
            "intFeature", CAS.TYPE_NAME_INTEGER);
    AnnotationFeature booleanFeature = new AnnotationFeature(
            "booleanFeature", CAS.TYPE_NAME_BOOLEAN);
    AnnotationFeature floatFeature = new AnnotationFeature(
            "floatFeature", CAS.TYPE_NAME_FLOAT);

    SoftAssertions softly = new SoftAssertions();
    softly.assertThat(analysis.getLayers())
        .containsExactlyInAnyOrder(relationLayer, relationTargetLayer)
        .usingFieldByFieldElementComparator();
    softly.assertThat(analysis.getFeatures(relationLayer.getName()))
            .containsExactlyInAnyOrder(stringFeature, intFeature, booleanFeature, floatFeature)
            .usingFieldByFieldElementComparator();
    softly.assertAll();
}
 
Example 19
Source File: NewFeatureUtils.java    From baleen with Apache License 2.0 4 votes vote down vote up
/**
 * Set the primitve value for the given feature on the given annotation
 *
 * @param annotation to add the feature
 * @param feature to add
 * @param value to add
 */
public static void setPrimitive(
    final BaleenAnnotation annotation, final Feature feature, final Object value) {

  // Nothing to do
  if (value == null) {
    return;
  }

  // We could do more type conversion here (got double -> want integer)
  // but fail fast is better - this is a common / standard type system after all.

  switch (feature.getRange().getName()) {
    case CAS.TYPE_NAME_STRING:
      annotation.setStringValue(feature, value.toString()); // Can be stored as different type
      break;
    case CAS.TYPE_NAME_INTEGER:
      annotation.setIntValue(feature, ((Number) value).intValue());
      break;
    case CAS.TYPE_NAME_FLOAT:
      annotation.setFloatValue(feature, ((Number) value).floatValue());
      break;
    case CAS.TYPE_NAME_BOOLEAN:
      annotation.setBooleanValue(feature, (boolean) value);
      break;
    case CAS.TYPE_NAME_BYTE:
      annotation.setByteValue(feature, (byte) value);
      break;
    case CAS.TYPE_NAME_SHORT:
      annotation.setShortValue(feature, ((Number) value).shortValue());
      break;
    case CAS.TYPE_NAME_LONG:
      annotation.setLongValue(feature, ((Number) value).longValue());
      break;
    case CAS.TYPE_NAME_DOUBLE:
      annotation.setDoubleValue(feature, ((Number) value).doubleValue());
      break;
    default:
      break;
  }
}
 
Example 20
Source File: GazeteerExporterTest.java    From inception with Apache License 2.0 4 votes vote down vote up
@Before
public void setUp() throws Exception
{
    initMocks(this);

    sourceProject = new Project();
    sourceProject.setId(1l);
    sourceProject.setName("Test Project");
    sourceProject.setMode(WebAnnoConst.PROJECT_TYPE_ANNOTATION);

    sourceLayer = new AnnotationLayer("span", "span", SPAN_TYPE, sourceProject, false, TOKENS,
            NO_OVERLAP);
    sourceFeature = new AnnotationFeature(sourceProject, sourceLayer, "value", "value",
            CAS.TYPE_NAME_STRING);
    sourceRecommender = new Recommender("rec1", sourceLayer);
    sourceRecommender.setFeature(sourceFeature);
    
    targetProject = new Project();
    targetProject.setId(2l);
    targetProject.setName("Test Project");
    targetProject.setMode(WebAnnoConst.PROJECT_TYPE_ANNOTATION);

    targetLayer = new AnnotationLayer("span", "span", SPAN_TYPE, sourceProject, false, TOKENS,
            NO_OVERLAP);
    targetFeature = new AnnotationFeature(sourceProject, targetLayer, "value", "value",
            CAS.TYPE_NAME_STRING);
    targetRecommender = new Recommender("rec1", targetLayer);
    targetRecommender.setFeature(targetFeature);
    
    when(gazeteerService.listGazeteers(sourceRecommender)).thenReturn(gazeteers());
    
    when(gazeteerService.getGazeteerFile(Mockito.any())).thenAnswer(invocation -> {
        Gazeteer gaz = invocation.getArgument(0);
        File gazFile = temporaryFolder.newFile(gaz.getId() + ".txt");
        String data = "John\tVAL" + gaz.getId();
        FileUtils.writeStringToFile(gazFile, data, UTF_8);
        return gazFile;
    });

    when(recommendationService.listRecommenders(sourceProject))
            .thenReturn(asList(sourceRecommender));
    
    when(recommendationService.getRecommender(any(), any()))
            .thenReturn(Optional.of(targetRecommender));

    sut = new GazeteerExporter(recommendationService, gazeteerService);
}