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

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


                    ConsumerUID intid = (ConsumerUID) interests.get(i);
                    ConsumerUID sid = (ConsumerUID)sToCmap.get(intid);
                    if (sid == null) sid = intid;

                    try {
                        Session s = Session.getSession(intid);
                        if (s != null) {
                            PacketReference r1 = null;
                            if (fi.FAULT_INJECTION && fi.checkFault(
                                FaultInjection.FAULT_TXN_COMMIT_1_7_1, null)) {
                                Globals.getConnectionManager().getConnection(
                                        s.getConnectionUID()).destroyConnection(
                                        true, GoodbyeReason.OTHER,
                                        "Fault injection of closing connection");
                            }
                            r1 =s.ackMessage(intid, sysid, id, remoteNotified, true);
                            if (r1 != null) {
                                if (fi.FAULT_INJECTION) {
                                    fi.checkFaultAndExit(FaultInjection.FAULT_TXN_COMMIT_1_7, null, 2, false);
                                }
                                dst.removeMessage(ref.getSysMessageID(),
View Full Code Here


 
                if (ref == null || ref.isInvalid()) {
                    continue;
                }
                Session s= Session.getSession(id);
                Consumer c = null;
                if (s != null) {
                    if (!sessions.contains(s)) {
                        s.pause("redeliver");
                        sessions.add(s);
                    }
                    c = s.getConsumerOnSession(id);
                }

                if (c == null) {
                    //ok, make sure the consumer has really gone away
                    //if not, something is really wrong
                    // otherwise ...
                    // consumer has gone away but session is still
                    // valid ->
                    c = Consumer.getConsumer(id);
                   
                    if (c != null) {
                        logger.log(Logger.WARNING,"Internal Error " +
                           " consumer with id of " + id + " is unavailable "
                           + " on session " + s + "[conuid,sess conuid] ="
                           + "[" + con.getConnectionUID().longValue() +
                             "," + (s == null ? 0 : s.getConnectionUID().longValue())
                           + "] consumer session is : " +c.getSessionUID()) ;
                        continue;
                    } else {
                        if (s != null && s.isClientAck(id) && !s.isTransacted() &&
                            redeliver && tid == null) {

                            ConsumerUID storedID = s.getStoredIDForDetatchedConsumer(id);
                            if (storedID != null && !storedID.equals(id)) {
                                storedIDToConsumerUIDMap.put(id, storedID);
                                SortedSet refset = (SortedSet)noConsumerMap.get(id);
                                if (refset == null) {
                                    refset = new TreeSet(new RefCompare());
                                    noConsumerMap.put(id, refset);
                                }
                                ref.removeInDelivery(storedID);
                                refset.add(ref);
                            }
                        }
                        // the consumer for this message has been
                        // closed before the redeliver was requested
                        // (this means the message has not been acked and
                        // the session is open)
                        // we dont need to deliver this message, ignore it
                        logger.log(Logger.DEBUG,
                           " consumer with id of " + id + " is unavailable "
                           + " on session " + s + "[conuid,sess conuid] ="
                           + "[" + con.getConnectionUID().longValue() +
                             "," + (s == null ? 0 : s.getConnectionUID().longValue())
                           + "] it has been closed") ;
                        continue;
                    }
                }

                //for client < 4.1, need check 'redeliver' as well
                if (redeliver && (tid != null || s.isTransacted())) {
                    if (tid == null) tid = s.getCurrentTransactionID();
                    TransactionList translist = Globals.getTransactionList();
                    HashMap cmap = translist.retrieveRemovedConsumedMessages(tid);
                    if (cmap != null && cmap.size() > 0) {
                        List interests = (List) cmap.get(sysid);
                        if (interests != null && interests.size() > 0) {
                            boolean found = false;
                            for (int j = 0; j < interests.size(); j++) {
                                ConsumerUID intid = (ConsumerUID)interests.get(j);
                                if (intid.equals(id)) {
                                    TransactionState ts = translist.retrieveState(tid);
                                    if (ts != null && ts.getState() == TransactionState.FAILED) {
                                        found = true;
                                        break;
                                    }
                                }
                            }
                            if (found) {
                               if (DEBUG_CLUSTER_TXN) {
                                   logger.log(logger.INFO,
                                   "Ignore redeliver request for ["+sysid+ ":"+id+
                                   "], removed with transaction "+tid);
                               }
                               continue;
                            }
                        }
                    }
                }
                     
                Set set = (Set)cToM.get(c);
                if (set == null) {
                    set = new LinkedHashSet();
                    cToM.put(c, set);
                }
                if (!set.contains(ref)) {
                    ref.removeInDelivery((c.getStoredConsumerUID() == null ? c.getConsumerUID():c.getStoredConsumerUID()));
                    set.add(ref);
                } else if (DEBUG_CLUSTER_TXN) {
                    logger.log(logger.INFO, "Ignore duplicated redeliver request ["+sysid+ ":"+id+"]" );
                }
                if (redeliver) {
                    ref.consumed(c.getStoredConsumerUID(),
                        s.isDupsOK(c.getConsumerUID()), false);
                } else {
                    ref.removeDelivered(c.getStoredConsumerUID(), true);
                }
            }
            Iterator itr = cToM.entrySet().iterator();
            while (itr.hasNext()) {
                Map.Entry entry = (Map.Entry)itr.next();
                Consumer c = (Consumer)entry.getKey();
                Set msgs = (Set)entry.getValue();
                c.pause("start redeliver");
                c.routeMessages(msgs, true);
                c.resume("end redeliver");
            }
            cToM.clear(); // help gc

            if (noConsumerMap.size() > 0) {
                try {
                    logger.log(logger.DEBUG, "REDELIVER unacked for closed consumers: "+noConsumerMap);

                    TransactionHandler.redeliverUnackedNoConsumer(noConsumerMap,
                                       storedIDToConsumerUIDMap, redeliver, null, null);
                } catch(Exception e) {
                    logger.logStack(logger.WARNING, "Exception in redelivering unacked messages for closed consumers", e);
                }
            }
               
            itr = sessions.iterator();
            while (itr.hasNext()) {
                Session s = (Session)itr.next();
                s.resume("redeliver");
            }

    }
View Full Code Here

                   }
              } else if (targetType.equals("ses")) {
                  try {
                      SessionUID uid = new SessionUID(
                          Long.parseLong(target));
                      Session ses = Session.getSession(uid);
                      if (ses == null) {
                          status = Status.ERROR;
                          msg = "Error listing consumers on session  "
                             + target + " unknown sessionUID";
                      } else {
                          Iterator itr = ses.getConsumers();
                          if (!itr.hasNext()) {
                              status = Status.ERROR;
                              msg = "No consumers on session  " + target ;
                          }
                          while (ses != null && itr.hasNext()) {
                              Consumer c = (Consumer)itr.next();
                              if (uid.equals(c.getConnectionUID())) {
                                  debugHash.put(String.valueOf(
                                        c.getConsumerUID().longValue()),
                                        c.getDestinationUID().toString());
                              }
                          }
                      }
                } catch (Exception ex) {
                    status = Status.ERROR;
                    msg = "Error listing consumers on connection  " + target +
                         " because " + ex.toString();
                    logger.logStack(Logger.INFO,msg, ex);
                }
              } else if (targetType.equals("cxn")) {
                  try {
                      ConnectionUID uid = new ConnectionUID(
                          Long.parseLong(target));
                      IMQConnection cxn = (IMQConnection)
                          Globals.getConnectionManager()
                                  .getConnection(uid);
                      if (cxn == null) {
                          status = Status.ERROR;
                          msg = "Error listing consumers on connection  " + target +
                             " unknown connectionUID";
                      } else {
                          Iterator itr = Consumer.getAllConsumers();
                          while (cxn != null && itr.hasNext()) {
                              Consumer c = (Consumer)itr.next();
                              if (uid.equals(c.getConnectionUID())) {
                                  debugHash.put(String.valueOf(
                                        c.getConsumerUID().longValue()),
                                        c.getDestinationUID().toString());
                              }
                          }
                      }
                } catch (Exception ex) {
                    status = Status.ERROR;
                    msg = "Error listing consumers on connection  " + target +
                         " because " + ex.toString();
                    logger.logStack(Logger.INFO,msg, ex);
                }
              } else  {
                  status = Status.ERROR;
                  msg = "Unknown targetType (-t) " + target
                        + "\n Valid formats are of the form: "
                        + "[q|t|ses|cxn]";
              }
            } else if (cmdarg.equals("prd")) {
           debugHash = new Hashtable();
             
              if (target == null) { // all
                  Iterator itr = Producer.getAllProducers();
                  while (itr.hasNext()) {
                      Producer c = (Producer)itr.next();
                      IMQConnection cxn = (IMQConnection)
                          Globals.getConnectionManager()
                              .getConnection(c.getConnectionUID());
                      debugHash.put(String.valueOf(
                             c.getProducerUID().longValue()),
                             cxn.getRemoteConnectionString()  + " ["
                            +  String.valueOf(c.getConnectionUID()
                                 .longValue()) + "]");
                  }
              } else if (targetType == null) {
                  msg = "Please supply targetType if you are supplying a target ";
                  status = Status.ERROR;
              } else if (targetType.equals("t") || targetType.equals("q")) {
                  // destination
                  boolean isQueue = false;
                  if (targetType.equals("q")) {
                     isQueue = true;
                  }
                  try {
                      DestinationUID uid = DestinationUID.getUID(target, isQueue);
                      Destination d = Destination.getDestination(uid);
                      if (d == null) {
                          status = Status.ERROR;
                          msg = "Error listing producers on destination  " + target +
                             " unknown destination";
                      } else {
                          Iterator itr = d.getProducers();
                          while (itr.hasNext()) {
                              Producer c = (Producer)itr.next();
                              IMQConnection cxn = (IMQConnection)
                              Globals.getConnectionManager()
                                  .getConnection(c.getConnectionUID());
                              debugHash.put(String.valueOf(
                                  c.getProducerUID().longValue()),
                                  cxn.getRemoteConnectionString()  + " ["
                                  + String.valueOf(c.getConnectionUID()
                                     .longValue()) + "]");
                          }
                      }
                   } catch (Exception ex) {
                       status = Status.ERROR;
                       msg = "Error listing producers on connection  " + target +
                         " because " + ex.toString();
                      logger.logStack(Logger.INFO,msg, ex);
                   }
              } else if (targetType.equals("cxn")) {
                  try {
                      ConnectionUID uid = new ConnectionUID(
                          Long.parseLong(target));
                      IMQConnection cxn = (IMQConnection)
                          Globals.getConnectionManager()
                                  .getConnection(uid);
                      if (cxn == null) {
                          status = Status.ERROR;
                          msg = "Error listing producers on connection  " + target +
                             " unknown connectionUID";
                      } else {
                          Iterator itr = Producer.getAllProducers();
                          while (cxn != null && itr.hasNext()) {
                              Producer c = (Producer)itr.next();
                              if (uid.equals(c.getConnectionUID())) {
                                  debugHash.put(String.valueOf(
                                        c.getProducerUID().longValue()),
                                        c.getDestinationUID().toString());
                              }
                          }
                      }
                } catch (Exception ex) {
                    status = Status.ERROR;
                    msg = "Error listing producers on connection  " + target +
                         " because " + ex.toString();
                    logger.logStack(Logger.INFO,msg, ex);
                }
              } else  {
                  status = Status.ERROR;
                  msg = "Unknown targetType (-t) " + targetType
                        + "\n Valid formats are of the form: "
                        + "[t|q|cxn]";
              }
            } else {
                status = Status.ERROR;
                msg = "Unknown argument " + cmdarg;
            }
               
        } else if (cmd.equals("debug")) {
            String debugStr = (String) p.get("enable");

            if (debugStr != null && !debugStr.equalsIgnoreCase("true")
                 && !debugStr.equalsIgnoreCase("false")) {
                status = Status.ERROR;
                msg = "bad enable flag setting " +
                   debugStr + " defauling to false";
            }
            boolean debugOn=(debugStr == null) ? true :
                      Boolean.valueOf(debugStr).booleanValue();
            if (cmdarg.equals("reset")) {
                if (targetType == null) {
                    msg = "Please supply targetType (-t)\n Valid formats are of the form: [metrics|jdbcconnpool]";
                    status = Status.ERROR;
                } else if (targetType.equalsIgnoreCase("jdbcconnpool")) {
                    try {
                        if (Globals.getStore().isJDBCStore()) {
                            com.sun.messaging.jmq.jmsserver.persist.jdbc.DBManager.getDBManager().resetConnectionPool();
                        } else {
                            status = Status.ERROR;
                            msg = "Operation is not applicable for a file-based data store.";                           
                        }
                    } catch (Exception ex) {
                        status = Status.ERROR;
                        msg = "Error resetting JDBC connection pool because " +
                            ex.toString();
                        logger.logStack(Logger.INFO, msg, ex);
                    }
                } else if (targetType.equalsIgnoreCase("metrics")) {
                    com.sun.messaging.jmq.jmsserver.data.handlers.admin.ResetMetricsHandler.resetAllMetrics();
                }
            } else if (cmdarg.equals("fault")) {

                // handle fault injection
                String faultName = (String)p.get("name");
                if (faultName == null)
                    faultName = target;
                String faultSelector = (String)p.get("selector");
                FaultInjection fi = FaultInjection.getInjection();
                boolean faultOn = true;

                // ok only turn off fault injection if no name pair
                if (debugStr != null && debugStr.equalsIgnoreCase("false")) {
                    if (faultName == null) {
                        fi.setFaultInjection(false);
                    } else {
                        fi.unsetFault(faultName);
                    }
                } else {
                    fi.setFaultInjection(true);
                    if (faultName != null) {
                        try {
                            fi.setFault(faultName, faultSelector, p);
                        } catch (Exception ex) {
                          status = Status.ERROR;
                          msg = "Bad Selector " + faultSelector;
                        }
                    }
                }

            } else if (cmdarg.equals("gc")) {
                logger.log(Logger.INFO,"GC'ing the system");
                com.sun.messaging.jmq.jmsserver.Broker.runGC();
                long usedMem = (Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory());
                msg = "Used memory is " +
                    (usedMem/1024l) + "k, "  +
                   " this is " + (usedMem*100/Runtime.getRuntime().maxMemory())
                    + "% of " + (Runtime.getRuntime().maxMemory()/1024l)
                     + "k";
                logger.log(Logger.INFO,msg);
                if (debugHash == null) debugHash = new Hashtable();
                debugHash.put("Memory", msg);
                debugHash.put("Used", (usedMem/1024l)+"k");
                debugHash.put("Total", ((Runtime.getRuntime().totalMemory()/1024l)+"k"));
                debugHash.put("Free", ((Runtime.getRuntime().freeMemory()/1024l)+"k"));
                debugHash.put("Max", ((Runtime.getRuntime().maxMemory()/1024l)+"k"));
            } else if (cmdarg.equals("threads")) {
                // log
                try {
                    debugHash = new Hashtable();
                    debugHash.put("threads", "dumped to log");
                } catch (Exception ex) {
                    status = Status.ERROR;
                    msg = "Error "+cmd+"ing " + cmdarg + " because "
                         + ex.getMessage() + "";
                    logger.logStack(Logger.INFO,msg, ex);
                }
                logger.log(Logger.INFO,"Dumping threads:\n" + SupportUtil.getAllStackTraces("\t"));
            } else if (cmdarg.equals("pkt")) {
                IMQBasicConnection.dumpPacket(debugOn);
            } else if (cmdarg.equals("pktin")) {
                IMQBasicConnection.dumpInPacket(debugOn);
            } else if (cmdarg.equals("pktout")) {
                IMQBasicConnection.dumpOutPacket(debugOn);
            } else if (cmdarg.equals("class")) {
                try {
                    Class cl = Class.forName(target);
                    Field[] fields = cl.getDeclaredFields();
                    boolean found = false;
                    for (int i = 0; i < fields.length; i++) {
                         if (fields[i].getName().equals(Debug.debugFieldName)) {
                             fields[i].setAccessible(true);
                             fields[i].setBoolean(null, debugOn);
                             found = true;
                             break;
                         }
                    }
                    if (!found) throw new NoSuchFieldException(Debug.debugFieldName);
                } catch (Exception ex) {
                   status = Status.ERROR;
                   msg = "Unable to set DEBUG on class " + target +
                         " because " + ex.toString();
                   logger.logStack(Logger.INFO,msg, ex);
                }
            } else {
                status = Status.ERROR;
                msg = "Unknown debug argument " + cmdarg;           
            }
        } else if (cmd.equals("resume")) {
            // session, connection, consumerUID, producer
            if (cmdarg.equals("prd")) {
                try {
                    ProducerUID pid = new ProducerUID(
                        Long.parseLong(target));
                    Producer pr = Producer.getProducer(pid);
                    Destination d = Destination.getDestination(
                          pr.getDestinationUID());
                    logger.log(Logger.INFO,"Resuming " + pr);
                    d.forceResumeFlow(pr);
                   
                } catch (Exception ex) {
                    status = Status.ERROR;
                    msg = "Error resuming flow from producer  " + target +
                         " because " + ex.toString();
                   logger.logStack(Logger.INFO,msg, ex);
                }
            } else if (cmdarg.equals("cxn")) {
                try {
                    ConnectionUID uid = new ConnectionUID(
                        Long.parseLong(target));
                    IMQConnection cxn = (IMQConnection)
                        Globals.getConnectionManager()
                                .getConnection(uid);
                    cxn.resumeFlow(-1);
                   
                } catch (Exception ex) {
                    status = Status.ERROR;
                    msg = "Error resuming flow on connection  " + target +
                         " because " + ex.toString();
                   logger.logStack(Logger.INFO,msg, ex);
                }
            } else if (cmdarg.equals("con")) {
                try {
                    ConsumerUID cid = new ConsumerUID(
                        Long.parseLong(target));
                    Consumer cxn = (Consumer)
                        Consumer.getConsumer(cid);
                    cxn.resume("admin debug");
                } catch (Exception ex) {
                    status = Status.ERROR;
                    msg = "Error resuming flow to consumer  " + target +
                         " because " + ex.toString();
                   logger.logStack(Logger.INFO,msg, ex);
                }
            } else if (cmdarg.equals("ses")) {
                try {
                    SessionUID sid = new SessionUID(
                        Long.parseLong(target));
                    Session session = (Session)
                        Session.getSession(sid);
                    session.resume("admin debug");
                } catch (Exception ex) {
                    status = Status.ERROR;
                    msg = "Error resuming flow to session  " + target +
                         " because " + ex.toString();
                   logger.logStack(Logger.INFO,msg, ex);
View Full Code Here

            if (target == null) {
                throw new Exception("Please specify SessionUID" );
            }
            SessionUID uid = new SessionUID(
                      Long.parseLong(target));
            Session sess = Session.getSession(uid);
            if (sess == null)
                throw new Exception("Can not find session " + uid);
            ht.put(target,sess.getDebugMessages(full));
        } else {
            ht.put("Error", "Unknown pkt type " + type);
        }
        return ht;
    }
View Full Code Here

    }

    private Hashtable getSession(SessionUID uid)
        throws Exception
    {
        Session c = Session.getSession(uid);
        if (c == null)
            throw new Exception("Can not find session " + uid);
        return c.getDebugState();
    }
