作者存档
2018一月21

Elasticsearch 6.1.2 (二)分页查询、排序、关键词查询,集合beetl实现前台展示

后台代码,自定义tag:

package cn.wizzer.app.web.modules.tags;

import cn.wizzer.app.web.commons.ex.elasticsearch.EsService;
import cn.wizzer.app.web.commons.utils.YcDateUtil;
import cn.wizzer.app.ycold.modules.services.YcoldInquiryService;
import cn.wizzer.framework.page.Pagination;
import org.apache.commons.lang3.BooleanUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.math.NumberUtils;
import org.beetl.core.GeneralVarTagBinding;
import org.elasticsearch.action.search.SearchRequestBuilder;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.action.search.SearchType;
import org.elasticsearch.common.text.Text;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.elasticsearch.search.sort.SortOrder;
import org.nutz.ioc.impl.PropertiesProxy;
import org.nutz.ioc.loader.annotation.Inject;
import org.nutz.ioc.loader.annotation.IocBean;
import org.nutz.lang.Strings;
import org.nutz.lang.Times;
import org.nutz.log.Log;
import org.nutz.log.Logs;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * Created by wizzer on 2018/1/20.
 */
@IocBean
public class YcoldInquiryListTag extends GeneralVarTagBinding {
    private final static Log log = Logs.get();
    @Inject
    private EsService esService;
    @Inject
    private YcoldInquiryService ycoldInquiryService;
    @Inject
    private PropertiesProxy cfg;

    @Override
    public void render() {
        String startDate = Strings.sNull(this.getAttributeValue("startDate"));
        String endDate = Strings.sNull(this.getAttributeValue("endDate"));
        String keyword = Strings.sNull(this.getAttributeValue("keyword"));
        int pageNumber = NumberUtils.toInt(Strings.sNull(this.getAttributeValue("pageNumber")), 1);
        int pageSize = NumberUtils.toInt(Strings.sNull(this.getAttributeValue("pageSize")), 10);
        boolean highlight = BooleanUtils.toBoolean(Strings.sNull(this.getAttributeValue("highlight")));
        boolean explain = BooleanUtils.toBoolean(Strings.sNull(this.getAttributeValue("explain")));
        String sortName = Strings.sNull(this.getAttributeValue("sortName"));
        String sortOrder = Strings.sNull(this.getAttributeValue("sortOrder"));
        Pagination page = new Pagination();
        page.setPageNo(pageNumber);
        page.setPageSize(pageSize);
        try {
            BoolQueryBuilder query = QueryBuilders.boolQuery();
            //根据名称查询
            if (Strings.isNotBlank(keyword)) {
                query.must(QueryBuilders.wildcardQuery("CASNM", "*" + keyword + "*"));
            }
            //截止时间大于等于现在
            query.must(QueryBuilders.rangeQuery("IQDAT").gte(Times.format("yyyyMMddHHmmss", new Date())));
            //公共日期起
            if (Strings.isNotBlank(startDate)) {
                query.must(QueryBuilders.rangeQuery("ANNODAT").gte(startDate.replaceAll("-","")));
            }
            //公共日期至
            if (Strings.isNotBlank(endDate)) {
                query.must(QueryBuilders.rangeQuery("ANNODAT").lte(endDate.replaceAll("-","")));
            }
            //几个状态条件
            query.must(QueryBuilders.matchQuery("BUYER_STS", "N"));//采购商状态
            query.must(QueryBuilders.matchQuery("STS", "A"));//状态
            query.must(QueryBuilders.matchQuery("ANNOMK", "Y"));//公告註記
            SearchRequestBuilder srb = esService.getClient().prepareSearch(cfg.get("es.index.name"))
                    .setSearchType(SearchType.DFS_QUERY_THEN_FETCH)
                    .setTypes("inquiry")
                    .setQuery(query)
                    //分页
                    .setFrom((pageNumber - 1) * pageSize).setSize(pageSize)
                    //是否按匹配度排序
                    .setExplain(explain);

            if (highlight) {
                HighlightBuilder highlightBuilder = new HighlightBuilder().field("*").requireFieldMatch(false);
                highlightBuilder.preTags("<span style=\"color:red\">");
                highlightBuilder.postTags("</span>");
                srb.highlighter(highlightBuilder);
            }
            if (Strings.isNotBlank(sortName)) {
                String[] sortNames = StringUtils.split(sortName, ",");
                if ("asc".equalsIgnoreCase(sortOrder)) {
                    for (String s : sortNames) {
                        srb.addSort(s, SortOrder.ASC);
                    }
                } else {
                    for (String s : sortNames) {
                        srb.addSort(s, SortOrder.DESC);
                    }
                }
            }
            log.debug("srb:::\r\n" + srb.toString());

            SearchResponse response = srb.execute().actionGet();
            SearchHits hits = response.getHits();
            page.setTotalCount((int) hits.getTotalHits());
            List<Map<String, Object>> list = new ArrayList<>();
            hits.forEach(searchHit -> {
                Map<String, Object> source = searchHit.getSourceAsMap();
                Map<String, HighlightField> highlightFields = searchHit.getHighlightFields();
                //name高亮
                HighlightField nameField = highlightFields.get("CASNM");
                if (nameField != null) {
                    Text[] fragments = nameField.fragments();
                    String tmp = "";
                    for (Text text : fragments) {
                        tmp += text;
                    }
                    source.put("CASNM", tmp);
                }
                source.put("IQDAT", YcDateUtil.get_yyyyMMdd_HHmm(Strings.sNull(source.get("IQDAT"))));
                source.put("ANNODAT", YcDateUtil.get_yyyyMMdd(Strings.sNull(source.get("ANNODAT"))));
                list.add(source);
            });
            page.setList(list);
        } catch (Exception e) {
            e.printStackTrace();
        }
        this.binds(page);
        this.doBodyRender();
    }
}

前台beetl页面:

  <#ycold_inquiry_list pageNumber="${pageNumber}" pageSize="${pageSize}" startDate="${startDate}" endDate="${endDate}" keyword="${keyword}" sortName="ANNODAT" sortOrder="desc" highlight="false" var="p">

    <table class="list_table_blue even_table">
        <thead>
        <tr>
            <th>公告日期</th>
            <th>案件名称</th>
            <th>交货地点</th>
            <th>报价截止日期</th>
            <th width="110">查看详细</th>
        </tr>
        </thead>
        <tbody>
        <%for(o in p.list){%>
        <tr>
            <td>${o.ANNODAT!}</td>
            <td class="l_text"><a href="${base!}/purchase/info/${o.XUID!}" target="_blank" class="td_a hide1">${o.CASNM!}</a>
            </td>
            <td class="l_text">${o.DLSITE!}</td>
            <td>${o.IQDAT!}</td>
            <td><a href="${base!}/purchase/info/${o.XUID!}" target="_blank" class="more_a png"></a></td>
        </tr>
        <%}%>
        </tbody>
    </table>
    <%if(p.totalCount>1){%>
    <div class="page round_s_a"></div>
    <script type="text/javascript">
        $(function () {
            $(".page").createPage({
                pageCount: ${p.totalPage},
                totalCount: ${p.totalCount},
                current: ${p.pageNo},
                backFn: function (p) {
                    window.location.href = "?page=" + p + "&size=${p.pageSize}";
                }
            });
        });
    </script>
    <%}%>
2018一月21

Elasticsearch 6.1.2 (一)中文分词设置、字符串字段排序设置

