org.apache.uima.UimaContext Java Examples

The following examples show how to use org.apache.uima.UimaContext. 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: ExternalResourceInitializer.java    From uima-uimafit with Apache License 2.0 6 votes vote down vote up
/**
 * Get all resources declared in the context.
 */
private static Collection<?> getResources(UimaContext aContext)
        throws ResourceInitializationException {
  if (!(aContext instanceof UimaContextAdmin)) {
    return Collections.emptyList();
  }

  ResourceManager resMgr = ((UimaContextAdmin) aContext).getResourceManager();
  if (!(resMgr instanceof ResourceManager_impl)) {
    // Unfortunately there is not official way to access the list of resources. Thus we
    // have to rely on the UIMA implementation details and access the internal resource
    // map via reflection. If the resource manager is not derived from the default
    // UIMA resource manager, then we cannot really do anything here.
    throw new IllegalStateException("Unsupported resource manager implementation ["
            + resMgr.getClass() + "]");
  }
  
  return resMgr.getExternalResources();
}
 
Example #2
Source File: BioNLPGeniaEventsCollectionReader.java    From bluima with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
   @Override
   public void initialize(UimaContext context)
    throws ResourceInitializationException {
super.initialize(context);

try {
    File dir = ResourceHelper.getFile(inputDirectory);

    directoryIterator = FileUtils.iterateFiles(dir,
	    new String[] { EXTENSION }, true);

} catch (Exception e) {
    LOG.debug(StringUtils.print(e));
    throw new ResourceInitializationException(
	    ResourceInitializationException.NO_RESOURCE_FOR_PARAMETERS,
	    new Object[] { inputDirectory }, e);
}
   }
 
Example #3
Source File: FrequencyFilterAnnotator.java    From bluima with Apache License 2.0 6 votes vote down vote up
@Override
public void initialize(UimaContext context)
        throws ResourceInitializationException {
    super.initialize(context);
    // load frequency list into Set
    try {
        for (String line : linesFrom(tokenFrequencyFile)) {
            String[] split = line.split("\t");
            int freq = parseInt(split[1]);
            if (freq > minimumFrequency && freq < maximumFrequency) {
                String txt = caseSensitive ? split[0] : split[0]
                        .toLowerCase();
                normalText.add(txt);
            }
        }
    } catch (FileNotFoundException e) {
        throw new ResourceInitializationException(e);
    }

    // validate min max params
    checkArgument(maximumFrequency > minimumFrequency,
            "expected: maximumFrequency>minimumFrequency");
    checkArgument(minimumFrequency >= 0, "expected: minimumFrequency >= 0");
    if (maximumFrequency == 0)
        LOG.info("FrequencyFilterAnnotator's minimumFrequency set to 0 --> Filter inactive");
}
 
Example #4
Source File: CsvFolderReader.java    From baleen with Apache License 2.0 6 votes vote down vote up
@Override
public void doInitialize(UimaContext context) throws ResourceInitializationException {
  if (folders == null || folders.length == 0) {
    folders = new String[1];
    folders[0] = System.getProperty("user.dir");
  }

  try {
    watcher = FileSystems.getDefault().newWatchService();
  } catch (IOException ioe) {
    throw new ResourceInitializationException(ioe);
  }

  csvParser = new CSVParserBuilder().withSeparator(separator.charAt(0)).build();
  registerFolders();
}
 
Example #5
Source File: ConcurrentTokenizer.java    From deeplearning4j with Apache License 2.0 6 votes vote down vote up
/**
 * Initializes the current instance with the given context.
 * 
 * Note: Do all initialization in this method, do not use the constructor.
 */
public void initialize(UimaContext context) throws ResourceInitializationException {

    super.initialize(context);

    TokenizerModel model;

    try {
        TokenizerModelResource modelResource =
                        (TokenizerModelResource) context.getResourceObject(UimaUtil.MODEL_PARAMETER);

        model = modelResource.getModel();
    } catch (ResourceAccessException e) {
        throw new ResourceInitializationException(e);
    }

    tokenizer = new TokenizerME(model);
}
 
