Java tutorial
/******************************************************************************* * Copyright (c) 2014,2015 Hideki Yatomi * All rights reserved. This program and the accompanying materials are made * available under the terms of the Eclipse Public License v1.0 which * accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html ******************************************************************************/ package net.yatomiya.nicherry.services.bbs; import java.util.regex.*; import org.jsoup.*; import org.jsoup.nodes.*; import com.squareup.okhttp.*; import net.yatomiya.e4.util.*; import net.yatomiya.nicherry.model.bbs.*; public abstract class PostEvent<MODEL extends MBBSModel> { public enum Type { SUCCESS, CONFIRM, SCRIPT_ERROR, STATUS_ERROR, CONNECTION_ERROR, UNKNOWN_ERROR, } private MODEL model; private Type type = Type.UNKNOWN_ERROR; private Request request; private Response response; private String responseHtml = ""; private Document responseDocument; private String title = ""; private String xTag = ""; private long postTime; private Exception exception; void setupWithResponse(MODEL model, Request request, Response response, String responseHtml) { this.model = model; this.request = request; this.response = response; this.responseHtml = responseHtml; if (response.code() == 200) { responseDocument = Jsoup.parse(responseHtml); title = JUtils.nonNull(findTitle(responseHtml)); xTag = JUtils.nonNull(findXTag(responseHtml)); if (title.contains("???????") || xTag.equals("true")) { type = Type.SUCCESS; } else if (title.contains("????") || xTag.equals("cookie")) { type = Type.CONFIRM; } else { type = Type.SCRIPT_ERROR; } } else { type = Type.STATUS_ERROR; } postTime = JUtils.getCurrentTime(); } void setupConnectionError(MODEL model, Request request, Exception e) { this.model = model; this.request = request; this.exception = e; type = Type.CONNECTION_ERROR; } public MODEL getModel() { return model; } public Type getType() { return type; } public Request getRequest() { return request; } public Response getResponse() { return response; } public Exception getException() { return exception; } public String getResponseHtml() { return responseHtml; } public long getPostTime() { return postTime; } public static final String TITLE_EXPR = "(?i)<title>(.*)</title>"; public static final String X_TAG_EXPR = "<!-- 2ch_X:(.*) -->"; public static final Pattern TITLE_PATTERN = Pattern.compile(TITLE_EXPR); public static final Pattern X_TAG_PATTERN = Pattern.compile(X_TAG_EXPR); public static String findTitle(String html) { String title = null; Matcher m = TITLE_PATTERN.matcher(html); if (m.find()) { title = m.group(1); } return title; } public static String findXTag(String html) { String xTag = null; Matcher m = X_TAG_PATTERN.matcher(html); if (m.find()) { xTag = m.group(1); } return xTag; } }