Change-Id: Ifb09e87748b8ca58108a14fbb6803a4cbe4e0a6d
This commit is contained in:
rui.zhang 2018-12-19 19:20:32 +08:00
parent 1fd31e1b4b
commit f7466f84ab
25 changed files with 2269 additions and 0 deletions

26
.gitignore vendored Normal file
View File

@ -0,0 +1,26 @@
# Compiled class file
*.class
# Log file
*.log
# BlueJ files
*.ctxt
# Mobile Tools for Java (J2ME)
.mtj.tmp/
# Package Files #
*.jar
*.war
*.nar
*.ear
*.zip
*.tar.gz
*.rar
# virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml
hs_err_pid*
/.idea/
*.iml
/src/test/resources/config.properties

147
pom.xml Normal file
View File

@ -0,0 +1,147 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>org.chobit.wp</groupId>
<artifactId>wordpress-client</artifactId>
<version>0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>WordPress-Client</name>
<description>WordPress Java client</description>
<url>https://github.com/zhyea/wordpress-client</url>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<licenses>
<license>
<name>The Apache License, Version 2.0</name>
<url>http://www.apache.org/licenses/LICENSE-2.0.txt</url>
</license>
</licenses>
<dependencies>
<dependency>
<groupId>org.apache.xmlrpc</groupId>
<artifactId>xmlrpc-client</artifactId>
<version>3.1.3</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>2.9.7</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
<version>2.9.7</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.9.7</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.11</version>
<scope>test</scope>
</dependency>
</dependencies>
<scm>
<connection>scm:git:https://github.com/zhyea/wordpress-client.git</connection>
<developerConnection>scm:git:https://github.com/zhyea/wordpress-client.git</developerConnection>
<url>https://github.com/zhyea/wordpress-client</url>
</scm>
<developers>
<developer>
<name>robin</name>
<email>robin@zhyea.com</email>
<url>http://www.zhyea.com</url>
</developer>
</developers>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.3</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
</plugins>
</build>
<profiles>
<profile>
<id>release</id>
<build>
<plugins>
<!-- Source -->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-source-plugin</artifactId>
<version>3.0.1</version>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>jar-no-fork</goal>
</goals>
</execution>
</executions>
</plugin>
<!-- Javadoc -->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-javadoc-plugin</artifactId>
<version>2.10.4</version>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>jar</goal>
</goals>
</execution>
</executions>
</plugin>
<!-- GPG -->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-gpg-plugin</artifactId>
<version>1.6</version>
<executions>
<execution>
<phase>verify</phase>
<goals>
<goal>sign</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
<distributionManagement>
<snapshotRepository>
<id>oss</id>
<url>https://oss.sonatype.org/content/repositories/snapshots/</url>
</snapshotRepository>
<repository>
<id>oss</id>
<url>https://oss.sonatype.org/service/local/staging/deploy/maven2/</url>
</repository>
</distributionManagement>
</profile>
</profiles>
</project>

View File

