portal web service

WareService.java 21KB

    package com.ekexiu.portal.ware; import java.io.ByteArrayInputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.concurrent.atomic.AtomicInteger; import org.jfw.apt.annotation.Autowrie; import org.jfw.apt.annotation.DefaultValue; import org.jfw.apt.annotation.Nullable; import org.jfw.apt.web.annotation.Path; import org.jfw.apt.web.annotation.operate.Get; import org.jfw.apt.web.annotation.operate.Post; import org.jfw.apt.web.annotation.param.JdbcConn; import org.jfw.apt.web.annotation.param.RequestParam; import org.jfw.apt.web.annotation.param.Upload; import org.jfw.util.JpgUtil; import org.jfw.util.ListUtil; import org.jfw.util.PageQueryResult; import org.jfw.util.StringUtil; import org.jfw.util.io.IoUtil; import org.jfw.util.jdbc.JdbcUtil; import org.jfw.util.jdbc.PreparedStatementConfig; import org.jfw.util.jdbc.ResultSetExtractor; import org.jfw.util.web.fileupload.Item; import org.jfw.util.web.fileupload.UploadItemIterator; import com.ekexiu.portal.service.GrowthLogService; import com.ekexiu.portal.service.KeyWordService; @Path("/ware") public class WareService { private static final AtomicInteger FN_IDX = new AtomicInteger(1); private File imgPath; private int imgMaxWidth = 70; @Autowrie private GrowthLogService growthLogService; @Autowrie private KeyWordService keyWordService; @Autowrie private WareDao wareDao; public GrowthLogService getGrowthLogService() { return growthLogService; } public void setGrowthLogService(GrowthLogService growthLogService) { this.growthLogService = growthLogService; } public KeyWordService getKeyWordService() { return keyWordService; } public void setKeyWordService(KeyWordService keyWordService) { this.keyWordService = keyWordService; } public WareDao getWareDao() { return wareDao; } public void setWareDao(WareDao wareDao) { this.wareDao = wareDao; } public File getImgPath() { return imgPath; } public void setImgPath(File imgPath) { this.imgPath = imgPath; } public int getImgMaxWidth() { return imgMaxWidth; } public void setImgMaxWidth(int imgMaxWidth) { this.imgMaxWidth = imgMaxWidth; } /** * 上传文件 * * @param it * @return * @throws Exception */ @Path("/upload") @Post public List<UploadFile> upload(@Upload UploadItemIterator it) throws Exception { List<UploadFile> ret = new LinkedList<UploadFile>(); try { while (it.hasNext()) { Item item = it.next(); if (!item.isFormField()) { String name = normalizeFileName(item.getName()); int index = name.lastIndexOf('.'); String ext = index >= 0 ? name.substring(index + 1) : ""; ext = ext.trim(); long fileLen = 0; int len = 0; UploadFile uf = this.buildTargetFile(ext); uf.setName(name); File file = uf.getFn(); ret.add(uf); byte[] buf = new byte[8092]; OutputStream of = new FileOutputStream(file); try { InputStream in = item.getInputStream(); try { while ((len = in.read(buf)) >= 0) { if (len > 0) { of.write(buf, 0, len); fileLen += len; } } uf.setSize(fileLen); } finally { in.close(); } } finally { of.close(); } } } return ret; } catch (Exception e) { this.remove(ret); throw e; } finally { if (it != null) it.clean(); } } public String insert(Connection con, Ware ware, String[] professor, String[] resource) throws SQLException, IOException { String id = StringUtil.buildUUID(); ware.setId(id); wareDao.insert(con, ware); this.saveSmallImg(ware.getImages()); String[] kws = null; if (ware.getKeywords() != null) { kws = ListUtil.splitTrimExcludeEmpty(ware.getKeywords(), ',').toArray(new String[0]); } if (ware.getState().equals("1")) { keyWordService.refreshWrae(con, id, kws); } if (resource != null && resource.length > 0) { for (String rid : resource) { WareRes wr = new WareRes(); wr.setId(id); wr.setResource(rid); wareDao.insert(con, wr); } } if (professor != null && professor.length > 0) { for (String pid : professor) { WarePro wp = new WarePro(); wp.setId(id); wp.setProfessor(pid); wareDao.insert(con, wp); } } return id; } public boolean update(Connection con, Ware ware, String[] professor, String[] resource) throws SQLException, IOException { String id = ware.getId(); if (wareDao.update(con, ware) > 0) { this.saveSmallImg(ware.getImages()); String[] kws = null; if (ware.getKeywords() != null) { kws = ListUtil.splitTrimExcludeEmpty(ware.getKeywords(), ',').toArray(new String[0]); } if (ware.getState().equals("1")) { keyWordService.refreshWrae(con, id, kws); } else { keyWordService.deleteWare(con, id); } wareDao.deleteWareRes(con, id); if (resource != null && resource.length > 0) { for (String rid : resource) { WareRes wr = new WareRes(); wr.setId(id); wr.setResource(rid); wareDao.insert(con, wr); } } wareDao.deleteWarePro(con, id); if (professor != null && professor.length > 0) { for (String pid : professor) { WarePro wp = new WarePro(); wp.setId(id); wp.setProfessor(pid); wareDao.insert(con, wp); } } return true; } return false; } /** * 新增草稿状态的服务(个人) * * @param con * @param ware * @param resource * @return * @throws SQLException * @throws IOException */ @Post @Path("/draft") public String draft(@JdbcConn(true) Connection con, @RequestParam(excludeFields = { "category", "id", "state", "createTime", "modifyTime", "shareId", "pageViews", "sortFirst" }) Ware ware, @Nullable String[] resource) throws SQLException, IOException { ware.setState("2"); ware.setCategory("1"); return insert(con, ware, null, resource); } /** * 新增草稿状态的服务(企业) * * @param con * @param ware * @param resource * @param professor * @return * @throws SQLException * @throws IOException */ @Post @Path("/draft/org") public String draft(@JdbcConn(true) Connection con, @RequestParam(excludeFields = { "category", "id", "state", "createTime", "modifyTime", "shareId", "pageViews", "sortFirst" }) Ware ware, String[] resource, String[] professor) throws SQLException, IOException { ware.setState("2"); ware.setCategory("2"); return insert(con, ware, professor, resource); } /** * 新增发布状态的服务(个人) * * @param con * @param ware * @param resource * @return * @throws SQLException * @throws IOException */ @Post @Path("/publish") public String publish(@JdbcConn(true) Connection con, @RequestParam(excludeFields = { "category", "id", "state", "createTime", "modifyTime", "shareId", "pageViews", "sortFirst" }) Ware ware, String[] resource) throws SQLException, IOException { ware.setState("1"); ware.setCategory("1"); return insert(con, ware, null, resource); } /** * 新增发布状态的服务(企业) * * @param con * @param ware * @param resource * @param professor * @return * @throws SQLException * @throws IOException */ @Post @Path("/publish/org") public String publish(@JdbcConn(true) Connection con, @RequestParam(excludeFields = { "category", "id", "state", "createTime", "modifyTime", "shareId", "pageViews", "sortFirst" }) Ware ware, String[] resource, String[] professor) throws SQLException, IOException { ware.setState("1"); ware.setCategory("2"); return insert(con, ware, professor, resource); } /** * 修改为草稿状态服务(个人) * * @param con * @param ware * @param resource * @return * @throws SQLException * @throws IOException */ @Post @Path("/draft/update") public boolean updateDraft(@JdbcConn(true) Connection con, @RequestParam(excludeFields = { "category", "state", "createTime", "modifyTime", "shareId", "pageViews", "sortFirst" }) Ware ware, @Nullable String[] resource) throws SQLException, IOException { ware.setState("2"); ware.setCategory("1"); return update(con, ware, null, resource); } /** * 修改为草稿状态服务(企业) * * @param con * @param ware * @param resource * @param professor * @return * @throws SQLException * @throws IOException */ @Post @Path("/draft/org/update") public boolean updateDraft(@JdbcConn(true) Connection con, @RequestParam(excludeFields = { "category", "state", "createTime", "modifyTime", "shareId", "pageViews", "sortFirst" }) Ware ware, String[] resource, String[] professor) throws SQLException, IOException { ware.setState("2"); ware.setCategory("2"); return update(con, ware, professor, resource); } /** * 修改为发布状态服务(个人) * * @param con * @param ware * @param resource * @return * @throws SQLException * @throws IOException */ @Post @Path("/publish/update") public String updatePublish(@JdbcConn(true) Connection con, @RequestParam(excludeFields = { "category", "state", "createTime", "modifyTime", "shareId", "pageViews", "sortFirst" }) Ware ware, String[] resource) throws SQLException, IOException { ware.setState("1"); ware.setCategory("1"); return insert(con, ware, null, resource); } /** * 修改为发布状态服务(企业) * * @param con * @param ware * @param resource * @param professor * @return * @throws SQLException * @throws IOException */ @Post @Path("/publish/org/update") public String updatePublish(@JdbcConn(true) Connection con, @RequestParam(excludeFields = { "category", "state", "createTime", "modifyTime", "shareId", "pageViews", "sortFirst" }) Ware ware, String[] resource, String[] professor) throws SQLException, IOException { ware.setState("1"); ware.setCategory("2"); return insert(con, ware, professor, resource); } /** * 查询指定的服务(单个) * * @param con * @param id * @param shareId * @return * @throws SQLException */ @Get @Path("/qo") public Ware queryOne(@JdbcConn Connection con, @Nullable String id, @DefaultValue("-1") long shareId) throws SQLException { if (id != null) { return wareDao.queryById(con, id); } else { return wareDao.queryByShareId(con, shareId); } } /** * 查询指定的服务(多个) * * @param con * @param id * @param shareId * @return * @throws SQLException */ @Get @Path("/qm") public List<Ware> queryByIds(@JdbcConn Connection con, String[] id) throws SQLException { return wareDao.queryById(con, id); } @Get @Path("/pro") public List<WarePro> queryPro(@JdbcConn Connection con, String id) throws SQLException { return wareDao.queryPro(con, id); } @Get @Path("/res") public List<WareRes> queryRes(@JdbcConn Connection con, String id) throws SQLException { return wareDao.queryRes(con, id); } private static final Comparator<CountWare> CountWareComparator = new Comparator<CountWare>() { @Override public int compare(CountWare o1, CountWare o2) { int v = o1.getState().compareTo(o2.getState()); if (v == 0) { long l1 = o1.getNum(); long l2 = o2.getNum(); if (l1 == 0 && l2 != 0) { return 1; } else if (l2 == 0 && l1 != 0) { return -1; } else { return o1.getModifyTime().compareTo(o2.getModifyTime()); } } return v; } }; /** * 根据服务名称、内容、关键词查询指定企业的服务(草稿在前,按最后修改时间由新到旧排序;已发布服务在后,其中未设置联系人的在前, * 按发布时间由新到旧排序) * * @param con * @param key * @param oid * @param pageSize * @param pageNo * @return * @throws SQLException */ @Get @Path("/pq/org/search") public PageQueryResult<CountWare> pageQueryOrg(@JdbcConn Connection con, @Nullable String key, String oid, int pageSize, int pageNo) throws SQLException { if (key != null) { key = "%" + key + "%"; } final List<CountWare> list = wareDao.queryByOwner(con, key, oid); PageQueryResult<CountWare> result = new PageQueryResult<CountWare>(); if (list != null && list.size() > 0) { StringBuilder sb = new StringBuilder(); sb.append("SELECT ID,COUNT(1) FROM WARE_PRO WHERE ID IN ("); for (int i = 0; i < list.size(); ++i) { sb.append("?,"); } sb.setCharAt(sb.length() - 1, ')'); sb.append(" GROUP BY ID"); JdbcUtil.queryList(con, sb.toString(), new ResultSetExtractor<CountWare>() { @Override public CountWare extractData(ResultSet rs) throws SQLException { String id = rs.getString(1); long c = rs.getLong(2); for (CountWare cw : list) { if (cw.getId().equals(id)) { cw.setNum(c); return cw; } } return null; } }, new PreparedStatementConfig() { @Override public void config(PreparedStatement ps) throws SQLException { int i = 1; for (CountWare cw : list) { ps.setString(i++, cw.getId()); } } }); Collections.sort(list, CountWareComparator); result.setTotal(list.size()); if (pageNo == 1) { result.setPageNo(1); if (pageSize >= list.size()) { result.setData(list); } else { result.setData(list.subList(0, pageSize)); } } else if (pageNo > 1) { int _m_7 = list.size() / pageSize; if (list.size() % pageSize != 0) { ++_m_7; } if (pageNo > _m_7) { pageNo = _m_7; } result.setPageNo(pageNo); --pageNo; int begin = pageNo * pageSize - 1; int end = begin + pageSize; if (end > list.size()) { end = list.size(); } result.setData(list.subList(begin, end)); } } else { result.setTotal(0); } return result; } /** * 根据服务名称、内容、关键词查询指定个人的服务(草稿在前,按最后修改时间排序;已发布服务在后,按发布时间倒序 * * @param con * @param key * @param pid * @param pageSize * @param pageNo * @return * @throws SQLException */ @Get @Path("/pq/search") public PageQueryResult<Ware> pageQuery(@JdbcConn Connection con, @Nullable String key, String pid, int pageSize, int pageNo) throws SQLException { if (key != null) { key = "%" + key + "%"; } return wareDao.pageQuery(con, key, pid, pageSize, pageNo); } /** * 逻辑删除服务 * * @param con * @param id * @return * @throws SQLException */ @Post @Path("/delete") public int delete(@JdbcConn Connection con, String id) throws SQLException { return wareDao.logicDelete(con, id); } /** * 指定所有者下发布状态下的服务数量 * * @param con * @param category * @param owner * @return * @throws SQLException */ @Get @Path("/count/publish") public long countPublish(@JdbcConn Connection con, String category, String owner) throws SQLException { return wareDao.countPublish(con, category, owner); } /** * 指定所有者下发布状态下的服务(下拉加载,modifyTime ) * * @param con * @param category * @param owner * @param modifyTime * @param rows * @return * @throws SQLException */ @Get @Path("/publish") public List<Ware> queryPublish(@JdbcConn Connection con, String category, String owner, @DefaultValue("\"9\"") String modifyTime, int rows) throws SQLException { return wareDao.queryPublish(con, category, owner, modifyTime, rows); } @Post @Path("/incPageViews") public int incPageViews(@JdbcConn Connection con, String id) throws SQLException { return wareDao.incPageViews(con, id); } @Get @Path("/index/search") public List<Ware> indexSeach(@JdbcConn Connection con, @Nullable String key, @DefaultValue("Long.MAX_VALUE") long sortFirst, @DefaultValue("\"9\"") String time, @DefaultValue("\"G\"") String id, int rows) throws SQLException { if (key != null) { key = "%" + key + "%"; } return wareDao.indexSeach(con, key, sortFirst, time, id, rows); } @Get @Path("/ralateWare") public List<Map<String, Object>> queryRalateWare(@JdbcConn Connection con, final String id, final int rows) throws SQLException { return JdbcUtil.queryList(con, "SELECT ID,NUM FROM (SELECT ID,COUNT(1) NUM FROM WRE_KEY_WORD WEHRE ID <> ? AND KW IN (SELECT KW FROM WRE_KEY_WORD WHERE ID=?)) T ORDER BY NUM DESC LIMIT ?", new ResultSetExtractor<Map<String, Object>>() { @Override public Map<String, Object> extractData(ResultSet rs) throws SQLException { Map<String, Object> map = new HashMap<String, Object>(); map.put(rs.getString(1), rs.getLong(2)); return map; } }, new PreparedStatementConfig() { @Override public void config(PreparedStatement ps) throws SQLException { ps.setString(1, id); ps.setString(2, id); ps.setInt(3, rows); } }); } @Get @Path("/byOwnerWithPageViews") public List<Ware> queryBySameKwWithPageViews(@JdbcConn Connection con,String category,String owner,@Nullable String id,int rows) throws SQLException{ return wareDao.queryByOwnerWithPageViews(con, category, owner, id, rows); } @Get @Path("/byResourceWithModifyTime") public List<Ware> queryByResourceWithModifyTime(@JdbcConn Connection con,String id,int rows) throws SQLException{ return wareDao.queryByResource(con, id, rows); } @Get @Path("/byArticle") public List<Ware> queryByArticle(@JdbcConn Connection con,String id,@DefaultValue("Integer.MAX_VALUE" ) int rows) throws SQLException{ return wareDao.queryByArticle(con, id, rows); } // // @Post // @Path("/update") // public void update(@JdbcConn(true) Connection // con,@RequestParam(excludeFields={})) private void saveSmallImg(String imgs) throws IOException { if (imgs != null) { List<String> list = ListUtil.splitTrimExcludeEmpty(imgs, ','); if (list.size() > 0) { String oname = list.get(0); if (oname != null) { if (oname.startsWith("/")) { oname = oname.substring(1); int idx = oname.indexOf('.'); if (idx > 0) { String dname = oname.substring(0, idx) + "_s.jpg"; File dest = new File(this.imgPath, dname); if (dest.exists()) return; File src = new File(this.imgPath, oname); if (src.exists()) { byte[] obs = IoUtil.readStream(new FileInputStream(src), true); obs = JpgUtil.read(obs); FileOutputStream out = new FileOutputStream(dest); try { JpgUtil.scalingZoom(new ByteArrayInputStream(obs), out, this.imgMaxWidth); out.flush(); } finally { IoUtil.close(out); } } } } } } } } private void remove(List<UploadFile> list) { for (UploadFile file : list) { if (file.fn != null) file.fn.delete(); } } private UploadFile buildTargetFile(String ext) { StringBuilder sb = new StringBuilder(); sb.append(System.currentTimeMillis() / (1000 * 60 * 60 * 24)); File path = new File(this.imgPath, sb.toString()); if (!path.exists()) { synchronized (this) { if (!path.mkdirs()) throw new RuntimeException("mkdir error[" + path + "]"); FN_IDX.set(1); } } File file; do { String fn = FN_IDX.toString(); if (ext.isEmpty()) { file = new File(path, fn); } else { file = new File(path, fn + "." + ext); } FN_IDX.incrementAndGet(); } while (file.exists()); sb.append("/").append(file.getName()); UploadFile uf = new UploadFile(); uf.setFn(file); uf.setUri("/" + sb.toString()); return uf; } private String normalizeFileName(String fn) { int index = fn.indexOf('\\'); if (index >= 0) { fn = fn.substring(fn.lastIndexOf('\\') + 1); } index = fn.indexOf('/'); if (index >= 0) { fn = fn.substring(fn.lastIndexOf('/') + 1); } if (fn.length() == 0) throw new RuntimeException("invalid filename in Multipart/data request"); return fn; } public static class UploadFile { private String name; private String uri; private long size; private transient File fn; public File getFn() { return fn; } public void setFn(File fn) { this.fn = fn; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getUri() { return uri; } public void setUri(String uri) { this.uri = uri; } public long getSize() { return size; } public void setSize(long size) { this.size = size; } } }