Package org.apache.uima.resource

Examples of org.apache.uima.resource.ResourceProcessException


  public void processCas(CAS aCAS) throws ResourceProcessException {
    JCas jcas;
    try {
      jcas = aCAS.getJCas();
    } catch (CASException e) {
      throw new ResourceProcessException(e);
    }

    // retreive the filename of the input file from the CAS
    File outFile = null;
    boolean hasDefaultView = false;

    if (mTEXT) {
      // get the default View if it exists
      try {
        jcas = aCAS.getView(CAS.NAME_DEFAULT_SOFA).getJCas();
        hasDefaultView = true;
        FSIterator it = jcas.getAnnotationIndex(SourceDocumentInformation.type).iterator();
        if (it.hasNext()) {
          // get the output file name from the annotation in the CAS ...
          // ... note this is a little flakey if processing an XCAS file,
          // which could have such an annotation with a different name than the input XCAS file!
          // So we don't do this if XCAS output is specified.
          SourceDocumentInformation fileLoc = (SourceDocumentInformation) it.next();
          File inFile;
          inFile = new File(new URL(fileLoc.getUri()).getPath());
          outFile = new File(mOutputDir, inFile.getName());
        }
      } catch (CASRuntimeException e) {
        // default Sofa name does not exist, use default processing below
      } catch (CASException e) {
        // invalid something (??), use default processing below
      } catch (MalformedURLException e1) {
        // invalid URL, use default processing below
      }
    }
    if (outFile == null) {
      // default processing, create a name for the output file
      outFile = new File(mOutputDir, "doc" + mDocNum++);
    }
    // convert CAS to xml format and write to output file in UTF-8
    FileOutputStream outStream = null;
    try {
      outStream = new FileOutputStream(outFile);
      if (hasDefaultView) {
        String xmlAnnotations = cas2xml.generateXML(aCAS);
        outStream.write(xmlAnnotations.getBytes("UTF-8"));
      } else {
        XMLSerializer xmlSer = new XMLSerializer(outStream, false);
        if (mXCAS.equalsIgnoreCase("xcas")) {
          XCASSerializer ser = new XCASSerializer(aCAS.getTypeSystem());
          ser.serialize(aCAS, xmlSer.getContentHandler());
        }
        else {
          XmiCasSerializer ser = new XmiCasSerializer(aCAS.getTypeSystem());
          ser.serialize(aCAS, xmlSer.getContentHandler());
        }
      }
    } catch (CASException e) {
      throw new ResourceProcessException(e);
    } catch (IOException e) {
      throw new ResourceProcessException(e);
    } catch (SAXException e) {
      throw new ResourceProcessException(e);
    } finally {
      if (outStream != null) {
        try {
          outStream.close();
        } catch (IOException e) {
View Full Code Here


    JCas jcas;
    try {
      jcas = aCAS.getJCas();
    } catch (CASException e) {
      throw new ResourceProcessException(e);
    }

    // retreive the filename of the input file from the CAS
    FSIterator it = jcas.getAnnotationIndex(SourceDocumentInformation.type).iterator();
    File outFile = null;
    if (it.hasNext()) {
      SourceDocumentInformation fileLoc = (SourceDocumentInformation) it.next();
      File inFile;
      try {
        inFile = new File(new URL(fileLoc.getUri()).getPath());
        String outFileName = inFile.getName();
        if (fileLoc.getOffsetInSource() > 0) {
          outFileName += ("_" + fileLoc.getOffsetInSource());
        }
        outFileName += ".xmi";
        outFile = new File(mOutputDir, outFileName);
        modelFileName = mOutputDir.getAbsolutePath() + "/" + inFile.getName() + ".ecore";
      } catch (MalformedURLException e1) {
        // invalid URL, use default processing below
      }
    }
    if (outFile == null) {
      outFile = new File(mOutputDir, "doc" + mDocNum++ + ".xmi"); // Jira UIMA-629
    }
    // serialize XCAS and write to output file
    try {
      writeXmi(jcas.getCas(), outFile, modelFileName);
    } catch (IOException e) {
      throw new ResourceProcessException(e);
    } catch (SAXException e) {
      throw new ResourceProcessException(e);
    }
  }
View Full Code Here

  public synchronized void processCas(CAS aCAS) throws ResourceProcessException
  {
    if (this.reconfig == true)
    {
      throw new ResourceProcessException(
        ResourceInitializationException.CONFIG_SETTING_ABSENT,
        new Object[] { "outputFile" });
    }

    //get low level CAS
    LowLevelCAS ll_cas = aCAS.getLowLevelCAS();

    //get low level TypeSystem
    LowLevelTypeSystem ll_typeSystem = ll_cas.ll_getTypeSystem();

    //get types and feature interessted in
    HashMap types = processTofs(aCAS, this.tofs);

    try
    {
      //iterate and print annotations
      FSIterator typeIterator = aCAS.getAnnotationIndex().iterator();

      for (typeIterator.moveToFirst(); typeIterator.isValid(); typeIterator.moveToNext())
      {
        Iterator it = types.keySet().iterator();

        while (it.hasNext())
        {
          //get current type and features
          Type currentType = (Type) it.next();
          boolean isFeatureOnly = false;
         
          ArrayList featureList = (ArrayList) types.get(currentType);
          if(featureList.size() >0 && featureList.get(0).equals(featureOnlyKey)){
            featureList.remove(0);
            isFeatureOnly = true;
          }
          Feature[] features = (Feature[]) featureList.toArray(new Feature[] {
          });
         
          AnnotationFS annot = (AnnotationFS) typeIterator.get();

          if (annot.getType().getName() == currentType.getName())
          {
            //only for formatting necessary
            boolean firstFeature = true;

            String span = annot.getCoveredText();
            if(!isFeatureOnly){
              this.fileWriter.write(
                annot.getType().getShortName()
                  + "(" + annot.getBegin() + "," + annot.getEnd()  + "): "  + span);
            }else{
              this.fileWriter.write(
                annot.getType().getShortName()
                  + ": ");
            }

            for (int f = 0; f < features.length; f++)
            {
              if (firstFeature)
              {
                this.fileWriter.write("  { ");
                firstFeature = false;
              }
              else
              {
                this.fileWriter.write(", ");
              }

              Feature fs = features[f];
              int typeClass = ll_cas.ll_getTypeClass(ll_typeSystem.ll_getCodeForType(fs.getRange()));
              this.fileWriter.write(fs.getShortName() + "=");
             
              switch (typeClass)
              {
                case LowLevelCAS.TYPE_CLASS_FLOAT :
                  this.fileWriter.write(Float.toString(annot.getFloatValue(fs)));
                  break;

                case LowLevelCAS.TYPE_CLASS_INT :
                  this.fileWriter.write(Integer.toString(annot.getIntValue(fs)));
                  break;

                case LowLevelCAS.TYPE_CLASS_STRING :
                  String value = annot.getStringValue(fs);
                  if(value != null) {
                    this.fileWriter.write(value)
                  } else {
                    this.fileWriter.write("null");
                  }
                  break;
               
                case LowLevelCAS.TYPE_CLASS_FS:
               
                  FeatureStructure fStruct = annot.getFeatureValue(fs);
                  if(fStruct != null) {
                    this.fileWriter.write(fStruct.toString())
                  } else {
                    this.fileWriter.write("null");
                  }
                  break;
              }
            }

            if (firstFeature == false)
            {
              this.fileWriter.write(" }");
            }

            this.fileWriter.write(System.getProperty("line.separator"));
          }

        }
      }

      this.fileWriter.flush();
    }
    catch (Exception ex)
    {
      throw new ResourceProcessException(ex);
    }

  }
View Full Code Here

              boolean releasedCas = false;
              for (int i = 0; i < casObjectList.length && casObjectList[i] != null; i++) {
                ChunkMetadata meta = CPMUtils.getChunkMetadata((CAS) casObjectList[i]);
                if (meta != null) {
                  if (timedoutDocs.containsKey(meta.getDocId())) {
                    notifyListeners(casList[i], new ResourceProcessException(new SkipCasException(
                            "Dropping CAS due chunk Timeout. Doc Id::" + meta.getDocId()
                                    + " Sequence:" + meta.getSequence())));

                    casPool.releaseCas((CAS) casObjectList[i]);
//                    synchronized (casPool) {  // redundant, releaseCas call does this
View Full Code Here

              UIMAFramework.getLogger(this.getClass()).logrb(Level.SEVERE,
                      this.getClass().getName(), "process", CPMUtils.CPM_LOG_RESOURCE_BUNDLE,
                      "UIMA_CPM_checkout_null_cp_from_container__SEVERE",
                      new Object[] { Thread.currentThread().getName(), containerName });
            }
            throw new ResourceProcessException(CpmLocalizedMessage.getLocalizedMessage(
                    CPMUtils.CPM_LOG_RESOURCE_BUNDLE,
                    "UIMA_CPM_EXP_invalid_component_reference__WARNING", new Object[] {
                        Thread.currentThread().getName(), "CasProcessor", "NULL" }), null);
          }
          // Check to see if the CasProcessor is available for processing
View Full Code Here

        // aContainer.incrementRestartCount(1);
        status = "success";
      } catch (ResourceProcessException rpe) {
        throw rpe;
      } catch (Exception rpe) {
        throw new ResourceProcessException(rpe);
      } finally {
        aProcessTrace.endEvent(containerName, "Process", status);
      }
    } catch (SkipCasException ex) {
      try {
        handleSkipCasProcessor(aContainer, aCasObjectList, false);
        retry = false;
      } catch (Exception sEx) {
        throw new ResourceProcessException(sEx);
      }
    } catch (Exception ex) {
      if (UIMAFramework.getLogger().isLoggable(Level.SEVERE)) {
        UIMAFramework.getLogger(this.getClass()).log(Level.SEVERE,
                Thread.currentThread().getName(), e);
View Full Code Here

    if (functionCounted >= functionCounter) {
      exceptionThrown();
      logger.log(LOG_LEVEL, "the function " + functionName
              + " is trying to throw the following exception: " + functionError);
      if (functionError.equals("ResourceProcessException")) {
        throw new ResourceProcessException();
      } else {
        throwAnException(functionError);
      }
    }
  }
View Full Code Here

        for (int i = 0; listeners != null && i < listeners.size(); i++) {
          ((UimaASStatusCallbackListener) listeners.get(i)).collectionProcessComplete(null);
        }
      }
    } catch (Exception e) {
      throw new ResourceProcessException(e);
    }
  }
