Java源码示例:org.nutz.lang.Streams
示例1
@Override
public void delete(Session session) {
if (session == null || session.getId() == null) {
return;
}
Jedis jedis = null;
try {
jedis = jedisAgent.getResource();
jedis.hdel(JedisUtils.getBytesKey(sessionKeyPrefix), JedisUtils.getBytesKey(session.getId().toString()));
jedis.del(JedisUtils.getBytesKey(sessionKeyPrefix + session.getId()));
logger.debug("delete {} ", session.getId());
} catch (Exception e) {
logger.error("delete {} ", session.getId(), e);
} finally {
Streams.safeClose(jedis);
}
}
示例2
@Override
public V put(K key, V value) throws CacheException {
if (key == null){
return null;
}
Jedis jedis = null;
try {
jedis = jedisAgent.getResource();
jedis.hset(JedisUtils.getBytesKey(cacheKeyName), JedisUtils.getBytesKey(key), JedisUtils.toBytes(value));
logger.debug("put {} {} = {}", cacheKeyName, key, value);
} catch (Exception e) {
logger.error("put {} {}", cacheKeyName, key, e);
} finally {
Streams.safeClose(jedis);
}
return value;
}
示例3
@SuppressWarnings("unchecked")
@Override
public V remove(K key) throws CacheException {
V value = null;
Jedis jedis = null;
try {
jedis = jedisAgent.getResource();
value = (V)JedisUtils.toObject(jedis.hget(JedisUtils.getBytesKey(cacheKeyName), JedisUtils.getBytesKey(key)));
jedis.hdel(JedisUtils.getBytesKey(cacheKeyName), JedisUtils.getBytesKey(key));
logger.debug("remove {} {}", cacheKeyName, key);
} catch (Exception e) {
logger.warn("remove {} {}", cacheKeyName, key, e);
} finally {
Streams.safeClose(jedis);
}
return value;
}
示例4
@SuppressWarnings("unchecked")
@Override
public Collection<V> values() {
Collection<V> vals = Collections.emptyList();;
Jedis jedis = null;
try {
jedis = jedisAgent.getResource();
Collection<byte[]> col = jedis.hvals(JedisUtils.getBytesKey(cacheKeyName));
for(byte[] val : col){
Object obj = JedisUtils.toObject(val);
if (obj != null){
vals.add((V) obj);
}
}
logger.debug("values {} {} ", cacheKeyName, vals);
return vals;
} catch (Exception e) {
logger.error("values {}", cacheKeyName, e);
} finally {
Streams.safeClose(jedis);
}
return vals;
}
示例5
public String generateCode(String packageName, String templatePath) throws IOException {
VelocityContext context = new VelocityContext();
context.put("table", table);
context.put("packageName", packageName);
StringWriter writer = new StringWriter();
String template = new String(Streams.readBytes(ClassLoader.getSystemResourceAsStream(templatePath)),
Charset.forName("utf8"));
VelocityEngine engine = new VelocityEngine();
engine.setProperty("runtime.references.strict", false);
engine.init();
engine.evaluate(context, writer, "generator", template);
return writer.toString();
}
示例6
@SuppressWarnings("unchecked")
@Override
@Aop("redis")
public V get(K key) throws CacheException {
if (key == null){
return null;
}
V v = null;
HttpServletRequest request = Mvcs.getReq();
if (request != null){
v = (V)request.getAttribute(cacheKeyName);
if (v != null){
return v;
}
}
V value = null;
Jedis jedis = null;
try {
jedis = jedisAgent.getResource();
value = (V) jedis().hget(JedisUtils.getBytesKey(cacheKeyName),JedisUtils.getBytesKey(cacheKeyName));
logger.debug("get {} {} {}", cacheKeyName, key, request != null ? request.getRequestURI() : "");
} catch (Exception e) {
logger.error("get {} {} {}", cacheKeyName, key, request != null ? request.getRequestURI() : "", e);
} finally {
Streams.safeClose(jedis);
}
if (request != null && value != null){
request.setAttribute(cacheKeyName, value);
}
return value;
}
示例7
@Override
public void clear() throws CacheException {
Jedis jedis = null;
try {
jedis = jedisAgent.getResource();
jedis.hdel(JedisUtils.getBytesKey(cacheKeyName));
logger.debug("clear {}", cacheKeyName);
} catch (Exception e) {
logger.error("clear {}", cacheKeyName, e);
} finally {
Streams.safeClose(jedis);
}
}
示例8
public String generateCode(String packageName, String templatePath) throws IOException {
VelocityContext context = new VelocityContext();
context.put("table", table);
context.put("packageName", packageName);
StringWriter writer = new StringWriter();
String template = new String(Streams.readBytes(ClassLoader.getSystemResourceAsStream(templatePath)),
Charset.forName("utf8"));
VelocityEngine engine = new VelocityEngine();
engine.setProperty("runtime.references.strict", false);
engine.init();
engine.evaluate(context, writer, "generator", template);
return writer.toString();
}
示例9
protected static SnakerEngine buildSnaker(DataSource ds, Object...paths) throws IOException {
// 首先,我们构建一个snaker的上下文
SimpleContext ctx = new SimpleContext();
// 将集成nutz所必须的两个类,关联之. 这样使用者仅需要声明本IocLoader即可完成全部配置
ctx.put(NutzAccess.class.getName(), NutzAccess.class);
ctx.put(NutzTransactionInterceptor.class.getName(), NutzTransactionInterceptor.class);
// 开始构建sanker的配置对象
Configuration cnf = new Configuration(ctx);
cnf.initAccessDBObject(ds);
SnakerEngine engine = cnf.buildSnakerEngine();
// 如果用户声明了流程描述文件的路径,加载之
if (paths != null) {
for (Object path : paths) {
for(NutResource re : Scans.me().scan(String.valueOf(path))) {
if (log.isDebugEnabled())
log.debug("Found snakerflow xml > " + re.getName());
//*********************************************************
// 这部分属于hack的部分, 因为snaker并不识别相同的流程配置,而是简单地作为新流程
// 所以,需要自行查询一下是不是数据相同,不一样的时候才deploy
byte[] data = Streams.readBytesAndClose(re.getInputStream());
ProcessModel model = ModelParser.parse(data);
List<Process> list = ctx.find(DBAccess.class).queryList(Process.class, querySql, model.getName());
if (!list.isEmpty()) {
Process p = list.get(0);
byte[] cnt = p.getDBContent();
if (cnt != null && Arrays.equals(cnt, data)) {
log.debug("Same snakerflow xml > " + re.getName() + " skiped");
continue;
}
}
//*********************************************************
// 同名的流程数据有更新或这是全新的流程,部署之
engine.process().deploy(new ByteArrayInputStream(data));
}
}
}
// 工厂方法完成, snaker引擎已经准备好了,可以返回了
return engine;
}
示例10
public WxAccessToken get() {
Map<String, String> map;
Jedis jedis = null;
try {
jedis = jedisAgent.getResource();
map = jedis.hgetAll(tokenKey);
} finally {
Streams.safeClose(jedis);
}
if (map == null || map.isEmpty())
return null;
return Lang.map2Object(map, WxAccessToken.class);
}
示例11
public void save(String token, int expires, long lastCacheTimeMillis) {
Map<String, String> map = new HashMap<String, String>();
map.put("token", token);
map.put("expires", "" + expires);
map.put("lastCacheTimeMillis", "" + lastCacheTimeMillis);
Jedis jedis = null;
try {
jedis = jedisAgent.getResource();
jedis.hmset(tokenKey, map);
} finally {
Streams.safeClose(jedis);
}
}
示例12
/**
* 将一个输入流转为WxInMsg
*/
public static <T> T convert(InputStream in, Class<T> klass) {
Map<String, Object> map;
String raw;
try {
// fix:
// DocumentBuilder不支持直接传入Reader,如果直接传InputStream的话又按系统默认编码,所以,用InputSource中转一下
Reader r = Streams.utf8r(in);
raw = Lang.readAll(r);
map = Xmls.asMap(xmls().parse(new InputSource(new StringReader(raw)))
.getDocumentElement());
}
catch (Exception e) {
throw Lang.wrapThrow(e);
}
Lang.convertMapKey(map, new MapKeyConvertor() {
@Override
public String convertKey(String key) {
return Strings.lowerFirst(key);
}
}, true);
if (DEV_MODE) {
log.debug("Income >> \n" + Json.toJson(map));
}
T t = Lang.map2Object(map, klass);
if (t instanceof WxInMsg)
((WxInMsg) t).raw(raw);
else if (t instanceof WxOutMsg)
((WxOutMsg) t).raw(raw);
return t;
}
示例13
public void init() throws IOException {
log.debug("beetl init ....");
Configuration cfg = Configuration.defaultConfiguration();
Properties prop = new Properties();
InputStream ins = Configuration.class.getResourceAsStream("/beetl.properties");
if (ins != null) {
log.debug("found beetl.properties, loading ...");
try {
prop.load(ins);
}
finally {
Streams.safeClose(ins);
}
}
if (!prop.containsKey(Configuration.RESOURCE_LOADER)) {
// 默认选用WebAppResourceLoader,除非用户自定义了RESOURCE_LOADER
log.debug("no custom RESOURCE_LOADER found , select WebAppResourceLoader");
cfg.setResourceLoader(WebAppResourceLoader.class.getName());
}
if (!prop.containsKey(Configuration.DIRECT_BYTE_OUTPUT)) {
// 默认启用DIRECT_BYTE_OUTPUT,除非用户自定义, 一般不会.
log.debug("no custom DIRECT_BYTE_OUTPUT found , set to true");
// 当DIRECT_BYTE_OUTPUT为真时, beetl渲染会通过getOutputStream获取输出流
// 而BeetlView会使用LazyResponseWrapper代理getOutputStream方法
// 从而实现在模板输出之前,避免真正调用getOutputStream
// 这样@Fail视图就能正常工作了
cfg.setDirectByteOutput(true);
}
if (!prop.containsKey(Configuration.ERROR_HANDLER)) {
// 没有自定义ERROR_HANDLER,用定制的
cfg.setErrorHandlerClass(LogErrorHandler.class.getName());
}
groupTemplate = new GroupTemplate(cfg);
render = new WebRender(groupTemplate);
log.debug("beetl init complete");
}
示例14
@Override
public void update(Session session) throws UnknownSessionException {
if (session == null || session.getId() == null) {
return;
}
HttpServletRequest request = Mvcs.getReq();
if (request != null){
String uri = request.getServletPath();
// 如果是静态文件,则不更新SESSION
if (isStaticFile(uri)){
return;
}
// 手动控制不更新SESSION
// if (Global.NO.equals(request.getParameter("updateSession"))){
// return;
// }
}
Jedis jedis = null;
try {
jedis = jedisAgent.getResource();
// 获取登录者编号
PrincipalCollection pc = (PrincipalCollection)session.getAttribute(DefaultSubjectContext.PRINCIPALS_SESSION_KEY);
String principalId = pc != null ? pc.getPrimaryPrincipal().toString() : StringUtils.EMPTY;
jedis.hset(sessionKeyPrefix, session.getId().toString(), principalId + "|" + session.getTimeout() + "|" + session.getLastAccessTime().getTime());
jedis.set(JedisUtils.getBytesKey(sessionKeyPrefix + session.getId()), JedisUtils.toBytes(session));
// 设置超期时间
int timeoutSeconds = (int)(session.getTimeout() / 1000);
jedis.expire((sessionKeyPrefix + session.getId()), timeoutSeconds);
logger.debug("update {} {}", session.getId(), request != null ? request.getRequestURI() : "");
} catch (Exception e) {
logger.error("update {} {}", session.getId(), request != null ? request.getRequestURI() : "", e);
} finally {
Streams.safeClose(jedis);
}
}
示例15
public void destroyObject(SocketAddress key, PooledObject<SocketHolder> p) throws Exception {
Streams.safeClose(p.getObject().socket);
}
示例16
public static Object download(String url) {
if (log.isDebugEnabled()) {
log.debugf("Download url: %s, default timeout: %d", url, CONNECT_TIME_OUT);
}
try {
Response resp = Http.get(url);
if (resp.isOK()) {
String cd = resp.getHeader().get("Content-disposition");
if (log.isInfoEnabled()) {
log.infof("Get download file info: %s", cd);
}
if (Lang.isEmpty(cd)) {
return resp.getContent();
}
cd = cd.substring(cd.indexOf(FILE_NAME_FLAG) + FILE_NAME_FLAG.length());
String tmp = cd.startsWith("\"") ? cd.substring(1) : cd;
tmp = tmp.endsWith("\"") ? cd.replace("\"", "") : cd;
String filename = tmp.substring(0, tmp.lastIndexOf("."));
String fileext = tmp.substring(tmp.lastIndexOf("."));
if (log.isInfoEnabled()) {
log.infof("Download file name: %s", filename);
log.infof("Download file ext: %s", fileext);
}
File tmpfile = File.createTempFile(filename, fileext);
InputStream is = resp.getStream();
OutputStream os = new FileOutputStream(tmpfile);
Streams.writeAndClose(os, is);
return tmpfile;
}
throw Lang.wrapThrow(new RuntimeException(String.format("Download file [%s] failed. status: %d, content: %s",
url,
resp.getStatus(),
resp.getContent())));
}
catch (Exception e) {
throw Lang.wrapThrow(e);
}
}
示例17
/**
* 用一个wxHandler处理对应的用户请求
*/
public static View handle(WxHandler wxHandler, HttpServletRequest req, String key)
throws IOException {
if (wxHandler == null) {
log.info("WxHandler is NULL");
return HttpStatusView.HTTP_502;
}
String signature = req.getParameter("signature");
String timestamp = req.getParameter("timestamp");
String nonce = req.getParameter("nonce");
String msg_signature = req.getParameter("msg_signature");
String encrypt_type = req.getParameter("encrypt_type");
if (!wxHandler.check(signature, timestamp, nonce, key)) {
log.info("token is invalid");
return HttpStatusView.HTTP_502;
}
if ("GET".equalsIgnoreCase(req.getMethod())) {
String echostr = req.getParameter("echostr");
log.info("GET? return echostr=" + echostr);
return new ViewWrapper(new RawView(null), echostr);
}
String postData = Streams.readAndClose(new InputStreamReader(req.getInputStream(),
Encoding.CHARSET_UTF8));
if ("aes".equals(encrypt_type)) {
WXBizMsgCrypt msgCrypt = wxHandler.getMsgCrypt();
try {
// 若抛出Illegal key size,请更新JDK的加密库为不限制长度
postData = msgCrypt.decryptMsg(msg_signature, timestamp, nonce, postData);
}
catch (AesException e) {
return new HttpStatusView(403);
}
}
WxInMsg in = Wxs.convert(postData);
in.setExtkey(key);
WxOutMsg out = wxHandler.handle(in);
if (out != null) {
Wxs.fix(in, out);
}
return new ViewWrapper(WxView.me, out);
}