ru.apertum.qsystem.common.Uses.java Source code

Java tutorial

Introduction

Here is the source code for ru.apertum.qsystem.common.Uses.java

Source

/*
 *  Copyright (C) 2010 {Apertum}Projects. web: www.apertum.ru email: info@apertum.ru
 *
 *  This program is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
package ru.apertum.qsystem.common;

import ru.apertum.qsystem.common.exceptions.ServerException;
import java.awt.AlphaComposite;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.Graphics2D;
import java.awt.GraphicsDevice;
import java.awt.GraphicsEnvironment;
import java.awt.HeadlessException;
import java.awt.Image;
import java.awt.Rectangle;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import java.io.DataInputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.MalformedURLException;
import java.net.ServerSocket;
import java.net.SocketException;
import java.net.URL;
import java.net.URLClassLoader;
import java.net.UnknownHostException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JDesktopPane;
import javax.swing.JDialog;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JLayeredPane;
import javax.swing.SwingUtilities;
import javax.swing.Timer;
import javax.swing.filechooser.FileNameExtensionFilter;
import org.dom4j.Element;
import org.jdesktop.application.Application;
import org.jdesktop.application.ResourceMap;
import ru.apertum.qsystem.QSystem;
import ru.apertum.qsystem.client.Locales;
import ru.apertum.qsystem.client.forms.FClient;
import ru.apertum.qsystem.client.forms.FServicePriority;
import ru.apertum.qsystem.server.ServerProps;

/**
 * @author Evgeniy Egorov ? ??? ?  ? ?
 *
 */
public final class Uses {

    // ?  ""
    public static final int PRIORITY_LOW = 0;
    public static final int PRIORITY_NORMAL = 1;
    public static final int PRIORITY_HI = 2;
    public static final int PRIORITY_VIP = 3;
    public static final int[] PRIORITYS = { PRIORITY_LOW, PRIORITY_NORMAL, PRIORITY_HI, PRIORITY_VIP };
    private static final LinkedHashMap<Integer, String> PRIORITYS_WORD = new LinkedHashMap<>();
    public static final String PROPERTIES_FILE = "config/qsystem.properties";

    public static LinkedHashMap<Integer, String> get_PRIORITYS_WORD() {
        PRIORITYS_WORD.put(PRIORITY_LOW, FServicePriority.getLocaleMessage("client.priority.low"));
        PRIORITYS_WORD.put(PRIORITY_NORMAL, FServicePriority.getLocaleMessage("client.priority.standard"));
        PRIORITYS_WORD.put(PRIORITY_HI, FServicePriority.getLocaleMessage("client.priority.hi"));
        PRIORITYS_WORD.put(PRIORITY_VIP, FServicePriority.getLocaleMessage("client.priority.vip"));
        return PRIORITYS_WORD;
    }

    // ?   ? ? 
    // public static final int SERVICE_EXCLUDE = -1;
    public static final int SERVICE_REMAINS = 0;
    public static final int SERVICE_NORMAL = 1;
    public static final int SERVICE_VIP = 2;
    //public static final int[] SERVICE_PRIORITYS = {SERVICE_EXCLUDE, SERVICE_REMAINS, SERVICE_NORMAL, SERVICE_VIP};
    public static final LinkedHashMap<Integer, String> COEFF_WORD = new LinkedHashMap<>();

    public static LinkedHashMap<Integer, String> get_COEFF_WORD() {
        COEFF_WORD.put(SERVICE_REMAINS, FServicePriority.getLocaleMessage("service.priority.low"));
        COEFF_WORD.put(SERVICE_NORMAL, FServicePriority.getLocaleMessage("service.priority.basic"));
        int n = 0;
        if (QConfig.cfg().isAdminApp()) {
            n = ServerProps.getInstance().getProps().getExtPriorNumber();
        }
        if (QConfig.cfg().isClient()) {
            n = FClient.extPriorClient;
        }
        for (int i = 2; i <= n + 1; i++) {
            COEFF_WORD.put(i, Integer.toString(i));
        }
        COEFF_WORD.put(SERVICE_VIP + n, FServicePriority.getLocaleMessage("service.priority.vip"));

        return COEFF_WORD;
    }

