Package com.sun.messaging.jmq.jmsserver.core

Examples of com.sun.messaging.jmq.jmsserver.core.Consumer


        String err_reason = null;

        Boolean blockprop = (Boolean)props.get("JMQBlock");

        Consumer newc = null;

        assert blockprop == null || msg.getPacketType() == PacketType.DELETE_CONSUMER
               : msg;

        boolean blockprop_bool = (blockprop != null && blockprop.booleanValue());


        boolean isIndemp = msg.getIndempotent();


        // OK ... set up the reply packet
        Packet pkt = new Packet(con.useDirectBuffers());
        pkt.setConsumerID(msg.getConsumerID()); // correlation ID
        Hashtable hash = new Hashtable();
        pkt.setPacketType(msg.getPacketType() + 1);

        int status = Status.OK;
        String warning = BrokerResources.W_ADD_CONSUMER_FAILED;

        ConsumerUID uid = null;
        Integer destType = null;
        Integer oldid = null;
        Subscription sub = null;
        try {
            con.suspend();
            conPaused = true;
            if (msg.getPacketType() == PacketType.ADD_CONSUMER) {
                if (DEBUG) {
                    logger.log(Logger.DEBUGHIGH, "ConsumerHandler: handle() "
                      + "[ Received AddConsumer message {0}]", msg.toString());
                }
                pkt.setPacketType(PacketType.ADD_CONSUMER_REPLY);
                if (lsessionid == null) {
                    if (DEBUG)
                    logger.log(Logger.DEBUG,"not Raptor consumer packet (no session id)");
                    // assign session same # as consumer
                    SessionUID sessionID = new SessionUID(
                               con.getConnectionUID().longValue());
                    // single threaded .. we dont have to worry about
                    // someone else creating it
                    session = con.getSession(sessionID);
                    if (session == null) {
                       session = Session.createSession(sessionID,
                                  con.getConnectionUID(), null);
                       con.attachSession(session);
                    }
                } else {
                    SessionUID sessionID = new SessionUID(lsessionid.longValue());
                    session = con.getSession(sessionID);
                    if (session == null) {
                        throw new BrokerException("Internal Error: client set invalid"
                         + " sessionUID " + sessionID + " session does not exist");
                    }
                }

                if (blockprop_bool) { // turn off all processing
                   session.pause("Consumer - Block flag");
                   sessionPaused = true;
                }


                /* XXX-LKS KLUDGE FOR 2.0 compatibility */
               
                // for now, we just pass the consumer ID back on the old
                // packet .. I need to revisit this in the future
                oldid = (Integer)props.get("JMQConsumerID"); // old consumer ID
                if (oldid != null)
                    hash.put("JMQOldConsumerID", oldid);


               
                if (props == null) {
                    throw new BrokerException(Globals.getBrokerResources().getString(
                   BrokerResources.X_INTERNAL_EXCEPTION,"no properties in addConsumer "
                      + "packet - client does not match protocol"));
                }
                Integer inttype = (Integer )props.get("JMQDestType");
                int type = (inttype == null ? -1 : inttype.intValue());
                if (type == -1) {
                    throw new BrokerException(Globals.getBrokerResources().getString(
                   BrokerResources.X_INTERNAL_EXCEPTION,"Client is not sending DestType, "
                         + "unable to add interest"));
                }

                boolean queue = DestType.isQueue(type) ;

                String destination = (String)props.get("JMQDestination");
                String selector =  (String)props.get("JMQSelector");
                Boolean nolocal = (Boolean)props.get("JMQNoLocal");
                String durablename = (String)props.get("JMQDurableName");
                String clientid = getClientID(props, con);
                Boolean reconnect = (Boolean)props.get("JMQReconnect");
                Boolean share = (Boolean)props.get("JMQShare");
                Integer size = (Integer)props.get("JMQSize");

                if (queue && nolocal != null && nolocal.booleanValue()) {
                    Globals.getLogger().log(Logger.ERROR, BrokerResources.E_INTERNAL_BROKER_ERROR,
                            "NoLocal is not supported on Queue Receivers");
                   throw new BrokerException("Unsupported property on queues JMQNoLocal "
                        + "is set to " + nolocal, Status.ERROR);
                }
                if (reconnect != null && reconnect.booleanValue()) {
                    Globals.getLogger().log(Logger.ERROR,
                        BrokerResources.E_INTERNAL_BROKER_ERROR,
                        "JMQReconnect not implemented");
                }


                if (share != null && share.booleanValue() &&
                       ! ClientIDHandler.CAN_USE_SHARED_CONSUMERS) {
                    throw new BrokerException(
                        Globals.getBrokerResources().getKString(
                            BrokerResources.X_FEATURE_UNAVAILABLE,
                            Globals.getBrokerResources().getKString(
                                BrokerResources.M_SHARED_CONS), destination),
                            BrokerResources.X_FEATURE_UNAVAILABLE,
                            (Throwable) null,
                            Status.NOT_ALLOWED);
                }

               

                // see if we are a wildcard destination
                DestinationUID dest_uid = null;

                Destination d = null;

                if (DestinationUID.isWildcard(destination)) { // dont create a destination
                    dest_uid = DestinationUID.getUID(destination, DestType.isQueue(type));

                } else {
                    d = null;
                    while (true ) {
                       d =  Destination.getDestination(destination,
                                     type, true /* autocreate if possible*/,
                                     !con.isAdminConnection());
                       if (d.isAutoCreated())
                           warning = BrokerResources.W_ADD_AUTO_CONSUMER_FAILED;
                       try {
                           if (d != null)
                               d.incrementRefCount();
                       } catch (BrokerException ex) {
                           continue; // was destroyed in process
                       } catch (IllegalStateException ex) {
                            throw new BrokerException(
                                Globals.getBrokerResources().getKString(
                                BrokerResources.X_SHUTTING_DOWN_BROKER),
                                BrokerResources.X_SHUTTING_DOWN_BROKER,
                                ex,
                                Status.ERROR);
                       }
                       break; // we got one
                    }
   
   
                    if (d == null) {
                        // unable to autocreate destination
                        status  = Status.NOT_FOUND;
                        // XXX error
                        throw new BrokerException(
                            Globals.getBrokerResources().getKString(
                                BrokerResources.X_DESTINATION_NOT_FOUND, destination),
                                BrokerResources.X_DESTINATION_NOT_FOUND,
                                null,
                                Status.NOT_FOUND);
                    }
                    dest_uid = d.getDestinationUID();
                }
   
                // Must have a clientID to add a durable
                if (durablename != null && clientid == null) {
                    throw new BrokerException(
                        Globals.getBrokerResources().getKString(
                        BrokerResources.X_NO_CLIENTID, durablename),
                            BrokerResources.X_NO_CLIENTID,
                            null,
                            Status.PRECONDITION_FAILED);
                }

                Consumer c = null;
               
                try {

//LKS

                    Consumer[] retc = createConsumer( dest_uid,  con,
                         session, selector,  clientid,
                         durablename,  (nolocal != null && nolocal.booleanValue())
                         (size == null ? -1 : size.intValue()),
                         (share != null && share.booleanValue())
                         msg.getSysMessageID().toString(),  isIndemp, true);

                    c = retc[0];
                    newc = retc[1];
                    sub = (Subscription)retc[2];
                    if (c.getPrefetch() != -1 || size != null)
                        hash.put("JMQSize", c.getPrefetch());

                } catch (SelectorFormatException ex) {
                      throw new BrokerException(
                            Globals.getBrokerResources().getKString(
                            BrokerResources.W_SELECTOR_PARSE, selector),
                            BrokerResources.W_SELECTOR_PARSE,
                            ex,
                            Status.BAD_REQUEST);
                } catch (OutOfLimitsException ex) {
                    if (d != null && d.isQueue()) {
                        String args[] = { dest_uid.getName(),
                            String.valueOf(d.getActiveConsumerCount()),
                            String.valueOf(d.getFailoverConsumerCount()) };
                        throw new BrokerException(
                            Globals.getBrokerResources().getKString(
                            BrokerResources.X_S_QUEUE_ATTACH_FAILED, args),
                            BrokerResources.X_S_QUEUE_ATTACH_FAILED,
                            ex,
                            Status.CONFLICT);
                    } else { // durable
                        String args[] = { dest_uid.getName(),
                            durablename, clientid,
                            String.valueOf(ex.getLimit()) };
                        throw new BrokerException(
                            Globals.getBrokerResources().getKString(
                            BrokerResources.X_S_DUR_ATTACH_FAILED, args),
                            BrokerResources.X_S_DUR_ATTACH_FAILED,
                            ex,
                            Status.CONFLICT);
                    }
                } finally {
                    if (d != null)
                        d.decrementRefCount();
                }

                // add the consumer to the session
       
                Integer acktype = (Integer)props.get("JMQAckMode");
                if (acktype != null) {
                    c.getConsumerUID().setAckType(acktype.intValue());
                }

                uid = c.getConsumerUID();

            } else { // removing Interest
                if (DEBUG) {
                    logger.log(Logger.DEBUGHIGH,
                        "ConsumerHandler: handle() [ Received DestroyConsumer message {0}]",
View Full Code Here


                    BrokerResources.X_CONSUMER_SESSION_NOT_FOUND, uid, con.getConnectionUID()), Status.NOT_FOUND);
                }
            }

            if (session != null) { // should only be null w/ indemp
                Consumer c = session.detatchConsumer(uid, lastid, redeliver, redeliverAll);
                if (DEBUG) {
                logger.log(Logger.INFO, "Closed consumer "+c+", with {lastid="+lastid+", redeliver="+
                           redeliver+ ", redeliverAll="+redeliverAll+", isindemp="+isIndemp+"}");
                }
                DestinationUID dest_uid = c.getDestinationUID();
                Destination d = Destination.getDestination(dest_uid);
                if (d != null)
                    d.removeConsumer(uid, true);
            }
        }
View Full Code Here

                        Session session,String selector, String clientid,
                        String durablename, boolean nolocal, int size,
                        boolean shared, String consumerString, boolean isIndemp, boolean useFlowControl)
        throws BrokerException, SelectorFormatException, IOException
    {
        Consumer c = null;
        Consumer newc = null;
        Subscription sub = null;
        // need to deal w/ reconnection AND ackType

        try {

        int prefetch = -1;
        if (isIndemp) { // see if we already created it
            c = Consumer.getConsumer(consumerString);
            if (c != null)
                prefetch = c.getPrefetch();
        }

        if (c == null) {
            c = new Consumer(dest_uid, selector,
                    nolocal,
                    con.getConnectionUID());
            c.setCreator(consumerString);
            newc = c;
            newc.pause("Consumer: new consumer");

            // OK, determine if we are a wildcard or not
            Destination d = Destination.getDestination(dest_uid);
            boolean wildcard = dest_uid.isWildcard();
View Full Code Here

        }
        ht.put("consumersCount", l.size());
        itr = l.iterator();
        while (itr.hasNext()) {
            ConsumerUID cuid = (com.sun.messaging.jmq.jmsserver.core.ConsumerUID)itr.next();
            Consumer c = (Consumer)consumers.get(cuid);
            if (c instanceof Subscription) {
                ht.put("[consumers]"+cuid.toString(), "Subscription: "+c);
            } else {
                ht.put("[consumers]"+cuid.toString(), c.toString());
            }
        }

        synchronized(activeConsumers) {
            l = new ArrayList(activeConsumers);
        }
        ht.put("activeConsumersCount", l.size());
        Vector v = new Vector();
        itr = l.iterator();
        while (itr.hasNext()) {
            Consumer c = (Consumer)itr.next();
            if (c instanceof Subscription) {
                v.add("Subscription: "+c);
            } else {
                v.add(c.toString());
            }
        }
        ht.put("activeConsumers", v);

        synchronized(pendingConsumerUIDs) {
View Full Code Here

    {
        if (type != EventType.BUSY_STATE_CHANGED) {
            assert false; // bad type
        }
        // OK .. add to busy list
        Consumer c = (Consumer)target;

        synchronized(activeConsumers) {
            if (c.isBusy() ) {
                activeConsumers.add(c);
            }
            activeConsumers.notify();
        }
    }
View Full Code Here

    public void forwardMessageToRemote(PacketReference ref, Collection cons)
    {
         Iterator itr = cons.iterator();
         while (itr.hasNext()) {
             // hey create an ack entry since we are bypassing consumer
            Consumer consumer = (Consumer)itr.next();
            com.sun.messaging.jmq.jmsserver.core.ConsumerUID sid = consumer.getStoredConsumerUID();
            com.sun.messaging.jmq.jmsserver.core.ConsumerUID uid = consumer.getConsumerUID();

            // if we dont have an ack, go on
            if (uid.isNoAck()) continue;

            synchronized(removeConsumerLock) {
View Full Code Here

          if (DEBUG) {
              logger.log(logger.INFO, "BrokerConsumers.removeConsumer:"+uid+
                         ", pending="+(pendingMsgs == null ? "null":pendingMsgs.size())+
                         ", cleanup="+cleanup);
          }
          Consumer c = null;
          synchronized(removeConsumerLock) {
              c = (Consumer)consumers.remove(uid);
          }
          if (c == null && !cleanup) return;

          Destination d = null;
          if (c != null) {
              c.pause("MultiBroker - removing consumer");
              // remove it from the destination
              d= Destination.getDestination(c.getDestinationUID());

              // quit listening for busy events
              Object listener= listeners.remove(uid);
              if (listener != null) {
                  c.removeEventListener(listener);
              }

              // remove it from the active list
              activeConsumers.remove(c);
          }

          Set destroySet = new LinkedHashSet();
          LinkedHashSet openacks = new LinkedHashSet();
          LinkedHashSet openmsgs = new LinkedHashSet();
          // OK .. get the acks .. if its a FalconRemote
          // we sent the messages directly and must explicitly ack
          synchronized(deliveredMessages) {
              if (c != null) {
                  cleanupList.put(uid, c.getParentList());
              }
              Prioritized cparent = (Prioritized)cleanupList.get(uid);
              if (DEBUG) {
              logger.log(logger.INFO, "BrokerConsumers.removeConsumer:"+uid+
                          ", pending="+pendingMsgs+", cleanup="+cleanup+", cparent="+cparent);
              }
              Iterator itr = deliveredMessages.values().iterator();
              while (itr.hasNext()) {
                  ackEntry e = (ackEntry)itr.next();
                  if (!e.getConsumerUID().equals(uid)) continue;
                  if (e.getTUID() != null) continue;
                  if (pendingMsgs != null && !cleanup) {
                      if (pendingMsgs.contains(e.getSysMessageID())) {
                          continue;
                      }
                  }
                  if (DEBUG && DEBUG_CLUSTER_MSG) {
                      logger.log(logger.DEBUG,
                      "BrokerConsumers.removeConsumer:"+uid+", remove ackEntry="+e+ ", c="+c);
                  }
                  itr.remove();
                  if (c != null) {
                      if (c.isFalconRemote()) {
                          e.acknowledged(false);
                      } else {
                          PacketReference ref = e.getReference();
                          if (ref != null)  {
                              ref.removeInDelivery(e.getStoredConsumerUID());
                              destroySet.add(ref);
                          }
                      }
                      continue;
                  }
                  PacketReference ref = e.getReference();
                  if (ref != null) {
                      ref.removeInDelivery(e.getStoredConsumerUID());
                  }
                  openacks.add(e);
              }
              itr = openacks.iterator();
              while (itr.hasNext()) {
                  ackEntry e = (ackEntry)itr.next();
                  if (cparent == null) {
                      e.acknowledged(false);
                  } else {
                      PacketReference ref = e.getReference();
                      if (ref != null) openmsgs.add(ref);
                  }
              }
              if (cparent != null && openmsgs.size() > 0) {
                  cparent.addAllOrdered(openmsgs);
              }
              if (cleanup || pendingMsgs == null) {
                  cleanupList.remove(uid);
                  pendingConsumerUIDs.remove(uid);
              } else {
                  pendingConsumerUIDs.put(uid, pendingMsgs);
              }
          }

          if (c != null) {
              c.destroyConsumer(destroySet, false, false);
              if (d != null)  {
              d.removeConsumer(uid, false);
              }
          }
    }
View Full Code Here

    public boolean acknowledgeMessageFromRemote(int ackType, SysMessageID sysid,
                              com.sun.messaging.jmq.jmsserver.core.ConsumerUID cuid,
                              Map optionalProps) throws BrokerException {

        if (ackType == ClusterBroadcast.MSG_DELIVERED) {
            Consumer c = Consumer.getConsumer(cuid);
            if (c != null) {
                if (optionalProps != null) {
                    Integer pref = (Integer)optionalProps.get(Consumer.PREFETCH);
                    if (pref != null) {
                        int prefetch = Consumer.calcPrefetch(c, pref.intValue());
                        if (prefetch <= 0 || prefetch > BTOBFLOW) {
                            prefetch = BTOBFLOW;
                        }
                        c.resumeFlow(prefetch);
                    } else {
                        c.resumeFlow();
                    }
                } else {
                    c.resumeFlow();
                }
            }
            return true;
        }
        if (ackType == ClusterBroadcast.MSG_IGNORED) {
            String tid = null, tidi = null, tido = null;
            if (optionalProps != null &&
                ((tidi = (String)optionalProps.get(ClusterBroadcast.RB_RELEASE_MSG_INACTIVE)) != null ||
                 (tido = (String)optionalProps.get(ClusterBroadcast.RB_RELEASE_MSG_ORPHAN)) != null ||
                 optionalProps.get(ClusterBroadcast.RC_RELEASE_MSG_INACTIVE) != null)) { 

                tid = (tidi == null ? tido:tidi);

                String logstrop = " for rollback remote transaction "+tid;
                String logstrtyp = "";
                if (tidi == null && tido == null) {
                    logstrop = " CLIENT_ACKNOWLEDGE recover";
                } else {
                    logstrtyp = (tidi == null ? "orphaned":"inactive");
                }
                if (DEBUG) {
                    logger.log(Logger.INFO,
                    "Releasing message ["+cuid+", "+sysid+"]("+logstrtyp+")"+logstrop);
                }
                ackEntry entry = new ackEntry(sysid, cuid, null);
                ackEntry value = null;
                synchronized(deliveredMessages) {
                    value = (ackEntry)deliveredMessages.remove(entry);
                    cleanupPendingConsumerUID(cuid, sysid);
                }
                if (value == null) {
                    if (DEBUG) {
                        logger.log(Logger.INFO,
                        "Releasing message ["+cuid+", "+sysid+"]("+logstrtyp+")"+logstrop);
                    }
                    return true;
                }
                PacketReference ref =value.getReference();
                if (ref == null) {
                    if (DEBUG) {
                        logger.log(Logger.INFO,
                        "Releasing message ["+value+"]("+logstrtyp+") ref null"+logstrop);
                    }
                    return true;
                }
                com.sun.messaging.jmq.jmsserver.core.ConsumerUID sid = value.getStoredConsumerUID();
                com.sun.messaging.jmq.jmsserver.core.ConsumerUID uid = value.getConsumerUID();
                if (sid== null || sid == uid) {
                    try {
                        if (ref.acknowledged(uid, sid, !uid.isDupsOK(), false)) {
                            Destination d=Destination.getDestination(ref.getDestinationUID());
                            d.removeMessage(ref.getSysMessageID(), RemoveReason.ACKNOWLEDGED);
                        }
                    } catch (Exception e) {
                        logger.logStack(Logger.WARNING,
                        "Unable to cleanup message "+ref.getSysMessageID()+logstrop, e);
                    }
                    return true;
                }
                   
                ref.removeInDelivery(value.getStoredConsumerUID());
                ref.getDestination().forwardOrphanMessage(ref, value.getStoredConsumerUID());
                return true;
            }

            if (optionalProps != null &&
                optionalProps.get(ClusterBroadcast.MSG_NOT_SENT_TO_REMOTE) != null &&
                ((String)optionalProps.get(ClusterBroadcast.MSG_NOT_SENT_TO_REMOTE)).equals("true")) {
                ackEntry entry = new ackEntry(sysid, cuid, null);
                ackEntry value = null;
                synchronized(deliveredMessages) {
                    value = (ackEntry)deliveredMessages.get(entry);
                }
                if (value == null) return true;
                PacketReference ref =value.getReference();
                if (ref == null || ref.isDestroyed() || ref.isInvalid()) {
                    if (DEBUG) {
                    logger.log(Logger.INFO, "Cleanup dead message (not remote delivered): "+ value);
                    }
                    synchronized(deliveredMessages) {
                        deliveredMessages.remove(entry);
                    }
                }
                return true;
            }

            if (REDELIVER_REMOTE_REJECTED && optionalProps != null &&
                optionalProps.get(ClusterBroadcast.MSG_REMOTE_REJECTED) != null &&
                ((String)optionalProps.get(ClusterBroadcast.MSG_REMOTE_REJECTED)).equals("true")) {
                ackEntry entry = new ackEntry(sysid, cuid, null);
                ackEntry value = null;
                if (DEBUG) {
                    logger.log(Logger.INFO, "Cleanup remote rejected message: "+ value);
                }
                Long msgoutt = (Long)optionalProps.get(ClusterBroadcast.MSG_OUT_TIME_MILLIS);
                synchronized(removeConsumerLock) {
                    Consumer c = (Consumer)consumers.get(cuid);
                    if (c != null) {
                        synchronized(deliveredMessages) {
                            value = (ackEntry)deliveredMessages.remove(entry);
                        }
                        if (value == null) {
                            return true;
                        }
                        PacketReference ref =value.getReference();
                        if (ref == null || ref.isDestroyed() || ref.isInvalid()) {
                            return true;
                        }
                        ref.removeInDelivery((c.getStoredConsumerUID() == null ?
                                  c.getConsumerUID():c.getStoredConsumerUID()));
                        ref.removeDelivered(c.getStoredConsumerUID(), true);
                        c.pause("start remote redeliver");
                        if (msgoutt != null) {
                            c.delayNextFetchForRemote(msgoutt.longValue());
                        }
                        c.routeMessage(ref, true);
                        c.resume("end remote redeliver");
                    }
                }
                return true;
            }
View Full Code Here

        }
    }

    public void run() {
        while (valid) {
            Consumer c = null;
            synchronized(activeConsumers) {
                while (valid && activeConsumers.isEmpty()) {
                    try {
                        activeConsumers.wait();
                    } catch (InterruptedException ex) {
                    }
                }
                if (valid) {
                    Iterator itr = activeConsumers.iterator();
                    c = (Consumer) itr.next();
                    itr.remove();
                    if (c.isBusy())
                        activeConsumers.add(c);
                }
            }
            if (c == null) continue;

            PacketReference ref =  null;
            HashSet s = null;
            boolean cb = false;
            synchronized(removeConsumerLock) {
                if (consumers.get(c.getConsumerUID()) == null) {
                    if (DEBUG || DEBUG_CLUSTER_TXN || DEBUG_CLUSTER_MSG) {
                    Globals.getLogger().log(Logger.INFO,
                    "BrokerConsumers.run(): ignore removed consumer: "+c);
                    }
                    continue;
                }

                ref =  c.getAndFillNextPacket(null);
                if (ref == null) continue;

                s = new HashSet();
                s.add(c);
                cb = ref.getMessageDeliveredAck(c.getConsumerUID())
                                 || c.isPaused();

                if (!c.getConsumerUID().isNoAck()) {
                    ackEntry entry = new ackEntry(ref, c.getConsumerUID(),
                                                  c.getStoredConsumerUID());
                    synchronized(deliveredMessages) {
                        deliveredMessages.put(entry, entry);
                        if (DEBUG && DEBUG_CLUSTER_MSG) {
                        logger.log(logger.DEBUG, "deliveredMessages:"+entry);
                        }
View Full Code Here

        ignoreUnroutableProp.put(ClusterBroadcast.MSG_REMOTE_REJECTED, "true");

        Iterator itr = consumers.iterator();
        while (itr.hasNext()) {
            ConsumerUID uid = (ConsumerUID)itr.next();
            Consumer interest = Consumer.getConsumer(uid);

            if (interest != null && interest.isValid()) {
                // we need the interest for updating the ref
                targetVector.add(interest);
                ConsumerUID suid = interest.getStoredConsumerUID();
                if ((suid == null || suid.equals(uid)) &&
                    interest.getSubscription() == null) {
                    hasflowcontrol = false;
                }
            } else {
                ignoreVector.add(uid);
            }
        }

        boolean exists = false;
        PacketReference ref = Destination.get(p.getSysMessageID());
        if (ref != null) {
            BrokerAddress addr = ref.getAddress();
            if (addr == null || !addr.equals(sender)) {
                if (DEBUG) {
                logger.log(Logger.INFO,
                "Remote message "+ref.getSysMessageID()+ " home broker "+addr+" changed to "+sender);
                }
                Destination.remoteCheckMessageHomeChange(ref, sender);
            }
        }
        ref = Destination.get(p.getSysMessageID());
        if (ref != null) {
            exists = true;
            ref.setBrokerAddress(sender);
            if (p.getRedelivered()) ref.overrideRedeliver();
        } else {
            ref = PacketReference.createReference(p, null);
            ref.setBrokerAddress(sender);
        }
        // XXX - note, we send a reply for all message delivered
        //       acks, that is incorrect
        //       really, we should have a sendMsgDeliveredAck per
        //       consumer
        if (sendMsgDeliveredAck) {
            for (int i=0; i < targetVector.size(); i ++) {
                Consumer c = (Consumer)targetVector.get(i);
                //ref.addMessageDeliveredAck(c.getStoredConsumerUID());
                ref.addMessageDeliveredAck(c.getConsumerUID());
            }
        }
        List dsts = null;
        ArrayList cleanupDests = new ArrayList();
        try {
            if (ref == null)  {
                return;
            }
            if (ref.getDestinationUID().isWildcard()) {
                dsts = Destination.findMatchingIDs(ref.getDestinationUID());
            } else {
                // ok, autocreate the destination if necessary
                Destination d = Destination.getDestination(
                    ref.getDestinationUID().getName(),
                    ref.getDestinationUID().isQueue() ? DestType.DEST_TYPE_QUEUE
                       : DestType.DEST_TYPE_TOPIC, true, true);
                if (d != null) {
                    dsts = new ArrayList();
                    dsts.add(d.getDestinationUID());
                }
            }
            if (dsts == null || dsts.isEmpty()) {
               ignoreVector.addAll(targetVector);
               targetVector.clear();
            } else {
                if (!exists && !targetVector.isEmpty()) {
                    ref.setNeverStore(true);
                    // OK .. we dont need to route .. its already happened
                    ref.store(targetVector);
                    boolean enforcelimit = false;
                    itr = dsts.iterator();
                    while (itr.hasNext()) {
                        DestinationUID did = (DestinationUID)itr.next();
                        Destination d = Destination.getDestination(did);
                        if (!hasflowcontrol) {
                            enforcelimit = true;
                        } else {
                            String k = ENFORCE_REMOTE_DEST_LIMIT_PROP+did.getLongString();
                            if (Globals.getConfig().getProperty(k) == null) {
                                enforcelimit = ENFORCE_REMOTE_DEST_LIMIT;
                            } else {
                                enforcelimit = Globals.getConfig().getBooleanProperty(k);
                            }
                        }
                        if (DEBUG) {
                            logger.log(logger.INFO, "Route remote message "+ref+ " sent from "+sender+
                                " to destination(s) "+did+" for consumer(s) "+targetVector+" hasflowcontrol="+
                                hasflowcontrol+", enforcelimit="+enforcelimit);
                        }
                        if ((Destination.CHECK_MSGS_RATE_FOR_ALL ||
                             !ref.getDestinationUID().isQueue()) && !ROUTE_REJECTED_REMOTE_MSG) {
                            Consumer cs = null;
                            Subscription sub = null;
                            Iterator csitr = targetVector.iterator();
                            while (csitr.hasNext()) {
                                cs = (Consumer)csitr.next();
                                sub = cs.getSubscription();
                                if (Destination.CHECK_MSGS_RATE_FOR_ALL ||
                                    (CHECK_MSGRATE_ON_ARRIVAL &&
                                     sub != null && sub.getShared() && !sub.isDurable())) {
                                    int ret = cs.checkIfMsgsInRateGTOutRate(d);
                                    if (ret == 0) {
                                        ignoreVector.addAll(targetVector);
                                        targetVector.clear();
                                        ignoreProps = ignoreUnroutableProp;
                                        break;
                                    }
                                }
                            }
                            if (targetVector.isEmpty()) {
                                break;
                            }
                        }
                        if (!d.queueMessage(ref, false, enforcelimit)) { // add to message count
                            ignoreVector.addAll(targetVector);
                            if (!ROUTE_REJECTED_REMOTE_MSG) {
                                targetVector.clear();
                            }
                            break;
                        } else {
                            cleanupDests.add(d);
                        }
                    }
                } else if (exists) {
                    ref.add(targetVector);
                }
            }
        } catch (IOException ex) {
            logger.logStack(logger.INFO,"Internal Exception ", ex);
            ignoreVector.addAll(targetVector);
            if (!ROUTE_REJECTED_REMOTE_MSG) {
                targetVector.clear();
                ignoreProps = ignoreUnroutableProp;
            }
        } catch (BrokerException ex) {
            // unable to store
            ignoreVector.addAll(targetVector);
            if (!ROUTE_REJECTED_REMOTE_MSG) {
                targetVector.clear();
                ignoreProps = ignoreUnroutableProp;
            }
        }

        if (targetVector.isEmpty()) {
            Destination d = null;
            itr = cleanupDests.iterator();
            while (itr.hasNext()) {
                try {
                    d = (Destination)itr.next();
                    d.removeMessage(ref.getSysMessageID(), null);
                } catch (Throwable e) {
                    Object[] args = { ref.getSysMessageID(),
                                      (sender == null ? "":sender),
                                      d, targetVector.toString(), e.toString() };
                    String emsg = Globals.getBrokerResources().getKString(
                                  BrokerResources.W_UNABLE_CLEANUP_REMOTE_MSG_ON_ROUTE, args);
                    if (DEBUG) {
                        logger.logStack(Logger.WARNING,  emsg, e);
                    } else {
                        logger.log(Logger.WARNING, emsg);
                    }
                }
            }
            cleanupDests.clear();
       }

        // Now deliver the message...
        String debugString = "\n";

        int i;
        for (i = 0; i < targetVector.size(); i++) {
            Consumer interest = (Consumer)targetVector.get(i);

            if (!interest.routeMessage(ref, false)) {
                // it disappeard on us, take care of it
               try {
                    if (ref.acknowledged(interest.getConsumerUID(),
                          interest.getStoredConsumerUID(), true, false)) {
                        if (dsts == null) continue;
                        itr = dsts.iterator();
                        while (itr.hasNext()) {
                            DestinationUID did = (DestinationUID)itr.next();
                            Destination d=Destination.getDestination(did);
                            d.removeRemoteMessage(ref.getSysMessageID(),
                                          RemoveReason.ACKNOWLEDGED, ref);
                        }
                    }
                } catch (Exception ex) {
                    logger.log(logger.INFO,"Internal error processing ack",
                           ex);
                }
            } else {
                ref.addRemoteConsumerUID(interest.getConsumerUID(),
                        interest.getConsumerUID().getConnectionUID());
            }



            if (DEBUG) {
                debugString = debugString +
                    "\t" + interest.getConsumerUID() + "\n";
            }
        }

        if (DEBUG) {
            logger.log(logger.DEBUGHIGH,
                "MessageBus: Delivering message to : {0}",
                debugString);
        }

        debugString = "\n";
        // Finally, send  ClusterGlobals.MB_MSG_IGNORED acks if any...
        Object o = null;
        ConsumerUID cuid = null;
        Consumer interest = null;
        for (i = 0; i < ignoreVector.size(); i++) {
            try {
                o = ignoreVector.get(i);
                if (o instanceof Consumer) {
                    cuid = ((Consumer)o).getConsumerUID();
                    interest = (Consumer)o;
                } else {
                    cuid = (ConsumerUID)o;
                    interest = Consumer.getConsumer(cuid);
                }
                if (interest != null && dsts != null && ignoreProps == ignoreUnroutableProp) {
                    long  msgoutt = 0, t = 0;
                    Destination d = null;
                    Iterator ditr = dsts.iterator();
                    while (ditr.hasNext()) {
                        d = Destination.findDestination((DestinationUID)ditr.next());
                        if (d == null)  {
                            continue;
                        }
                        t = interest.getMsgOutTimeMillis(d);
                        if (t > msgoutt) {
                            msgoutt = t;
                        }
                    }
                    if (msgoutt > 0) {
                        ignoreProps.put(ClusterBroadcast.MSG_OUT_TIME_MILLIS,
                                        new Long(msgoutt));
                    }
                }
                cb.acknowledgeMessage(sender, ref.getSysMessageID(), cuid,
                         ClusterBroadcast.MSG_IGNORED, ignoreProps, false);
            } catch (Exception e) {
                logger.logStack(logger.WARNING, "sendMessageAck IGNORE failed to "+sender, e);
            } finally {
                if (!ROUTE_REJECTED_REMOTE_MSG) {
                    if (interest != null && sendMsgDeliveredAck) {
                        ref.setBrokerAddress(sender);
                        interest.throttleRemoteFlow(ref);
                     }
                }
            }

            if (DEBUG) {
View Full Code Here

TOP

Related Classes of com.sun.messaging.jmq.jmsserver.core.Consumer

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.