验证队列消息

时间:2016-06-16 13:24:07

标签: java smtp ibm-mq ftp-client

我使用Java代码使用WebSphere MQ工具在队列中插入消息。输入文本时,它会将消息存储在队列中。我想在插入消息时验证是否

1.队列是否存在

2.是否存在任何频道错误

3.Port编号不匹配

4.主机地址错误

我想捕获这些错误并将其存储在带有时间戳和错误日志服务的文本文件中。

帮我解决这个问题。

在队列中插入消息的菜单

Menu based insertion of messages in queue

Message inserted in Websphere MQ

公共类QueueMessage {      public static Sc​​anner sc = new Scanner(System.in);

private MQQueueManager _queueManager = null;
public int port = 1413;
public String hostname = "192.168.100.120";
public String channel = "QM_HOME.Q_LOCAL";
public String qManager = "QM_HOME";
public String inputQName = "Q_LOCAL_END";
public String outputQName = "Q_LOCAL_END";

public QueueMessage()
{
    super();
}

public void init(String[] args) throws IllegalArgumentException
{
    // Set up MQ environment
    MQEnvironment.hostname = hostname;
    System.out.println("HOST :"+hostname);
    MQEnvironment.channel = channel;
    MQEnvironment.port = port;
    System.out.println("init");
}

public void selectQMgr() throws MQException 
{

    _queueManager = new MQQueueManager(qManager);

}


public void write() throws MQException {

    int openOptions = MQC.MQOO_OUTPUT + MQC.MQOO_FAIL_IF_QUIESCING;
    try {
        MQQueue queue = _queueManager.accessQueue(outputQName, openOptions,
                null, // default q manager
                null, // no dynamic q name
                null); // no alternate user id

        DataInputStream input = new DataInputStream(System.in);

        System.out
                .println("MQWrite v1.0 connected and ready for input, terminate with ^Z\n\n");
        // Define a simple MQ message, and write some text in UTF format..
        MQMessage sendmsg = new MQMessage();
        sendmsg.format = MQC.MQFMT_STRING;
        sendmsg.feedback = MQC.MQFB_NONE;
        sendmsg.messageType = MQC.MQMT_DATAGRAM;
        sendmsg.replyToQueueName = "QM_LOCAL_END";
        sendmsg.replyToQueueManagerName = qManager;

        MQPutMessageOptions pmo = new MQPutMessageOptions(); // accept the
        String line = null; 



        System.out.print("Enter your Message: ");
        line = sc.nextLine();

        sendmsg.clearMessage();
        sendmsg.messageId = MQC.MQMI_NONE;
        sendmsg.correlationId = MQC.MQCI_NONE;
        sendmsg.writeString(line);
        // put the message on the queue
        queue.put(sendmsg, pmo);

        System.out.println("Message inserted: " + line);
        queue.close();
        _queueManager.disconnect();

        // same
        // as MQPMO_DEFAULT constant



    }

    catch (com.ibm.mq.MQException mqex) {
        System.out.println(mqex);
    } catch (java.io.IOException ioex) {
        System.out.println("An MQ IO error occurred : " + ioex);

    }
}

private void While(boolean b) {
    // TODO Auto-generated method stub

}

}

3 个答案:

答案 0 :(得分:1)

  

使用java代码

标准Java编码 - 您只需捕获MQException。

try
{
   _qMgr = new MQQueueManager(qMgrName, myHashTable);
}
catch (MQException e)
{
   System.err.println("Completion Code=" + e.completionCode + " Reason Code=" + e.reasonCode);
}

关于MQ的一切都记录在MQ Knowledge Center中。记录了所有MQ / Java类 - 即MQQueueManager class

要记住的#1规则是对象名称(队列,通道等)区分大小写。规则#2是MQ不是数据库。规则#3,确保您的应用程序记录所有'异常'。

  

1.队列是否存在

原因代码2085(MQRC_UNKNOWN_OBJECT_NAME)

  

2.是否存在任何频道错误

2009年的原因代码(MQRC_CONNECTION_BROKEN)

  

3.Port编号不匹配

原因代码2059(MQRC_Q_MGR_NOT_AVAILABLE)

  

4.主机地址错误

原因代码2538(MQRC_HOST_NOT_AVAILABLE)

答案 1 :(得分:0)

这是我的代码,它在插入消息时工作正常,如果消息未存储在Websphere MQ中,我想捕获错误。并将错误存储在日志文件中