View Full Code Here

        ht.put("sessionCnt", String.valueOf(sessions.size()));
        if (sessions.size() > 0) {
            Vector v = new Vector();
            Iterator itr = sessions.values().iterator();
            while (itr.hasNext()) {
                Session p = (Session)itr.next();
                v.add(p.getSessionUID().toString());
            }
            ht.put("sessions", v);
        }
        ht.put("busySessionCnt", String.valueOf(busySessions.size()));
        if (busySessions.size() > 0) {
             Vector v = new Vector();
             Iterator itr = busySessions.iterator();
             while (itr.hasNext()) {
                Session p = (Session)itr.next();
                v.add(p.getSessionUID().toString());
             }
             ht.put("busySessions", v);
        }
        ht.put("tempDestCnt", String.valueOf(tmpDestinations.size()));
        if (tmpDestinations.size() > 0) {
             Vector v = new Vector();
             Iterator itr = tmpDestinations.iterator();
             while (itr.hasNext()) {
                DestinationUID p = (DestinationUID)itr.next();
                v.add(p.toString());
             }
             ht.put("tempDestinations", v);
        }
        ht.put("runningMsgs", String.valueOf(runningMsgs));
        ht.put("paused", String.valueOf(paused));
View Full Code Here

    public List getConsumers() {
        ArrayList cons = new ArrayList();
        Iterator itr = sessions.values().iterator();
        while (itr.hasNext()) {
            Session s = (Session)itr.next();
            Iterator citr = s.getConsumers();
            while (citr.hasNext()) {
                Consumer c = (Consumer)citr.next();
                cons.add(c);
            }
        }
View Full Code Here

    public List getConsumersIDs() {
        ArrayList cons = new ArrayList();
        Iterator itr = sessions.values().iterator();
        while (itr.hasNext()) {
            Session s = (Session)itr.next();
            Iterator citr = s.getConsumers();
            while (citr.hasNext()) {
                Consumer c = (Consumer)citr.next();
                cons.add(c.getConsumerUID());
            }
        }
View Full Code Here

    }
    public void closeSession(SessionUID uid)
        throws BrokerException
    {
        synchronized(sessions) {
            Session s = (Session)sessions.remove(uid);
            if (s == null)
                throw new BrokerException("Requested removal of "
                 + " session " + uid + " which is not associated with"
                 + " connection " + getConnectionUID());
            if (lockToSession != null && s != null)
                lockToSession.remove(s.getSessionUID());
        }
        Session.closeSession(uid);
    }
View Full Code Here

        }

        Long lsessionid = (Long)props.get("JMQSessionID");


        Session session = null;


        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}]",
                         msg.toString());
                }

                warning = BrokerResources.W_DESTROY_CONSUMER_FAILED;
                pkt.setPacketType(PacketType.DELETE_CONSUMER_REPLY);

                String durableName = (String)props.get("JMQDurableName");
                String clientID = getClientID(props, con);
                Long cid = (Long)props.get("JMQConsumerID");
                uid = (cid == null ? null new ConsumerUID( cid.longValue()));

                if (lsessionid != null) { //  passed on in
                    SessionUID sessionID = new SessionUID(lsessionid.longValue());
                    session = con.getSession(sessionID);
                } else {
                    session = Session.getSession(uid);
                }
                if (session == null && durableName == null && !isIndemp) {
                     if (con.getConnectionState() < Connection.STATE_CLOSED) {
                     logger.log(Logger.ERROR,"Internal error processing"+
                           " delete consumer\n"+
                            com.sun.messaging.jmq.jmsserver.util
                              .PacketUtil.dumpPacket(msg));
                     Session.dumpAll();
                     }
                }

                // retrieve the LastDelivered property
                Integer bodytype = (Integer)props.get("JMQBodyType");
                int btype = (bodytype == null ? 0 : bodytype.intValue());
               
                SysMessageID lastid = null;

                if (btype == PacketType.SYSMESSAGEID) {
                    int size = msg.getMessageBodySize();
                    if (size == 0) {
                        logger.log(Logger.INFO,"Warning, bad body in destroy consumer");
                     } else {
                         DataInputStream is = new DataInputStream(
                                msg.getMessageBodyStream());
                         lastid = new SysMessageID();
                         lastid.readID(is);
                     }
                }
                if (DEBUG && lastid != null) {
                    logger.log(Logger.DEBUG,"Sent lastID [" + lastid + "]"
                       + " for consumer " + uid + Destination.get(lastid));
                }

                Boolean rAll = (Boolean)props.get("JMQRedeliverAll");
                boolean redeliverAll = (rAll == null ? false : rAll.booleanValue());

                if (!sessionPaused && session != null) {
                    sessionPaused = true;
                    session.pause("Consumer removeconsumer");
                }
                destroyConsumer(con, session, uid, durableName, clientID, lastid,
                       redeliverAll, isIndemp);

            }

        } catch (BrokerException ex) {

            status = ex.getStatusCode();
            String consumid = null;
            String destination = null;
            try {
                destination = (String) props.get("JMQDestination");
                if (destination == null && msg.getPacketType()
                     != PacketType.ADD_CONSUMER)
                     destination = "";
                if (oldid != null)
                    consumid = oldid.toString();
                else
                    consumid = "";
            } catch (Exception ex1) {}
            String args[] = {consumid, con.getRemoteConnectionString(), destination};

            err_reason = ex.getMessage();

            if (ex.getStatusCode() == Status.PRECONDITION_FAILED
                  || ex.getStatusCode() == Status.CONFLICT ) {
                logger.log(Logger.WARNING, warning, args, ex);
            } else if (ex.getStatusCode() == Status.BAD_REQUEST) {
                // Probably a bad selector
                logger.log(Logger.WARNING, warning, args, ex);
                if (ex.getCause() != null) {
                    logger.log(Logger.INFO, ex.getCause().toString());
                }
            } else {
                if (isIndemp && msg.getPacketType() == PacketType.DELETE_CONSUMER) {
                    logger.logStack(Logger.DEBUG, "Reprocessing Indempotent message for "
                          + "{0} on destination {2} from {1}",args, ex);
                    status = Status.OK;
                    err_reason = null;
                } else {
                    logger.logStack(Logger.WARNING, warning,args, ex);
                }
            }
        } catch (IOException ex) {
            logger.log(Logger.INFO,"Internal Error: unable to process "+
                " consumer request " + msg, ex);
            props = new Hashtable();
            err_reason = ex.getMessage();
            assert false;
        } catch (SecurityException ex) {
            status = Status.FORBIDDEN;
            err_reason = ex.getMessage();
            String destination = null;
            String consumid = null;
            try {
                destination = (String) props.get("JMQDestination");
                if (oldid != null)
                    consumid = oldid.toString();
            } catch (Exception ex1) {}
            logger.log(Logger.WARNING, warning, destination, consumid,ex);
        } finally {
            if (conPaused)
                con.resume();
        }
        hash.put("JMQStatus", new Integer(status));

        if (err_reason != null)
            hash.put("JMQReason", err_reason);

        if (uid != null) {
            hash.put("JMQConsumerID", new Long(uid.longValue()));
            if (DEBUG || logger.getLevel() <= Logger.DEBUG) {
                if (props.get("JMQOldConsumerID") != null ) {
                logger.log(Logger.INFO, "Consumer "+ uid+ ", JMQOldConsumerID:"+
                                        props.get("JMQOldConsumerID"));
                }
            }
        }

        if (destType != null)
            hash.put("JMQDestType", destType);

        if (((IMQBasicConnection)con).getDumpPacket() ||
                ((IMQBasicConnection)con).getDumpOutPacket())
            hash.put("JMQReqID", msg.getSysMessageID().toString());

        pkt.setProperties(hash);
        con.sendControlMessage(pkt);

        if (sessionPaused)
             session.resume("Consumer - session was paused");

        if (sub != null)
            sub.resume("Consumer - added to sub");
       
        if (newc != null)
View Full Code Here

TOP

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

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.