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

📄 util.java

📁 jrobin,使用纯java实现的RRD数据库,使用RRD数据库来统计数据.
💻 JAVA
📖 第 1 页 / 共 2 页
字号:

	/**
	 * Returns path to user's home directory.
	 *
	 * @return Path to users home directory, with file separator appended.
	 */
	public static String getUserHomeDirectory() {
		return System.getProperty("user.home") + getFileSeparator();
	}

	/**
	 * Returns path to directory used for placement of JRobin demo graphs and creates it
	 * if necessary.
	 *
	 * @return Path to demo directory (defaults to $HOME/jrobin/) if directory exists or
	 *         was successfully created. Null if such directory could not be created.
	 */
	public static String getJRobinDemoDirectory() {
		String homeDirPath = getUserHomeDirectory() + JROBIN_DIR + getFileSeparator();
		File homeDirFile = new File(homeDirPath);
		return (homeDirFile.exists() || homeDirFile.mkdirs()) ? homeDirPath : null;
	}

	/**
	 * Returns full path to the file stored in the demo directory of JRobin
	 *
	 * @param filename Partial path to the file stored in the demo directory of JRobin
	 *                 (just name and extension, without parent directories)
	 * @return Full path to the file
	 */
	public static String getJRobinDemoPath(String filename) {
		String demoDir = getJRobinDemoDirectory();
		if (demoDir != null) {
			return demoDir + filename;
		}
		else {
			return null;
		}
	}

	static boolean sameFilePath(String path1, String path2) throws IOException {
		File file1 = new File(path1);
		File file2 = new File(path2);
		return file1.getCanonicalPath().equals(file2.getCanonicalPath());
	}

	static int getMatchingDatasourceIndex(RrdDb rrd1, int dsIndex, RrdDb rrd2) throws IOException {
		String dsName = rrd1.getDatasource(dsIndex).getDsName();
		try {
			return rrd2.getDsIndex(dsName);
		}
		catch (RrdException e) {
			return -1;
		}
	}

	static int getMatchingArchiveIndex(RrdDb rrd1, int arcIndex, RrdDb rrd2)
			throws IOException {
		Archive archive = rrd1.getArchive(arcIndex);
		String consolFun = archive.getConsolFun();
		int steps = archive.getSteps();
		try {
			return rrd2.getArcIndex(consolFun, steps);
		}
		catch (RrdException e) {
			return -1;
		}
	}

	static String getTmpFilename() throws IOException {
		return File.createTempFile("JROBIN_", ".tmp").getCanonicalPath();
	}

	static final String ISO_DATE_FORMAT = "yyyy-MM-dd HH:mm:ss";   // ISO

	/**
	 * Creates Calendar object from a string. The string should represent
	 * either a long integer (UNIX timestamp in seconds without milliseconds,
	 * like "1002354657") or a human readable date string in the format "yyyy-MM-dd HH:mm:ss"
	 * (like "2004-02-25 12:23:45").
	 *
	 * @param timeStr Input string
	 * @return Calendar object
	 */
	public static Calendar getCalendar(String timeStr) {
		// try to parse it as long
		try {
			long timestamp = Long.parseLong(timeStr);
			return Util.getCalendar(timestamp);
		}
		catch (NumberFormatException nfe) {
			// not a long timestamp, try to parse it as data
			SimpleDateFormat df = new SimpleDateFormat(ISO_DATE_FORMAT);
			df.setLenient(false);
			try {
				Date date = df.parse(timeStr);
				return Util.getCalendar(date);
			}
			catch (ParseException pe) {
				throw new IllegalArgumentException("Time/date not in " + ISO_DATE_FORMAT +
						" format: " + timeStr);
			}
		}
	}

	/**
	 * Various DOM utility functions
	 */
	public static class Xml {
		public static Node[] getChildNodes(Node parentNode) {
			return getChildNodes(parentNode, null);
		}

		public static Node[] getChildNodes(Node parentNode, String childName) {
			ArrayList<Node> nodes = new ArrayList<Node>();
			NodeList nodeList = parentNode.getChildNodes();
			for (int i = 0; i < nodeList.getLength(); i++) {
				Node node = nodeList.item(i);
				if (childName == null || node.getNodeName().equals(childName)) {
					nodes.add(node);
				}
			}
			return nodes.toArray(new Node[0]);
		}

		public static Node getFirstChildNode(Node parentNode, String childName) throws RrdException {
			Node[] childs = getChildNodes(parentNode, childName);
			if (childs.length > 0) {
				return childs[0];
			}
			throw new RrdException("XML Error, no such child: " + childName);
		}

		public static boolean hasChildNode(Node parentNode, String childName) {
			Node[] childs = getChildNodes(parentNode, childName);
			return childs.length > 0;
		}

		// -- Wrapper around getChildValue with trim
		public static String getChildValue(Node parentNode, String childName) throws RrdException {
			return getChildValue(parentNode, childName, true);
		}

		public static String getChildValue(Node parentNode, String childName, boolean trim) throws RrdException {
			NodeList children = parentNode.getChildNodes();
			for (int i = 0; i < children.getLength(); i++) {
				Node child = children.item(i);
				if (child.getNodeName().equals(childName)) {
					return getValue(child, trim);
				}
			}
			throw new RrdException("XML Error, no such child: " + childName);
		}

		// -- Wrapper around getValue with trim
		public static String getValue(Node node) {
			return getValue(node, true);
		}

		public static String getValue(Node node, boolean trimValue) {
			String value = null;
			Node child = node.getFirstChild();
			if (child != null) {
				value = child.getNodeValue();
				if (value != null && trimValue) {
					value = value.trim();
				}
			}
			return value;
		}

		public static int getChildValueAsInt(Node parentNode, String childName) throws RrdException {
			String valueStr = getChildValue(parentNode, childName);
			return Integer.parseInt(valueStr);
		}

		public static int getValueAsInt(Node node) {
			String valueStr = getValue(node);
			return Integer.parseInt(valueStr);
		}

		public static long getChildValueAsLong(Node parentNode, String childName) throws RrdException {
			String valueStr = getChildValue(parentNode, childName);
			return Long.parseLong(valueStr);
		}

		public static long getValueAsLong(Node node) {
			String valueStr = getValue(node);
			return Long.parseLong(valueStr);
		}

		public static double getChildValueAsDouble(Node parentNode, String childName) throws RrdException {
			String valueStr = getChildValue(parentNode, childName);
			return Util.parseDouble(valueStr);
		}

		public static double getValueAsDouble(Node node) {
			String valueStr = getValue(node);
			return Util.parseDouble(valueStr);
		}

		public static boolean getChildValueAsBoolean(Node parentNode, String childName) throws RrdException {
			String valueStr = getChildValue(parentNode, childName);
			return Util.parseBoolean(valueStr);
		}

		public static boolean getValueAsBoolean(Node node) {
			String valueStr = getValue(node);
			return Util.parseBoolean(valueStr);
		}

		public static Element getRootElement(InputSource inputSource) throws RrdException, IOException {
			DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
			factory.setValidating(false);
			factory.setNamespaceAware(false);
			try {
				DocumentBuilder builder = factory.newDocumentBuilder();
				Document doc = builder.parse(inputSource);
				return doc.getDocumentElement();
			}
			catch (ParserConfigurationException e) {
				throw new RrdException(e);
			}
			catch (SAXException e) {
				throw new RrdException(e);
			}
		}

		public static Element getRootElement(String xmlString) throws RrdException, IOException {
			return getRootElement(new InputSource(new StringReader(xmlString)));
		}

		public static Element getRootElement(File xmlFile) throws RrdException, IOException {
			Reader reader = null;
			try {
				reader = new FileReader(xmlFile);
				return getRootElement(new InputSource(reader));
			}
			finally {
				if (reader != null) {
					reader.close();
				}
			}
		}
	}

	private static long lastLap = System.currentTimeMillis();

	/**
	 * Function used for debugging purposes and performance bottlenecks detection.
	 * Probably of no use for end users of JRobin.
	 *
	 * @return String representing time in seconds since last
	 *         <code>getLapTime()</code> method call.
	 */
	public static String getLapTime() {
		long newLap = System.currentTimeMillis();
		double seconds = (newLap - lastLap) / 1000.0;
		lastLap = newLap;
		return "[" + seconds + " sec]";
	}

	/**
	 * Returns the root directory of the JRobin distribution. Useful in some demo applications,
	 * probably of no use anywhere else.<p>
	 * <p/>
	 * The function assumes that all JRobin .class files are placed under
	 * the &lt;root&gt;/classes subdirectory and that all jars (libraries) are placed in the
	 * &lt;root&gt;/lib subdirectory (the original JRobin directory structure).<p>
	 *
	 * @return absolute path to JRobin's home directory
	 */
	public static String getJRobinHomeDirectory() {
		String className = Util.class.getName().replace('.', '/');
		String uri = Util.class.getResource("/" + className + ".class").toString();
		//System.out.println(uri);
		if (uri.startsWith("file:/")) {
			uri = uri.substring(6);
			File file = new File(uri);
			// let's go 5 steps backwards
			for (int i = 0; i < 5; i++) {
				file = file.getParentFile();
			}
			uri = file.getAbsolutePath();
		}
		else if (uri.startsWith("jar:file:/")) {
			uri = uri.substring(9, uri.lastIndexOf('!'));
			File file = new File(uri);
			// let's go 2 steps backwards
			for (int i = 0; i < 2; i++) {
				file = file.getParentFile();
			}
			uri = file.getAbsolutePath();
		}
		else {
			uri = null;
		}
		return uri;
	}

	/**
	 * Compares two doubles but treats all NaNs as equal.
	 * In Java (by default) Double.NaN == Double.NaN always returns <code>false</code>
	 *
	 * @param x the first value
	 * @param y the second value
	 * @return <code>true</code> if x and y are both equal to Double.NaN, or if x == y. <code>false</code> otherwise
	 */
	public static boolean equal(double x, double y) {
		return (Double.isNaN(x) && Double.isNaN(y)) || (x == y);
	}

	/**
	 * Returns canonical file path for the given file path
	 *
	 * @param path Absolute or relative file path
	 * @return Canonical file path
	 * @throws IOException Thrown if canonical file path could not be resolved
	 */
	public static String getCanonicalPath(String path) throws IOException {
		return new File(path).getCanonicalPath();
	}

	/**
	 * Returns last modification time for the given file.
	 *
	 * @param file File object representing file on the disk
	 * @return Last modification time in seconds (without milliseconds)
	 */
	public static long getLastModified(String file) {
		return (new File(file).lastModified() + 500L) / 1000L;
	}

	/**
	 * Checks if the file with the given file name exists
	 *
	 * @param filename File name
	 * @return <code>true</code> if file exists, <code>false</code> otherwise
	 */
	public static boolean fileExists(String filename) {
		return new File(filename).exists();
	}

	/**
	 * Finds max value for an array of doubles (NaNs are ignored). If all values in the array
	 * are NaNs, NaN is returned.
	 *
	 * @param values Array of double values
	 * @return max value in the array (NaNs are ignored)
	 */
	public static double max(double[] values) {
		double max = Double.NaN;
		for (double value : values) {
			max = Util.max(max, value);
		}
		return max;
	}

	/**
	 * Finds min value for an array of doubles (NaNs are ignored). If all values in the array
	 * are NaNs, NaN is returned.
	 *
	 * @param values Array of double values
	 * @return min value in the array (NaNs are ignored)
	 */
	public static double min(double[] values) {
		double min = Double.NaN;
		for (double value : values) {
			min = Util.min(min, value);
		}
		return min;
	}

	/**
	 * Equivalent of the C-style sprintf function. Sorry, it works only in Java5.
	 *
	 * @param format Format string
	 * @param args   Arbitrary list of arguments
	 * @return Formatted string
	 */
	public static String sprintf(String format, Object ... args) {
		String fmt = format.replaceAll("([^%]|^)%([^a-zA-Z%]*)l(f|g|e)", "$1%$2$3");
		return String.format(fmt, args);
	}
}

⌨️ 快捷键说明

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