View Full Code Here

    return null;
  }

  public synchronized void process() throws ResourceProcessException {
    if (!initialized) {
      throw new ResourceProcessException();
    }
    if (collectionReader == null) {
      throw new ResourceProcessException();
    }
    if (!casQueueProducerReady) {
      serveCASes(); // start CAS producer thread
    }
    CAS cas = null;
    boolean hasNext = true;
    while (initialized && running ) {
      try {
         if ( (hasNext = collectionReader.hasNext()) == true) {
             cas = getCAS();
             collectionReader.getNext(cas);
             sendCAS(cas);
         } else {
           break;
         }
      } catch (Exception e) {
        e.printStackTrace();
    throw new ResourceProcessException(e);
      }
    }
    //  If the CR is done, enter a polling loop waiting for outstanding CASes to return
    //  from a service
    if (hasNext == false ) {
      Object mObject = new Object();
      //  if client is running and there are outstanding CASe go sleep for awhile and
      //  try again, until all CASes come back from a service
      while ( running && serviceDelegate.getCasPendingReplyListSize() > 0 ) {
        synchronized(mObject) {
          try {
              mObject.wait(100);
          } catch( Exception e) {
                e.printStackTrace();
            throw new ResourceProcessException(e);
          }
        }
      }
      collectionProcessingComplete();
    }
View Full Code Here

   *
   */
  private String sendCAS(CAS aCAS, ClientRequest requestToCache) throws ResourceProcessException {
    synchronized (sendMux) {
      if ( requestToCache == null ) {
        throw new ResourceProcessException(new Exception("Invalid Process Request. Cache Entry is Null"));
      }
      String casReferenceId = requestToCache.getCasReferenceId();
      try {
        if (!running) {
          if (UIMAFramework.getLogger(CLASS_NAME).isLoggable(Level.INFO)) {
            UIMAFramework.getLogger(CLASS_NAME).logrb(Level.INFO, CLASS_NAME.getName(), "sendCAS",
                    JmsConstants.JMS_LOG_RESOURCE_BUNDLE, "UIMAJMS_not_sending_cas_INFO",
                    new Object[] { "Asynchronous Client is Stopping" });
          }
          return null;
        }

        clientCache.put(casReferenceId, requestToCache);
        PendingMessage msg = new PendingMessage(AsynchAEMessage.Process);
        long t1 = System.nanoTime();
        if (serializationStrategy.equals("xmi")) {
          XmiSerializationSharedData serSharedData = new XmiSerializationSharedData();
          String serializedCAS = serializeCAS(aCAS, serSharedData);
          msg.put(AsynchAEMessage.CAS, serializedCAS);
          if (remoteService) {
            requestToCache.setCAS(aCAS);
            // Store the serialized CAS in case the timeout occurs and need to send the
            // the offending CAS to listeners for reporting
            requestToCache.setCAS(serializedCAS);
            requestToCache.setXmiSerializationSharedData(serSharedData);
          }
        } else {
          byte[] serializedCAS = uimaSerializer.serializeCasToBinary(aCAS);
          msg.put(AsynchAEMessage.CAS, serializedCAS);
          if (remoteService) {
            requestToCache.setCAS(aCAS);
          }
        }

        requestToCache.setSerializationTime(System.nanoTime() - t1);
        msg.put(AsynchAEMessage.CasReference, casReferenceId);
        requestToCache.setIsRemote(remoteService);
        requestToCache.setEndpoint(getEndPointName());
        requestToCache.setProcessTimeout(processTimeout);
        requestToCache.clearTimeoutException();

        // The sendCAS() method is synchronized no need to synchronize the code below
        if (serviceDelegate.getState() == Delegate.TIMEOUT_STATE ) {
          SharedConnection sharedConnection = lookupConnection(getBrokerURI());
         
          //  Send Ping to service as getMeta request
          if ( !serviceDelegate.isAwaitingPingReply() && sharedConnection.isOpen() ) {
            serviceDelegate.setAwaitingPingReply();
            // Add the cas to a list of CASes pending reply. Also start the timer if necessary
      // serviceDelegate.addCasToOutstandingList(requestToCache.getCasReferenceId());
           
            // since the service is in time out state, we dont send CASes to it just yet. Instead, place
            // a CAS in a pending dispatch list. CASes from this list will be sent once a response to PING
            // arrives.
            serviceDelegate.addCasToPendingDispatchList(requestToCache.getCasReferenceId(), aCAS.hashCode());
            if ( cpcReadySemaphore.availablePermits() > 0 ) {
              acquireCpcReadySemaphore();
            }

            // Send PING Request to check delegate's availability
            sendMetaRequest();
            // @@@@@@@@@@@@@@@ Changed on 4/20 serviceDelegate.cancelDelegateTimer();
            // Start a timer for GetMeta ping and associate a cas id
            // with this timer. The delegate is currently in a timed out
            // state due to a timeout on a CAS with a given casReferenceId.
            // 
            serviceDelegate.startGetMetaRequestTimer(casReferenceId);
           
            if (UIMAFramework.getLogger(CLASS_NAME).isLoggable(Level.INFO)) {
              UIMAFramework.getLogger(CLASS_NAME).logrb(Level.INFO, CLASS_NAME.getName(), "sendCAS",
                      JmsConstants.JMS_LOG_RESOURCE_BUNDLE, "UIMAJMS_client_sending_ping__FINE",
                      new Object[] { serviceDelegate.getKey() });
            }
            return casReferenceId;
          } else {
            if ( !requestToCache.isSynchronousInvocation() && !sharedConnection.isOpen() ) {
              Exception exception = new BrokerConnectionException("Unable To Deliver CAS:"+requestToCache.getCasReferenceId()+" To Destination. Connection To Broker "+getBrokerURI()+" Has Been Lost");
              handleException(exception, requestToCache.getCasReferenceId(), null, requestToCache, true);
              return casReferenceId;
            } else {
              //  Add to the outstanding list. 
        //  serviceDelegate.addCasToOutstandingList(requestToCache.getCasReferenceId());
            // since the service is in time out state, we dont send CASes to it just yet. Instead, place
            // a CAS in a pending dispatch list. CASes from this list will be sent once a response to PING
            // arrives.
              serviceDelegate.addCasToPendingDispatchList(requestToCache.getCasReferenceId(), aCAS.hashCode());
              return casReferenceId;
            }
          }
        }
        SharedConnection sharedConnection = lookupConnection(getBrokerURI());
        if ( !sharedConnection.isOpen() ) {
          if (requestToCache != null && !requestToCache.isSynchronousInvocation() && aCAS != null ) {
            aCAS.release();
          }
          throw new ResourceProcessException(new BrokerConnectionException("Unable To Deliver Message To Destination. Connection To Broker "+sharedConnection.getBroker()+" Has Been Lost"));
        }   
        // Incremented number of outstanding CASes sent to a service. When a reply comes
        // this counter is decremented
        outstandingCasRequests.incrementAndGet();
        // Increment total number of CASes sent to a service. This is reset
        // on CPC
        totalCasRequestsSentBetweenCpCs.incrementAndGet();
        // Add message to the pending queue
        addMessage(msg);
      } catch (ResourceProcessException e) {
        clientCache.remove(casReferenceId);
        throw e;
      } catch (Exception e) {
        clientCache.remove(casReferenceId);
        throw new ResourceProcessException(e);
      }
      return casReferenceId;
    }
  }
View Full Code Here

TOP

Related Classes of org.apache.uima.resource.ResourceProcessException

Copyright © 2018 www.massapicom. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.