简体   繁体   English

如何使用 JPOS ISO8583 消息格式通过传递字段名称来检索字段值

[英]How to retrieve field values by passing field name using JPOS ISO8583 message format

I want to retrieve field values by passing filed name.in order to achieve that i have implemented a method which loop through the ISOMsg object and then if it found a match to the passed filed name then it returns.my requirement is to read the.xml file once and have a static map using that then on the next time retrieve corresponding value by passing field name in order to achieve this is there a way to retrieve all field in config xml.我想通过传递文件名来检索字段值。为了实现这一点,我已经实现了一种循环遍历 ISOMsg object 的方法,然后如果它找到与传递的文件名匹配的内容,则返回。我的要求是阅读。 xml 文件一次,并有一个 static map 使用它,然后在下一次通过传递字段名称检索相应的值以实现此目的有没有办法检索配置 xml 中的所有字段。

protected static void getISO8583ValueByFieldName(ISOMsg isoMsg, String fieldName) {

for (int i = 1; i <= isoMsg.getMaxField(); i++) {

  if (isoMsg.hasField(i)) {

    if (isoMsg.getPackager().getFieldDescription(isoMsg, i).equalsIgnoreCase(fieldName)) {
      System.out.println(
          "    FOUND FIELD -" + i + " : " + isoMsg.getString(i) + " " + isoMsg.getPackager()
              .getFieldDescription(isoMsg, i));
       break;

    } 
  } 
} 

} }

You can also define an enum with the field names, mapped to field numbers. 您还可以使用映射到字段编号的字段名称定义枚举。 Please note the field names may vary from packager to packager, so your solution is kind of brittle, it's better to use an enum, or just constants. 请注意,字段名称因包装程序而异,因此您的解决方案有点脆弱,最好使用枚举或仅使用常量。

An enhancement to Seth's very helpful answer from above, to getFieldNameById instead of getFieldidByName :对上面 Seth 非常有用的答案的增强,以getFieldNameById而不是getFieldidByName

// package ... 

import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.jpos.iso.packager.GenericPackager;
import org.w3c.dom.Document;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

import com.imohsenb.ISO8583.exceptions.ISOException;

import lombok.extern.slf4j.Slf4j;

@Slf4j
public class ISO8583MapperFactory {

private static ISO8583MapperFactory instance = null;
private static HashMap<Integer, String> fieldMapper = null;

/**
 *
 * @throws IOException
 * @throws SAXException
 * @throws ParserConfigurationException
 */
private ISO8583MapperFactory() throws IOException, SAXException, ParserConfigurationException {
    fieldMapper = new HashMap<Integer, String>();
    mapFields();
}

/**
 *
 * @throws ParserConfigurationException
 * @throws IOException
 * @throws SAXException
 */
private void mapFields() throws ParserConfigurationException, IOException, SAXException {
    DocumentBuilder dBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder();

    dBuilder.setEntityResolver(new GenericPackager.GenericEntityResolver());
    // InputStream in = new
    // FileInputStream(ISO8583Constant.ISO8583_CONFIG_FILE_NAME);

    InputStream in = getClass().getClassLoader().getResourceAsStream(ISO8583Constant.ISO8583_CONFIG_FILE_NAME);
    Document doc = dBuilder.parse(in);

    // log.info("Root element :" + doc.getDocumentElement().getNodeName());

    if (doc.hasChildNodes()) {

        loadNodes(doc.getChildNodes(), fieldMapper);

    }
}

/**
 *
 * @return
 * @throws ParserConfigurationException
 * @throws SAXException
 * @throws IOException
 */
public static ISO8583MapperFactory getInstance()
        throws ParserConfigurationException, SAXException, IOException {
    if (instance == null) {
        instance = new ISO8583MapperFactory();
    }
    return instance;
}

/**
 *
 * @param fieldName
 * @return
 */
public String getFieldNameById(int fieldId) {
    return fieldMapper.get(Integer.valueOf(fieldId));
}

/**
 * Recursive method to read all the id and field name mappings
 * 
 * @param nodeList
 * @param fieldMapper
 */
protected void loadNodes(NodeList nodeList, HashMap<Integer, String> fieldMapper) {
    // log.info(" Invoked loadNodes(NodeList nodeList,HashMap<String,Integer>
    // fieldMapper)");

    for (int count = 0; count < nodeList.getLength(); count++) {

        Node tempNode = nodeList.item(count);

        // make sure it's element node.
        if (tempNode.getNodeType() == Node.ELEMENT_NODE) {

            // get node name and value
            // log.info("\nNode Name =" + tempNode.getNodeName() + " [OPEN]");
            // log.info("Node Value =" + tempNode.getTextContent());

            if (tempNode.hasAttributes()) {

                // get attributes names and values
                NamedNodeMap nodeMap = tempNode.getAttributes();

                // fieldMapper.put(nodeMap.getNamedItem(ISO8583Constant.FIELD_NAME).getNodeValue(),
                // Integer.valueOf(nodeMap.getNamedItem(ISO8583Constant.FIELD_ID).getNodeValue()));

                fieldMapper.put(Integer.valueOf(nodeMap.getNamedItem(ISO8583Constant.FIELD_ID).getNodeValue()),
                        nodeMap.getNamedItem(ISO8583Constant.FIELD_NAME).getNodeValue());

            }

            if (tempNode.hasChildNodes()) {

                // loop again if has child nodes
                loadNodes(tempNode.getChildNodes(), fieldMapper);

            }
            // log.info("Node Name =" + tempNode.getNodeName() + " [CLOSE]");

        }

    }

}

/**
 *
 * @return
 */
public static HashMap<Integer, String> getFieldMapper() {
    return fieldMapper;
}

/**
 *
 * @param fieldMapper
 */
public static void setFieldMapper(HashMap<Integer, String> fieldMapper) {
    ISO8583MapperFactory.fieldMapper = fieldMapper;
}

public static void main(String[] args) throws IOException, ISOException, InterruptedException {
    try {
        String a = ISO8583MapperFactory.getInstance().getFieldNameById(2);
        System.out.println(a);
    } catch (ParserConfigurationException e) {
        e.printStackTrace();
    } catch (SAXException e) {
        e.printStackTrace();
        }
    }
}