Example #6
Source File: WhiteTextCollectionReader.java    From bluima with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
@Override
public void initialize(UimaContext context)
        throws ResourceInitializationException {

    try {
        if (corpus == null) {
            corpus = CorporaHelper.CORPORA_HOME
                    + "/src/main/resources/pear_resources/whitetext/WhiteText.1.3.xml";
        }
        checkArgument(new File(corpus).exists());
        InputStream corpusIs = new FileInputStream(corpus);

        SAXBuilder builder = new SAXBuilder();
        Document doc = builder.build(corpusIs);
        Element rootNode = doc.getRootElement();

        articleIt = rootNode.getChildren("PubmedArticle").iterator();

    } catch (Exception e) {
        throw new ResourceInitializationException(
                ResourceConfigurationException.NONEXISTENT_PARAMETER,
                new Object[] { corpus });
    }
}
 
Example #7
Source File: ViewMigratorJCasMultiplier.java    From biomedicus with Apache License 2.0 6 votes vote down vote up
/**
 * {@inheritDoc} <p>Initializes the 3 parameters, "sourceViewName", "targetViewName", and
 * "deleteOriginalView".</p>
 */
@Override
public void initialize(UimaContext aContext) throws ResourceInitializationException {
  super.initialize(aContext);

  sourceViewName = (String) aContext.getConfigParameterValue(PARAM_SOURCE_VIEW_NAME);
  targetViewName = (String) aContext.getConfigParameterValue(PARAM_TARGET_VIEW_NAME);
  deleteOriginalView = (Boolean) aContext.getConfigParameterValue(PARAM_DELETE_ORIGINAL_VIEW);

  try {
    String className = (String) aContext.getConfigParameterValue(PARAM_VIEW_MIGRATOR_CLASS);
    viewMigratorClass = Class.forName(className).asSubclass(ViewMigrator.class);
  } catch (ClassNotFoundException e) {
    throw new ResourceInitializationException(e);
  }
}
 
Example #8
Source File: LuceneDocumentRetrievalExecutor.java    From bioasq with Apache License 2.0 6 votes vote down vote up
@Override
public void initialize(UimaContext context) throws ResourceInitializationException {
  super.initialize(context);
  hits = UimaContextHelper.getConfigParameterIntValue(context, "hits", 100);
  // query constructor
  constructor = UimaContextHelper.createObjectFromConfigParameter(context,
          "query-string-constructor", "query-string-constructor-params",
          BooleanBagOfPhraseQueryStringConstructor.class, QueryStringConstructor.class);
  // lucene
  Analyzer analyzer = UimaContextHelper.createObjectFromConfigParameter(context, "query-analyzer",
          "query-analyzer-params", StandardAnalyzer.class, Analyzer.class);
  String[] fields = UimaContextHelper.getConfigParameterStringArrayValue(context, "fields");
  parser = new MultiFieldQueryParser(fields, analyzer);
  String index = UimaContextHelper.getConfigParameterStringValue(context, "index");
  try {
    reader = DirectoryReader.open(FSDirectory.open(Paths.get(index)));
  } catch (IOException e) {
    throw new ResourceInitializationException(e);
  }
  searcher = new IndexSearcher(reader);
  idFieldName = UimaContextHelper.getConfigParameterStringValue(context, "id-field", null);
  titleFieldName = UimaContextHelper.getConfigParameterStringValue(context, "title-field", null);
  textFieldName = UimaContextHelper.getConfigParameterStringValue(context, "text-field", null);
  uriPrefix = UimaContextHelper.getConfigParameterStringValue(context, "uri-prefix", null);
}
 
Example #9
Source File: AbbreviationsAnnotator.java    From bluima with Apache License 2.0 6 votes vote down vote up
@Override
public void initialize(UimaContext context)
        throws ResourceInitializationException {
    super.initialize(context);
    try {
        long start = currentTimeMillis();
        model = new AlignmentPredictionModel();
        if (retrain)
            model.setTrainingDataDir(ABREVIATIONS_HOME + RESOURCES_PATH
                    + "model_train/");
        // where the model is saved/loaded from
        model.setModelParamsFile(ABREVIATIONS_HOME + RESOURCES_PATH
                + "model_trained");
        model.trainIfNeeded();
        LOG.debug("Abbrev model trained in {}ms", currentTimeMillis()
                - start);
    } catch (IOException e) {
        throw new ResourceInitializationException(e);
    }
}
 