if (!esService.isExistsType(cfg.get("es.index.name"), type)) {
                //初始化索引表
                XContentBuilder mapping = jsonBuilder().startObject()
                        .startObject(type)
                        .startObject("_all")//设置IK分词
                        .field("analyzer", "ik_max_word")
                        .field("search_analyzer", "ik_max_word")
                        .field("term_vector", "no")
                        .field("store", "false")
                        .endObject()
                        .startObject("properties")
                        .startObject("CASNM").field("type", "text").field("analyzer", "ik_max_word").endObject()
                        .startObject("IQDAT").field("type", "text").field("index", "true").field("fielddata","true").endObject()
                        .startObject("ANNODAT").field("type", "text").field("index", "true").field("fielddata","true").endObject()
                        .endObject()
                        .endObject()
                        .endObject();
                esService.putMapping(cfg.get("es.index.name"), "inquiry", mapping);
            }

    /**
     * @param indexName 索引名
     * @param type      数据类型(表名)
     * @param mapping   mapping对象
     */
    public boolean putMapping(String indexName, String type, XContentBuilder mapping) {
        PutMappingRequest mappingRequest = Requests.putMappingRequest(indexName).type(type).source(mapping);
        PutMappingResponse response = getClient().admin().indices().putMapping(mappingRequest).actionGet();
        return response.isAcknowledged();
    }

.field(“fielddata”,”true”) //text字段默认不允许排序,是单独设置数据格式

2017七月4

分享:微信电子导航DEMO

后台JAVA代码:

 

package cn.wizzer.app.web.modules.controllers.front.wx;

import cn.wizzer.app.web.commons.base.Globals;
import cn.wizzer.app.wx.modules.services.WxAddressService;
import cn.wizzer.app.wx.modules.services.WxConfigService;
import org.nutz.dao.Cnd;
import org.nutz.ioc.loader.annotation.Inject;
import org.nutz.ioc.loader.annotation.IocBean;
import org.nutz.json.Json;
import org.nutz.lang.Lang;
import org.nutz.lang.Strings;
import org.nutz.lang.util.NutMap;
import org.nutz.log.Log;
import org.nutz.log.Logs;
import org.nutz.mvc.annotation.At;
import org.nutz.mvc.annotation.Ok;
import org.nutz.weixin.at.impl.MemoryJsapiTicketStore;
import org.nutz.weixin.spi.WxApi2;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

/**
 * Created by wizzer on 2017/6/27.
 */
@IocBean
@At("/public/wx/add")
public class AddController {
    private static final Log log = Logs.get();
    @Inject
    private WxConfigService wxConfigService;
    @Inject
    private WxAddressService wxAddressService;

    @At("/index/?")
    @Ok("beetl:/public/add/index.html")
    public void index(String wxid,HttpServletRequest req, HttpSession session) {
        WxApi2 wxApi2 = wxConfigService.getWxApi2(wxid);
        if (Lang.isEmpty(Globals.memoryJsapiTicketStore.get(wxid))) {
            Globals.memoryJsapiTicketStore.put(wxid, new MemoryJsapiTicketStore());
        }
        MemoryJsapiTicketStore memoryJsapiTicketStore = Globals.memoryJsapiTicketStore.get(wxid);
        wxApi2.setJsapiTicketStore(memoryJsapiTicketStore);
        String url = "http://" + Globals.AppDomain + Globals.AppBase + "/public/wx/add/index/"+wxid;
        NutMap jsConfig = wxApi2.genJsSDKConfig(url, "getLocation");

        req.setAttribute("list", wxAddressService.query(Cnd.orderBy().asc("opAt")));
        req.setAttribute("jsConfig", Json.toJson(jsConfig));
    }
}

前台代码:

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>电子导航</title>

    <link rel="stylesheet" type="text/css" href="${base!}/assets/public/wx/add/css/css.css"/>
    <link rel="stylesheet" href="${base!}/assets/public/wx/add/css/zepto.mdatetimer.css">
    <meta content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0" name="viewport"/>
    <meta content="yes" name="apple-mobile-web-app-capable"/>
    <meta content="black" name="apple-mobile-web-app-status-bar-style"/>
    <meta name="format-detection" content="telephone=no"/>
    <meta name="format-detection" content="email=no"/>
    <meta name="msapplication-tap-highlight" content="no">
    <meta charset="utf-8">
    <script type="text/javascript">
        var base = '${base!}';
    </script>
    <script type="text/javascript" src="${base!}/assets/public/wx/add/js/zepto.js"></script>
    <script type="text/javascript" src="${base!}/assets/public/wx/add/js/zepto.mdatetimer.js"></script>
    <script src="https://res.wx.qq.com/open/js/jweixin-1.0.0.js"></script>

