net.NET_INFO.java Source code

Java tutorial

Introduction

Here is the source code for net.NET_INFO.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 net;

import java.io.IOException;
import static java.lang.System.out;
import java.net.InetAddress;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import org.apache.commons.net.ntp.NTPUDPClient;
import org.apache.commons.net.ntp.TimeInfo;
import org.apache.http.client.config.CookieSpecs;
import org.apache.http.client.config.RequestConfig;

/**
 * ?
 * @author Jasper
 */
public class NET_INFO {
    public static final String RAILWAY_HOST_1 = "http://railway.hinet.net/";
    public static final String RAILWAY_HOST_2 = "http://railway1.hinet.net/";

    public static final String SEARCH_PAGE_HOST = "http://twtraffic.tra.gov.tw";

    public static final RequestConfig DEFAULT_PARAMS = RequestConfig.custom().setConnectTimeout(10000)
            .setSocketTimeout(10000).setCookieSpec(CookieSpecs.STANDARD).build();

    private static final String TIME_SERVER = "tick.stdtime.gov.tw";
    private static boolean INIT_TIME_SERVER = false;
    private static long RETURN_TIME = 0;
    private static long START_TIME = 0;

    /**
     * ??
     */
    static {
        try {
            NTPUDPClient timeClient = new NTPUDPClient();
            InetAddress inetAddress = InetAddress.getByName(TIME_SERVER);
            TimeInfo timeInfo = timeClient.getTime(inetAddress);
            START_TIME = System.nanoTime();
            RETURN_TIME = timeInfo.getMessage().getTransmitTimeStamp().getTime();

            INIT_TIME_SERVER = true;
        } catch (IOException ex) {
            out.println("Initialization failed in case :" + ex.toString());
        }

        for (int i = 0; i < 100; i++)
            getCurrentTime();
    }

    /**
     * ?
     * @return the difference, measured in milliseconds, between the current time and midnight, January 1, 1970 UTC.
     */
    public static long getCurrentMilli() {
        return (System.nanoTime() - START_TIME) / 1000000 + RETURN_TIME;
    }

    /**
     * ? LocalDateTime
     * @return the current date-time using the system clock and default time-zone.
     */
    public static LocalDateTime getCurrentTime() {
        return LocalDateTime.ofInstant(Instant.ofEpochMilli(getCurrentMilli()), ZoneId.systemDefault());
    }

    public static boolean isINIT_TIME_SERVER() {
        return INIT_TIME_SERVER;
    }

}