Example #10
Source File: WriteCoocurrencesToLoadfile.java    From bluima with Apache License 2.0 6 votes vote down vote up
@Override
public void initialize(UimaContext context)
        throws ResourceInitializationException {
    super.initialize(context);
    try {
        // writer
        LOG.info("writing LOAD DATA file to {}", outputFile);
        writer = new LoadDataFileWriter(new File(outputFile), "\t", FIELDS);
        if (writeSnippets)
            snippetWriter = new LoadDataFileWriter(new File(outputFile
                    + ".snippet"), "\t");

    } catch (Exception e) {
        throw new ResourceInitializationException(e);
    }
}
 
Example #11
Source File: Mongo.java    From baleen with Apache License 2.0 6 votes vote down vote up
/** Get the mongo db, collection and create some indexes */
@Override
public void doInitialize(UimaContext aContext) throws ResourceInitializationException {
  MongoDatabase db = mongoResource.getDB();
  entitiesCollection = db.getCollection(entitiesCollectionName);
  relationsCollection = db.getCollection(relationsCollectionName);
  documentsCollection = db.getCollection(documentsCollectionName);

  documentsCollection.createIndex(new Document(fields.getExternalId(), 1));
  entitiesCollection.createIndex(new Document(fields.getExternalId(), 1));
  relationsCollection.createIndex(new Document(fields.getExternalId(), 1));
  relationsCollection.createIndex(new Document(FIELD_DOCUMENT_ID, 1));
  entitiesCollection.createIndex(new Document(FIELD_DOCUMENT_ID, 1));

  stopFeatures = new HashSet<>();
  stopFeatures.add("uima.cas.AnnotationBase:sofa");
  stopFeatures.add("uk.gov.dstl.baleen.types.BaleenAnnotation:internalId");
}
 
Example #12
Source File: Blacklist.java    From baleen with Apache License 2.0 6 votes vote down vote up
@Override
public void doInitialize(UimaContext aContext) throws ResourceInitializationException {
  try {
    et =
        TypeUtils.getEntityClass(
            type, JCasFactory.createJCas(TypeSystemSingleton.getTypeSystemDescriptionInstance()));
  } catch (UIMAException | BaleenException e) {
    throw new ResourceInitializationException(e);
  }

  thingsToRemove = Arrays.asList(terms);

  if (!caseSensitive) {
    thingsToRemove = toLowerCase(thingsToRemove);
  }
}
 
Example #13
Source File: ImprovedLuceneInMemorySentenceRetrievalExecutor.java    From bioasq with Apache License 2.0 6 votes vote down vote up
@Override
public void initialize(UimaContext context) throws ResourceInitializationException {
  super.initialize(context);
  TokenizerFactory tokenizerFactory = UimaContextHelper.createObjectFromConfigParameter(context,
          "tokenizer-factory", "tokenizer-factory-params", IndoEuropeanTokenizerFactory.class,
          TokenizerFactory.class);
  SentenceModel sentenceModel = UimaContextHelper.createObjectFromConfigParameter(context,
          "sentence-model", "sentence-model-params", IndoEuropeanSentenceModel.class,
          SentenceModel.class);
  chunker = new SentenceChunker(tokenizerFactory, sentenceModel);
  // initialize hits
  hits = UimaContextHelper.getConfigParameterIntValue(context, "hits", 200);
  // initialize query analyzer, index writer config, and query parser
  analyzer = UimaContextHelper.createObjectFromConfigParameter(context, "query-analyzer",
          "query-analyzer-params", StandardAnalyzer.class, Analyzer.class);
  parser = new QueryParser("text", analyzer);
  // initialize query string constructor
  queryStringConstructor = UimaContextHelper.createObjectFromConfigParameter(context,
          "query-string-constructor", "query-string-constructor-params",
          BagOfPhraseQueryStringConstructor.class, QueryStringConstructor.class);
  String parserProviderName = UimaContextHelper
          .getConfigParameterStringValue(context, "parser-provider");
  parserProvider = ProviderCache.getProvider(parserProviderName, ParserProvider.class);

  lemma = new StanfordLemmatizer();
}
 