    // ??      XML  ??
    public static final String TAG_REP_STATISTIC = "?";
    public static final String TAG_REP_PARAM_COUNT = "";
    public static final String TAG_REP_PARAM_AVG = "";
    public static final String TAG_REP_RECORD = "?";
    public static final String TAG_REP_SERVICE_WORKED = "??";
    public static final String TAG_REP_SERVICE_WAIT = "?";
    public static final String TAG_REP_SERVICE_AVG_WORK = "???";
    public static final String TAG_REP_SERVICE_AVG_WAIT = "??";
    public static final String TAG_REP_SERVICE_KILLED = "?";
    public static final String TAG_REP_USER_WORKED = "?";
    public static final String TAG_REP_USER_AVG_WORK = "??";
    public static final String TAG_REP_USER_KILLED = "";
    public static final String TAG_REP_WORKED = "?";
    public static final String TAG_REP_AVG_TIME_WORK = "??";
    public static final String TAG_REP_KILLED = "";
    //     ? 
    public static final String TAG_PROP_SERVICES = "?";
    public static final String TAG_PROP_SERVICE = "?";
    public static final String TAG_PROP_NAME = "?";
    public static final String TAG_PROP_DESCRIPTION = "?";
    public static final String TAG_PROP_PREFIX = "?";
    public static final String TAG_PROP_ADVANCE_LIMIT = "";
    public static final String TAG_PROP_ADVANCE_PERIOD_LIMIT = "??";
    public static final String TAG_PROP_USERS = "";
    public static final String TAG_PROP_USER = "";
    public static final String TAG_PROP_PASSWORD = "";
    public static final String TAG_PROP_OWN_SERVS = "?";
    public static final String TAG_PROP_OWN_SRV = "??";
    public static final String TAG_PROP_KOEF = "???";
    public static final String TAG_PROP_CONNECTION = "";
    public static final String TAG_PROP_SERV_PORT = "";
    public static final String TAG_PROP_WEB_SERV_PORT = "";
    public static final String TAG_PROP_CLIENT_PORT = "";
    public static final String TAG_PROP_SERV_ADDRESS = "??";
    public static final String TAG_PROP_CLIENT_ADDRESS = "??";
    public static final String TAG_PROP_STATUS = "?";
    public static final String TAG_PROP_START_TIME = "??";
    public static final String TAG_PROP_FINISH_TIME = "??";
    public static final String TAG_PROP_VERSION = "??";
    public static final String TAG_PROP_INPUT_REQUIRED = "?";
    public static final String TAG_PROP_INPUT_CAPTION = "";
    public static final String TAG_PROP_RESULT_REQUIRED = "";
    //        
    public static final String TAG_BOARD_PROPS = "";
    public static final String TAG_BOARD_PROP = "";
    public static final String TAG_BOARD_NAME = "?";
    public static final String TAG_BOARD_VALUE = "";
    public static final String TAG_BOARD_TYPE = "";
    public static final String TAG_BOARD_READ_ONLY = "ReadOnly";
    //   ?  
    public static final String TAG_BOARD_FRACTAL = "Fractal";
    public static final String TAG_BOARD_MONITOR = "?   ? ";
    public static final String TAG_BOARD_LINES_COUNT = "? ?  ";
    public static final String TAG_BOARD_COLS_COUNT = "? ?  ";
    public static final String TAG_BOARD_DELAY_VISIBLE = " ?   ";
    public static final String TAG_BOARD_FON_IMG = " ";
    public static final String TAG_BOARD_FONT_SIZE = " ";
    public static final String TAG_BOARD_FONT_COLOR = " ";
    public static final String TAG_BOARD_PANEL_SIZE = "";
    public static final String TAG_BOARD_RUNNING_TEXT = " ?";
    public static final String TAG_BOARD_VIDEO_FILE = "";
    public static final String TAG_BOARD_VISIBLE_PANEL = "visible";
    public static final String TAG_BOARD_SPEED_TEXT = "?  ?";
    public static final String TAG_BOARD_GRID_NEXT_COLS = "  ?";
    public static final String TAG_BOARD_GRID_NEXT_ROWS = "  ?";
    public static final String TAG_BOARD_SIMPLE_DATE = "?? ";
    public static final String TAG_BOARD_GRID_NEXT = " ?";
    public static final String TAG_BOARD_FON_COLOR = " ";
    public static final String TAG_BOARD_FONT_SIZE_CAPTION = "  ";
    public static final String TAG_BOARD_FONT_NAME = "Font name";
    public static final String TAG_BOARD_FONT_SIZE_LINE = "  ?";
    public static final String TAG_BOARD_FONT_COLOR_CAPTION = "  ";
    public static final String TAG_BOARD_FONT_COLOR_LEFT = "   ?";
    public static final String TAG_BOARD_FONT_COLOR_RIGHT = "   ?";
    public static final String TAG_BOARD_FONT_COLOR_LINE = " ? ? ";
    public static final String TAG_BOARD_LINE_BORDER = " ?";
    public static final String TAG_BOARD_LINE_DELIMITER = " ?";
    public static final String TAG_BOARD_LEFT_PIC = "Left column pic";
    public static final String TAG_BOARD_RIGHT_PIC = "Right column pic";
    public static final String TAG_BOARD_EXT_PIC = "Ext column pic";
    public static final String TAG_BOARD_LEFT_CAPTION = "  ?";
    public static final String TAG_BOARD_RIGHT_CAPTION = "  ?";
    public static final String TAG_BOARD_EXT_CAPTION = "  ?";
    public static final String TAG_BOARD_EXT_POSITION = "?  ?";
    public static final String TAG_BOARD_GRID_NEXT_CAPTION = "  ?";
    public static final String TAG_BOARD_GRID_NEXT_FRAME_BORDER = "  ?";
    public static final String TAG_BOARD_LINE_COLOR = "  ? ";
    public static final String TAG_BOARD_LINE_CAPTION = "?? ? ";
    public static final String TAG_BOARD_CALL_PANEL = " ";
    public static final String TAG_BOARD_CALL_PANEL_BACKGROUND = "  ";
    public static final String TAG_BOARD_CALL_PANEL_X = " -X";
    public static final String TAG_BOARD_CALL_PANEL_Y = " -Y";
    public static final String TAG_BOARD_CALL_PANEL_WIDTH = " -";
    public static final String TAG_BOARD_CALL_PANEL_HEIGHT = " -?";
    public static final String TAG_BOARD_CALL_PANEL_DELAY = " -?  ?";
    public static final String TAG_BOARD_CALL_PANEL_TEMPLATE = " -? html+###";
    // - ? 
    public static final String TAG_BOARD = "Board";
    public static final String TAG_BOARD_MAIN = "Main";
    public static final String TAG_BOARD_TOP = "Top";
    public static final String TAG_BOARD_BOTTOM = "Bottom";
    public static final String TAG_BOARD_BOTTOM_2 = "Bottom2";
    public static final String TAG_BOARD_LEFT = "Left";
    public static final String TAG_BOARD_RIGHT = "Right";
    // ??     
    public static final String BOARD_VALUE_PAUSE = "? ??? ?  ";
    public static final String BOARD_ADRESS_MAIN_BOARD = "??   ??";
    public static final int BOARD_TYPE_INT = 1;
    public static final int BOARD_TYPE_DOUBLE = 2;
    public static final int BOARD_TYPE_STR = 3;
    public static final int BOARD_TYPE_BOOL = 4;
    // ?? 
    public static final String TASK_FOR_ALL_SITE = "? ? ? ";
    public static final String TASK_STAND_IN = "?  ";
    public static final String TASK_STAND_COMPLEX = "?  ? ";
    public static final String TASK_ADVANCE_STAND_IN = "?   ";
    public static final String TASK_ADVANCE_CHECK_AND_STAND = "?  ?";
    public static final String TASK_REMOVE_ADVANCE_CUSTOMER = "  ?";
    public static final String TASK_REDIRECT_CUSTOMER = "?    ?";
    public static final String TASK_GET_SERVICES = "  ?";
    public static final String TASK_ABOUT_SERVICE = " ? ?";
    public static final String TASK_GET_SERVICE_CONSISANCY = "  ?";
    public static final String TASK_ABOUT_SERVICE_PERSON_LIMIT = " ? ? ? ? ";
    public static final String TASK_GET_SERVICE_PREINFO = "   ?";
    public static final String TASK_GET_INFO_PRINT = "  ? ";
    public static final String TASK_GET_USERS = "  ";
    public static final String TASK_GET_SELF = " ? ?";
    public static final String TASK_GET_SELF_SERVICES = " ??? ";
    public static final String TASK_GET_POSTPONED_POOL = " ???  ";
    public static final String TASK_GET_BAN_LIST = " ?? ";
    public static final String TASK_INVITE_POSTPONED = "    ";
    public static final String TASK_GET_SELF_SERVICES_CHECK = " ???  ? ";
    public static final String TASK_INVITE_NEXT_CUSTOMER = " ? ";
    public static final String TASK_KILL_NEXT_CUSTOMER = " ? ";
    public static final String TASK_CUSTOMER_TO_POSTPON = "   ";
    public static final String TASK_POSTPON_CHANGE_STATUS = " ?? ";
    public static final String TASK_START_CUSTOMER = "?  ? ";
    public static final String TASK_FINISH_CUSTOMER = "  ? ";
    public static final String TASK_I_AM_LIVE = " !";
    public static final String TASK_RESTART = "RESTART";
    public static final String TASK_RESTART_MAIN_TABLO = "?  ";
    public static final String TASK_REFRESH_POSTPONED_POOL = "NEW_POSTPONED_NOW";
    public static final String TASK_SERVER_STATE = " ??? ?";
    public static final String TASK_SET_SERVICE_FIRE = " ?  ?";
    public static final String TASK_DELETE_SERVICE_FIRE = " ?  ?"; // ?? , ?? ? ?  ?   
    public static final String TASK_GET_BOARD_CONFIG = "  ";
    public static final String TASK_SAVE_BOARD_CONFIG = "  ";
    public static final String TASK_GET_GRID_OF_WEEK = "   ";
    public static final String TASK_GET_GRID_OF_DAY = "   ";
    public static final String TASK_GET_INFO_TREE = "  ";
    public static final String TASK_GET_RESULTS_LIST = "  ??  ";
    public static final String TASK_GET_RESPONSE_LIST = " ?? ";
    public static final String TASK_SET_RESPONSE_ANSWER = "? ";
    public static final String REPORT_CURRENT_USERS = "current_users";
    public static final String REPORT_CURRENT_SERVICES = "current_services";
    public static final String TASK_GET_CLIENT_AUTHORIZATION = " ";
    public static final String TASK_SET_CUSTOMER_PRIORITY = " ";
    public static final String TASK_CHECK_CUSTOMER_NUMBER = " ";
    public static final String TASK_CHANGE_FLEX_PRIORITY = "  ";
    public static final String TASK_CHANGE_RUNNING_TEXT_ON_BOARD = "  ?  ";
    public static final String TASK_CHANGE_TEMP_AVAILABLE_SERVICE = "  ??";
    public static final String TASK_GET_STANDARDS = " ";
    public static final String TASK_SET_BUSSY = " ";
    public static final String TASK_GET_PROPERTIES = "?   ";
    public static final String TASK_SAVE_PROPERTIES = " ?   ";
    public static final String TASK_INIT_PROPERTIES = " ?   ";
    //  
    public static final String REPORT_FORMAT_HTML = "html";
    public static final String REPORT_FORMAT_RTF = "rtf";
    public static final String REPORT_FORMAT_PDF = "pdf";
    public static final String REPORT_FORMAT_XLSX = "xlsx";
    public static final String REPORT_FORMAT_CSV = "csv";
    //  ? ?? ? 
    public static final String ANCHOR_REPORT_LIST = "<tr><td><center>#REPORT_LIST_ANCHOR#</center></td></tr>";
    public static final String ANCHOR_DATA_FOR_REPORT = "#DATA_FOR_REPORT#";
    public static final String ANCHOR_ERROR_INPUT_DATA = "#ERROR_INPUT_DATA#";
    public static final String ANCHOR_USERS_FOR_REPORT = "#USERS_LIST_ANCHOR#";
    public static final String ANCHOR_PROJECT_NAME_FOR_REPORT = "#PROJECT_NAME_ANCHOR#";
    public static final String ANCHOR_COOCIES = "#COOCIES_ANCHOR#";
    // ? ?  ?
    public static final String WELCOME_LOCK = "#WELCOME_LOCK#";
    public static final String WELCOME_UNLOCK = "#WELCOME_UNLOCK#";
    public static final String WELCOME_OFF = "#WELCOME_OFF#";
    public static final String WELCOME_REINIT = "#WELCOME_REINIT#";
    public final static String[] RUSSIAN_MONAT = { "?", "?", "", "??",
            "?", "?", "?", "??", "??", "??",
            "???", "?" };
    public final static String[] UKRAINIAN_MONAT = { "?", "", "?", "?",
            "?", "?", "?", "?", "??", "?",
            "?", "?" };