</head>
<body>
<header class="ds-head">
    <h1>公司检索</h1>
</header>
<div class="time">
    <div class="time-li round-a"><span>公司名称:</span><input id="name"  type="text"
                                                          value=""/></div>
    <div class="btn"><input id="btn" type="button" value="立即查询" class="round-a"/></div>

    <div class="time-li round-a"><span>当前位置:</span><input id="longitude"  type="text"
                                                          value="" readonly/><input id="latitude"  type="text"
                                                                                    value="" readonly/></div>
</div>
<ul class="earn">
    <%for(o in list){%>
    <li class="earn-li">
        <dl>
            <dt class="cf2"><span class="earn-lil">${oLP.index}、${o.name} </span></dt>
            <dd class="cf2"><span class="earn-lil">lng:${o.lng}, lat:${o.lat}</span></dd>
            <dd class="cf2">
                <span><button onclick="goTo('walk','${o.name}','${o.lng}','${o.lat}');">步行</button></span>
                <span><button onclick="goTo('drive','${o.name}','${o.lng}','${o.lat}');">驾车</button></span>
                </dd>
            </dl>
        </li>
    <%}elsefor{%>
    没有检索到结果
    <%}%>
</ul>
<script language="JavaScript">
    function goTo(type,name,lng,lat) {
        var longitude=$("#longitude").val();
        var latitude=$("#latitude").val();
        window.location.href="http://apis.map.qq.com/uri/v1/routeplan?type="+type+"&from=我的位置&fromcoord="+latitude+","+longitude+"&to="+name+"&tocoord="+lat+","+lng+"&policy=1&referer=电子导航";

    //window.location.href="http://api.map.baidu.com/direction?origin=latlng:"+latitude+","+longitude+"|name:我的位置&destination=latlng:"+lat+","+lng+"|name:"+name+"&mode=driving&region=合肥&output=html&src=电子导航";
    }
    wx.config(${jsConfig});
    wx.ready(function(){
        wx.getLocation({
            type: 'gcj02', // 默认为wgs84的gps坐标,如果要返回直接给openLocation用的火星坐标,可传入'gcj02'
            success: function (res) {
                var latitude = res.latitude; // 纬度,浮点数,范围为90 ~ -90
                var longitude = res.longitude; // 经度,浮点数,范围为180 ~ -180。
                var speed = res.speed; // 速度,以米/每秒计
                var accuracy = res.accuracy; // 位置精度
                $("#latitude").val(latitude);
                $("#longitude").val(longitude);
            }
        });
    });
</script>
</body>
</html>
2017三月23

NutzWk: 微信AccessToken没有持久化造成超出调用限制的问题解决

1、wx_config 实体类添加三个字段,对应的表结构也要手动修改:


    @Column
    @Comment("access_token")
    @ColDefine(type = ColType.VARCHAR, width = 255)
    private String access_token;

    @Column
    @Comment("access_token_expires")
    @ColDefine(type = ColType.INT)
    private Integer access_token_expires;

    @Column
    @Comment("access_token_lastat")
    @ColDefine(type = ColType.VARCHAR, width = 50)
    private String access_token_lastat;

    get  set ...方法生成出来

2、nutzwx版本升级为1.r.61-SNAPSHOT

        <dependency>
            <groupId>org.nutz</groupId>
            <artifactId>nutzwx</artifactId>
            <version>1.r.61-SNAPSHOT</version>
        </dependency>


