com.u2apple.rt.tool.DeviceValidator.java Source code

Java tutorial

Introduction

Here is the source code for com.u2apple.rt.tool.DeviceValidator.java

Source

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.u2apple.rt.tool;

import com.u2apple.rt.constant.Configuration;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import org.apache.commons.lang3.StringUtils;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Node;
import org.dom4j.io.SAXReader;
import org.slf4j.LoggerFactory;

/**
 *
 * @author Adam
 */
public class DeviceValidator {

    private static final org.slf4j.Logger logger = LoggerFactory.getLogger(DeviceValidator.class);
    private static List<String> productIds = new ArrayList<>();

    static {
        try {
            init();
        } catch (DocumentException ex) {
            logger.error("fail to init product id list.  {}", ex);
        }
    }

    private static void init() throws DocumentException {
        String path = Configuration.getProductsXml();
        if (StringUtils.isNotBlank(path)) {
            File file = new File(path);
            if (file.exists()) {
                Document document = parse(file);
                List<Node> productIdNodes = document.selectNodes("//Device/ProductId");
                for (Node node : productIdNodes) {
                    productIds.add(node.getText());
                }
            }
        }
    }

    public static void refresh() {
        productIds.clear();
        try {
            init();
        } catch (DocumentException ex) {
            logger.error("fail to init product id list. {}", ex);
        }
    }

    public static void addProductId(String productId) {
        productIds.add(productId);
    }

    private static Document parse(File file) throws DocumentException {
        SAXReader reader = new SAXReader();
        Document document = reader.read(file);
        return document;
    }

    public static boolean productIdExists(String productId) {
        return productIds.contains(productId);
    }

}