    public final static String[] AZERBAIJAN_MONAT = { "Yanvar", "Fevral", "Mart", "Aprel", "May", "Iyun", "Iyul",
            "Avqust", "Sentyabr", "Oktyabr", "Noyabr", "Dekabr" };

    public static String getRusDate(Date date, String format) {
        return new SimpleDateFormat(format, Locales.getInstance().getRussSymbolDateFormat()).format(date);
    }

    public static String getUkrDate(Date date, String format) {
        return new SimpleDateFormat(format, Locales.getInstance().getUkrSymbolDateFormat()).format(date);
    }

    /**
     *  
     */
    public static final String DATE_FORMAT = "dd.MM.yyyy HH:mm:ss";
    /**
     *    
     */
    public static final String DATE_FORMAT_ONLY = "dd.MM.yyyy";
    /**
     *  .
     */
    public final static DateFormat FORMAT_HH_MM = new SimpleDateFormat("HH:mm");
    /**
     *  .
     */
    public final static DateFormat FORMAT_HH_MM_SS = new SimpleDateFormat("HH:mm:ss");
    /**
     *  .
     */
    public final static DateFormat FORMAT_DD_MM_YYYY = new SimpleDateFormat(DATE_FORMAT_ONLY);
    /**
     *  .
     */
    public final static DateFormat FORMAT_DD_MM_YYYY_TIME = new SimpleDateFormat(DATE_FORMAT);
    /**
     *  ./2009-01-26 16:10:41
     */
    public final static DateFormat FORMAT_FOR_REP = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    /**
     *  ./2009-01-26 16:10
     */
    public final static DateFormat FORMAT_FOR_TRANS = new SimpleDateFormat("yyyy-MM-dd HH:mm");
    /**
     * ?  ?  ?? ???? ? ??
     */
    public static final String TEMP_FOLDER = "temp";
    /**
     *   ?? ???? ? ??
     */
    public static final String TEMP_STATE_FILE = "temp.json";
    /**
     *   ??  ? ?
     */
    public static final String TEMP_COMPLEX_FILE = "complex.json";
    /**
     *   ??  ?? ? ??
     */
    public static final String TEMP_STATATISTIC_FILE = "temp_statistic.xml";
    /**
     *        ? " ?  ?"      .
     */
    public static final int DELAY_BACK_TO_ROOT = 10000;
    /**
     *    ?  ?
     */
    public static final int DELAY_CHECK_TO_LOCK = 55000;
    /**
     * ?    ? -   ,  ? ? ?  ??   
     */
    public static final int LOCK_INT = 1000000000;
    /**
     * ?    ? -   ,  ? ? ?  ?? ? ??
     */
    public static final int LOCK_FREE_INT = 1000000011;
    /**
     * ?    ? -   ,  ? ? ?  ?? ?  ?    
     * ?
     */
    public static final int LOCK_PER_DAY_INT = 1000000022;
    /**
     * ?  ?
     */
    public static final String HOW_DO_YOU_DO = "do you live?";