@ -0,0 +1,169 @@
package org.chobit.wp;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import org.apache.xmlrpc.XmlRpcException;
import org.apache.xmlrpc.client.XmlRpcClient;
import org.apache.xmlrpc.client.XmlRpcClientConfigImpl;
import org.chobit.wp.exception.WPClientException;
import org.chobit.wp.model.request.PostFilter;
import org.chobit.wp.model.request.PostRequest;
import org.chobit.wp.model.response.Author;
import org.chobit.wp.model.response.Post;
import org.chobit.wp.model.response.UserBlog;
import org.chobit.wp.tools.JsonKit;
import javax.net.ssl.*;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
/**
* @author robin
*/
class WPClient {
private WordPressConfig config;
private XmlRpcClient client;
WPClient(String xmlRpcUrl, boolean trustAll) throws MalformedURLException {
XmlRpcClientConfigImpl c = new XmlRpcClientConfigImpl();
c.setServerURL(new URL(xmlRpcUrl));
if (trustAll) {
acceptAndCertificate();
}
client = new XmlRpcClient();
client.setConfig(c);
}
WPClient(WordPressConfig cfg) throws MalformedURLException {
this(cfg.getXmlRpcUrl(), cfg.isTrustAll());
this.config = cfg;
}
boolean deletePost(int postId) throws XmlRpcException, IOException {
Object[] params = new Object[]{config.getBlogId(), config.getUsername(), config.getPassword(), postId};
boolean result = execute("wp.deletePost", params, Boolean.class);
return result;
}
boolean editPost(int postId, PostRequest post) throws XmlRpcException, IOException {
Object[] params = new Object[]{config.getBlogId(), config.getUsername(), config.getPassword(), postId, post.toMap()};
boolean result = execute("wp.editPost", params, Boolean.class);
return result;
}
String newPost(PostRequest post) throws XmlRpcException, IOException {
Object[] params = new Object[]{config.getBlogId(), config.getUsername(), config.getPassword(), post.toMap()};
String postId = execute("wp.newPost", params);
return postId;
}
Post getPost(int postId, String... fields) throws XmlRpcException, IOException {
ArrayList<Object> params = new ArrayList<>(5);
params.addAll(Arrays.asList(config.getBlogId(), config.getUsername(), config.getPassword(), postId));
if (null != fields && fields.length > 0) {
params.add(fields);
}
Post post = execute("wp.getPost", params.toArray(), Post.class);
return post;
}
List<Post> getPosts(PostFilter filter, String... fields) throws XmlRpcException, IOException {
ArrayList<Object> params = new ArrayList<>(5);
params.addAll(Arrays.asList(config.getBlogId(), config.getUsername(), config.getPassword()));
if (null != filter) {
params.add(filter.toMap());
}
if (null != fields && fields.length > 0) {
params.add(fields);
}
List<Post> posts = execute("wp.getPosts", params.toArray(), new TypeReference<List<Post>>() {
});
return posts;
}
List<Author> getAuthors() throws XmlRpcException, IOException {
Object[] params = new Object[]{config.getBlogId(), config.getUsername(), config.getPassword()};
List<Author> authors = execute("wp.getAuthors", params, new TypeReference<List<Author>>() {
});
return authors;
}
List<UserBlog> getUsersBlogs() throws XmlRpcException, IOException {
return getUsersBlogs(config.getUsername(), config.getPassword());
}
List<UserBlog> getUsersBlogs(String username, String password) throws XmlRpcException, IOException {
Object[] params = new Object[]{username, password};
List<UserBlog> ubList = execute("wp.getUsersBlogs", params, new TypeReference<List<UserBlog>>() {
});
return ubList;
}
private <T> T execute(String methodName, Object[] params, Class<T> classOfT) throws XmlRpcException, IOException {
String json = execute(methodName, params);
return JsonKit.fromJson(json, classOfT);
}
private <T> T execute(String methodName, Object[] params, TypeReference<T> typeReference) throws XmlRpcException, IOException {
String json = execute(methodName, params);
return JsonKit.fromJson(json, typeReference);
}
private String execute(String methodName, Object[] params) throws XmlRpcException, JsonProcessingException {
Object obj = client.execute(methodName, params);
return JsonKit.toJson(obj);
}
private void acceptAndCertificate() {
try {
// Create a trust manager that does not validate certificate chains
TrustManager[] trustAllCerts = new TrustManager[]{new X509TrustManager() {
@Override
public java.security.cert.X509Certificate[] getAcceptedIssuers() {
return null;
}
@Override
public void checkClientTrusted(java.security.cert.X509Certificate[] certs,
String authType) {// Trust always
}
@Override
public void checkServerTrusted(X509Certificate[] certs,
String authType) {// Trust always
}
}};
// Install the all-trusting trust manager
SSLContext sc = SSLContext.getInstance("SSL");
// Create empty HostnameVerifier
HostnameVerifier hv = (arg0, arg1) -> true;
sc.init(null, trustAllCerts, new java.security.SecureRandom());
HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
HttpsURLConnection.setDefaultHostnameVerifier(hv);
} catch (Exception e) {
throw new WPClientException(e);
}
}
}

View File

@ -0,0 +1,110 @@
package org.chobit.wp;
import org.chobit.wp.exception.WPClientException;
import org.chobit.wp.model.request.PostFilter;
import org.chobit.wp.model.request.PostRequest;
import org.chobit.wp.model.response.Author;
import org.chobit.wp.model.response.Post;
import org.chobit.wp.model.response.UserBlog;
import java.util.List;
/**
* @author robin
*/
public final class WordPress {
private WordPressConfig config;
private WPClient client;
public WordPress(WordPressConfig config) {
this.config = config;
try {
client = new WPClient(config);
} catch (Exception e) {
throw new WPClientException("Error in creating wp client.", e);
}
}
public UserBlog getUserBlog() {
List<UserBlog> list = getUsersBlogs();
if (null == list || list.isEmpty()) {
throw new WPClientException("Cannot get users and blogs.");
}
return list.get(0);
}
public List<UserBlog> getUsersBlogs() {
try {
return client.getUsersBlogs();
} catch (Exception e) {
throw new WPClientException("Error in getting users and blogs.", e);
}
}
public Author getAuthor() {
List<Author> list = getAuthors();
if (null == list || list.isEmpty()) {
throw new WPClientException("Cannot get authors.");
}
return list.get(0);
}
public List<Author> getAuthors() {
try {
return client.getAuthors();
} catch (Exception e) {
throw new WPClientException("Error in getting authors.", e);
}
}
public List<Post> getPosts(PostFilter filter, String... fields) {
try {
return client.getPosts(filter, fields);
} catch (Exception e) {
throw new WPClientException("Error in getting posts.", e);
}
}
public Post getPost(int postId, String... fields) {
try {
return client.getPost(postId, fields);
} catch (Exception e) {
throw new WPClientException("Error in getting posts.", e);
}
}
public String newPost(PostRequest post) {
try {
return client.newPost(post);
} catch (Exception e) {
throw new WPClientException("Creating new post failed.", e);
}
}
public boolean editPost(int postId, PostRequest post) {
try {
return client.editPost(postId, post);
} catch (Exception e) {
throw new WPClientException("Editing post with id " + postId + " failed.", e);
}
}
public boolean deletePost(int postId) {
try {
return client.deletePost(postId);
} catch (Exception e) {
throw new WPClientException("Deleting post with id " + postId + " failed.", e);
}
}
}