Example #14
Source File: ZipXmiCollectionReader.java    From bluima with Apache License 2.0 6 votes vote down vote up
@Override
public void initialize(UimaContext context)
        throws ResourceInitializationException {
    super.initialize(context);
    try {
        // we duplicate the code from AbstractFileReader to add "zip"
        // filtering
        File dir = getFile(inputDir);
        fileIterator = DirectoryIterator.get(directoryIterator, dir, "zip",
                isRecursive);

    } catch (Exception e) {
        throw new ResourceInitializationException(
                ResourceInitializationException.NO_RESOURCE_FOR_PARAMETERS,
                new Object[] { inputDir });
    }
}
 
Example #15
Source File: AnnotationFilterAnnotator.java    From bluima with Apache License 2.0 6 votes vote down vote up
@Override
public void initialize(UimaContext context)
        throws ResourceInitializationException {
    super.initialize(context);

    // validate that the class exists
    for (String annotationClass : annotationClasses) {
        try {
            @SuppressWarnings({ "unchecked" })
            Class<? extends Annotation> classz = (Class<? extends Annotation>) Class
                    .forName(annotationClass);
            checkNotNull(classz, "could not load class " + annotationClass);
            annotationClassesList.add(classz);
        } catch (Exception e) {
            throw new ResourceInitializationException(e);
        }
    }
}
 
Example #16
Source File: FilterIfNotRodent.java    From bluima with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
@Override
public void initialize(UimaContext context)
        throws ResourceInitializationException {
    super.initialize(context);
    try {
        if (!className.equals("all"))
            aClass = (Class<? extends Annotation>) Class.forName(className);
    } catch (Throwable t) {
        throw new RuntimeException("could not find class " + className);
    }
}
 
Example #17
Source File: CopyAnnotationsAnnotator2.java    From bluima with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
@Override
public void initialize(UimaContext context)
        throws ResourceInitializationException {
    super.initialize(context);
    try {
        annotation = (Class<? extends Annotation>) Class
                .forName(annotationStr);
    } catch (Throwable t) {
        throw new ResourceInitializationException(t);
    }
}
 
Example #18
Source File: MongoSentences.java    From baleen with Apache License 2.0 5 votes vote down vote up
/** Get the mongo db, collection and create some indexes */
@Override
public void doInitialize(UimaContext aContext) throws ResourceInitializationException {
  MongoDatabase db = mongoResource.getDB();
  sentencesCollection = db.getCollection(sentencesCollectionName);

  sentencesCollection.createIndex(new Document(FIELD_DOCUMENT_ID, 1));
  sentencesCollection.createIndex(new Document(FIELD_BEGIN, 1));
}
 
Example #19
Source File: QuestionConceptRecognizer.java    From bioasq with Apache License 2.0 5 votes vote down vote up
@Override
public void initialize(UimaContext context) throws ResourceInitializationException {
  super.initialize(context);
  String conceptProviderName = UimaContextHelper.getConfigParameterStringValue(context,
          "concept-provider");
  conceptProvider = ProviderCache.getProvider(conceptProviderName, ConceptProvider.class);
}
 
Example #20
Source File: CountAnnotations.java    From bluima with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
@Override
public void initialize(UimaContext context)
        throws ResourceInitializationException {
    super.initialize(context);
    checkArgument(annotationClassesStr.length > 0,
            "no annotations provided");
    try {
        List<String> fields = newArrayList();
        for (String c : annotationClassesStr) {
            try {
                Class<? extends Annotation> ac = (Class<? extends Annotation>) Class
                        .forName(c);
                annotationClasses.add(ac);
                fields.add(ac.getSimpleName());
            } catch (Exception e) {
                throw new Exception("Could not instantialize class " + c);
            }
        }

        LOG.info("writing annotations file to {}", outFile);
        writer = new LoadDataFileWriter(new File(outFile), "\t",
                fields.toArray(new String[fields.size()]));

    } catch (Throwable t) {
        throw new ResourceInitializationException(t);
    }
}
 