    /**
     *   ? public static ArrayList elements(Element root, String tagName).
     *
     * @param list ?? ?
     * @param el  ? 
     * @param tagName ? ? 
     */
    private static void getList(ArrayList list, Element el, String tagName) {
        list.addAll(el.elements(tagName));
        el.elements().stream().forEach((obj) -> {
            getList(list, (Element) obj, tagName);
        });
    }

    /**
     *  ?? ? ?    
     *
     * @param root  ? 
     * @param tagName ? ? 
     * @return ?? ?
     */
    public static ArrayList<Element> elements(Element root, String tagName) {
        ArrayList<Element> list = new ArrayList<>();
        //list.addAll(root.elements(tagName));
        getList(list, root, tagName);
        return list;
    }

    /**
     *   ? public static ArrayList elementsByAttr(...).
     *
     * @param list ?? ?
     * @param el  ? 
     * @param attrName ? ? 
     * @param attrValue  
     */
    private static void getList(ArrayList list, Element el, String attrName, String attrValue) {
        if (attrValue.equals(el.attributeValue(attrName))) {
            list.add(el);
        }
        el.elements().stream().forEach((obj) -> {
            getList(list, (Element) obj, attrName, attrValue);
        });
    }

    /**
     *  ?? ? ?     
     *
     * @param root  ? 
     * @param attrName ? ? 
     * @param attrValue  
     * @return ?? ?
     */
    public static ArrayList<Element> elementsByAttr(Element root, String attrName, String attrValue) {
        ArrayList<Element> list = new ArrayList<>();
        //list.addAll(root.elements(tagName));
        getList(list, root, attrName, attrValue);
        return list;
    }

    /**
     *   ? public static ArrayList elementsByAttr(...).
     *
     * @param list ?? ?
     * @param el  ? 
     * @param text  CData
     */
    private static void getListCData(ArrayList list, Element el, String text) {
        if (text.equals(el.getTextTrim())) {
            list.add(el);
        }
        el.elements().stream().forEach((obj) -> {
            getListCData(list, (Element) obj, text);
        });
    }

    /**
     *  ?? ? ?   CData  
     *
     * @param root  ? 
     * @param text ?  CData  xml-
     * @return ?? ?
     */
    public static ArrayList<Element> elementsByCData(Element root, String text) {
        ArrayList<Element> list = new ArrayList<>();
        //list.addAll(root.elements(tagName));
        getListCData(list, root, text);
        return list;
    }

    /**
     *  ?  ?.
     *
     * @param adress ?  "125.256.214.854"  "rambler.ru"
     * @return InetAddress
     */
    public static InetAddress getInetAddress(String adress) {
        InetAddress adr = null;
        try {
            adr = InetAddress.getByName(adress);
        } catch (UnknownHostException ex) {
            throw new ServerException(
                    " ? ?  ? \'" + adress + "\". " + ex);
        }
        return adr;
    }

    /**
     * ? ?  UDP
     *
     * @param message ? ? ??
     * @param address ? ?. ? ? "255.255.255.255",  ??  .
     * @param port  ?
     */
    public static void sendUDPMessage(String message, InetAddress address, int port) {
        QLog.l().logger().trace(" UDP ? \"" + message + "\"  ? \""
                + address.getHostAddress() + "\"   \"" + port + "\"");
        final DatagramSocket socket;
        final byte mess_b[] = message.getBytes();
        final DatagramPacket packet = new DatagramPacket(mess_b, mess_b.length, address, port);
        try {
            socket = new DatagramSocket();
        } catch (SocketException ex) {
            throw new ServerException(" ? ? UDP." + ex.getMessage());
        }
        try {
            socket.send(packet);
        } catch (IOException io) {
            throw new ServerException(
                    "  ??  UDP. " + io.getMessage());
        } finally {
            socket.close();
        }
    }