3、nutz版本升级为1.r.60

        <dependency>
            <groupId>org.nutz</groupId>
            <artifactId>nutz</artifactId>
            <version>1.r.60</version>
        </dependency>

4、WxConfigService 类getWxApi2替换为如下代码(主要是DaoAccessTokenStore从数据库取access_token)

    public WxApi2 getWxApi2(String wxid) {
        Wx_config appInfo = this.fetch(Cnd.where("id", "=", wxid));
        DaoAccessTokenStore myDaoAccessTokenStore = new DaoAccessTokenStore(dao());
        Map<String, Object> params = new HashMap<>();
        params.put("id", appInfo.getId());
        myDaoAccessTokenStore.setTableAccessToken("access_token");
        myDaoAccessTokenStore.setTableAccessTokenExpires("access_token_expires");
        myDaoAccessTokenStore.setTableAccessTokenLastat("access_token_lastat");
        myDaoAccessTokenStore.setFetch("select access_token,access_token_expires,access_token_lastat from wx_config where id=@id");
        myDaoAccessTokenStore.setUpdate("update wx_config set access_token=@access_token, access_token_expires=@access_token_expires, access_token_lastat=@access_token_lastat where id=@id");
        myDaoAccessTokenStore.setParams(params);
        WxApi2Impl wxApi2 = new WxApi2Impl();
        wxApi2.setAppid(appInfo.getAppid());
        wxApi2.setAppsecret(appInfo.getAppsecret());
        wxApi2.setEncodingAesKey(appInfo.getEncodingAESKey());
        wxApi2.setToken(appInfo.getToken());
        wxApi2.setAccessTokenStore(myDaoAccessTokenStore);
        return wxApi2;
    }
2017三月17

log4j 换成 logback 注意事项

pom.xml

 

<dependency>  
    <groupId>ch.qos.logback</groupId>  
    <artifactId>logback-classic</artifactId>  
    <version>1.2.2</version>  
</dependency>  
<dependency>  
    <groupId>org.logback-extensions</groupId>  
    <artifactId>logback-ext-spring</artifactId>  
    <version>0.1.4</version>  
</dependency>  
<dependency>  
    <groupId>org.slf4j</groupId>  
    <artifactId>jcl-over-slf4j</artifactId>  
    <version>1.7.25</version>  
</dependency>
<dependency>  
    <groupId>org.slf4j</groupId>  
    <artifactId>log4j-over-slf4j</artifactId>  
    <version>1.7.25</version>  
</dependency>

 

排除其他包的log4j引用,特别是dubbo的、shiro的

 

        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>dubbo</artifactId>
            <version>2.8.4</version>
            <exclusions>
                <exclusion>
                    <groupId>log4j</groupId>
                    <artifactId>log4j</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
        <dependency>
            <groupId>javax.ws.rs</groupId>
            <artifactId>javax.ws.rs-api</artifactId>
            <version>2.0</version>
            <exclusions>
                <exclusion>
                    <groupId>log4j</groupId>
                    <artifactId>log4j</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
        <dependency>
            <groupId>org.apache.shiro</groupId>
            <artifactId>shiro-ehcache</artifactId>
            <version>1.3.2</version>
            <exclusions>
                <exclusion>
                    <groupId>log4j</groupId>
                    <artifactId>log4j</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
        <dependency>
            <groupId>org.apache.shiro</groupId>
            <artifactId>shiro-web</artifactId>
            <version>1.3.2</version>
            <exclusions>
                <exclusion>
                    <groupId>log4j</groupId>
                    <artifactId>log4j</artifactId>
                </exclusion>
            </exclusions>
        </dependency>

配置文件:

<?xml version="1.0" encoding="UTF-8"?>