Example #21
Source File: Util.java    From uima-uimaj with Apache License 2.0 5 votes vote down vote up
/**
 * Calls userCode with specified context, then restores the context holder
 * @param context to use while running the userCode
 * @param userCode the code to run.
 * @throws Exception -
 */
public static void withContextHolderX(UimaContext context, Runnable_withException userCode) throws Exception {
  UimaContext prevContext = UimaContextHolder.setContext(context);
  try {
    userCode.run();
  } finally {
    UimaContextHolder.setContext(prevContext);
  }
}
 
Example #22
Source File: NewsleakElasticsearchReader.java    From newsleak with GNU Affero General Public License v3.0 5 votes vote down vote up
@Override
public void initialize(UimaContext context) throws ResourceInitializationException {
	super.initialize(context);
	logger = context.getLogger();
	client = esResource.getClient();
	esIndex = esResource.getIndex();

	try {
		XContentBuilder builder = XContentFactory.jsonBuilder().startObject().field("match").startObject()
				.field("DocumentLanguage", language).endObject().endObject();

		// retrieve all ids
		totalIdList = new ArrayList<String>();
		SearchResponse scrollResp = client.prepareSearch(esIndex)
				.addSort(SortParseElement.DOC_FIELD_NAME, SortOrder.ASC).setScroll(new TimeValue(60000))
				.setQuery(builder).setSize(10000).execute().actionGet();
		while (true) {
			for (SearchHit hit : scrollResp.getHits().getHits()) {
				totalIdList.add(hit.getId());
			}
			scrollResp = client.prepareSearchScroll(scrollResp.getScrollId()).setScroll(new TimeValue(60000))
					.execute().actionGet();
			// Break condition: No hits are returned
			if (scrollResp.getHits().getHits().length == 0) {
				break;
			}
		}

		totalRecords = totalIdList.size();
		logger.log(Level.INFO, "Found " + totalRecords + " for language " + language + " in index");

	} catch (IOException e) {
		e.printStackTrace();
		System.exit(1);
	}

	// System.exit(1);

}
 
Example #23
Source File: PrimitiveAnalysisEngine_impl.java    From uima-uimaj with Apache License 2.0 5 votes vote down vote up
public void collectionProcessComplete() throws AnalysisEngineProcessException {
  enterCollectionProcessComplete();
  UimaContext prevContext = setContextHolder();  // for use by POJOs
  try {
    getAnalysisComponent().collectionProcessComplete();
  } finally {
    UimaContextHolder.setContext(prevContext);
    exitCollectionProcessComplete();
  }
}
 
Example #24
Source File: ActiveMQReader.java    From baleen with Apache License 2.0 5 votes vote down vote up
@Override
protected void doInitialize(final UimaContext context) throws ResourceInitializationException {
  try {
    consumer = activeMQ.createConsumer(endpoint, messageSelector);
  } catch (final JMSException e) {
    throw new ResourceInitializationException(e);
  }
}
 
Example #25
Source File: PosTagAnnotator.java    From bluima with Apache License 2.0 5 votes vote down vote up
@Override
public void initialize(UimaContext aContext)
		throws ResourceInitializationException {
	super.initialize(aContext);
	try {
		// Get OpenNLP POS Tagger, initialize with a model
		if (useTagdict)
			tagger = new PosTagger(modelFile, (Dictionary) null,
					new POSDictionary(tagdict, caseSensitive));
		else
			tagger = new PosTagger(modelFile, (Dictionary) null);
	} catch (Exception e) {
		throw new ResourceInitializationException(e);
	}
}
 
