⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 util.java

📁 jrobin,使用纯java实现的RRD数据库,使用RRD数据库来统计数据.
💻 JAVA
📖 第 1 页 / 共 2 页
字号:
/* ============================================================
 * JRobin : Pure java implementation of RRDTool's functionality
 * ============================================================
 *
 * Project Info:  http://www.jrobin.org
 * Project Lead:  Sasa Markovic (saxon@jrobin.org);
 *
 * (C) Copyright 2003-2005, by Sasa Markovic.
 *
 * Developers:    Sasa Markovic (saxon@jrobin.org)
 *
 *
 * This library is free software; you can redistribute it and/or modify it under the terms
 * of the GNU Lesser General Public License as published by the Free Software Foundation;
 * either version 2.1 of the License, or (at your option) any later version.
 *
 * This library 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 Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License along with this
 * library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330,
 * Boston, MA 02111-1307, USA.
 */

package org.jrobin.core;

import org.jrobin.core.timespec.TimeParser;
import org.jrobin.core.timespec.TimeSpec;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import java.awt.*;
import java.io.*;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;

/**
 * Class defines various utility functions used in JRobin.
 *
 * @author <a href="mailto:saxon@jrobin.org">Sasa Markovic</a>
 */
public class Util {

	public static final long MAX_LONG = Long.MAX_VALUE;
	public static final long MIN_LONG = -Long.MAX_VALUE;

	public static final double MAX_DOUBLE = Double.MAX_VALUE;
	public static final double MIN_DOUBLE = -Double.MAX_VALUE;

	// pattern RRDTool uses to format doubles in XML files
	static final String PATTERN = "0.0000000000E00";
	// directory under $USER_HOME used for demo graphs storing
	static final String JROBIN_DIR = "jrobin-demo";

	static final DecimalFormat df;

	static {
		df = (DecimalFormat) NumberFormat.getNumberInstance(Locale.ENGLISH);
		df.applyPattern(PATTERN);
		df.setPositivePrefix("+");
	}

	/**
	 * Converts an array of long primitives to an array of doubles.
	 *
	 * @return Same array but with all values as double.
	 */
	public static double[] toDoubleArray(final long[] array) {
		double[] values = new double[ array.length ];
		for (int i = 0; i < array.length; i++) {
			values[i] = array[i];
		}
		return values;
	}

	/**
	 * Returns current timestamp in seconds (without milliseconds). Returned timestamp
	 * is obtained with the following expression: <p>
	 * <p/>
	 * <code>(System.currentTimeMillis() + 500L) / 1000L</code>
	 *
	 * @return Current timestamp
	 */
	public static long getTime() {
		return (System.currentTimeMillis() + 500L) / 1000L;
	}

	/**
	 * Just an alias for {@link #getTime()} method.
	 *
	 * @return Current timestamp (without milliseconds)
	 */
	public static long getTimestamp() {
		return getTime();
	}

	/**
	 * Rounds the given timestamp to the nearest whole &quote;step&quote;. Rounded value is obtained
	 * from the following expression:<p>
	 * <code>timestamp - timestamp % step;</code><p>
	 *
	 * @param timestamp Timestamp in seconds
	 * @param step	  Step in seconds
	 * @return "Rounded" timestamp
	 */
	public static long normalize(long timestamp, long step) {
		return timestamp - timestamp % step;
	}

	/**
	 * Returns the greater of two double values, but treats NaN as the smallest possible
	 * value. Note that <code>Math.max()</code> behaves differently for NaN arguments.
	 *
	 * @param x an argument
	 * @param y another argument
	 * @return the lager of arguments
	 */
	public static double max(double x, double y) {
		return Double.isNaN(x) ? y : Double.isNaN(y) ? x : Math.max(x, y);
	}

	/**
	 * Returns the smaller of two double values, but treats NaN as the greatest possible
	 * value. Note that <code>Math.min()</code> behaves differently for NaN arguments.
	 *
	 * @param x an argument
	 * @param y another argument
	 * @return the smaller of arguments
	 */
	public static double min(double x, double y) {
		return Double.isNaN(x) ? y : Double.isNaN(y) ? x : Math.min(x, y);
	}

