All Downloads are FREE. Search and download functionalities are using the official Maven repository.

cn.sylinx.hbatis.ext.res.ClasspathSqlResourceManager Maven / Gradle / Ivy

There is a newer version: 2.0.0.RELEASE
Show newest version

package cn.sylinx.hbatis.ext.res;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;

import cn.sylinx.hbatis.io.Resources;
import cn.sylinx.hbatis.log.GLog;

public abstract class ClasspathSqlResourceManager {

	private final static Map cache = new HashMap();

	public static void clear() {
		synchronized (cache) {
			cache.clear();
		}
	}

	public static String loadAndGet(String sqlpath) {

		InputStream is = null;
		ByteArrayOutputStream baos = null;
		String statement = null;

		try {
			is = Resources.getResourceAsStream(sqlpath);
			if (is != null) {

				baos = new ByteArrayOutputStream();
				int i = -1;
				while ((i = is.read()) != -1) {
					baos.write(i);
				}
				statement = baos.toString();
			}
		} catch (Exception e) {

			GLog.error("sql resource not found: {}", sqlpath);
			statement = null;

		} finally {

			if (is != null) {

				try {
					is.close();
				} catch (IOException e) {
				}
			}

			if (baos != null) {
				try {
					baos.close();
				} catch (IOException e) {
				}
			}
		}

		if (statement != null) {
			cache.put(sqlpath, statement);
		}

		return statement;
	}

	public static String getStatement(String sqlpath) {

		if (cache.containsKey(sqlpath)) {
			GLog.debug("sql bingo: {}", sqlpath);
			return cache.get(sqlpath);
		}

		return loadAndGet(sqlpath);
	}
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy