Search in sources :

Example 51 with Destination

use of com.sun.messaging.jmq.jmsserver.core.Destination in project openmq by eclipse-ee4j.

the class ConsumerHandler method handle.

/**
 * Method to handle Consumer(add or delete) messages
 */
@Override
public boolean handle(IMQConnection con, Packet msg) throws BrokerException {
    boolean sessionPaused = false;
    boolean conPaused = false;
    Hashtable props = null;
    try {
        props = msg.getProperties();
    } catch (Exception ex) {
        logger.logStack(Logger.WARNING, "Unable to retrieve " + " properties from consumer message " + msg, ex);
    }
    if (props == null) {
        props = new Hashtable();
    }
    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());
    // correlation ID
    pkt.setConsumerID(msg.getConsumerID());
    Hashtable hash = new Hashtable();
    pkt.setPacketType(msg.getPacketType() + 1);
    int status = Status.OK;
    String warning = BrokerResources.W_ADD_CONSUMER_FAILED;
    ConsumerUID uid = null;
    Integer oldid = null;
    Subscription sub = null;
    try {
        DL.acquirePartitionLock(true);
        try {
            con.suspend();
            conPaused = true;
            if (msg.getPacketType() == PacketType.ADD_CONSUMER) {
                if (DEBUG) {
                    logger.log(Logger.INFO, "ConsumerHandler: " + "[Received AddConsumer message {0}]", msg.toString());
                }
                pkt.setPacketType(PacketType.ADD_CONSUMER_REPLY);
                if (lsessionid == null) {
                    if (DEBUG) {
                        logger.log(Logger.INFO, "ConsumerHandler: 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, coreLifecycle);
                        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
                // old consumer ID
                oldid = (Integer) props.get("JMQConsumerID");
                if (oldid != null) {
                    hash.put("JMQOldConsumerID", oldid);
                }
                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");
                // JMS spec
                if (selector != null && selector.trim().length() == 0) {
                    selector = null;
                }
                boolean mqshare = false;
                // JMS2.0
                boolean jmsshare = false;
                boolean nolocal = false;
                Boolean b = (Boolean) props.get("JMQNoLocal");
                if (b != null && b.booleanValue()) {
                    nolocal = true;
                }
                b = (Boolean) props.get("JMQShare");
                if (b != null && b.booleanValue()) {
                    mqshare = true;
                }
                // JMS2.0
                b = (Boolean) props.get("JMQJMSShare");
                if (b != null && b.booleanValue()) {
                    jmsshare = true;
                }
                String durablename = (String) props.get("JMQDurableName");
                // JMS2.0
                String subscriptionName = (String) props.get("JMQSharedSubscriptionName");
                String clientid = getClientID(props, con);
                Boolean reconnect = (Boolean) props.get("JMQReconnect");
                Integer size = (Integer) props.get("JMQSize");
                if (mqshare && jmsshare) {
                    String emsg = "Client protocol error: both JMQShare and JMQJMSShare set to true";
                    Globals.getLogger().log(Logger.ERROR, emsg);
                    throw new BrokerException(emsg);
                }
                boolean shared = (mqshare || jmsshare);
                boolean durable = false;
                if (durablename != null) {
                    if (subscriptionName != null) {
                        Object[] args = { Subscription.getDSubLogString(clientid, durablename), "" + destination, subscriptionName };
                        logger.log(Logger.INFO, br.getKString(br.I_ADD_CONSUMER_IGNORE_SUBSCRIPTION_NAME, args));
                    }
                    subscriptionName = durablename;
                    durable = true;
                }
                if (DestType.isTemporary(type)) {
                    if (durable) {
                        String emsg = br.getKString(br.X_INVALID_DEST_DURA_CONSUMER, "" + destination, "" + subscriptionName);
                        logger.log(Logger.ERROR, emsg);
                        throw new BrokerException(emsg, br.X_INVALID_DEST_DURA_CONSUMER, null, Status.PRECONDITION_FAILED);
                    }
                    if (shared) {
                        String emsg = br.getKString(br.X_INVALID_DEST_SHARE_CONSUMER, "" + destination, "" + subscriptionName);
                        logger.log(Logger.ERROR, emsg);
                        throw new BrokerException(emsg, br.X_INVALID_DEST_SHARE_CONSUMER, null, Status.PRECONDITION_FAILED);
                    }
                }
                ConsumerParameters pm = new ConsumerParameters();
                pm.isqueue = queue;
                pm.destination = destination;
                pm.selector = selector;
                pm.clientid = clientid;
                pm.subscriptionName = subscriptionName;
                pm.durable = durable;
                pm.shared = shared;
                pm.jmsshare = jmsshare;
                pm.nolocal = nolocal;
                checkSubscriptionName(pm);
                checkClientID(pm);
                checkNoLocal(pm);
                if (reconnect != null && reconnect.booleanValue()) {
                    Globals.getLogger().log(Logger.ERROR, BrokerResources.E_INTERNAL_BROKER_ERROR, "JMQReconnect not implemented");
                }
                // 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 {
                    Destination[] ds = null;
                    while (true) {
                        ds = DL.getDestination(con.getPartitionedStore(), destination, type, true, /* autocreate if possible */
                        !con.isAdminConnection());
                        // PART
                        d = ds[0];
                        if (d == null) {
                            break;
                        }
                        if (d.isAutoCreated()) {
                            warning = BrokerResources.W_ADD_AUTO_CONSUMER_FAILED;
                        }
                        try {
                            d.incrementRefCount();
                        } catch (BrokerException ex) {
                            // was destroyed in process
                            continue;
                        } catch (IllegalStateException ex) {
                            throw new BrokerException(Globals.getBrokerResources().getKString(BrokerResources.X_SHUTTING_DOWN_BROKER), BrokerResources.X_SHUTTING_DOWN_BROKER, ex, Status.ERROR);
                        }
                        // we got one
                        break;
                    }
                    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();
                }
                if (jmsshare && mqshare) {
                    Object[] args = { "JMS", (!durable ? Subscription.getNDSubLongLogString(clientid, dest_uid, selector, subscriptionName, nolocal) : Subscription.getDSubLogString(clientid, subscriptionName)), "" + destination, "JMQShare" };
                    logger.log(Logger.INFO, br.getKString(br.I_ADD_SHARE_CONSUMER_IGNORE_CLIENT_FLAG, args));
                    mqshare = false;
                }
                Consumer c = null;
                try {
                    // LKS
                    Consumer[] retc = _createConsumer(dest_uid, con, session, selector, clientid, subscriptionName, durable, shared, jmsshare, nolocal, (size == null ? -1 : size.intValue()), 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 = { Subscription.getDSubLogString(clientid, durablename), dest_uid.getName(), 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();
                if (props.get("JMQOldConsumerID") != null) {
                    Object[] args = { uid + (sub == null ? "" : "[" + sub + "]"), "" + dest_uid, props.get("JMQOldConsumerID") };
                    logger.log(Logger.INFO, br.getKString(br.I_CREATED_NEW_CONSUMER_FOR_OLD, args));
                }
            } else {
                // removing Interest
                if (DEBUG) {
                    logger.log(Logger.INFO, "ConsumerHandler: " + "[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_CLEANED) {
                        logger.log(Logger.ERROR, br.getKString(br.E_UNEXPECTED_EXCEPTION, br.getKString(br.E_DELETE_CONSUMER_NO_SESSION, (lsessionid == null ? "" : lsessionid), uid + "") + "\n" + com.sun.messaging.jmq.io.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;
                boolean lastidInTransaction = false;
                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);
                        Boolean val = (Boolean) props.get("JMQLastDeliveredIDInTransaction");
                        lastidInTransaction = (val != null && val.booleanValue());
                    }
                }
                if (DEBUG && lastid != null) {
                    logger.log(Logger.INFO, "ConsumerHandler: destroy consumer with lastID [" + lastid + ", " + lastidInTransaction + "]" + DL.get(con.getPartitionedStore(), lastid) + " for consumer " + uid);
                }
                Boolean rAll = (Boolean) props.get("JMQRedeliverAll");
                boolean redeliverAll = rAll != null && rAll.booleanValue();
                if (!sessionPaused && session != null) {
                    sessionPaused = true;
                    session.pause("Consumer removeconsumer");
                }
                destroyConsumer(con, session, uid, durableName, clientID, lastid, lastidInTransaction, redeliverAll, isIndemp);
            }
        } finally {
            DL.releasePartitionLock(true);
        }
    } 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.logStack(Logger.WARNING, "Unable to process " + " consumer request " + msg, ex);
        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", Integer.valueOf(status));
    if (err_reason != null) {
        hash.put("JMQReason", err_reason);
    }
    if (uid != null) {
        hash.put("JMQConsumerID", Long.valueOf(uid.longValue()));
    }
    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) {
        newc.resume("Consumer - new consumer");
    }
    return true;
}
Also used : Destination(com.sun.messaging.jmq.jmsserver.core.Destination) BrokerException(com.sun.messaging.jmq.jmsserver.util.BrokerException) Consumer(com.sun.messaging.jmq.jmsserver.core.Consumer) Subscription(com.sun.messaging.jmq.jmsserver.core.Subscription) OutOfLimitsException(com.sun.messaging.jmq.util.lists.OutOfLimitsException) ConsumerUID(com.sun.messaging.jmq.jmsserver.core.ConsumerUID) SessionUID(com.sun.messaging.jmq.jmsserver.core.SessionUID) OutOfLimitsException(com.sun.messaging.jmq.util.lists.OutOfLimitsException) SelectorFormatException(com.sun.messaging.jmq.util.selector.SelectorFormatException) ConsumerAlreadyAddedException(com.sun.messaging.jmq.jmsserver.util.ConsumerAlreadyAddedException) BrokerException(com.sun.messaging.jmq.jmsserver.util.BrokerException) SelectorFormatException(com.sun.messaging.jmq.util.selector.SelectorFormatException) DestinationUID(com.sun.messaging.jmq.jmsserver.core.DestinationUID) Session(com.sun.messaging.jmq.jmsserver.core.Session)

Example 52 with Destination

use of com.sun.messaging.jmq.jmsserver.core.Destination in project openmq by eclipse-ee4j.

the class DataHandler method handle.

/**
 * Method to handle normal/admin data messages
 */
protected boolean handle(IMQConnection con, Packet msg, boolean isadmin) throws BrokerException {
    // used for fault injection
    Hashtable props = null;
    if (!isadmin && fi.FAULT_INJECTION) {
        // for fault injection
        msgProcessCnt++;
        try {
            props = msg.getProperties();
        } catch (Exception ex) {
            props = new Properties();
        }
    } else {
        msgProcessCnt = 0;
    }
    boolean ack = msg.getSendAcknowledge();
    long cid = msg.getConsumerID();
    String refid = (((IMQBasicConnection) con).getDumpPacket() || ((IMQBasicConnection) con).getDumpOutPacket()) ? msg.getSysMessageID().toString() : "";
    boolean isIndemp = msg.getIndempotent();
    String reason = null;
    List failedrefs = null;
    int status = Status.OK;
    HashMap routedSet = null;
    List<MessageDeliveryTimeInfo> deliveryDelayReadyList = new ArrayList<>();
    boolean route = false;
    Producer pausedProducer = null;
    boolean transacted = false;
    try {
        pausedProducer = checkFlow(msg, con);
        transacted = (msg.getTransactionID() != 0);
        // OK .. handle Fault Injection
        if (!isadmin && fi.FAULT_INJECTION) {
            Map m = new HashMap();
            if (props != null) {
                m.putAll(props);
            }
            m.put("mqMsgCount", Integer.valueOf(msgProcessCnt));
            m.put("mqIsTransacted", Boolean.valueOf(transacted));
            fi.checkFaultAndExit(FaultInjection.FAULT_SEND_MSG_1, m, 2, false);
            if (fi.checkFault(FaultInjection.FAULT_SEND_MSG_1_EXCEPTION, m)) {
                fi.unsetFault(FaultInjection.FAULT_SEND_MSG_1_EXCEPTION);
                throw new BrokerException("FAULT INJECTION: " + FaultInjection.FAULT_SEND_MSG_1_EXCEPTION);
            }
            if (fi.checkFaultAndSleep(FaultInjection.FAULT_SEND_MSG_1_SLEEP, m, true)) {
                fi.unsetFault(FaultInjection.FAULT_SEND_MSG_1_SLEEP);
            }
            if (fi.checkFaultAndSleep(FaultInjection.FAULT_SEND_MSG_1_SLEEP_EXCEPTION, m, true)) {
                fi.unsetFault(FaultInjection.FAULT_SEND_MSG_1_SLEEP_EXCEPTION);
                throw new BrokerException("FAULT INJECTION: " + FaultInjection.FAULT_SEND_MSG_1_SLEEP_EXCEPTION);
            }
        }
        DestinationUID realduid = DestinationUID.getUID(msg.getDestination(), msg.getIsQueue());
        if (DEBUG) {
            logger.log(Logger.INFO, "DataHandler:Received JMS Message[" + msg.toString() + " : " + realduid + "]TID=" + msg.getTransactionID() + " on connection " + con + ", isadmin=" + isadmin);
        }
        // get the list of "real" destination UIDs (this will be one if the
        // destination if not a wildcard and 0 or more if it is
        List[] dds = DL.findMatchingIDs(con.getPartitionedStore(), realduid);
        List duids = dds[0];
        boolean packetUsed = false;
        if (duids.size() == 0) {
            // nothing to do
            route = false;
        } else {
            Iterator itr = duids.iterator();
            while (itr.hasNext()) {
                PacketReference ref = null;
                Exception lastthr = null;
                boolean isLast = false;
                DestinationUID duid = (DestinationUID) itr.next();
                isLast = !itr.hasNext();
                Destination[] ds = DL.getDestination(con.getPartitionedStore(), duid);
                Destination d = ds[0];
                try {
                    if (d == null) {
                        throw new BrokerException("Unknown Destination:" + msg.getDestination());
                    }
                    if (realduid.isWildcard() && d.isTemporary()) {
                        logger.log(Logger.DEBUG, "L10N-XXX: Wildcard production with destination name of " + realduid + " to temporary destination " + d.getUniqueName() + " is not supported, ignoring");
                        continue;
                    }
                    if (realduid.isWildcard() && d.isInternal()) {
                        logger.log(Logger.DEBUG, "L10N-XXX: Wildcard production with destination name of " + realduid + " to internal destination " + d.getUniqueName() + " is not supported, ignoring");
                        continue;
                    }
                    if (realduid.isWildcard() && d.isDMQ()) {
                        logger.log(Logger.DEBUG, "L10N-XXX: Wildcard production with destination name of " + realduid + " to the DeadMessageQueue" + d.getUniqueName() + " is not supported, ignoring");
                        continue;
                    }
                    if (pausedProducer != null) {
                        pauseProducer(d, duid, pausedProducer, con);
                        pausedProducer = null;
                    }
                    if (packetUsed) {
                        // create a new Packet for the message
                        // we need a new sysmsgid with it
                        Packet newp = new Packet();
                        newp.fill(msg);
                        newp.generateSequenceNumber(true);
                        newp.generateTimestamp(true);
                        newp.prepareToSend();
                        newp.generateSequenceNumber(false);
                        newp.generateTimestamp(false);
                        msg = newp;
                    }
                    packetUsed = true;
                    // OK generate a ref. This checks message size and
                    // will be needed for later operations
                    ref = createReference(msg, duid, con, isadmin);
                    // dont bother calling route if there are no messages
                    // 
                    // to improve performance, we route and later forward
                    route |= queueMessage(d, ref, transacted);
                    // ok ...
                    if (isLast && route && ack && !ref.isPersistent()) {
                        sendAcknowledge(refid, cid, status, con, reason, props, transacted);
                        ack = false;
                    }
                    Set s = routeMessage(con.getPartitionedStore(), transacted, ref, route, d, deliveryDelayReadyList);
                    if (s != null && !s.isEmpty()) {
                        if (routedSet == null) {
                            routedSet = new HashMap();
                        }
                        routedSet.put(ref, s);
                    }
                    // handle producer flow control
                    pauseProducer(d, duid, pausedProducer, con);
                } catch (Exception ex) {
                    if (ref != null) {
                        if (failedrefs == null) {
                            failedrefs = new ArrayList();
                        }
                        failedrefs.add(ref);
                    }
                    lastthr = ex;
                    logger.log(Logger.DEBUG, BrokerResources.W_MESSAGE_STORE_FAILED, con.toString(), ex);
                } finally {
                    if (pausedProducer != null) {
                        pauseProducer(d, duid, pausedProducer, con);
                        pausedProducer = null;
                    }
                    if (isLast && lastthr != null) {
                        throw lastthr;
                    }
                }
            }
        // while
        }
    } catch (BrokerException ex) {
        // dont log on dups if indemponent
        int loglevel = (isIndemp && ex.getStatusCode() == Status.NOT_MODIFIED) ? Logger.DEBUG : Logger.WARNING;
        logger.log(loglevel, BrokerResources.W_MESSAGE_STORE_FAILED, con.toString(), ex);
        reason = ex.getMessage();
        // LKS - we may want an improved error message in the wildcard case
        status = ex.getStatusCode();
    } catch (IOException ex) {
        logger.log(Logger.WARNING, BrokerResources.W_MESSAGE_STORE_FAILED, con.toString(), ex);
        reason = ex.getMessage();
        status = Status.ERROR;
    } catch (SecurityException ex) {
        logger.log(Logger.WARNING, BrokerResources.W_MESSAGE_STORE_FAILED, con.toString(), ex);
        reason = ex.getMessage();
        status = Status.FORBIDDEN;
    } catch (OutOfMemoryError err) {
        logger.logStack(Logger.WARNING, BrokerResources.W_MESSAGE_STORE_FAILED, con.toString() + ":" + msg.getPacketSize(), err);
        reason = err.getMessage();
        status = Status.ERROR;
    } catch (Exception ex) {
        logger.logStack(Logger.WARNING, BrokerResources.W_MESSAGE_STORE_FAILED, con.toString(), ex);
        reason = ex.getMessage();
        status = Status.ERROR;
    }
    if (status == Status.ERROR && failedrefs != null) {
        // make sure we remove the message
        // 
        // NOTE: we only want to remove the last failure (its too late
        // for the rest). In the non-wildcard case, this will be the
        // only entry. In the wildcard cause, it will be the one that had an issue
        Iterator itr = failedrefs.iterator();
        while (itr.hasNext()) {
            PacketReference ref = (PacketReference) itr.next();
            Destination[] ds = DL.getDestination(con.getPartitionedStore(), ref.getDestinationUID());
            Destination d = ds[0];
            if (d != null) {
                cleanupOnError(d, ref);
            }
        }
    }
    if (ack) {
        sendAcknowledge(refid, cid, status, con, reason, props, transacted);
    }
    if (route && routedSet != null) {
        Iterator<Map.Entry> itr = routedSet.entrySet().iterator();
        Map.Entry pair = null;
        while (itr.hasNext()) {
            pair = itr.next();
            PacketReference pktref = (PacketReference) pair.getKey();
            DestinationUID duid = pktref.getDestinationUID();
            Set s = (Set) pair.getValue();
            Destination[] ds = DL.getDestination(con.getPartitionedStore(), duid);
            Destination dest = ds[0];
            if (dest == null) {
                Object[] emsg = { pktref, s, duid };
                logger.log(logger.WARNING, br.getKString(br.W_ROUTE_PRODUCED_MSG_DEST_NOT_FOUND, emsg));
                continue;
            }
            try {
                forwardMessage(dest, pktref, s);
            } catch (Exception e) {
                Object[] emsg = { pktref, duid, s };
                logger.logStack(logger.WARNING, br.getKString(br.X_ROUTE_PRODUCED_MSG_FAIL, emsg), e);
            }
        }
    }
    if (deliveryDelayReadyList.size() > 0) {
        MessageDeliveryTimeInfo di = null;
        Iterator<MessageDeliveryTimeInfo> itr = deliveryDelayReadyList.iterator();
        while (itr.hasNext()) {
            di = itr.next();
            di.setDeliveryReady();
        }
    }
    // someone else will free
    return isadmin;
}
Also used : Destination(com.sun.messaging.jmq.jmsserver.core.Destination) BrokerException(com.sun.messaging.jmq.jmsserver.util.BrokerException) PacketReference(com.sun.messaging.jmq.jmsserver.core.PacketReference) TransactionList(com.sun.messaging.jmq.jmsserver.data.TransactionList) MessageDeliveryTimeInfo(com.sun.messaging.jmq.jmsserver.core.MessageDeliveryTimeInfo) SelectorFormatException(com.sun.messaging.jmq.util.selector.SelectorFormatException) BrokerException(com.sun.messaging.jmq.jmsserver.util.BrokerException) DestinationUID(com.sun.messaging.jmq.jmsserver.core.DestinationUID) Producer(com.sun.messaging.jmq.jmsserver.core.Producer)

Example 53 with Destination

use of com.sun.messaging.jmq.jmsserver.core.Destination in project openmq by eclipse-ee4j.

the class DestinationHandler method handle.

/**
 * Method to handle Destination (create or delete) messages
 */
@Override
public boolean handle(IMQConnection con, Packet msg) throws BrokerException {
    int status = Status.OK;
    String reason = null;
    // XXX - REVISIT 2/25/00 racer
    // do we need to create a reply packet each time ?
    Packet pkt = new Packet(con.useDirectBuffers());
    pkt.setConsumerID(msg.getConsumerID());
    Hashtable hash = new Hashtable();
    Hashtable props = null;
    try {
        props = msg.getProperties();
    } catch (Exception ex) {
        assert false;
        logger.logStack(Logger.ERROR, BrokerResources.E_INTERNAL_BROKER_ERROR, "Unable to create/destroy destination - no properties", ex);
        throw new BrokerException(Globals.getBrokerResources().getString(BrokerResources.X_INTERNAL_EXCEPTION, "Can not handle create/destroy destination"));
    }
    String destination = (String) props.get("JMQDestination");
    Integer inttype = (Integer) props.get("JMQDestType");
    int type = (inttype == null) ? 0 : inttype.intValue();
    pkt.setPacketType(msg.getPacketType() + 1);
    if (msg.getPacketType() == PacketType.CREATE_DESTINATION) {
        if (DEBUG) {
            logger.log(Logger.DEBUGHIGH, "ConsumerHandler: handle() [ Received AddDestination message {0}]", msg.toString());
        }
        assert destination != null;
        assert inttype != null;
        if (con.isAdminConnection()) {
            type |= DestType.DEST_ADMIN | DestType.DEST_LOCAL | DestType.DEST_AUTO;
        }
        assert pkt.getPacketType() == PacketType.CREATE_DESTINATION_REPLY;
        try {
            Destination d = null;
            if (DestType.isTemporary(type)) {
                // deal w/ versioning .. only store
                // 3.5 or later
                boolean storeTemps = con.getConnectionUID().getCanReconnect();
                long reconnectTime = con.getReconnectInterval();
                Destination[] ds = DL.createTempDestination(con.getPartitionedStore(), destination, type, con.getConnectionUID(), storeTemps, reconnectTime);
                d = ds[0];
                if (con.getConnectionUID().equals(d.getConnectionUID())) {
                    con.attachTempDestination(d.getDestinationUID());
                }
            } else if (destination.startsWith(Globals.INTERNAL_PREFIX)) {
            // do nothing
            } else if (DestinationUID.isWildcard(destination)) {
                pkt.setWildcard(true);
            // dont create a destination
            } else {
                Destination[] ds = DL.getDestination(con.getPartitionedStore(), destination, type, true, !con.isAdminConnection());
                d = ds[0];
            }
            hash.put("JMQDestType", Integer.valueOf(type));
            hash.put("JMQDestUID", destination);
            /*
                 * Set XML Schema validation properties
                 */
            hash.put("JMQValidateXMLSchema", Boolean.valueOf(isXMLSchemaValidationOn(d)));
            String uris = getXMLSchemaURIList(d);
            if (uris != null) {
                hash.put("JMQXMLSchemaURIList", uris);
            }
            hash.put("JMQReloadXMLSchemaOnFailure", Boolean.valueOf(getReloadXMLSchemaOnFailure(d)));
        } catch (BrokerException ex) {
            status = ex.getStatusCode();
            reason = ex.getMessage();
            if (status != Status.CONFLICT) {
                logger.log(Logger.WARNING, BrokerResources.W_CREATE_DEST_FAILED, destination, ex);
            } else if (DEBUG) {
                logger.log(Logger.DEBUG, BrokerResources.W_CREATE_DEST_FAILED, destination, ex);
            }
        } catch (IOException ex) {
            status = Status.ERROR;
            reason = ex.getMessage();
            logger.log(Logger.WARNING, BrokerResources.W_CREATE_DEST_FAILED, destination, ex);
        }
    } else {
        // removing Interest
        assert msg.getPacketType() == PacketType.DESTROY_DESTINATION;
        assert pkt.getPacketType() == PacketType.DESTROY_DESTINATION_REPLY;
        Destination d = null;
        try {
            DestinationUID rmuid = DestinationUID.getUID(destination, DestType.isQueue(type));
            if (destination == null) {
                throw new BrokerException(Globals.getBrokerResources().getString(BrokerResources.X_INTERNAL_EXCEPTION, "protocol error,  destination is null"), Status.NOT_FOUND);
            }
            Destination[] ds = DL.getDestination(con.getPartitionedStore(), rmuid);
            d = ds[0];
            assert d != null;
            DL.removeDestination(con.getPartitionedStore(), rmuid, true, Globals.getBrokerResources().getString(BrokerResources.M_CLIENT_REQUEST, con.getConnectionUID()));
            con.detachTempDestination(rmuid);
        } catch (BrokerException ex) {
            status = ex.getStatusCode();
            reason = ex.getMessage();
            logger.log(Logger.WARNING, BrokerResources.W_DESTROY_DEST_FAILED, destination, ex);
        } catch (IOException ex) {
            status = Status.ERROR;
            reason = ex.getMessage();
            logger.log(Logger.WARNING, BrokerResources.W_DESTROY_DEST_FAILED, destination, ex);
        }
    }
    hash.put("JMQStatus", Integer.valueOf(status));
    if (reason != null) {
        hash.put("JMQReason", reason);
    }
    if (((IMQBasicConnection) con).getDumpPacket() || ((IMQBasicConnection) con).getDumpOutPacket()) {
        hash.put("JMQReqID", msg.getSysMessageID().toString());
    }
    pkt.setProperties(hash);
    con.sendControlMessage(pkt);
    return true;
}
Also used : Destination(com.sun.messaging.jmq.jmsserver.core.Destination) BrokerException(com.sun.messaging.jmq.jmsserver.util.BrokerException) BrokerException(com.sun.messaging.jmq.jmsserver.util.BrokerException) DestinationUID(com.sun.messaging.jmq.jmsserver.core.DestinationUID)

Example 54 with Destination

use of com.sun.messaging.jmq.jmsserver.core.Destination in project openmq by eclipse-ee4j.

the class ProducerHandler method handle.

/**
 * Method to handle Producers
 */
@Override
public boolean handle(IMQConnection con, Packet msg) throws BrokerException {
    Packet reply = new Packet(con.useDirectBuffers());
    reply.setPacketType(msg.getPacketType() + 1);
    reply.setConsumerID(msg.getConsumerID());
    boolean isIndemp = msg.getIndempotent();
    int status = Status.OK;
    String reason = null;
    Hashtable props = null;
    try {
        props = msg.getProperties();
    } catch (Exception ex) {
        throw new RuntimeException("Can not load props", ex);
    }
    Hashtable returnprop = new Hashtable();
    Destination d = null;
    try {
        if (msg.getPacketType() == PacketType.ADD_PRODUCER) {
            String dest = (String) props.get("JMQDestination");
            Integer type = (Integer) props.get("JMQDestType");
            if (!con.isAdminConnection() && MemoryGlobals.getMEM_DISALLOW_PRODUCERS()) {
                status = Status.ERROR;
                reason = "Low memory";
                logger.log(Logger.WARNING, BrokerResources.W_LOW_MEM_REJECT_PRODUCER);
                throw new BrokerException(reason, status);
            }
            Long lsessionid = (Long) props.get("JMQSessionID");
            if (lsessionid != null) {
                // 3.5 protocol
                SessionUID sessionID = new SessionUID(lsessionid.longValue());
                // single threaded .. we dont have to worry about
                // someone else creating it
                Session session = con.getSession(sessionID);
                if (session == null) {
                    throw new BrokerException("Internal Error: client sent " + "invalid sessionUID w/ ADD_PRODUCER " + sessionID + " session does not exist");
                }
            }
            Destination[] ds = null;
            DestinationUID duid = null;
            if (dest != null && !DestinationUID.isWildcard(dest) && type != null) {
                while (true) {
                    ds = DL.getDestination(con.getPartitionedStore(), dest, type.intValue(), true, !con.isAdminConnection());
                    d = ds[0];
                    if (d != null) {
                        try {
                            d.incrementRefCount();
                        } catch (BrokerException ex) {
                            // try again
                            continue;
                        } catch (IllegalStateException ex) {
                            throw new BrokerException(Globals.getBrokerResources().getKString(BrokerResources.X_SHUTTING_DOWN_BROKER), BrokerResources.X_SHUTTING_DOWN_BROKER, ex, Status.ERROR);
                        }
                    }
                    // got a lock on the dest
                    break;
                }
                if (d == null) {
                    logger.log(Logger.DEBUG, "Unable to add " + "producer to " + dest + " :" + DestType.toString(type.intValue()) + " destination can not be autocreated ");
                    reason = "can not create destination";
                    status = Status.NOT_FOUND;
                    throw new BrokerException(reason, status);
                }
                duid = d.getDestinationUID();
            } else if (dest == null || type == null) {
                reason = "no destination passed [dest,type] = [" + dest + "," + type + "]";
                status = Status.ERROR;
                throw new BrokerException(reason, status);
            } else {
                duid = DestinationUID.getUID(dest, DestType.isQueue(type.intValue()));
            }
            String info = msg.getSysMessageID().toString();
            Producer p = addProducer(duid, con, info, isIndemp);
            ProducerUID pid = p.getProducerUID();
            assert pid != null;
            // LKS - XXX - REVISIT - WHAT ABOUT FLOW CONTROL
            boolean active = d == null || d.isProducerActive(pid);
            returnprop.put("JMQProducerID", Long.valueOf(pid.longValue()));
            returnprop.put("JMQDestinationID", duid.toString());
            if (d == null) {
                returnprop.put("JMQBytes", Long.valueOf(-1));
                returnprop.put("JMQSize", Integer.valueOf(-1));
            } else if (active) {
                returnprop.put("JMQBytes", Long.valueOf(d.getBytesProducerFlow()));
                returnprop.put("JMQSize", Integer.valueOf(d.getSizeProducerFlow()));
            } else {
                returnprop.put("JMQBytes", Long.valueOf(0));
                returnprop.put("JMQSize", Integer.valueOf(0));
            }
        } else {
            assert msg.getPacketType() == PacketType.DELETE_PRODUCER;
            Long pid_l = (Long) props.get("JMQProducerID");
            ProducerUID pid = new ProducerUID(pid_l == null ? 0 : pid_l.longValue());
            removeProducer(pid, isIndemp, con, "Producer closed requested:\n\tconnection: " + con.getConnectionUID() + "\n\tproducerID: " + pid + "\n\trequest sysmsgid message: " + msg.getSysMessageID());
        }
    } catch (BrokerException ex) {
        status = ex.getStatusCode();
        reason = ex.getMessage();
        logger.log(Logger.INFO, reason);
    } catch (Exception ex) {
        logger.logStack(Logger.INFO, BrokerResources.E_INTERNAL_BROKER_ERROR, "producer message ", ex);
        reason = ex.getMessage();
        status = Status.ERROR;
    } finally {
        if (d != null) {
            d.decrementRefCount();
        }
    }
    returnprop.put("JMQStatus", Integer.valueOf(status));
    if (reason != null) {
        returnprop.put("JMQReason", reason);
    }
    if (((IMQBasicConnection) con).getDumpPacket() || ((IMQBasicConnection) con).getDumpOutPacket()) {
        returnprop.put("JMQReqID", msg.getSysMessageID().toString());
    }
    reply.setProperties(returnprop);
    con.sendControlMessage(reply);
    return true;
}
Also used : Destination(com.sun.messaging.jmq.jmsserver.core.Destination) BrokerException(com.sun.messaging.jmq.jmsserver.util.BrokerException) SessionUID(com.sun.messaging.jmq.jmsserver.core.SessionUID) ProducerUID(com.sun.messaging.jmq.jmsserver.core.ProducerUID) BrokerException(com.sun.messaging.jmq.jmsserver.util.BrokerException) DestinationUID(com.sun.messaging.jmq.jmsserver.core.DestinationUID) Producer(com.sun.messaging.jmq.jmsserver.core.Producer) Session(com.sun.messaging.jmq.jmsserver.core.Session)

Example 55 with Destination

use of com.sun.messaging.jmq.jmsserver.core.Destination in project openmq by eclipse-ee4j.

the class ProducerHandler method addProducer.

public Producer addProducer(DestinationUID duid, IMQConnection con, String id, boolean isIndemp) throws BrokerException {
    Producer p = null;
    if (isIndemp) {
        p = (Producer) Producer.getProducer(id);
    }
    if (p == null) {
        p = Producer.createProducer(duid, con.getConnectionUID(), id, con.getPartitionedStore());
        assert p != null;
        con.addProducer(p);
        // Add to all destinations
        List[] ll = DL.findMatchingIDs(con.getPartitionedStore(), duid);
        List l = ll[0];
        Iterator itr = l.iterator();
        DestinationUID realuid = null;
        Destination[] ds = null;
        Destination d = null;
        while (itr.hasNext()) {
            realuid = (DestinationUID) itr.next();
            ds = DL.getDestination(con.getPartitionedStore(), realuid);
            d = ds[0];
            if (duid.isWildcard() && d.isTemporary()) {
                logger.log(Logger.DEBUG, "L10N-XXX: Wildcard production with destination name of " + duid + " to temporary destination " + d.getUniqueName() + " is not supported, ignoring");
                continue;
            }
            if (duid.isWildcard() && d.isInternal()) {
                logger.log(Logger.DEBUG, "L10N-XXX: Wildcard production with destination name of " + duid + " to internal destination " + d.getUniqueName() + " is not supported, ignoring");
                continue;
            }
            if (duid.isWildcard() && d.isDMQ()) {
                logger.log(Logger.DEBUG, "L10N-XXX: Wildcard production with destination name of " + duid + " to the DeadMessageQueue" + d.getUniqueName() + " is not supported, ignoring");
                continue;
            }
            d.addProducer(p);
        }
    }
    return p;
}
Also used : Destination(com.sun.messaging.jmq.jmsserver.core.Destination) DestinationUID(com.sun.messaging.jmq.jmsserver.core.DestinationUID) Producer(com.sun.messaging.jmq.jmsserver.core.Producer) DestinationList(com.sun.messaging.jmq.jmsserver.core.DestinationList)

Aggregations

Destination (com.sun.messaging.jmq.jmsserver.core.Destination)76 BrokerException (com.sun.messaging.jmq.jmsserver.util.BrokerException)39 Iterator (java.util.Iterator)29 DestinationUID (com.sun.messaging.jmq.jmsserver.core.DestinationUID)25 PacketReference (com.sun.messaging.jmq.jmsserver.core.PacketReference)25 ConsumerUID (com.sun.messaging.jmq.jmsserver.core.ConsumerUID)20 SelectorFormatException (com.sun.messaging.jmq.util.selector.SelectorFormatException)18 HashMap (java.util.HashMap)18 Consumer (com.sun.messaging.jmq.jmsserver.core.Consumer)17 IOException (java.io.IOException)16 SysMessageID (com.sun.messaging.jmq.io.SysMessageID)15 ArrayList (java.util.ArrayList)12 List (java.util.List)11 Packet (com.sun.messaging.jmq.io.Packet)9 AckEntryNotFoundException (com.sun.messaging.jmq.jmsserver.util.AckEntryNotFoundException)9 Map (java.util.Map)9 DestinationList (com.sun.messaging.jmq.jmsserver.core.DestinationList)8 SizeString (com.sun.messaging.jmq.util.SizeString)8 PartitionedStore (com.sun.messaging.jmq.jmsserver.persist.api.PartitionedStore)7 ConsumerAlreadyAddedException (com.sun.messaging.jmq.jmsserver.util.ConsumerAlreadyAddedException)7