View File

@ -0,0 +1,60 @@
package org.chobit.wp;
/**
* @author robin
*/
final class WordPressConfig {
private int blogId;
private String xmlRpcUrl;
private String username;
private String password;
private boolean trustAll;
WordPressConfig() {
}
public int getBlogId() {
return blogId;
}
public void setBlogId(int blogId) {
this.blogId = blogId;
}
public String getXmlRpcUrl() {
return xmlRpcUrl;
}
public void setXmlRpcUrl(String xmlRpcUrl) {
this.xmlRpcUrl = xmlRpcUrl;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public boolean isTrustAll() {
return trustAll;
}
public void setTrustAll(boolean trustAll) {
this.trustAll = trustAll;
}
}

View File

@ -0,0 +1,55 @@
package org.chobit.wp;
import org.chobit.wp.exception.WPClientException;
import org.chobit.wp.model.response.UserBlog;
import java.util.List;
/**
* @author robin
*/
public final class WordPressConfigBuilder {
private WordPressConfig config = new WordPressConfig();
public WordPressConfigBuilder username(String username) {
this.config.setUsername(username);
return this;
}
public WordPressConfigBuilder password(String password) {
this.config.setPassword(password);
return this;
}
public WordPressConfigBuilder xmlRpcUrl(String xmlRpcUrl) {
this.config.setXmlRpcUrl(xmlRpcUrl);
return this;
}
public WordPressConfigBuilder trustAll(boolean trustAll) {
this.config.setTrustAll(trustAll);
return this;
}
public WordPressConfig build() {
try {
WPClient client = new WPClient(config.getXmlRpcUrl(), config.isTrustAll());
List<UserBlog> list = client.getUsersBlogs(config.getUsername(), config.getPassword());
if (null == list || list.isEmpty()) {
throw new WPClientException("Error in wp config, please check");
}
UserBlog ub = list.get(0);
this.config.setBlogId(ub.getBlogId());
this.config.setXmlRpcUrl(config.getXmlRpcUrl());
return config;
} catch (Exception e) {
throw new WPClientException("Error in wp config, please check", e);
}
}
}

View File

@ -0,0 +1,48 @@
package org.chobit.wp.enums;
/**
* @author robin
*/
public enum PostStatus {
/**
* 公开的
*/
PUBLISH("publish"),
/**
* 待审核
*/
PENDING("pending"),
/**
* 草稿
*/
DRAFT("draft"),
/**
* 自动草稿
*/
AUTO_DRAFT("auto-draft"),
/**
* 定时
*/
FUTURE("future"),
/**
* 私有的
*/
PRIVATE("private"),
/**
* 继承子页面继承父级页面属性
*/
INHERIT("inherit"),
/**
* 垃圾箱
*/
TRASH("trash"),
;
public final String status;
PostStatus(String alias) {
this.status = alias;
}
}

View File

@ -0,0 +1,14 @@
package org.chobit.wp.enums;
public enum PostTaxonomy {
CATEGORY("category"),
TAG("post_tag"),
;
public final String taxonomy;
PostTaxonomy(String taxonomy) {
this.taxonomy = taxonomy;
}
}

View File

@ -0,0 +1,23 @@
package org.chobit.wp.exception;
/**
* @author robin
*/
public class WPClientException extends RuntimeException {
public WPClientException() {
super();
}
public WPClientException(String message) {
super(message);
}
public WPClientException(String message, Throwable cause) {
super(message, cause);
}
public WPClientException(Throwable cause) {
super(cause);
}
}

View File

@ -0,0 +1,34 @@
package org.chobit.wp.model.interval;
public class Enclosure {
private String url;
private int length;
private String type;
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public int getLength() {
return length;
}
public void setLength(int length) {
this.length = length;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
}

View File

@ -0,0 +1,70 @@
package org.chobit.wp.model.request;
import com.fasterxml.jackson.annotation.JsonProperty;
public class PostFilter extends Request {
@JsonProperty("post_type")
private String postType;
@JsonProperty("post_status")
private String postStatus;
private int number;
private int offset;
private String orderBy;
private String order;
public String getPostType() {
return postType;
}
public void setPostType(String postType) {
this.postType = postType;
}
public String getPostStatus() {
return postStatus;
}
public void setPostStatus(String postStatus) {
this.postStatus = postStatus;
}
public int getNumber() {
return number;
}
public void setNumber(int number) {
this.number = number;
}
public int getOffset() {
return offset;
}
public void setOffset(int offset) {
this.offset = offset;
}
public String getOrderBy() {
return orderBy;
}
public void setOrderBy(String orderBy) {
this.orderBy = orderBy;
}
public String getOrder() {
return order;
}
public void setOrder(String order) {
this.order = order;
}
}

View File

@ -0,0 +1,261 @@
package org.chobit.wp.model.request;
import com.fasterxml.jackson.annotation.JsonProperty;
import org.chobit.wp.enums.PostStatus;
import org.chobit.wp.model.interval.Enclosure;
import java.beans.Transient;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import static org.chobit.wp.enums.PostTaxonomy.CATEGORY;
import static org.chobit.wp.enums.PostTaxonomy.TAG;
public class PostRequest extends Request {
public PostRequest() {
}
@JsonProperty("post_type")
private String postType;
@JsonProperty("post_status")
private String postStatus = PostStatus.PUBLISH.status;
@JsonProperty("post_title")
private String postTitle;
@JsonProperty("post_author")
private Integer postAuthor;
@JsonProperty("post_excerpt")
private String postExcerpt;
@JsonProperty("post_content")
private String postContent;
@JsonProperty("post_date_gmt")
private Date postDateGmt;
@JsonProperty("post_format")
private String postFormat;
@JsonProperty("post_name")
private String postName;
@JsonProperty("post_password")
private String postPassword;
@JsonProperty("comment_status")
private String commentStatus;
@JsonProperty("ping_status")
private String pingStatus;
private Integer sticky;
@JsonProperty("post_thumbnail")
private Integer postThumbnail;
@JsonProperty("post_parent")
private Integer postParent;
@JsonProperty("custom_fields")
private List<CustomField> customFields;
private Enclosure enclosure;
@JsonProperty("terms_names")
private Map<String, String[]> termsNames;
public String getPostType() {
return postType;
}
public void setPostType(String postType) {
this.postType = postType;
}
public String getPostStatus() {
return postStatus;
}
public void setPostStatus(String postStatus) {
this.postStatus = postStatus;
}
public String getPostTitle() {
return postTitle;
}
public void setPostTitle(String postTitle) {
this.postTitle = postTitle;
}
public Integer getPostAuthor() {
return postAuthor;
}
public void setPostAuthor(Integer postAuthor) {
this.postAuthor = postAuthor;
}
public String getPostExcerpt() {
return postExcerpt;
}
public void setPostExcerpt(String postExcerpt) {
this.postExcerpt = postExcerpt;
}
public String getPostContent() {
return postContent;
}
public void setPostContent(String postContent) {
this.postContent = postContent;
}
public Date getPostDateGmt() {
return postDateGmt;
}
public void setPostDateGmt(Date postDateGmt) {
this.postDateGmt = postDateGmt;
}
public String getPostFormat() {
return postFormat;
}
public void setPostFormat(String postFormat) {
this.postFormat = postFormat;
}
public String getPostName() {
return postName;
}
public void setPostName(String postName) {
this.postName = postName;
}
public String getPostPassword() {
return postPassword;
}
public void setPostPassword(String postPassword) {
this.postPassword = postPassword;
}
public String getCommentStatus() {
return commentStatus;
}
public void setCommentStatus(String commentStatus) {
this.commentStatus = commentStatus;
}
public String getPingStatus() {
return pingStatus;
}
public void setPingStatus(String pingStatus) {
this.pingStatus = pingStatus;
}
public Integer getSticky() {
return sticky;
}
public void setSticky(Integer sticky) {
this.sticky = sticky;
}
public Integer getPostThumbnail() {
return postThumbnail;
}
public void setPostThumbnail(Integer postThumbnail) {
this.postThumbnail = postThumbnail;
}
public Integer getPostParent() {
return postParent;
}
public void setPostParent(Integer postParent) {
this.postParent = postParent;
}
public List<CustomField> getCustomFields() {
return customFields;
}
public void setCustomFields(List<CustomField> customFields) {
this.customFields = customFields;
}
public Enclosure getEnclosure() {
return enclosure;
}
public void setEnclosure(Enclosure enclosure) {
this.enclosure = enclosure;
}
public Map<String, String[]> getTermsNames() {
return termsNames;
}
public void setTermsNames(Map<String, String[]> termsNames) {
this.termsNames = termsNames;
}
@Transient
public void setCategories(String... categories) {
if (null == termsNames) {
setTermsNames(new HashMap<>(2));
}
if (null != categories && categories.length > 0) {
termsNames.put(CATEGORY.taxonomy, categories);
}
}
@Transient
public void setTags(String... tags) {
if (null == termsNames) {
setTermsNames(new HashMap<>(2));
}
if (null != tags && tags.length > 0) {
termsNames.put(TAG.taxonomy, tags);
}
}
public static class CustomField {
private String key;
private String value;
public String getKey() {
return key;
}
public void setKey(String key) {
this.key = key;
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
}
}

View File

@ -0,0 +1,19 @@
package org.chobit.wp.model.request;
import com.fasterxml.jackson.core.type.TypeReference;
import java.io.IOException;
import java.util.Map;
import static org.chobit.wp.tools.JsonKit.fromJson;
import static org.chobit.wp.tools.JsonKit.toJson;
public abstract class Request {
public Map<String, Object> toMap() throws IOException {
String json = toJson(this);
return fromJson(json, new TypeReference<Map<String, Object>>() {
});
}
}

View File

@ -0,0 +1,51 @@
package org.chobit.wp.model.response;
import com.fasterxml.jackson.annotation.JsonProperty;
public class Author {
@JsonProperty("user_id")
private String userId;
@JsonProperty("user_login")
private String userLogin;
@JsonProperty("display_name")
private String displayName;
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
public String getUserLogin() {
return userLogin;
}
public void setUserLogin(String userLogin) {
this.userLogin = userLogin;
}
public String getDisplayName() {
return displayName;
}
public void setDisplayName(String displayName) {
this.displayName = displayName;
}
@Override
public String toString() {
return "Author{" +
"userId='" + userId + '\'' +
", userLogin='" + userLogin + '\'' +
", displayName='" + displayName + '\'' +
'}';
}
}

View File

@ -0,0 +1,355 @@
package org.chobit.wp.model.response;
import com.fasterxml.jackson.annotation.JsonProperty;
import java.util.Date;
public class MediaItem {
@JsonProperty("attachment_id")
private String attachmentId;
@JsonProperty("date_created_gmt")
private Date dateCreatedGmt;
private int parent;
private String link;
private String title;
private String caption;
private String description;
private MediaItemMetadata metadata;
private String thumbnail;
public String getAttachmentId() {
return attachmentId;
}
public void setAttachmentId(String attachmentId) {
this.attachmentId = attachmentId;
}
public Date getDateCreatedGmt() {
return dateCreatedGmt;
}
public void setDateCreatedGmt(Date dateCreatedGmt) {
this.dateCreatedGmt = dateCreatedGmt;
}
public int getParent() {
return parent;
}
public void setParent(int parent) {
this.parent = parent;
}
public String getLink() {
return link;
}
public void setLink(String link) {
this.link = link;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getCaption() {
return caption;
}
public void setCaption(String caption) {
this.caption = caption;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public MediaItemMetadata getMetadata() {
return metadata;
}
public void setMetadata(MediaItemMetadata metadata) {
this.metadata = metadata;
}
public String getThumbnail() {
return thumbnail;
}
public void setThumbnail(String thumbnail) {
this.thumbnail = thumbnail;
}
public static class MediaItemMetadata {
private int width;
private int height;
private String file;
private MediaItemSizes sizes;
@JsonProperty("image_meta")
private PostThumbnailImageMeta imageMeta;
public int getWidth() {
return width;
}
public void setWidth(int width) {
this.width = width;
}
public int getHeight() {
return height;
}
public void setHeight(int height) {
this.height = height;
}
public String getFile() {
return file;
}
public void setFile(String file) {
this.file = file;
}
public MediaItemSizes getSizes() {
return sizes;
}
public void setSizes(MediaItemSizes sizes) {
this.sizes = sizes;
}
public PostThumbnailImageMeta getImageMeta() {
return imageMeta;
}
public void setImageMeta(PostThumbnailImageMeta imageMeta) {
this.imageMeta = imageMeta;
}
}
public static class MediaItemSizes {
private MediaItemSize thumbnail;
private MediaItemSize medium;
private MediaItemSize large;
@JsonProperty("post_thumbnail")
private MediaItemSize postThumbnail;
public MediaItemSize getThumbnail() {
return thumbnail;
}
public void setThumbnail(MediaItemSize thumbnail) {
this.thumbnail = thumbnail;
}
public MediaItemSize getMedium() {
return medium;
}
public void setMedium(MediaItemSize medium) {
this.medium = medium;
}
public MediaItemSize getLarge() {
return large;
}
public void setLarge(MediaItemSize large) {
this.large = large;
}
public MediaItemSize getPostThumbnail() {
return postThumbnail;
}
public void setPostThumbnail(MediaItemSize postThumbnail) {
this.postThumbnail = postThumbnail;
}
}
public static class MediaItemSize {
private String file;
private String width;
private String height;
@JsonProperty("mime_type")
private String mimeType;
public String getFile() {
return file;
}
public void setFile(String file) {
this.file = file;
}
public String getWidth() {
return width;
}
public void setWidth(String width) {
this.width = width;
}
public String getHeight() {
return height;
}
public void setHeight(String height) {
this.height = height;
}
public String getMimeType() {
return mimeType;
}
public void setMimeType(String mimeType) {
this.mimeType = mimeType;
}
}
public class PostThumbnailImageMeta {
private int aperture;
private String credit;
private String camera;
private String caption;
@JsonProperty("created_timestamp")
private int createdTimestamp;
private String copyright;
@JsonProperty("focal_length")
private int focalLength;
private int iso;
@JsonProperty("shutter_speed")
private int shutterSpeed;
private String title;
public int getAperture() {
return aperture;
}
public void setAperture(int aperture) {
this.aperture = aperture;
}
public String getCredit() {
return credit;
}
public void setCredit(String credit) {
this.credit = credit;
}
public String getCamera() {
return camera;
}
public void setCamera(String camera) {
this.camera = camera;
}
public String getCaption() {
return caption;
}
public void setCaption(String caption) {
this.caption = caption;
}
public int getCreatedTimestamp() {
return createdTimestamp;
}
public void setCreatedTimestamp(int createdTimestamp) {
this.createdTimestamp = createdTimestamp;
}
public String getCopyright() {
return copyright;
}
public void setCopyright(String copyright) {
this.copyright = copyright;
}
public int getFocalLength() {
return focalLength;
}
public void setFocalLength(int focalLength) {
this.focalLength = focalLength;
}
public int getIso() {
return iso;
}
public void setIso(int iso) {
this.iso = iso;
}
public int getShutterSpeed() {
return shutterSpeed;
}
public void setShutterSpeed(int shutterSpeed) {
this.shutterSpeed = shutterSpeed;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
}
}

View File

@ -0,0 +1,315 @@
package org.chobit.wp.model.response;
import com.fasterxml.jackson.annotation.JsonProperty;
import org.chobit.wp.model.interval.Enclosure;
import java.util.Date;
import java.util.List;
public class Post {
@JsonProperty("post_id")
private String postId;
@JsonProperty("post_title")
private String postTitle;
@JsonProperty("post_date_gmt")
private Date postDateGmt;
@JsonProperty("post_modified")
private Date postModified;
@JsonProperty("post_modified_gmt")
private Date postModifiedGmt;
@JsonProperty("post_status")
private String postStatus;
@JsonProperty("post_type")
private String postType;
@JsonProperty("post_format")
private String postFormat;
@JsonProperty("post_name")
private String postName;
@JsonProperty("post_author")
private String postAuthor;
@JsonProperty("post_password")
private String postPassword;
@JsonProperty("post_excerpt")
private String postExcerpt;
@JsonProperty("post_content")
private String postContent;
@JsonProperty("post_parent")
private String postParent;
@JsonProperty("post_mime_type")
private String postMimeType;
private String link;
private String guid;
@JsonProperty("menu_order")
private int menuOrder;
@JsonProperty("comment_status")
private String commentStatus;
@JsonProperty("ping_status")
private String pingStatus;
private boolean sticky;
@JsonProperty("post_thumbnail")
private List<MediaItem> postThumbnail;
private List<Term> terms;
@JsonProperty("custom_fields")
private List<CustomField> customFields;
private Enclosure enclosure;
public String getPostId() {
return postId;
}
public void setPostId(String postId) {
this.postId = postId;
}
public String getPostTitle() {
return postTitle;
}
public void setPostTitle(String postTitle) {
this.postTitle = postTitle;
}
public Date getPostDateGmt() {
return postDateGmt;
}
public void setPostDateGmt(Date postDateGmt) {
this.postDateGmt = postDateGmt;
}
public Date getPostModified() {
return postModified;
}
public void setPostModified(Date postModified) {
this.postModified = postModified;
}
public Date getPostModifiedGmt() {
return postModifiedGmt;
}
public void setPostModifiedGmt(Date postModifiedGmt) {
this.postModifiedGmt = postModifiedGmt;
}
public String getPostStatus() {
return postStatus;
}
public void setPostStatus(String postStatus) {
this.postStatus = postStatus;
}
public String getPostType() {
return postType;
}
public void setPostType(String postType) {
this.postType = postType;
}
public String getPostFormat() {
return postFormat;
}
public void setPostFormat(String postFormat) {
this.postFormat = postFormat;
}
public String getPostName() {
return postName;
}
public void setPostName(String postName) {
this.postName = postName;
}
public String getPostAuthor() {
return postAuthor;
}
public void setPostAuthor(String postAuthor) {
this.postAuthor = postAuthor;
}
public String getPostPassword() {
return postPassword;
}
public void setPostPassword(String postPassword) {
this.postPassword = postPassword;
}
public String getPostExcerpt() {
return postExcerpt;
}
public void setPostExcerpt(String postExcerpt) {
this.postExcerpt = postExcerpt;
}
public String getPostContent() {
return postContent;
}
public void setPostContent(String postContent) {
this.postContent = postContent;
}
public String getPostParent() {
return postParent;
}
public void setPostParent(String postParent) {
this.postParent = postParent;
}
public String getPostMimeType() {
return postMimeType;
}
public void setPostMimeType(String postMimeType) {
this.postMimeType = postMimeType;
}
public String getLink() {
return link;
}
public void setLink(String link) {
this.link = link;
}
public String getGuid() {
return guid;
}
public void setGuid(String guid) {
this.guid = guid;
}
public int getMenuOrder() {
return menuOrder;
}
public void setMenuOrder(int menuOrder) {
this.menuOrder = menuOrder;
}
public String getCommentStatus() {
return commentStatus;
}
public void setCommentStatus(String commentStatus) {
this.commentStatus = commentStatus;
}
public String getPingStatus() {
return pingStatus;
}
public void setPingStatus(String pingStatus) {
this.pingStatus = pingStatus;
}
public boolean isSticky() {
return sticky;
}
public void setSticky(boolean sticky) {
this.sticky = sticky;
}
public List<MediaItem> getPostThumbnail() {
return postThumbnail;
}
public void setPostThumbnail(List<MediaItem> postThumbnail) {
this.postThumbnail = postThumbnail;
}
public List<Term> getTerms() {
return terms;
}
public void setTerms(List<Term> terms) {
this.terms = terms;
}
public List<CustomField> getCustomFields() {
return customFields;
}
public void setCustomFields(List<CustomField> customFields) {
this.customFields = customFields;
}
public Enclosure getEnclosure() {
return enclosure;
}
public void setEnclosure(Enclosure enclosure) {
this.enclosure = enclosure;
}
public static class CustomField {
private String id;
private String key;
private String value;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getKey() {
return key;
}
public void setKey(String key) {
this.key = key;
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
}
}

View File

@ -0,0 +1,101 @@
package org.chobit.wp.model.response;
import com.fasterxml.jackson.annotation.JsonProperty;
public class Term {
private String termId;
private String name;
private String slug;
@JsonProperty("term_group")
private String termGroup;
@JsonProperty("term_taxonomy_id")
private String termTaxonomyId;
private String taxonomy;
private String description;
private String parent;
private int count;
public String getTermId() {
return termId;
}
public void setTermId(String termId) {
this.termId = termId;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSlug() {
return slug;
}
public void setSlug(String slug) {
this.slug = slug;
}
public String getTermGroup() {
return termGroup;
}
public void setTermGroup(String termGroup) {
this.termGroup = termGroup;
}
public String getTermTaxonomyId() {
return termTaxonomyId;
}
public void setTermTaxonomyId(String termTaxonomyId) {
this.termTaxonomyId = termTaxonomyId;
}
public String getTaxonomy() {
return taxonomy;
}
public void setTaxonomy(String taxonomy) {
this.taxonomy = taxonomy;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getParent() {
return parent;
}
public void setParent(String parent) {
this.parent = parent;
}
public int getCount() {
return count;
}
public void setCount(int count) {
this.count = count;
}
}

View File

@ -0,0 +1,75 @@
package org.chobit.wp.model.response;
import com.fasterxml.jackson.annotation.JsonProperty;
/**
* @author robin
*/
public class UserBlog {
@JsonProperty("blogid")
private int blogId;
private String blogName;
private String url;
private boolean isAdmin;
@JsonProperty("xmlrpc")
private String xmlRpc;
public int getBlogId() {
return blogId;
}
public void setBlogId(int blogId) {
this.blogId = blogId;
}
public String getBlogName() {
return blogName;
}
public void setBlogName(String blogName) {
this.blogName = blogName;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public boolean isAdmin() {
return isAdmin;
}
public void setAdmin(boolean admin) {
isAdmin = admin;
}
public String getXmlRpc() {
return xmlRpc;
}
public void setXmlRpc(String xmlRpc) {
this.xmlRpc = xmlRpc;
}
@Override
public String toString() {
return "UserBlog{" +
"blogId=" + blogId +
", blogName='" + blogName + '\'' +
", url='" + url + '\'' +
", isAdmin=" + isAdmin +
", xmlRpc='" + xmlRpc + '\'' +
'}';
}
}

View File

@ -0,0 +1,22 @@
package org.chobit.wp.tools;
/**
* @author robin
*/
public abstract class Args {
public static void check(boolean result, String errorMessage) {
if (result) {
throw new IllegalArgumentException(errorMessage);
}
}
public static void checkNotNull(Object source, String errorMessage) {
check(null == source, errorMessage);
}
private Args() {
throw new UnsupportedOperationException("Private constructor, cannot be accessed.");
}
}

View File

@ -0,0 +1,48 @@
package org.chobit.wp.tools;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.io.IOException;
/**
* @author robin
*/
public abstract class JsonKit {
private static final ObjectMapper MAPPER = new ObjectMapper();
static {
MAPPER.configure(DeserializationFeature.FAIL_ON_IGNORED_PROPERTIES, false);
MAPPER.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
MAPPER.configure(DeserializationFeature.FAIL_ON_NULL_FOR_PRIMITIVES, false);
MAPPER.setSerializationInclusion(JsonInclude.Include.NON_DEFAULT);
MAPPER.setSerializationInclusion(JsonInclude.Include.NON_NULL);
MAPPER.setSerializationInclusion(JsonInclude.Include.NON_EMPTY);
MAPPER.setSerializationInclusion(JsonInclude.Include.NON_ABSENT);
}
public static String toJson(Object src) throws JsonProcessingException {
return MAPPER.writeValueAsString(src);
}
public static <T> T fromJson(String json, Class<T> classOfT) throws IOException {
return MAPPER.readValue(json, classOfT);
}
public static <T> T fromJson(String json, TypeReference<T> typeReference) throws IOException {
return MAPPER.readValue(json, typeReference);
}
private JsonKit() {
throw new UnsupportedOperationException("private constructor, cannot be accessed.");
}
}

View File

@ -0,0 +1,25 @@
package org.chobit.wp;
/**
* @author robin
*/
public class Config {
static {
PropKit.load("/config.properties");
}
public static final Integer DEFAULT_BLOG_ID = 1;
public static final String XML_RPC_URL = PropKit.getProp("website", System.getProperty("website"));
public static final String USERNAME = PropKit.getProp("username", System.getProperty("username"));
public static final String PASSWORD = PropKit.getProp("password", System.getProperty("password"));
}

View File

@ -0,0 +1,19 @@
package org.chobit.wp;
import org.junit.Test;
import static org.chobit.wp.Config.*;
/**
* @author robin
*/
public class ConfigTest {
@Test
public void config() {
System.out.println(XML_RPC_URL);
System.out.println(USERNAME);
System.out.println(PASSWORD);
}
}

View File

@ -0,0 +1,93 @@
package org.chobit.wp;
import java.io.IOException;
import java.io.InputStream;
import java.util.Hashtable;
import java.util.Map;
import java.util.Properties;
/**
* properties文件操作类
*
* @author robin
*/
public abstract class PropKit {
private static final Map M = new Hashtable();
/**
* 加载配置文件
*
* @param propertyFileName 配置文件名称通常使用/name.properties这样的值
* @return 配置信息
*/
public static Properties load(String propertyFileName) {
Properties p = new Properties();
InputStream in = null;
try {
in = PropKit.class.getResourceAsStream(propertyFileName);
if (in != null) {
p.load(in);
M.putAll(p);
}
} catch (IOException e) {
throw new RuntimeException(e);
} finally {
if (in != null) {
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return p;
}
public static String getProp(String key, String defaultValue) {
Object oval = M.get(key);
String sval = (oval instanceof String) ? (String) oval : null;
return (sval == null) ? defaultValue : sval;
}
public static String getProp(String key) {
return getProp(key, null);
}
public static Object setProp(String key, String value) {
return M.put(key, value);
}
public static Integer getInt(String key, Integer defaultValue) {
String value = getProp(key);
return (value != null) ? Integer.parseInt(value) : defaultValue;
}
public static Integer getInt(String key) {
return getInt(key, 0);
}
public static Double getDouble(String key, Double defaultValue) {
String value = getProp(key);
return (value != null) ? Double.parseDouble(value) : defaultValue;
}
public static Double getDouble(String key) {
return getDouble(key, 0.0);
}
public static Boolean getBoolean(String key, Boolean defaultValue) {
String value = getProp(key);
return (value != null) ? Boolean.parseBoolean(value) : defaultValue;
}
public static Boolean getBoolean(String key) {
return getBoolean(key, false);
}
private PropKit() {
throw new UnsupportedOperationException("private constructor, cannot be called.");
}
}

View File

@ -0,0 +1,17 @@
package org.chobit.wp;
import org.chobit.wp.model.request.PostRequest;
import java.io.IOException;
/**
* @author robin
*/
public class Test {
public static void main(String[] args) throws IOException {
PostRequest request = new PostRequest();
request.setPostAuthor(11);
System.out.println(request.toMap());
}
}

View File

@ -0,0 +1,112 @@
package org.chobit.wp;
import com.fasterxml.jackson.core.JsonProcessingException;
import org.chobit.wp.model.request.PostFilter;
import org.chobit.wp.model.request.PostRequest;
import org.chobit.wp.model.response.Author;
import org.chobit.wp.model.response.Post;
import org.chobit.wp.model.response.UserBlog;
import org.junit.Assert;
import org.junit.Test;
import java.util.List;
import static org.chobit.wp.Config.*;
import static org.chobit.wp.tools.JsonKit.toJson;
/**
* @author robin
*/
public class WordPressTest {
private WordPress wp = new WordPress(buildConfig());
@Test
public void getUserBlog() {
UserBlog ub = wp.getUserBlog();
Assert.assertNotNull(ub);
}
@Test
public void getUsersBlogs() {
List<UserBlog> list = wp.getUsersBlogs();
System.out.println(list);
Assert.assertFalse(list.isEmpty());
}
@Test
public void getAuthor() {
Author a = wp.getAuthor();
Assert.assertNotNull(a);
}
@Test
public void getAuthors() {
List<Author> list = wp.getAuthors();
System.out.println(list);
Assert.assertFalse(list.isEmpty());
}
@Test
public void getPosts() throws JsonProcessingException {
PostFilter f = new PostFilter();
f.setNumber(30);
List<Post> list = wp.getPosts(f);
System.out.println(toJson(list));
Assert.assertFalse(list.isEmpty());
}
@Test
public void getPost() {
Post p = wp.getPost(29, "post_content");
System.out.println(p);
Assert.assertNotNull(p);
}
@Test
public void newPost() {
PostRequest post = new PostRequest();
post.setPostTitle("测试PostName" + System.currentTimeMillis());
post.setPostContent("这是一段测试内容:" + System.currentTimeMillis());
post.setCategories("测试");
post.setTags("a", "b", "c");
post.setPostName("abczzdddd");
String postId = wp.newPost(post);
System.out.println(postId);
Assert.assertNotNull(postId);
}
@Test
public void editPost() {
PostRequest post = new PostRequest();
post.setPostTitle("测试编辑" + System.currentTimeMillis());
post.setPostContent("这是一段编辑后的测试内容:" + System.currentTimeMillis());
boolean result = wp.editPost(29, post);
System.out.println(result);
Assert.assertTrue(result);
}
//@Test
public void deletePost() {
int postId = 26;
boolean result = wp.deletePost(postId);
System.out.println(result);
Assert.assertTrue(result);
}
private WordPressConfig buildConfig() {
return new WordPressConfigBuilder()
.username(USERNAME)
.password(PASSWORD)
.xmlRpcUrl(XML_RPC_URL)
.trustAll(true)
.build();
}
}