<!-- For assistance related to logback-translator or configuration  -->
<!-- files in general, please contact the logback user mailing list -->
<!-- at http://www.qos.ch/mailman/listinfo/logback-user             -->
<!--                                                                -->
<!-- For professional support please see                            -->
<!--    http://www.qos.ch/shop/products/professionalSupport         -->
<!--                                                                -->
<configuration>
    <appender name="Console" class="ch.qos.logback.core.ConsoleAppender">
        <file>/monitor.log</file>

        <!-- Policy定义如何滚动,按文件大小滚动生成日志 -->
        <!-- 如果是按文件大小滚动生成日志,前面的file标签可省略,而使用fileNamePattern标签定义的名字 -->
        <rollingPolicy class="ch.qos.logback.core.rolling.FixedWindowRollingPolicy">
            <fileNamePattern>/monitor.%i.log.gz
            </fileNamePattern>
            <!-- 归档日志的下标,替换fileNamePattern的%i,最多3个归档文件 -->
            <minIndex>1</minIndex>
            <maxIndex>5</maxIndex>
        </rollingPolicy>

        <!-- triggeringPolicy定义什么时候滚动,下面是定义了文件大小超过100M的时候产生归档文件 -->
        <triggeringPolicy
                class="ch.qos.logback.core.rolling.SizeBasedTriggeringPolicy">
            <maxFileSize>300MB</maxFileSize>
        </triggeringPolicy>

        <!-- append是否接着上次写文件结尾继续写,默认为true -->
        <append>true</append>
        <encoding>GBK</encoding>

        <!-- layout,定义格式 -->
        <layout class="ch.qos.logback.classic.PatternLayout">
            <pattern>[%-5level] %d{HH:mm:ss.SSS} [%thread] %logger %caller{2} - %msg%n</pattern>
        </layout>
    </appender>
    <logger name="org.springframework" level="info"/>
    <logger name="org.nutz.dao" level="debug"/>
    <logger name="net.sf.ehcache" level="info"/>
    <logger name="druid.sql" level="info"/>
    <logger name="com.alibaba.druid" level="info"/>
    <logger name="org.apache.shiro" level="info"/>
    <logger name="org.quartz" level="info"/>
    <root level="debug">
        <appender-ref ref="Console"/>
    </root>
</configuration>
2017三月8

怀孕

“医生,你得救救我们啊,我们在一起三年了都没有怀孕,父母还等着抱孙子呢!”医生:“这我也没办法啊,这都是你们自己的问题。”“不行啊,医生你帮帮我们吧。”医生:“首先,你们得各自找个女朋友。”

2017一月12

培训班

记得初入公司时,写的代码乱七八糟,错误百出,bug连连,不仅项目经理骂我,其他同事也对我怨声载道。后来听朋友介绍,就报了一个培训班。经过1个月的刻苦学习,终于功夫不负有心人啊—他们都骂不过我了。

2016十二月17

女上司

我们单位来了个女上司,长的还算过的去,很凶,在单位经常欺负我们。。同事们就怂恿单身的我追求她,然后报复她,欺负她,在同事们的多方帮助下,不出一个月,我把女上司就追到手了。。。从此,我不但在单位受她欺负,到了家还受她欺负。 ……

2016十二月8

Nutz:组合查询、子查询示例代码

        Cnd cnd = Cnd.NEW();
        if (!Strings.isBlank(src)) {
            cnd.and("srcFrom", "=", src);
        }
        if (!Strings.isBlank(name)) {
            String[] n = StringUtils.split(name, " ");
            SqlExpressionGroup group = new SqlExpressionGroup();
            for (String s : n) {
                SqlExpression sqlExpression = Cnd.exp("srcName", "like", "%" + s + "%");
                group.or(sqlExpression);
            }
            cnd.and(group);
        }
        cnd.and(Cnd.exps("productSku", "=", "").or("productSku", "is", null));
2016十二月8

石头

你认为大禹三过家门而不入真的什么都没干吗?不要忘了,他媳妇后来变成望夫石了,而孙悟空是石头里蹦出来的,关键是,大禹的定海神针还听孙悟空的话,你认为孙悟空当年定住了七仙女,什么都没有干吗?想想葫芦娃,正好七个,合在一起能变成石头…石头….