Java Code Examples for com.jfinal.kit.LogKit#error()

The following examples show how to use com.jfinal.kit.LogKit#error() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: HttpRequest.java    From sdb-mall with Apache License 2.0 6 votes vote down vote up
public synchronized static String postData(String url) throws Exception {
       CloseableHttpClient httpclient = HttpClients.createDefault();
       HttpPost httpPost = new HttpPost(url);
       CloseableHttpResponse response = httpclient.execute(httpPost);
       String result = "";
       try {
           StatusLine statusLine = response.getStatusLine();
           HttpEntity entity = response.getEntity();
           // do something useful with the response body
           if (entity != null) {
               result = EntityUtils.toString(entity, "UTF-8");
           }else{
               LogKit.error("httpRequest postData2 error entity = null code = "+statusLine.getStatusCode());
           }
           // and ensure it is fully consumed
           //消耗掉response
           EntityUtils.consume(entity);
       } finally {
           response.close();
       }

       return result;
}
 
Example 2
Source File: AddonUtil.java    From jpress with GNU Lesser General Public License v3.0 6 votes vote down vote up
private static String readString(InputStream stream) {
    ByteArrayOutputStream baos = null;
    try {
        baos = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];
        for (int len = 0; (len = stream.read(buffer)) > 0; ) {
            baos.write(buffer, 0, len);
        }
        return new String(baos.toByteArray(), JFinal.me().getConstants().getEncoding());
    } catch (Exception e) {
        LogKit.error(e.toString(), e);
    } finally {
        CommonsUtils.quietlyClose(baos);
    }
    return null;
}
 
Example 3
Source File: AddonUtil.java    From jpress with GNU Lesser General Public License v3.0 6 votes vote down vote up
public static AddonInfo readAddonInfo(File addonFile) {
    AddonInfo addonInfo = addonInfoCache.get(addonFile.getAbsolutePath());
    if (addonInfo == null) {
        addonInfo = readSimpleAddonInfo(addonFile);
        if (addonInfo == null) {
            return null;
        }
        AddonClassLoader classLoader = null;
        try {
            classLoader = new AddonClassLoader(addonInfo);
            List<String> classNameList = classLoader.getClassNameList();
            for (String className : classNameList) {
                EhcacheManager.addMapping(className, classLoader);
            }
            classLoader.load();
        } catch (IOException e) {
            LogKit.error(e.toString(), e);
        } finally {
            //必须关闭,在Windows下才能卸载插件的时候删除jar包
            //否则一旦被 AddonClassLoader load之后,无法被删除
            CommonsUtils.quietlyClose(classLoader);
        }
        addonInfoCache.put(addonFile.getAbsolutePath(), addonInfo);
    }
    return addonInfo;
}
 
Example 4
Source File: SeoManager.java    From jpress with GNU Lesser General Public License v3.0 6 votes vote down vote up
private void doPushOrUpdate(boolean pushAction, String... urls) {
    if (urls == null || urls.length == 0) {
        return;
    }

    boolean baiduRealTimePushEnable = JPressOptions.getAsBool("seo_baidu_realtime_push_enable");
    if (!baiduRealTimePushEnable) {
        return;
    }

    String site = JPressOptions.get("seo_baidu_realtime_push_site");
    String token = JPressOptions.get("seo_baidu_realtime_push_token");
    if (!StrUtil.areNotEmpty(site, token)) {
        LogKit.error("site or token is empty , can not update to baidu");
        return;
    }

    String[] newUrls = appendDomainIfNecessary(urls);
    if (pushAction) {
        fixedThreadPool.execute(() -> BaiduSeoProcesser.push(site, token, newUrls));
    } else {
        fixedThreadPool.execute(() -> BaiduSeoProcesser.update(site, token, newUrls));
    }
}
 
Example 5
Source File: JPressInterceptor.java    From jpress with GNU Lesser General Public License v3.0 6 votes vote down vote up
@Override
public void intercept(Invocation inv) {

    Controller controller = inv.getController();

    //方便模板开发者直接在模板里接收参数
    controller.setAttr("C", controller);
    controller.setAttr("CDN", JPressOptions.getCDNDomain());
    controller.setAttr(ADDON_PATH_KEY, ADDON_PATH_VALUE);

    Enumeration<String> paraKeys = controller.getParaNames();
    if (paraKeys != null) {
        while (paraKeys.hasMoreElements()) {
            String key = paraKeys.nextElement();
            // 有很多 options 字段的 model,为了扩展 model 本身的内容
            // 为了安全起见,不让客户端提交 .options 对 model 本身的 options 字段进行覆盖
            if (key != null && key.endsWith(".options")) {
                LogKit.error("paras has options key :" + key);
                controller.renderError(404);
                return;
            }
        }
    }

    inv.invoke();
}
 