公共类QueueMessage {      public static Sc​​anner sc = new Scanner(System.in);

private MQQueueManager _queueManager = null;
public int port = 1413;
public String hostname = "192.168.100.120";
public String channel = "QM_HOME.Q_LOCAL";
public String qManager = "QM_HOME";
public String inputQName = "Q_LOCAL_END";
public String outputQName = "Q_LOCAL_END";

public QueueMessage()
{
    super();
}

public void init(String[] args) throws IllegalArgumentException
{
    // Set up MQ environment
    MQEnvironment.hostname = hostname;
    MQEnvironment.channel = channel;
    MQEnvironment.port = port;

}

public void selectQMgr() throws MQException 
{
    _queueManager = new MQQueueManager(qManager);
}


public void write() throws MQException {

    int openOptions = MQC.MQOO_OUTPUT + MQC.MQOO_FAIL_IF_QUIESCING;
    try {
        MQQueue queue = _queueManager.accessQueue(outputQName, openOptions,
                null, // default q manager
                null, // no dynamic q name
                null); // no alternate user id

        DataInputStream input = new DataInputStream(System.in);

        System.out
                .println("MQWrite v1.0 connected and ready for input, terminate with ^Z\n\n");
        // Define a simple MQ message, and write some text in UTF format..
        MQMessage sendmsg = new MQMessage();
        sendmsg.format = MQC.MQFMT_STRING;
        sendmsg.feedback = MQC.MQFB_NONE;
        sendmsg.messageType = MQC.MQMT_DATAGRAM;
        sendmsg.replyToQueueName = "QM_LOCAL_END";
        sendmsg.replyToQueueManagerName = qManager;

        MQPutMessageOptions pmo = new MQPutMessageOptions(); // accept the
        String line = null; // defaults,

        System.out.print("Enter your Message: ");
        line = sc.nextLine();
        sendmsg.clearMessage();
        sendmsg.messageId = MQC.MQMI_NONE;
        sendmsg.correlationId = MQC.MQCI_NONE;
        sendmsg.writeString(line);
        // put the message on the queue
        queue.put(sendmsg, pmo);
        System.out.println("Message inserted: " + line);
        queue.close();
        _queueManager.disconnect();

        // same
        // as MQPMO_DEFAULT constant

    }

    catch (com.ibm.mq.MQException mqex) {
        System.out.println(mqex);
    } catch (java.io.IOException ioex) {
        System.out.println("An MQ IO error occurred : " + ioex);

    }
}

private void While(boolean b) {
    // TODO Auto-generated method stub

}

}

答案 2 :(得分:0)

姆。该代码看起来很熟悉 - 哦,等等,你下载了我的MQWrite示例代码。

首先,您应该远离使用MQEnvironment类。它专为基本的单线程应用程序而设计。您应该将信息放在HashTable中并将其传递给MQQueueManager类。

其次,添加日志记录是一项基本的Java编程工作。您可以使用内置记录器或使用第三方类。我使用Log4J很多年了。

因此,这里是MQWrite2 Java / MQ示例代码,用于在HashTable中设置连接信息,并使用Log4J作为记录器。

import java.io.IOException;
import java.util.Hashtable;

import org.apache.log4j.Logger;

import com.ibm.mq.MQException;
import com.ibm.mq.MQMessage;
import com.ibm.mq.MQPutMessageOptions;
import com.ibm.mq.MQQueue;
import com.ibm.mq.MQQueueManager;
import com.ibm.mq.constants.CMQC;

/**
 * Program Name
 *  MQWrite2
 *
 * Description
 *  This java class will connect to a queue manager and
 *  and write a message to a queue.
*
 * Sample Command Line Parameters
 *  -h 127.0.0.1 -p 1414 -c MY.TEST.EXIT -m MQA1 -q TEST.Q1
 *
 * @author Roger Lacroix, Capitalware Inc.
 */
public class MQWrite2
{
   private Logger logger = Logger.getLogger(MQWrite2.class.getName());
   private Hashtable<String, String> params = null;
   private Hashtable<String, Object> mqht = null;
   private String qMgrName;
   private String outputQName;

   /**
    * The constructor
    */
   public MQWrite2()
   {
      super();
      logger.info("MQWrite2 is now starting.");
   }

   /**
    * Make sure the required parameters are present.
    * @return true/false
    */
   private boolean allParamsPresent()
   {
      boolean b = params.containsKey("-h") && params.containsKey("-p") &&
                  params.containsKey("-c") && params.containsKey("-m") &&
                  params.containsKey("-q");
      if (b)
      {
         try
         {
            Integer.parseInt((String) params.get("-p"));
         }
         catch (NumberFormatException e)
         {
            b = false;
         }
      }

      return b;
   }

