Skip to content

Commit

Permalink
添加metaWeblog
Browse files Browse the repository at this point in the history
  • Loading branch information
zhou committed Mar 5, 2015
1 parent fb69324 commit 0387128
Show file tree
Hide file tree
Showing 48 changed files with 474 additions and 134 deletions.
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ a java blog
6. 会员注册登录,后台管理功能。
7. lucene实现的站内搜索。
8. 防xss、csrf攻击。
9. 支持metaWeblog Api

### 技术选型

Expand Down
8 changes: 7 additions & 1 deletion pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -219,7 +219,13 @@
<artifactId>shiro-web</artifactId>
<version>1.2.3</version>
</dependency>


<dependency>
<groupId>org.kohsuke.redstone</groupId>
<artifactId>redstone</artifactId>
<version>1.1.1</version>
</dependency>

</dependencies>
<build>
<pluginManagement>
Expand Down
208 changes: 208 additions & 0 deletions src/main/java/com/zblog/biz/MetaWeblogManager.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,208 @@
package com.zblog.biz;

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

import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.util.HtmlUtils;

import redstone.xmlrpc.XmlRpcArray;
import redstone.xmlrpc.XmlRpcException;
import redstone.xmlrpc.XmlRpcStruct;

import com.zblog.core.dal.entity.Category;
import com.zblog.core.dal.entity.Post;
import com.zblog.core.dal.entity.Upload;
import com.zblog.core.dal.entity.User;
import com.zblog.core.plugin.MapContainer;
import com.zblog.core.util.JsoupUtils;
import com.zblog.core.util.ServletUtils;
import com.zblog.core.util.StringUtils;
import com.zblog.core.util.constants.CategoryConstants;
import com.zblog.core.util.constants.PostConstants;
import com.zblog.core.util.constants.WebConstants;
import com.zblog.core.util.web.WebContextFactory;
import com.zblog.service.CategoryService;
import com.zblog.service.PostService;
import com.zblog.service.UserService;