    /**
     * ? ?  UDP 
     *
     * @param message ? ? ??
     * @param port  ?
     */
    public static void sendUDPBroadcast(String message, int port) {
        try {
            sendUDPMessage(message, InetAddress.getByName("255.255.255.255"), port);
        } catch (UnknownHostException ex) {
            throw new ServerException(" ? ? " + ex.getMessage());
        }
    }

    /**
     *  ??  jar-
     *
     * @param o - ??,  ? ? ??
     * @param resourceName   ??  jar-
     * @return ?? , ? ??
     * @throws IOException
     */
    public static byte[] readResource(Object o, String resourceName) throws IOException {
        //  ??  "/ru/apertum/qsystem/reports/web/name.jpg"
        final InputStream inStream = o.getClass().getResourceAsStream(resourceName);
        return readInputStream(inStream);
    }

    /**
     *      ??. ?  ?,   null.
     *
     * @param o  ?  ??  jar,  ? ??   ? ? .
     * @param resourceName   ??   .   ?.
     * @param defaultResourceName ?   ??  ??,  ?? ? ??
     * @return
     */
    public static Image loadImage(Object o, String resourceName, String defaultResourceName) {
        if ("".equals(resourceName)) {
            return null;
        } else {
            Image img = HASH_IMG.get(resourceName);
            if (img != null) {
                return img;
            }

            final DataInputStream inStream;
            File f = new File(resourceName);
            if (f.exists()) {
                img = new ImageIcon(resourceName).getImage();
                HASH_IMG.put(resourceName, img);
                return img;
            } else {
                final InputStream is = o.getClass().getResourceAsStream(resourceName);
                if (is == null) {
                    if (defaultResourceName == null || defaultResourceName.isEmpty()) {
                        return new BufferedImage(2000, 2000, BufferedImage.TYPE_INT_RGB);
                    }
                    if (o.getClass().getResourceAsStream(defaultResourceName) == null) {
                        QLog.l().logger().error(
                                "  ??  ?  ,  ??, ? ? ? \""
                                        + defaultResourceName + "\"");
                        return new BufferedImage(2000, 2000, BufferedImage.TYPE_INT_RGB);
                    }
                    inStream = new DataInputStream(o.getClass().getResourceAsStream(defaultResourceName));
                } else {
                    inStream = new DataInputStream(is);
                }

            }
            byte[] b = null;
            try {
                b = new byte[inStream.available()];
                inStream.readFully(b);
                inStream.close();
            } catch (IOException ex) {
                QLog.l().logger().error(ex);
            }
            img = new ImageIcon(b).getImage();
            HASH_IMG.put(resourceName, img);
            return img;
        }
    }

    private static final HashMap<String, Image> HASH_IMG = new HashMap<>();

    /**
     * ? ?   .  ? ?  ?? ? ?. readSocketInputStream(InputStream stream)
     *
     * @param stream   
     * @return byte[] 
     * @throws java.io.IOException
     */
    public static byte[] readInputStream(InputStream stream) throws IOException {
        final byte[] result;
        final DataInputStream dis = new DataInputStream(stream);
        result = new byte[stream.available()];
        dis.readFully(result);
        return result;
    }

    /**
     *   ?  ? ?.
     *
     * @param value
     * @param scale
     * @return    ?.
     */
    public static double roundAs(double value, int scale) {
        return new BigDecimal(value).setScale(scale, RoundingMode.UP).doubleValue();
    }

    /**
     *    .
     *
     * @param parent ?    .
     * @param title   .
     * @param description ? ,  " XML(*.xml)".
     * @param extension   ? ,  "xml".
     * @return  ?   null ?  .
     */
    public static String getFileName(Component parent, String title, String description, String extension) {
        final JFileChooser fileChooser = new JFileChooser();
        fileChooser.setLocale(Locales.getInstance().getLangCurrent());
        fileChooser.resetChoosableFileFilters();
        final FileNameExtensionFilter filter = new FileNameExtensionFilter(description, extension);
        fileChooser.setFileFilter(filter);
        fileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
        fileChooser.setDialogTitle(title);

        if (fileChooser.showOpenDialog(parent) == JFileChooser.APPROVE_OPTION) {
            if (fileChooser.getSelectedFile().exists()) {
                return fileChooser.getSelectedFile().getAbsolutePath();
            }
        }
        return null;
    }

    /**
     *     ?
     *
     * @param component ?    
     */
    public static void setLocation(JDialog component) {
        component.setLocationRelativeTo(null);
        //component.setLocation((Math.round(firstMonitor.getDefaultConfiguration().getBounds().width - component.getWidth()) / 2),
        //        (Math.round(firstMonitor.getDefaultConfiguration().getBounds().height - component.getHeight()) / 2));
    }