   /**
    * Extract the command-line parameters and initialize the MQ variables.
    * @param args
    * @throws IllegalArgumentException
    */
   private void init(String[] args) throws IllegalArgumentException
   {
      params = new Hashtable<String, String>();
      if (args.length > 0 && (args.length % 2) == 0)
      {
         for (int i = 0; i < args.length; i += 2)
         {
            params.put(args[i], args[i + 1]);
         }
      }
      else
      {
         throw new IllegalArgumentException();
      }

      if (allParamsPresent())
      {
         qMgrName = (String) params.get("-m");
         outputQName = (String) params.get("-q");

         mqht = new Hashtable<String, Object>();

         mqht.put(CMQC.CHANNEL_PROPERTY, params.get("-c"));
         mqht.put(CMQC.HOST_NAME_PROPERTY, params.get("-h"));

         try
         {
            mqht.put(CMQC.PORT_PROPERTY, new Integer(params.get("-p")));
         }
         catch (NumberFormatException e)
         {
            mqht.put(CMQC.PORT_PROPERTY, new Integer(1414));
         }

         // I don't want to see MQ exceptions at the console.
         MQException.log = null;
      }
      else
      {
         throw new IllegalArgumentException();
      }
   }

   /**
    * Connect, open queue, write a message, close queue and disconnect.
    *
    */
   private void testReceive()
   {
      int openOptions = CMQC.MQOO_OUTPUT + CMQC.MQOO_FAIL_IF_QUIESCING;
      MQPutMessageOptions pmo = new MQPutMessageOptions();
      MQQueueManager _qMgr = null;
      MQQueue queue = null;
      MQMessage sendMsg = null;
      String line = "This is a test message.";

      try
      {
         _qMgr = new MQQueueManager(qMgrName, mqht);
         queue = _qMgr.accessQueue(outputQName, openOptions);

         sendMsg = new MQMessage();
         sendMsg.messageId = CMQC.MQMI_NONE;
         sendMsg.correlationId = CMQC.MQCI_NONE;
         sendMsg.writeString(line);
         // put the message on the queue
         queue.put(sendMsg, pmo);
         logger.info("MQWrite2 Message inserted: " + line);
      }
      catch (MQException mqex)
      {
         logger.error("MQWrite2 MQException CC=" +mqex.completionCode + " : RC=" + mqex.reasonCode);
      }
      catch (IOException e)
      {
         logger.error("MQWrite2 IOException " + e.getLocalizedMessage());
      }
      finally
      {
         try
         {
            if (queue != null)
               queue.close();
         }
         catch (MQException mqex2)
         {
            logger.error("MQWrite2 MQException CC=" +mqex2.completionCode + " : RC=" + mqex2.reasonCode);
         }
         finally
         {
            try
            {
               if (_qMgr != null)
                  _qMgr.disconnect();
            }
            catch (MQException mqex3)
            {
               logger.error("MQWrite2 MQException CC=" +mqex3.completionCode + " : RC=" + mqex3.reasonCode);
            }
         }
      }

      logger.info("MQWrite2 is now ending.");
   }

   /**
    * main line
    * @param args
    */
   public static void main(String[] args)
   {
      MQWrite2 write = new MQWrite2();

      try
      {
         write.init(args);
         write.testReceive();
      }
      catch (IllegalArgumentException e)
      {
         System.out.println("Usage: java MQWrite2 -h host -p port -c channel -m QueueManagerName -q QueueName");
         System.exit(1);
      }

      System.exit(0);
   }
}

以下是与代码一起使用的'log4j.properties'文件:

#
# stdout
#
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%m%n
#
# MQWrite
#
log4j.category.MQWrite2=DEBUG, mqwrite, stdout
#log4j.category.MQWrite2=INFO, mqwrite, stdout
# "mqwrite" appender writes to a file
log4j.appender.mqwrite=org.apache.log4j.RollingFileAppender
log4j.appender.mqwrite.File=log/MQWrite.log
log4j.appender.mqwrite.MaxFileSize=1000KB
log4j.appender.mqwrite.MaxBackupIndex=9
log4j.appender.mqwrite.layout=org.apache.log4j.PatternLayout
log4j.appender.mqwrite.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %p - %m%n
#log4j.appender.mqwrite.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss.SSS} [%t] %p (%F:%M:%L) - %m%n

确保在运行代码的目录下创建一个“log”目录,否则会抛出如下错误:

log4j:ERROR setFile(null,true) call failed.
java.io.FileNotFoundException: log\MQWrite.log (The system cannot find the path specified)