Example #26
Source File: StatsAnnotatorPlus.java    From bluima with Apache License 2.0 5 votes vote down vote up
@Override
public void initialize(UimaContext context)
        throws ResourceInitializationException {
    super.initialize(context);
    start = null;
    cnt = 0;
    threadMXBean = ManagementFactory.getThreadMXBean();
}
 
Example #27
Source File: WriteCoocurrencesToLoadfile3.java    From bluima with Apache License 2.0 5 votes vote down vote up
@Override
public void initialize(UimaContext context)
        throws ResourceInitializationException {
    super.initialize(context);
    try {
        LOG.info("writing LOAD DATA file to {}", outputFile);
        writer = new LoadDataFileWriter(new File(outputFile), "\t");
    } catch (Exception e) {
        throw new ResourceInitializationException(e);
    }
}
 
Example #28
Source File: PrintAbreviationsAnnotator.java    From bluima with Apache License 2.0 5 votes vote down vote up
@Override
public void initialize(UimaContext context)
        throws ResourceInitializationException {
    super.initialize(context);
    try {
        writer = new LoadDataFileWriter(new File("abrevs.loaddata"));
    } catch (IOException e) {
        throw new ResourceInitializationException(e);
    }
}
 
Example #29
Source File: UimaContextFactoryTest.java    From uima-uimafit with Apache License 2.0 5 votes vote down vote up
@Test
public void test() throws ResourceInitializationException {
  UimaContext context = UimaContextFactory
          .createUimaContext("myBoolean", true, "myBooleans", new Boolean[] { true, false, true,
              false }, "myFloat", 1.0f, "myFloats", new Float[] { 2.0f, 2.1f, 3.0f }, "myInt", 1,
                  "myInts", new Integer[] { 2, 3, 4 }, "myString", "yourString", "myStrings",
                  new String[] { "yourString1", "yourString2", "yourString3" });
  assertEquals(true, context.getConfigParameterValue("myBoolean"));
  Boolean[] myBooleans = (Boolean[]) context.getConfigParameterValue("myBooleans");
  assertEquals(4, myBooleans.length);
  assertEquals(true, myBooleans[0]);
  assertEquals(false, myBooleans[1]);
  assertEquals(true, myBooleans[2]);
  assertEquals(false, myBooleans[3]);

  assertEquals(1.0f, context.getConfigParameterValue("myFloat"));
  Float[] myFloats = (Float[]) context.getConfigParameterValue("myFloats");
  assertEquals(3, myFloats.length);
  assertEquals(2.0d, myFloats[0].doubleValue(), 0.001d);
  assertEquals(2.1d, myFloats[1].doubleValue(), 0.001d);
  assertEquals(3.0d, myFloats[2].doubleValue(), 0.001d);

  assertEquals(1, context.getConfigParameterValue("myInt"));
  Integer[] myInts = (Integer[]) context.getConfigParameterValue("myInts");
  assertEquals(3, myInts.length);
  assertEquals(2L, myInts[0].longValue());
  assertEquals(3L, myInts[1].longValue());
  assertEquals(4L, myInts[2].longValue());

  assertEquals("yourString", context.getConfigParameterValue("myString"));
  String[] myStrings = (String[]) context.getConfigParameterValue("myStrings");
  assertEquals(3, myStrings.length);
  assertEquals("yourString1", myStrings[0]);
  assertEquals("yourString2", myStrings[1]);
  assertEquals("yourString3", myStrings[2]);

}
 
Example #30
Source File: AbstractRdfDocumentGraphConsumer.java    From baleen with Apache License 2.0 5 votes vote down vote up
@Override
public void doInitialize(UimaContext aContext) throws ResourceInitializationException {
  outputDocument = true;

  try {
    TypeSystem typeSystem = JCasFactory.createJCas().getTypeSystem();
    OwlSchemaFactory schemaFactory =
        new OwlSchemaFactory(namespace, typeSystem, Arrays.asList(ignoreProperties));
    documentOntology = schemaFactory.createDocumentOntology();
  } catch (CASRuntimeException | UIMAException e) {
    throw new ResourceInitializationException(e);
  }
  super.doInitialize(aContext);
}