    public static void setLocation(JFrame component) {
        component.setLocationRelativeTo(null);
        //component.setLocation((Math.round(firstMonitor.getDefaultConfiguration().getBounds().width - component.getWidth()) / 2),
        //        (Math.round(firstMonitor.getDefaultConfiguration().getBounds().height - component.getHeight()) / 2));
    }

    /**
     * ??   ? ?
     *
     * @param component ?    ??
     */
    public static void setFullSize(Component component) {
        component.setBounds(0, 0, firstMonitor.getDefaultConfiguration().getBounds().width,
                firstMonitor.getDefaultConfiguration().getBounds().height);
    }

    /**
     * mointors
     */
    public static final HashMap<Integer, Rectangle> DISPLAYS = new HashMap<>();
    public static GraphicsDevice firstMonitor = null;

    static {
        /**
         * ?
         */
        GraphicsDevice[] screenDevices = null;
        try {
            screenDevices = GraphicsEnvironment.getLocalGraphicsEnvironment().getScreenDevices();
        } catch (HeadlessException th) {
            System.out.println("No screen Devices");
        }
        if (screenDevices != null && screenDevices.length > 0) {
            firstMonitor = screenDevices[0];
            int i = 1;
            for (GraphicsDevice graphicsDevice : screenDevices) {
                System.out.println("monitor " + i + "; graphicsDevice = " + graphicsDevice.getIDstring() + " "
                        + graphicsDevice.toString() + "; height, width = "
                        + graphicsDevice.getDefaultConfiguration().getBounds().height + "x"
                        + graphicsDevice.getDefaultConfiguration().getBounds().width + "; Coloreness = "
                        + graphicsDevice.getDisplayMode().getBitDepth() + "; RefreshRate = "
                        + graphicsDevice.getDisplayMode().getRefreshRate() + "; Origin(x, y) = "
                        + graphicsDevice.getDefaultConfiguration().getBounds().x + "-"
                        + graphicsDevice.getDefaultConfiguration().getBounds().y);
                DISPLAYS.put(i++, graphicsDevice.getDefaultConfiguration().getBounds());
                if (graphicsDevice.getDefaultConfiguration().getBounds().x == 0
                        && graphicsDevice.getDefaultConfiguration().getBounds().y == 0) {
                    firstMonitor = graphicsDevice;
                }
            }
        }
        COEFF_WORD.put(SERVICE_REMAINS, FServicePriority.getLocaleMessage("service.priority.low"));
        COEFF_WORD.put(SERVICE_NORMAL, FServicePriority.getLocaleMessage("service.priority.basic"));
        COEFF_WORD.put(SERVICE_VIP, FServicePriority.getLocaleMessage("service.priority.vip"));
    }

    /**
     *  ? jar    ??
     *
     * @param folder  ?  .
     */
    public static void loadPlugins(String folder) {
        //     plugins
        QLog.l().logger().info("    plugins.");
        final File[] list = new File(folder)
                .listFiles((File dir, String name) -> name.toLowerCase().endsWith(".jar"));
        if (list != null && list.length != 0) {
            final URLClassLoader sysloader = (URLClassLoader) ClassLoader.getSystemClassLoader();
            final Class sysclass = URLClassLoader.class;
            final Class[] parameters = new Class[] { URL.class };
            for (File file : list) {
                QLog.l().logger().debug(" " + file.getName());
                try {
                    final Method method = sysclass.getDeclaredMethod("addURL", parameters);
                    method.setAccessible(true);
                    method.invoke(sysloader, new Object[] { file.toURI().toURL() });
                } catch (NoSuchMethodException | SecurityException | IllegalAccessException
                        | IllegalArgumentException | InvocationTargetException | MalformedURLException ex) {
                    QLog.l().logger().error(" " + file.getName() + " ? . " + ex);
                }
            }
        }

    }

    /**
     * ?? ?
     */
    private static class SplashScreen extends JFrame {

        final BorderLayout borderLayout1 = new BorderLayout();
        final JLabel imageLabel = new JLabel();
        final JLabel imageLabel2 = new JLabel();
        final JLayeredPane lp = new JDesktopPane();
        final ImageIcon imageIcon;
        final ImageIcon imageIcon2;

        public SplashScreen() {
            imageIcon = new ImageIcon(
                    SplashScreen.class.getResource("/ru/apertum/qsystem/client/forms/resources/fon_login_bl.jpg"));
            imageIcon2 = new ImageIcon(
                    SplashScreen.class.getResource("/ru/apertum/qsystem/client/forms/resources/loading.gif"));
            init();
        }

