Search in sources :

Example 31 with UtilException

use of cn.hutool.core.exceptions.UtilException in project hutool by looly.

the class VelocityUtil method toWriter.

/**
 * 生成内容写到响应内容中<br>
 * 模板的变量来自于Request的Attribute对象
 *
 * @param templateFileName 模板文件
 * @param request 请求对象,用于获取模板中的变量值
 * @param response 响应对象
 */
public static void toWriter(String templateFileName, javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response) {
    final VelocityContext context = new VelocityContext();
    parseRequest(context, request);
    parseSession(context, request.getSession(false));
    Writer writer = null;
    try {
        writer = response.getWriter();
        toWriter(templateFileName, context, writer);
    } catch (Exception e) {
        throw new UtilException(e, "Write Velocity content template by [{}] to response error!", templateFileName);
    } finally {
        IoUtil.close(writer);
    }
}
Also used : VelocityContext(org.apache.velocity.VelocityContext) UtilException(cn.hutool.core.exceptions.UtilException) PrintWriter(java.io.PrintWriter) StringWriter(java.io.StringWriter) Writer(java.io.Writer) IORuntimeException(cn.hutool.core.io.IORuntimeException) UtilException(cn.hutool.core.exceptions.UtilException) NotInitedException(cn.hutool.core.exceptions.NotInitedException)

Example 32 with UtilException

use of cn.hutool.core.exceptions.UtilException in project hutool by looly.

the class ReUtil method replaceAll.

/**
 * 替换所有正则匹配的文本,并使用自定义函数决定如何替换<br>
 * replaceFun可以通过{@link Matcher}提取出匹配到的内容的不同部分,然后经过重新处理、组装变成新的内容放回原位。
 *
 * <pre class="code">
 *     replaceAll(this.content, "(\\d+)", parameters -&gt; "-" + parameters.group(1) + "-")
 *     // 结果为:"ZZZaaabbbccc中文-1234-"
 * </pre>
 *
 * @param str        要替换的字符串
 * @param pattern    用于匹配的正则式
 * @param replaceFun 决定如何替换的函数,可能被多次调用(当有多个匹配时)
 * @return 替换后的字符串
 * @since 4.2.2
 */
public static String replaceAll(CharSequence str, Pattern pattern, Func1<Matcher, String> replaceFun) {
    if (StrUtil.isEmpty(str)) {
        return StrUtil.str(str);
    }
    final Matcher matcher = pattern.matcher(str);
    final StringBuffer buffer = new StringBuffer();
    while (matcher.find()) {
        try {
            matcher.appendReplacement(buffer, replaceFun.call(matcher));
        } catch (Exception e) {
            throw new UtilException(e);
        }
    }
    matcher.appendTail(buffer);
    return buffer.toString();
}
Also used : Matcher(java.util.regex.Matcher) UtilException(cn.hutool.core.exceptions.UtilException) UtilException(cn.hutool.core.exceptions.UtilException)

Example 33 with UtilException

use of cn.hutool.core.exceptions.UtilException in project hutool by looly.

the class ReflectUtil method setFieldValue.

/**
 * 设置字段值
 *
 * @param obj   对象,如果是static字段,此参数为null
 * @param field 字段
 * @param value 值,值类型必须与字段类型匹配,不会自动转换对象类型
 * @throws UtilException UtilException 包装IllegalAccessException异常
 */
public static void setFieldValue(Object obj, Field field, Object value) throws UtilException {
    Assert.notNull(field, "Field in [{}] not exist !", obj);
    final Class<?> fieldType = field.getType();
    if (null != value) {
        if (false == fieldType.isAssignableFrom(value.getClass())) {
            // 对于类型不同的字段,尝试转换,转换失败则使用原对象类型
            final Object targetValue = Convert.convert(fieldType, value);
            if (null != targetValue) {
                value = targetValue;
            }
        }
    } else {
        // 获取null对应默认值,防止原始类型造成空指针问题
        value = ClassUtil.getDefaultValue(fieldType);
    }
    setAccessible(field);
    try {
        field.set(obj instanceof Class ? null : obj, value);
    } catch (IllegalAccessException e) {
        throw new UtilException(e, "IllegalAccess for {}.{}", obj, field.getName());
    }
}
Also used : UtilException(cn.hutool.core.exceptions.UtilException) AccessibleObject(java.lang.reflect.AccessibleObject)

Example 34 with UtilException

use of cn.hutool.core.exceptions.UtilException in project hutool by looly.

the class ReflectUtil method invoke.

/**
 * 执行方法
 *
 * <p>
 * 对于用户传入参数会做必要检查,包括:
 *
 * <pre>
 *     1、忽略多余的参数
 *     2、参数不够补齐默认值
 *     3、传入参数为null,但是目标参数类型为原始类型,做转换
 * </pre>
 *
 * @param <T>    返回对象类型
 * @param obj    对象,如果执行静态方法,此值为{@code null}
 * @param method 方法(对象方法或static方法都可)
 * @param args   参数对象
 * @return 结果
 * @throws UtilException 一些列异常的包装
 */
@SuppressWarnings("unchecked")
public static <T> T invoke(Object obj, Method method, Object... args) throws UtilException {
    setAccessible(method);
    // 检查用户传入参数:
    // 1、忽略多余的参数
    // 2、参数不够补齐默认值
    // 3、通过NullWrapperBean传递的参数,会直接赋值null
    // 4、传入参数为null,但是目标参数类型为原始类型,做转换
    // 5、传入参数类型不对应,尝试转换类型
    final Class<?>[] parameterTypes = method.getParameterTypes();
    final Object[] actualArgs = new Object[parameterTypes.length];
    if (null != args) {
        for (int i = 0; i < actualArgs.length; i++) {
            if (i >= args.length || null == args[i]) {
                // 越界或者空值
                actualArgs[i] = ClassUtil.getDefaultValue(parameterTypes[i]);
            } else if (args[i] instanceof NullWrapperBean) {
                // 如果是通过NullWrapperBean传递的null参数,直接赋值null
                actualArgs[i] = null;
            } else if (false == parameterTypes[i].isAssignableFrom(args[i].getClass())) {
                // 对于类型不同的字段,尝试转换,转换失败则使用原对象类型
                final Object targetValue = Convert.convert(parameterTypes[i], args[i]);
                if (null != targetValue) {
                    actualArgs[i] = targetValue;
                }
            } else {
                actualArgs[i] = args[i];
            }
        }
    }
    if (method.isDefault()) {
        // 代理对象情况下调用method.invoke会导致循环引用执行,最终栈溢出
        return MethodHandleUtil.invokeSpecial(obj, method, args);
    }
    try {
        return (T) method.invoke(ClassUtil.isStatic(method) ? null : obj, actualArgs);
    } catch (Exception e) {
        throw new UtilException(e);
    }
}
Also used : NullWrapperBean(cn.hutool.core.bean.NullWrapperBean) UtilException(cn.hutool.core.exceptions.UtilException) AccessibleObject(java.lang.reflect.AccessibleObject) UtilException(cn.hutool.core.exceptions.UtilException)

Example 35 with UtilException

use of cn.hutool.core.exceptions.UtilException in project hutool by looly.

the class URLUtil method toUrlForHttp.

/**
 * 将URL字符串转换为URL对象,并做必要验证
 *
 * @param urlStr  URL字符串
 * @param handler {@link URLStreamHandler}
 * @return URL
 * @since 4.1.9
 */
public static URL toUrlForHttp(String urlStr, URLStreamHandler handler) {
    Assert.notBlank(urlStr, "Url is blank !");
    // 编码空白符,防止空格引起的请求异常
    urlStr = encodeBlank(urlStr);
    try {
        return new URL(null, urlStr, handler);
    } catch (MalformedURLException e) {
        throw new UtilException(e);
    }
}
Also used : MalformedURLException(java.net.MalformedURLException) UtilException(cn.hutool.core.exceptions.UtilException) URL(java.net.URL)

Aggregations

UtilException (cn.hutool.core.exceptions.UtilException)50 IOException (java.io.IOException)19 FastByteArrayOutputStream (cn.hutool.core.io.FastByteArrayOutputStream)5 IORuntimeException (cn.hutool.core.io.IORuntimeException)5 URL (java.net.URL)5 ByteArrayInputStream (java.io.ByteArrayInputStream)3 ByteArrayOutputStream (java.io.ByteArrayOutputStream)3 File (java.io.File)3 ObjectInputStream (java.io.ObjectInputStream)3 PrintWriter (java.io.PrintWriter)3 AccessibleObject (java.lang.reflect.AccessibleObject)3 Method (java.lang.reflect.Method)3 MalformedURLException (java.net.MalformedURLException)3 SocketException (java.net.SocketException)3 HashSet (java.util.HashSet)3 CountDownLatch (java.util.concurrent.CountDownLatch)3 XPathExpressionException (javax.xml.xpath.XPathExpressionException)3 ConcurrentHashSet (cn.hutool.core.collection.ConcurrentHashSet)2 BufferedInputStream (java.io.BufferedInputStream)2 ObjectOutputStream (java.io.ObjectOutputStream)2