Example 6
Source File: JbootCoreConfig.java    From jboot with Apache License 2.0 6 votes vote down vote up
@Override
public void onStop() {
    Enumeration<Driver> drivers = DriverManager.getDrivers();
    if (drivers != null) {
        while (drivers.hasMoreElements()) {
            try {
                Driver driver = drivers.nextElement();
                DriverManager.deregisterDriver(driver);
            } catch (Exception e) {
                LogKit.error(e.toString(), e);
            }
        }
    }
    JbootAppListenerManager.me().onStop();
    JbootScheduleManager.me().stop();
    JbootSeataManager.me().stop();
    JbootrpcManager.me().stop();
}
 
Example 7
Source File: FileUtil.java    From jboot with Apache License 2.0 6 votes vote down vote up
public static String readString(File file) {
    ByteArrayOutputStream baos = null;
    FileInputStream fis = null;
    try {
        fis = new FileInputStream(file);
        baos = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];
        for (int len = 0; (len = fis.read(buffer)) > 0; ) {
            baos.write(buffer, 0, len);
        }
        return new String(baos.toByteArray(), JFinal.me().getConstants().getEncoding());
    } catch (Exception e) {
        LogKit.error(e.toString(), e);
    } finally {
        close(fis, baos);
    }
    return null;
}
 
Example 8
Source File: CookieUtil.java    From jboot with Apache License 2.0 6 votes vote down vote up
public static String get(Controller ctr, String key, String secretKey) {
    String cookieValue = ctr.getCookie(key);

    if (cookieValue == null) {
        return null;
    }

    try {
        String value = new String(Base64Kit.decode(cookieValue));
        return getFromCookieInfo(secretKey, value);
    }

    //倘若 cookie 被人为修改的情况下能会出现异常情况
    catch (Exception ex) {
        LogKit.error(ex.toString(), ex);
    }

    return null;
}
 
Example 9
Source File: HttpRequest.java    From sdb-mall with Apache License 2.0 6 votes vote down vote up
public synchronized static String postData(String url, Map<String, String> params) throws Exception {
       CloseableHttpClient httpclient = HttpClients.createDefault();
    HttpPost httpPost = new HttpPost(url);
	//拼接参数
	List<NameValuePair> nvps = new ArrayList<NameValuePair>();

       NameValuePair[] nameValuePairArray = assembleRequestParams(params);
       for (NameValuePair value:nameValuePairArray
            ) {
           nvps.add(value);
       }

       httpPost.setEntity(new UrlEncodedFormEntity(nvps, "UTF-8"));
	CloseableHttpResponse response = httpclient.execute(httpPost);
       String result = "";
       try {
           StatusLine statusLine = response.getStatusLine();
		HttpEntity entity = response.getEntity();
           // do something useful with the response body
           if (entity != null) {
               result = EntityUtils.toString(entity, "UTF-8");
           }else{
               LogKit.error("httpRequest postData1 error entity = null code = "+statusLine.getStatusCode());
           }
		// and ensure it is fully consumed
		//消耗掉response
		EntityUtils.consume(entity);
	} finally {
		response.close();
	}

	return result;
}
 
Example 10
Source File: FileUtil.java    From jboot with Apache License 2.0 5 votes vote down vote up
public static void close(Closeable... closeable) {
    if (closeable != null || closeable.length != 0) {
        for (Closeable c : closeable) {
            if (c != null) {
                try {
                    c.close();
                } catch (IOException e) {
                    LogKit.error(e.toString(), e);
                }
            }
        }
    }
}
 