enum ISO8583Constant {
    ;
    static String ISO8583_CONFIG_FILE_NAME = "iso8583map.xml";
    static String FIELD_NAME = "name";
    static String FIELD_ID = "id";
}

Solution is to implement a own custom mapper.here is an memory implementation singleton class which reads all the configurations one time and then provide key id by name. 解决方案是实现自己的自定义映射器。这是一个内存实现单例类,该类一次读取所有配置,然后按名称提供密钥ID。

 /**
 * This is an memory implementation of singleton mapper class which contains ISO8583
 * field mappings as Key Value pairs [Field Name,Field Value]
 * in order
 *
 * Created on 12/16/2014.
 */
public class ISO8583MapperFactory {

  private static Logger logger= Logger.getLogger(ISO8583MapperFactory.class);

  private static ISO8583MapperFactory instance = null;
  private static HashMap<String,Integer> fieldMapper=null;



  /**
   *
   * @throws IOException
   * @throws SAXException
   * @throws ParserConfigurationException
   */
  private ISO8583MapperFactory() throws IOException, SAXException, ParserConfigurationException {
    fieldMapper =new HashMap<String, Integer>();
    mapFields();
  }

  /**
   *
   * @throws ParserConfigurationException
   * @throws IOException
   * @throws SAXException
   */
  private void mapFields() throws ParserConfigurationException, IOException, SAXException {
    DocumentBuilder dBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder();


    dBuilder.setEntityResolver(new GenericPackager.GenericEntityResolver());
    //InputStream in = new FileInputStream(ISO8583Constant.ISO8583_CONFIG_FILE_NAME);

    InputStream in =  getClass().getClassLoader().getResourceAsStream(ISO8583Constant.ISO8583_CONFIG_FILE_NAME);
    Document doc = dBuilder.parse(in);


    logger.info("Root element :" + doc.getDocumentElement().getNodeName());

    if (doc.hasChildNodes()) {

      loadNodes(doc.getChildNodes(), fieldMapper);

    }
  }

  /**
   *
   * @return
   * @throws ParserConfigurationException
   * @throws SAXException
   * @throws IOException
   */
  public static ISO8583MapperFactory getInstance()
      throws ParserConfigurationException, SAXException, IOException {
    if(instance==null){
      instance=new ISO8583MapperFactory();
    }
    return instance;
  }

  /**
   *
   * @param fieldName
   * @return
   */
  public Integer getFieldidByName(String fieldName){
    return fieldMapper.get(fieldName);
  }



  /**
   * Recursive method to read all the id and field name mappings
   * @param nodeList
   * @param fieldMapper
   */
  protected void loadNodes(NodeList nodeList,HashMap<String,Integer> fieldMapper) {
    logger.info(" Invoked loadNodes(NodeList nodeList,HashMap<String,Integer> fieldMapper)");

    for (int count = 0; count < nodeList.getLength(); count++) {

      Node tempNode = nodeList.item(count);

      // make sure it's element node.
      if (tempNode.getNodeType() == Node.ELEMENT_NODE) {

        // get node name and value
        logger.info("\nNode Name =" + tempNode.getNodeName() + " [OPEN]");
        logger.info("Node Value =" + tempNode.getTextContent());


        if (tempNode.hasAttributes()) {

          // get attributes names and values
          NamedNodeMap nodeMap = tempNode.getAttributes();

          fieldMapper.put(nodeMap.getNamedItem(ISO8583Constant.FIELD_NAME).getNodeValue(),Integer.valueOf( nodeMap.getNamedItem(ISO8583Constant.FIELD_ID).getNodeValue()));

        }

        if (tempNode.hasChildNodes()) {

          // loop again if has child nodes
          loadNodes(tempNode.getChildNodes(), fieldMapper);

        }
        logger.info("Node Name =" + tempNode.getNodeName() + " [CLOSE]");


      }

    }

  }

  /**
   *
   * @return
   */
  public static HashMap<String, Integer> getFieldMapper() {
    return fieldMapper;
  }

  /**
   *
   * @param fieldMapper
   */
  public static void setFieldMapper(HashMap<String, Integer> fieldMapper) {
    ISO8583MapperFactory.fieldMapper = fieldMapper;
  }


}

Example

public static void main(String[] args) throws IOException, ISOException, InterruptedException {
try {

  ISO8583MapperFactory.getInstance().getFieldidByName("NAME");

} catch (ParserConfigurationException e) {
  e.printStackTrace();
} catch (SAXException e) {
  e.printStackTrace();
}

} }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM