You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@uima.apache.org by sc...@apache.org on 2008/01/08 15:38:51 UTC
svn commit: r610003 [4/7] - in
/incubator/uima/sandbox/trunk/uima-ee/uimaj-ee-core/src: ./ main/
main/java/ main/java/org/ main/java/org/apache/ main/java/org/apache/uima/
main/java/org/apache/uima/aae/ main/java/org/apache/uima/aae/client/
main/java/o...
Added: incubator/uima/sandbox/trunk/uima-ee/uimaj-ee-core/src/main/java/org/apache/uima/aae/controller/PrimitiveAnalysisEngineController_impl.java
URL: http://svn.apache.org/viewvc/incubator/uima/sandbox/trunk/uima-ee/uimaj-ee-core/src/main/java/org/apache/uima/aae/controller/PrimitiveAnalysisEngineController_impl.java?rev=610003&view=auto
==============================================================================
--- incubator/uima/sandbox/trunk/uima-ee/uimaj-ee-core/src/main/java/org/apache/uima/aae/controller/PrimitiveAnalysisEngineController_impl.java (added)
+++ incubator/uima/sandbox/trunk/uima-ee/uimaj-ee-core/src/main/java/org/apache/uima/aae/controller/PrimitiveAnalysisEngineController_impl.java Tue Jan 8 06:38:38 2008
@@ -0,0 +1,594 @@
+package org.apache.uima.aae.controller;
+
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Map;
+
+import javax.management.ObjectName;
+
+import org.apache.uima.UIMAFramework;
+import org.apache.uima.aae.AsynchAECasManager;
+import org.apache.uima.aae.InProcessCache;
+import org.apache.uima.aae.UIMAEE_Constants;
+import org.apache.uima.aae.UimaSerializer;
+import org.apache.uima.aae.InProcessCache.CacheEntry;
+import org.apache.uima.aae.error.AsynchAEException;
+import org.apache.uima.aae.error.ErrorContext;
+import org.apache.uima.aae.error.ErrorHandler;
+import org.apache.uima.aae.jmx.JmxManagement;
+import org.apache.uima.aae.jmx.JmxManager;
+import org.apache.uima.aae.jmx.PrimitiveServiceInfo;
+import org.apache.uima.aae.message.AsynchAEMessage;
+import org.apache.uima.aae.message.MessageContext;
+import org.apache.uima.aae.monitor.Monitor;
+import org.apache.uima.aae.monitor.statistics.ComponentStatistics;
+import org.apache.uima.aae.monitor.statistics.LongNumericStatistic;
+import org.apache.uima.aae.monitor.statistics.Statistic;
+import org.apache.uima.aae.monitor.statistics.Statistics;
+import org.apache.uima.analysis_engine.AnalysisEngine;
+import org.apache.uima.analysis_engine.CasIterator;
+import org.apache.uima.analysis_engine.metadata.AnalysisEngineMetaData;
+import org.apache.uima.cas.CAS;
+import org.apache.uima.cas.impl.CASImpl;
+import org.apache.uima.cas.impl.OutOfTypeSystemData;
+import org.apache.uima.cas.impl.XmiSerializationSharedData;
+import org.apache.uima.resource.metadata.ConfigurationParameter;
+import org.apache.uima.resource.metadata.impl.ConfigurationParameter_impl;
+import org.apache.uima.util.Level;
+
+public class PrimitiveAnalysisEngineController_impl
+extends BaseAnalysisEngineController implements PrimitiveAnalysisEngineController
+{
+ private static final Class CLASS_NAME = PrimitiveAnalysisEngineController_impl.class;
+
+ private AnalysisEngineMetaData analysisEngineMetadata;
+
+ private ControllerLatch latch = new ControllerLatch();
+
+ private int analysisEnginePoolSize;
+
+ protected Object notifyObj = new Object();
+
+ private List aeList = new ArrayList();
+
+ private List cmOutstandingCASes = new ArrayList();
+
+ private int throttleWindow = 0;
+
+ private Object gater = new Object();
+
+ private long howManyBeforeReplySeen = 0;
+
+ private boolean isMultiplier = false;
+
+ private Object syncObject = new Object();
+
+ private PrimitiveServiceInfo serviceInfo = null;
+
+ private AnalysisEngineInstancePool aeInstancePool = null;
+
+ private String abortedCASReferenceId = null;
+
+ public PrimitiveAnalysisEngineController_impl(String anEndpointName, String anAnalysisEngineDescriptor, AsynchAECasManager aCasManager, InProcessCache anInProcessCache, int aWorkQueueSize, int anAnalysisEnginePoolSize) throws Exception
+ {
+ this(null, anEndpointName, anAnalysisEngineDescriptor, aCasManager, anInProcessCache, aWorkQueueSize, anAnalysisEnginePoolSize, 0);
+ }
+
+ public PrimitiveAnalysisEngineController_impl(AnalysisEngineController aParentController, String anEndpointName, String anAnalysisEngineDescriptor, AsynchAECasManager aCasManager, InProcessCache anInProcessCache, int aWorkQueueSize, int anAnalysisEnginePoolSize) throws Exception
+ {
+ this(aParentController, anEndpointName, anAnalysisEngineDescriptor, aCasManager, anInProcessCache, aWorkQueueSize, anAnalysisEnginePoolSize, 0);
+ }
+
+ public PrimitiveAnalysisEngineController_impl(AnalysisEngineController aParentController, String anEndpointName, String anAnalysisEngineDescriptor, AsynchAECasManager aCasManager, InProcessCache anInProcessCache, int aWorkQueueSize, int anAnalysisEnginePoolSize, int aComponentCasPoolSize) throws Exception
+ {
+ this(aParentController, anEndpointName, anAnalysisEngineDescriptor, aCasManager, anInProcessCache, aWorkQueueSize, anAnalysisEnginePoolSize, aComponentCasPoolSize, null);
+ }
+
+ public PrimitiveAnalysisEngineController_impl(AnalysisEngineController aParentController, String anEndpointName, String anAnalysisEngineDescriptor, AsynchAECasManager aCasManager, InProcessCache anInProcessCache, int aWorkQueueSize, int anAnalysisEnginePoolSize, int aComponentCasPoolSize, long anInitialCasHeapSize) throws Exception
+ {
+ this(aParentController, anEndpointName, anAnalysisEngineDescriptor, aCasManager, anInProcessCache, aWorkQueueSize, anAnalysisEnginePoolSize, aComponentCasPoolSize, anInitialCasHeapSize, null);
+ }
+
+// public PrimitiveAnalysisEngineController_impl(AnalysisEngineController aParentController, String anEndpointName, String anAnalysisEngineDescriptor, AsynchAECasManager aCasManager, InProcessCache anInProcessCache, int aWorkQueueSize, int anAnalysisEnginePoolSize, int aComponentCasPoolSize, long anInitialCasHeapSize) throws Exception
+// {
+// this(aParentController, anEndpointName, anAnalysisEngineDescriptor, aCasManager, anInProcessCache, aWorkQueueSize, anAnalysisEnginePoolSize, aComponentCasPoolSize, null);
+// }
+ public PrimitiveAnalysisEngineController_impl(AnalysisEngineController aParentController, String anEndpointName, String anAnalysisEngineDescriptor, AsynchAECasManager aCasManager, InProcessCache anInProcessCache, int aWorkQueueSize, int anAnalysisEnginePoolSize, int aComponentCasPoolSize, JmxManagement aJmxManagement) throws Exception
+ {
+ this(aParentController, anEndpointName, anAnalysisEngineDescriptor, aCasManager, anInProcessCache, aWorkQueueSize, anAnalysisEnginePoolSize, aComponentCasPoolSize,0, aJmxManagement);
+ }
+ public PrimitiveAnalysisEngineController_impl(AnalysisEngineController aParentController, String anEndpointName, String anAnalysisEngineDescriptor, AsynchAECasManager aCasManager, InProcessCache anInProcessCache, int aWorkQueueSize, int anAnalysisEnginePoolSize, int aComponentCasPoolSize, long anInitialCasHeapSize, JmxManagement aJmxManagement) throws Exception
+ {
+ super(aParentController, aComponentCasPoolSize, anInitialCasHeapSize, anEndpointName, anAnalysisEngineDescriptor, aCasManager, anInProcessCache, null, aJmxManagement);
+ analysisEnginePoolSize = anAnalysisEnginePoolSize;
+ }
+ public PrimitiveAnalysisEngineController_impl(AnalysisEngineController aParentController, String anEndpointName, String anAnalysisEngineDescriptor, AsynchAECasManager aCasManager, InProcessCache anInProcessCache, int aWorkQueueSize, int anAnalysisEnginePoolSize, JmxManagement aJmxManagement) throws Exception
+ {
+ this(aParentController, anEndpointName, anAnalysisEngineDescriptor, aCasManager, anInProcessCache, aWorkQueueSize, anAnalysisEnginePoolSize, 0, aJmxManagement);
+ }
+
+ public void initialize() throws AsynchAEException
+ {
+ try
+ {
+
+ if (errorHandlerChain == null)
+ {
+ super.plugInDefaultErrorHandlerChain();
+ }
+
+ if ( aeInstancePool == null )
+ {
+ aeInstancePool = new AnalysisEngineInstancePoolWithThreadAffinity(analysisEnginePoolSize);
+ }
+
+ UIMAFramework.getLogger(CLASS_NAME).logrb(Level.CONFIG, getClass().getName(), "initialize", UIMAEE_Constants.JMS_LOG_RESOURCE_BUNDLE, "UIMAEE_primitive_ctrl_init_info__CONFIG", new Object[] { analysisEnginePoolSize });
+
+ for (int i = 0; i < analysisEnginePoolSize; i++)
+ {
+ AnalysisEngine ae = UIMAFramework.produceAnalysisEngine(resourceSpecifier, paramsMap);
+ aeList.add(ae);
+
+ // Cache metadata once
+ if (i == 0)
+ {
+ analysisEngineMetadata = ae.getAnalysisEngineMetaData();
+ if ( analysisEngineMetadata.getOperationalProperties().getOutputsNewCASes())
+ {
+ isMultiplier = true;
+ }
+ }
+ }
+
+ if ( serviceInfo == null )
+ {
+ serviceInfo = new PrimitiveServiceInfo();
+ }
+
+ serviceInfo.setAnalysisEngineInstanceCount(analysisEnginePoolSize);
+ aeInstancePool.intialize(aeList);
+
+
+ getMonitor().setThresholds(getErrorHandlerChain().getThresholds());
+// Statistics stats = getMonitor().getStatistics("");
+// ComponentStatistics componentStatistics = new ComponentStatistics(stats);
+ // Initialize Cas Manager
+ if (getCasManagerWrapper() != null)
+ {
+ try
+ {
+ if (getCasManagerWrapper().isInitialized())
+ {
+ getCasManagerWrapper().addMetadata(getAnalysisEngineMetadata());
+ if (isTopLevelComponent())
+ {
+ getCasManagerWrapper().initialize("PrimitiveAEService");
+ }
+ }
+
+ // All internal components of this Primitive have been initialized. Open the latch
+ // so that this service can start processing requests.
+ latch.openLatch(getName(), isTopLevelComponent(), true);
+
+ }
+ catch ( Exception e)
+ {
+ e.printStackTrace();
+ throw new AsynchAEException(e);
+ }
+ }
+ else
+ {
+ UIMAFramework.getLogger(CLASS_NAME).logrb(Level.CONFIG, getClass().getName(), "initialize", UIMAEE_Constants.JMS_LOG_RESOURCE_BUNDLE, "UIMAEE_cas_manager_wrapper_notdefined__CONFIG", new Object[] {});
+ }
+
+ }
+ catch ( AsynchAEException e)
+ {
+ throw e;
+ }
+ catch ( Exception e)
+ {
+ throw new AsynchAEException(e);
+ }
+
+ UIMAFramework.getLogger(CLASS_NAME).logrb(Level.INFO, CLASS_NAME.getName(), "initialize", UIMAEE_Constants.JMS_LOG_RESOURCE_BUNDLE, "UIMAEE_initialized_controller__INFO", new Object[] { getComponentName() });
+
+ }
+ public boolean isMultiplier()
+ {
+ return isMultiplier;
+ }
+
+ /**
+ *
+ */
+ public void collectionProcessComplete(Endpoint anEndpoint)// throws AsynchAEException
+ {
+ AnalysisEngine ae = null;
+
+ try
+ {
+ ae = aeInstancePool.checkout();
+ if ( ae != null)
+ {
+ ae.collectionProcessComplete();
+ }
+ UIMAFramework.getLogger(CLASS_NAME).logrb(Level.FINEST, getClass().getName(), "collectionProcessComplete", UIMAEE_Constants.JMS_LOG_RESOURCE_BUNDLE, "UIMAEE_cpc_all_cases_processed__FINEST", new Object[] { getComponentName() });
+ getOutputChannel().sendReply(AsynchAEMessage.CollectionProcessComplete, anEndpoint);
+ UIMAFramework.getLogger(CLASS_NAME).logrb(Level.FINE, getClass().getName(), "collectionProcessComplete", UIMAEE_Constants.JMS_LOG_RESOURCE_BUNDLE, "UIMAEE_cpc_completed__FINE", new Object[] { getComponentName()});
+ }
+ catch ( Exception e)
+ {
+// UIMAFramework.getLogger(CLASS_NAME).logrb(Level.WARNING, getClass().getName(), "collectionProcessComplete", UIMAEE_Constants.JMS_LOG_RESOURCE_BUNDLE, "UIMAEE_exception__WARNING", new Object[] { e });
+ ErrorContext errorContext = new ErrorContext();
+ errorContext.add(AsynchAEMessage.Command, AsynchAEMessage.CollectionProcessComplete);
+ errorContext.add(AsynchAEMessage.Endpoint, anEndpoint);
+ getErrorHandlerChain().handle(e, errorContext, this);
+ }
+ finally
+ {
+ clearStats();
+ }
+ }
+
+ private void rejectAndReturnInputCAS(String aCasReferenceId, Endpoint anEndpoint)
+ {
+ if ( getInProcessCache() != null )
+ {
+ try
+ {
+ // Set a flag on the input CAS to indicate that the processing was aborted
+ getInProcessCache().getCacheEntryForCAS(aCasReferenceId).setAborted(true);
+ getOutputChannel().sendReply(aCasReferenceId, anEndpoint);
+ }
+ catch( Exception e)
+ {
+ e.printStackTrace();
+ UIMAFramework.getLogger(CLASS_NAME).logrb(Level.WARNING, getClass().getName(), "rejectAndReturnInputCAS", UIMAEE_Constants.JMS_LOG_RESOURCE_BUNDLE, "UIMAEE_exception__WARNING", new Object[] { e });
+ }
+ }
+
+ }
+ public void addAbortedCasReferenceId( String aCasReferenceId )
+ {
+ abortedCASReferenceId = aCasReferenceId;
+ }
+ private boolean abortGeneratingCASes( String aCasReferenceId )
+ {
+ return ( aCasReferenceId.equals(abortedCASReferenceId));
+ }
+ public void process(CAS aCAS, String aCasReferenceId, Endpoint anEndpoint)// throws AnalysisEngineProcessException, AsynchAEException
+ {
+
+ if ( stopped )
+ {
+// Abort rejectAndReturnInputCAS(aCasReferenceId, anEndpoint);
+ return;
+ }
+
+ boolean processingFailed = false;
+ // This is a primitive controller. No more processing is to be done on the Cas. Mark the destination as final and return CAS in reply.
+ anEndpoint.setFinal(true);
+ AnalysisEngine ae = null;
+ try
+ {
+ // Use empty string as key. Top level component stats are stored under this key.
+// getMonitor().incrementCount("", Monitor.ProcessCount);
+
+ // Checkout an instance of AE from the pool
+ ae = aeInstancePool.checkout();
+
+ if ( ae == null )
+ {
+ // This block just logs the CAS that cannot be processed
+ try
+ {
+ XmiSerializationSharedData serSharedData = new XmiSerializationSharedData();
+ String serializedCas = UimaSerializer.serializeCasToXmi(aCAS, serSharedData);
+ UIMAFramework.getLogger(CLASS_NAME).logrb(Level.FINEST, getClass().getName(), "process", UIMAEE_Constants.JMS_LOG_RESOURCE_BUNDLE, "UIMAEE_dump_cas__FINEST", new Object[] { serializedCas });
+ }
+ catch( Exception e )
+ {
+ // ignore exceptions. This block just logs the CAS
+ }
+ UIMAFramework.getLogger(CLASS_NAME).logrb(Level.WARNING, getClass().getName(), "process", UIMAEE_Constants.JMS_LOG_RESOURCE_BUNDLE, "UIMAEE_dropping_cas_dueto_no_ae__WARNING", new Object[] { getComponentName(), aCasReferenceId});
+
+ return;
+ }
+ long time = System.nanoTime();
+
+ CasIterator casIterator = ae.processAndOutputNewCASes(aCAS);
+ long sequence = 1;
+ String newCasReferenceId = null;
+ while (casIterator.hasNext())
+ {
+ CAS casProduced = casIterator.next();
+ // If the service is stopped or aborted, stop generating new CASes and just return the input CAS
+ if ( stopped || abortGeneratingCASes(aCasReferenceId))
+ {
+ if ( getInProcessCache() != null )
+ {
+ // Set a flag on the input CAS to indicate that the processing was aborted
+ getInProcessCache().getCacheEntryForCAS(aCasReferenceId).setAborted(true);
+
+ // !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
+ // We are terminating the iterator here, release the internal CAS lock
+ // so that we can release the CAS. This approach may need to be changed
+ // as there may potentially be a problem with a Class Loader.
+ // !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
+ ((CASImpl)aCAS).enableReset(true);
+ }
+ return;
+// break;
+ }
+ OutOfTypeSystemData otsd = getInProcessCache().getOutOfTypeSystemData(aCasReferenceId);
+ MessageContext mContext = getInProcessCache().getMessageAccessorByReference(aCasReferenceId);
+ newCasReferenceId = getInProcessCache().register(casProduced, mContext, otsd);
+ CacheEntry entry = getInProcessCache().getCacheEntryForCAS(newCasReferenceId);
+ entry.setInputCasReferenceId(aCasReferenceId);
+ UIMAFramework.getLogger(CLASS_NAME).logrb(Level.FINE, getClass().getName(), "process", UIMAEE_Constants.JMS_LOG_RESOURCE_BUNDLE, "UIMAEE_produced_new_cas__FINE", new Object[] { Thread.currentThread().getName(),getComponentName(),newCasReferenceId, aCasReferenceId });
+ synchronized(syncObject)
+ {
+ cmOutstandingCASes.add(newCasReferenceId);
+ getOutputChannel().sendReply(casProduced, aCasReferenceId, newCasReferenceId, anEndpoint, sequence++);
+ }
+ }
+
+ LongNumericStatistic statistic = null;
+ if ( (statistic = getMonitor().getLongNumericStatistic("",Monitor.TotalAEProcessTime)) != null )
+ {
+ statistic.increment(System.nanoTime() - time);
+ }
+
+ if (newCasReferenceId != null)
+ {
+ UIMAFramework.getLogger(CLASS_NAME).logrb(Level.FINEST, getClass().getName(), "process", UIMAEE_Constants.JMS_LOG_RESOURCE_BUNDLE, "UIMAEE_completed_analysis__FINEST", new Object[] { Thread.currentThread().getName(), getComponentName(), newCasReferenceId, (double) (System.nanoTime() - time) / (double) 1000000 });
+ }
+ else
+ {
+ UIMAFramework.getLogger(CLASS_NAME).logrb(Level.FINEST, getClass().getName(), "process", UIMAEE_Constants.JMS_LOG_RESOURCE_BUNDLE, "UIMAEE_completed_analysis__FINEST", new Object[] { Thread.currentThread().getName(), getComponentName(), aCasReferenceId, (double) (System.nanoTime() - time) / (double) 1000000 });
+
+ }
+ getMonitor().resetCountingStatistic("", Monitor.ProcessErrorCount);
+
+ getOutputChannel().sendReply(aCasReferenceId, anEndpoint);
+ getServicePerformance().incrementNumberOfCASesProcessed();
+ }
+ catch ( Throwable e)
+ {
+ processingFailed = true;
+ ErrorContext errorContext = new ErrorContext();
+ errorContext.add(AsynchAEMessage.CasReference, aCasReferenceId);
+ errorContext.add(AsynchAEMessage.Command, AsynchAEMessage.Process);
+ errorContext.add(AsynchAEMessage.MessageType, AsynchAEMessage.Request);
+ errorContext.add(AsynchAEMessage.Endpoint, anEndpoint);
+ // Handle the exception. Pass reference to the PrimitiveController instance
+ getErrorHandlerChain().handle(e, errorContext, this);
+ }
+ finally
+ {
+ if ( ae != null )
+ {
+ try
+ {
+ aeInstancePool.checkin(ae);
+ }
+ catch( Exception e)
+ {
+ e.printStackTrace();
+ }
+ }
+ // drop the CAS if it has been successfully processed. If there was a failure, the Error Handler
+ // will drop the CAS
+ if ( isTopLevelComponent() && !processingFailed)
+ {
+ // Release CASes produced from the input CAS if the input CAS has been aborted
+ if ( abortGeneratingCASes(aCasReferenceId) )
+ {
+
+ UIMAFramework.getLogger(CLASS_NAME).logrb(Level.INFO, CLASS_NAME.getName(),
+ "process", UIMAEE_Constants.JMS_LOG_RESOURCE_BUNDLE, "UIMAEE_remove_cache_entry__INFO",
+ new Object[] { getComponentName(), aCasReferenceId });
+
+ getInProcessCache().releaseCASesProducedFromInputCAS(aCasReferenceId);
+ }
+ else
+ {
+ synchronized (getInProcessCache())
+ {
+ dropCAS(aCasReferenceId, true);
+ }
+ }
+ }
+ }
+ }
+ private void addConfigIntParameter( String aParamName, int aParamValue)
+ {
+ ConfigurationParameter cp = new ConfigurationParameter_impl();
+ cp.setMandatory(false);
+ cp.setMultiValued(false);
+ cp.setName(aParamName);
+ cp.setType("Integer");
+ getAnalysisEngineMetadata().getConfigurationParameterDeclarations().addConfigurationParameter(cp);
+ getAnalysisEngineMetadata().getConfigurationParameterSettings().setParameterValue(aParamName, aParamValue);
+
+ }
+ // Return metadata
+ public void sendMetadata(Endpoint anEndpoint) throws AsynchAEException
+ {
+ addConfigIntParameter(AnalysisEngineController.AEInstanceCount, analysisEnginePoolSize);
+
+
+ if ( getAnalysisEngineMetadata().getOperationalProperties().getOutputsNewCASes() )
+ {
+ addConfigIntParameter(AnalysisEngineController.CasPoolSize, super.componentCasPoolSize);
+
+/*
+ ConfigurationParameter cp = new ConfigurationParameter_impl();
+ cp.setMandatory(false);
+ cp.setMultiValued(false);
+ cp.setName(AnalysisEngineController.CasPoolSize);
+ cp.setType("Integer");
+ getAnalysisEngineMetadata().getConfigurationParameterDeclarations().addConfigurationParameter(cp);
+ getAnalysisEngineMetadata().getConfigurationParameterSettings().setParameterValue(AnalysisEngineController.CasPoolSize, super.componentCasPoolSize);
+ */
+ }
+ getOutputChannel().sendReply(getAnalysisEngineMetadata(), anEndpoint, true);
+ }
+
+ private AnalysisEngineMetaData getAnalysisEngineMetadata()
+ {
+ return analysisEngineMetadata;
+ }
+
+ /**
+ * Executes action on error. Primitive Controller allows two types of actions TERMINATE and DROPCAS.
+ */
+ public void takeAction(String anAction, String anEndpointName, ErrorContext anErrorContext)
+ {
+ try
+ {
+ if (ErrorHandler.TERMINATE.equalsIgnoreCase(anAction) || ErrorHandler.DROPCAS.equalsIgnoreCase(anAction))
+ {
+ super.handleAction(anAction, anEndpointName, anErrorContext);
+ }
+ }
+ catch ( Exception e)
+ {
+ e.printStackTrace();
+ UIMAFramework.getLogger(CLASS_NAME).logrb(Level.WARNING, getClass().getName(), "takeAction", UIMAEE_Constants.JMS_LOG_RESOURCE_BUNDLE, "UIMAEE_exception__WARNING", new Object[] { e });
+ }
+ }
+
+ public String getServiceEndpointName()
+ {
+ return getName();
+ }
+
+ public ControllerLatch getControllerLatch()
+ {
+ return latch;
+ }
+
+ public boolean isPrimitive()
+ {
+ return true;
+ }
+
+ public Monitor getMonitor()
+ {
+ return super.monitor;
+ }
+
+ public void setMonitor(Monitor monitor)
+ {
+ this.monitor = monitor;
+ }
+
+ public void handleDelegateLifeCycleEvent( String anEndpoint, int aDelegateCount)
+ {
+ if ( aDelegateCount == 0 )
+ {
+ // tbi
+ }
+ }
+
+ public int getThrottleWindowSize()
+ {
+ return throttleWindow;
+ }
+
+
+ public void throttleNext()
+ {
+ if (throttleWindow > 0)
+ {
+ synchronized (gater)
+ {
+ howManyBeforeReplySeen--;
+ gater.notifyAll();
+ }
+ }
+ }
+
+
+
+
+ protected String getNameFromMetadata()
+ {
+ return super.getMetaData().getName();
+ }
+ public void releaseNextCas()
+ {
+ synchronized(syncObject)
+ {
+ if ( cmOutstandingCASes.size() > 0 )
+ {
+ try
+ {
+ String casReferenceId = (String)cmOutstandingCASes.remove(0);
+ UIMAFramework.getLogger(CLASS_NAME).logrb(Level.FINE, CLASS_NAME.getName(),
+ "releaseNextCas", UIMAEE_Constants.JMS_LOG_RESOURCE_BUNDLE, "UIMAEE_release_cas_req__FINE",
+ new Object[] { getName(), casReferenceId });
+ if ( casReferenceId != null && getInProcessCache().entryExists(casReferenceId))
+ {
+ dropCAS(casReferenceId, true);
+ }
+ }
+ catch( Exception e)
+ {
+ UIMAFramework.getLogger(CLASS_NAME).logrb(Level.WARNING, CLASS_NAME.getName(),
+ "releaseNextCas", UIMAEE_Constants.JMS_LOG_RESOURCE_BUNDLE, "UIMAEE_exception__WARNING",
+ new Object[] { e});
+ }
+ }
+ }
+ }
+
+ public void setAnalysisEngineInstancePool( AnalysisEngineInstancePool aPool)
+ {
+ aeInstancePool = aPool;
+ }
+
+ public PrimitiveServiceInfo getServiceInfo()
+ {
+ if ( serviceInfo == null )
+ {
+ serviceInfo = new PrimitiveServiceInfo();
+ }
+ if ( getInputChannel() != null )
+ {
+ serviceInfo.setInputQueueName(getInputChannel().getServiceInfo().getInputQueueName());
+ serviceInfo.setBrokerURL(getInputChannel().getServiceInfo().getBrokerURL());
+ }
+
+ serviceInfo.setState("Running");
+ return serviceInfo;
+ }
+
+ public void stop()
+ {
+ super.stop();
+ stopInputChannel();
+ if ( aeInstancePool != null )
+ {
+ try
+ {
+ aeInstancePool.destroy();
+ }
+ catch( Exception e){ e.printStackTrace();}
+ }
+ if ( cmOutstandingCASes != null )
+ {
+ cmOutstandingCASes.clear();
+ cmOutstandingCASes = null;
+ }
+ if ( aeList != null )
+ {
+ aeList.clear();
+ aeList = null;
+ }
+ }
+ private static final String copyright = com.ibm.uima.copyright.Copyright.COPYRIGHT;
+}
Added: incubator/uima/sandbox/trunk/uima-ee/uimaj-ee-core/src/main/java/org/apache/uima/aae/controller/PrimitiveAnalysisEngineController_implMBean.java
URL: http://svn.apache.org/viewvc/incubator/uima/sandbox/trunk/uima-ee/uimaj-ee-core/src/main/java/org/apache/uima/aae/controller/PrimitiveAnalysisEngineController_implMBean.java?rev=610003&view=auto
==============================================================================
--- incubator/uima/sandbox/trunk/uima-ee/uimaj-ee-core/src/main/java/org/apache/uima/aae/controller/PrimitiveAnalysisEngineController_implMBean.java (added)
+++ incubator/uima/sandbox/trunk/uima-ee/uimaj-ee-core/src/main/java/org/apache/uima/aae/controller/PrimitiveAnalysisEngineController_implMBean.java Tue Jan 8 06:38:38 2008
@@ -0,0 +1,10 @@
+package org.apache.uima.aae.controller;
+
+import java.io.Serializable;
+
+public interface PrimitiveAnalysisEngineController_implMBean extends BaseAnalysisEngineControllerMBean
+{
+
+ public int getNumberOfAEInstances();
+
+}
Added: incubator/uima/sandbox/trunk/uima-ee/uimaj-ee-core/src/main/java/org/apache/uima/aae/controller/UimacppServiceController.java
URL: http://svn.apache.org/viewvc/incubator/uima/sandbox/trunk/uima-ee/uimaj-ee-core/src/main/java/org/apache/uima/aae/controller/UimacppServiceController.java?rev=610003&view=auto
==============================================================================
--- incubator/uima/sandbox/trunk/uima-ee/uimaj-ee-core/src/main/java/org/apache/uima/aae/controller/UimacppServiceController.java (added)
+++ incubator/uima/sandbox/trunk/uima-ee/uimaj-ee-core/src/main/java/org/apache/uima/aae/controller/UimacppServiceController.java Tue Jan 8 06:38:38 2008
@@ -0,0 +1,949 @@
+package org.apache.uima.aae.controller;
+
+import java.io.BufferedReader;
+import java.io.File;
+import java.io.IOException;
+import java.io.InputStreamReader;
+import java.net.ServerSocket;
+import java.net.Socket;
+import java.net.SocketTimeoutException;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
+import java.util.StringTokenizer;
+
+import javax.management.MalformedObjectNameException;
+import javax.management.ObjectName;
+
+import org.apache.uima.UIMAException;
+import org.apache.uima.UIMAFramework;
+import org.apache.uima.aae.jmx.JmxManagement;
+import org.apache.uima.internal.util.JmxMBeanAgent;
+import org.apache.uima.resource.ResourceInitializationException;
+import org.apache.uima.util.Level;
+
+/**
+ * This bean functions as a proxy for a Uima C++ service. It starts the Uima C++
+ * service given a UIMA descriptor, the input queue name, and environment
+ * settings required for the specific annotator and the Uima C++ runtime. On
+ * start up a socket connection is established between this instance of the
+ * proxy and the service. This connection is used for routing log message from
+ * the C++ service to the UIMA framework logger and to allow the proxy to send
+ * JMX and administrative requests such as shutdown.
+ *
+ *
+ *
+ */
+public class UimacppServiceController implements ControllerLifecycle {
+ protected ServerSocket server;
+
+ private int port;
+
+ private Socket loggerConnection;
+
+ private Socket commandConnection;
+
+ private Process uimacppProcess;
+
+ private LoggerHandler loggerHandler;
+
+ private StdoutHandler stdoutHandler;
+
+ private StderrHandler stderrHandler;
+
+ private ProcessBuilder builder;
+
+ private String aeDesc;
+
+ private String queueName;
+
+ private int numInstances;
+
+ private int processCasErrorThreshhold;
+
+ private int processCasErrorWindow;
+
+ private boolean terminateOnCPCError;
+
+ private org.apache.uima.util.Logger uimaLogger;
+
+ private UimacppServiceManagement mbean;
+
+ private JmxManagement jmxMgmt;
+
+ private UimacppShutdownHook shutdownHook;
+
+ private int initialFsHeapSize;
+
+ //private ControllerCallbackListener listener;
+
+ private List listeners = new ArrayList();
+
+ /**
+ * Configure and start a Uima C++ service that connects to an ActiveMG
+ * queue broker.
+ * This class initializes the process environment and starts a process
+ * to deploy the C++ service.
+ * Communication via sockets is established between this Controller and the
+ * C++ service through which logging, JMX and administrative messages are
+ * transmitted.
+ *
+ * @param aeDescriptorFileName -
+ * UIMA analysis engine descriptor file.
+ * @param queueName -
+ * input queue name
+ * @param brokerURL -
+ * queue broker URL
+ * @param numInstances -
+ * number of instance of AEs to start in the service.
+ * @param prefetchSize -
+ * number of message to prefetch
+ * @param envVarMap -
+ * enviroment variables to be set. These settings are valid only for
+ * the new process in which C++ service will run.
+ * @throws UIMAException
+ */
+ public UimacppServiceController(String aeDescriptorFileName,
+ String queueName, String brokerURL, int numInstances, int prefetchSize,
+ Map<String,String> envVarMap, int processCasErrorThreshhold, int processCasErrorWindow,
+ boolean terminateOnCPCError, int initialFsHeapSize) throws ResourceInitializationException {
+
+ try {
+ this.uimaLogger = UIMAFramework.getLogger(this.getClass());
+ this.aeDesc = aeDescriptorFileName;
+ this.numInstances = numInstances;
+ this.queueName = queueName;
+ this.processCasErrorThreshhold = processCasErrorThreshhold;
+ this.processCasErrorWindow = processCasErrorWindow;
+ this.terminateOnCPCError = terminateOnCPCError;
+ this.initialFsHeapSize = initialFsHeapSize;
+
+ /* start a listener */
+ server = new ServerSocket(0);
+ port = server.getLocalPort();
+ server.setSoTimeout(10000);
+
+ // System.out.println("Listening on port " + port);
+
+ /* setup the command */
+ ArrayList<String> commandArgs = new ArrayList<String>();
+ buildCommandArgs(commandArgs, envVarMap, "deployCppService");
+
+ if (brokerURL != null && brokerURL.length() > 0) {
+ commandArgs.add("-b");
+ commandArgs.add(brokerURL);
+ }
+
+ /* construct the process builder */
+ builder = new ProcessBuilder(commandArgs);
+ setEnvironmentVariables(envVarMap);
+
+ /* setup environment variables */
+
+ //System.out.println("Uima C++ Service " + aeDesc + " configured.");
+ //System.out.println("Listener started at port " + port + ".");
+ // System.out.println(builder.command().toString());
+ /* start the C++ service */
+ //try {
+ // start threads to accept two connections from the service
+
+ /* start the service */
+ startService();
+
+ /** register with JMX - for now register with the platform MBean server */
+ mbean = new UimacppServiceManagement("org.apache.uima:type=ee.jms.services",commandConnection, aeDesc,
+ numInstances, brokerURL, queueName);
+ JmxMBeanAgent.registerMBean(mbean, null);
+
+ // } catch (IOException e1) {
+ // e1.printStackTrace();
+ //}
+ } catch (IOException e) {
+ //e.printStackTrace();
+ throw new ResourceInitializationException(e);
+ } catch (UIMAException e) {
+ //e.printStackTrace();
+ throw new ResourceInitializationException(e);
+ }
+ }
+
+ public UimacppServiceController(String aeDescriptorFileName,
+ String queueName, String brokerURL, int numInstances, int prefetchSize,
+ Map<String,String> envVarMap, int processCasErrorThreshhold, int processCasErrorWindow,
+ boolean terminateOnCPCError) throws ResourceInitializationException {
+
+ this(aeDescriptorFileName,
+ queueName, brokerURL, numInstances, prefetchSize,
+ envVarMap, processCasErrorThreshhold, processCasErrorWindow,
+ terminateOnCPCError,0);
+
+ }
+
+ /**
+ * Configure and start a Uima C++ service that connects to an WebSphereMQ
+ * queue broker.
+ * This class initializes the process environment and starts a process
+ * to deploy the C++ service.
+ * Communication via sockets is established between this Controller and the
+ * C++ service through which logging, JMX and administrative messages are
+ * transmitted.
+ * @param uimaLogger
+ * @param aeDescriptorFileName
+ * @param mqQueueName
+ * @param mqHostName
+ * @param mqPort
+ * @param mqChannel
+ * @param mqQueueMgr
+ * @param numInstances
+ * @param envVarMap
+ * @param processCasErrorThreshhold
+ * @param processCasErrorWindow
+ * @param terminateOnCPCError
+ * @param mBeanServer
+ * @throws ResourceInitializationException
+ */
+ public UimacppServiceController(org.apache.uima.util.Logger uimaLogger,
+ String aeDescriptorFileName, String queueName, String mqHostName,
+ int mqPort, String mqChannel, String mqQueueMgr, int numInstances,
+ Map<String,String> envVarMap, int processCasErrorThreshhold, int processCasErrorWindow,
+ boolean terminateOnCPCError, JmxManagement jmxManagement,
+ int initialFsHeapSize)
+ throws ResourceInitializationException {
+
+ try {
+ this.uimaLogger = UIMAFramework.getLogger(this.getClass());
+ this.aeDesc = aeDescriptorFileName;
+ this.numInstances = numInstances;
+ this.queueName = queueName;
+ this.processCasErrorThreshhold = processCasErrorThreshhold;
+ this.processCasErrorWindow = processCasErrorWindow;
+ this.terminateOnCPCError = terminateOnCPCError;
+ this.initialFsHeapSize = initialFsHeapSize;
+ this.jmxMgmt = jmxManagement;
+
+ /* start a listener */
+ server = new ServerSocket(0);
+ port = server.getLocalPort();
+ server.setSoTimeout(10000);
+
+ // System.out.println("Listening on port " + port);
+ /* setup the command */
+ ArrayList<String> commandArgs = new ArrayList<String>();
+ buildCommandArgs(commandArgs, envVarMap, "deployWMQCppService");
+
+ //add MQ specific args
+ if (mqHostName != null && mqHostName.length() > 0) {
+ commandArgs.add("-mqh");
+ commandArgs.add(mqHostName);
+ }
+
+ commandArgs.add("-mqp");
+ commandArgs.add(Integer.toString(mqPort));
+
+ if (mqChannel != null && mqChannel.length() > 0) {
+ commandArgs.add("-mqc");
+ commandArgs.add(mqChannel);
+ }
+
+ if (mqQueueMgr != null && mqQueueMgr.length() > 0) {
+ commandArgs.add("-mqm");
+ commandArgs.add(mqQueueMgr);
+ }
+
+ /* construct the process builder */
+ builder = new ProcessBuilder(commandArgs);
+ setEnvironmentVariables(envVarMap);
+
+ //System.out.println("Uima C++ Service " + aeDesc + " configured.");
+ //System.out.println("Listener started at port " + port + ".");
+ // System.out.println(builder.command().toString());
+
+ /* start the service */
+ startService();
+
+ mbean = new UimacppServiceManagement(null, commandConnection, aeDesc,
+ numInstances, mqHostName + " " + mqPort + "//" + mqQueueMgr,
+ "queue://" +/* mqChannel +*/ "/" + queueName);
+
+ /** register with JMX */
+
+ if (jmxManagement == null ) {
+ throw new ResourceInitializationException( new IOException("JmxManagement object is null."));
+ }
+
+ if (jmxManagement instanceof JmxManagement) {
+ mbean = new UimacppServiceManagement(jmxManagement.getJmxDomain(), commandConnection, aeDesc,
+ numInstances, mqHostName + " " + mqPort + "//" + mqQueueMgr,
+ queueName);
+ ObjectName oname = new ObjectName(mbean.getUniqueMBeanName());
+ jmxManagement.registerMBean(mbean, oname);
+ } else {
+ uimaLogger.log(Level.WARNING,"UimacppServiceController failed to register the JMX MBean.");
+ //throw new ResourceInitializationException( new IOException("JmxManagement object is invalid."));
+ }
+
+ } catch (IOException e) {
+ throw new ResourceInitializationException(e);
+ } catch (UIMAException e) {
+ throw new ResourceInitializationException(e);
+ } catch (MalformedObjectNameException e) {
+ throw new ResourceInitializationException(e);
+ } catch (NullPointerException e) {
+ throw new ResourceInitializationException(e);
+ } catch (Exception e) {
+ throw new ResourceInitializationException(e);
+ }
+ }
+
+ private void buildCommandArgs(ArrayList<String> commandArgs,
+ Map<String,String> envVarMap,
+ String exeName)
+ throws ResourceInitializationException {
+
+ String uimacppHome = (String) envVarMap.get("UIMACPP_HOME");
+ if (uimacppHome == null) {
+ // throw new ResourceInitializationException(new IOException(
+ // "UIMACPP_HOME not specified." + uimacppHome));
+ uimacppHome = System.getenv("UIMA_HOME") + "/uimacpp";
+ }
+
+ if (!(new File(uimacppHome)).exists()) {
+ throw new ResourceInitializationException(new IOException(
+ "Invalid location of UIMACPP_HOME " + uimacppHome));
+ }
+
+ // the Uima C++ service wrapper exe
+ String cmd = uimacppHome + System.getProperty("file.separator") + "bin"
+ + System.getProperty("file.separator") + exeName;
+
+ commandArgs.add(cmd);
+
+ // arguments
+ // UIMA AE descriptor
+ commandArgs.add(aeDesc);
+ if (!(new File(aeDesc)).exists()) {
+ throw new ResourceInitializationException(new IOException(
+ "Invalid location of AE descriptor " + aeDesc));
+ }
+
+ // input queue name
+ commandArgs.add(queueName);
+
+ // port this server is listening at
+ commandArgs.add("-jport");
+ commandArgs.add(Integer.toString(port));
+
+ // number of instances of consumers the
+ // service should start
+ commandArgs.add("-n");
+ if (numInstances < 1) {
+ numInstances = 1;
+ }
+ commandArgs.add(Integer.toString(numInstances));
+
+ // logging level setting obtained from the UIMA framework
+ // translated to UIMA C++ logging levels.
+ commandArgs.add("-l");
+ if (uimaLogger.isLoggable(Level.FINE)
+ || uimaLogger.isLoggable(Level.CONFIG)
+ || uimaLogger.isLoggable(Level.FINER)
+ || uimaLogger.isLoggable(Level.FINEST)
+ || uimaLogger.isLoggable(Level.INFO)) {
+ commandArgs.add(Integer.toString(0));
+ } else if (uimaLogger.isLoggable(Level.WARNING)) {
+ commandArgs.add(Integer.toString(1));
+ } else if (uimaLogger.isLoggable(Level.SEVERE)) {
+ commandArgs.add(Integer.toString(2));
+ } else {
+ commandArgs.add(Integer.toString(-1));
+ }
+
+ // translate logger level to trace level 0-4.
+ // set based Level = CONFIG, INFO, FINE, FINER, FINEST...
+ commandArgs.add("-t");
+ if (uimaLogger.isLoggable(Level.FINEST)) {
+ commandArgs.add(Integer.toString(3));
+ } else if (uimaLogger.isLoggable(Level.FINER)) {
+ commandArgs.add(Integer.toString(2));
+ } else if (uimaLogger.isLoggable(Level.FINE)) {
+ commandArgs.add(Integer.toString(1));
+ } else if (uimaLogger.isLoggable(Level.CONFIG)) {
+ commandArgs.add(Integer.toString(0));
+ } else {
+ commandArgs.add(Integer.toString(-1));
+ }
+ // data directory used to resolve location of
+ // files used by annotator.
+ String uimacppDataPath = (String) envVarMap.get("UIMACPP_DATAPATH");
+ if (uimacppDataPath != null && uimacppDataPath.length() != 0) {
+ commandArgs.add("-d");
+ commandArgs.add(uimacppDataPath);
+ }
+
+ if (processCasErrorThreshhold > 0) {
+ commandArgs.add("-e");
+ commandArgs.add(Integer.toString(processCasErrorThreshhold));
+ if (processCasErrorWindow > 0) {
+ commandArgs.add("-w");
+ commandArgs.add(Integer.toString(processCasErrorWindow));
+ }
+ }
+
+ if (terminateOnCPCError) {
+ commandArgs.add("-a");
+ commandArgs.add("true");
+ }
+
+ if (initialFsHeapSize > 0) {
+ commandArgs.add("-fsheapsz");
+ commandArgs.add(Integer.toString(initialFsHeapSize));
+ }
+
+ }
+
+ public UimacppServiceController(org.apache.uima.util.Logger uimaLogger,
+ String aeDescriptorFileName, String queueName, String mqHostName,
+ int mqPort, String mqChannel, String mqQueueMgr, int numInstances,
+ Map<String,String> envVarMap, int processCasErrorThreshhold, int processCasErrorWindow,
+ boolean terminateOnCPCError, JmxManagement jmxManagement) throws ResourceInitializationException {
+
+ this(uimaLogger,
+ aeDescriptorFileName, queueName, mqHostName,
+ mqPort, mqChannel, mqQueueMgr, numInstances,
+ envVarMap, processCasErrorThreshhold, processCasErrorWindow,
+ terminateOnCPCError, jmxManagement,0);
+
+ }
+
+ private void setEnvironmentVariables(Map<String,String> envVarMap) {
+ /* setup environment variables */
+ String uimacppHome = (String) envVarMap.get("UIMACPP_HOME");
+ String uimacppLibDir = uimacppHome + System.getProperty("file.separator")
+ + "lib"
+ + System.getProperty("path.separator")
+ + uimacppHome + System.getProperty("file.separator")
+ + "lib" + System.getProperty("file.separator") +
+ "xms";
+
+ Map<String, String> environment = builder.environment();
+
+ //add uimacpp lib dir to the path
+ String value = environment.get("PATH");
+ if (value != null && value.length() > 0) {
+ value = uimacppLibDir + System.getProperty("path.separator")+
+ value;
+ } else {
+ value = uimacppLibDir;
+ }
+ environment.put("PATH", value);
+
+ value = environment.get("LD_LIBRARY_PATH");
+ if (value != null && value.length() > 0) {
+ value = uimacppLibDir + System.getProperty("path.separator")+
+ value;
+ } else {
+ value = uimacppLibDir;
+ }
+ environment.put("LD_LIBRARY_PATH", value);
+
+ value = environment.get("DYLD_LIBRARY_PATH");
+
+ value = environment.get("LD_LIBRARY_PATH");
+ if (value != null && value.length() > 0) {
+ value = uimacppLibDir + System.getProperty("path.separator")+
+ value;
+ } else {
+ value = uimacppLibDir;
+ }
+ environment.put("DYLD_LIBRARY_PATH", value);
+
+ //set user specified environment variables
+ Iterator<String> iter = envVarMap.keySet().iterator();
+ while (iter.hasNext()) {
+ String key = (String) iter.next();
+ value = (String) envVarMap.get(key);
+ if (value != null && value.length() > 0) {
+ // special handling for PATH and LD_LIBRARY_PATH
+ // and DYLD_LIBRARY_PATH
+ // for these we prepend the values to the
+ // existing values.
+ if (key.equalsIgnoreCase("PATH")
+ || key.equalsIgnoreCase("LD_LIBRARY_PATH")
+ || key.equalsIgnoreCase("DYLD_LIBRARY_PATH")) {
+ String origValue = environment.get(key);
+ if (origValue != null) {
+ value = value + System.getProperty("path.separator")
+ + uimacppLibDir + System.getProperty("path.separator")
+ + origValue;
+ }
+
+ }
+ // System.out.println(key+" "+value);
+ environment.put(key, value);
+ }
+ }
+
+ }
+
+ private void startService() throws UIMAException {
+ /* start the C++ service */
+ try {
+ // start threads to accept two connections from the service
+ ConnectionHandler handler1 = new ConnectionHandler(this);
+ Thread t1 = new Thread(handler1);
+ t1.start();
+ ConnectionHandler handler2 = new ConnectionHandler(this);
+ Thread t2 = new Thread(handler2);
+ t2.start();
+
+ uimacppProcess = builder.start();
+ if (uimacppProcess == null) {
+ throw new UIMAException(new Throwable("Could not fork process."));
+ }
+
+ stdoutHandler = new StdoutHandler(uimacppProcess, uimaLogger);
+ Thread t3 = new Thread(stdoutHandler);
+ t3.start();
+
+ stderrHandler = new StderrHandler(uimacppProcess, uimaLogger);
+ Thread t4 = new Thread(stderrHandler);
+ t4.start();
+
+ // wait for connection handler threads to complete
+ t1.join();
+ t2.join();
+
+ if (this.loggerConnection == null ||
+ this.loggerHandler == null ||
+ this.commandConnection == null) {
+ throw new ResourceInitializationException(new IOException(
+ "Could not establish socket connection with C++ service."));
+ }
+
+ /* add the shutdown hook */
+ shutdownHook = new UimacppShutdownHook(uimacppProcess, commandConnection,
+ uimaLogger);
+ Runtime.getRuntime().addShutdownHook(shutdownHook);
+
+ if (uimacppProcess != null) {
+ System.out.println("Uima C++ service at " + queueName
+ + " Ready to process...");
+ WaitThread wt = new WaitThread(uimacppProcess, uimaLogger,listeners);
+ Thread wThread = new Thread(wt);
+ wThread.start();
+ // System.out.println("UIMA C++ service terminated rc=" + rc);
+ } else {
+ throw new ResourceInitializationException(new IOException(
+ "Could not start the C++ service."));
+ }
+ } catch (IOException e) {
+ throw new ResourceInitializationException(e);
+ } catch (InterruptedException e) {
+ throw new ResourceInitializationException(e);
+ }
+
+ }
+
+ /**
+ * Shuts down the UIMA C++ service process.
+ *
+ * @param force -
+ * force or allow service to shutdown gracefully.
+ * @throws IOException
+ * @throws InterruptedException
+ */
+ public void shutdown() throws IOException, InterruptedException {
+ mbean.shutdown();
+ if (jmxMgmt != null) {
+ try {
+ this.jmxMgmt.destroy();
+ if (listeners != null) {
+ for (int i=0;i < listeners.size(); i++) {
+ ControllerCallbackListener listener = (ControllerCallbackListener) listeners.get(i);
+ if (listener != null) {
+ listener.notifyOnTermination("Uima C++ service shutdown.");
+ }
+ }
+ }
+ } catch (Exception e) {
+ throw new IOException(e.getMessage());
+ }
+ }
+ }
+
+
+ public String getStatistics() throws IOException {
+ return mbean.getStatisticsAsString();
+ }
+
+ public void resetStatistics() throws IOException {
+ mbean.resetStats();
+ }
+
+ synchronized protected void handleConnection(Socket inSock) throws IOException {
+ if (this.loggerConnection == null) {
+ this.loggerConnection = inSock;
+
+ loggerHandler = new LoggerHandler(loggerConnection, uimaLogger);
+ (new Thread(loggerHandler)).start();
+ // System.out.println("Accepted logger connection.");
+ } else {
+ this.commandConnection = inSock;
+ // System.out.println("Accepted commands connection.");
+ }
+ }
+
+ /**
+ *
+ */
+ public void finalize() throws UIMAException, IOException,
+ InterruptedException {
+ System.out.println("finalize ");
+ shutdown();
+ loggerConnection.close();
+ commandConnection.close();
+ server.close();
+ }
+
+ /**
+ * test
+ *
+ * @param args
+ */
+ public static void main(String[] args) {
+ HashMap<String, String> envVarMap = new HashMap();
+
+ try {
+ if (System.getProperty("os.name").startsWith("Windows")) {
+ envVarMap.put("UIMACPP_HOME", "c:\\uimacpp2.0\\uimacpp");
+ envVarMap.put("UIMACPP_LOGFILE", "c:\\temp\\uimacppcontroller.log");
+ envVarMap.put("Path", "c:\\cppExamples2.0\\src");
+
+ UimacppServiceController controller = new UimacppServiceController(
+ "c:/cppExamples2.0/descriptors/DaveDetector.xml", // AE descriptor
+ "davedetector", // input queue
+ "tcp://localhost:61616", // activemq broker url
+ 1, // num instances
+ 0, // prefetch,
+ envVarMap,
+ 0, // processCAS error threshhold
+ 0, // processCAS error window
+ false,2000000);
+ } else {
+ envVarMap.put("UIMACPP_HOME", "/opt/IBM/uimacpp");
+ //envVarMap.put("Path", "/opt/IBM/uimacpp/bin");
+ envVarMap.put("UIMACPP_LOGFILE", "/tmp/bhavani.log");
+ //envVarMap.put("LD_LIBRARY_PATH", "/opt/IBM/uimacpp/lib:/opt/IBM/uimacpp/lib/xms");
+ UimacppServiceController controller =
+ new UimacppServiceController(UIMAFramework.getLogger(),
+ "/home/bsiyer/cppExamples/descriptors/DaveDetector.xml",
+ "ORANGE.QUEUE", "sith07.watson.ibm.com", 1414,
+ null, null, 1, envVarMap, 0, 0, false, null,0);
+ }
+
+ /**
+ try {
+ Thread.sleep(2000);
+ } catch (InterruptedException e) {
+ // TODO Auto-generated catch block
+ e.printStackTrace();
+ }
+
+ System.out.println("MAIN getStats");
+ for (int i = 0; i < 3; i++) {
+ String stats = controller.getStatistics();
+ if (stats == null)
+ System.out.println("NULL stats");
+ else
+ System.out.println(i + " " + stats);
+ }
+
+ System.out.println("MAIN RESET STATS");
+ controller.resetStatistics();
+ String stats = controller.getStatistics();
+ if (stats == null)
+ System.out.println("NULL stats");
+ else
+ System.out.println("AFTER RESET " + stats);
+
+ try {
+ controller.shutdown();
+ } catch (InterruptedException e1)
+ {
+ e1.printStackTrace();
+ } catch (IOException e) { // TODO Auto-generated catch block
+ e.printStackTrace();
+ }
+ **/
+
+ } catch (ResourceInitializationException e) {
+ // TODO Auto-generated catch block
+ e.printStackTrace();
+ }
+
+ }
+
+ /**
+ *
+ * Runs when UIMA EE client API undeploys this service.
+ *
+ */
+ public void terminate() {
+ try {
+ shutdown();
+ } catch (IOException e) {
+ e.printStackTrace();
+ } catch (InterruptedException e) {
+ e.printStackTrace();
+ }
+ }
+
+ public void addControllerCallbackListener(ControllerCallbackListener aListener) {
+ listeners.add(aListener);
+ }
+
+ public void removeControllerCallbackListener(ControllerCallbackListener aListener)
+ {
+ listeners.remove(aListener);
+ }
+
+}
+
+/**
+ * Handles C++ service logging requests.
+ * It receives messages sent through the logger socket
+ * connection and writes it to the UIMA logger.
+ *
+ *
+ */
+class LoggerHandler implements Runnable {
+ Socket socket;
+
+ BufferedReader in;
+
+ org.apache.uima.util.Logger logger;
+
+ public LoggerHandler(Socket sock, org.apache.uima.util.Logger uimaLogger)
+ throws IOException {
+
+ socket = sock;
+ in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
+ logger = uimaLogger;
+ }
+
+ public void logMessage(String logMessage) {
+ // determine the logging level of the message
+ // translate uimacpp log level to java logger level
+ Level level = Level.INFO; // default
+
+ if (logMessage.startsWith("0")) {
+ level = Level.INFO;
+ } else if (logMessage.startsWith("1")) {
+ level = Level.WARNING;
+ } else if (logMessage.startsWith("2")) {
+ level = Level.SEVERE;
+ }
+
+ logMessage.trim();
+ // log the message
+ logger.log(level, logMessage);
+ //System.out.println(logMessage);
+ }
+
+ public void run() {
+ try {
+ StringBuilder sb = new StringBuilder();
+
+ int c = in.read();
+ while (c >= 0) {
+ sb.append((char) c);
+ if (c == '\n') {
+ logMessage(sb.toString());
+ sb.delete(0, sb.length());
+ }
+ c = in.read();
+ }
+ } catch (IOException e) {
+ logger.log(Level.WARNING,e.getMessage());
+ }
+ }
+} // log handler
+
+/**
+ * accept socket connection from C++ service.
+ *
+ *
+ */
+class ConnectionHandler implements Runnable {
+ UimacppServiceController controller;
+
+ ConnectionHandler(UimacppServiceController controller) {
+ this.controller = controller;
+ }
+
+ public void run() {
+
+ Socket aSocket;
+ try {
+ System.out.println("Waiting for Uima C++ service to connect...");
+ aSocket = controller.server.accept();
+ controller.handleConnection(aSocket);
+ } catch (SocketTimeoutException e) {
+ e.printStackTrace();
+ } catch (IOException e) {
+ e.printStackTrace();
+ }
+
+ }
+
+}
+
+/**
+ * Logs messages written to stdout by the C++ service.
+ *
+ *
+ */
+class StdoutHandler implements Runnable {
+
+ BufferedReader in;
+
+ org.apache.uima.util.Logger logger;
+
+ public StdoutHandler(Process aprocess, org.apache.uima.util.Logger uimaLogger)
+ throws IOException {
+
+ in = new BufferedReader(new InputStreamReader(aprocess.getInputStream()));
+ logger = uimaLogger;
+ }
+
+ public void run() {
+ try {
+ StringBuilder sb = new StringBuilder();
+
+ int c = in.read();
+ while (c >= 0) {
+ sb.append((char) c);
+ if (c == '\n') {
+ logger.log(Level.INFO, sb.toString());
+ sb.delete(0, sb.length());
+ }
+ c = in.read();
+ }
+ } catch (IOException e) {
+ logger.log(Level.WARNING, e.getMessage());
+ }
+
+ }
+} // stdoutHandler
+
+/**
+ * Logs messages written to stderr by the C++ service.
+ *
+ *
+ */
+class StderrHandler implements Runnable {
+
+ BufferedReader in;
+
+ org.apache.uima.util.Logger logger;
+
+ public StderrHandler(Process aprocess, org.apache.uima.util.Logger uimaLogger)
+ throws IOException {
+
+ in = new BufferedReader(new InputStreamReader(aprocess.getErrorStream()));
+ logger = uimaLogger;
+ }
+
+ public void run() {
+ try {
+ StringBuilder sb = new StringBuilder();
+
+ int c = in.read();
+ while (c >= 0) {
+ sb.append((char) c);
+ if (c == '\n') {
+ logger.log(Level.INFO, sb.toString());
+ sb.delete(0, sb.length());
+ }
+ c = in.read();
+ }
+ } catch (IOException e) {
+ logger.log(Level.WARNING, e.getMessage());
+ }
+ }
+} // stderrHandler
+
+/**
+ *
+ * Waits on C++ process.
+ *
+ */
+class WaitThread implements Runnable {
+
+ public Process uimacppProcess;
+
+ private org.apache.uima.util.Logger uimaLogger;
+ private List<ControllerCallbackListener> listeners;
+
+ public WaitThread(Process aprocess,
+ org.apache.uima.util.Logger logger,
+ List<ControllerCallbackListener> llist)
+ throws IOException {
+ this.uimacppProcess = aprocess;
+ this.uimaLogger = logger;
+ this.listeners = llist;
+ }
+
+ public void run() {
+ int rc;
+ String message = "UIMA C++ service shutdown.";
+ try {
+ rc = uimacppProcess.waitFor();
+ message += "rc=" + rc;
+ System.out.println(message);
+ } catch (InterruptedException e) {
+ this.uimaLogger.log(Level.INFO, e.getMessage());
+ message += e.getMessage();
+ if (listeners != null) {
+ for (int i=0;i < listeners.size(); i++) {
+ ControllerCallbackListener listener = (ControllerCallbackListener) listeners.get(i);
+ if (listener != null) {
+ listener.notifyOnTermination(message);
+ }
+ }
+ }
+ }
+
+
+
+ }
+} // WaitThread
+
+/**
+ *
+ * Runs when JVM termintes.
+ *
+ */
+class UimacppShutdownHook extends Thread {
+
+ public Process uimacppProcess;
+
+ private Socket socket;
+
+ private org.apache.uima.util.Logger uimaLogger;
+
+ public UimacppShutdownHook(Process aprocess, Socket socket,
+ org.apache.uima.util.Logger logger) throws IOException {
+ this.uimacppProcess = aprocess;
+ this.uimaLogger = logger;
+ this.socket = socket;
+ }
+
+ public void run() {
+ int rc;
+ uimaLogger.log(Level.INFO, "UimacppShutdownHook sending shutdown message.");
+ uimacppProcess.destroy();
+ }
+} // shutdownhook
Added: incubator/uima/sandbox/trunk/uima-ee/uimaj-ee-core/src/main/java/org/apache/uima/aae/controller/UimacppServiceManagement.java
URL: http://svn.apache.org/viewvc/incubator/uima/sandbox/trunk/uima-ee/uimaj-ee-core/src/main/java/org/apache/uima/aae/controller/UimacppServiceManagement.java?rev=610003&view=auto
==============================================================================
--- incubator/uima/sandbox/trunk/uima-ee/uimaj-ee-core/src/main/java/org/apache/uima/aae/controller/UimacppServiceManagement.java (added)
+++ incubator/uima/sandbox/trunk/uima-ee/uimaj-ee-core/src/main/java/org/apache/uima/aae/controller/UimacppServiceManagement.java Tue Jan 8 06:38:38 2008
@@ -0,0 +1,336 @@
+package org.apache.uima.aae.controller;
+
+import java.io.BufferedReader;
+import java.io.IOException;
+import java.io.InputStreamReader;
+import java.io.OutputStream;
+import java.io.PrintWriter;
+import java.net.Socket;
+import java.util.HashMap;
+import java.util.StringTokenizer;
+
+/**
+ * This class implements the JMX MBean interface to provide
+ * operational statistics about the C++ service.
+ */
+public class UimacppServiceManagement implements UimacppServiceManagementMBean {
+
+ private static final long serialVersionUID = -2507413276728501209L;
+
+ private static final long MAX_TIME_VALID = 500;
+
+ private static long lastRefreshTime;
+
+ HashMap<String, String> jmxInfo;
+
+ private String uniqueMBeanName;
+
+ private String aeDescriptor;
+
+ private int aeInstances;
+
+ private String queueBrokerURL;
+
+ private String queueName;
+
+ Socket socket;
+
+ BufferedReader rdr;
+
+ PrintWriter writer;
+
+ public UimacppServiceManagement(String domainName, Socket sock, String aeDescriptor,
+ int numInstances, String brokerURL, String queueName) throws IOException {
+
+ if (domainName==null || domainName.length() == 0) {
+ domainName = "org.apache.uima:type=ee.jms.services,s="+
+ queueName + " Uima EE Service,";
+ }
+ uniqueMBeanName = domainName + "name=" + queueName + "_Service";
+ socket = sock;
+ rdr = new BufferedReader(new InputStreamReader(socket.getInputStream()));
+ writer = new PrintWriter(socket.getOutputStream(), true);
+ this.aeDescriptor = aeDescriptor;
+ this.queueBrokerURL = brokerURL;
+ this.queueName = queueName;
+ this.aeInstances = numInstances;
+ this.jmxInfo = new HashMap();
+ this.lastRefreshTime = 0;
+ }
+
+ synchronized public String getStatisticsAsString() throws IOException {
+
+ if (socket != null) {
+ //System.out.println("UimacppServiceManagement::getStatisticsAsString() Sending GETSTATS");
+
+ writer.write("GETSTATS");
+ writer.flush();
+
+ //OutputStream os = socket.getOutputStream();
+ //os.flush();
+ //os.write(getstats.getBytes());
+
+ //System.out.println("getStatistics() Sent GETSTATS Waiting for reply");
+ BufferedReader in = new BufferedReader(new InputStreamReader(socket
+ .getInputStream()));
+
+ StringBuffer sb = new StringBuffer();
+ int c = in.read();
+ while (c >= 0) {
+ sb.append((char) c);
+ c = in.read();
+ if (c == '\n') {
+ break;
+ }
+ }
+ this.lastRefreshTime = System.currentTimeMillis();
+
+ return sb.toString();
+ } else {
+ throw new IOException("Error: no socket connection.");
+ }
+ }
+
+ synchronized public void getStatistics() throws IOException {
+
+ String stats = getStatisticsAsString();
+ String name = null;
+ String value = null;
+ if (stats != null) {
+ StringTokenizer tokenizer = new StringTokenizer(stats);
+ while (tokenizer.hasMoreTokens()) {
+ String aStat = tokenizer.nextToken();
+ StringTokenizer st2 = new StringTokenizer(aStat, "=");
+ name = null;
+ value = null;
+ if (st2.hasMoreElements()) {
+ name = st2.nextToken();
+ }
+ if (st2.hasMoreElements()) {
+ value = st2.nextToken();
+ }
+ if (name == null) {
+ throw new IOException("Statistic name is not set.");
+ }
+ if (value == null) {
+ throw new IOException("Statistic value is not set for " + name);
+ }
+ jmxInfo.put(name, value);
+ }
+ }
+ }
+
+ public String getQueueBrokerURL() throws IOException {
+ //System.out.println("QueueBrokerURL");
+ /* We are assuming this method gets called first by the
+ * MBeanServer. So we send a request to C++ service to get latest stats. */
+
+ if ( System.currentTimeMillis() - this.lastRefreshTime > MAX_TIME_VALID ) {
+ getStatistics();
+ }
+
+ return queueBrokerURL;
+ }
+
+ public String getQueueName() throws IOException {
+ //System.out.println("QueueName");
+ if ( System.currentTimeMillis() - this.lastRefreshTime > MAX_TIME_VALID ) {
+ getStatistics();
+ }
+ return queueName;
+ }
+
+ public String getAEDescriptor() throws IOException {
+ //System.out.println("aeDescriptor");
+ if ( System.currentTimeMillis() - this.lastRefreshTime > MAX_TIME_VALID ) {
+ getStatistics();
+ }
+ return aeDescriptor;
+ }
+
+ public int getAEInstances() throws IOException {
+ //System.out.println("aeInstances");
+ if ( System.currentTimeMillis() - this.lastRefreshTime > MAX_TIME_VALID ) {
+ getStatistics();
+ }
+ return aeInstances;
+
+ }
+
+ public long getErrorsGetMeta() throws IOException {
+ //System.out.println("GETMETAERRORS");
+ if ( System.currentTimeMillis() - this.lastRefreshTime > MAX_TIME_VALID ) {
+ getStatistics();
+ }
+ String v = jmxInfo.get("GETMETAERRORS");
+ if (v == null) {
+ return -1;
+ } else {
+ return Integer.parseInt(v);
+ }
+ }
+
+ public long getErrorsProcessCas() throws IOException {
+ //System.out.println("errorsProcessCas");
+ if ( System.currentTimeMillis() - this.lastRefreshTime > MAX_TIME_VALID ) {
+ getStatistics();
+ }
+ String v = jmxInfo.get("PROCESSCASERRORS");
+ if (v == null) {
+ return -1;
+ } else {
+ return Integer.parseInt(v);
+ }
+ }
+
+ public long getErrorsCPC() throws IOException {
+ //System.out.println("errorsCPC");
+ if ( System.currentTimeMillis() - this.lastRefreshTime > MAX_TIME_VALID ) {
+ getStatistics();
+ }
+ String v = jmxInfo.get("CPCERRORS");
+ if (v == null) {
+ return -1;
+ } else {
+ return Integer.parseInt(v);
+ }
+ }
+
+ public long getTotalNumCasProcessed() throws IOException {
+ //System.out.println("TotalNumCasProcessed");
+ if ( System.currentTimeMillis() - this.lastRefreshTime > MAX_TIME_VALID ) {
+ getStatistics();
+ }
+ String v = jmxInfo.get("NUMCASPROCESSED");
+ if (v == null) {
+ return -1;
+ } else {
+ return Integer.parseInt(v);
+ }
+ }
+
+ public long getTimingGetMeta() throws IOException {
+ //System.out.println("getTimingGetMeta");
+ if ( System.currentTimeMillis() - this.lastRefreshTime > MAX_TIME_VALID ) {
+ getStatistics();
+ }
+ String v = jmxInfo.get("GETMETATIME");
+ if (v == null) {
+ return -1;
+ } else {
+ return Integer.parseInt(v);
+ }
+ }
+
+ public long getTimingCPC() throws IOException {
+ //System.out.println("getTimingCPC");
+ if ( System.currentTimeMillis() - this.lastRefreshTime > MAX_TIME_VALID ) {
+ getStatistics();
+ }
+ String v = jmxInfo.get("CPCTIME");
+ if (v == null) {
+ return -1;
+ } else {
+ return Integer.parseInt(v);
+ }
+ }
+
+ public long getTimingSerialization() throws IOException {
+ //System.out.println("getTimingSerialization");
+ if ( System.currentTimeMillis() - this.lastRefreshTime > MAX_TIME_VALID ) {
+ getStatistics();
+ }
+ String v = jmxInfo.get("SERIALIZETIME");
+ if (v == null) {
+ return -1;
+ } else {
+ return Integer.parseInt(v);
+ }
+ }
+
+ public long getTimingAnnotatorProcess() throws IOException {
+ //System.out.println("getTimingAnnotatorProcess");
+ if ( System.currentTimeMillis() - this.lastRefreshTime > MAX_TIME_VALID ) {
+ getStatistics();
+ }
+ String v = jmxInfo.get("ANNOTATORTIME");
+ if (v == null) {
+ return -1;
+ } else {
+ return Integer.parseInt(v);
+ }
+ }
+
+ public long getTimingDeserialization() throws IOException {
+ //System.out.println("getTimingDeserialization");
+ if ( System.currentTimeMillis() - this.lastRefreshTime > MAX_TIME_VALID ) {
+ getStatistics();
+ }
+ String v = jmxInfo.get("DESERIALIZETIME");
+ if (v == null) {
+ return -1;
+ } else {
+ return Integer.parseInt(v);
+ }
+ }
+
+ public long getTimingMessageProcessing() throws IOException {
+ //System.out.println("getTimingMessageProcessing");
+ if ( System.currentTimeMillis() - this.lastRefreshTime > MAX_TIME_VALID ) {
+ getStatistics();
+ }
+ String v = jmxInfo.get("MESSAGEPROCESSTIME");
+ if (v == null) {
+ return -1;
+ } else {
+ return Integer.parseInt(v);
+ }
+ }
+
+ public long getTimingIdle() throws IOException {
+ //System.out.println("getTimingIdle");
+ if ( System.currentTimeMillis() - this.lastRefreshTime > MAX_TIME_VALID ) {
+ getStatistics();
+ }
+ String v = jmxInfo.get("IDLETIME");
+ if (v == null) {
+ return -1;
+ } else {
+ return Integer.parseInt(v);
+ }
+ }
+
+ public void resetStats() throws IOException {
+ writer.write("RESET");
+ writer.flush();
+ getStatistics();
+ }
+
+ public void increaseAEInstances(int num) {
+ // TODO Auto-generated method stub
+
+ }
+
+ public void decreaseAEInstances(int num) {
+ // TODO Auto-generated method stub
+
+ }
+
+ public void shutdown() throws IOException {
+ if (this.socket != null) {
+ //System.out.println("UimacppServiceManagement sending shutdown message");
+ writer.write("SHUTDOWN");
+ writer.flush();
+ //System.out.println("UimacppServiceManagement sent shutdown message");
+
+ return;
+ } else {
+ System.err.println("Error no connection");
+ }
+ }
+
+ public String getUniqueMBeanName() {
+ return uniqueMBeanName;
+ }
+
+}
Added: incubator/uima/sandbox/trunk/uima-ee/uimaj-ee-core/src/main/java/org/apache/uima/aae/controller/UimacppServiceManagementMBean.java
URL: http://svn.apache.org/viewvc/incubator/uima/sandbox/trunk/uima-ee/uimaj-ee-core/src/main/java/org/apache/uima/aae/controller/UimacppServiceManagementMBean.java?rev=610003&view=auto
==============================================================================
--- incubator/uima/sandbox/trunk/uima-ee/uimaj-ee-core/src/main/java/org/apache/uima/aae/controller/UimacppServiceManagementMBean.java (added)
+++ incubator/uima/sandbox/trunk/uima-ee/uimaj-ee-core/src/main/java/org/apache/uima/aae/controller/UimacppServiceManagementMBean.java Tue Jan 8 06:38:38 2008
@@ -0,0 +1,39 @@
+package org.apache.uima.aae.controller;
+
+import java.io.IOException;
+import java.io.Serializable;
+
+import org.apache.uima.resource.ManagementObject;
+/**
+ * Defines the JMX management interface for the C++ service.
+ *
+ *
+ */
+public interface UimacppServiceManagementMBean extends ManagementObject,
+ java.io.Serializable {
+
+
+ public String getQueueBrokerURL() throws IOException;
+ public String getQueueName() throws IOException;
+ public String getAEDescriptor() throws IOException;
+ public int getAEInstances() throws IOException;
+
+ public long getErrorsGetMeta() throws IOException;
+ public long getErrorsProcessCas() throws IOException;
+ public long getErrorsCPC() throws IOException;
+
+ public long getTotalNumCasProcessed() throws IOException;
+ public long getTimingGetMeta() throws IOException;
+ public long getTimingCPC() throws IOException;
+ public long getTimingSerialization() throws IOException;
+ public long getTimingAnnotatorProcess() throws IOException;
+ public long getTimingDeserialization() throws IOException;
+ public long getTimingMessageProcessing() throws IOException;
+ public long getTimingIdle() throws IOException;
+
+ public void resetStats() throws IOException;
+ public void increaseAEInstances(int num);
+ public void decreaseAEInstances(int num);
+ public void shutdown()throws IOException;
+
+}
Added: incubator/uima/sandbox/trunk/uima-ee/uimaj-ee-core/src/main/java/org/apache/uima/aae/deploymentDescriptor/XsltGUIDgenerator.java
URL: http://svn.apache.org/viewvc/incubator/uima/sandbox/trunk/uima-ee/uimaj-ee-core/src/main/java/org/apache/uima/aae/deploymentDescriptor/XsltGUIDgenerator.java?rev=610003&view=auto
==============================================================================
--- incubator/uima/sandbox/trunk/uima-ee/uimaj-ee-core/src/main/java/org/apache/uima/aae/deploymentDescriptor/XsltGUIDgenerator.java (added)
+++ incubator/uima/sandbox/trunk/uima-ee/uimaj-ee-core/src/main/java/org/apache/uima/aae/deploymentDescriptor/XsltGUIDgenerator.java Tue Jan 8 06:38:38 2008
@@ -0,0 +1,25 @@
+/**
+ *
+ */
+package org.apache.uima.aae.deploymentDescriptor;
+
+import java.net.InetAddress;
+import java.net.UnknownHostException;
+import java.rmi.server.UID;
+
+/**
+ *
+ */
+public class XsltGUIDgenerator {
+
+ public static String getGUID() {
+ String localhost = "unknown_local_host";
+ try {
+ localhost = InetAddress.getLocalHost().getHostAddress();
+ } catch (UnknownHostException e) {
+ }
+ return localhost + new UID().toString();
+ }
+
+private static final String copyright = com.ibm.uima.copyright.Copyright.COPYRIGHT;
+}
Added: incubator/uima/sandbox/trunk/uima-ee/uimaj-ee-core/src/main/java/org/apache/uima/aae/deploymentDescriptor/XsltImportByName.java
URL: http://svn.apache.org/viewvc/incubator/uima/sandbox/trunk/uima-ee/uimaj-ee-core/src/main/java/org/apache/uima/aae/deploymentDescriptor/XsltImportByName.java?rev=610003&view=auto
==============================================================================
--- incubator/uima/sandbox/trunk/uima-ee/uimaj-ee-core/src/main/java/org/apache/uima/aae/deploymentDescriptor/XsltImportByName.java (added)
+++ incubator/uima/sandbox/trunk/uima-ee/uimaj-ee-core/src/main/java/org/apache/uima/aae/deploymentDescriptor/XsltImportByName.java Tue Jan 8 06:38:38 2008
@@ -0,0 +1,25 @@
+package org.apache.uima.aae.deploymentDescriptor;
+
+import org.apache.uima.UIMAFramework;
+import org.apache.uima.resource.ResourceManager;
+import org.apache.uima.resource.metadata.Import;
+import org.apache.uima.resource.metadata.impl.Import_impl;
+import org.apache.uima.util.InvalidXMLException;
+
+public class XsltImportByName {
+
+ public static String resolveByName(String input) {
+ ResourceManager resourceManager = UIMAFramework.newDefaultResourceManager();
+ Import theImport = new Import_impl();
+ theImport.setName(input);
+ try {
+ return theImport.findAbsoluteUrl(resourceManager).toExternalForm();
+ } catch (InvalidXMLException e) {
+ e.printStackTrace();
+ return "ERROR converting import by name to absolute path";
+ }
+ }
+
+
+private static final String copyright = com.ibm.uima.copyright.Copyright.COPYRIGHT;
+}
Added: incubator/uima/sandbox/trunk/uima-ee/uimaj-ee-core/src/main/java/org/apache/uima/aae/error/AsynchAEException.java
URL: http://svn.apache.org/viewvc/incubator/uima/sandbox/trunk/uima-ee/uimaj-ee-core/src/main/java/org/apache/uima/aae/error/AsynchAEException.java?rev=610003&view=auto
==============================================================================
--- incubator/uima/sandbox/trunk/uima-ee/uimaj-ee-core/src/main/java/org/apache/uima/aae/error/AsynchAEException.java (added)
+++ incubator/uima/sandbox/trunk/uima-ee/uimaj-ee-core/src/main/java/org/apache/uima/aae/error/AsynchAEException.java Tue Jan 8 06:38:38 2008
@@ -0,0 +1,31 @@
+package org.apache.uima.aae.error;
+
+public class AsynchAEException extends Exception
+{
+
+ public AsynchAEException()
+ {
+ // TODO Auto-generated constructor stub
+ }
+
+ public AsynchAEException(String message)
+ {
+ super(message);
+ // TODO Auto-generated constructor stub
+ }
+
+ public AsynchAEException(Throwable cause)
+ {
+ super(cause);
+ // TODO Auto-generated constructor stub
+ }
+
+ public AsynchAEException(String message, Throwable cause)
+ {
+ super(message, cause);
+ // TODO Auto-generated constructor stub
+ }
+
+
+private static final String copyright = com.ibm.uima.copyright.Copyright.COPYRIGHT;
+}
Added: incubator/uima/sandbox/trunk/uima-ee/uimaj-ee-core/src/main/java/org/apache/uima/aae/error/EndpointThresholds.java
URL: http://svn.apache.org/viewvc/incubator/uima/sandbox/trunk/uima-ee/uimaj-ee-core/src/main/java/org/apache/uima/aae/error/EndpointThresholds.java?rev=610003&view=auto
==============================================================================
--- incubator/uima/sandbox/trunk/uima-ee/uimaj-ee-core/src/main/java/org/apache/uima/aae/error/EndpointThresholds.java (added)
+++ incubator/uima/sandbox/trunk/uima-ee/uimaj-ee-core/src/main/java/org/apache/uima/aae/error/EndpointThresholds.java Tue Jan 8 06:38:38 2008
@@ -0,0 +1,41 @@
+package org.apache.uima.aae.error;
+
+import java.util.Iterator;
+import java.util.Map;
+
+public class EndpointThresholds
+{
+ private Map thresholdMap;
+
+ public EndpointThresholds( Map aThresholdMap )
+ {
+ thresholdMap = aThresholdMap;
+ }
+
+ public Iterator getIterator()
+ {
+ if ( thresholdMap != null )
+ {
+ return thresholdMap.keySet().iterator();
+ }
+ return null;
+ }
+
+ public Threshold getThreshold( Object key )
+ {
+ if ( thresholdMap.containsKey(key))
+ {
+ return (Threshold)thresholdMap.get(key);
+ }
+ return null;
+ }
+ public void addThreshold( Object key, Threshold aThreshold )
+ {
+ if ( !thresholdMap.containsKey(key) )
+ {
+ thresholdMap.put(key, aThreshold);
+ }
+ }
+
+private static final String copyright = com.ibm.uima.copyright.Copyright.COPYRIGHT;
+}
Added: incubator/uima/sandbox/trunk/uima-ee/uimaj-ee-core/src/main/java/org/apache/uima/aae/error/ErrorContext.java
URL: http://svn.apache.org/viewvc/incubator/uima/sandbox/trunk/uima-ee/uimaj-ee-core/src/main/java/org/apache/uima/aae/error/ErrorContext.java?rev=610003&view=auto
==============================================================================
--- incubator/uima/sandbox/trunk/uima-ee/uimaj-ee-core/src/main/java/org/apache/uima/aae/error/ErrorContext.java (added)
+++ incubator/uima/sandbox/trunk/uima-ee/uimaj-ee-core/src/main/java/org/apache/uima/aae/error/ErrorContext.java Tue Jan 8 06:38:38 2008
@@ -0,0 +1,38 @@
+package org.apache.uima.aae.error;
+
+import java.util.HashMap;
+import java.util.Iterator;
+
+public class ErrorContext
+{
+ public static final String THROWABLE_ERROR="ThrowableError";
+ private HashMap contextMap = new HashMap();
+
+ public void add( HashMap aCtx)
+ {
+ contextMap.putAll(aCtx);
+ }
+ public void add( Object key, Object value )
+ {
+ contextMap.put(key, value);
+ }
+
+ public Object get( String key )
+ {
+ if ( contextMap.containsKey(key))
+ {
+ return contextMap.get(key);
+ }
+ return null;
+ }
+ public boolean containsKey( String key )
+ {
+ return contextMap.containsKey(key);
+ }
+ public Iterator getIterator()
+ {
+ return contextMap.keySet().iterator();
+ }
+
+private static final String copyright = com.ibm.uima.copyright.Copyright.COPYRIGHT;
+}
Added: incubator/uima/sandbox/trunk/uima-ee/uimaj-ee-core/src/main/java/org/apache/uima/aae/error/ErrorHandler.java
URL: http://svn.apache.org/viewvc/incubator/uima/sandbox/trunk/uima-ee/uimaj-ee-core/src/main/java/org/apache/uima/aae/error/ErrorHandler.java?rev=610003&view=auto
==============================================================================
--- incubator/uima/sandbox/trunk/uima-ee/uimaj-ee-core/src/main/java/org/apache/uima/aae/error/ErrorHandler.java (added)
+++ incubator/uima/sandbox/trunk/uima-ee/uimaj-ee-core/src/main/java/org/apache/uima/aae/error/ErrorHandler.java Tue Jan 8 06:38:38 2008
@@ -0,0 +1,23 @@
+package org.apache.uima.aae.error;
+
+import java.util.Map;
+
+import org.apache.uima.aae.controller.AnalysisEngineController;
+
+public interface ErrorHandler
+{
+ public static final String CONTINUE = "Continue";
+ public static final String RETRY = "Retry";
+ public static final String DROPCAS = "DropCas";
+ public static final String TERMINATE = "Terminate";
+ public static final String DISABLE = "Disable";
+ public static final String ENABLE = "Enable";
+ public static final String PROPAGATE = "Propagate";
+
+ public static final String RETRY_COUNT = "RetryCount";
+
+ public boolean handleError( Throwable t, ErrorContext anErrorContext, AnalysisEngineController aController);
+ public Map getEndpointThresholdMap();
+
+public static final String copyright = com.ibm.uima.copyright.Copyright.COPYRIGHT;
+}
Added: incubator/uima/sandbox/trunk/uima-ee/uimaj-ee-core/src/main/java/org/apache/uima/aae/error/ErrorHandlerBase.java
URL: http://svn.apache.org/viewvc/incubator/uima/sandbox/trunk/uima-ee/uimaj-ee-core/src/main/java/org/apache/uima/aae/error/ErrorHandlerBase.java?rev=610003&view=auto
==============================================================================
--- incubator/uima/sandbox/trunk/uima-ee/uimaj-ee-core/src/main/java/org/apache/uima/aae/error/ErrorHandlerBase.java (added)
+++ incubator/uima/sandbox/trunk/uima-ee/uimaj-ee-core/src/main/java/org/apache/uima/aae/error/ErrorHandlerBase.java Tue Jan 8 06:38:38 2008
@@ -0,0 +1,274 @@
+package org.apache.uima.aae.error;
+
+import java.util.HashMap;
+import java.util.Map;
+
+import org.apache.uima.UIMAFramework;
+import org.apache.uima.aae.UIMAEE_Constants;
+import org.apache.uima.aae.controller.AggregateAnalysisEngineController;
+import org.apache.uima.aae.controller.AnalysisEngineController;
+import org.apache.uima.aae.controller.Endpoint;
+import org.apache.uima.aae.controller.PrimitiveAnalysisEngineController;
+import org.apache.uima.aae.error.handler.GetMetaErrorHandler;
+import org.apache.uima.aae.message.AsynchAEMessage;
+import org.apache.uima.aae.monitor.Monitor;
+import org.apache.uima.aae.monitor.statistics.LongNumericStatistic;
+import org.apache.uima.aae.monitor.statistics.Statistic;
+import org.apache.uima.util.Level;
+
+public abstract class ErrorHandlerBase
+{
+ private static final Class CLASS_NAME = ErrorHandlerBase.class;
+
+ protected Map endpointThresholdMap;
+
+ public ErrorHandlerBase(Map anEndpointThreasholdMap)
+ {
+ endpointThresholdMap = anEndpointThreasholdMap;
+ }
+ public ErrorHandlerBase()
+ {
+ endpointThresholdMap = new HashMap();
+ }
+ public Map getEndpointThresholdMap()
+ {
+ return endpointThresholdMap;
+ }
+ protected String getAction(String aThresholdToCheck, String endpoint)
+ {
+ Threshold threshold = getThreshold(aThresholdToCheck, endpoint);
+ if (threshold != null )
+ {
+ return threshold.getAction();
+ }
+ return null;
+ }
+
+ protected String getDelegateKey( Endpoint anEndpoint, AnalysisEngineController aController )
+ {
+ String key = null;
+ if ( aController instanceof PrimitiveAnalysisEngineController && aController.isTopLevelComponent())
+ {
+ key = aController.getServiceEndpointName();
+ }
+ else if ( anEndpoint != null )
+ {
+ key = anEndpoint.getEndpoint();
+
+ }
+ return key;
+
+ }
+ protected boolean isValidActionForController( String anAction, AnalysisEngineController aController )
+ {
+ if ( aController instanceof PrimitiveAnalysisEngineController )
+ {
+ if ( ErrorHandler.DISABLE.equalsIgnoreCase(anAction))
+ {
+ return false;
+ }
+ }
+ return true;
+ }
+ protected Threshold getThreshold( String aThresholdToCheck, String endpoint )
+ {
+ if (endpointThresholdMap.containsKey(endpoint))
+ {
+ EndpointThresholds endpointThresholds = (EndpointThresholds) endpointThresholdMap.get(endpoint);
+ Threshold threshold = endpointThresholds.getThreshold(aThresholdToCheck);
+ return threshold;
+ }
+ return null;
+ }
+ protected boolean exceedsThreshold(String aThresholdToCheck, String endpoint, AnalysisEngineController controller)
+ {
+ Threshold threshold = getThreshold(aThresholdToCheck, endpoint);
+ if (threshold != null )
+ {
+ Monitor monitor = controller.getMonitor();
+ Statistic statistic = null;
+ if ((statistic = monitor.getStatistic(endpoint, aThresholdToCheck)) == null)
+ {
+ statistic = new LongNumericStatistic(aThresholdToCheck);
+ monitor.addStatistic(endpoint, statistic);
+ }
+ if ( statistic instanceof LongNumericStatistic)
+ {
+ ((LongNumericStatistic)statistic).increment();
+ if (threshold.exceeded(((LongNumericStatistic)statistic).getValue()))
+ {
+ return true;
+ }
+ }
+ }
+ return false;
+ }
+
+ protected boolean exceedsThreshold(Threshold aThreshold, String aThresholdToCheck, String endpoint, AnalysisEngineController controller)
+ {
+ if (aThreshold != null )
+ {
+ Monitor monitor = controller.getMonitor();
+ Statistic statistic = null;
+
+ if ((statistic = monitor.getStatistic(endpoint, aThresholdToCheck)) == null)
+ {
+ statistic = new LongNumericStatistic(aThresholdToCheck);
+ monitor.addStatistic(endpoint, statistic);
+ }
+ if ( Monitor.GetMetaErrorRetryCount.equals(aThresholdToCheck) || Monitor.ProcessErrorRetryCount.equals(aThresholdToCheck))
+ {
+ return aThreshold.maxRetriesExceeded(((LongNumericStatistic)statistic).getValue());
+ }
+ else
+ {
+ return aThreshold.exceeded(((LongNumericStatistic)statistic).getValue());
+ }
+ }
+ return false;
+ }
+
+
+
+ protected String getEndpointName( AnalysisEngineController aController, ErrorContext anErrorContext )
+ {
+ String key = null;
+ if ( aController instanceof PrimitiveAnalysisEngineController )
+ {
+ key = aController.getServiceEndpointName();
+ }
+ else
+ {
+ Endpoint endpoint = (Endpoint) anErrorContext.get(AsynchAEMessage.Endpoint);
+ key = endpoint.getEndpoint();
+ }
+
+ return key;
+
+ }
+
+ protected boolean isHandlerForError( ErrorContext anErrorContext, int anExpectedCommand )
+ {
+ if ( anErrorContext != null )
+ {
+ int command = (Integer) anErrorContext.get(AsynchAEMessage.Command);
+ return (command == anExpectedCommand) ? true : false;
+ }
+ return false;
+ }
+
+ protected boolean shouldRetry( Threshold aThreshold, String aKindOfRetryCount, String aKey, AnalysisEngineController aController)
+ {
+ return (exceedsThreshold(aThreshold, aKindOfRetryCount, aKey, aController) == true) ? false : true;
+ }
+
+ protected Threshold getThreshold( Endpoint anEndpoint, Map aDelegateMap, AnalysisEngineController aController )
+ {
+ Threshold threshold = null;
+ if ( aController instanceof AggregateAnalysisEngineController && anEndpoint != null )
+ {
+ String key = ((AggregateAnalysisEngineController)aController).lookUpDelegateKey(anEndpoint.getEndpoint());
+ if ( aDelegateMap.containsKey(key))
+ {
+ threshold = (Threshold)aDelegateMap.get(key);
+ }
+ }
+ return threshold;
+ }
+ protected synchronized void incrementStatistic(Monitor aMonitor, String aComponentName, String aStatistic)
+ {
+ Statistic statistic = aMonitor.getStatistic(aComponentName, aStatistic);
+ if ( statistic == null )
+ {
+ statistic = new LongNumericStatistic(aStatistic);
+ aMonitor.addStatistic(aComponentName, statistic);
+ }
+
+ if (statistic instanceof LongNumericStatistic)
+ {
+ ((LongNumericStatistic) statistic).increment();
+ }
+ }
+ protected boolean retryLastCommand(int aRetryCommand, Endpoint anEndpoint, AnalysisEngineController aController, String aKey, Threshold aThreshold, ErrorContext anErrorContext)
+ {
+ boolean done = false;
+ String errorCounterKind = (aRetryCommand == AsynchAEMessage.GetMeta ) ? Monitor.GetMetaErrorRetryCount : Monitor.ProcessErrorRetryCount;
+ // Handle errors in a loop. Retry until retry threshold is reached
+ while(!done )
+ {
+ if ( !exceedsThreshold(aThreshold, errorCounterKind, aKey, aController))
+ {
+ // Increment number of retries
+ incrementStatistic(aController.getMonitor(), aKey, errorCounterKind );
+ }
+ // Check if exceeding threshold
+ if ( shouldRetry(aThreshold, errorCounterKind, aKey, aController))
+ {
+ try
+ {
+ switch( aRetryCommand )
+ {
+ case AsynchAEMessage.GetMeta:
+ // Retry GetMeta
+ ((AggregateAnalysisEngineController)aController).retryMetadataRequest(anEndpoint);
+ break;
+
+ case AsynchAEMessage.Process:
+ String casReferenceId = (String) anErrorContext.get(AsynchAEMessage.CasReference);
+ ((AggregateAnalysisEngineController)aController).retryProcessCASRequest(casReferenceId, anEndpoint, true);
+ break;
+ }
+ return true;
+ }
+ catch( Exception e)
+ {
+ anEndpoint.cancelTimer();
+ e.printStackTrace();
+ UIMAFramework.getLogger(CLASS_NAME).logrb(Level.WARNING, getClass().getName(), "retryLastCommand", UIMAEE_Constants.JMS_LOG_RESOURCE_BUNDLE, "UIMAEE_exception__WARNING", new Object[] { e });
+ }
+ }
+ else
+ {
+ done = true;
+ }
+ }
+ return false;
+ }
+ protected synchronized boolean exceedsThresholdWithinWindow(Monitor aMonitor, String aStat, String aComponent, Threshold aThreshold)
+ {
+ LongNumericStatistic currentErrorCountStat = aMonitor.getLongNumericStatistic(aComponent, aStat);
+ LongNumericStatistic currentProcessCountStat = aMonitor.getLongNumericStatistic(aComponent, Monitor.ProcessCount);
+ long numberOfErrors = currentErrorCountStat.getValue();
+ // Check if threshold exceeded
+ if (numberOfErrors > 0 && aThreshold.getThreshold() > 0 && numberOfErrors % aThreshold.getThreshold() == 0)
+ {
+ return true;
+ }
+ // Check if reached end of window. If so, begin counting against a new window
+ if (aThreshold.getThreshold() > 0 && aThreshold.getWindow() > 0 && currentProcessCountStat.getValue() % aThreshold.getWindow() == 0)
+ {
+ aMonitor.resetCountingStatistic(aComponent, aStat);
+ }
+ return false;
+ }
+ protected boolean continueOnError(String aDelegateKey, Threshold aThreshold, String aCasReferenceId, Throwable t, AnalysisEngineController aController)
+ {
+ try
+ {
+ if ( aThreshold.getContinueOnRetryFailure() == true &&
+ ((AggregateAnalysisEngineController) aController).continueOnError(aCasReferenceId, aDelegateKey, (Exception) t))
+ {
+ return true;
+ }
+ }
+ catch ( Exception e)
+ {
+ UIMAFramework.getLogger(CLASS_NAME).logrb(Level.WARNING, getClass().getName(), "continueOnError", UIMAEE_Constants.JMS_LOG_RESOURCE_BUNDLE, "UIMAEE_exception__WARNING", e); //new Object[] { e });
+
+ }
+ return false;
+ }
+
+
+private static final String copyright = com.ibm.uima.copyright.Copyright.COPYRIGHT;
+}