        private void init() {
            try {
                setIconImage(ImageIO.read(
                        SplashScreen.class.getResource("/ru/apertum/qsystem/client/forms/resources/client.png")));
            } catch (IOException ex) {
                System.err.println(ex);
            }
            setTitle("? QSystem");
            setSize(imageIcon.getIconWidth(), imageIcon.getIconHeight());
            imageLabel.setIcon(imageIcon);
            imageLabel2.setIcon(imageIcon2);
            lp.setBounds(0, 0, 400, 400);
            lp.setOpaque(false);
            add(lp);
            this.getContentPane().add(imageLabel, BorderLayout.CENTER);
            imageLabel2.setBounds(175, 165, 300, 30);
            lp.add(imageLabel2, null);
            timer.start();
        }

        final Timer timer = new Timer(100, new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                if (sh == false) {
                    stopTimer();
                    setVisible(false);
                }
            }

            private void stopTimer() {
                timer.stop();
            }
        });
    }

    private static class SplashRun implements Runnable {

        @Override
        public void run() {
            final SplashScreen screen = new SplashScreen();
            //screen.setSize(480, 360);
            screen.setUndecorated(true);
            screen.setResizable(false);
            setLocation(screen);
            screen.pack();
            screen.setVisible(true);
            screen.setAlwaysOnTop(true);
        }
    }

    private static boolean sh = false;

    /**
     *    ??-? ?  ?  
     */
    public static void startSplashClient() {
        if (!QConfig.cfg().isTerminal()) {
            try {
                stopStartSecond = new ServerSocket(21210);
            } catch (Exception ex) {
                System.err.println(".QSystem: Application alredy started!!!");
                System.exit(15685);
            }
        }
        startSplash();
    }

    static ServerSocket stopStartSecond;

    /**
     *    ??-? ?  ?  
     */
    public static void startSplash() {
        sh = true;
        SwingUtilities.invokeLater(new SplashRun());
    }

    /**
     *    ??-?   ?  
     */
    public static void showSplash() {
        sh = true;
        SwingUtilities.invokeLater(new SplashRun());
    }

    /**
     *  ??-?
     */
    public static void closeSplash() {
        sh = false;
    }

    static void renderSplashFrame(Graphics2D g, int frame) {
        final String[] comps = { "foo", "bar", "baz" };
        g.setComposite(AlphaComposite.Clear);
        g.fillRect(120, 140, 200, 40);
        g.setPaintMode();
        g.setColor(Color.BLACK);
        g.drawString("Loading " + comps[(frame / 5) % 3] + "...", 120, 150);
    }

    public static String prepareAbsolutPathForImg(String html) {
        File f = new File(html.startsWith("file:///") ? html.substring(8) : html);
        if (f.exists()) {
            return f.toURI().toString().replace("file:/", "file:///");
        }
        final Pattern pattern = Pattern.compile("<\\s*img\\s*src\\s*=\\s*['\"].*?['\"]\\s*>");//<img src='file:///E:\WORK\apertum-qsystem\config\board\q.jpg'>
        final Matcher matcher = pattern.matcher(html);
        String res = html;
        while (matcher.find()) {
            String img = matcher.group();
            final String tci = img.contains("'") ? "'" : "\"";
            img = img.substring(img.indexOf(tci) + 1, img.indexOf(tci, img.indexOf(tci) + 1));

            String ff = img;
            if (img.startsWith("file:///")) {
                ff = img.substring(8);
            }
            f = new File(ff);
            if (f.isFile()) {
                res = res.replace(tci + img + tci, tci + f.toURI().toString().replace("file:/", "file:///") + tci);
            } else {
                QLog.l().logger().error("?   \"" + img + "\" ? HTML.");
            }
        }
        return res;
    }

    public static void main(String[] args) {
        String result = "<html dir=\"ltr\"><head></head><body contenteditable=\"true\"><b><p align=\"center\"><span style=\"font-size:20.0pt;color:blue\">Some service</span></p></b></body></html>";
        System.out.println(result);
        result = result.replaceAll("<.?(html).*?>", "");
        System.out.println(result);
        result = result.replaceAll("(<.?(head).*?>).*?(<.?(head).*?>)", "");
        System.out.println(result);
        result = result.replaceAll("<.?(body).*?>", "");
        System.out.println(result);

        result = result.replaceAll("<p\\S*?", "\n<p ");
        System.out.println(result);

        System.out.println("");
        System.out.println("");

        System.out.println(prepareAbsolutPathForImg("<img src='file:///config/board/q.png'>"));
        System.out.println(prepareAbsolutPathForImg("<img src=\"file:///config/board/q.png\">"));
        System.out.println(prepareAbsolutPathForImg("config/board/q.png"));
        System.out.println(prepareAbsolutPathForImg("file:///www/timed.html"));
        System.out.println(prepareAbsolutPathForImg("www/timed.html"));
    }

    private static ResourceMap localeMap = null;

    public static String getLocaleMessage(String key) {
        if (localeMap == null) {
            localeMap = Application.getInstance(QSystem.class).getContext().getResourceMap(Uses.class);
        }
        return localeMap.getString(key);
    }
}