Package org.apache.sandesha2.storage

Examples of org.apache.sandesha2.storage.Transaction


  public void run () {
   
    if (log.isDebugEnabled())
      log.debug("Enter: SenderWorker::run");

    Transaction transaction = null;
   
    try {
      StorageManager storageManager = SandeshaUtil.getSandeshaStorageManager(configurationContext, configurationContext.getAxisConfiguration());
      SenderBeanMgr senderBeanMgr = storageManager.getSenderBeanMgr();

      transaction = storageManager.getTransaction();

      String key = senderBean.getMessageContextRefKey();
      MessageContext msgCtx = null;
      RMMsgContext   rmMsgCtx = null;
      if(messageToSend != null) {
        msgCtx = messageToSend.getMessageContext();
        rmMsgCtx = messageToSend;
      } else {
        msgCtx = storageManager.retrieveMessageContext(key, configurationContext);
     
        if (msgCtx == null) {
          // This sender bean has already been processed
         
          if(transaction != null && transaction.isActive()) transaction.commit();
          transaction = null;

          return;
        }
     
        rmMsgCtx = MsgInitializer.initializeMessage(msgCtx);
      }

      // sender will not send the message if following property is
      // set and not true.
      // But it will set if it is not set (null)

      // This is used to make sure that the mesage get passed the
      // Sandesha2TransportSender.

      String qualifiedForSending = (String) msgCtx.getProperty(Sandesha2Constants.QUALIFIED_FOR_SENDING);
      if (qualifiedForSending != null && !qualifiedForSending.equals(Sandesha2Constants.VALUE_TRUE)) {
        if (log.isDebugEnabled())
          log.debug("Exit: SenderWorker::run, !qualified for sending");
       
        if(transaction != null && transaction.isActive()) {
          transaction.commit();
          transaction = null;
        }
       
        return;
      }

      if (msgCtx == null) {
        if (log.isDebugEnabled())
          log.debug(SandeshaMessageHelper.getMessage(SandeshaMessageKeys.sendHasUnavailableMsgEntry));
       
        if(transaction != null && transaction.isActive()) {
          transaction.commit();
          transaction = null;
        }
       
        return;     
      }

      // operation is the lowest level Sandesha2 should be attached
      ArrayList msgsNotToSend = SandeshaUtil.getPropertyBean(msgCtx.getAxisOperation()).getMsgTypesToDrop();

      if (msgsNotToSend != null && msgsNotToSend.contains(new Integer(rmMsgCtx.getMessageType()))) {
        if (log.isDebugEnabled())
          log.debug("Exit: SenderWorker::run, message type to be dropped " + rmMsgCtx.getMessageType());
       
        if(transaction != null && transaction.isActive()) {
          transaction.commit();
          transaction = null;
        }
       
        return
      }

      // If we are sending to the anonymous URI then we _must_ have a transport waiting,
      // or the message can't go anywhere. If there is nothing here then we leave the
      // message in the sender queue, and a MakeConnection (or a retransmitted request)
      // will hopefully pick it up soon.
      Boolean makeConnection = (Boolean) msgCtx.getProperty(Sandesha2Constants.MAKE_CONNECTION_RESPONSE);
      EndpointReference toEPR = msgCtx.getTo();

      MessageContext inMsg = null;
      OperationContext op = msgCtx.getOperationContext();
     
      RequestResponseTransport t = (RequestResponseTransport) msgCtx.getProperty(RequestResponseTransport.TRANSPORT_CONTROL);
     
      if (t==null) {
        if (op != null)
          inMsg = op.getMessageContext(WSDLConstants.MESSAGE_LABEL_IN_VALUE);
        if (inMsg != null)
          t = (RequestResponseTransport) inMsg.getProperty(RequestResponseTransport.TRANSPORT_CONTROL);
      }

      // If we are anonymous, and this is not a makeConnection, then we must have a transport waiting
      if((toEPR==null || toEPR.hasAnonymousAddress()) &&
         (makeConnection == null || !makeConnection.booleanValue()) &&
         (t != null && !t.getStatus().equals(RequestResponseTransportStatus.WAITING))) {
       
        // Mark this sender bean so that we know that the transport is unavailable, if the
        // bean is still stored.
        SenderBean bean = senderBeanMgr.retrieve(senderBean.getMessageID());
        if(bean != null && bean.isTransportAvailable()) {
          bean.setTransportAvailable(false);
          senderBeanMgr.update(bean);
        }
       
        // Commit the update
        if(transaction != null && transaction.isActive()) transaction.commit();
        transaction = null;
       
        if (log.isDebugEnabled())
          log.debug("Exit: SenderWorker::run, no response transport for anonymous message");
        return;
      }
     
      //if the message belong to the Replay Model, it will be send out only if


      boolean continueSending = updateMessage(rmMsgCtx,senderBean,storageManager);
      //save changes done @ updateMessage -> MessageRetransmissionAdjuster.adjustRetransmittion
      storageManager.getSenderBeanMgr().update(senderBean);
     

      if (!continueSending) {
        if (log.isDebugEnabled())
          log.debug("Exit: SenderWorker::run, !continueSending");
       
        if(transaction != null && transaction.isActive()) {
          transaction.commit();
          transaction = null;
        }
        invokeCallBackObject(storageManager,msgCtx ,"Exit: SenderWorker::run, !continueSending");
        return;
      }

      int messageType = senderBean.getMessageType();
     
      if (isAckPiggybackableMsgType(messageType)) {
        // Commit the update
        if(transaction != null && transaction.isActive()) transaction.commit();
        transaction = storageManager.getTransaction();

        // Piggyback ack messages based on the 'To' address of the message
        transaction = AcknowledgementManager.piggybackAcksIfPresent(rmMsgCtx, storageManager, transaction);
      }

      // sending the message
      boolean successfullySent = false;

      // Although not actually sent yet, update the send count to indicate an attempt
      if (senderBean.isReSend()) {
        SenderBean bean2 = senderBeanMgr.retrieve(senderBean.getMessageID());
        if (bean2 != null) {
          bean2.setSentCount(senderBean.getSentCount());
          senderBeanMgr.update(bean2);
        }
      }

      // have to commit the transaction before sending. This may
      // get changed when WS-AT is available.
      if(transaction != null) {
        transaction.commit();
        transaction = null;
      }

      msgCtx.getOptions().setTimeOutInMilliSeconds(1000000);
     
      boolean processResponseForFaults = false ;
      try {
        InvocationResponse response = InvocationResponse.CONTINUE;
       
        SandeshaPolicyBean policy = SandeshaUtil.getPropertyBean(msgCtx.getAxisOperation());
        if(policy.isUseMessageSerialization()) {
          if(msgCtx.isPaused()) {
            if (log.isDebugEnabled())
              log.debug("Resuming a send for message : " + msgCtx.getEnvelope().getHeader());
            msgCtx.setPaused(false);
            msgCtx.setProperty(MessageContext.TRANSPORT_NON_BLOCKING, Boolean.FALSE);
            response = AxisEngine.resumeSend(msgCtx);
          } else {
            if (log.isDebugEnabled())
              log.debug("Sending a message : " + msgCtx.getEnvelope().getHeader());
            msgCtx.setProperty(MessageContext.TRANSPORT_NON_BLOCKING, Boolean.FALSE);
            AxisEngine.send(msgCtx)// TODO check if this should return an invocation response
          }
        } else {
          // had to fully build the SOAP envelope to support
          // retransmissions.
          // Otherwise a 'parserAlreadyAccessed' exception could
          // get thrown in retransmissions.
          // But this has a performance reduction.
          msgCtx.getEnvelope().build();
 
          ArrayList retransmittablePhases = (ArrayList) msgCtx.getProperty(Sandesha2Constants.RETRANSMITTABLE_PHASES);
          if (retransmittablePhases!=null) {
            msgCtx.setExecutionChain(retransmittablePhases);
          } else {
            ArrayList emptyExecutionChain = new ArrayList ();
            msgCtx.setExecutionChain(emptyExecutionChain);
          }
         
          msgCtx.setCurrentHandlerIndex(0);
          msgCtx.setCurrentPhaseIndex(0);
          msgCtx.setPaused(false);
       
          if (log.isDebugEnabled())
            log.debug("Resuming a send for message : " + msgCtx.getEnvelope().getHeader());
          response = AxisEngine.resumeSend(msgCtx);
        }
        if(log.isDebugEnabled()) log.debug("Engine resume returned " + response);
        if(response != InvocationResponse.SUSPEND) {
          if(t != null) {
            if(log.isDebugEnabled()) log.debug("Signalling transport in " + t);
            t.signalResponseReady();
          }
        }
       
        successfullySent = true;
       
      } catch (AxisFault e) {
        //this is a possible SOAP 1.2 Fault. So letting it proceed.
       
        processResponseForFaults = true;
       
        recordError(e, rmMsgCtx, storageManager);
       
      } catch (Exception e) {
        String message = SandeshaMessageHelper.getMessage(
            SandeshaMessageKeys.sendMsgError, e.toString());
       
        if (log.isErrorEnabled())
          log.error(message, e);
       
        recordError(e, rmMsgCtx, storageManager);
       
      }
      // Establish the transaction for post-send processing
      transaction = storageManager.getTransaction();

      // update or delete only if the object is still present.
      SenderBean bean1 = senderBeanMgr
          .retrieve(senderBean.getMessageID());
      if (bean1 != null) {
        if (senderBean.isReSend()) {
          bean1.setTimeToSend(senderBean.getTimeToSend());
          senderBeanMgr.update(bean1);
        }
      }

      // Commit the transaction to release the SenderBean

      if (transaction!=null)
        transaction.commit();
     
      transaction = null;

            if ((processResponseForFaults || successfullySent) && !msgCtx.isServerSide()) {
                boolean  validCs = checkForSyncResponses(msgCtx );
                if (!validCs) {
                    invokeCallBackObject(storageManager,msgCtx ,
                            "Sandesha2 sender thread has not received a valid CreateSequnceResponse");
                }
            }

            if ((rmMsgCtx.getMessageType() == Sandesha2Constants.MessageTypes.TERMINATE_SEQ)
          &&
           (Sandesha2Constants.SPEC_2005_02.NS_URI.equals(rmMsgCtx.getRMNamespaceValue()))) {
        try {
          transaction = storageManager.getTransaction();
          //terminate message sent using the SandeshaClient. Since the terminate message will simply get the
          //InFlow of the reference message get called which could be zero sized (OutOnly operations).
         
          // terminate sending side if this is the WSRM 1.0 spec.
          // If the WSRM versoion is 1.1 termination will happen in the terminate sequence response message.
         
          TerminateSequence terminateSequence = (TerminateSequence) rmMsgCtx
              .getMessagePart(Sandesha2Constants.MessageParts.TERMINATE_SEQ);
          String sequenceID = terminateSequence.getIdentifier().getIdentifier();
 
          RMSBean rmsBean = SandeshaUtil.getRMSBeanFromSequenceId(storageManager, sequenceID);
          TerminateManager.terminateSendingSide(rmsBean, storageManager);
         
          if(transaction != null && transaction.isActive()) transaction.commit();
          transaction = null;
        } finally {
          if(transaction != null && transaction.isActive()) {
            transaction.rollback();
            transaction = null;
          }
        }
      }

    } catch (Exception e) {
      if (log.isDebugEnabled()) log.debug("Caught exception", e);
    } finally {
      if (lock!=null && workId!=null) {
        lock.removeWork(workId);
      }

      if (transaction!=null && transaction.isActive()) {
        try {
          transaction.rollback();
        } catch (SandeshaStorageException e) {
          if (log.isWarnEnabled())
            log.warn("Caught exception rolling back transaction", e);
        }
      }
View Full Code Here


 
  private void recordError (Exception e, RMMsgContext outRMMsg, StorageManager storageManager) throws SandeshaStorageException {
    // Store the Exception as a sequence property to enable the client to lookup the last
    // exception time and timestamp.
   
    Transaction transaction = null;
   
    try
    {
      // Get the internal sequence id from the context
      String internalSequenceId = (String)outRMMsg.getProperty(Sandesha2Constants.MessageContextProperties.INTERNAL_SEQUENCE_ID);
      if(internalSequenceId == null) internalSequenceId = senderBean.getInternalSequenceID();
     
      if(internalSequenceId != null) {
        // Create a new Transaction
        transaction = storageManager.getTransaction();
       
        RMSBean bean = SandeshaUtil.getRMSBeanFromInternalSequenceId(storageManager, internalSequenceId);
     
        if (bean != null) {           
          bean.setLastSendError(e);
          bean.setLastSendErrorTimestamp(System.currentTimeMillis());

          // Update the RMSBean
          storageManager.getRMSBeanMgr().update(bean);
        }
       
        // Commit the properties
        if(transaction != null) {
          transaction.commit();
          transaction = null;
        }
      }
    }
    catch (Exception e1)
    {
      if (log.isErrorEnabled())
        log.error(e1);
    } finally {
      if (transaction != null) {
        transaction.rollback();
        transaction = null;
      }
    }
  }
View Full Code Here

  }

    private void invokeCallBackObject(StorageManager storageManager,
                                      MessageContext msgCtx,
                                      String message) throws SandeshaStorageException {
        Transaction transaction = null;
        if (msgCtx.isServerSide()) {
            return;
        }
        try {
            transaction = storageManager.getTransaction();
            //terminate message sent using the SandeshaClient. Since the terminate message will simply get the
            //InFlow of the reference message get called which could be zero sized (OutOnly operations).

            // terminate sending side if this is the WSRM 1.0 spec.
            // If the WSRM versoion is 1.1 termination will happen in the terminate sequence response message.

            String internalSequenceId = (String) msgCtx.getProperty(Sandesha2Constants.MessageContextProperties.INTERNAL_SEQUENCE_ID);
            if (internalSequenceId == null) internalSequenceId = senderBean.getInternalSequenceID();
            if (internalSequenceId != null) {
                // Create a new Transaction
                transaction = storageManager.getTransaction();
                RMSBean bean = SandeshaUtil.getRMSBeanFromInternalSequenceId(storageManager, internalSequenceId);
                TerminateManager.terminateSendingSide(bean, storageManager);

                OperationContext opCtx =
                        configurationContext.getOperationContext(bean.getApplicationMessageMessageId());
                if (opCtx != null) {
                    AxisOperation applicationAxisOperation = opCtx.getAxisOperation();
                    if (applicationAxisOperation != null) {
                        MessageReceiver msgReceiver = applicationAxisOperation.getMessageReceiver();
                        if ((msgReceiver != null) && (msgReceiver instanceof CallbackReceiver)) {
                            Object callback = ((CallbackReceiver) msgReceiver)
                                    .lookupCallback(bean.getApplicationMessageMessageId());
                            if (callback != null) {
                                AxisCallback axisCallback = ((AxisCallback) callback);
                                axisCallback.onError(new Exception(message));
                                axisCallback.onComplete();
                            }
                        }
                    }
                }
                if (transaction != null && transaction.isActive()) transaction.commit();
                transaction = null;
            }

        } catch (Exception e) {
            if (log.isWarnEnabled())
                log.warn(e);
        } finally {
            if (transaction != null && transaction.isActive()) {
                transaction.rollback();
                transaction = null;
            }
        }
    }
View Full Code Here

    // Note that some messages (such as stand-alone acks) will be routed here, but
    // the headers will already have been processed. Therefore we should not assume
    // that we will have a MsgProcessor every time.
    MsgProcessor msgProcessor = MsgProcessorFactory.getMessageProcessor(rmMsgCtx);
    if(msgProcessor != null) {
      Transaction transaction = null;
     
      if (msgCtx.getAxisService() != null) {
        Parameter unreliableParam = msgCtx.getAxisService().getParameter(SandeshaClientConstants.UNRELIABLE_MESSAGE);
        if (null != unreliableParam && "true".equals(unreliableParam.getValue())) {
         
          if (rmMsgCtx.getMessageType() == Sandesha2Constants.MessageTypes.CREATE_SEQ)
            FaultManager.makeCreateSequenceRefusedFault(rmMsgCtx,
                SandeshaMessageHelper.getMessage(SandeshaMessageKeys.reliableMessagingNotEnabled, msgCtx.getAxisService().getName()),
                new Exception());
          else
            throw new AxisFault(SandeshaMessageHelper.getMessage(SandeshaMessageKeys.reliableMessagingNotEnabled, msgCtx.getAxisService().getName()));
         
          log.debug("Exit: RMMessageReceiver::invokeBusinessLogic, Service has disabled RM ");
          return;
        }
      }

      try {
        ConfigurationContext context = msgCtx.getConfigurationContext();
        StorageManager storageManager = SandeshaUtil.getSandeshaStorageManager(context, context.getAxisConfiguration());       
        transaction = storageManager.getTransaction();

        msgProcessor.processInMessage(rmMsgCtx, transaction);

        if(transaction != null && transaction.isActive()) transaction.commit();
          transaction = null;

      } catch (Exception e) {
        if (log.isDebugEnabled())
          log.debug("Exception caught during processInMessage", e);
        // message should not be sent in a exception situation.
        msgCtx.pause();
 
        if (!(e instanceof AxisFault)) {
          String message = SandeshaMessageHelper.getMessage(SandeshaMessageKeys.inMsgError, e.toString());
          throw new AxisFault(message, e);
        }
       
        throw (AxisFault)e;
      } finally {
        if (transaction != null && transaction.isActive()) {
          try {
            transaction.rollback();
          } catch (Exception e1) {
            String message = SandeshaMessageHelper.getMessage(SandeshaMessageKeys.rollbackError, e1.toString());
            log.debug(message, e1);
          }
        }
View Full Code Here

    }
   
    msgCtx.setProperty(Sandesha2Constants.APPLICATION_PROCESSING_DONE, "true");
    StorageManager storageManager = SandeshaUtil.getSandeshaStorageManager(context, context.getAxisConfiguration());

    Transaction transaction = null;

    try {
      transaction = storageManager.getTransaction();
     
      // getting rm message
      RMMsgContext rmMsgCtx = MsgInitializer.initializeMessage(msgCtx);

      MsgProcessor msgProcessor = null;
      int messageType = rmMsgCtx.getMessageType();
      if(log.isDebugEnabled()) log.debug("Message Type: " + messageType);
      if (messageType == Sandesha2Constants.MessageTypes.UNKNOWN) {
                if (msgCtx.isServerSide()) {
                  String inboundSequence = (String) msgCtx.getProperty(Sandesha2Constants.MessageContextProperties.INBOUND_SEQUENCE_ID);
                  Long   msgNum = (Long) msgCtx.getProperty(Sandesha2Constants.MessageContextProperties.INBOUND_MESSAGE_NUMBER);
                 
                    if (inboundSequence != null && msgNum != null) {
                  msgProcessor = new ApplicationMsgProcessor(inboundSequence, msgNum.longValue());
                    }
                } else // if client side.
                    msgProcessor = new ApplicationMsgProcessor();
               
      } else {
        msgProcessor = MsgProcessorFactory.getMessageProcessor(rmMsgCtx);
      }

      if (msgProcessor != null){
        if(msgProcessor.processOutMessage(rmMsgCtx)){
          //the msg was paused
          returnValue = InvocationResponse.SUSPEND;
        }
      } else if (messageType==Sandesha2Constants.MessageTypes.ACK_REQUEST) {
        AckRequestedProcessor ackRequestedProcessor = new AckRequestedProcessor ();
        if(ackRequestedProcessor.processOutgoingAckRequestMessage (rmMsgCtx)){
          //the msg was paused
          returnValue = InvocationResponse.SUSPEND;
        }
      }
       
      //we need the incoming thread to wait when suspending.
      //Hence adding the boolean property.
      //Should be done only to the server side
      OperationContext opCtx = msgCtx.getOperationContext();
      if(msgCtx.isServerSide() && opCtx != null && returnValue == InvocationResponse.SUSPEND) {
        if(log.isDebugEnabled()) log.debug("Setting HOLD_RESPONSE property");
        opCtx.setProperty(RequestResponseTransport.HOLD_RESPONSE, Boolean.TRUE);
      }

      if (transaction != null && transaction.isActive()) transaction.commit();
      transaction = null;

    } catch (Exception e) {
      // message should not be sent in a exception situation.
      msgCtx.pause();
      returnValue = InvocationResponse.SUSPEND;

      String message = SandeshaMessageHelper.getMessage(SandeshaMessageKeys.outMsgError, e.toString());
      throw new AxisFault(message, e);

    } finally {
      // roll back the transaction
      if (transaction != null && transaction.isActive()) {
        try {
          transaction.rollback();
        } catch (Exception e1) {
          String message = SandeshaMessageHelper.getMessage(SandeshaMessageKeys.rollbackError, e1.toString());
          log.debug(message, e1);
        }
      }
View Full Code Here

  }

  protected boolean internalRun() {
    if (log.isDebugEnabled()) log.debug("Enter: Sender::internalRun");

    Transaction transaction = null;
    boolean sleep = false;

    try {
      // Pick a sequence using a round-robin approach
      ArrayList allSequencesList = getSequences();
      int size = allSequencesList.size();

      if (log.isDebugEnabled())
        log.debug("Choosing one from " + size + " sequences");
      if(nextIndex >= size) {
        nextIndex = 0;

        // We just looped over the set of sequences. If we didn't process any
        // messages on this loop then we sleep before the next one
        if(size == 0 || !processedMessage) {
          sleep = true;
        }
        processedMessage = false;
       
        // At this point - delete any sequences that have timed out, or been terminated.
        deleteTerminatedSequences(storageManager);

        // Also clean up and sender beans that are not yet eligible for sending, but
        // are blocking the transport threads.
        unblockTransportThreads(storageManager);
       
        // Finally, check for messages that can only be serviced by polling, and warn
        // the user if they are too old
        checkForOrphanMessages(storageManager);

        if (log.isDebugEnabled()) log.debug("Exit: Sender::internalRun, looped over all sequences, sleep " + sleep);
        return sleep;
      }
     
      transaction = storageManager.getTransaction();

      SequenceEntry entry = (SequenceEntry) allSequencesList.get(nextIndex++);
      String sequenceId = entry.getSequenceId();
      if (log.isDebugEnabled())
        log.debug("Chose sequence " + sequenceId);

      String rmVersion = null;
      // Check that the sequence is still valid
      boolean found = false;
      if(entry.isRmSource()) {
        RMSBean matcher = new RMSBean();
        matcher.setInternalSequenceID(sequenceId);
        matcher.setTerminated(false);
        RMSBean rms = storageManager.getRMSBeanMgr().findUnique(matcher);
        if(rms != null && !rms.isTerminated() && !rms.isTimedOut()) {
          sequenceId = rms.getSequenceID();         
          if (SequenceManager.hasSequenceTimedOut(rms, sequenceId, storageManager))         
            SequenceManager.finalizeTimedOutSequence(rms.getInternalSequenceID(), null, storageManager);
          else
            found = true;
          rmVersion = rms.getRMVersion();
        }
       
      } else {
        RMDBean matcher = new RMDBean();
        matcher.setSequenceID(sequenceId);
        matcher.setTerminated(false);
        RMDBean rmd = storageManager.getRMDBeanMgr().findUnique(matcher);
        if(rmd != null) {
          found = true;
          rmVersion = rmd.getRMVersion();
        }
      }
      if (!found) {
        stopThreadForSequence(sequenceId, entry.isRmSource());
        if (log.isDebugEnabled()) log.debug("Exit: Sender::internalRun, sequence has ended");
       
        if(transaction != null && transaction.isActive()) {
          transaction.commit();
          transaction = null;
        }
       
        return false;
      }
     
      SenderBeanMgr mgr = storageManager.getSenderBeanMgr();
      SenderBean senderBean = mgr.getNextMsgToSend(sequenceId);
     
     
     
      if (senderBean == null ||
          (!senderBean.isReSend() && senderBean.getSentCount()>0)) {
       
        //We will be not proceeding if
        //senderBean is Null
        //OR
        //Sender bean is not valid for re-sending.
       
        if (log.isDebugEnabled()) log.debug("Exit: Sender::internalRun, no message for this sequence");
       
        if(transaction != null && transaction.isActive()) {
          transaction.commit();
          transaction = null;
        }
       
        return false; // Move on to the next sequence in the list
      }

      // work Id is used to define the piece of work that will be
      // assigned to the Worker thread,
      // to handle this Sender bean.
     
      //workId contains a timeTiSend part to cater for retransmissions.
      //This will cause retransmissions to be treated as new work.
      String workId = senderBean.getMessageID() + senderBean.getTimeToSend();

      // check weather the bean is already assigned to a worker.
      if (getWorkerLock().isWorkPresent(workId)) {
        // As there is already a worker running we are probably looping
        // too fast, so sleep on the next loop.
        if (log.isDebugEnabled()) {
          String message = SandeshaMessageHelper.getMessage(
                  SandeshaMessageKeys.workAlreadyAssigned,
                  workId);
          log.debug("Exit: Sender::internalRun, " + message + ", sleeping");
        }
       
        if(transaction != null && transaction.isActive()) {
          transaction.commit();
          transaction = null;
        }
       
        return true;
      }

      //commiting the transaction here to release resources early.
      if(transaction != null && transaction.isActive()) transaction.commit();
      transaction = null;

      // start a worker which will work on this messages.
      SenderWorker worker = new SenderWorker(context, senderBean, rmVersion);
      worker.setLock(getWorkerLock());
      worker.setWorkId(workId);
      threadPool.execute(worker);

      // adding the workId to the lock after assigning it to a thread
      // makes sure
      // that all the workIds in the Lock are handled by threads.
      getWorkerLock().addWork(workId);

      // If we got to here then we found work to do on the sequence, so we should
      // remember not to sleep at the end of the list of sequences.
      processedMessage = true;
     
    } catch (Exception e) {

      // TODO : when this is the client side throw the exception to
      // the client when necessary.

     
      //TODO rollback only if a SandeshaStorageException.
      //This allows the other Exceptions to be used within the Normal flow.
     
      String message = SandeshaMessageHelper.getMessage(SandeshaMessageKeys.sendMsgError, e.toString());
      log.debug(message, e);
    } finally {
      if (transaction != null && transaction.isActive()) {
        try {
          transaction.rollback();
          transaction = null;
        } catch (Exception e) {
          String message = SandeshaMessageHelper
              .getMessage(SandeshaMessageKeys.rollbackError, e.toString());
          log.debug(message, e);
View Full Code Here

      log.debug("Enter: Sender::deleteTerminatedSequences");

    RMSBean finderBean = new RMSBean();
    finderBean.setTerminated(true);
   
    Transaction transaction = null;
   
    try {
      transaction = storageManager.getTransaction();
     
      SandeshaPolicyBean propertyBean =
        SandeshaUtil.getPropertyBean(storageManager.getContext().getAxisConfiguration());     

      long deleteTime = propertyBean.getSequenceRemovalTimeoutInterval();
      if (deleteTime < 0)
        deleteTime = 0;

      if (deleteTime > 0) {
        // Find terminated sequences.
        List rmsBeans = storageManager.getRMSBeanMgr().find(finderBean);
       
        deleteRMSBeans(rmsBeans, propertyBean, deleteTime);
       
        finderBean.setTerminated(false);
        finderBean.setTimedOut(true);
       
        // Find timed out sequences
        rmsBeans = storageManager.getRMSBeanMgr().find(finderBean);
             
        deleteRMSBeans(rmsBeans, propertyBean, deleteTime);
       
        // Remove any terminated RMDBeans.
        RMDBean finderRMDBean = new RMDBean();
        finderRMDBean.setTerminated(true);
       
        List rmdBeans = storageManager.getRMDBeanMgr().find(finderRMDBean);
 
        Iterator beans = rmdBeans.iterator();
        while (beans.hasNext()) {
          RMDBean rmdBean = (RMDBean)beans.next();
         
          long timeNow = System.currentTimeMillis();
          long lastActivated = rmdBean.getLastActivatedTime();
 
          // delete sequences that have been timedout or deleted for more than
          // the SequenceRemovalTimeoutInterval
          if ((lastActivated + deleteTime) < timeNow) {
            if (log.isDebugEnabled())
              log.debug("Deleting RMDBean " + deleteTime + " : " + rmdBean);
            storageManager.getRMDBeanMgr().delete(rmdBean.getSequenceID());
          }               
        }
      }

      // Terminate RMD Sequences that have been inactive.     
      if (propertyBean.getInactivityTimeoutInterval() > 0) {
        RMDBean finderRMDBean = new RMDBean();
        finderRMDBean.setTerminated(false);
       
        List rmdBeans = storageManager.getRMDBeanMgr().find(finderRMDBean);
     
        Iterator beans = rmdBeans.iterator();
        while (beans.hasNext()) {
          RMDBean rmdBean = (RMDBean)beans.next();
         
          long timeNow = System.currentTimeMillis();
          long lastActivated = rmdBean.getLastActivatedTime();
         
          if ((lastActivated + propertyBean.getInactivityTimeoutInterval()) < timeNow) {
            // Terminate
            rmdBean.setTerminated(true);
            rmdBean.setLastActivatedTime(timeNow);
            if (log.isDebugEnabled())
              log.debug(System.currentTimeMillis() + "Marking RMDBean as terminated " + rmdBean);
            storageManager.getRMDBeanMgr().update(rmdBean);
          }               
        }
      }      
     
      if(transaction != null && transaction.isActive()) transaction.commit();
     
    } catch (SandeshaException e) {
      if (log.isErrorEnabled())
        log.error(e);
    } finally {
      if(transaction != null && transaction.isActive()) {
        try {
          transaction.rollback();
        } catch (SandeshaStorageException e) {
          if (log.isDebugEnabled())
            log.debug("Caught exception rolling back transaction", e);
        }
      }
View Full Code Here

  private void unblockTransportThreads(StorageManager manager)
  throws SandeshaStorageException
  {
    if (log.isDebugEnabled()) log.debug("Enter: Sender::unblockTransportThreads");

    Transaction transaction = null;
    try {
      transaction = manager.getTransaction();
     
      // This finder will look for beans that have been locking the transport for longer than
      // the TRANSPORT_WAIT_TIME. The match method for SenderBeans does the time comparison
      // for us.
      SenderBean finder = new SenderBean();
      finder.setSend(false);
      finder.setTransportAvailable(true);
      finder.setTimeToSend(System.currentTimeMillis() - Sandesha2Constants.TRANSPORT_WAIT_TIME);
     
      List beans = manager.getSenderBeanMgr().find(finder);
      Iterator beanIter = beans.iterator();
      while(beanIter.hasNext()) {
        // The beans we have found are assigned to an internal sequence id, but the create
        // sequence has not completed yet (and perhaps never will). Server-side, most of the
        // info that we can usefully print is associated with the inbound sequence that generated
        // this message.
        SenderBean bean = (SenderBean) beanIter.next();
       
        // Load the message, so that we can free the transport (if there is one there). The
        // case we are trying to free up is when there is a request-response transport, and
        // it's still there waiting.
        MessageContext msgCtx = manager.retrieveMessageContext(bean.getMessageContextRefKey(), context);

        RequestResponseTransport t = null;
        MessageContext inMsg = null;
        OperationContext op = msgCtx.getOperationContext();
        if (op != null)
          inMsg = op.getMessageContext(WSDLConstants.MESSAGE_LABEL_IN_VALUE);
        if (inMsg != null)
          t = (RequestResponseTransport) inMsg.getProperty(RequestResponseTransport.TRANSPORT_CONTROL);
 
        if((t != null && !RequestResponseTransportStatus.WAITING.equals(t.getStatus()))) {
          if(log.isWarnEnabled()) {
            String message = SandeshaMessageHelper.getMessage(SandeshaMessageKeys.freeingTransport);
            log.warn(message);
          }
          // If the message is a reply, then the request may need to be acked. Rather
          // than just return a HTTP 202, we should try to send an ack.
          boolean sendAck = false;
          RMDBean inbound = null;
          String inboundSeq = bean.getInboundSequenceId();
          if(inboundSeq != null)
            inbound = SandeshaUtil.getRMDBeanFromSequenceId(manager, inboundSeq);
         
          if(inbound != null) {
            String acksTo = inbound.getAcksToEPR();
            EndpointReference acksToEPR = new EndpointReference(acksTo);
            if(acksTo == null || acksToEPR.hasAnonymousAddress())
              sendAck = true;
          }
         
          if(sendAck) {
            RMMsgContext rmMsgCtx = MsgInitializer.initializeMessage(msgCtx);
            RMMsgContext ackRMMsgCtx = AcknowledgementManager.generateAckMessage(
                rmMsgCtx, inbound, inbound.getSequenceID(), storageManager, true);
            AcknowledgementManager.sendAckNow(ackRMMsgCtx);
            TransportUtils.setResponseWritten(msgCtx, true);
          } else {
            TransportUtils.setResponseWritten(msgCtx, false);
          }
 
          // Mark the bean so that we know the transport is missing, and reset the send time
          bean.setTransportAvailable(false);
          bean.setTimeToSend(System.currentTimeMillis());
         
          // Update the bean
          manager.getSenderBeanMgr().update(bean);
        }
      }
 
      if(transaction != null && transaction.isActive()) transaction.commit();
      transaction = null;
     
    } catch(Exception e) {
      // There isn't much we can do here, so log the exception and continue.
      if(log.isDebugEnabled()) log.debug("Exception", e);
    } finally {
      if(transaction != null && transaction.isActive()) transaction.rollback();
    }
   
    if (log.isDebugEnabled()) log.debug("Exit: Sender::unblockTransportThreads");
  }
View Full Code Here

  private void checkForOrphanMessages(StorageManager manager)
  throws SandeshaStorageException
  {
    if(log.isDebugEnabled()) log.debug("Enter: Sender::checkForOrphanMessages");
   
    Transaction tran = null;
    try {
      tran = manager.getTransaction();
 
      // This finder will look for beans that should have been sent, but could not be sent
      // because they need a MakeConnection message to come in to pick it up. We also factor
      // in TRANSPORT_WAIT_TIME to give the MakeConnection a chance to arrive.
      SenderBean finder = new SenderBean();
      finder.setSend(true);
      finder.setTransportAvailable(false);
      finder.setTimeToSend(System.currentTimeMillis() - Sandesha2Constants.TRANSPORT_WAIT_TIME);
     
      List beans = manager.getSenderBeanMgr().find(finder);
      Iterator beanIter = beans.iterator();
      while(beanIter.hasNext()) {
        SenderBean bean = (SenderBean) beanIter.next();
       
        // Emit a message to warn the user that MakeConnections are not arriving to pick
        // messages up
        if(log.isWarnEnabled()) {
          String messageType = Integer.toString(bean.getMessageType());
          String message = SandeshaMessageHelper.getMessage(SandeshaMessageKeys.noPolling, messageType);
          log.warn(message);
        }
       
        // Update the bean so that we won't emit another message for another TRANSPORT_WAIT_TIME
        bean.setTimeToSend(System.currentTimeMillis());
        manager.getSenderBeanMgr().update(bean);
      }
 
      if(tran != null && tran.isActive()) tran.commit();
      tran = null;
 
    } catch(Exception e) {
      // There isn't much we can do here, so log the exception and continue.
      if(log.isDebugEnabled()) log.debug("Exception", e);
    } finally {
      if(tran != null && tran.isActive()) tran.rollback();
    }
   
    if(log.isDebugEnabled()) log.debug("Exit: Sender::checkForOrphanMessages");
  }
View Full Code Here

        return returnValue;
      }
    }
    if (log.isDebugEnabled()) log.debug("SandeshaInHandler::invoke Continuing beyond basic checks");

    Transaction transaction = null;

    try {
      StorageManager storageManager = SandeshaUtil.getSandeshaStorageManager(context, context.getAxisConfiguration());
      transaction = storageManager.getTransaction();

      AxisService axisService = msgCtx.getAxisService();
      if (axisService == null) {
        String message = SandeshaMessageHelper.getMessage(SandeshaMessageKeys.axisServiceIsNull);
        log.debug(message);
        throw new AxisFault(message);
      }

      RMMsgContext rmMsgCtx = null;
     
      if (msgCtx.getProperty(Sandesha2Constants.MessageContextProperties.RM_MESSAGE_CONTEXT) != null)
        rmMsgCtx = (RMMsgContext)msgCtx.getProperty(Sandesha2Constants.MessageContextProperties.RM_MESSAGE_CONTEXT);
      else
        rmMsgCtx = MsgInitializer.initializeMessage(msgCtx);

      // validating the message
      MessageValidator.validateIncomingMessage(rmMsgCtx, storageManager);
     
      // commit the current transaction
      if(transaction != null && transaction.isActive()) transaction.commit();
      transaction = storageManager.getTransaction();

      // Process Ack headers in the message
      AcknowledgementProcessor ackProcessor = new AcknowledgementProcessor();
      ackProcessor.processAckHeaders(rmMsgCtx);

      // commit the current transaction
      if(transaction != null && transaction.isActive()) transaction.commit();
      transaction = storageManager.getTransaction();

      // Process Ack Request headers in the message
      AckRequestedProcessor reqProcessor = new AckRequestedProcessor();
      if(reqProcessor.processAckRequestedHeaders(rmMsgCtx)){
        returnValue = InvocationResponse.SUSPEND;
      }
     
      // Process MessagePending headers
      MessagePendingProcessor pendingProcessor = new MessagePendingProcessor();
      pendingProcessor.processMessagePendingHeaders(rmMsgCtx);

      // commit the current transaction
      if(transaction != null && transaction.isActive()) transaction.commit();
      transaction = storageManager.getTransaction();

      // Process the Sequence header, if there is one
      SequenceProcessor seqProcessor = new SequenceProcessor();
      returnValue = seqProcessor.processSequenceHeader(rmMsgCtx, transaction);

      // commit the current transaction
      if(transaction != null && transaction.isActive()) transaction.commit();
      transaction = null;
     
    } catch (Exception e) {
      if (log.isDebugEnabled())
        log.debug("SandeshaInHandler::invoke Exception caught during processInMessage", e);
      // message should not be sent in a exception situation.
      msgCtx.pause();
      returnValue = InvocationResponse.SUSPEND;
     
      // Rethrow the original exception if it is an AxisFault
      if (e instanceof AxisFault)
        throw (AxisFault)e;
     
      String message = SandeshaMessageHelper.getMessage(SandeshaMessageKeys.inMsgError, e.toString());
      throw new AxisFault(message, e);
    }
    finally {
      if (log.isDebugEnabled()) log.debug("SandeshaInHandler::invoke Doing final processing");
      if (transaction != null && transaction.isActive()) {
        try {
          transaction.rollback();
          transaction = null;
        } catch (Exception e) {
          String message = SandeshaMessageHelper.getMessage(SandeshaMessageKeys.rollbackError, e.toString());
          log.debug(message, e);
        }
View Full Code Here

TOP

Related Classes of org.apache.sandesha2.storage.Transaction

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.