/**
*
* @author zhou
*
*/
@Component
public class MetaWeblogManager{
@Autowired
private UserService userService;
@Autowired
private CategoryService categoryService;
@Autowired
private PostService postService;
@Autowired
private PostManager postManager;
@Autowired
private UploadManager uploadManager;
@Autowired
private OptionManager optionManager;

public Object getPost(String postid, String username, String pwd){
User user = userService.login(username, pwd);
if(user == null)
loginError();

Post post = postService.loadById(postid);
MapContainer mc = new MapContainer();
mc.put("dateCreated", post.getCreateTime()).put("userid", user.getId());
mc.put("postid", post.getId()).put("description", post.getContent());
mc.put("title", post.getTitle()).put("link", toLink("/posts/" + postid))
.put("permaLink", toLink("/posts/" + postid));
mc.put("categories", Arrays.asList(post.getCategoryid()));
mc.put("post_status", "public");

return mc;
}

public Object newMediaObject(String blogid, String username, String pwd, XmlRpcStruct file) throws XmlRpcException{
User user = userService.login(username, pwd);
if(user == null)
loginError();

byte[] bits = file.getBinary("bits");
String name = file.getString("name");// Windows-Live-Writer/123123_A453/file_1_8.jpg
int slash = name.lastIndexOf("/");
name = name.substring(slash + 1);
String type = file.getString("type");// image/jpeg

if(StringUtils.isBlank(type) || !type.startsWith("image/")){
return new MapContainer().put("faultCode", HttpServletResponse.SC_FORBIDDEN).put("faultString",
"img_file_not_accept");
}

Upload upload = uploadManager.insertUpload(bits, name, user.getId());
return new MapContainer("url", toLink(upload.getPath()));
}

public Object newPost(String blogid, String username, String pwd, XmlRpcStruct param, boolean publish){
User user = userService.login(username, pwd);
if(user == null)
loginError();

Post post = new Post();
post.setId(optionManager.getNextPostid());
/* param.getDate("dateCreated") */
post.setLastUpdate(new Date());
post.setTitle(param.getString("title"));
XmlRpcArray categories = param.getArray("categories");
if(categories != null && !categories.isEmpty())
post.setCategoryid(categoryService.loadByName(categories.getString(0)).getId());

/* 由于加入xss的过滤,html内容都被转义了,这里需要unescape */
String content = HtmlUtils.htmlUnescape(param.getString("description"));
post.setContent(JsoupUtils.filter(content));
String cleanTxt = JsoupUtils.plainText(content);
post.setExcerpt(cleanTxt.length() > PostConstants.EXCERPT_LENGTH ? cleanTxt.substring(0,
PostConstants.EXCERPT_LENGTH) : cleanTxt);
post.setParent(PostConstants.DEFAULT_PARENT);

postManager.insertPost(post);

return post.getId();
}

public Object deletePost(String appKey, String postid, String username, String pwd, boolean publish){
User user = userService.login(username, pwd);
if(user == null)
loginError();

postManager.removePost(postid, PostConstants.TYPE_POST);
return postid;
}

public Object editPost(String postid, String username, String pwd, XmlRpcStruct param, boolean publish){
User user = userService.login(username, pwd);
if(user == null)
loginError();

Post post = new Post();
post.setId(postid);
post.setTitle(param.getString("title"));
post.setLastUpdate(new Date());
String content = HtmlUtils.htmlUnescape(param.getString("description"));
post.setContent(JsoupUtils.filter(content));
String cleanTxt = JsoupUtils.plainText(content);
post.setExcerpt(cleanTxt.length() > PostConstants.EXCERPT_LENGTH ? cleanTxt.substring(0,
PostConstants.EXCERPT_LENGTH) : cleanTxt);
XmlRpcArray categories = param.getArray("categories");
if(categories != null && !categories.isEmpty())
post.setCategoryid(categoryService.loadByName(categories.getString(0)).getId());

postManager.updatePost(post);
return postid;
}

public Object getUsersBlogs(String key, String username, String pwd){
User user = userService.login(username, pwd);
if(user == null)
loginError();

MapContainer mc = new MapContainer("isAdmin", "false");
mc.put("isAdmin", false).put("blogid", user.getId()).put("blogName", WebConstants.TITLE);
mc.put("xmlrpc", toLink("/xmlrpc")).put("link", "");

return mc;
}

public Object getCategories(String blogid, String username, String pwd){
User user = userService.login(username, pwd);
if(user == null)
loginError();

List<MapContainer> categories = categoryService.list();
List<MapContainer> result = new ArrayList<>(categories.size() - 1);
for(MapContainer category : categories){
if(CategoryConstants.ROOT.equals(category.getAsString("text")))
continue;

MapContainer mc = new MapContainer("categoryid", category.getAsString("id"))
.put("title", category.getAsString("text")).put("description", category.getAsString("text"))
.put("htmlUrl", toLink("/categorys/" + category.getAsString("text"))).put("rssUrl", "");
result.add(mc);
}
return result;
}

public Object getRecentPosts(String blogid, String username, String pwd, int numberOfPosts){
User user = userService.login(username, pwd);
if(user == null)
loginError();

List<MapContainer> list = postService.listRecent(numberOfPosts);
MapContainer[] result = new MapContainer[list.size()];
for(int i = 0; i < list.size(); i++){
MapContainer temp = list.get(i);
Category category = categoryService.loadById(temp.getAsString("categoryid"));
result[i] = new MapContainer("dateCreated", temp.getAsDate("createTime"))
.put("userid", temp.getAsString("creator")).put("postid", temp.getAsString("id")).put("description", "")
.put("title", temp.getAsString("title")).put("link", toLink("/posts/" + temp.get("id")))
.put("permaLink", toLink("/posts/" + temp.get("id"))).put("categories", Arrays.asList(category.getName()))
.put("post_status", "publish");
;
}
return result;
}

private static void loginError() throws XmlRpcException{
throw new XmlRpcException("FORBIDDEN");
}

private static String toLink(String path){
return ServletUtils.getDomain(WebContextFactory.get().getRequest()) + path;
}

}
43 changes: 39 additions & 4 deletions src/main/java/com/zblog/biz/UploadManager.java
Original file line number Diff line number Diff line change
@@ -1,8 +1,11 @@
package com.zblog.biz;

import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.util.Date;

import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;
Expand All @@ -11,9 +14,11 @@
import com.zblog.core.util.DateUtils;
import com.zblog.core.util.FileUtils;
import com.zblog.core.util.IdGenarater;
import com.zblog.core.util.ServletUtils;
import com.zblog.core.util.constants.WebConstants;
import com.zblog.core.util.web.ServletRequestReader;
import com.zblog.core.util.web.WebContextHolder;
import com.zblog.core.util.web.WebContext;
import com.zblog.core.util.web.WebContextFactory;
import com.zblog.service.UploadService;