	/**
	 * Calculates sum of two doubles, but treats NaNs as zeros.
	 *
	 * @param x First double
	 * @param y Second double
	 * @return Sum(x,y) calculated as <code>Double.isNaN(x)? y: Double.isNaN(y)? x: x + y;</code>
	 */
	public static double sum(double x, double y) {
		return Double.isNaN(x) ? y : Double.isNaN(y) ? x : x + y;
	}

	static String formatDouble(double x, String nanString, boolean forceExponents) {
		if (Double.isNaN(x)) {
			return nanString;
		}
		if (forceExponents) {
			return df.format(x);
		}
		return "" + x;
	}

	static String formatDouble(double x, boolean forceExponents) {
		return formatDouble(x, "" + Double.NaN, forceExponents);
	}

	/**
	 * Formats double as a string using exponential notation (RRDTool like). Used for debugging
	 * throught the project.
	 *
	 * @param x value to be formatted
	 * @return string like "+1.234567E+02"
	 */
	public static String formatDouble(double x) {
		return formatDouble(x, true);
	}

	/**
	 * Returns <code>Date</code> object for the given timestamp (in seconds, without
	 * milliseconds)
	 *
	 * @param timestamp Timestamp in seconds.
	 * @return Corresponding Date object.
	 */
	public static Date getDate(long timestamp) {
		return new Date(timestamp * 1000L);
	}

	/**
	 * Returns <code>Calendar</code> object for the given timestamp
	 * (in seconds, without milliseconds)
	 *
	 * @param timestamp Timestamp in seconds.
	 * @return Corresponding Calendar object.
	 */
	public static Calendar getCalendar(long timestamp) {
		Calendar calendar = Calendar.getInstance();
		calendar.setTimeInMillis(timestamp * 1000L);
		return calendar;
	}

	/**
	 * Returns <code>Calendar</code> object for the given Date object
	 *
	 * @param date Date object
	 * @return Corresponding Calendar object.
	 */
	public static Calendar getCalendar(Date date) {
		Calendar calendar = Calendar.getInstance();
		calendar.setTime(date);
		return calendar;
	}

	/**
	 * Returns timestamp (unix epoch) for the given Date object
	 *
	 * @param date Date object
	 * @return Corresponding timestamp (without milliseconds)
	 */
	public static long getTimestamp(Date date) {
		// round to whole seconds, ignore milliseconds
		return (date.getTime() + 499L) / 1000L;
	}

	/**
	 * Returns timestamp (unix epoch) for the given Calendar object
	 *
	 * @param gc Calendar object
	 * @return Corresponding timestamp (without milliseconds)
	 */
	public static long getTimestamp(Calendar gc) {
		return getTimestamp(gc.getTime());
	}

	/**
	 * Returns timestamp (unix epoch) for the given year, month, day, hour and minute.
	 *
	 * @param year  Year
	 * @param month Month (zero-based)
	 * @param day   Day in month
	 * @param hour  Hour
	 * @param min   Minute
	 * @return Corresponding timestamp
	 */
	public static long getTimestamp(int year, int month, int day, int hour, int min) {
		Calendar calendar = Calendar.getInstance();
		calendar.clear();
		calendar.set(year, month, day, hour, min);
		return Util.getTimestamp(calendar);
	}

	/**
	 * Returns timestamp (unix epoch) for the given year, month and day.
	 *
	 * @param year  Year
	 * @param month Month (zero-based)
	 * @param day   Day in month
	 * @return Corresponding timestamp
	 */
	public static long getTimestamp(int year, int month, int day) {
		return Util.getTimestamp(year, month, day, 0, 0);
	}

	/**
	 * Parses at-style time specification and returns the corresponding timestamp. For example:<p>
	 * <pre>
	 * long t = Util.getTimestamp("now-1d");
	 * </pre>
	 *
	 * @param atStyleTimeSpec at-style time specification. For the complete explanation of the syntax
	 *                        allowed see RRDTool's <code>rrdfetch</code> man page.<p>
	 * @return timestamp in seconds since epoch.
	 * @throws RrdException Thrown if invalid time specification is supplied.
	 */
	public static long getTimestamp(String atStyleTimeSpec) throws RrdException {
		TimeSpec timeSpec = new TimeParser(atStyleTimeSpec).parse();
		return timeSpec.getTimestamp();
	}

