/** * 获取一个字段的泛型参数数组,如果这个字段没有泛型,返回空数组 * * @param f 字段 * @return 泛型参数数组 */ public static Class<?>[] getGenericTypes(Field f) { String gts = f.toGenericString(); Matcher m = PTN.matcher(gts); if (m.find()) { String s = m.group(2); String[] ss = Strings.splitIgnoreBlank(s); if (ss.length > 0) { Class<?>[] re = new Class<?>[ss.length]; try { for (int i = 0; i < ss.length; i++) { String className = ss[i]; if (className.length() > 0 && className.charAt(0) == '?') re[i] = Object.class; else { int pos = className.indexOf('<'); if (pos < 0) re[i] = Lang.loadClass(className); else re[i] = Lang.loadClass(className.substring(0, pos)); } } return re; } catch (ClassNotFoundException e) { throw Lang.wrapThrow(e); } } } return new Class<?>[0]; }
public void run() { // ----------------------------------------- 建立 log.infof("start TcpServer [%s] @ %d", Thread.currentThread().getName(), port); try { listener = new ServerSocket(port); } catch (IOException e1) { throw Lang.wrapThrow(e1); } // ----------------------------------------- 循环 log.infof("TcpServer listen @ %d", port); while (!stop) { log.info("before accept ..."); Socket socket = null; try { socket = listener.accept(); } catch (IOException e) { log.fatalf("Fail to accept %s @ %d , System.exit!", Thread.currentThread().getName(), port); System.exit(0); } log.info("do listen ..."); listen(socket); log.infof( "done for listen [%s:%d], stop=%b", socket.getInetAddress().getHostName(), socket.getPort(), stop); } // ----------------------------------------- 关闭 try { listener.close(); log.infof("TcpServer shutdown @ %d", port); } catch (IOException e) { throw Lang.wrapThrow(e); } }
public static SqlExpression create(String name, String op, Object value) { op = Strings.trim(op.toUpperCase()); // NULL if (null == value) { SqlExpression re; // IS NULL if ("IS".equals(op) || "NOT IS".equals(op) || "IS NOT".equals(op)) { re = isNull(name); } // !!! else { throw Lang.makeThrow("null can only use 'IS' or 'NOT IS'"); } return re.setNot(op.startsWith("NOT") || op.endsWith("NOT")); } // IN else if ("IN".equals(op) || "NOT IN".equals(op)) { Class<?> type = value.getClass(); SqlExpression re; // 数组 if (type.isArray()) { re = _evalRange((Mirror<?>) Mirror.me(type.getComponentType()), name, value); } // 集合 else if (Collection.class.isAssignableFrom(type)) { Object first = Lang.first(value); if (null == first) return null; re = _evalRange((Mirror<?>) Mirror.me(first), name, value); } // Sql Range else { re = inSql(name, value.toString()); } return re.setNot(op.startsWith("NOT")); } // LIKE || IS else if ("LIKE".equals(op) || "NOT LIKEs".equals(op)) { String v = value.toString(); Like re; if (v.length() == 1) { re = like(name, v); } else { re = like(name, v.substring(1, v.length() - 1)); re.left(v.substring(0, 1)); re.right(v.substring(v.length() - 1, v.length())); } return re.ignoreCase(false).setNot(op.startsWith("NOT")); } // = else if ("=".equals(op)) { return eq(name, value); } // != else if ("!=".equals(op) || "<>".equals(op)) { // TODO 检查一下,原本是&&, 明显永远成立 return eq(name, value).setNot(true); } // Others return new SimpleExpression(name, op, value); }
public void addCastor(Class<?> klass) { try { fillMap(klass, new HashMap<Class<?>, Method>()); } catch (Throwable e) { throw Lang.wrapThrow(Lang.unwrapThrow(e)); } }
public List<Article> getArticles() { if (!Lang.isEmpty(articles) && articles.size() > 10) { this.articles = articles.subList(0, 10); setCount(10); } else { this.setCount(Lang.length(articles)); } return articles; }
/** * 将对象转换成 Map * * @param <T> * @param obj POJO 对象 * @param mapType Map 的类型 * @return Map 对象 */ public static <T extends Map<String, Object>> T obj2map(Object obj, Class<T> mapType) { try { T map = mapType.newInstance(); Lang.obj2map(obj, map, new HashMap<Object, Object>()); return map; } catch (Exception e) { throw Lang.wrapThrow(e); } }
/** * 获取一个类的某个一个泛型参数 * * @param klass 类 * @param index 参数下标 (从 0 开始) * @return 泛型参数类型 */ @SuppressWarnings("unchecked") public static <T> Class<T> getTypeParam(Class<?> klass, int index) { Type[] types = getTypeParams(klass); if (index >= 0 && index < types.length) { Type t = types[index]; Class<T> clazz = (Class<T>) Lang.getTypeClass(t); if (clazz == null) throw Lang.makeThrow("Type '%s' is not a Class", t.toString()); return clazz; } throw Lang.makeThrow("Class type param out of range %d/%d", index, types.length); }
public <T> T insert(final T obj) { final EntityOperator opt = _optBy(Lang.first(obj)); if (null == opt) return null; Lang.each( obj, false, new Each<Object>() { public void invoke(int i, Object ele, int length) throws ExitLoop, LoopException { opt.addInsert(opt.entity, ele); } }); opt.exec(); return obj; }
public Object eject(Object obj) { try { return null == obj ? null : getter.invoke(obj); } catch (InvocationTargetException e) { throw new FailToGetValueException("getter=" + getter, e); } catch (Exception e) { if (log.isInfoEnabled()) log.info("Fail to value by getter", e); throw Lang.makeThrow( "Fail to invoke getter %s.'%s()' because [%s]: %s", getter.getDeclaringClass().getName(), getter.getName(), Lang.unwrapThrow(e), Lang.unwrapThrow(e).getMessage()); } }
/** * 根据一个文件建立一个输出流 * * @param file 文件 * @return 输出流 */ public static OutputStream fileOut(File file) { try { return buff(new FileOutputStream(file)); } catch (FileNotFoundException e) { throw Lang.wrapThrow(e); } }
/** * 根据一个文件路径建立一个输入流 * * @param file 文件 * @return 输入流 */ public static InputStream fileIn(File file) { try { return buff(Streams._input(file)); } catch (IOException e) { throw Lang.wrapThrow(e); } }
@At @Ok("json") public JDataGrid list_grid( @Attr(scope = Scope.SESSION, value = "account") Account acc, @Param("::columns") List<?> columns, @Param("::search") Map<?, ?> search, int draw, int start, int length) { start = start / length; Pager pager = new Pager(); pager.setPageNumber(start + 1); pager.setPageSize(length); Cnd cnd = Cnd.where("accountid", "=", acc.accountid); if (!Lang.isEmpty(search.get("value")) && !search.get("value").toString().equals("")) { cnd.and("name", "like", search.get("value")); } List<?> aaData = dao.query(Store.class, cnd); pager.setRecordCount(dao.count(Store.class, cnd)); JDataGrid ret = new JDataGrid(); ret.draw = draw; ret.data = aaData; ret.recordsTotal = pager.getRecordCount(); ret.recordsFiltered = pager.getRecordCount(); return ret; }
protected void listen(Socket socket) { SocketHandler handler = getHandler(); // 处理请求 try { handler.handle(socket); } // 仅仅是关闭连接 catch (SocketClosed e) { } // 停止服务 catch (ServerStopped e) { stop = true; } // 处理异常 catch (Throwable e) { handler.whenError(socket, e); } // 确保关闭 finally { if (!socket.isClosed()) try { socket.close(); } catch (IOException e) { throw Lang.wrapThrow(e); } } }
/** * 根据一个字段名和字段类型获取 Setter * * @param fieldName 字段名 * @param paramType 字段类型 * @return 方法 * @throws NoSuchMethodException 没找到 Setter */ public Method getSetter(String fieldName, Class<?> paramType) throws NoSuchMethodException { try { String setterName = "set" + Strings.capitalize(fieldName); try { return klass.getMethod(setterName, paramType); } catch (Throwable e) { try { return klass.getMethod(fieldName, paramType); } catch (Throwable e1) { Mirror<?> type = Mirror.me(paramType); for (Method method : klass.getMethods()) { if (method.getParameterTypes().length == 1) if (method.getName().equals(setterName) || method.getName().equals(fieldName)) { if (null == paramType || type.canCastToDirectly(method.getParameterTypes()[0])) return method; } } // 还是没有? 会不会是包装类型啊? if (!paramType.isPrimitive()) { Class<?> p = unWrapper(); if (null != p) return getSetter(fieldName, p); } throw new RuntimeException(); } } } catch (Throwable e) { throw Lang.makeThrow( NoSuchMethodException.class, "Fail to find setter for [%s]->[%s(%s)]", klass.getName(), fieldName, paramType.getName()); } }
protected List<Sql> createIndexs(Entity<?> en) { List<Sql> sqls = new ArrayList<Sql>(); StringBuilder sb = new StringBuilder(); List<EntityIndex> indexs = en.getIndexes(); for (EntityIndex index : indexs) { sb.setLength(0); if (index.isUnique()) sb.append("Create UNIQUE Index "); else sb.append("Create Index "); if (index.getName().contains("$")) sb.append(TableName.render(new CharSegment(index.getName()))); else sb.append(index.getName()); sb.append(" ON ").append(en.getTableName()).append("("); for (EntityField field : index.getFields()) { if (field instanceof MappingField) { MappingField mf = (MappingField) field; sb.append(mf.getColumnNameInSql()).append(','); } else { throw Lang.makeThrow( DaoException.class, "%s %s is NOT a mapping field, can't use as index field!!", en.getClass(), field.getName()); } } sb.setCharAt(sb.length() - 1, ')'); sqls.add(Sqls.create(sb.toString())); } return sqls; }
protected ParamInjector evalInjectorBy(Type type, Param param) { // TODO 这里的实现感觉很丑, 感觉可以直接用type进行验证与传递 // TODO 这里将Type的影响局限在了 github issue #30 中提到的局部范围 Class<?> clazz = Lang.getTypeClass(type); if (clazz == null) { if (log.isWarnEnabled()) log.warnf("!!Fail to get Type Class : type=%s , param=%s", type, param); return null; } // Map if (Map.class.isAssignableFrom(clazz)) return new MapSelfInjector(); if (null == param) return super.evalInjectorBy(type, null); String paramName = param.value(); // File if (File.class.isAssignableFrom(clazz)) return new FileInjector(paramName); // FileMeta if (FieldMeta.class.isAssignableFrom(clazz)) return new FileMetaInjector(paramName); // TempFile if (TempFile.class.isAssignableFrom(clazz)) return new TempFileInjector(paramName); // InputStream if (InputStream.class.isAssignableFrom(clazz)) return new InputStreamInjector(paramName); // Reader if (Reader.class.isAssignableFrom(clazz)) return new ReaderInjector(paramName); // List if (List.class.isAssignableFrom(clazz)) return new MapListInjector(paramName); if (TempFile[].class.isAssignableFrom(clazz)) { return new TempFileArrayInjector(paramName); } // Other return super.evalInjectorBy(type, param); }
public void process(ActionContext ac) throws Throwable { Object module = ac.getModule(); Method method = ac.getMethod(); Object[] args = ac.getMethodArgs(); try { Object re = method.invoke(module, args); ac.setMethodReturn(re); doNext(ac); } catch (IllegalAccessException e) { throw Lang.unwrapThrow(e); } catch (IllegalArgumentException e) { throw Lang.unwrapThrow(e); } catch (InvocationTargetException e) { throw Lang.unwrapThrow(e); } }
/** * 转换一个 POJO 从一个指定的类型到另外的类型 * * @param src 源对象 * @param fromType 源对象类型 * @param toType 目标类型 * @param args 转换时参数。有些 Castor 可能需要这个参数,比如 Array2Map * @return 目标对象 * @throws FailToCastObjectException 如果没有找到转换器,或者转换失败 */ @SuppressWarnings({"unchecked", "rawtypes"}) public <F, T> T cast(Object src, Class<F> fromType, Class<T> toType, String... args) throws FailToCastObjectException { if (null == src) { // 原生数据的默认值 if (toType.isPrimitive()) { if (toType == int.class) return (T) Integer.valueOf(0); else if (toType == long.class) return (T) Long.valueOf(0L); else if (toType == byte.class) return (T) Byte.valueOf((byte) 0); else if (toType == short.class) return (T) Short.valueOf((short) 0); else if (toType == float.class) return (T) Float.valueOf(.0f); else if (toType == double.class) return (T) Double.valueOf(.0); else if (toType == boolean.class) return (T) Boolean.FALSE; else if (toType == char.class) return (T) Character.valueOf(' '); throw Lang.impossible(); } // 是对象,直接返回 null return null; } if (fromType == toType || toType == null || fromType == null) return (T) src; if (fromType.getName().equals(toType.getName())) return (T) src; if (toType.isAssignableFrom(fromType)) return (T) src; Mirror<?> from = Mirror.me(fromType, extractor); if (from.canCastToDirectly(toType)) // Use language built-in cases return (T) src; Castor c = find(from, toType); if (null == c) throw new FailToCastObjectException( String.format( "Can not find castor for '%s'=>'%s' in (%d) because:\n%s", fromType.getName(), toType.getName(), map.size(), "Fail to find matched castor")); try { return (T) c.cast(src, toType, args); } catch (FailToCastObjectException e) { throw e; } catch (Exception e) { throw new FailToCastObjectException( String.format( "Fail to cast from <%s> to <%s> for {%s} because:\n%s:%s", fromType.getName(), toType.getName(), src, e.getClass().getSimpleName(), e.getMessage()), Lang.unwrapThrow(e)); } }
@SuppressWarnings({"unchecked", "rawtypes"}) public static boolean filterFields( Object obj, FieldMatcher matcher, Dao dao, Callback2<MappingField, Object> callback) { if (obj == null) return false; obj = Lang.first(obj); if (obj == null) { return false; } if (obj.getClass() == Class.class) { throw Lang.impossible(); } if (obj instanceof String || obj instanceof Number || obj instanceof Boolean) { throw Lang.impossible(); } Entity en = dao.getEntity(obj.getClass()); if (en == null) { throw Lang.impossible(); } List<MappingField> mfs = en.getMappingFields(); if (matcher != null) { Iterator<MappingField> it = mfs.iterator(); while (it.hasNext()) { MappingField mf = it.next(); if (!matcher.match(mf.getName())) it.remove(); } } boolean flag = false; for (MappingField mf : mfs) { if (matcher.isIgnoreId() && mf.isId()) continue; if (matcher.isIgnoreName() && mf.isName()) continue; if (matcher.isIgnorePk() && mf.isCompositePk()) continue; Object val = mf.getValue(obj); if (val == null) { if (matcher.isIgnoreNull()) continue; } if (val instanceof Number && ((Number) val).doubleValue() == 0.0) { if (matcher.isIgnoreZero()) continue; } if (val instanceof Date) { if (matcher.isIgnoreDate()) continue; } callback.invoke(mf, val); flag = true; } return flag; }
@Override protected java.util.Date cast(String src, Class<?> toType, String... args) { try { return dateTimeFormat.parse(src); } catch (ParseException e) { throw Lang.wrapThrow(e); } }
@Override public void close() throws IOException { try { for (MultipartItem item : items) item.close(); } catch (IOException e) { throw Lang.wrapThrow(e); } }
public MsgDigestInputStream(InputStream in, String name) { super(in); try { this.md = MessageDigest.getInstance(name); } catch (NoSuchAlgorithmException e) { throw Lang.wrapThrow(e); } }
public void formatQuery(DaoStatement daoStatement) { if (daoStatement == null) return; SqlContext ctx = daoStatement.getContext(); if (ctx == null || ctx.getPager() == null) return; if (daoStatement instanceof Pojo) formatQuery((Pojo) daoStatement); else if (daoStatement instanceof Sql) formatQuery((Sql) daoStatement); else throw Lang.noImplement(); }
/** * 将集合变成数组,数组的类型为集合的第一个元素的类型。如果集合为空,则返回 null * * @param coll 集合对象 * @return 数组 */ @SuppressWarnings("unchecked") public static <E> E[] collection2array(Collection<E> coll) { if (null == coll) return null; if (coll.size() == 0) return (E[]) new Object[0]; Class<E> eleType = (Class<E>) Lang.first(coll).getClass(); return collection2array(coll, eleType); }
public boolean createEntity(Dao dao, Entity<?> en) { StringBuilder sb = new StringBuilder("CREATE TABLE " + en.getTableName() + "("); // 创建字段 for (MappingField mf : en.getMappingFields()) { if (mf.isReadonly()) continue; sb.append('\n').append(mf.getColumnName()); // 自增主键特殊形式关键字 if (mf.isId() && mf.isAutoIncreasement()) { sb.append(" SERIAL"); } else { sb.append(' ').append(evalFieldType(mf)); // 非主键的 @Name,应该加入唯一性约束 if (mf.isName() && en.getPkType() != PkType.NAME) { sb.append(" UNIQUE NOT NULL"); } // 普通字段 else { if (mf.isUnsigned()) sb.append(" UNSIGNED"); if (mf.isNotNull()) sb.append(" NOT NULL"); if (mf.isAutoIncreasement()) throw Lang.noImplement(); if (mf.hasDefaultValue()) sb.append(" DEFAULT '").append(getDefaultValue(mf)).append('\''); } } sb.append(','); } // 创建主键 List<MappingField> pks = en.getPks(); if (!pks.isEmpty()) { sb.append('\n'); sb.append( String.format( "CONSTRAINT %s_pkey PRIMARY KEY (", en.getTableName().replace('.', '_').replace('"', '_'))); for (MappingField pk : pks) { sb.append(pk.getColumnName()).append(','); } sb.setCharAt(sb.length() - 1, ')'); sb.append("\n "); } // 结束表字段设置 sb.setCharAt(sb.length() - 1, ')'); // 执行创建语句 dao.execute(Sqls.create(sb.toString())); // 创建索引 dao.execute(createIndexs(en).toArray(new Sql[0])); // 创建关联表 createRelation(dao, en); // 添加注释(表注释与字段注释) addComment(dao, en); return true; }
/** * @return 获得外覆类 * @throws RuntimeException 如果当前类型不是原生类型,则抛出 */ public Class<?> getWrapperClass() { if (!klass.isPrimitive()) { if (this.isPrimitiveNumber() || this.is(Boolean.class) || this.is(Character.class)) return klass; throw Lang.makeThrow("Class '%s' should be a primitive class", klass.getName()); } // TODO 用散列能快一点 if (is(int.class)) return Integer.class; if (is(char.class)) return Character.class; if (is(boolean.class)) return Boolean.class; if (is(long.class)) return Long.class; if (is(float.class)) return Float.class; if (is(byte.class)) return Byte.class; if (is(short.class)) return Short.class; if (is(double.class)) return Double.class; throw Lang.makeThrow("Class [%s] has no wrapper class!", klass.getName()); }
/** * 根据Type生成Mirror, 如果type是 {@link ParameterizedType} 类型的对象<br> * 可以使用 getGenericsTypes() 方法取得它的泛型数组 * * @param type * @return */ @SuppressWarnings({"unchecked"}) public static <T> Mirror<T> me(Type type) { if (null == type) { return null; } Mirror<T> mir = (Mirror<T>) Mirror.me(Lang.getTypeClass(type)); mir.type = type; return mir; }
public static String encode(Object s) { if (null == s) return ""; try { // Fix issue 283, 按照“茶几”的意见再次修改 return URLEncoder.encode(s.toString(), Encoding.CHARSET_UTF8.name()); } catch (UnsupportedEncodingException e) { throw Lang.wrapThrow(e); } }
/** * 将一段文本全部写入一个writer。 * * <p><b style=color:red>注意</b>,它会关闭输出流 * * @param writer 输出流 * @param cs 文本 */ public static void writeAndClose(Writer writer, CharSequence cs) { try { write(writer, cs); } catch (IOException e) { throw Lang.wrapThrow(e); } finally { safeClose(writer); } }
/** * 子类复写:修改 get 后的值,以便设置给 DBObject * * <p>如果不是严格检查的话, adaptor 如果发现自己不能接受这个类型,则可以直接返回输入的对象 * * @param val get 后的值 * @param check 是否严格检查 * @return 修改 get 后的值,这个值是 ejecting 从对象中取出的 */ public Object adaptForGet(Object val, boolean check) { if (null != val && CoIdType.DEFAULT == field.getIdType() && !(val instanceof ObjectId)) { String s = val.toString(); if (!Mongos.isDefaultMongoId(s)) throw Lang.makeThrow("Expect Mongo ID format, but is was '%s'", s); return new ObjectId(s); } return val; }