@Component
Expand Down Expand Up @@ -42,8 +47,7 @@ public Upload insertUpload(ServletRequestReader reader, String fileVal){

upload = new Upload();
upload.setId(IdGenarater.uuid19());
upload.setCreateTime(new Date());
upload.setCreator(WebContextHolder.get().getUser().getNickName());
upload.setCreator(WebContextFactory.get().getUser().getId());
upload.setName(file.getOriginalFilename());
upload.setPath("/post/uploads/" + year + "/" + savePath.getName());

Expand All @@ -56,6 +60,37 @@ public Upload insertUpload(ServletRequestReader reader, String fileVal){
return upload;
}

public Upload insertUpload(byte[] file, String fileName, String userid){
Upload upload = null;
OutputStream out = null;
try{
String year = DateUtils.currentDate("yyyy");
WebContext context = WebContextFactory.get();
File parent = new File(ServletUtils.getRealPath(context.getRequest(), "/post/uploads"), year);
if(!parent.exists())
parent.mkdirs();

File savePath = determineFile(parent, fileName);
IOUtils.write(file, out = new FileOutputStream(savePath));

upload = new Upload();
upload.setId(IdGenarater.uuid19());
upload.setCreateTime(new Date());
upload.setCreator(userid);
upload.setName(fileName);
upload.setPath("/post/uploads/" + year + "/" + savePath.getName());

uploadService.insert(upload);
}catch(Exception e){
e.printStackTrace();
upload = null;
}finally{
IOUtils.closeQuietly(out);
}

return upload;
}

/**
* 删除记录,同时删除文件
*
Expand Down Expand Up @@ -84,5 +119,5 @@ private File determineFile(File parent, String fileName){

return temp;
}

}
17 changes: 13 additions & 4 deletions src/main/java/com/zblog/biz/aop/PostIndexManager.java
Original file line number Diff line number Diff line change
Expand Up @@ -5,16 +5,18 @@
import org.apache.lucene.index.Term;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.zblog.core.dal.entity.Post;
import com.zblog.core.lucene.LuceneUtils;
import com.zblog.core.lucene.QueryBuilder;
import com.zblog.core.lucene.SearchEnginer;
import com.zblog.core.plugin.MapContainer;
import com.zblog.core.plugin.PageModel;
import com.zblog.core.util.DateUtils;
import com.zblog.core.util.JsoupUtils;
import com.zblog.core.util.constants.PostConstants;
import com.zblog.service.PostService;

/**
* 文章Lucene索引管理器
Expand All @@ -25,6 +27,8 @@
@Component
public class PostIndexManager{
private static final Logger logger = LoggerFactory.getLogger(PostIndexManager.class);
@Autowired
private PostService postService;

/**
* 只有添加文章才插入Lucene索引
Expand All @@ -50,14 +54,19 @@ public void update(Post post){

public void remove(String postid, String postType){
if(PostConstants.TYPE_POST.equals(postType))
SearchEnginer.postEnginer().delete(new Term("id", postid));
SearchEnginer.postEnginer().delete(new Term("id", postid));
}

public PageModel search(String word, int pageIndex){
PageModel result = new PageModel(pageIndex, 15);
QueryBuilder builder = new QueryBuilder(SearchEnginer.postEnginer().getAnalyzer());
builder.addShould("title", word).addShould("excerpt", word);
SearchEnginer.postEnginer().searchHighlight(builder, result);
/* 填充其他属性 */
for(MapContainer mc : result.getContent()){
MapContainer all = postService.loadReadById(mc.getAsString("id"));
mc.put("createTime", all.get("createTime")).put("nickName", all.get("nickName")).put("rcount", all.get("rcount"));
}

return result;
}
Expand All @@ -69,8 +78,8 @@ private Document convert(Post post){
/* 用jsoup剔除html标签 */
doc.add(new Field("excerpt", JsoupUtils.plainText(post.getContent()), LuceneUtils.searchType()));
doc.add(new Field("creator", post.getCreator(), LuceneUtils.storeType()));
doc.add(new Field("createTime", DateUtils.formatDate("yyyy-MM-dd", post.getCreateTime()), LuceneUtils.storeType()));

// doc.add(new LongField("createTime", post.getCreateTime().getTime(),
// LuceneUtils.storeType()));
return doc;
}

Expand Down
Loading

0 comments on commit 0387128

Please sign in to comment.