Example 11
Source File: _WechatArticleImport.java    From jpress with GNU Lesser General Public License v3.0 5 votes vote down vote up
private static void doDownload(String url) {

            String remoteUrl = url.startsWith("/attachment/s")
                    ?url.replace("/attachment/s","https://")
                    :url.replace("/attachment/", "http://");

            remoteUrl = replaceLast(remoteUrl, "__", "/")
                    .replace(".png?","?");

            String path = URI.create(url).getPath();
            File downloadToFile = AttachmentUtils.file(path);
            if (downloadToFile.exists() && downloadToFile.length() > 0) {
                return;
            }

            JbootHttpRequest request = JbootHttpRequest.create(remoteUrl);
            request.setDownloadFile(downloadToFile);

            JbootHttpResponse response = HttpUtil.handle(request);
            if (response.isError()) {
                LogKit.error("download attachment error by url:" + remoteUrl);
                return;
            }

            Attachment attachment = new Attachment();
            attachment.setMimeType(response.getContentType());
            attachment.setPath(path);
            attachment.setSuffix(FileUtil.getSuffix(path));
            attachment.setTitle(downloadToFile.getName());
            attachment.save();
        }
 
Example 12
Source File: AliyunOssUtils.java    From jpress with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * 同步本地文件到阿里云OSS
 *
 * @param path
 * @param file
 * @return
 */
public static boolean uploadsync(String path, File file) {

    boolean enable = JPressOptions.getAsBool(KEY_ENABLE);

    if (!enable || StrUtil.isBlank(path)) {
        return false;
    }

    path = removeFileSeparator(path);
    path = path.replace('\\', '/');

    String ossBucketName = JPressOptions.get(KEY_BUCKETNAME);
    OSSClient ossClient = createOSSClient();

    try {
        ossClient.putObject(ossBucketName, path, file);
        boolean success = ossClient.doesObjectExist(ossBucketName, path);
        if (!success) {
            LogKit.error("aliyun oss upload error! path:" + path + "\nfile:" + file);
        }
        return success;

    } catch (Throwable e) {
        log.error("aliyun oss upload error!!!", e);
        return false;
    } finally {
        ossClient.shutdown();
    }
}
 
Example 13
Source File: TemplateRender.java    From jpress with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Override
public void render() {
    response.setContentType(getContentType());
    if (errorCode > 0) {
        response.setStatus(errorCode);
    }

    Map<Object, Object> data = new HashMap<>();
    for (Enumeration<String> attrs = request.getAttributeNames(); attrs.hasMoreElements(); ) {
        String attrName = attrs.nextElement();
        data.put(attrName, request.getAttribute(attrName));
    }

    com.jfinal.template.Template template = null;
    try {
        template = getEngine().getTemplate(view);
    } catch (RuntimeException ex) {
        if (ex.getMessage().contains("File not found")) {
            RenderHelpler.renderHtml(response, buildTemplateNotExistsMessage(), contentType);
            LogKit.error(ex.toString(), ex);
        } else {
            throw ex;
        }
    }

    RenderHelpler.renderHtml(response, buildNormalHtml(template.renderToString(data)), contentType);
}
 
Example 14
Source File: AddonManager.java    From jpress with GNU Lesser General Public License v3.0 5 votes vote down vote up
private List<com.jfinal.plugin.activerecord.Table> getTableList(ActiveRecordPlugin arp) {
    try {
        Field tableListField = ActiveRecordPlugin.class.getDeclaredField("tableList");
        tableListField.setAccessible(true);
        return (List<com.jfinal.plugin.activerecord.Table>) tableListField.get(arp);
    } catch (Exception ex) {
        LogKit.error(ex.toString(), ex);
    }
    return null;
}
 
Example 15
Source File: AttachmentDownloader.java    From jpress with GNU Lesser General Public License v3.0 5 votes vote down vote up
private static void doDownload(Attachment attachment) {

        if (attachment.isLocal()) {
            return;
        }

        String url = attachment.getPath();
        if (StrUtil.isBlank(url)) {
            return;
        }

        String path = "/attachment" + URI.create(url).getPath();

        File downloadToFile = AttachmentUtils.file(path);

        JbootHttpRequest request = JbootHttpRequest.create(url);
        request.setDownloadFile(downloadToFile);

        JbootHttpResponse response = HttpUtil.handle(request);
        if (response.isError()) {
            LogKit.error("download attachment error by url:" + url);
            return;
        }

        attachment.setMimeType(response.getContentType());
        attachment.setPath(path);
        attachment.update();

    }
 
Example 16
Source File: _AttachmentController.java    From jpress with GNU Lesser General Public License v3.0 5 votes vote down vote up
public String getPermission() {
    try {
        PosixFileAttributeView posixView = Files.getFileAttributeView(Paths.get(file.toURI()), PosixFileAttributeView.class);
        if (posixView != null) {
            PosixFileAttributes attrs = posixView.readAttributes();
            if (attrs != null) {
                return PosixFilePermissions.toString(attrs.permissions());
            }
        }
    } catch (Exception e) {
        LogKit.error(e.toString(), e);
    }
    return "";
}
 
Example 17
Source File: ArticleServiceProvider.java    From jpress with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Override
public Page<Article> search(String queryString, int pageNum, int pageSize) {
    try {
        ArticleSearcher searcher = ArticleSearcherFactory.getSearcher();
        Page<Article> page = searcher.search(queryString, pageNum, pageSize);
        if (page != null) {
            return page;
        }
    } catch (Exception ex) {
        LogKit.error(ex.toString(), ex);
    }
    return new Page<>(new ArrayList<>(), pageNum, pageSize, 0, 0);
}
 
Example 18
Source File: PayController.java    From jpress with GNU Lesser General Public License v3.0 5 votes vote down vote up
private boolean tryVerify(PayService payService, Map<String, Object> params) {
    try {
        return payService.verify(params);
    } catch (Exception ex) {
        LogKit.error(ex.toString(), ex);
    }
    return false;
}
 
Example 19
Source File: _MarkdownImport.java    From jpress with GNU Lesser General Public License v3.0 4 votes vote down vote up
public void doMarkdownImport() {

        UploadFile ufile = getFile();
        if (ufile == null) {
            renderJson(Ret.fail("message", "您还未选择Markdown文件"));
            return;
        }

        if (!".md".equals(FileUtil.getSuffix(ufile.getFileName()))) {
            renderJson(Ret.fail("message", "请选择Markdown格式的文件"));
            return;
        }

        String newPath = AttachmentUtils.moveFile(ufile);
        File mdFile = AttachmentUtils.file(newPath);

        MarkdownParser markdownParser = new MarkdownParser();
        markdownParser.parse(mdFile);

        Article article = null;
        String[] categoryNames = null;

        try {
            article = markdownParser.getArticle();
            categoryNames = markdownParser.getCategories();
        } catch (ParseException e) {
            LogKit.error(e.toString(), e);
            renderJson(Ret.fail("message", "导入失败,可能markdown文件格式错误"));
        } finally {
            mdFile.delete();
        }

        if (null != article) {
            article.setUserId(getLoginedUser().getId());
            articleService.save(article);
        }

        if (null != article && null != categoryNames && categoryNames.length > 0) {
            List<ArticleCategory> categoryList = articleCategoryService.doNewOrFindByCategoryString(categoryNames);
            Long[] allIds = new Long[categoryList.size()];
            for (int i = 0; i < allIds.length; i++) {
                allIds[i] = categoryList.get(i).getId();
            }
            articleService.doUpdateCategorys(article.getId(), allIds);
        }

        renderOkJson();
    }
 
Example 20
Source File: PayController.java    From jpress with GNU Lesser General Public License v3.0 4 votes vote down vote up
/**
 * 微信手机调用js直接支付(无需扫码),参考 pay_wechatjs.html
 */
public void getWechatOrderInfo() {
    PayService service = PayConfigUtil.getWxPayService();
    if (service == null) {
        renderFailJson("微信支付未配置正确或未开启");
        return;
    }


    PaymentRecord payment = paymentService.findByTrxNo(getPara("trx"));
    if (payment == null) {
        renderFailJson("payment is null");
        return;
    }

    if (payment.isPaySuccess()) {
        renderFailJson("payment is pay success");
        return;
    }

    if (notLoginedUserModel(payment, "payer_user_id")) {
        renderFailJson("not logined user payment");
        return;
    }


    String openId = getPara("openId");
    if (StrUtil.isBlank(openId)) {
        renderFailJson("openId is null or empty.");
        return;
    }


    try {
        PayOrder order = createPayOrder(payment);
        order.setTransactionType(WxTransactionType.JSAPI);
        order.setOpenid(openId);
        renderJson(Ret.ok().set("orderInfo", service.orderInfo(order)));
        PrePayNotifytKit.notify(payment, getLoginedUser());
    } catch (Exception ex) {
        LogKit.error(ex.toString(), ex);
        renderFailJson(ex.getMessage());
    }
}