	/**
	 * Parses two related at-style time specifications and returns corresponding timestamps. For example:<p>
	 * <pre>
	 * long[] t = Util.getTimestamps("end-1d","now");
	 * </pre>
	 *
	 * @param atStyleTimeSpec1 Starting at-style time specification. For the complete explanation of the syntax
	 *                         allowed see RRDTool's <code>rrdfetch</code> man page.<p>
	 * @param atStyleTimeSpec2 Ending at-style time specification. For the complete explanation of the syntax
	 *                         allowed see RRDTool's <code>rrdfetch</code> man page.<p>
	 * @return An array of two longs representing starting and ending timestamp in seconds since epoch.
	 * @throws RrdException Thrown if any input time specification is invalid.
	 */
	public static long[] getTimestamps(String atStyleTimeSpec1, String atStyleTimeSpec2) throws RrdException {
		TimeSpec timeSpec1 = new TimeParser(atStyleTimeSpec1).parse();
		TimeSpec timeSpec2 = new TimeParser(atStyleTimeSpec2).parse();
		return TimeSpec.getTimestamps(timeSpec1, timeSpec2);
	}

	/**
	 * Parses input string as a double value. If the value cannot be parsed, Double.NaN
	 * is returned (NumberFormatException is never thrown).
	 *
	 * @param valueStr String representing double value
	 * @return a double corresponding to the input string
	 */
	public static double parseDouble(String valueStr) {
		double value;
		try {
			value = Double.parseDouble(valueStr);
		}
		catch (NumberFormatException nfe) {
			value = Double.NaN;
		}
		return value;
	}

	/**
	 * Checks if a string can be parsed as double.
	 *
	 * @param s Input string
	 * @return <code>true</code> if the string can be parsed as double, <code>false</code> otherwise
	 */
	public static boolean isDouble(String s) {
		try {
			Double.parseDouble(s);
			return true;
		}
		catch (NumberFormatException nfe) {
			return false;
		}
	}

	/**
	 * Parses input string as a boolean value. The parser is case insensitive.
	 *
	 * @param valueStr String representing boolean value
	 * @return <code>true</code>, if valueStr equals to 'true', 'on', 'yes', 'y' or '1';
	 *         <code>false</code> in all other cases.
	 */
	public static boolean parseBoolean(String valueStr) {
		return valueStr.equalsIgnoreCase("true") ||
				valueStr.equalsIgnoreCase("on") ||
				valueStr.equalsIgnoreCase("yes") ||
				valueStr.equalsIgnoreCase("y") ||
				valueStr.equalsIgnoreCase("1");
	}

	/**
	 * Parses input string as color. The color string should be of the form #RRGGBB (no alpha specified,
	 * opaque color) or #RRGGBBAA (alpa specified, transparent colors). Leading character '#' is
	 * optional.
	 *
	 * @param valueStr Input string, for example #FFAA24, #AABBCC33, 010203 or ABC13E4F
	 * @return Paint object
	 * @throws RrdException If the input string is not 6 or 8 characters long (without optional '#')
	 */
	public static Paint parseColor(String valueStr) throws RrdException {
		String c = valueStr.startsWith("#") ? valueStr.substring(1) : valueStr;
		if (c.length() != 6 && c.length() != 8) {
			throw new RrdException("Invalid color specification: " + valueStr);
		}
		String r = c.substring(0, 2), g = c.substring(2, 4), b = c.substring(4, 6);
		if (c.length() == 6) {
			return new Color(Integer.parseInt(r, 16), Integer.parseInt(g, 16), Integer.parseInt(b, 16));
		}
		else {
			String a = c.substring(6);
			return new Color(Integer.parseInt(r, 16), Integer.parseInt(g, 16),
					Integer.parseInt(b, 16), Integer.parseInt(a, 16));
		}
	}

	/**
	 * Returns file system separator string.
	 *
	 * @return File system separator ("/" on Unix, "\" on Windows)
	 */
	public static String getFileSeparator() {
		return System.getProperty("file.separator");
	}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -