file_id
int64 1
66.7k
| content
stringlengths 14
343k
| repo
stringlengths 6
92
| path
stringlengths 5
169
|
---|---|---|---|
1 | package edu.stanford.nlp.coref.data;
import java.util.Arrays;
import java.util.Set;
import edu.stanford.nlp.util.Generics;
/** Word lists for Chinese and English used in the coref system.
*
* @author Heeyoung Lee
* @author Rob Voigt
* @author Christopher Manning
*/
public class WordLists {
private WordLists() { } // just variable declarations
//
// WordLists for English
//
public static final Set<String> reportVerbEn = Generics.newHashSet(Arrays.asList(
"accuse", "acknowledge", "add", "admit", "advise", "agree", "alert",
"allege", "announce", "answer", "apologize", "argue",
"ask", "assert", "assure", "beg", "blame", "boast",
"caution", "charge", "cite", "claim", "clarify", "command", "comment",
"compare", "complain", "concede", "conclude", "confirm", "confront", "congratulate",
"contend", "contradict", "convey", "counter", "criticize",
"debate", "decide", "declare", "defend", "demand", "demonstrate", "deny",
"describe", "determine", "disagree", "disclose", "discount", "discover", "discuss",
"dismiss", "dispute", "disregard", "doubt", "emphasize", "encourage", "endorse",
"equate", "estimate", "expect", "explain", "express", "extol", "fear", "feel",
"find", "forbid", "forecast", "foretell", "forget", "gather", "guarantee", "guess",
"hear", "hint", "hope", "illustrate", "imagine", "imply", "indicate", "inform",
"insert", "insist", "instruct", "interpret", "interview", "invite", "issue",
"justify", "learn", "maintain", "mean", "mention", "negotiate", "note",
"observe", "offer", "oppose", "order", "persuade", "pledge", "point", "point out",
"praise", "pray", "predict", "prefer", "present", "promise", "prompt", "propose",
"protest", "prove", "provoke", "question", "quote", "raise", "rally", "read",
"reaffirm", "realise", "realize", "rebut", "recall", "reckon", "recommend", "refer",
"reflect", "refuse", "refute", "reiterate", "reject", "relate", "remark",
"remember", "remind", "repeat", "reply", "report", "request", "respond",
"restate", "reveal", "rule", "say", "see", "show", "shout", "signal", "sing",
"slam", "speculate", "spoke", "spread", "state", "stipulate", "stress",
"suggest", "support", "suppose", "surmise", "suspect", "swear", "teach",
"tell", "testify", "think", "threaten", "told", "uncover", "underline",
"underscore", "urge", "voice", "vow", "warn", "welcome",
"wish", "wonder", "worry", "write"));
public static final Set<String> reportNounEn = Generics.newHashSet(Arrays.asList(
"acclamation", "account", "accusation", "acknowledgment", "address", "addressing",
"admission", "advertisement", "advice", "advisory", "affidavit", "affirmation", "alert",
"allegation", "analysis", "anecdote", "annotation", "announcement", "answer", "antiphon",
"apology", "applause", "appreciation", "argument", "arraignment", "article", "articulation",
"aside", "assertion", "asseveration", "assurance", "attestation", "attitude",
"averment", "avouchment", "avowal", "axiom", "backcap", "band-aid", "basic", "belief", "bestowal",
"bill", "blame", "blow-by-blow", "bomb", "book", "bow", "break", "breakdown", "brief", "briefing",
"broadcast", "broadcasting", "bulletin", "buzz", "cable", "calendar", "call", "canard", "canon",
"card", "cause", "censure", "certification", "characterization", "charge", "chat", "chatter",
"chitchat", "chronicle", "chronology", "citation", "claim", "clarification", "close", "cognizance",
"comeback", "comment", "commentary", "communication", "communique", "composition", "concept",
"concession", "conference", "confession", "confirmation", "conjecture", "connotation", "construal",
"construction", "consultation", "contention", "contract", "convention", "conversation", "converse",
"conviction", "counterclaim", "credenda", "creed", "critique",
"cry", "declaration", "defense", "definition", "delineation", "delivery", "demonstration",
"denial", "denotation", "depiction", "deposition", "description", "detail", "details", "detention",
"dialogue", "diction", "dictum", "digest", "directive", "disclosure", "discourse", "discovery",
"discussion", "dispatch", "display", "disquisition", "dissemination", "dissertation", "divulgence",
"dogma", "editorial", "ejaculation", "emphasis", "enlightenment",
"enunciation", "essay", "evidence", "examination", "example", "excerpt", "exclamation",
"excuse", "execution", "exegesis", "explanation", "explication", "exposing", "exposition", "expounding",
"expression", "eye-opener", "feedback", "fiction", "findings", "fingerprint", "flash", "formulation",
"fundamental", "gift", "gloss", "goods", "gospel", "gossip", "gratitude", "greeting",
"guarantee", "hail", "hailing", "handout", "hash", "headlines", "hearing", "hearsay",
"ideas", "idiom", "illustration", "impeachment", "implantation", "implication", "imputation",
"incrimination", "indication", "indoctrination", "inference", "info", "information",
"innuendo", "insinuation", "insistence", "instruction", "intelligence", "interpretation", "interview",
"intimation", "intonation", "issue", "item", "itemization", "justification", "key", "knowledge",
"leak", "letter", "locution", "manifesto",
"meaning", "meeting", "mention", "message", "missive", "mitigation", "monograph", "motive", "murmur",
"narration", "narrative", "news", "nod", "note", "notice", "notification", "oath", "observation",
"okay", "opinion", "oral", "outline", "paper", "parley", "particularization", "phrase", "phraseology",
"phrasing", "picture", "piece", "pipeline", "pitch", "plea", "plot", "portraiture", "portrayal",
"position", "potboiler", "prating", "precept", "prediction", "presentation", "presentment", "principle",
"proclamation", "profession", "program", "promulgation", "pronouncement", "pronunciation", "propaganda",
"prophecy", "proposal", "proposition", "prosecution", "protestation", "publication", "publicity",
"publishing", "quotation", "ratification", "reaction", "reason", "rebuttal", "receipt", "recital",
"recitation", "recognition", "record", "recount", "recountal", "refutation", "regulation", "rehearsal",
"rejoinder", "relation", "release", "remark", "rendition", "repartee", "reply", "report", "reporting",
"representation", "resolution", "response", "result", "retort", "return", "revelation", "review",
"rule", "rumble", "rumor", "rundown", "saying", "scandal", "scoop",
"scuttlebutt", "sense", "showing", "sign", "signature", "significance", "sketch", "skinny", "solution",
"speaking", "specification", "speech", "statement", "story", "study", "style", "suggestion",
"summarization", "summary", "summons", "tale", "talk", "talking", "tattle", "telecast",
"telegram", "telling", "tenet", "term", "testimonial", "testimony", "text", "theme", "thesis",
"tract", "tractate", "tradition", "translation", "treatise", "utterance", "vent", "ventilation",
"verbalization", "version", "vignette", "vindication", "warning",
"warrant", "whispering", "wire", "word", "work", "writ", "write-up", "writeup", "writing",
"acceptance", "complaint", "concern", "disappointment", "disclose", "estimate", "laugh", "pleasure", "regret",
"resentment", "view"));
public static final Set<String> nonWordsEn = Generics.newHashSet(Arrays.asList("mm", "hmm", "ahem", "um"));
public static final Set<String> copulasEn = Generics.newHashSet(Arrays.asList("is","are","were", "was","be", "been","become","became","becomes","seem","seemed","seems","remain","remains","remained"));
public static final Set<String> quantifiersEn = Generics.newHashSet(Arrays.asList("not","every","any","none","everything","anything","nothing","all","enough"));
public static final Set<String> partsEn = Generics.newHashSet(Arrays.asList("half","one","two","three","four","five","six","seven","eight","nine","ten","hundred","thousand","million","billion","tens","dozens","hundreds","thousands","millions","billions","group","groups","bunch","number","numbers","pinch","amount","amount","total","all","mile","miles","pounds"));
public static final Set<String> temporalsEn = Generics.newHashSet(Arrays.asList(
"second", "minute", "hour", "day", "week", "month", "year", "decade", "century", "millennium",
"monday", "tuesday", "wednesday", "thursday", "friday", "saturday", "sunday", "now",
"yesterday", "tomorrow", "age", "time", "era", "epoch", "morning", "evening", "day", "night", "noon", "afternoon",
"semester", "trimester", "quarter", "term", "winter", "spring", "summer", "fall", "autumn", "season",
"january", "february", "march", "april", "may", "june", "july", "august", "september", "october", "november", "december"));
public static final Set<String> femalePronounsEn = Generics.newHashSet(Arrays.asList(new String[]{ "her", "hers", "herself", "she" }));
public static final Set<String> malePronounsEn = Generics.newHashSet(Arrays.asList(new String[]{ "he", "him", "himself", "his" }));
public static final Set<String> neutralPronounsEn = Generics.newHashSet(Arrays.asList(new String[]{ "it", "its", "itself", "where", "here", "there", "which" }));
public static final Set<String> possessivePronounsEn = Generics.newHashSet(Arrays.asList(new String[]{ "my", "your", "his", "her", "its","our","their","whose" }));
public static final Set<String> otherPronounsEn = Generics.newHashSet(Arrays.asList(new String[]{ "who", "whom", "whose", "where", "when","which" }));
public static final Set<String> thirdPersonPronounsEn = Generics.newHashSet(Arrays.asList(new String[]{ "he", "him", "himself", "his", "she", "her", "herself", "hers", "her", "it", "itself", "its", "one", "oneself", "one's", "they", "them", "themself", "themselves", "theirs", "their", "they", "them", "'em", "themselves" }));
public static final Set<String> secondPersonPronounsEn = Generics.newHashSet(Arrays.asList(new String[]{ "you", "yourself", "yours", "your", "yourselves" }));
public static final Set<String> firstPersonPronounsEn = Generics.newHashSet(Arrays.asList(new String[]{ "i", "me", "myself", "mine", "my", "we", "us", "ourself", "ourselves", "ours", "our" }));
public static final Set<String> moneyPercentNumberPronounsEn = Generics.newHashSet(Arrays.asList(new String[]{ "it", "its" }));
public static final Set<String> dateTimePronounsEn = Generics.newHashSet(Arrays.asList(new String[]{ "when" }));
public static final Set<String> organizationPronounsEn = Generics.newHashSet(Arrays.asList(new String[]{ "it", "its", "they", "their", "them", "which"}));
public static final Set<String> locationPronounsEn = Generics.newHashSet(Arrays.asList(new String[]{ "it", "its", "where", "here", "there" }));
public static final Set<String> inanimatePronounsEn = Generics.newHashSet(Arrays.asList(new String[]{ "it", "itself", "its", "where", "when" }));
public static final Set<String> animatePronounsEn = Generics.newHashSet(Arrays.asList(new String[]{ "i", "me", "myself", "mine", "my", "we", "us", "ourself", "ourselves", "ours", "our", "you", "yourself", "yours", "your", "yourselves", "he", "him", "himself", "his", "she", "her", "herself", "hers", "her", "one", "oneself", "one's", "they", "them", "themself", "themselves", "theirs", "their", "they", "them", "'em", "themselves", "who", "whom", "whose" }));
public static final Set<String> indefinitePronounsEn = Generics.newHashSet(Arrays.asList(new String[]{"another", "anybody", "anyone", "anything", "each", "either", "enough", "everybody", "everyone", "everything", "less", "little", "much", "neither", "no one", "nobody", "nothing", "one", "other", "plenty", "somebody", "someone", "something", "both", "few", "fewer", "many", "others", "several", "all", "any", "more", "most", "none", "some", "such"}));
public static final Set<String> relativePronounsEn = Generics.newHashSet(Arrays.asList(new String[]{"that","who","which","whom","where","whose"}));
public static final Set<String> GPEPronounsEn = Generics.newHashSet(Arrays.asList(new String[]{ "it", "itself", "its", "they","where" }));
public static final Set<String> pluralPronounsEn = Generics.newHashSet(Arrays.asList(new String[]{ "we", "us", "ourself", "ourselves", "ours", "our", "yourself", "yourselves", "they", "them", "themself", "themselves", "theirs", "their" }));
public static final Set<String> singularPronounsEn = Generics.newHashSet(Arrays.asList(new String[]{ "i", "me", "myself", "mine", "my", "yourself", "he", "him", "himself", "his", "she", "her", "herself", "hers", "her", "it", "itself", "its", "one", "oneself", "one's" }));
public static final Set<String> facilityVehicleWeaponPronounsEn = Generics.newHashSet(Arrays.asList(new String[]{ "it", "itself", "its", "they", "where" }));
public static final Set<String> miscPronounsEn = Generics.newHashSet(Arrays.asList(new String[]{"it", "itself", "its", "they", "where" }));
public static final Set<String> reflexivePronounsEn = Generics.newHashSet(Arrays.asList(new String[]{"myself", "yourself", "yourselves", "himself", "herself", "itself", "ourselves", "themselves", "oneself"}));
public static final Set<String> transparentNounsEn = Generics.newHashSet(Arrays.asList(new String[]{"bunch", "group",
"breed", "class", "ilk", "kind", "half", "segment", "top", "bottom", "glass", "bottle",
"box", "cup", "gem", "idiot", "unit", "part", "stage", "name", "division", "label", "group", "figure",
"series", "member", "members", "first", "version", "site", "side", "role", "largest", "title", "fourth",
"third", "second", "number", "place", "trio", "two", "one", "longest", "highest", "shortest",
"head", "resident", "collection", "result", "last"
}));
public static final Set<String> stopWordsEn = Generics.newHashSet(Arrays.asList(new String[]{"a", "an", "the", "of", "at",
"on", "upon", "in", "to", "from", "out", "as", "so", "such", "or", "and", "those", "this", "these", "that",
"for", ",", "is", "was", "am", "are", "'s", "been", "were"}));
public static final Set<String> notOrganizationPRPEn = Generics.newHashSet(Arrays.asList(new String[]{"i", "me", "myself",
"mine", "my", "yourself", "he", "him", "himself", "his", "she", "her", "herself", "hers", "here"}));
public static final Set<String> quantifiers2En = Generics.newHashSet(Arrays.asList("all", "both", "neither", "either"));
public static final Set<String> determinersEn = Generics.newHashSet(Arrays.asList("the", "this", "that", "these", "those", "his", "her", "my", "your", "their", "our"));
public static final Set<String> negationsEn = Generics.newHashSet(Arrays.asList("n't","not", "nor", "neither", "never", "no", "non", "any", "none", "nobody", "nothing", "nowhere", "nearly","almost",
"if", "false", "fallacy", "unsuccessfully", "unlikely", "impossible", "improbable", "uncertain", "unsure", "impossibility", "improbability", "cancellation", "breakup", "lack",
"long-stalled", "end", "rejection", "failure", "avoid", "bar", "block", "break", "cancel", "cease", "cut", "decline", "deny", "deprive", "destroy", "excuse",
"fail", "forbid", "forestall", "forget", "halt", "lose", "nullify", "prevent", "refrain", "reject", "rebut", "remain", "refuse", "stop", "suspend", "ward"));
public static final Set<String> neg_relationsEn = Generics.newHashSet(Arrays.asList("prep_without", "prepc_without", "prep_except", "prepc_except", "prep_excluding", "prepx_excluding",
"prep_if", "prepc_if", "prep_whether", "prepc_whether", "prep_away_from", "prepc_away_from", "prep_instead_of", "prepc_instead_of"));
public static final Set<String> modalsEn = Generics.newHashSet(Arrays.asList("can", "could", "may", "might", "must", "should", "would", "seem",
"able", "apparently", "necessarily", "presumably", "probably", "possibly", "reportedly", "supposedly",
"inconceivable", "chance", "impossibility", "improbability", "encouragement", "improbable", "impossible",
"likely", "necessary", "probable", "possible", "uncertain", "unlikely", "unsure", "likelihood", "probability",
"possibility", "eventual", "hypothetical" , "presumed", "supposed", "reported", "apparent"));
//
// WordLists for Chinese
//
public static final Set<String> reportVerbZh = Generics.newHashSet(Arrays.asList(
"说", "讲", "问", "曰", "劝", "唱", "告诉", "报告", "回答", "承认", "描述", "忠告", "解释", "表示", "保证", "感觉", "预测", "预计", "忘记", "希望",
"想象", "暗示", "指示", "证明", "提示", "说服", "提倡", "拒绝", "否认", "欢迎", "怀疑", "总结", "演讲", "争论"));
public static final Set<String> reportNounZh = Generics.newHashSet(Arrays.asList(
"报告", "回答", "描述", "忠告", "解释", "表示", "保证", "感觉", "预测", "预计", "希望", "想象", "暗示", "指示", "证明", "提示", "提倡", "欢迎",
"怀疑", "总结", "演讲", "争论", "意识", "论文", "看法"));
public static final Set<String> nonWordsZh = Generics.newHashSet(Arrays.asList("啊", "嗯", "哦"));
public static final Set<String> copulasZh = Generics.newHashSet(Arrays.asList(new String[]{}));
public static final Set<String> quantifiersZh = Generics.newHashSet(Arrays.asList("所有", "没有", "一些", "有些", "都"));
public static final Set<String> partsZh = Generics.newHashSet(Arrays.asList("半", "一", "二", "三", "四", "五", "六", "七", "八", "九", "十", "都"));
public static final Set<String> temporalsZh = Generics.newHashSet(Arrays.asList(
"秒", "分钟", "刻", "小时", "钟头", "天", "星期", "礼拜", "月", "年", "年代", "世纪",
"星期一", "星期二", "星期三", "星期四", "星期五", "星期六", "星期日", "星期天", "现在",
"昨天", "明天", "时代", "时间", "时候", "早上", "中午", "下午", "晚上", "天", "夜",
"学期", "冬天", "春天", "夏天", "秋天", "季节",
"一月份", "二月份", "三月份", "四月份", "五月份", "六月份", "七月份", "八月份", "九月份", "十月份", "十一月份", "十二月份"));
public static final Set<String> femalePronounsZh = Generics.newHashSet(Arrays.asList(new String[]{ "她", "她们" }));
public static final Set<String> malePronounsZh = Generics.newHashSet(Arrays.asList(new String[]{ "他", "他们" }));
public static final Set<String> neutralPronounsZh = Generics.newHashSet(Arrays.asList(new String[]{ "它", "它们", "谁", "什么", "那", "那儿", "那个", "那里", "哪", "哪个", "哪儿", "哪里", "这","这儿", "这个", "这里" }));
public static final Set<String> possessivePronounsZh = Generics.newHashSet(Arrays.asList(new String[]{}));
public static final Set<String> otherPronounsZh = Generics.newHashSet(Arrays.asList(new String[]{ "谁", "哪里", "哪个", "哪些", "哪儿" }));
public static final Set<String> thirdPersonPronounsZh = Generics.newHashSet(Arrays.asList(new String[]{ "她", "她们", "他", "他们" }));
public static final Set<String> secondPersonPronounsZh = Generics.newHashSet(Arrays.asList(new String[]{ "你", "你们", "您" }));
public static final Set<String> firstPersonPronounsZh = Generics.newHashSet(Arrays.asList(new String[]{ "我", "我们", "咱们", "咱"}));
public static final Set<String> moneyPercentNumberPronounsZh = Generics.newHashSet(Arrays.asList(new String[]{ "它" }));
public static final Set<String> dateTimePronounsZh = Generics.newHashSet(Arrays.asList(new String[]{}));
public static final Set<String> organizationPronounsZh = Generics.newHashSet(Arrays.asList(new String[]{ "它", "他们", "谁", "什么", "那", "那个", "那里", "哪", "哪个", "哪里", "这", "这个", "这里" }));
public static final Set<String> locationPronounsZh = Generics.newHashSet(Arrays.asList(new String[]{ "它", "哪里", "哪个", "这里", "这儿", "那里", "那儿" }));
public static final Set<String> inanimatePronounsZh = Generics.newHashSet(Arrays.asList(new String[]{ "它", "它们", "那", "那儿", "那个", "那里", "哪", "哪个", "哪儿", "哪里", "这","这儿", "这个", "这里" }));
public static final Set<String> animatePronounsZh = Generics.newHashSet(Arrays.asList(new String[]{ "我", "我们", "你", "你们", "她", "她们", "他", "他们", "谁" }));
public static final Set<String> indefinitePronounsZh = Generics.newHashSet(Arrays.asList(new String[]{ "谁", "另外", "任何", "每", "所有", "许多", "一些" }));
public static final Set<String> relativePronounsZh = Generics.newHashSet(); // Chinese doesn't have relative pronouns
public static final Set<String> interrogativePronounsZh = Generics.newHashSet(Arrays.asList(new String[]{"什", "什么时候", "哪边", "怎", "甚么", "谁们", "啥", "干什么", "为何", "哪里", "哪个", "么", "哪", "哪些", "什么样", "多少", "怎样", "怎么样", "为什么", "谁", "怎么", "几", "什么"})); // Need to filter these
public static final Set<String> GPEPronounsZh = Generics.newHashSet(Arrays.asList(new String[]{ "它", "它们", "他们", "那", "那儿", "那个", "那里", "哪", "哪个", "哪儿", "哪里", "这","这儿", "这个", "这里" }));
public static final Set<String> pluralPronounsZh = Generics.newHashSet(Arrays.asList(new String[]{ "我们", "你们", "她们", "他们", "它们", "咱们" }));
public static final Set<String> singularPronounsZh = Generics.newHashSet(Arrays.asList(new String[]{ "我", "你", "您", "她", "他" }));
public static final Set<String> facilityVehicleWeaponPronounsZh = Generics.newHashSet(Arrays.asList(new String[]{ "它", "他们", "哪里", "哪儿" }));
public static final Set<String> miscPronounsZh = Generics.newHashSet(Arrays.asList(new String[]{ "它", "他们", "哪里", "哪儿" }));
public static final Set<String> reflexivePronounsZh = Generics.newHashSet(Arrays.asList(new String[]{ "自己" }));
public static final Set<String> transparentNounsZh = Generics.newHashSet(Arrays.asList(new String[]{}));
public static final Set<String> stopWordsZh = Generics.newHashSet(Arrays.asList(new String[]{ "是", "和", "在" }));
public static final Set<String> notOrganizationPRPZh = Generics.newHashSet(Arrays.asList(new String[]{ "我", "我们", "你", "你们", "她", "她们", "他", "他们" }));
public static final Set<String> quantifiers2Zh = Generics.newHashSet(Arrays.asList( "每", "所有" ));
public static final Set<String> determinersZh = Generics.newHashSet(Arrays.asList( "这", "这个", "这些", "那", "那个", "那些" ));
public static final Set<String> negationsZh = Generics.newHashSet(Arrays.asList( "不", "没", "否", "如果", "可能", "输", "失败", "否认" ));
public static final Set<String> neg_relationsZh = Generics.newHashSet();
public static final Set<String> modalsZh = Generics.newHashSet(Arrays.asList( "能", "可能", "可以", "应该", "必须" ));
public static final Set<String> titleWordsZh = Generics.newHashSet(Arrays.asList(
"总统", "总理", "顾问", "部长", "市长", "省长", "先生", "外长", "教授", "副总理", "副总统",
"大使", "同志", "王妃", "国王", "主席", "王后", "王子", "首相", "经理", "秘书", "女士",
"总经理"));
public static final Set<String> removeWordsZh = Generics.newHashSet(Arrays.asList(
"_", // [cdm] Don't know the source of this one; doesn't seem to be in devset (with gold mentions)
"quot", //"quot" is a formatting error in CoNLL data
// "人", // a little dangerous 14 real cases though many not.
"时候", // okay but rare
// "问题", // dangerous - real case 1/3 of the time
// "情况", // dangerous - real case 1/3 of the time
"未来", // ok
// "战争", // a little dangerous
"可能", // ok
"新华社", // Xinhua news agency -- kind of a cheat, but....
"第一", "第二", "第三", "第四", "第五", "第六", "第七", "第八", "第九", // ordinals - should have regex or NER; there are also some with arabic numerals
"美军", "中央台", "时间" // cdm added these ones
));
public static final Set<String> removeCharsZh = Generics.newHashSet(Arrays.asList(
// "什么的", // in one spurious mention, but caught by general de rule!
// "哪", // slightly dangerous
"什么", // "what" -- good one, this interrogative isn't in mentions
"谁", // "Who" -- good interrogative to have
"啥", // "What"
"哪儿", // "where" -- rare but okay
// "哪里", // "where" but some are mentions
// "人们", // "people" -- dangerous
// "年", // year -- dangerous
"原因", // "reason" -- okay
// "啥时", // doesn't seem to appear in devset; ends in de
// "quot",
"多少" // "How many" [cdm added used to be t ested separately]
));
/** KBP pronominal mentions are at present only 3rd person, non-neuter, non-reflexive pronouns.
* At present we just mix English and Chinese ones, since it does no harm.
*/
private static final Set<String> kbpPronominalMentions = Generics.newHashSet(Arrays.asList(
"he", "him", "his", "she", "her", "hers",
"他", "她", "他们", "她们", "她的", "他的"
));
/**
* Returns whether the given token counts as a valid pronominal mention for KBP.
* This method (at present) works for either Chinese or English.
*
* @param word The token to classify.
* @return true if this token is a pronoun that KBP should recognize (3rd person, non-neuter, non reflexive).
*/
public static boolean isKbpPronominalMention(String word) {
return kbpPronominalMentions.contains(word.toLowerCase());
}
}
| stanfordnlp/CoreNLP | src/edu/stanford/nlp/coref/data/WordLists.java |
2 | /*Copyright (C) 2020 THL A29 Limited, a Tencent company. All rights reserved.
This source code is licensed under the Apache License Version 2.0.*/
package apijson;
import java.io.File;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.util.Objects;
import java.util.regex.Pattern;
/**通用字符串(String)相关类,为null时返回""
* @author Lemon
* @use StringUtil.
*/
public class StringUtil {
private static final String TAG = "StringUtil";
public StringUtil() {
}
public static final String UTF_8 = "utf-8";
public static final String EMPTY = "无";
public static final String UNKNOWN = "未知";
public static final String UNLIMITED = "不限";
public static final String I = "我";
public static final String YOU = "你";
public static final String HE = "他";
public static final String SHE = "她";
public static final String IT = "它";
public static final String MALE = "男";
public static final String FEMALE = "女";
public static final String TODO = "未完成";
public static final String DONE = "已完成";
public static final String FAIL = "失败";
public static final String SUCCESS = "成功";
public static final String SUNDAY = "日";
public static final String MONDAY = "一";
public static final String TUESDAY = "二";
public static final String WEDNESDAY = "三";
public static final String THURSDAY = "四";
public static final String FRIDAY = "五";
public static final String SATURDAY = "六";
public static final String YUAN = "元";
private static String currentString = "";
/**获取刚传入处理后的string
* @must 上个影响currentString的方法 和 这个方法都应该在同一线程中,否则返回值可能不对
* @return
*/
public static String getCurrentString() {
return currentString == null ? "" : currentString;
}
//获取string,为null时返回"" <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
/**获取string,为null则返回""
* @param object
* @return
*/
public static String getString(Object object) {
return object == null ? "" : object.toString();
}
/**获取string,为null则返回""
* @param cs
* @return
*/
public static String getString(CharSequence cs) {
return cs == null ? "" : cs.toString();
}
/**获取string,为null则返回""
* @param s
* @return
*/
public static String getString(String s) {
return s == null ? "" : s;
}
/**获取string,为null则返回""
* ignoreEmptyItem = false;
* split = ","
* @param array
* @return {@link #getString(Object[], boolean)}
*/
public static String getString(Object[] array) {
return getString(array, false);
}
/**获取string,为null则返回""
* split = ","
* @param array
* @param ignoreEmptyItem
* @return {@link #getString(Object[], boolean)}
*/
public static String getString(Object[] array, boolean ignoreEmptyItem) {
return getString(array, null, ignoreEmptyItem);
}
/**获取string,为null则返回""
* ignoreEmptyItem = false;
* @param array
* @param split
* @return {@link #getString(Object[], String, boolean)}
*/
public static String getString(Object[] array, String split) {
return getString(array, split, false);
}
//CS304 Issue link: https://github.com/Tencent/APIJSON/issues/182
/**获取string,为null则返回""
* @param array -the str array given
* @param split -the token used to split
* @param ignoreEmptyItem -whether to ignore empty item or not
* @return {@link #getString(Object[], String, boolean)}
* <p>Here we replace the simple "+" way of concatenating with Stringbuilder 's append</p>
*/
public static String getString(Object[] array, String split, boolean ignoreEmptyItem) {
StringBuilder s = new StringBuilder("");
if (array != null) {
if (split == null) {
split = ",";
}
for (int i = 0; i < array.length; i++) {
if (ignoreEmptyItem && isEmpty(array[i], true)) {
continue;
}
s.append(((i > 0 ? split : "") + array[i]));
}
}
return getString(s.toString());
}
//获取string,为null时返回"" >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
//获取去掉前后空格后的string<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
/**获取去掉前后空格后的string,为null则返回""
* @param object
* @return
*/
public static String getTrimedString(Object object) {
return getTrimedString(getString(object));
}
/**获取去掉前后空格后的string,为null则返回""
* @param cs
* @return
*/
public static String getTrimedString(CharSequence cs) {
return getTrimedString(getString(cs));
}
/**获取去掉前后空格后的string,为null则返回""
* @param s
* @return
*/
public static String getTrimedString(String s) {
return getString(s).trim();
}
//获取去掉前后空格后的string>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
//获取去掉所有空格后的string <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
/**获取去掉所有空格后的string,为null则返回""
* @param object
* @return
*/
public static String getNoBlankString(Object object) {
return getNoBlankString(getString(object));
}
/**获取去掉所有空格后的string,为null则返回""
* @param cs
* @return
*/
public static String getNoBlankString(CharSequence cs) {
return getNoBlankString(getString(cs));
}
/**获取去掉所有空格后的string,为null则返回""
* @param s
* @return
*/
public static String getNoBlankString(String s) {
return getString(s).replaceAll("\\s", "");
}
//获取去掉所有空格后的string >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
//获取string的长度<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
/**获取string的长度,为null则返回0
* @param object
* @param trim
* @return
*/
public static int getLength(Object object, boolean trim) {
return getLength(getString(object), trim);
}
/**获取string的长度,为null则返回0
* @param cs
* @param trim
* @return
*/
public static int getLength(CharSequence cs, boolean trim) {
return getLength(getString(cs), trim);
}
/**获取string的长度,为null则返回0
* @param s
* @param trim
* @return
*/
public static int getLength(String s, boolean trim) {
s = trim ? getTrimedString(s) : s;
return getString(s).length();
}
//获取string的长度>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
//判断字符是否为空 <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
/**判断字符是否为空 trim = true
* @param obj
* @return
*/
public static boolean isEmpty(Object obj) {
return isEmpty(obj, true);
}
/**判断字符是否为空
* @param obj
* @param trim
* @return
*/
public static boolean isEmpty(Object obj, boolean trim) {
return isEmpty(getString(obj), trim);
}
/**判断字符是否为空 trim = true
* @param cs
* @return
*/
public static boolean isEmpty(CharSequence cs) {
return isEmpty(cs, true);
}
/**判断字符是否为空
* @param cs
* @param trim
* @return
*/
public static boolean isEmpty(CharSequence cs, boolean trim) {
return isEmpty(getString(cs), trim);
}
/**判断字符是否为空 trim = true
* @param s
* @return
*/
public static boolean isEmpty(String s) {
return isEmpty(s, true);
}
/**判断字符是否为空
* @param s
* @param trim
* @return
*/
public static boolean isEmpty(String s, boolean trim) {
// Log.i(TAG, "getTrimedString s = " + s);
if (s == null) {
return true;
}
if (trim) {
s = s.trim();
}
if (s.isEmpty()) {
return true;
}
currentString = s;
return false;
}
//判断字符是否为空 >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
//判断字符是否非空 <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
/**判断字符是否非空 trim = true
* @param object
* @return
*/
public static boolean isNotEmpty(Object obj) {
return ! isEmpty(obj);
}
/**判断字符是否非空
* @param obj
* @param trim
* @return
*/
public static boolean isNotEmpty(Object obj, boolean trim) {
return ! isEmpty(obj, trim);
}
/**判断字符是否非空 trim = true
* @param cs
* @return
*/
public static boolean isNotEmpty(CharSequence cs) {
return ! isEmpty(cs);
}
/**判断字符是否非空
* @param cs
* @param trim
* @return
*/
public static boolean isNotEmpty(CharSequence cs, boolean trim) {
return ! isEmpty(cs, trim);
}
/**判断字符是否非空 trim = true
* @param s
* @return
*/
public static boolean isNotEmpty(String s) {
return ! isEmpty(s);
}
/**判断字符是否非空
* @param s
* @param trim
* @return
*/
public static boolean isNotEmpty(String s, boolean trim) {
return ! isEmpty(s, trim);
}
//判断字符是否非空 >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
//判断字符类型 <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
public static final Pattern PATTERN_NUMBER;
public static final Pattern PATTERN_PHONE;
public static final Pattern PATTERN_EMAIL;
public static final Pattern PATTERN_ID_CARD;
public static final Pattern PATTERN_ALPHA;
public static final Pattern PATTERN_PASSWORD; //TODO
public static final Pattern PATTERN_NAME;
public static final Pattern PATTERN_ALPHA_BIG;
public static final Pattern PATTERN_ALPHA_SMALL;
public static final Pattern PATTERN_BRANCH_URL;
static {
PATTERN_NUMBER = Pattern.compile("^[0-9]+$");
PATTERN_ALPHA = Pattern.compile("^[a-zA-Z]+$");
PATTERN_ALPHA_BIG = Pattern.compile("^[A-Z]+$");
PATTERN_ALPHA_SMALL = Pattern.compile("^[a-z]+$");
PATTERN_NAME = Pattern.compile("^[0-9a-zA-Z_.:]+$");//已用55个中英字符测试通过
//newest phone regex expression reference https://github.com/VincentSit/ChinaMobilePhoneNumberRegex
PATTERN_PHONE = Pattern.compile("^1(?:3\\d{3}|5[^4\\D]\\d{2}|8\\d{3}|7(?:[0-35-9]\\d{2}|4(?:0\\d|1[0-2]|9\\d))|9[0-35-9]\\d{2}|6[2567]\\d{2}|4(?:(?:10|4[01])\\d{3}|[68]\\d{4}|[579]\\d{2}))\\d{6}$");
PATTERN_EMAIL = Pattern.compile("^([a-zA-Z0-9_\\-\\.]+)@((\\[[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.)|(([a-zA-Z0-9\\-]+\\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\\]?)$");
PATTERN_ID_CARD = Pattern.compile("(^[1-9]\\d{5}(18|19|([23]\\d))\\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\\d{3}[0-9Xx]$)|(^[1-9]\\d{5}\\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\\d{2}$)");
PATTERN_PASSWORD = Pattern.compile("^[0-9a-zA-Z]+$");
PATTERN_BRANCH_URL = Pattern.compile("^[0-9a-zA-Z-_/]+$");
}
/**判断手机格式是否正确
* @param phone
* @return
*/
public static boolean isPhone(String phone) {
if (isNotEmpty(phone, true) == false) {
return false;
}
currentString = phone;
return PATTERN_PHONE.matcher(phone).matches();
}
/**判断手机格式是否正确
* @param s
* @return
*/
public static boolean isPassword(String s) {
return getLength(s, false) >= 6 && PATTERN_PASSWORD.matcher(s).matches();
}
/**判断是否全是数字密码
* @param s
* @return
*/
public static boolean isNumberPassword(String s) {
return getLength(s, false) == 6 && isNumer(s);
}
/**判断email格式是否正确
* @param email
* @return
*/
public static boolean isEmail(String email) {
if (isEmpty(email, true)) {
return false;
}
currentString = email;
return PATTERN_EMAIL.matcher(email).matches();
}
/**判断是否全是验证码
* @param s
* @return
*/
public static boolean isVerify(String s) {
return getLength(s, false) >= 4 && isNumer(s);
}
/**判断是否全是数字
* @param s
* @return
*/
public static boolean isNumer(String s) {
if (isNotEmpty(s, true) == false) {
return false;
}
currentString = s;
return PATTERN_NUMBER.matcher(s).matches();
}
/**判断是否全是字母
* @param s
* @return
*/
public static boolean isAlpha(String s) {
if (isEmpty(s, true)) {
return false;
}
currentString = s;
return PATTERN_ALPHA.matcher(s).matches();
}
/**判断是否全是数字或字母
* @param s
* @return
*/
public static boolean isNumberOrAlpha(String s) {
return isNumer(s) || isAlpha(s);
}
/**判断是否为代码名称,只能包含字母,数字或下划线
* @param s
* @return
*/
public static boolean isName(String s) {
if (s == null || s.isEmpty()) {
return false;
}
String first = s.substring(0, 1);
if ("_".equals(first) == false && PATTERN_ALPHA.matcher(first).matches() == false) {
return false;
}
return s.length() <= 1 ? true : PATTERN_NAME.matcher(s.substring(1)).matches();
}
/**判断是否为首字母大写的代码名称
* @param s
* @return
*/
public static boolean isBigName(String s) {
if (s == null || s.isEmpty() || PATTERN_ALPHA_BIG.matcher(s.substring(0, 1)).matches() == false) {
return false;
}
return s.length() <= 1 ? true : PATTERN_NAME.matcher(s.substring(1)).matches();
}
/**判断是否为首字母小写的代码名称
* @param s
* @return
*/
public static boolean isSmallName(String s) {
if (s == null || s.isEmpty() || PATTERN_ALPHA_SMALL.matcher(s.substring(0, 1)).matches() == false) {
return false;
}
return s.length() <= 1 ? true : PATTERN_NAME.matcher(s.substring(1)).matches();
}
/**判断字符类型是否是身份证号
* @param number
* @return
*/
public static boolean isIDCard(String number) {
if (isNumberOrAlpha(number) == false) {
return false;
}
number = getString(number);
if (number.length() == 15) {
Log.i(TAG, "isIDCard number.length() == 15 old IDCard");
currentString = number;
return true;
}
if (number.length() == 18) {
currentString = number;
return true;
}
return false;
}
public static final String HTTP = "http";
public static final String URL_PREFIX = "http://";
public static final String URL_PREFIXs = "https://";
public static final String URL_STAFFIX = URL_PREFIX;
public static final String URL_STAFFIXs = URL_PREFIXs;
/**判断字符类型是否是网址
* @param url
* @return
*/
public static boolean isUrl(String url) {
if (isNotEmpty(url, true) == false) {
return false;
}
if (! url.startsWith(URL_PREFIX) && ! url.startsWith(URL_PREFIXs)) {
return false;
}
currentString = url;
return true;
}
public static boolean isBranchUrl(String branchUrl) {
if (isEmpty(branchUrl, false)) {
return false;
}
return PATTERN_BRANCH_URL.matcher(branchUrl).matches();
}
public static final String FILE_PATH_PREFIX = "file://";
/**判断文件路径是否存在
* @param path
* @return
*/
public static boolean isFilePathExist(String path) {
return StringUtil.isFilePath(path) && new File(path).exists();
}
public static final String SEPARATOR = "/";
/**判断是否为路径
* @param path
* @return
*/
public static boolean isPath(String path) {
return StringUtil.isNotEmpty(path, true) && path.contains(SEPARATOR)
&& path.contains(SEPARATOR + SEPARATOR) == false && path.endsWith(SEPARATOR) == false;
}
/**判断字符类型是否是路径
* @param path
* @return
*/
public static boolean isFilePath(String path) {
if (isNotEmpty(path, true) == false) {
return false;
}
if (! path.contains(".") || path.endsWith(".")) {
return false;
}
currentString = path;
return true;
}
//判断字符类型 >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
//提取特殊字符<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
/**去掉string内所有非数字类型字符
* @param object
* @return
*/
public static String getNumber(Object object) {
return getNumber(getString(object));
}
/**去掉string内所有非数字类型字符
* @param cs
* @return
*/
public static String getNumber(CharSequence cs) {
return getNumber(getString(cs));
}
/**去掉string内所有非数字类型字符
* @param s
* @return
*/
public static String getNumber(String s) {
return getNumber(s, false);
}
//CS304 Issue link: https://github.com/Tencent/APIJSON/issues/182
/**去掉string内所有非数字类型字符
* @param s -string passed in
* @param onlyStart 中间有非数字时只获取前面的数字
* @return limit String
* <p>Here we replace the simple "+" way of concatenating with Stringbuilder 's append</p>
*/
public static String getNumber(String s, boolean onlyStart) {
if (isNotEmpty(s, true) == false) {
return "";
}
StringBuilder numberString = new StringBuilder("");
String single;
for (int i = 0; i < s.length(); i++) {
single = s.substring(i, i + 1);
if (isNumer(single)) {
numberString.append(single);
} else {
if (onlyStart) {
return numberString.toString();
}
}
}
return numberString.toString();
}
//提取特殊字符>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
//校正(自动补全等)字符串<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
/**获取网址,自动补全
* @param url
* @return
*/
public static String getCorrectUrl(String url) {
Log.i(TAG, "getCorrectUrl : \n" + url);
if (isNotEmpty(url, true) == false) {
return "";
}
// if (! url.endsWith("/") && ! url.endsWith(".html")) {
// url = url + "/";
// }
if (isUrl(url) == false) {
return URL_PREFIX + url;
}
return url;
}
/**获取去掉所有 空格 、"-" 、"+86" 后的phone
* @param phone
* @return
*/
public static String getCorrectPhone(String phone) {
if (isNotEmpty(phone, true) == false) {
return "";
}
phone = getNoBlankString(phone);
phone = phone.replaceAll("-", "");
if (phone.startsWith("+86")) {
phone = phone.substring(3);
}
return phone;
}
/**获取邮箱,自动补全
* @param email
* @return
*/
public static String getCorrectEmail(String email) {
if (isNotEmpty(email, true) == false) {
return "";
}
email = getNoBlankString(email);
if (isEmail(email) == false && ! email.endsWith(".com")) {
email += ".com";
}
return email;
}
public static final int PRICE_FORMAT_DEFAULT = 0;
public static final int PRICE_FORMAT_PREFIX = 1;
public static final int PRICE_FORMAT_SUFFIX = 2;
public static final int PRICE_FORMAT_PREFIX_WITH_BLANK = 3;
public static final int PRICE_FORMAT_SUFFIX_WITH_BLANK = 4;
public static final String[] PRICE_FORMATS = {
"", "¥", "元", "¥ ", " 元"
};
/**获取价格,保留两位小数
* @param price
* @return
*/
public static String getPrice(String price) {
return getPrice(price, PRICE_FORMAT_DEFAULT);
}
//CS304 Issue link: https://github.com/Tencent/APIJSON/issues/182
/**获取价格,保留两位小数
* @param price -price passed in
* @param formatType 添加单位(元)
* @return limit String
* <p>Here we replace the simple "+" way of concatenating with Stringbuilder 's append</p>
*/
public static String getPrice(String price, int formatType) {
if (isNotEmpty(price, true) == false) {
return getPrice(0, formatType);
}
//单独写到getCorrectPrice? <<<<<<<<<<<<<<<<<<<<<<
String correctPrice;
StringBuilder correctPriceBuilder = new StringBuilder("");
String s;
for (int i = 0; i < price.length(); i++) {
s = price.substring(i, i + 1);
if (".".equals(s) || isNumer(s)) {
correctPriceBuilder.append(s);
}
}
correctPrice = correctPriceBuilder.toString();
//单独写到getCorrectPrice? >>>>>>>>>>>>>>>>>>>>>>
Log.i(TAG, "getPrice <<<<<<<<<<<<<<<<<< correctPrice = " + correctPrice);
if (correctPrice.contains(".")) {
// if (correctPrice.startsWith(".")) {
// correctPrice = 0 + correctPrice;
// }
if (correctPrice.endsWith(".")) {
correctPrice = correctPrice.replaceAll(".", "");
}
}
Log.i(TAG, "getPrice correctPrice = " + correctPrice + " >>>>>>>>>>>>>>>>");
return isNotEmpty(correctPrice, true) ? getPrice(new BigDecimal(0 + correctPrice), formatType) : getPrice(0, formatType);
}
/**获取价格,保留两位小数
* @param price
* @return
*/
public static String getPrice(BigDecimal price) {
return getPrice(price, PRICE_FORMAT_DEFAULT);
}
/**获取价格,保留两位小数
* @param price
* @return
*/
public static String getPrice(double price) {
return getPrice(price, PRICE_FORMAT_DEFAULT);
}
/**获取价格,保留两位小数
* @param price
* @param formatType 添加单位(元)
* @return
*/
public static String getPrice(BigDecimal price, int formatType) {
return getPrice(price == null ? 0 : price.doubleValue(), formatType);
}
/**获取价格,保留两位小数
* @param price
* @param formatType 添加单位(元)
* @return
*/
public static String getPrice(double price, int formatType) {
String s = new DecimalFormat("#########0.00").format(price);
switch (formatType) {
case PRICE_FORMAT_PREFIX:
return PRICE_FORMATS[PRICE_FORMAT_PREFIX] + s;
case PRICE_FORMAT_SUFFIX:
return s + PRICE_FORMATS[PRICE_FORMAT_SUFFIX];
case PRICE_FORMAT_PREFIX_WITH_BLANK:
return PRICE_FORMATS[PRICE_FORMAT_PREFIX_WITH_BLANK] + s;
case PRICE_FORMAT_SUFFIX_WITH_BLANK:
return s + PRICE_FORMATS[PRICE_FORMAT_SUFFIX_WITH_BLANK];
default:
return s;
}
}
public static String join(String[] arr) {
return join(arr);
}
/** 数组以指定分隔s拼接
* @param arr
* @param s
* @return
*/
public static String join(String[] arr, String s) {
if (s == null) {
s = ",";
}
StringBuilder sb = new StringBuilder();
for (int i = 0; i < arr.length; i++) {
sb.append(arr[i]);
if (i < arr.length-1) {
sb.append(s);
}
}
return sb.toString();
}
/**分割路径
* @param path
* @return
*/
public static String[] splitPath(String path) {
if (StringUtil.isNotEmpty(path, true) == false) {
return null;
}
return isPath(path) ? split(path, SEPARATOR) : new String[] {path};
}
/**将s分割成String[]
* @param s
* @return
*/
public static String[] split(String s) {
return split(s, null);
}
/**将s用split分割成String[]
* trim = true;
* @param s
* @param split
* @return
*/
public static String[] split(String s, String split) {
return split(s, split, true);
}
/**将s用split分割成String[]
* @param s
* @param trim 去掉前后两端的split
* @return
*/
public static String[] split(String s, boolean trim) {
return split(s, null, trim);
}
/**将s用split分割成String[]
* @param s
* @param split
* @param trim 去掉前后两端的split
* @return
*/
public static String[] split(String s, String split, boolean trim) {
s = getString(s);
if (s.isEmpty()) {
return null;
}
if (isEmpty(split, false)) {
split = ",";
}
if (trim) {
while (s.startsWith(split)) {
s = s.substring(split.length());
}
while (s.endsWith(split)) {
s = s.substring(0, s.length() - split.length());
}
}
return s.contains(split) ? s.split(split) : new String[]{s};
}
/**
* @param key
* @param suffix
* @return key + suffix,第一个字母小写
*/
public static String addSuffix(String key, String suffix) {
key = getNoBlankString(key);
if (key.isEmpty()) {
return firstCase(suffix);
}
return firstCase(key) + firstCase(suffix, true);
}
/**
* @param key
*/
public static String firstCase(String key) {
return firstCase(key, false);
}
/**
* @param key
* @param upper
* @return
*/
public static String firstCase(String key, boolean upper) {
key = getString(key);
if (key.isEmpty()) {
return "";
}
String first = key.substring(0, 1);
key = (upper ? first.toUpperCase() : first.toLowerCase()) + key.substring(1, key.length());
return key;
}
/**全部大写
* @param s
* @return
*/
public static String toUpperCase(String s) {
return toUpperCase(s, false);
}
/**全部大写
* @param s
* @param trim
* @return
*/
public static String toUpperCase(String s, boolean trim) {
s = trim ? getTrimedString(s) : getString(s);
return s.toUpperCase();
}
/**全部小写
* @param s
* @return
*/
public static String toLowerCase(String s) {
return toLowerCase(s, false);
}
/**全部小写
* @param s
* @return
*/
public static String toLowerCase(String s, boolean trim) {
s = trim ? getTrimedString(s) : getString(s);
return s.toLowerCase();
}
public static String concat(String left, String right) {
return concat(left, right, null);
}
public static String concat(String left, String right, String split) {
return concat(left, right, split, true);
}
public static String concat(String left, String right, boolean trim) {
return concat(left, right, null, trim);
}
public static String concat(String left, String right, String split, boolean trim) {
if (isEmpty(left, trim)) {
return right;
}
if (isEmpty(right, trim)) {
return left;
}
if (split == null) {
split = ",";
}
return left + split + right;
}
//校正(自动补全等)字符串>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
public static boolean equals(Object s1, Object s2) {
return Objects.equals(s1, s2);
}
public static boolean equalsIgnoreCase(String s1, String s2) {
if (s1 == s2) {
return true;
}
if (s1 == null || s2 == null) {
return false;
}
return s1.equalsIgnoreCase(s2);
}
}
| Tencent/APIJSON | APIJSONORM/src/main/java/apijson/StringUtil.java |
3 | package org.nutz.lang;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.Closeable;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.Flushable;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PushbackInputStream;
import java.io.Reader;
import java.io.Writer;
import org.nutz.lang.stream.FileChannelInputStream;
import org.nutz.lang.stream.FileChannelOutputStream;
import org.nutz.lang.stream.VoidInputStream;
import org.nutz.resource.NutResource;
import org.nutz.resource.Scans;
/**
* 提供了一组创建 Reader/Writer/InputStream/OutputStream 的便利函数
*
* @author zozoh([email protected])
* @author Wendal([email protected])
* @author bonyfish([email protected])
*/
public abstract class Streams {
private static final int BUF_SIZE = 8192;
/**
* 判断两个输入流是否严格相等
*/
public static boolean equals(InputStream sA, InputStream sB) throws IOException {
int dA;
while ((dA = sA.read()) != -1) {
int dB = sB.read();
if (dA != dB)
return false;
}
return sB.read() == -1;
}
/**
* 将一段文本全部写入一个writer。
* <p>
* <b style=color:red>注意</b>,它并不会关闭输出流
*
* @param writer
*
* @param cs
* 文本
* @throws IOException
*/
public static void write(Writer writer, CharSequence cs) throws IOException {
if (null != cs && null != writer) {
writer.write(cs.toString());
writer.flush();
}
}
/**
* 将一段文本全部写入一个writer。
* <p>
* <b style=color:red>注意</b>,它会关闭输出流
*
* @param writer
* 输出流
* @param cs
* 文本
*/
public static void writeAndClose(Writer writer, CharSequence cs) {
try {
write(writer, cs);
}
catch (IOException e) {
throw Lang.wrapThrow(e);
}
finally {
safeFlush(writer);
safeClose(writer);
}
}
/**
* 将输入流写入一个输出流。块大小为 8192
* <p>
* <b style=color:red>注意</b>,它并不会关闭输入/出流
*
* @param ops
* 输出流
* @param ins
* 输入流
*
* @return 写入的字节数
* @throws IOException
*/
public static long write(OutputStream ops, InputStream ins) throws IOException {
return write(ops, ins, BUF_SIZE);
}
/**
* 将输入流写入一个输出流。
* <p>
* <b style=color:red>注意</b>,它并不会关闭输入/出流
*
* @param ops
* 输出流
* @param ins
* 输入流
* @param bufferSize
* 缓冲块大小
*
* @return 写入的字节数
*
* @throws IOException
*/
public static long write(OutputStream ops, InputStream ins, int bufferSize) throws IOException {
return write(ops, ins, -1, bufferSize);
}
/**
* 将输入流写入一个输出流。
* <p>
* <b style=color:red>注意</b>,它并不会关闭输入/出流
*
* @param ops
* 输出流
* @param ins
* 输入流
* @param limit
* 最多写入多少字节,0 或负数表示不限
* @param bufferSize
* 缓冲块大小
*
* @return 写入的字节数
*
* @throws IOException
*/
public static long write(OutputStream ops, InputStream ins, long limit, int bufferSize)
throws IOException {
if (null == ops || null == ins)
return 0;
byte[] buf = new byte[bufferSize];
int len;
long bytesCount = 0;
if (limit > 0) {
long remain = limit;
while (-1 != (len = ins.read(buf))) {
// 还可以写入的字节数
if (len > remain) {
len = (int) remain;
remain = 0;
}
// 减去
else {
remain -= len;
}
bytesCount += len;
ops.write(buf, 0, len);
// 写够了
if (remain <= 0) {
break;
}
}
}
// 全写
else {
while (-1 != (len = ins.read(buf))) {
bytesCount += len;
ops.write(buf, 0, len);
}
}
// 啥都没写,强制触发一下写
// 这是考虑到 walnut 的输出流实现,比如你写一个空文件
// 那么输入流就是空的,但是 walnut 的包裹输出流并不知道你写过了
// 它人你就是打开一个输出流,然后再关上,所以自然不会对内容做改动
// 所以这里触发一个写,它就知道,喔你要写个空喔。
if (0 == bytesCount) {
ops.write(buf, 0, 0);
}
ops.flush();
return bytesCount;
}
/**
* 将输入流写入一个输出流。块大小为 8192
* <p>
* <b style=color:red>注意</b>,它会关闭输入/出流
*
* @param ops
* 输出流
* @param ins
* 输入流
* @return 写入的字节数
*/
public static long writeAndClose(OutputStream ops, InputStream ins) {
try {
return write(ops, ins);
}
catch (IOException e) {
throw Lang.wrapThrow(e);
}
finally {
safeFlush(ops);
safeClose(ops);
safeClose(ins);
}
}
/**
* 将文本输入流写入一个文本输出流。块大小为 8192
* <p>
* <b style=color:red>注意</b>,它并不会关闭输入/出流
*
* @param writer
* 输出流
* @param reader
* 输入流
* @throws IOException
*/
public static long write(Writer writer, Reader reader) throws IOException {
if (null == writer || null == reader)
return 0;
char[] cbuf = new char[BUF_SIZE];
int len, count = 0;
while (true) {
len = reader.read(cbuf);
if (len == -1)
break;
writer.write(cbuf, 0, len);
count += len;
}
return count;
}
/**
* 将文本输入流写入一个文本输出流。块大小为 8192
* <p>
* <b style=color:red>注意</b>,它会关闭输入/出流
*
* @param writer
* 输出流
* @param reader
* 输入流
*/
public static long writeAndClose(Writer writer, Reader reader) {
try {
return write(writer, reader);
}
catch (IOException e) {
throw Lang.wrapThrow(e);
}
finally {
safeFlush(writer);
safeClose(writer);
safeClose(reader);
}
}
/**
* 将一个字节数组写入一个输出流。
* <p>
* <b style=color:red>注意</b>,它并不会关闭输出流
*
* @param ops
* 输出流
* @param bytes
* 字节数组
* @throws IOException
*/
public static void write(OutputStream ops, byte[] bytes) throws IOException {
if (null == ops || null == bytes || bytes.length == 0)
return;
ops.write(bytes);
}
/**
* 将一个字节数组写入一个输出流。
* <p>
* <b style=color:red>注意</b>,它会关闭输出流
*
* @param ops
* 输出流
* @param bytes
* 字节数组
*/
public static void writeAndClose(OutputStream ops, byte[] bytes) {
try {
write(ops, bytes);
}
catch (IOException e) {
throw Lang.wrapThrow(e);
}
finally {
safeFlush(ops);
safeClose(ops);
}
}
/**
* 从一个文本流中读取全部内容并返回
* <p>
* <b style=color:red>注意</b>,它并不会关闭输出流
*
* @param reader
* 文本输出流
* @return 文本内容
* @throws IOException
*/
public static StringBuilder read(Reader reader) throws IOException {
StringBuilder sb = new StringBuilder();
read(reader, sb);
return sb;
}
/**
* 从一个文本流中读取全部内容并返回
* <p>
* <b style=color:red>注意</b>,它会关闭输入流
*
* @param reader
* 文本输入流
* @return 文本内容
* @throws IOException
*/
public static String readAndClose(Reader reader) {
try {
return read(reader).toString();
}
catch (IOException e) {
throw Lang.wrapThrow(e);
}
finally {
safeClose(reader);
}
}
/**
* 从一个文本流中读取全部内容并写入缓冲
* <p>
* <b style=color:red>注意</b>,它并不会关闭输出流
*
* @param reader
* 文本输出流
* @param sb
* 输出的文本缓冲
* @return 读取的字符数量
* @throws IOException
*/
public static int read(Reader reader, StringBuilder sb) throws IOException {
char[] cbuf = new char[BUF_SIZE];
int count = 0;
int len;
while (-1 != (len = reader.read(cbuf))) {
sb.append(cbuf, 0, len);
count += len;
}
return count;
}
/**
* 从一个文本流中读取全部内容并写入缓冲
* <p>
* <b style=color:red>注意</b>,它会关闭输出流
*
* @param reader
* 文本输出流
* @param sb
* 输出的文本缓冲
* @return 读取的字符数量
*/
public static int readAndClose(InputStreamReader reader, StringBuilder sb) {
try {
return read(reader, sb);
}
catch (IOException e) {
throw Lang.wrapThrow(e);
}
finally {
safeClose(reader);
}
}
/**
* 读取一个输入流中所有的字节
*
* @param ins
* 输入流,必须支持 available()
* @return 一个字节数组
* @throws IOException
*/
public static byte[] readBytes(InputStream ins) throws IOException {
ByteArrayOutputStream out = new ByteArrayOutputStream();
write(out, ins);
return out.toByteArray();
}
/**
* 读取一个输入流中所有的字节,并关闭输入流
*
* @param ins
* 输入流,必须支持 available()
* @return 一个字节数组
* @throws IOException
*/
public static byte[] readBytesAndClose(InputStream ins) {
byte[] bytes = null;
try {
bytes = readBytes(ins);
}
catch (IOException e) {
throw Lang.wrapThrow(e);
}
finally {
Streams.safeClose(ins);
}
return bytes;
}
/**
* 关闭一个可关闭对象,可以接受 null。如果成功关闭,返回 true,发生异常 返回 false
*
* @param cb
* 可关闭对象
* @return 是否成功关闭
*/
public static boolean safeClose(Closeable cb) {
if (null != cb)
try {
cb.close();
}
catch (IOException e) {
return false;
}
return true;
}
/**
* 安全刷新一个可刷新的对象,可接受 null
*
* @param fa
* 可刷新对象
*/
public static void safeFlush(Flushable fa) {
if (null != fa)
try {
fa.flush();
}
catch (IOException e) {}
}
/**
* 为一个输入流包裹一个缓冲流。如果这个输入流本身就是缓冲流,则直接返回
*
* @param ins
* 输入流。
* @return 缓冲输入流
*/
public static BufferedInputStream buff(InputStream ins) {
if (ins == null)
throw new NullPointerException("ins is null!");
if (ins instanceof BufferedInputStream)
return (BufferedInputStream) ins;
// BufferedInputStream的构造方法,竟然是允许null参数的!! 我&$#^$&%
return new BufferedInputStream(ins);
}
/**
* 创建采用 nio 方式更快速的文件输入流
*
* @param f
* 文件对象
* @return 管道文件数据流
*
* @throws FileNotFoundException
*/
public static FileChannelInputStream chanIn(File f) throws FileNotFoundException {
return chan(new FileInputStream(f));
}
/**
* 包裹采用 nio 方式更快速的文件输入流
*
* @param ins
* 文件输入流
* @return 管道文件数据流
*/
public static FileChannelInputStream chan(FileInputStream ins) {
if (ins == null)
throw new NullPointerException("ins is null!");
return new FileChannelInputStream(ins);
}
/**
* 创建采用 nio 方式更快速的文件输出流
*
* @param f
* 文件对象
* @param append
* true 为末尾附加模式,false 表示从开头开始写
*
* @return 管道文件数据流
* @throws FileNotFoundException
*/
public static FileChannelOutputStream chanOps(File f, boolean append)
throws FileNotFoundException {
return chan(new FileOutputStream(f, append));
}
/**
* 包裹采用 nio 方式更快速的文件输出流
*
* @param ins
* 文件输入流
* @return 管道文件数据流
*/
public static FileChannelOutputStream chan(FileOutputStream ops) {
if (ops == null)
throw new NullPointerException("ops is null!");
return new FileChannelOutputStream(ops);
}
/**
* 为一个输出流包裹一个缓冲流。如果这个输出流本身就是缓冲流,则直接返回
*
* @param ops
* 输出流。
* @return 缓冲输出流
*/
public static BufferedOutputStream buff(OutputStream ops) {
if (ops == null)
throw new NullPointerException("ops is null!");
if (ops instanceof BufferedOutputStream)
return (BufferedOutputStream) ops;
return new BufferedOutputStream(ops);
}
/**
* 为一个文本输入流包裹一个缓冲流。如果这个输入流本身就是缓冲流,则直接返回
*
* @param reader
* 文本输入流。
* @return 缓冲文本输入流
*/
public static BufferedReader buffr(Reader reader) {
if (reader instanceof BufferedReader)
return (BufferedReader) reader;
return new BufferedReader(reader);
}
/**
* 为一个文本输出流包裹一个缓冲流。如果这个文本输出流本身就是缓冲流,则直接返回
*
* @param ops
* 文本输出流。
* @return 缓冲文本输出流
*/
public static BufferedWriter buffw(Writer ops) {
if (ops instanceof BufferedWriter)
return (BufferedWriter) ops;
return new BufferedWriter(ops);
}
/**
* 根据一个文件路径建立一个输入流
*
* @param path
* 文件路径
* @return 输入流
*/
public static InputStream fileIn(String path) {
InputStream ins = Files.findFileAsStream(path);
if (null == ins) {
File f = Files.findFile(path);
if (null != f)
try {
ins = Streams._input(f);
}
catch (IOException e) {}
}
if (null == ins) {
// TODO 考虑一下,应该抛异常呢?还是返回null呢?
throw new RuntimeException(new FileNotFoundException(path));
// return null;
}
return buff(ins);
}
/**
* 根据一个文件路径建立一个输入流
*
* @param file
* 文件
* @return 输入流
*/
public static InputStream fileIn(File file) {
try {
return buff(Streams._input(file));
}
catch (IOException e) {
throw Lang.wrapThrow(e);
}
}
/**
* 根据一个文件路径建立一个 UTF-8文本输入流 <b>警告!! 本方法会预先读取3个字节以判断该文件是否存在BOM头</b>
* <p/>
* <b>警告!! 如果存在BOM头,则自动跳过</b>
* <p/>
*
* @param path
* 文件路径
* @return 文本输入流
*/
public static Reader fileInr(String path) {
return utf8r(fileIn(path));
}
/**
* 根据一个文件路径建立一个 UTF-8 文本输入流 <b>警告!! 本方法会预先读取3个字节以判断该文件是否存在BOM头</b>
* <p/>
* <b>警告!! 如果存在BOM头,则自动跳过</b>
* <p/>
*
* @param file
* 文件
* @return 文本输入流
*/
public static Reader fileInr(File file) {
return utf8r(fileIn(file));
}
private static final byte[] UTF_BOM = new byte[]{(byte) 0xEF, (byte) 0xBB, (byte) 0xBF};
/**
* 判断并移除UTF-8的BOM头
*/
public static InputStream utf8filte(InputStream in) {
try {
if (in.available() == -1)
return in;
PushbackInputStream pis = new PushbackInputStream(in, 3);
byte[] header = new byte[3];
int len = pis.read(header, 0, 3);
if (len < 1)
return in;
if (header[0] != UTF_BOM[0] || header[1] != UTF_BOM[1] || header[2] != UTF_BOM[2]) {
pis.unread(header, 0, len);
}
return pis;
}
catch (IOException e) {
throw Lang.wrapThrow(e);
}
}
/**
* 根据一个文件路径建立一个输出流
*
* @param path
* 文件路径
* @return 输出流
*/
public static OutputStream fileOut(String path) {
return fileOut(Files.findFile(path));
}
/**
* 根据一个文件建立一个输出流
*
* @param file
* 文件
* @return 输出流
*/
public static OutputStream fileOut(File file) {
try {
return buff(new FileOutputStream(file));
}
catch (FileNotFoundException e) {
throw Lang.wrapThrow(e);
}
}
/**
* 根据一个文件路径建立一个 UTF-8 文本输出流
*
* @param path
* 文件路径
* @return 文本输出流
*/
public static Writer fileOutw(String path) {
return fileOutw(Files.findFile(path));
}
/**
* 根据一个文件建立一个 UTF-8 文本输出流
*
* @param file
* 文件
* @return 输出流
*/
public static Writer fileOutw(File file) {
return utf8w(fileOut(file));
}
public static Reader utf8r(InputStream is) {
return new InputStreamReader(utf8filte(is), Encoding.CHARSET_UTF8);
}
public static Writer utf8w(OutputStream os) {
return new OutputStreamWriter(os, Encoding.CHARSET_UTF8);
}
public static InputStream nullInputStream() {
return new VoidInputStream();
}
public static InputStream wrap(byte[] bytes) {
return new ByteArrayInputStream(bytes);
}
/**
* 对一个文本输入流迭代每一行,并将其关闭
*
* @param r
* 文本输入流
* @param callback
* 回调
* @return 迭代的行数
*/
public static int eachLine(Reader r, Each<String> callback) {
if (null == callback || null == r)
return 0;
BufferedReader br = null;
try {
br = Streams.buffr(r);
String line;
int index = 0;
while (null != (line = br.readLine())) {
try {
callback.invoke(index++, line, -1);
}
catch (ExitLoop e) {
break;
}
catch (ContinueLoop e) {
continue;
}
}
return index;
}
catch (IOException e2) {
throw Lang.wrapThrow(e2);
}
finally {
Streams.safeClose(br);
}
}
/**
* 获取File对象输入流,即使在Jar文件中一样工作良好!! <b>强烈推荐</b>
*
*/
protected static InputStream _input(File file) throws IOException {
if (file.exists())
return new FileInputStream(file);
if (Scans.isInJar(file)) {
NutResource nutResource = Scans.makeJarNutResource(file);
if (nutResource != null)
return nutResource.getInputStream();
}
throw new FileNotFoundException(file.toString());
}
public static void appendWriteAndClose(File f, String text) {
FileWriter fw = null;
try {
fw = new FileWriter(f, true);
fw.write(text);
}
catch (IOException e) {
throw Lang.wrapThrow(e);
}
finally {
safeClose(fw);
}
}
public static String nextLineTrim(BufferedReader br) throws IOException {
String line = null;
while (br.ready()) {
line = br.readLine();
if (line == null)
break;
if (Strings.isBlank(line))
continue;
return line.trim();
}
return line;
}
public static long writeAndClose(OutputStream ops, InputStream ins, int buf) {
try {
return write(ops, ins, buf);
}
catch (IOException e) {
throw Lang.wrapThrow(e);
}
finally {
safeFlush(ops);
safeClose(ops);
safeClose(ins);
}
}
}
| nutzam/nutz | src/org/nutz/lang/Streams.java |
4 | package stack;
/**
* 基于链表实现的栈。
*
* Author: Zheng
*/
public class StackBasedOnLinkedList {
private Node top = null;
public void push(int value) {
Node newNode = new Node(value, null);
// 判断是否栈空
if (top == null) {
top = newNode;
} else {
newNode.next = top;
top = newNode;
}
}
/**
* 我用-1表示栈中没有数据。
*/
public int pop() {
if (top == null) return -1;
int value = top.data;
top = top.next;
return value;
}
public void printAll() {
Node p = top;
while (p != null) {
System.out.print(p.data + " ");
p = p.next;
}
System.out.println();
}
private static class Node {
private int data;
private Node next;
public Node(int data, Node next) {
this.data = data;
this.next = next;
}
public int getData() {
return data;
}
}
}
| wangzheng0822/algo | java/08_stack/StackBasedOnLinkedList.java |
5 | package com.crossoverjie.guava.callback;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Function:
*
* @author crossoverJie
* Date: 2018/7/15 13:52
* @since JDK 1.8
*/
public class Caller {
private final static Logger LOGGER = LoggerFactory.getLogger(Caller.class);
private CallBackListener callBackListener ;
private Notifier notifier ;
private String question ;
/**
* 使用
*/
public void call(){
LOGGER.info("开始提问");
//新建线程,达到异步效果
new Thread(new Runnable() {
@Override
public void run() {
try {
notifier.execute(Caller.this,question);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}).start();
LOGGER.info("提问完毕,我去干其他事了");
}
public Notifier getNotifier() {
return notifier;
}
public void setNotifier(Notifier notifier) {
this.notifier = notifier;
}
public CallBackListener getCallBackListener() {
return callBackListener;
}
public void setCallBackListener(CallBackListener callBackListener) {
this.callBackListener = callBackListener;
}
public String getQuestion() {
return question;
}
public void setQuestion(String question) {
this.question = question;
}
@Override
public String toString() {
return "Caller{" +
"callBackListener=" + callBackListener +
", notifier=" + notifier +
", question='" + question + '\'' +
'}';
}
}
| crossoverJie/JCSprout | src/main/java/com/crossoverjie/guava/callback/Caller.java |
6 | package org.yousharp.julycoding.string;
/**
* 1.2 字符串包含
* (july github链接:https://github.com/julycoding/The-Art-Of-Programming-By-July/blob/master/ebook/zh/01.02.md)
*
* User: lingguo
* Date: 14-6-29
*/
public class StringContain {
/**
* * 问题描述:
* 给定两个分别由字母组成的字符串A和字符串B,字符串B的长度比字符串A短。请问,如何最快地判断字符串B
* 中所有字母是否都在字符串A里?为了简单起见,我们规定输入的字符串只包含大写英文字母。比如String A:ABCD,String B:BAD,
* 返回true;string A:ABCD,string B:BCE,返回false;String A:ABCD,String B:AA,返回true。
*
* 思路:
* 思路一:遍历字符串B,判断每一个字符是否出现在字符串A中,时间复杂度O(n*m),空间复杂度O(1);
* 思路二:先对两个字符串排序,然后同时遍历字符串A和B,判断B中的每一个字符是否都在字符串A中。时间复杂度O(nlogn),空间复杂度O(1);
* 思路三:将每一个字符映射到一个素数上,对字符串A中的每一个字符表示的素数,求累积;然后遍历字符串B,用每一个字符表示的素
* 数去除字符串A的累积,判断余数是否为0。时间复杂度:O(n),空间复杂度O(1)。可能存在的问题:乘积时可能会溢出。
* 思路四:如果可以使用Java中的数据结构,HashMap和Set可以很方便地解决问题;如果不能,我们可以构造一个“签名”,将每一个字
* 符映射为整数(范围:0到26),然后遍历A中的每一个字符,将32位整数的对应位置1(整数初始为0),最后遍历B中的每一个字符,判断
* 每一个字符代表的整数在整数中是否已置位。时间复杂度O(n),空间复杂度O(1),思路四为最优算法。
*
* 这里仅给出思路四的示例代码。
*
* @param s1
* @param s2
* @return
*/
public static boolean hashCheck(char[] s1, char[] s2) {
int mask = 0;
for (char c: s1) {
mask = mask | (1 << (c - 'A'));
}
for (char c: s2) {
if ((mask & (1 << (c - 'A'))) == 0) {
return false;
}
}
return true;
}
}
| julycoding/The-Art-Of-Programming-By-July-2nd | ebook/code/java/chapter1/1.2:字符串包含.java |
7 | /**
* DFA全称为:Deterministic Finite Automaton,即确定有穷自动机。<br>
* 解释起来原理其实也不难,就是用所有关键字构造一棵树,然后用正文遍历这棵树,遍历到叶子节点即表示文章中存在这个关键字。<br>
* 我们暂且忽略构建关键词树的时间,每次查找正文只需要O(n)复杂度就可以搞定。<br>
*
* @author looly
*
*/
package cn.hutool.dfa; | dromara/hutool | hutool-dfa/src/main/java/cn/hutool/dfa/package-info.java |
8 | M
1520921982
tags: Binary Search
二分的思想: 判断的是一个 validate() function, 而不是简单的'=='
不需要sort! 为什么呢? 因为我们不是在given array上面二分, 我们是根据最大值在[0, max]上二分.
Overall time: O(nLogM), where M = largest wood length
```
/*
Given n pieces of wood with length L[i] (integer array). Cut them into small pieces to guarantee you could have equal or more than k pieces with the same length. What is the longest length you can get from the n pieces of wood? Given L & k, return the maximum length of the small pieces.
Note
You couldn't cut wood into float length.
Example
For L=[232, 124, 456], k=7, return 114.
Challenge
O(n log Len), where Len is the longest length of the wood.
Tags Expand
Binary Search
*/
/*
Thoughts:
Find a number, that can split all L's into K parts. The number should range:
[0, L(largest)]
1. binary search [0, largest value]
2. condition check: count pieces
3. Need find the mid: valid(mid) && !valid(mid + 1)
Time: O(n) find max
Time: O(n * logM)
Overall: O(nLogM), where M = largest wood length
*/
public class Solution {
/**
* @param L: Given n pieces of wood with length L[i]
* @param k: An integer
* @return: The maximum length of the small pieces
*/
public int woodCut(int[] L, int k) {
if (L == null || L.length == 0 || k < 0) {
return 0;
}
int m = L.length;
int max = 0;
for (int i = 0; i < m; i++) {
max = Math.max(max, L[i]);
}
int start = 0;
int end = max;
while (start + 1 < end) {
int mid = start + (end - start) / 2;
if (validate(mid, k, L) && mid + 1 < max && !validate(mid + 1, k , L)) {
return mid;
} else if (validate(mid, k, L)) {
start = mid;
} else {
end = mid;
}
}
if (validate(end, k , L)) {
return end;
} else {
return start;
}
}
private boolean validate(int size, int k, int[] L) {
int count = 0;
for (int length : L) {
count += length / size;
}
return count >= k;
}
}
``` | awangdev/leet-code | Java/Wood Cut.java |
9 | package org.ansj.util;
import java.io.IOException;
import java.io.Reader;
/**
* 我又剽窃了下jdk...职业嫖客 为了效率这个流的操作是不支持多线程的,要么就是长时间不写这种东西了。发现好费劲啊 这个reader的特点。。只会输入
* 句子不会输出\r\n .会有一个start来记录当前返回字符串。起始偏移量
*
* @author ansj
*
*/
public class AnsjReader extends Reader {
private Reader in;
private char cb[];
private static int defaultCharBufferSize = 8192;
/**
* Creates a buffering character-input stream that uses an input buffer of
* the specified size.
*
* @param in
* A Reader
* @param sz
* Input-buffer size
*
* @exception IllegalArgumentException
* If {@code sz <= 0}
*/
public AnsjReader(Reader in, int sz) {
super(in);
if (sz <= 0) {
throw new IllegalArgumentException("Buffer size <= 0");
}
this.in = in;
cb = new char[sz];
}
/**
* Creates a buffering character-input stream that uses a default-sized
* input buffer.
*
* @param in
* A Reader
*/
public AnsjReader(Reader in) {
this(in, defaultCharBufferSize);
}
/** Checks to make sure that the stream has not been closed */
private void ensureOpen() throws IOException {
if (in == null) {
throw new IOException("Stream closed");
}
}
/**
* 为了功能的单一性我还是不实现了
*/
@Override
public int read(char cbuf[], int off, int len) throws IOException {
throw new IOException("AnsjBufferedReader not support this interface! ");
}
private int start = 0;
private int tempStart = 0;
/**
* 读取一行数据。ps 读取结果会忽略 \n \r
*/
public String readLine() throws IOException {
ensureOpen();
StringBuilder sb = null;
start = tempStart;
firstRead = true;
while (true) {
tempLen = 0;
ok = false;
readString();
// if (tempLen != 0)
// System.out.println(new String(cb, tempOffe, tempLen));
if (!isRead && (tempLen == 0 || len == 0)) {
if (sb != null) {
return sb.toString();
}
return null;
}
if (!isRead) { // 如果不是需要读状态,那么返回
tempStart += tempLen;
if (sb == null) {
return new String(cb, tempOffe, tempLen);
} else {
sb.append(cb, tempOffe, tempLen);
return sb.toString();
}
}
if (tempLen == 0) {
continue;
}
// 如果是需要读状态那么读取
if (sb == null) {
sb = new StringBuilder();
}
sb.append(cb, tempOffe, tempLen);
tempStart += tempLen;
}
}
int offe = 0;
int len = 0;
boolean isRead = false;
boolean ok = false;
boolean firstRead = true;
int tempOffe;
int tempLen;
private void readString() throws IOException {
if (offe <= 0) {
if (offe == -1) {
isRead = false;
return;
}
len = in.read(cb);
if (len <= 0) { // 说明到结尾了
isRead = false;
return;
}
}
isRead = true;
char c = 0;
int i = offe;
for (; i < len; i++) {
c = cb[i];
if (c != '\r' && c != '\n') {
break;
}
if (!firstRead) {
i++;
tempStart++;
offe = i;
tempOffe = offe;
isRead = false;
return;
}
tempStart++;
start++;
}
if (i == len) {
isRead = true;
offe = 0;
return;
}
firstRead = false;
offe = i;
for (; i < len; i++) {
c = cb[i];
if (c == '\n' || c == '\r') {
isRead = false;
break;
}
}
tempOffe = offe;
tempLen = i - offe;
if (i == len) {
if (len < cb.length) { // 说明到结尾了
isRead = false;
offe = -1;
} else {
offe = 0;
}
} else {
offe = i;
}
}
@Override
public void close() throws IOException {
synchronized (lock) {
if (in == null) {
return;
}
try {
in.close();
} finally {
in = null;
cb = null;
}
}
}
public int getStart() {
return this.start;
}
}
| NLPchina/ansj_seg | src/main/java/org/ansj/util/AnsjReader.java |
10 | /*
* Copyright 2016 jeasonlzy(廖子尧)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.lzy.demo.utils;
/**
* ================================================
* 作 者:jeasonlzy(廖子尧)
* 版 本:1.0
* 创建日期:2016/4/6
* 描 述:我的Github地址 https://github.com/jeasonlzy
* 修订历史:
* ================================================
*/
public class Urls {
public static final String SERVER = "http://server.jeasonlzy.com/OkHttpUtils/";
// public static final String SERVER = "http://192.168.1.121:8080/OkHttpUtils/";
public static final String URL_METHOD = SERVER + "method";
public static final String URL_CACHE = SERVER + "cache";
public static final String URL_IMAGE = SERVER + "image";
public static final String URL_JSONOBJECT = SERVER + "jsonObject";
public static final String URL_JSONARRAY = SERVER + "jsonArray";
public static final String URL_FORM_UPLOAD = SERVER + "upload";
public static final String URL_TEXT_UPLOAD = SERVER + "uploadString";
public static final String URL_DOWNLOAD = SERVER + "download";
public static final String URL_REDIRECT = SERVER + "redirect";
public static final String URL_GANK_BASE = "http://gank.io/api/data/";
}
| jeasonlzy/okhttp-OkGo | demo/src/main/java/com/lzy/demo/utils/Urls.java |
11 | package com.xkcoding.rbac.security.config;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
/**
* <p>
* JWT 配置
* </p>
*
* @author yangkai.shen
* @date Created in 2018-12-07 13:42
*/
@ConfigurationProperties(prefix = "jwt.config")
@Data
public class JwtConfig {
/**
* jwt 加密 key,默认值:xkcoding.
*/
private String key = "xkcoding";
/**
* jwt 过期时间,默认值:600000 {@code 10 分钟}.
*/
private Long ttl = 600000L;
/**
* 开启 记住我 之后 jwt 过期时间,默认值 604800000 {@code 7 天}
*/
private Long remember = 604800000L;
}
| xkcoding/spring-boot-demo | demo-rbac-security/src/main/java/com/xkcoding/rbac/security/config/JwtConfig.java |
12 | package com.blankj.base;
import android.app.Application;
import android.content.Context;
import androidx.multidex.MultiDex;
import com.blankj.utilcode.util.AppUtils;
import com.blankj.utilcode.util.CrashUtils;
import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.ProcessUtils;
import com.blankj.utildebug.DebugUtils;
import com.blankj.utildebug.debug.IDebug;
import java.util.ArrayList;
/**
* <pre>
* author: Blankj
* blog : http://blankj.com
* time : 2018/11/16
* desc : base about application
* </pre>
*/
public class BaseApplication extends Application {
private static BaseApplication sInstance;
public static BaseApplication getInstance() {
return sInstance;
}
private Boolean isDebug;
private Boolean isMainProcess;
@Override
protected void attachBaseContext(Context base) {
super.attachBaseContext(base);
MultiDex.install(this);
}
@Override
public void onCreate() {
super.onCreate();
sInstance = this;
initLog();
initCrash();
initDebugMenu();
}
// init it in ur application
public void initLog() {
LogUtils.Config config = LogUtils.getConfig()
.setLogSwitch(isDebug())// 设置 log 总开关,包括输出到控制台和文件,默认开
.setConsoleSwitch(isDebug())// 设置是否输出到控制台开关,默认开
.setGlobalTag(null)// 设置 log 全局标签,默认为空
// 当全局标签不为空时,我们输出的 log 全部为该 tag,
// 为空时,如果传入的 tag 为空那就显示类名,否则显示 tag
.setLogHeadSwitch(true)// 设置 log 头信息开关,默认为开
.setLog2FileSwitch(false)// 打印 log 时是否存到文件的开关,默认关
.setDir("")// 当自定义路径为空时,写入应用的/cache/log/目录中
.setFilePrefix("")// 当文件前缀为空时,默认为"util",即写入文件为"util-yyyy-MM-dd$fileExtension"
.setFileExtension(".log")// 设置日志文件后缀
.setBorderSwitch(true)// 输出日志是否带边框开关,默认开
.setSingleTagSwitch(true)// 一条日志仅输出一条,默认开,为美化 AS 3.1 的 Logcat
.setConsoleFilter(LogUtils.V)// log 的控制台过滤器,和 logcat 过滤器同理,默认 Verbose
.setFileFilter(LogUtils.V)// log 文件过滤器,和 logcat 过滤器同理,默认 Verbose
.setStackDeep(1)// log 栈深度,默认为 1
.setStackOffset(0)// 设置栈偏移,比如二次封装的话就需要设置,默认为 0
.setSaveDays(3)// 设置日志可保留天数,默认为 -1 表示无限时长
// 新增 ArrayList 格式化器,默认已支持 Array, Throwable, Bundle, Intent 的格式化输出
.addFormatter(new LogUtils.IFormatter<ArrayList>() {
@Override
public String format(ArrayList arrayList) {
return "LogUtils Formatter ArrayList { " + arrayList.toString() + " }";
}
})
.addFileExtraHead("ExtraKey", "ExtraValue");
LogUtils.i(config.toString());
}
private void initCrash() {
CrashUtils.init(new CrashUtils.OnCrashListener() {
@Override
public void onCrash(CrashUtils.CrashInfo crashInfo) {
crashInfo.addExtraHead("extraKey", "extraValue");
LogUtils.e(crashInfo.toString());
AppUtils.relaunchApp();
}
});
}
private void initDebugMenu() {
DebugUtils.addDebugs(new ArrayList<IDebug>());
}
private boolean isDebug() {
if (isDebug == null) isDebug = AppUtils.isAppDebug();
return isDebug;
}
public boolean isMainProcess() {
if (isMainProcess == null) isMainProcess = ProcessUtils.isMainProcess();
return isMainProcess;
}
}
| Blankj/AndroidUtilCode | lib/base/src/main/java/com/blankj/base/BaseApplication.java |
13 | /** Half width Katakana variants (FF00 - <TYPO>FFEF</TYPO>)
* ワタシハジャバガスキデス。
*/
/** Full width ASCII variants (FF00 - <TYPO>FFEF</TYPO>)
* I LOVE JAVA
*/
/** Hiragana (3040 - 309F)
* わたしはじゃばがすきです。
*/
/** Katakana (30A0 - 30FF)
* ワタシハジャバガスキデス。
*/
/** CJK Unified Ideographs (4E00 - 9FBF)
* 我愛爪哇
*/
/** CJK Compatibility Ideographs (F900 - FAFF)
* 﨎鶴﨎鶴﨎鶴
*/
/* 私は<TYPO>Jaba</TYPO>が好きです。私は<TYPO>Jaba</TYPO>が好きです。*/
/**
* プロセス毎に使われるコールスタックは一つだけ !!!
*/
class TestClassForCJKComments {}
| JetBrains/intellij-community | plugins/java-i18n/testData/inspections/spellchecker/Japanese.java |
14 | package me.zhyd.oauth.enums.scope;
import lombok.AllArgsConstructor;
import lombok.Getter;
/**
* 微博平台 OAuth 授权范围
*
* @author yadong.zhang (yadong.zhang0415(a)gmail.com)
* @version 1.0.0
* @since 1.0.0
*/
@Getter
@AllArgsConstructor
public enum AuthWeiboScope implements AuthScope {
/**
* {@code scope} 含义,以{@code description} 为准
*/
ALL("all", "获取所有权限", true),
EMAIL("email", "用户的联系邮箱,<a rel=\"nofollow\" href=\"http://open.weibo.com/wiki/2/account/profile/email\">接口文档</a>", false),
DIRECT_MESSAGES_WRITE("direct_messages_write", "私信发送接口,<a rel=\"nofollow\" href=\"http://open.weibo.com/wiki/C/2/direct_messages/send\">接口文档</a>", false),
DIRECT_MESSAGES_READ("direct_messages_read", "私信读取接口,<a rel=\"nofollow\" href=\"http://open.weibo.com/wiki/C/2/direct_messages\">接口文档</a>", false),
INVITATION_WRITE("invitation_write", "邀请发送接口,<a rel=\"nofollow\" href=\"http://open.weibo.com/wiki/Messages#.E5.A5.BD.E5.8F.8B.E9.82.80.E8.AF.B7\">接口文档</a>", false),
FRIENDSHIPS_GROUPS_READ("friendships_groups_read", "好友分组读取接口组,<a rel=\"nofollow\" href=\"http://open.weibo.com/wiki/API%E6%96%87%E6%A1%A3_V2#.E5.A5.BD.E5.8F.8B.E5.88.86.E7.BB.84\">接口文档</a>", false),
FRIENDSHIPS_GROUPS_WRITE("friendships_groups_write", "好友分组写入接口组,<a rel=\"nofollow\" href=\"http://open.weibo.com/wiki/API%E6%96%87%E6%A1%A3_V2#.E5.A5.BD.E5.8F.8B.E5.88.86.E7.BB.84\">接口文档</a>", false),
STATUSES_TO_ME_READ("statuses_to_me_read", "定向微博读取接口组,<a rel=\"nofollow\" href=\"http://open.weibo.com/wiki/API%E6%96%87%E6%A1%A3_V2#.E5.BE.AE.E5.8D.9A\">接口文档</a>", false),
FOLLOW_APP_OFFICIAL_MICROBLOG("follow_app_official_microblog", "关注应用官方微博,该参数不对应具体接口,只需在应用控制台填写官方帐号即可。填写的路径:我的应用-选择自己的应用-应用信息-基本信息-官方运营账号(默认值是应用开发者帐号)", false);
private final String scope;
private final String description;
private final boolean isDefault;
}
| justauth/JustAuth | src/main/java/me/zhyd/oauth/enums/scope/AuthWeiboScope.java |
15 | package dshomewrok;
import java.util.*;
/*ZigZagging on a Tree
*/
public class Zigzagtree {
public static class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int x) {
val = x;
}
}
private static int find(int[] array, int v) {
for (int i = 0; i < array.length; i++) {
if (array[i] == v) {
return i;
}
}
return -1;
}
public static void main(String[] args) {
int n = 0;
int i = 0,j = 0;
Scanner sc = new Scanner(System.in);
n = sc.nextInt();
int[] arr1,arr2;
arr1 = new int[n]; // inorder
arr2 = new int[n]; // postorder
for(i = 0;i < arr1.length;i++) {
arr1[i] = sc.nextInt();
}
for(i = 0;i < arr2.length;i++) {
arr2[i] = sc.nextInt();
}
sc.close();
TreeNode root1 = BuildTree(arr1,arr2);
}
/*build a Tree from postorder and inorder
后序遍历的最后一个数为根结点,根据这个根结点来划分中序遍历,将其分为左子树和右子树
②确定左右子树的中序遍历和后遍历中的界限,中序从0 - root为左, root+1 到最后为右. 后序0-root为左,root到postOrder.length-1 为右.
③递归调用
*/
public static TreeNode BuildTree(int[] inOrder, int[] postOrder ) {
if(postOrder.length == 0) {
return null;
}
if(postOrder.length == 1) {
TreeNode tmp = new TreeNode(postOrder[postOrder.length-1]);
return tmp;
}
TreeNode root = new TreeNode(postOrder[postOrder.length-1]); //先判断特殊,再new 一个.
int rootpos = find(inOrder,root.val);
int[] leftInorder = Arrays.copyOfRange(inOrder, 0, rootpos); //copyOfRange 包括0 不包括rootpos.
int[] rightInorder = Arrays.copyOfRange(inOrder, rootpos+1, inOrder.length);
//System.out.println(rootpos);
//System.out.println(Arrays.toString(rightInorder));
//System.out.println(Arrays.toString(leftInorder)); //不能直接打印数组要tostring
int[] leftPostorder = Arrays.copyOfRange(postOrder, 0, rootpos);
int[] rightPostorder = Arrays.copyOfRange(postOrder, rootpos, postOrder.length-1);;
//System.out.println(Arrays.toString(leftPostorder));
//System.out.println(Arrays.toString(rightPostorder));
root.left = BuildTree(leftInorder,leftPostorder);
root.right = BuildTree(rightInorder,rightPostorder);
return root;
}
/*要进行层次遍历,需要建立一个循环队列。先将二叉树头结点入队列,然后出队列,访问该结点,如果它有左子树
则将左子树的根结点入队:如果它有右子树,则将右子树的根结点入队。然后出队列,对出队结点访问,如此反复,直到队列为空为止。
z字形层次遍历是对层次遍历加上了一个限制条件(即相邻层,从左到右的遍历顺序相反),
我们取queue大小,就是上一层的结点数. for循环把这一层都加入进去,如果奇数层就第一个结点开始(因为上一层是偶数)先加右再加左.
如果偶数层就最后结点开始(因为上一层是奇数)先加左再加右.
一层结束深度增加,同时用一个栈,因为遍历下一层的数据 和输出这一层的数据 是刚好相反的..
data arraylist是因为他最后不要空格, 所以全部保存了再输出. 不然stack其实就有正确答案了,最后多一个空格.
*/
public static void zigzagorder(JudgeRedBlackTree.TreeNode root ) {
ArrayDeque<JudgeRedBlackTree.TreeNode> queue = new ArrayDeque<JudgeRedBlackTree.TreeNode>(32);
ArrayList<Integer> data = new ArrayList<Integer>(32); //no int but Integer
JudgeRedBlackTree.TreeNode temp = root;
Stack<JudgeRedBlackTree.TreeNode> res = new Stack<JudgeRedBlackTree.TreeNode>(); // 就是把他
queue.add(temp);
int depth = 0 ,i = 0;
while(!queue.isEmpty()){
int size = queue.size();
for(i =0;i<size;i++) {
if(depth %2 == 0) {
temp = queue.pollLast();
if(temp.left != null) {
queue.addFirst(temp.left);
}
if(temp.right != null){
queue.addFirst(temp.right);
}
}
else {
temp = queue.poll();
if(temp.right != null){
queue.add(temp.right);
}
if(temp.left != null) {
queue.add(temp.left);
}
}
res.push(temp);
}
while(!res.empty())
data.add(res.pop().val);
depth ++;
}
for(i = 0;i<data.size()-1;i++) {
System.out.print(data.get(i)+" ");
}
System.out.print(data.get(i));
}
}
| QSCTech/zju-icicles | 数据结构基础/作业/dsHomework/tree/Zigzagtree.java |
16 | package decaf.frontend;
import java.util.List;
import decaf.Location;
import decaf.tree.Tree;
import decaf.tree.Tree.ClassDef;
import decaf.tree.Tree.Expr;
import decaf.tree.Tree.GuardedES;
import decaf.tree.Tree.MethodDef;
import decaf.tree.Tree.LValue;
import decaf.tree.Tree.TopLevel;
import decaf.tree.Tree.VarDef;
import decaf.tree.Tree.TypeLiteral;
import decaf.utils.MiscUtils;
public class SemValue {
public int code;
public Location loc;
public int typeTag;
public Object literal;
public String ident;
public List<ClassDef> clist;
/**
* field list
*/
public List<Tree> flist;
public List<VarDef> vlist;
/**
* statement list
*/
public List<Tree> slist;
public List<Expr> elist;
// no.4
public List<GuardedES> myList;
public TopLevel prog;
public ClassDef cdef;
public VarDef vdef;
public MethodDef fdef;
public TypeLiteral type;
public Tree stmt;
public Expr expr;
public LValue lvalue;
public GuardedES guardedES;
/**
* 创建一个关键字的语义值
*
* @param code
* 关键字的代表码
* @return 对应关键字的语义值
*/
public static SemValue createKeyword(int code) {
SemValue v = new SemValue();
v.code = code;
return v;
}
/**
* 创建一个操作符的语义值
*
* @param code
* 操作符的代表码
* @return 对应操作符的语义值
*/
public static SemValue createOperator(int code) {
SemValue v = new SemValue();
v.code = code;
return v;
}
/**
* 创建一个常量的语义值
*
* @param value
* 常量的值
* @return 对应的语义值
*/
public static SemValue createLiteral(int tag, Object value) {
SemValue v = new SemValue();
v.code = Parser.LITERAL;
v.typeTag = tag;
v.literal = value;
return v;
}
/**
* 创建一个标识符的语义值
*
* @param name
* 标识符的名字
* @return 对应的语义值(标识符名字存放在sval域)
*/
public static SemValue createIdentifier(String name) {
SemValue v = new SemValue();
v.code = Parser.IDENTIFIER;
v.ident = name;
return v;
}
/**
* 获取这个语义值的字符串表示<br>
*
* 我们建议你在构造词法分析器之前先阅读一下这个函数。
*/
public String toString() {
String msg;
switch (code) {
// 关键字
case Parser.BOOL:
msg = "keyword : bool";
break;
case Parser.BREAK:
msg = "keyword : break";
break;
case Parser.CLASS:
msg = "keyword : class";
break;
case Parser.ELSE:
msg = "keyword : else";
break;
case Parser.EXTENDS:
msg = "keyword : extends";
break;
case Parser.FOR:
msg = "keyword : for";
break;
case Parser.IF:
msg = "keyword : if";
break;
case Parser.INT:
msg = "keyword : int";
break;
case Parser.INSTANCEOF:
msg = "keyword : instanceof";
break;
case Parser.NEW:
msg = "keyword : new";
break;
case Parser.NULL:
msg = "keyword : null";
break;
case Parser.PRINT:
msg = "keyword : Print";
break;
case Parser.READ_INTEGER:
msg = "keyword : ReadInteger";
break;
case Parser.READ_LINE:
msg = "keyword : ReadLine";
break;
case Parser.RETURN:
msg = "keyword : return";
break;
case Parser.STRING:
msg = "keyword : string";
break;
case Parser.THIS:
msg = "keyword : this";
break;
case Parser.VOID:
msg = "keyword : void";
break;
case Parser.WHILE:
msg = "keyword : while";
break;
case Parser.STATIC:
msg = "keyword : static";
break;
// 常量
case Parser.LITERAL:
switch (typeTag) {
case Tree.INT:
case Tree.BOOL:
msg = "constant : " + literal;
break;
default:
msg = "constant : " + MiscUtils.quote((String)literal);
}
break;
// 标识符
case Parser.IDENTIFIER:
msg = "identifier: " + ident;
break;
// 操作符
case Parser.AND:
msg = "operator : &&";
break;
case Parser.EQUAL:
msg = "operator : ==";
break;
case Parser.GREATER_EQUAL:
msg = "operator : >=";
break;
case Parser.LESS_EQUAL:
msg = "operator : <=";
break;
case Parser.NOT_EQUAL:
msg = "operator : !=";
break;
case Parser.OR:
msg = "operator : ||";
break;
default:
msg = "operator : " + (char) code;
break;
}
return (String.format("%-15s%s", loc, msg));
}
}
| PKUanonym/REKCARC-TSC-UHT | 大三上/编译原理/hw/2015_刘智峰_PA/PA2/src/decaf/frontend/SemValue.java |
17 | /*
* Copyright (c) 2020, OpenCloudDB/MyCAT and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software;Designed and Developed mainly by many Chinese
* opensource volunteers. you can redistribute it and/or modify it under the
* terms of the GNU General Public License version 2 only, as published by the
* Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Any questions about this component can be directed to it's project Web address
* https://code.google.com/p/opencloudb/.
*
*/
package io.mycat.config;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import io.mycat.config.loader.zkprocess.comm.ZkConfig;
import io.mycat.config.loader.zkprocess.comm.ZkParamCfg;
import org.apache.log4j.Logger;
import io.mycat.backend.datasource.PhysicalDBNode;
import io.mycat.backend.datasource.PhysicalDBPool;
import io.mycat.backend.datasource.PhysicalDatasource;
import io.mycat.backend.jdbc.JDBCDatasource;
import io.mycat.backend.mysql.nio.MySQLDataSource;
import io.mycat.backend.postgresql.PostgreSQLDataSource;
import io.mycat.config.loader.ConfigLoader;
import io.mycat.config.loader.SchemaLoader;
import io.mycat.config.loader.xml.XMLConfigLoader;
import io.mycat.config.loader.xml.XMLSchemaLoader;
import io.mycat.config.model.DBHostConfig;
import io.mycat.config.model.DataHostConfig;
import io.mycat.config.model.DataNodeConfig;
import io.mycat.config.model.FirewallConfig;
import io.mycat.config.model.SchemaConfig;
import io.mycat.config.model.SystemConfig;
import io.mycat.config.model.UserConfig;
import io.mycat.config.util.ConfigException;
import io.mycat.route.sequence.handler.DistributedSequenceHandler;
import io.mycat.route.sequence.handler.IncrSequenceMySQLHandler;
import io.mycat.route.sequence.handler.IncrSequenceTimeHandler;
import io.mycat.route.sequence.handler.IncrSequenceZKHandler;
/**
* @author mycat
*/
public class ConfigInitializer {
private static final Logger LOGGER = Logger.getLogger( ConfigInitializer.class );
private volatile SystemConfig system;
private volatile MycatCluster cluster;
private volatile FirewallConfig firewall;
private volatile Map<String, UserConfig> users;
private volatile Map<String, SchemaConfig> schemas;
private volatile Map<String, PhysicalDBNode> dataNodes;
private volatile Map<String, PhysicalDBPool> dataHosts;
public ConfigInitializer(boolean loadDataHost) {
//读取rule.xml和schema.xml
SchemaLoader schemaLoader = new XMLSchemaLoader();
//读取server.xml
XMLConfigLoader configLoader = new XMLConfigLoader(schemaLoader);
schemaLoader = null;
//加载配置
this.system = configLoader.getSystemConfig();
this.users = configLoader.getUserConfigs();
this.schemas = configLoader.getSchemaConfigs();
//是否重新加载DataHost和对应的DataNode
if (loadDataHost) {
this.dataHosts = initDataHosts(configLoader);
this.dataNodes = initDataNodes(configLoader);
}
//权限管理
this.firewall = configLoader.getFirewallConfig();
this.cluster = initCobarCluster(configLoader);
//不同类型的全局序列处理器的配置加载
if (system.getSequenceHandlerType() == SystemConfig.SEQUENCEHANDLER_MYSQLDB) {
IncrSequenceMySQLHandler.getInstance().load();
}
if (system.getSequenceHandlerType() == SystemConfig.SEQUENCEHANDLER_LOCAL_TIME) {
IncrSequenceTimeHandler.getInstance().load();
}
if (system.getSequenceHandlerType() == SystemConfig.SEQUENCEHANDLER_ZK_DISTRIBUTED) {
DistributedSequenceHandler.getInstance(system).load();
}
if (system.getSequenceHandlerType() == SystemConfig.SEQUENCEHANDLER_ZK_GLOBAL_INCREMENT) {
IncrSequenceZKHandler.getInstance().load();
}
/**
* 配置文件初始化, 自检
*/
this.selfChecking0();
}
private void selfChecking0() throws ConfigException {
// 检查user与schema配置对应以及schema配置不为空
if (users == null || users.isEmpty()) {
throw new ConfigException("SelfCheck### user all node is empty!");
} else {
for (UserConfig uc : users.values()) {
if (uc == null) {
throw new ConfigException("SelfCheck### users node within the item is empty!");
}
Set<String> authSchemas = uc.getSchemas();
if (authSchemas == null) {
throw new ConfigException("SelfCheck### user " + uc.getName() + "refered schemas is empty!");
}
for (String schema : authSchemas) {
if ( !schemas.containsKey(schema) ) {
String errMsg = "SelfCheck### schema " + schema + " refered by user " + uc.getName() + " is not exist!";
throw new ConfigException(errMsg);
}
}
}
}
// schema 配置检测
for (SchemaConfig sc : schemas.values()) {
if (null == sc) {
throw new ConfigException("SelfCheck### schema all node is empty!");
} else {
// check dataNode / dataHost 节点
if ( this.dataNodes != null && this.dataHosts != null ) {
Set<String> dataNodeNames = sc.getAllDataNodes();
for(String dataNodeName: dataNodeNames) {
PhysicalDBNode node = this.dataNodes.get(dataNodeName);
if ( node == null ) {
throw new ConfigException("SelfCheck### schema dbnode is empty!");
}
}
}
}
}
}
public void testConnection() {
// 实际链路的连接测试
if ( this.dataNodes != null && this.dataHosts != null ) {
Map<String, Boolean> map = new HashMap<String, Boolean>();
for(PhysicalDBNode dataNode: dataNodes.values() ) {
String database = dataNode.getDatabase();
PhysicalDBPool pool = dataNode.getDbPool();
for (PhysicalDatasource ds : pool.getAllDataSources()) {
String key = ds.getName() + "_" + database;
if ( map.get( key ) == null ) {
map.put( key, false );
boolean isConnected = false;
try {
isConnected = ds.testConnection( database );
map.put( key, isConnected );
} catch (IOException e) {
LOGGER.warn("test conn error:", e);
}
}
}
}
//
boolean isConnectivity = true;
for (Map.Entry<String, Boolean> entry : map.entrySet()) {
String key = entry.getKey();
Boolean value = entry.getValue();
if ( !value && isConnectivity ) {
LOGGER.warn("SelfCheck### test " + key + " database connection failed ");
isConnectivity = false;
} else {
LOGGER.info("SelfCheck### test " + key + " database connection success ");
}
}
if ( !isConnectivity ) {
throw new ConfigException("SelfCheck### there are some datasource connection failed, pls check!");
}
}
}
public SystemConfig getSystem() {
return system;
}
public MycatCluster getCluster() {
return cluster;
}
public FirewallConfig getFirewall() {
return firewall;
}
public Map<String, UserConfig> getUsers() {
return users;
}
public Map<String, SchemaConfig> getSchemas() {
return schemas;
}
public Map<String, PhysicalDBNode> getDataNodes() {
return dataNodes;
}
public Map<String, PhysicalDBPool> getDataHosts() {
return this.dataHosts;
}
private MycatCluster initCobarCluster(ConfigLoader configLoader) {
return new MycatCluster(configLoader.getClusterConfig());
}
private Map<String, PhysicalDBPool> initDataHosts(ConfigLoader configLoader) {
Map<String, DataHostConfig> nodeConfs = configLoader.getDataHosts();
boolean isBooster="booster".equalsIgnoreCase(ZkConfig.getInstance().getValue(ZkParamCfg.MYCAT_SERVER_TYPE) ) ;
//根据DataHost建立PhysicalDBPool,其实就是实际数据库连接池,每个DataHost对应一个PhysicalDBPool
Map<String, PhysicalDBPool> nodes = new HashMap<String, PhysicalDBPool>(
nodeConfs.size());
for (DataHostConfig conf : nodeConfs.values()) {
if(isBooster){
conf.setMinCon(2);
}
//建立PhysicalDBPool
PhysicalDBPool pool = getPhysicalDBPool(conf, configLoader);
nodes.put(pool.getHostName(), pool);
}
return nodes;
}
private PhysicalDatasource[] createDataSource(DataHostConfig conf,
String hostName, String dbType, String dbDriver,
DBHostConfig[] nodes, boolean isRead) {
PhysicalDatasource[] dataSources = new PhysicalDatasource[nodes.length];
if (dbType.equals("mysql") && dbDriver.equals("native")) {
for (int i = 0; i < nodes.length; i++) {
//设置最大idle时间,默认为30分钟
nodes[i].setIdleTimeout(system.getIdleTimeout());
MySQLDataSource ds = new MySQLDataSource(nodes[i], conf, isRead);
dataSources[i] = ds;
}
} else if (dbDriver.equals("jdbc")) {
for (int i = 0; i < nodes.length; i++) {
nodes[i].setIdleTimeout(system.getIdleTimeout());
JDBCDatasource ds = new JDBCDatasource(nodes[i], conf, isRead);
dataSources[i] = ds;
}
} else if ("postgresql".equalsIgnoreCase(dbType) && dbDriver.equalsIgnoreCase("native")){
for (int i = 0; i < nodes.length; i++) {
nodes[i].setIdleTimeout(system.getIdleTimeout());
PostgreSQLDataSource ds = new PostgreSQLDataSource(nodes[i], conf, isRead);
dataSources[i] = ds;
}
} else{
throw new ConfigException("not supported yet !" + hostName);
}
return dataSources;
}
private PhysicalDBPool getPhysicalDBPool(DataHostConfig conf,
ConfigLoader configLoader) {
String name = conf.getName();
//数据库类型,我们这里只讨论MySQL
String dbType = conf.getDbType();
//连接数据库驱动,我们这里只讨论MyCat自己实现的native
String dbDriver = conf.getDbDriver();
//针对所有写节点创建PhysicalDatasource
PhysicalDatasource[] writeSources = createDataSource(conf, name,
dbType, dbDriver, conf.getWriteHosts(), false);
Map<Integer, DBHostConfig[]> readHostsMap = conf.getReadHosts();
Map<Integer, PhysicalDatasource[]> readSourcesMap = new HashMap<Integer, PhysicalDatasource[]>(
readHostsMap.size());
//对于每个读节点建立key为writeHost下标value为readHost的PhysicalDatasource[]的哈希表
for (Map.Entry<Integer, DBHostConfig[]> entry : readHostsMap.entrySet()) {
PhysicalDatasource[] readSources = createDataSource(conf, name,
dbType, dbDriver, entry.getValue(), true);
readSourcesMap.put(entry.getKey(), readSources);
}
PhysicalDBPool pool = new PhysicalDBPool(conf.getName(), conf,
writeSources, readSourcesMap, conf.getBalance(),
conf.getWriteType());
pool.setSlaveIDs(conf.getSlaveIDs());
return pool;
}
private Map<String, PhysicalDBNode> initDataNodes(ConfigLoader configLoader) {
Map<String, DataNodeConfig> nodeConfs = configLoader.getDataNodes();
Map<String, PhysicalDBNode> nodes = new HashMap<String, PhysicalDBNode>(
nodeConfs.size());
for (DataNodeConfig conf : nodeConfs.values()) {
PhysicalDBPool pool = this.dataHosts.get(conf.getDataHost());
if (pool == null) {
throw new ConfigException("dataHost not exists "
+ conf.getDataHost());
}
PhysicalDBNode dataNode = new PhysicalDBNode(conf.getName(),
conf.getDatabase(), pool);
nodes.put(dataNode.getName(), dataNode);
}
return nodes;
}
}
| MyCATApache/Mycat-Server | src/main/java/io/mycat/config/ConfigInitializer.java |
18 | /*
* Copyright (C) 2013 Chen Hui <[email protected]>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.sample;
import android.graphics.Color;
import android.text.TextUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.xml.sax.Attributes;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;
import org.xml.sax.helpers.DefaultHandler;
import org.xml.sax.helpers.XMLReaderFactory;
import java.io.IOException;
import java.util.Locale;
import master.flame.danmaku.danmaku.model.AlphaValue;
import master.flame.danmaku.danmaku.model.BaseDanmaku;
import master.flame.danmaku.danmaku.model.Duration;
import master.flame.danmaku.danmaku.model.IDisplayer;
import master.flame.danmaku.danmaku.model.SpecialDanmaku;
import master.flame.danmaku.danmaku.model.android.Danmakus;
import master.flame.danmaku.danmaku.parser.BaseDanmakuParser;
import master.flame.danmaku.danmaku.model.android.DanmakuFactory;
import master.flame.danmaku.danmaku.parser.android.AndroidFileSource;
import master.flame.danmaku.danmaku.util.DanmakuUtils;
import static master.flame.danmaku.danmaku.model.IDanmakus.ST_BY_TIME;
public class BiliDanmukuParser extends BaseDanmakuParser {
static {
System.setProperty("org.xml.sax.driver", "org.xmlpull.v1.sax2.Driver");
}
protected float mDispScaleX;
protected float mDispScaleY;
@Override
public Danmakus parse() {
if (mDataSource != null) {
AndroidFileSource source = (AndroidFileSource) mDataSource;
try {
XMLReader xmlReader = XMLReaderFactory.createXMLReader();
XmlContentHandler contentHandler = new XmlContentHandler();
xmlReader.setContentHandler(contentHandler);
xmlReader.parse(new InputSource(source.data()));
return contentHandler.getResult();
} catch (SAXException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
public class XmlContentHandler extends DefaultHandler {
private static final String TRUE_STRING = "true";
public Danmakus result;
public BaseDanmaku item = null;
public boolean completed = false;
public int index = 0;
public Danmakus getResult() {
return result;
}
@Override
public void startDocument() throws SAXException {
result = new Danmakus(ST_BY_TIME, false, mContext.getBaseComparator());
}
@Override
public void endDocument() throws SAXException {
completed = true;
}
@Override
public void startElement(String uri, String localName, String qName, Attributes attributes)
throws SAXException {
String tagName = localName.length() != 0 ? localName : qName;
tagName = tagName.toLowerCase(Locale.getDefault()).trim();
if (tagName.equals("d")) {
// <d p="23.826000213623,1,25,16777215,1422201084,0,057075e9,757076900">我从未见过如此厚颜无耻之猴</d>
// 0:时间(弹幕出现时间)
// 1:类型(1从右至左滚动弹幕|6从左至右滚动弹幕|5顶端固定弹幕|4底端固定弹幕|7高级弹幕|8脚本弹幕)
// 2:字号
// 3:颜色
// 4:时间戳 ?
// 5:弹幕池id
// 6:用户hash
// 7:弹幕id
String pValue = attributes.getValue("p");
// parse p value to danmaku
String[] values = pValue.split(",");
if (values.length > 0) {
long time = (long) (parseFloat(values[0]) * 1000); // 出现时间
int type = parseInteger(values[1]); // 弹幕类型
float textSize = parseFloat(values[2]); // 字体大小
int color = (int) ((0x00000000ff000000 | parseLong(values[3])) & 0x00000000ffffffff); // 颜色
// int poolType = parseInteger(values[5]); // 弹幕池类型(忽略
item = mContext.mDanmakuFactory.createDanmaku(type, mContext);
if (item != null) {
item.setTime(time);
item.textSize = textSize * (mDispDensity - 0.6f);
item.textColor = color;
item.textShadowColor = color <= Color.BLACK ? Color.WHITE : Color.BLACK;
}
}
}
}
@Override
public void endElement(String uri, String localName, String qName) throws SAXException {
if (item != null && item.text != null) {
if (item.duration != null) {
String tagName = localName.length() != 0 ? localName : qName;
if (tagName.equalsIgnoreCase("d")) {
item.setTimer(mTimer);
item.flags = mContext.mGlobalFlagValues;
Object lock = result.obtainSynchronizer();
synchronized (lock) {
result.addItem(item);
}
}
}
item = null;
}
}
@Override
public void characters(char[] ch, int start, int length) {
if (item != null) {
DanmakuUtils.fillText(item, decodeXmlString(new String(ch, start, length)));
item.index = index++;
// initial specail danmaku data
String text = String.valueOf(item.text).trim();
if (item.getType() == BaseDanmaku.TYPE_SPECIAL && text.startsWith("[")
&& text.endsWith("]")) {
//text = text.substring(1, text.length() - 1);
String[] textArr = null;//text.split(",", -1);
try {
JSONArray jsonArray = new JSONArray(text);
textArr = new String[jsonArray.length()];
for (int i = 0; i < textArr.length; i++) {
textArr[i] = jsonArray.getString(i);
}
} catch (JSONException e) {
e.printStackTrace();
}
if (textArr == null || textArr.length < 5 || TextUtils.isEmpty(textArr[4])) {
item = null;
return;
}
DanmakuUtils.fillText(item, textArr[4]);
float beginX = parseFloat(textArr[0]);
float beginY = parseFloat(textArr[1]);
float endX = beginX;
float endY = beginY;
String[] alphaArr = textArr[2].split("-");
int beginAlpha = (int) (AlphaValue.MAX * parseFloat(alphaArr[0]));
int endAlpha = beginAlpha;
if (alphaArr.length > 1) {
endAlpha = (int) (AlphaValue.MAX * parseFloat(alphaArr[1]));
}
long alphaDuraion = (long) (parseFloat(textArr[3]) * 1000);
long translationDuration = alphaDuraion;
long translationStartDelay = 0;
float rotateY = 0, rotateZ = 0;
if (textArr.length >= 7) {
rotateZ = parseFloat(textArr[5]);
rotateY = parseFloat(textArr[6]);
}
if (textArr.length >= 11) {
endX = parseFloat(textArr[7]);
endY = parseFloat(textArr[8]);
if (!"".equals(textArr[9])) {
translationDuration = parseInteger(textArr[9]);
}
if (!"".equals(textArr[10])) {
translationStartDelay = (long) (parseFloat(textArr[10]));
}
}
if (isPercentageNumber(textArr[0])) {
beginX *= DanmakuFactory.BILI_PLAYER_WIDTH;
}
if (isPercentageNumber(textArr[1])) {
beginY *= DanmakuFactory.BILI_PLAYER_HEIGHT;
}
if (textArr.length >= 8 && isPercentageNumber(textArr[7])) {
endX *= DanmakuFactory.BILI_PLAYER_WIDTH;
}
if (textArr.length >= 9 && isPercentageNumber(textArr[8])) {
endY *= DanmakuFactory.BILI_PLAYER_HEIGHT;
}
item.duration = new Duration(alphaDuraion);
item.rotationZ = rotateZ;
item.rotationY = rotateY;
mContext.mDanmakuFactory.fillTranslationData(item, beginX,
beginY, endX, endY, translationDuration, translationStartDelay, mDispScaleX, mDispScaleY);
mContext.mDanmakuFactory.fillAlphaData(item, beginAlpha, endAlpha, alphaDuraion);
if (textArr.length >= 12) {
// 是否有描边
if (!TextUtils.isEmpty(textArr[11]) && TRUE_STRING.equalsIgnoreCase(textArr[11])) {
item.textShadowColor = Color.TRANSPARENT;
}
}
if (textArr.length >= 13) {
//TODO 字体 textArr[12]
}
if (textArr.length >= 14) {
// Linear.easeIn or Quadratic.easeOut
((SpecialDanmaku) item).isQuadraticEaseOut = ("0".equals(textArr[13]));
}
if (textArr.length >= 15) {
// 路径数据
if (!"".equals(textArr[14])) {
String motionPathString = textArr[14].substring(1);
if (!TextUtils.isEmpty(motionPathString)) {
String[] pointStrArray = motionPathString.split("L");
if (pointStrArray.length > 0) {
float[][] points = new float[pointStrArray.length][2];
for (int i = 0; i < pointStrArray.length; i++) {
String[] pointArray = pointStrArray[i].split(",");
if (pointArray.length >= 2) {
points[i][0] = parseFloat(pointArray[0]);
points[i][1] = parseFloat(pointArray[1]);
}
}
mContext.mDanmakuFactory.fillLinePathData(item, points, mDispScaleX,
mDispScaleY);
}
}
}
}
}
}
}
private String decodeXmlString(String title) {
if (title.contains("&")) {
title = title.replace("&", "&");
}
if (title.contains(""")) {
title = title.replace(""", "\"");
}
if (title.contains(">")) {
title = title.replace(">", ">");
}
if (title.contains("<")) {
title = title.replace("<", "<");
}
return title;
}
}
private boolean isPercentageNumber(String number) {
//return number >= 0f && number <= 1f;
return number != null && number.contains(".");
}
private float parseFloat(String floatStr) {
try {
return Float.parseFloat(floatStr);
} catch (NumberFormatException e) {
return 0.0f;
}
}
private int parseInteger(String intStr) {
try {
return Integer.parseInt(intStr);
} catch (NumberFormatException e) {
return 0;
}
}
private long parseLong(String longStr) {
try {
return Long.parseLong(longStr);
} catch (NumberFormatException e) {
return 0;
}
}
@Override
public BaseDanmakuParser setDisplayer(IDisplayer disp) {
super.setDisplayer(disp);
mDispScaleX = mDispWidth / DanmakuFactory.BILI_PLAYER_WIDTH;
mDispScaleY = mDispHeight / DanmakuFactory.BILI_PLAYER_HEIGHT;
return this;
}
}
| bilibili/DanmakuFlameMaster | Sample/src/main/java/com/sample/BiliDanmukuParser.java |
19 | package com.macro.mall;
import org.mybatis.generator.api.MyBatisGenerator;
import org.mybatis.generator.config.Configuration;
import org.mybatis.generator.config.xml.ConfigurationParser;
import org.mybatis.generator.internal.DefaultShellCallback;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
/**
* MBG代码生成工具
* Created by macro on 2018/4/26.
*/
public class Generator {
public static void main(String[] args) throws Exception {
//MBG 执行过程中的警告信息
List<String> warnings = new ArrayList<String>();
//当生成的代码重复时,覆盖原代码
boolean overwrite = true;
//读取我们的 MBG 配置文件
InputStream is = Generator.class.getResourceAsStream("/generatorConfig.xml");
ConfigurationParser cp = new ConfigurationParser(warnings);
Configuration config = cp.parseConfiguration(is);
is.close();
DefaultShellCallback callback = new DefaultShellCallback(overwrite);
//创建 MBG
MyBatisGenerator myBatisGenerator = new MyBatisGenerator(config, callback, warnings);
//执行生成代码
myBatisGenerator.generate(null);
//输出警告信息
for (String warning : warnings) {
System.out.println(warning);
}
}
}
| macrozheng/mall | mall-mbg/src/main/java/com/macro/mall/Generator.java |
20 | package com.alibaba.datax.core.job;
import com.alibaba.datax.common.constant.PluginType;
import com.alibaba.datax.common.exception.DataXException;
import com.alibaba.datax.common.plugin.AbstractJobPlugin;
import com.alibaba.datax.common.plugin.JobPluginCollector;
import com.alibaba.datax.common.spi.Reader;
import com.alibaba.datax.common.spi.Writer;
import com.alibaba.datax.common.statistics.PerfTrace;
import com.alibaba.datax.common.statistics.VMInfo;
import com.alibaba.datax.common.util.Configuration;
import com.alibaba.datax.common.util.StrUtil;
import com.alibaba.datax.core.AbstractContainer;
import com.alibaba.datax.core.Engine;
import com.alibaba.datax.core.container.util.HookInvoker;
import com.alibaba.datax.core.container.util.JobAssignUtil;
import com.alibaba.datax.core.job.scheduler.AbstractScheduler;
import com.alibaba.datax.core.job.scheduler.processinner.StandAloneScheduler;
import com.alibaba.datax.core.statistics.communication.Communication;
import com.alibaba.datax.core.statistics.communication.CommunicationTool;
import com.alibaba.datax.core.statistics.container.communicator.AbstractContainerCommunicator;
import com.alibaba.datax.core.statistics.container.communicator.job.StandAloneJobContainerCommunicator;
import com.alibaba.datax.core.statistics.plugin.DefaultJobPluginCollector;
import com.alibaba.datax.core.util.ErrorRecordChecker;
import com.alibaba.datax.core.util.FrameworkErrorCode;
import com.alibaba.datax.core.util.container.ClassLoaderSwapper;
import com.alibaba.datax.core.util.container.CoreConstant;
import com.alibaba.datax.core.util.container.LoadUtil;
import com.alibaba.datax.dataxservice.face.domain.enums.ExecuteMode;
import com.alibaba.fastjson2.JSON;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.Validate;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
/**
* Created by jingxing on 14-8-24.
* <p/>
* job实例运行在jobContainer容器中,它是所有任务的master,负责初始化、拆分、调度、运行、回收、监控和汇报
* 但它并不做实际的数据同步操作
*/
public class JobContainer extends AbstractContainer {
private static final Logger LOG = LoggerFactory
.getLogger(JobContainer.class);
private static final SimpleDateFormat dateFormat = new SimpleDateFormat(
"yyyy-MM-dd HH:mm:ss");
private ClassLoaderSwapper classLoaderSwapper = ClassLoaderSwapper
.newCurrentThreadClassLoaderSwapper();
private long jobId;
private String readerPluginName;
private String writerPluginName;
/**
* reader和writer jobContainer的实例
*/
private Reader.Job jobReader;
private Writer.Job jobWriter;
private Configuration userConf;
private long startTimeStamp;
private long endTimeStamp;
private long startTransferTimeStamp;
private long endTransferTimeStamp;
private int needChannelNumber;
private int totalStage = 1;
private ErrorRecordChecker errorLimit;
public JobContainer(Configuration configuration) {
super(configuration);
errorLimit = new ErrorRecordChecker(configuration);
}
/**
* jobContainer主要负责的工作全部在start()里面,包括init、prepare、split、scheduler、
* post以及destroy和statistics
*/
@Override
public void start() {
LOG.info("DataX jobContainer starts job.");
boolean hasException = false;
boolean isDryRun = false;
try {
this.startTimeStamp = System.currentTimeMillis();
isDryRun = configuration.getBool(CoreConstant.DATAX_JOB_SETTING_DRYRUN, false);
if(isDryRun) {
LOG.info("jobContainer starts to do preCheck ...");
this.preCheck();
} else {
userConf = configuration.clone();
LOG.debug("jobContainer starts to do preHandle ...");
this.preHandle();
LOG.debug("jobContainer starts to do init ...");
this.init();
LOG.info("jobContainer starts to do prepare ...");
this.prepare();
LOG.info("jobContainer starts to do split ...");
this.totalStage = this.split();
LOG.info("jobContainer starts to do schedule ...");
this.schedule();
LOG.debug("jobContainer starts to do post ...");
this.post();
LOG.debug("jobContainer starts to do postHandle ...");
this.postHandle();
LOG.info("DataX jobId [{}] completed successfully.", this.jobId);
this.invokeHooks();
}
} catch (Throwable e) {
LOG.error("Exception when job run", e);
hasException = true;
if (e instanceof OutOfMemoryError) {
this.destroy();
System.gc();
}
if (super.getContainerCommunicator() == null) {
// 由于 containerCollector 是在 scheduler() 中初始化的,所以当在 scheduler() 之前出现异常时,需要在此处对 containerCollector 进行初始化
AbstractContainerCommunicator tempContainerCollector;
// standalone
tempContainerCollector = new StandAloneJobContainerCommunicator(configuration);
super.setContainerCommunicator(tempContainerCollector);
}
Communication communication = super.getContainerCommunicator().collect();
// 汇报前的状态,不需要手动进行设置
// communication.setState(State.FAILED);
communication.setThrowable(e);
communication.setTimestamp(this.endTimeStamp);
Communication tempComm = new Communication();
tempComm.setTimestamp(this.startTransferTimeStamp);
Communication reportCommunication = CommunicationTool.getReportCommunication(communication, tempComm, this.totalStage);
super.getContainerCommunicator().report(reportCommunication);
throw DataXException.asDataXException(
FrameworkErrorCode.RUNTIME_ERROR, e);
} finally {
if(!isDryRun) {
this.destroy();
this.endTimeStamp = System.currentTimeMillis();
if (!hasException) {
//最后打印cpu的平均消耗,GC的统计
VMInfo vmInfo = VMInfo.getVmInfo();
if (vmInfo != null) {
vmInfo.getDelta(false);
LOG.info(vmInfo.totalString());
}
LOG.info(PerfTrace.getInstance().summarizeNoException());
this.logStatistics();
}
}
}
}
private void preCheck() {
this.preCheckInit();
this.adjustChannelNumber();
if (this.needChannelNumber <= 0) {
this.needChannelNumber = 1;
}
this.preCheckReader();
this.preCheckWriter();
LOG.info("PreCheck通过");
}
private void preCheckInit() {
this.jobId = this.configuration.getLong(
CoreConstant.DATAX_CORE_CONTAINER_JOB_ID, -1);
if (this.jobId < 0) {
LOG.info("Set jobId = 0");
this.jobId = 0;
this.configuration.set(CoreConstant.DATAX_CORE_CONTAINER_JOB_ID,
this.jobId);
}
Thread.currentThread().setName("job-" + this.jobId);
JobPluginCollector jobPluginCollector = new DefaultJobPluginCollector(
this.getContainerCommunicator());
this.jobReader = this.preCheckReaderInit(jobPluginCollector);
this.jobWriter = this.preCheckWriterInit(jobPluginCollector);
}
private Reader.Job preCheckReaderInit(JobPluginCollector jobPluginCollector) {
this.readerPluginName = this.configuration.getString(
CoreConstant.DATAX_JOB_CONTENT_READER_NAME);
classLoaderSwapper.setCurrentThreadClassLoader(LoadUtil.getJarLoader(
PluginType.READER, this.readerPluginName));
Reader.Job jobReader = (Reader.Job) LoadUtil.loadJobPlugin(
PluginType.READER, this.readerPluginName);
this.configuration.set(CoreConstant.DATAX_JOB_CONTENT_READER_PARAMETER + ".dryRun", true);
// 设置reader的jobConfig
jobReader.setPluginJobConf(this.configuration.getConfiguration(
CoreConstant.DATAX_JOB_CONTENT_READER_PARAMETER));
// 设置reader的readerConfig
jobReader.setPeerPluginJobConf(this.configuration.getConfiguration(
CoreConstant.DATAX_JOB_CONTENT_READER_PARAMETER));
jobReader.setJobPluginCollector(jobPluginCollector);
classLoaderSwapper.restoreCurrentThreadClassLoader();
return jobReader;
}
private Writer.Job preCheckWriterInit(JobPluginCollector jobPluginCollector) {
this.writerPluginName = this.configuration.getString(
CoreConstant.DATAX_JOB_CONTENT_WRITER_NAME);
classLoaderSwapper.setCurrentThreadClassLoader(LoadUtil.getJarLoader(
PluginType.WRITER, this.writerPluginName));
Writer.Job jobWriter = (Writer.Job) LoadUtil.loadJobPlugin(
PluginType.WRITER, this.writerPluginName);
this.configuration.set(CoreConstant.DATAX_JOB_CONTENT_WRITER_PARAMETER + ".dryRun", true);
// 设置writer的jobConfig
jobWriter.setPluginJobConf(this.configuration.getConfiguration(
CoreConstant.DATAX_JOB_CONTENT_WRITER_PARAMETER));
// 设置reader的readerConfig
jobWriter.setPeerPluginJobConf(this.configuration.getConfiguration(
CoreConstant.DATAX_JOB_CONTENT_READER_PARAMETER));
jobWriter.setPeerPluginName(this.readerPluginName);
jobWriter.setJobPluginCollector(jobPluginCollector);
classLoaderSwapper.restoreCurrentThreadClassLoader();
return jobWriter;
}
private void preCheckReader() {
classLoaderSwapper.setCurrentThreadClassLoader(LoadUtil.getJarLoader(
PluginType.READER, this.readerPluginName));
LOG.info(String.format("DataX Reader.Job [%s] do preCheck work .",
this.readerPluginName));
this.jobReader.preCheck();
classLoaderSwapper.restoreCurrentThreadClassLoader();
}
private void preCheckWriter() {
classLoaderSwapper.setCurrentThreadClassLoader(LoadUtil.getJarLoader(
PluginType.WRITER, this.writerPluginName));
LOG.info(String.format("DataX Writer.Job [%s] do preCheck work .",
this.writerPluginName));
this.jobWriter.preCheck();
classLoaderSwapper.restoreCurrentThreadClassLoader();
}
/**
* reader和writer的初始化
*/
private void init() {
this.jobId = this.configuration.getLong(
CoreConstant.DATAX_CORE_CONTAINER_JOB_ID, -1);
if (this.jobId < 0) {
LOG.info("Set jobId = 0");
this.jobId = 0;
this.configuration.set(CoreConstant.DATAX_CORE_CONTAINER_JOB_ID,
this.jobId);
}
Thread.currentThread().setName("job-" + this.jobId);
JobPluginCollector jobPluginCollector = new DefaultJobPluginCollector(
this.getContainerCommunicator());
//必须先Reader ,后Writer
this.jobReader = this.initJobReader(jobPluginCollector);
this.jobWriter = this.initJobWriter(jobPluginCollector);
}
private void prepare() {
this.prepareJobReader();
this.prepareJobWriter();
}
private void preHandle() {
String handlerPluginTypeStr = this.configuration.getString(
CoreConstant.DATAX_JOB_PREHANDLER_PLUGINTYPE);
if(!StringUtils.isNotEmpty(handlerPluginTypeStr)){
return;
}
PluginType handlerPluginType;
try {
handlerPluginType = PluginType.valueOf(handlerPluginTypeStr.toUpperCase());
} catch (IllegalArgumentException e) {
throw DataXException.asDataXException(
FrameworkErrorCode.CONFIG_ERROR,
String.format("Job preHandler's pluginType(%s) set error, reason(%s)", handlerPluginTypeStr.toUpperCase(), e.getMessage()));
}
String handlerPluginName = this.configuration.getString(
CoreConstant.DATAX_JOB_PREHANDLER_PLUGINNAME);
classLoaderSwapper.setCurrentThreadClassLoader(LoadUtil.getJarLoader(
handlerPluginType, handlerPluginName));
AbstractJobPlugin handler = LoadUtil.loadJobPlugin(
handlerPluginType, handlerPluginName);
JobPluginCollector jobPluginCollector = new DefaultJobPluginCollector(
this.getContainerCommunicator());
handler.setJobPluginCollector(jobPluginCollector);
//todo configuration的安全性,将来必须保证
handler.preHandler(configuration);
classLoaderSwapper.restoreCurrentThreadClassLoader();
LOG.info("After PreHandler: \n" + Engine.filterJobConfiguration(configuration) + "\n");
}
private void postHandle() {
String handlerPluginTypeStr = this.configuration.getString(
CoreConstant.DATAX_JOB_POSTHANDLER_PLUGINTYPE);
if(!StringUtils.isNotEmpty(handlerPluginTypeStr)){
return;
}
PluginType handlerPluginType;
try {
handlerPluginType = PluginType.valueOf(handlerPluginTypeStr.toUpperCase());
} catch (IllegalArgumentException e) {
throw DataXException.asDataXException(
FrameworkErrorCode.CONFIG_ERROR,
String.format("Job postHandler's pluginType(%s) set error, reason(%s)", handlerPluginTypeStr.toUpperCase(), e.getMessage()));
}
String handlerPluginName = this.configuration.getString(
CoreConstant.DATAX_JOB_POSTHANDLER_PLUGINNAME);
classLoaderSwapper.setCurrentThreadClassLoader(LoadUtil.getJarLoader(
handlerPluginType, handlerPluginName));
AbstractJobPlugin handler = LoadUtil.loadJobPlugin(
handlerPluginType, handlerPluginName);
JobPluginCollector jobPluginCollector = new DefaultJobPluginCollector(
this.getContainerCommunicator());
handler.setJobPluginCollector(jobPluginCollector);
handler.postHandler(configuration);
classLoaderSwapper.restoreCurrentThreadClassLoader();
}
/**
* 执行reader和writer最细粒度的切分,需要注意的是,writer的切分结果要参照reader的切分结果,
* 达到切分后数目相等,才能满足1:1的通道模型,所以这里可以将reader和writer的配置整合到一起,
* 然后,为避免顺序给读写端带来长尾影响,将整合的结果shuffler掉
*/
private int split() {
this.adjustChannelNumber();
if (this.needChannelNumber <= 0) {
this.needChannelNumber = 1;
}
List<Configuration> readerTaskConfigs = this
.doReaderSplit(this.needChannelNumber);
int taskNumber = readerTaskConfigs.size();
List<Configuration> writerTaskConfigs = this
.doWriterSplit(taskNumber);
List<Configuration> transformerList = this.configuration.getListConfiguration(CoreConstant.DATAX_JOB_CONTENT_TRANSFORMER);
LOG.debug("transformer configuration: "+ JSON.toJSONString(transformerList));
/**
* 输入是reader和writer的parameter list,输出是content下面元素的list
*/
List<Configuration> contentConfig = mergeReaderAndWriterTaskConfigs(
readerTaskConfigs, writerTaskConfigs, transformerList);
LOG.debug("contentConfig configuration: "+ JSON.toJSONString(contentConfig));
this.configuration.set(CoreConstant.DATAX_JOB_CONTENT, contentConfig);
return contentConfig.size();
}
private void adjustChannelNumber() {
int needChannelNumberByByte = Integer.MAX_VALUE;
int needChannelNumberByRecord = Integer.MAX_VALUE;
boolean isByteLimit = (this.configuration.getInt(
CoreConstant.DATAX_JOB_SETTING_SPEED_BYTE, 0) > 0);
if (isByteLimit) {
long globalLimitedByteSpeed = this.configuration.getInt(
CoreConstant.DATAX_JOB_SETTING_SPEED_BYTE, 10 * 1024 * 1024);
// 在byte流控情况下,单个Channel流量最大值必须设置,否则报错!
Long channelLimitedByteSpeed = this.configuration
.getLong(CoreConstant.DATAX_CORE_TRANSPORT_CHANNEL_SPEED_BYTE);
if (channelLimitedByteSpeed == null || channelLimitedByteSpeed <= 0) {
throw DataXException.asDataXException(
FrameworkErrorCode.CONFIG_ERROR,
"在有总bps限速条件下,单个channel的bps值不能为空,也不能为非正数");
}
needChannelNumberByByte =
(int) (globalLimitedByteSpeed / channelLimitedByteSpeed);
needChannelNumberByByte =
needChannelNumberByByte > 0 ? needChannelNumberByByte : 1;
LOG.info("Job set Max-Byte-Speed to " + globalLimitedByteSpeed + " bytes.");
}
boolean isRecordLimit = (this.configuration.getInt(
CoreConstant.DATAX_JOB_SETTING_SPEED_RECORD, 0)) > 0;
if (isRecordLimit) {
long globalLimitedRecordSpeed = this.configuration.getInt(
CoreConstant.DATAX_JOB_SETTING_SPEED_RECORD, 100000);
Long channelLimitedRecordSpeed = this.configuration.getLong(
CoreConstant.DATAX_CORE_TRANSPORT_CHANNEL_SPEED_RECORD);
if (channelLimitedRecordSpeed == null || channelLimitedRecordSpeed <= 0) {
throw DataXException.asDataXException(FrameworkErrorCode.CONFIG_ERROR,
"在有总tps限速条件下,单个channel的tps值不能为空,也不能为非正数");
}
needChannelNumberByRecord =
(int) (globalLimitedRecordSpeed / channelLimitedRecordSpeed);
needChannelNumberByRecord =
needChannelNumberByRecord > 0 ? needChannelNumberByRecord : 1;
LOG.info("Job set Max-Record-Speed to " + globalLimitedRecordSpeed + " records.");
}
// 取较小值
this.needChannelNumber = needChannelNumberByByte < needChannelNumberByRecord ?
needChannelNumberByByte : needChannelNumberByRecord;
// 如果从byte或record上设置了needChannelNumber则退出
if (this.needChannelNumber < Integer.MAX_VALUE) {
return;
}
boolean isChannelLimit = (this.configuration.getInt(
CoreConstant.DATAX_JOB_SETTING_SPEED_CHANNEL, 0) > 0);
if (isChannelLimit) {
this.needChannelNumber = this.configuration.getInt(
CoreConstant.DATAX_JOB_SETTING_SPEED_CHANNEL);
LOG.info("Job set Channel-Number to " + this.needChannelNumber
+ " channels.");
return;
}
throw DataXException.asDataXException(
FrameworkErrorCode.CONFIG_ERROR,
"Job运行速度必须设置");
}
/**
* schedule首先完成的工作是把上一步reader和writer split的结果整合到具体taskGroupContainer中,
* 同时不同的执行模式调用不同的调度策略,将所有任务调度起来
*/
private void schedule() {
/**
* 这里的全局speed和每个channel的速度设置为B/s
*/
int channelsPerTaskGroup = this.configuration.getInt(
CoreConstant.DATAX_CORE_CONTAINER_TASKGROUP_CHANNEL, 5);
int taskNumber = this.configuration.getList(
CoreConstant.DATAX_JOB_CONTENT).size();
this.needChannelNumber = Math.min(this.needChannelNumber, taskNumber);
PerfTrace.getInstance().setChannelNumber(needChannelNumber);
/**
* 通过获取配置信息得到每个taskGroup需要运行哪些tasks任务
*/
List<Configuration> taskGroupConfigs = JobAssignUtil.assignFairly(this.configuration,
this.needChannelNumber, channelsPerTaskGroup);
LOG.info("Scheduler starts [{}] taskGroups.", taskGroupConfigs.size());
ExecuteMode executeMode = null;
AbstractScheduler scheduler;
try {
executeMode = ExecuteMode.STANDALONE;
scheduler = initStandaloneScheduler(this.configuration);
//设置 executeMode
for (Configuration taskGroupConfig : taskGroupConfigs) {
taskGroupConfig.set(CoreConstant.DATAX_CORE_CONTAINER_JOB_MODE, executeMode.getValue());
}
if (executeMode == ExecuteMode.LOCAL || executeMode == ExecuteMode.DISTRIBUTE) {
if (this.jobId <= 0) {
throw DataXException.asDataXException(FrameworkErrorCode.RUNTIME_ERROR,
"在[ local | distribute ]模式下必须设置jobId,并且其值 > 0 .");
}
}
LOG.info("Running by {} Mode.", executeMode);
this.startTransferTimeStamp = System.currentTimeMillis();
scheduler.schedule(taskGroupConfigs);
this.endTransferTimeStamp = System.currentTimeMillis();
} catch (Exception e) {
LOG.error("运行scheduler 模式[{}]出错.", executeMode);
this.endTransferTimeStamp = System.currentTimeMillis();
throw DataXException.asDataXException(
FrameworkErrorCode.RUNTIME_ERROR, e);
}
/**
* 检查任务执行情况
*/
this.checkLimit();
}
private AbstractScheduler initStandaloneScheduler(Configuration configuration) {
AbstractContainerCommunicator containerCommunicator = new StandAloneJobContainerCommunicator(configuration);
super.setContainerCommunicator(containerCommunicator);
return new StandAloneScheduler(containerCommunicator);
}
private void post() {
this.postJobWriter();
this.postJobReader();
}
private void destroy() {
if (this.jobWriter != null) {
this.jobWriter.destroy();
this.jobWriter = null;
}
if (this.jobReader != null) {
this.jobReader.destroy();
this.jobReader = null;
}
}
private void logStatistics() {
long totalCosts = (this.endTimeStamp - this.startTimeStamp) / 1000;
long transferCosts = (this.endTransferTimeStamp - this.startTransferTimeStamp) / 1000;
if (0L == transferCosts) {
transferCosts = 1L;
}
if (super.getContainerCommunicator() == null) {
return;
}
Communication communication = super.getContainerCommunicator().collect();
communication.setTimestamp(this.endTimeStamp);
Communication tempComm = new Communication();
tempComm.setTimestamp(this.startTransferTimeStamp);
Communication reportCommunication = CommunicationTool.getReportCommunication(communication, tempComm, this.totalStage);
// 字节速率
long byteSpeedPerSecond = communication.getLongCounter(CommunicationTool.READ_SUCCEED_BYTES)
/ transferCosts;
long recordSpeedPerSecond = communication.getLongCounter(CommunicationTool.READ_SUCCEED_RECORDS)
/ transferCosts;
reportCommunication.setLongCounter(CommunicationTool.BYTE_SPEED, byteSpeedPerSecond);
reportCommunication.setLongCounter(CommunicationTool.RECORD_SPEED, recordSpeedPerSecond);
super.getContainerCommunicator().report(reportCommunication);
LOG.info(String.format(
"\n" + "%-26s: %-18s\n" + "%-26s: %-18s\n" + "%-26s: %19s\n"
+ "%-26s: %19s\n" + "%-26s: %19s\n" + "%-26s: %19s\n"
+ "%-26s: %19s\n",
"任务启动时刻",
dateFormat.format(startTimeStamp),
"任务结束时刻",
dateFormat.format(endTimeStamp),
"任务总计耗时",
String.valueOf(totalCosts) + "s",
"任务平均流量",
StrUtil.stringify(byteSpeedPerSecond)
+ "/s",
"记录写入速度",
String.valueOf(recordSpeedPerSecond)
+ "rec/s", "读出记录总数",
String.valueOf(CommunicationTool.getTotalReadRecords(communication)),
"读写失败总数",
String.valueOf(CommunicationTool.getTotalErrorRecords(communication))
));
if (communication.getLongCounter(CommunicationTool.TRANSFORMER_SUCCEED_RECORDS) > 0
|| communication.getLongCounter(CommunicationTool.TRANSFORMER_FAILED_RECORDS) > 0
|| communication.getLongCounter(CommunicationTool.TRANSFORMER_FILTER_RECORDS) > 0) {
LOG.info(String.format(
"\n" + "%-26s: %19s\n" + "%-26s: %19s\n" + "%-26s: %19s\n",
"Transformer成功记录总数",
communication.getLongCounter(CommunicationTool.TRANSFORMER_SUCCEED_RECORDS),
"Transformer失败记录总数",
communication.getLongCounter(CommunicationTool.TRANSFORMER_FAILED_RECORDS),
"Transformer过滤记录总数",
communication.getLongCounter(CommunicationTool.TRANSFORMER_FILTER_RECORDS)
));
}
}
/**
* reader job的初始化,返回Reader.Job
*
* @return
*/
private Reader.Job initJobReader(
JobPluginCollector jobPluginCollector) {
this.readerPluginName = this.configuration.getString(
CoreConstant.DATAX_JOB_CONTENT_READER_NAME);
classLoaderSwapper.setCurrentThreadClassLoader(LoadUtil.getJarLoader(
PluginType.READER, this.readerPluginName));
Reader.Job jobReader = (Reader.Job) LoadUtil.loadJobPlugin(
PluginType.READER, this.readerPluginName);
// 设置reader的jobConfig
jobReader.setPluginJobConf(this.configuration.getConfiguration(
CoreConstant.DATAX_JOB_CONTENT_READER_PARAMETER));
// 设置reader的readerConfig
jobReader.setPeerPluginJobConf(this.configuration.getConfiguration(
CoreConstant.DATAX_JOB_CONTENT_WRITER_PARAMETER));
jobReader.setJobPluginCollector(jobPluginCollector);
jobReader.init();
classLoaderSwapper.restoreCurrentThreadClassLoader();
return jobReader;
}
/**
* writer job的初始化,返回Writer.Job
*
* @return
*/
private Writer.Job initJobWriter(
JobPluginCollector jobPluginCollector) {
this.writerPluginName = this.configuration.getString(
CoreConstant.DATAX_JOB_CONTENT_WRITER_NAME);
classLoaderSwapper.setCurrentThreadClassLoader(LoadUtil.getJarLoader(
PluginType.WRITER, this.writerPluginName));
Writer.Job jobWriter = (Writer.Job) LoadUtil.loadJobPlugin(
PluginType.WRITER, this.writerPluginName);
// 设置writer的jobConfig
jobWriter.setPluginJobConf(this.configuration.getConfiguration(
CoreConstant.DATAX_JOB_CONTENT_WRITER_PARAMETER));
// 设置reader的readerConfig
jobWriter.setPeerPluginJobConf(this.configuration.getConfiguration(
CoreConstant.DATAX_JOB_CONTENT_READER_PARAMETER));
jobWriter.setPeerPluginName(this.readerPluginName);
jobWriter.setJobPluginCollector(jobPluginCollector);
jobWriter.init();
classLoaderSwapper.restoreCurrentThreadClassLoader();
return jobWriter;
}
private void prepareJobReader() {
classLoaderSwapper.setCurrentThreadClassLoader(LoadUtil.getJarLoader(
PluginType.READER, this.readerPluginName));
LOG.info(String.format("DataX Reader.Job [%s] do prepare work .",
this.readerPluginName));
this.jobReader.prepare();
classLoaderSwapper.restoreCurrentThreadClassLoader();
}
private void prepareJobWriter() {
classLoaderSwapper.setCurrentThreadClassLoader(LoadUtil.getJarLoader(
PluginType.WRITER, this.writerPluginName));
LOG.info(String.format("DataX Writer.Job [%s] do prepare work .",
this.writerPluginName));
this.jobWriter.prepare();
classLoaderSwapper.restoreCurrentThreadClassLoader();
}
// TODO: 如果源头就是空数据
private List<Configuration> doReaderSplit(int adviceNumber) {
classLoaderSwapper.setCurrentThreadClassLoader(LoadUtil.getJarLoader(
PluginType.READER, this.readerPluginName));
List<Configuration> readerSlicesConfigs =
this.jobReader.split(adviceNumber);
if (readerSlicesConfigs == null || readerSlicesConfigs.size() <= 0) {
throw DataXException.asDataXException(
FrameworkErrorCode.PLUGIN_SPLIT_ERROR,
"reader切分的task数目不能小于等于0");
}
LOG.info("DataX Reader.Job [{}] splits to [{}] tasks.",
this.readerPluginName, readerSlicesConfigs.size());
classLoaderSwapper.restoreCurrentThreadClassLoader();
return readerSlicesConfigs;
}
private List<Configuration> doWriterSplit(int readerTaskNumber) {
classLoaderSwapper.setCurrentThreadClassLoader(LoadUtil.getJarLoader(
PluginType.WRITER, this.writerPluginName));
List<Configuration> writerSlicesConfigs = this.jobWriter
.split(readerTaskNumber);
if (writerSlicesConfigs == null || writerSlicesConfigs.size() <= 0) {
throw DataXException.asDataXException(
FrameworkErrorCode.PLUGIN_SPLIT_ERROR,
"writer切分的task不能小于等于0");
}
LOG.info("DataX Writer.Job [{}] splits to [{}] tasks.",
this.writerPluginName, writerSlicesConfigs.size());
classLoaderSwapper.restoreCurrentThreadClassLoader();
return writerSlicesConfigs;
}
/**
* 按顺序整合reader和writer的配置,这里的顺序不能乱! 输入是reader、writer级别的配置,输出是一个完整task的配置
*
* @param readerTasksConfigs
* @param writerTasksConfigs
* @return
*/
private List<Configuration> mergeReaderAndWriterTaskConfigs(
List<Configuration> readerTasksConfigs,
List<Configuration> writerTasksConfigs) {
return mergeReaderAndWriterTaskConfigs(readerTasksConfigs, writerTasksConfigs, null);
}
private List<Configuration> mergeReaderAndWriterTaskConfigs(
List<Configuration> readerTasksConfigs,
List<Configuration> writerTasksConfigs,
List<Configuration> transformerConfigs) {
if (readerTasksConfigs.size() != writerTasksConfigs.size()) {
throw DataXException.asDataXException(
FrameworkErrorCode.PLUGIN_SPLIT_ERROR,
String.format("reader切分的task数目[%d]不等于writer切分的task数目[%d].",
readerTasksConfigs.size(), writerTasksConfigs.size())
);
}
List<Configuration> contentConfigs = new ArrayList<Configuration>();
for (int i = 0; i < readerTasksConfigs.size(); i++) {
Configuration taskConfig = Configuration.newDefault();
taskConfig.set(CoreConstant.JOB_READER_NAME,
this.readerPluginName);
taskConfig.set(CoreConstant.JOB_READER_PARAMETER,
readerTasksConfigs.get(i));
taskConfig.set(CoreConstant.JOB_WRITER_NAME,
this.writerPluginName);
taskConfig.set(CoreConstant.JOB_WRITER_PARAMETER,
writerTasksConfigs.get(i));
if(transformerConfigs!=null && transformerConfigs.size()>0){
taskConfig.set(CoreConstant.JOB_TRANSFORMER, transformerConfigs);
}
taskConfig.set(CoreConstant.TASK_ID, i);
contentConfigs.add(taskConfig);
}
return contentConfigs;
}
/**
* 这里比较复杂,分两步整合 1. tasks到channel 2. channel到taskGroup
* 合起来考虑,其实就是把tasks整合到taskGroup中,需要满足计算出的channel数,同时不能多起channel
* <p/>
* example:
* <p/>
* 前提条件: 切分后是1024个分表,假设用户要求总速率是1000M/s,每个channel的速率的3M/s,
* 每个taskGroup负责运行7个channel
* <p/>
* 计算: 总channel数为:1000M/s / 3M/s =
* 333个,为平均分配,计算可知有308个每个channel有3个tasks,而有25个每个channel有4个tasks,
* 需要的taskGroup数为:333 / 7 =
* 47...4,也就是需要48个taskGroup,47个是每个负责7个channel,有4个负责1个channel
* <p/>
* 处理:我们先将这负责4个channel的taskGroup处理掉,逻辑是:
* 先按平均为3个tasks找4个channel,设置taskGroupId为0,
* 接下来就像发牌一样轮询分配task到剩下的包含平均channel数的taskGroup中
* <p/>
* TODO delete it
*
* @param averTaskPerChannel
* @param channelNumber
* @param channelsPerTaskGroup
* @return 每个taskGroup独立的全部配置
*/
@SuppressWarnings("serial")
private List<Configuration> distributeTasksToTaskGroup(
int averTaskPerChannel, int channelNumber,
int channelsPerTaskGroup) {
Validate.isTrue(averTaskPerChannel > 0 && channelNumber > 0
&& channelsPerTaskGroup > 0,
"每个channel的平均task数[averTaskPerChannel],channel数目[channelNumber],每个taskGroup的平均channel数[channelsPerTaskGroup]都应该为正数");
List<Configuration> taskConfigs = this.configuration
.getListConfiguration(CoreConstant.DATAX_JOB_CONTENT);
int taskGroupNumber = channelNumber / channelsPerTaskGroup;
int leftChannelNumber = channelNumber % channelsPerTaskGroup;
if (leftChannelNumber > 0) {
taskGroupNumber += 1;
}
/**
* 如果只有一个taskGroup,直接打标返回
*/
if (taskGroupNumber == 1) {
final Configuration taskGroupConfig = this.configuration.clone();
/**
* configure的clone不能clone出
*/
taskGroupConfig.set(CoreConstant.DATAX_JOB_CONTENT, this.configuration
.getListConfiguration(CoreConstant.DATAX_JOB_CONTENT));
taskGroupConfig.set(CoreConstant.DATAX_CORE_CONTAINER_TASKGROUP_CHANNEL,
channelNumber);
taskGroupConfig.set(CoreConstant.DATAX_CORE_CONTAINER_TASKGROUP_ID, 0);
return new ArrayList<Configuration>() {
{
add(taskGroupConfig);
}
};
}
List<Configuration> taskGroupConfigs = new ArrayList<Configuration>();
/**
* 将每个taskGroup中content的配置清空
*/
for (int i = 0; i < taskGroupNumber; i++) {
Configuration taskGroupConfig = this.configuration.clone();
List<Configuration> taskGroupJobContent = taskGroupConfig
.getListConfiguration(CoreConstant.DATAX_JOB_CONTENT);
taskGroupJobContent.clear();
taskGroupConfig.set(CoreConstant.DATAX_JOB_CONTENT, taskGroupJobContent);
taskGroupConfigs.add(taskGroupConfig);
}
int taskConfigIndex = 0;
int channelIndex = 0;
int taskGroupConfigIndex = 0;
/**
* 先处理掉taskGroup包含channel数不是平均值的taskGroup
*/
if (leftChannelNumber > 0) {
Configuration taskGroupConfig = taskGroupConfigs.get(taskGroupConfigIndex);
for (; channelIndex < leftChannelNumber; channelIndex++) {
for (int i = 0; i < averTaskPerChannel; i++) {
List<Configuration> taskGroupJobContent = taskGroupConfig
.getListConfiguration(CoreConstant.DATAX_JOB_CONTENT);
taskGroupJobContent.add(taskConfigs.get(taskConfigIndex++));
taskGroupConfig.set(CoreConstant.DATAX_JOB_CONTENT,
taskGroupJobContent);
}
}
taskGroupConfig.set(CoreConstant.DATAX_CORE_CONTAINER_TASKGROUP_CHANNEL,
leftChannelNumber);
taskGroupConfig.set(CoreConstant.DATAX_CORE_CONTAINER_TASKGROUP_ID,
taskGroupConfigIndex++);
}
/**
* 下面需要轮询分配,并打上channel数和taskGroupId标记
*/
int equalDivisionStartIndex = taskGroupConfigIndex;
for (; taskConfigIndex < taskConfigs.size()
&& equalDivisionStartIndex < taskGroupConfigs.size(); ) {
for (taskGroupConfigIndex = equalDivisionStartIndex; taskGroupConfigIndex < taskGroupConfigs
.size() && taskConfigIndex < taskConfigs.size(); taskGroupConfigIndex++) {
Configuration taskGroupConfig = taskGroupConfigs.get(taskGroupConfigIndex);
List<Configuration> taskGroupJobContent = taskGroupConfig
.getListConfiguration(CoreConstant.DATAX_JOB_CONTENT);
taskGroupJobContent.add(taskConfigs.get(taskConfigIndex++));
taskGroupConfig.set(
CoreConstant.DATAX_JOB_CONTENT, taskGroupJobContent);
}
}
for (taskGroupConfigIndex = equalDivisionStartIndex;
taskGroupConfigIndex < taskGroupConfigs.size(); ) {
Configuration taskGroupConfig = taskGroupConfigs.get(taskGroupConfigIndex);
taskGroupConfig.set(CoreConstant.DATAX_CORE_CONTAINER_TASKGROUP_CHANNEL,
channelsPerTaskGroup);
taskGroupConfig.set(CoreConstant.DATAX_CORE_CONTAINER_TASKGROUP_ID,
taskGroupConfigIndex++);
}
return taskGroupConfigs;
}
private void postJobReader() {
classLoaderSwapper.setCurrentThreadClassLoader(LoadUtil.getJarLoader(
PluginType.READER, this.readerPluginName));
LOG.info("DataX Reader.Job [{}] do post work.",
this.readerPluginName);
this.jobReader.post();
classLoaderSwapper.restoreCurrentThreadClassLoader();
}
private void postJobWriter() {
classLoaderSwapper.setCurrentThreadClassLoader(LoadUtil.getJarLoader(
PluginType.WRITER, this.writerPluginName));
LOG.info("DataX Writer.Job [{}] do post work.",
this.writerPluginName);
this.jobWriter.post();
classLoaderSwapper.restoreCurrentThreadClassLoader();
}
/**
* 检查最终结果是否超出阈值,如果阈值设定小于1,则表示百分数阈值,大于1表示条数阈值。
*
* @param
*/
private void checkLimit() {
Communication communication = super.getContainerCommunicator().collect();
errorLimit.checkRecordLimit(communication);
errorLimit.checkPercentageLimit(communication);
}
/**
* 调用外部hook
*/
private void invokeHooks() {
Communication comm = super.getContainerCommunicator().collect();
HookInvoker invoker = new HookInvoker(CoreConstant.DATAX_HOME + "/hook", configuration, comm.getCounter());
invoker.invokeAll();
}
}
| alibaba/DataX | core/src/main/java/com/alibaba/datax/core/job/JobContainer.java |
21 | package com.neo.config;
import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.handler.SimpleMappingExceptionResolver;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Properties;
@Configuration
public class ShiroConfig {
@Bean
public ShiroFilterFactoryBean shirFilter(SecurityManager securityManager) {
System.out.println("ShiroConfiguration.shirFilter()");
ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();
shiroFilterFactoryBean.setSecurityManager(securityManager);
//拦截器.
Map<String,String> filterChainDefinitionMap = new LinkedHashMap<String,String>();
// 配置不会被拦截的链接 顺序判断
filterChainDefinitionMap.put("/static/**", "anon");
//配置退出 过滤器,其中的具体的退出代码Shiro已经替我们实现了
filterChainDefinitionMap.put("/logout", "logout");
//<!-- 过滤链定义,从上向下顺序执行,一般将/**放在最为下边 -->:这是一个坑呢,一不小心代码就不好使了;
//<!-- authc:所有url都必须认证通过才可以访问; anon:所有url都都可以匿名访问-->
filterChainDefinitionMap.put("/**", "authc");
// 如果不设置默认会自动寻找Web工程根目录下的"/login.jsp"页面
shiroFilterFactoryBean.setLoginUrl("/login");
// 登录成功后要跳转的链接
shiroFilterFactoryBean.setSuccessUrl("/index");
//未授权界面;
shiroFilterFactoryBean.setUnauthorizedUrl("/403");
shiroFilterFactoryBean.setFilterChainDefinitionMap(filterChainDefinitionMap);
return shiroFilterFactoryBean;
}
/**
* 凭证匹配器
* (由于我们的密码校验交给Shiro的SimpleAuthenticationInfo进行处理了
* )
* @return
*/
@Bean
public HashedCredentialsMatcher hashedCredentialsMatcher(){
HashedCredentialsMatcher hashedCredentialsMatcher = new HashedCredentialsMatcher();
hashedCredentialsMatcher.setHashAlgorithmName("md5");//散列算法:这里使用MD5算法;
hashedCredentialsMatcher.setHashIterations(2);//散列的次数,比如散列两次,相当于 md5(md5(""));
return hashedCredentialsMatcher;
}
@Bean
public MyShiroRealm myShiroRealm(){
MyShiroRealm myShiroRealm = new MyShiroRealm();
myShiroRealm.setCredentialsMatcher(hashedCredentialsMatcher());
return myShiroRealm;
}
@Bean
public SecurityManager securityManager(){
DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
securityManager.setRealm(myShiroRealm());
return securityManager;
}
/**
* 开启shiro aop注解支持.
* 使用代理方式;所以需要开启代码支持;
* @param securityManager
* @return
*/
@Bean
public AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor(SecurityManager securityManager){
AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor = new AuthorizationAttributeSourceAdvisor();
authorizationAttributeSourceAdvisor.setSecurityManager(securityManager);
return authorizationAttributeSourceAdvisor;
}
@Bean(name="simpleMappingExceptionResolver")
public SimpleMappingExceptionResolver
createSimpleMappingExceptionResolver() {
SimpleMappingExceptionResolver r = new SimpleMappingExceptionResolver();
Properties mappings = new Properties();
mappings.setProperty("DatabaseException", "databaseError");//数据库异常处理
mappings.setProperty("UnauthorizedException","403");
r.setExceptionMappings(mappings); // None by default
r.setDefaultErrorView("error"); // No default
r.setExceptionAttribute("ex"); // Default is "exception"
//r.setWarnLogCategory("example.MvcLogger"); // No default
return r;
}
} | ityouknow/spring-boot-examples | 2.x/spring-boot-shiro/src/main/java/com/neo/config/ShiroConfig.java |
22 | package com.zheng.common.util.key;
import java.sql.Timestamp;
import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicLong;
/**
* 高并发场景下System.currentTimeMillis()的性能问题的优化
* <p><p>
* System.currentTimeMillis()的调用比new一个普通对象要耗时的多(具体耗时高出多少我还没测试过,有人说是100倍左右)<p>
* System.currentTimeMillis()之所以慢是因为去跟系统打了一次交道<p>
* 后台定时更新时钟,JVM退出时,线程自动回收<p>
* 10亿:43410,206,210.72815533980582%<p>
* 1亿:4699,29,162.0344827586207%<p>
* 1000万:480,12,40.0%<p>
* 100万:50,10,5.0%<p>
* @author lry
*/
public class SystemClock {
private final long period;
private final AtomicLong now;
ExecutorService executor = Executors.newSingleThreadExecutor();
private SystemClock(long period) {
this.period = period;
this.now = new AtomicLong(System.currentTimeMillis());
scheduleClockUpdating();
}
private static class InstanceHolder {
public static final SystemClock INSTANCE = new SystemClock(1);
}
private static SystemClock instance() {
return InstanceHolder.INSTANCE;
}
private void scheduleClockUpdating() {
ScheduledExecutorService scheduler = Executors.newSingleThreadScheduledExecutor(new ThreadFactory() {
@Override
public Thread newThread(Runnable runnable) {
Thread thread = new Thread(runnable, "System Clock");
thread.setDaemon(true);
return thread;
}
});
scheduler.scheduleAtFixedRate(new Runnable() {
@Override
public void run() {
now.set(System.currentTimeMillis());
}
}, period, period, TimeUnit.MILLISECONDS);
}
private long currentTimeMillis() {
return now.get();
}
public static long now() {
return instance().currentTimeMillis();
}
public static String nowDate() {
return new Timestamp(instance().currentTimeMillis()).toString();
}
}
| shuzheng/zheng | zheng-common/src/main/java/com/zheng/common/util/key/SystemClock.java |
End of preview. Expand
in Dataset Viewer.
README.md exists but content is empty.
Use the Edit dataset card button to edit it.
- Downloads last month
- 38